Restart Chrome on ChromeOS as early as possible to speed up restart.
[chromium-blink-merge.git] / chrome / browser / profiles / profile_impl.cc
blobd3d00e95bcedbe212066931500279be0cd54e694
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/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/extensions/extension_service.h"
44 #include "chrome/browser/extensions/extension_special_storage_policy.h"
45 #include "chrome/browser/history/top_sites.h"
46 #include "chrome/browser/net/chrome_url_request_context.h"
47 #include "chrome/browser/net/net_pref_observer.h"
48 #include "chrome/browser/net/predictor.h"
49 #include "chrome/browser/net/pref_proxy_config_tracker.h"
50 #include "chrome/browser/net/proxy_service_factory.h"
51 #include "chrome/browser/net/ssl_config_service_manager.h"
52 #include "chrome/browser/plugins/chrome_plugin_service_filter.h"
53 #include "chrome/browser/plugins/plugin_prefs.h"
54 #include "chrome/browser/policy/profile_policy_connector.h"
55 #include "chrome/browser/policy/profile_policy_connector_factory.h"
56 #include "chrome/browser/prefs/browser_prefs.h"
57 #include "chrome/browser/prefs/chrome_pref_service_factory.h"
58 #include "chrome/browser/prefs/pref_service_syncable.h"
59 #include "chrome/browser/prefs/tracked/tracked_preference_validation_delegate.h"
60 #include "chrome/browser/prerender/prerender_manager_factory.h"
61 #include "chrome/browser/profiles/bookmark_model_loaded_observer.h"
62 #include "chrome/browser/profiles/chrome_version_service.h"
63 #include "chrome/browser/profiles/gaia_info_update_service_factory.h"
64 #include "chrome/browser/profiles/profile_destroyer.h"
65 #include "chrome/browser/profiles/profile_info_cache.h"
66 #include "chrome/browser/profiles/profile_manager.h"
67 #include "chrome/browser/profiles/profile_metrics.h"
68 #include "chrome/browser/safe_browsing/safe_browsing_service.h"
69 #include "chrome/browser/search_engines/template_url_fetcher.h"
70 #include "chrome/browser/services/gcm/gcm_profile_service.h"
71 #include "chrome/browser/services/gcm/gcm_profile_service_factory.h"
72 #include "chrome/browser/services/gcm/push_messaging_service_impl.h"
73 #include "chrome/browser/sessions/session_service_factory.h"
74 #include "chrome/browser/ui/startup/startup_browser_creator.h"
75 #include "chrome/browser/ui/webui/extensions/extension_icon_source.h"
76 #include "chrome/browser/webdata/web_data_service.h"
77 #include "chrome/common/chrome_constants.h"
78 #include "chrome/common/chrome_paths_internal.h"
79 #include "chrome/common/chrome_switches.h"
80 #include "chrome/common/chrome_version_info.h"
81 #include "chrome/common/pref_names.h"
82 #include "chrome/common/url_constants.h"
83 #include "components/bookmarks/browser/bookmark_model.h"
84 #include "components/dom_distiller/content/dom_distiller_viewer_source.h"
85 #include "components/domain_reliability/monitor.h"
86 #include "components/domain_reliability/service.h"
87 #include "components/keyed_service/content/browser_context_dependency_manager.h"
88 #include "components/metrics/metrics_service.h"
89 #include "components/pref_registry/pref_registry_syncable.h"
90 #include "components/startup_metric_utils/startup_metric_utils.h"
91 #include "components/url_fixer/url_fixer.h"
92 #include "components/user_prefs/user_prefs.h"
93 #include "content/public/browser/browser_thread.h"
94 #include "content/public/browser/dom_storage_context.h"
95 #include "content/public/browser/host_zoom_map.h"
96 #include "content/public/browser/notification_service.h"
97 #include "content/public/browser/render_process_host.h"
98 #include "content/public/browser/storage_partition.h"
99 #include "content/public/browser/url_data_source.h"
100 #include "content/public/browser/user_metrics.h"
101 #include "content/public/common/content_constants.h"
102 #include "content/public/common/page_zoom.h"
103 #include "extensions/browser/extension_pref_store.h"
104 #include "extensions/browser/extension_pref_value_map.h"
105 #include "extensions/browser/extension_pref_value_map_factory.h"
106 #include "extensions/browser/extension_system.h"
107 #include "grit/chromium_strings.h"
108 #include "grit/generated_resources.h"
109 #include "ui/base/l10n/l10n_util.h"
111 #if defined(OS_ANDROID)
112 #include "chrome/browser/media/protected_media_identifier_permission_context.h"
113 #include "chrome/browser/media/protected_media_identifier_permission_context_factory.h"
114 #endif
116 #if defined(OS_CHROMEOS)
117 #include "chrome/browser/chromeos/locale_change_guard.h"
118 #include "chrome/browser/chromeos/login/users/user_manager.h"
119 #include "chrome/browser/chromeos/preferences.h"
120 #include "chrome/browser/chromeos/profiles/profile_helper.h"
121 #endif
123 #if defined(ENABLE_CONFIGURATION_POLICY)
124 #include "chrome/browser/policy/schema_registry_service.h"
125 #include "chrome/browser/policy/schema_registry_service_factory.h"
126 #include "components/policy/core/browser/browser_policy_connector.h"
127 #if defined(OS_CHROMEOS)
128 #include "chrome/browser/chromeos/login/login_utils.h"
129 #include "chrome/browser/chromeos/policy/user_cloud_policy_manager_chromeos.h"
130 #include "chrome/browser/chromeos/policy/user_cloud_policy_manager_factory_chromeos.h"
131 #else
132 #include "chrome/browser/policy/cloud/user_cloud_policy_manager_factory.h"
133 #include "components/policy/core/common/cloud/user_cloud_policy_manager.h"
134 #endif
135 #endif
137 #if defined(ENABLE_EXTENSIONS)
138 #include "chrome/browser/guest_view/guest_view_manager.h"
139 #endif
141 #if defined(ENABLE_MANAGED_USERS)
142 #include "chrome/browser/supervised_user/supervised_user_settings_service.h"
143 #include "chrome/browser/supervised_user/supervised_user_settings_service_factory.h"
144 #endif
146 using base::Time;
147 using base::TimeDelta;
148 using base::UserMetricsAction;
149 using content::BrowserThread;
150 using content::DownloadManagerDelegate;
151 using content::HostZoomMap;
153 namespace {
155 #if defined(ENABLE_SESSION_SERVICE)
156 // Delay, in milliseconds, before we explicitly create the SessionService.
157 static const int kCreateSessionServiceDelayMS = 500;
158 #endif
160 // Text content of README file created in each profile directory. Both %s
161 // placeholders must contain the product name. This is not localizable and hence
162 // not in resources.
163 static const char kReadmeText[] =
164 "%s settings and storage represent user-selected preferences and "
165 "information and MUST not be extracted, overwritten or modified except "
166 "through %s defined APIs.";
168 // Value written to prefs for EXIT_CRASHED and EXIT_SESSION_ENDED.
169 const char* const kPrefExitTypeCrashed = "Crashed";
170 const char* const kPrefExitTypeSessionEnded = "SessionEnded";
172 // Helper method needed because PostTask cannot currently take a Callback
173 // function with non-void return type.
174 void CreateDirectoryAndSignal(const base::FilePath& path,
175 base::WaitableEvent* done_creating) {
176 DVLOG(1) << "Creating directory " << path.value();
177 base::CreateDirectory(path);
178 done_creating->Signal();
181 // Task that blocks the FILE thread until CreateDirectoryAndSignal() finishes on
182 // blocking I/O pool.
183 void BlockFileThreadOnDirectoryCreate(base::WaitableEvent* done_creating) {
184 done_creating->Wait();
187 // Initiates creation of profile directory on |sequenced_task_runner| and
188 // ensures that FILE thread is blocked until that operation finishes.
189 void CreateProfileDirectory(base::SequencedTaskRunner* sequenced_task_runner,
190 const base::FilePath& path) {
191 base::WaitableEvent* done_creating = new base::WaitableEvent(false, false);
192 sequenced_task_runner->PostTask(FROM_HERE,
193 base::Bind(&CreateDirectoryAndSignal,
194 path,
195 done_creating));
196 // Block the FILE thread until directory is created on I/O pool to make sure
197 // that we don't attempt any operation until that part completes.
198 BrowserThread::PostTask(
199 BrowserThread::FILE, FROM_HERE,
200 base::Bind(&BlockFileThreadOnDirectoryCreate,
201 base::Owned(done_creating)));
204 base::FilePath GetCachePath(const base::FilePath& base) {
205 return base.Append(chrome::kCacheDirname);
208 base::FilePath GetMediaCachePath(const base::FilePath& base) {
209 return base.Append(chrome::kMediaCacheDirname);
212 void EnsureReadmeFile(const base::FilePath& base) {
213 base::FilePath readme_path = base.Append(chrome::kReadmeFilename);
214 if (base::PathExists(readme_path))
215 return;
216 std::string product_name = l10n_util::GetStringUTF8(IDS_PRODUCT_NAME);
217 std::string readme_text = base::StringPrintf(
218 kReadmeText, product_name.c_str(), product_name.c_str());
219 if (base::WriteFile(readme_path, readme_text.data(), readme_text.size()) ==
220 -1) {
221 LOG(ERROR) << "Could not create README file.";
225 // Converts the kSessionExitedCleanly pref to the corresponding EXIT_TYPE.
226 Profile::ExitType SessionTypePrefValueToExitType(const std::string& value) {
227 if (value == kPrefExitTypeSessionEnded)
228 return Profile::EXIT_SESSION_ENDED;
229 if (value == kPrefExitTypeCrashed)
230 return Profile::EXIT_CRASHED;
231 return Profile::EXIT_NORMAL;
234 // Converts an ExitType into a string that is written to prefs.
235 std::string ExitTypeToSessionTypePrefValue(Profile::ExitType type) {
236 switch (type) {
237 case Profile::EXIT_NORMAL:
238 return ProfileImpl::kPrefExitTypeNormal;
239 case Profile::EXIT_SESSION_ENDED:
240 return kPrefExitTypeSessionEnded;
241 case Profile::EXIT_CRASHED:
242 return kPrefExitTypeCrashed;
244 NOTREACHED();
245 return std::string();
248 // Setup URLDataSource for the chrome-distiller:// scheme for the given
249 // |profile|.
250 void RegisterDomDistillerViewerSource(Profile* profile) {
251 const CommandLine& command_line = *CommandLine::ForCurrentProcess();
252 if (command_line.HasSwitch(switches::kEnableDomDistiller)) {
253 dom_distiller::DomDistillerServiceFactory* dom_distiller_service_factory =
254 dom_distiller::DomDistillerServiceFactory::GetInstance();
255 // The LazyDomDistillerService deletes itself when the profile is destroyed.
256 dom_distiller::LazyDomDistillerService* lazy_service =
257 new dom_distiller::LazyDomDistillerService(
258 profile, dom_distiller_service_factory);
259 content::URLDataSource::Add(profile,
260 new dom_distiller::DomDistillerViewerSource(
261 lazy_service, chrome::kDomDistillerScheme));
265 } // namespace
267 // static
268 Profile* Profile::CreateProfile(const base::FilePath& path,
269 Delegate* delegate,
270 CreateMode create_mode) {
271 TRACE_EVENT_BEGIN1("browser",
272 "Profile::CreateProfile",
273 "profile_path",
274 path.value().c_str());
276 // Get sequenced task runner for making sure that file operations of
277 // this profile (defined by |path|) are executed in expected order
278 // (what was previously assured by the FILE thread).
279 scoped_refptr<base::SequencedTaskRunner> sequenced_task_runner =
280 JsonPrefStore::GetTaskRunnerForFile(path,
281 BrowserThread::GetBlockingPool());
282 if (create_mode == CREATE_MODE_ASYNCHRONOUS) {
283 DCHECK(delegate);
284 CreateProfileDirectory(sequenced_task_runner.get(), path);
285 } else if (create_mode == CREATE_MODE_SYNCHRONOUS) {
286 if (!base::PathExists(path)) {
287 // TODO(tc): http://b/1094718 Bad things happen if we can't write to the
288 // profile directory. We should eventually be able to run in this
289 // situation.
290 if (!base::CreateDirectory(path))
291 return NULL;
293 } else {
294 NOTREACHED();
297 return new ProfileImpl(
298 path, delegate, create_mode, sequenced_task_runner.get());
301 // static
302 int ProfileImpl::create_readme_delay_ms = 60000;
304 // static
305 const char* const ProfileImpl::kPrefExitTypeNormal = "Normal";
307 // static
308 void ProfileImpl::RegisterProfilePrefs(
309 user_prefs::PrefRegistrySyncable* registry) {
310 registry->RegisterBooleanPref(
311 prefs::kSavingBrowserHistoryDisabled,
312 false,
313 user_prefs::PrefRegistrySyncable::UNSYNCABLE_PREF);
314 registry->RegisterBooleanPref(
315 prefs::kAllowDeletingBrowserHistory,
316 true,
317 user_prefs::PrefRegistrySyncable::UNSYNCABLE_PREF);
318 registry->RegisterBooleanPref(
319 prefs::kSigninAllowed,
320 true,
321 user_prefs::PrefRegistrySyncable::UNSYNCABLE_PREF);
322 registry->RegisterBooleanPref(
323 prefs::kForceSafeSearch,
324 false,
325 user_prefs::PrefRegistrySyncable::UNSYNCABLE_PREF);
326 registry->RegisterIntegerPref(
327 prefs::kProfileAvatarIndex,
329 user_prefs::PrefRegistrySyncable::SYNCABLE_PREF);
330 registry->RegisterStringPref(prefs::kSupervisedUserId,
331 std::string(),
332 user_prefs::PrefRegistrySyncable::SYNCABLE_PREF);
333 registry->RegisterStringPref(prefs::kProfileName,
334 std::string(),
335 user_prefs::PrefRegistrySyncable::SYNCABLE_PREF);
336 registry->RegisterBooleanPref(
337 prefs::kProfileIsSupervised,
338 false,
339 user_prefs::PrefRegistrySyncable::SYNCABLE_PREF);
340 registry->RegisterStringPref(prefs::kHomePage,
341 std::string(),
342 user_prefs::PrefRegistrySyncable::SYNCABLE_PREF);
343 #if defined(ENABLE_PRINTING)
344 registry->RegisterBooleanPref(
345 prefs::kPrintingEnabled,
346 true,
347 user_prefs::PrefRegistrySyncable::UNSYNCABLE_PREF);
348 #endif
349 registry->RegisterBooleanPref(
350 prefs::kPrintPreviewDisabled,
351 false,
352 user_prefs::PrefRegistrySyncable::UNSYNCABLE_PREF);
353 registry->RegisterBooleanPref(
354 prefs::kForceEphemeralProfiles,
355 false,
356 user_prefs::PrefRegistrySyncable::UNSYNCABLE_PREF);
358 // Initialize the cache prefs.
359 registry->RegisterFilePathPref(
360 prefs::kDiskCacheDir,
361 base::FilePath(),
362 user_prefs::PrefRegistrySyncable::UNSYNCABLE_PREF);
363 registry->RegisterIntegerPref(
364 prefs::kDiskCacheSize,
366 user_prefs::PrefRegistrySyncable::UNSYNCABLE_PREF);
367 registry->RegisterIntegerPref(
368 prefs::kMediaCacheSize,
370 user_prefs::PrefRegistrySyncable::UNSYNCABLE_PREF);
372 // Deprecated. Kept around for migration.
373 registry->RegisterBooleanPref(
374 prefs::kClearSiteDataOnExit,
375 false,
376 user_prefs::PrefRegistrySyncable::SYNCABLE_PREF);
379 ProfileImpl::ProfileImpl(
380 const base::FilePath& path,
381 Delegate* delegate,
382 CreateMode create_mode,
383 base::SequencedTaskRunner* sequenced_task_runner)
384 : path_(path),
385 pref_registry_(new user_prefs::PrefRegistrySyncable),
386 io_data_(this),
387 host_content_settings_map_(NULL),
388 last_session_exit_type_(EXIT_NORMAL),
389 start_time_(Time::Now()),
390 delegate_(delegate),
391 predictor_(NULL) {
392 TRACE_EVENT0("browser", "ProfileImpl::ctor")
393 DCHECK(!path.empty()) << "Using an empty path will attempt to write " <<
394 "profile files to the root directory!";
396 #if defined(ENABLE_SESSION_SERVICE)
397 create_session_service_timer_.Start(FROM_HERE,
398 TimeDelta::FromMilliseconds(kCreateSessionServiceDelayMS), this,
399 &ProfileImpl::EnsureSessionServiceCreated);
400 #endif
402 // Determine if prefetch is enabled for this profile.
403 // If not profile_manager is present, it means we are in a unittest.
404 const CommandLine* command_line = CommandLine::ForCurrentProcess();
405 predictor_ = chrome_browser_net::Predictor::CreatePredictor(
406 !command_line->HasSwitch(switches::kDisablePreconnect),
407 g_browser_process->profile_manager() == NULL);
409 // If we are creating the profile synchronously, then we should load the
410 // policy data immediately.
411 bool force_immediate_policy_load = (create_mode == CREATE_MODE_SYNCHRONOUS);
412 #if defined(ENABLE_CONFIGURATION_POLICY)
413 policy::BrowserPolicyConnector* connector =
414 g_browser_process->browser_policy_connector();
415 schema_registry_service_ =
416 policy::SchemaRegistryServiceFactory::CreateForContext(
417 this, connector->GetChromeSchema(), connector->GetSchemaRegistry());
418 #if defined(OS_CHROMEOS)
419 cloud_policy_manager_ =
420 policy::UserCloudPolicyManagerFactoryChromeOS::CreateForProfile(
421 this, force_immediate_policy_load, sequenced_task_runner);
422 #else
423 cloud_policy_manager_ =
424 policy::UserCloudPolicyManagerFactory::CreateForOriginalBrowserContext(
425 this,
426 force_immediate_policy_load,
427 sequenced_task_runner,
428 BrowserThread::GetMessageLoopProxyForThread(BrowserThread::FILE),
429 BrowserThread::GetMessageLoopProxyForThread(BrowserThread::IO));
430 #endif
431 #endif
432 profile_policy_connector_ =
433 policy::ProfilePolicyConnectorFactory::CreateForProfile(
434 this, force_immediate_policy_load);
436 DCHECK(create_mode == CREATE_MODE_ASYNCHRONOUS ||
437 create_mode == CREATE_MODE_SYNCHRONOUS);
438 bool async_prefs = create_mode == CREATE_MODE_ASYNCHRONOUS;
440 #if defined(OS_CHROMEOS)
441 if (chromeos::ProfileHelper::IsSigninProfile(this))
442 chrome::RegisterLoginProfilePrefs(pref_registry_.get());
443 else
444 #endif
445 chrome::RegisterUserProfilePrefs(pref_registry_.get());
447 BrowserContextDependencyManager::GetInstance()->
448 RegisterProfilePrefsForServices(this, pref_registry_.get());
450 SupervisedUserSettingsService* supervised_user_settings = NULL;
451 #if defined(ENABLE_MANAGED_USERS)
452 supervised_user_settings =
453 SupervisedUserSettingsServiceFactory::GetForProfile(this);
454 supervised_user_settings->Init(
455 path_, sequenced_task_runner, create_mode == CREATE_MODE_SYNCHRONOUS);
456 #endif
458 scoped_refptr<SafeBrowsingService> safe_browsing_service(
459 g_browser_process->safe_browsing_service());
460 if (safe_browsing_service) {
461 pref_validation_delegate_ =
462 safe_browsing_service->CreatePreferenceValidationDelegate(this).Pass();
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 supervised_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::kSupervisedUserId,
509 base::Bind(&ProfileImpl::UpdateProfileSupervisedUserIdCache,
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 UpdateProfileSupervisedUserIdCache();
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_, session_cookie_mode, GetSpecialStoragePolicy(),
612 CreateDomainReliabilityMonitor());
614 #if defined(ENABLE_PLUGINS)
615 ChromePluginServiceFilter::GetInstance()->RegisterResourceContext(
616 PluginPrefs::GetForProfile(this).get(),
617 io_data_.GetResourceContextNoInit());
618 #endif
620 // Delay README creation to not impact startup performance.
621 BrowserThread::PostDelayedTask(
622 BrowserThread::FILE, FROM_HERE,
623 base::Bind(&EnsureReadmeFile, GetPath()),
624 base::TimeDelta::FromMilliseconds(create_readme_delay_ms));
626 TRACE_EVENT0("browser", "ProfileImpl::SetSaveSessionStorageOnDisk");
627 content::BrowserContext::GetDefaultStoragePartition(this)->
628 GetDOMStorageContext()->SetSaveSessionStorageOnDisk();
630 // The DomDistillerViewerSource is not a normal WebUI so it must be registered
631 // as a URLDataSource early.
632 RegisterDomDistillerViewerSource(this);
634 // Creation has been finished.
635 TRACE_EVENT_END1("browser",
636 "Profile::CreateProfile",
637 "profile_path",
638 path_.value().c_str());
640 #if defined(OS_CHROMEOS)
641 if (chromeos::LoginUtils::Get()->RestartToApplyPerSessionFlagsIfNeed(this,
642 true)) {
643 return;
645 #endif
647 if (delegate_) {
648 TRACE_EVENT0("browser", "ProfileImpl::DoFileInit:DelegateOnProfileCreated")
649 delegate_->OnProfileCreated(this, true, IsNewProfile());
652 content::NotificationService::current()->Notify(
653 chrome::NOTIFICATION_PROFILE_CREATED,
654 content::Source<Profile>(this),
655 content::NotificationService::NoDetails());
657 #if !defined(OS_CHROMEOS)
658 // Listen for bookmark model load, to bootstrap the sync service.
659 // On CrOS sync service will be initialized after sign in.
660 BookmarkModel* model = BookmarkModelFactory::GetForProfile(this);
661 model->AddObserver(new BookmarkModelLoadedObserver(this));
662 #endif
664 gcm::PushMessagingServiceImpl::InitializeForProfile(this);
667 void ProfileImpl::InitHostZoomMap() {
668 HostZoomMap* host_zoom_map = HostZoomMap::GetForBrowserContext(this);
669 host_zoom_map->SetDefaultZoomLevel(
670 prefs_->GetDouble(prefs::kDefaultZoomLevel));
672 const base::DictionaryValue* host_zoom_dictionary =
673 prefs_->GetDictionary(prefs::kPerHostZoomLevels);
674 // Careful: The returned value could be NULL if the pref has never been set.
675 if (host_zoom_dictionary != NULL) {
676 std::vector<std::string> keys_to_remove;
677 for (base::DictionaryValue::Iterator i(*host_zoom_dictionary); !i.IsAtEnd();
678 i.Advance()) {
679 const std::string& host(i.key());
680 double zoom_level = 0;
682 bool success = i.value().GetAsDouble(&zoom_level);
683 DCHECK(success);
685 // Filter out A) the empty host, B) zoom levels equal to the default; and
686 // remember them, so that we can later erase them from Prefs.
687 // Values of type A and B could have been stored due to crbug.com/364399.
688 // Values of type B could further have been stored before the default zoom
689 // level was set to its current value. In either case, SetZoomLevelForHost
690 // will ignore type B values, thus, to have consistency with HostZoomMap's
691 // internal state, these values must also be removed from Prefs.
692 if (host.empty() ||
693 content::ZoomValuesEqual(zoom_level,
694 host_zoom_map->GetDefaultZoomLevel())) {
695 keys_to_remove.push_back(host);
696 continue;
699 host_zoom_map->SetZoomLevelForHost(host, zoom_level);
702 DictionaryPrefUpdate update(prefs_.get(), prefs::kPerHostZoomLevels);
703 base::DictionaryValue* host_zoom_dictionary = update.Get();
704 for (std::vector<std::string>::const_iterator it = keys_to_remove.begin();
705 it != keys_to_remove.end(); ++it) {
706 host_zoom_dictionary->RemoveWithoutPathExpansion(*it, NULL);
710 zoom_subscription_ = host_zoom_map->AddZoomLevelChangedCallback(
711 base::Bind(&ProfileImpl::OnZoomLevelChanged, base::Unretained(this)));
714 base::FilePath ProfileImpl::last_selected_directory() {
715 return GetPrefs()->GetFilePath(prefs::kSelectFileLastDirectory);
718 void ProfileImpl::set_last_selected_directory(const base::FilePath& path) {
719 GetPrefs()->SetFilePath(prefs::kSelectFileLastDirectory, path);
722 ProfileImpl::~ProfileImpl() {
723 MaybeSendDestroyedNotification();
725 bool prefs_loaded = prefs_->GetInitializationStatus() !=
726 PrefService::INITIALIZATION_STATUS_WAITING;
728 #if defined(ENABLE_SESSION_SERVICE)
729 StopCreateSessionServiceTimer();
730 #endif
732 // Remove pref observers
733 pref_change_registrar_.RemoveAll();
735 #if defined(ENABLE_PLUGINS)
736 ChromePluginServiceFilter::GetInstance()->UnregisterResourceContext(
737 io_data_.GetResourceContextNoInit());
738 #endif
740 // Destroy OTR profile and its profile services first.
741 if (off_the_record_profile_) {
742 ProfileDestroyer::DestroyOffTheRecordProfileNow(
743 off_the_record_profile_.get());
744 } else {
745 ExtensionPrefValueMapFactory::GetForBrowserContext(this)->
746 ClearAllIncognitoSessionOnlyPreferences();
749 BrowserContextDependencyManager::GetInstance()->DestroyBrowserContextServices(
750 this);
752 if (top_sites_.get())
753 top_sites_->Shutdown();
755 if (pref_proxy_config_tracker_)
756 pref_proxy_config_tracker_->DetachFromPrefService();
758 if (host_content_settings_map_.get())
759 host_content_settings_map_->ShutdownOnUIThread();
761 // This causes the Preferences file to be written to disk.
762 if (prefs_loaded)
763 SetExitType(EXIT_NORMAL);
766 std::string ProfileImpl::GetProfileName() {
767 return GetPrefs()->GetString(prefs::kGoogleServicesUsername);
770 Profile::ProfileType ProfileImpl::GetProfileType() const {
771 return REGULAR_PROFILE;
774 base::FilePath ProfileImpl::GetPath() const {
775 return path_;
778 scoped_refptr<base::SequencedTaskRunner> ProfileImpl::GetIOTaskRunner() {
779 return JsonPrefStore::GetTaskRunnerForFile(
780 GetPath(), BrowserThread::GetBlockingPool());
783 bool ProfileImpl::IsOffTheRecord() const {
784 return false;
787 Profile* ProfileImpl::GetOffTheRecordProfile() {
788 if (!off_the_record_profile_) {
789 scoped_ptr<Profile> p(CreateOffTheRecordProfile());
790 off_the_record_profile_.swap(p);
792 content::NotificationService::current()->Notify(
793 chrome::NOTIFICATION_PROFILE_CREATED,
794 content::Source<Profile>(off_the_record_profile_.get()),
795 content::NotificationService::NoDetails());
797 return off_the_record_profile_.get();
800 void ProfileImpl::DestroyOffTheRecordProfile() {
801 off_the_record_profile_.reset();
802 ExtensionPrefValueMapFactory::GetForBrowserContext(this)->
803 ClearAllIncognitoSessionOnlyPreferences();
806 bool ProfileImpl::HasOffTheRecordProfile() {
807 return off_the_record_profile_.get() != NULL;
810 Profile* ProfileImpl::GetOriginalProfile() {
811 return this;
814 bool ProfileImpl::IsSupervised() {
815 return !GetPrefs()->GetString(prefs::kSupervisedUserId).empty();
818 ExtensionSpecialStoragePolicy*
819 ProfileImpl::GetExtensionSpecialStoragePolicy() {
820 if (!extension_special_storage_policy_.get()) {
821 TRACE_EVENT0("browser", "ProfileImpl::GetExtensionSpecialStoragePolicy")
822 extension_special_storage_policy_ = new ExtensionSpecialStoragePolicy(
823 CookieSettings::Factory::GetForProfile(this).get());
825 return extension_special_storage_policy_.get();
828 void ProfileImpl::OnPrefsLoaded(bool success) {
829 TRACE_EVENT0("browser", "ProfileImpl::OnPrefsLoaded")
830 if (!success) {
831 if (delegate_)
832 delegate_->OnProfileCreated(this, false, false);
833 return;
836 // TODO(mirandac): remove migration code after 6 months (crbug.com/69995).
837 if (g_browser_process->local_state())
838 chrome::MigrateBrowserPrefs(this, g_browser_process->local_state());
839 // TODO(ivankr): remove cleanup code eventually (crbug.com/165672).
840 chrome::MigrateUserPrefs(this);
842 // |kSessionExitType| was added after |kSessionExitedCleanly|. If the pref
843 // value is empty fallback to checking for |kSessionExitedCleanly|.
844 const std::string exit_type_pref_value(
845 prefs_->GetString(prefs::kSessionExitType));
846 if (exit_type_pref_value.empty()) {
847 last_session_exit_type_ =
848 prefs_->GetBoolean(prefs::kSessionExitedCleanly) ?
849 EXIT_NORMAL : EXIT_CRASHED;
850 } else {
851 last_session_exit_type_ =
852 SessionTypePrefValueToExitType(exit_type_pref_value);
854 // Mark the session as open.
855 prefs_->SetString(prefs::kSessionExitType, kPrefExitTypeCrashed);
856 // Force this to true in case we fallback and use it.
857 // TODO(sky): remove this in a couple of releases (m28ish).
858 prefs_->SetBoolean(prefs::kSessionExitedCleanly, true);
860 #if defined(OS_ANDROID) && defined(FULL_SAFE_BROWSING)
861 // Force safe browsing to false in the case we need to roll back for users
862 // enrolled in Finch trial before.
863 if (!SafeBrowsingService::IsEnabledByFieldTrial())
864 prefs_->SetBoolean(prefs::kSafeBrowsingEnabled, false);
865 #endif
867 g_browser_process->profile_manager()->InitProfileUserPrefs(this);
869 BrowserContextDependencyManager::GetInstance()->CreateBrowserContextServices(
870 this);
872 DCHECK(!net_pref_observer_);
874 TRACE_EVENT0("browser", "ProfileImpl::OnPrefsLoaded:NetPrefObserver")
875 net_pref_observer_.reset(new NetPrefObserver(
876 prefs_.get(),
877 prerender::PrerenderManagerFactory::GetForProfile(this),
878 predictor_));
881 chrome_prefs::SchedulePrefsFilePathVerification(path_);
883 ChromeVersionService::OnProfileLoaded(prefs_.get(), IsNewProfile());
884 DoFinalInit();
887 bool ProfileImpl::WasCreatedByVersionOrLater(const std::string& version) {
888 Version profile_version(ChromeVersionService::GetVersion(prefs_.get()));
889 Version arg_version(version);
890 return (profile_version.CompareTo(arg_version) >= 0);
893 void ProfileImpl::SetExitType(ExitType exit_type) {
894 #if defined(OS_CHROMEOS)
895 if (chromeos::ProfileHelper::IsSigninProfile(this))
896 return;
897 #endif
898 if (!prefs_)
899 return;
900 ExitType current_exit_type = SessionTypePrefValueToExitType(
901 prefs_->GetString(prefs::kSessionExitType));
902 // This may be invoked multiple times during shutdown. Only persist the value
903 // first passed in (unless it's a reset to the crash state, which happens when
904 // foregrounding the app on mobile).
905 if (exit_type == EXIT_CRASHED || current_exit_type == EXIT_CRASHED) {
906 prefs_->SetString(prefs::kSessionExitType,
907 ExitTypeToSessionTypePrefValue(exit_type));
909 // NOTE: If you change what thread this writes on, be sure and update
910 // chrome::SessionEnding().
911 prefs_->CommitPendingWrite();
915 Profile::ExitType ProfileImpl::GetLastSessionExitType() {
916 // last_session_exited_cleanly_ is set when the preferences are loaded. Force
917 // it to be set by asking for the prefs.
918 GetPrefs();
919 return last_session_exit_type_;
922 PrefService* ProfileImpl::GetPrefs() {
923 DCHECK(prefs_); // Should explicitly be initialized.
924 return prefs_.get();
927 PrefService* ProfileImpl::GetOffTheRecordPrefs() {
928 DCHECK(prefs_);
929 if (!otr_prefs_) {
930 // The new ExtensionPrefStore is ref_counted and the new PrefService
931 // stores a reference so that we do not leak memory here.
932 otr_prefs_.reset(prefs_->CreateIncognitoPrefService(
933 new ExtensionPrefStore(
934 ExtensionPrefValueMapFactory::GetForBrowserContext(this), true)));
936 return otr_prefs_.get();
939 net::URLRequestContextGetter* ProfileImpl::CreateRequestContext(
940 content::ProtocolHandlerMap* protocol_handlers,
941 content::URLRequestInterceptorScopedVector request_interceptors) {
942 return io_data_.CreateMainRequestContextGetter(
943 protocol_handlers,
944 request_interceptors.Pass(),
945 g_browser_process->local_state(),
946 g_browser_process->io_thread()).get();
949 net::URLRequestContextGetter* ProfileImpl::GetRequestContext() {
950 return GetDefaultStoragePartition(this)->GetURLRequestContext();
953 net::URLRequestContextGetter* ProfileImpl::GetRequestContextForRenderProcess(
954 int renderer_child_id) {
955 content::RenderProcessHost* rph = content::RenderProcessHost::FromID(
956 renderer_child_id);
958 return rph->GetStoragePartition()->GetURLRequestContext();
961 net::URLRequestContextGetter* ProfileImpl::GetMediaRequestContext() {
962 // Return the default media context.
963 return io_data_.GetMediaRequestContextGetter().get();
966 net::URLRequestContextGetter*
967 ProfileImpl::GetMediaRequestContextForRenderProcess(
968 int renderer_child_id) {
969 content::RenderProcessHost* rph = content::RenderProcessHost::FromID(
970 renderer_child_id);
971 content::StoragePartition* storage_partition = rph->GetStoragePartition();
973 return storage_partition->GetMediaURLRequestContext();
976 net::URLRequestContextGetter*
977 ProfileImpl::GetMediaRequestContextForStoragePartition(
978 const base::FilePath& partition_path,
979 bool in_memory) {
980 return io_data_
981 .GetIsolatedMediaRequestContextGetter(partition_path, in_memory).get();
984 content::ResourceContext* ProfileImpl::GetResourceContext() {
985 return io_data_.GetResourceContext();
988 net::URLRequestContextGetter* ProfileImpl::GetRequestContextForExtensions() {
989 return io_data_.GetExtensionsRequestContextGetter().get();
992 net::URLRequestContextGetter*
993 ProfileImpl::CreateRequestContextForStoragePartition(
994 const base::FilePath& partition_path,
995 bool in_memory,
996 content::ProtocolHandlerMap* protocol_handlers,
997 content::URLRequestInterceptorScopedVector request_interceptors) {
998 return io_data_.CreateIsolatedAppRequestContextGetter(
999 partition_path,
1000 in_memory,
1001 protocol_handlers,
1002 request_interceptors.Pass()).get();
1005 net::SSLConfigService* ProfileImpl::GetSSLConfigService() {
1006 // If ssl_config_service_manager_ is null, this typically means that some
1007 // KeyedService is trying to create a RequestContext at startup,
1008 // but SSLConfigServiceManager is not initialized until DoFinalInit() which is
1009 // invoked after all KeyedServices have been initialized (see
1010 // http://crbug.com/171406).
1011 DCHECK(ssl_config_service_manager_) <<
1012 "SSLConfigServiceManager is not initialized yet";
1013 return ssl_config_service_manager_->Get();
1016 HostContentSettingsMap* ProfileImpl::GetHostContentSettingsMap() {
1017 if (!host_content_settings_map_.get()) {
1018 host_content_settings_map_ = new HostContentSettingsMap(GetPrefs(), false);
1020 return host_content_settings_map_.get();
1023 content::BrowserPluginGuestManager* ProfileImpl::GetGuestManager() {
1024 #if defined(ENABLE_EXTENSIONS)
1025 return GuestViewManager::FromBrowserContext(this);
1026 #else
1027 return NULL;
1028 #endif
1031 DownloadManagerDelegate* ProfileImpl::GetDownloadManagerDelegate() {
1032 return DownloadServiceFactory::GetForBrowserContext(this)->
1033 GetDownloadManagerDelegate();
1036 quota::SpecialStoragePolicy* ProfileImpl::GetSpecialStoragePolicy() {
1037 return GetExtensionSpecialStoragePolicy();
1040 content::PushMessagingService* ProfileImpl::GetPushMessagingService() {
1041 return gcm::GCMProfileServiceFactory::GetForProfile(
1042 this)->push_messaging_service();
1045 bool ProfileImpl::IsSameProfile(Profile* profile) {
1046 if (profile == static_cast<Profile*>(this))
1047 return true;
1048 Profile* otr_profile = off_the_record_profile_.get();
1049 return otr_profile && profile == otr_profile;
1052 Time ProfileImpl::GetStartTime() const {
1053 return start_time_;
1056 history::TopSites* ProfileImpl::GetTopSites() {
1057 if (!top_sites_.get()) {
1058 top_sites_ = history::TopSites::Create(
1059 this, GetPath().Append(chrome::kTopSitesFilename));
1061 return top_sites_.get();
1064 history::TopSites* ProfileImpl::GetTopSitesWithoutCreating() {
1065 return top_sites_.get();
1068 void ProfileImpl::OnDefaultZoomLevelChanged() {
1069 HostZoomMap::GetForBrowserContext(this)->SetDefaultZoomLevel(
1070 pref_change_registrar_.prefs()->GetDouble(prefs::kDefaultZoomLevel));
1073 void ProfileImpl::OnZoomLevelChanged(
1074 const HostZoomMap::ZoomLevelChange& change) {
1076 if (change.mode != HostZoomMap::ZOOM_CHANGED_FOR_HOST)
1077 return;
1078 HostZoomMap* host_zoom_map = HostZoomMap::GetForBrowserContext(this);
1079 double level = change.zoom_level;
1080 DictionaryPrefUpdate update(prefs_.get(), prefs::kPerHostZoomLevels);
1081 base::DictionaryValue* host_zoom_dictionary = update.Get();
1082 if (content::ZoomValuesEqual(level, host_zoom_map->GetDefaultZoomLevel())) {
1083 host_zoom_dictionary->RemoveWithoutPathExpansion(change.host, NULL);
1084 } else {
1085 host_zoom_dictionary->SetWithoutPathExpansion(
1086 change.host, base::Value::CreateDoubleValue(level));
1090 #if defined(ENABLE_SESSION_SERVICE)
1091 void ProfileImpl::StopCreateSessionServiceTimer() {
1092 create_session_service_timer_.Stop();
1095 void ProfileImpl::EnsureSessionServiceCreated() {
1096 SessionServiceFactory::GetForProfile(this);
1098 #endif
1100 #if defined(OS_CHROMEOS)
1101 void ProfileImpl::ChangeAppLocale(
1102 const std::string& new_locale, AppLocaleChangedVia via) {
1103 if (new_locale.empty()) {
1104 NOTREACHED();
1105 return;
1107 PrefService* local_state = g_browser_process->local_state();
1108 DCHECK(local_state);
1109 if (local_state->IsManagedPreference(prefs::kApplicationLocale))
1110 return;
1111 std::string pref_locale = GetPrefs()->GetString(prefs::kApplicationLocale);
1112 bool do_update_pref = true;
1113 switch (via) {
1114 case APP_LOCALE_CHANGED_VIA_SETTINGS:
1115 case APP_LOCALE_CHANGED_VIA_REVERT: {
1116 // We keep kApplicationLocaleBackup value as a reference. In case value
1117 // of kApplicationLocale preference would change due to sync from other
1118 // device then kApplicationLocaleBackup value will trigger and allow us to
1119 // show notification about automatic locale change in LocaleChangeGuard.
1120 GetPrefs()->SetString(prefs::kApplicationLocaleBackup, new_locale);
1121 GetPrefs()->ClearPref(prefs::kApplicationLocaleAccepted);
1122 // We maintain kApplicationLocale property in both a global storage
1123 // and user's profile. Global property determines locale of login screen,
1124 // while user's profile determines his personal locale preference.
1125 break;
1127 case APP_LOCALE_CHANGED_VIA_LOGIN: {
1128 if (!pref_locale.empty()) {
1129 DCHECK(pref_locale == new_locale);
1130 std::string accepted_locale =
1131 GetPrefs()->GetString(prefs::kApplicationLocaleAccepted);
1132 if (accepted_locale == new_locale) {
1133 // If locale is accepted then we do not want to show LocaleChange
1134 // notification. This notification is triggered by different values
1135 // of kApplicationLocaleBackup and kApplicationLocale preferences,
1136 // so make them identical.
1137 GetPrefs()->SetString(prefs::kApplicationLocaleBackup, new_locale);
1138 } else {
1139 // Back up locale of login screen.
1140 std::string cur_locale = g_browser_process->GetApplicationLocale();
1141 GetPrefs()->SetString(prefs::kApplicationLocaleBackup, cur_locale);
1142 if (locale_change_guard_ == NULL)
1143 locale_change_guard_.reset(new chromeos::LocaleChangeGuard(this));
1144 locale_change_guard_->PrepareChangingLocale(cur_locale, new_locale);
1146 } else {
1147 std::string cur_locale = g_browser_process->GetApplicationLocale();
1148 std::string backup_locale =
1149 GetPrefs()->GetString(prefs::kApplicationLocaleBackup);
1150 // Profile synchronization takes time and is not completed at that
1151 // moment at first login. So we initialize locale preference in steps:
1152 // (1) first save it to temporary backup;
1153 // (2) on next login we assume that synchronization is already completed
1154 // and we may finalize initialization.
1155 GetPrefs()->SetString(prefs::kApplicationLocaleBackup, cur_locale);
1156 if (!new_locale.empty())
1157 GetPrefs()->SetString(prefs::kApplicationLocale, new_locale);
1158 else if (!backup_locale.empty())
1159 GetPrefs()->SetString(prefs::kApplicationLocale, backup_locale);
1160 do_update_pref = false;
1162 break;
1164 case APP_LOCALE_CHANGED_VIA_UNKNOWN:
1165 default: {
1166 NOTREACHED();
1167 break;
1170 if (do_update_pref)
1171 GetPrefs()->SetString(prefs::kApplicationLocale, new_locale);
1172 local_state->SetString(prefs::kApplicationLocale, new_locale);
1174 if (chromeos::UserManager::Get()->GetOwnerEmail() ==
1175 chromeos::UserManager::Get()->GetUserByProfile(this)->email())
1176 local_state->SetString(prefs::kOwnerLocale, new_locale);
1179 void ProfileImpl::OnLogin() {
1180 if (locale_change_guard_ == NULL)
1181 locale_change_guard_.reset(new chromeos::LocaleChangeGuard(this));
1182 locale_change_guard_->OnLogin();
1185 void ProfileImpl::InitChromeOSPreferences() {
1186 chromeos_preferences_.reset(new chromeos::Preferences());
1187 chromeos_preferences_->Init(
1188 PrefServiceSyncable::FromProfile(this),
1189 chromeos::UserManager::Get()->GetUserByProfile(this));
1192 #endif // defined(OS_CHROMEOS)
1194 PrefProxyConfigTracker* ProfileImpl::GetProxyConfigTracker() {
1195 if (!pref_proxy_config_tracker_)
1196 pref_proxy_config_tracker_.reset(CreateProxyConfigTracker());
1197 return pref_proxy_config_tracker_.get();
1200 chrome_browser_net::Predictor* ProfileImpl::GetNetworkPredictor() {
1201 return predictor_;
1204 DevToolsNetworkController* ProfileImpl::GetDevToolsNetworkController() {
1205 return io_data_.GetDevToolsNetworkController();
1208 void ProfileImpl::ClearNetworkingHistorySince(
1209 base::Time time,
1210 const base::Closure& completion) {
1211 io_data_.ClearNetworkingHistorySince(time, completion);
1214 GURL ProfileImpl::GetHomePage() {
1215 // --homepage overrides any preferences.
1216 const CommandLine& command_line = *CommandLine::ForCurrentProcess();
1217 if (command_line.HasSwitch(switches::kHomePage)) {
1218 // TODO(evanm): clean up usage of DIR_CURRENT.
1219 // http://code.google.com/p/chromium/issues/detail?id=60630
1220 // For now, allow this code to call getcwd().
1221 base::ThreadRestrictions::ScopedAllowIO allow_io;
1223 base::FilePath browser_directory;
1224 PathService::Get(base::DIR_CURRENT, &browser_directory);
1225 GURL home_page(url_fixer::FixupRelativeFile(
1226 browser_directory,
1227 command_line.GetSwitchValuePath(switches::kHomePage)));
1228 if (home_page.is_valid())
1229 return home_page;
1232 if (GetPrefs()->GetBoolean(prefs::kHomePageIsNewTabPage))
1233 return GURL(chrome::kChromeUINewTabURL);
1234 GURL home_page(url_fixer::FixupURL(GetPrefs()->GetString(prefs::kHomePage),
1235 std::string()));
1236 if (!home_page.is_valid())
1237 return GURL(chrome::kChromeUINewTabURL);
1238 return home_page;
1241 void ProfileImpl::UpdateProfileUserNameCache() {
1242 ProfileManager* profile_manager = g_browser_process->profile_manager();
1243 ProfileInfoCache& cache = profile_manager->GetProfileInfoCache();
1244 size_t index = cache.GetIndexOfProfileWithPath(GetPath());
1245 if (index != std::string::npos) {
1246 std::string user_name =
1247 GetPrefs()->GetString(prefs::kGoogleServicesUsername);
1248 cache.SetUserNameOfProfileAtIndex(index, base::UTF8ToUTF16(user_name));
1249 ProfileMetrics::UpdateReportedProfilesStatistics(profile_manager);
1253 void ProfileImpl::UpdateProfileSupervisedUserIdCache() {
1254 ProfileManager* profile_manager = g_browser_process->profile_manager();
1255 ProfileInfoCache& cache = profile_manager->GetProfileInfoCache();
1256 size_t index = cache.GetIndexOfProfileWithPath(GetPath());
1257 if (index != std::string::npos) {
1258 std::string supervised_user_id =
1259 GetPrefs()->GetString(prefs::kSupervisedUserId);
1260 cache.SetSupervisedUserIdOfProfileAtIndex(index, supervised_user_id);
1261 ProfileMetrics::UpdateReportedProfilesStatistics(profile_manager);
1265 void ProfileImpl::UpdateProfileNameCache() {
1266 ProfileManager* profile_manager = g_browser_process->profile_manager();
1267 ProfileInfoCache& cache = profile_manager->GetProfileInfoCache();
1268 size_t index = cache.GetIndexOfProfileWithPath(GetPath());
1269 if (index != std::string::npos) {
1270 std::string profile_name =
1271 GetPrefs()->GetString(prefs::kProfileName);
1272 cache.SetNameOfProfileAtIndex(index, base::UTF8ToUTF16(profile_name));
1276 void ProfileImpl::UpdateProfileAvatarCache() {
1277 ProfileManager* profile_manager = g_browser_process->profile_manager();
1278 ProfileInfoCache& cache = profile_manager->GetProfileInfoCache();
1279 size_t index = cache.GetIndexOfProfileWithPath(GetPath());
1280 if (index != std::string::npos) {
1281 size_t avatar_index =
1282 GetPrefs()->GetInteger(prefs::kProfileAvatarIndex);
1283 cache.SetAvatarIconOfProfileAtIndex(index, avatar_index);
1287 void ProfileImpl::UpdateProfileIsEphemeralCache() {
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 bool is_ephemeral = GetPrefs()->GetBoolean(prefs::kForceEphemeralProfiles);
1293 cache.SetProfileIsEphemeralAtIndex(index, is_ephemeral);
1297 // Gets the cache parameters from the command line. If |is_media_context| is
1298 // set to true then settings for the media context type is what we need,
1299 // |cache_path| will be set to the user provided path, or will not be touched if
1300 // there is not an argument. |max_size| will be the user provided value or zero
1301 // by default.
1302 void ProfileImpl::GetCacheParameters(bool is_media_context,
1303 base::FilePath* cache_path,
1304 int* max_size) {
1305 DCHECK(cache_path);
1306 DCHECK(max_size);
1307 base::FilePath path(prefs_->GetFilePath(prefs::kDiskCacheDir));
1308 if (!path.empty())
1309 *cache_path = path;
1310 *max_size = is_media_context ? prefs_->GetInteger(prefs::kMediaCacheSize) :
1311 prefs_->GetInteger(prefs::kDiskCacheSize);
1314 PrefProxyConfigTracker* ProfileImpl::CreateProxyConfigTracker() {
1315 #if defined(OS_CHROMEOS)
1316 if (chromeos::ProfileHelper::IsSigninProfile(this)) {
1317 return ProxyServiceFactory::CreatePrefProxyConfigTrackerOfLocalState(
1318 g_browser_process->local_state());
1320 #endif // defined(OS_CHROMEOS)
1321 return ProxyServiceFactory::CreatePrefProxyConfigTrackerOfProfile(
1322 GetPrefs(), g_browser_process->local_state());
1325 scoped_ptr<domain_reliability::DomainReliabilityMonitor>
1326 ProfileImpl::CreateDomainReliabilityMonitor() {
1327 domain_reliability::DomainReliabilityService* service =
1328 domain_reliability::DomainReliabilityServiceFactory::GetInstance()->
1329 GetForBrowserContext(this);
1330 if (!service)
1331 return scoped_ptr<domain_reliability::DomainReliabilityMonitor>();
1333 return service->CreateMonitor(
1334 BrowserThread::GetMessageLoopProxyForThread(BrowserThread::IO));