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.
4
5 #include "chrome/browser/extensions/api/sessions/sessions_api.h"
6
7 #include <vector>
8
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"
42
43 namespace extensions {
44
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;
50
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.";
59
60 // Comparator function for use with std::sort that will sort sessions by
61 // descending modified_time (i.e., most recent first).
SortSessionsByRecency(const browser_sync::SyncedSession * s1,const browser_sync::SyncedSession * s2)62 bool SortSessionsByRecency(const browser_sync::SyncedSession* s1,
63 const browser_sync::SyncedSession* s2) {
64 return s1->modified_time > s2->modified_time;
65 }
66
67 // Comparator function for use with std::sort that will sort tabs in a window
68 // by descending timestamp (i.e., most recent first).
SortTabsByRecency(const SessionTab * t1,const SessionTab * t2)69 bool SortTabsByRecency(const SessionTab* t1, const SessionTab* t2) {
70 return t1->timestamp > t2->timestamp;
71 }
72
CreateTabModelHelper(Profile * profile,const sessions::SerializedNavigationEntry & current_navigation,const std::string & session_id,int index,bool pinned,int selected_index,const Extension * extension)73 scoped_ptr<tabs::Tab> CreateTabModelHelper(
74 Profile* profile,
75 const sessions::SerializedNavigationEntry& current_navigation,
76 const std::string& session_id,
77 int index,
78 bool pinned,
79 int selected_index,
80 const Extension* extension) {
81 scoped_ptr<tabs::Tab> tab_struct(new tabs::Tab);
82
83 GURL gurl = current_navigation.virtual_url();
84 std::string title = base::UTF16ToUTF8(current_navigation.title());
85
86 tab_struct->session_id.reset(new std::string(session_id));
87 tab_struct->url.reset(new std::string(gurl.spec()));
88 if (!title.empty()) {
89 tab_struct->title.reset(new std::string(title));
90 } else {
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))));
95 }
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();
104 }
105
CreateWindowModelHelper(scoped_ptr<std::vector<linked_ptr<tabs::Tab>>> tabs,const std::string & session_id,const windows::Window::Type & type,const windows::Window::State & state)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();
120 }
121
CreateSessionModelHelper(int last_modified,scoped_ptr<tabs::Tab> tab,scoped_ptr<windows::Window> window)122 scoped_ptr<api::sessions::Session> CreateSessionModelHelper(
123 int last_modified,
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;
128 if (tab)
129 session_struct->tab = tab.Pass();
130 else if (window)
131 session_struct->window = window.Pass();
132 else
133 NOTREACHED();
134 return session_struct.Pass();
135 }
136
is_tab_entry(const TabRestoreService::Entry * entry)137 bool is_tab_entry(const TabRestoreService::Entry* entry) {
138 return entry->type == TabRestoreService::TAB;
139 }
140
is_window_entry(const TabRestoreService::Entry * entry)141 bool is_window_entry(const TabRestoreService::Entry* entry) {
142 return entry->type == TabRestoreService::WINDOW;
143 }
144
CreateTabModel(const TabRestoreService::Tab & tab,int session_id,int selected_index)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),
150 tab.tabstrip_index,
151 tab.pinned,
152 selected_index,
153 extension());
154 }
155
156 scoped_ptr<windows::Window>
CreateWindowModel(const TabRestoreService::Window & window,int session_id)157 SessionsGetRecentlyClosedFunction::CreateWindowModel(
158 const TabRestoreService::Window& window,
159 int session_id) {
160 DCHECK(!window.tabs.empty());
161
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()));
168 }
169
170 return CreateWindowModelHelper(tabs.Pass(),
171 base::IntToString(session_id),
172 windows::Window::TYPE_NORMAL,
173 windows::Window::STATE_NORMAL);
174 }
175
176 scoped_ptr<api::sessions::Session>
CreateSessionModel(const TabRestoreService::Entry * entry)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);
185 break;
186 case TabRestoreService::WINDOW:
187 window = CreateWindowModel(
188 *static_cast<const TabRestoreService::Window*>(entry), entry->id);
189 break;
190 default:
191 NOTREACHED();
192 }
193 return CreateSessionModelHelper(entry->timestamp.ToTimeT(),
194 tab.Pass(),
195 window.Pass());
196 }
197
RunSync()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);
207
208 std::vector<linked_ptr<api::sessions::Session> > result;
209 TabRestoreService* tab_restore_service =
210 TabRestoreServiceFactory::GetForProfile(GetProfile());
211
212 // TabRestoreServiceFactory::GetForProfile() can return NULL (i.e., when in
213 // incognito mode)
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> >());
219 return true;
220 }
221
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;
228 ++it) {
229 TabRestoreService::Entry* entry = *it;
230 result.push_back(make_linked_ptr(CreateSessionModel(entry).release()));
231 }
232
233 results_ = GetRecentlyClosed::Results::Create(result);
234 return true;
235 }
236
CreateTabModel(const std::string & session_tag,const SessionTab & tab,int tab_index,int selected_index)237 scoped_ptr<tabs::Tab> SessionsGetDevicesFunction::CreateTabModel(
238 const std::string& session_tag,
239 const SessionTab& tab,
240 int tab_index,
241 int selected_index) {
242 std::string session_id = SessionId(session_tag, tab.tab_id.id()).ToString();
243 return CreateTabModelHelper(
244 GetProfile(),
245 tab.navigations[tab.normalized_navigation_index()],
246 session_id,
247 tab_index,
248 tab.pinned,
249 selected_index,
250 extension());
251 }
252
CreateWindowModel(const SessionWindow & window,const std::string & session_tag)253 scoped_ptr<windows::Window> SessionsGetDevicesFunction::CreateWindowModel(
254 const SessionWindow& window, const std::string& session_tag) {
255 DCHECK(!window.tabs.empty());
256
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())
263 continue;
264 const sessions::SerializedNavigationEntry& current_navigation =
265 tab->navigations.at(tab->normalized_navigation_index());
266 if (chrome::IsNTPURL(current_navigation.virtual_url(), GetProfile())) {
267 continue;
268 }
269 tabs_in_window.push_back(tab);
270 }
271 if (tabs_in_window.empty())
272 return scoped_ptr<windows::Window>();
273 std::sort(tabs_in_window.begin(), tabs_in_window.end(), SortTabsByRecency);
274
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()));
281 }
282
283 std::string session_id =
284 SessionId(session_tag, window.window_id.id()).ToString();
285
286 windows::Window::Type type = windows::Window::TYPE_NONE;
287 switch (window.type) {
288 case Browser::TYPE_TABBED:
289 type = windows::Window::TYPE_NORMAL;
290 break;
291 case Browser::TYPE_POPUP:
292 type = windows::Window::TYPE_POPUP;
293 break;
294 }
295
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;
300 break;
301 case ui::SHOW_STATE_MINIMIZED:
302 state = windows::Window::STATE_MINIMIZED;
303 break;
304 case ui::SHOW_STATE_MAXIMIZED:
305 state = windows::Window::STATE_MAXIMIZED;
306 break;
307 case ui::SHOW_STATE_FULLSCREEN:
308 state = windows::Window::STATE_FULLSCREEN;
309 break;
310 case ui::SHOW_STATE_DEFAULT:
311 case ui::SHOW_STATE_INACTIVE:
312 case ui::SHOW_STATE_END:
313 break;
314 }
315
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()));
324
325 return window_struct.Pass();
326 }
327
328 scoped_ptr<api::sessions::Session>
CreateSessionModel(const SessionWindow & window,const std::string & session_tag)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
334 // empty.
335 return !window_model ? scoped_ptr<api::sessions::Session>()
336 : CreateSessionModelHelper(window.timestamp.ToTimeT(),
337 scoped_ptr<tabs::Tab>(),
338 window_model.Pass());
339 }
340
CreateDeviceModel(const browser_sync::SyncedSession * session)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;
348
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;
352
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));
358 if (session_model)
359 device_struct->sessions.push_back(make_linked_ptr(
360 session_model.release()));
361 }
362 return device_struct.Pass();
363 }
364
RunSync()365 bool SessionsGetDevicesFunction::RunSync() {
366 ProfileSyncService* service =
367 ProfileSyncServiceFactory::GetInstance()->GetForProfile(GetProfile());
368 if (!(service && service->GetPreferredDataTypes().Has(syncer::SESSIONS))) {
369 // Sync not enabled.
370 results_ = GetDevices::Results::Create(
371 std::vector<linked_ptr<api::sessions::Device> >());
372 return true;
373 }
374
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> >());
381 return true;
382 }
383
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);
389 }
390
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()));
396 }
397
398 results_ = GetDevices::Results::Create(result);
399 return true;
400 }
401
SetInvalidIdError(const std::string & invalid_id)402 void SessionsRestoreFunction::SetInvalidIdError(const std::string& invalid_id) {
403 SetError(ErrorUtils::FormatErrorMessage(kInvalidSessionIdError, invalid_id));
404 }
405
406
SetResultRestoredTab(content::WebContents * contents)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(),
414 tab.Pass(),
415 scoped_ptr<windows::Window>()));
416 results_ = Restore::Results::Create(*restored_session);
417 }
418
SetResultRestoredWindow(int window_id)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.
423 return false;
424 }
425 scoped_ptr<base::DictionaryValue> window_value(
426 controller->CreateWindowValueWithTabs(extension()));
427 scoped_ptr<windows::Window> window(windows::Window::FromValue(
428 *window_value));
429 results_ = Restore::Results::Create(*CreateSessionModelHelper(
430 base::Time::Now().ToTimeT(),
431 scoped_ptr<tabs::Tab>(),
432 window.Pass()));
433 return true;
434 }
435
RestoreMostRecentlyClosed(Browser * browser)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();
441
442 if (entries.empty()) {
443 SetError(kNoRecentlyClosedSessionsError);
444 return false;
445 }
446
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());
454
455 if (is_window) {
456 return SetResultRestoredWindow(
457 ExtensionTabUtil::GetWindowIdOfTab(contents[0]));
458 }
459
460 SetResultRestoredTab(contents[0]);
461 return true;
462 }
463
RestoreLocalSession(const SessionId & session_id,Browser * browser)464 bool SessionsRestoreFunction::RestoreLocalSession(const SessionId& session_id,
465 Browser* browser) {
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();
470
471 if (entries.empty()) {
472 SetInvalidIdError(session_id.ToString());
473 return false;
474 }
475
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);
484 break;
485 }
486 }
487
488 TabRestoreServiceDelegate* delegate =
489 TabRestoreServiceDelegate::FindDelegateForWebContents(
490 browser->tab_strip_model()->GetActiveWebContents());
491 std::vector<content::WebContents*> contents =
492 tab_restore_service->RestoreEntryById(delegate,
493 session_id.id(),
494 host_desktop_type,
495 UNKNOWN);
496 // If the ID is invalid, contents will be empty.
497 if (!contents.size()) {
498 SetInvalidIdError(session_id.ToString());
499 return false;
500 }
501
502 // Retrieve the window through any of the tabs in contents.
503 if (is_window) {
504 return SetResultRestoredWindow(
505 ExtensionTabUtil::GetWindowIdOfTab(contents[0]));
506 }
507
508 SetResultRestoredTab(contents[0]);
509 return true;
510 }
511
RestoreForeignSession(const SessionId & session_id,Browser * browser)512 bool SessionsRestoreFunction::RestoreForeignSession(const SessionId& session_id,
513 Browser* browser) {
514 ProfileSyncService* service =
515 ProfileSyncServiceFactory::GetInstance()->GetForProfile(GetProfile());
516 if (!(service && service->GetPreferredDataTypes().Has(syncer::SESSIONS))) {
517 SetError(kSessionSyncError);
518 return false;
519 }
520 browser_sync::OpenTabsUIDelegate* open_tabs =
521 service->GetOpenTabsUIDelegate();
522 if (!open_tabs) {
523 SetError(kSessionSyncError);
524 return false;
525 }
526
527 const SessionTab* tab = NULL;
528 if (open_tabs->GetForeignTab(session_id.session_tag(),
529 session_id.id(),
530 &tab)) {
531 TabStripModel* tab_strip = browser->tab_strip_model();
532 content::WebContents* contents = tab_strip->GetActiveWebContents();
533
534 content::WebContents* tab_contents =
535 SessionRestore::RestoreForeignSessionTab(contents, *tab,
536 NEW_FOREGROUND_TAB);
537 SetResultRestoredTab(tab_contents);
538 return true;
539 }
540
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());
545 return false;
546 }
547
548 std::vector<const SessionWindow*>::const_iterator window = windows.begin();
549 while (window != windows.end()
550 && (*window)->window_id.id() != session_id.id()) {
551 ++window;
552 }
553 if (window == windows.end()) {
554 SetInvalidIdError(session_id.ToString());
555 return false;
556 }
557
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]));
565 }
566
RunSync()567 bool SessionsRestoreFunction::RunSync() {
568 scoped_ptr<Restore::Params> params(Restore::Params::Create(*args_));
569 EXTENSION_FUNCTION_VALIDATE(params);
570
571 Browser* browser = chrome::FindBrowserWithProfile(
572 GetProfile(), chrome::HOST_DESKTOP_TYPE_NATIVE);
573 if (!browser) {
574 SetError(kNoBrowserToRestoreSession);
575 return false;
576 }
577
578 if (GetProfile() != GetProfile()->GetOriginalProfile()) {
579 SetError(kRestoreInIncognitoError);
580 return false;
581 }
582
583 if (!params->session_id)
584 return RestoreMostRecentlyClosed(browser);
585
586 scoped_ptr<SessionId> session_id(SessionId::Parse(*params->session_id));
587 if (!session_id) {
588 SetInvalidIdError(*params->session_id);
589 return false;
590 }
591
592 return session_id->IsForeign() ?
593 RestoreForeignSession(*session_id, browser)
594 : RestoreLocalSession(*session_id, browser);
595 }
596
SessionsEventRouter(Profile * profile)597 SessionsEventRouter::SessionsEventRouter(Profile* profile)
598 : profile_(profile),
599 tab_restore_service_(TabRestoreServiceFactory::GetForProfile(profile)) {
600 // TabRestoreServiceFactory::GetForProfile() can return NULL (i.e., when in
601 // incognito mode)
602 if (tab_restore_service_) {
603 tab_restore_service_->LoadTabsFromLastSession();
604 tab_restore_service_->AddObserver(this);
605 }
606 }
607
~SessionsEventRouter()608 SessionsEventRouter::~SessionsEventRouter() {
609 if (tab_restore_service_)
610 tab_restore_service_->RemoveObserver(this);
611 }
612
TabRestoreServiceChanged(TabRestoreService * service)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())));
618 }
619
TabRestoreServiceDestroyed(TabRestoreService * service)620 void SessionsEventRouter::TabRestoreServiceDestroyed(
621 TabRestoreService* service) {
622 tab_restore_service_ = NULL;
623 }
624
SessionsAPI(content::BrowserContext * context)625 SessionsAPI::SessionsAPI(content::BrowserContext* context)
626 : browser_context_(context) {
627 EventRouter::Get(browser_context_)->RegisterObserver(this,
628 api::sessions::OnChanged::kEventName);
629 }
630
~SessionsAPI()631 SessionsAPI::~SessionsAPI() {
632 }
633
Shutdown()634 void SessionsAPI::Shutdown() {
635 EventRouter::Get(browser_context_)->UnregisterObserver(this);
636 }
637
638 static base::LazyInstance<BrowserContextKeyedAPIFactory<SessionsAPI> >
639 g_factory = LAZY_INSTANCE_INITIALIZER;
640
641 BrowserContextKeyedAPIFactory<SessionsAPI>*
GetFactoryInstance()642 SessionsAPI::GetFactoryInstance() {
643 return g_factory.Pointer();
644 }
645
OnListenerAdded(const EventListenerInfo & details)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);
650 }
651
652 } // namespace extensions
653