Chromium Code Reviews
chromiumcodereview-hr@appspot.gserviceaccount.com (chromiumcodereview-hr) | Please choose your nickname with Settings | Help | Chromium Project | Gerrit Changes | Sign out
(58)

Unified Diff: chrome/browser/ui/toolbar/recent_tabs_sub_menu_model.cc

Issue 11298004: alternate ntp: add "Recent Tabs" submenu to wrench menu (Closed) Base URL: svn://svn.chromium.org/chrome/trunk/src
Patch Set: fixed disposition, minor style cleanup Created 8 years, 1 month ago
Use n/p to move between diff chunks; N/P to move between comments. Draft comments are only viewable by you.
Jump to:
View side-by-side diff with in-line comments
Download patch
Index: chrome/browser/ui/toolbar/recent_tabs_sub_menu_model.cc
diff --git a/chrome/browser/ui/toolbar/recent_tabs_sub_menu_model.cc b/chrome/browser/ui/toolbar/recent_tabs_sub_menu_model.cc
new file mode 100644
index 0000000000000000000000000000000000000000..8fad7326453b1c18eedc947d0ba68c67a61304e5
--- /dev/null
+++ b/chrome/browser/ui/toolbar/recent_tabs_sub_menu_model.cc
@@ -0,0 +1,390 @@
+// Copyright 2012 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#include "chrome/browser/ui/toolbar/recent_tabs_sub_menu_model.h"
+
+#include "base/bind.h"
+#include "base/string_number_conversions.h"
+#include "base/utf_string_conversions.h"
+#include "chrome/app/chrome_command_ids.h"
+#include "chrome/browser/favicon/favicon_service_factory.h"
+#include "chrome/browser/prefs/scoped_user_pref_update.h"
+#include "chrome/browser/profiles/profile.h"
+#include "chrome/browser/sessions/session_restore.h"
+#include "chrome/browser/sessions/tab_restore_service_delegate.h"
+#include "chrome/browser/sessions/tab_restore_service_factory.h"
+#include "chrome/browser/sync/glue/session_model_associator.h"
+#include "chrome/browser/sync/glue/synced_session.h"
+#include "chrome/browser/sync/profile_sync_service.h"
+#include "chrome/browser/sync/profile_sync_service_factory.h"
+#include "chrome/browser/ui/browser.h"
+#include "chrome/browser/ui/browser_commands.h"
+#include "chrome/browser/ui/browser_tabstrip.h"
+#include "chrome/browser/ui/tabs/tab_strip_model.h"
+#include "chrome/common/pref_names.h"
+#include "chrome/common/time_format.h"
+#include "chrome/common/url_constants.h"
+#include "grit/generated_resources.h"
+#include "grit/ui_resources.h"
+#include "ui/base/accelerators/accelerator.h"
+#include "ui/base/l10n/l10n_util.h"
+#include "ui/base/resource/resource_bundle.h"
+#include "ui/base/text/text_elider.h"
+#include "ui/gfx/favicon_size.h"
+
+#if defined(USE_ASH)
+#include "ash/accelerators/accelerator_table.h"
+#endif // defined(USE_ASH)
+
+namespace {
+
+// Comparator function for use with std::sort that will sort sessions by
+// descending modified_time (i.e., most recent first).
+bool SortSessionsByRecency(const browser_sync::SyncedSession* s1,
+ const browser_sync::SyncedSession* s2) {
+ return s1->modified_time > s2->modified_time;
+}
+
+// Comparator function for use with std::sort that will sort tabs by
+// descending timestamp (i.e., most recent first).
+bool SortTabsByRecency(const SessionTab* t1, const SessionTab* t2) {
+ return t1->timestamp > t2->timestamp;
+}
+
+// Convert |model_index| into index in menu, since model and menu are not 1-1.
+int ModelIndexToMenuIndex(int model_index) {
+ // |RecentTabsSubMenuModel::model_| doesn't include IDC_RESTORE_TAB and the
+ // separator after.
+ const int kNumItemsNotInModel = 2;
+ // |model_index| indexes into |model_|, which doesn't include
+ // kNumItemsNotInModel, so add that to get index in menu.
+ return model_index + kNumItemsNotInModel;
+}
+
+} // namepace
+
+// An element in |RecentTabsSubMenuModel::model_| that stores the navigation
+// information of a local or foreign tab required to restore the tab.
+// Because |model_| maps to the actual menu items for easier and faster access,
+// it also stores device section headers and separators, which use -1 for tab_id
+// to indicate non-navigatable (and hence non-executable) items.
+struct RecentTabsSubMenuModel::NavigationItem {
+ NavigationItem() : tab_id(-1) {}
+
+ NavigationItem(const std::string& session_tag,
+ const SessionID::id_type& tab_id,
+ const GURL& url)
+ : session_tag(session_tag),
+ tab_id(tab_id),
+ url(url) {}
+
+ // For use by std::set for sorting.
+ bool operator<(const NavigationItem& other) const {
+ return url < other.url;
+ }
+
+ std::string session_tag; // Empty for local tabs, non-empty for foreign tabs.
+ SessionID::id_type tab_id; // -1 for invalid, >= 0 otherwise.
+ GURL url;
+};
+
+RecentTabsSubMenuModel::RecentTabsSubMenuModel(
+ ui::AcceleratorProvider* accelerator_provider,
+ Browser* browser)
+ : ALLOW_THIS_IN_INITIALIZER_LIST(ui::SimpleMenuModel(this)),
+ browser_(browser),
+ associator_(NULL),
+ default_favicon_(NULL),
+ ALLOW_THIS_IN_INITIALIZER_LIST(weak_ptr_factory_(this)) {
+ Build();
+
+ // Retrieve accelerator key for IDC_RESTORE_TAB now, because on ASH, it's not
+ // defined in |accelerator_provider|, but in shell, so simply retrieve it now
+ // for all ASH and non-ASH for use in |GetAcceleratorForCommandId|.
+#if defined(USE_ASH)
+ for (size_t i = 0; i < ash::kAcceleratorDataLength; ++i) {
+ const ash::AcceleratorData& accel_data = ash::kAcceleratorData[i];
+ if (accel_data.action == ash::RESTORE_TAB) {
+ reopen_closed_tab_accelerator_ = ui::Accelerator(accel_data.keycode,
+ accel_data.modifiers);
+ break;
+ }
+ }
+#else
+ accelerator_provider->GetAcceleratorForCommandId(
+ IDC_RESTORE_TAB, &reopen_closed_tab_accelerator_);
+#endif // defined(USE_ASH)
+}
+
+RecentTabsSubMenuModel::RecentTabsSubMenuModel(
+ ui::AcceleratorProvider* accelerator_provider,
+ Browser* browser,
+ browser_sync::SessionModelAssociator* associator,
+ bool setup_for_test)
+ : ALLOW_THIS_IN_INITIALIZER_LIST(ui::SimpleMenuModel(this)),
+ browser_(browser),
+ associator_(associator),
+ default_favicon_(NULL),
+ ALLOW_THIS_IN_INITIALIZER_LIST(weak_ptr_factory_(this)) {
+ DCHECK(associator_);
+ DCHECK(setup_for_test);
+ Build();
+}
+
+RecentTabsSubMenuModel::~RecentTabsSubMenuModel() {
+}
+
+bool RecentTabsSubMenuModel::IsCommandIdChecked(int command_id) const {
+ return false;
+}
+
+bool RecentTabsSubMenuModel::IsCommandIdEnabled(int command_id) const {
+ if (command_id == IDC_RESTORE_TAB)
+ return chrome::IsCommandEnabled(browser_, command_id);
+ // An empty |model_| means there's no menu item to enable.
+ if (model_.empty())
+ return false;
+ // If |command_id| is 0, it's a device section header to be disabled.
+ return command_id != 0;
+}
+
+bool RecentTabsSubMenuModel::GetAcceleratorForCommandId(
+ int command_id, ui::Accelerator* accelerator) {
+ if (command_id == IDC_RESTORE_TAB &&
+ reopen_closed_tab_accelerator_.key_code() != ui::VKEY_UNKNOWN) {
+ *accelerator = reopen_closed_tab_accelerator_;
+ return true;
+ }
+ return false;
+}
+
+bool RecentTabsSubMenuModel::IsItemForCommandIdDynamic(int command_id) const {
+ return command_id == IDC_RESTORE_TAB;
+}
+
+string16 RecentTabsSubMenuModel::GetLabelForCommandId(int command_id) const {
+ DCHECK_EQ(command_id, IDC_RESTORE_TAB);
+
+ int string_id = IDS_RESTORE_TAB;
+ if (IsCommandIdEnabled(command_id)) {
+ TabRestoreService* service =
+ TabRestoreServiceFactory::GetForProfile(browser_->profile());
+ if (service &&
sky 2012/11/09 18:13:05 Check the size here.
kuan 2012/11/09 20:27:52 size is checked in CanRestoreTab which is called f
+ service->entries().front()->type == TabRestoreService::WINDOW) {
+ string_id = IDS_RESTORE_WINDOW;
+ }
+ }
+ return l10n_util::GetStringUTF16(string_id);
+}
+
+void RecentTabsSubMenuModel::ExecuteCommand(int command_id) {
+ ExecuteCommand(command_id, 0);
+}
+
+void RecentTabsSubMenuModel::ExecuteCommand(int command_id, int event_flags) {
+ if (command_id == IDC_RESTORE_TAB) {
+ chrome::ExecuteCommandWithDisposition(browser_, command_id,
+ chrome::DispositionFromEventFlags(event_flags));
+ return;
+ }
+
+ // See IsCommandIdEnabled for explanation.
+ DCHECK(!model_.empty() && command_id > 0);
sky 2012/11/09 18:13:05 How about starting at a particular command id for
kuan 2012/11/09 20:27:52 Done.
+
+ DCHECK_LT(command_id, static_cast<int>(model_.size()));
+ const NavigationItem& item = model_[command_id];
+ DCHECK(item.tab_id > -1 && item.url.is_valid());
+
+ WindowOpenDisposition disposition =
+ chrome::DispositionFromEventFlags(event_flags);
+ if (disposition == CURRENT_TAB) // Force to open a new foreground tab.
+ disposition = NEW_FOREGROUND_TAB;
+
+ if (item.session_tag.empty()) { // Restore tab of local session.
+ TabRestoreService* service =
+ TabRestoreServiceFactory::GetForProfile(browser_->profile());
+ if (!service)
+ return;
+ TabRestoreServiceDelegate* delegate =
+ TabRestoreServiceDelegate::FindDelegateForWebContents(
+ chrome::GetActiveWebContents(browser_));
+ if (!delegate)
+ return;
+ service->RestoreEntryById(delegate, item.tab_id, disposition);
+ } else { // Restore tab of foreign session.
+ browser_sync::SessionModelAssociator* associator = GetModelAssociator();
+ if (!associator)
+ return;
+ const SessionTab* tab;
+ if (!associator->GetForeignTab(item.session_tag, item.tab_id, &tab))
+ return;
+ if (tab->navigations.empty())
+ return;
+ int prev_num_tabs = browser_->tab_strip_model()->count();
+ SessionRestore::RestoreForeignSessionTab(
+ chrome::GetActiveWebContents(browser_), *tab, disposition);
+ if (browser_->tab_strip_model()->count() == prev_num_tabs + 1)
+ chrome::ActivateTabAt(browser_, prev_num_tabs, true);
+ }
+}
+
+void RecentTabsSubMenuModel::Build() {
+ // The menu contains:
+ // - Reopen closed tab, then separator
+ // - device 1 section header, then list of tabs from device, then separator
+ // - device 2 section header, then list of tabs from device, then separator
+ // ...
+ // |model_| only contains items for other devices:
+ // - section header for device name (command_id = 0)
+ // - tabs from other devices (command_id = index into |model_|, which will
+ // never be 0 since there would be always be a section header)
+ // - separator that separates tabs of each device (comand id = -1)
+ BuildLastClosed();
+ BuildDevices();
+ if (model_.empty())
+ AddItemWithStringId(0, IDS_RECENT_TABS_NO_DEVICE_TABS);
+}
+
+void RecentTabsSubMenuModel::BuildLastClosed() {
+ AddItem(IDC_RESTORE_TAB, GetLabelForCommandId(IDC_RESTORE_TAB));
+ AddSeparator(ui::NORMAL_SEPARATOR);
+}
+
+void RecentTabsSubMenuModel::BuildDevices() {
+ browser_sync::SessionModelAssociator* associator = GetModelAssociator();
+ if (!associator)
+ return;
+
+ std::vector<const browser_sync::SyncedSession*> sessions;
+ if (!associator->GetAllForeignSessions(&sessions))
+ return;
+
+ // Sort sessions from most recent to least recent.
+ std::sort(sessions.begin(), sessions.end(), SortSessionsByRecency);
+
+ const size_t kMaxSessionsToShow = 3;
+ bool need_separator = false;
+ for (size_t i = 0; i < std::min(sessions.size(), kMaxSessionsToShow); ++i) {
sky 2012/11/09 18:13:05 Shouldn't you only consider sessions you actually
kuan 2012/11/09 20:27:52 Done.
+ const browser_sync::SyncedSession* session = sessions[i];
+ const std::string& session_tag = session->session_tag;
+
+ // Get windows of session.
+ std::vector<const SessionWindow*> windows;
+ if (!associator->GetForeignSession(session_tag, &windows) ||
+ windows.empty()) {
+ continue;
+ }
+
+ // Sort tabs in all windows of session from most recent to least recent,
+ // independent of which window the tabs were from.
+ std::vector<SessionTab*> tabs_in_session;
+ for (size_t j = 0; j < windows.size(); ++j) {
+ tabs_in_session.insert(tabs_in_session.end(), windows[j]->tabs.begin(),
+ windows[j]->tabs.end());
+ }
+ if (tabs_in_session.empty())
+ continue;
+ std::sort(tabs_in_session.begin(), tabs_in_session.end(),
+ SortTabsByRecency);
+
+ // Build tab menu items from sorted session tabs.
+ const size_t kMaxTabsPerSessionToShow = 4;
+ for (size_t k = 0;
+ k < std::min(tabs_in_session.size(), kMaxTabsPerSessionToShow);
+ ++k) {
+ if (BuildForeignTabItem(session_tag, *tabs_in_session[k],
+ // Only need |session_name| for the first tab of the session.
+ !k ? session->session_name : std::string(), need_separator)) {
sky 2012/11/09 18:13:05 Since BuildForeightTabItem may return false, your
kuan 2012/11/09 20:27:52 duh.. i had previously counted the tabs added, the
sky 2012/11/09 21:44:56 By prune I meant remove ones that match the criter
kuan 2012/11/09 23:25:05 Done.
+ need_separator = false;
+ }
+ } // for all tabs in one session
+
+ need_separator = true;
+ } // for all sessions
+}
+
+bool RecentTabsSubMenuModel::BuildForeignTabItem(
+ const std::string& session_tag,
+ const SessionTab& tab,
+ const std::string& session_name,
+ bool need_separator) {
+ if (tab.navigations.empty())
+ return false;
+
+ int selected_index = tab.normalized_navigation_index();
+ const TabNavigation& current_navigation = tab.navigations.at(selected_index);
+ const GURL& tab_url = current_navigation.virtual_url();
+ if (tab_url == GURL(chrome::kChromeUINewTabURL))
+ return false;
+
+ if (need_separator) {
+ AddSeparator(ui::NORMAL_SEPARATOR);
+ model_.push_back(NavigationItem());
sky 2012/11/09 18:13:05 Why do you need to add an item to the model here a
kuan 2012/11/09 20:27:52 Done.
+ }
+
+ if (!session_name.empty()) {
+ AddItem(0, UTF8ToUTF16(session_name));
+ model_.push_back(NavigationItem());
+ }
+
+ NavigationItem item(session_tag, tab.tab_id.id(),
+ current_navigation.virtual_url());
+ const int kMaxTabTitleWidth = 320;
+ string16 tab_title = ui::ElideText(current_navigation.title(), gfx::Font(),
+ kMaxTabTitleWidth, ui::ELIDE_AT_END);
+ AddItem(model_.size(), tab_title);
+ AddFavicon(model_.size(), item.url);
+ model_.push_back(item);
+ return true;
+}
+
+void RecentTabsSubMenuModel::AddFavicon(int model_index, const GURL& url) {
+ if (!default_favicon_) {
+ ResourceBundle& rb = ResourceBundle::GetSharedInstance();
+ default_favicon_ = &rb.GetNativeImageNamed(IDR_DEFAULT_FAVICON);
sky 2012/11/09 18:13:05 Is there a compelling reason to make this a pointe
kuan 2012/11/09 20:27:52 Done.
+ }
+ // Set default icon first.
+ SetIcon(ModelIndexToMenuIndex(model_index), *default_favicon_);
+ // Start request to fetch actual icon if possible.
+ FaviconService* favicon_service = FaviconServiceFactory::GetForProfile(
+ browser_->profile(), Profile::EXPLICIT_ACCESS);
+ if (!favicon_service)
+ return;
+ FaviconService::Handle handle = favicon_service->GetFaviconImageForURL(
sky 2012/11/09 18:13:05 See email from Kai about this being deprecated.
kuan 2012/11/09 20:27:52 i just saw that; however he hasn't changed Favicon
+ FaviconService::FaviconForURLParams(browser_->profile(), url,
+ history::FAVICON, gfx::kFaviconSize, &favicon_consumer_),
+ base::Bind(&RecentTabsSubMenuModel::OnFaviconDataAvailable,
+ weak_ptr_factory_.GetWeakPtr()));
+ favicon_consumer_.SetClientData(favicon_service, handle, model_index);
+}
+
+void RecentTabsSubMenuModel::OnFaviconDataAvailable(
+ FaviconService::Handle handle,
+ const history::FaviconImageResult& image_result) {
+ if (image_result.image.IsEmpty())
+ return;
+ DCHECK(!model_.empty());
+ int model_index = favicon_consumer_.GetClientData(
+ FaviconServiceFactory::GetForProfile(browser_->profile(),
+ Profile::EXPLICIT_ACCESS),
+ handle);
+ DCHECK(model_index > 0 && model_index < static_cast<int>(model_.size()));
+ DCHECK(model_[model_index].tab_id > -1 && model_[model_index].url.is_valid());
+ int index_in_menu = ModelIndexToMenuIndex(model_index);
+ SetIcon(index_in_menu, image_result.image);
+ if (menu_model_delegate())
+ menu_model_delegate()->OnIconChanged(index_in_menu);
+}
+
+browser_sync::SessionModelAssociator*
+ RecentTabsSubMenuModel::GetModelAssociator() {
+ if (!associator_) {
+ ProfileSyncService* service = ProfileSyncServiceFactory::GetInstance()->
+ GetForProfile(browser_->profile());
+ // Only return the associator if it exists and it is done syncing sessions.
+ if (service && service->ShouldPushChanges())
+ associator_ = service->GetSessionModelAssociator();
+ }
+ return associator_;
+}

Powered by Google App Engine
This is Rietveld 408576698