browser_action_view.cc revision 03b57e008b61dfcb1fbad3aea950ae0e001748b0
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.
4
5#include "chrome/browser/ui/views/toolbar/browser_action_view.h"
6
7#include <string>
8
9#include "base/strings/utf_string_conversions.h"
10#include "chrome/browser/chrome_notification_types.h"
11#include "chrome/browser/extensions/extension_action.h"
12#include "chrome/browser/profiles/profile.h"
13#include "chrome/browser/themes/theme_service.h"
14#include "chrome/browser/themes/theme_service_factory.h"
15#include "chrome/browser/ui/browser.h"
16#include "chrome/browser/ui/view_ids.h"
17#include "chrome/browser/ui/views/frame/browser_view.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/button/label_button_border.h"
32
33using extensions::Extension;
34using views::LabelButtonBorder;
35
36namespace {
37
38// We have smaller insets than normal STYLE_TEXTBUTTON buttons so that we can
39// fit user supplied icons in without clipping them.
40const int kBorderInset = 4;
41
42}  // namespace
43
44////////////////////////////////////////////////////////////////////////////////
45// BrowserActionView
46
47BrowserActionView::BrowserActionView(const Extension* extension,
48                                     ExtensionAction* extension_action,
49                                     Browser* browser,
50                                     BrowserActionView::Delegate* delegate)
51    : MenuButton(this, base::string16(), NULL, false),
52      view_controller_(new ExtensionActionViewController(
53          extension,
54          browser,
55          extension_action,
56          this)),
57      delegate_(delegate),
58      called_registered_extension_command_(false),
59      icon_observer_(NULL) {
60  set_id(VIEW_ID_BROWSER_ACTION);
61  SetHorizontalAlignment(gfx::ALIGN_CENTER);
62  set_context_menu_controller(view_controller_.get());
63  set_drag_controller(delegate_);
64
65  content::NotificationSource notification_source =
66      content::Source<Profile>(browser->profile()->GetOriginalProfile());
67  registrar_.Add(this,
68                 extensions::NOTIFICATION_EXTENSION_COMMAND_ADDED,
69                 notification_source);
70  registrar_.Add(this,
71                 extensions::NOTIFICATION_EXTENSION_COMMAND_REMOVED,
72                 notification_source);
73
74  // We also listen for browser theme changes on linux because a switch from or
75  // to GTK requires that we regrab our browser action images.
76  registrar_.Add(
77      this,
78      chrome::NOTIFICATION_BROWSER_THEME_CHANGED,
79      content::Source<ThemeService>(
80          ThemeServiceFactory::GetForProfile(browser->profile())));
81
82  UpdateState();
83}
84
85BrowserActionView::~BrowserActionView() {
86}
87
88void BrowserActionView::ViewHierarchyChanged(
89    const ViewHierarchyChangedDetails& details) {
90  if (details.is_add && !called_registered_extension_command_ &&
91      GetFocusManager()) {
92    view_controller_->RegisterCommand();
93    called_registered_extension_command_ = true;
94  }
95
96  MenuButton::ViewHierarchyChanged(details);
97}
98
99void BrowserActionView::OnDragDone() {
100  delegate_->OnBrowserActionViewDragDone();
101}
102
103gfx::Size BrowserActionView::GetPreferredSize() const {
104  return gfx::Size(BrowserActionsContainer::IconWidth(false),
105                   BrowserActionsContainer::IconHeight());
106}
107
108void BrowserActionView::PaintChildren(gfx::Canvas* canvas,
109                                      const views::CullSet& cull_set) {
110  View::PaintChildren(canvas, cull_set);
111  int tab_id = view_controller_->GetCurrentTabId();
112  if (tab_id >= 0)
113    extension_action()->PaintBadge(canvas, GetLocalBounds(), tab_id);
114}
115
116void BrowserActionView::GetAccessibleState(ui::AXViewState* state) {
117  views::MenuButton::GetAccessibleState(state);
118  state->name = l10n_util::GetStringUTF16(
119      IDS_ACCNAME_EXTENSIONS_BROWSER_ACTION);
120  state->role = ui::AX_ROLE_BUTTON;
121}
122
123void BrowserActionView::ButtonPressed(views::Button* sender,
124                                      const ui::Event& event) {
125  view_controller_->ExecuteActionByUser();
126}
127
128void BrowserActionView::UpdateState() {
129  int tab_id = view_controller_->GetCurrentTabId();
130  if (tab_id < 0)
131    return;
132
133  if (!IsEnabled(tab_id)) {
134    SetState(views::CustomButton::STATE_DISABLED);
135  } else {
136    SetState(menu_visible_ ?
137             views::CustomButton::STATE_PRESSED :
138             views::CustomButton::STATE_NORMAL);
139  }
140
141  gfx::ImageSkia icon = *view_controller_->GetIcon(tab_id).ToImageSkia();
142
143  if (!icon.isNull()) {
144    if (!extension_action()->GetIsVisible(tab_id))
145      icon = gfx::ImageSkiaOperations::CreateTransparentImage(icon, .25);
146
147    ThemeService* theme = ThemeServiceFactory::GetForProfile(
148        view_controller_->browser()->profile());
149
150    gfx::ImageSkia bg = *theme->GetImageSkiaNamed(IDR_BROWSER_ACTION);
151    SetImage(views::Button::STATE_NORMAL,
152             gfx::ImageSkiaOperations::CreateSuperimposedImage(bg, icon));
153  }
154
155  // If the browser action name is empty, show the extension name instead.
156  std::string title = extension_action()->GetTitle(tab_id);
157  base::string16 name =
158      base::UTF8ToUTF16(title.empty() ? extension()->name() : title);
159  SetTooltipText(name);
160  SetAccessibleName(name);
161
162  SchedulePaint();
163}
164
165bool BrowserActionView::IsPopup() {
166  int tab_id = view_controller_->GetCurrentTabId();
167  return (tab_id < 0) ? false : extension_action()->HasPopup(tab_id);
168}
169
170void BrowserActionView::Observe(int type,
171                                const content::NotificationSource& source,
172                                const content::NotificationDetails& details) {
173  switch (type) {
174    case extensions::NOTIFICATION_EXTENSION_COMMAND_ADDED:
175    case extensions::NOTIFICATION_EXTENSION_COMMAND_REMOVED: {
176      std::pair<const std::string, const std::string>* payload =
177          content::Details<std::pair<const std::string, const std::string> >(
178              details).ptr();
179      if (extension()->id() == payload->first &&
180          payload->second ==
181              extensions::manifest_values::kBrowserActionCommandEvent) {
182        if (type == extensions::NOTIFICATION_EXTENSION_COMMAND_ADDED)
183          view_controller_->RegisterCommand();
184        else
185          view_controller_->UnregisterCommand(true);
186      }
187      break;
188    }
189    case chrome::NOTIFICATION_BROWSER_THEME_CHANGED:
190      UpdateState();
191      break;
192    default:
193      NOTREACHED();
194      break;
195  }
196}
197
198bool BrowserActionView::Activate() {
199  if (!IsPopup())
200    return true;
201
202  view_controller_->ExecuteActionByUser();
203
204  // TODO(erikkay): Run a nested modal loop while the mouse is down to
205  // enable menu-like drag-select behavior.
206
207  // The return value of this method is returned via OnMousePressed.
208  // We need to return false here since we're handing off focus to another
209  // widget/view, and true will grab it right back and try to send events
210  // to us.
211  return false;
212}
213
214bool BrowserActionView::OnMousePressed(const ui::MouseEvent& event) {
215  if (!event.IsRightMouseButton()) {
216    return IsPopup() ? MenuButton::OnMousePressed(event) :
217                       LabelButton::OnMousePressed(event);
218  }
219  return false;
220}
221
222void BrowserActionView::OnMouseReleased(const ui::MouseEvent& event) {
223  if (IsPopup() || view_controller_->is_menu_running()) {
224    // TODO(erikkay) this never actually gets called (probably because of the
225    // loss of focus).
226    MenuButton::OnMouseReleased(event);
227  } else {
228    LabelButton::OnMouseReleased(event);
229  }
230}
231
232void BrowserActionView::OnMouseExited(const ui::MouseEvent& event) {
233  if (IsPopup() || view_controller_->is_menu_running())
234    MenuButton::OnMouseExited(event);
235  else
236    LabelButton::OnMouseExited(event);
237}
238
239bool BrowserActionView::OnKeyReleased(const ui::KeyEvent& event) {
240  return IsPopup() ? MenuButton::OnKeyReleased(event) :
241                     LabelButton::OnKeyReleased(event);
242}
243
244void BrowserActionView::OnGestureEvent(ui::GestureEvent* event) {
245  if (IsPopup())
246    MenuButton::OnGestureEvent(event);
247  else
248    LabelButton::OnGestureEvent(event);
249}
250
251scoped_ptr<LabelButtonBorder> BrowserActionView::CreateDefaultBorder() const {
252  scoped_ptr<LabelButtonBorder> border = LabelButton::CreateDefaultBorder();
253  border->set_insets(gfx::Insets(kBorderInset, kBorderInset,
254                                 kBorderInset, kBorderInset));
255  return border.Pass();
256}
257
258void BrowserActionView::SetButtonPushed() {
259  SetState(views::CustomButton::STATE_PRESSED);
260  menu_visible_ = true;
261}
262
263void BrowserActionView::SetButtonNotPushed() {
264  SetState(views::CustomButton::STATE_NORMAL);
265  menu_visible_ = false;
266}
267
268bool BrowserActionView::IsEnabled(int tab_id) const {
269  return view_controller_->extension_action()->GetIsVisible(tab_id);
270}
271
272gfx::ImageSkia BrowserActionView::GetIconWithBadge() {
273  int tab_id = view_controller_->GetCurrentTabId();
274  gfx::Size spacing(0, ToolbarView::kVertSpacing);
275  gfx::ImageSkia icon = *view_controller_->GetIcon(tab_id).ToImageSkia();
276  if (!IsEnabled(tab_id))
277    icon = gfx::ImageSkiaOperations::CreateTransparentImage(icon, .25);
278  return extension_action()->GetIconWithBadge(icon, tab_id, spacing);
279}
280
281gfx::ImageSkia BrowserActionView::GetIconForTest() {
282  return GetImage(views::Button::STATE_NORMAL);
283}
284
285void BrowserActionView::OnIconUpdated() {
286  UpdateState();
287  if (icon_observer_)
288    icon_observer_->OnIconUpdated(GetIconWithBadge());
289}
290
291views::View* BrowserActionView::GetAsView() {
292  return this;
293}
294
295bool BrowserActionView::IsShownInMenu() {
296  return delegate_->ShownInsideMenu();
297}
298
299views::FocusManager* BrowserActionView::GetFocusManagerForAccelerator() {
300  return GetFocusManager();
301}
302
303views::Widget* BrowserActionView::GetParentForContextMenu() {
304  // RunMenuAt expects a nested menu to be parented by the same widget as the
305  // already visible menu, in this case the Chrome menu.
306  return delegate_->ShownInsideMenu() ?
307      BrowserView::GetBrowserViewForBrowser(view_controller_->browser())
308          ->toolbar()->app_menu()->GetWidget() :
309      GetWidget();
310}
311
312views::View* BrowserActionView::GetReferenceViewForPopup() {
313  // Browser actions in the overflow menu can still show popups, so we may need
314  // a reference view other than this button's parent. If so, use the overflow
315  // view.
316  return visible() ? this : delegate_->GetOverflowReferenceView();
317}
318
319content::WebContents* BrowserActionView::GetCurrentWebContents() {
320  return delegate_->GetCurrentWebContents();
321}
322
323void BrowserActionView::HideActivePopup() {
324  delegate_->HideActivePopup();
325}
326
327void BrowserActionView::OnPopupShown(bool grant_tab_permissions) {
328  delegate_->SetPopupOwner(this);
329  if (grant_tab_permissions)
330    SetButtonPushed();
331}
332
333void BrowserActionView::CleanupPopup() {
334  // We need to do these actions synchronously (instead of closing and then
335  // performing the rest of the cleanup in OnWidgetDestroyed()) because
336  // OnWidgetDestroyed() can be called asynchronously from Close(), and we need
337  // to keep the delegate's popup owner up-to-date.
338  SetButtonNotPushed();
339  delegate_->SetPopupOwner(NULL);
340}
341
342void BrowserActionView::OnWillShowContextMenus() {
343  SetButtonPushed();
344}
345
346void BrowserActionView::OnContextMenuDone() {
347  SetButtonNotPushed();
348}
349