Enterprise policy: Ignore the deprecated ForceSafeSearch if ForceGoogleSafeSearch...
[chromium-blink-merge.git] / chrome / browser / profiles / profile_impl.cc
blob1ddc4fc3f2c97e2869b59622598ef57a8d0f9310
1 // Copyright (c) 2012 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 #include "chrome/browser/profiles/profile_impl.h"
7 #include <vector>
9 #include "base/bind.h"
10 #include "base/callback.h"
11 #include "base/command_line.h"
12 #include "base/compiler_specific.h"
13 #include "base/environment.h"
14 #include "base/files/file_path.h"
15 #include "base/files/file_util.h"
16 #include "base/memory/scoped_ptr.h"
17 #include "base/memory/weak_ptr.h"
18 #include "base/metrics/histogram_macros.h"
19 #include "base/path_service.h"
20 #include "base/prefs/json_pref_store.h"
21 #include "base/prefs/scoped_user_pref_update.h"
22 #include "base/strings/string_number_conversions.h"
23 #include "base/strings/string_util.h"
24 #include "base/strings/stringprintf.h"
25 #include "base/strings/utf_string_conversions.h"
26 #include "base/synchronization/waitable_event.h"
27 #include "base/threading/sequenced_worker_pool.h"
28 #include "base/trace_event/trace_event.h"
29 #include "base/version.h"
30 #include "chrome/browser/autocomplete/autocomplete_classifier.h"
31 #include "chrome/browser/autocomplete/shortcuts_backend.h"
32 #include "chrome/browser/background/background_contents_service_factory.h"
33 #include "chrome/browser/bookmarks/bookmark_model_factory.h"
34 #include "chrome/browser/browser_process.h"
35 #include "chrome/browser/chrome_notification_types.h"
36 #include "chrome/browser/content_settings/cookie_settings.h"
37 #include "chrome/browser/dom_distiller/profile_utils.h"
38 #include "chrome/browser/domain_reliability/service_factory.h"
39 #include "chrome/browser/download/chrome_download_manager_delegate.h"
40 #include "chrome/browser/download/download_service.h"
41 #include "chrome/browser/download/download_service_factory.h"
42 #include "chrome/browser/net/net_pref_observer.h"
43 #include "chrome/browser/net/predictor.h"
44 #include "chrome/browser/net/pref_proxy_config_tracker.h"
45 #include "chrome/browser/net/proxy_service_factory.h"
46 #include "chrome/browser/net/ssl_config_service_manager.h"
47 #include "chrome/browser/permissions/permission_manager.h"
48 #include "chrome/browser/permissions/permission_manager_factory.h"
49 #include "chrome/browser/plugins/chrome_plugin_service_filter.h"
50 #include "chrome/browser/plugins/plugin_prefs.h"
51 #include "chrome/browser/policy/profile_policy_connector.h"
52 #include "chrome/browser/policy/profile_policy_connector_factory.h"
53 #include "chrome/browser/prefs/browser_prefs.h"
54 #include "chrome/browser/prefs/chrome_pref_service_factory.h"
55 #include "chrome/browser/prefs/pref_service_syncable.h"
56 #include "chrome/browser/prefs/tracked/tracked_preference_validation_delegate.h"
57 #include "chrome/browser/prerender/prerender_manager_factory.h"
58 #include "chrome/browser/profiles/bookmark_model_loaded_observer.h"
59 #include "chrome/browser/profiles/chrome_version_service.h"
60 #include "chrome/browser/profiles/gaia_info_update_service_factory.h"
61 #include "chrome/browser/profiles/profile_destroyer.h"
62 #include "chrome/browser/profiles/profile_info_cache.h"
63 #include "chrome/browser/profiles/profile_manager.h"
64 #include "chrome/browser/profiles/profile_metrics.h"
65 #include "chrome/browser/push_messaging/push_messaging_service_factory.h"
66 #include "chrome/browser/push_messaging/push_messaging_service_impl.h"
67 #include "chrome/browser/safe_browsing/safe_browsing_service.h"
68 #include "chrome/browser/services/gcm/gcm_profile_service.h"
69 #include "chrome/browser/sessions/session_service_factory.h"
70 #include "chrome/browser/signin/signin_manager_factory.h"
71 #include "chrome/browser/signin/signin_ui_util.h"
72 #include "chrome/browser/ssl/chrome_ssl_host_state_delegate.h"
73 #include "chrome/browser/ssl/chrome_ssl_host_state_delegate_factory.h"
74 #include "chrome/browser/ui/startup/startup_browser_creator.h"
75 #include "chrome/browser/ui/zoom/chrome_zoom_level_prefs.h"
76 #include "chrome/common/chrome_constants.h"
77 #include "chrome/common/chrome_paths_internal.h"
78 #include "chrome/common/chrome_switches.h"
79 #include "chrome/common/chrome_version_info.h"
80 #include "chrome/common/pref_names.h"
81 #include "chrome/common/url_constants.h"
82 #include "chrome/grit/chromium_strings.h"
83 #include "components/bookmarks/browser/bookmark_model.h"
84 #include "components/content_settings/core/browser/host_content_settings_map.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/signin/core/browser/signin_manager.h"
91 #include "components/startup_metric_utils/startup_metric_utils.h"
92 #include "components/ui/zoom/zoom_event_manager.h"
93 #include "components/url_fixer/url_fixer.h"
94 #include "components/user_prefs/user_prefs.h"
95 #include "content/public/browser/browser_thread.h"
96 #include "content/public/browser/dom_storage_context.h"
97 #include "content/public/browser/notification_service.h"
98 #include "content/public/browser/render_process_host.h"
99 #include "content/public/browser/storage_partition.h"
100 #include "content/public/browser/url_data_source.h"
101 #include "content/public/browser/user_metrics.h"
102 #include "content/public/common/content_constants.h"
103 #include "content/public/common/page_zoom.h"
104 #include "ui/base/l10n/l10n_util.h"
106 #if defined(OS_ANDROID)
107 #include "chrome/browser/media/protected_media_identifier_permission_context.h"
108 #include "chrome/browser/media/protected_media_identifier_permission_context_factory.h"
109 #endif
111 #if defined(OS_CHROMEOS)
112 #include "chrome/browser/chromeos/locale_change_guard.h"
113 #include "chrome/browser/chromeos/preferences.h"
114 #include "chrome/browser/chromeos/profiles/profile_helper.h"
115 #include "components/user_manager/user_manager.h"
116 #endif
118 #if defined(ENABLE_BACKGROUND)
119 #include "chrome/browser/background/background_mode_manager.h"
120 #endif
122 #if defined(ENABLE_CONFIGURATION_POLICY)
123 #include "chrome/browser/policy/schema_registry_service.h"
124 #include "chrome/browser/policy/schema_registry_service_factory.h"
125 #include "components/policy/core/browser/browser_policy_connector.h"
126 #if defined(OS_CHROMEOS)
127 #include "chrome/browser/chromeos/login/session/user_session_manager.h"
128 #include "chrome/browser/chromeos/policy/user_cloud_policy_manager_chromeos.h"
129 #include "chrome/browser/chromeos/policy/user_cloud_policy_manager_factory_chromeos.h"
130 #else
131 #include "chrome/browser/policy/cloud/user_cloud_policy_manager_factory.h"
132 #include "components/policy/core/common/cloud/user_cloud_policy_manager.h"
133 #endif
134 #endif
136 #if defined(ENABLE_EXTENSIONS)
137 #include "chrome/browser/extensions/extension_service.h"
138 #include "chrome/browser/extensions/extension_special_storage_policy.h"
139 #include "chrome/browser/ui/webui/extensions/extension_icon_source.h"
140 #include "extensions/browser/extension_pref_store.h"
141 #include "extensions/browser/extension_pref_value_map.h"
142 #include "extensions/browser/extension_pref_value_map_factory.h"
143 #include "extensions/browser/extension_system.h"
144 #include "extensions/browser/guest_view/guest_view_manager.h"
145 #endif
147 #if defined(ENABLE_SUPERVISED_USERS)
148 #include "chrome/browser/content_settings/content_settings_supervised_provider.h"
149 #include "chrome/browser/supervised_user/supervised_user_constants.h"
150 #include "chrome/browser/supervised_user/supervised_user_settings_service.h"
151 #include "chrome/browser/supervised_user/supervised_user_settings_service_factory.h"
152 #endif
154 using base::Time;
155 using base::TimeDelta;
156 using base::UserMetricsAction;
157 using bookmarks::BookmarkModel;
158 using content::BrowserThread;
159 using content::DownloadManagerDelegate;
161 namespace {
163 #if defined(ENABLE_SESSION_SERVICE)
164 // Delay, in milliseconds, before we explicitly create the SessionService.
165 const int kCreateSessionServiceDelayMS = 500;
166 #endif
168 // Text content of README file created in each profile directory. Both %s
169 // placeholders must contain the product name. This is not localizable and hence
170 // not in resources.
171 const char kReadmeText[] =
172 "%s settings and storage represent user-selected preferences and "
173 "information and MUST not be extracted, overwritten or modified except "
174 "through %s defined APIs.";
176 // Value written to prefs for EXIT_CRASHED and EXIT_SESSION_ENDED.
177 const char kPrefExitTypeCrashed[] = "Crashed";
178 const char kPrefExitTypeSessionEnded[] = "SessionEnded";
180 // Helper method needed because PostTask cannot currently take a Callback
181 // function with non-void return type.
182 void CreateDirectoryAndSignal(const base::FilePath& path,
183 base::WaitableEvent* done_creating) {
184 DVLOG(1) << "Creating directory " << path.value();
185 base::CreateDirectory(path);
186 done_creating->Signal();
189 // Task that blocks the FILE thread until CreateDirectoryAndSignal() finishes on
190 // blocking I/O pool.
191 void BlockFileThreadOnDirectoryCreate(base::WaitableEvent* done_creating) {
192 done_creating->Wait();
195 // Initiates creation of profile directory on |sequenced_task_runner| and
196 // ensures that FILE thread is blocked until that operation finishes.
197 void CreateProfileDirectory(base::SequencedTaskRunner* sequenced_task_runner,
198 const base::FilePath& path) {
199 base::WaitableEvent* done_creating = new base::WaitableEvent(false, false);
200 sequenced_task_runner->PostTask(FROM_HERE,
201 base::Bind(&CreateDirectoryAndSignal,
202 path,
203 done_creating));
204 // Block the FILE thread until directory is created on I/O pool to make sure
205 // that we don't attempt any operation until that part completes.
206 BrowserThread::PostTask(
207 BrowserThread::FILE, FROM_HERE,
208 base::Bind(&BlockFileThreadOnDirectoryCreate,
209 base::Owned(done_creating)));
212 base::FilePath GetCachePath(const base::FilePath& base) {
213 return base.Append(chrome::kCacheDirname);
216 base::FilePath GetMediaCachePath(const base::FilePath& base) {
217 return base.Append(chrome::kMediaCacheDirname);
220 void EnsureReadmeFile(const base::FilePath& base) {
221 base::FilePath readme_path = base.Append(chrome::kReadmeFilename);
222 if (base::PathExists(readme_path))
223 return;
224 std::string product_name = l10n_util::GetStringUTF8(IDS_PRODUCT_NAME);
225 std::string readme_text = base::StringPrintf(
226 kReadmeText, product_name.c_str(), product_name.c_str());
227 if (base::WriteFile(readme_path, readme_text.data(), readme_text.size()) ==
228 -1) {
229 LOG(ERROR) << "Could not create README file.";
233 // Converts the kSessionExitedCleanly pref to the corresponding EXIT_TYPE.
234 Profile::ExitType SessionTypePrefValueToExitType(const std::string& value) {
235 if (value == kPrefExitTypeSessionEnded)
236 return Profile::EXIT_SESSION_ENDED;
237 if (value == kPrefExitTypeCrashed)
238 return Profile::EXIT_CRASHED;
239 return Profile::EXIT_NORMAL;
242 // Converts an ExitType into a string that is written to prefs.
243 std::string ExitTypeToSessionTypePrefValue(Profile::ExitType type) {
244 switch (type) {
245 case Profile::EXIT_NORMAL:
246 return ProfileImpl::kPrefExitTypeNormal;
247 case Profile::EXIT_SESSION_ENDED:
248 return kPrefExitTypeSessionEnded;
249 case Profile::EXIT_CRASHED:
250 return kPrefExitTypeCrashed;
252 NOTREACHED();
253 return std::string();
256 PrefStore* CreateExtensionPrefStore(Profile* profile,
257 bool incognito_pref_store) {
258 #if defined(ENABLE_EXTENSIONS)
259 return new ExtensionPrefStore(
260 ExtensionPrefValueMapFactory::GetForBrowserContext(profile),
261 incognito_pref_store);
262 #else
263 return NULL;
264 #endif
267 } // namespace
269 // static
270 Profile* Profile::CreateProfile(const base::FilePath& path,
271 Delegate* delegate,
272 CreateMode create_mode) {
273 TRACE_EVENT1("browser,startup",
274 "Profile::CreateProfile",
275 "profile_path",
276 path.AsUTF8Unsafe());
278 // Get sequenced task runner for making sure that file operations of
279 // this profile (defined by |path|) are executed in expected order
280 // (what was previously assured by the FILE thread).
281 scoped_refptr<base::SequencedTaskRunner> sequenced_task_runner =
282 JsonPrefStore::GetTaskRunnerForFile(path,
283 BrowserThread::GetBlockingPool());
284 if (create_mode == CREATE_MODE_ASYNCHRONOUS) {
285 DCHECK(delegate);
286 CreateProfileDirectory(sequenced_task_runner.get(), path);
287 } else if (create_mode == CREATE_MODE_SYNCHRONOUS) {
288 if (!base::PathExists(path)) {
289 // TODO(rogerta): http://crbug/160553 - Bad things happen if we can't
290 // write to the profile directory. We should eventually be able to run in
291 // this situation.
292 if (!base::CreateDirectory(path))
293 return NULL;
295 } else {
296 NOTREACHED();
299 return new ProfileImpl(
300 path, delegate, create_mode, sequenced_task_runner.get());
303 // static
304 int ProfileImpl::create_readme_delay_ms = 60000;
306 // static
307 const char* const ProfileImpl::kPrefExitTypeNormal = "Normal";
309 // static
310 void ProfileImpl::RegisterProfilePrefs(
311 user_prefs::PrefRegistrySyncable* registry) {
312 registry->RegisterBooleanPref(
313 prefs::kSavingBrowserHistoryDisabled,
314 false,
315 user_prefs::PrefRegistrySyncable::UNSYNCABLE_PREF);
316 registry->RegisterBooleanPref(
317 prefs::kAllowDeletingBrowserHistory,
318 true,
319 user_prefs::PrefRegistrySyncable::UNSYNCABLE_PREF);
320 registry->RegisterBooleanPref(
321 prefs::kSigninAllowed,
322 true,
323 user_prefs::PrefRegistrySyncable::UNSYNCABLE_PREF);
324 registry->RegisterBooleanPref(
325 prefs::kForceGoogleSafeSearch,
326 false,
327 user_prefs::PrefRegistrySyncable::UNSYNCABLE_PREF);
328 registry->RegisterBooleanPref(
329 prefs::kForceYouTubeSafetyMode,
330 false,
331 user_prefs::PrefRegistrySyncable::UNSYNCABLE_PREF);
332 registry->RegisterBooleanPref(
333 prefs::kRecordHistory,
334 false,
335 user_prefs::PrefRegistrySyncable::UNSYNCABLE_PREF);
336 registry->RegisterIntegerPref(
337 prefs::kProfileAvatarIndex,
339 user_prefs::PrefRegistrySyncable::SYNCABLE_PREF);
340 // Whether a profile is using an avatar without having explicitely chosen it
341 // (i.e. was assigned by default by legacy profile creation).
342 registry->RegisterBooleanPref(
343 prefs::kProfileUsingDefaultAvatar,
344 true,
345 user_prefs::PrefRegistrySyncable::SYNCABLE_PREF);
346 registry->RegisterBooleanPref(
347 prefs::kProfileUsingGAIAAvatar,
348 false,
349 user_prefs::PrefRegistrySyncable::SYNCABLE_PREF);
350 // Whether a profile is using a default avatar name (eg. Pickles or Person 1).
351 registry->RegisterBooleanPref(
352 prefs::kProfileUsingDefaultName,
353 true,
354 user_prefs::PrefRegistrySyncable::SYNCABLE_PREF);
355 registry->RegisterStringPref(
356 prefs::kSupervisedUserId,
357 std::string(),
358 user_prefs::PrefRegistrySyncable::UNSYNCABLE_PREF);
359 registry->RegisterStringPref(prefs::kProfileName,
360 std::string(),
361 user_prefs::PrefRegistrySyncable::SYNCABLE_PREF);
362 registry->RegisterStringPref(prefs::kHomePage,
363 std::string(),
364 user_prefs::PrefRegistrySyncable::SYNCABLE_PREF);
365 #if defined(ENABLE_PRINTING)
366 registry->RegisterBooleanPref(
367 prefs::kPrintingEnabled,
368 true,
369 user_prefs::PrefRegistrySyncable::UNSYNCABLE_PREF);
370 #endif
371 registry->RegisterBooleanPref(
372 prefs::kPrintPreviewDisabled,
373 false,
374 user_prefs::PrefRegistrySyncable::UNSYNCABLE_PREF);
375 registry->RegisterBooleanPref(
376 prefs::kForceEphemeralProfiles,
377 false,
378 user_prefs::PrefRegistrySyncable::UNSYNCABLE_PREF);
380 // Initialize the cache prefs.
381 registry->RegisterFilePathPref(
382 prefs::kDiskCacheDir,
383 base::FilePath(),
384 user_prefs::PrefRegistrySyncable::UNSYNCABLE_PREF);
385 registry->RegisterIntegerPref(
386 prefs::kDiskCacheSize,
388 user_prefs::PrefRegistrySyncable::UNSYNCABLE_PREF);
389 registry->RegisterIntegerPref(
390 prefs::kMediaCacheSize,
392 user_prefs::PrefRegistrySyncable::UNSYNCABLE_PREF);
394 // Deprecated. Kept around for migration.
395 registry->RegisterBooleanPref(
396 prefs::kClearSiteDataOnExit,
397 false,
398 user_prefs::PrefRegistrySyncable::SYNCABLE_PREF);
401 ProfileImpl::ProfileImpl(
402 const base::FilePath& path,
403 Delegate* delegate,
404 CreateMode create_mode,
405 base::SequencedTaskRunner* sequenced_task_runner)
406 : path_(path),
407 pref_registry_(new user_prefs::PrefRegistrySyncable),
408 io_data_(this),
409 host_content_settings_map_(NULL),
410 last_session_exit_type_(EXIT_NORMAL),
411 start_time_(Time::Now()),
412 delegate_(delegate),
413 predictor_(NULL) {
414 TRACE_EVENT0("browser,startup", "ProfileImpl::ctor")
415 DCHECK(!path.empty()) << "Using an empty path will attempt to write " <<
416 "profile files to the root directory!";
418 #if defined(ENABLE_SESSION_SERVICE)
419 create_session_service_timer_.Start(FROM_HERE,
420 TimeDelta::FromMilliseconds(kCreateSessionServiceDelayMS), this,
421 &ProfileImpl::EnsureSessionServiceCreated);
422 #endif
424 set_is_guest_profile(path == ProfileManager::GetGuestProfilePath());
425 set_is_system_profile(path == ProfileManager::GetSystemProfilePath());
427 // Determine if prefetch is enabled for this profile.
428 // If not profile_manager is present, it means we are in a unittest.
429 const base::CommandLine* command_line =
430 base::CommandLine::ForCurrentProcess();
431 predictor_ = chrome_browser_net::Predictor::CreatePredictor(
432 !command_line->HasSwitch(switches::kDisablePreconnect),
433 !command_line->HasSwitch(switches::kDnsPrefetchDisable),
434 g_browser_process->profile_manager() == NULL);
436 // If we are creating the profile synchronously, then we should load the
437 // policy data immediately.
438 bool force_immediate_policy_load = (create_mode == CREATE_MODE_SYNCHRONOUS);
439 #if defined(ENABLE_CONFIGURATION_POLICY)
440 policy::BrowserPolicyConnector* connector =
441 g_browser_process->browser_policy_connector();
442 schema_registry_service_ =
443 policy::SchemaRegistryServiceFactory::CreateForContext(
444 this, connector->GetChromeSchema(), connector->GetSchemaRegistry());
445 #if defined(OS_CHROMEOS)
446 cloud_policy_manager_ =
447 policy::UserCloudPolicyManagerFactoryChromeOS::CreateForProfile(
448 this, force_immediate_policy_load, sequenced_task_runner);
449 #else
450 cloud_policy_manager_ =
451 policy::UserCloudPolicyManagerFactory::CreateForOriginalBrowserContext(
452 this,
453 force_immediate_policy_load,
454 sequenced_task_runner,
455 BrowserThread::GetMessageLoopProxyForThread(BrowserThread::FILE),
456 BrowserThread::GetMessageLoopProxyForThread(BrowserThread::IO));
457 #endif
458 #endif
459 profile_policy_connector_ =
460 policy::ProfilePolicyConnectorFactory::CreateForBrowserContext(
461 this, force_immediate_policy_load);
463 DCHECK(create_mode == CREATE_MODE_ASYNCHRONOUS ||
464 create_mode == CREATE_MODE_SYNCHRONOUS);
465 bool async_prefs = create_mode == CREATE_MODE_ASYNCHRONOUS;
467 #if defined(OS_CHROMEOS)
468 if (chromeos::ProfileHelper::IsSigninProfile(this))
469 chrome::RegisterLoginProfilePrefs(pref_registry_.get());
470 else
471 #endif
472 chrome::RegisterUserProfilePrefs(pref_registry_.get());
474 BrowserContextDependencyManager::GetInstance()->
475 RegisterProfilePrefsForServices(this, pref_registry_.get());
477 SupervisedUserSettingsService* supervised_user_settings = nullptr;
478 #if defined(ENABLE_SUPERVISED_USERS)
479 supervised_user_settings =
480 SupervisedUserSettingsServiceFactory::GetForProfile(this);
481 supervised_user_settings->Init(
482 path_, sequenced_task_runner, create_mode == CREATE_MODE_SYNCHRONOUS);
483 #endif
485 scoped_refptr<SafeBrowsingService> safe_browsing_service(
486 g_browser_process->safe_browsing_service());
487 if (safe_browsing_service.get()) {
488 pref_validation_delegate_ =
489 safe_browsing_service->CreatePreferenceValidationDelegate(this).Pass();
493 // On startup, preference loading is always synchronous so a scoped timer
494 // will work here.
495 startup_metric_utils::ScopedSlowStartupUMA
496 scoped_timer("Startup.SlowStartupPreferenceLoading");
497 prefs_ = chrome_prefs::CreateProfilePrefs(
498 path_,
499 sequenced_task_runner,
500 pref_validation_delegate_.get(),
501 profile_policy_connector_->policy_service(),
502 supervised_user_settings,
503 CreateExtensionPrefStore(this, false),
504 pref_registry_,
505 async_prefs).Pass();
506 // Register on BrowserContext.
507 user_prefs::UserPrefs::Set(this, prefs_.get());
510 startup_metric_utils::ScopedSlowStartupUMA
511 scoped_timer("Startup.SlowStartupFinalProfileInit");
512 if (async_prefs) {
513 // Wait for the notification that prefs has been loaded
514 // (successfully or not). Note that we can use base::Unretained
515 // because the PrefService is owned by this class and lives on
516 // the same thread.
517 prefs_->AddPrefInitObserver(base::Bind(&ProfileImpl::OnPrefsLoaded,
518 base::Unretained(this)));
519 } else {
520 // Prefs were loaded synchronously so we can continue directly.
521 OnPrefsLoaded(true);
525 void ProfileImpl::DoFinalInit() {
526 TRACE_EVENT0("browser", "ProfileImpl::DoFinalInit")
527 SCOPED_UMA_HISTOGRAM_TIMER("Profile.ProfileImplDoFinalInit");
529 PrefService* prefs = GetPrefs();
530 pref_change_registrar_.Init(prefs);
531 pref_change_registrar_.Add(
532 prefs::kSupervisedUserId,
533 base::Bind(&ProfileImpl::UpdateProfileSupervisedUserIdCache,
534 base::Unretained(this)));
536 // Changes in the profile avatar.
537 pref_change_registrar_.Add(
538 prefs::kProfileAvatarIndex,
539 base::Bind(&ProfileImpl::UpdateProfileAvatarCache,
540 base::Unretained(this)));
541 pref_change_registrar_.Add(
542 prefs::kProfileUsingDefaultAvatar,
543 base::Bind(&ProfileImpl::UpdateProfileAvatarCache,
544 base::Unretained(this)));
545 pref_change_registrar_.Add(
546 prefs::kProfileUsingGAIAAvatar,
547 base::Bind(&ProfileImpl::UpdateProfileAvatarCache,
548 base::Unretained(this)));
550 // Changes in the profile name.
551 pref_change_registrar_.Add(
552 prefs::kProfileUsingDefaultName,
553 base::Bind(&ProfileImpl::UpdateProfileNameCache,
554 base::Unretained(this)));
555 pref_change_registrar_.Add(
556 prefs::kProfileName,
557 base::Bind(&ProfileImpl::UpdateProfileNameCache,
558 base::Unretained(this)));
560 pref_change_registrar_.Add(
561 prefs::kForceEphemeralProfiles,
562 base::Bind(&ProfileImpl::UpdateProfileIsEphemeralCache,
563 base::Unretained(this)));
565 // It would be nice to use PathService for fetching this directory, but
566 // the cache directory depends on the profile directory, which isn't available
567 // to PathService.
568 chrome::GetUserCacheDirectory(path_, &base_cache_path_);
569 // Always create the cache directory asynchronously.
570 scoped_refptr<base::SequencedTaskRunner> sequenced_task_runner =
571 JsonPrefStore::GetTaskRunnerForFile(base_cache_path_,
572 BrowserThread::GetBlockingPool());
573 CreateProfileDirectory(sequenced_task_runner.get(), base_cache_path_);
575 // Initialize components that depend on the current value.
576 UpdateProfileSupervisedUserIdCache();
577 UpdateProfileIsEphemeralCache();
578 GAIAInfoUpdateServiceFactory::GetForProfile(this);
580 PrefService* local_state = g_browser_process->local_state();
581 ssl_config_service_manager_.reset(
582 SSLConfigServiceManager::CreateDefaultManager(local_state));
584 #if defined(ENABLE_BACKGROUND)
585 // Initialize the BackgroundModeManager - this has to be done here before
586 // InitExtensions() is called because it relies on receiving notifications
587 // when extensions are loaded. BackgroundModeManager is not needed under
588 // ChromeOS because Chrome is always running, no need for special keep-alive
589 // or launch-on-startup support unless kKeepAliveForTest is set.
590 bool init_background_mode_manager = true;
591 #if defined(OS_CHROMEOS)
592 if (!base::CommandLine::ForCurrentProcess()->HasSwitch(
593 switches::kKeepAliveForTest))
594 init_background_mode_manager = false;
595 #endif
596 if (init_background_mode_manager) {
597 if (g_browser_process->background_mode_manager())
598 g_browser_process->background_mode_manager()->RegisterProfile(this);
600 #endif // defined(ENABLE_BACKGROUND)
602 base::FilePath cookie_path = GetPath();
603 cookie_path = cookie_path.Append(chrome::kCookieFilename);
604 base::FilePath channel_id_path = GetPath();
605 channel_id_path = channel_id_path.Append(chrome::kChannelIDFilename);
606 base::FilePath cache_path = base_cache_path_;
607 int cache_max_size;
608 GetCacheParameters(false, &cache_path, &cache_max_size);
609 cache_path = GetCachePath(cache_path);
611 base::FilePath media_cache_path = base_cache_path_;
612 int media_cache_max_size;
613 GetCacheParameters(true, &media_cache_path, &media_cache_max_size);
614 media_cache_path = GetMediaCachePath(media_cache_path);
616 base::FilePath extensions_cookie_path = GetPath();
617 extensions_cookie_path =
618 extensions_cookie_path.Append(chrome::kExtensionsCookieFilename);
620 #if defined(OS_ANDROID)
621 SessionStartupPref::Type startup_pref_type =
622 SessionStartupPref::GetDefaultStartupType();
623 #else
624 SessionStartupPref::Type startup_pref_type =
625 StartupBrowserCreator::GetSessionStartupPref(
626 *base::CommandLine::ForCurrentProcess(), this).type;
627 #endif
628 content::CookieStoreConfig::SessionCookieMode session_cookie_mode =
629 content::CookieStoreConfig::PERSISTANT_SESSION_COOKIES;
630 if (GetLastSessionExitType() == Profile::EXIT_CRASHED ||
631 startup_pref_type == SessionStartupPref::LAST) {
632 session_cookie_mode = content::CookieStoreConfig::RESTORED_SESSION_COOKIES;
635 // Make sure we initialize the ProfileIOData after everything else has been
636 // initialized that we might be reading from the IO thread.
638 io_data_.Init(cookie_path, channel_id_path, cache_path,
639 cache_max_size, media_cache_path, media_cache_max_size,
640 extensions_cookie_path, GetPath(), predictor_,
641 session_cookie_mode, GetSpecialStoragePolicy(),
642 CreateDomainReliabilityMonitor(local_state));
644 #if defined(ENABLE_PLUGINS)
645 ChromePluginServiceFilter::GetInstance()->RegisterResourceContext(
646 PluginPrefs::GetForProfile(this).get(),
647 io_data_.GetResourceContextNoInit());
648 #endif
650 // Delay README creation to not impact startup performance.
651 BrowserThread::PostDelayedTask(
652 BrowserThread::FILE, FROM_HERE,
653 base::Bind(&EnsureReadmeFile, GetPath()),
654 base::TimeDelta::FromMilliseconds(create_readme_delay_ms));
656 TRACE_EVENT0("browser", "ProfileImpl::SetSaveSessionStorageOnDisk");
657 content::BrowserContext::GetDefaultStoragePartition(this)->
658 GetDOMStorageContext()->SetSaveSessionStorageOnDisk();
660 // TODO(wjmaclean): Remove this. crbug.com/420643
661 chrome::MigrateProfileZoomLevelPrefs(this);
663 // The DomDistillerViewerSource is not a normal WebUI so it must be registered
664 // as a URLDataSource early.
665 RegisterDomDistillerViewerSource(this);
667 #if defined(OS_CHROMEOS)
668 if (chromeos::UserSessionManager::GetInstance()
669 ->RestartToApplyPerSessionFlagsIfNeed(this, true)) {
670 return;
672 #endif
674 if (delegate_) {
675 TRACE_EVENT0("browser", "ProfileImpl::DoFileInit:DelegateOnProfileCreated")
676 delegate_->OnProfileCreated(this, true, IsNewProfile());
680 SCOPED_UMA_HISTOGRAM_TIMER("Profile.NotifyProfileCreatedTime");
681 content::NotificationService::current()->Notify(
682 chrome::NOTIFICATION_PROFILE_CREATED,
683 content::Source<Profile>(this),
684 content::NotificationService::NoDetails());
686 #if !defined(OS_CHROMEOS)
687 // Listen for bookmark model load, to bootstrap the sync service.
688 // On CrOS sync service will be initialized after sign in.
689 BookmarkModel* model = BookmarkModelFactory::GetForProfile(this);
690 model->AddObserver(new BookmarkModelLoadedObserver(this));
691 #endif
693 PushMessagingServiceImpl::InitializeForProfile(this);
695 #if !defined(OS_ANDROID) && !defined(OS_CHROMEOS) && !defined(OS_IOS)
696 signin_ui_util::InitializePrefsForProfile(this);
697 #endif
700 base::FilePath ProfileImpl::last_selected_directory() {
701 return GetPrefs()->GetFilePath(prefs::kSelectFileLastDirectory);
704 void ProfileImpl::set_last_selected_directory(const base::FilePath& path) {
705 GetPrefs()->SetFilePath(prefs::kSelectFileLastDirectory, path);
708 ProfileImpl::~ProfileImpl() {
709 MaybeSendDestroyedNotification();
711 bool prefs_loaded = prefs_->GetInitializationStatus() !=
712 PrefService::INITIALIZATION_STATUS_WAITING;
714 #if defined(ENABLE_SESSION_SERVICE)
715 StopCreateSessionServiceTimer();
716 #endif
718 // Remove pref observers
719 pref_change_registrar_.RemoveAll();
721 #if defined(ENABLE_PLUGINS)
722 ChromePluginServiceFilter::GetInstance()->UnregisterResourceContext(
723 io_data_.GetResourceContextNoInit());
724 #endif
726 // Destroy OTR profile and its profile services first.
727 if (off_the_record_profile_) {
728 ProfileDestroyer::DestroyOffTheRecordProfileNow(
729 off_the_record_profile_.get());
730 } else {
731 #if defined(ENABLE_EXTENSIONS)
732 ExtensionPrefValueMapFactory::GetForBrowserContext(this)->
733 ClearAllIncognitoSessionOnlyPreferences();
734 #endif
737 BrowserContextDependencyManager::GetInstance()->DestroyBrowserContextServices(
738 this);
740 if (pref_proxy_config_tracker_)
741 pref_proxy_config_tracker_->DetachFromPrefService();
743 if (host_content_settings_map_.get())
744 host_content_settings_map_->ShutdownOnUIThread();
746 // This causes the Preferences file to be written to disk.
747 if (prefs_loaded)
748 SetExitType(EXIT_NORMAL);
751 std::string ProfileImpl::GetProfileUserName() const {
752 const SigninManagerBase* signin_manager =
753 SigninManagerFactory::GetForProfileIfExists(this);
754 if (signin_manager)
755 return signin_manager->GetAuthenticatedUsername();
757 return std::string();
760 Profile::ProfileType ProfileImpl::GetProfileType() const {
761 return REGULAR_PROFILE;
764 scoped_ptr<content::ZoomLevelDelegate>
765 ProfileImpl::CreateZoomLevelDelegate(const base::FilePath& partition_path) {
766 return make_scoped_ptr(new chrome::ChromeZoomLevelPrefs(
767 GetPrefs(), GetPath(), partition_path,
768 ui_zoom::ZoomEventManager::GetForBrowserContext(this)->GetWeakPtr()));
771 base::FilePath ProfileImpl::GetPath() const {
772 return path_;
775 scoped_refptr<base::SequencedTaskRunner> ProfileImpl::GetIOTaskRunner() {
776 return JsonPrefStore::GetTaskRunnerForFile(
777 GetPath(), BrowserThread::GetBlockingPool());
780 bool ProfileImpl::IsOffTheRecord() const {
781 return false;
784 Profile* ProfileImpl::GetOffTheRecordProfile() {
785 if (!off_the_record_profile_) {
786 scoped_ptr<Profile> p(CreateOffTheRecordProfile());
787 off_the_record_profile_.swap(p);
789 content::NotificationService::current()->Notify(
790 chrome::NOTIFICATION_PROFILE_CREATED,
791 content::Source<Profile>(off_the_record_profile_.get()),
792 content::NotificationService::NoDetails());
794 return off_the_record_profile_.get();
797 void ProfileImpl::DestroyOffTheRecordProfile() {
798 off_the_record_profile_.reset();
799 #if defined(ENABLE_EXTENSIONS)
800 ExtensionPrefValueMapFactory::GetForBrowserContext(this)->
801 ClearAllIncognitoSessionOnlyPreferences();
802 #endif
805 bool ProfileImpl::HasOffTheRecordProfile() {
806 return off_the_record_profile_.get() != NULL;
809 Profile* ProfileImpl::GetOriginalProfile() {
810 return this;
813 bool ProfileImpl::IsSupervised() {
814 return !GetPrefs()->GetString(prefs::kSupervisedUserId).empty();
817 bool ProfileImpl::IsChild() {
818 #if defined(ENABLE_SUPERVISED_USERS)
819 return GetPrefs()->GetString(prefs::kSupervisedUserId) ==
820 supervised_users::kChildAccountSUID;
821 #else
822 return false;
823 #endif
826 bool ProfileImpl::IsLegacySupervised() {
827 return IsSupervised() && !IsChild();
830 ExtensionSpecialStoragePolicy*
831 ProfileImpl::GetExtensionSpecialStoragePolicy() {
832 #if defined(ENABLE_EXTENSIONS)
833 if (!extension_special_storage_policy_.get()) {
834 TRACE_EVENT0("browser", "ProfileImpl::GetExtensionSpecialStoragePolicy")
835 extension_special_storage_policy_ = new ExtensionSpecialStoragePolicy(
836 CookieSettings::Factory::GetForProfile(this).get());
838 return extension_special_storage_policy_.get();
839 #else
840 return NULL;
841 #endif
844 void ProfileImpl::OnPrefsLoaded(bool success) {
845 TRACE_EVENT0("browser", "ProfileImpl::OnPrefsLoaded");
846 SCOPED_UMA_HISTOGRAM_TIMER("Profile.OnPrefsLoadedTime");
847 if (!success) {
848 if (delegate_)
849 delegate_->OnProfileCreated(this, false, false);
850 return;
853 // Migrate obsolete prefs.
854 if (g_browser_process->local_state())
855 chrome::MigrateObsoleteBrowserPrefs(this, g_browser_process->local_state());
856 chrome::MigrateObsoleteProfilePrefs(this);
858 // |kSessionExitType| was added after |kSessionExitedCleanly|. If the pref
859 // value is empty fallback to checking for |kSessionExitedCleanly|.
860 const std::string exit_type_pref_value(
861 prefs_->GetString(prefs::kSessionExitType));
862 if (exit_type_pref_value.empty()) {
863 last_session_exit_type_ =
864 prefs_->GetBoolean(prefs::kSessionExitedCleanly) ?
865 EXIT_NORMAL : EXIT_CRASHED;
866 } else {
867 last_session_exit_type_ =
868 SessionTypePrefValueToExitType(exit_type_pref_value);
870 // Mark the session as open.
871 prefs_->SetString(prefs::kSessionExitType, kPrefExitTypeCrashed);
872 // Force this to true in case we fallback and use it.
873 // TODO(sky): remove this in a couple of releases (m28ish).
874 prefs_->SetBoolean(prefs::kSessionExitedCleanly, true);
876 #if defined(OS_ANDROID) && defined(FULL_SAFE_BROWSING)
877 // Clear safe browsing setting in the case we need to roll back
878 // for users enrolled in Finch trial before.
879 if (!SafeBrowsingService::IsEnabledByFieldTrial())
880 prefs_->ClearPref(prefs::kSafeBrowsingEnabled);
881 #endif
883 g_browser_process->profile_manager()->InitProfileUserPrefs(this);
886 SCOPED_UMA_HISTOGRAM_TIMER("Profile.CreateBrowserContextServicesTime");
887 BrowserContextDependencyManager::GetInstance()->
888 CreateBrowserContextServices(this);
891 DCHECK(!net_pref_observer_);
893 TRACE_EVENT0("browser", "ProfileImpl::OnPrefsLoaded:NetPrefObserver")
894 net_pref_observer_.reset(new NetPrefObserver(prefs_.get()));
897 chrome_prefs::SchedulePrefsFilePathVerification(path_);
899 ChromeVersionService::OnProfileLoaded(prefs_.get(), IsNewProfile());
900 DoFinalInit();
903 bool ProfileImpl::WasCreatedByVersionOrLater(const std::string& version) {
904 Version profile_version(ChromeVersionService::GetVersion(prefs_.get()));
905 Version arg_version(version);
906 return (profile_version.CompareTo(arg_version) >= 0);
909 void ProfileImpl::SetExitType(ExitType exit_type) {
910 #if defined(OS_CHROMEOS)
911 if (chromeos::ProfileHelper::IsSigninProfile(this))
912 return;
913 #endif
914 if (!prefs_)
915 return;
916 ExitType current_exit_type = SessionTypePrefValueToExitType(
917 prefs_->GetString(prefs::kSessionExitType));
918 // This may be invoked multiple times during shutdown. Only persist the value
919 // first passed in (unless it's a reset to the crash state, which happens when
920 // foregrounding the app on mobile).
921 if (exit_type == EXIT_CRASHED || current_exit_type == EXIT_CRASHED) {
922 prefs_->SetString(prefs::kSessionExitType,
923 ExitTypeToSessionTypePrefValue(exit_type));
927 Profile::ExitType ProfileImpl::GetLastSessionExitType() {
928 // last_session_exited_cleanly_ is set when the preferences are loaded. Force
929 // it to be set by asking for the prefs.
930 GetPrefs();
931 return last_session_exit_type_;
934 PrefService* ProfileImpl::GetPrefs() {
935 return const_cast<PrefService*>(
936 static_cast<const ProfileImpl*>(this)->GetPrefs());
939 const PrefService* ProfileImpl::GetPrefs() const {
940 DCHECK(prefs_); // Should explicitly be initialized.
941 return prefs_.get();
944 chrome::ChromeZoomLevelPrefs* ProfileImpl::GetZoomLevelPrefs() {
945 return static_cast<chrome::ChromeZoomLevelPrefs*>(
946 GetDefaultStoragePartition(this)->GetZoomLevelDelegate());
949 PrefService* ProfileImpl::GetOffTheRecordPrefs() {
950 DCHECK(prefs_);
951 if (!otr_prefs_) {
952 // The new ExtensionPrefStore is ref_counted and the new PrefService
953 // stores a reference so that we do not leak memory here.
954 otr_prefs_.reset(prefs_->CreateIncognitoPrefService(
955 CreateExtensionPrefStore(this, true)));
957 return otr_prefs_.get();
960 net::URLRequestContextGetter* ProfileImpl::CreateRequestContext(
961 content::ProtocolHandlerMap* protocol_handlers,
962 content::URLRequestInterceptorScopedVector request_interceptors) {
963 return io_data_.CreateMainRequestContextGetter(
964 protocol_handlers,
965 request_interceptors.Pass(),
966 g_browser_process->local_state(),
967 g_browser_process->io_thread()).get();
970 net::URLRequestContextGetter* ProfileImpl::GetRequestContext() {
971 return GetDefaultStoragePartition(this)->GetURLRequestContext();
974 net::URLRequestContextGetter* ProfileImpl::GetRequestContextForRenderProcess(
975 int renderer_child_id) {
976 content::RenderProcessHost* rph = content::RenderProcessHost::FromID(
977 renderer_child_id);
979 return rph->GetStoragePartition()->GetURLRequestContext();
982 net::URLRequestContextGetter* ProfileImpl::GetMediaRequestContext() {
983 // Return the default media context.
984 return io_data_.GetMediaRequestContextGetter().get();
987 net::URLRequestContextGetter*
988 ProfileImpl::GetMediaRequestContextForRenderProcess(
989 int renderer_child_id) {
990 content::RenderProcessHost* rph = content::RenderProcessHost::FromID(
991 renderer_child_id);
992 content::StoragePartition* storage_partition = rph->GetStoragePartition();
994 return storage_partition->GetMediaURLRequestContext();
997 net::URLRequestContextGetter*
998 ProfileImpl::GetMediaRequestContextForStoragePartition(
999 const base::FilePath& partition_path,
1000 bool in_memory) {
1001 return io_data_
1002 .GetIsolatedMediaRequestContextGetter(partition_path, in_memory).get();
1005 content::ResourceContext* ProfileImpl::GetResourceContext() {
1006 return io_data_.GetResourceContext();
1009 net::URLRequestContextGetter* ProfileImpl::GetRequestContextForExtensions() {
1010 return io_data_.GetExtensionsRequestContextGetter().get();
1013 net::URLRequestContextGetter*
1014 ProfileImpl::CreateRequestContextForStoragePartition(
1015 const base::FilePath& partition_path,
1016 bool in_memory,
1017 content::ProtocolHandlerMap* protocol_handlers,
1018 content::URLRequestInterceptorScopedVector request_interceptors) {
1019 return io_data_.CreateIsolatedAppRequestContextGetter(
1020 partition_path,
1021 in_memory,
1022 protocol_handlers,
1023 request_interceptors.Pass()).get();
1026 net::SSLConfigService* ProfileImpl::GetSSLConfigService() {
1027 // If ssl_config_service_manager_ is null, this typically means that some
1028 // KeyedService is trying to create a RequestContext at startup,
1029 // but SSLConfigServiceManager is not initialized until DoFinalInit() which is
1030 // invoked after all KeyedServices have been initialized (see
1031 // http://crbug.com/171406).
1032 DCHECK(ssl_config_service_manager_) <<
1033 "SSLConfigServiceManager is not initialized yet";
1034 return ssl_config_service_manager_->Get();
1037 HostContentSettingsMap* ProfileImpl::GetHostContentSettingsMap() {
1038 DCHECK_CURRENTLY_ON(BrowserThread::UI);
1039 if (!host_content_settings_map_.get()) {
1040 host_content_settings_map_ = new HostContentSettingsMap(GetPrefs(), false);
1041 #if defined(ENABLE_SUPERVISED_USERS)
1042 SupervisedUserSettingsService* supervised_user_settings =
1043 SupervisedUserSettingsServiceFactory::GetForProfile(this);
1044 scoped_ptr<content_settings::SupervisedProvider> supervised_provider(
1045 new content_settings::SupervisedProvider(supervised_user_settings));
1046 host_content_settings_map_->RegisterProvider(
1047 HostContentSettingsMap::SUPERVISED_PROVIDER,
1048 supervised_provider.Pass());
1049 #endif
1051 return host_content_settings_map_.get();
1054 content::BrowserPluginGuestManager* ProfileImpl::GetGuestManager() {
1055 #if defined(ENABLE_EXTENSIONS)
1056 return extensions::GuestViewManager::FromBrowserContext(this);
1057 #else
1058 return NULL;
1059 #endif
1062 DownloadManagerDelegate* ProfileImpl::GetDownloadManagerDelegate() {
1063 return DownloadServiceFactory::GetForBrowserContext(this)->
1064 GetDownloadManagerDelegate();
1067 storage::SpecialStoragePolicy* ProfileImpl::GetSpecialStoragePolicy() {
1068 #if defined(ENABLE_EXTENSIONS)
1069 return GetExtensionSpecialStoragePolicy();
1070 #else
1071 return NULL;
1072 #endif
1075 content::PushMessagingService* ProfileImpl::GetPushMessagingService() {
1076 return PushMessagingServiceFactory::GetForProfile(this);
1079 content::SSLHostStateDelegate* ProfileImpl::GetSSLHostStateDelegate() {
1080 return ChromeSSLHostStateDelegateFactory::GetForProfile(this);
1083 // TODO(mlamouri): we should all these BrowserContext implementation to Profile
1084 // instead of repeating them inside all Profile implementations.
1085 content::PermissionManager* ProfileImpl::GetPermissionManager() {
1086 return PermissionManagerFactory::GetForProfile(this);
1089 bool ProfileImpl::IsSameProfile(Profile* profile) {
1090 if (profile == static_cast<Profile*>(this))
1091 return true;
1092 Profile* otr_profile = off_the_record_profile_.get();
1093 return otr_profile && profile == otr_profile;
1096 Time ProfileImpl::GetStartTime() const {
1097 return start_time_;
1100 #if defined(ENABLE_SESSION_SERVICE)
1101 void ProfileImpl::StopCreateSessionServiceTimer() {
1102 create_session_service_timer_.Stop();
1105 void ProfileImpl::EnsureSessionServiceCreated() {
1106 SessionServiceFactory::GetForProfile(this);
1108 #endif
1110 #if defined(OS_CHROMEOS)
1111 void ProfileImpl::ChangeAppLocale(
1112 const std::string& new_locale, AppLocaleChangedVia via) {
1113 if (new_locale.empty()) {
1114 NOTREACHED();
1115 return;
1117 PrefService* local_state = g_browser_process->local_state();
1118 DCHECK(local_state);
1119 if (local_state->IsManagedPreference(prefs::kApplicationLocale))
1120 return;
1121 std::string pref_locale = GetPrefs()->GetString(prefs::kApplicationLocale);
1122 bool do_update_pref = true;
1123 switch (via) {
1124 case APP_LOCALE_CHANGED_VIA_SETTINGS:
1125 case APP_LOCALE_CHANGED_VIA_REVERT: {
1126 // We keep kApplicationLocaleBackup value as a reference. In case value
1127 // of kApplicationLocale preference would change due to sync from other
1128 // device then kApplicationLocaleBackup value will trigger and allow us to
1129 // show notification about automatic locale change in LocaleChangeGuard.
1130 GetPrefs()->SetString(prefs::kApplicationLocaleBackup, new_locale);
1131 GetPrefs()->ClearPref(prefs::kApplicationLocaleAccepted);
1132 // We maintain kApplicationLocale property in both a global storage
1133 // and user's profile. Global property determines locale of login screen,
1134 // while user's profile determines his personal locale preference.
1135 break;
1137 case APP_LOCALE_CHANGED_VIA_LOGIN:
1138 case APP_LOCALE_CHANGED_VIA_PUBLIC_SESSION_LOGIN: {
1139 if (!pref_locale.empty()) {
1140 DCHECK(pref_locale == new_locale);
1141 std::string accepted_locale =
1142 GetPrefs()->GetString(prefs::kApplicationLocaleAccepted);
1143 if (accepted_locale == new_locale) {
1144 // If locale is accepted then we do not want to show LocaleChange
1145 // notification. This notification is triggered by different values
1146 // of kApplicationLocaleBackup and kApplicationLocale preferences,
1147 // so make them identical.
1148 GetPrefs()->SetString(prefs::kApplicationLocaleBackup, new_locale);
1149 } else {
1150 // Back up locale of login screen.
1151 std::string cur_locale = g_browser_process->GetApplicationLocale();
1152 GetPrefs()->SetString(prefs::kApplicationLocaleBackup, cur_locale);
1153 if (locale_change_guard_ == NULL)
1154 locale_change_guard_.reset(new chromeos::LocaleChangeGuard(this));
1155 locale_change_guard_->PrepareChangingLocale(cur_locale, new_locale);
1157 } else {
1158 std::string cur_locale = g_browser_process->GetApplicationLocale();
1159 std::string backup_locale =
1160 GetPrefs()->GetString(prefs::kApplicationLocaleBackup);
1161 // Profile synchronization takes time and is not completed at that
1162 // moment at first login. So we initialize locale preference in steps:
1163 // (1) first save it to temporary backup;
1164 // (2) on next login we assume that synchronization is already completed
1165 // and we may finalize initialization.
1166 GetPrefs()->SetString(prefs::kApplicationLocaleBackup, cur_locale);
1167 if (!new_locale.empty())
1168 GetPrefs()->SetString(prefs::kApplicationLocale, new_locale);
1169 else if (!backup_locale.empty())
1170 GetPrefs()->SetString(prefs::kApplicationLocale, backup_locale);
1171 do_update_pref = false;
1173 break;
1175 case APP_LOCALE_CHANGED_VIA_UNKNOWN:
1176 default: {
1177 NOTREACHED();
1178 break;
1181 if (do_update_pref)
1182 GetPrefs()->SetString(prefs::kApplicationLocale, new_locale);
1183 if (via != APP_LOCALE_CHANGED_VIA_PUBLIC_SESSION_LOGIN)
1184 local_state->SetString(prefs::kApplicationLocale, new_locale);
1186 if (user_manager::UserManager::Get()->GetOwnerEmail() ==
1187 chromeos::ProfileHelper::Get()->GetUserByProfile(this)->email())
1188 local_state->SetString(prefs::kOwnerLocale, new_locale);
1191 void ProfileImpl::OnLogin() {
1192 if (locale_change_guard_ == NULL)
1193 locale_change_guard_.reset(new chromeos::LocaleChangeGuard(this));
1194 locale_change_guard_->OnLogin();
1197 void ProfileImpl::InitChromeOSPreferences() {
1198 chromeos_preferences_.reset(new chromeos::Preferences());
1199 chromeos_preferences_->Init(
1200 this, chromeos::ProfileHelper::Get()->GetUserByProfile(this));
1203 #endif // defined(OS_CHROMEOS)
1205 PrefProxyConfigTracker* ProfileImpl::GetProxyConfigTracker() {
1206 if (!pref_proxy_config_tracker_)
1207 pref_proxy_config_tracker_.reset(CreateProxyConfigTracker());
1208 return pref_proxy_config_tracker_.get();
1211 chrome_browser_net::Predictor* ProfileImpl::GetNetworkPredictor() {
1212 return predictor_;
1215 DevToolsNetworkController* ProfileImpl::GetDevToolsNetworkController() {
1216 return io_data_.GetDevToolsNetworkController();
1219 void ProfileImpl::ClearNetworkingHistorySince(
1220 base::Time time,
1221 const base::Closure& completion) {
1222 io_data_.ClearNetworkingHistorySince(time, completion);
1225 GURL ProfileImpl::GetHomePage() {
1226 // --homepage overrides any preferences.
1227 const base::CommandLine& command_line =
1228 *base::CommandLine::ForCurrentProcess();
1229 if (command_line.HasSwitch(switches::kHomePage)) {
1230 // TODO(evanm): clean up usage of DIR_CURRENT.
1231 // http://code.google.com/p/chromium/issues/detail?id=60630
1232 // For now, allow this code to call getcwd().
1233 base::ThreadRestrictions::ScopedAllowIO allow_io;
1235 base::FilePath browser_directory;
1236 PathService::Get(base::DIR_CURRENT, &browser_directory);
1237 GURL home_page(url_fixer::FixupRelativeFile(
1238 browser_directory,
1239 command_line.GetSwitchValuePath(switches::kHomePage)));
1240 if (home_page.is_valid())
1241 return home_page;
1244 if (GetPrefs()->GetBoolean(prefs::kHomePageIsNewTabPage))
1245 return GURL(chrome::kChromeUINewTabURL);
1246 GURL home_page(url_fixer::FixupURL(GetPrefs()->GetString(prefs::kHomePage),
1247 std::string()));
1248 if (!home_page.is_valid())
1249 return GURL(chrome::kChromeUINewTabURL);
1250 return home_page;
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));
1273 bool default_name =
1274 GetPrefs()->GetBoolean(prefs::kProfileUsingDefaultName);
1275 cache.SetProfileIsUsingDefaultNameAtIndex(index, default_name);
1279 void ProfileImpl::UpdateProfileAvatarCache() {
1280 ProfileManager* profile_manager = g_browser_process->profile_manager();
1281 ProfileInfoCache& cache = profile_manager->GetProfileInfoCache();
1282 size_t index = cache.GetIndexOfProfileWithPath(GetPath());
1283 if (index != std::string::npos) {
1284 size_t avatar_index =
1285 GetPrefs()->GetInteger(prefs::kProfileAvatarIndex);
1286 cache.SetAvatarIconOfProfileAtIndex(index, avatar_index);
1287 bool default_avatar =
1288 GetPrefs()->GetBoolean(prefs::kProfileUsingDefaultAvatar);
1289 cache.SetProfileIsUsingDefaultAvatarAtIndex(index, default_avatar);
1290 bool gaia_avatar =
1291 GetPrefs()->GetBoolean(prefs::kProfileUsingGAIAAvatar);
1292 cache.SetIsUsingGAIAPictureOfProfileAtIndex(index, gaia_avatar);
1296 void ProfileImpl::UpdateProfileIsEphemeralCache() {
1297 ProfileManager* profile_manager = g_browser_process->profile_manager();
1298 ProfileInfoCache& cache = profile_manager->GetProfileInfoCache();
1299 size_t index = cache.GetIndexOfProfileWithPath(GetPath());
1300 if (index != std::string::npos) {
1301 bool is_ephemeral = GetPrefs()->GetBoolean(prefs::kForceEphemeralProfiles);
1302 cache.SetProfileIsEphemeralAtIndex(index, is_ephemeral);
1306 // Gets the cache parameters from the command line. If |is_media_context| is
1307 // set to true then settings for the media context type is what we need,
1308 // |cache_path| will be set to the user provided path, or will not be touched if
1309 // there is not an argument. |max_size| will be the user provided value or zero
1310 // by default.
1311 void ProfileImpl::GetCacheParameters(bool is_media_context,
1312 base::FilePath* cache_path,
1313 int* max_size) {
1314 DCHECK(cache_path);
1315 DCHECK(max_size);
1316 base::FilePath path(prefs_->GetFilePath(prefs::kDiskCacheDir));
1317 if (!path.empty())
1318 *cache_path = path;
1319 *max_size = is_media_context ? prefs_->GetInteger(prefs::kMediaCacheSize) :
1320 prefs_->GetInteger(prefs::kDiskCacheSize);
1323 PrefProxyConfigTracker* ProfileImpl::CreateProxyConfigTracker() {
1324 #if defined(OS_CHROMEOS)
1325 if (chromeos::ProfileHelper::IsSigninProfile(this)) {
1326 return ProxyServiceFactory::CreatePrefProxyConfigTrackerOfLocalState(
1327 g_browser_process->local_state());
1329 #endif // defined(OS_CHROMEOS)
1330 return ProxyServiceFactory::CreatePrefProxyConfigTrackerOfProfile(
1331 GetPrefs(), g_browser_process->local_state());
1334 scoped_ptr<domain_reliability::DomainReliabilityMonitor>
1335 ProfileImpl::CreateDomainReliabilityMonitor(PrefService* local_state) {
1336 domain_reliability::DomainReliabilityService* service =
1337 domain_reliability::DomainReliabilityServiceFactory::GetInstance()->
1338 GetForBrowserContext(this);
1339 if (!service)
1340 return scoped_ptr<domain_reliability::DomainReliabilityMonitor>();
1342 return service->CreateMonitor(
1343 BrowserThread::GetMessageLoopProxyForThread(BrowserThread::IO));