Popular sites on the NTP: re-download popular suggestions once per Chrome run
[chromium-blink-merge.git] / chrome / browser / profiles / profile_impl.cc
blob5c8bc9980f58da16d80fe7a0d84af61227173064
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_util.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/syncable_prefs/pref_service_syncable.h"
92 #include "components/ui/zoom/zoom_event_manager.h"
93 #include "components/url_formatter/url_fixer.h"
94 #include "components/user_prefs/tracked/tracked_preference_validation_delegate.h"
95 #include "components/user_prefs/user_prefs.h"
96 #include "content/public/browser/browser_thread.h"
97 #include "content/public/browser/dom_storage_context.h"
98 #include "content/public/browser/notification_service.h"
99 #include "content/public/browser/render_process_host.h"
100 #include "content/public/browser/storage_partition.h"
101 #include "content/public/browser/url_data_source.h"
102 #include "content/public/browser/user_metrics.h"
103 #include "content/public/common/content_constants.h"
104 #include "content/public/common/page_zoom.h"
105 #include "ui/base/l10n/l10n_util.h"
107 #if defined(OS_ANDROID)
108 #include "chrome/browser/media/protected_media_identifier_permission_context.h"
109 #include "chrome/browser/media/protected_media_identifier_permission_context_factory.h"
110 #endif
112 #if defined(OS_CHROMEOS)
113 #include "chrome/browser/chromeos/locale_change_guard.h"
114 #include "chrome/browser/chromeos/preferences.h"
115 #include "chrome/browser/chromeos/profiles/profile_helper.h"
116 #include "components/user_manager/user_manager.h"
117 #endif
119 #if defined(ENABLE_BACKGROUND)
120 #include "chrome/browser/background/background_mode_manager.h"
121 #endif
123 #if defined(ENABLE_CONFIGURATION_POLICY)
124 #include "chrome/browser/policy/schema_registry_service.h"
125 #include "chrome/browser/policy/schema_registry_service_factory.h"
126 #include "components/policy/core/browser/browser_policy_connector.h"
127 #if defined(OS_CHROMEOS)
128 #include "chrome/browser/chromeos/login/session/user_session_manager.h"
129 #include "chrome/browser/chromeos/policy/user_cloud_policy_manager_chromeos.h"
130 #include "chrome/browser/chromeos/policy/user_cloud_policy_manager_factory_chromeos.h"
131 #else
132 #include "chrome/browser/policy/cloud/user_cloud_policy_manager_factory.h"
133 #include "components/policy/core/common/cloud/user_cloud_policy_manager.h"
134 #endif
135 #endif
137 #if defined(ENABLE_EXTENSIONS)
138 #include "chrome/browser/extensions/extension_service.h"
139 #include "chrome/browser/extensions/extension_special_storage_policy.h"
140 #include "chrome/browser/ui/webui/extensions/extension_icon_source.h"
141 #include "components/guest_view/browser/guest_view_manager.h"
142 #include "extensions/browser/extension_pref_store.h"
143 #include "extensions/browser/extension_pref_value_map.h"
144 #include "extensions/browser/extension_pref_value_map_factory.h"
145 #include "extensions/browser/extension_system.h"
146 #endif
148 #if defined(ENABLE_SUPERVISED_USERS)
149 #include "chrome/browser/content_settings/content_settings_supervised_provider.h"
150 #include "chrome/browser/supervised_user/supervised_user_constants.h"
151 #include "chrome/browser/supervised_user/supervised_user_settings_service.h"
152 #include "chrome/browser/supervised_user/supervised_user_settings_service_factory.h"
153 #endif
155 using base::Time;
156 using base::TimeDelta;
157 using base::UserMetricsAction;
158 using bookmarks::BookmarkModel;
159 using content::BrowserThread;
160 using content::DownloadManagerDelegate;
162 namespace {
164 #if defined(ENABLE_SESSION_SERVICE)
165 // Delay, in milliseconds, before we explicitly create the SessionService.
166 const int kCreateSessionServiceDelayMS = 500;
167 #endif
169 // Text content of README file created in each profile directory. Both %s
170 // placeholders must contain the product name. This is not localizable and hence
171 // not in resources.
172 const char kReadmeText[] =
173 "%s settings and storage represent user-selected preferences and "
174 "information and MUST not be extracted, overwritten or modified except "
175 "through %s defined APIs.";
177 // Value written to prefs for EXIT_CRASHED and EXIT_SESSION_ENDED.
178 const char kPrefExitTypeCrashed[] = "Crashed";
179 const char kPrefExitTypeSessionEnded[] = "SessionEnded";
181 void CreateProfileReadme(const base::FilePath& profile_path) {
182 base::ThreadRestrictions::AssertIOAllowed();
183 base::FilePath readme_path = profile_path.Append(chrome::kReadmeFilename);
184 std::string product_name = l10n_util::GetStringUTF8(IDS_PRODUCT_NAME);
185 std::string readme_text = base::StringPrintf(
186 kReadmeText, product_name.c_str(), product_name.c_str());
187 if (base::WriteFile(readme_path, readme_text.data(), readme_text.size()) ==
188 -1) {
189 LOG(ERROR) << "Could not create README file.";
193 // Helper method needed because PostTask cannot currently take a Callback
194 // function with non-void return type.
195 void CreateDirectoryAndSignal(const base::FilePath& path,
196 base::WaitableEvent* done_creating,
197 bool create_readme) {
198 // If the readme exists, the profile directory must also already exist.
199 base::FilePath readme_path = path.Append(chrome::kReadmeFilename);
200 if (base::PathExists(readme_path)) {
201 done_creating->Signal();
202 return;
205 DVLOG(1) << "Creating directory " << path.value();
206 if (base::CreateDirectory(path) && create_readme)
207 CreateProfileReadme(path);
208 done_creating->Signal();
211 // Task that blocks the FILE thread until CreateDirectoryAndSignal() finishes on
212 // blocking I/O pool.
213 void BlockFileThreadOnDirectoryCreate(base::WaitableEvent* done_creating) {
214 done_creating->Wait();
217 // Initiates creation of profile directory on |sequenced_task_runner| and
218 // ensures that FILE thread is blocked until that operation finishes. If
219 // |create_readme| is true, the profile README will be created in the profile
220 // directory.
221 void CreateProfileDirectory(base::SequencedTaskRunner* sequenced_task_runner,
222 const base::FilePath& path,
223 bool create_readme) {
224 base::WaitableEvent* done_creating = new base::WaitableEvent(false, false);
225 sequenced_task_runner->PostTask(
226 FROM_HERE, base::Bind(&CreateDirectoryAndSignal, path, done_creating,
227 create_readme));
228 // Block the FILE thread until directory is created on I/O pool to make sure
229 // that we don't attempt any operation until that part completes.
230 BrowserThread::PostTask(
231 BrowserThread::FILE, FROM_HERE,
232 base::Bind(&BlockFileThreadOnDirectoryCreate,
233 base::Owned(done_creating)));
236 base::FilePath GetCachePath(const base::FilePath& base) {
237 return base.Append(chrome::kCacheDirname);
240 base::FilePath GetMediaCachePath(const base::FilePath& base) {
241 return base.Append(chrome::kMediaCacheDirname);
244 // Converts the kSessionExitedCleanly pref to the corresponding EXIT_TYPE.
245 Profile::ExitType SessionTypePrefValueToExitType(const std::string& value) {
246 if (value == kPrefExitTypeSessionEnded)
247 return Profile::EXIT_SESSION_ENDED;
248 if (value == kPrefExitTypeCrashed)
249 return Profile::EXIT_CRASHED;
250 return Profile::EXIT_NORMAL;
253 // Converts an ExitType into a string that is written to prefs.
254 std::string ExitTypeToSessionTypePrefValue(Profile::ExitType type) {
255 switch (type) {
256 case Profile::EXIT_NORMAL:
257 return ProfileImpl::kPrefExitTypeNormal;
258 case Profile::EXIT_SESSION_ENDED:
259 return kPrefExitTypeSessionEnded;
260 case Profile::EXIT_CRASHED:
261 return kPrefExitTypeCrashed;
263 NOTREACHED();
264 return std::string();
267 PrefStore* CreateExtensionPrefStore(Profile* profile,
268 bool incognito_pref_store) {
269 #if defined(ENABLE_EXTENSIONS)
270 return new ExtensionPrefStore(
271 ExtensionPrefValueMapFactory::GetForBrowserContext(profile),
272 incognito_pref_store);
273 #else
274 return NULL;
275 #endif
278 } // namespace
280 // static
281 Profile* Profile::CreateProfile(const base::FilePath& path,
282 Delegate* delegate,
283 CreateMode create_mode) {
284 TRACE_EVENT1("browser,startup",
285 "Profile::CreateProfile",
286 "profile_path",
287 path.AsUTF8Unsafe());
289 // Get sequenced task runner for making sure that file operations of
290 // this profile (defined by |path|) are executed in expected order
291 // (what was previously assured by the FILE thread).
292 scoped_refptr<base::SequencedTaskRunner> sequenced_task_runner =
293 JsonPrefStore::GetTaskRunnerForFile(path,
294 BrowserThread::GetBlockingPool());
295 if (create_mode == CREATE_MODE_ASYNCHRONOUS) {
296 DCHECK(delegate);
297 CreateProfileDirectory(sequenced_task_runner.get(), path, true);
298 } else if (create_mode == CREATE_MODE_SYNCHRONOUS) {
299 if (!base::PathExists(path)) {
300 // TODO(rogerta): http://crbug/160553 - Bad things happen if we can't
301 // write to the profile directory. We should eventually be able to run in
302 // this situation.
303 if (!base::CreateDirectory(path))
304 return NULL;
306 CreateProfileReadme(path);
308 } else {
309 NOTREACHED();
312 return new ProfileImpl(
313 path, delegate, create_mode, sequenced_task_runner.get());
316 // static
317 const char* const ProfileImpl::kPrefExitTypeNormal = "Normal";
319 // static
320 void ProfileImpl::RegisterProfilePrefs(
321 user_prefs::PrefRegistrySyncable* registry) {
322 registry->RegisterBooleanPref(prefs::kSavingBrowserHistoryDisabled, false);
323 registry->RegisterBooleanPref(prefs::kAllowDeletingBrowserHistory, true);
324 registry->RegisterBooleanPref(prefs::kSigninAllowed, true);
325 registry->RegisterBooleanPref(prefs::kForceGoogleSafeSearch, false);
326 registry->RegisterBooleanPref(prefs::kForceYouTubeSafetyMode, false);
327 registry->RegisterBooleanPref(prefs::kRecordHistory, false);
328 registry->RegisterIntegerPref(
329 prefs::kProfileAvatarIndex,
331 user_prefs::PrefRegistrySyncable::SYNCABLE_PREF);
332 // Whether a profile is using an avatar without having explicitely chosen it
333 // (i.e. was assigned by default by legacy profile creation).
334 registry->RegisterBooleanPref(
335 prefs::kProfileUsingDefaultAvatar,
336 true,
337 user_prefs::PrefRegistrySyncable::SYNCABLE_PREF);
338 registry->RegisterBooleanPref(
339 prefs::kProfileUsingGAIAAvatar,
340 false,
341 user_prefs::PrefRegistrySyncable::SYNCABLE_PREF);
342 // Whether a profile is using a default avatar name (eg. Pickles or Person 1).
343 registry->RegisterBooleanPref(
344 prefs::kProfileUsingDefaultName,
345 true,
346 user_prefs::PrefRegistrySyncable::SYNCABLE_PREF);
347 registry->RegisterStringPref(prefs::kSupervisedUserId, std::string());
348 registry->RegisterStringPref(prefs::kProfileName,
349 std::string(),
350 user_prefs::PrefRegistrySyncable::SYNCABLE_PREF);
351 registry->RegisterStringPref(prefs::kHomePage,
352 std::string(),
353 user_prefs::PrefRegistrySyncable::SYNCABLE_PREF);
354 #if defined(ENABLE_PRINTING)
355 registry->RegisterBooleanPref(prefs::kPrintingEnabled, true);
356 #endif
357 registry->RegisterBooleanPref(prefs::kPrintPreviewDisabled, false);
358 registry->RegisterBooleanPref(prefs::kForceEphemeralProfiles, false);
360 // Initialize the cache prefs.
361 registry->RegisterFilePathPref(prefs::kDiskCacheDir, base::FilePath());
362 registry->RegisterIntegerPref(prefs::kDiskCacheSize, 0);
363 registry->RegisterIntegerPref(prefs::kMediaCacheSize, 0);
366 ProfileImpl::ProfileImpl(
367 const base::FilePath& path,
368 Delegate* delegate,
369 CreateMode create_mode,
370 base::SequencedTaskRunner* sequenced_task_runner)
371 : path_(path),
372 pref_registry_(new user_prefs::PrefRegistrySyncable),
373 io_data_(this),
374 last_session_exit_type_(EXIT_NORMAL),
375 start_time_(Time::Now()),
376 delegate_(delegate),
377 predictor_(NULL) {
378 TRACE_EVENT0("browser,startup", "ProfileImpl::ctor")
379 DCHECK(!path.empty()) << "Using an empty path will attempt to write " <<
380 "profile files to the root directory!";
382 #if defined(ENABLE_SESSION_SERVICE)
383 create_session_service_timer_.Start(FROM_HERE,
384 TimeDelta::FromMilliseconds(kCreateSessionServiceDelayMS), this,
385 &ProfileImpl::EnsureSessionServiceCreated);
386 #endif
388 set_is_guest_profile(path == ProfileManager::GetGuestProfilePath());
389 set_is_system_profile(path == ProfileManager::GetSystemProfilePath());
391 // Determine if prefetch is enabled for this profile.
392 // If not profile_manager is present, it means we are in a unittest.
393 const base::CommandLine* command_line =
394 base::CommandLine::ForCurrentProcess();
395 predictor_ = chrome_browser_net::Predictor::CreatePredictor(
396 !command_line->HasSwitch(switches::kDisablePreconnect),
397 !command_line->HasSwitch(switches::kDnsPrefetchDisable),
398 g_browser_process->profile_manager() == NULL);
400 // If we are creating the profile synchronously, then we should load the
401 // policy data immediately.
402 bool force_immediate_policy_load = (create_mode == CREATE_MODE_SYNCHRONOUS);
403 #if defined(ENABLE_CONFIGURATION_POLICY)
404 policy::BrowserPolicyConnector* connector =
405 g_browser_process->browser_policy_connector();
406 schema_registry_service_ =
407 policy::SchemaRegistryServiceFactory::CreateForContext(
408 this, connector->GetChromeSchema(), connector->GetSchemaRegistry());
409 #if defined(OS_CHROMEOS)
410 cloud_policy_manager_ =
411 policy::UserCloudPolicyManagerFactoryChromeOS::CreateForProfile(
412 this, force_immediate_policy_load, sequenced_task_runner);
413 #else
414 cloud_policy_manager_ =
415 policy::UserCloudPolicyManagerFactory::CreateForOriginalBrowserContext(
416 this,
417 force_immediate_policy_load,
418 sequenced_task_runner,
419 BrowserThread::GetMessageLoopProxyForThread(BrowserThread::FILE),
420 BrowserThread::GetMessageLoopProxyForThread(BrowserThread::IO));
421 #endif
422 #endif
423 profile_policy_connector_ =
424 policy::ProfilePolicyConnectorFactory::CreateForBrowserContext(
425 this, force_immediate_policy_load);
427 DCHECK(create_mode == CREATE_MODE_ASYNCHRONOUS ||
428 create_mode == CREATE_MODE_SYNCHRONOUS);
429 bool async_prefs = create_mode == CREATE_MODE_ASYNCHRONOUS;
431 #if defined(OS_CHROMEOS)
432 if (chromeos::ProfileHelper::IsSigninProfile(this))
433 chrome::RegisterLoginProfilePrefs(pref_registry_.get());
434 else
435 #endif
436 chrome::RegisterUserProfilePrefs(pref_registry_.get());
438 BrowserContextDependencyManager::GetInstance()->
439 RegisterProfilePrefsForServices(this, pref_registry_.get());
441 SupervisedUserSettingsService* supervised_user_settings = nullptr;
442 #if defined(ENABLE_SUPERVISED_USERS)
443 supervised_user_settings =
444 SupervisedUserSettingsServiceFactory::GetForProfile(this);
445 supervised_user_settings->Init(
446 path_, sequenced_task_runner, create_mode == CREATE_MODE_SYNCHRONOUS);
447 #endif
449 scoped_refptr<SafeBrowsingService> safe_browsing_service(
450 g_browser_process->safe_browsing_service());
451 if (safe_browsing_service.get()) {
452 pref_validation_delegate_ =
453 safe_browsing_service->CreatePreferenceValidationDelegate(this).Pass();
457 prefs_ = chrome_prefs::CreateProfilePrefs(
458 path_,
459 sequenced_task_runner,
460 pref_validation_delegate_.get(),
461 profile_policy_connector_->policy_service(),
462 supervised_user_settings,
463 CreateExtensionPrefStore(this, false),
464 pref_registry_,
465 async_prefs).Pass();
466 // Register on BrowserContext.
467 user_prefs::UserPrefs::Set(this, prefs_.get());
470 if (async_prefs) {
471 // Wait for the notification that prefs has been loaded
472 // (successfully or not). Note that we can use base::Unretained
473 // because the PrefService is owned by this class and lives on
474 // the same thread.
475 prefs_->AddPrefInitObserver(base::Bind(
476 &ProfileImpl::OnPrefsLoaded, base::Unretained(this), create_mode));
477 } else {
478 // Prefs were loaded synchronously so we can continue directly.
479 OnPrefsLoaded(create_mode, true);
483 void ProfileImpl::DoFinalInit() {
484 TRACE_EVENT0("browser", "ProfileImpl::DoFinalInit")
485 SCOPED_UMA_HISTOGRAM_TIMER("Profile.ProfileImplDoFinalInit");
487 PrefService* prefs = GetPrefs();
488 pref_change_registrar_.Init(prefs);
489 pref_change_registrar_.Add(
490 prefs::kSupervisedUserId,
491 base::Bind(&ProfileImpl::UpdateProfileSupervisedUserIdCache,
492 base::Unretained(this)));
494 // Changes in the profile avatar.
495 pref_change_registrar_.Add(
496 prefs::kProfileAvatarIndex,
497 base::Bind(&ProfileImpl::UpdateProfileAvatarCache,
498 base::Unretained(this)));
499 pref_change_registrar_.Add(
500 prefs::kProfileUsingDefaultAvatar,
501 base::Bind(&ProfileImpl::UpdateProfileAvatarCache,
502 base::Unretained(this)));
503 pref_change_registrar_.Add(
504 prefs::kProfileUsingGAIAAvatar,
505 base::Bind(&ProfileImpl::UpdateProfileAvatarCache,
506 base::Unretained(this)));
508 // Changes in the profile name.
509 pref_change_registrar_.Add(
510 prefs::kProfileUsingDefaultName,
511 base::Bind(&ProfileImpl::UpdateProfileNameCache,
512 base::Unretained(this)));
513 pref_change_registrar_.Add(
514 prefs::kProfileName,
515 base::Bind(&ProfileImpl::UpdateProfileNameCache,
516 base::Unretained(this)));
518 pref_change_registrar_.Add(
519 prefs::kForceEphemeralProfiles,
520 base::Bind(&ProfileImpl::UpdateProfileIsEphemeralCache,
521 base::Unretained(this)));
523 // It would be nice to use PathService for fetching this directory, but
524 // the cache directory depends on the profile directory, which isn't available
525 // to PathService.
526 chrome::GetUserCacheDirectory(path_, &base_cache_path_);
527 // Always create the cache directory asynchronously.
528 scoped_refptr<base::SequencedTaskRunner> sequenced_task_runner =
529 JsonPrefStore::GetTaskRunnerForFile(base_cache_path_,
530 BrowserThread::GetBlockingPool());
531 CreateProfileDirectory(sequenced_task_runner.get(), base_cache_path_, false);
533 // Initialize components that depend on the current value.
534 UpdateProfileSupervisedUserIdCache();
535 UpdateProfileIsEphemeralCache();
536 GAIAInfoUpdateServiceFactory::GetForProfile(this);
538 PrefService* local_state = g_browser_process->local_state();
539 ssl_config_service_manager_.reset(
540 SSLConfigServiceManager::CreateDefaultManager(local_state));
542 #if defined(ENABLE_BACKGROUND)
543 // Initialize the BackgroundModeManager - this has to be done here before
544 // InitExtensions() is called because it relies on receiving notifications
545 // when extensions are loaded. BackgroundModeManager is not needed under
546 // ChromeOS because Chrome is always running, no need for special keep-alive
547 // or launch-on-startup support unless kKeepAliveForTest is set.
548 bool init_background_mode_manager = true;
549 #if defined(OS_CHROMEOS)
550 if (!base::CommandLine::ForCurrentProcess()->HasSwitch(
551 switches::kKeepAliveForTest))
552 init_background_mode_manager = false;
553 #endif
554 if (init_background_mode_manager) {
555 if (g_browser_process->background_mode_manager())
556 g_browser_process->background_mode_manager()->RegisterProfile(this);
558 #endif // defined(ENABLE_BACKGROUND)
560 base::FilePath cookie_path = GetPath();
561 cookie_path = cookie_path.Append(chrome::kCookieFilename);
562 base::FilePath channel_id_path = GetPath();
563 channel_id_path = channel_id_path.Append(chrome::kChannelIDFilename);
564 base::FilePath cache_path = base_cache_path_;
565 int cache_max_size;
566 GetCacheParameters(false, &cache_path, &cache_max_size);
567 cache_path = GetCachePath(cache_path);
569 base::FilePath media_cache_path = base_cache_path_;
570 int media_cache_max_size;
571 GetCacheParameters(true, &media_cache_path, &media_cache_max_size);
572 media_cache_path = GetMediaCachePath(media_cache_path);
574 base::FilePath extensions_cookie_path = GetPath();
575 extensions_cookie_path =
576 extensions_cookie_path.Append(chrome::kExtensionsCookieFilename);
578 #if defined(OS_ANDROID)
579 SessionStartupPref::Type startup_pref_type =
580 SessionStartupPref::GetDefaultStartupType();
581 #else
582 SessionStartupPref::Type startup_pref_type =
583 StartupBrowserCreator::GetSessionStartupPref(
584 *base::CommandLine::ForCurrentProcess(), this).type;
585 #endif
586 content::CookieStoreConfig::SessionCookieMode session_cookie_mode =
587 content::CookieStoreConfig::PERSISTANT_SESSION_COOKIES;
588 if (GetLastSessionExitType() == Profile::EXIT_CRASHED ||
589 startup_pref_type == SessionStartupPref::LAST) {
590 session_cookie_mode = content::CookieStoreConfig::RESTORED_SESSION_COOKIES;
593 // Make sure we initialize the ProfileIOData after everything else has been
594 // initialized that we might be reading from the IO thread.
596 io_data_.Init(cookie_path, channel_id_path, cache_path,
597 cache_max_size, media_cache_path, media_cache_max_size,
598 extensions_cookie_path, GetPath(), predictor_,
599 session_cookie_mode, GetSpecialStoragePolicy(),
600 CreateDomainReliabilityMonitor(local_state));
602 #if defined(ENABLE_PLUGINS)
603 ChromePluginServiceFilter::GetInstance()->RegisterResourceContext(
604 PluginPrefs::GetForProfile(this).get(),
605 io_data_.GetResourceContextNoInit());
606 #endif
608 TRACE_EVENT0("browser", "ProfileImpl::SetSaveSessionStorageOnDisk");
609 content::BrowserContext::GetDefaultStoragePartition(this)->
610 GetDOMStorageContext()->SetSaveSessionStorageOnDisk();
612 // The DomDistillerViewerSource is not a normal WebUI so it must be registered
613 // as a URLDataSource early.
614 RegisterDomDistillerViewerSource(this);
616 #if defined(OS_CHROMEOS)
617 if (chromeos::UserSessionManager::GetInstance()
618 ->RestartToApplyPerSessionFlagsIfNeed(this, true)) {
619 return;
621 #endif
623 if (delegate_) {
624 TRACE_EVENT0("browser", "ProfileImpl::DoFileInit:DelegateOnProfileCreated")
625 delegate_->OnProfileCreated(this, true, IsNewProfile());
629 SCOPED_UMA_HISTOGRAM_TIMER("Profile.NotifyProfileCreatedTime");
630 content::NotificationService::current()->Notify(
631 chrome::NOTIFICATION_PROFILE_CREATED,
632 content::Source<Profile>(this),
633 content::NotificationService::NoDetails());
635 #if !defined(OS_CHROMEOS)
636 // Listen for bookmark model load, to bootstrap the sync service.
637 // On CrOS sync service will be initialized after sign in.
638 BookmarkModel* model = BookmarkModelFactory::GetForProfile(this);
639 model->AddObserver(new BookmarkModelLoadedObserver(this));
640 #endif
642 PushMessagingServiceImpl::InitializeForProfile(this);
644 #if !defined(OS_ANDROID) && !defined(OS_CHROMEOS) && !defined(OS_IOS)
645 signin_ui_util::InitializePrefsForProfile(this);
646 #endif
649 base::FilePath ProfileImpl::last_selected_directory() {
650 return GetPrefs()->GetFilePath(prefs::kSelectFileLastDirectory);
653 void ProfileImpl::set_last_selected_directory(const base::FilePath& path) {
654 GetPrefs()->SetFilePath(prefs::kSelectFileLastDirectory, path);
657 ProfileImpl::~ProfileImpl() {
658 MaybeSendDestroyedNotification();
660 bool prefs_loaded = prefs_->GetInitializationStatus() !=
661 PrefService::INITIALIZATION_STATUS_WAITING;
663 #if defined(ENABLE_SESSION_SERVICE)
664 StopCreateSessionServiceTimer();
665 #endif
667 // Remove pref observers
668 pref_change_registrar_.RemoveAll();
670 #if defined(ENABLE_PLUGINS)
671 ChromePluginServiceFilter::GetInstance()->UnregisterResourceContext(
672 io_data_.GetResourceContextNoInit());
673 #endif
675 // Destroy OTR profile and its profile services first.
676 if (off_the_record_profile_) {
677 ProfileDestroyer::DestroyOffTheRecordProfileNow(
678 off_the_record_profile_.get());
679 } else {
680 #if defined(ENABLE_EXTENSIONS)
681 ExtensionPrefValueMapFactory::GetForBrowserContext(this)->
682 ClearAllIncognitoSessionOnlyPreferences();
683 #endif
686 BrowserContextDependencyManager::GetInstance()->DestroyBrowserContextServices(
687 this);
689 if (pref_proxy_config_tracker_)
690 pref_proxy_config_tracker_->DetachFromPrefService();
692 // This causes the Preferences file to be written to disk.
693 if (prefs_loaded)
694 SetExitType(EXIT_NORMAL);
697 std::string ProfileImpl::GetProfileUserName() const {
698 const SigninManagerBase* signin_manager =
699 SigninManagerFactory::GetForProfileIfExists(this);
700 if (signin_manager)
701 return signin_manager->GetAuthenticatedAccountInfo().email;
703 return std::string();
706 Profile::ProfileType ProfileImpl::GetProfileType() const {
707 return REGULAR_PROFILE;
710 scoped_ptr<content::ZoomLevelDelegate> ProfileImpl::CreateZoomLevelDelegate(
711 const base::FilePath& partition_path) {
712 return make_scoped_ptr(new ChromeZoomLevelPrefs(
713 GetPrefs(), GetPath(), partition_path,
714 ui_zoom::ZoomEventManager::GetForBrowserContext(this)->GetWeakPtr()));
717 base::FilePath ProfileImpl::GetPath() const {
718 return path_;
721 scoped_refptr<base::SequencedTaskRunner> ProfileImpl::GetIOTaskRunner() {
722 return JsonPrefStore::GetTaskRunnerForFile(
723 GetPath(), BrowserThread::GetBlockingPool());
726 bool ProfileImpl::IsOffTheRecord() const {
727 return false;
730 Profile* ProfileImpl::GetOffTheRecordProfile() {
731 if (!off_the_record_profile_) {
732 scoped_ptr<Profile> p(CreateOffTheRecordProfile());
733 off_the_record_profile_.swap(p);
735 content::NotificationService::current()->Notify(
736 chrome::NOTIFICATION_PROFILE_CREATED,
737 content::Source<Profile>(off_the_record_profile_.get()),
738 content::NotificationService::NoDetails());
740 return off_the_record_profile_.get();
743 void ProfileImpl::DestroyOffTheRecordProfile() {
744 off_the_record_profile_.reset();
745 #if defined(ENABLE_EXTENSIONS)
746 ExtensionPrefValueMapFactory::GetForBrowserContext(this)->
747 ClearAllIncognitoSessionOnlyPreferences();
748 #endif
751 bool ProfileImpl::HasOffTheRecordProfile() {
752 return off_the_record_profile_.get() != NULL;
755 Profile* ProfileImpl::GetOriginalProfile() {
756 return this;
759 bool ProfileImpl::IsSupervised() const {
760 return !GetPrefs()->GetString(prefs::kSupervisedUserId).empty();
763 bool ProfileImpl::IsChild() const {
764 #if defined(ENABLE_SUPERVISED_USERS)
765 return GetPrefs()->GetString(prefs::kSupervisedUserId) ==
766 supervised_users::kChildAccountSUID;
767 #else
768 return false;
769 #endif
772 bool ProfileImpl::IsLegacySupervised() const {
773 return IsSupervised() && !IsChild();
776 ExtensionSpecialStoragePolicy*
777 ProfileImpl::GetExtensionSpecialStoragePolicy() {
778 #if defined(ENABLE_EXTENSIONS)
779 if (!extension_special_storage_policy_.get()) {
780 TRACE_EVENT0("browser", "ProfileImpl::GetExtensionSpecialStoragePolicy")
781 extension_special_storage_policy_ = new ExtensionSpecialStoragePolicy(
782 CookieSettingsFactory::GetForProfile(this).get());
784 return extension_special_storage_policy_.get();
785 #else
786 return NULL;
787 #endif
790 void ProfileImpl::OnLocaleReady() {
791 TRACE_EVENT0("browser", "ProfileImpl::OnLocaleReady");
792 SCOPED_UMA_HISTOGRAM_TIMER("Profile.OnLocaleReadyTime");
793 // Migrate obsolete prefs.
794 if (g_browser_process->local_state())
795 chrome::MigrateObsoleteBrowserPrefs(this, g_browser_process->local_state());
796 chrome::MigrateObsoleteProfilePrefs(this);
798 // |kSessionExitType| was added after |kSessionExitedCleanly|. If the pref
799 // value is empty fallback to checking for |kSessionExitedCleanly|.
800 const std::string exit_type_pref_value(
801 prefs_->GetString(prefs::kSessionExitType));
802 if (exit_type_pref_value.empty()) {
803 last_session_exit_type_ =
804 prefs_->GetBoolean(prefs::kSessionExitedCleanly) ?
805 EXIT_NORMAL : EXIT_CRASHED;
806 } else {
807 last_session_exit_type_ =
808 SessionTypePrefValueToExitType(exit_type_pref_value);
810 // Mark the session as open.
811 prefs_->SetString(prefs::kSessionExitType, kPrefExitTypeCrashed);
812 // Force this to true in case we fallback and use it.
813 // TODO(sky): remove this in a couple of releases (m28ish).
814 prefs_->SetBoolean(prefs::kSessionExitedCleanly, true);
816 g_browser_process->profile_manager()->InitProfileUserPrefs(this);
819 SCOPED_UMA_HISTOGRAM_TIMER("Profile.CreateBrowserContextServicesTime");
820 BrowserContextDependencyManager::GetInstance()->
821 CreateBrowserContextServices(this);
824 DCHECK(!net_pref_observer_);
826 TRACE_EVENT0("browser", "ProfileImpl::OnPrefsLoaded:NetPrefObserver")
827 net_pref_observer_.reset(new NetPrefObserver(prefs_.get()));
830 chrome_prefs::SchedulePrefsFilePathVerification(path_);
832 ChromeVersionService::OnProfileLoaded(prefs_.get(), IsNewProfile());
833 DoFinalInit();
836 void ProfileImpl::OnPrefsLoaded(CreateMode create_mode, bool success) {
837 TRACE_EVENT0("browser", "ProfileImpl::OnPrefsLoaded");
838 if (!success) {
839 if (delegate_)
840 delegate_->OnProfileCreated(this, false, false);
841 return;
844 #if defined(OS_CHROMEOS)
845 if (create_mode == CREATE_MODE_SYNCHRONOUS) {
846 // Synchronous create mode implies that either it is restart after crash,
847 // or we are in tests. In both cases the first loaded locale is correct.
848 OnLocaleReady();
849 } else {
850 chromeos::UserSessionManager::GetInstance()->RespectLocalePreferenceWrapper(
851 this, base::Bind(&ProfileImpl::OnLocaleReady, base::Unretained(this)));
853 #else
854 OnLocaleReady();
855 #endif
858 bool ProfileImpl::WasCreatedByVersionOrLater(const std::string& version) {
859 Version profile_version(ChromeVersionService::GetVersion(prefs_.get()));
860 Version arg_version(version);
861 return (profile_version.CompareTo(arg_version) >= 0);
864 void ProfileImpl::SetExitType(ExitType exit_type) {
865 #if defined(OS_CHROMEOS)
866 if (chromeos::ProfileHelper::IsSigninProfile(this))
867 return;
868 #endif
869 if (!prefs_)
870 return;
871 ExitType current_exit_type = SessionTypePrefValueToExitType(
872 prefs_->GetString(prefs::kSessionExitType));
873 // This may be invoked multiple times during shutdown. Only persist the value
874 // first passed in (unless it's a reset to the crash state, which happens when
875 // foregrounding the app on mobile).
876 if (exit_type == EXIT_CRASHED || current_exit_type == EXIT_CRASHED) {
877 prefs_->SetString(prefs::kSessionExitType,
878 ExitTypeToSessionTypePrefValue(exit_type));
882 Profile::ExitType ProfileImpl::GetLastSessionExitType() {
883 // last_session_exited_cleanly_ is set when the preferences are loaded. Force
884 // it to be set by asking for the prefs.
885 GetPrefs();
886 return last_session_exit_type_;
889 PrefService* ProfileImpl::GetPrefs() {
890 return const_cast<PrefService*>(
891 static_cast<const ProfileImpl*>(this)->GetPrefs());
894 const PrefService* ProfileImpl::GetPrefs() const {
895 DCHECK(prefs_); // Should explicitly be initialized.
896 return prefs_.get();
899 ChromeZoomLevelPrefs* ProfileImpl::GetZoomLevelPrefs() {
900 return static_cast<ChromeZoomLevelPrefs*>(
901 GetDefaultStoragePartition(this)->GetZoomLevelDelegate());
904 PrefService* ProfileImpl::GetOffTheRecordPrefs() {
905 DCHECK(prefs_);
906 if (!otr_prefs_) {
907 // The new ExtensionPrefStore is ref_counted and the new PrefService
908 // stores a reference so that we do not leak memory here.
909 otr_prefs_.reset(CreateIncognitoPrefServiceSyncable(
910 prefs_.get(), CreateExtensionPrefStore(this, true)));
912 return otr_prefs_.get();
915 net::URLRequestContextGetter* ProfileImpl::CreateRequestContext(
916 content::ProtocolHandlerMap* protocol_handlers,
917 content::URLRequestInterceptorScopedVector request_interceptors) {
918 return io_data_.CreateMainRequestContextGetter(
919 protocol_handlers,
920 request_interceptors.Pass(),
921 g_browser_process->local_state(),
922 g_browser_process->io_thread()).get();
925 net::URLRequestContextGetter* ProfileImpl::GetRequestContext() {
926 return GetDefaultStoragePartition(this)->GetURLRequestContext();
929 net::URLRequestContextGetter* ProfileImpl::GetRequestContextForRenderProcess(
930 int renderer_child_id) {
931 content::RenderProcessHost* rph = content::RenderProcessHost::FromID(
932 renderer_child_id);
934 return rph->GetStoragePartition()->GetURLRequestContext();
937 net::URLRequestContextGetter* ProfileImpl::GetMediaRequestContext() {
938 // Return the default media context.
939 return io_data_.GetMediaRequestContextGetter().get();
942 net::URLRequestContextGetter*
943 ProfileImpl::GetMediaRequestContextForRenderProcess(
944 int renderer_child_id) {
945 content::RenderProcessHost* rph = content::RenderProcessHost::FromID(
946 renderer_child_id);
947 content::StoragePartition* storage_partition = rph->GetStoragePartition();
949 return storage_partition->GetMediaURLRequestContext();
952 net::URLRequestContextGetter*
953 ProfileImpl::GetMediaRequestContextForStoragePartition(
954 const base::FilePath& partition_path,
955 bool in_memory) {
956 return io_data_
957 .GetIsolatedMediaRequestContextGetter(partition_path, in_memory).get();
960 content::ResourceContext* ProfileImpl::GetResourceContext() {
961 return io_data_.GetResourceContext();
964 net::URLRequestContextGetter* ProfileImpl::GetRequestContextForExtensions() {
965 return io_data_.GetExtensionsRequestContextGetter().get();
968 net::URLRequestContextGetter*
969 ProfileImpl::CreateRequestContextForStoragePartition(
970 const base::FilePath& partition_path,
971 bool in_memory,
972 content::ProtocolHandlerMap* protocol_handlers,
973 content::URLRequestInterceptorScopedVector request_interceptors) {
974 return io_data_.CreateIsolatedAppRequestContextGetter(
975 partition_path,
976 in_memory,
977 protocol_handlers,
978 request_interceptors.Pass()).get();
981 net::SSLConfigService* ProfileImpl::GetSSLConfigService() {
982 // If ssl_config_service_manager_ is null, this typically means that some
983 // KeyedService is trying to create a RequestContext at startup,
984 // but SSLConfigServiceManager is not initialized until DoFinalInit() which is
985 // invoked after all KeyedServices have been initialized (see
986 // http://crbug.com/171406).
987 DCHECK(ssl_config_service_manager_) <<
988 "SSLConfigServiceManager is not initialized yet";
989 return ssl_config_service_manager_->Get();
992 content::BrowserPluginGuestManager* ProfileImpl::GetGuestManager() {
993 #if defined(ENABLE_EXTENSIONS)
994 return guest_view::GuestViewManager::FromBrowserContext(this);
995 #else
996 return NULL;
997 #endif
1000 DownloadManagerDelegate* ProfileImpl::GetDownloadManagerDelegate() {
1001 return DownloadServiceFactory::GetForBrowserContext(this)->
1002 GetDownloadManagerDelegate();
1005 storage::SpecialStoragePolicy* ProfileImpl::GetSpecialStoragePolicy() {
1006 #if defined(ENABLE_EXTENSIONS)
1007 return GetExtensionSpecialStoragePolicy();
1008 #else
1009 return NULL;
1010 #endif
1013 content::PushMessagingService* ProfileImpl::GetPushMessagingService() {
1014 return PushMessagingServiceFactory::GetForProfile(this);
1017 content::SSLHostStateDelegate* ProfileImpl::GetSSLHostStateDelegate() {
1018 return ChromeSSLHostStateDelegateFactory::GetForProfile(this);
1021 // TODO(mlamouri): we should all these BrowserContext implementation to Profile
1022 // instead of repeating them inside all Profile implementations.
1023 content::PermissionManager* ProfileImpl::GetPermissionManager() {
1024 return PermissionManagerFactory::GetForProfile(this);
1027 bool ProfileImpl::IsSameProfile(Profile* profile) {
1028 if (profile == static_cast<Profile*>(this))
1029 return true;
1030 Profile* otr_profile = off_the_record_profile_.get();
1031 return otr_profile && profile == otr_profile;
1034 Time ProfileImpl::GetStartTime() const {
1035 return start_time_;
1038 #if defined(ENABLE_SESSION_SERVICE)
1039 void ProfileImpl::StopCreateSessionServiceTimer() {
1040 create_session_service_timer_.Stop();
1043 void ProfileImpl::EnsureSessionServiceCreated() {
1044 SessionServiceFactory::GetForProfile(this);
1046 #endif
1048 #if defined(OS_CHROMEOS)
1049 void ProfileImpl::ChangeAppLocale(
1050 const std::string& new_locale, AppLocaleChangedVia via) {
1051 if (new_locale.empty()) {
1052 NOTREACHED();
1053 return;
1055 PrefService* local_state = g_browser_process->local_state();
1056 DCHECK(local_state);
1057 if (local_state->IsManagedPreference(prefs::kApplicationLocale))
1058 return;
1059 std::string pref_locale = GetPrefs()->GetString(prefs::kApplicationLocale);
1060 bool do_update_pref = true;
1061 switch (via) {
1062 case APP_LOCALE_CHANGED_VIA_SETTINGS:
1063 case APP_LOCALE_CHANGED_VIA_REVERT: {
1064 // We keep kApplicationLocaleBackup value as a reference. In case value
1065 // of kApplicationLocale preference would change due to sync from other
1066 // device then kApplicationLocaleBackup value will trigger and allow us to
1067 // show notification about automatic locale change in LocaleChangeGuard.
1068 GetPrefs()->SetString(prefs::kApplicationLocaleBackup, new_locale);
1069 GetPrefs()->ClearPref(prefs::kApplicationLocaleAccepted);
1070 // We maintain kApplicationLocale property in both a global storage
1071 // and user's profile. Global property determines locale of login screen,
1072 // while user's profile determines his personal locale preference.
1073 break;
1075 case APP_LOCALE_CHANGED_VIA_LOGIN:
1076 case APP_LOCALE_CHANGED_VIA_PUBLIC_SESSION_LOGIN: {
1077 if (!pref_locale.empty()) {
1078 DCHECK(pref_locale == new_locale);
1079 std::string accepted_locale =
1080 GetPrefs()->GetString(prefs::kApplicationLocaleAccepted);
1081 if (accepted_locale == new_locale) {
1082 // If locale is accepted then we do not want to show LocaleChange
1083 // notification. This notification is triggered by different values
1084 // of kApplicationLocaleBackup and kApplicationLocale preferences,
1085 // so make them identical.
1086 GetPrefs()->SetString(prefs::kApplicationLocaleBackup, new_locale);
1087 } else {
1088 // Back up locale of login screen.
1089 std::string cur_locale = g_browser_process->GetApplicationLocale();
1090 GetPrefs()->SetString(prefs::kApplicationLocaleBackup, cur_locale);
1091 if (locale_change_guard_ == NULL)
1092 locale_change_guard_.reset(new chromeos::LocaleChangeGuard(this));
1093 locale_change_guard_->PrepareChangingLocale(cur_locale, new_locale);
1095 } else {
1096 std::string cur_locale = g_browser_process->GetApplicationLocale();
1097 std::string backup_locale =
1098 GetPrefs()->GetString(prefs::kApplicationLocaleBackup);
1099 // Profile synchronization takes time and is not completed at that
1100 // moment at first login. So we initialize locale preference in steps:
1101 // (1) first save it to temporary backup;
1102 // (2) on next login we assume that synchronization is already completed
1103 // and we may finalize initialization.
1104 GetPrefs()->SetString(prefs::kApplicationLocaleBackup, cur_locale);
1105 if (!new_locale.empty())
1106 GetPrefs()->SetString(prefs::kApplicationLocale, new_locale);
1107 else if (!backup_locale.empty())
1108 GetPrefs()->SetString(prefs::kApplicationLocale, backup_locale);
1109 do_update_pref = false;
1111 break;
1113 case APP_LOCALE_CHANGED_VIA_UNKNOWN:
1114 default: {
1115 NOTREACHED();
1116 break;
1119 if (do_update_pref)
1120 GetPrefs()->SetString(prefs::kApplicationLocale, new_locale);
1121 if (via != APP_LOCALE_CHANGED_VIA_PUBLIC_SESSION_LOGIN)
1122 local_state->SetString(prefs::kApplicationLocale, new_locale);
1124 if (user_manager::UserManager::Get()->GetOwnerEmail() ==
1125 chromeos::ProfileHelper::Get()->GetUserByProfile(this)->email())
1126 local_state->SetString(prefs::kOwnerLocale, new_locale);
1129 void ProfileImpl::OnLogin() {
1130 if (locale_change_guard_ == NULL)
1131 locale_change_guard_.reset(new chromeos::LocaleChangeGuard(this));
1132 locale_change_guard_->OnLogin();
1135 void ProfileImpl::InitChromeOSPreferences() {
1136 chromeos_preferences_.reset(new chromeos::Preferences());
1137 chromeos_preferences_->Init(
1138 this, chromeos::ProfileHelper::Get()->GetUserByProfile(this));
1141 #endif // defined(OS_CHROMEOS)
1143 PrefProxyConfigTracker* ProfileImpl::GetProxyConfigTracker() {
1144 if (!pref_proxy_config_tracker_)
1145 pref_proxy_config_tracker_.reset(CreateProxyConfigTracker());
1146 return pref_proxy_config_tracker_.get();
1149 chrome_browser_net::Predictor* ProfileImpl::GetNetworkPredictor() {
1150 return predictor_;
1153 DevToolsNetworkControllerHandle*
1154 ProfileImpl::GetDevToolsNetworkControllerHandle() {
1155 return io_data_.GetDevToolsNetworkControllerHandle();
1158 void ProfileImpl::ClearNetworkingHistorySince(
1159 base::Time time,
1160 const base::Closure& completion) {
1161 io_data_.ClearNetworkingHistorySince(time, completion);
1164 GURL ProfileImpl::GetHomePage() {
1165 // --homepage overrides any preferences.
1166 const base::CommandLine& command_line =
1167 *base::CommandLine::ForCurrentProcess();
1168 if (command_line.HasSwitch(switches::kHomePage)) {
1169 // TODO(evanm): clean up usage of DIR_CURRENT.
1170 // http://code.google.com/p/chromium/issues/detail?id=60630
1171 // For now, allow this code to call getcwd().
1172 base::ThreadRestrictions::ScopedAllowIO allow_io;
1174 base::FilePath browser_directory;
1175 PathService::Get(base::DIR_CURRENT, &browser_directory);
1176 GURL home_page(url_formatter::FixupRelativeFile(
1177 browser_directory,
1178 command_line.GetSwitchValuePath(switches::kHomePage)));
1179 if (home_page.is_valid())
1180 return home_page;
1183 if (GetPrefs()->GetBoolean(prefs::kHomePageIsNewTabPage))
1184 return GURL(chrome::kChromeUINewTabURL);
1185 GURL home_page(url_formatter::FixupURL(
1186 GetPrefs()->GetString(prefs::kHomePage), std::string()));
1187 if (!home_page.is_valid())
1188 return GURL(chrome::kChromeUINewTabURL);
1189 return home_page;
1192 void ProfileImpl::UpdateProfileSupervisedUserIdCache() {
1193 ProfileManager* profile_manager = g_browser_process->profile_manager();
1194 ProfileInfoCache& cache = profile_manager->GetProfileInfoCache();
1195 size_t index = cache.GetIndexOfProfileWithPath(GetPath());
1196 if (index != std::string::npos) {
1197 std::string supervised_user_id =
1198 GetPrefs()->GetString(prefs::kSupervisedUserId);
1199 cache.SetSupervisedUserIdOfProfileAtIndex(index, supervised_user_id);
1200 ProfileMetrics::UpdateReportedProfilesStatistics(profile_manager);
1204 void ProfileImpl::UpdateProfileNameCache() {
1205 ProfileManager* profile_manager = g_browser_process->profile_manager();
1206 ProfileInfoCache& cache = profile_manager->GetProfileInfoCache();
1207 size_t index = cache.GetIndexOfProfileWithPath(GetPath());
1208 if (index != std::string::npos) {
1209 std::string profile_name =
1210 GetPrefs()->GetString(prefs::kProfileName);
1211 cache.SetNameOfProfileAtIndex(index, base::UTF8ToUTF16(profile_name));
1212 bool default_name =
1213 GetPrefs()->GetBoolean(prefs::kProfileUsingDefaultName);
1214 cache.SetProfileIsUsingDefaultNameAtIndex(index, default_name);
1218 void ProfileImpl::UpdateProfileAvatarCache() {
1219 ProfileManager* profile_manager = g_browser_process->profile_manager();
1220 ProfileInfoCache& cache = profile_manager->GetProfileInfoCache();
1221 size_t index = cache.GetIndexOfProfileWithPath(GetPath());
1222 if (index != std::string::npos) {
1223 size_t avatar_index =
1224 GetPrefs()->GetInteger(prefs::kProfileAvatarIndex);
1225 cache.SetAvatarIconOfProfileAtIndex(index, avatar_index);
1226 bool default_avatar =
1227 GetPrefs()->GetBoolean(prefs::kProfileUsingDefaultAvatar);
1228 cache.SetProfileIsUsingDefaultAvatarAtIndex(index, default_avatar);
1229 bool gaia_avatar =
1230 GetPrefs()->GetBoolean(prefs::kProfileUsingGAIAAvatar);
1231 cache.SetIsUsingGAIAPictureOfProfileAtIndex(index, gaia_avatar);
1235 void ProfileImpl::UpdateProfileIsEphemeralCache() {
1236 ProfileManager* profile_manager = g_browser_process->profile_manager();
1237 ProfileInfoCache& cache = profile_manager->GetProfileInfoCache();
1238 size_t index = cache.GetIndexOfProfileWithPath(GetPath());
1239 if (index != std::string::npos) {
1240 bool is_ephemeral = GetPrefs()->GetBoolean(prefs::kForceEphemeralProfiles);
1241 cache.SetProfileIsEphemeralAtIndex(index, is_ephemeral);
1245 // Gets the cache parameters from the command line. If |is_media_context| is
1246 // set to true then settings for the media context type is what we need,
1247 // |cache_path| will be set to the user provided path, or will not be touched if
1248 // there is not an argument. |max_size| will be the user provided value or zero
1249 // by default.
1250 void ProfileImpl::GetCacheParameters(bool is_media_context,
1251 base::FilePath* cache_path,
1252 int* max_size) {
1253 DCHECK(cache_path);
1254 DCHECK(max_size);
1255 base::FilePath path(prefs_->GetFilePath(prefs::kDiskCacheDir));
1256 if (!path.empty())
1257 *cache_path = path;
1258 *max_size = is_media_context ? prefs_->GetInteger(prefs::kMediaCacheSize) :
1259 prefs_->GetInteger(prefs::kDiskCacheSize);
1262 PrefProxyConfigTracker* ProfileImpl::CreateProxyConfigTracker() {
1263 #if defined(OS_CHROMEOS)
1264 if (chromeos::ProfileHelper::IsSigninProfile(this)) {
1265 return ProxyServiceFactory::CreatePrefProxyConfigTrackerOfLocalState(
1266 g_browser_process->local_state());
1268 #endif // defined(OS_CHROMEOS)
1269 return ProxyServiceFactory::CreatePrefProxyConfigTrackerOfProfile(
1270 GetPrefs(), g_browser_process->local_state());
1273 scoped_ptr<domain_reliability::DomainReliabilityMonitor>
1274 ProfileImpl::CreateDomainReliabilityMonitor(PrefService* local_state) {
1275 domain_reliability::DomainReliabilityService* service =
1276 domain_reliability::DomainReliabilityServiceFactory::GetInstance()->
1277 GetForBrowserContext(this);
1278 if (!service)
1279 return scoped_ptr<domain_reliability::DomainReliabilityMonitor>();
1281 return service->CreateMonitor(
1282 BrowserThread::GetMessageLoopProxyForThread(BrowserThread::IO));