browser_action_view.cc revision 1320f92c476a1ad9d19dba2a48c72b75566198e9
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 "chrome/grit/generated_resources.h"
21#include "extensions/common/extension.h"
22#include "extensions/common/manifest_constants.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
136  gfx::ImageSkia icon = *view_controller_->GetIcon(tab_id).ToImageSkia();
137
138  if (!icon.isNull()) {
139    if (!extension_action()->GetIsVisible(tab_id))
140      icon = gfx::ImageSkiaOperations::CreateTransparentImage(icon, .25);
141
142    ThemeService* theme = ThemeServiceFactory::GetForProfile(
143        view_controller_->browser()->profile());
144
145    gfx::ImageSkia bg = *theme->GetImageSkiaNamed(IDR_BROWSER_ACTION);
146    SetImage(views::Button::STATE_NORMAL,
147             gfx::ImageSkiaOperations::CreateSuperimposedImage(bg, icon));
148  }
149
150  // If the browser action name is empty, show the extension name instead.
151  std::string title = extension_action()->GetTitle(tab_id);
152  base::string16 name =
153      base::UTF8ToUTF16(title.empty() ? extension()->name() : title);
154  SetTooltipText(name);
155  SetAccessibleName(name);
156
157  SchedulePaint();
158}
159
160bool BrowserActionView::IsPopup() {
161  int tab_id = view_controller_->GetCurrentTabId();
162  return (tab_id < 0) ? false : extension_action()->HasPopup(tab_id);
163}
164
165void BrowserActionView::Observe(int type,
166                                const content::NotificationSource& source,
167                                const content::NotificationDetails& details) {
168  switch (type) {
169    case extensions::NOTIFICATION_EXTENSION_COMMAND_ADDED:
170    case extensions::NOTIFICATION_EXTENSION_COMMAND_REMOVED: {
171      std::pair<const std::string, const std::string>* payload =
172          content::Details<std::pair<const std::string, const std::string> >(
173              details).ptr();
174      if (extension()->id() == payload->first &&
175          payload->second ==
176              extensions::manifest_values::kBrowserActionCommandEvent) {
177        if (type == extensions::NOTIFICATION_EXTENSION_COMMAND_ADDED)
178          view_controller_->RegisterCommand();
179        else
180          view_controller_->UnregisterCommand(true);
181      }
182      break;
183    }
184    case chrome::NOTIFICATION_BROWSER_THEME_CHANGED:
185      UpdateState();
186      break;
187    default:
188      NOTREACHED();
189      break;
190  }
191}
192
193bool BrowserActionView::Activate() {
194  if (!IsPopup())
195    return true;
196
197  view_controller_->ExecuteActionByUser();
198
199  // TODO(erikkay): Run a nested modal loop while the mouse is down to
200  // enable menu-like drag-select behavior.
201
202  // The return value of this method is returned via OnMousePressed.
203  // We need to return false here since we're handing off focus to another
204  // widget/view, and true will grab it right back and try to send events
205  // to us.
206  return false;
207}
208
209bool BrowserActionView::OnMousePressed(const ui::MouseEvent& event) {
210  if (!event.IsRightMouseButton()) {
211    return IsPopup() ? MenuButton::OnMousePressed(event) :
212                       LabelButton::OnMousePressed(event);
213  }
214  return false;
215}
216
217void BrowserActionView::OnMouseReleased(const ui::MouseEvent& event) {
218  if (IsPopup() || view_controller_->is_menu_running()) {
219    // TODO(erikkay) this never actually gets called (probably because of the
220    // loss of focus).
221    MenuButton::OnMouseReleased(event);
222  } else {
223    LabelButton::OnMouseReleased(event);
224  }
225}
226
227void BrowserActionView::OnMouseExited(const ui::MouseEvent& event) {
228  if (IsPopup() || view_controller_->is_menu_running())
229    MenuButton::OnMouseExited(event);
230  else
231    LabelButton::OnMouseExited(event);
232}
233
234bool BrowserActionView::OnKeyReleased(const ui::KeyEvent& event) {
235  return IsPopup() ? MenuButton::OnKeyReleased(event) :
236                     LabelButton::OnKeyReleased(event);
237}
238
239void BrowserActionView::OnGestureEvent(ui::GestureEvent* event) {
240  if (IsPopup())
241    MenuButton::OnGestureEvent(event);
242  else
243    LabelButton::OnGestureEvent(event);
244}
245
246scoped_ptr<LabelButtonBorder> BrowserActionView::CreateDefaultBorder() const {
247  scoped_ptr<LabelButtonBorder> border = LabelButton::CreateDefaultBorder();
248  border->set_insets(gfx::Insets(kBorderInset, kBorderInset,
249                                 kBorderInset, kBorderInset));
250  return border.Pass();
251}
252
253bool BrowserActionView::IsEnabled(int tab_id) const {
254  return view_controller_->extension_action()->GetIsVisible(tab_id);
255}
256
257gfx::ImageSkia BrowserActionView::GetIconWithBadge() {
258  int tab_id = view_controller_->GetCurrentTabId();
259  gfx::Size spacing(0, ToolbarView::kVertSpacing);
260  gfx::ImageSkia icon = *view_controller_->GetIcon(tab_id).ToImageSkia();
261  if (!IsEnabled(tab_id))
262    icon = gfx::ImageSkiaOperations::CreateTransparentImage(icon, .25);
263  return extension_action()->GetIconWithBadge(icon, tab_id, spacing);
264}
265
266gfx::ImageSkia BrowserActionView::GetIconForTest() {
267  return GetImage(views::Button::STATE_NORMAL);
268}
269
270void BrowserActionView::OnIconUpdated() {
271  UpdateState();
272  if (icon_observer_)
273    icon_observer_->OnIconUpdated(GetIconWithBadge());
274}
275
276views::View* BrowserActionView::GetAsView() {
277  return this;
278}
279
280bool BrowserActionView::IsShownInMenu() {
281  return delegate_->ShownInsideMenu();
282}
283
284views::FocusManager* BrowserActionView::GetFocusManagerForAccelerator() {
285  return GetFocusManager();
286}
287
288views::Widget* BrowserActionView::GetParentForContextMenu() {
289  // RunMenuAt expects a nested menu to be parented by the same widget as the
290  // already visible menu, in this case the Chrome menu.
291  return delegate_->ShownInsideMenu() ?
292      BrowserView::GetBrowserViewForBrowser(view_controller_->browser())
293          ->toolbar()->app_menu()->GetWidget() :
294      GetWidget();
295}
296
297ExtensionActionViewController*
298BrowserActionView::GetPreferredPopupViewController() {
299  return delegate_->ShownInsideMenu() ?
300      delegate_->GetMainViewForExtension(extension())->view_controller() :
301      view_controller();
302}
303
304views::View* BrowserActionView::GetReferenceViewForPopup() {
305  // Browser actions in the overflow menu can still show popups, so we may need
306  // a reference view other than this button's parent. If so, use the overflow
307  // view.
308  return visible() ? this : delegate_->GetOverflowReferenceView();
309}
310
311views::MenuButton* BrowserActionView::GetContextMenuButton() {
312  DCHECK(visible());  // We should never show a context menu for a hidden item.
313  return this;
314}
315
316content::WebContents* BrowserActionView::GetCurrentWebContents() {
317  return delegate_->GetCurrentWebContents();
318}
319
320void BrowserActionView::HideActivePopup() {
321  delegate_->HideActivePopup();
322}
323
324void BrowserActionView::OnPopupShown(bool grant_tab_permissions) {
325  delegate_->SetPopupOwner(this);
326  // If this was through direct user action, we press the menu button.
327  if (grant_tab_permissions) {
328    // We set the state of the menu button we're using as a reference view,
329    // which is either this or the overflow reference view.
330    // This cast is safe because GetReferenceViewForPopup returns either |this|
331    // or delegate_->GetOverflowReferenceView(), which returns a MenuButton.
332    views::MenuButton* reference_view =
333        static_cast<views::MenuButton*>(GetReferenceViewForPopup());
334    pressed_lock_.reset(new views::MenuButton::PressedLock(reference_view));
335  }
336}
337
338void BrowserActionView::CleanupPopup() {
339  // We need to do these actions synchronously (instead of closing and then
340  // performing the rest of the cleanup in OnWidgetDestroyed()) because
341  // OnWidgetDestroyed() can be called asynchronously from Close(), and we need
342  // to keep the delegate's popup owner up-to-date.
343  delegate_->SetPopupOwner(NULL);
344  pressed_lock_.reset();  // Unpress the menu button if it was pressed.
345}
346