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.
5 #include "chrome/browser/extensions/api/sessions/sessions_api.h"
9 #include "base/i18n/rtl.h"
10 #include "base/lazy_instance.h"
11 #include "base/prefs/pref_service.h"
12 #include "base/strings/string_number_conversions.h"
13 #include "base/strings/stringprintf.h"
14 #include "base/strings/utf_string_conversions.h"
15 #include "base/time/time.h"
16 #include "chrome/browser/extensions/api/sessions/session_id.h"
17 #include "chrome/browser/extensions/api/tabs/windows_util.h"
18 #include "chrome/browser/extensions/extension_tab_util.h"
19 #include "chrome/browser/extensions/window_controller.h"
20 #include "chrome/browser/extensions/window_controller_list.h"
21 #include "chrome/browser/profiles/profile.h"
22 #include "chrome/browser/search/search.h"
23 #include "chrome/browser/sessions/session_restore.h"
24 #include "chrome/browser/sessions/tab_restore_service_delegate.h"
25 #include "chrome/browser/sessions/tab_restore_service_factory.h"
26 #include "chrome/browser/sync/glue/synced_session.h"
27 #include "chrome/browser/sync/open_tabs_ui_delegate.h"
28 #include "chrome/browser/sync/profile_sync_service.h"
29 #include "chrome/browser/sync/profile_sync_service_factory.h"
30 #include "chrome/browser/ui/browser.h"
31 #include "chrome/browser/ui/browser_finder.h"
32 #include "chrome/browser/ui/host_desktop.h"
33 #include "chrome/browser/ui/tabs/tab_strip_model.h"
34 #include "chrome/common/pref_names.h"
35 #include "content/public/browser/web_contents.h"
36 #include "extensions/browser/extension_function_dispatcher.h"
37 #include "extensions/browser/extension_function_registry.h"
38 #include "extensions/browser/extension_system.h"
39 #include "extensions/common/error_utils.h"
40 #include "net/base/net_util.h"
41 #include "ui/base/layout.h"
43 namespace extensions {
45 namespace GetRecentlyClosed = api::sessions::GetRecentlyClosed;
46 namespace GetDevices = api::sessions::GetDevices;
47 namespace Restore = api::sessions::Restore;
48 namespace tabs = api::tabs;
49 namespace windows = api::windows;
51 const char kNoRecentlyClosedSessionsError[] =
52 "There are no recently closed sessions.";
53 const char kInvalidSessionIdError[] = "Invalid session id: \"*\".";
54 const char kNoBrowserToRestoreSession[] =
55 "There are no browser windows to restore the session.";
56 const char kSessionSyncError[] = "Synced sessions are not available.";
57 const char kRestoreInIncognitoError[] =
58 "Can not restore sessions in incognito mode.";
60 // Comparator function for use with std::sort that will sort sessions by
61 // descending modified_time (i.e., most recent first).
62 bool SortSessionsByRecency(const browser_sync::SyncedSession* s1,
63 const browser_sync::SyncedSession* s2) {
64 return s1->modified_time > s2->modified_time;
67 // Comparator function for use with std::sort that will sort tabs in a window
68 // by descending timestamp (i.e., most recent first).
69 bool SortTabsByRecency(const SessionTab* t1, const SessionTab* t2) {
70 return t1->timestamp > t2->timestamp;
73 scoped_ptr<tabs::Tab> CreateTabModelHelper(
75 const sessions::SerializedNavigationEntry& current_navigation,
76 const std::string& session_id,
80 const Extension* extension) {
81 scoped_ptr<tabs::Tab> tab_struct(new tabs::Tab);
83 GURL gurl = current_navigation.virtual_url();
84 std::string title = base::UTF16ToUTF8(current_navigation.title());
86 tab_struct->session_id.reset(new std::string(session_id));
87 tab_struct->url.reset(new std::string(gurl.spec()));
89 tab_struct->title.reset(new std::string(title));
91 const std::string languages =
92 profile->GetPrefs()->GetString(prefs::kAcceptLanguages);
93 tab_struct->title.reset(new std::string(base::UTF16ToUTF8(
94 net::FormatUrl(gurl, languages))));
96 tab_struct->index = index;
97 tab_struct->pinned = pinned;
98 tab_struct->selected = index == selected_index;
99 tab_struct->active = false;
100 tab_struct->highlighted = false;
101 tab_struct->incognito = false;
102 ExtensionTabUtil::ScrubTabForExtension(extension, tab_struct.get());
103 return tab_struct.Pass();
106 scoped_ptr<windows::Window> CreateWindowModelHelper(
107 scoped_ptr<std::vector<linked_ptr<tabs::Tab> > > tabs,
108 const std::string& session_id,
109 const windows::Window::Type& type,
110 const windows::Window::State& state) {
111 scoped_ptr<windows::Window> window_struct(new windows::Window);
112 window_struct->tabs = tabs.Pass();
113 window_struct->session_id.reset(new std::string(session_id));
114 window_struct->incognito = false;
115 window_struct->always_on_top = false;
116 window_struct->focused = false;
117 window_struct->type = type;
118 window_struct->state = state;
119 return window_struct.Pass();
122 scoped_ptr<api::sessions::Session> CreateSessionModelHelper(
124 scoped_ptr<tabs::Tab> tab,
125 scoped_ptr<windows::Window> window) {
126 scoped_ptr<api::sessions::Session> session_struct(new api::sessions::Session);
127 session_struct->last_modified = last_modified;
129 session_struct->tab = tab.Pass();
131 session_struct->window = window.Pass();
134 return session_struct.Pass();
137 bool is_tab_entry(const TabRestoreService::Entry* entry) {
138 return entry->type == TabRestoreService::TAB;
141 bool is_window_entry(const TabRestoreService::Entry* entry) {
142 return entry->type == TabRestoreService::WINDOW;
145 scoped_ptr<tabs::Tab> SessionsGetRecentlyClosedFunction::CreateTabModel(
146 const TabRestoreService::Tab& tab, int session_id, int selected_index) {
147 return CreateTabModelHelper(GetProfile(),
148 tab.navigations[tab.current_navigation_index],
149 base::IntToString(session_id),
156 scoped_ptr<windows::Window>
157 SessionsGetRecentlyClosedFunction::CreateWindowModel(
158 const TabRestoreService::Window& window,
160 DCHECK(!window.tabs.empty());
162 scoped_ptr<std::vector<linked_ptr<tabs::Tab> > > tabs(
163 new std::vector<linked_ptr<tabs::Tab> >);
164 for (size_t i = 0; i < window.tabs.size(); ++i) {
165 tabs->push_back(make_linked_ptr(
166 CreateTabModel(window.tabs[i], window.tabs[i].id,
167 window.selected_tab_index).release()));
170 return CreateWindowModelHelper(tabs.Pass(),
171 base::IntToString(session_id),
172 windows::Window::TYPE_NORMAL,
173 windows::Window::STATE_NORMAL);
176 scoped_ptr<api::sessions::Session>
177 SessionsGetRecentlyClosedFunction::CreateSessionModel(
178 const TabRestoreService::Entry* entry) {
179 scoped_ptr<tabs::Tab> tab;
180 scoped_ptr<windows::Window> window;
181 switch (entry->type) {
182 case TabRestoreService::TAB:
183 tab = CreateTabModel(
184 *static_cast<const TabRestoreService::Tab*>(entry), entry->id, -1);
186 case TabRestoreService::WINDOW:
187 window = CreateWindowModel(
188 *static_cast<const TabRestoreService::Window*>(entry), entry->id);
193 return CreateSessionModelHelper(entry->timestamp.ToTimeT(),
198 bool SessionsGetRecentlyClosedFunction::RunSync() {
199 scoped_ptr<GetRecentlyClosed::Params> params(
200 GetRecentlyClosed::Params::Create(*args_));
201 EXTENSION_FUNCTION_VALIDATE(params);
202 int max_results = api::sessions::MAX_SESSION_RESULTS;
203 if (params->filter && params->filter->max_results)
204 max_results = *params->filter->max_results;
205 EXTENSION_FUNCTION_VALIDATE(max_results >= 0 &&
206 max_results <= api::sessions::MAX_SESSION_RESULTS);
208 std::vector<linked_ptr<api::sessions::Session> > result;
209 TabRestoreService* tab_restore_service =
210 TabRestoreServiceFactory::GetForProfile(GetProfile());
212 // TabRestoreServiceFactory::GetForProfile() can return NULL (i.e., when in
214 if (!tab_restore_service) {
215 DCHECK_NE(GetProfile(), GetProfile()->GetOriginalProfile())
216 << "TabRestoreService expected for normal profiles";
217 results_ = GetRecentlyClosed::Results::Create(
218 std::vector<linked_ptr<api::sessions::Session> >());
222 // List of entries. They are ordered from most to least recent.
223 // We prune the list to contain max 25 entries at any time and removes
224 // uninteresting entries.
225 TabRestoreService::Entries entries = tab_restore_service->entries();
226 for (TabRestoreService::Entries::const_iterator it = entries.begin();
227 it != entries.end() && static_cast<int>(result.size()) < max_results;
229 TabRestoreService::Entry* entry = *it;
230 result.push_back(make_linked_ptr(CreateSessionModel(entry).release()));
233 results_ = GetRecentlyClosed::Results::Create(result);
237 scoped_ptr<tabs::Tab> SessionsGetDevicesFunction::CreateTabModel(
238 const std::string& session_tag,
239 const SessionTab& tab,
241 int selected_index) {
242 std::string session_id = SessionId(session_tag, tab.tab_id.id()).ToString();
243 return CreateTabModelHelper(
245 tab.navigations[tab.normalized_navigation_index()],
253 scoped_ptr<windows::Window> SessionsGetDevicesFunction::CreateWindowModel(
254 const SessionWindow& window, const std::string& session_tag) {
255 DCHECK(!window.tabs.empty());
257 // Prune tabs that are not syncable or are NewTabPage. Then, sort the tabs
258 // from most recent to least recent.
259 std::vector<const SessionTab*> tabs_in_window;
260 for (size_t i = 0; i < window.tabs.size(); ++i) {
261 const SessionTab* tab = window.tabs[i];
262 if (tab->navigations.empty())
264 const sessions::SerializedNavigationEntry& current_navigation =
265 tab->navigations.at(tab->normalized_navigation_index());
266 if (chrome::IsNTPURL(current_navigation.virtual_url(), GetProfile())) {
269 tabs_in_window.push_back(tab);
271 if (tabs_in_window.empty())
272 return scoped_ptr<windows::Window>();
273 std::sort(tabs_in_window.begin(), tabs_in_window.end(), SortTabsByRecency);
275 scoped_ptr<std::vector<linked_ptr<tabs::Tab> > > tabs(
276 new std::vector<linked_ptr<tabs::Tab> >);
277 for (size_t i = 0; i < tabs_in_window.size(); ++i) {
278 tabs->push_back(make_linked_ptr(
279 CreateTabModel(session_tag, *tabs_in_window[i], i,
280 window.selected_tab_index).release()));
283 std::string session_id =
284 SessionId(session_tag, window.window_id.id()).ToString();
286 windows::Window::Type type = windows::Window::TYPE_NONE;
287 switch (window.type) {
288 case Browser::TYPE_TABBED:
289 type = windows::Window::TYPE_NORMAL;
291 case Browser::TYPE_POPUP:
292 type = windows::Window::TYPE_POPUP;
296 windows::Window::State state = windows::Window::STATE_NONE;
297 switch (window.show_state) {
298 case ui::SHOW_STATE_NORMAL:
299 state = windows::Window::STATE_NORMAL;
301 case ui::SHOW_STATE_MINIMIZED:
302 state = windows::Window::STATE_MINIMIZED;
304 case ui::SHOW_STATE_MAXIMIZED:
305 state = windows::Window::STATE_MAXIMIZED;
307 case ui::SHOW_STATE_FULLSCREEN:
308 state = windows::Window::STATE_FULLSCREEN;
310 case ui::SHOW_STATE_DEFAULT:
311 case ui::SHOW_STATE_INACTIVE:
312 case ui::SHOW_STATE_END:
316 scoped_ptr<windows::Window> window_struct(
317 CreateWindowModelHelper(tabs.Pass(), session_id, type, state));
318 // TODO(dwankri): Dig deeper to resolve bounds not being optional, so closed
319 // windows in GetRecentlyClosed can have set values in Window helper.
320 window_struct->left.reset(new int(window.bounds.x()));
321 window_struct->top.reset(new int(window.bounds.y()));
322 window_struct->width.reset(new int(window.bounds.width()));
323 window_struct->height.reset(new int(window.bounds.height()));
325 return window_struct.Pass();
328 scoped_ptr<api::sessions::Session>
329 SessionsGetDevicesFunction::CreateSessionModel(
330 const SessionWindow& window, const std::string& session_tag) {
331 scoped_ptr<windows::Window> window_model(
332 CreateWindowModel(window, session_tag));
333 // There is a chance that after pruning uninteresting tabs the window will be
335 return !window_model ? scoped_ptr<api::sessions::Session>()
336 : CreateSessionModelHelper(window.timestamp.ToTimeT(),
337 scoped_ptr<tabs::Tab>(),
338 window_model.Pass());
341 scoped_ptr<api::sessions::Device> SessionsGetDevicesFunction::CreateDeviceModel(
342 const browser_sync::SyncedSession* session) {
343 int max_results = api::sessions::MAX_SESSION_RESULTS;
344 // Already validated in RunAsync().
345 scoped_ptr<GetDevices::Params> params(GetDevices::Params::Create(*args_));
346 if (params->filter && params->filter->max_results)
347 max_results = *params->filter->max_results;
349 scoped_ptr<api::sessions::Device> device_struct(new api::sessions::Device);
350 device_struct->info = session->session_name;
351 device_struct->device_name = session->session_name;
353 for (browser_sync::SyncedSession::SyncedWindowMap::const_iterator it =
354 session->windows.begin(); it != session->windows.end() &&
355 static_cast<int>(device_struct->sessions.size()) < max_results; ++it) {
356 scoped_ptr<api::sessions::Session> session_model(CreateSessionModel(
357 *it->second, session->session_tag));
359 device_struct->sessions.push_back(make_linked_ptr(
360 session_model.release()));
362 return device_struct.Pass();
365 bool SessionsGetDevicesFunction::RunSync() {
366 ProfileSyncService* service =
367 ProfileSyncServiceFactory::GetInstance()->GetForProfile(GetProfile());
368 if (!(service && service->GetPreferredDataTypes().Has(syncer::SESSIONS))) {
370 results_ = GetDevices::Results::Create(
371 std::vector<linked_ptr<api::sessions::Device> >());
375 browser_sync::OpenTabsUIDelegate* open_tabs =
376 service->GetOpenTabsUIDelegate();
377 std::vector<const browser_sync::SyncedSession*> sessions;
378 if (!(open_tabs && open_tabs->GetAllForeignSessions(&sessions))) {
379 results_ = GetDevices::Results::Create(
380 std::vector<linked_ptr<api::sessions::Device> >());
384 scoped_ptr<GetDevices::Params> params(GetDevices::Params::Create(*args_));
385 EXTENSION_FUNCTION_VALIDATE(params);
386 if (params->filter && params->filter->max_results) {
387 EXTENSION_FUNCTION_VALIDATE(*params->filter->max_results >= 0 &&
388 *params->filter->max_results <= api::sessions::MAX_SESSION_RESULTS);
391 std::vector<linked_ptr<api::sessions::Device> > result;
392 // Sort sessions from most recent to least recent.
393 std::sort(sessions.begin(), sessions.end(), SortSessionsByRecency);
394 for (size_t i = 0; i < sessions.size(); ++i) {
395 result.push_back(make_linked_ptr(CreateDeviceModel(sessions[i]).release()));
398 results_ = GetDevices::Results::Create(result);
402 void SessionsRestoreFunction::SetInvalidIdError(const std::string& invalid_id) {
403 SetError(ErrorUtils::FormatErrorMessage(kInvalidSessionIdError, invalid_id));
407 void SessionsRestoreFunction::SetResultRestoredTab(
408 content::WebContents* contents) {
409 scoped_ptr<base::DictionaryValue> tab_value(
410 ExtensionTabUtil::CreateTabValue(contents, extension()));
411 scoped_ptr<tabs::Tab> tab(tabs::Tab::FromValue(*tab_value));
412 scoped_ptr<api::sessions::Session> restored_session(CreateSessionModelHelper(
413 base::Time::Now().ToTimeT(),
415 scoped_ptr<windows::Window>()));
416 results_ = Restore::Results::Create(*restored_session);
419 bool SessionsRestoreFunction::SetResultRestoredWindow(int window_id) {
420 WindowController* controller = NULL;
421 if (!windows_util::GetWindowFromWindowID(this, window_id, &controller)) {
422 // error_ is set by GetWindowFromWindowId function call.
425 scoped_ptr<base::DictionaryValue> window_value(
426 controller->CreateWindowValueWithTabs(extension()));
427 scoped_ptr<windows::Window> window(windows::Window::FromValue(
429 results_ = Restore::Results::Create(*CreateSessionModelHelper(
430 base::Time::Now().ToTimeT(),
431 scoped_ptr<tabs::Tab>(),
436 bool SessionsRestoreFunction::RestoreMostRecentlyClosed(Browser* browser) {
437 TabRestoreService* tab_restore_service =
438 TabRestoreServiceFactory::GetForProfile(GetProfile());
439 chrome::HostDesktopType host_desktop_type = browser->host_desktop_type();
440 TabRestoreService::Entries entries = tab_restore_service->entries();
442 if (entries.empty()) {
443 SetError(kNoRecentlyClosedSessionsError);
447 bool is_window = is_window_entry(entries.front());
448 TabRestoreServiceDelegate* delegate =
449 TabRestoreServiceDelegate::FindDelegateForWebContents(
450 browser->tab_strip_model()->GetActiveWebContents());
451 std::vector<content::WebContents*> contents =
452 tab_restore_service->RestoreMostRecentEntry(delegate, host_desktop_type);
453 DCHECK(contents.size());
456 return SetResultRestoredWindow(
457 ExtensionTabUtil::GetWindowIdOfTab(contents[0]));
460 SetResultRestoredTab(contents[0]);
464 bool SessionsRestoreFunction::RestoreLocalSession(const SessionId& session_id,
466 TabRestoreService* tab_restore_service =
467 TabRestoreServiceFactory::GetForProfile(GetProfile());
468 chrome::HostDesktopType host_desktop_type = browser->host_desktop_type();
469 TabRestoreService::Entries entries = tab_restore_service->entries();
471 if (entries.empty()) {
472 SetInvalidIdError(session_id.ToString());
476 // Check if the recently closed list contains an entry with the provided id.
477 bool is_window = false;
478 for (TabRestoreService::Entries::iterator it = entries.begin();
479 it != entries.end(); ++it) {
480 if ((*it)->id == session_id.id()) {
481 // The only time a full window is being restored is if the entry ID
482 // matches the provided ID and the entry type is Window.
483 is_window = is_window_entry(*it);
488 TabRestoreServiceDelegate* delegate =
489 TabRestoreServiceDelegate::FindDelegateForWebContents(
490 browser->tab_strip_model()->GetActiveWebContents());
491 std::vector<content::WebContents*> contents =
492 tab_restore_service->RestoreEntryById(delegate,
496 // If the ID is invalid, contents will be empty.
497 if (!contents.size()) {
498 SetInvalidIdError(session_id.ToString());
502 // Retrieve the window through any of the tabs in contents.
504 return SetResultRestoredWindow(
505 ExtensionTabUtil::GetWindowIdOfTab(contents[0]));
508 SetResultRestoredTab(contents[0]);
512 bool SessionsRestoreFunction::RestoreForeignSession(const SessionId& session_id,
514 ProfileSyncService* service =
515 ProfileSyncServiceFactory::GetInstance()->GetForProfile(GetProfile());
516 if (!(service && service->GetPreferredDataTypes().Has(syncer::SESSIONS))) {
517 SetError(kSessionSyncError);
520 browser_sync::OpenTabsUIDelegate* open_tabs =
521 service->GetOpenTabsUIDelegate();
523 SetError(kSessionSyncError);
527 const SessionTab* tab = NULL;
528 if (open_tabs->GetForeignTab(session_id.session_tag(),
531 TabStripModel* tab_strip = browser->tab_strip_model();
532 content::WebContents* contents = tab_strip->GetActiveWebContents();
534 content::WebContents* tab_contents =
535 SessionRestore::RestoreForeignSessionTab(contents, *tab,
537 SetResultRestoredTab(tab_contents);
541 // Restoring a full window.
542 std::vector<const SessionWindow*> windows;
543 if (!open_tabs->GetForeignSession(session_id.session_tag(), &windows)) {
544 SetInvalidIdError(session_id.ToString());
548 std::vector<const SessionWindow*>::const_iterator window = windows.begin();
549 while (window != windows.end()
550 && (*window)->window_id.id() != session_id.id()) {
553 if (window == windows.end()) {
554 SetInvalidIdError(session_id.ToString());
558 chrome::HostDesktopType host_desktop_type = browser->host_desktop_type();
559 // Only restore one window at a time.
560 std::vector<Browser*> browsers = SessionRestore::RestoreForeignSessionWindows(
561 GetProfile(), host_desktop_type, window, window + 1);
562 // Will always create one browser because we only restore one window per call.
563 DCHECK_EQ(1u, browsers.size());
564 return SetResultRestoredWindow(ExtensionTabUtil::GetWindowId(browsers[0]));
567 bool SessionsRestoreFunction::RunSync() {
568 scoped_ptr<Restore::Params> params(Restore::Params::Create(*args_));
569 EXTENSION_FUNCTION_VALIDATE(params);
571 Browser* browser = chrome::FindBrowserWithProfile(
572 GetProfile(), chrome::HOST_DESKTOP_TYPE_NATIVE);
574 SetError(kNoBrowserToRestoreSession);
578 if (GetProfile() != GetProfile()->GetOriginalProfile()) {
579 SetError(kRestoreInIncognitoError);
583 if (!params->session_id)
584 return RestoreMostRecentlyClosed(browser);
586 scoped_ptr<SessionId> session_id(SessionId::Parse(*params->session_id));
588 SetInvalidIdError(*params->session_id);
592 return session_id->IsForeign() ?
593 RestoreForeignSession(*session_id, browser)
594 : RestoreLocalSession(*session_id, browser);
597 SessionsEventRouter::SessionsEventRouter(Profile* profile)
599 tab_restore_service_(TabRestoreServiceFactory::GetForProfile(profile)) {
600 // TabRestoreServiceFactory::GetForProfile() can return NULL (i.e., when in
602 if (tab_restore_service_) {
603 tab_restore_service_->LoadTabsFromLastSession();
604 tab_restore_service_->AddObserver(this);
608 SessionsEventRouter::~SessionsEventRouter() {
609 if (tab_restore_service_)
610 tab_restore_service_->RemoveObserver(this);
613 void SessionsEventRouter::TabRestoreServiceChanged(
614 TabRestoreService* service) {
615 scoped_ptr<base::ListValue> args(new base::ListValue());
616 EventRouter::Get(profile_)->BroadcastEvent(make_scoped_ptr(
617 new Event(api::sessions::OnChanged::kEventName, args.Pass())));
620 void SessionsEventRouter::TabRestoreServiceDestroyed(
621 TabRestoreService* service) {
622 tab_restore_service_ = NULL;
625 SessionsAPI::SessionsAPI(content::BrowserContext* context)
626 : browser_context_(context) {
627 EventRouter::Get(browser_context_)->RegisterObserver(this,
628 api::sessions::OnChanged::kEventName);
631 SessionsAPI::~SessionsAPI() {
634 void SessionsAPI::Shutdown() {
635 EventRouter::Get(browser_context_)->UnregisterObserver(this);
638 static base::LazyInstance<BrowserContextKeyedAPIFactory<SessionsAPI> >
639 g_factory = LAZY_INSTANCE_INITIALIZER;
641 BrowserContextKeyedAPIFactory<SessionsAPI>*
642 SessionsAPI::GetFactoryInstance() {
643 return g_factory.Pointer();
646 void SessionsAPI::OnListenerAdded(const EventListenerInfo& details) {
647 sessions_event_router_.reset(
648 new SessionsEventRouter(Profile::FromBrowserContext(browser_context_)));
649 EventRouter::Get(browser_context_)->UnregisterObserver(this);
652 } // namespace extensions