Add ability to gather metrics to BubbleManager.
[chromium-blink-merge.git] / chrome / browser / ui / toolbar / back_forward_menu_model.cc
blob15d58e7e35532c9a6b5ce2bab6d70e1719ccb069
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.
5 #include "chrome/browser/ui/toolbar/back_forward_menu_model.h"
7 #include "base/bind.h"
8 #include "base/bind_helpers.h"
9 #include "base/prefs/pref_service.h"
10 #include "base/strings/string_number_conversions.h"
11 #include "build/build_config.h"
12 #include "chrome/browser/favicon/favicon_service_factory.h"
13 #include "chrome/browser/profiles/profile.h"
14 #include "chrome/browser/ui/browser.h"
15 #include "chrome/browser/ui/browser_commands.h"
16 #include "chrome/browser/ui/singleton_tabs.h"
17 #include "chrome/browser/ui/tabs/tab_strip_model.h"
18 #include "chrome/common/pref_names.h"
19 #include "chrome/common/url_constants.h"
20 #include "chrome/grit/generated_resources.h"
21 #include "components/favicon_base/favicon_types.h"
22 #include "content/public/browser/favicon_status.h"
23 #include "content/public/browser/navigation_controller.h"
24 #include "content/public/browser/navigation_entry.h"
25 #include "content/public/browser/user_metrics.h"
26 #include "content/public/browser/web_contents.h"
27 #include "grit/theme_resources.h"
28 #include "net/base/registry_controlled_domains/registry_controlled_domain.h"
29 #include "ui/base/l10n/l10n_util.h"
30 #include "ui/base/resource/resource_bundle.h"
31 #include "ui/base/window_open_disposition.h"
32 #include "ui/gfx/text_elider.h"
34 using base::UserMetricsAction;
35 using content::NavigationController;
36 using content::NavigationEntry;
37 using content::WebContents;
39 const int BackForwardMenuModel::kMaxHistoryItems = 12;
40 const int BackForwardMenuModel::kMaxChapterStops = 5;
41 static const int kMaxWidth = 700;
43 BackForwardMenuModel::BackForwardMenuModel(Browser* browser,
44 ModelType model_type)
45 : browser_(browser),
46 test_web_contents_(NULL),
47 model_type_(model_type),
48 menu_model_delegate_(NULL) {
51 BackForwardMenuModel::~BackForwardMenuModel() {
54 bool BackForwardMenuModel::HasIcons() const {
55 return true;
58 int BackForwardMenuModel::GetItemCount() const {
59 int items = GetHistoryItemCount();
61 if (items > 0) {
62 int chapter_stops = 0;
64 // Next, we count ChapterStops, if any.
65 if (items == kMaxHistoryItems)
66 chapter_stops = GetChapterStopCount(items);
68 if (chapter_stops)
69 items += chapter_stops + 1; // Chapter stops also need a separator.
71 // If the menu is not empty, add two positions in the end
72 // for a separator and a "Show Full History" item.
73 items += 2;
76 return items;
79 ui::MenuModel::ItemType BackForwardMenuModel::GetTypeAt(int index) const {
80 return IsSeparator(index) ? TYPE_SEPARATOR : TYPE_COMMAND;
83 ui::MenuSeparatorType BackForwardMenuModel::GetSeparatorTypeAt(
84 int index) const {
85 return ui::NORMAL_SEPARATOR;
88 int BackForwardMenuModel::GetCommandIdAt(int index) const {
89 return index;
92 base::string16 BackForwardMenuModel::GetLabelAt(int index) const {
93 // Return label "Show Full History" for the last item of the menu.
94 if (index == GetItemCount() - 1)
95 return l10n_util::GetStringUTF16(IDS_SHOWFULLHISTORY_LINK);
97 // Return an empty string for a separator.
98 if (IsSeparator(index))
99 return base::string16();
101 // Return the entry title, escaping any '&' characters and eliding it if it's
102 // super long.
103 NavigationEntry* entry = GetNavigationEntry(index);
104 Profile* profile =
105 Profile::FromBrowserContext(GetWebContents()->GetBrowserContext());
106 base::string16 menu_text(entry->GetTitleForDisplay(
107 profile->GetPrefs()->GetString(prefs::kAcceptLanguages)));
108 menu_text =
109 gfx::ElideText(menu_text, gfx::FontList(), kMaxWidth, gfx::ELIDE_TAIL);
111 #if !defined(OS_MACOSX)
112 for (size_t i = menu_text.find('&'); i != base::string16::npos;
113 i = menu_text.find('&', i + 2)) {
114 menu_text.insert(i, 1, '&');
116 #endif
118 return menu_text;
121 bool BackForwardMenuModel::IsItemDynamicAt(int index) const {
122 // This object is only used for a single showing of a menu.
123 return false;
126 bool BackForwardMenuModel::GetAcceleratorAt(
127 int index,
128 ui::Accelerator* accelerator) const {
129 return false;
132 bool BackForwardMenuModel::IsItemCheckedAt(int index) const {
133 return false;
136 int BackForwardMenuModel::GetGroupIdAt(int index) const {
137 return false;
140 bool BackForwardMenuModel::GetIconAt(int index, gfx::Image* icon) {
141 if (!ItemHasIcon(index))
142 return false;
144 if (index == GetItemCount() - 1) {
145 *icon = ResourceBundle::GetSharedInstance().GetNativeImageNamed(
146 IDR_HISTORY_FAVICON);
147 } else {
148 NavigationEntry* entry = GetNavigationEntry(index);
149 *icon = entry->GetFavicon().image;
150 if (!entry->GetFavicon().valid && menu_model_delegate()) {
151 FetchFavicon(entry);
155 return true;
158 ui::ButtonMenuItemModel* BackForwardMenuModel::GetButtonMenuItemAt(
159 int index) const {
160 return NULL;
163 bool BackForwardMenuModel::IsEnabledAt(int index) const {
164 return index < GetItemCount() && !IsSeparator(index);
167 ui::MenuModel* BackForwardMenuModel::GetSubmenuModelAt(int index) const {
168 return NULL;
171 void BackForwardMenuModel::HighlightChangedTo(int index) {
174 void BackForwardMenuModel::ActivatedAt(int index) {
175 ActivatedAt(index, 0);
178 void BackForwardMenuModel::ActivatedAt(int index, int event_flags) {
179 DCHECK(!IsSeparator(index));
181 // Execute the command for the last item: "Show Full History".
182 if (index == GetItemCount() - 1) {
183 content::RecordComputedAction(BuildActionName("ShowFullHistory", -1));
184 chrome::ShowSingletonTabOverwritingNTP(browser_,
185 chrome::GetSingletonTabNavigateParams(
186 browser_, GURL(chrome::kChromeUIHistoryURL)));
187 return;
190 // Log whether it was a history or chapter click.
191 if (index < GetHistoryItemCount()) {
192 content::RecordComputedAction(
193 BuildActionName("HistoryClick", index));
194 } else {
195 content::RecordComputedAction(
196 BuildActionName("ChapterClick", index - GetHistoryItemCount() - 1));
199 int controller_index = MenuIndexToNavEntryIndex(index);
200 WindowOpenDisposition disposition =
201 ui::DispositionFromEventFlags(event_flags);
202 if (!chrome::NavigateToIndexWithDisposition(browser_,
203 controller_index,
204 disposition)) {
205 NOTREACHED();
209 void BackForwardMenuModel::MenuWillShow() {
210 content::RecordComputedAction(BuildActionName("Popup", -1));
211 requested_favicons_.clear();
212 cancelable_task_tracker_.TryCancelAll();
215 bool BackForwardMenuModel::IsSeparator(int index) const {
216 int history_items = GetHistoryItemCount();
217 // If the index is past the number of history items + separator,
218 // we then consider if it is a chapter-stop entry.
219 if (index > history_items) {
220 // We either are in ChapterStop area, or at the end of the list (the "Show
221 // Full History" link).
222 int chapter_stops = GetChapterStopCount(history_items);
223 if (chapter_stops == 0)
224 return false; // We must have reached the "Show Full History" link.
225 // Otherwise, look to see if we have reached the separator for the
226 // chapter-stops. If not, this is a chapter stop.
227 return (index == history_items + 1 + chapter_stops);
230 // Look to see if we have reached the separator for the history items.
231 return index == history_items;
234 void BackForwardMenuModel::SetMenuModelDelegate(
235 ui::MenuModelDelegate* menu_model_delegate) {
236 menu_model_delegate_ = menu_model_delegate;
239 ui::MenuModelDelegate* BackForwardMenuModel::GetMenuModelDelegate() const {
240 return menu_model_delegate_;
243 void BackForwardMenuModel::FetchFavicon(NavigationEntry* entry) {
244 // If the favicon has already been requested for this menu, don't do
245 // anything.
246 if (requested_favicons_.find(entry->GetUniqueID()) !=
247 requested_favicons_.end()) {
248 return;
250 requested_favicons_.insert(entry->GetUniqueID());
251 favicon::FaviconService* favicon_service =
252 FaviconServiceFactory::GetForProfile(browser_->profile(),
253 ServiceAccessType::EXPLICIT_ACCESS);
254 if (!favicon_service)
255 return;
257 favicon_service->GetFaviconImageForPageURL(
258 entry->GetURL(),
259 base::Bind(&BackForwardMenuModel::OnFavIconDataAvailable,
260 base::Unretained(this),
261 entry->GetUniqueID()),
262 &cancelable_task_tracker_);
265 void BackForwardMenuModel::OnFavIconDataAvailable(
266 int navigation_entry_unique_id,
267 const favicon_base::FaviconImageResult& image_result) {
268 if (!image_result.image.IsEmpty()) {
269 // Find the current model_index for the unique id.
270 NavigationEntry* entry = NULL;
271 int model_index = -1;
272 for (int i = 0; i < GetItemCount() - 1; i++) {
273 if (IsSeparator(i))
274 continue;
275 if (GetNavigationEntry(i)->GetUniqueID() == navigation_entry_unique_id) {
276 model_index = i;
277 entry = GetNavigationEntry(i);
278 break;
282 if (!entry)
283 // The NavigationEntry wasn't found, this can happen if the user
284 // navigates to another page and a NavigatationEntry falls out of the
285 // range of kMaxHistoryItems.
286 return;
288 // Now that we have a valid NavigationEntry, decode the favicon and assign
289 // it to the NavigationEntry.
290 entry->GetFavicon().valid = true;
291 entry->GetFavicon().url = image_result.icon_url;
292 entry->GetFavicon().image = image_result.image;
293 if (menu_model_delegate()) {
294 menu_model_delegate()->OnIconChanged(model_index);
299 int BackForwardMenuModel::GetHistoryItemCount() const {
300 WebContents* contents = GetWebContents();
301 int items = 0;
303 if (model_type_ == FORWARD_MENU) {
304 // Only count items from n+1 to end (if n is current entry)
305 items = contents->GetController().GetEntryCount() -
306 contents->GetController().GetCurrentEntryIndex() - 1;
307 } else {
308 items = contents->GetController().GetCurrentEntryIndex();
311 if (items > kMaxHistoryItems)
312 items = kMaxHistoryItems;
313 else if (items < 0)
314 items = 0;
316 return items;
319 int BackForwardMenuModel::GetChapterStopCount(int history_items) const {
320 WebContents* contents = GetWebContents();
322 int chapter_stops = 0;
323 int current_entry = contents->GetController().GetCurrentEntryIndex();
325 if (history_items == kMaxHistoryItems) {
326 int chapter_id = current_entry;
327 if (model_type_ == FORWARD_MENU) {
328 chapter_id += history_items;
329 } else {
330 chapter_id -= history_items;
333 do {
334 chapter_id = GetIndexOfNextChapterStop(chapter_id,
335 model_type_ == FORWARD_MENU);
336 if (chapter_id != -1)
337 ++chapter_stops;
338 } while (chapter_id != -1 && chapter_stops < kMaxChapterStops);
341 return chapter_stops;
344 int BackForwardMenuModel::GetIndexOfNextChapterStop(int start_from,
345 bool forward) const {
346 WebContents* contents = GetWebContents();
347 NavigationController& controller = contents->GetController();
349 int max_count = controller.GetEntryCount();
350 if (start_from < 0 || start_from >= max_count)
351 return -1; // Out of bounds.
353 if (forward) {
354 if (start_from < max_count - 1) {
355 // We want to advance over the current chapter stop, so we add one.
356 // We don't need to do this when direction is backwards.
357 start_from++;
358 } else {
359 return -1;
363 NavigationEntry* start_entry = controller.GetEntryAtIndex(start_from);
364 const GURL& url = start_entry->GetURL();
366 if (!forward) {
367 // When going backwards we return the first entry we find that has a
368 // different domain.
369 for (int i = start_from - 1; i >= 0; --i) {
370 if (!net::registry_controlled_domains::SameDomainOrHost(url,
371 controller.GetEntryAtIndex(i)->GetURL(),
372 net::registry_controlled_domains::EXCLUDE_PRIVATE_REGISTRIES))
373 return i;
375 // We have reached the beginning without finding a chapter stop.
376 return -1;
377 } else {
378 // When going forwards we return the entry before the entry that has a
379 // different domain.
380 for (int i = start_from + 1; i < max_count; ++i) {
381 if (!net::registry_controlled_domains::SameDomainOrHost(url,
382 controller.GetEntryAtIndex(i)->GetURL(),
383 net::registry_controlled_domains::EXCLUDE_PRIVATE_REGISTRIES))
384 return i - 1;
386 // Last entry is always considered a chapter stop.
387 return max_count - 1;
391 int BackForwardMenuModel::FindChapterStop(int offset,
392 bool forward,
393 int skip) const {
394 if (offset < 0 || skip < 0)
395 return -1;
397 if (!forward)
398 offset *= -1;
400 WebContents* contents = GetWebContents();
401 int entry = contents->GetController().GetCurrentEntryIndex() + offset;
402 for (int i = 0; i < skip + 1; i++)
403 entry = GetIndexOfNextChapterStop(entry, forward);
405 return entry;
408 bool BackForwardMenuModel::ItemHasCommand(int index) const {
409 return index < GetItemCount() && !IsSeparator(index);
412 bool BackForwardMenuModel::ItemHasIcon(int index) const {
413 return index < GetItemCount() && !IsSeparator(index);
416 base::string16 BackForwardMenuModel::GetShowFullHistoryLabel() const {
417 return l10n_util::GetStringUTF16(IDS_SHOWFULLHISTORY_LINK);
420 WebContents* BackForwardMenuModel::GetWebContents() const {
421 // We use the test web contents if the unit test has specified it.
422 return test_web_contents_ ?
423 test_web_contents_ :
424 browser_->tab_strip_model()->GetActiveWebContents();
427 int BackForwardMenuModel::MenuIndexToNavEntryIndex(int index) const {
428 WebContents* contents = GetWebContents();
429 int history_items = GetHistoryItemCount();
431 DCHECK_GE(index, 0);
433 // Convert anything above the History items separator.
434 if (index < history_items) {
435 if (model_type_ == FORWARD_MENU) {
436 index += contents->GetController().GetCurrentEntryIndex() + 1;
437 } else {
438 // Back menu is reverse.
439 index = contents->GetController().GetCurrentEntryIndex() - (index + 1);
441 return index;
443 if (index == history_items)
444 return -1; // Don't translate the separator for history items.
446 if (index >= history_items + 1 + GetChapterStopCount(history_items))
447 return -1; // This is beyond the last chapter stop so we abort.
449 // This menu item is a chapter stop located between the two separators.
450 index = FindChapterStop(history_items,
451 model_type_ == FORWARD_MENU,
452 index - history_items - 1);
454 return index;
457 NavigationEntry* BackForwardMenuModel::GetNavigationEntry(int index) const {
458 int controller_index = MenuIndexToNavEntryIndex(index);
459 NavigationController& controller = GetWebContents()->GetController();
460 if (controller_index >= 0 && controller_index < controller.GetEntryCount())
461 return controller.GetEntryAtIndex(controller_index);
463 NOTREACHED();
464 return NULL;
467 std::string BackForwardMenuModel::BuildActionName(
468 const std::string& action, int index) const {
469 DCHECK(!action.empty());
470 DCHECK(index >= -1);
471 std::string metric_string;
472 if (model_type_ == FORWARD_MENU)
473 metric_string += "ForwardMenu_";
474 else
475 metric_string += "BackMenu_";
476 metric_string += action;
477 if (index != -1) {
478 // +1 is for historical reasons (indices used to start at 1).
479 metric_string += base::IntToString(index + 1);
481 return metric_string;