Make sure the win_chromium_gn_x64_dbg bot is using symbol_level=1
[chromium-blink-merge.git] / chrome / browser / profiles / profile_impl.cc
blobdc1d34549376c14c689d37e72c0ab62b48a99a88
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/threading/thread_restrictions.h"
29 #include "base/trace_event/trace_event.h"
30 #include "base/version.h"
31 #include "chrome/browser/background/background_contents_service_factory.h"
32 #include "chrome/browser/bookmarks/bookmark_model_factory.h"
33 #include "chrome/browser/browser_process.h"
34 #include "chrome/browser/chrome_notification_types.h"
35 #include "chrome/browser/content_settings/cookie_settings_factory.h"
36 #include "chrome/browser/dom_distiller/profile_utils.h"
37 #include "chrome/browser/domain_reliability/service_factory.h"
38 #include "chrome/browser/download/chrome_download_manager_delegate.h"
39 #include "chrome/browser/download/download_service.h"
40 #include "chrome/browser/download/download_service_factory.h"
41 #include "chrome/browser/net/net_pref_observer.h"
42 #include "chrome/browser/net/predictor.h"
43 #include "chrome/browser/net/proxy_service_factory.h"
44 #include "chrome/browser/net/ssl_config_service_manager.h"
45 #include "chrome/browser/permissions/permission_manager.h"
46 #include "chrome/browser/permissions/permission_manager_factory.h"
47 #include "chrome/browser/plugins/chrome_plugin_service_filter.h"
48 #include "chrome/browser/plugins/plugin_prefs.h"
49 #include "chrome/browser/policy/profile_policy_connector.h"
50 #include "chrome/browser/policy/profile_policy_connector_factory.h"
51 #include "chrome/browser/prefs/browser_prefs.h"
52 #include "chrome/browser/prefs/chrome_pref_service_factory.h"
53 #include "chrome/browser/prefs/pref_service_syncable.h"
54 #include "chrome/browser/prerender/prerender_manager_factory.h"
55 #include "chrome/browser/profiles/bookmark_model_loaded_observer.h"
56 #include "chrome/browser/profiles/chrome_version_service.h"
57 #include "chrome/browser/profiles/gaia_info_update_service_factory.h"
58 #include "chrome/browser/profiles/profile_destroyer.h"
59 #include "chrome/browser/profiles/profile_info_cache.h"
60 #include "chrome/browser/profiles/profile_manager.h"
61 #include "chrome/browser/profiles/profile_metrics.h"
62 #include "chrome/browser/push_messaging/push_messaging_service_factory.h"
63 #include "chrome/browser/push_messaging/push_messaging_service_impl.h"
64 #include "chrome/browser/safe_browsing/safe_browsing_service.h"
65 #include "chrome/browser/services/gcm/gcm_profile_service.h"
66 #include "chrome/browser/sessions/session_service_factory.h"
67 #include "chrome/browser/signin/signin_manager_factory.h"
68 #include "chrome/browser/signin/signin_ui_util.h"
69 #include "chrome/browser/ssl/chrome_ssl_host_state_delegate.h"
70 #include "chrome/browser/ssl/chrome_ssl_host_state_delegate_factory.h"
71 #include "chrome/browser/ui/startup/startup_browser_creator.h"
72 #include "chrome/common/chrome_constants.h"
73 #include "chrome/common/chrome_paths_internal.h"
74 #include "chrome/common/chrome_switches.h"
75 #include "chrome/common/pref_names.h"
76 #include "chrome/common/url_constants.h"
77 #include "chrome/grit/chromium_strings.h"
78 #include "components/bookmarks/browser/bookmark_model.h"
79 #include "components/content_settings/core/browser/cookie_settings.h"
80 #include "components/content_settings/core/browser/host_content_settings_map.h"
81 #include "components/domain_reliability/monitor.h"
82 #include "components/domain_reliability/service.h"
83 #include "components/keyed_service/content/browser_context_dependency_manager.h"
84 #include "components/metrics/metrics_service.h"
85 #include "components/omnibox/browser/autocomplete_classifier.h"
86 #include "components/omnibox/browser/shortcuts_backend.h"
87 #include "components/pref_registry/pref_registry_syncable.h"
88 #include "components/proxy_config/pref_proxy_config_tracker.h"
89 #include "components/signin/core/browser/signin_manager.h"
90 #include "components/ui/zoom/zoom_event_manager.h"
91 #include "components/url_formatter/url_fixer.h"
92 #include "components/user_prefs/tracked/tracked_preference_validation_delegate.h"
93 #include "components/user_prefs/user_prefs.h"
94 #include "content/public/browser/browser_thread.h"
95 #include "content/public/browser/dom_storage_context.h"
96 #include "content/public/browser/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 "ui/base/l10n/l10n_util.h"
105 #if defined(OS_ANDROID)
106 #include "chrome/browser/media/protected_media_identifier_permission_context.h"
107 #include "chrome/browser/media/protected_media_identifier_permission_context_factory.h"
108 #endif
110 #if defined(OS_CHROMEOS)
111 #include "chrome/browser/chromeos/locale_change_guard.h"
112 #include "chrome/browser/chromeos/preferences.h"
113 #include "chrome/browser/chromeos/profiles/profile_helper.h"
114 #include "components/user_manager/user_manager.h"
115 #endif
117 #if defined(ENABLE_BACKGROUND)
118 #include "chrome/browser/background/background_mode_manager.h"
119 #endif
121 #if defined(ENABLE_CONFIGURATION_POLICY)
122 #include "chrome/browser/policy/schema_registry_service.h"
123 #include "chrome/browser/policy/schema_registry_service_factory.h"
124 #include "components/policy/core/browser/browser_policy_connector.h"
125 #if defined(OS_CHROMEOS)
126 #include "chrome/browser/chromeos/login/session/user_session_manager.h"
127 #include "chrome/browser/chromeos/policy/user_cloud_policy_manager_chromeos.h"
128 #include "chrome/browser/chromeos/policy/user_cloud_policy_manager_factory_chromeos.h"
129 #else
130 #include "chrome/browser/policy/cloud/user_cloud_policy_manager_factory.h"
131 #include "components/policy/core/common/cloud/user_cloud_policy_manager.h"
132 #endif
133 #endif
135 #if defined(ENABLE_EXTENSIONS)
136 #include "chrome/browser/extensions/extension_service.h"
137 #include "chrome/browser/extensions/extension_special_storage_policy.h"
138 #include "chrome/browser/ui/webui/extensions/extension_icon_source.h"
139 #include "components/guest_view/browser/guest_view_manager.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 #endif
146 #if defined(ENABLE_SUPERVISED_USERS)
147 #include "chrome/browser/content_settings/content_settings_supervised_provider.h"
148 #include "chrome/browser/supervised_user/supervised_user_constants.h"
149 #include "chrome/browser/supervised_user/supervised_user_settings_service.h"
150 #include "chrome/browser/supervised_user/supervised_user_settings_service_factory.h"
151 #endif
153 using base::Time;
154 using base::TimeDelta;
155 using base::UserMetricsAction;
156 using bookmarks::BookmarkModel;
157 using content::BrowserThread;
158 using content::DownloadManagerDelegate;
160 namespace {
162 #if defined(ENABLE_SESSION_SERVICE)
163 // Delay, in milliseconds, before we explicitly create the SessionService.
164 const int kCreateSessionServiceDelayMS = 500;
165 #endif
167 // Text content of README file created in each profile directory. Both %s
168 // placeholders must contain the product name. This is not localizable and hence
169 // not in resources.
170 const char kReadmeText[] =
171 "%s settings and storage represent user-selected preferences and "
172 "information and MUST not be extracted, overwritten or modified except "
173 "through %s defined APIs.";
175 // Value written to prefs for EXIT_CRASHED and EXIT_SESSION_ENDED.
176 const char kPrefExitTypeCrashed[] = "Crashed";
177 const char kPrefExitTypeSessionEnded[] = "SessionEnded";
179 void CreateProfileReadme(const base::FilePath& profile_path) {
180 base::ThreadRestrictions::AssertIOAllowed();
181 base::FilePath readme_path = profile_path.Append(chrome::kReadmeFilename);
182 std::string product_name = l10n_util::GetStringUTF8(IDS_PRODUCT_NAME);
183 std::string readme_text = base::StringPrintf(
184 kReadmeText, product_name.c_str(), product_name.c_str());
185 if (base::WriteFile(readme_path, readme_text.data(), readme_text.size()) ==
186 -1) {
187 LOG(ERROR) << "Could not create README file.";
191 // Helper method needed because PostTask cannot currently take a Callback
192 // function with non-void return type.
193 void CreateDirectoryAndSignal(const base::FilePath& path,
194 base::WaitableEvent* done_creating,
195 bool create_readme) {
196 // If the readme exists, the profile directory must also already exist.
197 base::FilePath readme_path = path.Append(chrome::kReadmeFilename);
198 if (base::PathExists(readme_path)) {
199 done_creating->Signal();
200 return;
203 DVLOG(1) << "Creating directory " << path.value();
204 if (base::CreateDirectory(path) && create_readme)
205 CreateProfileReadme(path);
206 done_creating->Signal();
209 // Task that blocks the FILE thread until CreateDirectoryAndSignal() finishes on
210 // blocking I/O pool.
211 void BlockFileThreadOnDirectoryCreate(base::WaitableEvent* done_creating) {
212 done_creating->Wait();
215 // Initiates creation of profile directory on |sequenced_task_runner| and
216 // ensures that FILE thread is blocked until that operation finishes. If
217 // |create_readme| is true, the profile README will be created in the profile
218 // directory.
219 void CreateProfileDirectory(base::SequencedTaskRunner* sequenced_task_runner,
220 const base::FilePath& path,
221 bool create_readme) {
222 base::WaitableEvent* done_creating = new base::WaitableEvent(false, false);
223 sequenced_task_runner->PostTask(
224 FROM_HERE, base::Bind(&CreateDirectoryAndSignal, path, done_creating,
225 create_readme));
226 // Block the FILE thread until directory is created on I/O pool to make sure
227 // that we don't attempt any operation until that part completes.
228 BrowserThread::PostTask(
229 BrowserThread::FILE, FROM_HERE,
230 base::Bind(&BlockFileThreadOnDirectoryCreate,
231 base::Owned(done_creating)));
234 base::FilePath GetCachePath(const base::FilePath& base) {
235 return base.Append(chrome::kCacheDirname);
238 base::FilePath GetMediaCachePath(const base::FilePath& base) {
239 return base.Append(chrome::kMediaCacheDirname);
242 // Converts the kSessionExitedCleanly pref to the corresponding EXIT_TYPE.
243 Profile::ExitType SessionTypePrefValueToExitType(const std::string& value) {
244 if (value == kPrefExitTypeSessionEnded)
245 return Profile::EXIT_SESSION_ENDED;
246 if (value == kPrefExitTypeCrashed)
247 return Profile::EXIT_CRASHED;
248 return Profile::EXIT_NORMAL;
251 // Converts an ExitType into a string that is written to prefs.
252 std::string ExitTypeToSessionTypePrefValue(Profile::ExitType type) {
253 switch (type) {
254 case Profile::EXIT_NORMAL:
255 return ProfileImpl::kPrefExitTypeNormal;
256 case Profile::EXIT_SESSION_ENDED:
257 return kPrefExitTypeSessionEnded;
258 case Profile::EXIT_CRASHED:
259 return kPrefExitTypeCrashed;
261 NOTREACHED();
262 return std::string();
265 PrefStore* CreateExtensionPrefStore(Profile* profile,
266 bool incognito_pref_store) {
267 #if defined(ENABLE_EXTENSIONS)
268 return new ExtensionPrefStore(
269 ExtensionPrefValueMapFactory::GetForBrowserContext(profile),
270 incognito_pref_store);
271 #else
272 return NULL;
273 #endif
276 } // namespace
278 // static
279 Profile* Profile::CreateProfile(const base::FilePath& path,
280 Delegate* delegate,
281 CreateMode create_mode) {
282 TRACE_EVENT1("browser,startup",
283 "Profile::CreateProfile",
284 "profile_path",
285 path.AsUTF8Unsafe());
287 // Get sequenced task runner for making sure that file operations of
288 // this profile (defined by |path|) are executed in expected order
289 // (what was previously assured by the FILE thread).
290 scoped_refptr<base::SequencedTaskRunner> sequenced_task_runner =
291 JsonPrefStore::GetTaskRunnerForFile(path,
292 BrowserThread::GetBlockingPool());
293 if (create_mode == CREATE_MODE_ASYNCHRONOUS) {
294 DCHECK(delegate);
295 CreateProfileDirectory(sequenced_task_runner.get(), path, true);
296 } else if (create_mode == CREATE_MODE_SYNCHRONOUS) {
297 if (!base::PathExists(path)) {
298 // TODO(rogerta): http://crbug/160553 - Bad things happen if we can't
299 // write to the profile directory. We should eventually be able to run in
300 // this situation.
301 if (!base::CreateDirectory(path))
302 return NULL;
304 CreateProfileReadme(path);
306 } else {
307 NOTREACHED();
310 return new ProfileImpl(
311 path, delegate, create_mode, sequenced_task_runner.get());
314 // static
315 const char* const ProfileImpl::kPrefExitTypeNormal = "Normal";
317 // static
318 void ProfileImpl::RegisterProfilePrefs(
319 user_prefs::PrefRegistrySyncable* registry) {
320 registry->RegisterBooleanPref(prefs::kSavingBrowserHistoryDisabled, false);
321 registry->RegisterBooleanPref(prefs::kAllowDeletingBrowserHistory, true);
322 registry->RegisterBooleanPref(prefs::kSigninAllowed, true);
323 registry->RegisterBooleanPref(prefs::kForceGoogleSafeSearch, false);
324 registry->RegisterBooleanPref(prefs::kForceYouTubeSafetyMode, false);
325 registry->RegisterBooleanPref(prefs::kRecordHistory, false);
326 registry->RegisterIntegerPref(
327 prefs::kProfileAvatarIndex,
329 user_prefs::PrefRegistrySyncable::SYNCABLE_PREF);
330 // Whether a profile is using an avatar without having explicitely chosen it
331 // (i.e. was assigned by default by legacy profile creation).
332 registry->RegisterBooleanPref(
333 prefs::kProfileUsingDefaultAvatar,
334 true,
335 user_prefs::PrefRegistrySyncable::SYNCABLE_PREF);
336 registry->RegisterBooleanPref(
337 prefs::kProfileUsingGAIAAvatar,
338 false,
339 user_prefs::PrefRegistrySyncable::SYNCABLE_PREF);
340 // Whether a profile is using a default avatar name (eg. Pickles or Person 1).
341 registry->RegisterBooleanPref(
342 prefs::kProfileUsingDefaultName,
343 true,
344 user_prefs::PrefRegistrySyncable::SYNCABLE_PREF);
345 registry->RegisterStringPref(prefs::kSupervisedUserId, std::string());
346 registry->RegisterStringPref(prefs::kProfileName,
347 std::string(),
348 user_prefs::PrefRegistrySyncable::SYNCABLE_PREF);
349 registry->RegisterStringPref(prefs::kHomePage,
350 std::string(),
351 user_prefs::PrefRegistrySyncable::SYNCABLE_PREF);
352 #if defined(ENABLE_PRINTING)
353 registry->RegisterBooleanPref(prefs::kPrintingEnabled, true);
354 #endif
355 registry->RegisterBooleanPref(prefs::kPrintPreviewDisabled, false);
356 registry->RegisterBooleanPref(prefs::kForceEphemeralProfiles, false);
358 // Initialize the cache prefs.
359 registry->RegisterFilePathPref(prefs::kDiskCacheDir, base::FilePath());
360 registry->RegisterIntegerPref(prefs::kDiskCacheSize, 0);
361 registry->RegisterIntegerPref(prefs::kMediaCacheSize, 0);
364 ProfileImpl::ProfileImpl(
365 const base::FilePath& path,
366 Delegate* delegate,
367 CreateMode create_mode,
368 base::SequencedTaskRunner* sequenced_task_runner)
369 : path_(path),
370 pref_registry_(new user_prefs::PrefRegistrySyncable),
371 io_data_(this),
372 host_content_settings_map_(NULL),
373 last_session_exit_type_(EXIT_NORMAL),
374 start_time_(Time::Now()),
375 delegate_(delegate),
376 predictor_(NULL) {
377 TRACE_EVENT0("browser,startup", "ProfileImpl::ctor")
378 DCHECK(!path.empty()) << "Using an empty path will attempt to write " <<
379 "profile files to the root directory!";
381 #if defined(ENABLE_SESSION_SERVICE)
382 create_session_service_timer_.Start(FROM_HERE,
383 TimeDelta::FromMilliseconds(kCreateSessionServiceDelayMS), this,
384 &ProfileImpl::EnsureSessionServiceCreated);
385 #endif
387 set_is_guest_profile(path == ProfileManager::GetGuestProfilePath());
388 set_is_system_profile(path == ProfileManager::GetSystemProfilePath());
390 // Determine if prefetch is enabled for this profile.
391 // If not profile_manager is present, it means we are in a unittest.
392 const base::CommandLine* command_line =
393 base::CommandLine::ForCurrentProcess();
394 predictor_ = chrome_browser_net::Predictor::CreatePredictor(
395 !command_line->HasSwitch(switches::kDisablePreconnect),
396 !command_line->HasSwitch(switches::kDnsPrefetchDisable),
397 g_browser_process->profile_manager() == NULL);
399 // If we are creating the profile synchronously, then we should load the
400 // policy data immediately.
401 bool force_immediate_policy_load = (create_mode == CREATE_MODE_SYNCHRONOUS);
402 #if defined(ENABLE_CONFIGURATION_POLICY)
403 policy::BrowserPolicyConnector* connector =
404 g_browser_process->browser_policy_connector();
405 schema_registry_service_ =
406 policy::SchemaRegistryServiceFactory::CreateForContext(
407 this, connector->GetChromeSchema(), connector->GetSchemaRegistry());
408 #if defined(OS_CHROMEOS)
409 cloud_policy_manager_ =
410 policy::UserCloudPolicyManagerFactoryChromeOS::CreateForProfile(
411 this, force_immediate_policy_load, sequenced_task_runner);
412 #else
413 cloud_policy_manager_ =
414 policy::UserCloudPolicyManagerFactory::CreateForOriginalBrowserContext(
415 this,
416 force_immediate_policy_load,
417 sequenced_task_runner,
418 BrowserThread::GetMessageLoopProxyForThread(BrowserThread::FILE),
419 BrowserThread::GetMessageLoopProxyForThread(BrowserThread::IO));
420 #endif
421 #endif
422 profile_policy_connector_ =
423 policy::ProfilePolicyConnectorFactory::CreateForBrowserContext(
424 this, force_immediate_policy_load);
426 DCHECK(create_mode == CREATE_MODE_ASYNCHRONOUS ||
427 create_mode == CREATE_MODE_SYNCHRONOUS);
428 bool async_prefs = create_mode == CREATE_MODE_ASYNCHRONOUS;
430 #if defined(OS_CHROMEOS)
431 if (chromeos::ProfileHelper::IsSigninProfile(this))
432 chrome::RegisterLoginProfilePrefs(pref_registry_.get());
433 else
434 #endif
435 chrome::RegisterUserProfilePrefs(pref_registry_.get());
437 BrowserContextDependencyManager::GetInstance()->
438 RegisterProfilePrefsForServices(this, pref_registry_.get());
440 SupervisedUserSettingsService* supervised_user_settings = nullptr;
441 #if defined(ENABLE_SUPERVISED_USERS)
442 supervised_user_settings =
443 SupervisedUserSettingsServiceFactory::GetForProfile(this);
444 supervised_user_settings->Init(
445 path_, sequenced_task_runner, create_mode == CREATE_MODE_SYNCHRONOUS);
446 #endif
448 scoped_refptr<SafeBrowsingService> safe_browsing_service(
449 g_browser_process->safe_browsing_service());
450 if (safe_browsing_service.get()) {
451 pref_validation_delegate_ =
452 safe_browsing_service->CreatePreferenceValidationDelegate(this).Pass();
456 prefs_ = chrome_prefs::CreateProfilePrefs(
457 path_,
458 sequenced_task_runner,
459 pref_validation_delegate_.get(),
460 profile_policy_connector_->policy_service(),
461 supervised_user_settings,
462 CreateExtensionPrefStore(this, false),
463 pref_registry_,
464 async_prefs).Pass();
465 // Register on BrowserContext.
466 user_prefs::UserPrefs::Set(this, prefs_.get());
469 if (async_prefs) {
470 // Wait for the notification that prefs has been loaded
471 // (successfully or not). Note that we can use base::Unretained
472 // because the PrefService is owned by this class and lives on
473 // the same thread.
474 prefs_->AddPrefInitObserver(base::Bind(
475 &ProfileImpl::OnPrefsLoaded, base::Unretained(this), create_mode));
476 } else {
477 // Prefs were loaded synchronously so we can continue directly.
478 OnPrefsLoaded(create_mode, true);
482 void ProfileImpl::DoFinalInit() {
483 TRACE_EVENT0("browser", "ProfileImpl::DoFinalInit")
484 SCOPED_UMA_HISTOGRAM_TIMER("Profile.ProfileImplDoFinalInit");
486 PrefService* prefs = GetPrefs();
487 pref_change_registrar_.Init(prefs);
488 pref_change_registrar_.Add(
489 prefs::kSupervisedUserId,
490 base::Bind(&ProfileImpl::UpdateProfileSupervisedUserIdCache,
491 base::Unretained(this)));
493 // Changes in the profile avatar.
494 pref_change_registrar_.Add(
495 prefs::kProfileAvatarIndex,
496 base::Bind(&ProfileImpl::UpdateProfileAvatarCache,
497 base::Unretained(this)));
498 pref_change_registrar_.Add(
499 prefs::kProfileUsingDefaultAvatar,
500 base::Bind(&ProfileImpl::UpdateProfileAvatarCache,
501 base::Unretained(this)));
502 pref_change_registrar_.Add(
503 prefs::kProfileUsingGAIAAvatar,
504 base::Bind(&ProfileImpl::UpdateProfileAvatarCache,
505 base::Unretained(this)));
507 // Changes in the profile name.
508 pref_change_registrar_.Add(
509 prefs::kProfileUsingDefaultName,
510 base::Bind(&ProfileImpl::UpdateProfileNameCache,
511 base::Unretained(this)));
512 pref_change_registrar_.Add(
513 prefs::kProfileName,
514 base::Bind(&ProfileImpl::UpdateProfileNameCache,
515 base::Unretained(this)));
517 pref_change_registrar_.Add(
518 prefs::kForceEphemeralProfiles,
519 base::Bind(&ProfileImpl::UpdateProfileIsEphemeralCache,
520 base::Unretained(this)));
522 // It would be nice to use PathService for fetching this directory, but
523 // the cache directory depends on the profile directory, which isn't available
524 // to PathService.
525 chrome::GetUserCacheDirectory(path_, &base_cache_path_);
526 // Always create the cache directory asynchronously.
527 scoped_refptr<base::SequencedTaskRunner> sequenced_task_runner =
528 JsonPrefStore::GetTaskRunnerForFile(base_cache_path_,
529 BrowserThread::GetBlockingPool());
530 CreateProfileDirectory(sequenced_task_runner.get(), base_cache_path_, false);
532 // Initialize components that depend on the current value.
533 UpdateProfileSupervisedUserIdCache();
534 UpdateProfileIsEphemeralCache();
535 GAIAInfoUpdateServiceFactory::GetForProfile(this);
537 PrefService* local_state = g_browser_process->local_state();
538 ssl_config_service_manager_.reset(
539 SSLConfigServiceManager::CreateDefaultManager(local_state));
541 #if defined(ENABLE_BACKGROUND)
542 // Initialize the BackgroundModeManager - this has to be done here before
543 // InitExtensions() is called because it relies on receiving notifications
544 // when extensions are loaded. BackgroundModeManager is not needed under
545 // ChromeOS because Chrome is always running, no need for special keep-alive
546 // or launch-on-startup support unless kKeepAliveForTest is set.
547 bool init_background_mode_manager = true;
548 #if defined(OS_CHROMEOS)
549 if (!base::CommandLine::ForCurrentProcess()->HasSwitch(
550 switches::kKeepAliveForTest))
551 init_background_mode_manager = false;
552 #endif
553 if (init_background_mode_manager) {
554 if (g_browser_process->background_mode_manager())
555 g_browser_process->background_mode_manager()->RegisterProfile(this);
557 #endif // defined(ENABLE_BACKGROUND)
559 base::FilePath cookie_path = GetPath();
560 cookie_path = cookie_path.Append(chrome::kCookieFilename);
561 base::FilePath channel_id_path = GetPath();
562 channel_id_path = channel_id_path.Append(chrome::kChannelIDFilename);
563 base::FilePath cache_path = base_cache_path_;
564 int cache_max_size;
565 GetCacheParameters(false, &cache_path, &cache_max_size);
566 cache_path = GetCachePath(cache_path);
568 base::FilePath media_cache_path = base_cache_path_;
569 int media_cache_max_size;
570 GetCacheParameters(true, &media_cache_path, &media_cache_max_size);
571 media_cache_path = GetMediaCachePath(media_cache_path);
573 base::FilePath extensions_cookie_path = GetPath();
574 extensions_cookie_path =
575 extensions_cookie_path.Append(chrome::kExtensionsCookieFilename);
577 #if defined(OS_ANDROID)
578 SessionStartupPref::Type startup_pref_type =
579 SessionStartupPref::GetDefaultStartupType();
580 #else
581 SessionStartupPref::Type startup_pref_type =
582 StartupBrowserCreator::GetSessionStartupPref(
583 *base::CommandLine::ForCurrentProcess(), this).type;
584 #endif
585 content::CookieStoreConfig::SessionCookieMode session_cookie_mode =
586 content::CookieStoreConfig::PERSISTANT_SESSION_COOKIES;
587 if (GetLastSessionExitType() == Profile::EXIT_CRASHED ||
588 startup_pref_type == SessionStartupPref::LAST) {
589 session_cookie_mode = content::CookieStoreConfig::RESTORED_SESSION_COOKIES;
592 // Make sure we initialize the ProfileIOData after everything else has been
593 // initialized that we might be reading from the IO thread.
595 io_data_.Init(cookie_path, channel_id_path, cache_path,
596 cache_max_size, media_cache_path, media_cache_max_size,
597 extensions_cookie_path, GetPath(), predictor_,
598 session_cookie_mode, GetSpecialStoragePolicy(),
599 CreateDomainReliabilityMonitor(local_state));
601 #if defined(ENABLE_PLUGINS)
602 ChromePluginServiceFilter::GetInstance()->RegisterResourceContext(
603 PluginPrefs::GetForProfile(this).get(),
604 io_data_.GetResourceContextNoInit());
605 #endif
607 TRACE_EVENT0("browser", "ProfileImpl::SetSaveSessionStorageOnDisk");
608 content::BrowserContext::GetDefaultStoragePartition(this)->
609 GetDOMStorageContext()->SetSaveSessionStorageOnDisk();
611 // The DomDistillerViewerSource is not a normal WebUI so it must be registered
612 // as a URLDataSource early.
613 RegisterDomDistillerViewerSource(this);
615 #if defined(OS_CHROMEOS)
616 if (chromeos::UserSessionManager::GetInstance()
617 ->RestartToApplyPerSessionFlagsIfNeed(this, true)) {
618 return;
620 #endif
622 if (delegate_) {
623 TRACE_EVENT0("browser", "ProfileImpl::DoFileInit:DelegateOnProfileCreated")
624 delegate_->OnProfileCreated(this, true, IsNewProfile());
628 SCOPED_UMA_HISTOGRAM_TIMER("Profile.NotifyProfileCreatedTime");
629 content::NotificationService::current()->Notify(
630 chrome::NOTIFICATION_PROFILE_CREATED,
631 content::Source<Profile>(this),
632 content::NotificationService::NoDetails());
634 #if !defined(OS_CHROMEOS)
635 // Listen for bookmark model load, to bootstrap the sync service.
636 // On CrOS sync service will be initialized after sign in.
637 BookmarkModel* model = BookmarkModelFactory::GetForProfile(this);
638 model->AddObserver(new BookmarkModelLoadedObserver(this));
639 #endif
641 PushMessagingServiceImpl::InitializeForProfile(this);
643 #if !defined(OS_ANDROID) && !defined(OS_CHROMEOS) && !defined(OS_IOS)
644 signin_ui_util::InitializePrefsForProfile(this);
645 #endif
648 base::FilePath ProfileImpl::last_selected_directory() {
649 return GetPrefs()->GetFilePath(prefs::kSelectFileLastDirectory);
652 void ProfileImpl::set_last_selected_directory(const base::FilePath& path) {
653 GetPrefs()->SetFilePath(prefs::kSelectFileLastDirectory, path);
656 ProfileImpl::~ProfileImpl() {
657 MaybeSendDestroyedNotification();
659 bool prefs_loaded = prefs_->GetInitializationStatus() !=
660 PrefService::INITIALIZATION_STATUS_WAITING;
662 #if defined(ENABLE_SESSION_SERVICE)
663 StopCreateSessionServiceTimer();
664 #endif
666 // Remove pref observers
667 pref_change_registrar_.RemoveAll();
669 #if defined(ENABLE_PLUGINS)
670 ChromePluginServiceFilter::GetInstance()->UnregisterResourceContext(
671 io_data_.GetResourceContextNoInit());
672 #endif
674 // Destroy OTR profile and its profile services first.
675 if (off_the_record_profile_) {
676 ProfileDestroyer::DestroyOffTheRecordProfileNow(
677 off_the_record_profile_.get());
678 } else {
679 #if defined(ENABLE_EXTENSIONS)
680 ExtensionPrefValueMapFactory::GetForBrowserContext(this)->
681 ClearAllIncognitoSessionOnlyPreferences();
682 #endif
685 BrowserContextDependencyManager::GetInstance()->DestroyBrowserContextServices(
686 this);
688 if (pref_proxy_config_tracker_)
689 pref_proxy_config_tracker_->DetachFromPrefService();
691 if (host_content_settings_map_.get())
692 host_content_settings_map_->ShutdownOnUIThread();
694 // This causes the Preferences file to be written to disk.
695 if (prefs_loaded)
696 SetExitType(EXIT_NORMAL);
699 std::string ProfileImpl::GetProfileUserName() const {
700 const SigninManagerBase* signin_manager =
701 SigninManagerFactory::GetForProfileIfExists(this);
702 if (signin_manager)
703 return signin_manager->GetAuthenticatedAccountInfo().email;
705 return std::string();
708 Profile::ProfileType ProfileImpl::GetProfileType() const {
709 return REGULAR_PROFILE;
712 scoped_ptr<content::ZoomLevelDelegate>
713 ProfileImpl::CreateZoomLevelDelegate(const base::FilePath& partition_path) {
714 return make_scoped_ptr(new chrome::ChromeZoomLevelPrefs(
715 GetPrefs(), GetPath(), partition_path,
716 ui_zoom::ZoomEventManager::GetForBrowserContext(this)->GetWeakPtr()));
719 base::FilePath ProfileImpl::GetPath() const {
720 return path_;
723 scoped_refptr<base::SequencedTaskRunner> ProfileImpl::GetIOTaskRunner() {
724 return JsonPrefStore::GetTaskRunnerForFile(
725 GetPath(), BrowserThread::GetBlockingPool());
728 bool ProfileImpl::IsOffTheRecord() const {
729 return false;
732 Profile* ProfileImpl::GetOffTheRecordProfile() {
733 if (!off_the_record_profile_) {
734 scoped_ptr<Profile> p(CreateOffTheRecordProfile());
735 off_the_record_profile_.swap(p);
737 content::NotificationService::current()->Notify(
738 chrome::NOTIFICATION_PROFILE_CREATED,
739 content::Source<Profile>(off_the_record_profile_.get()),
740 content::NotificationService::NoDetails());
742 return off_the_record_profile_.get();
745 void ProfileImpl::DestroyOffTheRecordProfile() {
746 off_the_record_profile_.reset();
747 #if defined(ENABLE_EXTENSIONS)
748 ExtensionPrefValueMapFactory::GetForBrowserContext(this)->
749 ClearAllIncognitoSessionOnlyPreferences();
750 #endif
753 bool ProfileImpl::HasOffTheRecordProfile() {
754 return off_the_record_profile_.get() != NULL;
757 Profile* ProfileImpl::GetOriginalProfile() {
758 return this;
761 bool ProfileImpl::IsSupervised() const {
762 return !GetPrefs()->GetString(prefs::kSupervisedUserId).empty();
765 bool ProfileImpl::IsChild() const {
766 #if defined(ENABLE_SUPERVISED_USERS)
767 return GetPrefs()->GetString(prefs::kSupervisedUserId) ==
768 supervised_users::kChildAccountSUID;
769 #else
770 return false;
771 #endif
774 bool ProfileImpl::IsLegacySupervised() const {
775 return IsSupervised() && !IsChild();
778 ExtensionSpecialStoragePolicy*
779 ProfileImpl::GetExtensionSpecialStoragePolicy() {
780 #if defined(ENABLE_EXTENSIONS)
781 if (!extension_special_storage_policy_.get()) {
782 TRACE_EVENT0("browser", "ProfileImpl::GetExtensionSpecialStoragePolicy")
783 extension_special_storage_policy_ = new ExtensionSpecialStoragePolicy(
784 CookieSettingsFactory::GetForProfile(this).get());
786 return extension_special_storage_policy_.get();
787 #else
788 return NULL;
789 #endif
792 void ProfileImpl::OnLocaleReady() {
793 TRACE_EVENT0("browser", "ProfileImpl::OnLocaleReady");
794 SCOPED_UMA_HISTOGRAM_TIMER("Profile.OnLocaleReadyTime");
795 // Migrate obsolete prefs.
796 if (g_browser_process->local_state())
797 chrome::MigrateObsoleteBrowserPrefs(this, g_browser_process->local_state());
798 chrome::MigrateObsoleteProfilePrefs(this);
800 // |kSessionExitType| was added after |kSessionExitedCleanly|. If the pref
801 // value is empty fallback to checking for |kSessionExitedCleanly|.
802 const std::string exit_type_pref_value(
803 prefs_->GetString(prefs::kSessionExitType));
804 if (exit_type_pref_value.empty()) {
805 last_session_exit_type_ =
806 prefs_->GetBoolean(prefs::kSessionExitedCleanly) ?
807 EXIT_NORMAL : EXIT_CRASHED;
808 } else {
809 last_session_exit_type_ =
810 SessionTypePrefValueToExitType(exit_type_pref_value);
812 // Mark the session as open.
813 prefs_->SetString(prefs::kSessionExitType, kPrefExitTypeCrashed);
814 // Force this to true in case we fallback and use it.
815 // TODO(sky): remove this in a couple of releases (m28ish).
816 prefs_->SetBoolean(prefs::kSessionExitedCleanly, true);
818 #if defined(SAFE_BROWSING_DB_REMOTE)
819 // Hardcode this pref on this build of Android until the UX is developed.
820 // http://crbug.com/481558
821 prefs_->SetBoolean(prefs::kSafeBrowsingEnabled, true);
822 #endif
824 g_browser_process->profile_manager()->InitProfileUserPrefs(this);
827 SCOPED_UMA_HISTOGRAM_TIMER("Profile.CreateBrowserContextServicesTime");
828 BrowserContextDependencyManager::GetInstance()->
829 CreateBrowserContextServices(this);
832 DCHECK(!net_pref_observer_);
834 TRACE_EVENT0("browser", "ProfileImpl::OnPrefsLoaded:NetPrefObserver")
835 net_pref_observer_.reset(new NetPrefObserver(prefs_.get()));
838 chrome_prefs::SchedulePrefsFilePathVerification(path_);
840 ChromeVersionService::OnProfileLoaded(prefs_.get(), IsNewProfile());
841 DoFinalInit();
844 void ProfileImpl::OnPrefsLoaded(CreateMode create_mode, bool success) {
845 TRACE_EVENT0("browser", "ProfileImpl::OnPrefsLoaded");
846 if (!success) {
847 if (delegate_)
848 delegate_->OnProfileCreated(this, false, false);
849 return;
852 #if defined(OS_CHROMEOS)
853 if (create_mode == CREATE_MODE_SYNCHRONOUS) {
854 // Synchronous create mode implies that either it is restart after crash,
855 // or we are in tests. In both cases the first loaded locale is correct.
856 OnLocaleReady();
857 } else {
858 chromeos::UserSessionManager::GetInstance()->RespectLocalePreferenceWrapper(
859 this, base::Bind(&ProfileImpl::OnLocaleReady, base::Unretained(this)));
861 #else
862 OnLocaleReady();
863 #endif
866 bool ProfileImpl::WasCreatedByVersionOrLater(const std::string& version) {
867 Version profile_version(ChromeVersionService::GetVersion(prefs_.get()));
868 Version arg_version(version);
869 return (profile_version.CompareTo(arg_version) >= 0);
872 void ProfileImpl::SetExitType(ExitType exit_type) {
873 #if defined(OS_CHROMEOS)
874 if (chromeos::ProfileHelper::IsSigninProfile(this))
875 return;
876 #endif
877 if (!prefs_)
878 return;
879 ExitType current_exit_type = SessionTypePrefValueToExitType(
880 prefs_->GetString(prefs::kSessionExitType));
881 // This may be invoked multiple times during shutdown. Only persist the value
882 // first passed in (unless it's a reset to the crash state, which happens when
883 // foregrounding the app on mobile).
884 if (exit_type == EXIT_CRASHED || current_exit_type == EXIT_CRASHED) {
885 prefs_->SetString(prefs::kSessionExitType,
886 ExitTypeToSessionTypePrefValue(exit_type));
890 Profile::ExitType ProfileImpl::GetLastSessionExitType() {
891 // last_session_exited_cleanly_ is set when the preferences are loaded. Force
892 // it to be set by asking for the prefs.
893 GetPrefs();
894 return last_session_exit_type_;
897 PrefService* ProfileImpl::GetPrefs() {
898 return const_cast<PrefService*>(
899 static_cast<const ProfileImpl*>(this)->GetPrefs());
902 const PrefService* ProfileImpl::GetPrefs() const {
903 DCHECK(prefs_); // Should explicitly be initialized.
904 return prefs_.get();
907 chrome::ChromeZoomLevelPrefs* ProfileImpl::GetZoomLevelPrefs() {
908 return static_cast<chrome::ChromeZoomLevelPrefs*>(
909 GetDefaultStoragePartition(this)->GetZoomLevelDelegate());
912 PrefService* ProfileImpl::GetOffTheRecordPrefs() {
913 DCHECK(prefs_);
914 if (!otr_prefs_) {
915 // The new ExtensionPrefStore is ref_counted and the new PrefService
916 // stores a reference so that we do not leak memory here.
917 otr_prefs_.reset(prefs_->CreateIncognitoPrefService(
918 CreateExtensionPrefStore(this, true)));
920 return otr_prefs_.get();
923 net::URLRequestContextGetter* ProfileImpl::CreateRequestContext(
924 content::ProtocolHandlerMap* protocol_handlers,
925 content::URLRequestInterceptorScopedVector request_interceptors) {
926 return io_data_.CreateMainRequestContextGetter(
927 protocol_handlers,
928 request_interceptors.Pass(),
929 g_browser_process->local_state(),
930 g_browser_process->io_thread()).get();
933 net::URLRequestContextGetter* ProfileImpl::GetRequestContext() {
934 return GetDefaultStoragePartition(this)->GetURLRequestContext();
937 net::URLRequestContextGetter* ProfileImpl::GetRequestContextForRenderProcess(
938 int renderer_child_id) {
939 content::RenderProcessHost* rph = content::RenderProcessHost::FromID(
940 renderer_child_id);
942 return rph->GetStoragePartition()->GetURLRequestContext();
945 net::URLRequestContextGetter* ProfileImpl::GetMediaRequestContext() {
946 // Return the default media context.
947 return io_data_.GetMediaRequestContextGetter().get();
950 net::URLRequestContextGetter*
951 ProfileImpl::GetMediaRequestContextForRenderProcess(
952 int renderer_child_id) {
953 content::RenderProcessHost* rph = content::RenderProcessHost::FromID(
954 renderer_child_id);
955 content::StoragePartition* storage_partition = rph->GetStoragePartition();
957 return storage_partition->GetMediaURLRequestContext();
960 net::URLRequestContextGetter*
961 ProfileImpl::GetMediaRequestContextForStoragePartition(
962 const base::FilePath& partition_path,
963 bool in_memory) {
964 return io_data_
965 .GetIsolatedMediaRequestContextGetter(partition_path, in_memory).get();
968 content::ResourceContext* ProfileImpl::GetResourceContext() {
969 return io_data_.GetResourceContext();
972 net::URLRequestContextGetter* ProfileImpl::GetRequestContextForExtensions() {
973 return io_data_.GetExtensionsRequestContextGetter().get();
976 net::URLRequestContextGetter*
977 ProfileImpl::CreateRequestContextForStoragePartition(
978 const base::FilePath& partition_path,
979 bool in_memory,
980 content::ProtocolHandlerMap* protocol_handlers,
981 content::URLRequestInterceptorScopedVector request_interceptors) {
982 return io_data_.CreateIsolatedAppRequestContextGetter(
983 partition_path,
984 in_memory,
985 protocol_handlers,
986 request_interceptors.Pass()).get();
989 net::SSLConfigService* ProfileImpl::GetSSLConfigService() {
990 // If ssl_config_service_manager_ is null, this typically means that some
991 // KeyedService is trying to create a RequestContext at startup,
992 // but SSLConfigServiceManager is not initialized until DoFinalInit() which is
993 // invoked after all KeyedServices have been initialized (see
994 // http://crbug.com/171406).
995 DCHECK(ssl_config_service_manager_) <<
996 "SSLConfigServiceManager is not initialized yet";
997 return ssl_config_service_manager_->Get();
1000 HostContentSettingsMap* ProfileImpl::GetHostContentSettingsMap() {
1001 DCHECK_CURRENTLY_ON(BrowserThread::UI);
1002 if (!host_content_settings_map_.get()) {
1003 host_content_settings_map_ = new HostContentSettingsMap(GetPrefs(), false);
1004 #if defined(ENABLE_SUPERVISED_USERS)
1005 SupervisedUserSettingsService* supervised_user_settings =
1006 SupervisedUserSettingsServiceFactory::GetForProfile(this);
1007 scoped_ptr<content_settings::SupervisedProvider> supervised_provider(
1008 new content_settings::SupervisedProvider(supervised_user_settings));
1009 host_content_settings_map_->RegisterProvider(
1010 HostContentSettingsMap::SUPERVISED_PROVIDER,
1011 supervised_provider.Pass());
1012 #endif
1014 return host_content_settings_map_.get();
1017 content::BrowserPluginGuestManager* ProfileImpl::GetGuestManager() {
1018 #if defined(ENABLE_EXTENSIONS)
1019 return guest_view::GuestViewManager::FromBrowserContext(this);
1020 #else
1021 return NULL;
1022 #endif
1025 DownloadManagerDelegate* ProfileImpl::GetDownloadManagerDelegate() {
1026 return DownloadServiceFactory::GetForBrowserContext(this)->
1027 GetDownloadManagerDelegate();
1030 storage::SpecialStoragePolicy* ProfileImpl::GetSpecialStoragePolicy() {
1031 #if defined(ENABLE_EXTENSIONS)
1032 return GetExtensionSpecialStoragePolicy();
1033 #else
1034 return NULL;
1035 #endif
1038 content::PushMessagingService* ProfileImpl::GetPushMessagingService() {
1039 return PushMessagingServiceFactory::GetForProfile(this);
1042 content::SSLHostStateDelegate* ProfileImpl::GetSSLHostStateDelegate() {
1043 return ChromeSSLHostStateDelegateFactory::GetForProfile(this);
1046 // TODO(mlamouri): we should all these BrowserContext implementation to Profile
1047 // instead of repeating them inside all Profile implementations.
1048 content::PermissionManager* ProfileImpl::GetPermissionManager() {
1049 return PermissionManagerFactory::GetForProfile(this);
1052 bool ProfileImpl::IsSameProfile(Profile* profile) {
1053 if (profile == static_cast<Profile*>(this))
1054 return true;
1055 Profile* otr_profile = off_the_record_profile_.get();
1056 return otr_profile && profile == otr_profile;
1059 Time ProfileImpl::GetStartTime() const {
1060 return start_time_;
1063 #if defined(ENABLE_SESSION_SERVICE)
1064 void ProfileImpl::StopCreateSessionServiceTimer() {
1065 create_session_service_timer_.Stop();
1068 void ProfileImpl::EnsureSessionServiceCreated() {
1069 SessionServiceFactory::GetForProfile(this);
1071 #endif
1073 #if defined(OS_CHROMEOS)
1074 void ProfileImpl::ChangeAppLocale(
1075 const std::string& new_locale, AppLocaleChangedVia via) {
1076 if (new_locale.empty()) {
1077 NOTREACHED();
1078 return;
1080 PrefService* local_state = g_browser_process->local_state();
1081 DCHECK(local_state);
1082 if (local_state->IsManagedPreference(prefs::kApplicationLocale))
1083 return;
1084 std::string pref_locale = GetPrefs()->GetString(prefs::kApplicationLocale);
1085 bool do_update_pref = true;
1086 switch (via) {
1087 case APP_LOCALE_CHANGED_VIA_SETTINGS:
1088 case APP_LOCALE_CHANGED_VIA_REVERT: {
1089 // We keep kApplicationLocaleBackup value as a reference. In case value
1090 // of kApplicationLocale preference would change due to sync from other
1091 // device then kApplicationLocaleBackup value will trigger and allow us to
1092 // show notification about automatic locale change in LocaleChangeGuard.
1093 GetPrefs()->SetString(prefs::kApplicationLocaleBackup, new_locale);
1094 GetPrefs()->ClearPref(prefs::kApplicationLocaleAccepted);
1095 // We maintain kApplicationLocale property in both a global storage
1096 // and user's profile. Global property determines locale of login screen,
1097 // while user's profile determines his personal locale preference.
1098 break;
1100 case APP_LOCALE_CHANGED_VIA_LOGIN:
1101 case APP_LOCALE_CHANGED_VIA_PUBLIC_SESSION_LOGIN: {
1102 if (!pref_locale.empty()) {
1103 DCHECK(pref_locale == new_locale);
1104 std::string accepted_locale =
1105 GetPrefs()->GetString(prefs::kApplicationLocaleAccepted);
1106 if (accepted_locale == new_locale) {
1107 // If locale is accepted then we do not want to show LocaleChange
1108 // notification. This notification is triggered by different values
1109 // of kApplicationLocaleBackup and kApplicationLocale preferences,
1110 // so make them identical.
1111 GetPrefs()->SetString(prefs::kApplicationLocaleBackup, new_locale);
1112 } else {
1113 // Back up locale of login screen.
1114 std::string cur_locale = g_browser_process->GetApplicationLocale();
1115 GetPrefs()->SetString(prefs::kApplicationLocaleBackup, cur_locale);
1116 if (locale_change_guard_ == NULL)
1117 locale_change_guard_.reset(new chromeos::LocaleChangeGuard(this));
1118 locale_change_guard_->PrepareChangingLocale(cur_locale, new_locale);
1120 } else {
1121 std::string cur_locale = g_browser_process->GetApplicationLocale();
1122 std::string backup_locale =
1123 GetPrefs()->GetString(prefs::kApplicationLocaleBackup);
1124 // Profile synchronization takes time and is not completed at that
1125 // moment at first login. So we initialize locale preference in steps:
1126 // (1) first save it to temporary backup;
1127 // (2) on next login we assume that synchronization is already completed
1128 // and we may finalize initialization.
1129 GetPrefs()->SetString(prefs::kApplicationLocaleBackup, cur_locale);
1130 if (!new_locale.empty())
1131 GetPrefs()->SetString(prefs::kApplicationLocale, new_locale);
1132 else if (!backup_locale.empty())
1133 GetPrefs()->SetString(prefs::kApplicationLocale, backup_locale);
1134 do_update_pref = false;
1136 break;
1138 case APP_LOCALE_CHANGED_VIA_UNKNOWN:
1139 default: {
1140 NOTREACHED();
1141 break;
1144 if (do_update_pref)
1145 GetPrefs()->SetString(prefs::kApplicationLocale, new_locale);
1146 if (via != APP_LOCALE_CHANGED_VIA_PUBLIC_SESSION_LOGIN)
1147 local_state->SetString(prefs::kApplicationLocale, new_locale);
1149 if (user_manager::UserManager::Get()->GetOwnerEmail() ==
1150 chromeos::ProfileHelper::Get()->GetUserByProfile(this)->email())
1151 local_state->SetString(prefs::kOwnerLocale, new_locale);
1154 void ProfileImpl::OnLogin() {
1155 if (locale_change_guard_ == NULL)
1156 locale_change_guard_.reset(new chromeos::LocaleChangeGuard(this));
1157 locale_change_guard_->OnLogin();
1160 void ProfileImpl::InitChromeOSPreferences() {
1161 chromeos_preferences_.reset(new chromeos::Preferences());
1162 chromeos_preferences_->Init(
1163 this, chromeos::ProfileHelper::Get()->GetUserByProfile(this));
1166 #endif // defined(OS_CHROMEOS)
1168 PrefProxyConfigTracker* ProfileImpl::GetProxyConfigTracker() {
1169 if (!pref_proxy_config_tracker_)
1170 pref_proxy_config_tracker_.reset(CreateProxyConfigTracker());
1171 return pref_proxy_config_tracker_.get();
1174 chrome_browser_net::Predictor* ProfileImpl::GetNetworkPredictor() {
1175 return predictor_;
1178 DevToolsNetworkControllerHandle*
1179 ProfileImpl::GetDevToolsNetworkControllerHandle() {
1180 return io_data_.GetDevToolsNetworkControllerHandle();
1183 void ProfileImpl::ClearNetworkingHistorySince(
1184 base::Time time,
1185 const base::Closure& completion) {
1186 io_data_.ClearNetworkingHistorySince(time, completion);
1189 GURL ProfileImpl::GetHomePage() {
1190 // --homepage overrides any preferences.
1191 const base::CommandLine& command_line =
1192 *base::CommandLine::ForCurrentProcess();
1193 if (command_line.HasSwitch(switches::kHomePage)) {
1194 // TODO(evanm): clean up usage of DIR_CURRENT.
1195 // http://code.google.com/p/chromium/issues/detail?id=60630
1196 // For now, allow this code to call getcwd().
1197 base::ThreadRestrictions::ScopedAllowIO allow_io;
1199 base::FilePath browser_directory;
1200 PathService::Get(base::DIR_CURRENT, &browser_directory);
1201 GURL home_page(url_formatter::FixupRelativeFile(
1202 browser_directory,
1203 command_line.GetSwitchValuePath(switches::kHomePage)));
1204 if (home_page.is_valid())
1205 return home_page;
1208 if (GetPrefs()->GetBoolean(prefs::kHomePageIsNewTabPage))
1209 return GURL(chrome::kChromeUINewTabURL);
1210 GURL home_page(url_formatter::FixupURL(
1211 GetPrefs()->GetString(prefs::kHomePage), std::string()));
1212 if (!home_page.is_valid())
1213 return GURL(chrome::kChromeUINewTabURL);
1214 return home_page;
1217 void ProfileImpl::UpdateProfileSupervisedUserIdCache() {
1218 ProfileManager* profile_manager = g_browser_process->profile_manager();
1219 ProfileInfoCache& cache = profile_manager->GetProfileInfoCache();
1220 size_t index = cache.GetIndexOfProfileWithPath(GetPath());
1221 if (index != std::string::npos) {
1222 std::string supervised_user_id =
1223 GetPrefs()->GetString(prefs::kSupervisedUserId);
1224 cache.SetSupervisedUserIdOfProfileAtIndex(index, supervised_user_id);
1225 ProfileMetrics::UpdateReportedProfilesStatistics(profile_manager);
1229 void ProfileImpl::UpdateProfileNameCache() {
1230 ProfileManager* profile_manager = g_browser_process->profile_manager();
1231 ProfileInfoCache& cache = profile_manager->GetProfileInfoCache();
1232 size_t index = cache.GetIndexOfProfileWithPath(GetPath());
1233 if (index != std::string::npos) {
1234 std::string profile_name =
1235 GetPrefs()->GetString(prefs::kProfileName);
1236 cache.SetNameOfProfileAtIndex(index, base::UTF8ToUTF16(profile_name));
1237 bool default_name =
1238 GetPrefs()->GetBoolean(prefs::kProfileUsingDefaultName);
1239 cache.SetProfileIsUsingDefaultNameAtIndex(index, default_name);
1243 void ProfileImpl::UpdateProfileAvatarCache() {
1244 ProfileManager* profile_manager = g_browser_process->profile_manager();
1245 ProfileInfoCache& cache = profile_manager->GetProfileInfoCache();
1246 size_t index = cache.GetIndexOfProfileWithPath(GetPath());
1247 if (index != std::string::npos) {
1248 size_t avatar_index =
1249 GetPrefs()->GetInteger(prefs::kProfileAvatarIndex);
1250 cache.SetAvatarIconOfProfileAtIndex(index, avatar_index);
1251 bool default_avatar =
1252 GetPrefs()->GetBoolean(prefs::kProfileUsingDefaultAvatar);
1253 cache.SetProfileIsUsingDefaultAvatarAtIndex(index, default_avatar);
1254 bool gaia_avatar =
1255 GetPrefs()->GetBoolean(prefs::kProfileUsingGAIAAvatar);
1256 cache.SetIsUsingGAIAPictureOfProfileAtIndex(index, gaia_avatar);
1260 void ProfileImpl::UpdateProfileIsEphemeralCache() {
1261 ProfileManager* profile_manager = g_browser_process->profile_manager();
1262 ProfileInfoCache& cache = profile_manager->GetProfileInfoCache();
1263 size_t index = cache.GetIndexOfProfileWithPath(GetPath());
1264 if (index != std::string::npos) {
1265 bool is_ephemeral = GetPrefs()->GetBoolean(prefs::kForceEphemeralProfiles);
1266 cache.SetProfileIsEphemeralAtIndex(index, is_ephemeral);
1270 // Gets the cache parameters from the command line. If |is_media_context| is
1271 // set to true then settings for the media context type is what we need,
1272 // |cache_path| will be set to the user provided path, or will not be touched if
1273 // there is not an argument. |max_size| will be the user provided value or zero
1274 // by default.
1275 void ProfileImpl::GetCacheParameters(bool is_media_context,
1276 base::FilePath* cache_path,
1277 int* max_size) {
1278 DCHECK(cache_path);
1279 DCHECK(max_size);
1280 base::FilePath path(prefs_->GetFilePath(prefs::kDiskCacheDir));
1281 if (!path.empty())
1282 *cache_path = path;
1283 *max_size = is_media_context ? prefs_->GetInteger(prefs::kMediaCacheSize) :
1284 prefs_->GetInteger(prefs::kDiskCacheSize);
1287 PrefProxyConfigTracker* ProfileImpl::CreateProxyConfigTracker() {
1288 #if defined(OS_CHROMEOS)
1289 if (chromeos::ProfileHelper::IsSigninProfile(this)) {
1290 return ProxyServiceFactory::CreatePrefProxyConfigTrackerOfLocalState(
1291 g_browser_process->local_state());
1293 #endif // defined(OS_CHROMEOS)
1294 return ProxyServiceFactory::CreatePrefProxyConfigTrackerOfProfile(
1295 GetPrefs(), g_browser_process->local_state());
1298 scoped_ptr<domain_reliability::DomainReliabilityMonitor>
1299 ProfileImpl::CreateDomainReliabilityMonitor(PrefService* local_state) {
1300 domain_reliability::DomainReliabilityService* service =
1301 domain_reliability::DomainReliabilityServiceFactory::GetInstance()->
1302 GetForBrowserContext(this);
1303 if (!service)
1304 return scoped_ptr<domain_reliability::DomainReliabilityMonitor>();
1306 return service->CreateMonitor(
1307 BrowserThread::GetMessageLoopProxyForThread(BrowserThread::IO));