Fire an error if a pref used in the UI is missing once all prefs are fetched.
[chromium-blink-merge.git] / chrome / browser / profiles / profile_impl.cc
blobaa365dd3beef5faab6788e880dd25f645ed01d19
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/trace_event/trace_event.h"
29 #include "base/version.h"
30 #include "chrome/browser/autocomplete/autocomplete_classifier.h"
31 #include "chrome/browser/autocomplete/shortcuts_backend.h"
32 #include "chrome/browser/background/background_contents_service_factory.h"
33 #include "chrome/browser/bookmarks/bookmark_model_factory.h"
34 #include "chrome/browser/browser_process.h"
35 #include "chrome/browser/chrome_notification_types.h"
36 #include "chrome/browser/content_settings/cookie_settings.h"
37 #include "chrome/browser/dom_distiller/profile_utils.h"
38 #include "chrome/browser/domain_reliability/service_factory.h"
39 #include "chrome/browser/download/chrome_download_manager_delegate.h"
40 #include "chrome/browser/download/download_service.h"
41 #include "chrome/browser/download/download_service_factory.h"
42 #include "chrome/browser/net/net_pref_observer.h"
43 #include "chrome/browser/net/predictor.h"
44 #include "chrome/browser/net/pref_proxy_config_tracker.h"
45 #include "chrome/browser/net/proxy_service_factory.h"
46 #include "chrome/browser/net/ssl_config_service_manager.h"
47 #include "chrome/browser/plugins/chrome_plugin_service_filter.h"
48 #include "chrome/browser/plugins/plugin_prefs.h"
49 #include "chrome/browser/policy/profile_policy_connector.h"
50 #include "chrome/browser/policy/profile_policy_connector_factory.h"
51 #include "chrome/browser/prefs/browser_prefs.h"
52 #include "chrome/browser/prefs/chrome_pref_service_factory.h"
53 #include "chrome/browser/prefs/pref_service_syncable.h"
54 #include "chrome/browser/prefs/tracked/tracked_preference_validation_delegate.h"
55 #include "chrome/browser/prerender/prerender_manager_factory.h"
56 #include "chrome/browser/profiles/bookmark_model_loaded_observer.h"
57 #include "chrome/browser/profiles/chrome_version_service.h"
58 #include "chrome/browser/profiles/gaia_info_update_service_factory.h"
59 #include "chrome/browser/profiles/profile_destroyer.h"
60 #include "chrome/browser/profiles/profile_info_cache.h"
61 #include "chrome/browser/profiles/profile_manager.h"
62 #include "chrome/browser/profiles/profile_metrics.h"
63 #include "chrome/browser/push_messaging/push_messaging_service_factory.h"
64 #include "chrome/browser/push_messaging/push_messaging_service_impl.h"
65 #include "chrome/browser/safe_browsing/safe_browsing_service.h"
66 #include "chrome/browser/services/gcm/gcm_profile_service.h"
67 #include "chrome/browser/sessions/session_service_factory.h"
68 #include "chrome/browser/signin/signin_manager_factory.h"
69 #include "chrome/browser/signin/signin_ui_util.h"
70 #include "chrome/browser/ssl/chrome_ssl_host_state_delegate.h"
71 #include "chrome/browser/ssl/chrome_ssl_host_state_delegate_factory.h"
72 #include "chrome/browser/ui/startup/startup_browser_creator.h"
73 #include "chrome/browser/ui/zoom/chrome_zoom_level_prefs.h"
74 #include "chrome/common/chrome_constants.h"
75 #include "chrome/common/chrome_paths_internal.h"
76 #include "chrome/common/chrome_switches.h"
77 #include "chrome/common/chrome_version_info.h"
78 #include "chrome/common/pref_names.h"
79 #include "chrome/common/url_constants.h"
80 #include "chrome/grit/chromium_strings.h"
81 #include "components/bookmarks/browser/bookmark_model.h"
82 #include "components/content_settings/core/browser/host_content_settings_map.h"
83 #include "components/domain_reliability/monitor.h"
84 #include "components/domain_reliability/service.h"
85 #include "components/keyed_service/content/browser_context_dependency_manager.h"
86 #include "components/metrics/metrics_service.h"
87 #include "components/pref_registry/pref_registry_syncable.h"
88 #include "components/signin/core/browser/signin_manager.h"
89 #include "components/startup_metric_utils/startup_metric_utils.h"
90 #include "components/ui/zoom/zoom_event_manager.h"
91 #include "components/url_fixer/url_fixer.h"
92 #include "components/user_prefs/user_prefs.h"
93 #include "content/public/browser/browser_thread.h"
94 #include "content/public/browser/dom_storage_context.h"
95 #include "content/public/browser/notification_service.h"
96 #include "content/public/browser/render_process_host.h"
97 #include "content/public/browser/storage_partition.h"
98 #include "content/public/browser/url_data_source.h"
99 #include "content/public/browser/user_metrics.h"
100 #include "content/public/common/content_constants.h"
101 #include "content/public/common/page_zoom.h"
102 #include "ui/base/l10n/l10n_util.h"
104 #if defined(OS_ANDROID)
105 #include "chrome/browser/media/protected_media_identifier_permission_context.h"
106 #include "chrome/browser/media/protected_media_identifier_permission_context_factory.h"
107 #endif
109 #if defined(OS_CHROMEOS)
110 #include "chrome/browser/chromeos/locale_change_guard.h"
111 #include "chrome/browser/chromeos/preferences.h"
112 #include "chrome/browser/chromeos/profiles/profile_helper.h"
113 #include "components/user_manager/user_manager.h"
114 #endif
116 #if defined(ENABLE_BACKGROUND)
117 #include "chrome/browser/background/background_mode_manager.h"
118 #endif
120 #if defined(ENABLE_CONFIGURATION_POLICY)
121 #include "chrome/browser/policy/schema_registry_service.h"
122 #include "chrome/browser/policy/schema_registry_service_factory.h"
123 #include "components/policy/core/browser/browser_policy_connector.h"
124 #if defined(OS_CHROMEOS)
125 #include "chrome/browser/chromeos/login/session/user_session_manager.h"
126 #include "chrome/browser/chromeos/policy/user_cloud_policy_manager_chromeos.h"
127 #include "chrome/browser/chromeos/policy/user_cloud_policy_manager_factory_chromeos.h"
128 #else
129 #include "chrome/browser/policy/cloud/user_cloud_policy_manager_factory.h"
130 #include "components/policy/core/common/cloud/user_cloud_policy_manager.h"
131 #endif
132 #endif
134 #if defined(ENABLE_EXTENSIONS)
135 #include "chrome/browser/extensions/extension_service.h"
136 #include "chrome/browser/extensions/extension_special_storage_policy.h"
137 #include "chrome/browser/ui/webui/extensions/extension_icon_source.h"
138 #include "extensions/browser/extension_pref_store.h"
139 #include "extensions/browser/extension_pref_value_map.h"
140 #include "extensions/browser/extension_pref_value_map_factory.h"
141 #include "extensions/browser/extension_system.h"
142 #include "extensions/browser/guest_view/guest_view_manager.h"
143 #endif
145 #if defined(ENABLE_SUPERVISED_USERS)
146 #include "chrome/browser/content_settings/content_settings_supervised_provider.h"
147 #include "chrome/browser/supervised_user/supervised_user_constants.h"
148 #include "chrome/browser/supervised_user/supervised_user_settings_service.h"
149 #include "chrome/browser/supervised_user/supervised_user_settings_service_factory.h"
150 #endif
152 using base::Time;
153 using base::TimeDelta;
154 using base::UserMetricsAction;
155 using bookmarks::BookmarkModel;
156 using content::BrowserThread;
157 using content::DownloadManagerDelegate;
159 namespace {
161 #if defined(ENABLE_SESSION_SERVICE)
162 // Delay, in milliseconds, before we explicitly create the SessionService.
163 const int kCreateSessionServiceDelayMS = 500;
164 #endif
166 // Text content of README file created in each profile directory. Both %s
167 // placeholders must contain the product name. This is not localizable and hence
168 // not in resources.
169 const char kReadmeText[] =
170 "%s settings and storage represent user-selected preferences and "
171 "information and MUST not be extracted, overwritten or modified except "
172 "through %s defined APIs.";
174 // Value written to prefs for EXIT_CRASHED and EXIT_SESSION_ENDED.
175 const char kPrefExitTypeCrashed[] = "Crashed";
176 const char kPrefExitTypeSessionEnded[] = "SessionEnded";
178 // Helper method needed because PostTask cannot currently take a Callback
179 // function with non-void return type.
180 void CreateDirectoryAndSignal(const base::FilePath& path,
181 base::WaitableEvent* done_creating) {
182 DVLOG(1) << "Creating directory " << path.value();
183 base::CreateDirectory(path);
184 done_creating->Signal();
187 // Task that blocks the FILE thread until CreateDirectoryAndSignal() finishes on
188 // blocking I/O pool.
189 void BlockFileThreadOnDirectoryCreate(base::WaitableEvent* done_creating) {
190 done_creating->Wait();
193 // Initiates creation of profile directory on |sequenced_task_runner| and
194 // ensures that FILE thread is blocked until that operation finishes.
195 void CreateProfileDirectory(base::SequencedTaskRunner* sequenced_task_runner,
196 const base::FilePath& path) {
197 base::WaitableEvent* done_creating = new base::WaitableEvent(false, false);
198 sequenced_task_runner->PostTask(FROM_HERE,
199 base::Bind(&CreateDirectoryAndSignal,
200 path,
201 done_creating));
202 // Block the FILE thread until directory is created on I/O pool to make sure
203 // that we don't attempt any operation until that part completes.
204 BrowserThread::PostTask(
205 BrowserThread::FILE, FROM_HERE,
206 base::Bind(&BlockFileThreadOnDirectoryCreate,
207 base::Owned(done_creating)));
210 base::FilePath GetCachePath(const base::FilePath& base) {
211 return base.Append(chrome::kCacheDirname);
214 base::FilePath GetMediaCachePath(const base::FilePath& base) {
215 return base.Append(chrome::kMediaCacheDirname);
218 void EnsureReadmeFile(const base::FilePath& base) {
219 base::FilePath readme_path = base.Append(chrome::kReadmeFilename);
220 if (base::PathExists(readme_path))
221 return;
222 std::string product_name = l10n_util::GetStringUTF8(IDS_PRODUCT_NAME);
223 std::string readme_text = base::StringPrintf(
224 kReadmeText, product_name.c_str(), product_name.c_str());
225 if (base::WriteFile(readme_path, readme_text.data(), readme_text.size()) ==
226 -1) {
227 LOG(ERROR) << "Could not create README file.";
231 // Converts the kSessionExitedCleanly pref to the corresponding EXIT_TYPE.
232 Profile::ExitType SessionTypePrefValueToExitType(const std::string& value) {
233 if (value == kPrefExitTypeSessionEnded)
234 return Profile::EXIT_SESSION_ENDED;
235 if (value == kPrefExitTypeCrashed)
236 return Profile::EXIT_CRASHED;
237 return Profile::EXIT_NORMAL;
240 // Converts an ExitType into a string that is written to prefs.
241 std::string ExitTypeToSessionTypePrefValue(Profile::ExitType type) {
242 switch (type) {
243 case Profile::EXIT_NORMAL:
244 return ProfileImpl::kPrefExitTypeNormal;
245 case Profile::EXIT_SESSION_ENDED:
246 return kPrefExitTypeSessionEnded;
247 case Profile::EXIT_CRASHED:
248 return kPrefExitTypeCrashed;
250 NOTREACHED();
251 return std::string();
254 PrefStore* CreateExtensionPrefStore(Profile* profile,
255 bool incognito_pref_store) {
256 #if defined(ENABLE_EXTENSIONS)
257 return new ExtensionPrefStore(
258 ExtensionPrefValueMapFactory::GetForBrowserContext(profile),
259 incognito_pref_store);
260 #else
261 return NULL;
262 #endif
265 } // namespace
267 // static
268 Profile* Profile::CreateProfile(const base::FilePath& path,
269 Delegate* delegate,
270 CreateMode create_mode) {
271 TRACE_EVENT1("browser,startup",
272 "Profile::CreateProfile",
273 "profile_path",
274 path.AsUTF8Unsafe());
276 // Get sequenced task runner for making sure that file operations of
277 // this profile (defined by |path|) are executed in expected order
278 // (what was previously assured by the FILE thread).
279 scoped_refptr<base::SequencedTaskRunner> sequenced_task_runner =
280 JsonPrefStore::GetTaskRunnerForFile(path,
281 BrowserThread::GetBlockingPool());
282 if (create_mode == CREATE_MODE_ASYNCHRONOUS) {
283 DCHECK(delegate);
284 CreateProfileDirectory(sequenced_task_runner.get(), path);
285 } else if (create_mode == CREATE_MODE_SYNCHRONOUS) {
286 if (!base::PathExists(path)) {
287 // TODO(rogerta): http://crbug/160553 - Bad things happen if we can't
288 // write to the profile directory. We should eventually be able to run in
289 // this situation.
290 if (!base::CreateDirectory(path))
291 return NULL;
293 } else {
294 NOTREACHED();
297 return new ProfileImpl(
298 path, delegate, create_mode, sequenced_task_runner.get());
301 // static
302 int ProfileImpl::create_readme_delay_ms = 60000;
304 // static
305 const char* const ProfileImpl::kPrefExitTypeNormal = "Normal";
307 // static
308 void ProfileImpl::RegisterProfilePrefs(
309 user_prefs::PrefRegistrySyncable* registry) {
310 registry->RegisterBooleanPref(
311 prefs::kSavingBrowserHistoryDisabled,
312 false,
313 user_prefs::PrefRegistrySyncable::UNSYNCABLE_PREF);
314 registry->RegisterBooleanPref(
315 prefs::kAllowDeletingBrowserHistory,
316 true,
317 user_prefs::PrefRegistrySyncable::UNSYNCABLE_PREF);
318 registry->RegisterBooleanPref(
319 prefs::kSigninAllowed,
320 true,
321 user_prefs::PrefRegistrySyncable::UNSYNCABLE_PREF);
322 registry->RegisterBooleanPref(
323 prefs::kForceSafeSearch,
324 false,
325 user_prefs::PrefRegistrySyncable::UNSYNCABLE_PREF);
326 registry->RegisterBooleanPref(
327 prefs::kForceGoogleSafeSearch,
328 false,
329 user_prefs::PrefRegistrySyncable::UNSYNCABLE_PREF);
330 registry->RegisterBooleanPref(
331 prefs::kForceYouTubeSafetyMode,
332 false,
333 user_prefs::PrefRegistrySyncable::UNSYNCABLE_PREF);
334 registry->RegisterBooleanPref(
335 prefs::kRecordHistory,
336 false,
337 user_prefs::PrefRegistrySyncable::UNSYNCABLE_PREF);
338 registry->RegisterIntegerPref(
339 prefs::kProfileAvatarIndex,
341 user_prefs::PrefRegistrySyncable::SYNCABLE_PREF);
342 // Whether a profile is using an avatar without having explicitely chosen it
343 // (i.e. was assigned by default by legacy profile creation).
344 registry->RegisterBooleanPref(
345 prefs::kProfileUsingDefaultAvatar,
346 true,
347 user_prefs::PrefRegistrySyncable::SYNCABLE_PREF);
348 registry->RegisterBooleanPref(
349 prefs::kProfileUsingGAIAAvatar,
350 false,
351 user_prefs::PrefRegistrySyncable::SYNCABLE_PREF);
352 // Whether a profile is using a default avatar name (eg. Pickles or Person 1).
353 registry->RegisterBooleanPref(
354 prefs::kProfileUsingDefaultName,
355 true,
356 user_prefs::PrefRegistrySyncable::SYNCABLE_PREF);
357 registry->RegisterStringPref(
358 prefs::kSupervisedUserId,
359 std::string(),
360 user_prefs::PrefRegistrySyncable::UNSYNCABLE_PREF);
361 registry->RegisterStringPref(prefs::kProfileName,
362 std::string(),
363 user_prefs::PrefRegistrySyncable::SYNCABLE_PREF);
364 registry->RegisterStringPref(prefs::kHomePage,
365 std::string(),
366 user_prefs::PrefRegistrySyncable::SYNCABLE_PREF);
367 #if defined(ENABLE_PRINTING)
368 registry->RegisterBooleanPref(
369 prefs::kPrintingEnabled,
370 true,
371 user_prefs::PrefRegistrySyncable::UNSYNCABLE_PREF);
372 #endif
373 registry->RegisterBooleanPref(
374 prefs::kPrintPreviewDisabled,
375 false,
376 user_prefs::PrefRegistrySyncable::UNSYNCABLE_PREF);
377 registry->RegisterBooleanPref(
378 prefs::kForceEphemeralProfiles,
379 false,
380 user_prefs::PrefRegistrySyncable::UNSYNCABLE_PREF);
382 // Initialize the cache prefs.
383 registry->RegisterFilePathPref(
384 prefs::kDiskCacheDir,
385 base::FilePath(),
386 user_prefs::PrefRegistrySyncable::UNSYNCABLE_PREF);
387 registry->RegisterIntegerPref(
388 prefs::kDiskCacheSize,
390 user_prefs::PrefRegistrySyncable::UNSYNCABLE_PREF);
391 registry->RegisterIntegerPref(
392 prefs::kMediaCacheSize,
394 user_prefs::PrefRegistrySyncable::UNSYNCABLE_PREF);
396 // Deprecated. Kept around for migration.
397 registry->RegisterBooleanPref(
398 prefs::kClearSiteDataOnExit,
399 false,
400 user_prefs::PrefRegistrySyncable::SYNCABLE_PREF);
403 ProfileImpl::ProfileImpl(
404 const base::FilePath& path,
405 Delegate* delegate,
406 CreateMode create_mode,
407 base::SequencedTaskRunner* sequenced_task_runner)
408 : path_(path),
409 pref_registry_(new user_prefs::PrefRegistrySyncable),
410 io_data_(this),
411 host_content_settings_map_(NULL),
412 last_session_exit_type_(EXIT_NORMAL),
413 start_time_(Time::Now()),
414 delegate_(delegate),
415 predictor_(NULL) {
416 TRACE_EVENT0("browser,startup", "ProfileImpl::ctor")
417 DCHECK(!path.empty()) << "Using an empty path will attempt to write " <<
418 "profile files to the root directory!";
420 #if defined(ENABLE_SESSION_SERVICE)
421 create_session_service_timer_.Start(FROM_HERE,
422 TimeDelta::FromMilliseconds(kCreateSessionServiceDelayMS), this,
423 &ProfileImpl::EnsureSessionServiceCreated);
424 #endif
426 set_is_guest_profile(path == ProfileManager::GetGuestProfilePath());
427 set_is_system_profile(path == ProfileManager::GetSystemProfilePath());
429 // Determine if prefetch is enabled for this profile.
430 // If not profile_manager is present, it means we are in a unittest.
431 const base::CommandLine* command_line =
432 base::CommandLine::ForCurrentProcess();
433 predictor_ = chrome_browser_net::Predictor::CreatePredictor(
434 !command_line->HasSwitch(switches::kDisablePreconnect),
435 !command_line->HasSwitch(switches::kDnsPrefetchDisable),
436 g_browser_process->profile_manager() == NULL);
438 // If we are creating the profile synchronously, then we should load the
439 // policy data immediately.
440 bool force_immediate_policy_load = (create_mode == CREATE_MODE_SYNCHRONOUS);
441 #if defined(ENABLE_CONFIGURATION_POLICY)
442 policy::BrowserPolicyConnector* connector =
443 g_browser_process->browser_policy_connector();
444 schema_registry_service_ =
445 policy::SchemaRegistryServiceFactory::CreateForContext(
446 this, connector->GetChromeSchema(), connector->GetSchemaRegistry());
447 #if defined(OS_CHROMEOS)
448 cloud_policy_manager_ =
449 policy::UserCloudPolicyManagerFactoryChromeOS::CreateForProfile(
450 this, force_immediate_policy_load, sequenced_task_runner);
451 #else
452 cloud_policy_manager_ =
453 policy::UserCloudPolicyManagerFactory::CreateForOriginalBrowserContext(
454 this,
455 force_immediate_policy_load,
456 sequenced_task_runner,
457 BrowserThread::GetMessageLoopProxyForThread(BrowserThread::FILE),
458 BrowserThread::GetMessageLoopProxyForThread(BrowserThread::IO));
459 #endif
460 #endif
461 profile_policy_connector_ =
462 policy::ProfilePolicyConnectorFactory::CreateForBrowserContext(
463 this, force_immediate_policy_load);
465 DCHECK(create_mode == CREATE_MODE_ASYNCHRONOUS ||
466 create_mode == CREATE_MODE_SYNCHRONOUS);
467 bool async_prefs = create_mode == CREATE_MODE_ASYNCHRONOUS;
469 #if defined(OS_CHROMEOS)
470 if (chromeos::ProfileHelper::IsSigninProfile(this))
471 chrome::RegisterLoginProfilePrefs(pref_registry_.get());
472 else
473 #endif
474 chrome::RegisterUserProfilePrefs(pref_registry_.get());
476 BrowserContextDependencyManager::GetInstance()->
477 RegisterProfilePrefsForServices(this, pref_registry_.get());
479 SupervisedUserSettingsService* supervised_user_settings = nullptr;
480 #if defined(ENABLE_SUPERVISED_USERS)
481 supervised_user_settings =
482 SupervisedUserSettingsServiceFactory::GetForProfile(this);
483 supervised_user_settings->Init(
484 path_, sequenced_task_runner, create_mode == CREATE_MODE_SYNCHRONOUS);
485 #endif
487 scoped_refptr<SafeBrowsingService> safe_browsing_service(
488 g_browser_process->safe_browsing_service());
489 if (safe_browsing_service.get()) {
490 pref_validation_delegate_ =
491 safe_browsing_service->CreatePreferenceValidationDelegate(this).Pass();
495 // On startup, preference loading is always synchronous so a scoped timer
496 // will work here.
497 startup_metric_utils::ScopedSlowStartupUMA
498 scoped_timer("Startup.SlowStartupPreferenceLoading");
499 prefs_ = chrome_prefs::CreateProfilePrefs(
500 path_,
501 sequenced_task_runner,
502 pref_validation_delegate_.get(),
503 profile_policy_connector_->policy_service(),
504 supervised_user_settings,
505 CreateExtensionPrefStore(this, false),
506 pref_registry_,
507 async_prefs).Pass();
508 // Register on BrowserContext.
509 user_prefs::UserPrefs::Set(this, prefs_.get());
512 startup_metric_utils::ScopedSlowStartupUMA
513 scoped_timer("Startup.SlowStartupFinalProfileInit");
514 if (async_prefs) {
515 // Wait for the notification that prefs has been loaded
516 // (successfully or not). Note that we can use base::Unretained
517 // because the PrefService is owned by this class and lives on
518 // the same thread.
519 prefs_->AddPrefInitObserver(base::Bind(&ProfileImpl::OnPrefsLoaded,
520 base::Unretained(this)));
521 } else {
522 // Prefs were loaded synchronously so we can continue directly.
523 OnPrefsLoaded(true);
527 void ProfileImpl::DoFinalInit() {
528 TRACE_EVENT0("browser", "ProfileImpl::DoFinalInit")
529 PrefService* prefs = GetPrefs();
530 pref_change_registrar_.Init(prefs);
531 pref_change_registrar_.Add(
532 prefs::kSupervisedUserId,
533 base::Bind(&ProfileImpl::UpdateProfileSupervisedUserIdCache,
534 base::Unretained(this)));
536 // Changes in the profile avatar.
537 pref_change_registrar_.Add(
538 prefs::kProfileAvatarIndex,
539 base::Bind(&ProfileImpl::UpdateProfileAvatarCache,
540 base::Unretained(this)));
541 pref_change_registrar_.Add(
542 prefs::kProfileUsingDefaultAvatar,
543 base::Bind(&ProfileImpl::UpdateProfileAvatarCache,
544 base::Unretained(this)));
545 pref_change_registrar_.Add(
546 prefs::kProfileUsingGAIAAvatar,
547 base::Bind(&ProfileImpl::UpdateProfileAvatarCache,
548 base::Unretained(this)));
550 // Changes in the profile name.
551 pref_change_registrar_.Add(
552 prefs::kProfileUsingDefaultName,
553 base::Bind(&ProfileImpl::UpdateProfileNameCache,
554 base::Unretained(this)));
555 pref_change_registrar_.Add(
556 prefs::kProfileName,
557 base::Bind(&ProfileImpl::UpdateProfileNameCache,
558 base::Unretained(this)));
560 pref_change_registrar_.Add(
561 prefs::kForceEphemeralProfiles,
562 base::Bind(&ProfileImpl::UpdateProfileIsEphemeralCache,
563 base::Unretained(this)));
565 // It would be nice to use PathService for fetching this directory, but
566 // the cache directory depends on the profile directory, which isn't available
567 // to PathService.
568 chrome::GetUserCacheDirectory(path_, &base_cache_path_);
569 // Always create the cache directory asynchronously.
570 scoped_refptr<base::SequencedTaskRunner> sequenced_task_runner =
571 JsonPrefStore::GetTaskRunnerForFile(base_cache_path_,
572 BrowserThread::GetBlockingPool());
573 CreateProfileDirectory(sequenced_task_runner.get(), base_cache_path_);
575 // Initialize components that depend on the current value.
576 UpdateProfileSupervisedUserIdCache();
577 UpdateProfileIsEphemeralCache();
578 GAIAInfoUpdateServiceFactory::GetForProfile(this);
580 PrefService* local_state = g_browser_process->local_state();
581 ssl_config_service_manager_.reset(
582 SSLConfigServiceManager::CreateDefaultManager(local_state));
584 #if defined(ENABLE_BACKGROUND)
585 // Initialize the BackgroundModeManager - this has to be done here before
586 // InitExtensions() is called because it relies on receiving notifications
587 // when extensions are loaded. BackgroundModeManager is not needed under
588 // ChromeOS because Chrome is always running, no need for special keep-alive
589 // or launch-on-startup support unless kKeepAliveForTest is set.
590 bool init_background_mode_manager = true;
591 #if defined(OS_CHROMEOS)
592 if (!base::CommandLine::ForCurrentProcess()->HasSwitch(
593 switches::kKeepAliveForTest))
594 init_background_mode_manager = false;
595 #endif
596 if (init_background_mode_manager) {
597 if (g_browser_process->background_mode_manager())
598 g_browser_process->background_mode_manager()->RegisterProfile(this);
600 #endif // defined(ENABLE_BACKGROUND)
602 base::FilePath cookie_path = GetPath();
603 cookie_path = cookie_path.Append(chrome::kCookieFilename);
604 base::FilePath channel_id_path = GetPath();
605 channel_id_path = channel_id_path.Append(chrome::kChannelIDFilename);
606 base::FilePath cache_path = base_cache_path_;
607 int cache_max_size;
608 GetCacheParameters(false, &cache_path, &cache_max_size);
609 cache_path = GetCachePath(cache_path);
611 base::FilePath media_cache_path = base_cache_path_;
612 int media_cache_max_size;
613 GetCacheParameters(true, &media_cache_path, &media_cache_max_size);
614 media_cache_path = GetMediaCachePath(media_cache_path);
616 base::FilePath extensions_cookie_path = GetPath();
617 extensions_cookie_path =
618 extensions_cookie_path.Append(chrome::kExtensionsCookieFilename);
620 base::FilePath infinite_cache_path = GetPath();
621 infinite_cache_path =
622 infinite_cache_path.Append(FILE_PATH_LITERAL("Infinite Cache"));
624 #if defined(OS_ANDROID)
625 SessionStartupPref::Type startup_pref_type =
626 SessionStartupPref::GetDefaultStartupType();
627 #else
628 SessionStartupPref::Type startup_pref_type =
629 StartupBrowserCreator::GetSessionStartupPref(
630 *base::CommandLine::ForCurrentProcess(), this).type;
631 #endif
632 content::CookieStoreConfig::SessionCookieMode session_cookie_mode =
633 content::CookieStoreConfig::PERSISTANT_SESSION_COOKIES;
634 if (GetLastSessionExitType() == Profile::EXIT_CRASHED ||
635 startup_pref_type == SessionStartupPref::LAST) {
636 session_cookie_mode = content::CookieStoreConfig::RESTORED_SESSION_COOKIES;
639 // Make sure we initialize the ProfileIOData after everything else has been
640 // initialized that we might be reading from the IO thread.
642 io_data_.Init(cookie_path, channel_id_path, cache_path,
643 cache_max_size, media_cache_path, media_cache_max_size,
644 extensions_cookie_path, GetPath(), infinite_cache_path,
645 predictor_, session_cookie_mode, GetSpecialStoragePolicy(),
646 CreateDomainReliabilityMonitor(local_state));
648 #if defined(ENABLE_PLUGINS)
649 ChromePluginServiceFilter::GetInstance()->RegisterResourceContext(
650 PluginPrefs::GetForProfile(this).get(),
651 io_data_.GetResourceContextNoInit());
652 #endif
654 // Delay README creation to not impact startup performance.
655 BrowserThread::PostDelayedTask(
656 BrowserThread::FILE, FROM_HERE,
657 base::Bind(&EnsureReadmeFile, GetPath()),
658 base::TimeDelta::FromMilliseconds(create_readme_delay_ms));
660 TRACE_EVENT0("browser", "ProfileImpl::SetSaveSessionStorageOnDisk");
661 content::BrowserContext::GetDefaultStoragePartition(this)->
662 GetDOMStorageContext()->SetSaveSessionStorageOnDisk();
664 // TODO(wjmaclean): Remove this. crbug.com/420643
665 chrome::MigrateProfileZoomLevelPrefs(this);
667 // The DomDistillerViewerSource is not a normal WebUI so it must be registered
668 // as a URLDataSource early.
669 RegisterDomDistillerViewerSource(this);
671 #if defined(OS_CHROMEOS)
672 if (chromeos::UserSessionManager::GetInstance()
673 ->RestartToApplyPerSessionFlagsIfNeed(this, true)) {
674 return;
676 #endif
678 if (delegate_) {
679 TRACE_EVENT0("browser", "ProfileImpl::DoFileInit:DelegateOnProfileCreated")
680 delegate_->OnProfileCreated(this, true, IsNewProfile());
683 content::NotificationService::current()->Notify(
684 chrome::NOTIFICATION_PROFILE_CREATED,
685 content::Source<Profile>(this),
686 content::NotificationService::NoDetails());
688 #if !defined(OS_CHROMEOS)
689 // Listen for bookmark model load, to bootstrap the sync service.
690 // On CrOS sync service will be initialized after sign in.
691 BookmarkModel* model = BookmarkModelFactory::GetForProfile(this);
692 model->AddObserver(new BookmarkModelLoadedObserver(this));
693 #endif
695 PushMessagingServiceImpl::InitializeForProfile(this);
697 #if !defined(OS_ANDROID) && !defined(OS_CHROMEOS) && !defined(OS_IOS)
698 signin_ui_util::InitializePrefsForProfile(this);
699 #endif
702 base::FilePath ProfileImpl::last_selected_directory() {
703 return GetPrefs()->GetFilePath(prefs::kSelectFileLastDirectory);
706 void ProfileImpl::set_last_selected_directory(const base::FilePath& path) {
707 GetPrefs()->SetFilePath(prefs::kSelectFileLastDirectory, path);
710 ProfileImpl::~ProfileImpl() {
711 MaybeSendDestroyedNotification();
713 bool prefs_loaded = prefs_->GetInitializationStatus() !=
714 PrefService::INITIALIZATION_STATUS_WAITING;
716 #if defined(ENABLE_SESSION_SERVICE)
717 StopCreateSessionServiceTimer();
718 #endif
720 // Remove pref observers
721 pref_change_registrar_.RemoveAll();
723 #if defined(ENABLE_PLUGINS)
724 ChromePluginServiceFilter::GetInstance()->UnregisterResourceContext(
725 io_data_.GetResourceContextNoInit());
726 #endif
728 // Destroy OTR profile and its profile services first.
729 if (off_the_record_profile_) {
730 ProfileDestroyer::DestroyOffTheRecordProfileNow(
731 off_the_record_profile_.get());
732 } else {
733 #if defined(ENABLE_EXTENSIONS)
734 ExtensionPrefValueMapFactory::GetForBrowserContext(this)->
735 ClearAllIncognitoSessionOnlyPreferences();
736 #endif
739 BrowserContextDependencyManager::GetInstance()->DestroyBrowserContextServices(
740 this);
742 if (pref_proxy_config_tracker_)
743 pref_proxy_config_tracker_->DetachFromPrefService();
745 if (host_content_settings_map_.get())
746 host_content_settings_map_->ShutdownOnUIThread();
748 // This causes the Preferences file to be written to disk.
749 if (prefs_loaded)
750 SetExitType(EXIT_NORMAL);
753 std::string ProfileImpl::GetProfileUserName() const {
754 const SigninManagerBase* signin_manager =
755 SigninManagerFactory::GetForProfileIfExists(this);
756 if (signin_manager)
757 return signin_manager->GetAuthenticatedUsername();
759 return std::string();
762 Profile::ProfileType ProfileImpl::GetProfileType() const {
763 return REGULAR_PROFILE;
766 scoped_ptr<content::ZoomLevelDelegate>
767 ProfileImpl::CreateZoomLevelDelegate(const base::FilePath& partition_path) {
768 return make_scoped_ptr(new chrome::ChromeZoomLevelPrefs(
769 GetPrefs(), GetPath(), partition_path,
770 ui_zoom::ZoomEventManager::GetForBrowserContext(this)->GetWeakPtr()));
773 base::FilePath ProfileImpl::GetPath() const {
774 return path_;
777 scoped_refptr<base::SequencedTaskRunner> ProfileImpl::GetIOTaskRunner() {
778 return JsonPrefStore::GetTaskRunnerForFile(
779 GetPath(), BrowserThread::GetBlockingPool());
782 bool ProfileImpl::IsOffTheRecord() const {
783 return false;
786 Profile* ProfileImpl::GetOffTheRecordProfile() {
787 if (!off_the_record_profile_) {
788 scoped_ptr<Profile> p(CreateOffTheRecordProfile());
789 off_the_record_profile_.swap(p);
791 content::NotificationService::current()->Notify(
792 chrome::NOTIFICATION_PROFILE_CREATED,
793 content::Source<Profile>(off_the_record_profile_.get()),
794 content::NotificationService::NoDetails());
796 return off_the_record_profile_.get();
799 void ProfileImpl::DestroyOffTheRecordProfile() {
800 off_the_record_profile_.reset();
801 #if defined(ENABLE_EXTENSIONS)
802 ExtensionPrefValueMapFactory::GetForBrowserContext(this)->
803 ClearAllIncognitoSessionOnlyPreferences();
804 #endif
807 bool ProfileImpl::HasOffTheRecordProfile() {
808 return off_the_record_profile_.get() != NULL;
811 Profile* ProfileImpl::GetOriginalProfile() {
812 return this;
815 bool ProfileImpl::IsSupervised() {
816 return !GetPrefs()->GetString(prefs::kSupervisedUserId).empty();
819 bool ProfileImpl::IsChild() {
820 #if defined(ENABLE_SUPERVISED_USERS)
821 return GetPrefs()->GetString(prefs::kSupervisedUserId) ==
822 supervised_users::kChildAccountSUID;
823 #else
824 return false;
825 #endif
828 bool ProfileImpl::IsLegacySupervised() {
829 return IsSupervised() && !IsChild();
832 ExtensionSpecialStoragePolicy*
833 ProfileImpl::GetExtensionSpecialStoragePolicy() {
834 #if defined(ENABLE_EXTENSIONS)
835 if (!extension_special_storage_policy_.get()) {
836 TRACE_EVENT0("browser", "ProfileImpl::GetExtensionSpecialStoragePolicy")
837 extension_special_storage_policy_ = new ExtensionSpecialStoragePolicy(
838 CookieSettings::Factory::GetForProfile(this).get());
840 return extension_special_storage_policy_.get();
841 #else
842 return NULL;
843 #endif
846 void ProfileImpl::OnPrefsLoaded(bool success) {
847 TRACE_EVENT0("browser", "ProfileImpl::OnPrefsLoaded");
848 SCOPED_UMA_HISTOGRAM_TIMER("Profile.OnPrefsLoadedTime");
849 if (!success) {
850 if (delegate_)
851 delegate_->OnProfileCreated(this, false, false);
852 return;
855 // Migrate obsolete prefs.
856 if (g_browser_process->local_state())
857 chrome::MigrateObsoleteBrowserPrefs(this, g_browser_process->local_state());
858 chrome::MigrateObsoleteProfilePrefs(this);
860 // |kSessionExitType| was added after |kSessionExitedCleanly|. If the pref
861 // value is empty fallback to checking for |kSessionExitedCleanly|.
862 const std::string exit_type_pref_value(
863 prefs_->GetString(prefs::kSessionExitType));
864 if (exit_type_pref_value.empty()) {
865 last_session_exit_type_ =
866 prefs_->GetBoolean(prefs::kSessionExitedCleanly) ?
867 EXIT_NORMAL : EXIT_CRASHED;
868 } else {
869 last_session_exit_type_ =
870 SessionTypePrefValueToExitType(exit_type_pref_value);
872 // Mark the session as open.
873 prefs_->SetString(prefs::kSessionExitType, kPrefExitTypeCrashed);
874 // Force this to true in case we fallback and use it.
875 // TODO(sky): remove this in a couple of releases (m28ish).
876 prefs_->SetBoolean(prefs::kSessionExitedCleanly, true);
878 #if defined(OS_ANDROID) && defined(FULL_SAFE_BROWSING)
879 // Clear safe browsing setting in the case we need to roll back
880 // for users enrolled in Finch trial before.
881 if (!SafeBrowsingService::IsEnabledByFieldTrial())
882 prefs_->ClearPref(prefs::kSafeBrowsingEnabled);
883 #endif
885 g_browser_process->profile_manager()->InitProfileUserPrefs(this);
887 BrowserContextDependencyManager::GetInstance()->CreateBrowserContextServices(
888 this);
890 DCHECK(!net_pref_observer_);
892 TRACE_EVENT0("browser", "ProfileImpl::OnPrefsLoaded:NetPrefObserver")
893 net_pref_observer_.reset(new NetPrefObserver(prefs_.get()));
896 chrome_prefs::SchedulePrefsFilePathVerification(path_);
898 ChromeVersionService::OnProfileLoaded(prefs_.get(), IsNewProfile());
899 DoFinalInit();
902 bool ProfileImpl::WasCreatedByVersionOrLater(const std::string& version) {
903 Version profile_version(ChromeVersionService::GetVersion(prefs_.get()));
904 Version arg_version(version);
905 return (profile_version.CompareTo(arg_version) >= 0);
908 void ProfileImpl::SetExitType(ExitType exit_type) {
909 #if defined(OS_CHROMEOS)
910 if (chromeos::ProfileHelper::IsSigninProfile(this))
911 return;
912 #endif
913 if (!prefs_)
914 return;
915 ExitType current_exit_type = SessionTypePrefValueToExitType(
916 prefs_->GetString(prefs::kSessionExitType));
917 // This may be invoked multiple times during shutdown. Only persist the value
918 // first passed in (unless it's a reset to the crash state, which happens when
919 // foregrounding the app on mobile).
920 if (exit_type == EXIT_CRASHED || current_exit_type == EXIT_CRASHED) {
921 prefs_->SetString(prefs::kSessionExitType,
922 ExitTypeToSessionTypePrefValue(exit_type));
924 // NOTE: If you change what thread this writes on, be sure and update
925 // chrome::SessionEnding().
926 prefs_->CommitPendingWrite();
930 Profile::ExitType ProfileImpl::GetLastSessionExitType() {
931 // last_session_exited_cleanly_ is set when the preferences are loaded. Force
932 // it to be set by asking for the prefs.
933 GetPrefs();
934 return last_session_exit_type_;
937 PrefService* ProfileImpl::GetPrefs() {
938 return const_cast<PrefService*>(
939 static_cast<const ProfileImpl*>(this)->GetPrefs());
942 const PrefService* ProfileImpl::GetPrefs() const {
943 DCHECK(prefs_); // Should explicitly be initialized.
944 return prefs_.get();
947 chrome::ChromeZoomLevelPrefs* ProfileImpl::GetZoomLevelPrefs() {
948 return static_cast<chrome::ChromeZoomLevelPrefs*>(
949 GetDefaultStoragePartition(this)->GetZoomLevelDelegate());
952 PrefService* ProfileImpl::GetOffTheRecordPrefs() {
953 DCHECK(prefs_);
954 if (!otr_prefs_) {
955 // The new ExtensionPrefStore is ref_counted and the new PrefService
956 // stores a reference so that we do not leak memory here.
957 otr_prefs_.reset(prefs_->CreateIncognitoPrefService(
958 CreateExtensionPrefStore(this, true)));
960 return otr_prefs_.get();
963 net::URLRequestContextGetter* ProfileImpl::CreateRequestContext(
964 content::ProtocolHandlerMap* protocol_handlers,
965 content::URLRequestInterceptorScopedVector request_interceptors) {
966 return io_data_.CreateMainRequestContextGetter(
967 protocol_handlers,
968 request_interceptors.Pass(),
969 g_browser_process->local_state(),
970 g_browser_process->io_thread()).get();
973 net::URLRequestContextGetter* ProfileImpl::GetRequestContext() {
974 return GetDefaultStoragePartition(this)->GetURLRequestContext();
977 net::URLRequestContextGetter* ProfileImpl::GetRequestContextForRenderProcess(
978 int renderer_child_id) {
979 content::RenderProcessHost* rph = content::RenderProcessHost::FromID(
980 renderer_child_id);
982 return rph->GetStoragePartition()->GetURLRequestContext();
985 net::URLRequestContextGetter* ProfileImpl::GetMediaRequestContext() {
986 // Return the default media context.
987 return io_data_.GetMediaRequestContextGetter().get();
990 net::URLRequestContextGetter*
991 ProfileImpl::GetMediaRequestContextForRenderProcess(
992 int renderer_child_id) {
993 content::RenderProcessHost* rph = content::RenderProcessHost::FromID(
994 renderer_child_id);
995 content::StoragePartition* storage_partition = rph->GetStoragePartition();
997 return storage_partition->GetMediaURLRequestContext();
1000 net::URLRequestContextGetter*
1001 ProfileImpl::GetMediaRequestContextForStoragePartition(
1002 const base::FilePath& partition_path,
1003 bool in_memory) {
1004 return io_data_
1005 .GetIsolatedMediaRequestContextGetter(partition_path, in_memory).get();
1008 content::ResourceContext* ProfileImpl::GetResourceContext() {
1009 return io_data_.GetResourceContext();
1012 net::URLRequestContextGetter* ProfileImpl::GetRequestContextForExtensions() {
1013 return io_data_.GetExtensionsRequestContextGetter().get();
1016 net::URLRequestContextGetter*
1017 ProfileImpl::CreateRequestContextForStoragePartition(
1018 const base::FilePath& partition_path,
1019 bool in_memory,
1020 content::ProtocolHandlerMap* protocol_handlers,
1021 content::URLRequestInterceptorScopedVector request_interceptors) {
1022 return io_data_.CreateIsolatedAppRequestContextGetter(
1023 partition_path,
1024 in_memory,
1025 protocol_handlers,
1026 request_interceptors.Pass()).get();
1029 net::SSLConfigService* ProfileImpl::GetSSLConfigService() {
1030 // If ssl_config_service_manager_ is null, this typically means that some
1031 // KeyedService is trying to create a RequestContext at startup,
1032 // but SSLConfigServiceManager is not initialized until DoFinalInit() which is
1033 // invoked after all KeyedServices have been initialized (see
1034 // http://crbug.com/171406).
1035 DCHECK(ssl_config_service_manager_) <<
1036 "SSLConfigServiceManager is not initialized yet";
1037 return ssl_config_service_manager_->Get();
1040 HostContentSettingsMap* ProfileImpl::GetHostContentSettingsMap() {
1041 DCHECK_CURRENTLY_ON(BrowserThread::UI);
1042 if (!host_content_settings_map_.get()) {
1043 host_content_settings_map_ = new HostContentSettingsMap(GetPrefs(), false);
1044 #if defined(ENABLE_SUPERVISED_USERS)
1045 SupervisedUserSettingsService* supervised_user_settings =
1046 SupervisedUserSettingsServiceFactory::GetForProfile(this);
1047 scoped_ptr<content_settings::SupervisedProvider> supervised_provider(
1048 new content_settings::SupervisedProvider(supervised_user_settings));
1049 host_content_settings_map_->RegisterProvider(
1050 HostContentSettingsMap::SUPERVISED_PROVIDER,
1051 supervised_provider.Pass());
1052 #endif
1054 return host_content_settings_map_.get();
1057 content::BrowserPluginGuestManager* ProfileImpl::GetGuestManager() {
1058 #if defined(ENABLE_EXTENSIONS)
1059 return extensions::GuestViewManager::FromBrowserContext(this);
1060 #else
1061 return NULL;
1062 #endif
1065 DownloadManagerDelegate* ProfileImpl::GetDownloadManagerDelegate() {
1066 return DownloadServiceFactory::GetForBrowserContext(this)->
1067 GetDownloadManagerDelegate();
1070 storage::SpecialStoragePolicy* ProfileImpl::GetSpecialStoragePolicy() {
1071 #if defined(ENABLE_EXTENSIONS)
1072 return GetExtensionSpecialStoragePolicy();
1073 #else
1074 return NULL;
1075 #endif
1078 content::PushMessagingService* ProfileImpl::GetPushMessagingService() {
1079 return PushMessagingServiceFactory::GetForProfile(this);
1082 content::SSLHostStateDelegate* ProfileImpl::GetSSLHostStateDelegate() {
1083 return ChromeSSLHostStateDelegateFactory::GetForProfile(this);
1086 bool ProfileImpl::IsSameProfile(Profile* profile) {
1087 if (profile == static_cast<Profile*>(this))
1088 return true;
1089 Profile* otr_profile = off_the_record_profile_.get();
1090 return otr_profile && profile == otr_profile;
1093 Time ProfileImpl::GetStartTime() const {
1094 return start_time_;
1097 #if defined(ENABLE_SESSION_SERVICE)
1098 void ProfileImpl::StopCreateSessionServiceTimer() {
1099 create_session_service_timer_.Stop();
1102 void ProfileImpl::EnsureSessionServiceCreated() {
1103 SessionServiceFactory::GetForProfile(this);
1105 #endif
1107 #if defined(OS_CHROMEOS)
1108 void ProfileImpl::ChangeAppLocale(
1109 const std::string& new_locale, AppLocaleChangedVia via) {
1110 if (new_locale.empty()) {
1111 NOTREACHED();
1112 return;
1114 PrefService* local_state = g_browser_process->local_state();
1115 DCHECK(local_state);
1116 if (local_state->IsManagedPreference(prefs::kApplicationLocale))
1117 return;
1118 std::string pref_locale = GetPrefs()->GetString(prefs::kApplicationLocale);
1119 bool do_update_pref = true;
1120 switch (via) {
1121 case APP_LOCALE_CHANGED_VIA_SETTINGS:
1122 case APP_LOCALE_CHANGED_VIA_REVERT: {
1123 // We keep kApplicationLocaleBackup value as a reference. In case value
1124 // of kApplicationLocale preference would change due to sync from other
1125 // device then kApplicationLocaleBackup value will trigger and allow us to
1126 // show notification about automatic locale change in LocaleChangeGuard.
1127 GetPrefs()->SetString(prefs::kApplicationLocaleBackup, new_locale);
1128 GetPrefs()->ClearPref(prefs::kApplicationLocaleAccepted);
1129 // We maintain kApplicationLocale property in both a global storage
1130 // and user's profile. Global property determines locale of login screen,
1131 // while user's profile determines his personal locale preference.
1132 break;
1134 case APP_LOCALE_CHANGED_VIA_LOGIN:
1135 case APP_LOCALE_CHANGED_VIA_PUBLIC_SESSION_LOGIN: {
1136 if (!pref_locale.empty()) {
1137 DCHECK(pref_locale == new_locale);
1138 std::string accepted_locale =
1139 GetPrefs()->GetString(prefs::kApplicationLocaleAccepted);
1140 if (accepted_locale == new_locale) {
1141 // If locale is accepted then we do not want to show LocaleChange
1142 // notification. This notification is triggered by different values
1143 // of kApplicationLocaleBackup and kApplicationLocale preferences,
1144 // so make them identical.
1145 GetPrefs()->SetString(prefs::kApplicationLocaleBackup, new_locale);
1146 } else {
1147 // Back up locale of login screen.
1148 std::string cur_locale = g_browser_process->GetApplicationLocale();
1149 GetPrefs()->SetString(prefs::kApplicationLocaleBackup, cur_locale);
1150 if (locale_change_guard_ == NULL)
1151 locale_change_guard_.reset(new chromeos::LocaleChangeGuard(this));
1152 locale_change_guard_->PrepareChangingLocale(cur_locale, new_locale);
1154 } else {
1155 std::string cur_locale = g_browser_process->GetApplicationLocale();
1156 std::string backup_locale =
1157 GetPrefs()->GetString(prefs::kApplicationLocaleBackup);
1158 // Profile synchronization takes time and is not completed at that
1159 // moment at first login. So we initialize locale preference in steps:
1160 // (1) first save it to temporary backup;
1161 // (2) on next login we assume that synchronization is already completed
1162 // and we may finalize initialization.
1163 GetPrefs()->SetString(prefs::kApplicationLocaleBackup, cur_locale);
1164 if (!new_locale.empty())
1165 GetPrefs()->SetString(prefs::kApplicationLocale, new_locale);
1166 else if (!backup_locale.empty())
1167 GetPrefs()->SetString(prefs::kApplicationLocale, backup_locale);
1168 do_update_pref = false;
1170 break;
1172 case APP_LOCALE_CHANGED_VIA_UNKNOWN:
1173 default: {
1174 NOTREACHED();
1175 break;
1178 if (do_update_pref)
1179 GetPrefs()->SetString(prefs::kApplicationLocale, new_locale);
1180 if (via != APP_LOCALE_CHANGED_VIA_PUBLIC_SESSION_LOGIN)
1181 local_state->SetString(prefs::kApplicationLocale, new_locale);
1183 if (user_manager::UserManager::Get()->GetOwnerEmail() ==
1184 chromeos::ProfileHelper::Get()->GetUserByProfile(this)->email())
1185 local_state->SetString(prefs::kOwnerLocale, new_locale);
1188 void ProfileImpl::OnLogin() {
1189 if (locale_change_guard_ == NULL)
1190 locale_change_guard_.reset(new chromeos::LocaleChangeGuard(this));
1191 locale_change_guard_->OnLogin();
1194 void ProfileImpl::InitChromeOSPreferences() {
1195 chromeos_preferences_.reset(new chromeos::Preferences());
1196 chromeos_preferences_->Init(
1197 this, chromeos::ProfileHelper::Get()->GetUserByProfile(this));
1200 #endif // defined(OS_CHROMEOS)
1202 PrefProxyConfigTracker* ProfileImpl::GetProxyConfigTracker() {
1203 if (!pref_proxy_config_tracker_)
1204 pref_proxy_config_tracker_.reset(CreateProxyConfigTracker());
1205 return pref_proxy_config_tracker_.get();
1208 chrome_browser_net::Predictor* ProfileImpl::GetNetworkPredictor() {
1209 return predictor_;
1212 DevToolsNetworkController* ProfileImpl::GetDevToolsNetworkController() {
1213 return io_data_.GetDevToolsNetworkController();
1216 void ProfileImpl::ClearNetworkingHistorySince(
1217 base::Time time,
1218 const base::Closure& completion) {
1219 io_data_.ClearNetworkingHistorySince(time, completion);
1222 GURL ProfileImpl::GetHomePage() {
1223 // --homepage overrides any preferences.
1224 const base::CommandLine& command_line =
1225 *base::CommandLine::ForCurrentProcess();
1226 if (command_line.HasSwitch(switches::kHomePage)) {
1227 // TODO(evanm): clean up usage of DIR_CURRENT.
1228 // http://code.google.com/p/chromium/issues/detail?id=60630
1229 // For now, allow this code to call getcwd().
1230 base::ThreadRestrictions::ScopedAllowIO allow_io;
1232 base::FilePath browser_directory;
1233 PathService::Get(base::DIR_CURRENT, &browser_directory);
1234 GURL home_page(url_fixer::FixupRelativeFile(
1235 browser_directory,
1236 command_line.GetSwitchValuePath(switches::kHomePage)));
1237 if (home_page.is_valid())
1238 return home_page;
1241 if (GetPrefs()->GetBoolean(prefs::kHomePageIsNewTabPage))
1242 return GURL(chrome::kChromeUINewTabURL);
1243 GURL home_page(url_fixer::FixupURL(GetPrefs()->GetString(prefs::kHomePage),
1244 std::string()));
1245 if (!home_page.is_valid())
1246 return GURL(chrome::kChromeUINewTabURL);
1247 return home_page;
1250 void ProfileImpl::UpdateProfileSupervisedUserIdCache() {
1251 ProfileManager* profile_manager = g_browser_process->profile_manager();
1252 ProfileInfoCache& cache = profile_manager->GetProfileInfoCache();
1253 size_t index = cache.GetIndexOfProfileWithPath(GetPath());
1254 if (index != std::string::npos) {
1255 std::string supervised_user_id =
1256 GetPrefs()->GetString(prefs::kSupervisedUserId);
1257 cache.SetSupervisedUserIdOfProfileAtIndex(index, supervised_user_id);
1258 ProfileMetrics::UpdateReportedProfilesStatistics(profile_manager);
1262 void ProfileImpl::UpdateProfileNameCache() {
1263 ProfileManager* profile_manager = g_browser_process->profile_manager();
1264 ProfileInfoCache& cache = profile_manager->GetProfileInfoCache();
1265 size_t index = cache.GetIndexOfProfileWithPath(GetPath());
1266 if (index != std::string::npos) {
1267 std::string profile_name =
1268 GetPrefs()->GetString(prefs::kProfileName);
1269 cache.SetNameOfProfileAtIndex(index, base::UTF8ToUTF16(profile_name));
1270 bool default_name =
1271 GetPrefs()->GetBoolean(prefs::kProfileUsingDefaultName);
1272 cache.SetProfileIsUsingDefaultNameAtIndex(index, default_name);
1276 void ProfileImpl::UpdateProfileAvatarCache() {
1277 ProfileManager* profile_manager = g_browser_process->profile_manager();
1278 ProfileInfoCache& cache = profile_manager->GetProfileInfoCache();
1279 size_t index = cache.GetIndexOfProfileWithPath(GetPath());
1280 if (index != std::string::npos) {
1281 size_t avatar_index =
1282 GetPrefs()->GetInteger(prefs::kProfileAvatarIndex);
1283 cache.SetAvatarIconOfProfileAtIndex(index, avatar_index);
1284 bool default_avatar =
1285 GetPrefs()->GetBoolean(prefs::kProfileUsingDefaultAvatar);
1286 cache.SetProfileIsUsingDefaultAvatarAtIndex(index, default_avatar);
1287 bool gaia_avatar =
1288 GetPrefs()->GetBoolean(prefs::kProfileUsingGAIAAvatar);
1289 cache.SetIsUsingGAIAPictureOfProfileAtIndex(index, gaia_avatar);
1293 void ProfileImpl::UpdateProfileIsEphemeralCache() {
1294 ProfileManager* profile_manager = g_browser_process->profile_manager();
1295 ProfileInfoCache& cache = profile_manager->GetProfileInfoCache();
1296 size_t index = cache.GetIndexOfProfileWithPath(GetPath());
1297 if (index != std::string::npos) {
1298 bool is_ephemeral = GetPrefs()->GetBoolean(prefs::kForceEphemeralProfiles);
1299 cache.SetProfileIsEphemeralAtIndex(index, is_ephemeral);
1303 // Gets the cache parameters from the command line. If |is_media_context| is
1304 // set to true then settings for the media context type is what we need,
1305 // |cache_path| will be set to the user provided path, or will not be touched if
1306 // there is not an argument. |max_size| will be the user provided value or zero
1307 // by default.
1308 void ProfileImpl::GetCacheParameters(bool is_media_context,
1309 base::FilePath* cache_path,
1310 int* max_size) {
1311 DCHECK(cache_path);
1312 DCHECK(max_size);
1313 base::FilePath path(prefs_->GetFilePath(prefs::kDiskCacheDir));
1314 if (!path.empty())
1315 *cache_path = path;
1316 *max_size = is_media_context ? prefs_->GetInteger(prefs::kMediaCacheSize) :
1317 prefs_->GetInteger(prefs::kDiskCacheSize);
1320 PrefProxyConfigTracker* ProfileImpl::CreateProxyConfigTracker() {
1321 #if defined(OS_CHROMEOS)
1322 if (chromeos::ProfileHelper::IsSigninProfile(this)) {
1323 return ProxyServiceFactory::CreatePrefProxyConfigTrackerOfLocalState(
1324 g_browser_process->local_state());
1326 #endif // defined(OS_CHROMEOS)
1327 return ProxyServiceFactory::CreatePrefProxyConfigTrackerOfProfile(
1328 GetPrefs(), g_browser_process->local_state());
1331 scoped_ptr<domain_reliability::DomainReliabilityMonitor>
1332 ProfileImpl::CreateDomainReliabilityMonitor(PrefService* local_state) {
1333 domain_reliability::DomainReliabilityService* service =
1334 domain_reliability::DomainReliabilityServiceFactory::GetInstance()->
1335 GetForBrowserContext(this);
1336 if (!service)
1337 return scoped_ptr<domain_reliability::DomainReliabilityMonitor>();
1339 return service->CreateMonitor(
1340 BrowserThread::GetMessageLoopProxyForThread(BrowserThread::IO));