Merge Chromium + Blink git repositories
[chromium-blink-merge.git] / chrome / browser / profiles / profile_manager.h
blob14158eb93eb9f637faf63cc3f827b933d9e9ef08
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 // This class keeps track of the currently-active profiles in the runtime.
7 #ifndef CHROME_BROWSER_PROFILES_PROFILE_MANAGER_H_
8 #define CHROME_BROWSER_PROFILES_PROFILE_MANAGER_H_
10 #include <list>
11 #include <vector>
13 #include "base/basictypes.h"
14 #include "base/containers/hash_tables.h"
15 #include "base/files/file_path.h"
16 #include "base/gtest_prod_util.h"
17 #include "base/memory/linked_ptr.h"
18 #include "base/memory/scoped_ptr.h"
19 #include "base/message_loop/message_loop.h"
20 #include "base/threading/non_thread_safe.h"
21 #include "chrome/browser/profiles/profile.h"
22 #include "chrome/browser/profiles/profile_shortcut_manager.h"
23 #include "chrome/browser/ui/browser_list_observer.h"
24 #include "content/public/browser/notification_observer.h"
25 #include "content/public/browser/notification_registrar.h"
27 class NewProfileLauncher;
28 class ProfileInfoCache;
30 class ProfileManager : public base::NonThreadSafe,
31 public content::NotificationObserver,
32 public Profile::Delegate {
33 public:
34 typedef base::Callback<void(Profile*, Profile::CreateStatus)> CreateCallback;
36 explicit ProfileManager(const base::FilePath& user_data_dir);
37 ~ProfileManager() override;
39 #if defined(ENABLE_SESSION_SERVICE)
40 // Invokes SessionServiceFactory::ShutdownForProfile() for all profiles.
41 static void ShutdownSessionServices();
42 #endif
44 // Physically remove deleted profile directories from disk.
45 static void NukeDeletedProfilesFromDisk();
47 // Same as instance method but provides the default user_data_dir as well.
48 // If the Profile is going to be used to open a new window then consider using
49 // GetLastUsedProfileAllowedByPolicy() instead.
50 static Profile* GetLastUsedProfile();
52 // Same as GetLastUsedProfile() but returns the incognito Profile if
53 // incognito mode is forced. This should be used if the last used Profile
54 // will be used to open new browser windows.
55 static Profile* GetLastUsedProfileAllowedByPolicy();
57 // Same as instance method but provides the default user_data_dir as well.
58 static std::vector<Profile*> GetLastOpenedProfiles();
60 // Get the profile for the user which created the current session.
61 // Note that in case of a guest account this will return a 'suitable' profile.
62 // This function is temporary and will soon be moved to ash. As such avoid
63 // using it at all cost.
64 // TODO(skuhne): Move into ash's new user management function.
65 static Profile* GetPrimaryUserProfile();
67 // Get the profile for the currently active user.
68 // Note that in case of a guest account this will return a 'suitable' profile.
69 // This function is temporary and will soon be moved to ash. As such avoid
70 // using it at all cost.
71 // TODO(skuhne): Move into ash's new user management function.
72 static Profile* GetActiveUserProfile();
74 // Returns a profile for a specific profile directory within the user data
75 // dir. This will return an existing profile it had already been created,
76 // otherwise it will create and manage it.
77 // Because this method might synchronously create a new profile, it should
78 // only be called for the initial profile or in tests, where blocking is
79 // acceptable.
80 // TODO(bauerb): Migrate calls from other code to GetProfileByPath(), then
81 // make this method private.
82 Profile* GetProfile(const base::FilePath& profile_dir);
84 // Returns total number of profiles available on this machine.
85 size_t GetNumberOfProfiles();
87 // Explicit asynchronous creation of a profile located at |profile_path|.
88 // If the profile has already been created then callback is called
89 // immediately. Should be called on the UI thread.
90 void CreateProfileAsync(const base::FilePath& profile_path,
91 const CreateCallback& callback,
92 const base::string16& name,
93 const base::string16& icon_url,
94 const std::string& supervised_user_id);
96 // Returns true if the profile pointer is known to point to an existing
97 // profile.
98 bool IsValidProfile(Profile* profile);
100 // Returns the directory where the first created profile is stored,
101 // relative to the user data directory currently in use.
102 base::FilePath GetInitialProfileDir();
104 // Get the Profile last used (the Profile to which owns the most recently
105 // focused window) with this Chrome build. If no signed profile has been
106 // stored in Local State, hand back the Default profile.
107 Profile* GetLastUsedProfile(const base::FilePath& user_data_dir);
109 // Get the path of the last used profile, or if that's undefined, the default
110 // profile.
111 base::FilePath GetLastUsedProfileDir(const base::FilePath& user_data_dir);
113 // Get the name of the last used profile, or if that's undefined, the default
114 // profile.
115 std::string GetLastUsedProfileName();
117 // Get the Profiles which are currently open, i.e., have open browsers, or
118 // were open the last time Chrome was running. The Profiles appear in the
119 // order they were opened. The last used profile will be on the list, but its
120 // index on the list will depend on when it was opened (it is not necessarily
121 // the last one).
122 std::vector<Profile*> GetLastOpenedProfiles(
123 const base::FilePath& user_data_dir);
125 // Returns created and fully initialized profiles. Note, profiles order is NOT
126 // guaranteed to be related with the creation order.
127 std::vector<Profile*> GetLoadedProfiles() const;
129 // If a profile with the given path is currently managed by this object and
130 // fully initialized, return a pointer to the corresponding Profile object;
131 // otherwise return null.
132 Profile* GetProfileByPath(const base::FilePath& path) const;
134 // Creates a new profile in the next available multiprofile directory.
135 // Directories are named "profile_1", "profile_2", etc., in sequence of
136 // creation. (Because directories can be removed, however, it may be the case
137 // that at some point the list of numbered profiles is not continuous.)
138 // |callback| may be invoked multiple times (for CREATE_STATUS_INITIALIZED
139 // and CREATE_STATUS_CREATED) so binding parameters with bind::Passed() is
140 // prohibited. Returns the file path to the profile that will be created
141 // asynchronously.
142 static base::FilePath CreateMultiProfileAsync(
143 const base::string16& name,
144 const base::string16& icon_url,
145 const CreateCallback& callback,
146 const std::string& supervised_user_id);
148 // Returns the full path to be used for guest profiles.
149 static base::FilePath GetGuestProfilePath();
151 // Returns the full path to be used for system profiles.
152 static base::FilePath GetSystemProfilePath();
154 // Get the path of the next profile directory and increment the internal
155 // count.
156 // Lack of side effects:
157 // This function doesn't actually create the directory or touch the file
158 // system.
159 base::FilePath GenerateNextProfileDirectoryPath();
161 // Returns a ProfileInfoCache object which can be used to get information
162 // about profiles without having to load them from disk.
163 ProfileInfoCache& GetProfileInfoCache();
165 // Returns a ProfileShortcut Manager that enables the caller to create
166 // profile specfic desktop shortcuts.
167 ProfileShortcutManager* profile_shortcut_manager();
169 // Schedules the profile at the given path to be deleted on shutdown. If we're
170 // deleting the last profile, a new one will be created in its place, and in
171 // that case the callback will be called when profile creation is complete.
172 void ScheduleProfileForDeletion(const base::FilePath& profile_dir,
173 const CreateCallback& callback);
175 // Autoloads profiles if they are running background apps.
176 void AutoloadProfiles();
178 // Checks if any ephemeral profiles are left behind (e.g. because of a browser
179 // crash) and schedule them for deletion.
180 void CleanUpEphemeralProfiles();
182 // Initializes user prefs of |profile|. This includes profile name and
183 // avatar values.
184 void InitProfileUserPrefs(Profile* profile);
186 // Register and add testing profile to the ProfileManager. Use ONLY in tests.
187 // This allows the creation of Profiles outside of the standard creation path
188 // for testing. If |addToCache|, adds to ProfileInfoCache as well.
189 // If |start_deferred_task_runners|, starts the deferred task runners.
190 // Use ONLY in tests.
191 void RegisterTestingProfile(Profile* profile,
192 bool addToCache,
193 bool start_deferred_task_runners);
195 const base::FilePath& user_data_dir() const { return user_data_dir_; }
197 // For ChromeOS, determines if the user has logged in to a real profile.
198 bool IsLoggedIn() const { return logged_in_; }
200 // content::NotificationObserver implementation.
201 void Observe(int type,
202 const content::NotificationSource& source,
203 const content::NotificationDetails& details) override;
205 // Profile::Delegate implementation:
206 void OnProfileCreated(Profile* profile,
207 bool success,
208 bool is_new_profile) override;
210 protected:
211 // Does final initial actions.
212 virtual void DoFinalInit(Profile* profile, bool go_off_the_record);
213 virtual void DoFinalInitForServices(Profile* profile, bool go_off_the_record);
214 virtual void DoFinalInitLogging(Profile* profile);
216 // Creates a new profile by calling into the profile's profile creation
217 // method. Virtual so that unittests can return a TestingProfile instead
218 // of the Profile's result.
219 virtual Profile* CreateProfileHelper(const base::FilePath& path);
221 // Creates a new profile asynchronously by calling into the profile's
222 // asynchronous profile creation method. Virtual so that unittests can return
223 // a TestingProfile instead of the Profile's result.
224 virtual Profile* CreateProfileAsyncHelper(const base::FilePath& path,
225 Delegate* delegate);
227 private:
228 friend class TestingProfileManager;
229 FRIEND_TEST_ALL_PREFIXES(ProfileManagerBrowserTest, DeleteAllProfiles);
230 FRIEND_TEST_ALL_PREFIXES(ProfileManagerBrowserTest, SwitchToProfile);
232 // This struct contains information about profiles which are being loaded or
233 // were loaded.
234 struct ProfileInfo {
235 ProfileInfo(Profile* profile, bool created);
237 ~ProfileInfo();
239 scoped_ptr<Profile> profile;
240 // Whether profile has been fully loaded (created and initialized).
241 bool created;
242 // List of callbacks to run when profile initialization is done. Note, when
243 // profile is fully loaded this vector will be empty.
244 std::vector<CreateCallback> callbacks;
246 private:
247 DISALLOW_COPY_AND_ASSIGN(ProfileInfo);
250 // Returns the profile of the active user and / or the off the record profile
251 // if needed. This adds the profile to the ProfileManager if it doesn't
252 // already exist. The method will return NULL if the profile doesn't exist
253 // and we can't create it.
254 // The profile used can be overridden by using --login-profile on cros.
255 Profile* GetActiveUserOrOffTheRecordProfileFromPath(
256 const base::FilePath& user_data_dir);
258 // Adds a pre-existing Profile object to the set managed by this
259 // ProfileManager. This ProfileManager takes ownership of the Profile.
260 // The Profile should not already be managed by this ProfileManager.
261 // Returns true if the profile was added, false otherwise.
262 bool AddProfile(Profile* profile);
264 // Synchronously creates and returns a profile. This handles both the full
265 // creation and adds it to the set managed by this ProfileManager.
266 Profile* CreateAndInitializeProfile(const base::FilePath& profile_dir);
268 // Schedules the profile at the given path to be deleted on shutdown,
269 // and marks the new profile as active.
270 void FinishDeletingProfile(const base::FilePath& profile_dir,
271 const base::FilePath& new_active_profile_dir);
273 // Registers profile with given info. Returns pointer to created ProfileInfo
274 // entry.
275 ProfileInfo* RegisterProfile(Profile* profile, bool created);
277 // Returns ProfileInfo associated with given |path|, registered earlier with
278 // RegisterProfile.
279 ProfileInfo* GetProfileInfoByPath(const base::FilePath& path) const;
281 // Returns a registered profile. In contrast to GetProfileByPath(), this will
282 // also return a profile that is not fully initialized yet, so this method
283 // should be used carefully.
284 Profile* GetProfileByPathInternal(const base::FilePath& path) const;
286 // Adds |profile| to the profile info cache if it hasn't been added yet.
287 void AddProfileToCache(Profile* profile);
289 // Apply settings for profiles created by the system rather than users: The
290 // (desktop) Guest User profile and (desktop) System Profile.
291 void SetNonPersonalProfilePrefs(Profile* profile);
293 // For ChromeOS, determines if profile should be otr.
294 bool ShouldGoOffTheRecord(Profile* profile);
296 void RunCallbacks(const std::vector<CreateCallback>& callbacks,
297 Profile* profile,
298 Profile::CreateStatus status);
300 #if !defined(OS_ANDROID) && !defined(OS_IOS)
301 // Updates the last active user of the current session.
302 // On Chrome OS updating this user will have no effect since when browser is
303 // restored after crash there's another preference that is taken into account.
304 // See kLastActiveUser in UserManagerBase.
305 void UpdateLastUser(Profile* last_active);
307 class BrowserListObserver : public chrome::BrowserListObserver {
308 public:
309 explicit BrowserListObserver(ProfileManager* manager);
310 ~BrowserListObserver() override;
312 // chrome::BrowserListObserver implementation.
313 void OnBrowserAdded(Browser* browser) override;
314 void OnBrowserRemoved(Browser* browser) override;
315 void OnBrowserSetLastActive(Browser* browser) override;
317 private:
318 ProfileManager* profile_manager_;
319 DISALLOW_COPY_AND_ASSIGN(BrowserListObserver);
321 #endif // !defined(OS_ANDROID) && !defined(OS_IOS)
323 // If the |loaded_profile| has been loaded successfully (according to
324 // |status|) and isn't already scheduled for deletion, then finishes adding
325 // |profile_to_delete_dir| to the queue of profiles to be deleted, and updates
326 // the kProfileLastUsed preference based on
327 // |last_non_supervised_profile_path|.
328 void OnNewActiveProfileLoaded(
329 const base::FilePath& profile_to_delete_path,
330 const base::FilePath& last_non_supervised_profile_path,
331 const CreateCallback& original_callback,
332 Profile* loaded_profile,
333 Profile::CreateStatus status);
335 // Object to cache various information about profiles. Contains information
336 // about every profile which has been created for this instance of Chrome,
337 // if it has not been explicitly deleted. It must be destroyed after
338 // |profiles_info_| because ~ProfileInfo can trigger a chain of events leading
339 // to an access to this member.
340 scoped_ptr<ProfileInfoCache> profile_info_cache_;
342 content::NotificationRegistrar registrar_;
344 // The path to the user data directory (DIR_USER_DATA).
345 const base::FilePath user_data_dir_;
347 // Indicates that a user has logged in and that the profile specified
348 // in the --login-profile command line argument should be used as the
349 // default.
350 bool logged_in_;
352 #if !defined(OS_ANDROID) && !defined(OS_IOS)
353 BrowserListObserver browser_list_observer_;
354 #endif // !defined(OS_ANDROID) && !defined(OS_IOS)
356 // Maps profile path to ProfileInfo (if profile has been created). Use
357 // RegisterProfile() to add into this map. This map owns all loaded profile
358 // objects in a running instance of Chrome.
359 typedef std::map<base::FilePath, linked_ptr<ProfileInfo> > ProfilesInfoMap;
360 ProfilesInfoMap profiles_info_;
362 // Manages the process of creating, deleteing and updating Desktop shortcuts.
363 scoped_ptr<ProfileShortcutManager> profile_shortcut_manager_;
365 // For keeping track of the last active profiles.
366 std::map<Profile*, int> browser_counts_;
367 // On startup we launch the active profiles in the order they became active
368 // during the last run. This is why they are kept in a list, not in a set.
369 std::vector<Profile*> active_profiles_;
370 bool closing_all_browsers_;
372 DISALLOW_COPY_AND_ASSIGN(ProfileManager);
375 // Same as the ProfileManager, but doesn't initialize some services of the
376 // profile. This one is useful in unittests.
377 class ProfileManagerWithoutInit : public ProfileManager {
378 public:
379 explicit ProfileManagerWithoutInit(const base::FilePath& user_data_dir);
381 protected:
382 void DoFinalInitForServices(Profile*, bool) override {}
383 void DoFinalInitLogging(Profile*) override {}
386 #endif // CHROME_BROWSER_PROFILES_PROFILE_MANAGER_H_