Popular sites on the NTP: check that experiment group StartsWith (rather than IS...
[chromium-blink-merge.git] / chrome / browser / profiles / profile_impl.cc
blob9ee9a804212c0e234fb56b3e86f53960d37a069e
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/content_settings/host_content_settings_map_factory.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/proxy_service_factory.h"
45 #include "chrome/browser/net/ssl_config_service_manager.h"
46 #include "chrome/browser/permissions/permission_manager.h"
47 #include "chrome/browser/permissions/permission_manager_factory.h"
48 #include "chrome/browser/plugins/chrome_plugin_service_filter.h"
49 #include "chrome/browser/plugins/plugin_prefs.h"
50 #include "chrome/browser/policy/profile_policy_connector.h"
51 #include "chrome/browser/policy/profile_policy_connector_factory.h"
52 #include "chrome/browser/prefs/browser_prefs.h"
53 #include "chrome/browser/prefs/chrome_pref_service_factory.h"
54 #include "chrome/browser/prefs/pref_service_syncable.h"
55 #include "chrome/browser/prerender/prerender_manager_factory.h"
56 #include "chrome/browser/profiles/bookmark_model_loaded_observer.h"
57 #include "chrome/browser/profiles/chrome_version_service.h"
58 #include "chrome/browser/profiles/gaia_info_update_service_factory.h"
59 #include "chrome/browser/profiles/profile_destroyer.h"
60 #include "chrome/browser/profiles/profile_info_cache.h"
61 #include "chrome/browser/profiles/profile_manager.h"
62 #include "chrome/browser/profiles/profile_metrics.h"
63 #include "chrome/browser/push_messaging/push_messaging_service_factory.h"
64 #include "chrome/browser/push_messaging/push_messaging_service_impl.h"
65 #include "chrome/browser/safe_browsing/safe_browsing_service.h"
66 #include "chrome/browser/services/gcm/gcm_profile_service.h"
67 #include "chrome/browser/sessions/session_service_factory.h"
68 #include "chrome/browser/signin/signin_manager_factory.h"
69 #include "chrome/browser/signin/signin_ui_util.h"
70 #include "chrome/browser/ssl/chrome_ssl_host_state_delegate.h"
71 #include "chrome/browser/ssl/chrome_ssl_host_state_delegate_factory.h"
72 #include "chrome/browser/ui/startup/startup_browser_creator.h"
73 #include "chrome/common/chrome_constants.h"
74 #include "chrome/common/chrome_paths_internal.h"
75 #include "chrome/common/chrome_switches.h"
76 #include "chrome/common/pref_names.h"
77 #include "chrome/common/url_constants.h"
78 #include "chrome/grit/chromium_strings.h"
79 #include "components/bookmarks/browser/bookmark_model.h"
80 #include "components/content_settings/core/browser/cookie_settings.h"
81 #include "components/content_settings/core/browser/host_content_settings_map.h"
82 #include "components/domain_reliability/monitor.h"
83 #include "components/domain_reliability/service.h"
84 #include "components/keyed_service/content/browser_context_dependency_manager.h"
85 #include "components/metrics/metrics_service.h"
86 #include "components/omnibox/browser/autocomplete_classifier.h"
87 #include "components/omnibox/browser/shortcuts_backend.h"
88 #include "components/pref_registry/pref_registry_syncable.h"
89 #include "components/proxy_config/pref_proxy_config_tracker.h"
90 #include "components/signin/core/browser/signin_manager.h"
91 #include "components/ui/zoom/zoom_event_manager.h"
92 #include "components/url_formatter/url_fixer.h"
93 #include "components/user_prefs/tracked/tracked_preference_validation_delegate.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 "components/guest_view/browser/guest_view_manager.h"
141 #include "extensions/browser/extension_pref_store.h"
142 #include "extensions/browser/extension_pref_value_map.h"
143 #include "extensions/browser/extension_pref_value_map_factory.h"
144 #include "extensions/browser/extension_system.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 void CreateProfileReadme(const base::FilePath& profile_path) {
181 base::ThreadRestrictions::AssertIOAllowed();
182 base::FilePath readme_path = profile_path.Append(chrome::kReadmeFilename);
183 std::string product_name = l10n_util::GetStringUTF8(IDS_PRODUCT_NAME);
184 std::string readme_text = base::StringPrintf(
185 kReadmeText, product_name.c_str(), product_name.c_str());
186 if (base::WriteFile(readme_path, readme_text.data(), readme_text.size()) ==
187 -1) {
188 LOG(ERROR) << "Could not create README file.";
192 // Helper method needed because PostTask cannot currently take a Callback
193 // function with non-void return type.
194 void CreateDirectoryAndSignal(const base::FilePath& path,
195 base::WaitableEvent* done_creating,
196 bool create_readme) {
197 // If the readme exists, the profile directory must also already exist.
198 base::FilePath readme_path = path.Append(chrome::kReadmeFilename);
199 if (base::PathExists(readme_path)) {
200 done_creating->Signal();
201 return;
204 DVLOG(1) << "Creating directory " << path.value();
205 if (base::CreateDirectory(path) && create_readme)
206 CreateProfileReadme(path);
207 done_creating->Signal();
210 // Task that blocks the FILE thread until CreateDirectoryAndSignal() finishes on
211 // blocking I/O pool.
212 void BlockFileThreadOnDirectoryCreate(base::WaitableEvent* done_creating) {
213 done_creating->Wait();
216 // Initiates creation of profile directory on |sequenced_task_runner| and
217 // ensures that FILE thread is blocked until that operation finishes. If
218 // |create_readme| is true, the profile README will be created in the profile
219 // directory.
220 void CreateProfileDirectory(base::SequencedTaskRunner* sequenced_task_runner,
221 const base::FilePath& path,
222 bool create_readme) {
223 base::WaitableEvent* done_creating = new base::WaitableEvent(false, false);
224 sequenced_task_runner->PostTask(
225 FROM_HERE, base::Bind(&CreateDirectoryAndSignal, path, done_creating,
226 create_readme));
227 // Block the FILE thread until directory is created on I/O pool to make sure
228 // that we don't attempt any operation until that part completes.
229 BrowserThread::PostTask(
230 BrowserThread::FILE, FROM_HERE,
231 base::Bind(&BlockFileThreadOnDirectoryCreate,
232 base::Owned(done_creating)));
235 base::FilePath GetCachePath(const base::FilePath& base) {
236 return base.Append(chrome::kCacheDirname);
239 base::FilePath GetMediaCachePath(const base::FilePath& base) {
240 return base.Append(chrome::kMediaCacheDirname);
243 // Converts the kSessionExitedCleanly pref to the corresponding EXIT_TYPE.
244 Profile::ExitType SessionTypePrefValueToExitType(const std::string& value) {
245 if (value == kPrefExitTypeSessionEnded)
246 return Profile::EXIT_SESSION_ENDED;
247 if (value == kPrefExitTypeCrashed)
248 return Profile::EXIT_CRASHED;
249 return Profile::EXIT_NORMAL;
252 // Converts an ExitType into a string that is written to prefs.
253 std::string ExitTypeToSessionTypePrefValue(Profile::ExitType type) {
254 switch (type) {
255 case Profile::EXIT_NORMAL:
256 return ProfileImpl::kPrefExitTypeNormal;
257 case Profile::EXIT_SESSION_ENDED:
258 return kPrefExitTypeSessionEnded;
259 case Profile::EXIT_CRASHED:
260 return kPrefExitTypeCrashed;
262 NOTREACHED();
263 return std::string();
266 PrefStore* CreateExtensionPrefStore(Profile* profile,
267 bool incognito_pref_store) {
268 #if defined(ENABLE_EXTENSIONS)
269 return new ExtensionPrefStore(
270 ExtensionPrefValueMapFactory::GetForBrowserContext(profile),
271 incognito_pref_store);
272 #else
273 return NULL;
274 #endif
277 } // namespace
279 // static
280 Profile* Profile::CreateProfile(const base::FilePath& path,
281 Delegate* delegate,
282 CreateMode create_mode) {
283 TRACE_EVENT1("browser,startup",
284 "Profile::CreateProfile",
285 "profile_path",
286 path.AsUTF8Unsafe());
288 // Get sequenced task runner for making sure that file operations of
289 // this profile (defined by |path|) are executed in expected order
290 // (what was previously assured by the FILE thread).
291 scoped_refptr<base::SequencedTaskRunner> sequenced_task_runner =
292 JsonPrefStore::GetTaskRunnerForFile(path,
293 BrowserThread::GetBlockingPool());
294 if (create_mode == CREATE_MODE_ASYNCHRONOUS) {
295 DCHECK(delegate);
296 CreateProfileDirectory(sequenced_task_runner.get(), path, true);
297 } else if (create_mode == CREATE_MODE_SYNCHRONOUS) {
298 if (!base::PathExists(path)) {
299 // TODO(rogerta): http://crbug/160553 - Bad things happen if we can't
300 // write to the profile directory. We should eventually be able to run in
301 // this situation.
302 if (!base::CreateDirectory(path))
303 return NULL;
305 CreateProfileReadme(path);
307 } else {
308 NOTREACHED();
311 return new ProfileImpl(
312 path, delegate, create_mode, sequenced_task_runner.get());
315 // static
316 const char* const ProfileImpl::kPrefExitTypeNormal = "Normal";
318 // static
319 void ProfileImpl::RegisterProfilePrefs(
320 user_prefs::PrefRegistrySyncable* registry) {
321 registry->RegisterBooleanPref(prefs::kSavingBrowserHistoryDisabled, false);
322 registry->RegisterBooleanPref(prefs::kAllowDeletingBrowserHistory, true);
323 registry->RegisterBooleanPref(prefs::kSigninAllowed, true);
324 registry->RegisterBooleanPref(prefs::kForceGoogleSafeSearch, false);
325 registry->RegisterBooleanPref(prefs::kForceYouTubeSafetyMode, false);
326 registry->RegisterBooleanPref(prefs::kRecordHistory, false);
327 registry->RegisterIntegerPref(
328 prefs::kProfileAvatarIndex,
330 user_prefs::PrefRegistrySyncable::SYNCABLE_PREF);
331 // Whether a profile is using an avatar without having explicitely chosen it
332 // (i.e. was assigned by default by legacy profile creation).
333 registry->RegisterBooleanPref(
334 prefs::kProfileUsingDefaultAvatar,
335 true,
336 user_prefs::PrefRegistrySyncable::SYNCABLE_PREF);
337 registry->RegisterBooleanPref(
338 prefs::kProfileUsingGAIAAvatar,
339 false,
340 user_prefs::PrefRegistrySyncable::SYNCABLE_PREF);
341 // Whether a profile is using a default avatar name (eg. Pickles or Person 1).
342 registry->RegisterBooleanPref(
343 prefs::kProfileUsingDefaultName,
344 true,
345 user_prefs::PrefRegistrySyncable::SYNCABLE_PREF);
346 registry->RegisterStringPref(prefs::kSupervisedUserId, std::string());
347 registry->RegisterStringPref(prefs::kProfileName,
348 std::string(),
349 user_prefs::PrefRegistrySyncable::SYNCABLE_PREF);
350 registry->RegisterStringPref(prefs::kHomePage,
351 std::string(),
352 user_prefs::PrefRegistrySyncable::SYNCABLE_PREF);
353 #if defined(ENABLE_PRINTING)
354 registry->RegisterBooleanPref(prefs::kPrintingEnabled, true);
355 #endif
356 registry->RegisterBooleanPref(prefs::kPrintPreviewDisabled, false);
357 registry->RegisterBooleanPref(prefs::kForceEphemeralProfiles, false);
359 // Initialize the cache prefs.
360 registry->RegisterFilePathPref(prefs::kDiskCacheDir, base::FilePath());
361 registry->RegisterIntegerPref(prefs::kDiskCacheSize, 0);
362 registry->RegisterIntegerPref(prefs::kMediaCacheSize, 0);
365 ProfileImpl::ProfileImpl(
366 const base::FilePath& path,
367 Delegate* delegate,
368 CreateMode create_mode,
369 base::SequencedTaskRunner* sequenced_task_runner)
370 : path_(path),
371 pref_registry_(new user_prefs::PrefRegistrySyncable),
372 io_data_(this),
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 // This causes the Preferences file to be written to disk.
692 if (prefs_loaded)
693 SetExitType(EXIT_NORMAL);
696 std::string ProfileImpl::GetProfileUserName() const {
697 const SigninManagerBase* signin_manager =
698 SigninManagerFactory::GetForProfileIfExists(this);
699 if (signin_manager)
700 return signin_manager->GetAuthenticatedAccountInfo().email;
702 return std::string();
705 Profile::ProfileType ProfileImpl::GetProfileType() const {
706 return REGULAR_PROFILE;
709 scoped_ptr<content::ZoomLevelDelegate> ProfileImpl::CreateZoomLevelDelegate(
710 const base::FilePath& partition_path) {
711 return make_scoped_ptr(new ChromeZoomLevelPrefs(
712 GetPrefs(), GetPath(), partition_path,
713 ui_zoom::ZoomEventManager::GetForBrowserContext(this)->GetWeakPtr()));
716 base::FilePath ProfileImpl::GetPath() const {
717 return path_;
720 scoped_refptr<base::SequencedTaskRunner> ProfileImpl::GetIOTaskRunner() {
721 return JsonPrefStore::GetTaskRunnerForFile(
722 GetPath(), BrowserThread::GetBlockingPool());
725 bool ProfileImpl::IsOffTheRecord() const {
726 return false;
729 Profile* ProfileImpl::GetOffTheRecordProfile() {
730 if (!off_the_record_profile_) {
731 scoped_ptr<Profile> p(CreateOffTheRecordProfile());
732 off_the_record_profile_.swap(p);
734 content::NotificationService::current()->Notify(
735 chrome::NOTIFICATION_PROFILE_CREATED,
736 content::Source<Profile>(off_the_record_profile_.get()),
737 content::NotificationService::NoDetails());
739 return off_the_record_profile_.get();
742 void ProfileImpl::DestroyOffTheRecordProfile() {
743 off_the_record_profile_.reset();
744 #if defined(ENABLE_EXTENSIONS)
745 ExtensionPrefValueMapFactory::GetForBrowserContext(this)->
746 ClearAllIncognitoSessionOnlyPreferences();
747 #endif
750 bool ProfileImpl::HasOffTheRecordProfile() {
751 return off_the_record_profile_.get() != NULL;
754 Profile* ProfileImpl::GetOriginalProfile() {
755 return this;
758 bool ProfileImpl::IsSupervised() const {
759 return !GetPrefs()->GetString(prefs::kSupervisedUserId).empty();
762 bool ProfileImpl::IsChild() const {
763 #if defined(ENABLE_SUPERVISED_USERS)
764 return GetPrefs()->GetString(prefs::kSupervisedUserId) ==
765 supervised_users::kChildAccountSUID;
766 #else
767 return false;
768 #endif
771 bool ProfileImpl::IsLegacySupervised() const {
772 return IsSupervised() && !IsChild();
775 ExtensionSpecialStoragePolicy*
776 ProfileImpl::GetExtensionSpecialStoragePolicy() {
777 #if defined(ENABLE_EXTENSIONS)
778 if (!extension_special_storage_policy_.get()) {
779 TRACE_EVENT0("browser", "ProfileImpl::GetExtensionSpecialStoragePolicy")
780 extension_special_storage_policy_ = new ExtensionSpecialStoragePolicy(
781 CookieSettingsFactory::GetForProfile(this).get());
783 return extension_special_storage_policy_.get();
784 #else
785 return NULL;
786 #endif
789 void ProfileImpl::OnLocaleReady() {
790 TRACE_EVENT0("browser", "ProfileImpl::OnLocaleReady");
791 SCOPED_UMA_HISTOGRAM_TIMER("Profile.OnLocaleReadyTime");
792 // Migrate obsolete prefs.
793 if (g_browser_process->local_state())
794 chrome::MigrateObsoleteBrowserPrefs(this, g_browser_process->local_state());
795 chrome::MigrateObsoleteProfilePrefs(this);
797 // |kSessionExitType| was added after |kSessionExitedCleanly|. If the pref
798 // value is empty fallback to checking for |kSessionExitedCleanly|.
799 const std::string exit_type_pref_value(
800 prefs_->GetString(prefs::kSessionExitType));
801 if (exit_type_pref_value.empty()) {
802 last_session_exit_type_ =
803 prefs_->GetBoolean(prefs::kSessionExitedCleanly) ?
804 EXIT_NORMAL : EXIT_CRASHED;
805 } else {
806 last_session_exit_type_ =
807 SessionTypePrefValueToExitType(exit_type_pref_value);
809 // Mark the session as open.
810 prefs_->SetString(prefs::kSessionExitType, kPrefExitTypeCrashed);
811 // Force this to true in case we fallback and use it.
812 // TODO(sky): remove this in a couple of releases (m28ish).
813 prefs_->SetBoolean(prefs::kSessionExitedCleanly, true);
815 g_browser_process->profile_manager()->InitProfileUserPrefs(this);
818 SCOPED_UMA_HISTOGRAM_TIMER("Profile.CreateBrowserContextServicesTime");
819 BrowserContextDependencyManager::GetInstance()->
820 CreateBrowserContextServices(this);
823 DCHECK(!net_pref_observer_);
825 TRACE_EVENT0("browser", "ProfileImpl::OnPrefsLoaded:NetPrefObserver")
826 net_pref_observer_.reset(new NetPrefObserver(prefs_.get()));
829 chrome_prefs::SchedulePrefsFilePathVerification(path_);
831 ChromeVersionService::OnProfileLoaded(prefs_.get(), IsNewProfile());
832 DoFinalInit();
835 void ProfileImpl::OnPrefsLoaded(CreateMode create_mode, bool success) {
836 TRACE_EVENT0("browser", "ProfileImpl::OnPrefsLoaded");
837 if (!success) {
838 if (delegate_)
839 delegate_->OnProfileCreated(this, false, false);
840 return;
843 #if defined(OS_CHROMEOS)
844 if (create_mode == CREATE_MODE_SYNCHRONOUS) {
845 // Synchronous create mode implies that either it is restart after crash,
846 // or we are in tests. In both cases the first loaded locale is correct.
847 OnLocaleReady();
848 } else {
849 chromeos::UserSessionManager::GetInstance()->RespectLocalePreferenceWrapper(
850 this, base::Bind(&ProfileImpl::OnLocaleReady, base::Unretained(this)));
852 #else
853 OnLocaleReady();
854 #endif
857 bool ProfileImpl::WasCreatedByVersionOrLater(const std::string& version) {
858 Version profile_version(ChromeVersionService::GetVersion(prefs_.get()));
859 Version arg_version(version);
860 return (profile_version.CompareTo(arg_version) >= 0);
863 void ProfileImpl::SetExitType(ExitType exit_type) {
864 #if defined(OS_CHROMEOS)
865 if (chromeos::ProfileHelper::IsSigninProfile(this))
866 return;
867 #endif
868 if (!prefs_)
869 return;
870 ExitType current_exit_type = SessionTypePrefValueToExitType(
871 prefs_->GetString(prefs::kSessionExitType));
872 // This may be invoked multiple times during shutdown. Only persist the value
873 // first passed in (unless it's a reset to the crash state, which happens when
874 // foregrounding the app on mobile).
875 if (exit_type == EXIT_CRASHED || current_exit_type == EXIT_CRASHED) {
876 prefs_->SetString(prefs::kSessionExitType,
877 ExitTypeToSessionTypePrefValue(exit_type));
881 Profile::ExitType ProfileImpl::GetLastSessionExitType() {
882 // last_session_exited_cleanly_ is set when the preferences are loaded. Force
883 // it to be set by asking for the prefs.
884 GetPrefs();
885 return last_session_exit_type_;
888 PrefService* ProfileImpl::GetPrefs() {
889 return const_cast<PrefService*>(
890 static_cast<const ProfileImpl*>(this)->GetPrefs());
893 const PrefService* ProfileImpl::GetPrefs() const {
894 DCHECK(prefs_); // Should explicitly be initialized.
895 return prefs_.get();
898 ChromeZoomLevelPrefs* ProfileImpl::GetZoomLevelPrefs() {
899 return static_cast<ChromeZoomLevelPrefs*>(
900 GetDefaultStoragePartition(this)->GetZoomLevelDelegate());
903 PrefService* ProfileImpl::GetOffTheRecordPrefs() {
904 DCHECK(prefs_);
905 if (!otr_prefs_) {
906 // The new ExtensionPrefStore is ref_counted and the new PrefService
907 // stores a reference so that we do not leak memory here.
908 otr_prefs_.reset(prefs_->CreateIncognitoPrefService(
909 CreateExtensionPrefStore(this, true)));
911 return otr_prefs_.get();
914 net::URLRequestContextGetter* ProfileImpl::CreateRequestContext(
915 content::ProtocolHandlerMap* protocol_handlers,
916 content::URLRequestInterceptorScopedVector request_interceptors) {
917 return io_data_.CreateMainRequestContextGetter(
918 protocol_handlers,
919 request_interceptors.Pass(),
920 g_browser_process->local_state(),
921 g_browser_process->io_thread()).get();
924 net::URLRequestContextGetter* ProfileImpl::GetRequestContext() {
925 return GetDefaultStoragePartition(this)->GetURLRequestContext();
928 net::URLRequestContextGetter* ProfileImpl::GetRequestContextForRenderProcess(
929 int renderer_child_id) {
930 content::RenderProcessHost* rph = content::RenderProcessHost::FromID(
931 renderer_child_id);
933 return rph->GetStoragePartition()->GetURLRequestContext();
936 net::URLRequestContextGetter* ProfileImpl::GetMediaRequestContext() {
937 // Return the default media context.
938 return io_data_.GetMediaRequestContextGetter().get();
941 net::URLRequestContextGetter*
942 ProfileImpl::GetMediaRequestContextForRenderProcess(
943 int renderer_child_id) {
944 content::RenderProcessHost* rph = content::RenderProcessHost::FromID(
945 renderer_child_id);
946 content::StoragePartition* storage_partition = rph->GetStoragePartition();
948 return storage_partition->GetMediaURLRequestContext();
951 net::URLRequestContextGetter*
952 ProfileImpl::GetMediaRequestContextForStoragePartition(
953 const base::FilePath& partition_path,
954 bool in_memory) {
955 return io_data_
956 .GetIsolatedMediaRequestContextGetter(partition_path, in_memory).get();
959 content::ResourceContext* ProfileImpl::GetResourceContext() {
960 return io_data_.GetResourceContext();
963 net::URLRequestContextGetter* ProfileImpl::GetRequestContextForExtensions() {
964 return io_data_.GetExtensionsRequestContextGetter().get();
967 net::URLRequestContextGetter*
968 ProfileImpl::CreateRequestContextForStoragePartition(
969 const base::FilePath& partition_path,
970 bool in_memory,
971 content::ProtocolHandlerMap* protocol_handlers,
972 content::URLRequestInterceptorScopedVector request_interceptors) {
973 return io_data_.CreateIsolatedAppRequestContextGetter(
974 partition_path,
975 in_memory,
976 protocol_handlers,
977 request_interceptors.Pass()).get();
980 net::SSLConfigService* ProfileImpl::GetSSLConfigService() {
981 // If ssl_config_service_manager_ is null, this typically means that some
982 // KeyedService is trying to create a RequestContext at startup,
983 // but SSLConfigServiceManager is not initialized until DoFinalInit() which is
984 // invoked after all KeyedServices have been initialized (see
985 // http://crbug.com/171406).
986 DCHECK(ssl_config_service_manager_) <<
987 "SSLConfigServiceManager is not initialized yet";
988 return ssl_config_service_manager_->Get();
991 HostContentSettingsMap* ProfileImpl::GetHostContentSettingsMap() {
992 // TODO(peconn): Once HostContentSettingsMapFactory works for TestingProfiles
993 // remove Profile::GetHostContentSettingsMap and replace all references to it.
994 // Don't forget to remove the #include "host_content_settings_map_factory"!
995 return HostContentSettingsMapFactory::GetForProfile(this);
998 content::BrowserPluginGuestManager* ProfileImpl::GetGuestManager() {
999 #if defined(ENABLE_EXTENSIONS)
1000 return guest_view::GuestViewManager::FromBrowserContext(this);
1001 #else
1002 return NULL;
1003 #endif
1006 DownloadManagerDelegate* ProfileImpl::GetDownloadManagerDelegate() {
1007 return DownloadServiceFactory::GetForBrowserContext(this)->
1008 GetDownloadManagerDelegate();
1011 storage::SpecialStoragePolicy* ProfileImpl::GetSpecialStoragePolicy() {
1012 #if defined(ENABLE_EXTENSIONS)
1013 return GetExtensionSpecialStoragePolicy();
1014 #else
1015 return NULL;
1016 #endif
1019 content::PushMessagingService* ProfileImpl::GetPushMessagingService() {
1020 return PushMessagingServiceFactory::GetForProfile(this);
1023 content::SSLHostStateDelegate* ProfileImpl::GetSSLHostStateDelegate() {
1024 return ChromeSSLHostStateDelegateFactory::GetForProfile(this);
1027 // TODO(mlamouri): we should all these BrowserContext implementation to Profile
1028 // instead of repeating them inside all Profile implementations.
1029 content::PermissionManager* ProfileImpl::GetPermissionManager() {
1030 return PermissionManagerFactory::GetForProfile(this);
1033 bool ProfileImpl::IsSameProfile(Profile* profile) {
1034 if (profile == static_cast<Profile*>(this))
1035 return true;
1036 Profile* otr_profile = off_the_record_profile_.get();
1037 return otr_profile && profile == otr_profile;
1040 Time ProfileImpl::GetStartTime() const {
1041 return start_time_;
1044 #if defined(ENABLE_SESSION_SERVICE)
1045 void ProfileImpl::StopCreateSessionServiceTimer() {
1046 create_session_service_timer_.Stop();
1049 void ProfileImpl::EnsureSessionServiceCreated() {
1050 SessionServiceFactory::GetForProfile(this);
1052 #endif
1054 #if defined(OS_CHROMEOS)
1055 void ProfileImpl::ChangeAppLocale(
1056 const std::string& new_locale, AppLocaleChangedVia via) {
1057 if (new_locale.empty()) {
1058 NOTREACHED();
1059 return;
1061 PrefService* local_state = g_browser_process->local_state();
1062 DCHECK(local_state);
1063 if (local_state->IsManagedPreference(prefs::kApplicationLocale))
1064 return;
1065 std::string pref_locale = GetPrefs()->GetString(prefs::kApplicationLocale);
1066 bool do_update_pref = true;
1067 switch (via) {
1068 case APP_LOCALE_CHANGED_VIA_SETTINGS:
1069 case APP_LOCALE_CHANGED_VIA_REVERT: {
1070 // We keep kApplicationLocaleBackup value as a reference. In case value
1071 // of kApplicationLocale preference would change due to sync from other
1072 // device then kApplicationLocaleBackup value will trigger and allow us to
1073 // show notification about automatic locale change in LocaleChangeGuard.
1074 GetPrefs()->SetString(prefs::kApplicationLocaleBackup, new_locale);
1075 GetPrefs()->ClearPref(prefs::kApplicationLocaleAccepted);
1076 // We maintain kApplicationLocale property in both a global storage
1077 // and user's profile. Global property determines locale of login screen,
1078 // while user's profile determines his personal locale preference.
1079 break;
1081 case APP_LOCALE_CHANGED_VIA_LOGIN:
1082 case APP_LOCALE_CHANGED_VIA_PUBLIC_SESSION_LOGIN: {
1083 if (!pref_locale.empty()) {
1084 DCHECK(pref_locale == new_locale);
1085 std::string accepted_locale =
1086 GetPrefs()->GetString(prefs::kApplicationLocaleAccepted);
1087 if (accepted_locale == new_locale) {
1088 // If locale is accepted then we do not want to show LocaleChange
1089 // notification. This notification is triggered by different values
1090 // of kApplicationLocaleBackup and kApplicationLocale preferences,
1091 // so make them identical.
1092 GetPrefs()->SetString(prefs::kApplicationLocaleBackup, new_locale);
1093 } else {
1094 // Back up locale of login screen.
1095 std::string cur_locale = g_browser_process->GetApplicationLocale();
1096 GetPrefs()->SetString(prefs::kApplicationLocaleBackup, cur_locale);
1097 if (locale_change_guard_ == NULL)
1098 locale_change_guard_.reset(new chromeos::LocaleChangeGuard(this));
1099 locale_change_guard_->PrepareChangingLocale(cur_locale, new_locale);
1101 } else {
1102 std::string cur_locale = g_browser_process->GetApplicationLocale();
1103 std::string backup_locale =
1104 GetPrefs()->GetString(prefs::kApplicationLocaleBackup);
1105 // Profile synchronization takes time and is not completed at that
1106 // moment at first login. So we initialize locale preference in steps:
1107 // (1) first save it to temporary backup;
1108 // (2) on next login we assume that synchronization is already completed
1109 // and we may finalize initialization.
1110 GetPrefs()->SetString(prefs::kApplicationLocaleBackup, cur_locale);
1111 if (!new_locale.empty())
1112 GetPrefs()->SetString(prefs::kApplicationLocale, new_locale);
1113 else if (!backup_locale.empty())
1114 GetPrefs()->SetString(prefs::kApplicationLocale, backup_locale);
1115 do_update_pref = false;
1117 break;
1119 case APP_LOCALE_CHANGED_VIA_UNKNOWN:
1120 default: {
1121 NOTREACHED();
1122 break;
1125 if (do_update_pref)
1126 GetPrefs()->SetString(prefs::kApplicationLocale, new_locale);
1127 if (via != APP_LOCALE_CHANGED_VIA_PUBLIC_SESSION_LOGIN)
1128 local_state->SetString(prefs::kApplicationLocale, new_locale);
1130 if (user_manager::UserManager::Get()->GetOwnerEmail() ==
1131 chromeos::ProfileHelper::Get()->GetUserByProfile(this)->email())
1132 local_state->SetString(prefs::kOwnerLocale, new_locale);
1135 void ProfileImpl::OnLogin() {
1136 if (locale_change_guard_ == NULL)
1137 locale_change_guard_.reset(new chromeos::LocaleChangeGuard(this));
1138 locale_change_guard_->OnLogin();
1141 void ProfileImpl::InitChromeOSPreferences() {
1142 chromeos_preferences_.reset(new chromeos::Preferences());
1143 chromeos_preferences_->Init(
1144 this, chromeos::ProfileHelper::Get()->GetUserByProfile(this));
1147 #endif // defined(OS_CHROMEOS)
1149 PrefProxyConfigTracker* ProfileImpl::GetProxyConfigTracker() {
1150 if (!pref_proxy_config_tracker_)
1151 pref_proxy_config_tracker_.reset(CreateProxyConfigTracker());
1152 return pref_proxy_config_tracker_.get();
1155 chrome_browser_net::Predictor* ProfileImpl::GetNetworkPredictor() {
1156 return predictor_;
1159 DevToolsNetworkControllerHandle*
1160 ProfileImpl::GetDevToolsNetworkControllerHandle() {
1161 return io_data_.GetDevToolsNetworkControllerHandle();
1164 void ProfileImpl::ClearNetworkingHistorySince(
1165 base::Time time,
1166 const base::Closure& completion) {
1167 io_data_.ClearNetworkingHistorySince(time, completion);
1170 GURL ProfileImpl::GetHomePage() {
1171 // --homepage overrides any preferences.
1172 const base::CommandLine& command_line =
1173 *base::CommandLine::ForCurrentProcess();
1174 if (command_line.HasSwitch(switches::kHomePage)) {
1175 // TODO(evanm): clean up usage of DIR_CURRENT.
1176 // http://code.google.com/p/chromium/issues/detail?id=60630
1177 // For now, allow this code to call getcwd().
1178 base::ThreadRestrictions::ScopedAllowIO allow_io;
1180 base::FilePath browser_directory;
1181 PathService::Get(base::DIR_CURRENT, &browser_directory);
1182 GURL home_page(url_formatter::FixupRelativeFile(
1183 browser_directory,
1184 command_line.GetSwitchValuePath(switches::kHomePage)));
1185 if (home_page.is_valid())
1186 return home_page;
1189 if (GetPrefs()->GetBoolean(prefs::kHomePageIsNewTabPage))
1190 return GURL(chrome::kChromeUINewTabURL);
1191 GURL home_page(url_formatter::FixupURL(
1192 GetPrefs()->GetString(prefs::kHomePage), std::string()));
1193 if (!home_page.is_valid())
1194 return GURL(chrome::kChromeUINewTabURL);
1195 return home_page;
1198 void ProfileImpl::UpdateProfileSupervisedUserIdCache() {
1199 ProfileManager* profile_manager = g_browser_process->profile_manager();
1200 ProfileInfoCache& cache = profile_manager->GetProfileInfoCache();
1201 size_t index = cache.GetIndexOfProfileWithPath(GetPath());
1202 if (index != std::string::npos) {
1203 std::string supervised_user_id =
1204 GetPrefs()->GetString(prefs::kSupervisedUserId);
1205 cache.SetSupervisedUserIdOfProfileAtIndex(index, supervised_user_id);
1206 ProfileMetrics::UpdateReportedProfilesStatistics(profile_manager);
1210 void ProfileImpl::UpdateProfileNameCache() {
1211 ProfileManager* profile_manager = g_browser_process->profile_manager();
1212 ProfileInfoCache& cache = profile_manager->GetProfileInfoCache();
1213 size_t index = cache.GetIndexOfProfileWithPath(GetPath());
1214 if (index != std::string::npos) {
1215 std::string profile_name =
1216 GetPrefs()->GetString(prefs::kProfileName);
1217 cache.SetNameOfProfileAtIndex(index, base::UTF8ToUTF16(profile_name));
1218 bool default_name =
1219 GetPrefs()->GetBoolean(prefs::kProfileUsingDefaultName);
1220 cache.SetProfileIsUsingDefaultNameAtIndex(index, default_name);
1224 void ProfileImpl::UpdateProfileAvatarCache() {
1225 ProfileManager* profile_manager = g_browser_process->profile_manager();
1226 ProfileInfoCache& cache = profile_manager->GetProfileInfoCache();
1227 size_t index = cache.GetIndexOfProfileWithPath(GetPath());
1228 if (index != std::string::npos) {
1229 size_t avatar_index =
1230 GetPrefs()->GetInteger(prefs::kProfileAvatarIndex);
1231 cache.SetAvatarIconOfProfileAtIndex(index, avatar_index);
1232 bool default_avatar =
1233 GetPrefs()->GetBoolean(prefs::kProfileUsingDefaultAvatar);
1234 cache.SetProfileIsUsingDefaultAvatarAtIndex(index, default_avatar);
1235 bool gaia_avatar =
1236 GetPrefs()->GetBoolean(prefs::kProfileUsingGAIAAvatar);
1237 cache.SetIsUsingGAIAPictureOfProfileAtIndex(index, gaia_avatar);
1241 void ProfileImpl::UpdateProfileIsEphemeralCache() {
1242 ProfileManager* profile_manager = g_browser_process->profile_manager();
1243 ProfileInfoCache& cache = profile_manager->GetProfileInfoCache();
1244 size_t index = cache.GetIndexOfProfileWithPath(GetPath());
1245 if (index != std::string::npos) {
1246 bool is_ephemeral = GetPrefs()->GetBoolean(prefs::kForceEphemeralProfiles);
1247 cache.SetProfileIsEphemeralAtIndex(index, is_ephemeral);
1251 // Gets the cache parameters from the command line. If |is_media_context| is
1252 // set to true then settings for the media context type is what we need,
1253 // |cache_path| will be set to the user provided path, or will not be touched if
1254 // there is not an argument. |max_size| will be the user provided value or zero
1255 // by default.
1256 void ProfileImpl::GetCacheParameters(bool is_media_context,
1257 base::FilePath* cache_path,
1258 int* max_size) {
1259 DCHECK(cache_path);
1260 DCHECK(max_size);
1261 base::FilePath path(prefs_->GetFilePath(prefs::kDiskCacheDir));
1262 if (!path.empty())
1263 *cache_path = path;
1264 *max_size = is_media_context ? prefs_->GetInteger(prefs::kMediaCacheSize) :
1265 prefs_->GetInteger(prefs::kDiskCacheSize);
1268 PrefProxyConfigTracker* ProfileImpl::CreateProxyConfigTracker() {
1269 #if defined(OS_CHROMEOS)
1270 if (chromeos::ProfileHelper::IsSigninProfile(this)) {
1271 return ProxyServiceFactory::CreatePrefProxyConfigTrackerOfLocalState(
1272 g_browser_process->local_state());
1274 #endif // defined(OS_CHROMEOS)
1275 return ProxyServiceFactory::CreatePrefProxyConfigTrackerOfProfile(
1276 GetPrefs(), g_browser_process->local_state());
1279 scoped_ptr<domain_reliability::DomainReliabilityMonitor>
1280 ProfileImpl::CreateDomainReliabilityMonitor(PrefService* local_state) {
1281 domain_reliability::DomainReliabilityService* service =
1282 domain_reliability::DomainReliabilityServiceFactory::GetInstance()->
1283 GetForBrowserContext(this);
1284 if (!service)
1285 return scoped_ptr<domain_reliability::DomainReliabilityMonitor>();
1287 return service->CreateMonitor(
1288 BrowserThread::GetMessageLoopProxyForThread(BrowserThread::IO));