Pin Chrome's shortcut to the Win10 Start menu on install and OS upgrade.
[chromium-blink-merge.git] / chrome / browser / profiles / profile_impl.cc
blob4db6a3fccc4998fda4171b624e75b31c37548455
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 #include "chrome/browser/profiles/profile_impl.h"
7 #include <vector>
9 #include "base/bind.h"
10 #include "base/callback.h"
11 #include "base/command_line.h"
12 #include "base/compiler_specific.h"
13 #include "base/environment.h"
14 #include "base/files/file_path.h"
15 #include "base/files/file_util.h"
16 #include "base/memory/scoped_ptr.h"
17 #include "base/memory/weak_ptr.h"
18 #include "base/metrics/histogram_macros.h"
19 #include "base/path_service.h"
20 #include "base/prefs/json_pref_store.h"
21 #include "base/prefs/scoped_user_pref_update.h"
22 #include "base/strings/string_number_conversions.h"
23 #include "base/strings/string_util.h"
24 #include "base/strings/stringprintf.h"
25 #include "base/strings/utf_string_conversions.h"
26 #include "base/synchronization/waitable_event.h"
27 #include "base/threading/sequenced_worker_pool.h"
28 #include "base/threading/thread_restrictions.h"
29 #include "base/trace_event/trace_event.h"
30 #include "base/version.h"
31 #include "chrome/browser/background/background_contents_service_factory.h"
32 #include "chrome/browser/bookmarks/bookmark_model_factory.h"
33 #include "chrome/browser/browser_process.h"
34 #include "chrome/browser/chrome_notification_types.h"
35 #include "chrome/browser/content_settings/cookie_settings_factory.h"
36 #include "chrome/browser/dom_distiller/profile_utils.h"
37 #include "chrome/browser/domain_reliability/service_factory.h"
38 #include "chrome/browser/download/chrome_download_manager_delegate.h"
39 #include "chrome/browser/download/download_service.h"
40 #include "chrome/browser/download/download_service_factory.h"
41 #include "chrome/browser/net/net_pref_observer.h"
42 #include "chrome/browser/net/predictor.h"
43 #include "chrome/browser/net/pref_proxy_config_tracker.h"
44 #include "chrome/browser/net/proxy_service_factory.h"
45 #include "chrome/browser/net/ssl_config_service_manager.h"
46 #include "chrome/browser/permissions/permission_manager.h"
47 #include "chrome/browser/permissions/permission_manager_factory.h"
48 #include "chrome/browser/plugins/chrome_plugin_service_filter.h"
49 #include "chrome/browser/plugins/plugin_prefs.h"
50 #include "chrome/browser/policy/profile_policy_connector.h"
51 #include "chrome/browser/policy/profile_policy_connector_factory.h"
52 #include "chrome/browser/prefs/browser_prefs.h"
53 #include "chrome/browser/prefs/chrome_pref_service_factory.h"
54 #include "chrome/browser/prefs/pref_service_syncable.h"
55 #include "chrome/browser/prefs/tracked/tracked_preference_validation_delegate.h"
56 #include "chrome/browser/prerender/prerender_manager_factory.h"
57 #include "chrome/browser/profiles/bookmark_model_loaded_observer.h"
58 #include "chrome/browser/profiles/chrome_version_service.h"
59 #include "chrome/browser/profiles/gaia_info_update_service_factory.h"
60 #include "chrome/browser/profiles/profile_destroyer.h"
61 #include "chrome/browser/profiles/profile_info_cache.h"
62 #include "chrome/browser/profiles/profile_manager.h"
63 #include "chrome/browser/profiles/profile_metrics.h"
64 #include "chrome/browser/push_messaging/push_messaging_service_factory.h"
65 #include "chrome/browser/push_messaging/push_messaging_service_impl.h"
66 #include "chrome/browser/safe_browsing/safe_browsing_service.h"
67 #include "chrome/browser/services/gcm/gcm_profile_service.h"
68 #include "chrome/browser/sessions/session_service_factory.h"
69 #include "chrome/browser/signin/signin_manager_factory.h"
70 #include "chrome/browser/signin/signin_ui_util.h"
71 #include "chrome/browser/ssl/chrome_ssl_host_state_delegate.h"
72 #include "chrome/browser/ssl/chrome_ssl_host_state_delegate_factory.h"
73 #include "chrome/browser/ui/startup/startup_browser_creator.h"
74 #include "chrome/browser/ui/zoom/chrome_zoom_level_prefs.h"
75 #include "chrome/common/chrome_constants.h"
76 #include "chrome/common/chrome_paths_internal.h"
77 #include "chrome/common/chrome_switches.h"
78 #include "chrome/common/chrome_version_info.h"
79 #include "chrome/common/pref_names.h"
80 #include "chrome/common/url_constants.h"
81 #include "chrome/grit/chromium_strings.h"
82 #include "components/bookmarks/browser/bookmark_model.h"
83 #include "components/content_settings/core/browser/cookie_settings.h"
84 #include "components/content_settings/core/browser/host_content_settings_map.h"
85 #include "components/domain_reliability/monitor.h"
86 #include "components/domain_reliability/service.h"
87 #include "components/keyed_service/content/browser_context_dependency_manager.h"
88 #include "components/metrics/metrics_service.h"
89 #include "components/omnibox/browser/autocomplete_classifier.h"
90 #include "components/omnibox/browser/shortcuts_backend.h"
91 #include "components/pref_registry/pref_registry_syncable.h"
92 #include "components/signin/core/browser/signin_manager.h"
93 #include "components/ui/zoom/zoom_event_manager.h"
94 #include "components/url_fixer/url_fixer.h"
95 #include "components/user_prefs/user_prefs.h"
96 #include "content/public/browser/browser_thread.h"
97 #include "content/public/browser/dom_storage_context.h"
98 #include "content/public/browser/notification_service.h"
99 #include "content/public/browser/render_process_host.h"
100 #include "content/public/browser/storage_partition.h"
101 #include "content/public/browser/url_data_source.h"
102 #include "content/public/browser/user_metrics.h"
103 #include "content/public/common/content_constants.h"
104 #include "content/public/common/page_zoom.h"
105 #include "ui/base/l10n/l10n_util.h"
107 #if defined(OS_ANDROID)
108 #include "chrome/browser/media/protected_media_identifier_permission_context.h"
109 #include "chrome/browser/media/protected_media_identifier_permission_context_factory.h"
110 #endif
112 #if defined(OS_CHROMEOS)
113 #include "chrome/browser/chromeos/locale_change_guard.h"
114 #include "chrome/browser/chromeos/preferences.h"
115 #include "chrome/browser/chromeos/profiles/profile_helper.h"
116 #include "components/user_manager/user_manager.h"
117 #endif
119 #if defined(ENABLE_BACKGROUND)
120 #include "chrome/browser/background/background_mode_manager.h"
121 #endif
123 #if defined(ENABLE_CONFIGURATION_POLICY)
124 #include "chrome/browser/policy/schema_registry_service.h"
125 #include "chrome/browser/policy/schema_registry_service_factory.h"
126 #include "components/policy/core/browser/browser_policy_connector.h"
127 #if defined(OS_CHROMEOS)
128 #include "chrome/browser/chromeos/login/session/user_session_manager.h"
129 #include "chrome/browser/chromeos/policy/user_cloud_policy_manager_chromeos.h"
130 #include "chrome/browser/chromeos/policy/user_cloud_policy_manager_factory_chromeos.h"
131 #else
132 #include "chrome/browser/policy/cloud/user_cloud_policy_manager_factory.h"
133 #include "components/policy/core/common/cloud/user_cloud_policy_manager.h"
134 #endif
135 #endif
137 #if defined(ENABLE_EXTENSIONS)
138 #include "chrome/browser/extensions/extension_service.h"
139 #include "chrome/browser/extensions/extension_special_storage_policy.h"
140 #include "chrome/browser/ui/webui/extensions/extension_icon_source.h"
141 #include "components/guest_view/browser/guest_view_manager.h"
142 #include "extensions/browser/extension_pref_store.h"
143 #include "extensions/browser/extension_pref_value_map.h"
144 #include "extensions/browser/extension_pref_value_map_factory.h"
145 #include "extensions/browser/extension_system.h"
146 #endif
148 #if defined(ENABLE_SUPERVISED_USERS)
149 #include "chrome/browser/content_settings/content_settings_supervised_provider.h"
150 #include "chrome/browser/supervised_user/supervised_user_constants.h"
151 #include "chrome/browser/supervised_user/supervised_user_settings_service.h"
152 #include "chrome/browser/supervised_user/supervised_user_settings_service_factory.h"
153 #endif
155 using base::Time;
156 using base::TimeDelta;
157 using base::UserMetricsAction;
158 using bookmarks::BookmarkModel;
159 using content::BrowserThread;
160 using content::DownloadManagerDelegate;
162 namespace {
164 #if defined(ENABLE_SESSION_SERVICE)
165 // Delay, in milliseconds, before we explicitly create the SessionService.
166 const int kCreateSessionServiceDelayMS = 500;
167 #endif
169 // Text content of README file created in each profile directory. Both %s
170 // placeholders must contain the product name. This is not localizable and hence
171 // not in resources.
172 const char kReadmeText[] =
173 "%s settings and storage represent user-selected preferences and "
174 "information and MUST not be extracted, overwritten or modified except "
175 "through %s defined APIs.";
177 // Value written to prefs for EXIT_CRASHED and EXIT_SESSION_ENDED.
178 const char kPrefExitTypeCrashed[] = "Crashed";
179 const char kPrefExitTypeSessionEnded[] = "SessionEnded";
181 void CreateProfileReadme(const base::FilePath& profile_path) {
182 base::ThreadRestrictions::AssertIOAllowed();
183 base::FilePath readme_path = profile_path.Append(chrome::kReadmeFilename);
184 std::string product_name = l10n_util::GetStringUTF8(IDS_PRODUCT_NAME);
185 std::string readme_text = base::StringPrintf(
186 kReadmeText, product_name.c_str(), product_name.c_str());
187 if (base::WriteFile(readme_path, readme_text.data(), readme_text.size()) ==
188 -1) {
189 LOG(ERROR) << "Could not create README file.";
193 // Helper method needed because PostTask cannot currently take a Callback
194 // function with non-void return type.
195 void CreateDirectoryAndSignal(const base::FilePath& path,
196 base::WaitableEvent* done_creating,
197 bool create_readme) {
198 // If the readme exists, the profile directory must also already exist.
199 base::FilePath readme_path = path.Append(chrome::kReadmeFilename);
200 if (base::PathExists(readme_path)) {
201 done_creating->Signal();
202 return;
205 DVLOG(1) << "Creating directory " << path.value();
206 if (base::CreateDirectory(path) && create_readme)
207 CreateProfileReadme(path);
208 done_creating->Signal();
211 // Task that blocks the FILE thread until CreateDirectoryAndSignal() finishes on
212 // blocking I/O pool.
213 void BlockFileThreadOnDirectoryCreate(base::WaitableEvent* done_creating) {
214 done_creating->Wait();
217 // Initiates creation of profile directory on |sequenced_task_runner| and
218 // ensures that FILE thread is blocked until that operation finishes. If
219 // |create_readme| is true, the profile README will be created in the profile
220 // directory.
221 void CreateProfileDirectory(base::SequencedTaskRunner* sequenced_task_runner,
222 const base::FilePath& path,
223 bool create_readme) {
224 base::WaitableEvent* done_creating = new base::WaitableEvent(false, false);
225 sequenced_task_runner->PostTask(
226 FROM_HERE, base::Bind(&CreateDirectoryAndSignal, path, done_creating,
227 create_readme));
228 // Block the FILE thread until directory is created on I/O pool to make sure
229 // that we don't attempt any operation until that part completes.
230 BrowserThread::PostTask(
231 BrowserThread::FILE, FROM_HERE,
232 base::Bind(&BlockFileThreadOnDirectoryCreate,
233 base::Owned(done_creating)));
236 base::FilePath GetCachePath(const base::FilePath& base) {
237 return base.Append(chrome::kCacheDirname);
240 base::FilePath GetMediaCachePath(const base::FilePath& base) {
241 return base.Append(chrome::kMediaCacheDirname);
244 // Converts the kSessionExitedCleanly pref to the corresponding EXIT_TYPE.
245 Profile::ExitType SessionTypePrefValueToExitType(const std::string& value) {
246 if (value == kPrefExitTypeSessionEnded)
247 return Profile::EXIT_SESSION_ENDED;
248 if (value == kPrefExitTypeCrashed)
249 return Profile::EXIT_CRASHED;
250 return Profile::EXIT_NORMAL;
253 // Converts an ExitType into a string that is written to prefs.
254 std::string ExitTypeToSessionTypePrefValue(Profile::ExitType type) {
255 switch (type) {
256 case Profile::EXIT_NORMAL:
257 return ProfileImpl::kPrefExitTypeNormal;
258 case Profile::EXIT_SESSION_ENDED:
259 return kPrefExitTypeSessionEnded;
260 case Profile::EXIT_CRASHED:
261 return kPrefExitTypeCrashed;
263 NOTREACHED();
264 return std::string();
267 PrefStore* CreateExtensionPrefStore(Profile* profile,
268 bool incognito_pref_store) {
269 #if defined(ENABLE_EXTENSIONS)
270 return new ExtensionPrefStore(
271 ExtensionPrefValueMapFactory::GetForBrowserContext(profile),
272 incognito_pref_store);
273 #else
274 return NULL;
275 #endif
278 } // namespace
280 // static
281 Profile* Profile::CreateProfile(const base::FilePath& path,
282 Delegate* delegate,
283 CreateMode create_mode) {
284 TRACE_EVENT1("browser,startup",
285 "Profile::CreateProfile",
286 "profile_path",
287 path.AsUTF8Unsafe());
289 // Get sequenced task runner for making sure that file operations of
290 // this profile (defined by |path|) are executed in expected order
291 // (what was previously assured by the FILE thread).
292 scoped_refptr<base::SequencedTaskRunner> sequenced_task_runner =
293 JsonPrefStore::GetTaskRunnerForFile(path,
294 BrowserThread::GetBlockingPool());
295 if (create_mode == CREATE_MODE_ASYNCHRONOUS) {
296 DCHECK(delegate);
297 CreateProfileDirectory(sequenced_task_runner.get(), path, true);
298 } else if (create_mode == CREATE_MODE_SYNCHRONOUS) {
299 if (!base::PathExists(path)) {
300 // TODO(rogerta): http://crbug/160553 - Bad things happen if we can't
301 // write to the profile directory. We should eventually be able to run in
302 // this situation.
303 if (!base::CreateDirectory(path))
304 return NULL;
306 CreateProfileReadme(path);
308 } else {
309 NOTREACHED();
312 return new ProfileImpl(
313 path, delegate, create_mode, sequenced_task_runner.get());
316 // static
317 const char* const ProfileImpl::kPrefExitTypeNormal = "Normal";
319 // static
320 void ProfileImpl::RegisterProfilePrefs(
321 user_prefs::PrefRegistrySyncable* registry) {
322 registry->RegisterBooleanPref(prefs::kSavingBrowserHistoryDisabled, false);
323 registry->RegisterBooleanPref(prefs::kAllowDeletingBrowserHistory, true);
324 registry->RegisterBooleanPref(prefs::kSigninAllowed, true);
325 registry->RegisterBooleanPref(prefs::kForceGoogleSafeSearch, false);
326 registry->RegisterBooleanPref(prefs::kForceYouTubeSafetyMode, false);
327 registry->RegisterBooleanPref(prefs::kRecordHistory, false);
328 registry->RegisterIntegerPref(
329 prefs::kProfileAvatarIndex,
331 user_prefs::PrefRegistrySyncable::SYNCABLE_PREF);
332 // Whether a profile is using an avatar without having explicitely chosen it
333 // (i.e. was assigned by default by legacy profile creation).
334 registry->RegisterBooleanPref(
335 prefs::kProfileUsingDefaultAvatar,
336 true,
337 user_prefs::PrefRegistrySyncable::SYNCABLE_PREF);
338 registry->RegisterBooleanPref(
339 prefs::kProfileUsingGAIAAvatar,
340 false,
341 user_prefs::PrefRegistrySyncable::SYNCABLE_PREF);
342 // Whether a profile is using a default avatar name (eg. Pickles or Person 1).
343 registry->RegisterBooleanPref(
344 prefs::kProfileUsingDefaultName,
345 true,
346 user_prefs::PrefRegistrySyncable::SYNCABLE_PREF);
347 registry->RegisterStringPref(prefs::kSupervisedUserId, std::string());
348 registry->RegisterStringPref(prefs::kProfileName,
349 std::string(),
350 user_prefs::PrefRegistrySyncable::SYNCABLE_PREF);
351 registry->RegisterStringPref(prefs::kHomePage,
352 std::string(),
353 user_prefs::PrefRegistrySyncable::SYNCABLE_PREF);
354 #if defined(ENABLE_PRINTING)
355 registry->RegisterBooleanPref(prefs::kPrintingEnabled, true);
356 #endif
357 registry->RegisterBooleanPref(prefs::kPrintPreviewDisabled, false);
358 registry->RegisterBooleanPref(prefs::kForceEphemeralProfiles, false);
360 // Initialize the cache prefs.
361 registry->RegisterFilePathPref(prefs::kDiskCacheDir, base::FilePath());
362 registry->RegisterIntegerPref(prefs::kDiskCacheSize, 0);
363 registry->RegisterIntegerPref(prefs::kMediaCacheSize, 0);
365 // Deprecated. Kept around for migration.
366 registry->RegisterBooleanPref(
367 prefs::kClearSiteDataOnExit,
368 false,
369 user_prefs::PrefRegistrySyncable::SYNCABLE_PREF);
372 ProfileImpl::ProfileImpl(
373 const base::FilePath& path,
374 Delegate* delegate,
375 CreateMode create_mode,
376 base::SequencedTaskRunner* sequenced_task_runner)
377 : path_(path),
378 pref_registry_(new user_prefs::PrefRegistrySyncable),
379 io_data_(this),
380 host_content_settings_map_(NULL),
381 last_session_exit_type_(EXIT_NORMAL),
382 start_time_(Time::Now()),
383 delegate_(delegate),
384 predictor_(NULL) {
385 TRACE_EVENT0("browser,startup", "ProfileImpl::ctor")
386 DCHECK(!path.empty()) << "Using an empty path will attempt to write " <<
387 "profile files to the root directory!";
389 #if defined(ENABLE_SESSION_SERVICE)
390 create_session_service_timer_.Start(FROM_HERE,
391 TimeDelta::FromMilliseconds(kCreateSessionServiceDelayMS), this,
392 &ProfileImpl::EnsureSessionServiceCreated);
393 #endif
395 set_is_guest_profile(path == ProfileManager::GetGuestProfilePath());
396 set_is_system_profile(path == ProfileManager::GetSystemProfilePath());
398 // Determine if prefetch is enabled for this profile.
399 // If not profile_manager is present, it means we are in a unittest.
400 const base::CommandLine* command_line =
401 base::CommandLine::ForCurrentProcess();
402 predictor_ = chrome_browser_net::Predictor::CreatePredictor(
403 !command_line->HasSwitch(switches::kDisablePreconnect),
404 !command_line->HasSwitch(switches::kDnsPrefetchDisable),
405 g_browser_process->profile_manager() == NULL);
407 // If we are creating the profile synchronously, then we should load the
408 // policy data immediately.
409 bool force_immediate_policy_load = (create_mode == CREATE_MODE_SYNCHRONOUS);
410 #if defined(ENABLE_CONFIGURATION_POLICY)
411 policy::BrowserPolicyConnector* connector =
412 g_browser_process->browser_policy_connector();
413 schema_registry_service_ =
414 policy::SchemaRegistryServiceFactory::CreateForContext(
415 this, connector->GetChromeSchema(), connector->GetSchemaRegistry());
416 #if defined(OS_CHROMEOS)
417 cloud_policy_manager_ =
418 policy::UserCloudPolicyManagerFactoryChromeOS::CreateForProfile(
419 this, force_immediate_policy_load, sequenced_task_runner);
420 #else
421 cloud_policy_manager_ =
422 policy::UserCloudPolicyManagerFactory::CreateForOriginalBrowserContext(
423 this,
424 force_immediate_policy_load,
425 sequenced_task_runner,
426 BrowserThread::GetMessageLoopProxyForThread(BrowserThread::FILE),
427 BrowserThread::GetMessageLoopProxyForThread(BrowserThread::IO));
428 #endif
429 #endif
430 profile_policy_connector_ =
431 policy::ProfilePolicyConnectorFactory::CreateForBrowserContext(
432 this, force_immediate_policy_load);
434 DCHECK(create_mode == CREATE_MODE_ASYNCHRONOUS ||
435 create_mode == CREATE_MODE_SYNCHRONOUS);
436 bool async_prefs = create_mode == CREATE_MODE_ASYNCHRONOUS;
438 #if defined(OS_CHROMEOS)
439 if (chromeos::ProfileHelper::IsSigninProfile(this))
440 chrome::RegisterLoginProfilePrefs(pref_registry_.get());
441 else
442 #endif
443 chrome::RegisterUserProfilePrefs(pref_registry_.get());
445 BrowserContextDependencyManager::GetInstance()->
446 RegisterProfilePrefsForServices(this, pref_registry_.get());
448 SupervisedUserSettingsService* supervised_user_settings = nullptr;
449 #if defined(ENABLE_SUPERVISED_USERS)
450 supervised_user_settings =
451 SupervisedUserSettingsServiceFactory::GetForProfile(this);
452 supervised_user_settings->Init(
453 path_, sequenced_task_runner, create_mode == CREATE_MODE_SYNCHRONOUS);
454 #endif
456 scoped_refptr<SafeBrowsingService> safe_browsing_service(
457 g_browser_process->safe_browsing_service());
458 if (safe_browsing_service.get()) {
459 pref_validation_delegate_ =
460 safe_browsing_service->CreatePreferenceValidationDelegate(this).Pass();
464 prefs_ = chrome_prefs::CreateProfilePrefs(
465 path_,
466 sequenced_task_runner,
467 pref_validation_delegate_.get(),
468 profile_policy_connector_->policy_service(),
469 supervised_user_settings,
470 CreateExtensionPrefStore(this, false),
471 pref_registry_,
472 async_prefs).Pass();
473 // Register on BrowserContext.
474 user_prefs::UserPrefs::Set(this, prefs_.get());
477 if (async_prefs) {
478 // Wait for the notification that prefs has been loaded
479 // (successfully or not). Note that we can use base::Unretained
480 // because the PrefService is owned by this class and lives on
481 // the same thread.
482 prefs_->AddPrefInitObserver(base::Bind(
483 &ProfileImpl::OnPrefsLoaded, base::Unretained(this), create_mode));
484 } else {
485 // Prefs were loaded synchronously so we can continue directly.
486 OnPrefsLoaded(create_mode, true);
490 void ProfileImpl::DoFinalInit() {
491 TRACE_EVENT0("browser", "ProfileImpl::DoFinalInit")
492 SCOPED_UMA_HISTOGRAM_TIMER("Profile.ProfileImplDoFinalInit");
494 PrefService* prefs = GetPrefs();
495 pref_change_registrar_.Init(prefs);
496 pref_change_registrar_.Add(
497 prefs::kSupervisedUserId,
498 base::Bind(&ProfileImpl::UpdateProfileSupervisedUserIdCache,
499 base::Unretained(this)));
501 // Changes in the profile avatar.
502 pref_change_registrar_.Add(
503 prefs::kProfileAvatarIndex,
504 base::Bind(&ProfileImpl::UpdateProfileAvatarCache,
505 base::Unretained(this)));
506 pref_change_registrar_.Add(
507 prefs::kProfileUsingDefaultAvatar,
508 base::Bind(&ProfileImpl::UpdateProfileAvatarCache,
509 base::Unretained(this)));
510 pref_change_registrar_.Add(
511 prefs::kProfileUsingGAIAAvatar,
512 base::Bind(&ProfileImpl::UpdateProfileAvatarCache,
513 base::Unretained(this)));
515 // Changes in the profile name.
516 pref_change_registrar_.Add(
517 prefs::kProfileUsingDefaultName,
518 base::Bind(&ProfileImpl::UpdateProfileNameCache,
519 base::Unretained(this)));
520 pref_change_registrar_.Add(
521 prefs::kProfileName,
522 base::Bind(&ProfileImpl::UpdateProfileNameCache,
523 base::Unretained(this)));
525 pref_change_registrar_.Add(
526 prefs::kForceEphemeralProfiles,
527 base::Bind(&ProfileImpl::UpdateProfileIsEphemeralCache,
528 base::Unretained(this)));
530 // It would be nice to use PathService for fetching this directory, but
531 // the cache directory depends on the profile directory, which isn't available
532 // to PathService.
533 chrome::GetUserCacheDirectory(path_, &base_cache_path_);
534 // Always create the cache directory asynchronously.
535 scoped_refptr<base::SequencedTaskRunner> sequenced_task_runner =
536 JsonPrefStore::GetTaskRunnerForFile(base_cache_path_,
537 BrowserThread::GetBlockingPool());
538 CreateProfileDirectory(sequenced_task_runner.get(), base_cache_path_, false);
540 // Initialize components that depend on the current value.
541 UpdateProfileSupervisedUserIdCache();
542 UpdateProfileIsEphemeralCache();
543 GAIAInfoUpdateServiceFactory::GetForProfile(this);
545 PrefService* local_state = g_browser_process->local_state();
546 ssl_config_service_manager_.reset(
547 SSLConfigServiceManager::CreateDefaultManager(local_state));
549 #if defined(ENABLE_BACKGROUND)
550 // Initialize the BackgroundModeManager - this has to be done here before
551 // InitExtensions() is called because it relies on receiving notifications
552 // when extensions are loaded. BackgroundModeManager is not needed under
553 // ChromeOS because Chrome is always running, no need for special keep-alive
554 // or launch-on-startup support unless kKeepAliveForTest is set.
555 bool init_background_mode_manager = true;
556 #if defined(OS_CHROMEOS)
557 if (!base::CommandLine::ForCurrentProcess()->HasSwitch(
558 switches::kKeepAliveForTest))
559 init_background_mode_manager = false;
560 #endif
561 if (init_background_mode_manager) {
562 if (g_browser_process->background_mode_manager())
563 g_browser_process->background_mode_manager()->RegisterProfile(this);
565 #endif // defined(ENABLE_BACKGROUND)
567 base::FilePath cookie_path = GetPath();
568 cookie_path = cookie_path.Append(chrome::kCookieFilename);
569 base::FilePath channel_id_path = GetPath();
570 channel_id_path = channel_id_path.Append(chrome::kChannelIDFilename);
571 base::FilePath cache_path = base_cache_path_;
572 int cache_max_size;
573 GetCacheParameters(false, &cache_path, &cache_max_size);
574 cache_path = GetCachePath(cache_path);
576 base::FilePath media_cache_path = base_cache_path_;
577 int media_cache_max_size;
578 GetCacheParameters(true, &media_cache_path, &media_cache_max_size);
579 media_cache_path = GetMediaCachePath(media_cache_path);
581 base::FilePath extensions_cookie_path = GetPath();
582 extensions_cookie_path =
583 extensions_cookie_path.Append(chrome::kExtensionsCookieFilename);
585 #if defined(OS_ANDROID)
586 SessionStartupPref::Type startup_pref_type =
587 SessionStartupPref::GetDefaultStartupType();
588 #else
589 SessionStartupPref::Type startup_pref_type =
590 StartupBrowserCreator::GetSessionStartupPref(
591 *base::CommandLine::ForCurrentProcess(), this).type;
592 #endif
593 content::CookieStoreConfig::SessionCookieMode session_cookie_mode =
594 content::CookieStoreConfig::PERSISTANT_SESSION_COOKIES;
595 if (GetLastSessionExitType() == Profile::EXIT_CRASHED ||
596 startup_pref_type == SessionStartupPref::LAST) {
597 session_cookie_mode = content::CookieStoreConfig::RESTORED_SESSION_COOKIES;
600 // Make sure we initialize the ProfileIOData after everything else has been
601 // initialized that we might be reading from the IO thread.
603 io_data_.Init(cookie_path, channel_id_path, cache_path,
604 cache_max_size, media_cache_path, media_cache_max_size,
605 extensions_cookie_path, GetPath(), predictor_,
606 session_cookie_mode, GetSpecialStoragePolicy(),
607 CreateDomainReliabilityMonitor(local_state));
609 #if defined(ENABLE_PLUGINS)
610 ChromePluginServiceFilter::GetInstance()->RegisterResourceContext(
611 PluginPrefs::GetForProfile(this).get(),
612 io_data_.GetResourceContextNoInit());
613 #endif
615 TRACE_EVENT0("browser", "ProfileImpl::SetSaveSessionStorageOnDisk");
616 content::BrowserContext::GetDefaultStoragePartition(this)->
617 GetDOMStorageContext()->SetSaveSessionStorageOnDisk();
619 // TODO(wjmaclean): Remove this. crbug.com/420643
620 chrome::MigrateProfileZoomLevelPrefs(this);
622 // The DomDistillerViewerSource is not a normal WebUI so it must be registered
623 // as a URLDataSource early.
624 RegisterDomDistillerViewerSource(this);
626 #if defined(OS_CHROMEOS)
627 if (chromeos::UserSessionManager::GetInstance()
628 ->RestartToApplyPerSessionFlagsIfNeed(this, true)) {
629 return;
631 #endif
633 if (delegate_) {
634 TRACE_EVENT0("browser", "ProfileImpl::DoFileInit:DelegateOnProfileCreated")
635 delegate_->OnProfileCreated(this, true, IsNewProfile());
639 SCOPED_UMA_HISTOGRAM_TIMER("Profile.NotifyProfileCreatedTime");
640 content::NotificationService::current()->Notify(
641 chrome::NOTIFICATION_PROFILE_CREATED,
642 content::Source<Profile>(this),
643 content::NotificationService::NoDetails());
645 #if !defined(OS_CHROMEOS)
646 // Listen for bookmark model load, to bootstrap the sync service.
647 // On CrOS sync service will be initialized after sign in.
648 BookmarkModel* model = BookmarkModelFactory::GetForProfile(this);
649 model->AddObserver(new BookmarkModelLoadedObserver(this));
650 #endif
652 PushMessagingServiceImpl::InitializeForProfile(this);
654 #if !defined(OS_ANDROID) && !defined(OS_CHROMEOS) && !defined(OS_IOS)
655 signin_ui_util::InitializePrefsForProfile(this);
656 #endif
659 base::FilePath ProfileImpl::last_selected_directory() {
660 return GetPrefs()->GetFilePath(prefs::kSelectFileLastDirectory);
663 void ProfileImpl::set_last_selected_directory(const base::FilePath& path) {
664 GetPrefs()->SetFilePath(prefs::kSelectFileLastDirectory, path);
667 ProfileImpl::~ProfileImpl() {
668 MaybeSendDestroyedNotification();
670 bool prefs_loaded = prefs_->GetInitializationStatus() !=
671 PrefService::INITIALIZATION_STATUS_WAITING;
673 #if defined(ENABLE_SESSION_SERVICE)
674 StopCreateSessionServiceTimer();
675 #endif
677 // Remove pref observers
678 pref_change_registrar_.RemoveAll();
680 #if defined(ENABLE_PLUGINS)
681 ChromePluginServiceFilter::GetInstance()->UnregisterResourceContext(
682 io_data_.GetResourceContextNoInit());
683 #endif
685 // Destroy OTR profile and its profile services first.
686 if (off_the_record_profile_) {
687 ProfileDestroyer::DestroyOffTheRecordProfileNow(
688 off_the_record_profile_.get());
689 } else {
690 #if defined(ENABLE_EXTENSIONS)
691 ExtensionPrefValueMapFactory::GetForBrowserContext(this)->
692 ClearAllIncognitoSessionOnlyPreferences();
693 #endif
696 BrowserContextDependencyManager::GetInstance()->DestroyBrowserContextServices(
697 this);
699 if (pref_proxy_config_tracker_)
700 pref_proxy_config_tracker_->DetachFromPrefService();
702 if (host_content_settings_map_.get())
703 host_content_settings_map_->ShutdownOnUIThread();
705 // This causes the Preferences file to be written to disk.
706 if (prefs_loaded)
707 SetExitType(EXIT_NORMAL);
710 std::string ProfileImpl::GetProfileUserName() const {
711 const SigninManagerBase* signin_manager =
712 SigninManagerFactory::GetForProfileIfExists(this);
713 if (signin_manager)
714 return signin_manager->GetAuthenticatedUsername();
716 return std::string();
719 Profile::ProfileType ProfileImpl::GetProfileType() const {
720 return REGULAR_PROFILE;
723 scoped_ptr<content::ZoomLevelDelegate>
724 ProfileImpl::CreateZoomLevelDelegate(const base::FilePath& partition_path) {
725 return make_scoped_ptr(new chrome::ChromeZoomLevelPrefs(
726 GetPrefs(), GetPath(), partition_path,
727 ui_zoom::ZoomEventManager::GetForBrowserContext(this)->GetWeakPtr()));
730 base::FilePath ProfileImpl::GetPath() const {
731 return path_;
734 scoped_refptr<base::SequencedTaskRunner> ProfileImpl::GetIOTaskRunner() {
735 return JsonPrefStore::GetTaskRunnerForFile(
736 GetPath(), BrowserThread::GetBlockingPool());
739 bool ProfileImpl::IsOffTheRecord() const {
740 return false;
743 Profile* ProfileImpl::GetOffTheRecordProfile() {
744 if (!off_the_record_profile_) {
745 scoped_ptr<Profile> p(CreateOffTheRecordProfile());
746 off_the_record_profile_.swap(p);
748 content::NotificationService::current()->Notify(
749 chrome::NOTIFICATION_PROFILE_CREATED,
750 content::Source<Profile>(off_the_record_profile_.get()),
751 content::NotificationService::NoDetails());
753 return off_the_record_profile_.get();
756 void ProfileImpl::DestroyOffTheRecordProfile() {
757 off_the_record_profile_.reset();
758 #if defined(ENABLE_EXTENSIONS)
759 ExtensionPrefValueMapFactory::GetForBrowserContext(this)->
760 ClearAllIncognitoSessionOnlyPreferences();
761 #endif
764 bool ProfileImpl::HasOffTheRecordProfile() {
765 return off_the_record_profile_.get() != NULL;
768 Profile* ProfileImpl::GetOriginalProfile() {
769 return this;
772 bool ProfileImpl::IsSupervised() {
773 return !GetPrefs()->GetString(prefs::kSupervisedUserId).empty();
776 bool ProfileImpl::IsChild() {
777 #if defined(ENABLE_SUPERVISED_USERS)
778 return GetPrefs()->GetString(prefs::kSupervisedUserId) ==
779 supervised_users::kChildAccountSUID;
780 #else
781 return false;
782 #endif
785 bool ProfileImpl::IsLegacySupervised() {
786 return IsSupervised() && !IsChild();
789 ExtensionSpecialStoragePolicy*
790 ProfileImpl::GetExtensionSpecialStoragePolicy() {
791 #if defined(ENABLE_EXTENSIONS)
792 if (!extension_special_storage_policy_.get()) {
793 TRACE_EVENT0("browser", "ProfileImpl::GetExtensionSpecialStoragePolicy")
794 extension_special_storage_policy_ = new ExtensionSpecialStoragePolicy(
795 CookieSettingsFactory::GetForProfile(this).get());
797 return extension_special_storage_policy_.get();
798 #else
799 return NULL;
800 #endif
803 void ProfileImpl::OnLocaleReady() {
804 TRACE_EVENT0("browser", "ProfileImpl::OnLocaleReady");
805 SCOPED_UMA_HISTOGRAM_TIMER("Profile.OnLocaleReadyTime");
806 // Migrate obsolete prefs.
807 if (g_browser_process->local_state())
808 chrome::MigrateObsoleteBrowserPrefs(this, g_browser_process->local_state());
809 chrome::MigrateObsoleteProfilePrefs(this);
811 // |kSessionExitType| was added after |kSessionExitedCleanly|. If the pref
812 // value is empty fallback to checking for |kSessionExitedCleanly|.
813 const std::string exit_type_pref_value(
814 prefs_->GetString(prefs::kSessionExitType));
815 if (exit_type_pref_value.empty()) {
816 last_session_exit_type_ =
817 prefs_->GetBoolean(prefs::kSessionExitedCleanly) ?
818 EXIT_NORMAL : EXIT_CRASHED;
819 } else {
820 last_session_exit_type_ =
821 SessionTypePrefValueToExitType(exit_type_pref_value);
823 // Mark the session as open.
824 prefs_->SetString(prefs::kSessionExitType, kPrefExitTypeCrashed);
825 // Force this to true in case we fallback and use it.
826 // TODO(sky): remove this in a couple of releases (m28ish).
827 prefs_->SetBoolean(prefs::kSessionExitedCleanly, true);
829 #if defined(SAFE_BROWSING_DB_REMOTE)
830 // Hardcode this pref on this build of Android until the UX is developed.
831 // http://crbug.com/481558
832 prefs_->SetBoolean(prefs::kSafeBrowsingEnabled, true);
833 #endif
835 g_browser_process->profile_manager()->InitProfileUserPrefs(this);
838 SCOPED_UMA_HISTOGRAM_TIMER("Profile.CreateBrowserContextServicesTime");
839 BrowserContextDependencyManager::GetInstance()->
840 CreateBrowserContextServices(this);
843 DCHECK(!net_pref_observer_);
845 TRACE_EVENT0("browser", "ProfileImpl::OnPrefsLoaded:NetPrefObserver")
846 net_pref_observer_.reset(new NetPrefObserver(prefs_.get()));
849 chrome_prefs::SchedulePrefsFilePathVerification(path_);
851 ChromeVersionService::OnProfileLoaded(prefs_.get(), IsNewProfile());
852 DoFinalInit();
855 void ProfileImpl::OnPrefsLoaded(CreateMode create_mode, bool success) {
856 TRACE_EVENT0("browser", "ProfileImpl::OnPrefsLoaded");
857 if (!success) {
858 if (delegate_)
859 delegate_->OnProfileCreated(this, false, false);
860 return;
863 #if defined(OS_CHROMEOS)
864 if (create_mode == CREATE_MODE_SYNCHRONOUS) {
865 // Synchronous create mode implies that either it is restart after crash,
866 // or we are in tests. In both cases the first loaded locale is correct.
867 OnLocaleReady();
868 } else {
869 chromeos::UserSessionManager::GetInstance()->RespectLocalePreferenceWrapper(
870 this, base::Bind(&ProfileImpl::OnLocaleReady, base::Unretained(this)));
872 #else
873 OnLocaleReady();
874 #endif
877 bool ProfileImpl::WasCreatedByVersionOrLater(const std::string& version) {
878 Version profile_version(ChromeVersionService::GetVersion(prefs_.get()));
879 Version arg_version(version);
880 return (profile_version.CompareTo(arg_version) >= 0);
883 void ProfileImpl::SetExitType(ExitType exit_type) {
884 #if defined(OS_CHROMEOS)
885 if (chromeos::ProfileHelper::IsSigninProfile(this))
886 return;
887 #endif
888 if (!prefs_)
889 return;
890 ExitType current_exit_type = SessionTypePrefValueToExitType(
891 prefs_->GetString(prefs::kSessionExitType));
892 // This may be invoked multiple times during shutdown. Only persist the value
893 // first passed in (unless it's a reset to the crash state, which happens when
894 // foregrounding the app on mobile).
895 if (exit_type == EXIT_CRASHED || current_exit_type == EXIT_CRASHED) {
896 prefs_->SetString(prefs::kSessionExitType,
897 ExitTypeToSessionTypePrefValue(exit_type));
901 Profile::ExitType ProfileImpl::GetLastSessionExitType() {
902 // last_session_exited_cleanly_ is set when the preferences are loaded. Force
903 // it to be set by asking for the prefs.
904 GetPrefs();
905 return last_session_exit_type_;
908 PrefService* ProfileImpl::GetPrefs() {
909 return const_cast<PrefService*>(
910 static_cast<const ProfileImpl*>(this)->GetPrefs());
913 const PrefService* ProfileImpl::GetPrefs() const {
914 DCHECK(prefs_); // Should explicitly be initialized.
915 return prefs_.get();
918 chrome::ChromeZoomLevelPrefs* ProfileImpl::GetZoomLevelPrefs() {
919 return static_cast<chrome::ChromeZoomLevelPrefs*>(
920 GetDefaultStoragePartition(this)->GetZoomLevelDelegate());
923 PrefService* ProfileImpl::GetOffTheRecordPrefs() {
924 DCHECK(prefs_);
925 if (!otr_prefs_) {
926 // The new ExtensionPrefStore is ref_counted and the new PrefService
927 // stores a reference so that we do not leak memory here.
928 otr_prefs_.reset(prefs_->CreateIncognitoPrefService(
929 CreateExtensionPrefStore(this, true)));
931 return otr_prefs_.get();
934 net::URLRequestContextGetter* ProfileImpl::CreateRequestContext(
935 content::ProtocolHandlerMap* protocol_handlers,
936 content::URLRequestInterceptorScopedVector request_interceptors) {
937 return io_data_.CreateMainRequestContextGetter(
938 protocol_handlers,
939 request_interceptors.Pass(),
940 g_browser_process->local_state(),
941 g_browser_process->io_thread()).get();
944 net::URLRequestContextGetter* ProfileImpl::GetRequestContext() {
945 return GetDefaultStoragePartition(this)->GetURLRequestContext();
948 net::URLRequestContextGetter* ProfileImpl::GetRequestContextForRenderProcess(
949 int renderer_child_id) {
950 content::RenderProcessHost* rph = content::RenderProcessHost::FromID(
951 renderer_child_id);
953 return rph->GetStoragePartition()->GetURLRequestContext();
956 net::URLRequestContextGetter* ProfileImpl::GetMediaRequestContext() {
957 // Return the default media context.
958 return io_data_.GetMediaRequestContextGetter().get();
961 net::URLRequestContextGetter*
962 ProfileImpl::GetMediaRequestContextForRenderProcess(
963 int renderer_child_id) {
964 content::RenderProcessHost* rph = content::RenderProcessHost::FromID(
965 renderer_child_id);
966 content::StoragePartition* storage_partition = rph->GetStoragePartition();
968 return storage_partition->GetMediaURLRequestContext();
971 net::URLRequestContextGetter*
972 ProfileImpl::GetMediaRequestContextForStoragePartition(
973 const base::FilePath& partition_path,
974 bool in_memory) {
975 return io_data_
976 .GetIsolatedMediaRequestContextGetter(partition_path, in_memory).get();
979 content::ResourceContext* ProfileImpl::GetResourceContext() {
980 return io_data_.GetResourceContext();
983 net::URLRequestContextGetter* ProfileImpl::GetRequestContextForExtensions() {
984 return io_data_.GetExtensionsRequestContextGetter().get();
987 net::URLRequestContextGetter*
988 ProfileImpl::CreateRequestContextForStoragePartition(
989 const base::FilePath& partition_path,
990 bool in_memory,
991 content::ProtocolHandlerMap* protocol_handlers,
992 content::URLRequestInterceptorScopedVector request_interceptors) {
993 return io_data_.CreateIsolatedAppRequestContextGetter(
994 partition_path,
995 in_memory,
996 protocol_handlers,
997 request_interceptors.Pass()).get();
1000 net::SSLConfigService* ProfileImpl::GetSSLConfigService() {
1001 // If ssl_config_service_manager_ is null, this typically means that some
1002 // KeyedService is trying to create a RequestContext at startup,
1003 // but SSLConfigServiceManager is not initialized until DoFinalInit() which is
1004 // invoked after all KeyedServices have been initialized (see
1005 // http://crbug.com/171406).
1006 DCHECK(ssl_config_service_manager_) <<
1007 "SSLConfigServiceManager is not initialized yet";
1008 return ssl_config_service_manager_->Get();
1011 HostContentSettingsMap* ProfileImpl::GetHostContentSettingsMap() {
1012 DCHECK_CURRENTLY_ON(BrowserThread::UI);
1013 if (!host_content_settings_map_.get()) {
1014 host_content_settings_map_ = new HostContentSettingsMap(GetPrefs(), false);
1015 #if defined(ENABLE_SUPERVISED_USERS)
1016 SupervisedUserSettingsService* supervised_user_settings =
1017 SupervisedUserSettingsServiceFactory::GetForProfile(this);
1018 scoped_ptr<content_settings::SupervisedProvider> supervised_provider(
1019 new content_settings::SupervisedProvider(supervised_user_settings));
1020 host_content_settings_map_->RegisterProvider(
1021 HostContentSettingsMap::SUPERVISED_PROVIDER,
1022 supervised_provider.Pass());
1023 #endif
1025 return host_content_settings_map_.get();
1028 content::BrowserPluginGuestManager* ProfileImpl::GetGuestManager() {
1029 #if defined(ENABLE_EXTENSIONS)
1030 return guest_view::GuestViewManager::FromBrowserContext(this);
1031 #else
1032 return NULL;
1033 #endif
1036 DownloadManagerDelegate* ProfileImpl::GetDownloadManagerDelegate() {
1037 return DownloadServiceFactory::GetForBrowserContext(this)->
1038 GetDownloadManagerDelegate();
1041 storage::SpecialStoragePolicy* ProfileImpl::GetSpecialStoragePolicy() {
1042 #if defined(ENABLE_EXTENSIONS)
1043 return GetExtensionSpecialStoragePolicy();
1044 #else
1045 return NULL;
1046 #endif
1049 content::PushMessagingService* ProfileImpl::GetPushMessagingService() {
1050 return PushMessagingServiceFactory::GetForProfile(this);
1053 content::SSLHostStateDelegate* ProfileImpl::GetSSLHostStateDelegate() {
1054 return ChromeSSLHostStateDelegateFactory::GetForProfile(this);
1057 // TODO(mlamouri): we should all these BrowserContext implementation to Profile
1058 // instead of repeating them inside all Profile implementations.
1059 content::PermissionManager* ProfileImpl::GetPermissionManager() {
1060 return PermissionManagerFactory::GetForProfile(this);
1063 bool ProfileImpl::IsSameProfile(Profile* profile) {
1064 if (profile == static_cast<Profile*>(this))
1065 return true;
1066 Profile* otr_profile = off_the_record_profile_.get();
1067 return otr_profile && profile == otr_profile;
1070 Time ProfileImpl::GetStartTime() const {
1071 return start_time_;
1074 #if defined(ENABLE_SESSION_SERVICE)
1075 void ProfileImpl::StopCreateSessionServiceTimer() {
1076 create_session_service_timer_.Stop();
1079 void ProfileImpl::EnsureSessionServiceCreated() {
1080 SessionServiceFactory::GetForProfile(this);
1082 #endif
1084 #if defined(OS_CHROMEOS)
1085 void ProfileImpl::ChangeAppLocale(
1086 const std::string& new_locale, AppLocaleChangedVia via) {
1087 if (new_locale.empty()) {
1088 NOTREACHED();
1089 return;
1091 PrefService* local_state = g_browser_process->local_state();
1092 DCHECK(local_state);
1093 if (local_state->IsManagedPreference(prefs::kApplicationLocale))
1094 return;
1095 std::string pref_locale = GetPrefs()->GetString(prefs::kApplicationLocale);
1096 bool do_update_pref = true;
1097 switch (via) {
1098 case APP_LOCALE_CHANGED_VIA_SETTINGS:
1099 case APP_LOCALE_CHANGED_VIA_REVERT: {
1100 // We keep kApplicationLocaleBackup value as a reference. In case value
1101 // of kApplicationLocale preference would change due to sync from other
1102 // device then kApplicationLocaleBackup value will trigger and allow us to
1103 // show notification about automatic locale change in LocaleChangeGuard.
1104 GetPrefs()->SetString(prefs::kApplicationLocaleBackup, new_locale);
1105 GetPrefs()->ClearPref(prefs::kApplicationLocaleAccepted);
1106 // We maintain kApplicationLocale property in both a global storage
1107 // and user's profile. Global property determines locale of login screen,
1108 // while user's profile determines his personal locale preference.
1109 break;
1111 case APP_LOCALE_CHANGED_VIA_LOGIN:
1112 case APP_LOCALE_CHANGED_VIA_PUBLIC_SESSION_LOGIN: {
1113 if (!pref_locale.empty()) {
1114 DCHECK(pref_locale == new_locale);
1115 std::string accepted_locale =
1116 GetPrefs()->GetString(prefs::kApplicationLocaleAccepted);
1117 if (accepted_locale == new_locale) {
1118 // If locale is accepted then we do not want to show LocaleChange
1119 // notification. This notification is triggered by different values
1120 // of kApplicationLocaleBackup and kApplicationLocale preferences,
1121 // so make them identical.
1122 GetPrefs()->SetString(prefs::kApplicationLocaleBackup, new_locale);
1123 } else {
1124 // Back up locale of login screen.
1125 std::string cur_locale = g_browser_process->GetApplicationLocale();
1126 GetPrefs()->SetString(prefs::kApplicationLocaleBackup, cur_locale);
1127 if (locale_change_guard_ == NULL)
1128 locale_change_guard_.reset(new chromeos::LocaleChangeGuard(this));
1129 locale_change_guard_->PrepareChangingLocale(cur_locale, new_locale);
1131 } else {
1132 std::string cur_locale = g_browser_process->GetApplicationLocale();
1133 std::string backup_locale =
1134 GetPrefs()->GetString(prefs::kApplicationLocaleBackup);
1135 // Profile synchronization takes time and is not completed at that
1136 // moment at first login. So we initialize locale preference in steps:
1137 // (1) first save it to temporary backup;
1138 // (2) on next login we assume that synchronization is already completed
1139 // and we may finalize initialization.
1140 GetPrefs()->SetString(prefs::kApplicationLocaleBackup, cur_locale);
1141 if (!new_locale.empty())
1142 GetPrefs()->SetString(prefs::kApplicationLocale, new_locale);
1143 else if (!backup_locale.empty())
1144 GetPrefs()->SetString(prefs::kApplicationLocale, backup_locale);
1145 do_update_pref = false;
1147 break;
1149 case APP_LOCALE_CHANGED_VIA_UNKNOWN:
1150 default: {
1151 NOTREACHED();
1152 break;
1155 if (do_update_pref)
1156 GetPrefs()->SetString(prefs::kApplicationLocale, new_locale);
1157 if (via != APP_LOCALE_CHANGED_VIA_PUBLIC_SESSION_LOGIN)
1158 local_state->SetString(prefs::kApplicationLocale, new_locale);
1160 if (user_manager::UserManager::Get()->GetOwnerEmail() ==
1161 chromeos::ProfileHelper::Get()->GetUserByProfile(this)->email())
1162 local_state->SetString(prefs::kOwnerLocale, new_locale);
1165 void ProfileImpl::OnLogin() {
1166 if (locale_change_guard_ == NULL)
1167 locale_change_guard_.reset(new chromeos::LocaleChangeGuard(this));
1168 locale_change_guard_->OnLogin();
1171 void ProfileImpl::InitChromeOSPreferences() {
1172 chromeos_preferences_.reset(new chromeos::Preferences());
1173 chromeos_preferences_->Init(
1174 this, chromeos::ProfileHelper::Get()->GetUserByProfile(this));
1177 #endif // defined(OS_CHROMEOS)
1179 PrefProxyConfigTracker* ProfileImpl::GetProxyConfigTracker() {
1180 if (!pref_proxy_config_tracker_)
1181 pref_proxy_config_tracker_.reset(CreateProxyConfigTracker());
1182 return pref_proxy_config_tracker_.get();
1185 chrome_browser_net::Predictor* ProfileImpl::GetNetworkPredictor() {
1186 return predictor_;
1189 DevToolsNetworkController* ProfileImpl::GetDevToolsNetworkController() {
1190 return io_data_.GetDevToolsNetworkController();
1193 void ProfileImpl::ClearNetworkingHistorySince(
1194 base::Time time,
1195 const base::Closure& completion) {
1196 io_data_.ClearNetworkingHistorySince(time, completion);
1199 GURL ProfileImpl::GetHomePage() {
1200 // --homepage overrides any preferences.
1201 const base::CommandLine& command_line =
1202 *base::CommandLine::ForCurrentProcess();
1203 if (command_line.HasSwitch(switches::kHomePage)) {
1204 // TODO(evanm): clean up usage of DIR_CURRENT.
1205 // http://code.google.com/p/chromium/issues/detail?id=60630
1206 // For now, allow this code to call getcwd().
1207 base::ThreadRestrictions::ScopedAllowIO allow_io;
1209 base::FilePath browser_directory;
1210 PathService::Get(base::DIR_CURRENT, &browser_directory);
1211 GURL home_page(url_fixer::FixupRelativeFile(
1212 browser_directory,
1213 command_line.GetSwitchValuePath(switches::kHomePage)));
1214 if (home_page.is_valid())
1215 return home_page;
1218 if (GetPrefs()->GetBoolean(prefs::kHomePageIsNewTabPage))
1219 return GURL(chrome::kChromeUINewTabURL);
1220 GURL home_page(url_fixer::FixupURL(GetPrefs()->GetString(prefs::kHomePage),
1221 std::string()));
1222 if (!home_page.is_valid())
1223 return GURL(chrome::kChromeUINewTabURL);
1224 return home_page;
1227 void ProfileImpl::UpdateProfileSupervisedUserIdCache() {
1228 ProfileManager* profile_manager = g_browser_process->profile_manager();
1229 ProfileInfoCache& cache = profile_manager->GetProfileInfoCache();
1230 size_t index = cache.GetIndexOfProfileWithPath(GetPath());
1231 if (index != std::string::npos) {
1232 std::string supervised_user_id =
1233 GetPrefs()->GetString(prefs::kSupervisedUserId);
1234 cache.SetSupervisedUserIdOfProfileAtIndex(index, supervised_user_id);
1235 ProfileMetrics::UpdateReportedProfilesStatistics(profile_manager);
1239 void ProfileImpl::UpdateProfileNameCache() {
1240 ProfileManager* profile_manager = g_browser_process->profile_manager();
1241 ProfileInfoCache& cache = profile_manager->GetProfileInfoCache();
1242 size_t index = cache.GetIndexOfProfileWithPath(GetPath());
1243 if (index != std::string::npos) {
1244 std::string profile_name =
1245 GetPrefs()->GetString(prefs::kProfileName);
1246 cache.SetNameOfProfileAtIndex(index, base::UTF8ToUTF16(profile_name));
1247 bool default_name =
1248 GetPrefs()->GetBoolean(prefs::kProfileUsingDefaultName);
1249 cache.SetProfileIsUsingDefaultNameAtIndex(index, default_name);
1253 void ProfileImpl::UpdateProfileAvatarCache() {
1254 ProfileManager* profile_manager = g_browser_process->profile_manager();
1255 ProfileInfoCache& cache = profile_manager->GetProfileInfoCache();
1256 size_t index = cache.GetIndexOfProfileWithPath(GetPath());
1257 if (index != std::string::npos) {
1258 size_t avatar_index =
1259 GetPrefs()->GetInteger(prefs::kProfileAvatarIndex);
1260 cache.SetAvatarIconOfProfileAtIndex(index, avatar_index);
1261 bool default_avatar =
1262 GetPrefs()->GetBoolean(prefs::kProfileUsingDefaultAvatar);
1263 cache.SetProfileIsUsingDefaultAvatarAtIndex(index, default_avatar);
1264 bool gaia_avatar =
1265 GetPrefs()->GetBoolean(prefs::kProfileUsingGAIAAvatar);
1266 cache.SetIsUsingGAIAPictureOfProfileAtIndex(index, gaia_avatar);
1270 void ProfileImpl::UpdateProfileIsEphemeralCache() {
1271 ProfileManager* profile_manager = g_browser_process->profile_manager();
1272 ProfileInfoCache& cache = profile_manager->GetProfileInfoCache();
1273 size_t index = cache.GetIndexOfProfileWithPath(GetPath());
1274 if (index != std::string::npos) {
1275 bool is_ephemeral = GetPrefs()->GetBoolean(prefs::kForceEphemeralProfiles);
1276 cache.SetProfileIsEphemeralAtIndex(index, is_ephemeral);
1280 // Gets the cache parameters from the command line. If |is_media_context| is
1281 // set to true then settings for the media context type is what we need,
1282 // |cache_path| will be set to the user provided path, or will not be touched if
1283 // there is not an argument. |max_size| will be the user provided value or zero
1284 // by default.
1285 void ProfileImpl::GetCacheParameters(bool is_media_context,
1286 base::FilePath* cache_path,
1287 int* max_size) {
1288 DCHECK(cache_path);
1289 DCHECK(max_size);
1290 base::FilePath path(prefs_->GetFilePath(prefs::kDiskCacheDir));
1291 if (!path.empty())
1292 *cache_path = path;
1293 *max_size = is_media_context ? prefs_->GetInteger(prefs::kMediaCacheSize) :
1294 prefs_->GetInteger(prefs::kDiskCacheSize);
1297 PrefProxyConfigTracker* ProfileImpl::CreateProxyConfigTracker() {
1298 #if defined(OS_CHROMEOS)
1299 if (chromeos::ProfileHelper::IsSigninProfile(this)) {
1300 return ProxyServiceFactory::CreatePrefProxyConfigTrackerOfLocalState(
1301 g_browser_process->local_state());
1303 #endif // defined(OS_CHROMEOS)
1304 return ProxyServiceFactory::CreatePrefProxyConfigTrackerOfProfile(
1305 GetPrefs(), g_browser_process->local_state());
1308 scoped_ptr<domain_reliability::DomainReliabilityMonitor>
1309 ProfileImpl::CreateDomainReliabilityMonitor(PrefService* local_state) {
1310 domain_reliability::DomainReliabilityService* service =
1311 domain_reliability::DomainReliabilityServiceFactory::GetInstance()->
1312 GetForBrowserContext(this);
1313 if (!service)
1314 return scoped_ptr<domain_reliability::DomainReliabilityMonitor>();
1316 return service->CreateMonitor(
1317 BrowserThread::GetMessageLoopProxyForThread(BrowserThread::IO));