Upstream version 7.36.149.0
[platform/framework/web/crosswalk.git] / src / chrome / browser / ui / views / toolbar / browser_action_view.cc
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 "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"
33
34 using extensions::Extension;
35
36 ////////////////////////////////////////////////////////////////////////////////
37 // BrowserActionView
38
39 bool BrowserActionView::Delegate::NeedToShowMultipleIconStates() const {
40   return true;
41 }
42
43 bool BrowserActionView::Delegate::NeedToShowTooltip() const {
44   return true;
45 }
46
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();
59 }
60
61 BrowserActionView::~BrowserActionView() {
62   button_->Destroy();
63 }
64
65 gfx::ImageSkia BrowserActionView::GetIconWithBadge() {
66   return button_->GetIconWithBadge();
67 }
68
69 void BrowserActionView::Layout() {
70   button_->SetBounds(0, y(), width(), height());
71 }
72
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;
77 }
78
79 gfx::Size BrowserActionView::GetPreferredSize() {
80   return gfx::Size(BrowserActionsContainer::IconWidth(false),
81                    BrowserActionsContainer::IconHeight());
82 }
83
84 void BrowserActionView::PaintChildren(gfx::Canvas* canvas) {
85   View::PaintChildren(canvas);
86   ExtensionAction* action = button()->browser_action();
87   int tab_id = delegate_->GetCurrentTabId();
88   if (tab_id >= 0)
89     action->PaintBadge(canvas, GetLocalBounds(), tab_id);
90 }
91
92 ////////////////////////////////////////////////////////////////////////////////
93 // BrowserActionButton
94
95 BrowserActionButton::BrowserActionButton(const Extension* extension,
96                                          Browser* browser,
97                                          BrowserActionView::Delegate* delegate)
98     : MenuButton(this, base::string16(), NULL, false),
99       browser_(browser),
100       browser_action_(
101           extensions::ExtensionActionManager::Get(browser->profile())->
102           GetBrowserAction(*extension)),
103       extension_(extension),
104       icon_factory_(browser->profile(), extension, browser_action_, this),
105       delegate_(delegate),
106       context_menu_(NULL),
107       called_registered_extension_command_(false),
108       icon_observer_(NULL) {
109   SetBorder(views::Border::NullBorder());
110   set_alignment(TextButton::ALIGN_CENTER);
111   set_context_menu_controller(this);
112
113   // No UpdateState() here because View hierarchy not setup yet. Our parent
114   // should call UpdateState() after creation.
115
116   content::NotificationSource notification_source =
117       content::Source<Profile>(browser_->profile()->GetOriginalProfile());
118   registrar_.Add(this, chrome::NOTIFICATION_EXTENSION_BROWSER_ACTION_UPDATED,
119                  content::Source<ExtensionAction>(browser_action_));
120   registrar_.Add(this, chrome::NOTIFICATION_EXTENSION_COMMAND_ADDED,
121                  notification_source);
122   registrar_.Add(this, chrome::NOTIFICATION_EXTENSION_COMMAND_REMOVED,
123                  notification_source);
124
125   // We also listen for browser theme changes on linux because a switch from or
126   // to GTK requires that we regrab our browser action images.
127   registrar_.Add(
128       this,
129       chrome::NOTIFICATION_BROWSER_THEME_CHANGED,
130       content::Source<ThemeService>(
131           ThemeServiceFactory::GetForProfile(browser->profile())));
132 }
133
134 void BrowserActionButton::Destroy() {
135   MaybeUnregisterExtensionCommand(false);
136
137   if (context_menu_) {
138     context_menu_->Cancel();
139     base::MessageLoop::current()->DeleteSoon(FROM_HERE, this);
140   } else {
141     delete this;
142   }
143 }
144
145 void BrowserActionButton::ViewHierarchyChanged(
146     const ViewHierarchyChangedDetails& details) {
147   if (details.is_add && !called_registered_extension_command_ &&
148       GetFocusManager()) {
149     MaybeRegisterExtensionCommand();
150     called_registered_extension_command_ = true;
151   }
152
153   MenuButton::ViewHierarchyChanged(details);
154 }
155
156 bool BrowserActionButton::CanHandleAccelerators() const {
157   // View::CanHandleAccelerators() checks to see if the view is visible before
158   // allowing it to process accelerators. This is not appropriate for browser
159   // actions buttons, which can be hidden inside the overflow area.
160   return true;
161 }
162
163 void BrowserActionButton::GetAccessibleState(ui::AXViewState* state) {
164   views::MenuButton::GetAccessibleState(state);
165   state->role = ui::AX_ROLE_BUTTON;
166 }
167
168 void BrowserActionButton::ButtonPressed(views::Button* sender,
169                                         const ui::Event& event) {
170   delegate_->OnBrowserActionExecuted(this);
171 }
172
173 void BrowserActionButton::ShowContextMenuForView(
174     View* source,
175     const gfx::Point& point,
176     ui::MenuSourceType source_type) {
177   if (!extension()->ShowConfigureContextMenus())
178     return;
179
180   SetButtonPushed();
181
182   // Reconstructs the menu every time because the menu's contents are dynamic.
183   scoped_refptr<ExtensionContextMenuModel> context_menu_contents_(
184       new ExtensionContextMenuModel(extension(), browser_, delegate_));
185   menu_runner_.reset(new views::MenuRunner(context_menu_contents_.get()));
186
187   context_menu_ = menu_runner_->GetMenu();
188   gfx::Point screen_loc;
189   views::View::ConvertPointToScreen(this, &screen_loc);
190   if (menu_runner_->RunMenuAt(
191           GetWidget(),
192           NULL,
193           gfx::Rect(screen_loc, size()),
194           views::MENU_ANCHOR_TOPLEFT,
195           source_type,
196           views::MenuRunner::HAS_MNEMONICS | views::MenuRunner::CONTEXT_MENU) ==
197       views::MenuRunner::MENU_DELETED) {
198     return;
199   }
200
201   menu_runner_.reset();
202   SetButtonNotPushed();
203   context_menu_ = NULL;
204 }
205
206 void BrowserActionButton::UpdateState() {
207   int tab_id = delegate_->GetCurrentTabId();
208   if (tab_id < 0)
209     return;
210
211   SetShowMultipleIconStates(delegate_->NeedToShowMultipleIconStates());
212
213   if (!IsEnabled(tab_id)) {
214     SetState(views::CustomButton::STATE_DISABLED);
215   } else {
216     SetState(menu_visible_ ?
217              views::CustomButton::STATE_PRESSED :
218              views::CustomButton::STATE_NORMAL);
219   }
220
221   gfx::ImageSkia icon = *icon_factory_.GetIcon(tab_id).ToImageSkia();
222
223   if (!icon.isNull()) {
224     if (!browser_action()->GetIsVisible(tab_id))
225       icon = gfx::ImageSkiaOperations::CreateTransparentImage(icon, .25);
226
227     ThemeService* theme =
228         ThemeServiceFactory::GetForProfile(browser_->profile());
229
230     gfx::ImageSkia bg = *theme->GetImageSkiaNamed(IDR_BROWSER_ACTION);
231     SetIcon(gfx::ImageSkiaOperations::CreateSuperimposedImage(bg, icon));
232
233     gfx::ImageSkia bg_h = *theme->GetImageSkiaNamed(IDR_BROWSER_ACTION_H);
234     SetHoverIcon(gfx::ImageSkiaOperations::CreateSuperimposedImage(bg_h, icon));
235
236     gfx::ImageSkia bg_p = *theme->GetImageSkiaNamed(IDR_BROWSER_ACTION_P);
237     SetPushedIcon(
238         gfx::ImageSkiaOperations::CreateSuperimposedImage(bg_p, icon));
239   }
240
241   // If the browser action name is empty, show the extension name instead.
242   std::string title = browser_action()->GetTitle(tab_id);
243   base::string16 name =
244       base::UTF8ToUTF16(title.empty() ? extension()->name() : title);
245   SetTooltipText(delegate_->NeedToShowTooltip() ? name : base::string16());
246   SetAccessibleName(name);
247
248   parent()->SchedulePaint();
249 }
250
251 bool BrowserActionButton::IsPopup() {
252   int tab_id = delegate_->GetCurrentTabId();
253   return (tab_id < 0) ? false : browser_action_->HasPopup(tab_id);
254 }
255
256 GURL BrowserActionButton::GetPopupUrl() {
257   int tab_id = delegate_->GetCurrentTabId();
258   return (tab_id < 0) ? GURL() : browser_action_->GetPopupUrl(tab_id);
259 }
260
261 void BrowserActionButton::Observe(int type,
262                                   const content::NotificationSource& source,
263                                   const content::NotificationDetails& details) {
264   switch (type) {
265     case chrome::NOTIFICATION_EXTENSION_BROWSER_ACTION_UPDATED:
266       UpdateState();
267       // The browser action may have become visible/hidden so we need to make
268       // sure the state gets updated.
269       delegate_->OnBrowserActionVisibilityChanged();
270       break;
271     case chrome::NOTIFICATION_EXTENSION_COMMAND_ADDED:
272     case chrome::NOTIFICATION_EXTENSION_COMMAND_REMOVED: {
273       std::pair<const std::string, const std::string>* payload =
274           content::Details<std::pair<const std::string, const std::string> >(
275               details).ptr();
276       if (extension_->id() == payload->first &&
277           payload->second ==
278               extensions::manifest_values::kBrowserActionCommandEvent) {
279         if (type == chrome::NOTIFICATION_EXTENSION_COMMAND_ADDED)
280           MaybeRegisterExtensionCommand();
281         else
282           MaybeUnregisterExtensionCommand(true);
283       }
284       break;
285     }
286     case chrome::NOTIFICATION_BROWSER_THEME_CHANGED:
287       UpdateState();
288       break;
289     default:
290       NOTREACHED();
291       break;
292   }
293 }
294
295 void BrowserActionButton::OnIconUpdated() {
296   UpdateState();
297   if (icon_observer_)
298     icon_observer_->OnIconUpdated(GetIconWithBadge());
299 }
300
301 bool BrowserActionButton::Activate() {
302   if (!IsPopup())
303     return true;
304
305   delegate_->OnBrowserActionExecuted(this);
306
307   // TODO(erikkay): Run a nested modal loop while the mouse is down to
308   // enable menu-like drag-select behavior.
309
310   // The return value of this method is returned via OnMousePressed.
311   // We need to return false here since we're handing off focus to another
312   // widget/view, and true will grab it right back and try to send events
313   // to us.
314   return false;
315 }
316
317 bool BrowserActionButton::OnMousePressed(const ui::MouseEvent& event) {
318   if (!event.IsRightMouseButton()) {
319     return IsPopup() ? MenuButton::OnMousePressed(event) :
320                        TextButton::OnMousePressed(event);
321   }
322
323   if (!views::View::ShouldShowContextMenuOnMousePress()) {
324     // See comments in MenuButton::Activate() as to why this is needed.
325     SetMouseHandler(NULL);
326
327     ShowContextMenu(gfx::Point(), ui::MENU_SOURCE_MOUSE);
328   }
329   return false;
330 }
331
332 void BrowserActionButton::OnMouseReleased(const ui::MouseEvent& event) {
333   if (IsPopup() || context_menu_) {
334     // TODO(erikkay) this never actually gets called (probably because of the
335     // loss of focus).
336     MenuButton::OnMouseReleased(event);
337   } else {
338     TextButton::OnMouseReleased(event);
339   }
340 }
341
342 void BrowserActionButton::OnMouseExited(const ui::MouseEvent& event) {
343   if (IsPopup() || context_menu_)
344     MenuButton::OnMouseExited(event);
345   else
346     TextButton::OnMouseExited(event);
347 }
348
349 bool BrowserActionButton::OnKeyReleased(const ui::KeyEvent& event) {
350   return IsPopup() ? MenuButton::OnKeyReleased(event) :
351                      TextButton::OnKeyReleased(event);
352 }
353
354 void BrowserActionButton::OnGestureEvent(ui::GestureEvent* event) {
355   if (IsPopup())
356     MenuButton::OnGestureEvent(event);
357   else
358     TextButton::OnGestureEvent(event);
359 }
360
361 bool BrowserActionButton::AcceleratorPressed(
362     const ui::Accelerator& accelerator) {
363   delegate_->OnBrowserActionExecuted(this);
364   return true;
365 }
366
367 void BrowserActionButton::SetButtonPushed() {
368   SetState(views::CustomButton::STATE_PRESSED);
369   menu_visible_ = true;
370 }
371
372 void BrowserActionButton::SetButtonNotPushed() {
373   SetState(views::CustomButton::STATE_NORMAL);
374   menu_visible_ = false;
375 }
376
377 bool BrowserActionButton::IsEnabled(int tab_id) const {
378   return browser_action_->GetIsVisible(tab_id);
379 }
380
381 gfx::ImageSkia BrowserActionButton::GetIconWithBadge() {
382   int tab_id = delegate_->GetCurrentTabId();
383   gfx::Size spacing(0, ToolbarView::kVertSpacing);
384   gfx::ImageSkia icon = *icon_factory_.GetIcon(tab_id).ToImageSkia();
385   if (!IsEnabled(tab_id))
386     icon = gfx::ImageSkiaOperations::CreateTransparentImage(icon, .25);
387   return browser_action_->GetIconWithBadge(icon, tab_id, spacing);
388 }
389
390 gfx::ImageSkia BrowserActionButton::GetIconForTest() {
391   return icon();
392 }
393
394 BrowserActionButton::~BrowserActionButton() {
395 }
396
397 void BrowserActionButton::MaybeRegisterExtensionCommand() {
398   extensions::CommandService* command_service =
399       extensions::CommandService::Get(browser_->profile());
400   extensions::Command browser_action_command;
401   if (command_service->GetBrowserActionCommand(
402           extension_->id(),
403           extensions::CommandService::ACTIVE_ONLY,
404           &browser_action_command,
405           NULL)) {
406     keybinding_.reset(new ui::Accelerator(
407         browser_action_command.accelerator()));
408     GetFocusManager()->RegisterAccelerator(
409         *keybinding_.get(), ui::AcceleratorManager::kHighPriority, this);
410   }
411 }
412
413 void BrowserActionButton::MaybeUnregisterExtensionCommand(bool only_if_active) {
414   if (!keybinding_.get() || !GetFocusManager())
415     return;
416
417   extensions::CommandService* command_service =
418       extensions::CommandService::Get(browser_->profile());
419
420   extensions::Command browser_action_command;
421   if (!only_if_active || !command_service->GetBrowserActionCommand(
422           extension_->id(),
423           extensions::CommandService::ACTIVE_ONLY,
424           &browser_action_command,
425           NULL)) {
426     GetFocusManager()->UnregisterAccelerator(*keybinding_.get(), this);
427     keybinding_.reset(NULL);
428   }
429 }