1 // Copyright 2013 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 #include "chrome/browser/ui/views/toolbar/wrench_menu.h"
11 #include "base/strings/string_number_conversions.h"
12 #include "base/strings/utf_string_conversions.h"
13 #include "chrome/app/chrome_command_ids.h"
14 #include "chrome/browser/bookmarks/bookmark_model_factory.h"
15 #include "chrome/browser/bookmarks/bookmark_stats.h"
16 #include "chrome/browser/chrome_notification_types.h"
17 #include "chrome/browser/profiles/profile.h"
18 #include "chrome/browser/search/search.h"
19 #include "chrome/browser/ui/browser.h"
20 #include "chrome/browser/ui/browser_window.h"
21 #include "chrome/browser/ui/tabs/tab_strip_model.h"
22 #include "chrome/browser/ui/toolbar/wrench_menu_model.h"
23 #include "chrome/browser/ui/views/bookmarks/bookmark_menu_delegate.h"
24 #include "chrome/browser/ui/views/toolbar/extension_toolbar_menu_view.h"
25 #include "chrome/browser/ui/views/toolbar/wrench_menu_observer.h"
26 #include "chrome/browser/ui/zoom/zoom_controller.h"
27 #include "chrome/browser/ui/zoom/zoom_event_manager.h"
28 #include "chrome/grit/generated_resources.h"
29 #include "components/bookmarks/browser/bookmark_model.h"
30 #include "content/public/browser/host_zoom_map.h"
31 #include "content/public/browser/notification_observer.h"
32 #include "content/public/browser/notification_registrar.h"
33 #include "content/public/browser/notification_source.h"
34 #include "content/public/browser/notification_types.h"
35 #include "content/public/browser/user_metrics.h"
36 #include "content/public/browser/web_contents.h"
37 #include "extensions/common/feature_switch.h"
38 #include "grit/theme_resources.h"
39 #include "third_party/skia/include/core/SkCanvas.h"
40 #include "third_party/skia/include/core/SkPaint.h"
41 #include "ui/base/l10n/l10n_util.h"
42 #include "ui/base/layout.h"
43 #include "ui/base/resource/resource_bundle.h"
44 #include "ui/gfx/canvas.h"
45 #include "ui/gfx/font_list.h"
46 #include "ui/gfx/image/image.h"
47 #include "ui/gfx/image/image_skia_source.h"
48 #include "ui/gfx/skia_util.h"
49 #include "ui/gfx/text_utils.h"
50 #include "ui/views/background.h"
51 #include "ui/views/controls/button/image_button.h"
52 #include "ui/views/controls/button/label_button.h"
53 #include "ui/views/controls/button/menu_button.h"
54 #include "ui/views/controls/label.h"
55 #include "ui/views/controls/menu/menu_config.h"
56 #include "ui/views/controls/menu/menu_item_view.h"
57 #include "ui/views/controls/menu/menu_model_adapter.h"
58 #include "ui/views/controls/menu/menu_runner.h"
59 #include "ui/views/controls/menu/menu_scroll_view_container.h"
60 #include "ui/views/controls/menu/submenu_view.h"
61 #include "ui/views/widget/widget.h"
63 using base::UserMetricsAction;
64 using content::HostZoomMap;
65 using content::WebContents;
67 using views::CustomButton;
68 using views::ImageButton;
70 using views::LabelButton;
71 using views::MenuConfig;
72 using views::MenuItemView;
77 // Horizontal padding on the edges of the in-menu buttons.
78 const int kHorizontalPadding = 15;
80 #if defined(OS_CHROMEOS)
81 // Extra horizontal space to reserve for the fullscreen button.
82 const int kFullscreenPadding = 74;
83 // Padding to left and right of the XX% label.
84 const int kZoomLabelHorizontalPadding = kHorizontalPadding;
86 const int kFullscreenPadding = 38;
87 const int kZoomLabelHorizontalPadding = 2;
90 // Returns true if |command_id| identifies a bookmark menu item.
91 bool IsBookmarkCommand(int command_id) {
92 return command_id >= WrenchMenuModel::kMinBookmarkCommandId &&
93 command_id <= WrenchMenuModel::kMaxBookmarkCommandId;
96 // Returns true if |command_id| identifies a recent tabs menu item.
97 bool IsRecentTabsCommand(int command_id) {
98 return command_id >= WrenchMenuModel::kMinRecentTabsCommandId &&
99 command_id <= WrenchMenuModel::kMaxRecentTabsCommandId;
102 // Subclass of ImageButton whose preferred size includes the size of the border.
103 class FullscreenButton : public ImageButton {
105 explicit FullscreenButton(views::ButtonListener* listener)
106 : ImageButton(listener) { }
108 // Overridden from ImageButton.
109 virtual gfx::Size GetPreferredSize() const OVERRIDE {
110 gfx::Size pref = ImageButton::GetPreferredSize();
112 gfx::Insets insets = border()->GetInsets();
113 pref.Enlarge(insets.width(), insets.height());
119 DISALLOW_COPY_AND_ASSIGN(FullscreenButton);
122 // Combination border/background for the buttons contained in the menu. The
123 // painting of the border/background is done here as LabelButton does not always
125 class InMenuButtonBackground : public views::Background {
134 explicit InMenuButtonBackground(ButtonType type)
135 : type_(type), left_button_(NULL), right_button_(NULL) {}
137 // Used when the type is CENTER_BUTTON to determine if the left/right edge
138 // needs to be rendered selected.
139 void SetOtherButtons(const CustomButton* left_button,
140 const CustomButton* right_button) {
141 if (base::i18n::IsRTL()) {
142 left_button_ = right_button;
143 right_button_ = left_button;
145 left_button_ = left_button;
146 right_button_ = right_button;
150 // Overridden from views::Background.
151 virtual void Paint(gfx::Canvas* canvas, View* view) const OVERRIDE {
152 CustomButton* button = CustomButton::AsCustomButton(view);
153 views::Button::ButtonState state =
154 button ? button->state() : views::Button::STATE_NORMAL;
155 int h = view->height();
157 // Normal buttons get a border drawn on the right side and the rest gets
158 // filled in. The left button however does not get a line to combine
160 if (type_ != RIGHT_BUTTON) {
161 canvas->FillRect(gfx::Rect(0, 0, 1, h),
162 BorderColor(view, views::Button::STATE_NORMAL));
165 gfx::Rect bounds(view->GetLocalBounds());
166 bounds.set_x(view->GetMirroredXForRect(bounds));
167 DrawBackground(canvas, view, bounds, state);
171 static SkColor BorderColor(View* view, views::Button::ButtonState state) {
172 ui::NativeTheme* theme = view->GetNativeTheme();
174 case views::Button::STATE_HOVERED:
175 return theme->GetSystemColor(
176 ui::NativeTheme::kColorId_HoverMenuButtonBorderColor);
177 case views::Button::STATE_PRESSED:
178 return theme->GetSystemColor(
179 ui::NativeTheme::kColorId_FocusedMenuButtonBorderColor);
181 return theme->GetSystemColor(
182 ui::NativeTheme::kColorId_EnabledMenuButtonBorderColor);
186 static SkColor BackgroundColor(const View* view,
187 views::Button::ButtonState state) {
188 const ui::NativeTheme* theme = view->GetNativeTheme();
190 case views::Button::STATE_HOVERED:
191 // Hovered should be handled in DrawBackground.
193 return theme->GetSystemColor(
194 ui::NativeTheme::kColorId_HoverMenuItemBackgroundColor);
195 case views::Button::STATE_PRESSED:
196 return theme->GetSystemColor(
197 ui::NativeTheme::kColorId_FocusedMenuItemBackgroundColor);
199 return theme->GetSystemColor(
200 ui::NativeTheme::kColorId_MenuBackgroundColor);
204 void DrawBackground(gfx::Canvas* canvas,
205 const views::View* view,
206 const gfx::Rect& bounds,
207 views::Button::ButtonState state) const {
208 if (state == views::Button::STATE_HOVERED ||
209 state == views::Button::STATE_PRESSED) {
210 view->GetNativeTheme()->Paint(canvas->sk_canvas(),
211 ui::NativeTheme::kMenuItemBackground,
212 ui::NativeTheme::kHovered,
214 ui::NativeTheme::ExtraParams());
218 ButtonType TypeAdjustedForRTL() const {
219 if (!base::i18n::IsRTL())
223 case LEFT_BUTTON: return RIGHT_BUTTON;
224 case RIGHT_BUTTON: return LEFT_BUTTON;
230 const ButtonType type_;
232 // See description above setter for details.
233 const CustomButton* left_button_;
234 const CustomButton* right_button_;
236 DISALLOW_COPY_AND_ASSIGN(InMenuButtonBackground);
239 base::string16 GetAccessibleNameForWrenchMenuItem(
240 MenuModel* model, int item_index, int accessible_string_id) {
241 base::string16 accessible_name =
242 l10n_util::GetStringUTF16(accessible_string_id);
243 base::string16 accelerator_text;
245 ui::Accelerator menu_accelerator;
246 if (model->GetAcceleratorAt(item_index, &menu_accelerator)) {
248 ui::Accelerator(menu_accelerator.key_code(),
249 menu_accelerator.modifiers()).GetShortcutText();
252 return MenuItemView::GetAccessibleNameForMenuItem(
253 accessible_name, accelerator_text);
256 // A button that lives inside a menu item.
257 class InMenuButton : public LabelButton {
259 InMenuButton(views::ButtonListener* listener, const base::string16& text)
260 : LabelButton(listener, text), in_menu_background_(NULL) {}
261 virtual ~InMenuButton() {}
263 void Init(InMenuButtonBackground::ButtonType type) {
265 set_request_focus_on_press(false);
266 SetHorizontalAlignment(gfx::ALIGN_CENTER);
268 in_menu_background_ = new InMenuButtonBackground(type);
269 set_background(in_menu_background_);
271 OnNativeThemeChanged(NULL);
274 void SetOtherButtons(const InMenuButton* left, const InMenuButton* right) {
275 in_menu_background_->SetOtherButtons(left, right);
278 // views::LabelButton
279 virtual void OnNativeThemeChanged(const ui::NativeTheme* theme) OVERRIDE {
280 const MenuConfig& menu_config = MenuConfig::instance(theme);
281 SetBorder(views::Border::CreateEmptyBorder(
282 0, kHorizontalPadding, 0, kHorizontalPadding));
283 SetFontList(menu_config.font_list);
287 views::Button::STATE_DISABLED,
288 theme->GetSystemColor(
289 ui::NativeTheme::kColorId_DisabledMenuItemForegroundColor));
291 views::Button::STATE_HOVERED,
292 theme->GetSystemColor(
293 ui::NativeTheme::kColorId_SelectedMenuItemForegroundColor));
295 views::Button::STATE_PRESSED,
296 theme->GetSystemColor(
297 ui::NativeTheme::kColorId_SelectedMenuItemForegroundColor));
299 views::Button::STATE_NORMAL,
300 theme->GetSystemColor(
301 ui::NativeTheme::kColorId_EnabledMenuItemForegroundColor));
306 InMenuButtonBackground* in_menu_background_;
308 DISALLOW_COPY_AND_ASSIGN(InMenuButton);
311 // WrenchMenuView is a view that can contain label buttons.
312 class WrenchMenuView : public views::View,
313 public views::ButtonListener,
314 public WrenchMenuObserver {
316 WrenchMenuView(WrenchMenu* menu, MenuModel* menu_model)
318 menu_model_(menu_model) {
319 menu_->AddObserver(this);
322 virtual ~WrenchMenuView() {
324 menu_->RemoveObserver(this);
327 // Overridden from views::View.
328 virtual void SchedulePaintInRect(const gfx::Rect& r) OVERRIDE {
329 // Normally when the mouse enters/exits a button the buttons invokes
330 // SchedulePaint. As part of the button border (InMenuButtonBackground) is
331 // rendered by the button to the left/right of it SchedulePaint on the the
332 // button may not be enough, so this forces a paint all.
333 View::SchedulePaintInRect(gfx::Rect(size()));
336 InMenuButton* CreateAndConfigureButton(
338 InMenuButtonBackground::ButtonType type,
340 return CreateButtonWithAccName(string_id, type, index, string_id);
343 InMenuButton* CreateButtonWithAccName(int string_id,
344 InMenuButtonBackground::ButtonType type,
347 // Should only be invoked during construction when |menu_| is valid.
349 InMenuButton* button = new InMenuButton(
351 gfx::RemoveAcceleratorChar(
352 l10n_util::GetStringUTF16(string_id), '&', NULL, NULL));
354 button->SetAccessibleName(
355 GetAccessibleNameForWrenchMenuItem(menu_model_, index, acc_string_id));
356 button->set_tag(index);
357 button->SetEnabled(menu_model_->IsEnabledAt(index));
359 AddChildView(button);
360 // all buttons on menu should must be a custom button in order for
361 // the keyboard nativigation work.
362 DCHECK(CustomButton::AsCustomButton(button));
366 // Overridden from WrenchMenuObserver:
367 virtual void WrenchMenuDestroyed() OVERRIDE {
368 menu_->RemoveObserver(this);
374 WrenchMenu* menu() { return menu_; }
375 MenuModel* menu_model() { return menu_model_; }
378 // Hosting WrenchMenu.
379 // WARNING: this may be NULL during shutdown.
382 // The menu model containing the increment/decrement/reset items.
383 // WARNING: this may be NULL during shutdown.
384 MenuModel* menu_model_;
386 DISALLOW_COPY_AND_ASSIGN(WrenchMenuView);
389 // Generate the button image for hover state.
390 class HoveredImageSource : public gfx::ImageSkiaSource {
392 HoveredImageSource(const gfx::ImageSkia& image, SkColor color)
396 virtual ~HoveredImageSource() {}
398 virtual gfx::ImageSkiaRep GetImageForScale(float scale) OVERRIDE {
399 const gfx::ImageSkiaRep& rep = image_.GetRepresentation(scale);
400 SkBitmap bitmap = rep.sk_bitmap();
402 white.allocN32Pixels(bitmap.width(), bitmap.height());
403 white.eraseARGB(0, 0, 0, 0);
405 for (int y = 0; y < bitmap.height(); ++y) {
406 uint32* image_row = bitmap.getAddr32(0, y);
407 uint32* dst_row = white.getAddr32(0, y);
408 for (int x = 0; x < bitmap.width(); ++x) {
409 uint32 image_pixel = image_row[x];
410 // Fill the non transparent pixels with |color_|.
411 dst_row[x] = (image_pixel & 0xFF000000) == 0x0 ? 0x0 : color_;
414 bitmap.unlockPixels();
415 return gfx::ImageSkiaRep(white, scale);
419 const gfx::ImageSkia image_;
420 const SkColor color_;
421 DISALLOW_COPY_AND_ASSIGN(HoveredImageSource);
426 // CutCopyPasteView ------------------------------------------------------------
428 // CutCopyPasteView is the view containing the cut/copy/paste buttons.
429 class WrenchMenu::CutCopyPasteView : public WrenchMenuView {
431 CutCopyPasteView(WrenchMenu* menu,
432 MenuModel* menu_model,
436 : WrenchMenuView(menu, menu_model) {
437 InMenuButton* cut = CreateAndConfigureButton(
438 IDS_CUT, InMenuButtonBackground::LEFT_BUTTON, cut_index);
439 InMenuButton* copy = CreateAndConfigureButton(
440 IDS_COPY, InMenuButtonBackground::CENTER_BUTTON, copy_index);
441 InMenuButton* paste = CreateAndConfigureButton(
442 IDS_PASTE, InMenuButtonBackground::CENTER_BUTTON, paste_index);
443 copy->SetOtherButtons(cut, paste);
446 // Overridden from View.
447 virtual gfx::Size GetPreferredSize() const OVERRIDE {
448 // Returned height doesn't matter as MenuItemView forces everything to the
449 // height of the menuitemview.
450 return gfx::Size(GetMaxChildViewPreferredWidth() * child_count(), 0);
453 virtual void Layout() OVERRIDE {
454 // All buttons are given the same width.
455 int width = GetMaxChildViewPreferredWidth();
456 for (int i = 0; i < child_count(); ++i)
457 child_at(i)->SetBounds(i * width, 0, width, height());
460 // Overridden from ButtonListener.
461 virtual void ButtonPressed(views::Button* sender,
462 const ui::Event& event) OVERRIDE {
463 menu()->CancelAndEvaluate(menu_model(), sender->tag());
467 // Returns the max preferred width of all the children.
468 int GetMaxChildViewPreferredWidth() const {
470 for (int i = 0; i < child_count(); ++i)
471 width = std::max(width, child_at(i)->GetPreferredSize().width());
475 DISALLOW_COPY_AND_ASSIGN(CutCopyPasteView);
478 // ZoomView --------------------------------------------------------------------
481 // ZoomView contains the various zoom controls: two buttons to increase/decrease
482 // the zoom, a label showing the current zoom percent, and a button to go
484 class WrenchMenu::ZoomView : public WrenchMenuView {
486 ZoomView(WrenchMenu* menu,
487 MenuModel* menu_model,
490 int fullscreen_index)
491 : WrenchMenuView(menu, menu_model),
492 fullscreen_index_(fullscreen_index),
493 increment_button_(NULL),
495 decrement_button_(NULL),
496 fullscreen_button_(NULL),
497 zoom_label_width_(0) {
498 content_zoom_subscription_ = HostZoomMap::GetDefaultForBrowserContext(
499 menu->browser_->profile())->AddZoomLevelChangedCallback(
500 base::Bind(&WrenchMenu::ZoomView::OnZoomLevelChanged,
501 base::Unretained(this)));
503 browser_zoom_subscription_ = ZoomEventManager::GetForBrowserContext(
504 menu->browser_->profile())->AddZoomLevelChangedCallback(
505 base::Bind(&WrenchMenu::ZoomView::OnZoomLevelChanged,
506 base::Unretained(this)));
508 decrement_button_ = CreateButtonWithAccName(
509 IDS_ZOOM_MINUS2, InMenuButtonBackground::LEFT_BUTTON,
510 decrement_index, IDS_ACCNAME_ZOOM_MINUS2);
512 zoom_label_ = new Label(
513 l10n_util::GetStringFUTF16Int(IDS_ZOOM_PERCENT, 100));
514 zoom_label_->SetAutoColorReadabilityEnabled(false);
515 zoom_label_->SetHorizontalAlignment(gfx::ALIGN_RIGHT);
517 InMenuButtonBackground* center_bg =
518 new InMenuButtonBackground(InMenuButtonBackground::RIGHT_BUTTON);
519 zoom_label_->set_background(center_bg);
521 AddChildView(zoom_label_);
522 zoom_label_width_ = MaxWidthForZoomLabel();
524 increment_button_ = CreateButtonWithAccName(
525 IDS_ZOOM_PLUS2, InMenuButtonBackground::RIGHT_BUTTON,
526 increment_index, IDS_ACCNAME_ZOOM_PLUS2);
528 center_bg->SetOtherButtons(decrement_button_, increment_button_);
530 fullscreen_button_ = new FullscreenButton(this);
531 // all buttons on menu should must be a custom button in order for
532 // the keyboard nativigation work.
533 DCHECK(CustomButton::AsCustomButton(fullscreen_button_));
534 gfx::ImageSkia* full_screen_image =
535 ui::ResourceBundle::GetSharedInstance().GetImageSkiaNamed(
536 IDR_FULLSCREEN_MENU_BUTTON);
537 fullscreen_button_->SetImage(ImageButton::STATE_NORMAL, full_screen_image);
539 fullscreen_button_->SetFocusable(true);
540 fullscreen_button_->set_request_focus_on_press(false);
541 fullscreen_button_->set_tag(fullscreen_index);
542 fullscreen_button_->SetImageAlignment(
543 ImageButton::ALIGN_CENTER, ImageButton::ALIGN_MIDDLE);
544 fullscreen_button_->set_background(
545 new InMenuButtonBackground(InMenuButtonBackground::SINGLE_BUTTON));
546 fullscreen_button_->SetAccessibleName(
547 GetAccessibleNameForWrenchMenuItem(
548 menu_model, fullscreen_index, IDS_ACCNAME_FULLSCREEN));
549 AddChildView(fullscreen_button_);
551 // Need to set a font list for the zoom label width calculations.
552 OnNativeThemeChanged(NULL);
553 UpdateZoomControls();
556 virtual ~ZoomView() {}
558 // Overridden from View.
559 virtual gfx::Size GetPreferredSize() const OVERRIDE {
560 // The increment/decrement button are forced to the same width.
561 int button_width = std::max(increment_button_->GetPreferredSize().width(),
562 decrement_button_->GetPreferredSize().width());
563 int fullscreen_width =
564 fullscreen_button_->GetPreferredSize().width() + kFullscreenPadding;
565 // Returned height doesn't matter as MenuItemView forces everything to the
566 // height of the menuitemview. Note that we have overridden the height when
567 // constructing the menu.
568 return gfx::Size(button_width + zoom_label_width_ + button_width +
569 fullscreen_width, 0);
572 virtual void Layout() OVERRIDE {
574 int button_width = std::max(increment_button_->GetPreferredSize().width(),
575 decrement_button_->GetPreferredSize().width());
576 gfx::Rect bounds(0, 0, button_width, height());
578 decrement_button_->SetBoundsRect(bounds);
582 bounds.set_width(zoom_label_width_);
583 zoom_label_->SetBoundsRect(bounds);
587 bounds.set_width(button_width);
588 increment_button_->SetBoundsRect(bounds);
592 bounds.set_width(fullscreen_button_->GetPreferredSize().width() +
594 fullscreen_button_->SetBoundsRect(bounds);
597 virtual void OnNativeThemeChanged(const ui::NativeTheme* theme) OVERRIDE {
598 WrenchMenuView::OnNativeThemeChanged(theme);
600 const MenuConfig& menu_config = MenuConfig::instance(theme);
601 zoom_label_->SetBorder(views::Border::CreateEmptyBorder(
602 0, kZoomLabelHorizontalPadding, 0, kZoomLabelHorizontalPadding));
603 zoom_label_->SetFontList(menu_config.font_list);
604 zoom_label_width_ = MaxWidthForZoomLabel();
607 zoom_label_->SetEnabledColor(theme->GetSystemColor(
608 ui::NativeTheme::kColorId_EnabledMenuItemForegroundColor));
609 gfx::ImageSkia* full_screen_image =
610 ui::ResourceBundle::GetSharedInstance().GetImageSkiaNamed(
611 IDR_FULLSCREEN_MENU_BUTTON);
612 SkColor fg_color = theme->GetSystemColor(
613 ui::NativeTheme::kColorId_SelectedMenuItemForegroundColor);
614 gfx::ImageSkia hovered_fullscreen_image(
615 new HoveredImageSource(*full_screen_image, fg_color),
616 full_screen_image->size());
617 fullscreen_button_->SetImage(
618 ImageButton::STATE_HOVERED, &hovered_fullscreen_image);
619 fullscreen_button_->SetImage(
620 ImageButton::STATE_PRESSED, &hovered_fullscreen_image);
624 // Overridden from ButtonListener.
625 virtual void ButtonPressed(views::Button* sender,
626 const ui::Event& event) OVERRIDE {
627 if (sender->tag() == fullscreen_index_) {
628 menu()->CancelAndEvaluate(menu_model(), sender->tag());
630 // Zoom buttons don't close the menu.
631 menu_model()->ActivatedAt(sender->tag());
635 // Overridden from WrenchMenuObserver.
636 virtual void WrenchMenuDestroyed() OVERRIDE {
637 WrenchMenuView::WrenchMenuDestroyed();
641 void OnZoomLevelChanged(const HostZoomMap::ZoomLevelChange& change) {
642 UpdateZoomControls();
645 void UpdateZoomControls() {
646 WebContents* selected_tab =
647 menu()->browser_->tab_strip_model()->GetActiveWebContents();
650 zoom = ZoomController::FromWebContents(selected_tab)->GetZoomPercent();
651 increment_button_->SetEnabled(zoom < selected_tab->GetMaximumZoomPercent());
652 decrement_button_->SetEnabled(zoom > selected_tab->GetMinimumZoomPercent());
653 zoom_label_->SetText(
654 l10n_util::GetStringFUTF16Int(IDS_ZOOM_PERCENT, zoom));
656 zoom_label_width_ = MaxWidthForZoomLabel();
659 // Calculates the max width the zoom string can be.
660 int MaxWidthForZoomLabel() {
661 const gfx::FontList& font_list = zoom_label_->font_list();
663 zoom_label_->border() ? zoom_label_->border()->GetInsets().width() : 0;
667 WebContents* selected_tab =
668 menu()->browser_->tab_strip_model()->GetActiveWebContents();
670 int min_percent = selected_tab->GetMinimumZoomPercent();
671 int max_percent = selected_tab->GetMaximumZoomPercent();
673 int step = (max_percent - min_percent) / 10;
674 for (int i = min_percent; i <= max_percent; i += step) {
675 int w = gfx::GetStringWidth(
676 l10n_util::GetStringFUTF16Int(IDS_ZOOM_PERCENT, i), font_list);
677 max_w = std::max(w, max_w);
680 max_w = gfx::GetStringWidth(
681 l10n_util::GetStringFUTF16Int(IDS_ZOOM_PERCENT, 100), font_list);
684 return max_w + border_width;
687 // Index of the fullscreen menu item in the model.
688 const int fullscreen_index_;
690 scoped_ptr<content::HostZoomMap::Subscription> content_zoom_subscription_;
691 scoped_ptr<content::HostZoomMap::Subscription> browser_zoom_subscription_;
692 content::NotificationRegistrar registrar_;
694 // Button for incrementing the zoom.
695 LabelButton* increment_button_;
697 // Label showing zoom as a percent.
700 // Button for decrementing the zoom.
701 LabelButton* decrement_button_;
703 ImageButton* fullscreen_button_;
705 // Width given to |zoom_label_|. This is the width at 100%.
706 int zoom_label_width_;
708 DISALLOW_COPY_AND_ASSIGN(ZoomView);
711 // RecentTabsMenuModelDelegate ------------------------------------------------
713 // Provides the ui::MenuModelDelegate implementation for RecentTabsSubMenuModel
715 class WrenchMenu::RecentTabsMenuModelDelegate : public ui::MenuModelDelegate {
717 RecentTabsMenuModelDelegate(WrenchMenu* wrench_menu,
718 ui::MenuModel* model,
719 views::MenuItemView* menu_item)
720 : wrench_menu_(wrench_menu),
722 menu_item_(menu_item) {
723 model_->SetMenuModelDelegate(this);
726 virtual ~RecentTabsMenuModelDelegate() {
727 model_->SetMenuModelDelegate(NULL);
730 // Return the specific menu width of recent tabs submenu if |menu| is the
731 // recent tabs submenu, else return -1.
732 int GetMaxWidthForMenu(views::MenuItemView* menu) {
733 if (!menu_item_->HasSubmenu())
735 const int kMaxMenuItemWidth = 320;
736 return menu->GetCommand() == menu_item_->GetCommand() ?
737 kMaxMenuItemWidth : -1;
740 const gfx::FontList* GetLabelFontListAt(int index) const {
741 return model_->GetLabelFontListAt(index);
744 bool GetShouldUseDisabledEmphasizedForegroundColor(int index) const {
745 // The items for which we get a font list, should be shown in the bolded
747 return GetLabelFontListAt(index) ? true : false;
750 // ui::MenuModelDelegate implementation:
752 virtual void OnIconChanged(int index) OVERRIDE {
753 int command_id = model_->GetCommandIdAt(index);
754 views::MenuItemView* item = menu_item_->GetMenuItemByID(command_id);
757 model_->GetIconAt(index, &icon);
758 item->SetIcon(*icon.ToImageSkia());
761 virtual void OnMenuStructureChanged() OVERRIDE {
762 if (menu_item_->HasSubmenu()) {
763 // Remove all menu items from submenu.
764 views::SubmenuView* submenu = menu_item_->GetSubmenu();
765 while (submenu->child_count() > 0)
766 menu_item_->RemoveMenuItemAt(submenu->child_count() - 1);
768 // Remove all elements in |WrenchMenu::command_id_to_entry_| that map to
770 WrenchMenu::CommandIDToEntry::iterator iter =
771 wrench_menu_->command_id_to_entry_.begin();
772 while (iter != wrench_menu_->command_id_to_entry_.end()) {
773 if (iter->second.first == model_)
774 wrench_menu_->command_id_to_entry_.erase(iter++);
780 // Add all menu items from |model| to submenu.
781 for (int i = 0; i < model_->GetItemCount(); ++i) {
782 wrench_menu_->AddMenuItem(menu_item_, i, model_, i, model_->GetTypeAt(i));
785 // In case recent tabs submenu was open when items were changing, force a
786 // ChildrenChanged().
787 menu_item_->ChildrenChanged();
791 WrenchMenu* wrench_menu_;
792 ui::MenuModel* model_;
793 views::MenuItemView* menu_item_;
795 DISALLOW_COPY_AND_ASSIGN(RecentTabsMenuModelDelegate);
798 // WrenchMenu ------------------------------------------------------------------
800 WrenchMenu::WrenchMenu(Browser* browser, int run_flags)
803 selected_menu_model_(NULL),
805 bookmark_menu_(NULL),
806 feedback_menu_item_(NULL),
807 run_flags_(run_flags) {
808 registrar_.Add(this, chrome::NOTIFICATION_GLOBAL_ERRORS_CHANGED,
809 content::Source<Profile>(browser_->profile()));
812 WrenchMenu::~WrenchMenu() {
813 if (bookmark_menu_delegate_.get()) {
814 BookmarkModel* model = BookmarkModelFactory::GetForProfile(
815 browser_->profile());
817 model->RemoveObserver(this);
819 FOR_EACH_OBSERVER(WrenchMenuObserver, observer_list_, WrenchMenuDestroyed());
822 void WrenchMenu::Init(ui::MenuModel* model) {
824 root_ = new MenuItemView(this);
825 root_->set_has_icons(true); // We have checks, radios and icons, set this
826 // so we get the taller menu style.
827 PopulateMenu(root_, model);
830 // Verify that the reserved command ID's for bookmarks menu are not used.
831 for (int i = WrenchMenuModel:kMinBookmarkCommandId;
832 i <= WrenchMenuModel::kMaxBookmarkCommandId; ++i)
833 DCHECK(command_id_to_entry_.find(i) == command_id_to_entry_.end());
834 #endif // defined(DEBUG)
836 int32 types = views::MenuRunner::HAS_MNEMONICS;
838 // We add NESTED_DRAG since currently the only operation to open the wrench
839 // menu for is an extension action drag, which is controlled by the child
840 // BrowserActionsContainer view.
841 types |= views::MenuRunner::FOR_DROP | views::MenuRunner::NESTED_DRAG;
843 menu_runner_.reset(new views::MenuRunner(root_, types));
846 void WrenchMenu::RunMenu(views::MenuButton* host) {
847 gfx::Point screen_loc;
848 views::View::ConvertPointToScreen(host, &screen_loc);
849 gfx::Rect bounds(screen_loc, host->size());
850 content::RecordAction(UserMetricsAction("ShowAppMenu"));
851 if (menu_runner_->RunMenuAt(host->GetWidget(),
854 views::MENU_ANCHOR_TOPRIGHT,
855 ui::MENU_SOURCE_NONE) ==
856 views::MenuRunner::MENU_DELETED)
858 if (bookmark_menu_delegate_.get()) {
859 BookmarkModel* model = BookmarkModelFactory::GetForProfile(
860 browser_->profile());
862 model->RemoveObserver(this);
864 if (selected_menu_model_)
865 selected_menu_model_->ActivatedAt(selected_index_);
868 void WrenchMenu::CloseMenu() {
869 if (menu_runner_.get())
870 menu_runner_->Cancel();
873 bool WrenchMenu::IsShowing() {
874 return menu_runner_.get() && menu_runner_->IsRunning();
877 void WrenchMenu::AddObserver(WrenchMenuObserver* observer) {
878 observer_list_.AddObserver(observer);
881 void WrenchMenu::RemoveObserver(WrenchMenuObserver* observer) {
882 observer_list_.RemoveObserver(observer);
885 const gfx::FontList* WrenchMenu::GetLabelFontList(int command_id) const {
886 if (IsRecentTabsCommand(command_id)) {
887 return recent_tabs_menu_model_delegate_->GetLabelFontListAt(
888 ModelIndexFromCommandId(command_id));
893 bool WrenchMenu::GetShouldUseDisabledEmphasizedForegroundColor(
894 int command_id) const {
895 if (IsRecentTabsCommand(command_id)) {
896 return recent_tabs_menu_model_delegate_->
897 GetShouldUseDisabledEmphasizedForegroundColor(
898 ModelIndexFromCommandId(command_id));
903 base::string16 WrenchMenu::GetTooltipText(int command_id,
904 const gfx::Point& p) const {
905 return IsBookmarkCommand(command_id) ?
906 bookmark_menu_delegate_->GetTooltipText(command_id, p) : base::string16();
909 bool WrenchMenu::IsTriggerableEvent(views::MenuItemView* menu,
910 const ui::Event& e) {
911 return IsBookmarkCommand(menu->GetCommand()) ?
912 bookmark_menu_delegate_->IsTriggerableEvent(menu, e) :
913 MenuDelegate::IsTriggerableEvent(menu, e);
916 bool WrenchMenu::GetDropFormats(
919 std::set<ui::OSExchangeData::CustomFormat>* custom_formats) {
920 CreateBookmarkMenu();
921 return bookmark_menu_delegate_.get() &&
922 bookmark_menu_delegate_->GetDropFormats(menu, formats, custom_formats);
925 bool WrenchMenu::AreDropTypesRequired(MenuItemView* menu) {
926 CreateBookmarkMenu();
927 return bookmark_menu_delegate_.get() &&
928 bookmark_menu_delegate_->AreDropTypesRequired(menu);
931 bool WrenchMenu::CanDrop(MenuItemView* menu,
932 const ui::OSExchangeData& data) {
933 CreateBookmarkMenu();
934 return bookmark_menu_delegate_.get() &&
935 bookmark_menu_delegate_->CanDrop(menu, data);
938 int WrenchMenu::GetDropOperation(
940 const ui::DropTargetEvent& event,
941 DropPosition* position) {
942 return IsBookmarkCommand(item->GetCommand()) ?
943 bookmark_menu_delegate_->GetDropOperation(item, event, position) :
944 ui::DragDropTypes::DRAG_NONE;
947 int WrenchMenu::OnPerformDrop(MenuItemView* menu,
948 DropPosition position,
949 const ui::DropTargetEvent& event) {
950 if (!IsBookmarkCommand(menu->GetCommand()))
951 return ui::DragDropTypes::DRAG_NONE;
953 int result = bookmark_menu_delegate_->OnPerformDrop(menu, position, event);
957 bool WrenchMenu::ShowContextMenu(MenuItemView* source,
960 ui::MenuSourceType source_type) {
961 return IsBookmarkCommand(command_id) ?
962 bookmark_menu_delegate_->ShowContextMenu(source, command_id, p,
967 bool WrenchMenu::CanDrag(MenuItemView* menu) {
968 return IsBookmarkCommand(menu->GetCommand()) ?
969 bookmark_menu_delegate_->CanDrag(menu) : false;
972 void WrenchMenu::WriteDragData(MenuItemView* sender,
973 ui::OSExchangeData* data) {
974 DCHECK(IsBookmarkCommand(sender->GetCommand()));
975 return bookmark_menu_delegate_->WriteDragData(sender, data);
978 int WrenchMenu::GetDragOperations(MenuItemView* sender) {
979 return IsBookmarkCommand(sender->GetCommand()) ?
980 bookmark_menu_delegate_->GetDragOperations(sender) :
981 MenuDelegate::GetDragOperations(sender);
984 int WrenchMenu::GetMaxWidthForMenu(MenuItemView* menu) {
985 if (IsBookmarkCommand(menu->GetCommand()))
986 return bookmark_menu_delegate_->GetMaxWidthForMenu(menu);
988 // If recent tabs menu is available, it will decide if |menu| is one of recent
989 // tabs; if yes, it would return the menu width for recent tabs.
990 // otherwise, it would return -1.
991 if (recent_tabs_menu_model_delegate_.get())
992 max_width = recent_tabs_menu_model_delegate_->GetMaxWidthForMenu(menu);
994 max_width = MenuDelegate::GetMaxWidthForMenu(menu);
998 bool WrenchMenu::IsItemChecked(int command_id) const {
999 if (IsBookmarkCommand(command_id))
1002 const Entry& entry = command_id_to_entry_.find(command_id)->second;
1003 return entry.first->IsItemCheckedAt(entry.second);
1006 bool WrenchMenu::IsCommandEnabled(int command_id) const {
1007 if (IsBookmarkCommand(command_id))
1010 if (command_id == 0)
1011 return false; // The root item.
1013 // The items representing the cut menu (cut/copy/paste), zoom menu
1014 // (increment/decrement/reset) and extension toolbar view are always enabled.
1015 // The child views of these items enabled state updates appropriately.
1016 if (command_id == IDC_CUT || command_id == IDC_ZOOM_MINUS ||
1017 command_id == IDC_EXTENSIONS_OVERFLOW_MENU)
1020 const Entry& entry = command_id_to_entry_.find(command_id)->second;
1021 return entry.first->IsEnabledAt(entry.second);
1024 void WrenchMenu::ExecuteCommand(int command_id, int mouse_event_flags) {
1025 if (IsBookmarkCommand(command_id)) {
1026 bookmark_menu_delegate_->ExecuteCommand(command_id, mouse_event_flags);
1030 if (command_id == IDC_CUT || command_id == IDC_ZOOM_MINUS ||
1031 command_id == IDC_EXTENSIONS_OVERFLOW_MENU) {
1032 // These items are represented by child views. If ExecuteCommand is invoked
1033 // it means the user clicked on the area around the buttons and we should
1038 const Entry& entry = command_id_to_entry_.find(command_id)->second;
1039 return entry.first->ActivatedAt(entry.second, mouse_event_flags);
1042 bool WrenchMenu::GetAccelerator(int command_id,
1043 ui::Accelerator* accelerator) const {
1044 if (IsBookmarkCommand(command_id))
1047 if (command_id == IDC_CUT || command_id == IDC_ZOOM_MINUS ||
1048 command_id == IDC_EXTENSIONS_OVERFLOW_MENU) {
1049 // These have special child views; don't show the accelerator for them.
1053 CommandIDToEntry::const_iterator ix = command_id_to_entry_.find(command_id);
1054 const Entry& entry = ix->second;
1055 ui::Accelerator menu_accelerator;
1056 if (!entry.first->GetAcceleratorAt(entry.second, &menu_accelerator))
1059 *accelerator = ui::Accelerator(menu_accelerator.key_code(),
1060 menu_accelerator.modifiers());
1064 void WrenchMenu::WillShowMenu(MenuItemView* menu) {
1065 if (menu == bookmark_menu_)
1066 CreateBookmarkMenu();
1069 void WrenchMenu::WillHideMenu(MenuItemView* menu) {
1070 // Turns off the fade out animation of the wrench menus if
1071 // |feedback_menu_item_| is selected. This excludes the wrench menu itself
1072 // from the snapshot in the feedback UI.
1073 if (menu->HasSubmenu() && feedback_menu_item_ &&
1074 feedback_menu_item_->IsSelected()) {
1075 // It's okay to just turn off the animation and no to take care the
1076 // animation back because the menu widget will be recreated next time
1077 // it's opened. See ToolbarView::RunMenu() and Init() of this class.
1078 menu->GetSubmenu()->GetWidget()->
1079 SetVisibilityChangedAnimationsEnabled(false);
1083 bool WrenchMenu::ShouldCloseOnDragComplete() {
1087 void WrenchMenu::BookmarkModelChanged() {
1088 DCHECK(bookmark_menu_delegate_.get());
1089 if (!bookmark_menu_delegate_->is_mutating_model())
1093 void WrenchMenu::Observe(int type,
1094 const content::NotificationSource& source,
1095 const content::NotificationDetails& details) {
1097 case chrome::NOTIFICATION_GLOBAL_ERRORS_CHANGED:
1098 // A change in the global errors list can add or remove items from the
1099 // menu. Close the menu to avoid have a stale menu on-screen.
1108 void WrenchMenu::PopulateMenu(MenuItemView* parent,
1110 for (int i = 0, max = model->GetItemCount(); i < max; ++i) {
1111 // Add the menu item at the end.
1112 int menu_index = parent->HasSubmenu() ?
1113 parent->GetSubmenu()->child_count() : 0;
1114 MenuItemView* item =
1115 AddMenuItem(parent, menu_index, model, i, model->GetTypeAt(i));
1117 if (model->GetCommandIdAt(i) == IDC_CUT ||
1118 model->GetCommandIdAt(i) == IDC_ZOOM_MINUS) {
1119 const MenuConfig& config = item->GetMenuConfig();
1120 int top_margin = config.item_top_margin + config.separator_height / 2;
1122 config.item_bottom_margin + config.separator_height / 2;
1124 // Chromeos adds extra vertical space for the menu buttons.
1125 #if defined(OS_CHROMEOS)
1130 item->SetMargins(top_margin, bottom_margin);
1133 if (model->GetTypeAt(i) == MenuModel::TYPE_SUBMENU)
1134 PopulateMenu(item, model->GetSubmenuModelAt(i));
1136 switch (model->GetCommandIdAt(i)) {
1137 case IDC_EXTENSIONS_OVERFLOW_MENU: {
1138 scoped_ptr<ExtensionToolbarMenuView> extension_toolbar(
1139 new ExtensionToolbarMenuView(browser_, this));
1140 if (extension_toolbar->ShouldShow())
1141 item->AddChildView(extension_toolbar.release());
1143 item->SetVisible(false);
1148 DCHECK_EQ(MenuModel::TYPE_COMMAND, model->GetTypeAt(i));
1149 DCHECK_LT(i + 2, max);
1150 DCHECK_EQ(IDC_COPY, model->GetCommandIdAt(i + 1));
1151 DCHECK_EQ(IDC_PASTE, model->GetCommandIdAt(i + 2));
1152 item->SetTitle(l10n_util::GetStringUTF16(IDS_EDIT2));
1153 item->AddChildView(new CutCopyPasteView(this, model,
1158 case IDC_ZOOM_MINUS:
1159 DCHECK_EQ(MenuModel::TYPE_COMMAND, model->GetTypeAt(i));
1160 DCHECK_EQ(IDC_ZOOM_PLUS, model->GetCommandIdAt(i + 1));
1161 DCHECK_EQ(IDC_FULLSCREEN, model->GetCommandIdAt(i + 2));
1162 item->SetTitle(l10n_util::GetStringUTF16(IDS_ZOOM_MENU2));
1163 item->AddChildView(new ZoomView(this, model, i, i + 1, i + 2));
1167 case IDC_BOOKMARKS_MENU:
1168 DCHECK(!bookmark_menu_);
1169 bookmark_menu_ = item;
1172 #if defined(GOOGLE_CHROME_BUILD)
1174 DCHECK(!feedback_menu_item_);
1175 feedback_menu_item_ = item;
1179 case IDC_RECENT_TABS_MENU:
1180 DCHECK(!recent_tabs_menu_model_delegate_.get());
1181 recent_tabs_menu_model_delegate_.reset(
1182 new RecentTabsMenuModelDelegate(this, model->GetSubmenuModelAt(i),
1192 MenuItemView* WrenchMenu::AddMenuItem(MenuItemView* parent,
1196 MenuModel::ItemType menu_type) {
1197 int command_id = model->GetCommandIdAt(model_index);
1198 DCHECK(command_id > -1 ||
1199 (command_id == -1 &&
1200 model->GetTypeAt(model_index) == MenuModel::TYPE_SEPARATOR));
1202 if (command_id > -1) { // Don't add separators to |command_id_to_entry_|.
1203 // All command ID's should be unique except for IDC_SHOW_HISTORY which is
1204 // in both wrench menu and RecentTabs submenu,
1205 if (command_id != IDC_SHOW_HISTORY) {
1206 DCHECK(command_id_to_entry_.find(command_id) ==
1207 command_id_to_entry_.end())
1208 << "command ID " << command_id << " already exists!";
1210 command_id_to_entry_[command_id].first = model;
1211 command_id_to_entry_[command_id].second = model_index;
1214 MenuItemView* menu_item = views::MenuModelAdapter::AddMenuItemFromModelAt(
1215 model, model_index, parent, menu_index, command_id);
1218 // Flush all buttons to the right side of the menu for the new menu type.
1219 menu_item->set_use_right_margin(false);
1220 menu_item->SetVisible(model->IsVisibleAt(model_index));
1222 if (menu_type == MenuModel::TYPE_COMMAND && model->HasIcons()) {
1224 if (model->GetIconAt(model_index, &icon))
1225 menu_item->SetIcon(*icon.ToImageSkia());
1232 void WrenchMenu::CancelAndEvaluate(MenuModel* model, int index) {
1233 selected_menu_model_ = model;
1234 selected_index_ = index;
1238 void WrenchMenu::CreateBookmarkMenu() {
1239 if (bookmark_menu_delegate_.get())
1240 return; // Already created the menu.
1242 BookmarkModel* model =
1243 BookmarkModelFactory::GetForProfile(browser_->profile());
1244 if (!model->loaded())
1247 model->AddObserver(this);
1249 // TODO(oshima): Replace with views only API.
1250 views::Widget* parent = views::Widget::GetWidgetForNativeWindow(
1251 browser_->window()->GetNativeWindow());
1252 bookmark_menu_delegate_.reset(
1253 new BookmarkMenuDelegate(browser_,
1256 WrenchMenuModel::kMinBookmarkCommandId,
1257 WrenchMenuModel::kMaxBookmarkCommandId));
1258 bookmark_menu_delegate_->Init(this,
1260 model->bookmark_bar_node(),
1262 BookmarkMenuDelegate::SHOW_PERMANENT_FOLDERS,
1263 BOOKMARK_LAUNCH_LOCATION_WRENCH_MENU);
1266 int WrenchMenu::ModelIndexFromCommandId(int command_id) const {
1267 CommandIDToEntry::const_iterator ix = command_id_to_entry_.find(command_id);
1268 DCHECK(ix != command_id_to_entry_.end());
1269 return ix->second.second;