Home | History | Annotate | Download | only in profiles
      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.
      4 
      5 // This class keeps track of the currently-active profiles in the runtime.
      6 
      7 #ifndef CHROME_BROWSER_PROFILES_PROFILE_MANAGER_H_
      8 #define CHROME_BROWSER_PROFILES_PROFILE_MANAGER_H_
      9 
     10 #include <list>
     11 #include <vector>
     12 
     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"
     26 
     27 class CommandLine;
     28 class NewProfileLauncher;
     29 class ProfileInfoCache;
     30 
     31 class ProfileManager : public base::NonThreadSafe,
     32                        public content::NotificationObserver,
     33                        public Profile::Delegate {
     34  public:
     35   typedef base::Callback<void(Profile*, Profile::CreateStatus)> CreateCallback;
     36 
     37   explicit ProfileManager(const base::FilePath& user_data_dir);
     38   virtual ~ProfileManager();
     39 
     40 #if defined(ENABLE_SESSION_SERVICE)
     41   // Invokes SessionServiceFactory::ShutdownForProfile() for all profiles.
     42   static void ShutdownSessionServices();
     43 #endif
     44 
     45   // Physically remove deleted profile directories from disk.
     46   static void NukeDeletedProfilesFromDisk();
     47 
     48   // The following DEPRECATED functions should be removed: crbug.com/83792.
     49 
     50   // DEPRECATED: DO NOT USE unless in ChromeOS.
     51   // Returns the default profile.  This adds the profile to the
     52   // ProfileManager if it doesn't already exist.  This method returns NULL if
     53   // the profile doesn't exist and we can't create it.
     54   // The profile used can be overridden by using --login-profile on cros.
     55   Profile* GetDefaultProfile(const base::FilePath& user_data_dir);
     56 
     57   // DEPRECATED: Temporary measure to ensure that GetDefaultProfile() is not
     58   // called before CreateProfile() is called in chrome_browser_main.cc.
     59   // If GetDefaultProfile() or GetDefaultProfileOrOffTheRecord() is called
     60   // before this, a CHECK will be triggered.
     61   static void AllowGetDefaultProfile();
     62   static bool IsGetDefaultProfileAllowed();
     63 
     64   // DEPRECATED: DO NOT USE unless in ChromeOS.
     65   // Same as instance method but provides the default user_data_dir as well.
     66   static Profile* GetDefaultProfile();
     67 
     68   // DEPRECATED: DO NOT USE unless in ChromeOS.
     69   // Same as GetDefaultProfile() but returns OffTheRecord profile
     70   // if guest login.
     71   static Profile* GetDefaultProfileOrOffTheRecord();
     72 
     73   // Returns a profile for a specific profile directory within the user data
     74   // dir. This will return an existing profile it had already been created,
     75   // otherwise it will create and manage it.
     76   Profile* GetProfile(const base::FilePath& profile_dir);
     77 
     78   // Returns total number of profiles available on this machine.
     79   size_t GetNumberOfProfiles();
     80 
     81   // Explicit asynchronous creation of a profile located at |profile_path|.
     82   // If the profile has already been created then callback is called
     83   // immediately. Should be called on the UI thread.
     84   void CreateProfileAsync(const base::FilePath& profile_path,
     85                           const CreateCallback& callback,
     86                           const string16& name,
     87                           const string16& icon_url,
     88                           const std::string& managed_user_id);
     89 
     90   // Initiates profile creation identified by |active_profile_username_hash_|.
     91   // If profile has already been created then the callback is called
     92   // immediately. Should be called on the UI thread.
     93   // This method is only used on Chrome OS where every user profile
     94   // has username_hash associated with it.
     95   static void CreateDefaultProfileAsync(const CreateCallback& callback);
     96 
     97   // Returns true if the profile pointer is known to point to an existing
     98   // profile.
     99   bool IsValidProfile(Profile* profile);
    100 
    101   // Returns the directory where the first created profile is stored,
    102   // relative to the user data directory currently in use..
    103   base::FilePath GetInitialProfileDir();
    104 
    105   // Get the Profile last used (the Profile to which owns the most recently
    106   // focused window) with this Chrome build. If no signed profile has been
    107   // stored in Local State, hand back the Default profile.
    108   Profile* GetLastUsedProfile(const base::FilePath& user_data_dir);
    109 
    110   // Same as instance method but provides the default user_data_dir as well.
    111   // If the Profile is going to be used to open a new window then consider using
    112   // GetLastUsedProfileAllowedByPolicy() instead.
    113   static Profile* GetLastUsedProfile();
    114 
    115   // Same as GetLastUsedProfile() but returns the incognito Profile if
    116   // incognito mode is forced. This should be used if the last used Profile
    117   // will be used to open new browser windows.
    118   static Profile* GetLastUsedProfileAllowedByPolicy();
    119 
    120   // Get the path of the last used profile, or if that's undefined, the default
    121   // profile.
    122   base::FilePath GetLastUsedProfileDir(const base::FilePath& user_data_dir);
    123 
    124   // Get the Profiles which are currently open, i.e., have open browsers, or
    125   // were open the last time Chrome was running. The Profiles appear in the
    126   // order they were opened. The last used profile will be on the list, but its
    127   // index on the list will depend on when it was opened (it is not necessarily
    128   // the last one).
    129   std::vector<Profile*> GetLastOpenedProfiles(
    130       const base::FilePath& user_data_dir);
    131 
    132   // Same as instance method but provides the default user_data_dir as well.
    133   static std::vector<Profile*> GetLastOpenedProfiles();
    134 
    135   // Returns created profiles. Note, profiles order is NOT guaranteed to be
    136   // related with the creation order.
    137   std::vector<Profile*> GetLoadedProfiles() const;
    138 
    139   // content::NotificationObserver implementation.
    140   virtual void Observe(int type,
    141                        const content::NotificationSource& source,
    142                        const content::NotificationDetails& details) OVERRIDE;
    143 
    144   // If a profile with the given path is currently managed by this object,
    145   // return a pointer to the corresponding Profile object;
    146   // otherwise return NULL.
    147   Profile* GetProfileByPath(const base::FilePath& path) const;
    148 
    149   // Profile::Delegate implementation:
    150   virtual void OnProfileCreated(Profile* profile,
    151                                 bool success,
    152                                 bool is_new_profile) OVERRIDE;
    153 
    154   // Add or remove a profile launcher to/from the list of launchers waiting for
    155   // new profiles to be created from the multi-profile menu.
    156   void AddProfileLauncher(NewProfileLauncher* profile_launcher);
    157   void RemoveProfileLauncher(NewProfileLauncher* profile_launcher);
    158 
    159   // Creates a new profile in the next available multiprofile directory.
    160   // Directories are named "profile_1", "profile_2", etc., in sequence of
    161   // creation. (Because directories can be removed, however, it may be the case
    162   // that at some point the list of numbered profiles is not continuous.)
    163   // |callback| may be invoked multiple times (for CREATE_STATUS_INITIALIZED
    164   // and CREATE_STATUS_CREATED) so binding parameters with bind::Passed() is
    165   // prohibited. Returns the file path to the profile that will be created
    166   // asynchronously.
    167   static base::FilePath CreateMultiProfileAsync(
    168       const string16& name,
    169       const string16& icon_url,
    170       const CreateCallback& callback,
    171       const std::string& managed_user_id);
    172 
    173   // Returns the full path to be used for guest profiles.
    174   static base::FilePath GetGuestProfilePath();
    175 
    176   // Returns a ProfileInfoCache object which can be used to get information
    177   // about profiles without having to load them from disk.
    178   ProfileInfoCache& GetProfileInfoCache();
    179 
    180   // Returns a ProfileShortcut Manager that enables the caller to create
    181   // profile specfic desktop shortcuts.
    182   ProfileShortcutManager* profile_shortcut_manager();
    183 
    184   // Schedules the profile at the given path to be deleted on shutdown. If we're
    185   // deleting the last profile, a new one will be created in its place, and in
    186   // that case the callback will be called when profile creation is complete.
    187   void ScheduleProfileForDeletion(const base::FilePath& profile_dir,
    188                                   const CreateCallback& callback);
    189 
    190   // Autoloads profiles if they are running background apps.
    191   void AutoloadProfiles();
    192 
    193   // Sign-Out a profile against use until re-authentication.
    194   void SignOutProfile(Profile* profile);
    195 
    196   // Register and add testing profile to the ProfileManager. Use ONLY in tests.
    197   // This allows the creation of Profiles outside of the standard creation path
    198   // for testing. If |addToCache|, adds to ProfileInfoCache as well.
    199   // If |start_deferred_task_runners|, starts the deferred task runners.
    200   // Use ONLY in tests.
    201   void RegisterTestingProfile(Profile* profile,
    202                               bool addToCache,
    203                               bool start_deferred_task_runners);
    204 
    205   const base::FilePath& user_data_dir() const { return user_data_dir_; }
    206 
    207   // For ChromeOS, determines if the user has logged in to a real profile.
    208   bool IsLoggedIn() const { return logged_in_; }
    209 
    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);
    215 
    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);
    220 
    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);
    226 
    227  private:
    228   friend class TestingProfileManager;
    229   FRIEND_TEST_ALL_PREFIXES(ProfileManagerBrowserTest, DeleteAllProfiles);
    230   FRIEND_TEST_ALL_PREFIXES(ProfileManagerBrowserTest, SwitchToProfile);
    231 
    232   // This struct contains information about profiles which are being loaded or
    233   // were loaded.
    234   struct ProfileInfo {
    235     ProfileInfo(Profile* profile, bool created);
    236 
    237     ~ProfileInfo();
    238 
    239     scoped_ptr<Profile> profile;
    240     // Whether profile has been fully loaded (created and initialized).
    241     bool created;
    242     // Whether or not this profile should have a shortcut.
    243     bool create_shortcut;
    244     // List of callbacks to run when profile initialization is done. Note, when
    245     // profile is fully loaded this vector will be empty.
    246     std::vector<CreateCallback> callbacks;
    247 
    248    private:
    249     DISALLOW_COPY_AND_ASSIGN(ProfileInfo);
    250   };
    251 
    252   // Adds a pre-existing Profile object to the set managed by this
    253   // ProfileManager. This ProfileManager takes ownership of the Profile.
    254   // The Profile should not already be managed by this ProfileManager.
    255   // Returns true if the profile was added, false otherwise.
    256   bool AddProfile(Profile* profile);
    257 
    258   // Schedules the profile at the given path to be deleted on shutdown.
    259   void FinishDeletingProfile(const base::FilePath& profile_dir);
    260 
    261   // Registers profile with given info. Returns pointer to created ProfileInfo
    262   // entry.
    263   ProfileInfo* RegisterProfile(Profile* profile, bool created);
    264 
    265   // Returns ProfileInfo associated with given |path|, registred earlier with
    266   // RegisterProfile.
    267   ProfileInfo* GetProfileInfoByPath(const base::FilePath& path) const;
    268 
    269   typedef std::pair<base::FilePath, string16> ProfilePathAndName;
    270   typedef std::vector<ProfilePathAndName> ProfilePathAndNames;
    271   ProfilePathAndNames GetSortedProfilesFromDirectoryMap();
    272 
    273   static bool CompareProfilePathAndName(
    274       const ProfileManager::ProfilePathAndName& pair1,
    275       const ProfileManager::ProfilePathAndName& pair2);
    276 
    277   // Adds |profile| to the profile info cache if it hasn't been added yet.
    278   void AddProfileToCache(Profile* profile);
    279 
    280   // Initializes user prefs of |profile|. This includes profile name and
    281   // avatar values
    282   void InitProfileUserPrefs(Profile* profile);
    283 
    284   // For ChromeOS, determines if profile should be otr.
    285   bool ShouldGoOffTheRecord(Profile* profile);
    286 
    287   // Get the path of the next profile directory and increment the internal
    288   // count.
    289   // Lack of side effects:
    290   // This function doesn't actually create the directory or touch the file
    291   // system.
    292   base::FilePath GenerateNextProfileDirectoryPath();
    293 
    294   void RunCallbacks(const std::vector<CreateCallback>& callbacks,
    295                     Profile* profile,
    296                     Profile::CreateStatus status);
    297 
    298   // If the |loaded_profile| has been loaded succesfully (according to |status|)
    299   // and isn't already scheduled for deletion, then finishes adding
    300   // |profile_to_delete_dir| to the queue of profiles to be deleted, and updates
    301   // the kProfileLastUsed preference based on |last_non_managed_profile_path|.
    302   void OnNewActiveProfileLoaded(
    303       const base::FilePath& profile_to_delete_path,
    304       const base::FilePath& last_non_managed_profile_path,
    305       const CreateCallback& original_callback,
    306       Profile* loaded_profile,
    307       Profile::CreateStatus status);
    308 
    309   content::NotificationRegistrar registrar_;
    310 
    311   // The path to the user data directory (DIR_USER_DATA).
    312   const base::FilePath user_data_dir_;
    313 
    314   // Indicates that a user has logged in and that the profile specified
    315   // in the --login-profile command line argument should be used as the
    316   // default.
    317   bool logged_in_;
    318 
    319   // Maps profile path to ProfileInfo (if profile has been created). Use
    320   // RegisterProfile() to add into this map. This map owns all loaded profile
    321   // objects in a running instance of Chrome.
    322   typedef std::map<base::FilePath, linked_ptr<ProfileInfo> > ProfilesInfoMap;
    323   ProfilesInfoMap profiles_info_;
    324 
    325   // Object to cache various information about profiles. Contains information
    326   // about every profile which has been created for this instance of Chrome,
    327   // if it has not been explicitly deleted.
    328   scoped_ptr<ProfileInfoCache> profile_info_cache_;
    329 
    330   // Manages the process of creating, deleteing and updating Desktop shortcuts.
    331   scoped_ptr<ProfileShortcutManager> profile_shortcut_manager_;
    332 
    333 #if !defined(OS_ANDROID) && !defined(OS_IOS)
    334   class BrowserListObserver : public chrome::BrowserListObserver {
    335    public:
    336     explicit BrowserListObserver(ProfileManager* manager);
    337     virtual ~BrowserListObserver();
    338 
    339     // chrome::BrowserListObserver implementation.
    340     virtual void OnBrowserAdded(Browser* browser) OVERRIDE;
    341     virtual void OnBrowserRemoved(Browser* browser) OVERRIDE;
    342     virtual void OnBrowserSetLastActive(Browser* browser) OVERRIDE;
    343 
    344    private:
    345     ProfileManager* profile_manager_;
    346     DISALLOW_COPY_AND_ASSIGN(BrowserListObserver);
    347   };
    348 
    349   BrowserListObserver browser_list_observer_;
    350 #endif  // !defined(OS_ANDROID) && !defined(OS_IOS)
    351 
    352   // For keeping track of the last active profiles.
    353   std::map<Profile*, int> browser_counts_;
    354   // On startup we launch the active profiles in the order they became active
    355   // during the last run. This is why they are kept in a list, not in a set.
    356   std::vector<Profile*> active_profiles_;
    357   bool closing_all_browsers_;
    358 
    359   DISALLOW_COPY_AND_ASSIGN(ProfileManager);
    360 };
    361 
    362 // Same as the ProfileManager, but doesn't initialize some services of the
    363 // profile. This one is useful in unittests.
    364 class ProfileManagerWithoutInit : public ProfileManager {
    365  public:
    366   explicit ProfileManagerWithoutInit(const base::FilePath& user_data_dir);
    367 
    368  protected:
    369   virtual void DoFinalInitForServices(Profile*, bool) OVERRIDE {}
    370   virtual void DoFinalInitLogging(Profile*) OVERRIDE {}
    371 };
    372 
    373 #endif  // CHROME_BROWSER_PROFILES_PROFILE_MANAGER_H_
    374