Add ability to gather metrics to BubbleManager.
[chromium-blink-merge.git] / chrome / browser / ui / toolbar / toolbar_actions_bar.cc
blob4760d0b7903c6dbe1887bb26b198c55157dded11
1 // Copyright 2014 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/toolbar/toolbar_actions_bar.h"
7 #include "base/auto_reset.h"
8 #include "base/location.h"
9 #include "base/profiler/scoped_tracker.h"
10 #include "base/single_thread_task_runner.h"
11 #include "base/thread_task_runner_handle.h"
12 #include "chrome/browser/extensions/extension_action_manager.h"
13 #include "chrome/browser/extensions/extension_message_bubble_controller.h"
14 #include "chrome/browser/extensions/extension_util.h"
15 #include "chrome/browser/profiles/profile.h"
16 #include "chrome/browser/sessions/session_tab_helper.h"
17 #include "chrome/browser/ui/browser.h"
18 #include "chrome/browser/ui/browser_window.h"
19 #include "chrome/browser/ui/extensions/extension_action_view_controller.h"
20 #include "chrome/browser/ui/extensions/extension_message_bubble_factory.h"
21 #include "chrome/browser/ui/tabs/tab_strip_model.h"
22 #include "chrome/browser/ui/toolbar/component_toolbar_actions_factory.h"
23 #include "chrome/browser/ui/toolbar/toolbar_action_view_controller.h"
24 #include "chrome/browser/ui/toolbar/toolbar_actions_bar_delegate.h"
25 #include "chrome/common/pref_names.h"
26 #include "components/crx_file/id_util.h"
27 #include "components/pref_registry/pref_registry_syncable.h"
28 #include "extensions/browser/extension_registry.h"
29 #include "extensions/browser/extension_system.h"
30 #include "extensions/browser/runtime_data.h"
31 #include "extensions/common/extension.h"
32 #include "extensions/common/feature_switch.h"
33 #include "grit/theme_resources.h"
34 #include "ui/base/resource/resource_bundle.h"
35 #include "ui/gfx/image/image_skia.h"
37 namespace {
39 using WeakToolbarActions = std::vector<ToolbarActionViewController*>;
41 // Matches ToolbarView::kStandardSpacing;
42 const int kLeftPadding = 3;
43 const int kRightPadding = kLeftPadding;
44 const int kItemSpacing = kLeftPadding;
45 const int kOverflowLeftPadding = kItemSpacing;
46 const int kOverflowRightPadding = kItemSpacing;
48 enum DimensionType { WIDTH, HEIGHT };
50 // Returns the width or height of the toolbar action icon size.
51 int GetIconDimension(DimensionType type) {
52 static bool initialized = false;
53 static int icon_height = 0;
54 static int icon_width = 0;
55 if (!initialized) {
56 initialized = true;
57 gfx::ImageSkia* skia =
58 ui::ResourceBundle::GetSharedInstance().GetImageSkiaNamed(
59 IDR_BROWSER_ACTION);
60 icon_height = skia->height();
61 icon_width = skia->width();
63 return type == WIDTH ? icon_width : icon_height;
66 // Takes a reference vector |reference| of length n, where n is less than or
67 // equal to the length of |to_sort|, and rearranges |to_sort| so that
68 // |to_sort|'s first n elements match the n elements of |reference| (the order
69 // of any remaining elements in |to_sort| is unspecified).
70 // |equal| is used to compare the elements of |to_sort| and |reference|.
71 // This allows us to sort a vector to match another vector of two different
72 // types without needing to construct a more cumbersome comparator class.
73 // |FunctionType| should equate to (something similar to)
74 // bool Equal(const Type1&, const Type2&), but we can't enforce this
75 // because of MSVC compilation limitations.
76 template<typename Type1, typename Type2, typename FunctionType>
77 void SortContainer(std::vector<Type1>* to_sort,
78 const std::vector<Type2>& reference,
79 FunctionType equal) {
80 DCHECK_GE(to_sort->size(), reference.size()) <<
81 "|to_sort| must contain all elements in |reference|.";
82 if (reference.empty())
83 return;
84 // Run through the each element and compare it to the reference. If something
85 // is out of place, find the correct spot for it.
86 for (size_t i = 0; i < reference.size() - 1; ++i) {
87 if (!equal(to_sort->at(i), reference[i])) {
88 // Find the correct index (it's guaranteed to be after our current
89 // index, since everything up to this point is correct), and swap.
90 size_t j = i + 1;
91 while (!equal(to_sort->at(j), reference[i])) {
92 ++j;
93 DCHECK_LT(j, to_sort->size()) <<
94 "Item in |reference| not found in |to_sort|.";
96 std::swap(to_sort->at(i), to_sort->at(j));
101 } // namespace
103 // static
104 bool ToolbarActionsBar::disable_animations_for_testing_ = false;
106 ToolbarActionsBar::PlatformSettings::PlatformSettings(bool in_overflow_mode)
107 : left_padding(in_overflow_mode ? kOverflowLeftPadding : kLeftPadding),
108 right_padding(in_overflow_mode ? kOverflowRightPadding : kRightPadding),
109 item_spacing(kItemSpacing),
110 icons_per_overflow_menu_row(1),
111 chevron_enabled(!extensions::FeatureSwitch::extension_action_redesign()->
112 IsEnabled()) {
115 ToolbarActionsBar::ToolbarActionsBar(ToolbarActionsBarDelegate* delegate,
116 Browser* browser,
117 ToolbarActionsBar* main_bar)
118 : delegate_(delegate),
119 browser_(browser),
120 model_(ToolbarActionsModel::Get(browser_->profile())),
121 main_bar_(main_bar),
122 platform_settings_(main_bar != nullptr),
123 popup_owner_(nullptr),
124 model_observer_(this),
125 suppress_layout_(false),
126 suppress_animation_(true),
127 checked_extension_bubble_(false),
128 popped_out_action_(nullptr),
129 weak_ptr_factory_(this) {
130 if (model_) // |model_| can be null in unittests.
131 model_observer_.Add(model_);
134 ToolbarActionsBar::~ToolbarActionsBar() {
135 // We don't just call DeleteActions() here because it makes assumptions about
136 // the order of deletion between the views and the ToolbarActionsBar.
137 DCHECK(toolbar_actions_.empty()) <<
138 "Must call DeleteActions() before destruction.";
141 // static
142 int ToolbarActionsBar::IconWidth(bool include_padding) {
143 return GetIconDimension(WIDTH) + (include_padding ? kItemSpacing : 0);
146 // static
147 int ToolbarActionsBar::IconHeight() {
148 return GetIconDimension(HEIGHT);
151 // static
152 void ToolbarActionsBar::RegisterProfilePrefs(
153 user_prefs::PrefRegistrySyncable* registry) {
154 registry->RegisterBooleanPref(
155 prefs::kToolbarIconSurfacingBubbleAcknowledged,
156 false,
157 user_prefs::PrefRegistrySyncable::SYNCABLE_PREF);
158 registry->RegisterInt64Pref(prefs::kToolbarIconSurfacingBubbleLastShowTime,
162 gfx::Size ToolbarActionsBar::GetPreferredSize() const {
163 int icon_count = GetIconCount();
164 if (in_overflow_mode()) {
165 // In overflow, we always have a preferred size of a full row (even if we
166 // don't use it), and always of at least one row. The parent may decide to
167 // show us even when empty, e.g. as a drag target for dragging in icons from
168 // the main container.
169 int row_count = ((std::max(0, icon_count - 1)) /
170 platform_settings_.icons_per_overflow_menu_row) + 1;
171 return gfx::Size(
172 IconCountToWidth(platform_settings_.icons_per_overflow_menu_row),
173 row_count * IconHeight());
176 // If there are no actions to show (and this isn't an overflow container),
177 // then don't show the container at all.
178 if (toolbar_actions_.empty())
179 return gfx::Size();
181 return gfx::Size(IconCountToWidth(icon_count), IconHeight());
184 int ToolbarActionsBar::GetMinimumWidth() const {
185 if (!platform_settings_.chevron_enabled || toolbar_actions_.empty())
186 return kLeftPadding;
187 return kLeftPadding + delegate_->GetChevronWidth() + kRightPadding;
190 int ToolbarActionsBar::GetMaximumWidth() const {
191 return IconCountToWidth(-1);
194 int ToolbarActionsBar::IconCountToWidth(int icons) const {
195 if (icons < 0)
196 icons = toolbar_actions_.size();
197 bool display_chevron =
198 platform_settings_.chevron_enabled &&
199 static_cast<size_t>(icons) < toolbar_actions_.size();
200 if (icons == 0 && !display_chevron)
201 return platform_settings_.left_padding;
202 int icons_size = (icons == 0) ? 0 :
203 (icons * IconWidth(true)) - platform_settings_.item_spacing;
204 int chevron_size = display_chevron ? delegate_->GetChevronWidth() : 0;
205 int padding = platform_settings_.left_padding +
206 platform_settings_.right_padding;
207 return icons_size + chevron_size + padding;
210 size_t ToolbarActionsBar::WidthToIconCount(int pixels) const {
211 // Check for widths large enough to show the entire icon set.
212 if (pixels >= IconCountToWidth(-1))
213 return toolbar_actions_.size();
215 // We reserve space for the padding on either side of the toolbar...
216 int available_space = pixels -
217 (platform_settings_.left_padding + platform_settings_.right_padding);
218 // ... and, if the chevron is enabled, the chevron.
219 if (platform_settings_.chevron_enabled)
220 available_space -= delegate_->GetChevronWidth();
222 // Now we add an extra between-item padding value so the space can be divided
223 // evenly by (size of icon with padding).
224 return static_cast<size_t>(std::max(
225 0, available_space + platform_settings_.item_spacing) / IconWidth(true));
228 size_t ToolbarActionsBar::GetIconCount() const {
229 if (!model_)
230 return 0u;
232 int pop_out_modifier = 0;
233 // If there is a popped out action, it could affect the number of visible
234 // icons - but only if it wouldn't otherwise be visible.
235 if (popped_out_action_) {
236 size_t popped_out_index =
237 std::find(toolbar_actions_.begin(),
238 toolbar_actions_.end(),
239 popped_out_action_) - toolbar_actions_.begin();
240 pop_out_modifier = popped_out_index >= model_->visible_icon_count() ? 1 : 0;
243 // We purposefully do not account for any "popped out" actions in overflow
244 // mode. This is because the popup cannot be showing while the overflow menu
245 // is open, so there's no concern there. Also, if the user has a popped out
246 // action, and immediately opens the overflow menu, we *want* the action there
247 // (since it will close the popup, but do so asynchronously, and we don't
248 // want to "slide" the action back in.
249 size_t visible_icons = in_overflow_mode() ?
250 toolbar_actions_.size() - model_->visible_icon_count() :
251 model_->visible_icon_count() + pop_out_modifier;
253 #if DCHECK_IS_ON()
254 // Good time for some sanity checks: We should never try to display more
255 // icons than we have, and we should always have a view per item in the model.
256 // (The only exception is if this is in initialization.)
257 if (!toolbar_actions_.empty() && !suppress_layout_ &&
258 model_->actions_initialized()) {
259 DCHECK_LE(visible_icons, toolbar_actions_.size());
260 DCHECK_EQ(model_->toolbar_items().size(), toolbar_actions_.size());
262 #endif
264 return visible_icons;
267 gfx::Rect ToolbarActionsBar::GetFrameForIndex(size_t index) const {
268 size_t start_index = in_overflow_mode() ?
269 toolbar_actions_.size() - GetIconCount() : 0u;
271 // If the index is for an action that is before range we show (i.e., is for
272 // a button that's on the main bar, and this is the overflow), send back an
273 // empty rect.
274 if (index < start_index)
275 return gfx::Rect();
277 size_t relative_index = index - start_index;
278 int icons_per_overflow_row = platform_settings().icons_per_overflow_menu_row;
279 size_t row_index = in_overflow_mode() ?
280 relative_index / icons_per_overflow_row : 0;
281 size_t index_in_row = in_overflow_mode() ?
282 relative_index % icons_per_overflow_row : relative_index;
284 return gfx::Rect(platform_settings().left_padding +
285 index_in_row * IconWidth(true),
286 row_index * IconHeight(),
287 IconWidth(false),
288 IconHeight());
291 std::vector<ToolbarActionViewController*>
292 ToolbarActionsBar::GetActions() const {
293 std::vector<ToolbarActionViewController*> actions = toolbar_actions_.get();
295 // If there is an action that should be popped out, and it's not visible by
296 // default, make it the final action in the list.
297 if (popped_out_action_) {
298 size_t index =
299 std::find(actions.begin(), actions.end(), popped_out_action_) -
300 actions.begin();
301 DCHECK_NE(actions.size(), index);
302 size_t visible = GetIconCount();
303 if (index >= visible) {
304 size_t rindex = actions.size() - index - 1;
305 std::rotate(actions.rbegin() + rindex,
306 actions.rbegin() + rindex + 1,
307 actions.rend() - visible + 1);
311 return actions;
314 void ToolbarActionsBar::CreateActions() {
315 DCHECK(toolbar_actions_.empty());
316 // If the model isn't initialized, wait for it.
317 if (!model_ || !model_->actions_initialized())
318 return;
321 // TODO(robliao): Remove ScopedTracker below once https://crbug.com/463337
322 // is fixed.
323 tracked_objects::ScopedTracker tracking_profile1(
324 FROM_HERE_WITH_EXPLICIT_FUNCTION("ToolbarActionsBar::CreateActions1"));
325 // We don't redraw the view while creating actions.
326 base::AutoReset<bool> layout_resetter(&suppress_layout_, true);
328 // Get the toolbar actions.
329 toolbar_actions_ = model_->CreateActions(browser_, this);
330 if (!model_->is_highlighting()) {
331 // TODO(robliao): Remove ScopedTracker below once https://crbug.com/463337
332 // is fixed.
333 tracked_objects::ScopedTracker tracking_profile2(
334 FROM_HERE_WITH_EXPLICIT_FUNCTION(
335 "ToolbarActionsBar::CreateActions2"));
338 if (!toolbar_actions_.empty()) {
339 // TODO(robliao): Remove ScopedTracker below once https://crbug.com/463337
340 // is fixed.
341 tracked_objects::ScopedTracker tracking_profile3(
342 FROM_HERE_WITH_EXPLICIT_FUNCTION(
343 "ToolbarActionsBar::CreateActions3"));
344 ReorderActions();
347 tracked_objects::ScopedTracker tracking_profile4(
348 FROM_HERE_WITH_EXPLICIT_FUNCTION("ToolbarActionsBar::CreateActions4"));
350 for (size_t i = 0; i < toolbar_actions_.size(); ++i)
351 delegate_->AddViewForAction(toolbar_actions_[i], i);
354 // Once the actions are created, we should animate the changes.
355 suppress_animation_ = false;
357 // CreateActions() can be called multiple times, so we need to make sure we
358 // haven't already shown the bubble.
359 // Extension bubbles can also highlight a subset of actions, so don't show the
360 // bubble if the toolbar is already highlighting a different set.
361 if (!checked_extension_bubble_ && !is_highlighting()) {
362 checked_extension_bubble_ = true;
363 // CreateActions() can be called as part of the browser window set up, which
364 // we need to let finish before showing the actions.
365 scoped_ptr<extensions::ExtensionMessageBubbleController> controller =
366 ExtensionMessageBubbleFactory(browser_).GetController();
367 if (controller) {
368 base::ThreadTaskRunnerHandle::Get()->PostTask(
369 FROM_HERE, base::Bind(&ToolbarActionsBar::MaybeShowExtensionBubble,
370 weak_ptr_factory_.GetWeakPtr(),
371 base::Passed(controller.Pass())));
376 void ToolbarActionsBar::DeleteActions() {
377 HideActivePopup();
378 delegate_->RemoveAllViews();
379 toolbar_actions_.clear();
382 void ToolbarActionsBar::Update() {
383 if (toolbar_actions_.empty())
384 return; // Nothing to do.
387 // Don't layout until the end.
388 base::AutoReset<bool> layout_resetter(&suppress_layout_, true);
389 for (ToolbarActionViewController* action : toolbar_actions_)
390 action->UpdateState();
393 ReorderActions(); // Also triggers a draw.
396 bool ToolbarActionsBar::ShowToolbarActionPopup(const std::string& action_id,
397 bool grant_active_tab) {
398 // Don't override another popup, and only show in the active window.
399 if (popup_owner() || !browser_->window()->IsActive())
400 return false;
402 ToolbarActionViewController* action = GetActionForId(action_id);
403 return action && action->ExecuteAction(grant_active_tab);
406 void ToolbarActionsBar::SetOverflowRowWidth(int width) {
407 DCHECK(in_overflow_mode());
408 platform_settings_.icons_per_overflow_menu_row =
409 std::max((width - kItemSpacing) / IconWidth(true), 1);
412 void ToolbarActionsBar::OnResizeComplete(int width) {
413 DCHECK(!in_overflow_mode()); // The user can't resize the overflow container.
414 size_t resized_count = WidthToIconCount(width);
415 // Save off the desired number of visible icons. We do this now instead of
416 // at the end of the animation so that even if the browser is shut down
417 // while animating, the right value will be restored on next run.
418 model_->SetVisibleIconCount(resized_count);
421 void ToolbarActionsBar::OnDragDrop(int dragged_index,
422 int dropped_index,
423 DragType drag_type) {
424 // All drag-and-drop commands should go to the main bar.
425 if (in_overflow_mode()) {
426 main_bar_->OnDragDrop(dragged_index, dropped_index, drag_type);
427 return;
430 int delta = 0;
431 if (drag_type == DRAG_TO_OVERFLOW)
432 delta = -1;
433 else if (drag_type == DRAG_TO_MAIN)
434 delta = 1;
435 model_->MoveActionIcon(toolbar_actions_[dragged_index]->GetId(),
436 dropped_index);
437 if (delta)
438 model_->SetVisibleIconCount(model_->visible_icon_count() + delta);
441 void ToolbarActionsBar::OnAnimationEnded() {
442 // Check if we were waiting for animation to complete to either show a
443 // message bubble, or to show a popup.
444 if (pending_extension_bubble_controller_) {
445 MaybeShowExtensionBubble(pending_extension_bubble_controller_.Pass());
446 } else if (!popped_out_closure_.is_null()) {
447 popped_out_closure_.Run();
448 popped_out_closure_.Reset();
452 bool ToolbarActionsBar::IsActionVisibleOnMainBar(
453 const ToolbarActionViewController* action) const {
454 if (in_overflow_mode())
455 return main_bar_->IsActionVisibleOnMainBar(action);
457 size_t index = std::find(toolbar_actions_.begin(),
458 toolbar_actions_.end(),
459 action) - toolbar_actions_.begin();
460 return index < GetIconCount() || action == popped_out_action_;
463 void ToolbarActionsBar::PopOutAction(ToolbarActionViewController* controller,
464 const base::Closure& closure) {
465 DCHECK(!in_overflow_mode()) << "Only the main bar can pop out actions.";
466 DCHECK(!popped_out_action_) << "Only one action can be popped out at a time!";
467 bool needs_redraw = !IsActionVisibleOnMainBar(controller);
468 popped_out_action_ = controller;
469 if (needs_redraw) {
470 // We suppress animation for this draw, because we need the action to get
471 // into position immediately, since it's about to show its popup.
472 base::AutoReset<bool> layout_resetter(&suppress_animation_, false);
473 delegate_->Redraw(true);
476 ResizeDelegate(gfx::Tween::LINEAR, false);
477 if (!delegate_->IsAnimating()) {
478 // Don't call the closure re-entrantly.
479 base::ThreadTaskRunnerHandle::Get()->PostTask(FROM_HERE, closure);
480 } else {
481 popped_out_closure_ = closure;
485 void ToolbarActionsBar::UndoPopOut() {
486 DCHECK(!in_overflow_mode()) << "Only the main bar can pop out actions.";
487 DCHECK(popped_out_action_);
488 ToolbarActionViewController* controller = popped_out_action_;
489 popped_out_action_ = nullptr;
490 popped_out_closure_.Reset();
491 if (!IsActionVisibleOnMainBar(controller))
492 delegate_->Redraw(true);
493 ResizeDelegate(gfx::Tween::LINEAR, false);
496 void ToolbarActionsBar::SetPopupOwner(
497 ToolbarActionViewController* popup_owner) {
498 // We should never be setting a popup owner when one already exists, and
499 // never unsetting one when one wasn't set.
500 DCHECK((!popup_owner_ && popup_owner) ||
501 (popup_owner_ && !popup_owner));
502 popup_owner_ = popup_owner;
505 void ToolbarActionsBar::HideActivePopup() {
506 if (popup_owner_)
507 popup_owner_->HidePopup();
508 DCHECK(!popup_owner_);
511 ToolbarActionViewController* ToolbarActionsBar::GetMainControllerForAction(
512 ToolbarActionViewController* action) {
513 return in_overflow_mode() ?
514 main_bar_->GetActionForId(action->GetId()) : action;
517 void ToolbarActionsBar::MaybeShowExtensionBubble(
518 scoped_ptr<extensions::ExtensionMessageBubbleController> controller) {
519 controller->HighlightExtensionsIfNecessary(); // Safe to call multiple times.
520 if (delegate_->IsAnimating()) {
521 // If the toolbar is animating, we can't effectively anchor the bubble,
522 // so wait until animation stops.
523 pending_extension_bubble_controller_ = controller.Pass();
524 } else {
525 const std::vector<std::string>& affected_extensions =
526 controller->GetExtensionIdList();
527 ToolbarActionViewController* anchor_action = nullptr;
528 for (const std::string& id : affected_extensions) {
529 anchor_action = GetActionForId(id);
530 if (anchor_action)
531 break;
533 delegate_->ShowExtensionMessageBubble(controller.Pass(), anchor_action);
537 void ToolbarActionsBar::OnToolbarActionAdded(const std::string& action_id,
538 int index) {
539 DCHECK(GetActionForId(action_id) == nullptr)
540 << "Asked to add a toolbar action view for an extension that already "
541 "exists";
543 // TODO(devlin): This is a minor layering violation and the model should pass
544 // in an action directly.
545 const extensions::Extension* extension =
546 extensions::ExtensionRegistry::Get(browser_->profile())
547 ->enabled_extensions()
548 .GetByID(action_id);
549 // Only extensions should be added after initialization.
550 DCHECK(extension);
552 toolbar_actions_.insert(
553 toolbar_actions_.begin() + index,
554 new ExtensionActionViewController(
555 extension,
556 browser_,
557 extensions::ExtensionActionManager::Get(browser_->profile())->
558 GetExtensionAction(*extension),
559 this));
561 delegate_->AddViewForAction(toolbar_actions_[index], index);
563 // If we are still initializing the container, don't bother animating.
564 if (!model_->actions_initialized())
565 return;
567 // We may need to resize (e.g. to show the new icon, or the chevron). We don't
568 // need to check if the extension is upgrading here, because ResizeDelegate()
569 // checks to see if the container is already the proper size, and because
570 // if the action is newly incognito enabled, even though it's a reload, it's
571 // a new extension to this toolbar.
572 // We suppress the chevron during animation because, if we're expanding to
573 // show a new icon, we don't want to have the chevron visible only for the
574 // duration of the animation.
575 ResizeDelegate(gfx::Tween::LINEAR, true);
578 void ToolbarActionsBar::OnToolbarActionRemoved(const std::string& action_id) {
579 ToolbarActions::iterator iter = toolbar_actions_.begin();
580 while (iter != toolbar_actions_.end() && (*iter)->GetId() != action_id)
581 ++iter;
583 if (iter == toolbar_actions_.end())
584 return;
586 // The action should outlive the UI element (which is owned by the delegate),
587 // so we can't delete it just yet. But we should remove it from the list of
588 // actions so that any width calculations are correct.
589 scoped_ptr<ToolbarActionViewController> removed_action(*iter);
590 toolbar_actions_.weak_erase(iter);
591 delegate_->RemoveViewForAction(removed_action.get());
592 removed_action.reset();
594 // If the extension is being upgraded we don't want the bar to shrink
595 // because the icon is just going to get re-added to the same location.
596 // There is an exception if this is an off-the-record profile, and the
597 // extension is no longer incognito-enabled.
598 if (!extensions::ExtensionSystem::Get(browser_->profile())
599 ->runtime_data()
600 ->IsBeingUpgraded(action_id) ||
601 (browser_->profile()->IsOffTheRecord() &&
602 !extensions::util::IsIncognitoEnabled(action_id, browser_->profile()))) {
603 if (toolbar_actions_.size() > model_->visible_icon_count()) {
604 // If we have more icons than we can show, then we must not be changing
605 // the container size (since we either removed an icon from the main
606 // area and one from the overflow list will have shifted in, or we
607 // removed an entry directly from the overflow list).
608 delegate_->Redraw(false);
609 } else {
610 delegate_->SetChevronVisibility(false);
611 // Either we went from overflow to no-overflow, or we shrunk the no-
612 // overflow container by 1. Either way the size changed, so animate.
613 ResizeDelegate(gfx::Tween::EASE_OUT, false);
618 void ToolbarActionsBar::OnToolbarActionMoved(const std::string& action_id,
619 int index) {
620 DCHECK(index >= 0 && index < static_cast<int>(toolbar_actions_.size()));
621 // Unfortunately, |index| doesn't really mean a lot to us, because this
622 // window's toolbar could be different (if actions are popped out). Just
623 // do a full reorder.
624 ReorderActions();
627 void ToolbarActionsBar::OnToolbarActionUpdated(const std::string& action_id) {
628 ToolbarActionViewController* action = GetActionForId(action_id);
629 // There might not be a view in cases where we are highlighting or if we
630 // haven't fully initialized the actions.
631 if (action)
632 action->UpdateState();
635 void ToolbarActionsBar::OnToolbarVisibleCountChanged() {
636 ResizeDelegate(gfx::Tween::EASE_OUT, false);
639 void ToolbarActionsBar::ResizeDelegate(gfx::Tween::Type tween_type,
640 bool suppress_chevron) {
641 int desired_width = GetPreferredSize().width();
642 if (desired_width != delegate_->GetWidth()) {
643 delegate_->ResizeAndAnimate(tween_type, desired_width, suppress_chevron);
644 } else if (delegate_->IsAnimating()) {
645 // It's possible that we're right where we're supposed to be in terms of
646 // width, but that we're also currently resizing. If this is the case, end
647 // the current animation with the current width.
648 delegate_->StopAnimating();
649 } else {
650 // We may already be at the right size (this can happen frequently with
651 // overflow, where we have a fixed width, and in tests, where we skip
652 // animations). If this is the case, we still need to Redraw(), because the
653 // icons within the toolbar may have changed (e.g. if we removed one
654 // action and added a different one in quick succession).
655 delegate_->Redraw(false);
659 void ToolbarActionsBar::OnToolbarHighlightModeChanged(bool is_highlighting) {
660 if (!model_->actions_initialized())
661 return;
662 // It's a bit of a pain that we delete and recreate everything here, but given
663 // everything else going on (the lack of highlight, [n] more extensions
664 // appearing, etc), it's not worth the extra complexity to create and insert
665 // only the new actions.
666 DeleteActions();
667 CreateActions();
668 // Resize the delegate. We suppress the chevron so that we don't risk showing
669 // it only for the duration of the animation.
670 ResizeDelegate(gfx::Tween::LINEAR, true);
673 void ToolbarActionsBar::OnToolbarModelInitialized() {
674 // We shouldn't have any actions before the model is initialized.
675 DCHECK(toolbar_actions_.empty());
676 CreateActions();
678 // TODO(robliao): Remove ScopedTracker below once https://crbug.com/463337 is
679 // fixed.
680 tracked_objects::ScopedTracker tracking_profile(
681 FROM_HERE_WITH_EXPLICIT_FUNCTION(
682 "ToolbarActionsBar::OnToolbarModelInitialized"));
683 ResizeDelegate(gfx::Tween::EASE_OUT, false);
686 void ToolbarActionsBar::ReorderActions() {
687 if (toolbar_actions_.empty())
688 return;
690 // First, reset the order to that of the model.
691 auto compare = [](ToolbarActionViewController* const& action,
692 const ToolbarActionsModel::ToolbarItem& item) {
693 return action->GetId() == item.id;
695 SortContainer(&toolbar_actions_.get(), model_->toolbar_items(), compare);
697 // Our visible browser actions may have changed - re-Layout() and check the
698 // size (if we aren't suppressing the layout).
699 if (!suppress_layout_) {
700 ResizeDelegate(gfx::Tween::EASE_OUT, false);
701 delegate_->Redraw(true);
705 ToolbarActionViewController* ToolbarActionsBar::GetActionForId(
706 const std::string& action_id) {
707 for (ToolbarActionViewController* action : toolbar_actions_) {
708 if (action->GetId() == action_id)
709 return action;
711 return nullptr;
714 content::WebContents* ToolbarActionsBar::GetCurrentWebContents() {
715 return browser_->tab_strip_model()->GetActiveWebContents();