Add new certificateProvider extension API.
[chromium-blink-merge.git] / chrome / browser / extensions / api / sessions / sessions_api.cc
blobd081b47815dd6dad2f58e586f222604d022a8bef
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/profile_sync_service.h"
27 #include "chrome/browser/sync/profile_sync_service_factory.h"
28 #include "chrome/browser/ui/browser.h"
29 #include "chrome/browser/ui/browser_finder.h"
30 #include "chrome/browser/ui/host_desktop.h"
31 #include "chrome/browser/ui/tabs/tab_strip_model.h"
32 #include "chrome/common/pref_names.h"
33 #include "components/sync_driver/glue/synced_session.h"
34 #include "components/sync_driver/open_tabs_ui_delegate.h"
35 #include "components/url_formatter/url_formatter.h"
36 #include "content/public/browser/web_contents.h"
37 #include "extensions/browser/extension_function_dispatcher.h"
38 #include "extensions/browser/extension_function_registry.h"
39 #include "extensions/browser/extension_system.h"
40 #include "extensions/common/error_utils.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 sync_driver::SyncedSession* s1,
63 const sync_driver::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(new std::string(
97 base::UTF16ToUTF8(url_formatter::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 (search::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 case ui::SHOW_STATE_DOCKED:
304 state = windows::WINDOW_STATE_NORMAL;
305 break;
306 case ui::SHOW_STATE_MINIMIZED:
307 state = windows::WINDOW_STATE_MINIMIZED;
308 break;
309 case ui::SHOW_STATE_MAXIMIZED:
310 state = windows::WINDOW_STATE_MAXIMIZED;
311 break;
312 case ui::SHOW_STATE_FULLSCREEN:
313 state = windows::WINDOW_STATE_FULLSCREEN;
314 break;
315 case ui::SHOW_STATE_DEFAULT:
316 case ui::SHOW_STATE_INACTIVE:
317 case ui::SHOW_STATE_END:
318 break;
321 scoped_ptr<windows::Window> window_struct(
322 CreateWindowModelHelper(tabs.Pass(), session_id, type, state));
323 // TODO(dwankri): Dig deeper to resolve bounds not being optional, so closed
324 // windows in GetRecentlyClosed can have set values in Window helper.
325 window_struct->left.reset(new int(window.bounds.x()));
326 window_struct->top.reset(new int(window.bounds.y()));
327 window_struct->width.reset(new int(window.bounds.width()));
328 window_struct->height.reset(new int(window.bounds.height()));
330 return window_struct.Pass();
333 scoped_ptr<api::sessions::Session>
334 SessionsGetDevicesFunction::CreateSessionModel(
335 const sessions::SessionWindow& window, const std::string& session_tag) {
336 scoped_ptr<windows::Window> window_model(
337 CreateWindowModel(window, session_tag));
338 // There is a chance that after pruning uninteresting tabs the window will be
339 // empty.
340 return !window_model ? scoped_ptr<api::sessions::Session>()
341 : CreateSessionModelHelper(window.timestamp.ToTimeT(),
342 scoped_ptr<tabs::Tab>(),
343 window_model.Pass());
346 scoped_ptr<api::sessions::Device> SessionsGetDevicesFunction::CreateDeviceModel(
347 const sync_driver::SyncedSession* session) {
348 int max_results = api::sessions::MAX_SESSION_RESULTS;
349 // Already validated in RunAsync().
350 scoped_ptr<GetDevices::Params> params(GetDevices::Params::Create(*args_));
351 if (params->filter && params->filter->max_results)
352 max_results = *params->filter->max_results;
354 scoped_ptr<api::sessions::Device> device_struct(new api::sessions::Device);
355 device_struct->info = session->session_name;
356 device_struct->device_name = session->session_name;
358 for (sync_driver::SyncedSession::SyncedWindowMap::const_iterator it =
359 session->windows.begin();
360 it != session->windows.end() &&
361 static_cast<int>(device_struct->sessions.size()) < max_results;
362 ++it) {
363 scoped_ptr<api::sessions::Session> session_model(CreateSessionModel(
364 *it->second, session->session_tag));
365 if (session_model)
366 device_struct->sessions.push_back(make_linked_ptr(
367 session_model.release()));
369 return device_struct.Pass();
372 bool SessionsGetDevicesFunction::RunSync() {
373 ProfileSyncService* service =
374 ProfileSyncServiceFactory::GetInstance()->GetForProfile(GetProfile());
375 if (!(service && service->GetPreferredDataTypes().Has(syncer::SESSIONS))) {
376 // Sync not enabled.
377 results_ = GetDevices::Results::Create(
378 std::vector<linked_ptr<api::sessions::Device> >());
379 return true;
382 sync_driver::OpenTabsUIDelegate* open_tabs = service->GetOpenTabsUIDelegate();
383 std::vector<const sync_driver::SyncedSession*> sessions;
384 if (!(open_tabs && open_tabs->GetAllForeignSessions(&sessions))) {
385 results_ = GetDevices::Results::Create(
386 std::vector<linked_ptr<api::sessions::Device> >());
387 return true;
390 scoped_ptr<GetDevices::Params> params(GetDevices::Params::Create(*args_));
391 EXTENSION_FUNCTION_VALIDATE(params);
392 if (params->filter && params->filter->max_results) {
393 EXTENSION_FUNCTION_VALIDATE(*params->filter->max_results >= 0 &&
394 *params->filter->max_results <= api::sessions::MAX_SESSION_RESULTS);
397 std::vector<linked_ptr<api::sessions::Device> > result;
398 // Sort sessions from most recent to least recent.
399 std::sort(sessions.begin(), sessions.end(), SortSessionsByRecency);
400 for (size_t i = 0; i < sessions.size(); ++i) {
401 result.push_back(make_linked_ptr(CreateDeviceModel(sessions[i]).release()));
404 results_ = GetDevices::Results::Create(result);
405 return true;
408 void SessionsRestoreFunction::SetInvalidIdError(const std::string& invalid_id) {
409 SetError(ErrorUtils::FormatErrorMessage(kInvalidSessionIdError, invalid_id));
413 void SessionsRestoreFunction::SetResultRestoredTab(
414 content::WebContents* contents) {
415 scoped_ptr<base::DictionaryValue> tab_value(
416 ExtensionTabUtil::CreateTabValue(contents, extension()));
417 scoped_ptr<tabs::Tab> tab(tabs::Tab::FromValue(*tab_value));
418 scoped_ptr<api::sessions::Session> restored_session(CreateSessionModelHelper(
419 base::Time::Now().ToTimeT(),
420 tab.Pass(),
421 scoped_ptr<windows::Window>()));
422 results_ = Restore::Results::Create(*restored_session);
425 bool SessionsRestoreFunction::SetResultRestoredWindow(int window_id) {
426 WindowController* controller = NULL;
427 if (!windows_util::GetWindowFromWindowID(this, window_id, 0, &controller)) {
428 // error_ is set by GetWindowFromWindowId function call.
429 return false;
431 scoped_ptr<base::DictionaryValue> window_value(
432 controller->CreateWindowValueWithTabs(extension()));
433 scoped_ptr<windows::Window> window(windows::Window::FromValue(
434 *window_value));
435 results_ = Restore::Results::Create(*CreateSessionModelHelper(
436 base::Time::Now().ToTimeT(),
437 scoped_ptr<tabs::Tab>(),
438 window.Pass()));
439 return true;
442 bool SessionsRestoreFunction::RestoreMostRecentlyClosed(Browser* browser) {
443 TabRestoreService* tab_restore_service =
444 TabRestoreServiceFactory::GetForProfile(GetProfile());
445 chrome::HostDesktopType host_desktop_type = browser->host_desktop_type();
446 TabRestoreService::Entries entries = tab_restore_service->entries();
448 if (entries.empty()) {
449 SetError(kNoRecentlyClosedSessionsError);
450 return false;
453 bool is_window = is_window_entry(entries.front());
454 TabRestoreServiceDelegate* delegate =
455 TabRestoreServiceDelegate::FindDelegateForWebContents(
456 browser->tab_strip_model()->GetActiveWebContents());
457 std::vector<content::WebContents*> contents =
458 tab_restore_service->RestoreMostRecentEntry(delegate, host_desktop_type);
459 DCHECK(contents.size());
461 if (is_window) {
462 return SetResultRestoredWindow(
463 ExtensionTabUtil::GetWindowIdOfTab(contents[0]));
466 SetResultRestoredTab(contents[0]);
467 return true;
470 bool SessionsRestoreFunction::RestoreLocalSession(const SessionId& session_id,
471 Browser* browser) {
472 TabRestoreService* tab_restore_service =
473 TabRestoreServiceFactory::GetForProfile(GetProfile());
474 chrome::HostDesktopType host_desktop_type = browser->host_desktop_type();
475 TabRestoreService::Entries entries = tab_restore_service->entries();
477 if (entries.empty()) {
478 SetInvalidIdError(session_id.ToString());
479 return false;
482 // Check if the recently closed list contains an entry with the provided id.
483 bool is_window = false;
484 for (TabRestoreService::Entries::iterator it = entries.begin();
485 it != entries.end(); ++it) {
486 if ((*it)->id == session_id.id()) {
487 // The only time a full window is being restored is if the entry ID
488 // matches the provided ID and the entry type is Window.
489 is_window = is_window_entry(*it);
490 break;
494 TabRestoreServiceDelegate* delegate =
495 TabRestoreServiceDelegate::FindDelegateForWebContents(
496 browser->tab_strip_model()->GetActiveWebContents());
497 std::vector<content::WebContents*> contents =
498 tab_restore_service->RestoreEntryById(delegate,
499 session_id.id(),
500 host_desktop_type,
501 UNKNOWN);
502 // If the ID is invalid, contents will be empty.
503 if (!contents.size()) {
504 SetInvalidIdError(session_id.ToString());
505 return false;
508 // Retrieve the window through any of the tabs in contents.
509 if (is_window) {
510 return SetResultRestoredWindow(
511 ExtensionTabUtil::GetWindowIdOfTab(contents[0]));
514 SetResultRestoredTab(contents[0]);
515 return true;
518 bool SessionsRestoreFunction::RestoreForeignSession(const SessionId& session_id,
519 Browser* browser) {
520 ProfileSyncService* service =
521 ProfileSyncServiceFactory::GetInstance()->GetForProfile(GetProfile());
522 if (!(service && service->GetPreferredDataTypes().Has(syncer::SESSIONS))) {
523 SetError(kSessionSyncError);
524 return false;
526 sync_driver::OpenTabsUIDelegate* open_tabs = service->GetOpenTabsUIDelegate();
527 if (!open_tabs) {
528 SetError(kSessionSyncError);
529 return false;
532 const sessions::SessionTab* tab = NULL;
533 if (open_tabs->GetForeignTab(session_id.session_tag(),
534 session_id.id(),
535 &tab)) {
536 TabStripModel* tab_strip = browser->tab_strip_model();
537 content::WebContents* contents = tab_strip->GetActiveWebContents();
539 content::WebContents* tab_contents =
540 SessionRestore::RestoreForeignSessionTab(contents, *tab,
541 NEW_FOREGROUND_TAB);
542 SetResultRestoredTab(tab_contents);
543 return true;
546 // Restoring a full window.
547 std::vector<const sessions::SessionWindow*> windows;
548 if (!open_tabs->GetForeignSession(session_id.session_tag(), &windows)) {
549 SetInvalidIdError(session_id.ToString());
550 return false;
553 std::vector<const sessions::SessionWindow*>::const_iterator window =
554 windows.begin();
555 while (window != windows.end()
556 && (*window)->window_id.id() != session_id.id()) {
557 ++window;
559 if (window == windows.end()) {
560 SetInvalidIdError(session_id.ToString());
561 return false;
564 chrome::HostDesktopType host_desktop_type = browser->host_desktop_type();
565 // Only restore one window at a time.
566 std::vector<Browser*> browsers = SessionRestore::RestoreForeignSessionWindows(
567 GetProfile(), host_desktop_type, window, window + 1);
568 // Will always create one browser because we only restore one window per call.
569 DCHECK_EQ(1u, browsers.size());
570 return SetResultRestoredWindow(ExtensionTabUtil::GetWindowId(browsers[0]));
573 bool SessionsRestoreFunction::RunSync() {
574 scoped_ptr<Restore::Params> params(Restore::Params::Create(*args_));
575 EXTENSION_FUNCTION_VALIDATE(params);
577 Browser* browser = chrome::FindBrowserWithProfile(
578 GetProfile(), chrome::HOST_DESKTOP_TYPE_NATIVE);
579 if (!browser) {
580 SetError(kNoBrowserToRestoreSession);
581 return false;
584 if (GetProfile() != GetProfile()->GetOriginalProfile()) {
585 SetError(kRestoreInIncognitoError);
586 return false;
589 if (!params->session_id)
590 return RestoreMostRecentlyClosed(browser);
592 scoped_ptr<SessionId> session_id(SessionId::Parse(*params->session_id));
593 if (!session_id) {
594 SetInvalidIdError(*params->session_id);
595 return false;
598 return session_id->IsForeign() ?
599 RestoreForeignSession(*session_id, browser)
600 : RestoreLocalSession(*session_id, browser);
603 SessionsEventRouter::SessionsEventRouter(Profile* profile)
604 : profile_(profile),
605 tab_restore_service_(TabRestoreServiceFactory::GetForProfile(profile)) {
606 // TabRestoreServiceFactory::GetForProfile() can return NULL (i.e., when in
607 // incognito mode)
608 if (tab_restore_service_) {
609 tab_restore_service_->LoadTabsFromLastSession();
610 tab_restore_service_->AddObserver(this);
614 SessionsEventRouter::~SessionsEventRouter() {
615 if (tab_restore_service_)
616 tab_restore_service_->RemoveObserver(this);
619 void SessionsEventRouter::TabRestoreServiceChanged(
620 TabRestoreService* service) {
621 scoped_ptr<base::ListValue> args(new base::ListValue());
622 EventRouter::Get(profile_)->BroadcastEvent(make_scoped_ptr(
623 new Event(events::SESSIONS_ON_CHANGED,
624 api::sessions::OnChanged::kEventName, args.Pass())));
627 void SessionsEventRouter::TabRestoreServiceDestroyed(
628 TabRestoreService* service) {
629 tab_restore_service_ = NULL;
632 SessionsAPI::SessionsAPI(content::BrowserContext* context)
633 : browser_context_(context) {
634 EventRouter::Get(browser_context_)->RegisterObserver(this,
635 api::sessions::OnChanged::kEventName);
638 SessionsAPI::~SessionsAPI() {
641 void SessionsAPI::Shutdown() {
642 EventRouter::Get(browser_context_)->UnregisterObserver(this);
645 static base::LazyInstance<BrowserContextKeyedAPIFactory<SessionsAPI> >
646 g_factory = LAZY_INSTANCE_INITIALIZER;
648 BrowserContextKeyedAPIFactory<SessionsAPI>*
649 SessionsAPI::GetFactoryInstance() {
650 return g_factory.Pointer();
653 void SessionsAPI::OnListenerAdded(const EventListenerInfo& details) {
654 sessions_event_router_.reset(
655 new SessionsEventRouter(Profile::FromBrowserContext(browser_context_)));
656 EventRouter::Get(browser_context_)->UnregisterObserver(this);
659 } // namespace extensions