Refactor: Makes menus use gfx::FontList instead of gfx::Font.
[chromium-blink-merge.git] / chrome / browser / ui / toolbar / recent_tabs_sub_menu_model.cc
blob57f589831ad32f6ca8b0893c3e060de5adfd5de4
1 // Copyright 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/recent_tabs_sub_menu_model.h"
7 #include "base/bind.h"
8 #include "base/metrics/histogram.h"
9 #include "base/prefs/scoped_user_pref_update.h"
10 #include "base/strings/string_number_conversions.h"
11 #include "base/strings/utf_string_conversions.h"
12 #include "chrome/app/chrome_command_ids.h"
13 #include "chrome/browser/favicon/favicon_service_factory.h"
14 #include "chrome/browser/profiles/profile.h"
15 #include "chrome/browser/search/search.h"
16 #include "chrome/browser/sessions/session_restore.h"
17 #include "chrome/browser/sessions/tab_restore_service.h"
18 #include "chrome/browser/sessions/tab_restore_service_delegate.h"
19 #include "chrome/browser/sessions/tab_restore_service_factory.h"
20 #include "chrome/browser/sync/glue/synced_session.h"
21 #include "chrome/browser/sync/open_tabs_ui_delegate.h"
22 #include "chrome/browser/sync/profile_sync_service.h"
23 #include "chrome/browser/sync/profile_sync_service_factory.h"
24 #include "chrome/browser/ui/browser.h"
25 #include "chrome/browser/ui/browser_commands.h"
26 #include "chrome/browser/ui/tabs/tab_strip_model.h"
27 #include "chrome/browser/ui/toolbar/wrench_menu_model.h"
28 #include "chrome/common/favicon/favicon_types.h"
29 #include "chrome/common/pref_names.h"
30 #include "grit/browser_resources.h"
31 #include "grit/generated_resources.h"
32 #include "grit/theme_resources.h"
33 #include "grit/ui_resources.h"
34 #include "ui/base/accelerators/accelerator.h"
35 #include "ui/base/l10n/l10n_util.h"
36 #include "ui/base/resource/resource_bundle.h"
37 #include "ui/gfx/favicon_size.h"
39 #if defined(USE_ASH)
40 #include "ash/accelerators/accelerator_table.h"
41 #endif // defined(USE_ASH)
43 namespace {
45 // Initial comamnd ID's for navigatable (and hence executable) tab/window menu
46 // items. The menumodel and storage structures are not 1-1:
47 // - menumodel has "Recently closed" header, "No tabs from other devices",
48 // device section headers, separators, local and other devices' tab items, and
49 // local window items.
50 // - |local_tab_navigation_items_| and |other_devices_tab_navigation_items_|
51 // only have navigatabale/executable tab items.
52 // - |local_window_items_| only has executable open window items.
53 // Using initial command IDs for local tab, local window and other devices' tab
54 // items makes it easier and less error-prone to manipulate the menumodel and
55 // storage structures. These ids must be bigger than the maximum possible
56 // number of items in the menumodel, so that index of the last menu item doesn't
57 // clash with these values when menu items are retrieved via
58 // GetIndexOfCommandId().
59 // The range of all command ID's used in RecentTabsSubMenuModel, including the
60 // "Recently closed" headers, must be between
61 // |WrenchMenuModel::kMinRecentTabsCommandId| i.e. 1001 and 1200
62 // (|WrenchMenuModel::kMaxRecentTabsCommandId|) inclusively.
63 const int kFirstLocalTabCommandId = WrenchMenuModel::kMinRecentTabsCommandId;
64 const int kFirstLocalWindowCommandId = 1031;
65 const int kFirstOtherDevicesTabCommandId = 1051;
66 const int kMinDeviceNameCommandId = 1100;
67 const int kMaxDeviceNameCommandId = 1110;
69 // The maximum number of local recently closed entries (tab or window) to be
70 // shown in the menu.
71 const int kMaxLocalEntries = 8;
73 // Comparator function for use with std::sort that will sort sessions by
74 // descending modified_time (i.e., most recent first).
75 bool SortSessionsByRecency(const browser_sync::SyncedSession* s1,
76 const browser_sync::SyncedSession* s2) {
77 return s1->modified_time > s2->modified_time;
80 // Comparator function for use with std::sort that will sort tabs by
81 // descending timestamp (i.e., most recent first).
82 bool SortTabsByRecency(const SessionTab* t1, const SessionTab* t2) {
83 return t1->timestamp > t2->timestamp;
86 // Returns true if the command id identifies a tab menu item.
87 bool IsTabModelCommandId(int command_id) {
88 return ((command_id >= kFirstLocalTabCommandId &&
89 command_id < kFirstLocalWindowCommandId) ||
90 (command_id >= kFirstOtherDevicesTabCommandId &&
91 command_id < kMinDeviceNameCommandId));
94 // Returns true if the command id identifies a window menu item.
95 bool IsWindowModelCommandId(int command_id) {
96 return command_id >= kFirstLocalWindowCommandId &&
97 command_id < kFirstOtherDevicesTabCommandId;
100 bool IsDeviceNameCommandId(int command_id) {
101 return command_id >= kMinDeviceNameCommandId &&
102 command_id <= kMaxDeviceNameCommandId;
105 // Convert |tab_vector_index| to command id of menu item, with
106 // |first_command_id| as the base command id.
107 int TabVectorIndexToCommandId(int tab_vector_index, int first_command_id) {
108 int command_id = tab_vector_index + first_command_id;
109 DCHECK(IsTabModelCommandId(command_id));
110 return command_id;
113 // Convert |window_vector_index| to command id of menu item.
114 int WindowVectorIndexToCommandId(int window_vector_index) {
115 int command_id = window_vector_index + kFirstLocalWindowCommandId;
116 DCHECK(IsWindowModelCommandId(command_id));
117 return command_id;
120 // Convert |command_id| of menu item to index in |local_window_items_|.
121 int CommandIdToWindowVectorIndex(int command_id) {
122 DCHECK(IsWindowModelCommandId(command_id));
123 return command_id - kFirstLocalWindowCommandId;
126 } // namespace
128 enum RecentTabAction {
129 LOCAL_SESSION_TAB = 0,
130 OTHER_DEVICE_TAB,
131 RESTORE_WINDOW,
132 SHOW_MORE,
133 LIMIT_RECENT_TAB_ACTION
136 // An element in |RecentTabsSubMenuModel::local_tab_navigation_items_| or
137 // |RecentTabsSubMenuModel::other_devices_tab_navigation_items_| that stores
138 // the navigation information of a local or other devices' tab required to
139 // restore the tab.
140 struct RecentTabsSubMenuModel::TabNavigationItem {
141 TabNavigationItem() : tab_id(-1) {}
143 TabNavigationItem(const std::string& session_tag,
144 const SessionID::id_type& tab_id,
145 const base::string16& title,
146 const GURL& url)
147 : session_tag(session_tag),
148 tab_id(tab_id),
149 title(title),
150 url(url) {}
152 // For use by std::set for sorting.
153 bool operator<(const TabNavigationItem& other) const {
154 return url < other.url;
157 // Empty for local tabs, non-empty for other devices' tabs.
158 std::string session_tag;
159 SessionID::id_type tab_id; // -1 for invalid, >= 0 otherwise.
160 base::string16 title;
161 GURL url;
164 const int RecentTabsSubMenuModel::kRecentlyClosedHeaderCommandId = 1120;
165 const int RecentTabsSubMenuModel::kDisabledRecentlyClosedHeaderCommandId = 1121;
167 RecentTabsSubMenuModel::RecentTabsSubMenuModel(
168 ui::AcceleratorProvider* accelerator_provider,
169 Browser* browser,
170 browser_sync::OpenTabsUIDelegate* open_tabs_delegate)
171 : ui::SimpleMenuModel(this),
172 browser_(browser),
173 open_tabs_delegate_(open_tabs_delegate),
174 last_local_model_index_(-1),
175 default_favicon_(ui::ResourceBundle::GetSharedInstance().
176 GetNativeImageNamed(IDR_DEFAULT_FAVICON)),
177 weak_ptr_factory_(this) {
178 // Invoke asynchronous call to load tabs from local last session, which does
179 // nothing if the tabs have already been loaded or they shouldn't be loaded.
180 // TabRestoreServiceChanged() will be called after the tabs are loaded.
181 TabRestoreService* service =
182 TabRestoreServiceFactory::GetForProfile(browser_->profile());
183 if (service) {
184 service->LoadTabsFromLastSession();
186 // TODO(sail): enable this when mac implements the dynamic menu, together with
187 // MenuModelDelegate::MenuStructureChanged().
188 #if !defined(OS_MACOSX)
189 service->AddObserver(this);
190 #endif
193 Build();
195 // Retrieve accelerator key for IDC_RESTORE_TAB now, because on ASH, it's not
196 // defined in |accelerator_provider|, but in shell, so simply retrieve it now
197 // for all ASH and non-ASH for use in |GetAcceleratorForCommandId|.
198 #if defined(USE_ASH)
199 for (size_t i = 0; i < ash::kAcceleratorDataLength; ++i) {
200 const ash::AcceleratorData& accel_data = ash::kAcceleratorData[i];
201 if (accel_data.action == ash::RESTORE_TAB) {
202 reopen_closed_tab_accelerator_ = ui::Accelerator(accel_data.keycode,
203 accel_data.modifiers);
204 break;
207 #else
208 if (accelerator_provider) {
209 accelerator_provider->GetAcceleratorForCommandId(
210 IDC_RESTORE_TAB, &reopen_closed_tab_accelerator_);
212 #endif // defined(USE_ASH)
215 RecentTabsSubMenuModel::~RecentTabsSubMenuModel() {
216 TabRestoreService* service =
217 TabRestoreServiceFactory::GetForProfile(browser_->profile());
218 if (service)
219 service->RemoveObserver(this);
222 bool RecentTabsSubMenuModel::IsCommandIdChecked(int command_id) const {
223 return false;
226 bool RecentTabsSubMenuModel::IsCommandIdEnabled(int command_id) const {
227 if (command_id == kRecentlyClosedHeaderCommandId ||
228 command_id == kDisabledRecentlyClosedHeaderCommandId ||
229 command_id == IDC_RECENT_TABS_NO_DEVICE_TABS ||
230 IsDeviceNameCommandId(command_id)) {
231 return false;
233 return true;
236 bool RecentTabsSubMenuModel::GetAcceleratorForCommandId(
237 int command_id, ui::Accelerator* accelerator) {
238 // If there are no recently closed items, we show the accelerator beside
239 // the header, otherwise, we show it beside the first item underneath it.
240 int index_in_menu = GetIndexOfCommandId(command_id);
241 int header_index = GetIndexOfCommandId(kRecentlyClosedHeaderCommandId);
242 if ((command_id == kDisabledRecentlyClosedHeaderCommandId ||
243 (header_index != -1 && index_in_menu == header_index + 1)) &&
244 reopen_closed_tab_accelerator_.key_code() != ui::VKEY_UNKNOWN) {
245 *accelerator = reopen_closed_tab_accelerator_;
246 return true;
248 return false;
251 void RecentTabsSubMenuModel::ExecuteCommand(int command_id, int event_flags) {
252 if (command_id == IDC_SHOW_HISTORY) {
253 UMA_HISTOGRAM_ENUMERATION("WrenchMenu.RecentTabsSubMenu", SHOW_MORE,
254 LIMIT_RECENT_TAB_ACTION);
255 // We show all "other devices" on the history page.
256 chrome::ExecuteCommandWithDisposition(browser_, IDC_SHOW_HISTORY,
257 ui::DispositionFromEventFlags(event_flags));
258 return;
261 DCHECK_NE(IDC_RECENT_TABS_NO_DEVICE_TABS, command_id);
262 DCHECK(!IsDeviceNameCommandId(command_id));
264 WindowOpenDisposition disposition =
265 ui::DispositionFromEventFlags(event_flags);
266 if (disposition == CURRENT_TAB) // Force to open a new foreground tab.
267 disposition = NEW_FOREGROUND_TAB;
269 TabRestoreService* service =
270 TabRestoreServiceFactory::GetForProfile(browser_->profile());
271 TabRestoreServiceDelegate* delegate =
272 TabRestoreServiceDelegate::FindDelegateForWebContents(
273 browser_->tab_strip_model()->GetActiveWebContents());
274 if (IsTabModelCommandId(command_id)) {
275 TabNavigationItems* tab_items = NULL;
276 int tab_items_idx = CommandIdToTabVectorIndex(command_id, &tab_items);
277 const TabNavigationItem& item = (*tab_items)[tab_items_idx];
278 DCHECK(item.tab_id > -1 && item.url.is_valid());
280 if (item.session_tag.empty()) { // Restore tab of local session.
281 if (service && delegate) {
282 UMA_HISTOGRAM_ENUMERATION("WrenchMenu.RecentTabsSubMenu",
283 LOCAL_SESSION_TAB, LIMIT_RECENT_TAB_ACTION);
284 service->RestoreEntryById(delegate, item.tab_id,
285 browser_->host_desktop_type(), disposition);
287 } else { // Restore tab of session from other devices.
288 browser_sync::OpenTabsUIDelegate* open_tabs = GetOpenTabsUIDelegate();
289 if (!open_tabs)
290 return;
291 const SessionTab* tab;
292 if (!open_tabs->GetForeignTab(item.session_tag, item.tab_id, &tab))
293 return;
294 if (tab->navigations.empty())
295 return;
296 UMA_HISTOGRAM_ENUMERATION("WrenchMenu.RecentTabsSubMenu",
297 OTHER_DEVICE_TAB, LIMIT_RECENT_TAB_ACTION);
298 SessionRestore::RestoreForeignSessionTab(
299 browser_->tab_strip_model()->GetActiveWebContents(),
300 *tab, disposition);
302 } else {
303 DCHECK(IsWindowModelCommandId(command_id));
304 if (service && delegate) {
305 int window_items_idx = CommandIdToWindowVectorIndex(command_id);
306 DCHECK(window_items_idx >= 0 &&
307 window_items_idx < static_cast<int>(local_window_items_.size()));
308 UMA_HISTOGRAM_ENUMERATION("WrenchMenu.RecentTabsSubMenu", RESTORE_WINDOW,
309 LIMIT_RECENT_TAB_ACTION);
310 service->RestoreEntryById(delegate, local_window_items_[window_items_idx],
311 browser_->host_desktop_type(), disposition);
316 const gfx::FontList* RecentTabsSubMenuModel::GetLabelFontListAt(
317 int index) const {
318 int command_id = GetCommandIdAt(index);
319 if (command_id == kRecentlyClosedHeaderCommandId ||
320 IsDeviceNameCommandId(command_id)) {
321 return &ui::ResourceBundle::GetSharedInstance().GetFontList(
322 ui::ResourceBundle::BoldFont);
324 return NULL;
327 int RecentTabsSubMenuModel::GetMaxWidthForItemAtIndex(int item_index) const {
328 int command_id = GetCommandIdAt(item_index);
329 if (command_id == IDC_RECENT_TABS_NO_DEVICE_TABS ||
330 command_id == kRecentlyClosedHeaderCommandId ||
331 command_id == kDisabledRecentlyClosedHeaderCommandId) {
332 return -1;
334 return 320;
337 bool RecentTabsSubMenuModel::GetURLAndTitleForItemAtIndex(
338 int index,
339 std::string* url,
340 base::string16* title) {
341 int command_id = GetCommandIdAt(index);
342 if (IsTabModelCommandId(command_id)) {
343 TabNavigationItems* tab_items = NULL;
344 int tab_items_idx = CommandIdToTabVectorIndex(command_id, &tab_items);
345 const TabNavigationItem& item = (*tab_items)[tab_items_idx];
346 *url = item.url.possibly_invalid_spec();
347 *title = item.title;
348 return true;
350 return false;
353 void RecentTabsSubMenuModel::Build() {
354 // The menu contains:
355 // - Recently closed header, then list of local recently closed tabs/windows,
356 // then separator
357 // - device 1 section header, then list of tabs from device, then separator
358 // - device 2 section header, then list of tabs from device, then separator
359 // - device 3 section header, then list of tabs from device, then separator
360 // - More... to open the history tab to get more other devices.
361 // |local_tab_navigation_items_| and |other_devices_tab_navigation_items_|
362 // only contain navigatable (and hence executable) tab items for local
363 // recently closed tabs and tabs from other devices respectively.
364 // |local_window_items_| contains the local recently closed windows.
365 BuildLocalEntries();
366 BuildTabsFromOtherDevices();
369 void RecentTabsSubMenuModel::BuildLocalEntries() {
370 // All local items use InsertItem*At() to append or insert a menu item.
371 // We're appending if building the entries for the first time i.e. invoked
372 // from Constructor(), inserting when local entries change subsequently i.e.
373 // invoked from TabRestoreServiceChanged().
375 DCHECK_EQ(last_local_model_index_, -1);
377 TabRestoreService* service =
378 TabRestoreServiceFactory::GetForProfile(browser_->profile());
379 if (!service || service->entries().size() == 0) {
380 // This is to show a disabled restore tab entry with the accelerator to
381 // teach users about this command.
382 InsertItemWithStringIdAt(++last_local_model_index_,
383 kDisabledRecentlyClosedHeaderCommandId,
384 IDS_NEW_TAB_RECENTLY_CLOSED);
385 } else {
386 InsertItemWithStringIdAt(++last_local_model_index_,
387 kRecentlyClosedHeaderCommandId,
388 IDS_NEW_TAB_RECENTLY_CLOSED);
389 ui::ResourceBundle& rb = ui::ResourceBundle::GetSharedInstance();
390 SetIcon(last_local_model_index_,
391 rb.GetNativeImageNamed(IDR_RECENTLY_CLOSED_WINDOW));
393 int added_count = 0;
394 TabRestoreService::Entries entries = service->entries();
395 for (TabRestoreService::Entries::const_iterator it = entries.begin();
396 it != entries.end() && added_count < kMaxLocalEntries; ++it) {
397 TabRestoreService::Entry* entry = *it;
398 if (entry->type == TabRestoreService::TAB) {
399 TabRestoreService::Tab* tab =
400 static_cast<TabRestoreService::Tab*>(entry);
401 const sessions::SerializedNavigationEntry& current_navigation =
402 tab->navigations.at(tab->current_navigation_index);
403 BuildLocalTabItem(
404 entry->id,
405 current_navigation.title(),
406 current_navigation.virtual_url(),
407 ++last_local_model_index_);
408 } else {
409 DCHECK_EQ(entry->type, TabRestoreService::WINDOW);
410 BuildLocalWindowItem(
411 entry->id,
412 static_cast<TabRestoreService::Window*>(entry)->tabs.size(),
413 ++last_local_model_index_);
415 ++added_count;
419 DCHECK_GE(last_local_model_index_, 0);
422 void RecentTabsSubMenuModel::BuildTabsFromOtherDevices() {
423 // All other devices' items (device headers or tabs) use AddItem*() to append
424 // a menu item, because they are always only built once (i.e. invoked from
425 // Constructor()) and don't change after that.
427 browser_sync::OpenTabsUIDelegate* open_tabs = GetOpenTabsUIDelegate();
428 std::vector<const browser_sync::SyncedSession*> sessions;
429 if (!open_tabs || !open_tabs->GetAllForeignSessions(&sessions)) {
430 AddSeparator(ui::NORMAL_SEPARATOR);
431 AddItemWithStringId(IDC_RECENT_TABS_NO_DEVICE_TABS,
432 IDS_RECENT_TABS_NO_DEVICE_TABS);
433 return;
436 // Sort sessions from most recent to least recent.
437 std::sort(sessions.begin(), sessions.end(), SortSessionsByRecency);
439 const size_t kMaxSessionsToShow = 3;
440 size_t num_sessions_added = 0;
441 for (size_t i = 0;
442 i < sessions.size() && num_sessions_added < kMaxSessionsToShow; ++i) {
443 const browser_sync::SyncedSession* session = sessions[i];
444 const std::string& session_tag = session->session_tag;
446 // Get windows of session.
447 std::vector<const SessionWindow*> windows;
448 if (!open_tabs->GetForeignSession(session_tag, &windows) ||
449 windows.empty()) {
450 continue;
453 // Collect tabs from all windows of session, pruning those that are not
454 // syncable or are NewTabPage, then sort them from most recent to least
455 // recent, independent of which window the tabs were from.
456 std::vector<const SessionTab*> tabs_in_session;
457 for (size_t j = 0; j < windows.size(); ++j) {
458 const SessionWindow* window = windows[j];
459 for (size_t t = 0; t < window->tabs.size(); ++t) {
460 const SessionTab* tab = window->tabs[t];
461 if (tab->navigations.empty())
462 continue;
463 const sessions::SerializedNavigationEntry& current_navigation =
464 tab->navigations.at(tab->normalized_navigation_index());
465 if (chrome::IsNTPURL(current_navigation.virtual_url(),
466 browser_->profile())) {
467 continue;
469 tabs_in_session.push_back(tab);
472 if (tabs_in_session.empty())
473 continue;
474 std::sort(tabs_in_session.begin(), tabs_in_session.end(),
475 SortTabsByRecency);
477 // Add the header for the device session.
478 DCHECK(!session->session_name.empty());
479 AddSeparator(ui::NORMAL_SEPARATOR);
480 int command_id = kMinDeviceNameCommandId + i;
481 DCHECK_LE(command_id, kMaxDeviceNameCommandId);
482 AddItem(command_id, base::UTF8ToUTF16(session->session_name));
483 AddDeviceFavicon(GetItemCount() - 1, session->device_type);
485 // Build tab menu items from sorted session tabs.
486 const size_t kMaxTabsPerSessionToShow = 4;
487 for (size_t k = 0;
488 k < std::min(tabs_in_session.size(), kMaxTabsPerSessionToShow);
489 ++k) {
490 BuildOtherDevicesTabItem(session_tag, *tabs_in_session[k]);
491 } // for all tabs in one session
493 ++num_sessions_added;
494 } // for all sessions
496 // We are not supposed to get here unless at least some items were added.
497 DCHECK_GT(GetItemCount(), 0);
498 AddSeparator(ui::NORMAL_SEPARATOR);
499 AddItemWithStringId(IDC_SHOW_HISTORY, IDS_RECENT_TABS_MORE);
502 void RecentTabsSubMenuModel::BuildLocalTabItem(int session_id,
503 const base::string16& title,
504 const GURL& url,
505 int curr_model_index) {
506 TabNavigationItem item(std::string(), session_id, title, url);
507 int command_id = TabVectorIndexToCommandId(
508 local_tab_navigation_items_.size(), kFirstLocalTabCommandId);
509 // See comments in BuildLocalEntries() about usage of InsertItem*At().
510 // There may be no tab title, in which case, use the url as tab title.
511 InsertItemAt(curr_model_index, command_id,
512 title.empty() ? base::UTF8ToUTF16(item.url.spec()) : title);
513 AddTabFavicon(command_id, item.url);
514 local_tab_navigation_items_.push_back(item);
517 void RecentTabsSubMenuModel::BuildLocalWindowItem(
518 const SessionID::id_type& window_id,
519 int num_tabs,
520 int curr_model_index) {
521 int command_id = WindowVectorIndexToCommandId(local_window_items_.size());
522 // See comments in BuildLocalEntries() about usage of InsertItem*At().
523 if (num_tabs == 1) {
524 InsertItemWithStringIdAt(curr_model_index, command_id,
525 IDS_NEW_TAB_RECENTLY_CLOSED_WINDOW_SINGLE);
526 } else {
527 InsertItemAt(curr_model_index, command_id, l10n_util::GetStringFUTF16(
528 IDS_NEW_TAB_RECENTLY_CLOSED_WINDOW_MULTIPLE,
529 base::IntToString16(num_tabs)));
531 ui::ResourceBundle& rb = ui::ResourceBundle::GetSharedInstance();
532 SetIcon(curr_model_index, rb.GetNativeImageNamed(IDR_RECENTLY_CLOSED_WINDOW));
533 local_window_items_.push_back(window_id);
536 void RecentTabsSubMenuModel::BuildOtherDevicesTabItem(
537 const std::string& session_tag,
538 const SessionTab& tab) {
539 const sessions::SerializedNavigationEntry& current_navigation =
540 tab.navigations.at(tab.normalized_navigation_index());
541 TabNavigationItem item(session_tag, tab.tab_id.id(),
542 current_navigation.title(),
543 current_navigation.virtual_url());
544 int command_id = TabVectorIndexToCommandId(
545 other_devices_tab_navigation_items_.size(),
546 kFirstOtherDevicesTabCommandId);
547 // See comments in BuildTabsFromOtherDevices() about usage of AddItem*().
548 // There may be no tab title, in which case, use the url as tab title.
549 AddItem(command_id,
550 current_navigation.title().empty() ?
551 base::UTF8ToUTF16(item.url.spec()) : current_navigation.title());
552 AddTabFavicon(command_id, item.url);
553 other_devices_tab_navigation_items_.push_back(item);
556 void RecentTabsSubMenuModel::AddDeviceFavicon(
557 int index_in_menu,
558 browser_sync::SyncedSession::DeviceType device_type) {
559 int favicon_id = -1;
560 switch (device_type) {
561 case browser_sync::SyncedSession::TYPE_PHONE:
562 favicon_id = IDR_PHONE_FAVICON;
563 break;
565 case browser_sync::SyncedSession::TYPE_TABLET:
566 favicon_id = IDR_TABLET_FAVICON;
567 break;
569 case browser_sync::SyncedSession::TYPE_CHROMEOS:
570 case browser_sync::SyncedSession::TYPE_WIN:
571 case browser_sync::SyncedSession::TYPE_MACOSX:
572 case browser_sync::SyncedSession::TYPE_LINUX:
573 case browser_sync::SyncedSession::TYPE_OTHER:
574 case browser_sync::SyncedSession::TYPE_UNSET:
575 favicon_id = IDR_LAPTOP_FAVICON;
576 break;
579 ui::ResourceBundle& rb = ui::ResourceBundle::GetSharedInstance();
580 SetIcon(index_in_menu, rb.GetNativeImageNamed(favicon_id));
583 void RecentTabsSubMenuModel::AddTabFavicon(int command_id, const GURL& url) {
584 bool is_local_tab = command_id < kFirstOtherDevicesTabCommandId;
585 int index_in_menu = GetIndexOfCommandId(command_id);
587 if (!is_local_tab) {
588 // If tab has synced favicon, use it.
589 // Note that currently, other devices' tabs only have favicons if
590 // --sync-tab-favicons switch is on; according to zea@, this flag is now
591 // automatically enabled for iOS and android, and they're looking into
592 // enabling it for other platforms.
593 browser_sync::OpenTabsUIDelegate* open_tabs = GetOpenTabsUIDelegate();
594 scoped_refptr<base::RefCountedMemory> favicon_png;
595 if (open_tabs &&
596 open_tabs->GetSyncedFaviconForPageURL(url.spec(), &favicon_png)) {
597 gfx::Image image = gfx::Image::CreateFrom1xPNGBytes(favicon_png);
598 SetIcon(index_in_menu, image);
599 return;
603 // Otherwise, start to fetch the favicon from local history asynchronously.
604 // Set default icon first.
605 SetIcon(index_in_menu, default_favicon_);
606 // Start request to fetch actual icon if possible.
607 FaviconService* favicon_service = FaviconServiceFactory::GetForProfile(
608 browser_->profile(), Profile::EXPLICIT_ACCESS);
609 if (!favicon_service)
610 return;
612 favicon_service->GetFaviconImageForURL(
613 FaviconService::FaviconForURLParams(url,
614 chrome::FAVICON,
615 gfx::kFaviconSize),
616 base::Bind(&RecentTabsSubMenuModel::OnFaviconDataAvailable,
617 weak_ptr_factory_.GetWeakPtr(),
618 command_id),
619 is_local_tab ? &local_tab_cancelable_task_tracker_ :
620 &other_devices_tab_cancelable_task_tracker_);
623 void RecentTabsSubMenuModel::OnFaviconDataAvailable(
624 int command_id,
625 const chrome::FaviconImageResult& image_result) {
626 if (image_result.image.IsEmpty())
627 return;
628 int index_in_menu = GetIndexOfCommandId(command_id);
629 DCHECK_GT(index_in_menu, -1);
630 SetIcon(index_in_menu, image_result.image);
631 ui::MenuModelDelegate* menu_model_delegate = GetMenuModelDelegate();
632 if (menu_model_delegate)
633 menu_model_delegate->OnIconChanged(index_in_menu);
636 int RecentTabsSubMenuModel::CommandIdToTabVectorIndex(
637 int command_id,
638 TabNavigationItems** tab_items) {
639 DCHECK(IsTabModelCommandId(command_id));
640 if (command_id >= kFirstOtherDevicesTabCommandId) {
641 *tab_items = &other_devices_tab_navigation_items_;
642 return command_id - kFirstOtherDevicesTabCommandId;
644 *tab_items = &local_tab_navigation_items_;
645 return command_id - kFirstLocalTabCommandId;
648 void RecentTabsSubMenuModel::ClearLocalEntries() {
649 // Remove local items (recently closed tabs and windows) from menumodel.
650 while (last_local_model_index_ >= 0)
651 RemoveItemAt(last_local_model_index_--);
653 // Cancel asynchronous FaviconService::GetFaviconImageForURL() tasks of all
654 // local tabs.
655 local_tab_cancelable_task_tracker_.TryCancelAll();
657 // Remove all local tab navigation items.
658 local_tab_navigation_items_.clear();
660 // Remove all local window items.
661 local_window_items_.clear();
664 browser_sync::OpenTabsUIDelegate*
665 RecentTabsSubMenuModel::GetOpenTabsUIDelegate() {
666 if (!open_tabs_delegate_) {
667 ProfileSyncService* service = ProfileSyncServiceFactory::GetInstance()->
668 GetForProfile(browser_->profile());
669 // Only return the delegate if it exists and it is done syncing sessions.
670 if (service && service->ShouldPushChanges())
671 open_tabs_delegate_ = service->GetOpenTabsUIDelegate();
673 return open_tabs_delegate_;
676 void RecentTabsSubMenuModel::TabRestoreServiceChanged(
677 TabRestoreService* service) {
678 ClearLocalEntries();
680 BuildLocalEntries();
682 ui::MenuModelDelegate* menu_model_delegate = GetMenuModelDelegate();
683 if (menu_model_delegate)
684 menu_model_delegate->OnMenuStructureChanged();
687 void RecentTabsSubMenuModel::TabRestoreServiceDestroyed(
688 TabRestoreService* service) {
689 TabRestoreServiceChanged(service);