52acc0c0809f06fc6990de2410754feb35098613
[platform/framework/web/crosswalk.git] / src / chrome / browser / profiles / profile_impl.cc
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.
4
5 #include "chrome/browser/profiles/profile_impl.h"
6
7 #include "base/bind.h"
8 #include "base/callback.h"
9 #include "base/command_line.h"
10 #include "base/compiler_specific.h"
11 #include "base/debug/trace_event.h"
12 #include "base/environment.h"
13 #include "base/file_util.h"
14 #include "base/files/file_path.h"
15 #include "base/memory/scoped_ptr.h"
16 #include "base/path_service.h"
17 #include "base/prefs/json_pref_store.h"
18 #include "base/prefs/scoped_user_pref_update.h"
19 #include "base/strings/string_number_conversions.h"
20 #include "base/strings/string_util.h"
21 #include "base/strings/stringprintf.h"
22 #include "base/strings/utf_string_conversions.h"
23 #include "base/synchronization/waitable_event.h"
24 #include "base/threading/sequenced_worker_pool.h"
25 #include "base/version.h"
26 #include "chrome/browser/autocomplete/autocomplete_classifier.h"
27 #include "chrome/browser/background/background_contents_service_factory.h"
28 #include "chrome/browser/background/background_mode_manager.h"
29 #include "chrome/browser/bookmarks/bookmark_model.h"
30 #include "chrome/browser/bookmarks/bookmark_model_factory.h"
31 #include "chrome/browser/browser_process.h"
32 #include "chrome/browser/chrome_notification_types.h"
33 #include "chrome/browser/content_settings/cookie_settings.h"
34 #include "chrome/browser/content_settings/host_content_settings_map.h"
35 #include "chrome/browser/download/chrome_download_manager_delegate.h"
36 #include "chrome/browser/download/download_service.h"
37 #include "chrome/browser/download/download_service_factory.h"
38 #include "chrome/browser/extensions/extension_service.h"
39 #include "chrome/browser/extensions/extension_special_storage_policy.h"
40 #include "chrome/browser/geolocation/chrome_geolocation_permission_context.h"
41 #include "chrome/browser/geolocation/chrome_geolocation_permission_context_factory.h"
42 #include "chrome/browser/history/shortcuts_backend.h"
43 #include "chrome/browser/history/top_sites.h"
44 #include "chrome/browser/media/chrome_midi_permission_context.h"
45 #include "chrome/browser/media/chrome_midi_permission_context_factory.h"
46 #include "chrome/browser/metrics/metrics_service.h"
47 #include "chrome/browser/net/chrome_url_request_context.h"
48 #include "chrome/browser/net/net_pref_observer.h"
49 #include "chrome/browser/net/predictor.h"
50 #include "chrome/browser/net/pref_proxy_config_tracker.h"
51 #include "chrome/browser/net/proxy_service_factory.h"
52 #include "chrome/browser/net/ssl_config_service_manager.h"
53 #include "chrome/browser/plugins/chrome_plugin_service_filter.h"
54 #include "chrome/browser/plugins/plugin_prefs.h"
55 #include "chrome/browser/policy/profile_policy_connector.h"
56 #include "chrome/browser/policy/profile_policy_connector_factory.h"
57 #include "chrome/browser/prefs/browser_prefs.h"
58 #include "chrome/browser/prefs/chrome_pref_service_factory.h"
59 #include "chrome/browser/prefs/pref_service_syncable.h"
60 #include "chrome/browser/prerender/prerender_manager_factory.h"
61 #include "chrome/browser/profiles/bookmark_model_loaded_observer.h"
62 #include "chrome/browser/profiles/chrome_version_service.h"
63 #include "chrome/browser/profiles/gaia_info_update_service_factory.h"
64 #include "chrome/browser/profiles/profile_destroyer.h"
65 #include "chrome/browser/profiles/profile_info_cache.h"
66 #include "chrome/browser/profiles/profile_manager.h"
67 #include "chrome/browser/profiles/profile_metrics.h"
68 #include "chrome/browser/search_engines/template_url_fetcher.h"
69 #include "chrome/browser/sessions/session_service_factory.h"
70 #include "chrome/browser/ui/startup/startup_browser_creator.h"
71 #include "chrome/browser/ui/webui/extensions/extension_icon_source.h"
72 #include "chrome/browser/webdata/web_data_service.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/chrome_version_info.h"
77 #include "chrome/common/net/url_fixer_upper.h"
78 #include "chrome/common/pref_names.h"
79 #include "chrome/common/url_constants.h"
80 #include "components/browser_context_keyed_service/browser_context_dependency_manager.h"
81 #include "components/startup_metric_utils/startup_metric_utils.h"
82 #include "components/user_prefs/pref_registry_syncable.h"
83 #include "components/user_prefs/user_prefs.h"
84 #include "content/public/browser/browser_thread.h"
85 #include "content/public/browser/dom_storage_context.h"
86 #include "content/public/browser/host_zoom_map.h"
87 #include "content/public/browser/notification_service.h"
88 #include "content/public/browser/render_process_host.h"
89 #include "content/public/browser/storage_partition.h"
90 #include "content/public/browser/user_metrics.h"
91 #include "content/public/common/content_constants.h"
92 #include "extensions/browser/extension_pref_store.h"
93 #include "extensions/browser/extension_pref_value_map.h"
94 #include "extensions/browser/extension_pref_value_map_factory.h"
95 #include "extensions/browser/extension_system.h"
96 #include "grit/chromium_strings.h"
97 #include "grit/generated_resources.h"
98 #include "ui/base/l10n/l10n_util.h"
99
100 #if defined(OS_ANDROID)
101 #include "chrome/browser/media/protected_media_identifier_permission_context.h"
102 #include "chrome/browser/media/protected_media_identifier_permission_context_factory.h"
103 #endif  // defined(OS_ANDROID)
104
105 #if defined(ENABLE_CONFIGURATION_POLICY)
106 #include "chrome/browser/policy/schema_registry_service.h"
107 #include "chrome/browser/policy/schema_registry_service_factory.h"
108 #include "components/policy/core/browser/browser_policy_connector.h"
109 #if defined(OS_CHROMEOS)
110 #include "chrome/browser/chromeos/policy/user_cloud_policy_manager_chromeos.h"
111 #include "chrome/browser/chromeos/policy/user_cloud_policy_manager_factory_chromeos.h"
112 #else
113 #include "chrome/browser/policy/cloud/user_cloud_policy_manager_factory.h"
114 #include "components/policy/core/common/cloud/user_cloud_policy_manager.h"
115 #endif
116 #endif
117
118 #if defined(ENABLE_MANAGED_USERS)
119 #include "chrome/browser/managed_mode/managed_user_settings_service.h"
120 #include "chrome/browser/managed_mode/managed_user_settings_service_factory.h"
121 #endif
122
123 #if defined(OS_CHROMEOS)
124 #include "chrome/browser/chromeos/locale_change_guard.h"
125 #include "chrome/browser/chromeos/login/user_manager.h"
126 #include "chrome/browser/chromeos/preferences.h"
127 #include "chrome/browser/chromeos/profiles/profile_helper.h"
128 #endif
129
130 using base::Time;
131 using base::TimeDelta;
132 using base::UserMetricsAction;
133 using content::BrowserThread;
134 using content::DownloadManagerDelegate;
135 using content::HostZoomMap;
136
137 namespace {
138
139 // Constrict us to a very specific platform and architecture to make sure
140 // ifdefs don't cause problems with the check.
141 #if defined(OS_LINUX) && defined(TOOLKIT_GTK) && defined(ARCH_CPU_X86_64) && \
142   !defined(_GLIBCXX_DEBUG)
143 // Make sure that the ProfileImpl doesn't grow. We're currently trying to drive
144 // the number of services that are included in ProfileImpl (instead of using
145 // BrowserContextKeyedServiceFactory) to zero.
146 //
147 // If you don't know about this effort, please read:
148 //   https://sites.google.com/a/chromium.org/dev/developers/design-documents/profile-architecture
149 //
150 // REVIEWERS: Do not let anyone increment this. We need to drive the number of
151 // raw accessed services down to zero. DO NOT LET PEOPLE REGRESS THIS UNLESS
152 // THE PATCH ITSELF IS MAKING PROGRESS ON PKSF REFACTORING.
153 COMPILE_ASSERT(sizeof(ProfileImpl) <= 744u, profile_impl_size_unexpected);
154 #endif
155
156 #if defined(ENABLE_SESSION_SERVICE)
157 // Delay, in milliseconds, before we explicitly create the SessionService.
158 static const int kCreateSessionServiceDelayMS = 500;
159 #endif
160
161 // Text content of README file created in each profile directory. Both %s
162 // placeholders must contain the product name. This is not localizable and hence
163 // not in resources.
164 static const char kReadmeText[] =
165     "%s settings and storage represent user-selected preferences and "
166     "information and MUST not be extracted, overwritten or modified except "
167     "through %s defined APIs.";
168
169 // Value written to prefs for EXIT_CRASHED and EXIT_SESSION_ENDED.
170 const char* const kPrefExitTypeCrashed = "Crashed";
171 const char* const kPrefExitTypeSessionEnded = "SessionEnded";
172
173 // Helper method needed because PostTask cannot currently take a Callback
174 // function with non-void return type.
175 void CreateDirectoryAndSignal(const base::FilePath& path,
176                               base::WaitableEvent* done_creating) {
177   DVLOG(1) << "Creating directory " << path.value();
178   base::CreateDirectory(path);
179   done_creating->Signal();
180 }
181
182 // Task that blocks the FILE thread until CreateDirectoryAndSignal() finishes on
183 // blocking I/O pool.
184 void BlockFileThreadOnDirectoryCreate(base::WaitableEvent* done_creating) {
185   done_creating->Wait();
186 }
187
188 // Initiates creation of profile directory on |sequenced_task_runner| and
189 // ensures that FILE thread is blocked until that operation finishes.
190 void CreateProfileDirectory(base::SequencedTaskRunner* sequenced_task_runner,
191                             const base::FilePath& path) {
192   base::WaitableEvent* done_creating = new base::WaitableEvent(false, false);
193   sequenced_task_runner->PostTask(FROM_HERE,
194                                   base::Bind(&CreateDirectoryAndSignal,
195                                              path,
196                                              done_creating));
197   // Block the FILE thread until directory is created on I/O pool to make sure
198   // that we don't attempt any operation until that part completes.
199   BrowserThread::PostTask(
200       BrowserThread::FILE, FROM_HERE,
201       base::Bind(&BlockFileThreadOnDirectoryCreate,
202                  base::Owned(done_creating)));
203 }
204
205 base::FilePath GetCachePath(const base::FilePath& base) {
206   return base.Append(chrome::kCacheDirname);
207 }
208
209 base::FilePath GetMediaCachePath(const base::FilePath& base) {
210   return base.Append(chrome::kMediaCacheDirname);
211 }
212
213 void EnsureReadmeFile(const base::FilePath& base) {
214   base::FilePath readme_path = base.Append(chrome::kReadmeFilename);
215   if (base::PathExists(readme_path))
216     return;
217   std::string product_name = l10n_util::GetStringUTF8(IDS_PRODUCT_NAME);
218   std::string readme_text = base::StringPrintf(
219       kReadmeText, product_name.c_str(), product_name.c_str());
220   if (file_util::WriteFile(
221           readme_path, readme_text.data(), readme_text.size()) == -1) {
222     LOG(ERROR) << "Could not create README file.";
223   }
224 }
225
226 // Converts the kSessionExitedCleanly pref to the corresponding EXIT_TYPE.
227 Profile::ExitType SessionTypePrefValueToExitType(const std::string& value) {
228   if (value == kPrefExitTypeSessionEnded)
229     return Profile::EXIT_SESSION_ENDED;
230   if (value == kPrefExitTypeCrashed)
231     return Profile::EXIT_CRASHED;
232   return Profile::EXIT_NORMAL;
233 }
234
235 // Converts an ExitType into a string that is written to prefs.
236 std::string ExitTypeToSessionTypePrefValue(Profile::ExitType type) {
237   switch (type) {
238     case Profile::EXIT_NORMAL:
239         return ProfileImpl::kPrefExitTypeNormal;
240     case Profile::EXIT_SESSION_ENDED:
241       return kPrefExitTypeSessionEnded;
242     case Profile::EXIT_CRASHED:
243       return kPrefExitTypeCrashed;
244   }
245   NOTREACHED();
246   return std::string();
247 }
248
249 }  // namespace
250
251 // static
252 Profile* Profile::CreateProfile(const base::FilePath& path,
253                                 Delegate* delegate,
254                                 CreateMode create_mode) {
255   TRACE_EVENT0("browser", "Profile::CreateProfile")
256   // Get sequenced task runner for making sure that file operations of
257   // this profile (defined by |path|) are executed in expected order
258   // (what was previously assured by the FILE thread).
259   scoped_refptr<base::SequencedTaskRunner> sequenced_task_runner =
260       JsonPrefStore::GetTaskRunnerForFile(path,
261                                           BrowserThread::GetBlockingPool());
262   if (create_mode == CREATE_MODE_ASYNCHRONOUS) {
263     DCHECK(delegate);
264     CreateProfileDirectory(sequenced_task_runner.get(), path);
265   } else if (create_mode == CREATE_MODE_SYNCHRONOUS) {
266     if (!base::PathExists(path)) {
267       // TODO(tc): http://b/1094718 Bad things happen if we can't write to the
268       // profile directory.  We should eventually be able to run in this
269       // situation.
270       if (!base::CreateDirectory(path))
271         return NULL;
272     }
273   } else {
274     NOTREACHED();
275   }
276
277   return new ProfileImpl(
278       path, delegate, create_mode, sequenced_task_runner.get());
279 }
280
281 // static
282 int ProfileImpl::create_readme_delay_ms = 60000;
283
284 // static
285 const char* const ProfileImpl::kPrefExitTypeNormal = "Normal";
286
287 // static
288 void ProfileImpl::RegisterProfilePrefs(
289     user_prefs::PrefRegistrySyncable* registry) {
290   registry->RegisterBooleanPref(
291       prefs::kSavingBrowserHistoryDisabled,
292       false,
293       user_prefs::PrefRegistrySyncable::UNSYNCABLE_PREF);
294   registry->RegisterBooleanPref(
295       prefs::kAllowDeletingBrowserHistory,
296       true,
297       user_prefs::PrefRegistrySyncable::UNSYNCABLE_PREF);
298   registry->RegisterBooleanPref(
299       prefs::kSigninAllowed,
300       true,
301       user_prefs::PrefRegistrySyncable::UNSYNCABLE_PREF);
302   registry->RegisterBooleanPref(
303       prefs::kForceSafeSearch,
304       false,
305       user_prefs::PrefRegistrySyncable::UNSYNCABLE_PREF);
306   registry->RegisterIntegerPref(
307       prefs::kProfileAvatarIndex,
308       -1,
309       user_prefs::PrefRegistrySyncable::SYNCABLE_PREF);
310   registry->RegisterStringPref(prefs::kManagedUserId,
311                                std::string(),
312                                user_prefs::PrefRegistrySyncable::SYNCABLE_PREF);
313   registry->RegisterStringPref(prefs::kProfileName,
314                                std::string(),
315                                user_prefs::PrefRegistrySyncable::SYNCABLE_PREF);
316   registry->RegisterBooleanPref(
317       prefs::kProfileIsManaged,
318       false,
319       user_prefs::PrefRegistrySyncable::SYNCABLE_PREF);
320   registry->RegisterStringPref(prefs::kHomePage,
321                                std::string(),
322                                user_prefs::PrefRegistrySyncable::SYNCABLE_PREF);
323 #if defined(ENABLE_PRINTING)
324   registry->RegisterBooleanPref(
325       prefs::kPrintingEnabled,
326       true,
327       user_prefs::PrefRegistrySyncable::UNSYNCABLE_PREF);
328 #endif
329   registry->RegisterBooleanPref(
330       prefs::kPrintPreviewDisabled,
331 #if defined(GOOGLE_CHROME_BUILD)
332       false,
333 #else
334       true,
335 #endif
336       user_prefs::PrefRegistrySyncable::UNSYNCABLE_PREF);
337   registry->RegisterBooleanPref(
338       prefs::kForceEphemeralProfiles,
339       false,
340       user_prefs::PrefRegistrySyncable::UNSYNCABLE_PREF);
341
342   // Initialize the cache prefs.
343   registry->RegisterFilePathPref(
344       prefs::kDiskCacheDir,
345       base::FilePath(),
346       user_prefs::PrefRegistrySyncable::UNSYNCABLE_PREF);
347   registry->RegisterIntegerPref(
348       prefs::kDiskCacheSize,
349       0,
350       user_prefs::PrefRegistrySyncable::UNSYNCABLE_PREF);
351   registry->RegisterIntegerPref(
352       prefs::kMediaCacheSize,
353       0,
354       user_prefs::PrefRegistrySyncable::UNSYNCABLE_PREF);
355
356   // Deprecated. Kept around for migration.
357   registry->RegisterBooleanPref(
358       prefs::kClearSiteDataOnExit,
359       false,
360       user_prefs::PrefRegistrySyncable::SYNCABLE_PREF);
361 }
362
363 ProfileImpl::ProfileImpl(
364     const base::FilePath& path,
365     Delegate* delegate,
366     CreateMode create_mode,
367     base::SequencedTaskRunner* sequenced_task_runner)
368     : path_(path),
369       pref_registry_(new user_prefs::PrefRegistrySyncable),
370       io_data_(this),
371       host_content_settings_map_(NULL),
372       last_session_exit_type_(EXIT_NORMAL),
373       start_time_(Time::Now()),
374       delegate_(delegate),
375       predictor_(NULL) {
376   TRACE_EVENT0("browser", "ProfileImpl::ctor")
377   DCHECK(!path.empty()) << "Using an empty path will attempt to write " <<
378                             "profile files to the root directory!";
379
380 #if defined(ENABLE_SESSION_SERVICE)
381   create_session_service_timer_.Start(FROM_HERE,
382       TimeDelta::FromMilliseconds(kCreateSessionServiceDelayMS), this,
383       &ProfileImpl::EnsureSessionServiceCreated);
384 #endif
385
386   // Determine if prefetch is enabled for this profile.
387   // If not profile_manager is present, it means we are in a unittest.
388   const CommandLine* command_line = CommandLine::ForCurrentProcess();
389   predictor_ = chrome_browser_net::Predictor::CreatePredictor(
390       !command_line->HasSwitch(switches::kDisablePreconnect),
391       g_browser_process->profile_manager() == NULL);
392
393   // If we are creating the profile synchronously, then we should load the
394   // policy data immediately.
395   bool force_immediate_policy_load = (create_mode == CREATE_MODE_SYNCHRONOUS);
396 #if defined(ENABLE_CONFIGURATION_POLICY)
397   policy::BrowserPolicyConnector* connector =
398       g_browser_process->browser_policy_connector();
399   schema_registry_service_ =
400       policy::SchemaRegistryServiceFactory::CreateForContext(
401           this, connector->GetChromeSchema(), connector->GetSchemaRegistry());
402 #if defined(OS_CHROMEOS)
403   cloud_policy_manager_ =
404       policy::UserCloudPolicyManagerFactoryChromeOS::CreateForProfile(
405           this, force_immediate_policy_load, sequenced_task_runner);
406 #else
407   cloud_policy_manager_ =
408       policy::UserCloudPolicyManagerFactory::CreateForOriginalBrowserContext(
409           this,
410           force_immediate_policy_load,
411           sequenced_task_runner,
412           BrowserThread::GetMessageLoopProxyForThread(BrowserThread::FILE),
413           BrowserThread::GetMessageLoopProxyForThread(BrowserThread::IO));
414 #endif
415 #endif
416   profile_policy_connector_ =
417       policy::ProfilePolicyConnectorFactory::CreateForProfile(
418           this, force_immediate_policy_load);
419
420   DCHECK(create_mode == CREATE_MODE_ASYNCHRONOUS ||
421          create_mode == CREATE_MODE_SYNCHRONOUS);
422   bool async_prefs = create_mode == CREATE_MODE_ASYNCHRONOUS;
423
424 #if defined(OS_CHROMEOS)
425   if (chromeos::ProfileHelper::IsSigninProfile(this))
426     chrome::RegisterLoginProfilePrefs(pref_registry_.get());
427   else
428 #endif
429   chrome::RegisterUserProfilePrefs(pref_registry_.get());
430
431   BrowserContextDependencyManager::GetInstance()->
432       RegisterProfilePrefsForServices(this, pref_registry_.get());
433
434   ManagedUserSettingsService* managed_user_settings = NULL;
435 #if defined(ENABLE_MANAGED_USERS)
436   managed_user_settings =
437       ManagedUserSettingsServiceFactory::GetForProfile(this);
438   managed_user_settings->Init(
439       path_, sequenced_task_runner, create_mode == CREATE_MODE_SYNCHRONOUS);
440 #endif
441
442   {
443     // On startup, preference loading is always synchronous so a scoped timer
444     // will work here.
445     startup_metric_utils::ScopedSlowStartupUMA
446         scoped_timer("Startup.SlowStartupPreferenceLoading");
447     prefs_ = chrome_prefs::CreateProfilePrefs(
448         path_,
449         sequenced_task_runner,
450         profile_policy_connector_->policy_service(),
451         managed_user_settings,
452         new ExtensionPrefStore(
453             ExtensionPrefValueMapFactory::GetForBrowserContext(this), false),
454         pref_registry_,
455         async_prefs).Pass();
456     // Register on BrowserContext.
457     user_prefs::UserPrefs::Set(this, prefs_.get());
458   }
459
460   startup_metric_utils::ScopedSlowStartupUMA
461       scoped_timer("Startup.SlowStartupFinalProfileInit");
462   if (async_prefs) {
463     // Wait for the notification that prefs has been loaded
464     // (successfully or not).  Note that we can use base::Unretained
465     // because the PrefService is owned by this class and lives on
466     // the same thread.
467     prefs_->AddPrefInitObserver(base::Bind(&ProfileImpl::OnPrefsLoaded,
468                                            base::Unretained(this)));
469   } else {
470     // Prefs were loaded synchronously so we can continue directly.
471     OnPrefsLoaded(true);
472   }
473 }
474
475 void ProfileImpl::DoFinalInit() {
476   TRACE_EVENT0("browser", "ProfileImpl::DoFinalInit")
477   PrefService* prefs = GetPrefs();
478   pref_change_registrar_.Init(prefs);
479   pref_change_registrar_.Add(
480       prefs::kGoogleServicesUsername,
481       base::Bind(&ProfileImpl::UpdateProfileUserNameCache,
482                  base::Unretained(this)));
483   pref_change_registrar_.Add(
484       prefs::kDefaultZoomLevel,
485       base::Bind(&ProfileImpl::OnDefaultZoomLevelChanged,
486                  base::Unretained(this)));
487   pref_change_registrar_.Add(
488       prefs::kProfileAvatarIndex,
489       base::Bind(&ProfileImpl::UpdateProfileAvatarCache,
490                  base::Unretained(this)));
491   pref_change_registrar_.Add(
492       prefs::kProfileName,
493       base::Bind(&ProfileImpl::UpdateProfileNameCache,
494                  base::Unretained(this)));
495   pref_change_registrar_.Add(
496       prefs::kForceEphemeralProfiles,
497       base::Bind(&ProfileImpl::UpdateProfileIsEphemeralCache,
498                  base::Unretained(this)));
499
500   // It would be nice to use PathService for fetching this directory, but
501   // the cache directory depends on the profile directory, which isn't available
502   // to PathService.
503   chrome::GetUserCacheDirectory(path_, &base_cache_path_);
504   // Always create the cache directory asynchronously.
505   scoped_refptr<base::SequencedTaskRunner> sequenced_task_runner =
506       JsonPrefStore::GetTaskRunnerForFile(base_cache_path_,
507                                           BrowserThread::GetBlockingPool());
508   CreateProfileDirectory(sequenced_task_runner.get(), base_cache_path_);
509
510   // Now that the profile is hooked up to receive pref change notifications to
511   // kGoogleServicesUsername, initialize components that depend on it to reflect
512   // the current value.
513   UpdateProfileUserNameCache();
514   UpdateProfileIsEphemeralCache();
515   GAIAInfoUpdateServiceFactory::GetForProfile(this);
516
517   PrefService* local_state = g_browser_process->local_state();
518   ssl_config_service_manager_.reset(
519       SSLConfigServiceManager::CreateDefaultManager(local_state));
520
521   // Initialize the BackgroundModeManager - this has to be done here before
522   // InitExtensions() is called because it relies on receiving notifications
523   // when extensions are loaded. BackgroundModeManager is not needed under
524   // ChromeOS because Chrome is always running, no need for special keep-alive
525   // or launch-on-startup support unless kKeepAliveForTest is set.
526   bool init_background_mode_manager = true;
527 #if defined(OS_CHROMEOS)
528   if (!CommandLine::ForCurrentProcess()->HasSwitch(switches::kKeepAliveForTest))
529     init_background_mode_manager = false;
530 #endif
531   if (init_background_mode_manager) {
532     if (g_browser_process->background_mode_manager())
533       g_browser_process->background_mode_manager()->RegisterProfile(this);
534   }
535
536   base::FilePath cookie_path = GetPath();
537   cookie_path = cookie_path.Append(chrome::kCookieFilename);
538   base::FilePath server_bound_cert_path = GetPath();
539   server_bound_cert_path =
540       server_bound_cert_path.Append(chrome::kOBCertFilename);
541   base::FilePath cache_path = base_cache_path_;
542   int cache_max_size;
543   GetCacheParameters(false, &cache_path, &cache_max_size);
544   cache_path = GetCachePath(cache_path);
545
546   base::FilePath media_cache_path = base_cache_path_;
547   int media_cache_max_size;
548   GetCacheParameters(true, &media_cache_path, &media_cache_max_size);
549   media_cache_path = GetMediaCachePath(media_cache_path);
550
551   base::FilePath extensions_cookie_path = GetPath();
552   extensions_cookie_path =
553       extensions_cookie_path.Append(chrome::kExtensionsCookieFilename);
554
555   base::FilePath infinite_cache_path = GetPath();
556   infinite_cache_path =
557       infinite_cache_path.Append(FILE_PATH_LITERAL("Infinite Cache"));
558
559 #if defined(OS_ANDROID)
560   SessionStartupPref::Type startup_pref_type =
561       SessionStartupPref::GetDefaultStartupType();
562 #else
563   SessionStartupPref::Type startup_pref_type =
564       StartupBrowserCreator::GetSessionStartupPref(
565           *CommandLine::ForCurrentProcess(), this).type;
566 #endif
567   content::CookieStoreConfig::SessionCookieMode session_cookie_mode =
568       content::CookieStoreConfig::PERSISTANT_SESSION_COOKIES;
569   if (GetLastSessionExitType() == Profile::EXIT_CRASHED ||
570       startup_pref_type == SessionStartupPref::LAST) {
571     session_cookie_mode = content::CookieStoreConfig::RESTORED_SESSION_COOKIES;
572   }
573
574   InitHostZoomMap();
575
576   // Make sure we initialize the ProfileIOData after everything else has been
577   // initialized that we might be reading from the IO thread.
578
579   io_data_.Init(cookie_path, server_bound_cert_path, cache_path,
580                 cache_max_size, media_cache_path, media_cache_max_size,
581                 extensions_cookie_path, GetPath(), infinite_cache_path,
582                 predictor_,
583                 session_cookie_mode,
584                 GetSpecialStoragePolicy());
585
586 #if defined(ENABLE_PLUGINS)
587   ChromePluginServiceFilter::GetInstance()->RegisterResourceContext(
588       PluginPrefs::GetForProfile(this).get(),
589       io_data_.GetResourceContextNoInit());
590 #endif
591
592   // Delay README creation to not impact startup performance.
593   BrowserThread::PostDelayedTask(
594         BrowserThread::FILE, FROM_HERE,
595         base::Bind(&EnsureReadmeFile, GetPath()),
596         base::TimeDelta::FromMilliseconds(create_readme_delay_ms));
597
598   if (!CommandLine::ForCurrentProcess()->HasSwitch(
599           switches::kDisableRestoreSessionState)) {
600     TRACE_EVENT0("browser", "ProfileImpl::SetSaveSessionStorageOnDisk")
601     content::BrowserContext::GetDefaultStoragePartition(this)->
602         GetDOMStorageContext()->SetSaveSessionStorageOnDisk();
603   }
604
605   // Creation has been finished.
606   if (delegate_) {
607     TRACE_EVENT0("browser", "ProfileImpl::DoFileInit:DelegateOnProfileCreated")
608     delegate_->OnProfileCreated(this, true, IsNewProfile());
609   }
610
611   content::NotificationService::current()->Notify(
612       chrome::NOTIFICATION_PROFILE_CREATED,
613       content::Source<Profile>(this),
614       content::NotificationService::NoDetails());
615
616 #if !defined(OS_CHROMEOS)
617   // Listen for bookmark model load, to bootstrap the sync service.
618   // On CrOS sync service will be initialized after sign in.
619   BookmarkModel* model = BookmarkModelFactory::GetForProfile(this);
620   model->AddObserver(new BookmarkModelLoadedObserver(this));
621 #endif
622 }
623
624 void ProfileImpl::InitHostZoomMap() {
625   HostZoomMap* host_zoom_map = HostZoomMap::GetForBrowserContext(this);
626   host_zoom_map->SetDefaultZoomLevel(
627       prefs_->GetDouble(prefs::kDefaultZoomLevel));
628
629   const base::DictionaryValue* host_zoom_dictionary =
630       prefs_->GetDictionary(prefs::kPerHostZoomLevels);
631   // Careful: The returned value could be NULL if the pref has never been set.
632   if (host_zoom_dictionary != NULL) {
633     for (base::DictionaryValue::Iterator i(*host_zoom_dictionary); !i.IsAtEnd();
634          i.Advance()) {
635       const std::string& host(i.key());
636       double zoom_level = 0;
637
638       bool success = i.value().GetAsDouble(&zoom_level);
639       DCHECK(success);
640       host_zoom_map->SetZoomLevelForHost(host, zoom_level);
641     }
642   }
643
644   zoom_subscription_ = host_zoom_map->AddZoomLevelChangedCallback(
645       base::Bind(&ProfileImpl::OnZoomLevelChanged, base::Unretained(this)));
646 }
647
648 base::FilePath ProfileImpl::last_selected_directory() {
649   return GetPrefs()->GetFilePath(prefs::kSelectFileLastDirectory);
650 }
651
652 void ProfileImpl::set_last_selected_directory(const base::FilePath& path) {
653   GetPrefs()->SetFilePath(prefs::kSelectFileLastDirectory, path);
654 }
655
656 ProfileImpl::~ProfileImpl() {
657   MaybeSendDestroyedNotification();
658
659   bool prefs_loaded = prefs_->GetInitializationStatus() !=
660       PrefService::INITIALIZATION_STATUS_WAITING;
661
662 #if defined(ENABLE_SESSION_SERVICE)
663   StopCreateSessionServiceTimer();
664 #endif
665
666   // Remove pref observers
667   pref_change_registrar_.RemoveAll();
668
669 #if defined(ENABLE_PLUGINS)
670   ChromePluginServiceFilter::GetInstance()->UnregisterResourceContext(
671       io_data_.GetResourceContextNoInit());
672 #endif
673
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     ExtensionPrefValueMapFactory::GetForBrowserContext(this)->
680         ClearAllIncognitoSessionOnlyPreferences();
681   }
682
683   BrowserContextDependencyManager::GetInstance()->DestroyBrowserContextServices(
684       this);
685
686   if (top_sites_.get())
687     top_sites_->Shutdown();
688
689   if (pref_proxy_config_tracker_)
690     pref_proxy_config_tracker_->DetachFromPrefService();
691
692   if (host_content_settings_map_.get())
693     host_content_settings_map_->ShutdownOnUIThread();
694
695   // This causes the Preferences file to be written to disk.
696   if (prefs_loaded)
697     SetExitType(EXIT_NORMAL);
698 }
699
700 std::string ProfileImpl::GetProfileName() {
701   return GetPrefs()->GetString(prefs::kGoogleServicesUsername);
702 }
703
704 base::FilePath ProfileImpl::GetPath() const {
705   return path_;
706 }
707
708 scoped_refptr<base::SequencedTaskRunner> ProfileImpl::GetIOTaskRunner() {
709   return JsonPrefStore::GetTaskRunnerForFile(
710       GetPath(), BrowserThread::GetBlockingPool());
711 }
712
713 bool ProfileImpl::IsOffTheRecord() const {
714   return false;
715 }
716
717 Profile* ProfileImpl::GetOffTheRecordProfile() {
718   if (!off_the_record_profile_) {
719     scoped_ptr<Profile> p(CreateOffTheRecordProfile());
720     off_the_record_profile_.swap(p);
721
722     content::NotificationService::current()->Notify(
723         chrome::NOTIFICATION_PROFILE_CREATED,
724         content::Source<Profile>(off_the_record_profile_.get()),
725         content::NotificationService::NoDetails());
726   }
727   return off_the_record_profile_.get();
728 }
729
730 void ProfileImpl::DestroyOffTheRecordProfile() {
731   off_the_record_profile_.reset();
732   ExtensionPrefValueMapFactory::GetForBrowserContext(this)->
733       ClearAllIncognitoSessionOnlyPreferences();
734 }
735
736 bool ProfileImpl::HasOffTheRecordProfile() {
737   return off_the_record_profile_.get() != NULL;
738 }
739
740 Profile* ProfileImpl::GetOriginalProfile() {
741   return this;
742 }
743
744 bool ProfileImpl::IsManaged() {
745   return !GetPrefs()->GetString(prefs::kManagedUserId).empty();
746 }
747
748 ExtensionService* ProfileImpl::GetExtensionService() {
749   return extensions::ExtensionSystem::Get(this)->extension_service();
750 }
751
752 ExtensionSpecialStoragePolicy*
753     ProfileImpl::GetExtensionSpecialStoragePolicy() {
754   if (!extension_special_storage_policy_.get()) {
755     TRACE_EVENT0("browser", "ProfileImpl::GetExtensionSpecialStoragePolicy")
756     extension_special_storage_policy_ = new ExtensionSpecialStoragePolicy(
757         CookieSettings::Factory::GetForProfile(this).get());
758   }
759   return extension_special_storage_policy_.get();
760 }
761
762 void ProfileImpl::OnPrefsLoaded(bool success) {
763   TRACE_EVENT0("browser", "ProfileImpl::OnPrefsLoaded")
764   if (!success) {
765     if (delegate_)
766       delegate_->OnProfileCreated(this, false, false);
767     return;
768   }
769
770   // TODO(mirandac): remove migration code after 6 months (crbug.com/69995).
771   if (g_browser_process->local_state())
772     chrome::MigrateBrowserPrefs(this, g_browser_process->local_state());
773   // TODO(ivankr): remove cleanup code eventually (crbug.com/165672).
774   chrome::MigrateUserPrefs(this);
775
776   // |kSessionExitType| was added after |kSessionExitedCleanly|. If the pref
777   // value is empty fallback to checking for |kSessionExitedCleanly|.
778   const std::string exit_type_pref_value(
779       prefs_->GetString(prefs::kSessionExitType));
780   if (exit_type_pref_value.empty()) {
781     last_session_exit_type_ =
782         prefs_->GetBoolean(prefs::kSessionExitedCleanly) ?
783           EXIT_NORMAL : EXIT_CRASHED;
784   } else {
785     last_session_exit_type_ =
786         SessionTypePrefValueToExitType(exit_type_pref_value);
787   }
788   // Mark the session as open.
789   prefs_->SetString(prefs::kSessionExitType, kPrefExitTypeCrashed);
790   // Force this to true in case we fallback and use it.
791   // TODO(sky): remove this in a couple of releases (m28ish).
792   prefs_->SetBoolean(prefs::kSessionExitedCleanly, true);
793
794   g_browser_process->profile_manager()->InitProfileUserPrefs(this);
795
796   BrowserContextDependencyManager::GetInstance()->CreateBrowserContextServices(
797       this);
798
799   DCHECK(!net_pref_observer_);
800   {
801     TRACE_EVENT0("browser", "ProfileImpl::OnPrefsLoaded:NetPrefObserver")
802     net_pref_observer_.reset(new NetPrefObserver(
803         prefs_.get(),
804         prerender::PrerenderManagerFactory::GetForProfile(this),
805         predictor_));
806   }
807
808   chrome_prefs::SchedulePrefsFilePathVerification(path_);
809
810   ChromeVersionService::OnProfileLoaded(prefs_.get(), IsNewProfile());
811   DoFinalInit();
812 }
813
814 bool ProfileImpl::WasCreatedByVersionOrLater(const std::string& version) {
815   Version profile_version(ChromeVersionService::GetVersion(prefs_.get()));
816   Version arg_version(version);
817   return (profile_version.CompareTo(arg_version) >= 0);
818 }
819
820 void ProfileImpl::SetExitType(ExitType exit_type) {
821 #if defined(OS_CHROMEOS)
822   if (chromeos::ProfileHelper::IsSigninProfile(this))
823     return;
824 #endif
825   if (!prefs_)
826     return;
827   ExitType current_exit_type = SessionTypePrefValueToExitType(
828       prefs_->GetString(prefs::kSessionExitType));
829   // This may be invoked multiple times during shutdown. Only persist the value
830   // first passed in (unless it's a reset to the crash state, which happens when
831   // foregrounding the app on mobile).
832   if (exit_type == EXIT_CRASHED || current_exit_type == EXIT_CRASHED) {
833     prefs_->SetString(prefs::kSessionExitType,
834                       ExitTypeToSessionTypePrefValue(exit_type));
835
836     // NOTE: If you change what thread this writes on, be sure and update
837     // chrome::SessionEnding().
838     prefs_->CommitPendingWrite();
839   }
840 }
841
842 Profile::ExitType ProfileImpl::GetLastSessionExitType() {
843   // last_session_exited_cleanly_ is set when the preferences are loaded. Force
844   // it to be set by asking for the prefs.
845   GetPrefs();
846   return last_session_exit_type_;
847 }
848
849 PrefService* ProfileImpl::GetPrefs() {
850   DCHECK(prefs_);  // Should explicitly be initialized.
851   return prefs_.get();
852 }
853
854 PrefService* ProfileImpl::GetOffTheRecordPrefs() {
855   DCHECK(prefs_);
856   if (!otr_prefs_) {
857     // The new ExtensionPrefStore is ref_counted and the new PrefService
858     // stores a reference so that we do not leak memory here.
859     otr_prefs_.reset(prefs_->CreateIncognitoPrefService(
860         new ExtensionPrefStore(
861             ExtensionPrefValueMapFactory::GetForBrowserContext(this), true)));
862   }
863   return otr_prefs_.get();
864 }
865
866 net::URLRequestContextGetter* ProfileImpl::CreateRequestContext(
867     content::ProtocolHandlerMap* protocol_handlers) {
868   return io_data_
869       .CreateMainRequestContextGetter(protocol_handlers,
870                                       g_browser_process->local_state(),
871                                       g_browser_process->io_thread()).get();
872 }
873
874 net::URLRequestContextGetter* ProfileImpl::GetRequestContext() {
875   return GetDefaultStoragePartition(this)->GetURLRequestContext();
876 }
877
878 net::URLRequestContextGetter* ProfileImpl::GetRequestContextForRenderProcess(
879     int renderer_child_id) {
880   content::RenderProcessHost* rph = content::RenderProcessHost::FromID(
881       renderer_child_id);
882
883   return rph->GetStoragePartition()->GetURLRequestContext();
884 }
885
886 net::URLRequestContextGetter* ProfileImpl::GetMediaRequestContext() {
887   // Return the default media context.
888   return io_data_.GetMediaRequestContextGetter().get();
889 }
890
891 net::URLRequestContextGetter*
892 ProfileImpl::GetMediaRequestContextForRenderProcess(
893     int renderer_child_id) {
894   content::RenderProcessHost* rph = content::RenderProcessHost::FromID(
895       renderer_child_id);
896   content::StoragePartition* storage_partition = rph->GetStoragePartition();
897
898   return storage_partition->GetMediaURLRequestContext();
899 }
900
901 net::URLRequestContextGetter*
902 ProfileImpl::GetMediaRequestContextForStoragePartition(
903     const base::FilePath& partition_path,
904     bool in_memory) {
905   return io_data_
906       .GetIsolatedMediaRequestContextGetter(partition_path, in_memory).get();
907 }
908
909 void ProfileImpl::RequestMidiSysExPermission(
910       int render_process_id,
911       int render_view_id,
912       int bridge_id,
913       const GURL& requesting_frame,
914       const MidiSysExPermissionCallback& callback) {
915   ChromeMidiPermissionContext* context =
916       ChromeMidiPermissionContextFactory::GetForProfile(this);
917   context->RequestMidiSysExPermission(render_process_id,
918                                       render_view_id,
919                                       bridge_id,
920                                       requesting_frame,
921                                       callback);
922 }
923
924 void ProfileImpl::CancelMidiSysExPermissionRequest(
925     int render_process_id,
926     int render_view_id,
927     int bridge_id,
928     const GURL& requesting_frame) {
929   ChromeMidiPermissionContext* context =
930       ChromeMidiPermissionContextFactory::GetForProfile(this);
931   context->CancelMidiSysExPermissionRequest(
932       render_process_id, render_view_id, bridge_id, requesting_frame);
933 }
934
935 void ProfileImpl::RequestProtectedMediaIdentifierPermission(
936     int render_process_id,
937     int render_view_id,
938     int bridge_id,
939     int group_id,
940     const GURL& requesting_frame,
941     const ProtectedMediaIdentifierPermissionCallback& callback) {
942 #if defined(OS_ANDROID)
943   ProtectedMediaIdentifierPermissionContext* context =
944       ProtectedMediaIdentifierPermissionContextFactory::GetForProfile(this);
945   context->RequestProtectedMediaIdentifierPermission(render_process_id,
946                                                      render_view_id,
947                                                      bridge_id,
948                                                      group_id,
949                                                      requesting_frame,
950                                                      callback);
951 #else
952   NOTIMPLEMENTED();
953   callback.Run(false);
954 #endif  // defined(OS_ANDROID)
955 }
956
957 void ProfileImpl::CancelProtectedMediaIdentifierPermissionRequests(
958     int group_id) {
959 #if defined(OS_ANDROID)
960   ProtectedMediaIdentifierPermissionContext* context =
961       ProtectedMediaIdentifierPermissionContextFactory::GetForProfile(this);
962   context->CancelProtectedMediaIdentifierPermissionRequests(group_id);
963 #else
964   NOTIMPLEMENTED();
965 #endif  // defined(OS_ANDROID)
966 }
967
968 content::ResourceContext* ProfileImpl::GetResourceContext() {
969   return io_data_.GetResourceContext();
970 }
971
972 net::URLRequestContextGetter* ProfileImpl::GetRequestContextForExtensions() {
973   return io_data_.GetExtensionsRequestContextGetter().get();
974 }
975
976 net::URLRequestContextGetter*
977 ProfileImpl::CreateRequestContextForStoragePartition(
978     const base::FilePath& partition_path,
979     bool in_memory,
980     content::ProtocolHandlerMap* protocol_handlers) {
981   return io_data_.CreateIsolatedAppRequestContextGetter(
982                       partition_path, in_memory, protocol_handlers).get();
983 }
984
985 net::SSLConfigService* ProfileImpl::GetSSLConfigService() {
986   // If ssl_config_service_manager_ is null, this typically means that some
987   // BrowserContextKeyedService is trying to create a RequestContext at startup,
988   // but SSLConfigServiceManager is not initialized until DoFinalInit() which is
989   // invoked after all BrowserContextKeyedServices have been initialized (see
990   // http://crbug.com/171406).
991   DCHECK(ssl_config_service_manager_) <<
992       "SSLConfigServiceManager is not initialized yet";
993   return ssl_config_service_manager_->Get();
994 }
995
996 HostContentSettingsMap* ProfileImpl::GetHostContentSettingsMap() {
997   if (!host_content_settings_map_.get()) {
998     host_content_settings_map_ = new HostContentSettingsMap(GetPrefs(), false);
999   }
1000   return host_content_settings_map_.get();
1001 }
1002
1003 content::GeolocationPermissionContext*
1004     ProfileImpl::GetGeolocationPermissionContext() {
1005   return ChromeGeolocationPermissionContextFactory::GetForProfile(this);
1006 }
1007
1008 DownloadManagerDelegate* ProfileImpl::GetDownloadManagerDelegate() {
1009   return DownloadServiceFactory::GetForBrowserContext(this)->
1010       GetDownloadManagerDelegate();
1011 }
1012
1013 quota::SpecialStoragePolicy* ProfileImpl::GetSpecialStoragePolicy() {
1014   return GetExtensionSpecialStoragePolicy();
1015 }
1016
1017 bool ProfileImpl::IsSameProfile(Profile* profile) {
1018   if (profile == static_cast<Profile*>(this))
1019     return true;
1020   Profile* otr_profile = off_the_record_profile_.get();
1021   return otr_profile && profile == otr_profile;
1022 }
1023
1024 Time ProfileImpl::GetStartTime() const {
1025   return start_time_;
1026 }
1027
1028 history::TopSites* ProfileImpl::GetTopSites() {
1029   if (!top_sites_.get()) {
1030     top_sites_ = history::TopSites::Create(
1031         this, GetPath().Append(chrome::kTopSitesFilename));
1032   }
1033   return top_sites_.get();
1034 }
1035
1036 history::TopSites* ProfileImpl::GetTopSitesWithoutCreating() {
1037   return top_sites_.get();
1038 }
1039
1040 void ProfileImpl::OnDefaultZoomLevelChanged() {
1041   HostZoomMap::GetForBrowserContext(this)->SetDefaultZoomLevel(
1042       pref_change_registrar_.prefs()->GetDouble(prefs::kDefaultZoomLevel));
1043 }
1044
1045 void ProfileImpl::OnZoomLevelChanged(
1046     const HostZoomMap::ZoomLevelChange& change) {
1047
1048   if (change.mode != HostZoomMap::ZOOM_CHANGED_FOR_HOST)
1049     return;
1050   HostZoomMap* host_zoom_map = HostZoomMap::GetForBrowserContext(this);
1051   double level = change.zoom_level;
1052   DictionaryPrefUpdate update(prefs_.get(), prefs::kPerHostZoomLevels);
1053   base::DictionaryValue* host_zoom_dictionary = update.Get();
1054   if (level == host_zoom_map->GetDefaultZoomLevel()) {
1055     host_zoom_dictionary->RemoveWithoutPathExpansion(change.host, NULL);
1056   } else {
1057     host_zoom_dictionary->SetWithoutPathExpansion(
1058         change.host, base::Value::CreateDoubleValue(level));
1059   }
1060 }
1061
1062 #if defined(ENABLE_SESSION_SERVICE)
1063 void ProfileImpl::StopCreateSessionServiceTimer() {
1064   create_session_service_timer_.Stop();
1065 }
1066
1067 void ProfileImpl::EnsureSessionServiceCreated() {
1068   SessionServiceFactory::GetForProfile(this);
1069 }
1070 #endif
1071
1072 #if defined(OS_CHROMEOS)
1073 void ProfileImpl::ChangeAppLocale(
1074     const std::string& new_locale, AppLocaleChangedVia via) {
1075   if (new_locale.empty()) {
1076     NOTREACHED();
1077     return;
1078   }
1079   PrefService* local_state = g_browser_process->local_state();
1080   DCHECK(local_state);
1081   if (local_state->IsManagedPreference(prefs::kApplicationLocale))
1082     return;
1083   std::string pref_locale = GetPrefs()->GetString(prefs::kApplicationLocale);
1084   bool do_update_pref = true;
1085   switch (via) {
1086     case APP_LOCALE_CHANGED_VIA_SETTINGS:
1087     case APP_LOCALE_CHANGED_VIA_REVERT: {
1088       // We keep kApplicationLocaleBackup value as a reference.  In case value
1089       // of kApplicationLocale preference would change due to sync from other
1090       // device then kApplicationLocaleBackup value will trigger and allow us to
1091       // show notification about automatic locale change in LocaleChangeGuard.
1092       GetPrefs()->SetString(prefs::kApplicationLocaleBackup, new_locale);
1093       GetPrefs()->ClearPref(prefs::kApplicationLocaleAccepted);
1094       // We maintain kApplicationLocale property in both a global storage
1095       // and user's profile.  Global property determines locale of login screen,
1096       // while user's profile determines his personal locale preference.
1097       break;
1098     }
1099     case APP_LOCALE_CHANGED_VIA_LOGIN: {
1100       if (!pref_locale.empty()) {
1101         DCHECK(pref_locale == new_locale);
1102         std::string accepted_locale =
1103             GetPrefs()->GetString(prefs::kApplicationLocaleAccepted);
1104         if (accepted_locale == new_locale) {
1105           // If locale is accepted then we do not want to show LocaleChange
1106           // notification.  This notification is triggered by different values
1107           // of kApplicationLocaleBackup and kApplicationLocale preferences,
1108           // so make them identical.
1109           GetPrefs()->SetString(prefs::kApplicationLocaleBackup, new_locale);
1110         } else {
1111           // Back up locale of login screen.
1112           std::string cur_locale = g_browser_process->GetApplicationLocale();
1113           GetPrefs()->SetString(prefs::kApplicationLocaleBackup, cur_locale);
1114           if (locale_change_guard_ == NULL)
1115             locale_change_guard_.reset(new chromeos::LocaleChangeGuard(this));
1116           locale_change_guard_->PrepareChangingLocale(cur_locale, new_locale);
1117         }
1118       } else {
1119         std::string cur_locale = g_browser_process->GetApplicationLocale();
1120         std::string backup_locale =
1121             GetPrefs()->GetString(prefs::kApplicationLocaleBackup);
1122         // Profile synchronization takes time and is not completed at that
1123         // moment at first login.  So we initialize locale preference in steps:
1124         // (1) first save it to temporary backup;
1125         // (2) on next login we assume that synchronization is already completed
1126         //     and we may finalize initialization.
1127         GetPrefs()->SetString(prefs::kApplicationLocaleBackup, cur_locale);
1128         if (!new_locale.empty())
1129           GetPrefs()->SetString(prefs::kApplicationLocale, new_locale);
1130         else if (!backup_locale.empty())
1131           GetPrefs()->SetString(prefs::kApplicationLocale, backup_locale);
1132         do_update_pref = false;
1133       }
1134       break;
1135     }
1136     case APP_LOCALE_CHANGED_VIA_UNKNOWN:
1137     default: {
1138       NOTREACHED();
1139       break;
1140     }
1141   }
1142   if (do_update_pref)
1143     GetPrefs()->SetString(prefs::kApplicationLocale, new_locale);
1144   local_state->SetString(prefs::kApplicationLocale, new_locale);
1145
1146   if (chromeos::UserManager::Get()->GetOwnerEmail() ==
1147       chromeos::UserManager::Get()->GetUserByProfile(this)->email())
1148     local_state->SetString(prefs::kOwnerLocale, new_locale);
1149 }
1150
1151 void ProfileImpl::OnLogin() {
1152   if (locale_change_guard_ == NULL)
1153     locale_change_guard_.reset(new chromeos::LocaleChangeGuard(this));
1154   locale_change_guard_->OnLogin();
1155 }
1156
1157 void ProfileImpl::InitChromeOSPreferences() {
1158   chromeos_preferences_.reset(new chromeos::Preferences());
1159   chromeos_preferences_->Init(
1160       PrefServiceSyncable::FromProfile(this),
1161       chromeos::UserManager::Get()->GetUserByProfile(this));
1162 }
1163
1164 #endif  // defined(OS_CHROMEOS)
1165
1166 PrefProxyConfigTracker* ProfileImpl::GetProxyConfigTracker() {
1167   if (!pref_proxy_config_tracker_)
1168     pref_proxy_config_tracker_.reset(CreateProxyConfigTracker());
1169   return pref_proxy_config_tracker_.get();
1170 }
1171
1172 chrome_browser_net::Predictor* ProfileImpl::GetNetworkPredictor() {
1173   return predictor_;
1174 }
1175
1176 void ProfileImpl::ClearNetworkingHistorySince(base::Time time,
1177                                               const base::Closure& completion) {
1178   io_data_.ClearNetworkingHistorySince(time, completion);
1179 }
1180
1181 GURL ProfileImpl::GetHomePage() {
1182   // --homepage overrides any preferences.
1183   const CommandLine& command_line = *CommandLine::ForCurrentProcess();
1184   if (command_line.HasSwitch(switches::kHomePage)) {
1185     // TODO(evanm): clean up usage of DIR_CURRENT.
1186     //   http://code.google.com/p/chromium/issues/detail?id=60630
1187     // For now, allow this code to call getcwd().
1188     base::ThreadRestrictions::ScopedAllowIO allow_io;
1189
1190     base::FilePath browser_directory;
1191     PathService::Get(base::DIR_CURRENT, &browser_directory);
1192     GURL home_page(URLFixerUpper::FixupRelativeFile(browser_directory,
1193         command_line.GetSwitchValuePath(switches::kHomePage)));
1194     if (home_page.is_valid())
1195       return home_page;
1196   }
1197
1198   if (GetPrefs()->GetBoolean(prefs::kHomePageIsNewTabPage))
1199     return GURL(chrome::kChromeUINewTabURL);
1200   GURL home_page(URLFixerUpper::FixupURL(
1201       GetPrefs()->GetString(prefs::kHomePage),
1202       std::string()));
1203   if (!home_page.is_valid())
1204     return GURL(chrome::kChromeUINewTabURL);
1205   return home_page;
1206 }
1207
1208 void ProfileImpl::UpdateProfileUserNameCache() {
1209   ProfileManager* profile_manager = g_browser_process->profile_manager();
1210   ProfileInfoCache& cache = profile_manager->GetProfileInfoCache();
1211   size_t index = cache.GetIndexOfProfileWithPath(GetPath());
1212   if (index != std::string::npos) {
1213     std::string user_name =
1214         GetPrefs()->GetString(prefs::kGoogleServicesUsername);
1215     cache.SetUserNameOfProfileAtIndex(index, base::UTF8ToUTF16(user_name));
1216     ProfileMetrics::UpdateReportedProfilesStatistics(profile_manager);
1217   }
1218 }
1219
1220 void ProfileImpl::UpdateProfileNameCache() {
1221   ProfileManager* profile_manager = g_browser_process->profile_manager();
1222   ProfileInfoCache& cache = profile_manager->GetProfileInfoCache();
1223   size_t index = cache.GetIndexOfProfileWithPath(GetPath());
1224   if (index != std::string::npos) {
1225     std::string profile_name =
1226         GetPrefs()->GetString(prefs::kProfileName);
1227     cache.SetNameOfProfileAtIndex(index, base::UTF8ToUTF16(profile_name));
1228   }
1229 }
1230
1231 void ProfileImpl::UpdateProfileAvatarCache() {
1232   ProfileManager* profile_manager = g_browser_process->profile_manager();
1233   ProfileInfoCache& cache = profile_manager->GetProfileInfoCache();
1234   size_t index = cache.GetIndexOfProfileWithPath(GetPath());
1235   if (index != std::string::npos) {
1236     size_t avatar_index =
1237         GetPrefs()->GetInteger(prefs::kProfileAvatarIndex);
1238     cache.SetAvatarIconOfProfileAtIndex(index, avatar_index);
1239   }
1240 }
1241
1242 void ProfileImpl::UpdateProfileIsEphemeralCache() {
1243   ProfileManager* profile_manager = g_browser_process->profile_manager();
1244   ProfileInfoCache& cache = profile_manager->GetProfileInfoCache();
1245   size_t index = cache.GetIndexOfProfileWithPath(GetPath());
1246   if (index != std::string::npos) {
1247     bool is_ephemeral = GetPrefs()->GetBoolean(prefs::kForceEphemeralProfiles);
1248     cache.SetProfileIsEphemeralAtIndex(index, is_ephemeral);
1249   }
1250 }
1251
1252 // Gets the cache parameters from the command line. If |is_media_context| is
1253 // set to true then settings for the media context type is what we need,
1254 // |cache_path| will be set to the user provided path, or will not be touched if
1255 // there is not an argument. |max_size| will be the user provided value or zero
1256 // by default.
1257 void ProfileImpl::GetCacheParameters(bool is_media_context,
1258                                      base::FilePath* cache_path,
1259                                      int* max_size) {
1260   DCHECK(cache_path);
1261   DCHECK(max_size);
1262   base::FilePath path(prefs_->GetFilePath(prefs::kDiskCacheDir));
1263   if (!path.empty())
1264     *cache_path = path;
1265   *max_size = is_media_context ? prefs_->GetInteger(prefs::kMediaCacheSize) :
1266                                  prefs_->GetInteger(prefs::kDiskCacheSize);
1267 }
1268
1269 PrefProxyConfigTracker* ProfileImpl::CreateProxyConfigTracker() {
1270 #if defined(OS_CHROMEOS)
1271   if (chromeos::ProfileHelper::IsSigninProfile(this)) {
1272     return ProxyServiceFactory::CreatePrefProxyConfigTrackerOfLocalState(
1273         g_browser_process->local_state());
1274   }
1275 #endif  // defined(OS_CHROMEOS)
1276   return ProxyServiceFactory::CreatePrefProxyConfigTrackerOfProfile(
1277       GetPrefs(), g_browser_process->local_state());
1278 }