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