Add ENABLE_MEDIA_ROUTER define to builds other than Android and iOS.
[chromium-blink-merge.git] / chrome / browser / extensions / api / sessions / sessions_api.cc
blobe900b5922a243e2ab21bd50808c1a9e3ee5033cd
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"
7 #include <vector>
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 sessions::SessionTab* t1,
70 const sessions::SessionTab* t2) {
71 return t1->timestamp > t2->timestamp;
74 scoped_ptr<tabs::Tab> CreateTabModelHelper(
75 Profile* profile,
76 const sessions::SerializedNavigationEntry& current_navigation,
77 const std::string& session_id,
78 int index,
79 bool pinned,
80 int selected_index,
81 const Extension* extension) {
82 scoped_ptr<tabs::Tab> tab_struct(new tabs::Tab);
84 const GURL& url = current_navigation.virtual_url();
85 std::string title = base::UTF16ToUTF8(current_navigation.title());
87 tab_struct->session_id.reset(new std::string(session_id));
88 tab_struct->url.reset(new std::string(url.spec()));
89 tab_struct->fav_icon_url.reset(
90 new std::string(current_navigation.favicon_url().spec()));
91 if (!title.empty()) {
92 tab_struct->title.reset(new std::string(title));
93 } else {
94 const std::string languages =
95 profile->GetPrefs()->GetString(prefs::kAcceptLanguages);
96 tab_struct->title.reset(
97 new std::string(base::UTF16ToUTF8(net::FormatUrl(url, languages))));
99 tab_struct->index = index;
100 tab_struct->pinned = pinned;
101 // Note: |selected_index| from the sync sessions model is what we call
102 // "active" in extensions terminology. "selected" is deprecated because it's
103 // not clear whether it means "active" (user can see) or "highlighted" (user
104 // has highlighted, since you can select tabs without bringing them into the
105 // foreground).
106 tab_struct->active = index == selected_index;
107 ExtensionTabUtil::ScrubTabForExtension(extension, tab_struct.get());
108 return tab_struct.Pass();
111 scoped_ptr<windows::Window> CreateWindowModelHelper(
112 scoped_ptr<std::vector<linked_ptr<tabs::Tab>>> tabs,
113 const std::string& session_id,
114 const windows::WindowType& type,
115 const windows::WindowState& state) {
116 scoped_ptr<windows::Window> window_struct(new windows::Window);
117 window_struct->tabs = tabs.Pass();
118 window_struct->session_id.reset(new std::string(session_id));
119 window_struct->incognito = false;
120 window_struct->always_on_top = false;
121 window_struct->focused = false;
122 window_struct->type = type;
123 window_struct->state = state;
124 return window_struct.Pass();
127 scoped_ptr<api::sessions::Session> CreateSessionModelHelper(
128 int last_modified,
129 scoped_ptr<tabs::Tab> tab,
130 scoped_ptr<windows::Window> window) {
131 scoped_ptr<api::sessions::Session> session_struct(new api::sessions::Session);
132 session_struct->last_modified = last_modified;
133 if (tab)
134 session_struct->tab = tab.Pass();
135 else if (window)
136 session_struct->window = window.Pass();
137 else
138 NOTREACHED();
139 return session_struct.Pass();
142 bool is_tab_entry(const TabRestoreService::Entry* entry) {
143 return entry->type == TabRestoreService::TAB;
146 bool is_window_entry(const TabRestoreService::Entry* entry) {
147 return entry->type == TabRestoreService::WINDOW;
150 scoped_ptr<tabs::Tab> SessionsGetRecentlyClosedFunction::CreateTabModel(
151 const TabRestoreService::Tab& tab, int session_id, int selected_index) {
152 return CreateTabModelHelper(GetProfile(),
153 tab.navigations[tab.current_navigation_index],
154 base::IntToString(session_id),
155 tab.tabstrip_index,
156 tab.pinned,
157 selected_index,
158 extension());
161 scoped_ptr<windows::Window>
162 SessionsGetRecentlyClosedFunction::CreateWindowModel(
163 const TabRestoreService::Window& window,
164 int session_id) {
165 DCHECK(!window.tabs.empty());
167 scoped_ptr<std::vector<linked_ptr<tabs::Tab> > > tabs(
168 new std::vector<linked_ptr<tabs::Tab> >);
169 for (size_t i = 0; i < window.tabs.size(); ++i) {
170 tabs->push_back(make_linked_ptr(
171 CreateTabModel(window.tabs[i], window.tabs[i].id,
172 window.selected_tab_index).release()));
175 return CreateWindowModelHelper(tabs.Pass(), base::IntToString(session_id),
176 windows::WINDOW_TYPE_NORMAL,
177 windows::WINDOW_STATE_NORMAL);
180 scoped_ptr<api::sessions::Session>
181 SessionsGetRecentlyClosedFunction::CreateSessionModel(
182 const TabRestoreService::Entry* entry) {
183 scoped_ptr<tabs::Tab> tab;
184 scoped_ptr<windows::Window> window;
185 switch (entry->type) {
186 case TabRestoreService::TAB:
187 tab = CreateTabModel(
188 *static_cast<const TabRestoreService::Tab*>(entry), entry->id, -1);
189 break;
190 case TabRestoreService::WINDOW:
191 window = CreateWindowModel(
192 *static_cast<const TabRestoreService::Window*>(entry), entry->id);
193 break;
194 default:
195 NOTREACHED();
197 return CreateSessionModelHelper(entry->timestamp.ToTimeT(),
198 tab.Pass(),
199 window.Pass());
202 bool SessionsGetRecentlyClosedFunction::RunSync() {
203 scoped_ptr<GetRecentlyClosed::Params> params(
204 GetRecentlyClosed::Params::Create(*args_));
205 EXTENSION_FUNCTION_VALIDATE(params);
206 int max_results = api::sessions::MAX_SESSION_RESULTS;
207 if (params->filter && params->filter->max_results)
208 max_results = *params->filter->max_results;
209 EXTENSION_FUNCTION_VALIDATE(max_results >= 0 &&
210 max_results <= api::sessions::MAX_SESSION_RESULTS);
212 std::vector<linked_ptr<api::sessions::Session> > result;
213 TabRestoreService* tab_restore_service =
214 TabRestoreServiceFactory::GetForProfile(GetProfile());
216 // TabRestoreServiceFactory::GetForProfile() can return NULL (i.e., when in
217 // incognito mode)
218 if (!tab_restore_service) {
219 DCHECK_NE(GetProfile(), GetProfile()->GetOriginalProfile())
220 << "TabRestoreService expected for normal profiles";
221 results_ = GetRecentlyClosed::Results::Create(
222 std::vector<linked_ptr<api::sessions::Session> >());
223 return true;
226 // List of entries. They are ordered from most to least recent.
227 // We prune the list to contain max 25 entries at any time and removes
228 // uninteresting entries.
229 TabRestoreService::Entries entries = tab_restore_service->entries();
230 for (TabRestoreService::Entries::const_iterator it = entries.begin();
231 it != entries.end() && static_cast<int>(result.size()) < max_results;
232 ++it) {
233 TabRestoreService::Entry* entry = *it;
234 result.push_back(make_linked_ptr(CreateSessionModel(entry).release()));
237 results_ = GetRecentlyClosed::Results::Create(result);
238 return true;
241 scoped_ptr<tabs::Tab> SessionsGetDevicesFunction::CreateTabModel(
242 const std::string& session_tag,
243 const sessions::SessionTab& tab,
244 int tab_index,
245 int selected_index) {
246 std::string session_id = SessionId(session_tag, tab.tab_id.id()).ToString();
247 return CreateTabModelHelper(
248 GetProfile(),
249 tab.navigations[tab.normalized_navigation_index()],
250 session_id,
251 tab_index,
252 tab.pinned,
253 selected_index,
254 extension());
257 scoped_ptr<windows::Window> SessionsGetDevicesFunction::CreateWindowModel(
258 const sessions::SessionWindow& window, const std::string& session_tag) {
259 DCHECK(!window.tabs.empty());
261 // Prune tabs that are not syncable or are NewTabPage. Then, sort the tabs
262 // from most recent to least recent.
263 std::vector<const sessions::SessionTab*> tabs_in_window;
264 for (size_t i = 0; i < window.tabs.size(); ++i) {
265 const sessions::SessionTab* tab = window.tabs[i];
266 if (tab->navigations.empty())
267 continue;
268 const sessions::SerializedNavigationEntry& current_navigation =
269 tab->navigations.at(tab->normalized_navigation_index());
270 if (chrome::IsNTPURL(current_navigation.virtual_url(), GetProfile())) {
271 continue;
273 tabs_in_window.push_back(tab);
275 if (tabs_in_window.empty())
276 return scoped_ptr<windows::Window>();
277 std::sort(tabs_in_window.begin(), tabs_in_window.end(), SortTabsByRecency);
279 scoped_ptr<std::vector<linked_ptr<tabs::Tab> > > tabs(
280 new std::vector<linked_ptr<tabs::Tab> >);
281 for (size_t i = 0; i < tabs_in_window.size(); ++i) {
282 tabs->push_back(make_linked_ptr(
283 CreateTabModel(session_tag, *tabs_in_window[i], i,
284 window.selected_tab_index).release()));
287 std::string session_id =
288 SessionId(session_tag, window.window_id.id()).ToString();
290 windows::WindowType type = windows::WINDOW_TYPE_NONE;
291 switch (window.type) {
292 case sessions::SessionWindow::TYPE_TABBED:
293 type = windows::WINDOW_TYPE_NORMAL;
294 break;
295 case sessions::SessionWindow::TYPE_POPUP:
296 type = windows::WINDOW_TYPE_POPUP;
297 break;
300 windows::WindowState state = windows::WINDOW_STATE_NONE;
301 switch (window.show_state) {
302 case ui::SHOW_STATE_NORMAL:
303 state = windows::WINDOW_STATE_NORMAL;
304 break;
305 case ui::SHOW_STATE_MINIMIZED:
306 state = windows::WINDOW_STATE_MINIMIZED;
307 break;
308 case ui::SHOW_STATE_MAXIMIZED:
309 state = windows::WINDOW_STATE_MAXIMIZED;
310 break;
311 case ui::SHOW_STATE_FULLSCREEN:
312 state = windows::WINDOW_STATE_FULLSCREEN;
313 break;
314 case ui::SHOW_STATE_DEFAULT:
315 case ui::SHOW_STATE_INACTIVE:
316 case ui::SHOW_STATE_END:
317 break;
320 scoped_ptr<windows::Window> window_struct(
321 CreateWindowModelHelper(tabs.Pass(), session_id, type, state));
322 // TODO(dwankri): Dig deeper to resolve bounds not being optional, so closed
323 // windows in GetRecentlyClosed can have set values in Window helper.
324 window_struct->left.reset(new int(window.bounds.x()));
325 window_struct->top.reset(new int(window.bounds.y()));
326 window_struct->width.reset(new int(window.bounds.width()));
327 window_struct->height.reset(new int(window.bounds.height()));
329 return window_struct.Pass();
332 scoped_ptr<api::sessions::Session>
333 SessionsGetDevicesFunction::CreateSessionModel(
334 const sessions::SessionWindow& window, const std::string& session_tag) {
335 scoped_ptr<windows::Window> window_model(
336 CreateWindowModel(window, session_tag));
337 // There is a chance that after pruning uninteresting tabs the window will be
338 // empty.
339 return !window_model ? scoped_ptr<api::sessions::Session>()
340 : CreateSessionModelHelper(window.timestamp.ToTimeT(),
341 scoped_ptr<tabs::Tab>(),
342 window_model.Pass());
345 scoped_ptr<api::sessions::Device> SessionsGetDevicesFunction::CreateDeviceModel(
346 const browser_sync::SyncedSession* session) {
347 int max_results = api::sessions::MAX_SESSION_RESULTS;
348 // Already validated in RunAsync().
349 scoped_ptr<GetDevices::Params> params(GetDevices::Params::Create(*args_));
350 if (params->filter && params->filter->max_results)
351 max_results = *params->filter->max_results;
353 scoped_ptr<api::sessions::Device> device_struct(new api::sessions::Device);
354 device_struct->info = session->session_name;
355 device_struct->device_name = session->session_name;
357 for (browser_sync::SyncedSession::SyncedWindowMap::const_iterator it =
358 session->windows.begin(); it != session->windows.end() &&
359 static_cast<int>(device_struct->sessions.size()) < max_results; ++it) {
360 scoped_ptr<api::sessions::Session> session_model(CreateSessionModel(
361 *it->second, session->session_tag));
362 if (session_model)
363 device_struct->sessions.push_back(make_linked_ptr(
364 session_model.release()));
366 return device_struct.Pass();
369 bool SessionsGetDevicesFunction::RunSync() {
370 ProfileSyncService* service =
371 ProfileSyncServiceFactory::GetInstance()->GetForProfile(GetProfile());
372 if (!(service && service->GetPreferredDataTypes().Has(syncer::SESSIONS))) {
373 // Sync not enabled.
374 results_ = GetDevices::Results::Create(
375 std::vector<linked_ptr<api::sessions::Device> >());
376 return true;
379 browser_sync::OpenTabsUIDelegate* open_tabs =
380 service->GetOpenTabsUIDelegate();
381 std::vector<const browser_sync::SyncedSession*> sessions;
382 if (!(open_tabs && open_tabs->GetAllForeignSessions(&sessions))) {
383 results_ = GetDevices::Results::Create(
384 std::vector<linked_ptr<api::sessions::Device> >());
385 return true;
388 scoped_ptr<GetDevices::Params> params(GetDevices::Params::Create(*args_));
389 EXTENSION_FUNCTION_VALIDATE(params);
390 if (params->filter && params->filter->max_results) {
391 EXTENSION_FUNCTION_VALIDATE(*params->filter->max_results >= 0 &&
392 *params->filter->max_results <= api::sessions::MAX_SESSION_RESULTS);
395 std::vector<linked_ptr<api::sessions::Device> > result;
396 // Sort sessions from most recent to least recent.
397 std::sort(sessions.begin(), sessions.end(), SortSessionsByRecency);
398 for (size_t i = 0; i < sessions.size(); ++i) {
399 result.push_back(make_linked_ptr(CreateDeviceModel(sessions[i]).release()));
402 results_ = GetDevices::Results::Create(result);
403 return true;
406 void SessionsRestoreFunction::SetInvalidIdError(const std::string& invalid_id) {
407 SetError(ErrorUtils::FormatErrorMessage(kInvalidSessionIdError, invalid_id));
411 void SessionsRestoreFunction::SetResultRestoredTab(
412 content::WebContents* contents) {
413 scoped_ptr<base::DictionaryValue> tab_value(
414 ExtensionTabUtil::CreateTabValue(contents, extension()));
415 scoped_ptr<tabs::Tab> tab(tabs::Tab::FromValue(*tab_value));
416 scoped_ptr<api::sessions::Session> restored_session(CreateSessionModelHelper(
417 base::Time::Now().ToTimeT(),
418 tab.Pass(),
419 scoped_ptr<windows::Window>()));
420 results_ = Restore::Results::Create(*restored_session);
423 bool SessionsRestoreFunction::SetResultRestoredWindow(int window_id) {
424 WindowController* controller = NULL;
425 if (!windows_util::GetWindowFromWindowID(this, window_id, &controller)) {
426 // error_ is set by GetWindowFromWindowId function call.
427 return false;
429 scoped_ptr<base::DictionaryValue> window_value(
430 controller->CreateWindowValueWithTabs(extension()));
431 scoped_ptr<windows::Window> window(windows::Window::FromValue(
432 *window_value));
433 results_ = Restore::Results::Create(*CreateSessionModelHelper(
434 base::Time::Now().ToTimeT(),
435 scoped_ptr<tabs::Tab>(),
436 window.Pass()));
437 return true;
440 bool SessionsRestoreFunction::RestoreMostRecentlyClosed(Browser* browser) {
441 TabRestoreService* tab_restore_service =
442 TabRestoreServiceFactory::GetForProfile(GetProfile());
443 chrome::HostDesktopType host_desktop_type = browser->host_desktop_type();
444 TabRestoreService::Entries entries = tab_restore_service->entries();
446 if (entries.empty()) {
447 SetError(kNoRecentlyClosedSessionsError);
448 return false;
451 bool is_window = is_window_entry(entries.front());
452 TabRestoreServiceDelegate* delegate =
453 TabRestoreServiceDelegate::FindDelegateForWebContents(
454 browser->tab_strip_model()->GetActiveWebContents());
455 std::vector<content::WebContents*> contents =
456 tab_restore_service->RestoreMostRecentEntry(delegate, host_desktop_type);
457 DCHECK(contents.size());
459 if (is_window) {
460 return SetResultRestoredWindow(
461 ExtensionTabUtil::GetWindowIdOfTab(contents[0]));
464 SetResultRestoredTab(contents[0]);
465 return true;
468 bool SessionsRestoreFunction::RestoreLocalSession(const SessionId& session_id,
469 Browser* browser) {
470 TabRestoreService* tab_restore_service =
471 TabRestoreServiceFactory::GetForProfile(GetProfile());
472 chrome::HostDesktopType host_desktop_type = browser->host_desktop_type();
473 TabRestoreService::Entries entries = tab_restore_service->entries();
475 if (entries.empty()) {
476 SetInvalidIdError(session_id.ToString());
477 return false;
480 // Check if the recently closed list contains an entry with the provided id.
481 bool is_window = false;
482 for (TabRestoreService::Entries::iterator it = entries.begin();
483 it != entries.end(); ++it) {
484 if ((*it)->id == session_id.id()) {
485 // The only time a full window is being restored is if the entry ID
486 // matches the provided ID and the entry type is Window.
487 is_window = is_window_entry(*it);
488 break;
492 TabRestoreServiceDelegate* delegate =
493 TabRestoreServiceDelegate::FindDelegateForWebContents(
494 browser->tab_strip_model()->GetActiveWebContents());
495 std::vector<content::WebContents*> contents =
496 tab_restore_service->RestoreEntryById(delegate,
497 session_id.id(),
498 host_desktop_type,
499 UNKNOWN);
500 // If the ID is invalid, contents will be empty.
501 if (!contents.size()) {
502 SetInvalidIdError(session_id.ToString());
503 return false;
506 // Retrieve the window through any of the tabs in contents.
507 if (is_window) {
508 return SetResultRestoredWindow(
509 ExtensionTabUtil::GetWindowIdOfTab(contents[0]));
512 SetResultRestoredTab(contents[0]);
513 return true;
516 bool SessionsRestoreFunction::RestoreForeignSession(const SessionId& session_id,
517 Browser* browser) {
518 ProfileSyncService* service =
519 ProfileSyncServiceFactory::GetInstance()->GetForProfile(GetProfile());
520 if (!(service && service->GetPreferredDataTypes().Has(syncer::SESSIONS))) {
521 SetError(kSessionSyncError);
522 return false;
524 browser_sync::OpenTabsUIDelegate* open_tabs =
525 service->GetOpenTabsUIDelegate();
526 if (!open_tabs) {
527 SetError(kSessionSyncError);
528 return false;
531 const sessions::SessionTab* tab = NULL;
532 if (open_tabs->GetForeignTab(session_id.session_tag(),
533 session_id.id(),
534 &tab)) {
535 TabStripModel* tab_strip = browser->tab_strip_model();
536 content::WebContents* contents = tab_strip->GetActiveWebContents();
538 content::WebContents* tab_contents =
539 SessionRestore::RestoreForeignSessionTab(contents, *tab,
540 NEW_FOREGROUND_TAB);
541 SetResultRestoredTab(tab_contents);
542 return true;
545 // Restoring a full window.
546 std::vector<const sessions::SessionWindow*> windows;
547 if (!open_tabs->GetForeignSession(session_id.session_tag(), &windows)) {
548 SetInvalidIdError(session_id.ToString());
549 return false;
552 std::vector<const sessions::SessionWindow*>::const_iterator window =
553 windows.begin();
554 while (window != windows.end()
555 && (*window)->window_id.id() != session_id.id()) {
556 ++window;
558 if (window == windows.end()) {
559 SetInvalidIdError(session_id.ToString());
560 return false;
563 chrome::HostDesktopType host_desktop_type = browser->host_desktop_type();
564 // Only restore one window at a time.
565 std::vector<Browser*> browsers = SessionRestore::RestoreForeignSessionWindows(
566 GetProfile(), host_desktop_type, window, window + 1);
567 // Will always create one browser because we only restore one window per call.
568 DCHECK_EQ(1u, browsers.size());
569 return SetResultRestoredWindow(ExtensionTabUtil::GetWindowId(browsers[0]));
572 bool SessionsRestoreFunction::RunSync() {
573 scoped_ptr<Restore::Params> params(Restore::Params::Create(*args_));
574 EXTENSION_FUNCTION_VALIDATE(params);
576 Browser* browser = chrome::FindBrowserWithProfile(
577 GetProfile(), chrome::HOST_DESKTOP_TYPE_NATIVE);
578 if (!browser) {
579 SetError(kNoBrowserToRestoreSession);
580 return false;
583 if (GetProfile() != GetProfile()->GetOriginalProfile()) {
584 SetError(kRestoreInIncognitoError);
585 return false;
588 if (!params->session_id)
589 return RestoreMostRecentlyClosed(browser);
591 scoped_ptr<SessionId> session_id(SessionId::Parse(*params->session_id));
592 if (!session_id) {
593 SetInvalidIdError(*params->session_id);
594 return false;
597 return session_id->IsForeign() ?
598 RestoreForeignSession(*session_id, browser)
599 : RestoreLocalSession(*session_id, browser);
602 SessionsEventRouter::SessionsEventRouter(Profile* profile)
603 : profile_(profile),
604 tab_restore_service_(TabRestoreServiceFactory::GetForProfile(profile)) {
605 // TabRestoreServiceFactory::GetForProfile() can return NULL (i.e., when in
606 // incognito mode)
607 if (tab_restore_service_) {
608 tab_restore_service_->LoadTabsFromLastSession();
609 tab_restore_service_->AddObserver(this);
613 SessionsEventRouter::~SessionsEventRouter() {
614 if (tab_restore_service_)
615 tab_restore_service_->RemoveObserver(this);
618 void SessionsEventRouter::TabRestoreServiceChanged(
619 TabRestoreService* service) {
620 scoped_ptr<base::ListValue> args(new base::ListValue());
621 EventRouter::Get(profile_)->BroadcastEvent(make_scoped_ptr(
622 new Event(api::sessions::OnChanged::kEventName, args.Pass())));
625 void SessionsEventRouter::TabRestoreServiceDestroyed(
626 TabRestoreService* service) {
627 tab_restore_service_ = NULL;
630 SessionsAPI::SessionsAPI(content::BrowserContext* context)
631 : browser_context_(context) {
632 EventRouter::Get(browser_context_)->RegisterObserver(this,
633 api::sessions::OnChanged::kEventName);
636 SessionsAPI::~SessionsAPI() {
639 void SessionsAPI::Shutdown() {
640 EventRouter::Get(browser_context_)->UnregisterObserver(this);
643 static base::LazyInstance<BrowserContextKeyedAPIFactory<SessionsAPI> >
644 g_factory = LAZY_INSTANCE_INITIALIZER;
646 BrowserContextKeyedAPIFactory<SessionsAPI>*
647 SessionsAPI::GetFactoryInstance() {
648 return g_factory.Pointer();
651 void SessionsAPI::OnListenerAdded(const EventListenerInfo& details) {
652 sessions_event_router_.reset(
653 new SessionsEventRouter(Profile::FromBrowserContext(browser_context_)));
654 EventRouter::Get(browser_context_)->UnregisterObserver(this);
657 } // namespace extensions