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 gathers state related to a single user profile.
6
7#ifndef CHROME_BROWSER_PROFILES_PROFILE_H_
8#define CHROME_BROWSER_PROFILES_PROFILE_H_
9
10#include <string>
11
12#include "base/basictypes.h"
13#include "base/containers/hash_tables.h"
14#include "base/logging.h"
15#include "components/domain_reliability/clear_mode.h"
16#include "content/public/browser/browser_context.h"
17#include "content/public/browser/content_browser_client.h"
18
19class ChromeAppCacheService;
20class DevToolsNetworkController;
21class ExtensionSpecialStoragePolicy;
22class FaviconService;
23class HostContentSettingsMap;
24class PrefProxyConfigTracker;
25class PrefService;
26class PromoCounter;
27class ProtocolHandlerRegistry;
28class TestingProfile;
29
30namespace android {
31class TabContentsProvider;
32}
33
34namespace base {
35class SequencedTaskRunner;
36class Time;
37}
38
39namespace chrome_browser_net {
40class Predictor;
41}
42
43namespace chromeos {
44class LibCrosServiceLibraryImpl;
45class ResetDefaultProxyConfigServiceTask;
46}
47
48namespace content {
49class WebUI;
50}
51
52namespace storage {
53class FileSystemContext;
54}
55
56namespace history {
57class TopSites;
58}
59
60namespace net {
61class SSLConfigService;
62}
63
64namespace user_prefs {
65class PrefRegistrySyncable;
66}
67
68// Instead of adding more members to Profile, consider creating a
69// KeyedService. See
70// http://dev.chromium.org/developers/design-documents/profile-architecture
71class Profile : public content::BrowserContext {
72 public:
73  // Profile services are accessed with the following parameter. This parameter
74  // defines what the caller plans to do with the service.
75  // The caller is responsible for not performing any operation that would
76  // result in persistent implicit records while using an OffTheRecord profile.
77  // This flag allows the profile to perform an additional check.
78  //
79  // It also gives us an opportunity to perform further checks in the future. We
80  // could, for example, return an history service that only allow some specific
81  // methods.
82  enum ServiceAccessType {
83    // The caller plans to perform a read or write that takes place as a result
84    // of the user input. Use this flag when the operation you are doing can be
85    // performed while incognito. (ex: creating a bookmark)
86    //
87    // Since EXPLICIT_ACCESS means "as a result of a user action", this request
88    // always succeeds.
89    EXPLICIT_ACCESS,
90
91    // The caller plans to call a method that will permanently change some data
92    // in the profile, as part of Chrome's implicit data logging. Use this flag
93    // when you are about to perform an operation which is incompatible with the
94    // incognito mode.
95    IMPLICIT_ACCESS
96  };
97
98  enum CreateStatus {
99    // Profile services were not created due to a local error (e.g., disk full).
100    CREATE_STATUS_LOCAL_FAIL,
101    // Profile services were not created due to a remote error (e.g., network
102    // down during limited-user registration).
103    CREATE_STATUS_REMOTE_FAIL,
104    // Profile created but before initializing extensions and promo resources.
105    CREATE_STATUS_CREATED,
106    // Profile is created, extensions and promo resources are initialized.
107    CREATE_STATUS_INITIALIZED,
108    // Profile creation (supervised-user registration, generally) was canceled
109    // by the user.
110    CREATE_STATUS_CANCELED,
111    MAX_CREATE_STATUS  // For histogram display.
112  };
113
114  enum CreateMode {
115    CREATE_MODE_SYNCHRONOUS,
116    CREATE_MODE_ASYNCHRONOUS
117  };
118
119  enum ExitType {
120    // A normal shutdown. The user clicked exit/closed last window of the
121    // profile.
122    EXIT_NORMAL,
123
124    // The exit was the result of the system shutting down.
125    EXIT_SESSION_ENDED,
126
127    EXIT_CRASHED,
128  };
129
130  enum ProfileType {
131    REGULAR_PROFILE,  // Login user's normal profile
132    INCOGNITO_PROFILE,  // Login user's off-the-record profile
133    GUEST_PROFILE,  // Guest session's profile
134  };
135
136  class Delegate {
137   public:
138    virtual ~Delegate();
139
140    // Called when creation of the profile is finished.
141    virtual void OnProfileCreated(Profile* profile,
142                                  bool success,
143                                  bool is_new_profile) = 0;
144  };
145
146  // Key used to bind profile to the widget with which it is associated.
147  static const char kProfileKey[];
148
149  Profile();
150  virtual ~Profile();
151
152  // Profile prefs are registered as soon as the prefs are loaded for the first
153  // time.
154  static void RegisterProfilePrefs(user_prefs::PrefRegistrySyncable* registry);
155
156  // Create a new profile given a path. If |create_mode| is
157  // CREATE_MODE_ASYNCHRONOUS then the profile is initialized asynchronously.
158  static Profile* CreateProfile(const base::FilePath& path,
159                                Delegate* delegate,
160                                CreateMode create_mode);
161
162  // Returns the profile corresponding to the given browser context.
163  static Profile* FromBrowserContext(content::BrowserContext* browser_context);
164
165  // Returns the profile corresponding to the given WebUI.
166  static Profile* FromWebUI(content::WebUI* web_ui);
167
168  // content::BrowserContext implementation ------------------------------------
169
170  // Typesafe upcast.
171  virtual TestingProfile* AsTestingProfile();
172
173  // Returns sequenced task runner where browser context dependent I/O
174  // operations should be performed.
175  virtual scoped_refptr<base::SequencedTaskRunner> GetIOTaskRunner() = 0;
176
177  // Returns the name associated with this profile. This name is displayed in
178  // the browser frame.
179  virtual std::string GetProfileName() = 0;
180
181  // Returns the profile type.
182  virtual ProfileType GetProfileType() const = 0;
183
184  // Return the incognito version of this profile. The returned pointer
185  // is owned by the receiving profile. If the receiving profile is off the
186  // record, the same profile is returned.
187  //
188  // WARNING: This will create the OffTheRecord profile if it doesn't already
189  // exist. If this isn't what you want, you need to check
190  // HasOffTheRecordProfile() first.
191  virtual Profile* GetOffTheRecordProfile() = 0;
192
193  // Destroys the incognito profile.
194  virtual void DestroyOffTheRecordProfile() = 0;
195
196  // True if an incognito profile exists.
197  virtual bool HasOffTheRecordProfile() = 0;
198
199  // Return the original "recording" profile. This method returns this if the
200  // profile is not incognito.
201  virtual Profile* GetOriginalProfile() = 0;
202
203  // Returns whether the profile is supervised (see SupervisedUserService).
204  virtual bool IsSupervised() = 0;
205
206  // Returns a pointer to the TopSites (thumbnail manager) instance
207  // for this profile.
208  virtual history::TopSites* GetTopSites() = 0;
209
210  // Variant of GetTopSites that doesn't force creation.
211  virtual history::TopSites* GetTopSitesWithoutCreating() = 0;
212
213  // Accessor. The instance is created upon first access.
214  virtual ExtensionSpecialStoragePolicy*
215      GetExtensionSpecialStoragePolicy() = 0;
216
217  // Retrieves a pointer to the PrefService that manages the
218  // preferences for this user profile.
219  virtual PrefService* GetPrefs() = 0;
220
221  // Retrieves a pointer to the PrefService that manages the preferences
222  // for OffTheRecord Profiles.  This PrefService is lazily created the first
223  // time that this method is called.
224  virtual PrefService* GetOffTheRecordPrefs() = 0;
225
226  // Returns the main request context.
227  virtual net::URLRequestContextGetter* GetRequestContext() = 0;
228
229  // Returns the request context used for extension-related requests.  This
230  // is only used for a separate cookie store currently.
231  virtual net::URLRequestContextGetter* GetRequestContextForExtensions() = 0;
232
233  // Returns the SSLConfigService for this profile.
234  virtual net::SSLConfigService* GetSSLConfigService() = 0;
235
236  // Returns the Hostname <-> Content settings map for this profile.
237  virtual HostContentSettingsMap* GetHostContentSettingsMap() = 0;
238
239  // Return whether 2 profiles are the same. 2 profiles are the same if they
240  // represent the same profile. This can happen if there is pointer equality
241  // or if one profile is the incognito version of another profile (or vice
242  // versa).
243  virtual bool IsSameProfile(Profile* profile) = 0;
244
245  // Returns the time the profile was started. This is not the time the profile
246  // was created, rather it is the time the user started chrome and logged into
247  // this profile. For the single profile case, this corresponds to the time
248  // the user started chrome.
249  virtual base::Time GetStartTime() const = 0;
250
251  // Creates the main net::URLRequestContextGetter that will be returned by
252  // GetRequestContext(). Should only be called once per ContentBrowserClient
253  // object. This function is exposed because of the circular dependency where
254  // GetStoragePartition() is used to retrieve the request context, but creation
255  // still has to happen in the Profile so the StoragePartition calls
256  // ContextBrowserClient to call this function.
257  // TODO(ajwong): Remove once http://crbug.com/159193 is resolved.
258  virtual net::URLRequestContextGetter* CreateRequestContext(
259      content::ProtocolHandlerMap* protocol_handlers,
260      content::URLRequestInterceptorScopedVector request_interceptors) = 0;
261
262  // Creates the net::URLRequestContextGetter for a StoragePartition. Should
263  // only be called once per partition_path per ContentBrowserClient object.
264  // This function is exposed because the request context is retrieved from the
265  // StoragePartition, but creation still has to happen in the Profile so the
266  // StoragePartition calls ContextBrowserClient to call this function.
267  // TODO(ajwong): Remove once http://crbug.com/159193 is resolved.
268  virtual net::URLRequestContextGetter* CreateRequestContextForStoragePartition(
269      const base::FilePath& partition_path,
270      bool in_memory,
271      content::ProtocolHandlerMap* protocol_handlers,
272      content::URLRequestInterceptorScopedVector request_interceptors) = 0;
273
274  // Returns the last directory that was chosen for uploading or opening a file.
275  virtual base::FilePath last_selected_directory() = 0;
276  virtual void set_last_selected_directory(const base::FilePath& path) = 0;
277
278#if defined(OS_CHROMEOS)
279  enum AppLocaleChangedVia {
280    // Caused by chrome://settings change.
281    APP_LOCALE_CHANGED_VIA_SETTINGS,
282    // Locale has been reverted via LocaleChangeGuard.
283    APP_LOCALE_CHANGED_VIA_REVERT,
284    // From login screen.
285    APP_LOCALE_CHANGED_VIA_LOGIN,
286    // From login to a public session.
287    APP_LOCALE_CHANGED_VIA_PUBLIC_SESSION_LOGIN,
288    // Source unknown.
289    APP_LOCALE_CHANGED_VIA_UNKNOWN
290  };
291
292  // Changes application locale for a profile.
293  virtual void ChangeAppLocale(
294      const std::string& locale, AppLocaleChangedVia via) = 0;
295
296  // Called after login.
297  virtual void OnLogin() = 0;
298
299  // Initializes Chrome OS's preferences.
300  virtual void InitChromeOSPreferences() = 0;
301#endif  // defined(OS_CHROMEOS)
302
303  // Returns the helper object that provides the proxy configuration service
304  // access to the the proxy configuration possibly defined by preferences.
305  virtual PrefProxyConfigTracker* GetProxyConfigTracker() = 0;
306
307  // Returns the Predictor object used for dns prefetch.
308  virtual chrome_browser_net::Predictor* GetNetworkPredictor() = 0;
309
310  // Returns the DevToolsNetworkController for this profile.
311  virtual DevToolsNetworkController* GetDevToolsNetworkController() = 0;
312
313  // Deletes all network related data since |time|. It deletes transport
314  // security state since |time| and it also deletes HttpServerProperties data.
315  // Works asynchronously, however if the |completion| callback is non-null, it
316  // will be posted on the UI thread once the removal process completes.
317  // Be aware that theoretically it is possible that |completion| will be
318  // invoked after the Profile instance has been destroyed.
319  virtual void ClearNetworkingHistorySince(base::Time time,
320                                           const base::Closure& completion) = 0;
321
322  // Returns the home page for this profile.
323  virtual GURL GetHomePage() = 0;
324
325  // Returns whether or not the profile was created by a version of Chrome
326  // more recent (or equal to) the one specified.
327  virtual bool WasCreatedByVersionOrLater(const std::string& version) = 0;
328
329  std::string GetDebugName();
330
331  // Returns whether it is a guest session.
332  virtual bool IsGuestSession() const;
333
334  // Did the user restore the last session? This is set by SessionRestore.
335  void set_restored_last_session(bool restored_last_session) {
336    restored_last_session_ = restored_last_session;
337  }
338  bool restored_last_session() const {
339    return restored_last_session_;
340  }
341
342  // Sets the ExitType for the profile. This may be invoked multiple times
343  // during shutdown; only the first such change (the transition from
344  // EXIT_CRASHED to one of the other values) is written to prefs, any
345  // later calls are ignored.
346  //
347  // NOTE: this is invoked internally on a normal shutdown, but is public so
348  // that it can be invoked when the user logs out/powers down (WM_ENDSESSION),
349  // or to handle backgrounding/foregrounding on mobile.
350  virtual void SetExitType(ExitType exit_type) = 0;
351
352  // Returns how the last session was shutdown.
353  virtual ExitType GetLastSessionExitType() = 0;
354
355  // Stop sending accessibility events until ResumeAccessibilityEvents().
356  // Calls to Pause nest; no events will be sent until the number of
357  // Resume calls matches the number of Pause calls received.
358  void PauseAccessibilityEvents() {
359    accessibility_pause_level_++;
360  }
361
362  void ResumeAccessibilityEvents() {
363    DCHECK_GT(accessibility_pause_level_, 0);
364    accessibility_pause_level_--;
365  }
366
367  bool ShouldSendAccessibilityEvents() {
368    return 0 == accessibility_pause_level_;
369  }
370
371  // Returns whether the profile is new.  A profile is new if the browser has
372  // not been shut down since the profile was created.
373  bool IsNewProfile();
374
375  // Checks whether sync is configurable by the user. Returns false if sync is
376  // disabled or controlled by configuration management.
377  bool IsSyncAccessible();
378
379  // Send NOTIFICATION_PROFILE_DESTROYED for this Profile, if it has not
380  // already been sent. It is necessary because most Profiles are destroyed by
381  // ProfileDestroyer, but in tests, some are not.
382  void MaybeSendDestroyedNotification();
383
384  // Creates an OffTheRecordProfile which points to this Profile.
385  Profile* CreateOffTheRecordProfile();
386
387 private:
388  bool restored_last_session_;
389
390  // Used to prevent the notification that this Profile is destroyed from
391  // being sent twice.
392  bool sent_destroyed_notification_;
393
394  // Accessibility events will only be propagated when the pause
395  // level is zero.  PauseAccessibilityEvents and ResumeAccessibilityEvents
396  // increment and decrement the level, respectively, rather than set it to
397  // true or false, so that calls can be nested.
398  int accessibility_pause_level_;
399
400  DISALLOW_COPY_AND_ASSIGN(Profile);
401};
402
403// The comparator for profile pointers as key in a map.
404struct ProfileCompare {
405  bool operator()(Profile* a, Profile* b) const;
406};
407
408#if defined(COMPILER_GCC)
409namespace BASE_HASH_NAMESPACE {
410
411template<>
412struct hash<Profile*> {
413  std::size_t operator()(Profile* const& p) const {
414    return reinterpret_cast<std::size_t>(p);
415  }
416};
417
418}  // namespace BASE_HASH_NAMESPACE
419#endif
420
421#endif  // CHROME_BROWSER_PROFILES_PROFILE_H_
422