browser_action_view.cc revision 2a99a7e74a7f215066514fe81d2bfa6639d9eddd
1// Copyright (c) 2012 The Chromium Authors. All rights reserved.
2// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
4
5#include "chrome/browser/ui/views/browser_action_view.h"
6
7#include "base/utf_string_conversions.h"
8#include "chrome/browser/extensions/api/commands/command_service.h"
9#include "chrome/browser/extensions/extension_action.h"
10#include "chrome/browser/extensions/extension_action_manager.h"
11#include "chrome/browser/extensions/extension_context_menu_model.h"
12#include "chrome/browser/profiles/profile.h"
13#include "chrome/browser/ui/browser.h"
14#include "chrome/browser/ui/views/browser_actions_container.h"
15#include "chrome/browser/ui/views/toolbar_view.h"
16#include "chrome/common/chrome_notification_types.h"
17#include "chrome/common/extensions/extension.h"
18#include "chrome/common/extensions/extension_manifest_constants.h"
19#include "grit/generated_resources.h"
20#include "grit/theme_resources.h"
21#include "ui/base/accessibility/accessible_view_state.h"
22#include "ui/base/events/event.h"
23#include "ui/base/l10n/l10n_util.h"
24#include "ui/base/resource/resource_bundle.h"
25#include "ui/gfx/image/image_skia.h"
26#include "ui/gfx/image/image_skia_operations.h"
27#include "ui/gfx/image/image_skia_source.h"
28#include "ui/views/controls/menu/menu_model_adapter.h"
29#include "ui/views/controls/menu/menu_runner.h"
30
31using extensions::Extension;
32
33////////////////////////////////////////////////////////////////////////////////
34// BrowserActionView
35
36bool BrowserActionView::Delegate::NeedToShowMultipleIconStates() const {
37  return true;
38}
39
40bool BrowserActionView::Delegate::NeedToShowTooltip() const {
41  return true;
42}
43
44BrowserActionView::BrowserActionView(const Extension* extension,
45                                     Browser* browser,
46                                     BrowserActionView::Delegate* delegate)
47    : browser_(browser),
48      delegate_(delegate),
49      button_(NULL),
50      extension_(extension) {
51  button_ = new BrowserActionButton(extension_, browser_, delegate_);
52  button_->set_drag_controller(delegate_);
53  button_->set_owned_by_client();
54  AddChildView(button_);
55  button_->UpdateState();
56}
57
58BrowserActionView::~BrowserActionView() {
59  button_->Destroy();
60}
61
62gfx::ImageSkia BrowserActionView::GetIconWithBadge() {
63  int tab_id = delegate_->GetCurrentTabId();
64
65  const ExtensionAction* action =
66      extensions::ExtensionActionManager::Get(browser_->profile())->
67      GetBrowserAction(*button_->extension());
68  gfx::Size spacing(0, ToolbarView::kVertSpacing);
69  gfx::ImageSkia icon = *button_->icon_factory().GetIcon(tab_id).ToImageSkia();
70  if (!button_->IsEnabled(tab_id))
71    icon = gfx::ImageSkiaOperations::CreateTransparentImage(icon, .25);
72  return action->GetIconWithBadge(icon, tab_id, spacing);
73}
74
75void BrowserActionView::Layout() {
76  // We can't rely on button_->GetPreferredSize() here because that's not set
77  // correctly until the first call to
78  // BrowserActionsContainer::RefreshBrowserActionViews(), whereas this can be
79  // called before that when the initial bounds are set (and then not after,
80  // since the bounds don't change).  So instead of setting the height from the
81  // button's preferred size, we use IconHeight(), since that's how big the
82  // button should be regardless of what it's displaying.
83  gfx::Point offset = delegate_->GetViewContentOffset();
84  button_->SetBounds(offset.x(), offset.y(), width() - offset.x(),
85                     BrowserActionsContainer::IconHeight());
86}
87
88void BrowserActionView::GetAccessibleState(ui::AccessibleViewState* state) {
89  state->name = l10n_util::GetStringUTF16(
90      IDS_ACCNAME_EXTENSIONS_BROWSER_ACTION);
91  state->role = ui::AccessibilityTypes::ROLE_GROUPING;
92}
93
94gfx::Size BrowserActionView::GetPreferredSize() {
95  return gfx::Size(BrowserActionsContainer::IconWidth(false),
96                   BrowserActionsContainer::IconHeight());
97}
98
99void BrowserActionView::PaintChildren(gfx::Canvas* canvas) {
100  View::PaintChildren(canvas);
101  ExtensionAction* action = button()->browser_action();
102  int tab_id = delegate_->GetCurrentTabId();
103  if (tab_id >= 0)
104    action->PaintBadge(canvas, GetLocalBounds(), tab_id);
105}
106
107////////////////////////////////////////////////////////////////////////////////
108// BrowserActionButton
109
110BrowserActionButton::BrowserActionButton(const Extension* extension,
111                                         Browser* browser,
112                                         BrowserActionView::Delegate* delegate)
113    : ALLOW_THIS_IN_INITIALIZER_LIST(
114          MenuButton(this, string16(), NULL, false)),
115      browser_(browser),
116      browser_action_(
117          extensions::ExtensionActionManager::Get(browser->profile())->
118          GetBrowserAction(*extension)),
119      extension_(extension),
120      ALLOW_THIS_IN_INITIALIZER_LIST(
121          icon_factory_(browser->profile(), extension, browser_action_, this)),
122      delegate_(delegate),
123      context_menu_(NULL),
124      called_registered_extension_command_(false) {
125  set_border(NULL);
126  set_alignment(TextButton::ALIGN_CENTER);
127  set_context_menu_controller(this);
128
129  // No UpdateState() here because View hierarchy not setup yet. Our parent
130  // should call UpdateState() after creation.
131
132  content::NotificationSource notification_source =
133      content::Source<Profile>(browser_->profile()->GetOriginalProfile());
134  registrar_.Add(this, chrome::NOTIFICATION_EXTENSION_BROWSER_ACTION_UPDATED,
135                 content::Source<ExtensionAction>(browser_action_));
136  registrar_.Add(this, chrome::NOTIFICATION_EXTENSION_COMMAND_ADDED,
137                 notification_source);
138  registrar_.Add(this, chrome::NOTIFICATION_EXTENSION_COMMAND_REMOVED,
139                 notification_source);
140}
141
142void BrowserActionButton::Destroy() {
143  MaybeUnregisterExtensionCommand(false);
144
145  if (context_menu_) {
146    context_menu_->Cancel();
147    MessageLoop::current()->DeleteSoon(FROM_HERE, this);
148  } else {
149    delete this;
150  }
151}
152
153void BrowserActionButton::ViewHierarchyChanged(
154    bool is_add, View* parent, View* child) {
155
156  if (is_add && !called_registered_extension_command_ && GetFocusManager()) {
157    MaybeRegisterExtensionCommand();
158    called_registered_extension_command_ = true;
159  }
160
161  MenuButton::ViewHierarchyChanged(is_add, parent, child);
162}
163
164bool BrowserActionButton::CanHandleAccelerators() const {
165  // View::CanHandleAccelerators() checks to see if the view is visible before
166  // allowing it to process accelerators. This is not appropriate for browser
167  // actions buttons, which can be hidden inside the overflow area.
168  return true;
169}
170
171void BrowserActionButton::GetAccessibleState(ui::AccessibleViewState* state) {
172  views::MenuButton::GetAccessibleState(state);
173  state->role = ui::AccessibilityTypes::ROLE_PUSHBUTTON;
174}
175
176void BrowserActionButton::ButtonPressed(views::Button* sender,
177                                        const ui::Event& event) {
178  delegate_->OnBrowserActionExecuted(this);
179}
180
181void BrowserActionButton::ShowContextMenuForView(View* source,
182                                                 const gfx::Point& point) {
183  if (!extension()->ShowConfigureContextMenus())
184    return;
185
186  SetButtonPushed();
187
188  // Reconstructs the menu every time because the menu's contents are dynamic.
189  scoped_refptr<ExtensionContextMenuModel> context_menu_contents_(
190      new ExtensionContextMenuModel(extension(), browser_, delegate_));
191  views::MenuModelAdapter menu_model_adapter(context_menu_contents_.get());
192  menu_runner_.reset(new views::MenuRunner(menu_model_adapter.CreateMenu()));
193
194  context_menu_ = menu_runner_->GetMenu();
195  gfx::Point screen_loc;
196  views::View::ConvertPointToScreen(this, &screen_loc);
197  if (menu_runner_->RunMenuAt(GetWidget(), NULL, gfx::Rect(screen_loc, size()),
198          views::MenuItemView::TOPLEFT, views::MenuRunner::HAS_MNEMONICS |
199          views::MenuRunner::CONTEXT_MENU) ==
200      views::MenuRunner::MENU_DELETED) {
201    return;
202  }
203
204  menu_runner_.reset();
205  SetButtonNotPushed();
206  context_menu_ = NULL;
207}
208
209void BrowserActionButton::UpdateState() {
210  int tab_id = delegate_->GetCurrentTabId();
211  if (tab_id < 0)
212    return;
213
214  SetShowMultipleIconStates(delegate_->NeedToShowMultipleIconStates());
215
216  if (!IsEnabled(tab_id)) {
217    SetState(views::CustomButton::STATE_DISABLED);
218  } else {
219    SetState(menu_visible_ ?
220             views::CustomButton::STATE_PRESSED :
221             views::CustomButton::STATE_NORMAL);
222  }
223
224  gfx::ImageSkia icon = *icon_factory_.GetIcon(tab_id).ToImageSkia();
225
226  if (!icon.isNull()) {
227    if (!browser_action()->GetIsVisible(tab_id))
228      icon = gfx::ImageSkiaOperations::CreateTransparentImage(icon, .25);
229
230    ui::ResourceBundle& rb = ui::ResourceBundle::GetSharedInstance();
231
232    gfx::ImageSkia bg = *rb.GetImageSkiaNamed(IDR_BROWSER_ACTION);
233    SetIcon(gfx::ImageSkiaOperations::CreateSuperimposedImage(bg, icon));
234
235    gfx::ImageSkia bg_h = *rb.GetImageSkiaNamed(IDR_BROWSER_ACTION_H);
236    SetHoverIcon(gfx::ImageSkiaOperations::CreateSuperimposedImage(bg_h, icon));
237
238    gfx::ImageSkia bg_p = *rb.GetImageSkiaNamed(IDR_BROWSER_ACTION_P);
239    SetPushedIcon(
240        gfx::ImageSkiaOperations::CreateSuperimposedImage(bg_p, icon));
241  }
242
243  // If the browser action name is empty, show the extension name instead.
244  std::string title = browser_action()->GetTitle(tab_id);
245  string16 name = UTF8ToUTF16(title.empty() ? extension()->name() : title);
246  SetTooltipText(delegate_->NeedToShowTooltip() ? name : string16());
247  SetAccessibleName(name);
248
249  parent()->SchedulePaint();
250}
251
252bool BrowserActionButton::IsPopup() {
253  int tab_id = delegate_->GetCurrentTabId();
254  return (tab_id < 0) ? false : browser_action_->HasPopup(tab_id);
255}
256
257GURL BrowserActionButton::GetPopupUrl() {
258  int tab_id = delegate_->GetCurrentTabId();
259  return (tab_id < 0) ? GURL() : browser_action_->GetPopupUrl(tab_id);
260}
261
262void 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              extension_manifest_values::kBrowserActionCommandEvent) {
280        if (type == chrome::NOTIFICATION_EXTENSION_COMMAND_ADDED)
281          MaybeRegisterExtensionCommand();
282        else
283          MaybeUnregisterExtensionCommand(true);
284      }
285      break;
286    }
287    default:
288      NOTREACHED();
289      break;
290  }
291}
292
293void BrowserActionButton::OnIconUpdated() {
294  UpdateState();
295}
296
297bool BrowserActionButton::Activate() {
298  if (!IsPopup())
299    return true;
300
301  delegate_->OnBrowserActionExecuted(this);
302
303  // TODO(erikkay): Run a nested modal loop while the mouse is down to
304  // enable menu-like drag-select behavior.
305
306  // The return value of this method is returned via OnMousePressed.
307  // We need to return false here since we're handing off focus to another
308  // widget/view, and true will grab it right back and try to send events
309  // to us.
310  return false;
311}
312
313bool BrowserActionButton::OnMousePressed(const ui::MouseEvent& event) {
314  if (!event.IsRightMouseButton()) {
315    return IsPopup() ? MenuButton::OnMousePressed(event) :
316                       TextButton::OnMousePressed(event);
317  }
318
319  // See comments in MenuButton::Activate() as to why this is needed.
320  SetMouseHandler(NULL);
321
322  ShowContextMenu(gfx::Point(), true);
323  return false;
324}
325
326void BrowserActionButton::OnMouseReleased(const ui::MouseEvent& event) {
327  if (IsPopup() || context_menu_) {
328    // TODO(erikkay) this never actually gets called (probably because of the
329    // loss of focus).
330    MenuButton::OnMouseReleased(event);
331  } else {
332    TextButton::OnMouseReleased(event);
333  }
334}
335
336void BrowserActionButton::OnMouseExited(const ui::MouseEvent& event) {
337  if (IsPopup() || context_menu_)
338    MenuButton::OnMouseExited(event);
339  else
340    TextButton::OnMouseExited(event);
341}
342
343bool BrowserActionButton::OnKeyReleased(const ui::KeyEvent& event) {
344  return IsPopup() ? MenuButton::OnKeyReleased(event) :
345                     TextButton::OnKeyReleased(event);
346}
347
348void BrowserActionButton::OnGestureEvent(ui::GestureEvent* event) {
349  if (IsPopup())
350    MenuButton::OnGestureEvent(event);
351  else
352    TextButton::OnGestureEvent(event);
353}
354
355bool BrowserActionButton::AcceleratorPressed(
356    const ui::Accelerator& accelerator) {
357  delegate_->OnBrowserActionExecuted(this);
358  return true;
359}
360
361void BrowserActionButton::SetButtonPushed() {
362  SetState(views::CustomButton::STATE_PRESSED);
363  menu_visible_ = true;
364}
365
366void BrowserActionButton::SetButtonNotPushed() {
367  SetState(views::CustomButton::STATE_NORMAL);
368  menu_visible_ = false;
369}
370
371bool BrowserActionButton::IsEnabled(int tab_id) const {
372  return browser_action_->GetIsVisible(tab_id);
373}
374
375gfx::ImageSkia BrowserActionButton::GetIconForTest() {
376  return icon();
377}
378
379BrowserActionButton::~BrowserActionButton() {
380}
381
382void BrowserActionButton::MaybeRegisterExtensionCommand() {
383  extensions::CommandService* command_service =
384      extensions::CommandService::Get(browser_->profile());
385  extensions::Command browser_action_command;
386  if (command_service->GetBrowserActionCommand(
387          extension_->id(),
388          extensions::CommandService::ACTIVE_ONLY,
389          &browser_action_command,
390          NULL)) {
391    keybinding_.reset(new ui::Accelerator(
392        browser_action_command.accelerator()));
393    GetFocusManager()->RegisterAccelerator(
394        *keybinding_.get(), ui::AcceleratorManager::kHighPriority, this);
395  }
396}
397
398void BrowserActionButton::MaybeUnregisterExtensionCommand(bool only_if_active) {
399  if (!keybinding_.get() || !GetFocusManager())
400    return;
401
402  extensions::CommandService* command_service =
403      extensions::CommandService::Get(browser_->profile());
404
405  extensions::Command browser_action_command;
406  if (!only_if_active || !command_service->GetBrowserActionCommand(
407          extension_->id(),
408          extensions::CommandService::ACTIVE_ONLY,
409          &browser_action_command,
410          NULL)) {
411    GetFocusManager()->UnregisterAccelerator(*keybinding_.get(), this);
412  }
413}
414