Add more checks to investigate SupervisedUserPrefStore crash at startup.
[chromium-blink-merge.git] / chrome / browser / profiles / profile_impl.cc
blob9b7389fc542cb6ec4b5e9f6408f8e529c20c3b50
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/safe_browsing/safe_browsing_service.h"
64 #include "chrome/browser/services/gcm/gcm_profile_service.h"
65 #include "chrome/browser/services/gcm/gcm_profile_service_factory.h"
66 #include "chrome/browser/services/gcm/push_messaging_service_impl.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/supervised_user/supervised_user_constants.h"
147 #include "chrome/browser/supervised_user/supervised_user_settings_service.h"
148 #include "chrome/browser/supervised_user/supervised_user_settings_service_factory.h"
149 #endif
151 using base::Time;
152 using base::TimeDelta;
153 using base::UserMetricsAction;
154 using bookmarks::BookmarkModel;
155 using content::BrowserThread;
156 using content::DownloadManagerDelegate;
158 namespace {
160 #if defined(ENABLE_SESSION_SERVICE)
161 // Delay, in milliseconds, before we explicitly create the SessionService.
162 const int kCreateSessionServiceDelayMS = 500;
163 #endif
165 // Text content of README file created in each profile directory. Both %s
166 // placeholders must contain the product name. This is not localizable and hence
167 // not in resources.
168 const char kReadmeText[] =
169 "%s settings and storage represent user-selected preferences and "
170 "information and MUST not be extracted, overwritten or modified except "
171 "through %s defined APIs.";
173 // Value written to prefs for EXIT_CRASHED and EXIT_SESSION_ENDED.
174 const char kPrefExitTypeCrashed[] = "Crashed";
175 const char kPrefExitTypeSessionEnded[] = "SessionEnded";
177 // Helper method needed because PostTask cannot currently take a Callback
178 // function with non-void return type.
179 void CreateDirectoryAndSignal(const base::FilePath& path,
180 base::WaitableEvent* done_creating) {
181 DVLOG(1) << "Creating directory " << path.value();
182 base::CreateDirectory(path);
183 done_creating->Signal();
186 // Task that blocks the FILE thread until CreateDirectoryAndSignal() finishes on
187 // blocking I/O pool.
188 void BlockFileThreadOnDirectoryCreate(base::WaitableEvent* done_creating) {
189 done_creating->Wait();
192 // Initiates creation of profile directory on |sequenced_task_runner| and
193 // ensures that FILE thread is blocked until that operation finishes.
194 void CreateProfileDirectory(base::SequencedTaskRunner* sequenced_task_runner,
195 const base::FilePath& path) {
196 base::WaitableEvent* done_creating = new base::WaitableEvent(false, false);
197 sequenced_task_runner->PostTask(FROM_HERE,
198 base::Bind(&CreateDirectoryAndSignal,
199 path,
200 done_creating));
201 // Block the FILE thread until directory is created on I/O pool to make sure
202 // that we don't attempt any operation until that part completes.
203 BrowserThread::PostTask(
204 BrowserThread::FILE, FROM_HERE,
205 base::Bind(&BlockFileThreadOnDirectoryCreate,
206 base::Owned(done_creating)));
209 base::FilePath GetCachePath(const base::FilePath& base) {
210 return base.Append(chrome::kCacheDirname);
213 base::FilePath GetMediaCachePath(const base::FilePath& base) {
214 return base.Append(chrome::kMediaCacheDirname);
217 void EnsureReadmeFile(const base::FilePath& base) {
218 base::FilePath readme_path = base.Append(chrome::kReadmeFilename);
219 if (base::PathExists(readme_path))
220 return;
221 std::string product_name = l10n_util::GetStringUTF8(IDS_PRODUCT_NAME);
222 std::string readme_text = base::StringPrintf(
223 kReadmeText, product_name.c_str(), product_name.c_str());
224 if (base::WriteFile(readme_path, readme_text.data(), readme_text.size()) ==
225 -1) {
226 LOG(ERROR) << "Could not create README file.";
230 // Converts the kSessionExitedCleanly pref to the corresponding EXIT_TYPE.
231 Profile::ExitType SessionTypePrefValueToExitType(const std::string& value) {
232 if (value == kPrefExitTypeSessionEnded)
233 return Profile::EXIT_SESSION_ENDED;
234 if (value == kPrefExitTypeCrashed)
235 return Profile::EXIT_CRASHED;
236 return Profile::EXIT_NORMAL;
239 // Converts an ExitType into a string that is written to prefs.
240 std::string ExitTypeToSessionTypePrefValue(Profile::ExitType type) {
241 switch (type) {
242 case Profile::EXIT_NORMAL:
243 return ProfileImpl::kPrefExitTypeNormal;
244 case Profile::EXIT_SESSION_ENDED:
245 return kPrefExitTypeSessionEnded;
246 case Profile::EXIT_CRASHED:
247 return kPrefExitTypeCrashed;
249 NOTREACHED();
250 return std::string();
253 PrefStore* CreateExtensionPrefStore(Profile* profile,
254 bool incognito_pref_store) {
255 #if defined(ENABLE_EXTENSIONS)
256 return new ExtensionPrefStore(
257 ExtensionPrefValueMapFactory::GetForBrowserContext(profile),
258 incognito_pref_store);
259 #else
260 return NULL;
261 #endif
264 } // namespace
266 // static
267 Profile* Profile::CreateProfile(const base::FilePath& path,
268 Delegate* delegate,
269 CreateMode create_mode) {
270 TRACE_EVENT1("browser,startup",
271 "Profile::CreateProfile",
272 "profile_path",
273 path.AsUTF8Unsafe());
275 // Get sequenced task runner for making sure that file operations of
276 // this profile (defined by |path|) are executed in expected order
277 // (what was previously assured by the FILE thread).
278 scoped_refptr<base::SequencedTaskRunner> sequenced_task_runner =
279 JsonPrefStore::GetTaskRunnerForFile(path,
280 BrowserThread::GetBlockingPool());
281 if (create_mode == CREATE_MODE_ASYNCHRONOUS) {
282 DCHECK(delegate);
283 CreateProfileDirectory(sequenced_task_runner.get(), path);
284 } else if (create_mode == CREATE_MODE_SYNCHRONOUS) {
285 if (!base::PathExists(path)) {
286 // TODO(rogerta): http://crbug/160553 - Bad things happen if we can't
287 // write to the profile directory. We should eventually be able to run in
288 // this situation.
289 if (!base::CreateDirectory(path))
290 return NULL;
292 } else {
293 NOTREACHED();
296 return new ProfileImpl(
297 path, delegate, create_mode, sequenced_task_runner.get());
300 // static
301 int ProfileImpl::create_readme_delay_ms = 60000;
303 // static
304 const char* const ProfileImpl::kPrefExitTypeNormal = "Normal";
306 // static
307 void ProfileImpl::RegisterProfilePrefs(
308 user_prefs::PrefRegistrySyncable* registry) {
309 registry->RegisterBooleanPref(
310 prefs::kSavingBrowserHistoryDisabled,
311 false,
312 user_prefs::PrefRegistrySyncable::UNSYNCABLE_PREF);
313 registry->RegisterBooleanPref(
314 prefs::kAllowDeletingBrowserHistory,
315 true,
316 user_prefs::PrefRegistrySyncable::UNSYNCABLE_PREF);
317 registry->RegisterBooleanPref(
318 prefs::kSigninAllowed,
319 true,
320 user_prefs::PrefRegistrySyncable::UNSYNCABLE_PREF);
321 registry->RegisterBooleanPref(
322 prefs::kForceSafeSearch,
323 false,
324 user_prefs::PrefRegistrySyncable::UNSYNCABLE_PREF);
325 registry->RegisterBooleanPref(
326 prefs::kForceGoogleSafeSearch,
327 false,
328 user_prefs::PrefRegistrySyncable::UNSYNCABLE_PREF);
329 registry->RegisterBooleanPref(
330 prefs::kForceYouTubeSafetyMode,
331 false,
332 user_prefs::PrefRegistrySyncable::UNSYNCABLE_PREF);
333 registry->RegisterBooleanPref(
334 prefs::kRecordHistory,
335 false,
336 user_prefs::PrefRegistrySyncable::UNSYNCABLE_PREF);
337 registry->RegisterIntegerPref(
338 prefs::kProfileAvatarIndex,
340 user_prefs::PrefRegistrySyncable::SYNCABLE_PREF);
341 // Whether a profile is using an avatar without having explicitely chosen it
342 // (i.e. was assigned by default by legacy profile creation).
343 registry->RegisterBooleanPref(
344 prefs::kProfileUsingDefaultAvatar,
345 true,
346 user_prefs::PrefRegistrySyncable::SYNCABLE_PREF);
347 registry->RegisterBooleanPref(
348 prefs::kProfileUsingGAIAAvatar,
349 false,
350 user_prefs::PrefRegistrySyncable::SYNCABLE_PREF);
351 // Whether a profile is using a default avatar name (eg. Pickles or Person 1).
352 registry->RegisterBooleanPref(
353 prefs::kProfileUsingDefaultName,
354 true,
355 user_prefs::PrefRegistrySyncable::SYNCABLE_PREF);
356 registry->RegisterStringPref(
357 prefs::kSupervisedUserId,
358 std::string(),
359 user_prefs::PrefRegistrySyncable::UNSYNCABLE_PREF);
360 registry->RegisterStringPref(prefs::kProfileName,
361 std::string(),
362 user_prefs::PrefRegistrySyncable::SYNCABLE_PREF);
363 registry->RegisterStringPref(prefs::kHomePage,
364 std::string(),
365 user_prefs::PrefRegistrySyncable::SYNCABLE_PREF);
366 #if defined(ENABLE_PRINTING)
367 registry->RegisterBooleanPref(
368 prefs::kPrintingEnabled,
369 true,
370 user_prefs::PrefRegistrySyncable::UNSYNCABLE_PREF);
371 #endif
372 registry->RegisterBooleanPref(
373 prefs::kPrintPreviewDisabled,
374 false,
375 user_prefs::PrefRegistrySyncable::UNSYNCABLE_PREF);
376 registry->RegisterBooleanPref(
377 prefs::kForceEphemeralProfiles,
378 false,
379 user_prefs::PrefRegistrySyncable::UNSYNCABLE_PREF);
381 // Initialize the cache prefs.
382 registry->RegisterFilePathPref(
383 prefs::kDiskCacheDir,
384 base::FilePath(),
385 user_prefs::PrefRegistrySyncable::UNSYNCABLE_PREF);
386 registry->RegisterIntegerPref(
387 prefs::kDiskCacheSize,
389 user_prefs::PrefRegistrySyncable::UNSYNCABLE_PREF);
390 registry->RegisterIntegerPref(
391 prefs::kMediaCacheSize,
393 user_prefs::PrefRegistrySyncable::UNSYNCABLE_PREF);
395 // Deprecated. Kept around for migration.
396 registry->RegisterBooleanPref(
397 prefs::kClearSiteDataOnExit,
398 false,
399 user_prefs::PrefRegistrySyncable::SYNCABLE_PREF);
402 ProfileImpl::ProfileImpl(
403 const base::FilePath& path,
404 Delegate* delegate,
405 CreateMode create_mode,
406 base::SequencedTaskRunner* sequenced_task_runner)
407 : path_(path),
408 pref_registry_(new user_prefs::PrefRegistrySyncable),
409 io_data_(this),
410 host_content_settings_map_(NULL),
411 last_session_exit_type_(EXIT_NORMAL),
412 start_time_(Time::Now()),
413 delegate_(delegate),
414 predictor_(NULL) {
415 TRACE_EVENT0("browser,startup", "ProfileImpl::ctor")
416 DCHECK(!path.empty()) << "Using an empty path will attempt to write " <<
417 "profile files to the root directory!";
419 #if defined(ENABLE_SESSION_SERVICE)
420 create_session_service_timer_.Start(FROM_HERE,
421 TimeDelta::FromMilliseconds(kCreateSessionServiceDelayMS), this,
422 &ProfileImpl::EnsureSessionServiceCreated);
423 #endif
425 set_is_guest_profile(path == ProfileManager::GetGuestProfilePath());
426 set_is_system_profile(path == ProfileManager::GetSystemProfilePath());
428 // Determine if prefetch is enabled for this profile.
429 // If not profile_manager is present, it means we are in a unittest.
430 const base::CommandLine* command_line =
431 base::CommandLine::ForCurrentProcess();
432 predictor_ = chrome_browser_net::Predictor::CreatePredictor(
433 !command_line->HasSwitch(switches::kDisablePreconnect),
434 !command_line->HasSwitch(switches::kDnsPrefetchDisable),
435 g_browser_process->profile_manager() == NULL);
437 // If we are creating the profile synchronously, then we should load the
438 // policy data immediately.
439 bool force_immediate_policy_load = (create_mode == CREATE_MODE_SYNCHRONOUS);
440 #if defined(ENABLE_CONFIGURATION_POLICY)
441 policy::BrowserPolicyConnector* connector =
442 g_browser_process->browser_policy_connector();
443 schema_registry_service_ =
444 policy::SchemaRegistryServiceFactory::CreateForContext(
445 this, connector->GetChromeSchema(), connector->GetSchemaRegistry());
446 #if defined(OS_CHROMEOS)
447 cloud_policy_manager_ =
448 policy::UserCloudPolicyManagerFactoryChromeOS::CreateForProfile(
449 this, force_immediate_policy_load, sequenced_task_runner);
450 #else
451 cloud_policy_manager_ =
452 policy::UserCloudPolicyManagerFactory::CreateForOriginalBrowserContext(
453 this,
454 force_immediate_policy_load,
455 sequenced_task_runner,
456 BrowserThread::GetMessageLoopProxyForThread(BrowserThread::FILE),
457 BrowserThread::GetMessageLoopProxyForThread(BrowserThread::IO));
458 #endif
459 #endif
460 profile_policy_connector_ =
461 policy::ProfilePolicyConnectorFactory::CreateForBrowserContext(
462 this, force_immediate_policy_load);
464 DCHECK(create_mode == CREATE_MODE_ASYNCHRONOUS ||
465 create_mode == CREATE_MODE_SYNCHRONOUS);
466 bool async_prefs = create_mode == CREATE_MODE_ASYNCHRONOUS;
468 #if defined(OS_CHROMEOS)
469 if (chromeos::ProfileHelper::IsSigninProfile(this))
470 chrome::RegisterLoginProfilePrefs(pref_registry_.get());
471 else
472 #endif
473 chrome::RegisterUserProfilePrefs(pref_registry_.get());
475 BrowserContextDependencyManager::GetInstance()->
476 RegisterProfilePrefsForServices(this, pref_registry_.get());
478 SupervisedUserSettingsService* supervised_user_settings = NULL;
479 #if defined(ENABLE_SUPERVISED_USERS)
480 supervised_user_settings =
481 SupervisedUserSettingsServiceFactory::GetForProfile(this);
482 supervised_user_settings->Init(
483 path_, sequenced_task_runner, create_mode == CREATE_MODE_SYNCHRONOUS);
484 #endif
486 scoped_refptr<SafeBrowsingService> safe_browsing_service(
487 g_browser_process->safe_browsing_service());
488 if (safe_browsing_service.get()) {
489 pref_validation_delegate_ =
490 safe_browsing_service->CreatePreferenceValidationDelegate(this).Pass();
494 // On startup, preference loading is always synchronous so a scoped timer
495 // will work here.
496 startup_metric_utils::ScopedSlowStartupUMA
497 scoped_timer("Startup.SlowStartupPreferenceLoading");
498 prefs_ = chrome_prefs::CreateProfilePrefs(
499 path_,
500 sequenced_task_runner,
501 pref_validation_delegate_.get(),
502 profile_policy_connector_->policy_service(),
503 supervised_user_settings,
504 CreateExtensionPrefStore(this, false),
505 pref_registry_,
506 async_prefs).Pass();
507 // Register on BrowserContext.
508 user_prefs::UserPrefs::Set(this, prefs_.get());
511 startup_metric_utils::ScopedSlowStartupUMA
512 scoped_timer("Startup.SlowStartupFinalProfileInit");
513 if (async_prefs) {
514 // Wait for the notification that prefs has been loaded
515 // (successfully or not). Note that we can use base::Unretained
516 // because the PrefService is owned by this class and lives on
517 // the same thread.
518 prefs_->AddPrefInitObserver(base::Bind(&ProfileImpl::OnPrefsLoaded,
519 base::Unretained(this)));
520 } else {
521 // Prefs were loaded synchronously so we can continue directly.
522 OnPrefsLoaded(true);
526 void ProfileImpl::DoFinalInit() {
527 TRACE_EVENT0("browser", "ProfileImpl::DoFinalInit")
528 PrefService* prefs = GetPrefs();
529 pref_change_registrar_.Init(prefs);
530 pref_change_registrar_.Add(
531 prefs::kSupervisedUserId,
532 base::Bind(&ProfileImpl::UpdateProfileSupervisedUserIdCache,
533 base::Unretained(this)));
535 // Changes in the profile avatar.
536 pref_change_registrar_.Add(
537 prefs::kProfileAvatarIndex,
538 base::Bind(&ProfileImpl::UpdateProfileAvatarCache,
539 base::Unretained(this)));
540 pref_change_registrar_.Add(
541 prefs::kProfileUsingDefaultAvatar,
542 base::Bind(&ProfileImpl::UpdateProfileAvatarCache,
543 base::Unretained(this)));
544 pref_change_registrar_.Add(
545 prefs::kProfileUsingGAIAAvatar,
546 base::Bind(&ProfileImpl::UpdateProfileAvatarCache,
547 base::Unretained(this)));
549 // Changes in the profile name.
550 pref_change_registrar_.Add(
551 prefs::kProfileUsingDefaultName,
552 base::Bind(&ProfileImpl::UpdateProfileNameCache,
553 base::Unretained(this)));
554 pref_change_registrar_.Add(
555 prefs::kProfileName,
556 base::Bind(&ProfileImpl::UpdateProfileNameCache,
557 base::Unretained(this)));
559 pref_change_registrar_.Add(
560 prefs::kForceEphemeralProfiles,
561 base::Bind(&ProfileImpl::UpdateProfileIsEphemeralCache,
562 base::Unretained(this)));
564 // It would be nice to use PathService for fetching this directory, but
565 // the cache directory depends on the profile directory, which isn't available
566 // to PathService.
567 chrome::GetUserCacheDirectory(path_, &base_cache_path_);
568 // Always create the cache directory asynchronously.
569 scoped_refptr<base::SequencedTaskRunner> sequenced_task_runner =
570 JsonPrefStore::GetTaskRunnerForFile(base_cache_path_,
571 BrowserThread::GetBlockingPool());
572 CreateProfileDirectory(sequenced_task_runner.get(), base_cache_path_);
574 // Initialize components that depend on the current value.
575 UpdateProfileSupervisedUserIdCache();
576 UpdateProfileIsEphemeralCache();
577 GAIAInfoUpdateServiceFactory::GetForProfile(this);
579 PrefService* local_state = g_browser_process->local_state();
580 ssl_config_service_manager_.reset(
581 SSLConfigServiceManager::CreateDefaultManager(local_state));
583 #if defined(ENABLE_BACKGROUND)
584 // Initialize the BackgroundModeManager - this has to be done here before
585 // InitExtensions() is called because it relies on receiving notifications
586 // when extensions are loaded. BackgroundModeManager is not needed under
587 // ChromeOS because Chrome is always running, no need for special keep-alive
588 // or launch-on-startup support unless kKeepAliveForTest is set.
589 bool init_background_mode_manager = true;
590 #if defined(OS_CHROMEOS)
591 if (!base::CommandLine::ForCurrentProcess()->HasSwitch(
592 switches::kKeepAliveForTest))
593 init_background_mode_manager = false;
594 #endif
595 if (init_background_mode_manager) {
596 if (g_browser_process->background_mode_manager())
597 g_browser_process->background_mode_manager()->RegisterProfile(this);
599 #endif // defined(ENABLE_BACKGROUND)
601 base::FilePath cookie_path = GetPath();
602 cookie_path = cookie_path.Append(chrome::kCookieFilename);
603 base::FilePath channel_id_path = GetPath();
604 channel_id_path = channel_id_path.Append(chrome::kChannelIDFilename);
605 base::FilePath cache_path = base_cache_path_;
606 int cache_max_size;
607 GetCacheParameters(false, &cache_path, &cache_max_size);
608 cache_path = GetCachePath(cache_path);
610 base::FilePath media_cache_path = base_cache_path_;
611 int media_cache_max_size;
612 GetCacheParameters(true, &media_cache_path, &media_cache_max_size);
613 media_cache_path = GetMediaCachePath(media_cache_path);
615 base::FilePath extensions_cookie_path = GetPath();
616 extensions_cookie_path =
617 extensions_cookie_path.Append(chrome::kExtensionsCookieFilename);
619 base::FilePath infinite_cache_path = GetPath();
620 infinite_cache_path =
621 infinite_cache_path.Append(FILE_PATH_LITERAL("Infinite Cache"));
623 #if defined(OS_ANDROID)
624 SessionStartupPref::Type startup_pref_type =
625 SessionStartupPref::GetDefaultStartupType();
626 #else
627 SessionStartupPref::Type startup_pref_type =
628 StartupBrowserCreator::GetSessionStartupPref(
629 *base::CommandLine::ForCurrentProcess(), this).type;
630 #endif
631 content::CookieStoreConfig::SessionCookieMode session_cookie_mode =
632 content::CookieStoreConfig::PERSISTANT_SESSION_COOKIES;
633 if (GetLastSessionExitType() == Profile::EXIT_CRASHED ||
634 startup_pref_type == SessionStartupPref::LAST) {
635 session_cookie_mode = content::CookieStoreConfig::RESTORED_SESSION_COOKIES;
638 // Make sure we initialize the ProfileIOData after everything else has been
639 // initialized that we might be reading from the IO thread.
641 io_data_.Init(cookie_path, channel_id_path, cache_path,
642 cache_max_size, media_cache_path, media_cache_max_size,
643 extensions_cookie_path, GetPath(), infinite_cache_path,
644 predictor_, session_cookie_mode, GetSpecialStoragePolicy(),
645 CreateDomainReliabilityMonitor(local_state));
647 #if defined(ENABLE_PLUGINS)
648 ChromePluginServiceFilter::GetInstance()->RegisterResourceContext(
649 PluginPrefs::GetForProfile(this).get(),
650 io_data_.GetResourceContextNoInit());
651 #endif
653 // Delay README creation to not impact startup performance.
654 BrowserThread::PostDelayedTask(
655 BrowserThread::FILE, FROM_HERE,
656 base::Bind(&EnsureReadmeFile, GetPath()),
657 base::TimeDelta::FromMilliseconds(create_readme_delay_ms));
659 TRACE_EVENT0("browser", "ProfileImpl::SetSaveSessionStorageOnDisk");
660 content::BrowserContext::GetDefaultStoragePartition(this)->
661 GetDOMStorageContext()->SetSaveSessionStorageOnDisk();
663 // TODO(wjmaclean): Remove this. crbug.com/420643
664 chrome::MigrateProfileZoomLevelPrefs(this);
666 // The DomDistillerViewerSource is not a normal WebUI so it must be registered
667 // as a URLDataSource early.
668 RegisterDomDistillerViewerSource(this);
670 #if defined(OS_CHROMEOS)
671 if (chromeos::UserSessionManager::GetInstance()
672 ->RestartToApplyPerSessionFlagsIfNeed(this, true)) {
673 return;
675 #endif
677 if (delegate_) {
678 TRACE_EVENT0("browser", "ProfileImpl::DoFileInit:DelegateOnProfileCreated")
679 delegate_->OnProfileCreated(this, true, IsNewProfile());
682 content::NotificationService::current()->Notify(
683 chrome::NOTIFICATION_PROFILE_CREATED,
684 content::Source<Profile>(this),
685 content::NotificationService::NoDetails());
687 #if !defined(OS_CHROMEOS)
688 // Listen for bookmark model load, to bootstrap the sync service.
689 // On CrOS sync service will be initialized after sign in.
690 BookmarkModel* model = BookmarkModelFactory::GetForProfile(this);
691 model->AddObserver(new BookmarkModelLoadedObserver(this));
692 #endif
694 gcm::PushMessagingServiceImpl::InitializeForProfile(this);
696 #if !defined(OS_ANDROID) && !defined(OS_CHROMEOS) && !defined(OS_IOS)
697 signin_ui_util::InitializePrefsForProfile(this);
698 #endif
701 base::FilePath ProfileImpl::last_selected_directory() {
702 return GetPrefs()->GetFilePath(prefs::kSelectFileLastDirectory);
705 void ProfileImpl::set_last_selected_directory(const base::FilePath& path) {
706 GetPrefs()->SetFilePath(prefs::kSelectFileLastDirectory, path);
709 ProfileImpl::~ProfileImpl() {
710 MaybeSendDestroyedNotification();
712 bool prefs_loaded = prefs_->GetInitializationStatus() !=
713 PrefService::INITIALIZATION_STATUS_WAITING;
715 #if defined(ENABLE_SESSION_SERVICE)
716 StopCreateSessionServiceTimer();
717 #endif
719 // Remove pref observers
720 pref_change_registrar_.RemoveAll();
722 #if defined(ENABLE_PLUGINS)
723 ChromePluginServiceFilter::GetInstance()->UnregisterResourceContext(
724 io_data_.GetResourceContextNoInit());
725 #endif
727 // Destroy OTR profile and its profile services first.
728 if (off_the_record_profile_) {
729 ProfileDestroyer::DestroyOffTheRecordProfileNow(
730 off_the_record_profile_.get());
731 } else {
732 #if defined(ENABLE_EXTENSIONS)
733 ExtensionPrefValueMapFactory::GetForBrowserContext(this)->
734 ClearAllIncognitoSessionOnlyPreferences();
735 #endif
738 BrowserContextDependencyManager::GetInstance()->DestroyBrowserContextServices(
739 this);
741 if (pref_proxy_config_tracker_)
742 pref_proxy_config_tracker_->DetachFromPrefService();
744 if (host_content_settings_map_.get())
745 host_content_settings_map_->ShutdownOnUIThread();
747 // This causes the Preferences file to be written to disk.
748 if (prefs_loaded)
749 SetExitType(EXIT_NORMAL);
752 std::string ProfileImpl::GetProfileUserName() const {
753 const SigninManagerBase* signin_manager =
754 SigninManagerFactory::GetForProfileIfExists(this);
755 if (signin_manager)
756 return signin_manager->GetAuthenticatedUsername();
758 return std::string();
761 Profile::ProfileType ProfileImpl::GetProfileType() const {
762 return REGULAR_PROFILE;
765 scoped_ptr<content::ZoomLevelDelegate>
766 ProfileImpl::CreateZoomLevelDelegate(const base::FilePath& partition_path) {
767 return make_scoped_ptr(new chrome::ChromeZoomLevelPrefs(
768 GetPrefs(), GetPath(), partition_path,
769 ui_zoom::ZoomEventManager::GetForBrowserContext(this)->GetWeakPtr()));
772 base::FilePath ProfileImpl::GetPath() const {
773 return path_;
776 scoped_refptr<base::SequencedTaskRunner> ProfileImpl::GetIOTaskRunner() {
777 return JsonPrefStore::GetTaskRunnerForFile(
778 GetPath(), BrowserThread::GetBlockingPool());
781 bool ProfileImpl::IsOffTheRecord() const {
782 return false;
785 Profile* ProfileImpl::GetOffTheRecordProfile() {
786 if (!off_the_record_profile_) {
787 scoped_ptr<Profile> p(CreateOffTheRecordProfile());
788 off_the_record_profile_.swap(p);
790 content::NotificationService::current()->Notify(
791 chrome::NOTIFICATION_PROFILE_CREATED,
792 content::Source<Profile>(off_the_record_profile_.get()),
793 content::NotificationService::NoDetails());
795 return off_the_record_profile_.get();
798 void ProfileImpl::DestroyOffTheRecordProfile() {
799 off_the_record_profile_.reset();
800 #if defined(ENABLE_EXTENSIONS)
801 ExtensionPrefValueMapFactory::GetForBrowserContext(this)->
802 ClearAllIncognitoSessionOnlyPreferences();
803 #endif
806 bool ProfileImpl::HasOffTheRecordProfile() {
807 return off_the_record_profile_.get() != NULL;
810 Profile* ProfileImpl::GetOriginalProfile() {
811 return this;
814 bool ProfileImpl::IsSupervised() {
815 return !GetPrefs()->GetString(prefs::kSupervisedUserId).empty();
818 bool ProfileImpl::IsChild() {
819 #if defined(ENABLE_SUPERVISED_USERS)
820 return GetPrefs()->GetString(prefs::kSupervisedUserId) ==
821 supervised_users::kChildAccountSUID;
822 #else
823 return false;
824 #endif
827 bool ProfileImpl::IsLegacySupervised() {
828 return IsSupervised() && !IsChild();
831 ExtensionSpecialStoragePolicy*
832 ProfileImpl::GetExtensionSpecialStoragePolicy() {
833 #if defined(ENABLE_EXTENSIONS)
834 if (!extension_special_storage_policy_.get()) {
835 TRACE_EVENT0("browser", "ProfileImpl::GetExtensionSpecialStoragePolicy")
836 extension_special_storage_policy_ = new ExtensionSpecialStoragePolicy(
837 CookieSettings::Factory::GetForProfile(this).get());
839 return extension_special_storage_policy_.get();
840 #else
841 return NULL;
842 #endif
845 void ProfileImpl::OnPrefsLoaded(bool success) {
846 TRACE_EVENT0("browser", "ProfileImpl::OnPrefsLoaded");
847 SCOPED_UMA_HISTOGRAM_TIMER("Profile.OnPrefsLoadedTime");
848 if (!success) {
849 if (delegate_)
850 delegate_->OnProfileCreated(this, false, false);
851 return;
854 // TODO(mirandac): remove migration code after 6 months (crbug.com/69995).
855 if (g_browser_process->local_state())
856 chrome::MigrateBrowserPrefs(this, g_browser_process->local_state());
857 // TODO(ivankr): remove cleanup code eventually (crbug.com/165672).
858 chrome::MigrateUserPrefs(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);
1045 return host_content_settings_map_.get();
1048 content::BrowserPluginGuestManager* ProfileImpl::GetGuestManager() {
1049 #if defined(ENABLE_EXTENSIONS)
1050 return extensions::GuestViewManager::FromBrowserContext(this);
1051 #else
1052 return NULL;
1053 #endif
1056 DownloadManagerDelegate* ProfileImpl::GetDownloadManagerDelegate() {
1057 return DownloadServiceFactory::GetForBrowserContext(this)->
1058 GetDownloadManagerDelegate();
1061 storage::SpecialStoragePolicy* ProfileImpl::GetSpecialStoragePolicy() {
1062 #if defined(ENABLE_EXTENSIONS)
1063 return GetExtensionSpecialStoragePolicy();
1064 #else
1065 return NULL;
1066 #endif
1069 content::PushMessagingService* ProfileImpl::GetPushMessagingService() {
1070 return gcm::GCMProfileServiceFactory::GetForProfile(
1071 this)->push_messaging_service();
1074 content::SSLHostStateDelegate* ProfileImpl::GetSSLHostStateDelegate() {
1075 return ChromeSSLHostStateDelegateFactory::GetForProfile(this);
1078 bool ProfileImpl::IsSameProfile(Profile* profile) {
1079 if (profile == static_cast<Profile*>(this))
1080 return true;
1081 Profile* otr_profile = off_the_record_profile_.get();
1082 return otr_profile && profile == otr_profile;
1085 Time ProfileImpl::GetStartTime() const {
1086 return start_time_;
1089 #if defined(ENABLE_SESSION_SERVICE)
1090 void ProfileImpl::StopCreateSessionServiceTimer() {
1091 create_session_service_timer_.Stop();
1094 void ProfileImpl::EnsureSessionServiceCreated() {
1095 SessionServiceFactory::GetForProfile(this);
1097 #endif
1099 #if defined(OS_CHROMEOS)
1100 void ProfileImpl::ChangeAppLocale(
1101 const std::string& new_locale, AppLocaleChangedVia via) {
1102 if (new_locale.empty()) {
1103 NOTREACHED();
1104 return;
1106 PrefService* local_state = g_browser_process->local_state();
1107 DCHECK(local_state);
1108 if (local_state->IsManagedPreference(prefs::kApplicationLocale))
1109 return;
1110 std::string pref_locale = GetPrefs()->GetString(prefs::kApplicationLocale);
1111 bool do_update_pref = true;
1112 switch (via) {
1113 case APP_LOCALE_CHANGED_VIA_SETTINGS:
1114 case APP_LOCALE_CHANGED_VIA_REVERT: {
1115 // We keep kApplicationLocaleBackup value as a reference. In case value
1116 // of kApplicationLocale preference would change due to sync from other
1117 // device then kApplicationLocaleBackup value will trigger and allow us to
1118 // show notification about automatic locale change in LocaleChangeGuard.
1119 GetPrefs()->SetString(prefs::kApplicationLocaleBackup, new_locale);
1120 GetPrefs()->ClearPref(prefs::kApplicationLocaleAccepted);
1121 // We maintain kApplicationLocale property in both a global storage
1122 // and user's profile. Global property determines locale of login screen,
1123 // while user's profile determines his personal locale preference.
1124 break;
1126 case APP_LOCALE_CHANGED_VIA_LOGIN:
1127 case APP_LOCALE_CHANGED_VIA_PUBLIC_SESSION_LOGIN: {
1128 if (!pref_locale.empty()) {
1129 DCHECK(pref_locale == new_locale);
1130 std::string accepted_locale =
1131 GetPrefs()->GetString(prefs::kApplicationLocaleAccepted);
1132 if (accepted_locale == new_locale) {
1133 // If locale is accepted then we do not want to show LocaleChange
1134 // notification. This notification is triggered by different values
1135 // of kApplicationLocaleBackup and kApplicationLocale preferences,
1136 // so make them identical.
1137 GetPrefs()->SetString(prefs::kApplicationLocaleBackup, new_locale);
1138 } else {
1139 // Back up locale of login screen.
1140 std::string cur_locale = g_browser_process->GetApplicationLocale();
1141 GetPrefs()->SetString(prefs::kApplicationLocaleBackup, cur_locale);
1142 if (locale_change_guard_ == NULL)
1143 locale_change_guard_.reset(new chromeos::LocaleChangeGuard(this));
1144 locale_change_guard_->PrepareChangingLocale(cur_locale, new_locale);
1146 } else {
1147 std::string cur_locale = g_browser_process->GetApplicationLocale();
1148 std::string backup_locale =
1149 GetPrefs()->GetString(prefs::kApplicationLocaleBackup);
1150 // Profile synchronization takes time and is not completed at that
1151 // moment at first login. So we initialize locale preference in steps:
1152 // (1) first save it to temporary backup;
1153 // (2) on next login we assume that synchronization is already completed
1154 // and we may finalize initialization.
1155 GetPrefs()->SetString(prefs::kApplicationLocaleBackup, cur_locale);
1156 if (!new_locale.empty())
1157 GetPrefs()->SetString(prefs::kApplicationLocale, new_locale);
1158 else if (!backup_locale.empty())
1159 GetPrefs()->SetString(prefs::kApplicationLocale, backup_locale);
1160 do_update_pref = false;
1162 break;
1164 case APP_LOCALE_CHANGED_VIA_UNKNOWN:
1165 default: {
1166 NOTREACHED();
1167 break;
1170 if (do_update_pref)
1171 GetPrefs()->SetString(prefs::kApplicationLocale, new_locale);
1172 if (via != APP_LOCALE_CHANGED_VIA_PUBLIC_SESSION_LOGIN)
1173 local_state->SetString(prefs::kApplicationLocale, new_locale);
1175 if (user_manager::UserManager::Get()->GetOwnerEmail() ==
1176 chromeos::ProfileHelper::Get()->GetUserByProfile(this)->email())
1177 local_state->SetString(prefs::kOwnerLocale, new_locale);
1180 void ProfileImpl::OnLogin() {
1181 if (locale_change_guard_ == NULL)
1182 locale_change_guard_.reset(new chromeos::LocaleChangeGuard(this));
1183 locale_change_guard_->OnLogin();
1186 void ProfileImpl::InitChromeOSPreferences() {
1187 chromeos_preferences_.reset(new chromeos::Preferences());
1188 chromeos_preferences_->Init(
1189 this, chromeos::ProfileHelper::Get()->GetUserByProfile(this));
1192 #endif // defined(OS_CHROMEOS)
1194 PrefProxyConfigTracker* ProfileImpl::GetProxyConfigTracker() {
1195 if (!pref_proxy_config_tracker_)
1196 pref_proxy_config_tracker_.reset(CreateProxyConfigTracker());
1197 return pref_proxy_config_tracker_.get();
1200 chrome_browser_net::Predictor* ProfileImpl::GetNetworkPredictor() {
1201 return predictor_;
1204 DevToolsNetworkController* ProfileImpl::GetDevToolsNetworkController() {
1205 return io_data_.GetDevToolsNetworkController();
1208 void ProfileImpl::ClearNetworkingHistorySince(
1209 base::Time time,
1210 const base::Closure& completion) {
1211 io_data_.ClearNetworkingHistorySince(time, completion);
1214 GURL ProfileImpl::GetHomePage() {
1215 // --homepage overrides any preferences.
1216 const base::CommandLine& command_line =
1217 *base::CommandLine::ForCurrentProcess();
1218 if (command_line.HasSwitch(switches::kHomePage)) {
1219 // TODO(evanm): clean up usage of DIR_CURRENT.
1220 // http://code.google.com/p/chromium/issues/detail?id=60630
1221 // For now, allow this code to call getcwd().
1222 base::ThreadRestrictions::ScopedAllowIO allow_io;
1224 base::FilePath browser_directory;
1225 PathService::Get(base::DIR_CURRENT, &browser_directory);
1226 GURL home_page(url_fixer::FixupRelativeFile(
1227 browser_directory,
1228 command_line.GetSwitchValuePath(switches::kHomePage)));
1229 if (home_page.is_valid())
1230 return home_page;
1233 if (GetPrefs()->GetBoolean(prefs::kHomePageIsNewTabPage))
1234 return GURL(chrome::kChromeUINewTabURL);
1235 GURL home_page(url_fixer::FixupURL(GetPrefs()->GetString(prefs::kHomePage),
1236 std::string()));
1237 if (!home_page.is_valid())
1238 return GURL(chrome::kChromeUINewTabURL);
1239 return home_page;
1242 void ProfileImpl::UpdateProfileSupervisedUserIdCache() {
1243 ProfileManager* profile_manager = g_browser_process->profile_manager();
1244 ProfileInfoCache& cache = profile_manager->GetProfileInfoCache();
1245 size_t index = cache.GetIndexOfProfileWithPath(GetPath());
1246 if (index != std::string::npos) {
1247 std::string supervised_user_id =
1248 GetPrefs()->GetString(prefs::kSupervisedUserId);
1249 cache.SetSupervisedUserIdOfProfileAtIndex(index, supervised_user_id);
1250 ProfileMetrics::UpdateReportedProfilesStatistics(profile_manager);
1254 void ProfileImpl::UpdateProfileNameCache() {
1255 ProfileManager* profile_manager = g_browser_process->profile_manager();
1256 ProfileInfoCache& cache = profile_manager->GetProfileInfoCache();
1257 size_t index = cache.GetIndexOfProfileWithPath(GetPath());
1258 if (index != std::string::npos) {
1259 std::string profile_name =
1260 GetPrefs()->GetString(prefs::kProfileName);
1261 cache.SetNameOfProfileAtIndex(index, base::UTF8ToUTF16(profile_name));
1262 bool default_name =
1263 GetPrefs()->GetBoolean(prefs::kProfileUsingDefaultName);
1264 cache.SetProfileIsUsingDefaultNameAtIndex(index, default_name);
1268 void ProfileImpl::UpdateProfileAvatarCache() {
1269 ProfileManager* profile_manager = g_browser_process->profile_manager();
1270 ProfileInfoCache& cache = profile_manager->GetProfileInfoCache();
1271 size_t index = cache.GetIndexOfProfileWithPath(GetPath());
1272 if (index != std::string::npos) {
1273 size_t avatar_index =
1274 GetPrefs()->GetInteger(prefs::kProfileAvatarIndex);
1275 cache.SetAvatarIconOfProfileAtIndex(index, avatar_index);
1276 bool default_avatar =
1277 GetPrefs()->GetBoolean(prefs::kProfileUsingDefaultAvatar);
1278 cache.SetProfileIsUsingDefaultAvatarAtIndex(index, default_avatar);
1279 bool gaia_avatar =
1280 GetPrefs()->GetBoolean(prefs::kProfileUsingGAIAAvatar);
1281 cache.SetIsUsingGAIAPictureOfProfileAtIndex(index, gaia_avatar);
1285 void ProfileImpl::UpdateProfileIsEphemeralCache() {
1286 ProfileManager* profile_manager = g_browser_process->profile_manager();
1287 ProfileInfoCache& cache = profile_manager->GetProfileInfoCache();
1288 size_t index = cache.GetIndexOfProfileWithPath(GetPath());
1289 if (index != std::string::npos) {
1290 bool is_ephemeral = GetPrefs()->GetBoolean(prefs::kForceEphemeralProfiles);
1291 cache.SetProfileIsEphemeralAtIndex(index, is_ephemeral);
1295 // Gets the cache parameters from the command line. If |is_media_context| is
1296 // set to true then settings for the media context type is what we need,
1297 // |cache_path| will be set to the user provided path, or will not be touched if
1298 // there is not an argument. |max_size| will be the user provided value or zero
1299 // by default.
1300 void ProfileImpl::GetCacheParameters(bool is_media_context,
1301 base::FilePath* cache_path,
1302 int* max_size) {
1303 DCHECK(cache_path);
1304 DCHECK(max_size);
1305 base::FilePath path(prefs_->GetFilePath(prefs::kDiskCacheDir));
1306 if (!path.empty())
1307 *cache_path = path;
1308 *max_size = is_media_context ? prefs_->GetInteger(prefs::kMediaCacheSize) :
1309 prefs_->GetInteger(prefs::kDiskCacheSize);
1312 PrefProxyConfigTracker* ProfileImpl::CreateProxyConfigTracker() {
1313 #if defined(OS_CHROMEOS)
1314 if (chromeos::ProfileHelper::IsSigninProfile(this)) {
1315 return ProxyServiceFactory::CreatePrefProxyConfigTrackerOfLocalState(
1316 g_browser_process->local_state());
1318 #endif // defined(OS_CHROMEOS)
1319 return ProxyServiceFactory::CreatePrefProxyConfigTrackerOfProfile(
1320 GetPrefs(), g_browser_process->local_state());
1323 scoped_ptr<domain_reliability::DomainReliabilityMonitor>
1324 ProfileImpl::CreateDomainReliabilityMonitor(PrefService* local_state) {
1325 domain_reliability::DomainReliabilityService* service =
1326 domain_reliability::DomainReliabilityServiceFactory::GetInstance()->
1327 GetForBrowserContext(this);
1328 if (!service)
1329 return scoped_ptr<domain_reliability::DomainReliabilityMonitor>();
1331 return service->CreateMonitor(
1332 BrowserThread::GetMessageLoopProxyForThread(BrowserThread::IO));