GoogleURLTrackerInfoBarDelegate: Initialize uninitialized member in constructor.
[chromium-blink-merge.git] / chrome / browser / profiles / profile_impl.cc
blob069c314d9eca0f93a22328d3e513dddf6cfc5afb
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/file_util.h"
16 #include "base/files/file_path.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/download/chrome_download_manager_delegate.h"
40 #include "chrome/browser/download/download_service.h"
41 #include "chrome/browser/download/download_service_factory.h"
42 #include "chrome/browser/extensions/extension_service.h"
43 #include "chrome/browser/extensions/extension_special_storage_policy.h"
44 #include "chrome/browser/geolocation/chrome_geolocation_permission_context.h"
45 #include "chrome/browser/geolocation/chrome_geolocation_permission_context_factory.h"
46 #include "chrome/browser/guest_view/guest_view_manager.h"
47 #include "chrome/browser/history/top_sites.h"
48 #include "chrome/browser/media/chrome_midi_permission_context.h"
49 #include "chrome/browser/media/chrome_midi_permission_context_factory.h"
50 #include "chrome/browser/metrics/metrics_service.h"
51 #include "chrome/browser/net/chrome_url_request_context.h"
52 #include "chrome/browser/net/net_pref_observer.h"
53 #include "chrome/browser/net/predictor.h"
54 #include "chrome/browser/net/pref_proxy_config_tracker.h"
55 #include "chrome/browser/net/proxy_service_factory.h"
56 #include "chrome/browser/net/ssl_config_service_manager.h"
57 #include "chrome/browser/plugins/chrome_plugin_service_filter.h"
58 #include "chrome/browser/plugins/plugin_prefs.h"
59 #include "chrome/browser/policy/profile_policy_connector.h"
60 #include "chrome/browser/policy/profile_policy_connector_factory.h"
61 #include "chrome/browser/prefs/browser_prefs.h"
62 #include "chrome/browser/prefs/chrome_pref_service_factory.h"
63 #include "chrome/browser/prefs/pref_service_syncable.h"
64 #include "chrome/browser/prefs/tracked/tracked_preference_validation_delegate.h"
65 #include "chrome/browser/prerender/prerender_manager_factory.h"
66 #include "chrome/browser/profiles/bookmark_model_loaded_observer.h"
67 #include "chrome/browser/profiles/chrome_version_service.h"
68 #include "chrome/browser/profiles/gaia_info_update_service_factory.h"
69 #include "chrome/browser/profiles/profile_destroyer.h"
70 #include "chrome/browser/profiles/profile_info_cache.h"
71 #include "chrome/browser/profiles/profile_manager.h"
72 #include "chrome/browser/profiles/profile_metrics.h"
73 #include "chrome/browser/search_engines/template_url_fetcher.h"
74 #include "chrome/browser/sessions/session_service_factory.h"
75 #include "chrome/browser/ui/startup/startup_browser_creator.h"
76 #include "chrome/browser/ui/webui/extensions/extension_icon_source.h"
77 #include "chrome/browser/webdata/web_data_service.h"
78 #include "chrome/common/chrome_constants.h"
79 #include "chrome/common/chrome_paths_internal.h"
80 #include "chrome/common/chrome_switches.h"
81 #include "chrome/common/chrome_version_info.h"
82 #include "chrome/common/net/url_fixer_upper.h"
83 #include "chrome/common/pref_names.h"
84 #include "chrome/common/url_constants.h"
85 #include "components/bookmarks/browser/bookmark_model.h"
86 #include "components/dom_distiller/content/dom_distiller_viewer_source.h"
87 #include "components/keyed_service/content/browser_context_dependency_manager.h"
88 #include "components/pref_registry/pref_registry_syncable.h"
89 #include "components/startup_metric_utils/startup_metric_utils.h"
90 #include "components/user_prefs/user_prefs.h"
91 #include "content/public/browser/browser_thread.h"
92 #include "content/public/browser/dom_storage_context.h"
93 #include "content/public/browser/host_zoom_map.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 "extensions/browser/extension_pref_store.h"
102 #include "extensions/browser/extension_pref_value_map.h"
103 #include "extensions/browser/extension_pref_value_map_factory.h"
104 #include "extensions/browser/extension_system.h"
105 #include "grit/chromium_strings.h"
106 #include "grit/generated_resources.h"
107 #include "ui/base/l10n/l10n_util.h"
109 #if defined(OS_ANDROID)
110 #include "chrome/browser/media/protected_media_identifier_permission_context.h"
111 #include "chrome/browser/media/protected_media_identifier_permission_context_factory.h"
112 #endif // defined(OS_ANDROID)
114 #if defined(ENABLE_CONFIGURATION_POLICY)
115 #include "chrome/browser/policy/schema_registry_service.h"
116 #include "chrome/browser/policy/schema_registry_service_factory.h"
117 #include "components/policy/core/browser/browser_policy_connector.h"
118 #if defined(OS_CHROMEOS)
119 #include "chrome/browser/chromeos/policy/user_cloud_policy_manager_chromeos.h"
120 #include "chrome/browser/chromeos/policy/user_cloud_policy_manager_factory_chromeos.h"
121 #else
122 #include "chrome/browser/policy/cloud/user_cloud_policy_manager_factory.h"
123 #include "components/policy/core/common/cloud/user_cloud_policy_manager.h"
124 #endif
125 #endif
127 #if defined(ENABLE_MANAGED_USERS)
128 #include "chrome/browser/managed_mode/managed_user_settings_service.h"
129 #include "chrome/browser/managed_mode/managed_user_settings_service_factory.h"
130 #endif
132 #if defined(OS_CHROMEOS)
133 #include "chrome/browser/chromeos/locale_change_guard.h"
134 #include "chrome/browser/chromeos/login/users/user_manager.h"
135 #include "chrome/browser/chromeos/preferences.h"
136 #include "chrome/browser/chromeos/profiles/profile_helper.h"
137 #endif
139 using base::Time;
140 using base::TimeDelta;
141 using base::UserMetricsAction;
142 using content::BrowserThread;
143 using content::DownloadManagerDelegate;
144 using content::HostZoomMap;
146 namespace {
148 // Constrict us to a very specific platform and architecture to make sure
149 // ifdefs don't cause problems with the check.
150 #if defined(OS_LINUX) && defined(TOOLKIT_GTK) && defined(ARCH_CPU_X86_64) && \
151 !defined(_GLIBCXX_DEBUG)
152 // Make sure that the ProfileImpl doesn't grow. We're currently trying to drive
153 // the number of services that are included in ProfileImpl (instead of using
154 // BrowserContextKeyedServiceFactory) to zero.
156 // If you don't know about this effort, please read:
157 // https://sites.google.com/a/chromium.org/dev/developers/design-documents/profile-architecture
159 // REVIEWERS: Do not let anyone increment this. We need to drive the number of
160 // raw accessed services down to zero. DO NOT LET PEOPLE REGRESS THIS UNLESS
161 // THE PATCH ITSELF IS MAKING PROGRESS ON PKSF REFACTORING.
162 COMPILE_ASSERT(sizeof(ProfileImpl) <= 744u, profile_impl_size_unexpected);
163 #endif
165 #if defined(ENABLE_SESSION_SERVICE)
166 // Delay, in milliseconds, before we explicitly create the SessionService.
167 static const int kCreateSessionServiceDelayMS = 500;
168 #endif
170 // Text content of README file created in each profile directory. Both %s
171 // placeholders must contain the product name. This is not localizable and hence
172 // not in resources.
173 static const char kReadmeText[] =
174 "%s settings and storage represent user-selected preferences and "
175 "information and MUST not be extracted, overwritten or modified except "
176 "through %s defined APIs.";
178 // Value written to prefs for EXIT_CRASHED and EXIT_SESSION_ENDED.
179 const char* const kPrefExitTypeCrashed = "Crashed";
180 const char* const kPrefExitTypeSessionEnded = "SessionEnded";
182 // Helper method needed because PostTask cannot currently take a Callback
183 // function with non-void return type.
184 void CreateDirectoryAndSignal(const base::FilePath& path,
185 base::WaitableEvent* done_creating) {
186 DVLOG(1) << "Creating directory " << path.value();
187 base::CreateDirectory(path);
188 done_creating->Signal();
191 // Task that blocks the FILE thread until CreateDirectoryAndSignal() finishes on
192 // blocking I/O pool.
193 void BlockFileThreadOnDirectoryCreate(base::WaitableEvent* done_creating) {
194 done_creating->Wait();
197 // Initiates creation of profile directory on |sequenced_task_runner| and
198 // ensures that FILE thread is blocked until that operation finishes.
199 void CreateProfileDirectory(base::SequencedTaskRunner* sequenced_task_runner,
200 const base::FilePath& path) {
201 base::WaitableEvent* done_creating = new base::WaitableEvent(false, false);
202 sequenced_task_runner->PostTask(FROM_HERE,
203 base::Bind(&CreateDirectoryAndSignal,
204 path,
205 done_creating));
206 // Block the FILE thread until directory is created on I/O pool to make sure
207 // that we don't attempt any operation until that part completes.
208 BrowserThread::PostTask(
209 BrowserThread::FILE, FROM_HERE,
210 base::Bind(&BlockFileThreadOnDirectoryCreate,
211 base::Owned(done_creating)));
214 base::FilePath GetCachePath(const base::FilePath& base) {
215 return base.Append(chrome::kCacheDirname);
218 base::FilePath GetMediaCachePath(const base::FilePath& base) {
219 return base.Append(chrome::kMediaCacheDirname);
222 void EnsureReadmeFile(const base::FilePath& base) {
223 base::FilePath readme_path = base.Append(chrome::kReadmeFilename);
224 if (base::PathExists(readme_path))
225 return;
226 std::string product_name = l10n_util::GetStringUTF8(IDS_PRODUCT_NAME);
227 std::string readme_text = base::StringPrintf(
228 kReadmeText, product_name.c_str(), product_name.c_str());
229 if (base::WriteFile(readme_path, readme_text.data(), readme_text.size()) ==
230 -1) {
231 LOG(ERROR) << "Could not create README file.";
235 // Converts the kSessionExitedCleanly pref to the corresponding EXIT_TYPE.
236 Profile::ExitType SessionTypePrefValueToExitType(const std::string& value) {
237 if (value == kPrefExitTypeSessionEnded)
238 return Profile::EXIT_SESSION_ENDED;
239 if (value == kPrefExitTypeCrashed)
240 return Profile::EXIT_CRASHED;
241 return Profile::EXIT_NORMAL;
244 // Converts an ExitType into a string that is written to prefs.
245 std::string ExitTypeToSessionTypePrefValue(Profile::ExitType type) {
246 switch (type) {
247 case Profile::EXIT_NORMAL:
248 return ProfileImpl::kPrefExitTypeNormal;
249 case Profile::EXIT_SESSION_ENDED:
250 return kPrefExitTypeSessionEnded;
251 case Profile::EXIT_CRASHED:
252 return kPrefExitTypeCrashed;
254 NOTREACHED();
255 return std::string();
258 // Setup URLDataSource for the chrome-distiller:// scheme for the given
259 // |profile|.
260 void RegisterDomDistillerViewerSource(Profile* profile) {
261 const CommandLine& command_line = *CommandLine::ForCurrentProcess();
262 if (command_line.HasSwitch(switches::kEnableDomDistiller)) {
263 dom_distiller::DomDistillerServiceFactory* dom_distiller_service_factory =
264 dom_distiller::DomDistillerServiceFactory::GetInstance();
265 // The LazyDomDistillerService deletes itself when the profile is destroyed.
266 dom_distiller::LazyDomDistillerService* lazy_service =
267 new dom_distiller::LazyDomDistillerService(
268 profile, dom_distiller_service_factory);
269 content::URLDataSource::Add(profile,
270 new dom_distiller::DomDistillerViewerSource(
271 lazy_service, chrome::kDomDistillerScheme));
275 } // namespace
277 // static
278 Profile* Profile::CreateProfile(const base::FilePath& path,
279 Delegate* delegate,
280 CreateMode create_mode) {
281 TRACE_EVENT0("browser", "Profile::CreateProfile")
282 // Get sequenced task runner for making sure that file operations of
283 // this profile (defined by |path|) are executed in expected order
284 // (what was previously assured by the FILE thread).
285 scoped_refptr<base::SequencedTaskRunner> sequenced_task_runner =
286 JsonPrefStore::GetTaskRunnerForFile(path,
287 BrowserThread::GetBlockingPool());
288 if (create_mode == CREATE_MODE_ASYNCHRONOUS) {
289 DCHECK(delegate);
290 CreateProfileDirectory(sequenced_task_runner.get(), path);
291 } else if (create_mode == CREATE_MODE_SYNCHRONOUS) {
292 if (!base::PathExists(path)) {
293 // TODO(tc): http://b/1094718 Bad things happen if we can't write to the
294 // profile directory. We should eventually be able to run in this
295 // situation.
296 if (!base::CreateDirectory(path))
297 return NULL;
299 } else {
300 NOTREACHED();
303 return new ProfileImpl(
304 path, delegate, create_mode, sequenced_task_runner.get());
307 // static
308 int ProfileImpl::create_readme_delay_ms = 60000;
310 // static
311 const char* const ProfileImpl::kPrefExitTypeNormal = "Normal";
313 // static
314 void ProfileImpl::RegisterProfilePrefs(
315 user_prefs::PrefRegistrySyncable* registry) {
316 registry->RegisterBooleanPref(
317 prefs::kSavingBrowserHistoryDisabled,
318 false,
319 user_prefs::PrefRegistrySyncable::UNSYNCABLE_PREF);
320 registry->RegisterBooleanPref(
321 prefs::kAllowDeletingBrowserHistory,
322 true,
323 user_prefs::PrefRegistrySyncable::UNSYNCABLE_PREF);
324 registry->RegisterBooleanPref(
325 prefs::kSigninAllowed,
326 true,
327 user_prefs::PrefRegistrySyncable::UNSYNCABLE_PREF);
328 registry->RegisterBooleanPref(
329 prefs::kForceSafeSearch,
330 false,
331 user_prefs::PrefRegistrySyncable::UNSYNCABLE_PREF);
332 registry->RegisterIntegerPref(
333 prefs::kProfileAvatarIndex,
335 user_prefs::PrefRegistrySyncable::SYNCABLE_PREF);
336 registry->RegisterStringPref(prefs::kManagedUserId,
337 std::string(),
338 user_prefs::PrefRegistrySyncable::SYNCABLE_PREF);
339 registry->RegisterStringPref(prefs::kProfileName,
340 std::string(),
341 user_prefs::PrefRegistrySyncable::SYNCABLE_PREF);
342 registry->RegisterBooleanPref(
343 prefs::kProfileIsManaged,
344 false,
345 user_prefs::PrefRegistrySyncable::SYNCABLE_PREF);
346 registry->RegisterStringPref(prefs::kHomePage,
347 std::string(),
348 user_prefs::PrefRegistrySyncable::SYNCABLE_PREF);
349 #if defined(ENABLE_PRINTING)
350 registry->RegisterBooleanPref(
351 prefs::kPrintingEnabled,
352 true,
353 user_prefs::PrefRegistrySyncable::UNSYNCABLE_PREF);
354 #endif
355 registry->RegisterBooleanPref(
356 prefs::kPrintPreviewDisabled,
357 false,
358 user_prefs::PrefRegistrySyncable::UNSYNCABLE_PREF);
359 registry->RegisterBooleanPref(
360 prefs::kForceEphemeralProfiles,
361 false,
362 user_prefs::PrefRegistrySyncable::UNSYNCABLE_PREF);
364 // Initialize the cache prefs.
365 registry->RegisterFilePathPref(
366 prefs::kDiskCacheDir,
367 base::FilePath(),
368 user_prefs::PrefRegistrySyncable::UNSYNCABLE_PREF);
369 registry->RegisterIntegerPref(
370 prefs::kDiskCacheSize,
372 user_prefs::PrefRegistrySyncable::UNSYNCABLE_PREF);
373 registry->RegisterIntegerPref(
374 prefs::kMediaCacheSize,
376 user_prefs::PrefRegistrySyncable::UNSYNCABLE_PREF);
378 // Deprecated. Kept around for migration.
379 registry->RegisterBooleanPref(
380 prefs::kClearSiteDataOnExit,
381 false,
382 user_prefs::PrefRegistrySyncable::SYNCABLE_PREF);
385 ProfileImpl::ProfileImpl(
386 const base::FilePath& path,
387 Delegate* delegate,
388 CreateMode create_mode,
389 base::SequencedTaskRunner* sequenced_task_runner)
390 : path_(path),
391 pref_registry_(new user_prefs::PrefRegistrySyncable),
392 io_data_(this),
393 host_content_settings_map_(NULL),
394 last_session_exit_type_(EXIT_NORMAL),
395 start_time_(Time::Now()),
396 delegate_(delegate),
397 predictor_(NULL) {
398 TRACE_EVENT0("browser", "ProfileImpl::ctor")
399 DCHECK(!path.empty()) << "Using an empty path will attempt to write " <<
400 "profile files to the root directory!";
402 #if defined(ENABLE_SESSION_SERVICE)
403 create_session_service_timer_.Start(FROM_HERE,
404 TimeDelta::FromMilliseconds(kCreateSessionServiceDelayMS), this,
405 &ProfileImpl::EnsureSessionServiceCreated);
406 #endif
408 // Determine if prefetch is enabled for this profile.
409 // If not profile_manager is present, it means we are in a unittest.
410 const CommandLine* command_line = CommandLine::ForCurrentProcess();
411 predictor_ = chrome_browser_net::Predictor::CreatePredictor(
412 !command_line->HasSwitch(switches::kDisablePreconnect),
413 g_browser_process->profile_manager() == NULL);
415 // If we are creating the profile synchronously, then we should load the
416 // policy data immediately.
417 bool force_immediate_policy_load = (create_mode == CREATE_MODE_SYNCHRONOUS);
418 #if defined(ENABLE_CONFIGURATION_POLICY)
419 policy::BrowserPolicyConnector* connector =
420 g_browser_process->browser_policy_connector();
421 schema_registry_service_ =
422 policy::SchemaRegistryServiceFactory::CreateForContext(
423 this, connector->GetChromeSchema(), connector->GetSchemaRegistry());
424 #if defined(OS_CHROMEOS)
425 cloud_policy_manager_ =
426 policy::UserCloudPolicyManagerFactoryChromeOS::CreateForProfile(
427 this, force_immediate_policy_load, sequenced_task_runner);
428 #else
429 cloud_policy_manager_ =
430 policy::UserCloudPolicyManagerFactory::CreateForOriginalBrowserContext(
431 this,
432 force_immediate_policy_load,
433 sequenced_task_runner,
434 BrowserThread::GetMessageLoopProxyForThread(BrowserThread::FILE),
435 BrowserThread::GetMessageLoopProxyForThread(BrowserThread::IO));
436 #endif
437 #endif
438 profile_policy_connector_ =
439 policy::ProfilePolicyConnectorFactory::CreateForProfile(
440 this, force_immediate_policy_load);
442 DCHECK(create_mode == CREATE_MODE_ASYNCHRONOUS ||
443 create_mode == CREATE_MODE_SYNCHRONOUS);
444 bool async_prefs = create_mode == CREATE_MODE_ASYNCHRONOUS;
446 #if defined(OS_CHROMEOS)
447 if (chromeos::ProfileHelper::IsSigninProfile(this))
448 chrome::RegisterLoginProfilePrefs(pref_registry_.get());
449 else
450 #endif
451 chrome::RegisterUserProfilePrefs(pref_registry_.get());
453 BrowserContextDependencyManager::GetInstance()->
454 RegisterProfilePrefsForServices(this, pref_registry_.get());
456 ManagedUserSettingsService* managed_user_settings = NULL;
457 #if defined(ENABLE_MANAGED_USERS)
458 managed_user_settings =
459 ManagedUserSettingsServiceFactory::GetForProfile(this);
460 managed_user_settings->Init(
461 path_, sequenced_task_runner, create_mode == CREATE_MODE_SYNCHRONOUS);
462 #endif
464 // TODO(grt): construct pref_validation_delegate_.
466 // On startup, preference loading is always synchronous so a scoped timer
467 // will work here.
468 startup_metric_utils::ScopedSlowStartupUMA
469 scoped_timer("Startup.SlowStartupPreferenceLoading");
470 prefs_ = chrome_prefs::CreateProfilePrefs(
471 path_,
472 sequenced_task_runner,
473 pref_validation_delegate_.get(),
474 profile_policy_connector_->policy_service(),
475 managed_user_settings,
476 new ExtensionPrefStore(
477 ExtensionPrefValueMapFactory::GetForBrowserContext(this), false),
478 pref_registry_,
479 async_prefs).Pass();
480 // Register on BrowserContext.
481 user_prefs::UserPrefs::Set(this, prefs_.get());
484 startup_metric_utils::ScopedSlowStartupUMA
485 scoped_timer("Startup.SlowStartupFinalProfileInit");
486 if (async_prefs) {
487 // Wait for the notification that prefs has been loaded
488 // (successfully or not). Note that we can use base::Unretained
489 // because the PrefService is owned by this class and lives on
490 // the same thread.
491 prefs_->AddPrefInitObserver(base::Bind(&ProfileImpl::OnPrefsLoaded,
492 base::Unretained(this)));
493 } else {
494 // Prefs were loaded synchronously so we can continue directly.
495 OnPrefsLoaded(true);
499 void ProfileImpl::DoFinalInit() {
500 TRACE_EVENT0("browser", "ProfileImpl::DoFinalInit")
501 PrefService* prefs = GetPrefs();
502 pref_change_registrar_.Init(prefs);
503 pref_change_registrar_.Add(
504 prefs::kGoogleServicesUsername,
505 base::Bind(&ProfileImpl::UpdateProfileUserNameCache,
506 base::Unretained(this)));
507 pref_change_registrar_.Add(
508 prefs::kManagedUserId,
509 base::Bind(&ProfileImpl::UpdateProfileManagedUserIdCache,
510 base::Unretained(this)));
511 pref_change_registrar_.Add(
512 prefs::kDefaultZoomLevel,
513 base::Bind(&ProfileImpl::OnDefaultZoomLevelChanged,
514 base::Unretained(this)));
515 pref_change_registrar_.Add(
516 prefs::kProfileAvatarIndex,
517 base::Bind(&ProfileImpl::UpdateProfileAvatarCache,
518 base::Unretained(this)));
519 pref_change_registrar_.Add(
520 prefs::kProfileName,
521 base::Bind(&ProfileImpl::UpdateProfileNameCache,
522 base::Unretained(this)));
523 pref_change_registrar_.Add(
524 prefs::kForceEphemeralProfiles,
525 base::Bind(&ProfileImpl::UpdateProfileIsEphemeralCache,
526 base::Unretained(this)));
528 // It would be nice to use PathService for fetching this directory, but
529 // the cache directory depends on the profile directory, which isn't available
530 // to PathService.
531 chrome::GetUserCacheDirectory(path_, &base_cache_path_);
532 // Always create the cache directory asynchronously.
533 scoped_refptr<base::SequencedTaskRunner> sequenced_task_runner =
534 JsonPrefStore::GetTaskRunnerForFile(base_cache_path_,
535 BrowserThread::GetBlockingPool());
536 CreateProfileDirectory(sequenced_task_runner.get(), base_cache_path_);
538 // Now that the profile is hooked up to receive pref change notifications to
539 // kGoogleServicesUsername, initialize components that depend on it to reflect
540 // the current value.
541 UpdateProfileUserNameCache();
542 UpdateProfileManagedUserIdCache();
543 UpdateProfileIsEphemeralCache();
544 GAIAInfoUpdateServiceFactory::GetForProfile(this);
546 PrefService* local_state = g_browser_process->local_state();
547 ssl_config_service_manager_.reset(
548 SSLConfigServiceManager::CreateDefaultManager(local_state));
550 // Initialize the BackgroundModeManager - this has to be done here before
551 // InitExtensions() is called because it relies on receiving notifications
552 // when extensions are loaded. BackgroundModeManager is not needed under
553 // ChromeOS because Chrome is always running, no need for special keep-alive
554 // or launch-on-startup support unless kKeepAliveForTest is set.
555 bool init_background_mode_manager = true;
556 #if defined(OS_CHROMEOS)
557 if (!CommandLine::ForCurrentProcess()->HasSwitch(switches::kKeepAliveForTest))
558 init_background_mode_manager = false;
559 #endif
560 if (init_background_mode_manager) {
561 if (g_browser_process->background_mode_manager())
562 g_browser_process->background_mode_manager()->RegisterProfile(this);
565 base::FilePath cookie_path = GetPath();
566 cookie_path = cookie_path.Append(chrome::kCookieFilename);
567 base::FilePath server_bound_cert_path = GetPath();
568 server_bound_cert_path =
569 server_bound_cert_path.Append(chrome::kOBCertFilename);
570 base::FilePath cache_path = base_cache_path_;
571 int cache_max_size;
572 GetCacheParameters(false, &cache_path, &cache_max_size);
573 cache_path = GetCachePath(cache_path);
575 base::FilePath media_cache_path = base_cache_path_;
576 int media_cache_max_size;
577 GetCacheParameters(true, &media_cache_path, &media_cache_max_size);
578 media_cache_path = GetMediaCachePath(media_cache_path);
580 base::FilePath extensions_cookie_path = GetPath();
581 extensions_cookie_path =
582 extensions_cookie_path.Append(chrome::kExtensionsCookieFilename);
584 base::FilePath infinite_cache_path = GetPath();
585 infinite_cache_path =
586 infinite_cache_path.Append(FILE_PATH_LITERAL("Infinite Cache"));
588 #if defined(OS_ANDROID)
589 SessionStartupPref::Type startup_pref_type =
590 SessionStartupPref::GetDefaultStartupType();
591 #else
592 SessionStartupPref::Type startup_pref_type =
593 StartupBrowserCreator::GetSessionStartupPref(
594 *CommandLine::ForCurrentProcess(), this).type;
595 #endif
596 content::CookieStoreConfig::SessionCookieMode session_cookie_mode =
597 content::CookieStoreConfig::PERSISTANT_SESSION_COOKIES;
598 if (GetLastSessionExitType() == Profile::EXIT_CRASHED ||
599 startup_pref_type == SessionStartupPref::LAST) {
600 session_cookie_mode = content::CookieStoreConfig::RESTORED_SESSION_COOKIES;
603 InitHostZoomMap();
605 // Make sure we initialize the ProfileIOData after everything else has been
606 // initialized that we might be reading from the IO thread.
608 io_data_.Init(cookie_path, server_bound_cert_path, cache_path,
609 cache_max_size, media_cache_path, media_cache_max_size,
610 extensions_cookie_path, GetPath(), infinite_cache_path,
611 predictor_,
612 session_cookie_mode,
613 GetSpecialStoragePolicy());
615 #if defined(ENABLE_PLUGINS)
616 ChromePluginServiceFilter::GetInstance()->RegisterResourceContext(
617 PluginPrefs::GetForProfile(this).get(),
618 io_data_.GetResourceContextNoInit());
619 #endif
621 // Delay README creation to not impact startup performance.
622 BrowserThread::PostDelayedTask(
623 BrowserThread::FILE, FROM_HERE,
624 base::Bind(&EnsureReadmeFile, GetPath()),
625 base::TimeDelta::FromMilliseconds(create_readme_delay_ms));
627 TRACE_EVENT0("browser", "ProfileImpl::SetSaveSessionStorageOnDisk");
628 content::BrowserContext::GetDefaultStoragePartition(this)->
629 GetDOMStorageContext()->SetSaveSessionStorageOnDisk();
631 // The DomDistillerViewerSource is not a normal WebUI so it must be registered
632 // as a URLDataSource early.
633 RegisterDomDistillerViewerSource(this);
635 // Creation has been finished.
636 if (delegate_) {
637 TRACE_EVENT0("browser", "ProfileImpl::DoFileInit:DelegateOnProfileCreated")
638 delegate_->OnProfileCreated(this, true, IsNewProfile());
641 content::NotificationService::current()->Notify(
642 chrome::NOTIFICATION_PROFILE_CREATED,
643 content::Source<Profile>(this),
644 content::NotificationService::NoDetails());
646 #if !defined(OS_CHROMEOS)
647 // Listen for bookmark model load, to bootstrap the sync service.
648 // On CrOS sync service will be initialized after sign in.
649 BookmarkModel* model = BookmarkModelFactory::GetForProfile(this);
650 model->AddObserver(new BookmarkModelLoadedObserver(this));
651 #endif
654 void ProfileImpl::InitHostZoomMap() {
655 HostZoomMap* host_zoom_map = HostZoomMap::GetForBrowserContext(this);
656 host_zoom_map->SetDefaultZoomLevel(
657 prefs_->GetDouble(prefs::kDefaultZoomLevel));
659 const base::DictionaryValue* host_zoom_dictionary =
660 prefs_->GetDictionary(prefs::kPerHostZoomLevels);
661 // Careful: The returned value could be NULL if the pref has never been set.
662 if (host_zoom_dictionary != NULL) {
663 std::vector<std::string> keys_to_remove;
664 for (base::DictionaryValue::Iterator i(*host_zoom_dictionary); !i.IsAtEnd();
665 i.Advance()) {
666 const std::string& host(i.key());
667 double zoom_level = 0;
669 bool success = i.value().GetAsDouble(&zoom_level);
670 DCHECK(success);
672 // Filter out A) the empty host, B) zoom levels equal to the default; and
673 // remember them, so that we can later erase them from Prefs.
674 // Values of type A and B could have been stored due to crbug.com/364399.
675 // Values of type B could further have been stored before the default zoom
676 // level was set to its current value. In either case, SetZoomLevelForHost
677 // will ignore type B values, thus, to have consistency with HostZoomMap's
678 // internal state, these values must also be removed from Prefs.
679 if (host.empty() ||
680 content::ZoomValuesEqual(zoom_level,
681 host_zoom_map->GetDefaultZoomLevel())) {
682 keys_to_remove.push_back(host);
683 continue;
686 host_zoom_map->SetZoomLevelForHost(host, zoom_level);
689 DictionaryPrefUpdate update(prefs_.get(), prefs::kPerHostZoomLevels);
690 base::DictionaryValue* host_zoom_dictionary = update.Get();
691 for (std::vector<std::string>::const_iterator it = keys_to_remove.begin();
692 it != keys_to_remove.end(); ++it) {
693 host_zoom_dictionary->RemoveWithoutPathExpansion(*it, NULL);
697 zoom_subscription_ = host_zoom_map->AddZoomLevelChangedCallback(
698 base::Bind(&ProfileImpl::OnZoomLevelChanged, base::Unretained(this)));
701 base::FilePath ProfileImpl::last_selected_directory() {
702 return GetPrefs()->GetFilePath(prefs::kSelectFileLastDirectory);
705 void ProfileImpl::set_last_selected_directory(const base::FilePath& path) {
706 GetPrefs()->SetFilePath(prefs::kSelectFileLastDirectory, path);
709 ProfileImpl::~ProfileImpl() {
710 MaybeSendDestroyedNotification();
712 bool prefs_loaded = prefs_->GetInitializationStatus() !=
713 PrefService::INITIALIZATION_STATUS_WAITING;
715 #if defined(ENABLE_SESSION_SERVICE)
716 StopCreateSessionServiceTimer();
717 #endif
719 // Remove pref observers
720 pref_change_registrar_.RemoveAll();
722 #if defined(ENABLE_PLUGINS)
723 ChromePluginServiceFilter::GetInstance()->UnregisterResourceContext(
724 io_data_.GetResourceContextNoInit());
725 #endif
727 // Destroy OTR profile and its profile services first.
728 if (off_the_record_profile_) {
729 ProfileDestroyer::DestroyOffTheRecordProfileNow(
730 off_the_record_profile_.get());
731 } else {
732 ExtensionPrefValueMapFactory::GetForBrowserContext(this)->
733 ClearAllIncognitoSessionOnlyPreferences();
736 BrowserContextDependencyManager::GetInstance()->DestroyBrowserContextServices(
737 this);
739 if (top_sites_.get())
740 top_sites_->Shutdown();
742 if (pref_proxy_config_tracker_)
743 pref_proxy_config_tracker_->DetachFromPrefService();
745 if (host_content_settings_map_.get())
746 host_content_settings_map_->ShutdownOnUIThread();
748 // This causes the Preferences file to be written to disk.
749 if (prefs_loaded)
750 SetExitType(EXIT_NORMAL);
753 std::string ProfileImpl::GetProfileName() {
754 return GetPrefs()->GetString(prefs::kGoogleServicesUsername);
757 Profile::ProfileType ProfileImpl::GetProfileType() const {
758 return REGULAR_PROFILE;
761 base::FilePath ProfileImpl::GetPath() const {
762 return path_;
765 scoped_refptr<base::SequencedTaskRunner> ProfileImpl::GetIOTaskRunner() {
766 return JsonPrefStore::GetTaskRunnerForFile(
767 GetPath(), BrowserThread::GetBlockingPool());
770 bool ProfileImpl::IsOffTheRecord() const {
771 return false;
774 Profile* ProfileImpl::GetOffTheRecordProfile() {
775 if (!off_the_record_profile_) {
776 scoped_ptr<Profile> p(CreateOffTheRecordProfile());
777 off_the_record_profile_.swap(p);
779 content::NotificationService::current()->Notify(
780 chrome::NOTIFICATION_PROFILE_CREATED,
781 content::Source<Profile>(off_the_record_profile_.get()),
782 content::NotificationService::NoDetails());
784 return off_the_record_profile_.get();
787 void ProfileImpl::DestroyOffTheRecordProfile() {
788 off_the_record_profile_.reset();
789 ExtensionPrefValueMapFactory::GetForBrowserContext(this)->
790 ClearAllIncognitoSessionOnlyPreferences();
793 bool ProfileImpl::HasOffTheRecordProfile() {
794 return off_the_record_profile_.get() != NULL;
797 Profile* ProfileImpl::GetOriginalProfile() {
798 return this;
801 bool ProfileImpl::IsManaged() {
802 return !GetPrefs()->GetString(prefs::kManagedUserId).empty();
805 ExtensionService* ProfileImpl::GetExtensionService() {
806 return extensions::ExtensionSystem::Get(this)->extension_service();
809 ExtensionSpecialStoragePolicy*
810 ProfileImpl::GetExtensionSpecialStoragePolicy() {
811 if (!extension_special_storage_policy_.get()) {
812 TRACE_EVENT0("browser", "ProfileImpl::GetExtensionSpecialStoragePolicy")
813 extension_special_storage_policy_ = new ExtensionSpecialStoragePolicy(
814 CookieSettings::Factory::GetForProfile(this).get());
816 return extension_special_storage_policy_.get();
819 void ProfileImpl::OnPrefsLoaded(bool success) {
820 TRACE_EVENT0("browser", "ProfileImpl::OnPrefsLoaded")
821 if (!success) {
822 if (delegate_)
823 delegate_->OnProfileCreated(this, false, false);
824 return;
827 // TODO(mirandac): remove migration code after 6 months (crbug.com/69995).
828 if (g_browser_process->local_state())
829 chrome::MigrateBrowserPrefs(this, g_browser_process->local_state());
830 // TODO(ivankr): remove cleanup code eventually (crbug.com/165672).
831 chrome::MigrateUserPrefs(this);
833 // |kSessionExitType| was added after |kSessionExitedCleanly|. If the pref
834 // value is empty fallback to checking for |kSessionExitedCleanly|.
835 const std::string exit_type_pref_value(
836 prefs_->GetString(prefs::kSessionExitType));
837 if (exit_type_pref_value.empty()) {
838 last_session_exit_type_ =
839 prefs_->GetBoolean(prefs::kSessionExitedCleanly) ?
840 EXIT_NORMAL : EXIT_CRASHED;
841 } else {
842 last_session_exit_type_ =
843 SessionTypePrefValueToExitType(exit_type_pref_value);
845 // Mark the session as open.
846 prefs_->SetString(prefs::kSessionExitType, kPrefExitTypeCrashed);
847 // Force this to true in case we fallback and use it.
848 // TODO(sky): remove this in a couple of releases (m28ish).
849 prefs_->SetBoolean(prefs::kSessionExitedCleanly, true);
851 g_browser_process->profile_manager()->InitProfileUserPrefs(this);
853 BrowserContextDependencyManager::GetInstance()->CreateBrowserContextServices(
854 this);
856 DCHECK(!net_pref_observer_);
858 TRACE_EVENT0("browser", "ProfileImpl::OnPrefsLoaded:NetPrefObserver")
859 net_pref_observer_.reset(new NetPrefObserver(
860 prefs_.get(),
861 prerender::PrerenderManagerFactory::GetForProfile(this),
862 predictor_));
865 chrome_prefs::SchedulePrefsFilePathVerification(path_);
867 ChromeVersionService::OnProfileLoaded(prefs_.get(), IsNewProfile());
868 DoFinalInit();
871 bool ProfileImpl::WasCreatedByVersionOrLater(const std::string& version) {
872 Version profile_version(ChromeVersionService::GetVersion(prefs_.get()));
873 Version arg_version(version);
874 return (profile_version.CompareTo(arg_version) >= 0);
877 void ProfileImpl::SetExitType(ExitType exit_type) {
878 #if defined(OS_CHROMEOS)
879 if (chromeos::ProfileHelper::IsSigninProfile(this))
880 return;
881 #endif
882 if (!prefs_)
883 return;
884 ExitType current_exit_type = SessionTypePrefValueToExitType(
885 prefs_->GetString(prefs::kSessionExitType));
886 // This may be invoked multiple times during shutdown. Only persist the value
887 // first passed in (unless it's a reset to the crash state, which happens when
888 // foregrounding the app on mobile).
889 if (exit_type == EXIT_CRASHED || current_exit_type == EXIT_CRASHED) {
890 prefs_->SetString(prefs::kSessionExitType,
891 ExitTypeToSessionTypePrefValue(exit_type));
893 // NOTE: If you change what thread this writes on, be sure and update
894 // chrome::SessionEnding().
895 prefs_->CommitPendingWrite();
899 Profile::ExitType ProfileImpl::GetLastSessionExitType() {
900 // last_session_exited_cleanly_ is set when the preferences are loaded. Force
901 // it to be set by asking for the prefs.
902 GetPrefs();
903 return last_session_exit_type_;
906 PrefService* ProfileImpl::GetPrefs() {
907 DCHECK(prefs_); // Should explicitly be initialized.
908 return prefs_.get();
911 PrefService* ProfileImpl::GetOffTheRecordPrefs() {
912 DCHECK(prefs_);
913 if (!otr_prefs_) {
914 // The new ExtensionPrefStore is ref_counted and the new PrefService
915 // stores a reference so that we do not leak memory here.
916 otr_prefs_.reset(prefs_->CreateIncognitoPrefService(
917 new ExtensionPrefStore(
918 ExtensionPrefValueMapFactory::GetForBrowserContext(this), true)));
920 return otr_prefs_.get();
923 net::URLRequestContextGetter* ProfileImpl::CreateRequestContext(
924 content::ProtocolHandlerMap* protocol_handlers,
925 content::URLRequestInterceptorScopedVector request_interceptors) {
926 return io_data_.CreateMainRequestContextGetter(
927 protocol_handlers,
928 request_interceptors.Pass(),
929 g_browser_process->local_state(),
930 g_browser_process->io_thread()).get();
933 net::URLRequestContextGetter* ProfileImpl::GetRequestContext() {
934 return GetDefaultStoragePartition(this)->GetURLRequestContext();
937 net::URLRequestContextGetter* ProfileImpl::GetRequestContextForRenderProcess(
938 int renderer_child_id) {
939 content::RenderProcessHost* rph = content::RenderProcessHost::FromID(
940 renderer_child_id);
942 return rph->GetStoragePartition()->GetURLRequestContext();
945 net::URLRequestContextGetter* ProfileImpl::GetMediaRequestContext() {
946 // Return the default media context.
947 return io_data_.GetMediaRequestContextGetter().get();
950 net::URLRequestContextGetter*
951 ProfileImpl::GetMediaRequestContextForRenderProcess(
952 int renderer_child_id) {
953 content::RenderProcessHost* rph = content::RenderProcessHost::FromID(
954 renderer_child_id);
955 content::StoragePartition* storage_partition = rph->GetStoragePartition();
957 return storage_partition->GetMediaURLRequestContext();
960 net::URLRequestContextGetter*
961 ProfileImpl::GetMediaRequestContextForStoragePartition(
962 const base::FilePath& partition_path,
963 bool in_memory) {
964 return io_data_
965 .GetIsolatedMediaRequestContextGetter(partition_path, in_memory).get();
968 void ProfileImpl::RequestMidiSysExPermission(
969 int render_process_id,
970 int render_view_id,
971 int bridge_id,
972 const GURL& requesting_frame,
973 bool user_gesture,
974 const MidiSysExPermissionCallback& callback) {
975 ChromeMidiPermissionContext* context =
976 ChromeMidiPermissionContextFactory::GetForProfile(this);
977 context->RequestMidiSysExPermission(render_process_id,
978 render_view_id,
979 bridge_id,
980 requesting_frame,
981 user_gesture,
982 callback);
985 void ProfileImpl::CancelMidiSysExPermissionRequest(
986 int render_process_id,
987 int render_view_id,
988 int bridge_id,
989 const GURL& requesting_frame) {
990 ChromeMidiPermissionContext* context =
991 ChromeMidiPermissionContextFactory::GetForProfile(this);
992 context->CancelMidiSysExPermissionRequest(
993 render_process_id, render_view_id, bridge_id, requesting_frame);
996 void ProfileImpl::RequestProtectedMediaIdentifierPermission(
997 int render_process_id,
998 int render_view_id,
999 const GURL& origin,
1000 const ProtectedMediaIdentifierPermissionCallback& callback) {
1001 #if defined(OS_ANDROID)
1002 ProtectedMediaIdentifierPermissionContext* context =
1003 ProtectedMediaIdentifierPermissionContextFactory::GetForProfile(this);
1004 context->RequestProtectedMediaIdentifierPermission(render_process_id,
1005 render_view_id,
1006 origin,
1007 callback);
1008 #else
1009 NOTIMPLEMENTED();
1010 callback.Run(false);
1011 #endif // defined(OS_ANDROID)
1014 void ProfileImpl::CancelProtectedMediaIdentifierPermissionRequests(
1015 int render_process_id,
1016 int render_view_id,
1017 const GURL& origin) {
1018 #if defined(OS_ANDROID)
1019 ProtectedMediaIdentifierPermissionContext* context =
1020 ProtectedMediaIdentifierPermissionContextFactory::GetForProfile(this);
1021 context->CancelProtectedMediaIdentifierPermissionRequests(
1022 render_process_id, render_view_id, origin);
1023 #else
1024 NOTIMPLEMENTED();
1025 #endif // defined(OS_ANDROID)
1028 content::ResourceContext* ProfileImpl::GetResourceContext() {
1029 return io_data_.GetResourceContext();
1032 net::URLRequestContextGetter* ProfileImpl::GetRequestContextForExtensions() {
1033 return io_data_.GetExtensionsRequestContextGetter().get();
1036 net::URLRequestContextGetter*
1037 ProfileImpl::CreateRequestContextForStoragePartition(
1038 const base::FilePath& partition_path,
1039 bool in_memory,
1040 content::ProtocolHandlerMap* protocol_handlers,
1041 content::URLRequestInterceptorScopedVector request_interceptors) {
1042 return io_data_.CreateIsolatedAppRequestContextGetter(
1043 partition_path,
1044 in_memory,
1045 protocol_handlers,
1046 request_interceptors.Pass()).get();
1049 net::SSLConfigService* ProfileImpl::GetSSLConfigService() {
1050 // If ssl_config_service_manager_ is null, this typically means that some
1051 // KeyedService is trying to create a RequestContext at startup,
1052 // but SSLConfigServiceManager is not initialized until DoFinalInit() which is
1053 // invoked after all KeyedServices have been initialized (see
1054 // http://crbug.com/171406).
1055 DCHECK(ssl_config_service_manager_) <<
1056 "SSLConfigServiceManager is not initialized yet";
1057 return ssl_config_service_manager_->Get();
1060 HostContentSettingsMap* ProfileImpl::GetHostContentSettingsMap() {
1061 if (!host_content_settings_map_.get()) {
1062 host_content_settings_map_ = new HostContentSettingsMap(GetPrefs(), false);
1064 return host_content_settings_map_.get();
1067 content::GeolocationPermissionContext*
1068 ProfileImpl::GetGeolocationPermissionContext() {
1069 return ChromeGeolocationPermissionContextFactory::GetForProfile(this);
1072 content::BrowserPluginGuestManager* ProfileImpl::GetGuestManager() {
1073 return GuestViewManager::FromBrowserContext(this);
1076 DownloadManagerDelegate* ProfileImpl::GetDownloadManagerDelegate() {
1077 return DownloadServiceFactory::GetForBrowserContext(this)->
1078 GetDownloadManagerDelegate();
1081 quota::SpecialStoragePolicy* ProfileImpl::GetSpecialStoragePolicy() {
1082 return GetExtensionSpecialStoragePolicy();
1085 bool ProfileImpl::IsSameProfile(Profile* profile) {
1086 if (profile == static_cast<Profile*>(this))
1087 return true;
1088 Profile* otr_profile = off_the_record_profile_.get();
1089 return otr_profile && profile == otr_profile;
1092 Time ProfileImpl::GetStartTime() const {
1093 return start_time_;
1096 history::TopSites* ProfileImpl::GetTopSites() {
1097 if (!top_sites_.get()) {
1098 top_sites_ = history::TopSites::Create(
1099 this, GetPath().Append(chrome::kTopSitesFilename));
1101 return top_sites_.get();
1104 history::TopSites* ProfileImpl::GetTopSitesWithoutCreating() {
1105 return top_sites_.get();
1108 void ProfileImpl::OnDefaultZoomLevelChanged() {
1109 HostZoomMap::GetForBrowserContext(this)->SetDefaultZoomLevel(
1110 pref_change_registrar_.prefs()->GetDouble(prefs::kDefaultZoomLevel));
1113 void ProfileImpl::OnZoomLevelChanged(
1114 const HostZoomMap::ZoomLevelChange& change) {
1116 if (change.mode != HostZoomMap::ZOOM_CHANGED_FOR_HOST)
1117 return;
1118 HostZoomMap* host_zoom_map = HostZoomMap::GetForBrowserContext(this);
1119 double level = change.zoom_level;
1120 DictionaryPrefUpdate update(prefs_.get(), prefs::kPerHostZoomLevels);
1121 base::DictionaryValue* host_zoom_dictionary = update.Get();
1122 if (content::ZoomValuesEqual(level, host_zoom_map->GetDefaultZoomLevel())) {
1123 host_zoom_dictionary->RemoveWithoutPathExpansion(change.host, NULL);
1124 } else {
1125 host_zoom_dictionary->SetWithoutPathExpansion(
1126 change.host, base::Value::CreateDoubleValue(level));
1130 #if defined(ENABLE_SESSION_SERVICE)
1131 void ProfileImpl::StopCreateSessionServiceTimer() {
1132 create_session_service_timer_.Stop();
1135 void ProfileImpl::EnsureSessionServiceCreated() {
1136 SessionServiceFactory::GetForProfile(this);
1138 #endif
1140 #if defined(OS_CHROMEOS)
1141 void ProfileImpl::ChangeAppLocale(
1142 const std::string& new_locale, AppLocaleChangedVia via) {
1143 if (new_locale.empty()) {
1144 NOTREACHED();
1145 return;
1147 PrefService* local_state = g_browser_process->local_state();
1148 DCHECK(local_state);
1149 if (local_state->IsManagedPreference(prefs::kApplicationLocale))
1150 return;
1151 std::string pref_locale = GetPrefs()->GetString(prefs::kApplicationLocale);
1152 bool do_update_pref = true;
1153 switch (via) {
1154 case APP_LOCALE_CHANGED_VIA_SETTINGS:
1155 case APP_LOCALE_CHANGED_VIA_REVERT: {
1156 // We keep kApplicationLocaleBackup value as a reference. In case value
1157 // of kApplicationLocale preference would change due to sync from other
1158 // device then kApplicationLocaleBackup value will trigger and allow us to
1159 // show notification about automatic locale change in LocaleChangeGuard.
1160 GetPrefs()->SetString(prefs::kApplicationLocaleBackup, new_locale);
1161 GetPrefs()->ClearPref(prefs::kApplicationLocaleAccepted);
1162 // We maintain kApplicationLocale property in both a global storage
1163 // and user's profile. Global property determines locale of login screen,
1164 // while user's profile determines his personal locale preference.
1165 break;
1167 case APP_LOCALE_CHANGED_VIA_LOGIN: {
1168 if (!pref_locale.empty()) {
1169 DCHECK(pref_locale == new_locale);
1170 std::string accepted_locale =
1171 GetPrefs()->GetString(prefs::kApplicationLocaleAccepted);
1172 if (accepted_locale == new_locale) {
1173 // If locale is accepted then we do not want to show LocaleChange
1174 // notification. This notification is triggered by different values
1175 // of kApplicationLocaleBackup and kApplicationLocale preferences,
1176 // so make them identical.
1177 GetPrefs()->SetString(prefs::kApplicationLocaleBackup, new_locale);
1178 } else {
1179 // Back up locale of login screen.
1180 std::string cur_locale = g_browser_process->GetApplicationLocale();
1181 GetPrefs()->SetString(prefs::kApplicationLocaleBackup, cur_locale);
1182 if (locale_change_guard_ == NULL)
1183 locale_change_guard_.reset(new chromeos::LocaleChangeGuard(this));
1184 locale_change_guard_->PrepareChangingLocale(cur_locale, new_locale);
1186 } else {
1187 std::string cur_locale = g_browser_process->GetApplicationLocale();
1188 std::string backup_locale =
1189 GetPrefs()->GetString(prefs::kApplicationLocaleBackup);
1190 // Profile synchronization takes time and is not completed at that
1191 // moment at first login. So we initialize locale preference in steps:
1192 // (1) first save it to temporary backup;
1193 // (2) on next login we assume that synchronization is already completed
1194 // and we may finalize initialization.
1195 GetPrefs()->SetString(prefs::kApplicationLocaleBackup, cur_locale);
1196 if (!new_locale.empty())
1197 GetPrefs()->SetString(prefs::kApplicationLocale, new_locale);
1198 else if (!backup_locale.empty())
1199 GetPrefs()->SetString(prefs::kApplicationLocale, backup_locale);
1200 do_update_pref = false;
1202 break;
1204 case APP_LOCALE_CHANGED_VIA_UNKNOWN:
1205 default: {
1206 NOTREACHED();
1207 break;
1210 if (do_update_pref)
1211 GetPrefs()->SetString(prefs::kApplicationLocale, new_locale);
1212 local_state->SetString(prefs::kApplicationLocale, new_locale);
1214 if (chromeos::UserManager::Get()->GetOwnerEmail() ==
1215 chromeos::UserManager::Get()->GetUserByProfile(this)->email())
1216 local_state->SetString(prefs::kOwnerLocale, new_locale);
1219 void ProfileImpl::OnLogin() {
1220 if (locale_change_guard_ == NULL)
1221 locale_change_guard_.reset(new chromeos::LocaleChangeGuard(this));
1222 locale_change_guard_->OnLogin();
1225 void ProfileImpl::InitChromeOSPreferences() {
1226 chromeos_preferences_.reset(new chromeos::Preferences());
1227 chromeos_preferences_->Init(
1228 PrefServiceSyncable::FromProfile(this),
1229 chromeos::UserManager::Get()->GetUserByProfile(this));
1232 #endif // defined(OS_CHROMEOS)
1234 PrefProxyConfigTracker* ProfileImpl::GetProxyConfigTracker() {
1235 if (!pref_proxy_config_tracker_)
1236 pref_proxy_config_tracker_.reset(CreateProxyConfigTracker());
1237 return pref_proxy_config_tracker_.get();
1240 chrome_browser_net::Predictor* ProfileImpl::GetNetworkPredictor() {
1241 return predictor_;
1244 DevToolsNetworkController* ProfileImpl::GetDevToolsNetworkController() {
1245 return io_data_.GetDevToolsNetworkController();
1248 void ProfileImpl::ClearNetworkingHistorySince(
1249 base::Time time,
1250 const base::Closure& completion) {
1251 io_data_.ClearNetworkingHistorySince(time, completion);
1254 void ProfileImpl::ClearDomainReliabilityMonitor(
1255 domain_reliability::DomainReliabilityClearMode mode,
1256 const base::Closure& completion) {
1257 io_data_.ClearDomainReliabilityMonitor(mode, completion);
1260 GURL ProfileImpl::GetHomePage() {
1261 // --homepage overrides any preferences.
1262 const CommandLine& command_line = *CommandLine::ForCurrentProcess();
1263 if (command_line.HasSwitch(switches::kHomePage)) {
1264 // TODO(evanm): clean up usage of DIR_CURRENT.
1265 // http://code.google.com/p/chromium/issues/detail?id=60630
1266 // For now, allow this code to call getcwd().
1267 base::ThreadRestrictions::ScopedAllowIO allow_io;
1269 base::FilePath browser_directory;
1270 PathService::Get(base::DIR_CURRENT, &browser_directory);
1271 GURL home_page(URLFixerUpper::FixupRelativeFile(browser_directory,
1272 command_line.GetSwitchValuePath(switches::kHomePage)));
1273 if (home_page.is_valid())
1274 return home_page;
1277 if (GetPrefs()->GetBoolean(prefs::kHomePageIsNewTabPage))
1278 return GURL(chrome::kChromeUINewTabURL);
1279 GURL home_page(URLFixerUpper::FixupURL(
1280 GetPrefs()->GetString(prefs::kHomePage),
1281 std::string()));
1282 if (!home_page.is_valid())
1283 return GURL(chrome::kChromeUINewTabURL);
1284 return home_page;
1287 void ProfileImpl::UpdateProfileUserNameCache() {
1288 ProfileManager* profile_manager = g_browser_process->profile_manager();
1289 ProfileInfoCache& cache = profile_manager->GetProfileInfoCache();
1290 size_t index = cache.GetIndexOfProfileWithPath(GetPath());
1291 if (index != std::string::npos) {
1292 std::string user_name =
1293 GetPrefs()->GetString(prefs::kGoogleServicesUsername);
1294 cache.SetUserNameOfProfileAtIndex(index, base::UTF8ToUTF16(user_name));
1295 ProfileMetrics::UpdateReportedProfilesStatistics(profile_manager);
1299 void ProfileImpl::UpdateProfileManagedUserIdCache() {
1300 ProfileManager* profile_manager = g_browser_process->profile_manager();
1301 ProfileInfoCache& cache = profile_manager->GetProfileInfoCache();
1302 size_t index = cache.GetIndexOfProfileWithPath(GetPath());
1303 if (index != std::string::npos) {
1304 std::string managed_user_id = GetPrefs()->GetString(prefs::kManagedUserId);
1305 cache.SetManagedUserIdOfProfileAtIndex(index, managed_user_id);
1306 ProfileMetrics::UpdateReportedProfilesStatistics(profile_manager);
1310 void ProfileImpl::UpdateProfileNameCache() {
1311 ProfileManager* profile_manager = g_browser_process->profile_manager();
1312 ProfileInfoCache& cache = profile_manager->GetProfileInfoCache();
1313 size_t index = cache.GetIndexOfProfileWithPath(GetPath());
1314 if (index != std::string::npos) {
1315 std::string profile_name =
1316 GetPrefs()->GetString(prefs::kProfileName);
1317 cache.SetNameOfProfileAtIndex(index, base::UTF8ToUTF16(profile_name));
1321 void ProfileImpl::UpdateProfileAvatarCache() {
1322 ProfileManager* profile_manager = g_browser_process->profile_manager();
1323 ProfileInfoCache& cache = profile_manager->GetProfileInfoCache();
1324 size_t index = cache.GetIndexOfProfileWithPath(GetPath());
1325 if (index != std::string::npos) {
1326 size_t avatar_index =
1327 GetPrefs()->GetInteger(prefs::kProfileAvatarIndex);
1328 cache.SetAvatarIconOfProfileAtIndex(index, avatar_index);
1332 void ProfileImpl::UpdateProfileIsEphemeralCache() {
1333 ProfileManager* profile_manager = g_browser_process->profile_manager();
1334 ProfileInfoCache& cache = profile_manager->GetProfileInfoCache();
1335 size_t index = cache.GetIndexOfProfileWithPath(GetPath());
1336 if (index != std::string::npos) {
1337 bool is_ephemeral = GetPrefs()->GetBoolean(prefs::kForceEphemeralProfiles);
1338 cache.SetProfileIsEphemeralAtIndex(index, is_ephemeral);
1342 // Gets the cache parameters from the command line. If |is_media_context| is
1343 // set to true then settings for the media context type is what we need,
1344 // |cache_path| will be set to the user provided path, or will not be touched if
1345 // there is not an argument. |max_size| will be the user provided value or zero
1346 // by default.
1347 void ProfileImpl::GetCacheParameters(bool is_media_context,
1348 base::FilePath* cache_path,
1349 int* max_size) {
1350 DCHECK(cache_path);
1351 DCHECK(max_size);
1352 base::FilePath path(prefs_->GetFilePath(prefs::kDiskCacheDir));
1353 if (!path.empty())
1354 *cache_path = path;
1355 *max_size = is_media_context ? prefs_->GetInteger(prefs::kMediaCacheSize) :
1356 prefs_->GetInteger(prefs::kDiskCacheSize);
1359 PrefProxyConfigTracker* ProfileImpl::CreateProxyConfigTracker() {
1360 #if defined(OS_CHROMEOS)
1361 if (chromeos::ProfileHelper::IsSigninProfile(this)) {
1362 return ProxyServiceFactory::CreatePrefProxyConfigTrackerOfLocalState(
1363 g_browser_process->local_state());
1365 #endif // defined(OS_CHROMEOS)
1366 return ProxyServiceFactory::CreatePrefProxyConfigTrackerOfProfile(
1367 GetPrefs(), g_browser_process->local_state());