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 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 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 ~InMenuButton() override {}
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 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 ~WrenchMenuView() override {
324 menu_->RemoveObserver(this);
327 // Overridden from views::View.
328 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 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 ~HoveredImageSource() override {}
398 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 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 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 void ButtonPressed(views::Button* sender, const ui::Event& event) override {
462 menu()->CancelAndEvaluate(menu_model(), sender->tag());
466 // Returns the max preferred width of all the children.
467 int GetMaxChildViewPreferredWidth() const {
469 for (int i = 0; i < child_count(); ++i)
470 width = std::max(width, child_at(i)->GetPreferredSize().width());
474 DISALLOW_COPY_AND_ASSIGN(CutCopyPasteView);
477 // ZoomView --------------------------------------------------------------------
480 // ZoomView contains the various zoom controls: two buttons to increase/decrease
481 // the zoom, a label showing the current zoom percent, and a button to go
483 class WrenchMenu::ZoomView : public WrenchMenuView {
485 ZoomView(WrenchMenu* menu,
486 MenuModel* menu_model,
489 int fullscreen_index)
490 : WrenchMenuView(menu, menu_model),
491 fullscreen_index_(fullscreen_index),
492 increment_button_(NULL),
494 decrement_button_(NULL),
495 fullscreen_button_(NULL),
496 zoom_label_width_(0) {
497 content_zoom_subscription_ = HostZoomMap::GetDefaultForBrowserContext(
498 menu->browser_->profile())->AddZoomLevelChangedCallback(
499 base::Bind(&WrenchMenu::ZoomView::OnZoomLevelChanged,
500 base::Unretained(this)));
502 browser_zoom_subscription_ = ZoomEventManager::GetForBrowserContext(
503 menu->browser_->profile())->AddZoomLevelChangedCallback(
504 base::Bind(&WrenchMenu::ZoomView::OnZoomLevelChanged,
505 base::Unretained(this)));
507 decrement_button_ = CreateButtonWithAccName(
508 IDS_ZOOM_MINUS2, InMenuButtonBackground::LEFT_BUTTON,
509 decrement_index, IDS_ACCNAME_ZOOM_MINUS2);
511 zoom_label_ = new Label(
512 l10n_util::GetStringFUTF16Int(IDS_ZOOM_PERCENT, 100));
513 zoom_label_->SetAutoColorReadabilityEnabled(false);
514 zoom_label_->SetHorizontalAlignment(gfx::ALIGN_RIGHT);
516 InMenuButtonBackground* center_bg =
517 new InMenuButtonBackground(InMenuButtonBackground::RIGHT_BUTTON);
518 zoom_label_->set_background(center_bg);
520 AddChildView(zoom_label_);
521 zoom_label_width_ = MaxWidthForZoomLabel();
523 increment_button_ = CreateButtonWithAccName(
524 IDS_ZOOM_PLUS2, InMenuButtonBackground::RIGHT_BUTTON,
525 increment_index, IDS_ACCNAME_ZOOM_PLUS2);
527 center_bg->SetOtherButtons(decrement_button_, increment_button_);
529 fullscreen_button_ = new FullscreenButton(this);
530 // all buttons on menu should must be a custom button in order for
531 // the keyboard nativigation work.
532 DCHECK(CustomButton::AsCustomButton(fullscreen_button_));
533 gfx::ImageSkia* full_screen_image =
534 ui::ResourceBundle::GetSharedInstance().GetImageSkiaNamed(
535 IDR_FULLSCREEN_MENU_BUTTON);
536 fullscreen_button_->SetImage(ImageButton::STATE_NORMAL, full_screen_image);
538 fullscreen_button_->SetFocusable(true);
539 fullscreen_button_->set_request_focus_on_press(false);
540 fullscreen_button_->set_tag(fullscreen_index);
541 fullscreen_button_->SetImageAlignment(
542 ImageButton::ALIGN_CENTER, ImageButton::ALIGN_MIDDLE);
543 fullscreen_button_->set_background(
544 new InMenuButtonBackground(InMenuButtonBackground::SINGLE_BUTTON));
545 fullscreen_button_->SetAccessibleName(
546 GetAccessibleNameForWrenchMenuItem(
547 menu_model, fullscreen_index, IDS_ACCNAME_FULLSCREEN));
548 AddChildView(fullscreen_button_);
550 // Need to set a font list for the zoom label width calculations.
551 OnNativeThemeChanged(NULL);
552 UpdateZoomControls();
555 ~ZoomView() override {}
557 // Overridden from View.
558 gfx::Size GetPreferredSize() const override {
559 // The increment/decrement button are forced to the same width.
560 int button_width = std::max(increment_button_->GetPreferredSize().width(),
561 decrement_button_->GetPreferredSize().width());
562 int fullscreen_width =
563 fullscreen_button_->GetPreferredSize().width() + kFullscreenPadding;
564 // Returned height doesn't matter as MenuItemView forces everything to the
565 // height of the menuitemview. Note that we have overridden the height when
566 // constructing the menu.
567 return gfx::Size(button_width + zoom_label_width_ + button_width +
568 fullscreen_width, 0);
571 void Layout() override {
573 int button_width = std::max(increment_button_->GetPreferredSize().width(),
574 decrement_button_->GetPreferredSize().width());
575 gfx::Rect bounds(0, 0, button_width, height());
577 decrement_button_->SetBoundsRect(bounds);
581 bounds.set_width(zoom_label_width_);
582 zoom_label_->SetBoundsRect(bounds);
586 bounds.set_width(button_width);
587 increment_button_->SetBoundsRect(bounds);
591 bounds.set_width(fullscreen_button_->GetPreferredSize().width() +
593 fullscreen_button_->SetBoundsRect(bounds);
596 void OnNativeThemeChanged(const ui::NativeTheme* theme) override {
597 WrenchMenuView::OnNativeThemeChanged(theme);
599 const MenuConfig& menu_config = MenuConfig::instance(theme);
600 zoom_label_->SetBorder(views::Border::CreateEmptyBorder(
601 0, kZoomLabelHorizontalPadding, 0, kZoomLabelHorizontalPadding));
602 zoom_label_->SetFontList(menu_config.font_list);
603 zoom_label_width_ = MaxWidthForZoomLabel();
606 zoom_label_->SetEnabledColor(theme->GetSystemColor(
607 ui::NativeTheme::kColorId_EnabledMenuItemForegroundColor));
608 gfx::ImageSkia* full_screen_image =
609 ui::ResourceBundle::GetSharedInstance().GetImageSkiaNamed(
610 IDR_FULLSCREEN_MENU_BUTTON);
611 SkColor fg_color = theme->GetSystemColor(
612 ui::NativeTheme::kColorId_SelectedMenuItemForegroundColor);
613 gfx::ImageSkia hovered_fullscreen_image(
614 new HoveredImageSource(*full_screen_image, fg_color),
615 full_screen_image->size());
616 fullscreen_button_->SetImage(
617 ImageButton::STATE_HOVERED, &hovered_fullscreen_image);
618 fullscreen_button_->SetImage(
619 ImageButton::STATE_PRESSED, &hovered_fullscreen_image);
623 // Overridden from ButtonListener.
624 void ButtonPressed(views::Button* sender, const ui::Event& event) override {
625 if (sender->tag() == fullscreen_index_) {
626 menu()->CancelAndEvaluate(menu_model(), sender->tag());
628 // Zoom buttons don't close the menu.
629 menu_model()->ActivatedAt(sender->tag());
633 // Overridden from WrenchMenuObserver.
634 void WrenchMenuDestroyed() override { WrenchMenuView::WrenchMenuDestroyed(); }
637 void OnZoomLevelChanged(const HostZoomMap::ZoomLevelChange& change) {
638 UpdateZoomControls();
641 void UpdateZoomControls() {
642 WebContents* selected_tab =
643 menu()->browser_->tab_strip_model()->GetActiveWebContents();
646 zoom = ZoomController::FromWebContents(selected_tab)->GetZoomPercent();
647 increment_button_->SetEnabled(zoom < selected_tab->GetMaximumZoomPercent());
648 decrement_button_->SetEnabled(zoom > selected_tab->GetMinimumZoomPercent());
649 zoom_label_->SetText(
650 l10n_util::GetStringFUTF16Int(IDS_ZOOM_PERCENT, zoom));
652 zoom_label_width_ = MaxWidthForZoomLabel();
655 // Calculates the max width the zoom string can be.
656 int MaxWidthForZoomLabel() {
657 const gfx::FontList& font_list = zoom_label_->font_list();
659 zoom_label_->border() ? zoom_label_->border()->GetInsets().width() : 0;
663 WebContents* selected_tab =
664 menu()->browser_->tab_strip_model()->GetActiveWebContents();
666 int min_percent = selected_tab->GetMinimumZoomPercent();
667 int max_percent = selected_tab->GetMaximumZoomPercent();
669 int step = (max_percent - min_percent) / 10;
670 for (int i = min_percent; i <= max_percent; i += step) {
671 int w = gfx::GetStringWidth(
672 l10n_util::GetStringFUTF16Int(IDS_ZOOM_PERCENT, i), font_list);
673 max_w = std::max(w, max_w);
676 max_w = gfx::GetStringWidth(
677 l10n_util::GetStringFUTF16Int(IDS_ZOOM_PERCENT, 100), font_list);
680 return max_w + border_width;
683 // Index of the fullscreen menu item in the model.
684 const int fullscreen_index_;
686 scoped_ptr<content::HostZoomMap::Subscription> content_zoom_subscription_;
687 scoped_ptr<content::HostZoomMap::Subscription> browser_zoom_subscription_;
688 content::NotificationRegistrar registrar_;
690 // Button for incrementing the zoom.
691 LabelButton* increment_button_;
693 // Label showing zoom as a percent.
696 // Button for decrementing the zoom.
697 LabelButton* decrement_button_;
699 ImageButton* fullscreen_button_;
701 // Width given to |zoom_label_|. This is the width at 100%.
702 int zoom_label_width_;
704 DISALLOW_COPY_AND_ASSIGN(ZoomView);
707 // RecentTabsMenuModelDelegate ------------------------------------------------
709 // Provides the ui::MenuModelDelegate implementation for RecentTabsSubMenuModel
711 class WrenchMenu::RecentTabsMenuModelDelegate : public ui::MenuModelDelegate {
713 RecentTabsMenuModelDelegate(WrenchMenu* wrench_menu,
714 ui::MenuModel* model,
715 views::MenuItemView* menu_item)
716 : wrench_menu_(wrench_menu),
718 menu_item_(menu_item) {
719 model_->SetMenuModelDelegate(this);
722 ~RecentTabsMenuModelDelegate() override {
723 model_->SetMenuModelDelegate(NULL);
726 const gfx::FontList* GetLabelFontListAt(int index) const {
727 return model_->GetLabelFontListAt(index);
730 bool GetShouldUseDisabledEmphasizedForegroundColor(int index) const {
731 // The items for which we get a font list, should be shown in the bolded
733 return GetLabelFontListAt(index) ? true : false;
736 // ui::MenuModelDelegate implementation:
738 void OnIconChanged(int index) override {
739 int command_id = model_->GetCommandIdAt(index);
740 views::MenuItemView* item = menu_item_->GetMenuItemByID(command_id);
743 model_->GetIconAt(index, &icon);
744 item->SetIcon(*icon.ToImageSkia());
747 void OnMenuStructureChanged() override {
748 if (menu_item_->HasSubmenu()) {
749 // Remove all menu items from submenu.
750 views::SubmenuView* submenu = menu_item_->GetSubmenu();
751 while (submenu->child_count() > 0)
752 menu_item_->RemoveMenuItemAt(submenu->child_count() - 1);
754 // Remove all elements in |WrenchMenu::command_id_to_entry_| that map to
756 WrenchMenu::CommandIDToEntry::iterator iter =
757 wrench_menu_->command_id_to_entry_.begin();
758 while (iter != wrench_menu_->command_id_to_entry_.end()) {
759 if (iter->second.first == model_)
760 wrench_menu_->command_id_to_entry_.erase(iter++);
766 // Add all menu items from |model| to submenu.
767 for (int i = 0; i < model_->GetItemCount(); ++i) {
768 wrench_menu_->AddMenuItem(menu_item_, i, model_, i, model_->GetTypeAt(i));
771 // In case recent tabs submenu was open when items were changing, force a
772 // ChildrenChanged().
773 menu_item_->ChildrenChanged();
777 WrenchMenu* wrench_menu_;
778 ui::MenuModel* model_;
779 views::MenuItemView* menu_item_;
781 DISALLOW_COPY_AND_ASSIGN(RecentTabsMenuModelDelegate);
784 // WrenchMenu ------------------------------------------------------------------
786 WrenchMenu::WrenchMenu(Browser* browser, int run_flags)
789 selected_menu_model_(NULL),
791 bookmark_menu_(NULL),
792 feedback_menu_item_(NULL),
793 run_flags_(run_flags) {
794 registrar_.Add(this, chrome::NOTIFICATION_GLOBAL_ERRORS_CHANGED,
795 content::Source<Profile>(browser_->profile()));
798 WrenchMenu::~WrenchMenu() {
799 if (bookmark_menu_delegate_.get()) {
800 BookmarkModel* model = BookmarkModelFactory::GetForProfile(
801 browser_->profile());
803 model->RemoveObserver(this);
805 FOR_EACH_OBSERVER(WrenchMenuObserver, observer_list_, WrenchMenuDestroyed());
808 void WrenchMenu::Init(ui::MenuModel* model) {
810 root_ = new MenuItemView(this);
811 root_->set_has_icons(true); // We have checks, radios and icons, set this
812 // so we get the taller menu style.
813 PopulateMenu(root_, model);
816 // Verify that the reserved command ID's for bookmarks menu are not used.
817 for (int i = WrenchMenuModel::kMinBookmarkCommandId;
818 i <= WrenchMenuModel::kMaxBookmarkCommandId; ++i)
819 DCHECK(command_id_to_entry_.find(i) == command_id_to_entry_.end());
820 #endif // !defined(NDEBUG)
822 int32 types = views::MenuRunner::HAS_MNEMONICS;
824 // We add NESTED_DRAG since currently the only operation to open the wrench
825 // menu for is an extension action drag, which is controlled by the child
826 // BrowserActionsContainer view.
827 types |= views::MenuRunner::FOR_DROP | views::MenuRunner::NESTED_DRAG;
829 menu_runner_.reset(new views::MenuRunner(root_, types));
832 void WrenchMenu::RunMenu(views::MenuButton* host) {
833 gfx::Point screen_loc;
834 views::View::ConvertPointToScreen(host, &screen_loc);
835 gfx::Rect bounds(screen_loc, host->size());
836 content::RecordAction(UserMetricsAction("ShowAppMenu"));
837 if (menu_runner_->RunMenuAt(host->GetWidget(),
840 views::MENU_ANCHOR_TOPRIGHT,
841 ui::MENU_SOURCE_NONE) ==
842 views::MenuRunner::MENU_DELETED)
844 if (bookmark_menu_delegate_.get()) {
845 BookmarkModel* model = BookmarkModelFactory::GetForProfile(
846 browser_->profile());
848 model->RemoveObserver(this);
850 if (selected_menu_model_)
851 selected_menu_model_->ActivatedAt(selected_index_);
854 void WrenchMenu::CloseMenu() {
855 if (menu_runner_.get())
856 menu_runner_->Cancel();
859 bool WrenchMenu::IsShowing() {
860 return menu_runner_.get() && menu_runner_->IsRunning();
863 void WrenchMenu::AddObserver(WrenchMenuObserver* observer) {
864 observer_list_.AddObserver(observer);
867 void WrenchMenu::RemoveObserver(WrenchMenuObserver* observer) {
868 observer_list_.RemoveObserver(observer);
871 const gfx::FontList* WrenchMenu::GetLabelFontList(int command_id) const {
872 if (IsRecentTabsCommand(command_id)) {
873 return recent_tabs_menu_model_delegate_->GetLabelFontListAt(
874 ModelIndexFromCommandId(command_id));
879 bool WrenchMenu::GetShouldUseDisabledEmphasizedForegroundColor(
880 int command_id) const {
881 if (IsRecentTabsCommand(command_id)) {
882 return recent_tabs_menu_model_delegate_->
883 GetShouldUseDisabledEmphasizedForegroundColor(
884 ModelIndexFromCommandId(command_id));
889 base::string16 WrenchMenu::GetTooltipText(int command_id,
890 const gfx::Point& p) const {
891 return IsBookmarkCommand(command_id) ?
892 bookmark_menu_delegate_->GetTooltipText(command_id, p) : base::string16();
895 bool WrenchMenu::IsTriggerableEvent(views::MenuItemView* menu,
896 const ui::Event& e) {
897 return IsBookmarkCommand(menu->GetCommand()) ?
898 bookmark_menu_delegate_->IsTriggerableEvent(menu, e) :
899 MenuDelegate::IsTriggerableEvent(menu, e);
902 bool WrenchMenu::GetDropFormats(
905 std::set<ui::OSExchangeData::CustomFormat>* custom_formats) {
906 CreateBookmarkMenu();
907 return bookmark_menu_delegate_.get() &&
908 bookmark_menu_delegate_->GetDropFormats(menu, formats, custom_formats);
911 bool WrenchMenu::AreDropTypesRequired(MenuItemView* menu) {
912 CreateBookmarkMenu();
913 return bookmark_menu_delegate_.get() &&
914 bookmark_menu_delegate_->AreDropTypesRequired(menu);
917 bool WrenchMenu::CanDrop(MenuItemView* menu,
918 const ui::OSExchangeData& data) {
919 CreateBookmarkMenu();
920 return bookmark_menu_delegate_.get() &&
921 bookmark_menu_delegate_->CanDrop(menu, data);
924 int WrenchMenu::GetDropOperation(
926 const ui::DropTargetEvent& event,
927 DropPosition* position) {
928 return IsBookmarkCommand(item->GetCommand()) ?
929 bookmark_menu_delegate_->GetDropOperation(item, event, position) :
930 ui::DragDropTypes::DRAG_NONE;
933 int WrenchMenu::OnPerformDrop(MenuItemView* menu,
934 DropPosition position,
935 const ui::DropTargetEvent& event) {
936 if (!IsBookmarkCommand(menu->GetCommand()))
937 return ui::DragDropTypes::DRAG_NONE;
939 int result = bookmark_menu_delegate_->OnPerformDrop(menu, position, event);
943 bool WrenchMenu::ShowContextMenu(MenuItemView* source,
946 ui::MenuSourceType source_type) {
947 return IsBookmarkCommand(command_id) ?
948 bookmark_menu_delegate_->ShowContextMenu(source, command_id, p,
953 bool WrenchMenu::CanDrag(MenuItemView* menu) {
954 return IsBookmarkCommand(menu->GetCommand()) ?
955 bookmark_menu_delegate_->CanDrag(menu) : false;
958 void WrenchMenu::WriteDragData(MenuItemView* sender,
959 ui::OSExchangeData* data) {
960 DCHECK(IsBookmarkCommand(sender->GetCommand()));
961 return bookmark_menu_delegate_->WriteDragData(sender, data);
964 int WrenchMenu::GetDragOperations(MenuItemView* sender) {
965 return IsBookmarkCommand(sender->GetCommand()) ?
966 bookmark_menu_delegate_->GetDragOperations(sender) :
967 MenuDelegate::GetDragOperations(sender);
970 int WrenchMenu::GetMaxWidthForMenu(MenuItemView* menu) {
971 if (IsBookmarkCommand(menu->GetCommand()))
972 return bookmark_menu_delegate_->GetMaxWidthForMenu(menu);
973 return MenuDelegate::GetMaxWidthForMenu(menu);
976 bool WrenchMenu::IsItemChecked(int command_id) const {
977 if (IsBookmarkCommand(command_id))
980 const Entry& entry = command_id_to_entry_.find(command_id)->second;
981 return entry.first->IsItemCheckedAt(entry.second);
984 bool WrenchMenu::IsCommandEnabled(int command_id) const {
985 if (IsBookmarkCommand(command_id))
989 return false; // The root item.
991 // The items representing the cut menu (cut/copy/paste), zoom menu
992 // (increment/decrement/reset) and extension toolbar view are always enabled.
993 // The child views of these items enabled state updates appropriately.
994 if (command_id == IDC_CUT || command_id == IDC_ZOOM_MINUS ||
995 command_id == IDC_EXTENSIONS_OVERFLOW_MENU)
998 const Entry& entry = command_id_to_entry_.find(command_id)->second;
999 return entry.first->IsEnabledAt(entry.second);
1002 void WrenchMenu::ExecuteCommand(int command_id, int mouse_event_flags) {
1003 if (IsBookmarkCommand(command_id)) {
1004 bookmark_menu_delegate_->ExecuteCommand(command_id, mouse_event_flags);
1008 if (command_id == IDC_CUT || command_id == IDC_ZOOM_MINUS ||
1009 command_id == IDC_EXTENSIONS_OVERFLOW_MENU) {
1010 // These items are represented by child views. If ExecuteCommand is invoked
1011 // it means the user clicked on the area around the buttons and we should
1016 const Entry& entry = command_id_to_entry_.find(command_id)->second;
1017 return entry.first->ActivatedAt(entry.second, mouse_event_flags);
1020 bool WrenchMenu::GetAccelerator(int command_id,
1021 ui::Accelerator* accelerator) const {
1022 if (IsBookmarkCommand(command_id))
1025 if (command_id == IDC_CUT || command_id == IDC_ZOOM_MINUS ||
1026 command_id == IDC_EXTENSIONS_OVERFLOW_MENU) {
1027 // These have special child views; don't show the accelerator for them.
1031 CommandIDToEntry::const_iterator ix = command_id_to_entry_.find(command_id);
1032 const Entry& entry = ix->second;
1033 ui::Accelerator menu_accelerator;
1034 if (!entry.first->GetAcceleratorAt(entry.second, &menu_accelerator))
1037 *accelerator = ui::Accelerator(menu_accelerator.key_code(),
1038 menu_accelerator.modifiers());
1042 void WrenchMenu::WillShowMenu(MenuItemView* menu) {
1043 if (menu == bookmark_menu_)
1044 CreateBookmarkMenu();
1047 void WrenchMenu::WillHideMenu(MenuItemView* menu) {
1048 // Turns off the fade out animation of the wrench menus if
1049 // |feedback_menu_item_| is selected. This excludes the wrench menu itself
1050 // from the snapshot in the feedback UI.
1051 if (menu->HasSubmenu() && feedback_menu_item_ &&
1052 feedback_menu_item_->IsSelected()) {
1053 // It's okay to just turn off the animation and no to take care the
1054 // animation back because the menu widget will be recreated next time
1055 // it's opened. See ToolbarView::RunMenu() and Init() of this class.
1056 menu->GetSubmenu()->GetWidget()->
1057 SetVisibilityChangedAnimationsEnabled(false);
1061 bool WrenchMenu::ShouldCloseOnDragComplete() {
1065 void WrenchMenu::BookmarkModelChanged() {
1066 DCHECK(bookmark_menu_delegate_.get());
1067 if (!bookmark_menu_delegate_->is_mutating_model())
1071 void WrenchMenu::Observe(int type,
1072 const content::NotificationSource& source,
1073 const content::NotificationDetails& details) {
1075 case chrome::NOTIFICATION_GLOBAL_ERRORS_CHANGED:
1076 // A change in the global errors list can add or remove items from the
1077 // menu. Close the menu to avoid have a stale menu on-screen.
1086 void WrenchMenu::PopulateMenu(MenuItemView* parent,
1088 for (int i = 0, max = model->GetItemCount(); i < max; ++i) {
1089 // Add the menu item at the end.
1090 int menu_index = parent->HasSubmenu() ?
1091 parent->GetSubmenu()->child_count() : 0;
1092 MenuItemView* item =
1093 AddMenuItem(parent, menu_index, model, i, model->GetTypeAt(i));
1095 if (model->GetCommandIdAt(i) == IDC_CUT ||
1096 model->GetCommandIdAt(i) == IDC_ZOOM_MINUS) {
1097 const MenuConfig& config = item->GetMenuConfig();
1098 int top_margin = config.item_top_margin + config.separator_height / 2;
1100 config.item_bottom_margin + config.separator_height / 2;
1102 // Chromeos adds extra vertical space for the menu buttons.
1103 #if defined(OS_CHROMEOS)
1108 item->SetMargins(top_margin, bottom_margin);
1111 if (model->GetTypeAt(i) == MenuModel::TYPE_SUBMENU)
1112 PopulateMenu(item, model->GetSubmenuModelAt(i));
1114 switch (model->GetCommandIdAt(i)) {
1115 case IDC_EXTENSIONS_OVERFLOW_MENU: {
1116 scoped_ptr<ExtensionToolbarMenuView> extension_toolbar(
1117 new ExtensionToolbarMenuView(browser_, this));
1118 if (extension_toolbar->ShouldShow())
1119 item->AddChildView(extension_toolbar.release());
1121 item->SetVisible(false);
1126 DCHECK_EQ(MenuModel::TYPE_COMMAND, model->GetTypeAt(i));
1127 DCHECK_LT(i + 2, max);
1128 DCHECK_EQ(IDC_COPY, model->GetCommandIdAt(i + 1));
1129 DCHECK_EQ(IDC_PASTE, model->GetCommandIdAt(i + 2));
1130 item->SetTitle(l10n_util::GetStringUTF16(IDS_EDIT2));
1131 item->AddChildView(new CutCopyPasteView(this, model,
1136 case IDC_ZOOM_MINUS:
1137 DCHECK_EQ(MenuModel::TYPE_COMMAND, model->GetTypeAt(i));
1138 DCHECK_EQ(IDC_ZOOM_PLUS, model->GetCommandIdAt(i + 1));
1139 DCHECK_EQ(IDC_FULLSCREEN, model->GetCommandIdAt(i + 2));
1140 item->SetTitle(l10n_util::GetStringUTF16(IDS_ZOOM_MENU2));
1141 item->AddChildView(new ZoomView(this, model, i, i + 1, i + 2));
1145 case IDC_BOOKMARKS_MENU:
1146 DCHECK(!bookmark_menu_);
1147 bookmark_menu_ = item;
1150 #if defined(GOOGLE_CHROME_BUILD)
1152 DCHECK(!feedback_menu_item_);
1153 feedback_menu_item_ = item;
1157 case IDC_RECENT_TABS_MENU:
1158 DCHECK(!recent_tabs_menu_model_delegate_.get());
1159 recent_tabs_menu_model_delegate_.reset(
1160 new RecentTabsMenuModelDelegate(this, model->GetSubmenuModelAt(i),
1170 MenuItemView* WrenchMenu::AddMenuItem(MenuItemView* parent,
1174 MenuModel::ItemType menu_type) {
1175 int command_id = model->GetCommandIdAt(model_index);
1176 DCHECK(command_id > -1 ||
1177 (command_id == -1 &&
1178 model->GetTypeAt(model_index) == MenuModel::TYPE_SEPARATOR));
1180 if (command_id > -1) { // Don't add separators to |command_id_to_entry_|.
1181 // All command ID's should be unique except for IDC_SHOW_HISTORY which is
1182 // in both wrench menu and RecentTabs submenu,
1183 if (command_id != IDC_SHOW_HISTORY) {
1184 DCHECK(command_id_to_entry_.find(command_id) ==
1185 command_id_to_entry_.end())
1186 << "command ID " << command_id << " already exists!";
1188 command_id_to_entry_[command_id].first = model;
1189 command_id_to_entry_[command_id].second = model_index;
1192 MenuItemView* menu_item = views::MenuModelAdapter::AddMenuItemFromModelAt(
1193 model, model_index, parent, menu_index, command_id);
1196 // Flush all buttons to the right side of the menu for the new menu type.
1197 menu_item->set_use_right_margin(false);
1198 menu_item->SetVisible(model->IsVisibleAt(model_index));
1200 if (menu_type == MenuModel::TYPE_COMMAND && model->HasIcons()) {
1202 if (model->GetIconAt(model_index, &icon))
1203 menu_item->SetIcon(*icon.ToImageSkia());
1210 void WrenchMenu::CancelAndEvaluate(MenuModel* model, int index) {
1211 selected_menu_model_ = model;
1212 selected_index_ = index;
1216 void WrenchMenu::CreateBookmarkMenu() {
1217 if (bookmark_menu_delegate_.get())
1218 return; // Already created the menu.
1220 BookmarkModel* model =
1221 BookmarkModelFactory::GetForProfile(browser_->profile());
1222 if (!model->loaded())
1225 model->AddObserver(this);
1227 // TODO(oshima): Replace with views only API.
1228 views::Widget* parent = views::Widget::GetWidgetForNativeWindow(
1229 browser_->window()->GetNativeWindow());
1230 bookmark_menu_delegate_.reset(
1231 new BookmarkMenuDelegate(browser_,
1234 WrenchMenuModel::kMinBookmarkCommandId,
1235 WrenchMenuModel::kMaxBookmarkCommandId));
1236 bookmark_menu_delegate_->Init(this,
1238 model->bookmark_bar_node(),
1240 BookmarkMenuDelegate::SHOW_PERMANENT_FOLDERS,
1241 BOOKMARK_LAUNCH_LOCATION_WRENCH_MENU);
1244 int WrenchMenu::ModelIndexFromCommandId(int command_id) const {
1245 CommandIDToEntry::const_iterator ix = command_id_to_entry_.find(command_id);
1246 DCHECK(ix != command_id_to_entry_.end());
1247 return ix->second.second;