Prevent chrome://net-internals/#export from flickering
[chromium-blink-merge.git] / chrome / browser / sessions / session_service.h
blobca409cfe9aede8e262b12d24e15a4fdee8d662bd
1 // Copyright (c) 2012 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 #ifndef CHROME_BROWSER_SESSIONS_SESSION_SERVICE_H_
6 #define CHROME_BROWSER_SESSIONS_SESSION_SERVICE_H_
8 #include <map>
9 #include <string>
11 #include "base/basictypes.h"
12 #include "base/callback.h"
13 #include "base/memory/scoped_vector.h"
14 #include "base/memory/weak_ptr.h"
15 #include "base/task/cancelable_task_tracker.h"
16 #include "base/time/time.h"
17 #include "chrome/browser/defaults.h"
18 #include "chrome/browser/sessions/base_session_service_delegate_impl.h"
19 #include "chrome/browser/sessions/session_service_utils.h"
20 #include "chrome/browser/ui/browser.h"
21 #include "chrome/browser/ui/browser_finder.h"
22 #include "chrome/browser/ui/browser_list_observer.h"
23 #include "components/keyed_service/core/keyed_service.h"
24 #include "components/sessions/session_service_commands.h"
25 #include "content/public/browser/notification_observer.h"
26 #include "content/public/browser/notification_registrar.h"
27 #include "ui/base/ui_base_types.h"
29 class Profile;
31 namespace content {
32 class NavigationEntry;
33 class WebContents;
34 } // namespace content
36 namespace sessions {
37 class SessionCommand;
38 struct SessionTab;
39 struct SessionWindow;
40 } // namespace sessions
42 // SessionService ------------------------------------------------------------
44 // SessionService is responsible for maintaining the state of open windows
45 // and tabs so that they can be restored at a later date. The state of the
46 // currently open browsers is referred to as the current session.
48 // SessionService supports restoring from the last session. The last session
49 // typically corresponds to the last run of the browser, but not always. For
50 // example, if the user has a tabbed browser and app window running, closes the
51 // tabbed browser, then creates a new tabbed browser the current session is made
52 // the last session and the current session reset. This is done to provide the
53 // illusion that app windows run in separate processes. Similar behavior occurs
54 // with incognito windows.
56 // SessionService itself uses functions from session_service_commands to store
57 // commands which can rebuild the open state of the browser (as |SessionWindow|,
58 // |SessionTab| and |SerializedNavigationEntry|). The commands are periodically
59 // flushed to |SessionBackend| and written to a file. Every so often
60 // |SessionService| rebuilds the contents of the file from the open state of the
61 // browser.
62 class SessionService : public BaseSessionServiceDelegateImpl,
63 public KeyedService,
64 public content::NotificationObserver,
65 public chrome::BrowserListObserver {
66 friend class SessionServiceTestHelper;
67 public:
68 // Used to distinguish an application from a ordinary content window.
69 enum AppType {
70 TYPE_APP,
71 TYPE_NORMAL
74 // Creates a SessionService for the specified profile.
75 explicit SessionService(Profile* profile);
76 // For testing.
77 explicit SessionService(const base::FilePath& save_path);
79 ~SessionService() override;
81 // This may be NULL during testing.
82 Profile* profile() const { return profile_; }
84 // Returns true if a new window opening should really be treated like the
85 // start of a session (with potential session restore, startup URLs, etc.).
86 // In particular, this is true if there are no tabbed browsers running
87 // currently (eg. because only background or other app pages are running).
88 bool ShouldNewWindowStartSession();
90 // Invoke at a point when you think session restore might occur. For example,
91 // during startup and window creation this is invoked to see if a session
92 // needs to be restored. If a session needs to be restored it is done so
93 // asynchronously and true is returned. If false is returned the session was
94 // not restored and the caller needs to create a new window.
95 bool RestoreIfNecessary(const std::vector<GURL>& urls_to_open);
97 // Resets the contents of the file from the current state of all open
98 // browsers whose profile matches our profile.
99 void ResetFromCurrentBrowsers();
101 // Moves the current session to the last session. This is useful when a
102 // checkpoint occurs, such as when the user launches the app and no tabbed
103 // browsers are running.
104 void MoveCurrentSessionToLastSession();
106 // Deletes the last session.
107 void DeleteLastSession();
109 // Associates a tab with a window.
110 void SetTabWindow(const SessionID& window_id,
111 const SessionID& tab_id);
113 // Sets the bounds of a window.
114 void SetWindowBounds(const SessionID& window_id,
115 const gfx::Rect& bounds,
116 ui::WindowShowState show_state);
118 // Sets the visual index of the tab in its parent window.
119 void SetTabIndexInWindow(const SessionID& window_id,
120 const SessionID& tab_id,
121 int new_index);
123 // Sets the pinned state of the tab.
124 void SetPinnedState(const SessionID& window_id,
125 const SessionID& tab_id,
126 bool is_pinned);
128 // Notification that a tab has been closed. |closed_by_user_gesture| comes
129 // from |WebContents::closed_by_user_gesture|; see it for details.
131 // Note: this is invoked from the NavigationController's destructor, which is
132 // after the actual tab has been removed.
133 void TabClosed(const SessionID& window_id,
134 const SessionID& tab_id,
135 bool closed_by_user_gesture);
137 // Notification a window has opened.
138 void WindowOpened(Browser* browser);
140 // Notification the window is about to close.
141 void WindowClosing(const SessionID& window_id);
143 // Notification a window has finished closing.
144 void WindowClosed(const SessionID& window_id);
146 // Called when a tab is inserted.
147 void TabInserted(content::WebContents* contents);
149 // Called when a tab is closing.
150 void TabClosing(content::WebContents* contents);
152 // Sets the type of window. In order for the contents of a window to be
153 // tracked SetWindowType must be invoked with a type we track
154 // (ShouldRestoreOfWindowType returns true).
155 void SetWindowType(const SessionID& window_id,
156 Browser::Type type,
157 AppType app_type);
159 // Sets the application name of the specified window.
160 void SetWindowAppName(const SessionID& window_id,
161 const std::string& app_name);
163 // Invoked when the NavigationController has removed entries from the back of
164 // the list. |count| gives the number of entries in the navigation controller.
165 void TabNavigationPathPrunedFromBack(const SessionID& window_id,
166 const SessionID& tab_id,
167 int count);
169 // Invoked when the NavigationController has removed entries from the front of
170 // the list. |count| gives the number of entries that were removed.
171 void TabNavigationPathPrunedFromFront(const SessionID& window_id,
172 const SessionID& tab_id,
173 int count);
175 // Updates the navigation entry for the specified tab.
176 void UpdateTabNavigation(
177 const SessionID& window_id,
178 const SessionID& tab_id,
179 const sessions::SerializedNavigationEntry& navigation);
181 // Notification that a tab has restored its entries or a closed tab is being
182 // reused.
183 void TabRestored(content::WebContents* tab, bool pinned);
185 // Sets the index of the selected entry in the navigation controller for the
186 // specified tab.
187 void SetSelectedNavigationIndex(const SessionID& window_id,
188 const SessionID& tab_id,
189 int index);
191 // Sets the index of the selected tab in the specified window.
192 void SetSelectedTabInWindow(const SessionID& window_id, int index);
194 // Sets the user agent override of the specified tab.
195 void SetTabUserAgentOverride(const SessionID& window_id,
196 const SessionID& tab_id,
197 const std::string& user_agent_override);
199 // Sets the application extension id of the specified tab.
200 void SetTabExtensionAppID(const SessionID& window_id,
201 const SessionID& tab_id,
202 const std::string& extension_app_id);
204 // Callback from GetLastSession.
205 // The second parameter is the id of the window that was last active.
206 typedef base::Callback<void(ScopedVector<sessions::SessionWindow>,
207 SessionID::id_type)> SessionCallback;
209 // Fetches the contents of the last session, notifying the callback when
210 // done. If the callback is supplied an empty vector of SessionWindows
211 // it means the session could not be restored.
212 base::CancelableTaskTracker::TaskId GetLastSession(
213 const SessionCallback& callback,
214 base::CancelableTaskTracker* tracker);
216 // BaseSessionServiceDelegateImpl:
217 void OnSavedCommands() override;
219 private:
220 // Allow tests to access our innards for testing purposes.
221 FRIEND_TEST_ALL_PREFIXES(SessionServiceTest, SavedSessionNotification);
222 FRIEND_TEST_ALL_PREFIXES(SessionServiceTest, RestoreActivation1);
223 FRIEND_TEST_ALL_PREFIXES(SessionServiceTest, RestoreActivation2);
224 FRIEND_TEST_ALL_PREFIXES(SessionServiceTest, RemoveUnusedRestoreWindowsTest);
225 FRIEND_TEST_ALL_PREFIXES(NoStartupWindowTest, DontInitSessionServiceForApps);
227 typedef std::map<SessionID::id_type, std::pair<int, int> > IdToRange;
229 void Init();
231 // Returns true if a window of given |window_type| and |app_type| should get
232 // restored upon session restore.
233 bool ShouldRestoreWindowOfType(sessions::SessionWindow::WindowType type,
234 AppType app_type) const;
236 // Removes unrestorable windows from the previous windows list.
237 void RemoveUnusedRestoreWindows(
238 std::vector<sessions::SessionWindow*>* window_list);
240 // Implementation of RestoreIfNecessary. If |browser| is non-null and we need
241 // to restore, the tabs are added to it, otherwise a new browser is created.
242 bool RestoreIfNecessary(const std::vector<GURL>& urls_to_open,
243 Browser* browser);
245 void Observe(int type,
246 const content::NotificationSource& source,
247 const content::NotificationDetails& details) override;
249 // chrome::BrowserListObserver
250 void OnBrowserAdded(Browser* browser) override {}
251 void OnBrowserRemoved(Browser* browser) override {}
252 void OnBrowserSetLastActive(Browser* browser) override;
254 // Converts |commands| to SessionWindows and notifies the callback.
255 void OnGotSessionCommands(const SessionCallback& callback,
256 ScopedVector<sessions::SessionCommand> commands);
258 // Adds commands to commands that will recreate the state of the specified
259 // tab. This adds at most kMaxNavigationCountToPersist navigations (in each
260 // direction from the current navigation index).
261 // A pair is added to tab_to_available_range indicating the range of
262 // indices that were written.
263 void BuildCommandsForTab(
264 const SessionID& window_id,
265 content::WebContents* tab,
266 int index_in_window,
267 bool is_pinned,
268 IdToRange* tab_to_available_range);
270 // Adds commands to create the specified browser, and invokes
271 // BuildCommandsForTab for each of the tabs in the browser. This ignores
272 // any tabs not in the profile we were created with.
273 void BuildCommandsForBrowser(
274 Browser* browser,
275 IdToRange* tab_to_available_range,
276 std::set<SessionID::id_type>* windows_to_track);
278 // Iterates over all the known browsers invoking BuildCommandsForBrowser.
279 // This only adds browsers that should be tracked (|ShouldRestoreWindowOfType|
280 // returns true). All browsers that are tracked are added to windows_to_track
281 // (as long as it is non-null).
282 void BuildCommandsFromBrowsers(
283 IdToRange* tab_to_available_range,
284 std::set<SessionID::id_type>* windows_to_track);
286 // Schedules a reset of the existing commands. A reset means the contents
287 // of the file are recreated from the state of the browser.
288 void ScheduleResetCommands();
290 // Schedules the specified command.
291 void ScheduleCommand(scoped_ptr<sessions::SessionCommand> command);
293 // Converts all pending tab/window closes to commands and schedules them.
294 void CommitPendingCloses();
296 // Returns true if there is only one window open with a single tab that shares
297 // our profile.
298 bool IsOnlyOneTabLeft() const;
300 // Returns true if there are open trackable browser windows whose ids do
301 // match |window_id| with our profile. A trackable window is a window from
302 // which |ShouldRestoreWindowOfType| returns true. See
303 // |ShouldRestoreWindowOfType| for details.
304 bool HasOpenTrackableBrowsers(const SessionID& window_id) const;
306 // Returns true if changes to tabs in the specified window should be tracked.
307 bool ShouldTrackChangesToWindow(const SessionID& window_id) const;
309 // Returns true if we track changes to the specified browser.
310 bool ShouldTrackBrowser(Browser* browser) const;
312 // Call when certain session relevant notifications
313 // (tab_closed, nav_list_pruned) occur. In addition, this is
314 // currently called when Save() is called to compare how often the
315 // session data is currently saved verses when we may want to save it.
316 // It records the data in UMA stats.
317 void RecordSessionUpdateHistogramData(int type,
318 base::TimeTicks* last_updated_time);
320 // Helper methods to record the histogram data
321 void RecordUpdatedTabClosed(base::TimeDelta delta, bool use_long_period);
322 void RecordUpdatedNavListPruned(base::TimeDelta delta, bool use_long_period);
323 void RecordUpdatedNavEntryCommit(base::TimeDelta delta, bool use_long_period);
324 void RecordUpdatedSaveTime(base::TimeDelta delta, bool use_long_period);
325 void RecordUpdatedSessionNavigationOrTab(base::TimeDelta delta,
326 bool use_long_period);
328 // Deletes session data if no windows are open for the current profile.
329 void MaybeDeleteSessionOnlyData();
331 // Unit test accessors.
332 sessions::BaseSessionService* GetBaseSessionServiceForTest();
334 // The profile. This may be null during testing.
335 Profile* profile_;
337 // The owned BaseSessionService.
338 scoped_ptr<sessions::BaseSessionService> base_session_service_;
340 content::NotificationRegistrar registrar_;
342 // Maps from session tab id to the range of navigation entries that has
343 // been written to disk.
345 // This is only used if not all the navigation entries have been
346 // written.
347 IdToRange tab_to_available_range_;
349 // When the user closes the last window, where the last window is the
350 // last tabbed browser and no more tabbed browsers are open with the same
351 // profile, the window ID is added here. These IDs are only committed (which
352 // marks them as closed) if the user creates a new tabbed browser.
353 typedef std::set<SessionID::id_type> PendingWindowCloseIDs;
354 PendingWindowCloseIDs pending_window_close_ids_;
356 // Set of tabs that have been closed by way of the last window or last tab
357 // closing, but not yet committed.
358 typedef std::set<SessionID::id_type> PendingTabCloseIDs;
359 PendingTabCloseIDs pending_tab_close_ids_;
361 // When a window other than the last window (see description of
362 // pending_window_close_ids) is closed, the id is added to this set.
363 typedef std::set<SessionID::id_type> WindowClosingIDs;
364 WindowClosingIDs window_closing_ids_;
366 // Set of windows we're tracking changes to. This is only browsers that
367 // return true from |ShouldRestoreWindowOfType|.
368 typedef std::set<SessionID::id_type> WindowsTracking;
369 WindowsTracking windows_tracking_;
371 // Are there any open trackable browsers?
372 bool has_open_trackable_browsers_;
374 // If true and a new tabbed browser is created and there are no opened tabbed
375 // browser (has_open_trackable_browsers_ is false), then the current session
376 // is made the last session. See description above class for details on
377 // current/last session.
378 bool move_on_new_browser_;
380 // Used for reporting frequency of session altering operations.
381 base::TimeTicks last_updated_tab_closed_time_;
382 base::TimeTicks last_updated_nav_list_pruned_time_;
383 base::TimeTicks last_updated_nav_entry_commit_time_;
384 base::TimeTicks last_updated_save_time_;
386 // Constants used in calculating histogram data.
387 const base::TimeDelta save_delay_in_millis_;
388 const base::TimeDelta save_delay_in_mins_;
389 const base::TimeDelta save_delay_in_hrs_;
391 // For browser_tests, since we want to simulate the browser shutting down
392 // without quitting.
393 bool force_browser_not_alive_with_no_windows_;
395 base::WeakPtrFactory<SessionService> weak_factory_;
397 DISALLOW_COPY_AND_ASSIGN(SessionService);
400 #endif // CHROME_BROWSER_SESSIONS_SESSION_SERVICE_H_