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