Move Webstore URL concepts to //extensions and out
[chromium-blink-merge.git] / chrome / browser / profiles / profile_impl.cc
blobadf8ee4ddfb9ba4def205c654b656eff735c884e
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/debug/trace_event.h"
14 #include "base/environment.h"
15 #include "base/files/file_path.h"
16 #include "base/files/file_util.h"
17 #include "base/memory/scoped_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/version.h"
28 #include "chrome/browser/autocomplete/autocomplete_classifier.h"
29 #include "chrome/browser/autocomplete/shortcuts_backend.h"
30 #include "chrome/browser/background/background_contents_service_factory.h"
31 #include "chrome/browser/background/background_mode_manager.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/content_settings/host_content_settings_map.h"
37 #include "chrome/browser/dom_distiller/dom_distiller_service_factory.h"
38 #include "chrome/browser/dom_distiller/lazy_dom_distiller_service.h"
39 #include "chrome/browser/domain_reliability/service_factory.h"
40 #include "chrome/browser/download/chrome_download_manager_delegate.h"
41 #include "chrome/browser/download/download_service.h"
42 #include "chrome/browser/download/download_service_factory.h"
43 #include "chrome/browser/history/top_sites.h"
44 #include "chrome/browser/net/net_pref_observer.h"
45 #include "chrome/browser/net/predictor.h"
46 #include "chrome/browser/net/pref_proxy_config_tracker.h"
47 #include "chrome/browser/net/proxy_service_factory.h"
48 #include "chrome/browser/net/spdyproxy/data_reduction_proxy_chrome_configurator.h"
49 #include "chrome/browser/net/spdyproxy/data_reduction_proxy_chrome_settings.h"
50 #include "chrome/browser/net/ssl_config_service_manager.h"
51 #include "chrome/browser/plugins/chrome_plugin_service_filter.h"
52 #include "chrome/browser/plugins/plugin_prefs.h"
53 #include "chrome/browser/policy/profile_policy_connector.h"
54 #include "chrome/browser/policy/profile_policy_connector_factory.h"
55 #include "chrome/browser/prefs/browser_prefs.h"
56 #include "chrome/browser/prefs/chrome_pref_service_factory.h"
57 #include "chrome/browser/prefs/pref_service_syncable.h"
58 #include "chrome/browser/prefs/tracked/tracked_preference_validation_delegate.h"
59 #include "chrome/browser/prerender/prerender_manager_factory.h"
60 #include "chrome/browser/profiles/bookmark_model_loaded_observer.h"
61 #include "chrome/browser/profiles/chrome_version_service.h"
62 #include "chrome/browser/profiles/gaia_info_update_service_factory.h"
63 #include "chrome/browser/profiles/profile_destroyer.h"
64 #include "chrome/browser/profiles/profile_info_cache.h"
65 #include "chrome/browser/profiles/profile_manager.h"
66 #include "chrome/browser/profiles/profile_metrics.h"
67 #include "chrome/browser/safe_browsing/safe_browsing_service.h"
68 #include "chrome/browser/services/gcm/gcm_profile_service.h"
69 #include "chrome/browser/services/gcm/gcm_profile_service_factory.h"
70 #include "chrome/browser/services/gcm/push_messaging_service_impl.h"
71 #include "chrome/browser/sessions/session_service_factory.h"
72 #include "chrome/browser/signin/signin_ui_util.h"
73 #include "chrome/browser/ssl/chrome_ssl_host_state_delegate.h"
74 #include "chrome/browser/ssl/chrome_ssl_host_state_delegate_factory.h"
75 #include "chrome/browser/ui/startup/startup_browser_creator.h"
76 #include "chrome/common/chrome_constants.h"
77 #include "chrome/common/chrome_paths_internal.h"
78 #include "chrome/common/chrome_switches.h"
79 #include "chrome/common/chrome_version_info.h"
80 #include "chrome/common/pref_names.h"
81 #include "chrome/common/url_constants.h"
82 #include "chrome/grit/chromium_strings.h"
83 #include "components/bookmarks/browser/bookmark_model.h"
84 #include "components/dom_distiller/content/dom_distiller_viewer_source.h"
85 #include "components/dom_distiller/core/url_constants.h"
86 #include "components/domain_reliability/monitor.h"
87 #include "components/domain_reliability/service.h"
88 #include "components/keyed_service/content/browser_context_dependency_manager.h"
89 #include "components/metrics/metrics_service.h"
90 #include "components/pref_registry/pref_registry_syncable.h"
91 #include "components/startup_metric_utils/startup_metric_utils.h"
92 #include "components/url_fixer/url_fixer.h"
93 #include "components/user_prefs/user_prefs.h"
94 #include "content/public/browser/browser_thread.h"
95 #include "content/public/browser/dom_storage_context.h"
96 #include "content/public/browser/host_zoom_map.h"
97 #include "content/public/browser/notification_service.h"
98 #include "content/public/browser/render_process_host.h"
99 #include "content/public/browser/storage_partition.h"
100 #include "content/public/browser/url_data_source.h"
101 #include "content/public/browser/user_metrics.h"
102 #include "content/public/common/content_constants.h"
103 #include "content/public/common/page_zoom.h"
104 #include "ui/base/l10n/l10n_util.h"
106 #if defined(OS_ANDROID)
107 #include "chrome/browser/media/protected_media_identifier_permission_context.h"
108 #include "chrome/browser/media/protected_media_identifier_permission_context_factory.h"
109 #endif
111 #if defined(OS_CHROMEOS)
112 #include "chrome/browser/chromeos/locale_change_guard.h"
113 #include "chrome/browser/chromeos/preferences.h"
114 #include "chrome/browser/chromeos/profiles/profile_helper.h"
115 #include "components/user_manager/user_manager.h"
116 #endif
118 #if defined(SPDY_PROXY_AUTH_ORIGIN)
119 #include "chrome/browser/net/spdyproxy/data_reduction_proxy_chrome_settings_factory.h"
120 #include "components/data_reduction_proxy/browser/data_reduction_proxy_params.h"
121 #include "components/data_reduction_proxy/browser/data_reduction_proxy_settings.h"
122 #include "components/data_reduction_proxy/browser/data_reduction_proxy_statistics_prefs.h"
123 #endif
125 #if defined(ENABLE_CONFIGURATION_POLICY)
126 #include "chrome/browser/policy/schema_registry_service.h"
127 #include "chrome/browser/policy/schema_registry_service_factory.h"
128 #include "components/policy/core/browser/browser_policy_connector.h"
129 #if defined(OS_CHROMEOS)
130 #include "chrome/browser/chromeos/login/login_utils.h"
131 #include "chrome/browser/chromeos/policy/user_cloud_policy_manager_chromeos.h"
132 #include "chrome/browser/chromeos/policy/user_cloud_policy_manager_factory_chromeos.h"
133 #else
134 #include "chrome/browser/policy/cloud/user_cloud_policy_manager_factory.h"
135 #include "components/policy/core/common/cloud/user_cloud_policy_manager.h"
136 #endif
137 #endif
139 #if defined(ENABLE_EXTENSIONS)
140 #include "chrome/browser/extensions/extension_service.h"
141 #include "chrome/browser/extensions/extension_special_storage_policy.h"
142 #include "chrome/browser/ui/webui/extensions/extension_icon_source.h"
143 #include "extensions/browser/extension_pref_store.h"
144 #include "extensions/browser/extension_pref_value_map.h"
145 #include "extensions/browser/extension_pref_value_map_factory.h"
146 #include "extensions/browser/extension_system.h"
147 #include "extensions/browser/guest_view/guest_view_manager.h"
148 #endif
150 #if defined(ENABLE_MANAGED_USERS)
151 #include "chrome/browser/supervised_user/supervised_user_settings_service.h"
152 #include "chrome/browser/supervised_user/supervised_user_settings_service_factory.h"
153 #endif
155 using base::Time;
156 using base::TimeDelta;
157 using base::UserMetricsAction;
158 using content::BrowserThread;
159 using content::DownloadManagerDelegate;
160 using content::HostZoomMap;
162 namespace {
164 #if defined(ENABLE_SESSION_SERVICE)
165 // Delay, in milliseconds, before we explicitly create the SessionService.
166 const int kCreateSessionServiceDelayMS = 500;
167 #endif
169 // Text content of README file created in each profile directory. Both %s
170 // placeholders must contain the product name. This is not localizable and hence
171 // not in resources.
172 const char kReadmeText[] =
173 "%s settings and storage represent user-selected preferences and "
174 "information and MUST not be extracted, overwritten or modified except "
175 "through %s defined APIs.";
177 // Value written to prefs for EXIT_CRASHED and EXIT_SESSION_ENDED.
178 const char kPrefExitTypeCrashed[] = "Crashed";
179 const char kPrefExitTypeSessionEnded[] = "SessionEnded";
181 // Helper method needed because PostTask cannot currently take a Callback
182 // function with non-void return type.
183 void CreateDirectoryAndSignal(const base::FilePath& path,
184 base::WaitableEvent* done_creating) {
185 DVLOG(1) << "Creating directory " << path.value();
186 base::CreateDirectory(path);
187 done_creating->Signal();
190 // Task that blocks the FILE thread until CreateDirectoryAndSignal() finishes on
191 // blocking I/O pool.
192 void BlockFileThreadOnDirectoryCreate(base::WaitableEvent* done_creating) {
193 done_creating->Wait();
196 // Initiates creation of profile directory on |sequenced_task_runner| and
197 // ensures that FILE thread is blocked until that operation finishes.
198 void CreateProfileDirectory(base::SequencedTaskRunner* sequenced_task_runner,
199 const base::FilePath& path) {
200 base::WaitableEvent* done_creating = new base::WaitableEvent(false, false);
201 sequenced_task_runner->PostTask(FROM_HERE,
202 base::Bind(&CreateDirectoryAndSignal,
203 path,
204 done_creating));
205 // Block the FILE thread until directory is created on I/O pool to make sure
206 // that we don't attempt any operation until that part completes.
207 BrowserThread::PostTask(
208 BrowserThread::FILE, FROM_HERE,
209 base::Bind(&BlockFileThreadOnDirectoryCreate,
210 base::Owned(done_creating)));
213 base::FilePath GetCachePath(const base::FilePath& base) {
214 return base.Append(chrome::kCacheDirname);
217 base::FilePath GetMediaCachePath(const base::FilePath& base) {
218 return base.Append(chrome::kMediaCacheDirname);
221 void EnsureReadmeFile(const base::FilePath& base) {
222 base::FilePath readme_path = base.Append(chrome::kReadmeFilename);
223 if (base::PathExists(readme_path))
224 return;
225 std::string product_name = l10n_util::GetStringUTF8(IDS_PRODUCT_NAME);
226 std::string readme_text = base::StringPrintf(
227 kReadmeText, product_name.c_str(), product_name.c_str());
228 if (base::WriteFile(readme_path, readme_text.data(), readme_text.size()) ==
229 -1) {
230 LOG(ERROR) << "Could not create README file.";
234 // Converts the kSessionExitedCleanly pref to the corresponding EXIT_TYPE.
235 Profile::ExitType SessionTypePrefValueToExitType(const std::string& value) {
236 if (value == kPrefExitTypeSessionEnded)
237 return Profile::EXIT_SESSION_ENDED;
238 if (value == kPrefExitTypeCrashed)
239 return Profile::EXIT_CRASHED;
240 return Profile::EXIT_NORMAL;
243 // Converts an ExitType into a string that is written to prefs.
244 std::string ExitTypeToSessionTypePrefValue(Profile::ExitType type) {
245 switch (type) {
246 case Profile::EXIT_NORMAL:
247 return ProfileImpl::kPrefExitTypeNormal;
248 case Profile::EXIT_SESSION_ENDED:
249 return kPrefExitTypeSessionEnded;
250 case Profile::EXIT_CRASHED:
251 return kPrefExitTypeCrashed;
253 NOTREACHED();
254 return std::string();
257 // Setup URLDataSource for the chrome-distiller:// scheme for the given
258 // |profile|.
259 void RegisterDomDistillerViewerSource(Profile* profile) {
260 const CommandLine& command_line = *CommandLine::ForCurrentProcess();
261 if (command_line.HasSwitch(switches::kEnableDomDistiller)) {
262 dom_distiller::DomDistillerServiceFactory* dom_distiller_service_factory =
263 dom_distiller::DomDistillerServiceFactory::GetInstance();
264 // The LazyDomDistillerService deletes itself when the profile is destroyed.
265 dom_distiller::LazyDomDistillerService* lazy_service =
266 new dom_distiller::LazyDomDistillerService(
267 profile, dom_distiller_service_factory);
268 content::URLDataSource::Add(
269 profile,
270 new dom_distiller::DomDistillerViewerSource(
271 lazy_service, dom_distiller::kDomDistillerScheme));
275 PrefStore* CreateExtensionPrefStore(Profile* profile,
276 bool incognito_pref_store) {
277 #if defined(ENABLE_EXTENSIONS)
278 return new ExtensionPrefStore(
279 ExtensionPrefValueMapFactory::GetForBrowserContext(profile),
280 incognito_pref_store);
281 #else
282 return NULL;
283 #endif
286 } // namespace
288 // static
289 Profile* Profile::CreateProfile(const base::FilePath& path,
290 Delegate* delegate,
291 CreateMode create_mode) {
292 TRACE_EVENT_BEGIN1("browser",
293 "Profile::CreateProfile",
294 "profile_path",
295 path.value().c_str());
297 // Get sequenced task runner for making sure that file operations of
298 // this profile (defined by |path|) are executed in expected order
299 // (what was previously assured by the FILE thread).
300 scoped_refptr<base::SequencedTaskRunner> sequenced_task_runner =
301 JsonPrefStore::GetTaskRunnerForFile(path,
302 BrowserThread::GetBlockingPool());
303 if (create_mode == CREATE_MODE_ASYNCHRONOUS) {
304 DCHECK(delegate);
305 CreateProfileDirectory(sequenced_task_runner.get(), path);
306 } else if (create_mode == CREATE_MODE_SYNCHRONOUS) {
307 if (!base::PathExists(path)) {
308 // TODO(tc): http://b/1094718 Bad things happen if we can't write to the
309 // profile directory. We should eventually be able to run in this
310 // situation.
311 if (!base::CreateDirectory(path))
312 return NULL;
314 } else {
315 NOTREACHED();
318 return new ProfileImpl(
319 path, delegate, create_mode, sequenced_task_runner.get());
322 // static
323 int ProfileImpl::create_readme_delay_ms = 60000;
325 // static
326 const char* const ProfileImpl::kPrefExitTypeNormal = "Normal";
328 // static
329 void ProfileImpl::RegisterProfilePrefs(
330 user_prefs::PrefRegistrySyncable* registry) {
331 registry->RegisterBooleanPref(
332 prefs::kSavingBrowserHistoryDisabled,
333 false,
334 user_prefs::PrefRegistrySyncable::UNSYNCABLE_PREF);
335 registry->RegisterBooleanPref(
336 prefs::kAllowDeletingBrowserHistory,
337 true,
338 user_prefs::PrefRegistrySyncable::UNSYNCABLE_PREF);
339 registry->RegisterBooleanPref(
340 prefs::kSigninAllowed,
341 true,
342 user_prefs::PrefRegistrySyncable::UNSYNCABLE_PREF);
343 registry->RegisterBooleanPref(
344 prefs::kForceSafeSearch,
345 false,
346 user_prefs::PrefRegistrySyncable::UNSYNCABLE_PREF);
347 registry->RegisterIntegerPref(
348 prefs::kProfileAvatarIndex,
350 user_prefs::PrefRegistrySyncable::SYNCABLE_PREF);
351 // Whether a profile is using an avatar without having explicitely chosen it
352 // (i.e. was assigned by default by legacy profile creation).
353 registry->RegisterBooleanPref(
354 prefs::kProfileUsingDefaultAvatar,
355 true,
356 user_prefs::PrefRegistrySyncable::SYNCABLE_PREF);
357 registry->RegisterBooleanPref(
358 prefs::kProfileUsingGAIAAvatar,
359 false,
360 user_prefs::PrefRegistrySyncable::SYNCABLE_PREF);
361 // Whether a profile is using a default avatar name (eg. Pickles or Person 1).
362 registry->RegisterBooleanPref(
363 prefs::kProfileUsingDefaultName,
364 true,
365 user_prefs::PrefRegistrySyncable::SYNCABLE_PREF);
366 registry->RegisterStringPref(
367 prefs::kSupervisedUserId,
368 std::string(),
369 user_prefs::PrefRegistrySyncable::UNSYNCABLE_PREF);
370 registry->RegisterStringPref(prefs::kProfileName,
371 std::string(),
372 user_prefs::PrefRegistrySyncable::SYNCABLE_PREF);
373 registry->RegisterStringPref(prefs::kHomePage,
374 std::string(),
375 user_prefs::PrefRegistrySyncable::SYNCABLE_PREF);
376 #if defined(ENABLE_PRINTING)
377 registry->RegisterBooleanPref(
378 prefs::kPrintingEnabled,
379 true,
380 user_prefs::PrefRegistrySyncable::UNSYNCABLE_PREF);
381 #endif
382 registry->RegisterBooleanPref(
383 prefs::kForceEphemeralProfiles,
384 false,
385 user_prefs::PrefRegistrySyncable::UNSYNCABLE_PREF);
387 // Initialize the cache prefs.
388 registry->RegisterFilePathPref(
389 prefs::kDiskCacheDir,
390 base::FilePath(),
391 user_prefs::PrefRegistrySyncable::UNSYNCABLE_PREF);
392 registry->RegisterIntegerPref(
393 prefs::kDiskCacheSize,
395 user_prefs::PrefRegistrySyncable::UNSYNCABLE_PREF);
396 registry->RegisterIntegerPref(
397 prefs::kMediaCacheSize,
399 user_prefs::PrefRegistrySyncable::UNSYNCABLE_PREF);
401 // Deprecated. Kept around for migration.
402 registry->RegisterBooleanPref(
403 prefs::kClearSiteDataOnExit,
404 false,
405 user_prefs::PrefRegistrySyncable::SYNCABLE_PREF);
408 ProfileImpl::ProfileImpl(
409 const base::FilePath& path,
410 Delegate* delegate,
411 CreateMode create_mode,
412 base::SequencedTaskRunner* sequenced_task_runner)
413 : path_(path),
414 pref_registry_(new user_prefs::PrefRegistrySyncable),
415 io_data_(this),
416 host_content_settings_map_(NULL),
417 last_session_exit_type_(EXIT_NORMAL),
418 start_time_(Time::Now()),
419 delegate_(delegate),
420 predictor_(NULL) {
421 TRACE_EVENT0("browser", "ProfileImpl::ctor")
422 DCHECK(!path.empty()) << "Using an empty path will attempt to write " <<
423 "profile files to the root directory!";
425 #if defined(ENABLE_SESSION_SERVICE)
426 create_session_service_timer_.Start(FROM_HERE,
427 TimeDelta::FromMilliseconds(kCreateSessionServiceDelayMS), this,
428 &ProfileImpl::EnsureSessionServiceCreated);
429 #endif
431 // Determine if prefetch is enabled for this profile.
432 // If not profile_manager is present, it means we are in a unittest.
433 const CommandLine* command_line = CommandLine::ForCurrentProcess();
434 predictor_ = chrome_browser_net::Predictor::CreatePredictor(
435 !command_line->HasSwitch(switches::kDisablePreconnect),
436 !command_line->HasSwitch(switches::kDnsPrefetchDisable),
437 g_browser_process->profile_manager() == NULL);
439 // If we are creating the profile synchronously, then we should load the
440 // policy data immediately.
441 bool force_immediate_policy_load = (create_mode == CREATE_MODE_SYNCHRONOUS);
442 #if defined(ENABLE_CONFIGURATION_POLICY)
443 policy::BrowserPolicyConnector* connector =
444 g_browser_process->browser_policy_connector();
445 schema_registry_service_ =
446 policy::SchemaRegistryServiceFactory::CreateForContext(
447 this, connector->GetChromeSchema(), connector->GetSchemaRegistry());
448 #if defined(OS_CHROMEOS)
449 cloud_policy_manager_ =
450 policy::UserCloudPolicyManagerFactoryChromeOS::CreateForProfile(
451 this, force_immediate_policy_load, sequenced_task_runner);
452 #else
453 cloud_policy_manager_ =
454 policy::UserCloudPolicyManagerFactory::CreateForOriginalBrowserContext(
455 this,
456 force_immediate_policy_load,
457 sequenced_task_runner,
458 BrowserThread::GetMessageLoopProxyForThread(BrowserThread::FILE),
459 BrowserThread::GetMessageLoopProxyForThread(BrowserThread::IO));
460 #endif
461 #endif
462 profile_policy_connector_ =
463 policy::ProfilePolicyConnectorFactory::CreateForProfile(
464 this, force_immediate_policy_load);
466 DCHECK(create_mode == CREATE_MODE_ASYNCHRONOUS ||
467 create_mode == CREATE_MODE_SYNCHRONOUS);
468 bool async_prefs = create_mode == CREATE_MODE_ASYNCHRONOUS;
470 #if defined(OS_CHROMEOS)
471 if (chromeos::ProfileHelper::IsSigninProfile(this))
472 chrome::RegisterLoginProfilePrefs(pref_registry_.get());
473 else
474 #endif
475 chrome::RegisterUserProfilePrefs(pref_registry_.get());
477 BrowserContextDependencyManager::GetInstance()->
478 RegisterProfilePrefsForServices(this, pref_registry_.get());
480 SupervisedUserSettingsService* supervised_user_settings = NULL;
481 #if defined(ENABLE_MANAGED_USERS)
482 supervised_user_settings =
483 SupervisedUserSettingsServiceFactory::GetForProfile(this);
484 supervised_user_settings->Init(
485 path_, sequenced_task_runner, create_mode == CREATE_MODE_SYNCHRONOUS);
486 #endif
488 scoped_refptr<SafeBrowsingService> safe_browsing_service(
489 g_browser_process->safe_browsing_service());
490 if (safe_browsing_service.get()) {
491 pref_validation_delegate_ =
492 safe_browsing_service->CreatePreferenceValidationDelegate(this).Pass();
496 // On startup, preference loading is always synchronous so a scoped timer
497 // will work here.
498 startup_metric_utils::ScopedSlowStartupUMA
499 scoped_timer("Startup.SlowStartupPreferenceLoading");
500 prefs_ = chrome_prefs::CreateProfilePrefs(
501 path_,
502 sequenced_task_runner,
503 pref_validation_delegate_.get(),
504 profile_policy_connector_->policy_service(),
505 supervised_user_settings,
506 CreateExtensionPrefStore(this, false),
507 pref_registry_,
508 async_prefs).Pass();
509 // Register on BrowserContext.
510 user_prefs::UserPrefs::Set(this, prefs_.get());
513 startup_metric_utils::ScopedSlowStartupUMA
514 scoped_timer("Startup.SlowStartupFinalProfileInit");
515 if (async_prefs) {
516 // Wait for the notification that prefs has been loaded
517 // (successfully or not). Note that we can use base::Unretained
518 // because the PrefService is owned by this class and lives on
519 // the same thread.
520 prefs_->AddPrefInitObserver(base::Bind(&ProfileImpl::OnPrefsLoaded,
521 base::Unretained(this)));
522 } else {
523 // Prefs were loaded synchronously so we can continue directly.
524 OnPrefsLoaded(true);
528 void ProfileImpl::DoFinalInit() {
529 TRACE_EVENT0("browser", "ProfileImpl::DoFinalInit")
530 PrefService* prefs = GetPrefs();
531 pref_change_registrar_.Init(prefs);
532 pref_change_registrar_.Add(
533 prefs::kGoogleServicesUsername,
534 base::Bind(&ProfileImpl::UpdateProfileUserNameCache,
535 base::Unretained(this)));
536 pref_change_registrar_.Add(
537 prefs::kSupervisedUserId,
538 base::Bind(&ProfileImpl::UpdateProfileSupervisedUserIdCache,
539 base::Unretained(this)));
540 pref_change_registrar_.Add(
541 prefs::kDefaultZoomLevel,
542 base::Bind(&ProfileImpl::OnDefaultZoomLevelChanged,
543 base::Unretained(this)));
545 // Changes in the profile avatar.
546 pref_change_registrar_.Add(
547 prefs::kProfileAvatarIndex,
548 base::Bind(&ProfileImpl::UpdateProfileAvatarCache,
549 base::Unretained(this)));
550 pref_change_registrar_.Add(
551 prefs::kProfileUsingDefaultAvatar,
552 base::Bind(&ProfileImpl::UpdateProfileAvatarCache,
553 base::Unretained(this)));
554 pref_change_registrar_.Add(
555 prefs::kProfileUsingGAIAAvatar,
556 base::Bind(&ProfileImpl::UpdateProfileAvatarCache,
557 base::Unretained(this)));
559 // Changes in the profile name.
560 pref_change_registrar_.Add(
561 prefs::kProfileUsingDefaultName,
562 base::Bind(&ProfileImpl::UpdateProfileNameCache,
563 base::Unretained(this)));
564 pref_change_registrar_.Add(
565 prefs::kProfileName,
566 base::Bind(&ProfileImpl::UpdateProfileNameCache,
567 base::Unretained(this)));
569 pref_change_registrar_.Add(
570 prefs::kForceEphemeralProfiles,
571 base::Bind(&ProfileImpl::UpdateProfileIsEphemeralCache,
572 base::Unretained(this)));
574 // It would be nice to use PathService for fetching this directory, but
575 // the cache directory depends on the profile directory, which isn't available
576 // to PathService.
577 chrome::GetUserCacheDirectory(path_, &base_cache_path_);
578 // Always create the cache directory asynchronously.
579 scoped_refptr<base::SequencedTaskRunner> sequenced_task_runner =
580 JsonPrefStore::GetTaskRunnerForFile(base_cache_path_,
581 BrowserThread::GetBlockingPool());
582 CreateProfileDirectory(sequenced_task_runner.get(), base_cache_path_);
584 // Now that the profile is hooked up to receive pref change notifications to
585 // kGoogleServicesUsername, initialize components that depend on it to reflect
586 // the current value.
587 UpdateProfileUserNameCache();
588 UpdateProfileSupervisedUserIdCache();
589 UpdateProfileIsEphemeralCache();
590 GAIAInfoUpdateServiceFactory::GetForProfile(this);
592 PrefService* local_state = g_browser_process->local_state();
593 ssl_config_service_manager_.reset(
594 SSLConfigServiceManager::CreateDefaultManager(local_state));
596 // Initialize the BackgroundModeManager - this has to be done here before
597 // InitExtensions() is called because it relies on receiving notifications
598 // when extensions are loaded. BackgroundModeManager is not needed under
599 // ChromeOS because Chrome is always running, no need for special keep-alive
600 // or launch-on-startup support unless kKeepAliveForTest is set.
601 bool init_background_mode_manager = true;
602 #if defined(OS_CHROMEOS)
603 if (!CommandLine::ForCurrentProcess()->HasSwitch(switches::kKeepAliveForTest))
604 init_background_mode_manager = false;
605 #endif
606 if (init_background_mode_manager) {
607 if (g_browser_process->background_mode_manager())
608 g_browser_process->background_mode_manager()->RegisterProfile(this);
611 base::FilePath cookie_path = GetPath();
612 cookie_path = cookie_path.Append(chrome::kCookieFilename);
613 base::FilePath channel_id_path = GetPath();
614 channel_id_path = channel_id_path.Append(chrome::kChannelIDFilename);
615 base::FilePath cache_path = base_cache_path_;
616 int cache_max_size;
617 GetCacheParameters(false, &cache_path, &cache_max_size);
618 cache_path = GetCachePath(cache_path);
620 base::FilePath media_cache_path = base_cache_path_;
621 int media_cache_max_size;
622 GetCacheParameters(true, &media_cache_path, &media_cache_max_size);
623 media_cache_path = GetMediaCachePath(media_cache_path);
625 base::FilePath extensions_cookie_path = GetPath();
626 extensions_cookie_path =
627 extensions_cookie_path.Append(chrome::kExtensionsCookieFilename);
629 base::FilePath infinite_cache_path = GetPath();
630 infinite_cache_path =
631 infinite_cache_path.Append(FILE_PATH_LITERAL("Infinite Cache"));
633 #if defined(OS_ANDROID)
634 SessionStartupPref::Type startup_pref_type =
635 SessionStartupPref::GetDefaultStartupType();
636 #else
637 SessionStartupPref::Type startup_pref_type =
638 StartupBrowserCreator::GetSessionStartupPref(
639 *CommandLine::ForCurrentProcess(), this).type;
640 #endif
641 content::CookieStoreConfig::SessionCookieMode session_cookie_mode =
642 content::CookieStoreConfig::PERSISTANT_SESSION_COOKIES;
643 if (GetLastSessionExitType() == Profile::EXIT_CRASHED ||
644 startup_pref_type == SessionStartupPref::LAST) {
645 session_cookie_mode = content::CookieStoreConfig::RESTORED_SESSION_COOKIES;
648 InitHostZoomMap();
650 base::Callback<void(bool)> data_reduction_proxy_unavailable;
651 scoped_ptr<data_reduction_proxy::DataReductionProxyParams>
652 data_reduction_proxy_params;
653 scoped_ptr<DataReductionProxyChromeConfigurator> chrome_configurator;
654 scoped_ptr<data_reduction_proxy::DataReductionProxyStatisticsPrefs>
655 data_reduction_proxy_statistics_prefs;
656 #if defined(SPDY_PROXY_AUTH_ORIGIN)
657 DataReductionProxyChromeSettings* data_reduction_proxy_chrome_settings =
658 DataReductionProxyChromeSettingsFactory::GetForBrowserContext(this);
659 data_reduction_proxy_params =
660 data_reduction_proxy_chrome_settings->params()->Clone();
661 data_reduction_proxy_unavailable =
662 base::Bind(
663 &data_reduction_proxy::DataReductionProxySettings::SetUnreachable,
664 base::Unretained(data_reduction_proxy_chrome_settings));
665 // The configurator is used by DataReductionProxyChromeSettings and
666 // ProfileIOData. Ownership is passed to the latter via ProfileIOData::Handle,
667 // which is only destroyed after BrowserContextKeyedServices,
668 // including DataReductionProxyChromeSettings.
669 chrome_configurator.reset(
670 new DataReductionProxyChromeConfigurator(
671 prefs_.get(),
672 BrowserThread::GetMessageLoopProxyForThread(BrowserThread::IO)));
673 // Retain a raw pointer to use for initialization of data reduction proxy
674 // settings after ownership is passed.
675 DataReductionProxyChromeConfigurator*
676 data_reduction_proxy_chrome_configurator = chrome_configurator.get();
677 #if defined(OS_ANDROID) || defined(OS_IOS)
678 // On mobile we write data reduction proxy prefs directly to the pref service.
679 // On desktop we store data reduction proxy prefs in memory, writing to disk
680 // every 60 minutes and on termination. Shutdown hooks must be added for
681 // Android and iOS in order for non-zero delays to be supported.
682 // (http://crbug.com/408264)
683 base::TimeDelta commit_delay = base::TimeDelta();
684 #else
685 base::TimeDelta commit_delay = base::TimeDelta::FromMinutes(60);
686 #endif
687 data_reduction_proxy_statistics_prefs =
688 scoped_ptr<data_reduction_proxy::DataReductionProxyStatisticsPrefs>(
689 new data_reduction_proxy::DataReductionProxyStatisticsPrefs(
690 g_browser_process->local_state(),
691 base::MessageLoopProxy::current(),
692 commit_delay));
693 data_reduction_proxy_chrome_settings->SetDataReductionProxyStatisticsPrefs(
694 data_reduction_proxy_statistics_prefs.get());
695 #endif // defined(SPDY_PROXY_AUTH_ORIGIN)
697 // Make sure we initialize the ProfileIOData after everything else has been
698 // initialized that we might be reading from the IO thread.
700 io_data_.Init(cookie_path, channel_id_path, cache_path,
701 cache_max_size, media_cache_path, media_cache_max_size,
702 extensions_cookie_path, GetPath(), infinite_cache_path,
703 predictor_, session_cookie_mode, GetSpecialStoragePolicy(),
704 CreateDomainReliabilityMonitor(local_state),
705 data_reduction_proxy_unavailable,
706 chrome_configurator.Pass(),
707 data_reduction_proxy_params.Pass(),
708 data_reduction_proxy_statistics_prefs.Pass());
710 #if defined(SPDY_PROXY_AUTH_ORIGIN)
711 data_reduction_proxy_chrome_settings->InitDataReductionProxySettings(
712 data_reduction_proxy_chrome_configurator,
713 prefs_.get(),
714 g_browser_process->local_state(),
715 GetRequestContext());
716 #endif
718 #if defined(ENABLE_PLUGINS)
719 ChromePluginServiceFilter::GetInstance()->RegisterResourceContext(
720 PluginPrefs::GetForProfile(this).get(),
721 io_data_.GetResourceContextNoInit());
722 #endif
724 // Delay README creation to not impact startup performance.
725 BrowserThread::PostDelayedTask(
726 BrowserThread::FILE, FROM_HERE,
727 base::Bind(&EnsureReadmeFile, GetPath()),
728 base::TimeDelta::FromMilliseconds(create_readme_delay_ms));
730 TRACE_EVENT0("browser", "ProfileImpl::SetSaveSessionStorageOnDisk");
731 content::BrowserContext::GetDefaultStoragePartition(this)->
732 GetDOMStorageContext()->SetSaveSessionStorageOnDisk();
734 // The DomDistillerViewerSource is not a normal WebUI so it must be registered
735 // as a URLDataSource early.
736 RegisterDomDistillerViewerSource(this);
738 // Creation has been finished.
739 TRACE_EVENT_END1("browser",
740 "Profile::CreateProfile",
741 "profile_path",
742 path_.value().c_str());
744 #if defined(OS_CHROMEOS)
745 if (chromeos::LoginUtils::Get()->RestartToApplyPerSessionFlagsIfNeed(this,
746 true)) {
747 return;
749 #endif
751 if (delegate_) {
752 TRACE_EVENT0("browser", "ProfileImpl::DoFileInit:DelegateOnProfileCreated")
753 delegate_->OnProfileCreated(this, true, IsNewProfile());
756 content::NotificationService::current()->Notify(
757 chrome::NOTIFICATION_PROFILE_CREATED,
758 content::Source<Profile>(this),
759 content::NotificationService::NoDetails());
761 #if !defined(OS_CHROMEOS)
762 // Listen for bookmark model load, to bootstrap the sync service.
763 // On CrOS sync service will be initialized after sign in.
764 BookmarkModel* model = BookmarkModelFactory::GetForProfile(this);
765 model->AddObserver(new BookmarkModelLoadedObserver(this));
766 #endif
768 gcm::PushMessagingServiceImpl::InitializeForProfile(this);
770 #if !defined(OS_ANDROID) && !defined(OS_CHROMEOS) && !defined(OS_IOS)
771 signin_ui_util::InitializePrefsForProfile(this);
772 #endif
775 void ProfileImpl::InitHostZoomMap() {
776 HostZoomMap* host_zoom_map = HostZoomMap::GetDefaultForBrowserContext(this);
777 host_zoom_map->SetDefaultZoomLevel(
778 prefs_->GetDouble(prefs::kDefaultZoomLevel));
780 const base::DictionaryValue* host_zoom_dictionary =
781 prefs_->GetDictionary(prefs::kPerHostZoomLevels);
782 // Careful: The returned value could be NULL if the pref has never been set.
783 if (host_zoom_dictionary != NULL) {
784 std::vector<std::string> keys_to_remove;
785 for (base::DictionaryValue::Iterator i(*host_zoom_dictionary); !i.IsAtEnd();
786 i.Advance()) {
787 const std::string& host(i.key());
788 double zoom_level = 0;
790 bool success = i.value().GetAsDouble(&zoom_level);
791 DCHECK(success);
793 // Filter out A) the empty host, B) zoom levels equal to the default; and
794 // remember them, so that we can later erase them from Prefs.
795 // Values of type A and B could have been stored due to crbug.com/364399.
796 // Values of type B could further have been stored before the default zoom
797 // level was set to its current value. In either case, SetZoomLevelForHost
798 // will ignore type B values, thus, to have consistency with HostZoomMap's
799 // internal state, these values must also be removed from Prefs.
800 if (host.empty() ||
801 content::ZoomValuesEqual(zoom_level,
802 host_zoom_map->GetDefaultZoomLevel())) {
803 keys_to_remove.push_back(host);
804 continue;
807 host_zoom_map->SetZoomLevelForHost(host, zoom_level);
810 DictionaryPrefUpdate update(prefs_.get(), prefs::kPerHostZoomLevels);
811 base::DictionaryValue* host_zoom_dictionary = update.Get();
812 for (std::vector<std::string>::const_iterator it = keys_to_remove.begin();
813 it != keys_to_remove.end(); ++it) {
814 host_zoom_dictionary->RemoveWithoutPathExpansion(*it, NULL);
818 zoom_subscription_ = host_zoom_map->AddZoomLevelChangedCallback(
819 base::Bind(&ProfileImpl::OnZoomLevelChanged, base::Unretained(this)));
822 base::FilePath ProfileImpl::last_selected_directory() {
823 return GetPrefs()->GetFilePath(prefs::kSelectFileLastDirectory);
826 void ProfileImpl::set_last_selected_directory(const base::FilePath& path) {
827 GetPrefs()->SetFilePath(prefs::kSelectFileLastDirectory, path);
830 ProfileImpl::~ProfileImpl() {
831 MaybeSendDestroyedNotification();
833 bool prefs_loaded = prefs_->GetInitializationStatus() !=
834 PrefService::INITIALIZATION_STATUS_WAITING;
836 #if defined(ENABLE_SESSION_SERVICE)
837 StopCreateSessionServiceTimer();
838 #endif
840 // Remove pref observers
841 pref_change_registrar_.RemoveAll();
843 #if defined(ENABLE_PLUGINS)
844 ChromePluginServiceFilter::GetInstance()->UnregisterResourceContext(
845 io_data_.GetResourceContextNoInit());
846 #endif
848 // Destroy OTR profile and its profile services first.
849 if (off_the_record_profile_) {
850 ProfileDestroyer::DestroyOffTheRecordProfileNow(
851 off_the_record_profile_.get());
852 } else {
853 #if defined(ENABLE_EXTENSIONS)
854 ExtensionPrefValueMapFactory::GetForBrowserContext(this)->
855 ClearAllIncognitoSessionOnlyPreferences();
856 #endif
859 BrowserContextDependencyManager::GetInstance()->DestroyBrowserContextServices(
860 this);
862 if (top_sites_.get())
863 top_sites_->Shutdown();
865 if (pref_proxy_config_tracker_)
866 pref_proxy_config_tracker_->DetachFromPrefService();
868 if (host_content_settings_map_.get())
869 host_content_settings_map_->ShutdownOnUIThread();
871 // This causes the Preferences file to be written to disk.
872 if (prefs_loaded)
873 SetExitType(EXIT_NORMAL);
876 std::string ProfileImpl::GetProfileName() {
877 return GetPrefs()->GetString(prefs::kGoogleServicesUsername);
880 Profile::ProfileType ProfileImpl::GetProfileType() const {
881 return REGULAR_PROFILE;
884 base::FilePath ProfileImpl::GetPath() const {
885 return path_;
888 scoped_refptr<base::SequencedTaskRunner> ProfileImpl::GetIOTaskRunner() {
889 return JsonPrefStore::GetTaskRunnerForFile(
890 GetPath(), BrowserThread::GetBlockingPool());
893 bool ProfileImpl::IsOffTheRecord() const {
894 return false;
897 Profile* ProfileImpl::GetOffTheRecordProfile() {
898 if (!off_the_record_profile_) {
899 scoped_ptr<Profile> p(CreateOffTheRecordProfile());
900 off_the_record_profile_.swap(p);
902 content::NotificationService::current()->Notify(
903 chrome::NOTIFICATION_PROFILE_CREATED,
904 content::Source<Profile>(off_the_record_profile_.get()),
905 content::NotificationService::NoDetails());
907 return off_the_record_profile_.get();
910 void ProfileImpl::DestroyOffTheRecordProfile() {
911 off_the_record_profile_.reset();
912 #if defined(ENABLE_EXTENSIONS)
913 ExtensionPrefValueMapFactory::GetForBrowserContext(this)->
914 ClearAllIncognitoSessionOnlyPreferences();
915 #endif
918 bool ProfileImpl::HasOffTheRecordProfile() {
919 return off_the_record_profile_.get() != NULL;
922 Profile* ProfileImpl::GetOriginalProfile() {
923 return this;
926 bool ProfileImpl::IsSupervised() {
927 return !GetPrefs()->GetString(prefs::kSupervisedUserId).empty();
930 ExtensionSpecialStoragePolicy*
931 ProfileImpl::GetExtensionSpecialStoragePolicy() {
932 #if defined(ENABLE_EXTENSIONS)
933 if (!extension_special_storage_policy_.get()) {
934 TRACE_EVENT0("browser", "ProfileImpl::GetExtensionSpecialStoragePolicy")
935 extension_special_storage_policy_ = new ExtensionSpecialStoragePolicy(
936 CookieSettings::Factory::GetForProfile(this).get());
938 return extension_special_storage_policy_.get();
939 #else
940 return NULL;
941 #endif
944 void ProfileImpl::OnPrefsLoaded(bool success) {
945 TRACE_EVENT0("browser", "ProfileImpl::OnPrefsLoaded")
946 if (!success) {
947 if (delegate_)
948 delegate_->OnProfileCreated(this, false, false);
949 return;
952 // TODO(mirandac): remove migration code after 6 months (crbug.com/69995).
953 if (g_browser_process->local_state())
954 chrome::MigrateBrowserPrefs(this, g_browser_process->local_state());
955 // TODO(ivankr): remove cleanup code eventually (crbug.com/165672).
956 chrome::MigrateUserPrefs(this);
958 // |kSessionExitType| was added after |kSessionExitedCleanly|. If the pref
959 // value is empty fallback to checking for |kSessionExitedCleanly|.
960 const std::string exit_type_pref_value(
961 prefs_->GetString(prefs::kSessionExitType));
962 if (exit_type_pref_value.empty()) {
963 last_session_exit_type_ =
964 prefs_->GetBoolean(prefs::kSessionExitedCleanly) ?
965 EXIT_NORMAL : EXIT_CRASHED;
966 } else {
967 last_session_exit_type_ =
968 SessionTypePrefValueToExitType(exit_type_pref_value);
970 // Mark the session as open.
971 prefs_->SetString(prefs::kSessionExitType, kPrefExitTypeCrashed);
972 // Force this to true in case we fallback and use it.
973 // TODO(sky): remove this in a couple of releases (m28ish).
974 prefs_->SetBoolean(prefs::kSessionExitedCleanly, true);
976 #if defined(OS_ANDROID) && defined(FULL_SAFE_BROWSING)
977 // Clear safe browsing setting in the case we need to roll back
978 // for users enrolled in Finch trial before.
979 if (!SafeBrowsingService::IsEnabledByFieldTrial())
980 prefs_->ClearPref(prefs::kSafeBrowsingEnabled);
981 #endif
983 g_browser_process->profile_manager()->InitProfileUserPrefs(this);
985 BrowserContextDependencyManager::GetInstance()->CreateBrowserContextServices(
986 this);
988 DCHECK(!net_pref_observer_);
990 TRACE_EVENT0("browser", "ProfileImpl::OnPrefsLoaded:NetPrefObserver")
991 net_pref_observer_.reset(new NetPrefObserver(prefs_.get()));
994 chrome_prefs::SchedulePrefsFilePathVerification(path_);
996 ChromeVersionService::OnProfileLoaded(prefs_.get(), IsNewProfile());
997 DoFinalInit();
1000 bool ProfileImpl::WasCreatedByVersionOrLater(const std::string& version) {
1001 Version profile_version(ChromeVersionService::GetVersion(prefs_.get()));
1002 Version arg_version(version);
1003 return (profile_version.CompareTo(arg_version) >= 0);
1006 void ProfileImpl::SetExitType(ExitType exit_type) {
1007 #if defined(OS_CHROMEOS)
1008 if (chromeos::ProfileHelper::IsSigninProfile(this))
1009 return;
1010 #endif
1011 if (!prefs_)
1012 return;
1013 ExitType current_exit_type = SessionTypePrefValueToExitType(
1014 prefs_->GetString(prefs::kSessionExitType));
1015 // This may be invoked multiple times during shutdown. Only persist the value
1016 // first passed in (unless it's a reset to the crash state, which happens when
1017 // foregrounding the app on mobile).
1018 if (exit_type == EXIT_CRASHED || current_exit_type == EXIT_CRASHED) {
1019 prefs_->SetString(prefs::kSessionExitType,
1020 ExitTypeToSessionTypePrefValue(exit_type));
1022 // NOTE: If you change what thread this writes on, be sure and update
1023 // chrome::SessionEnding().
1024 prefs_->CommitPendingWrite();
1028 Profile::ExitType ProfileImpl::GetLastSessionExitType() {
1029 // last_session_exited_cleanly_ is set when the preferences are loaded. Force
1030 // it to be set by asking for the prefs.
1031 GetPrefs();
1032 return last_session_exit_type_;
1035 PrefService* ProfileImpl::GetPrefs() {
1036 DCHECK(prefs_); // Should explicitly be initialized.
1037 return prefs_.get();
1040 PrefService* ProfileImpl::GetOffTheRecordPrefs() {
1041 DCHECK(prefs_);
1042 if (!otr_prefs_) {
1043 // The new ExtensionPrefStore is ref_counted and the new PrefService
1044 // stores a reference so that we do not leak memory here.
1045 otr_prefs_.reset(prefs_->CreateIncognitoPrefService(
1046 CreateExtensionPrefStore(this, true)));
1048 return otr_prefs_.get();
1051 net::URLRequestContextGetter* ProfileImpl::CreateRequestContext(
1052 content::ProtocolHandlerMap* protocol_handlers,
1053 content::URLRequestInterceptorScopedVector request_interceptors) {
1054 return io_data_.CreateMainRequestContextGetter(
1055 protocol_handlers,
1056 request_interceptors.Pass(),
1057 g_browser_process->local_state(),
1058 g_browser_process->io_thread()).get();
1061 net::URLRequestContextGetter* ProfileImpl::GetRequestContext() {
1062 return GetDefaultStoragePartition(this)->GetURLRequestContext();
1065 net::URLRequestContextGetter* ProfileImpl::GetRequestContextForRenderProcess(
1066 int renderer_child_id) {
1067 content::RenderProcessHost* rph = content::RenderProcessHost::FromID(
1068 renderer_child_id);
1070 return rph->GetStoragePartition()->GetURLRequestContext();
1073 net::URLRequestContextGetter* ProfileImpl::GetMediaRequestContext() {
1074 // Return the default media context.
1075 return io_data_.GetMediaRequestContextGetter().get();
1078 net::URLRequestContextGetter*
1079 ProfileImpl::GetMediaRequestContextForRenderProcess(
1080 int renderer_child_id) {
1081 content::RenderProcessHost* rph = content::RenderProcessHost::FromID(
1082 renderer_child_id);
1083 content::StoragePartition* storage_partition = rph->GetStoragePartition();
1085 return storage_partition->GetMediaURLRequestContext();
1088 net::URLRequestContextGetter*
1089 ProfileImpl::GetMediaRequestContextForStoragePartition(
1090 const base::FilePath& partition_path,
1091 bool in_memory) {
1092 return io_data_
1093 .GetIsolatedMediaRequestContextGetter(partition_path, in_memory).get();
1096 content::ResourceContext* ProfileImpl::GetResourceContext() {
1097 return io_data_.GetResourceContext();
1100 net::URLRequestContextGetter* ProfileImpl::GetRequestContextForExtensions() {
1101 return io_data_.GetExtensionsRequestContextGetter().get();
1104 net::URLRequestContextGetter*
1105 ProfileImpl::CreateRequestContextForStoragePartition(
1106 const base::FilePath& partition_path,
1107 bool in_memory,
1108 content::ProtocolHandlerMap* protocol_handlers,
1109 content::URLRequestInterceptorScopedVector request_interceptors) {
1110 return io_data_.CreateIsolatedAppRequestContextGetter(
1111 partition_path,
1112 in_memory,
1113 protocol_handlers,
1114 request_interceptors.Pass()).get();
1117 net::SSLConfigService* ProfileImpl::GetSSLConfigService() {
1118 // If ssl_config_service_manager_ is null, this typically means that some
1119 // KeyedService is trying to create a RequestContext at startup,
1120 // but SSLConfigServiceManager is not initialized until DoFinalInit() which is
1121 // invoked after all KeyedServices have been initialized (see
1122 // http://crbug.com/171406).
1123 DCHECK(ssl_config_service_manager_) <<
1124 "SSLConfigServiceManager is not initialized yet";
1125 return ssl_config_service_manager_->Get();
1128 HostContentSettingsMap* ProfileImpl::GetHostContentSettingsMap() {
1129 if (!host_content_settings_map_.get()) {
1130 host_content_settings_map_ = new HostContentSettingsMap(GetPrefs(), false);
1132 return host_content_settings_map_.get();
1135 content::BrowserPluginGuestManager* ProfileImpl::GetGuestManager() {
1136 #if defined(ENABLE_EXTENSIONS)
1137 return extensions::GuestViewManager::FromBrowserContext(this);
1138 #else
1139 return NULL;
1140 #endif
1143 DownloadManagerDelegate* ProfileImpl::GetDownloadManagerDelegate() {
1144 return DownloadServiceFactory::GetForBrowserContext(this)->
1145 GetDownloadManagerDelegate();
1148 storage::SpecialStoragePolicy* ProfileImpl::GetSpecialStoragePolicy() {
1149 #if defined(ENABLE_EXTENSIONS)
1150 return GetExtensionSpecialStoragePolicy();
1151 #else
1152 return NULL;
1153 #endif
1156 content::PushMessagingService* ProfileImpl::GetPushMessagingService() {
1157 return gcm::GCMProfileServiceFactory::GetForProfile(
1158 this)->push_messaging_service();
1161 content::SSLHostStateDelegate* ProfileImpl::GetSSLHostStateDelegate() {
1162 return ChromeSSLHostStateDelegateFactory::GetForProfile(this);
1165 bool ProfileImpl::IsSameProfile(Profile* profile) {
1166 if (profile == static_cast<Profile*>(this))
1167 return true;
1168 Profile* otr_profile = off_the_record_profile_.get();
1169 return otr_profile && profile == otr_profile;
1172 Time ProfileImpl::GetStartTime() const {
1173 return start_time_;
1176 history::TopSites* ProfileImpl::GetTopSites() {
1177 if (!top_sites_.get()) {
1178 top_sites_ = history::TopSites::Create(
1179 this, GetPath().Append(chrome::kTopSitesFilename));
1181 return top_sites_.get();
1184 history::TopSites* ProfileImpl::GetTopSitesWithoutCreating() {
1185 return top_sites_.get();
1188 void ProfileImpl::OnDefaultZoomLevelChanged() {
1189 HostZoomMap::GetDefaultForBrowserContext(this)->SetDefaultZoomLevel(
1190 pref_change_registrar_.prefs()->GetDouble(prefs::kDefaultZoomLevel));
1193 void ProfileImpl::OnZoomLevelChanged(
1194 const HostZoomMap::ZoomLevelChange& change) {
1196 if (change.mode != HostZoomMap::ZOOM_CHANGED_FOR_HOST)
1197 return;
1198 HostZoomMap* host_zoom_map = HostZoomMap::GetDefaultForBrowserContext(this);
1199 double level = change.zoom_level;
1200 DictionaryPrefUpdate update(prefs_.get(), prefs::kPerHostZoomLevels);
1201 base::DictionaryValue* host_zoom_dictionary = update.Get();
1202 if (content::ZoomValuesEqual(level, host_zoom_map->GetDefaultZoomLevel()))
1203 host_zoom_dictionary->RemoveWithoutPathExpansion(change.host, NULL);
1204 else
1205 host_zoom_dictionary->SetDoubleWithoutPathExpansion(change.host, level);
1208 #if defined(ENABLE_SESSION_SERVICE)
1209 void ProfileImpl::StopCreateSessionServiceTimer() {
1210 create_session_service_timer_.Stop();
1213 void ProfileImpl::EnsureSessionServiceCreated() {
1214 SessionServiceFactory::GetForProfile(this);
1216 #endif
1218 #if defined(OS_CHROMEOS)
1219 void ProfileImpl::ChangeAppLocale(
1220 const std::string& new_locale, AppLocaleChangedVia via) {
1221 if (new_locale.empty()) {
1222 NOTREACHED();
1223 return;
1225 PrefService* local_state = g_browser_process->local_state();
1226 DCHECK(local_state);
1227 if (local_state->IsManagedPreference(prefs::kApplicationLocale))
1228 return;
1229 std::string pref_locale = GetPrefs()->GetString(prefs::kApplicationLocale);
1230 bool do_update_pref = true;
1231 switch (via) {
1232 case APP_LOCALE_CHANGED_VIA_SETTINGS:
1233 case APP_LOCALE_CHANGED_VIA_REVERT: {
1234 // We keep kApplicationLocaleBackup value as a reference. In case value
1235 // of kApplicationLocale preference would change due to sync from other
1236 // device then kApplicationLocaleBackup value will trigger and allow us to
1237 // show notification about automatic locale change in LocaleChangeGuard.
1238 GetPrefs()->SetString(prefs::kApplicationLocaleBackup, new_locale);
1239 GetPrefs()->ClearPref(prefs::kApplicationLocaleAccepted);
1240 // We maintain kApplicationLocale property in both a global storage
1241 // and user's profile. Global property determines locale of login screen,
1242 // while user's profile determines his personal locale preference.
1243 break;
1245 case APP_LOCALE_CHANGED_VIA_LOGIN:
1246 case APP_LOCALE_CHANGED_VIA_PUBLIC_SESSION_LOGIN: {
1247 if (!pref_locale.empty()) {
1248 DCHECK(pref_locale == new_locale);
1249 std::string accepted_locale =
1250 GetPrefs()->GetString(prefs::kApplicationLocaleAccepted);
1251 if (accepted_locale == new_locale) {
1252 // If locale is accepted then we do not want to show LocaleChange
1253 // notification. This notification is triggered by different values
1254 // of kApplicationLocaleBackup and kApplicationLocale preferences,
1255 // so make them identical.
1256 GetPrefs()->SetString(prefs::kApplicationLocaleBackup, new_locale);
1257 } else {
1258 // Back up locale of login screen.
1259 std::string cur_locale = g_browser_process->GetApplicationLocale();
1260 GetPrefs()->SetString(prefs::kApplicationLocaleBackup, cur_locale);
1261 if (locale_change_guard_ == NULL)
1262 locale_change_guard_.reset(new chromeos::LocaleChangeGuard(this));
1263 locale_change_guard_->PrepareChangingLocale(cur_locale, new_locale);
1265 } else {
1266 std::string cur_locale = g_browser_process->GetApplicationLocale();
1267 std::string backup_locale =
1268 GetPrefs()->GetString(prefs::kApplicationLocaleBackup);
1269 // Profile synchronization takes time and is not completed at that
1270 // moment at first login. So we initialize locale preference in steps:
1271 // (1) first save it to temporary backup;
1272 // (2) on next login we assume that synchronization is already completed
1273 // and we may finalize initialization.
1274 GetPrefs()->SetString(prefs::kApplicationLocaleBackup, cur_locale);
1275 if (!new_locale.empty())
1276 GetPrefs()->SetString(prefs::kApplicationLocale, new_locale);
1277 else if (!backup_locale.empty())
1278 GetPrefs()->SetString(prefs::kApplicationLocale, backup_locale);
1279 do_update_pref = false;
1281 break;
1283 case APP_LOCALE_CHANGED_VIA_UNKNOWN:
1284 default: {
1285 NOTREACHED();
1286 break;
1289 if (do_update_pref)
1290 GetPrefs()->SetString(prefs::kApplicationLocale, new_locale);
1291 if (via != APP_LOCALE_CHANGED_VIA_PUBLIC_SESSION_LOGIN)
1292 local_state->SetString(prefs::kApplicationLocale, new_locale);
1294 if (user_manager::UserManager::Get()->GetOwnerEmail() ==
1295 chromeos::ProfileHelper::Get()->GetUserByProfile(this)->email())
1296 local_state->SetString(prefs::kOwnerLocale, new_locale);
1299 void ProfileImpl::OnLogin() {
1300 if (locale_change_guard_ == NULL)
1301 locale_change_guard_.reset(new chromeos::LocaleChangeGuard(this));
1302 locale_change_guard_->OnLogin();
1305 void ProfileImpl::InitChromeOSPreferences() {
1306 chromeos_preferences_.reset(new chromeos::Preferences());
1307 chromeos_preferences_->Init(
1308 this, chromeos::ProfileHelper::Get()->GetUserByProfile(this));
1311 #endif // defined(OS_CHROMEOS)
1313 PrefProxyConfigTracker* ProfileImpl::GetProxyConfigTracker() {
1314 if (!pref_proxy_config_tracker_)
1315 pref_proxy_config_tracker_.reset(CreateProxyConfigTracker());
1316 return pref_proxy_config_tracker_.get();
1319 chrome_browser_net::Predictor* ProfileImpl::GetNetworkPredictor() {
1320 return predictor_;
1323 DevToolsNetworkController* ProfileImpl::GetDevToolsNetworkController() {
1324 return io_data_.GetDevToolsNetworkController();
1327 void ProfileImpl::ClearNetworkingHistorySince(
1328 base::Time time,
1329 const base::Closure& completion) {
1330 io_data_.ClearNetworkingHistorySince(time, completion);
1333 GURL ProfileImpl::GetHomePage() {
1334 // --homepage overrides any preferences.
1335 const CommandLine& command_line = *CommandLine::ForCurrentProcess();
1336 if (command_line.HasSwitch(switches::kHomePage)) {
1337 // TODO(evanm): clean up usage of DIR_CURRENT.
1338 // http://code.google.com/p/chromium/issues/detail?id=60630
1339 // For now, allow this code to call getcwd().
1340 base::ThreadRestrictions::ScopedAllowIO allow_io;
1342 base::FilePath browser_directory;
1343 PathService::Get(base::DIR_CURRENT, &browser_directory);
1344 GURL home_page(url_fixer::FixupRelativeFile(
1345 browser_directory,
1346 command_line.GetSwitchValuePath(switches::kHomePage)));
1347 if (home_page.is_valid())
1348 return home_page;
1351 if (GetPrefs()->GetBoolean(prefs::kHomePageIsNewTabPage))
1352 return GURL(chrome::kChromeUINewTabURL);
1353 GURL home_page(url_fixer::FixupURL(GetPrefs()->GetString(prefs::kHomePage),
1354 std::string()));
1355 if (!home_page.is_valid())
1356 return GURL(chrome::kChromeUINewTabURL);
1357 return home_page;
1360 void ProfileImpl::UpdateProfileUserNameCache() {
1361 ProfileManager* profile_manager = g_browser_process->profile_manager();
1362 ProfileInfoCache& cache = profile_manager->GetProfileInfoCache();
1363 size_t index = cache.GetIndexOfProfileWithPath(GetPath());
1364 if (index != std::string::npos) {
1365 std::string user_name =
1366 GetPrefs()->GetString(prefs::kGoogleServicesUsername);
1367 cache.SetUserNameOfProfileAtIndex(index, base::UTF8ToUTF16(user_name));
1368 ProfileMetrics::UpdateReportedProfilesStatistics(profile_manager);
1372 void ProfileImpl::UpdateProfileSupervisedUserIdCache() {
1373 ProfileManager* profile_manager = g_browser_process->profile_manager();
1374 ProfileInfoCache& cache = profile_manager->GetProfileInfoCache();
1375 size_t index = cache.GetIndexOfProfileWithPath(GetPath());
1376 if (index != std::string::npos) {
1377 std::string supervised_user_id =
1378 GetPrefs()->GetString(prefs::kSupervisedUserId);
1379 cache.SetSupervisedUserIdOfProfileAtIndex(index, supervised_user_id);
1380 ProfileMetrics::UpdateReportedProfilesStatistics(profile_manager);
1384 void ProfileImpl::UpdateProfileNameCache() {
1385 ProfileManager* profile_manager = g_browser_process->profile_manager();
1386 ProfileInfoCache& cache = profile_manager->GetProfileInfoCache();
1387 size_t index = cache.GetIndexOfProfileWithPath(GetPath());
1388 if (index != std::string::npos) {
1389 std::string profile_name =
1390 GetPrefs()->GetString(prefs::kProfileName);
1391 cache.SetNameOfProfileAtIndex(index, base::UTF8ToUTF16(profile_name));
1392 bool default_name =
1393 GetPrefs()->GetBoolean(prefs::kProfileUsingDefaultName);
1394 cache.SetProfileIsUsingDefaultNameAtIndex(index, default_name);
1398 void ProfileImpl::UpdateProfileAvatarCache() {
1399 ProfileManager* profile_manager = g_browser_process->profile_manager();
1400 ProfileInfoCache& cache = profile_manager->GetProfileInfoCache();
1401 size_t index = cache.GetIndexOfProfileWithPath(GetPath());
1402 if (index != std::string::npos) {
1403 size_t avatar_index =
1404 GetPrefs()->GetInteger(prefs::kProfileAvatarIndex);
1405 cache.SetAvatarIconOfProfileAtIndex(index, avatar_index);
1406 bool default_avatar =
1407 GetPrefs()->GetBoolean(prefs::kProfileUsingDefaultAvatar);
1408 cache.SetProfileIsUsingDefaultAvatarAtIndex(index, default_avatar);
1409 bool gaia_avatar =
1410 GetPrefs()->GetBoolean(prefs::kProfileUsingGAIAAvatar);
1411 cache.SetIsUsingGAIAPictureOfProfileAtIndex(index, gaia_avatar);
1415 void ProfileImpl::UpdateProfileIsEphemeralCache() {
1416 ProfileManager* profile_manager = g_browser_process->profile_manager();
1417 ProfileInfoCache& cache = profile_manager->GetProfileInfoCache();
1418 size_t index = cache.GetIndexOfProfileWithPath(GetPath());
1419 if (index != std::string::npos) {
1420 bool is_ephemeral = GetPrefs()->GetBoolean(prefs::kForceEphemeralProfiles);
1421 cache.SetProfileIsEphemeralAtIndex(index, is_ephemeral);
1425 // Gets the cache parameters from the command line. If |is_media_context| is
1426 // set to true then settings for the media context type is what we need,
1427 // |cache_path| will be set to the user provided path, or will not be touched if
1428 // there is not an argument. |max_size| will be the user provided value or zero
1429 // by default.
1430 void ProfileImpl::GetCacheParameters(bool is_media_context,
1431 base::FilePath* cache_path,
1432 int* max_size) {
1433 DCHECK(cache_path);
1434 DCHECK(max_size);
1435 base::FilePath path(prefs_->GetFilePath(prefs::kDiskCacheDir));
1436 if (!path.empty())
1437 *cache_path = path;
1438 *max_size = is_media_context ? prefs_->GetInteger(prefs::kMediaCacheSize) :
1439 prefs_->GetInteger(prefs::kDiskCacheSize);
1442 PrefProxyConfigTracker* ProfileImpl::CreateProxyConfigTracker() {
1443 #if defined(OS_CHROMEOS)
1444 if (chromeos::ProfileHelper::IsSigninProfile(this)) {
1445 return ProxyServiceFactory::CreatePrefProxyConfigTrackerOfLocalState(
1446 g_browser_process->local_state());
1448 #endif // defined(OS_CHROMEOS)
1449 return ProxyServiceFactory::CreatePrefProxyConfigTrackerOfProfile(
1450 GetPrefs(), g_browser_process->local_state());
1453 scoped_ptr<domain_reliability::DomainReliabilityMonitor>
1454 ProfileImpl::CreateDomainReliabilityMonitor(PrefService* local_state) {
1455 domain_reliability::DomainReliabilityService* service =
1456 domain_reliability::DomainReliabilityServiceFactory::GetInstance()->
1457 GetForBrowserContext(this);
1458 if (!service)
1459 return scoped_ptr<domain_reliability::DomainReliabilityMonitor>();
1461 return service->CreateMonitor(
1462 BrowserThread::GetMessageLoopProxyForThread(BrowserThread::IO),
1463 local_state,
1464 prefs::kMetricsReportingEnabled);