[Metrics] Make MetricsStateManager take a callback param to check if UMA is enabled.
[chromium-blink-merge.git] / chrome / browser / ui / views / toolbar / browser_action_view.cc
blob650798891a4731cba70985112b3ac77567fa5a24
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/browser_action_view.h"
7 #include "base/strings/utf_string_conversions.h"
8 #include "chrome/browser/chrome_notification_types.h"
9 #include "chrome/browser/extensions/api/commands/command_service.h"
10 #include "chrome/browser/extensions/extension_action.h"
11 #include "chrome/browser/extensions/extension_action_manager.h"
12 #include "chrome/browser/extensions/extension_context_menu_model.h"
13 #include "chrome/browser/extensions/extension_service.h"
14 #include "chrome/browser/profiles/profile.h"
15 #include "chrome/browser/themes/theme_service.h"
16 #include "chrome/browser/themes/theme_service_factory.h"
17 #include "chrome/browser/ui/browser.h"
18 #include "chrome/browser/ui/views/toolbar/browser_actions_container.h"
19 #include "chrome/browser/ui/views/toolbar/toolbar_view.h"
20 #include "extensions/common/extension.h"
21 #include "extensions/common/manifest_constants.h"
22 #include "grit/generated_resources.h"
23 #include "grit/theme_resources.h"
24 #include "ui/accessibility/ax_view_state.h"
25 #include "ui/base/l10n/l10n_util.h"
26 #include "ui/base/resource/resource_bundle.h"
27 #include "ui/events/event.h"
28 #include "ui/gfx/image/image_skia.h"
29 #include "ui/gfx/image/image_skia_operations.h"
30 #include "ui/gfx/image/image_skia_source.h"
31 #include "ui/views/controls/menu/menu_item_view.h"
32 #include "ui/views/controls/menu/menu_runner.h"
34 using extensions::Extension;
36 ////////////////////////////////////////////////////////////////////////////////
37 // BrowserActionView
39 bool BrowserActionView::Delegate::NeedToShowMultipleIconStates() const {
40 return true;
43 bool BrowserActionView::Delegate::NeedToShowTooltip() const {
44 return true;
47 BrowserActionView::BrowserActionView(const Extension* extension,
48 Browser* browser,
49 BrowserActionView::Delegate* delegate)
50 : browser_(browser),
51 delegate_(delegate),
52 button_(NULL),
53 extension_(extension) {
54 button_ = new BrowserActionButton(extension_, browser_, delegate_);
55 button_->set_drag_controller(delegate_);
56 button_->set_owned_by_client();
57 AddChildView(button_);
58 button_->UpdateState();
61 BrowserActionView::~BrowserActionView() {
62 button_->Destroy();
65 gfx::ImageSkia BrowserActionView::GetIconWithBadge() {
66 return button_->GetIconWithBadge();
69 void BrowserActionView::Layout() {
70 button_->SetBounds(0, y(), width(), height());
73 void BrowserActionView::GetAccessibleState(ui::AXViewState* state) {
74 state->name = l10n_util::GetStringUTF16(
75 IDS_ACCNAME_EXTENSIONS_BROWSER_ACTION);
76 state->role = ui::AX_ROLE_GROUP;
79 gfx::Size BrowserActionView::GetPreferredSize() const {
80 return gfx::Size(BrowserActionsContainer::IconWidth(false),
81 BrowserActionsContainer::IconHeight());
84 void BrowserActionView::PaintChildren(gfx::Canvas* canvas,
85 const views::CullSet& cull_set) {
86 View::PaintChildren(canvas, cull_set);
87 ExtensionAction* action = button()->browser_action();
88 int tab_id = delegate_->GetCurrentTabId();
89 if (tab_id >= 0)
90 action->PaintBadge(canvas, GetLocalBounds(), tab_id);
93 ////////////////////////////////////////////////////////////////////////////////
94 // BrowserActionButton
96 BrowserActionButton::BrowserActionButton(const Extension* extension,
97 Browser* browser,
98 BrowserActionView::Delegate* delegate)
99 : MenuButton(this, base::string16(), NULL, false),
100 browser_(browser),
101 browser_action_(
102 extensions::ExtensionActionManager::Get(browser->profile())->
103 GetBrowserAction(*extension)),
104 extension_(extension),
105 icon_factory_(browser->profile(), extension, browser_action_, this),
106 delegate_(delegate),
107 context_menu_(NULL),
108 called_registered_extension_command_(false),
109 icon_observer_(NULL) {
110 SetBorder(views::Border::NullBorder());
111 set_alignment(TextButton::ALIGN_CENTER);
112 set_context_menu_controller(this);
114 // No UpdateState() here because View hierarchy not setup yet. Our parent
115 // should call UpdateState() after creation.
117 content::NotificationSource notification_source =
118 content::Source<Profile>(browser_->profile()->GetOriginalProfile());
119 registrar_.Add(this, chrome::NOTIFICATION_EXTENSION_BROWSER_ACTION_UPDATED,
120 content::Source<ExtensionAction>(browser_action_));
121 registrar_.Add(this, chrome::NOTIFICATION_EXTENSION_COMMAND_ADDED,
122 notification_source);
123 registrar_.Add(this, chrome::NOTIFICATION_EXTENSION_COMMAND_REMOVED,
124 notification_source);
126 // We also listen for browser theme changes on linux because a switch from or
127 // to GTK requires that we regrab our browser action images.
128 registrar_.Add(
129 this,
130 chrome::NOTIFICATION_BROWSER_THEME_CHANGED,
131 content::Source<ThemeService>(
132 ThemeServiceFactory::GetForProfile(browser->profile())));
135 void BrowserActionButton::Destroy() {
136 MaybeUnregisterExtensionCommand(false);
138 if (context_menu_) {
139 context_menu_->Cancel();
140 base::MessageLoop::current()->DeleteSoon(FROM_HERE, this);
141 } else {
142 delete this;
146 void BrowserActionButton::ViewHierarchyChanged(
147 const ViewHierarchyChangedDetails& details) {
148 if (details.is_add && !called_registered_extension_command_ &&
149 GetFocusManager()) {
150 MaybeRegisterExtensionCommand();
151 called_registered_extension_command_ = true;
154 MenuButton::ViewHierarchyChanged(details);
157 bool BrowserActionButton::CanHandleAccelerators() const {
158 // View::CanHandleAccelerators() checks to see if the view is visible before
159 // allowing it to process accelerators. This is not appropriate for browser
160 // actions buttons, which can be hidden inside the overflow area.
161 return true;
164 void BrowserActionButton::GetAccessibleState(ui::AXViewState* state) {
165 views::MenuButton::GetAccessibleState(state);
166 state->role = ui::AX_ROLE_BUTTON;
169 void BrowserActionButton::ButtonPressed(views::Button* sender,
170 const ui::Event& event) {
171 delegate_->OnBrowserActionExecuted(this);
174 void BrowserActionButton::ShowContextMenuForView(
175 View* source,
176 const gfx::Point& point,
177 ui::MenuSourceType source_type) {
178 if (!extension()->ShowConfigureContextMenus())
179 return;
181 SetButtonPushed();
183 // Reconstructs the menu every time because the menu's contents are dynamic.
184 scoped_refptr<ExtensionContextMenuModel> context_menu_contents_(
185 new ExtensionContextMenuModel(extension(), browser_, delegate_));
186 menu_runner_.reset(new views::MenuRunner(context_menu_contents_.get()));
188 context_menu_ = menu_runner_->GetMenu();
189 gfx::Point screen_loc;
190 views::View::ConvertPointToScreen(this, &screen_loc);
191 if (menu_runner_->RunMenuAt(
192 GetWidget(),
193 NULL,
194 gfx::Rect(screen_loc, size()),
195 views::MENU_ANCHOR_TOPLEFT,
196 source_type,
197 views::MenuRunner::HAS_MNEMONICS | views::MenuRunner::CONTEXT_MENU) ==
198 views::MenuRunner::MENU_DELETED) {
199 return;
202 menu_runner_.reset();
203 SetButtonNotPushed();
204 context_menu_ = NULL;
207 void BrowserActionButton::UpdateState() {
208 int tab_id = delegate_->GetCurrentTabId();
209 if (tab_id < 0)
210 return;
212 SetShowMultipleIconStates(delegate_->NeedToShowMultipleIconStates());
214 if (!IsEnabled(tab_id)) {
215 SetState(views::CustomButton::STATE_DISABLED);
216 } else {
217 SetState(menu_visible_ ?
218 views::CustomButton::STATE_PRESSED :
219 views::CustomButton::STATE_NORMAL);
222 gfx::ImageSkia icon = *icon_factory_.GetIcon(tab_id).ToImageSkia();
224 if (!icon.isNull()) {
225 if (!browser_action()->GetIsVisible(tab_id))
226 icon = gfx::ImageSkiaOperations::CreateTransparentImage(icon, .25);
228 ThemeService* theme =
229 ThemeServiceFactory::GetForProfile(browser_->profile());
231 gfx::ImageSkia bg = *theme->GetImageSkiaNamed(IDR_BROWSER_ACTION);
232 SetIcon(gfx::ImageSkiaOperations::CreateSuperimposedImage(bg, icon));
234 gfx::ImageSkia bg_h = *theme->GetImageSkiaNamed(IDR_BROWSER_ACTION_H);
235 SetHoverIcon(gfx::ImageSkiaOperations::CreateSuperimposedImage(bg_h, icon));
237 gfx::ImageSkia bg_p = *theme->GetImageSkiaNamed(IDR_BROWSER_ACTION_P);
238 SetPushedIcon(
239 gfx::ImageSkiaOperations::CreateSuperimposedImage(bg_p, icon));
242 // If the browser action name is empty, show the extension name instead.
243 std::string title = browser_action()->GetTitle(tab_id);
244 base::string16 name =
245 base::UTF8ToUTF16(title.empty() ? extension()->name() : title);
246 SetTooltipText(delegate_->NeedToShowTooltip() ? name : base::string16());
247 SetAccessibleName(name);
249 parent()->SchedulePaint();
252 bool BrowserActionButton::IsPopup() {
253 int tab_id = delegate_->GetCurrentTabId();
254 return (tab_id < 0) ? false : browser_action_->HasPopup(tab_id);
257 GURL BrowserActionButton::GetPopupUrl() {
258 int tab_id = delegate_->GetCurrentTabId();
259 return (tab_id < 0) ? GURL() : browser_action_->GetPopupUrl(tab_id);
262 void BrowserActionButton::Observe(int type,
263 const content::NotificationSource& source,
264 const content::NotificationDetails& details) {
265 switch (type) {
266 case chrome::NOTIFICATION_EXTENSION_BROWSER_ACTION_UPDATED:
267 UpdateState();
268 // The browser action may have become visible/hidden so we need to make
269 // sure the state gets updated.
270 delegate_->OnBrowserActionVisibilityChanged();
271 break;
272 case chrome::NOTIFICATION_EXTENSION_COMMAND_ADDED:
273 case chrome::NOTIFICATION_EXTENSION_COMMAND_REMOVED: {
274 std::pair<const std::string, const std::string>* payload =
275 content::Details<std::pair<const std::string, const std::string> >(
276 details).ptr();
277 if (extension_->id() == payload->first &&
278 payload->second ==
279 extensions::manifest_values::kBrowserActionCommandEvent) {
280 if (type == chrome::NOTIFICATION_EXTENSION_COMMAND_ADDED)
281 MaybeRegisterExtensionCommand();
282 else
283 MaybeUnregisterExtensionCommand(true);
285 break;
287 case chrome::NOTIFICATION_BROWSER_THEME_CHANGED:
288 UpdateState();
289 break;
290 default:
291 NOTREACHED();
292 break;
296 void BrowserActionButton::OnIconUpdated() {
297 UpdateState();
298 if (icon_observer_)
299 icon_observer_->OnIconUpdated(GetIconWithBadge());
302 bool BrowserActionButton::Activate() {
303 if (!IsPopup())
304 return true;
306 delegate_->OnBrowserActionExecuted(this);
308 // TODO(erikkay): Run a nested modal loop while the mouse is down to
309 // enable menu-like drag-select behavior.
311 // The return value of this method is returned via OnMousePressed.
312 // We need to return false here since we're handing off focus to another
313 // widget/view, and true will grab it right back and try to send events
314 // to us.
315 return false;
318 bool BrowserActionButton::OnMousePressed(const ui::MouseEvent& event) {
319 if (!event.IsRightMouseButton()) {
320 return IsPopup() ? MenuButton::OnMousePressed(event) :
321 TextButton::OnMousePressed(event);
324 if (!views::View::ShouldShowContextMenuOnMousePress()) {
325 // See comments in MenuButton::Activate() as to why this is needed.
326 SetMouseHandler(NULL);
328 ShowContextMenu(gfx::Point(), ui::MENU_SOURCE_MOUSE);
330 return false;
333 void BrowserActionButton::OnMouseReleased(const ui::MouseEvent& event) {
334 if (IsPopup() || context_menu_) {
335 // TODO(erikkay) this never actually gets called (probably because of the
336 // loss of focus).
337 MenuButton::OnMouseReleased(event);
338 } else {
339 TextButton::OnMouseReleased(event);
343 void BrowserActionButton::OnMouseExited(const ui::MouseEvent& event) {
344 if (IsPopup() || context_menu_)
345 MenuButton::OnMouseExited(event);
346 else
347 TextButton::OnMouseExited(event);
350 bool BrowserActionButton::OnKeyReleased(const ui::KeyEvent& event) {
351 return IsPopup() ? MenuButton::OnKeyReleased(event) :
352 TextButton::OnKeyReleased(event);
355 void BrowserActionButton::OnGestureEvent(ui::GestureEvent* event) {
356 if (IsPopup())
357 MenuButton::OnGestureEvent(event);
358 else
359 TextButton::OnGestureEvent(event);
362 bool BrowserActionButton::AcceleratorPressed(
363 const ui::Accelerator& accelerator) {
364 delegate_->OnBrowserActionExecuted(this);
365 return true;
368 void BrowserActionButton::SetButtonPushed() {
369 SetState(views::CustomButton::STATE_PRESSED);
370 menu_visible_ = true;
373 void BrowserActionButton::SetButtonNotPushed() {
374 SetState(views::CustomButton::STATE_NORMAL);
375 menu_visible_ = false;
378 bool BrowserActionButton::IsEnabled(int tab_id) const {
379 return browser_action_->GetIsVisible(tab_id);
382 gfx::ImageSkia BrowserActionButton::GetIconWithBadge() {
383 int tab_id = delegate_->GetCurrentTabId();
384 gfx::Size spacing(0, ToolbarView::kVertSpacing);
385 gfx::ImageSkia icon = *icon_factory_.GetIcon(tab_id).ToImageSkia();
386 if (!IsEnabled(tab_id))
387 icon = gfx::ImageSkiaOperations::CreateTransparentImage(icon, .25);
388 return browser_action_->GetIconWithBadge(icon, tab_id, spacing);
391 gfx::ImageSkia BrowserActionButton::GetIconForTest() {
392 return icon();
395 BrowserActionButton::~BrowserActionButton() {
398 void BrowserActionButton::MaybeRegisterExtensionCommand() {
399 extensions::CommandService* command_service =
400 extensions::CommandService::Get(browser_->profile());
401 extensions::Command browser_action_command;
402 if (command_service->GetBrowserActionCommand(
403 extension_->id(),
404 extensions::CommandService::ACTIVE_ONLY,
405 &browser_action_command,
406 NULL)) {
407 keybinding_.reset(new ui::Accelerator(
408 browser_action_command.accelerator()));
409 GetFocusManager()->RegisterAccelerator(
410 *keybinding_.get(), ui::AcceleratorManager::kHighPriority, this);
414 void BrowserActionButton::MaybeUnregisterExtensionCommand(bool only_if_active) {
415 if (!keybinding_.get() || !GetFocusManager())
416 return;
418 extensions::CommandService* command_service =
419 extensions::CommandService::Get(browser_->profile());
421 extensions::Command browser_action_command;
422 if (!only_if_active || !command_service->GetBrowserActionCommand(
423 extension_->id(),
424 extensions::CommandService::ACTIVE_ONLY,
425 &browser_action_command,
426 NULL)) {
427 GetFocusManager()->UnregisterAccelerator(*keybinding_.get(), this);
428 keybinding_.reset(NULL);