Upstream version 7.35.139.0
[platform/framework/web/crosswalk.git] / src / chrome / browser / profiles / profile_impl.cc
index c634472..d0a962c 100644 (file)
@@ -4,6 +4,8 @@
 
 #include "chrome/browser/profiles/profile_impl.h"
 
+#include <vector>
+
 #include "base/bind.h"
 #include "base/callback.h"
 #include "base/command_line.h"
@@ -24,6 +26,7 @@
 #include "base/threading/sequenced_worker_pool.h"
 #include "base/version.h"
 #include "chrome/browser/autocomplete/autocomplete_classifier.h"
+#include "chrome/browser/autocomplete/shortcuts_backend.h"
 #include "chrome/browser/background/background_contents_service_factory.h"
 #include "chrome/browser/background/background_mode_manager.h"
 #include "chrome/browser/bookmarks/bookmark_model.h"
 #include "chrome/browser/chrome_notification_types.h"
 #include "chrome/browser/content_settings/cookie_settings.h"
 #include "chrome/browser/content_settings/host_content_settings_map.h"
+#include "chrome/browser/dom_distiller/dom_distiller_service_factory.h"
+#include "chrome/browser/dom_distiller/lazy_dom_distiller_service.h"
 #include "chrome/browser/download/chrome_download_manager_delegate.h"
 #include "chrome/browser/download/download_service.h"
 #include "chrome/browser/download/download_service_factory.h"
 #include "chrome/browser/extensions/extension_service.h"
 #include "chrome/browser/extensions/extension_special_storage_policy.h"
-#include "chrome/browser/extensions/extension_system.h"
 #include "chrome/browser/geolocation/chrome_geolocation_permission_context.h"
 #include "chrome/browser/geolocation/chrome_geolocation_permission_context_factory.h"
-#include "chrome/browser/history/shortcuts_backend.h"
 #include "chrome/browser/history/top_sites.h"
 #include "chrome/browser/media/chrome_midi_permission_context.h"
 #include "chrome/browser/media/chrome_midi_permission_context_factory.h"
@@ -57,7 +60,6 @@
 #include "chrome/browser/policy/profile_policy_connector_factory.h"
 #include "chrome/browser/prefs/browser_prefs.h"
 #include "chrome/browser/prefs/chrome_pref_service_factory.h"
-#include "chrome/browser/prefs/pref_hash_store_impl.h"
 #include "chrome/browser/prefs/pref_service_syncable.h"
 #include "chrome/browser/prerender/prerender_manager_factory.h"
 #include "chrome/browser/profiles/bookmark_model_loaded_observer.h"
@@ -79,7 +81,8 @@
 #include "chrome/common/net/url_fixer_upper.h"
 #include "chrome/common/pref_names.h"
 #include "chrome/common/url_constants.h"
-#include "components/browser_context_keyed_service/browser_context_dependency_manager.h"
+#include "components/dom_distiller/content/dom_distiller_viewer_source.h"
+#include "components/keyed_service/content/browser_context_dependency_manager.h"
 #include "components/startup_metric_utils/startup_metric_utils.h"
 #include "components/user_prefs/pref_registry_syncable.h"
 #include "components/user_prefs/user_prefs.h"
 #include "content/public/browser/notification_service.h"
 #include "content/public/browser/render_process_host.h"
 #include "content/public/browser/storage_partition.h"
+#include "content/public/browser/url_data_source.h"
 #include "content/public/browser/user_metrics.h"
 #include "content/public/common/content_constants.h"
+#include "content/public/common/page_zoom.h"
 #include "extensions/browser/extension_pref_store.h"
 #include "extensions/browser/extension_pref_value_map.h"
 #include "extensions/browser/extension_pref_value_map_factory.h"
-#include "grit/browser_resources.h"
+#include "extensions/browser/extension_system.h"
 #include "grit/chromium_strings.h"
 #include "grit/generated_resources.h"
 #include "ui/base/l10n/l10n_util.h"
 #include "chrome/browser/managed_mode/managed_user_settings_service_factory.h"
 #endif
 
-#if defined(OS_WIN)
-#include "chrome/browser/profiles/file_path_verifier_win.h"
-#include "chrome/installer/util/install_util.h"
-#if defined(ENABLE_RLZ)
-#include "rlz/lib/machine_id.h"
-#endif
-#endif
-
 #if defined(OS_CHROMEOS)
 #include "chrome/browser/chromeos/locale_change_guard.h"
 #include "chrome/browser/chromeos/login/user_manager.h"
@@ -227,8 +224,8 @@ void EnsureReadmeFile(const base::FilePath& base) {
   std::string product_name = l10n_util::GetStringUTF8(IDS_PRODUCT_NAME);
   std::string readme_text = base::StringPrintf(
       kReadmeText, product_name.c_str(), product_name.c_str());
-  if (file_util::WriteFile(
-          readme_path, readme_text.data(), readme_text.size()) == -1) {
+  if (base::WriteFile(readme_path, readme_text.data(), readme_text.size()) ==
+      -1) {
     LOG(ERROR) << "Could not create README file.";
   }
 }
@@ -256,48 +253,21 @@ std::string ExitTypeToSessionTypePrefValue(Profile::ExitType type) {
   return std::string();
 }
 
-void SchedulePrefsFileVerification(const base::FilePath& prefs_file) {
-#if defined(OS_WIN)
-  // Only do prefs file verification on Windows.
-  const int kVerifyPrefsFileDelaySeconds = 60;
-  BrowserThread::GetBlockingPool()->PostDelayedTask(
-        FROM_HERE,
-        base::Bind(&VerifyPreferencesFile, prefs_file),
-        base::TimeDelta::FromSeconds(kVerifyPrefsFileDelaySeconds));
-#endif
-}
-
-scoped_ptr<PrefHashStoreImpl> GetPrefHashStore(
-    const base::FilePath& profile_path) {
-  // TODO(erikwright): Enable this on Android when race condition is sorted out.
-#if defined(OS_ANDROID)
-  return scoped_ptr<PrefHashStoreImpl>();
-#else
-  std::string seed = ResourceBundle::GetSharedInstance().GetRawDataResource(
-      IDR_PREF_HASH_SEED_BIN).as_string();
-  std::string device_id;
-
-#if defined(OS_WIN) && defined(ENABLE_RLZ)
-  // This is used by
-  // chrome/browser/extensions/api/music_manager_private/device_id_win.cc
-  // but that API is private (http://crbug.com/276485) and other platforms are
-  // not available synchronously.
-  // As part of improving pref metrics on other platforms we may want to find
-  // ways to defer preference loading until the device ID can be used.
-  rlz_lib::GetMachineId(&device_id);
-#endif
-
-  return make_scoped_ptr(new PrefHashStoreImpl(
-      profile_path.AsUTF8Unsafe(),
-      seed,
-      device_id,
-      g_browser_process->local_state()));
-#endif
-}
-
-base::FilePath GetPrefFilePathFromProfilePath(
-    const base::FilePath& profile_path) {
-  return profile_path.Append(chrome::kPreferencesFilename);
+// Setup URLDataSource for the chrome-distiller:// scheme for the given
+// |profile|.
+void RegisterDomDistillerViewerSource(Profile* profile) {
+  const CommandLine& command_line = *CommandLine::ForCurrentProcess();
+  if (command_line.HasSwitch(switches::kEnableDomDistiller)) {
+    dom_distiller::DomDistillerServiceFactory* dom_distiller_service_factory =
+        dom_distiller::DomDistillerServiceFactory::GetInstance();
+    // The LazyDomDistillerService deletes itself when the profile is destroyed.
+    dom_distiller::LazyDomDistillerService* lazy_service =
+        new dom_distiller::LazyDomDistillerService(
+            profile, dom_distiller_service_factory);
+    content::URLDataSource::Add(profile,
+                                new dom_distiller::DomDistillerViewerSource(
+                                    lazy_service, chrome::kDomDistillerScheme));
+  }
 }
 
 }  // namespace
@@ -414,24 +384,6 @@ void ProfileImpl::RegisterProfilePrefs(
       user_prefs::PrefRegistrySyncable::SYNCABLE_PREF);
 }
 
-// static
-void ProfileImpl::InitializePrefHashStoreIfRequired(
-    const base::FilePath& profile_path) {
-  scoped_ptr<PrefHashStoreImpl> pref_hash_store(GetPrefHashStore(profile_path));
-  if (pref_hash_store && !pref_hash_store->IsInitialized()) {
-    chrome_prefs::InitializeHashStoreForPrefFile(
-        GetPrefFilePathFromProfilePath(profile_path),
-        JsonPrefStore::GetTaskRunnerForFile(
-            profile_path, BrowserThread::GetBlockingPool()),
-        pref_hash_store.PassAs<PrefHashStore>());
-  }
-}
-
-// static
-void ProfileImpl::ResetPrefHashStore(const base::FilePath& profile_path) {
-  GetPrefHashStore(profile_path)->Reset();
-}
-
 ProfileImpl::ProfileImpl(
     const base::FilePath& path,
     Delegate* delegate,
@@ -517,11 +469,10 @@ ProfileImpl::ProfileImpl(
     startup_metric_utils::ScopedSlowStartupUMA
         scoped_timer("Startup.SlowStartupPreferenceLoading");
     prefs_ = chrome_prefs::CreateProfilePrefs(
-        GetPrefFilePath(),
+        path_,
         sequenced_task_runner,
         profile_policy_connector_->policy_service(),
         managed_user_settings,
-        GetPrefHashStore(path_).PassAs<PrefHashStore>(),
         new ExtensionPrefStore(
             ExtensionPrefValueMapFactory::GetForBrowserContext(this), false),
         pref_registry_,
@@ -668,12 +619,13 @@ void ProfileImpl::DoFinalInit() {
         base::Bind(&EnsureReadmeFile, GetPath()),
         base::TimeDelta::FromMilliseconds(create_readme_delay_ms));
 
-  if (!CommandLine::ForCurrentProcess()->HasSwitch(
-          switches::kDisableRestoreSessionState)) {
-    TRACE_EVENT0("browser", "ProfileImpl::SetSaveSessionStorageOnDisk")
-    content::BrowserContext::GetDefaultStoragePartition(this)->
-        GetDOMStorageContext()->SetSaveSessionStorageOnDisk();
-  }
+  TRACE_EVENT0("browser", "ProfileImpl::SetSaveSessionStorageOnDisk");
+  content::BrowserContext::GetDefaultStoragePartition(this)->
+      GetDOMStorageContext()->SetSaveSessionStorageOnDisk();
+
+  // The DomDistillerViewerSource is not a normal WebUI so it must be registered
+  // as a URLDataSource early.
+  RegisterDomDistillerViewerSource(this);
 
   // Creation has been finished.
   if (delegate_) {
@@ -703,6 +655,7 @@ void ProfileImpl::InitHostZoomMap() {
       prefs_->GetDictionary(prefs::kPerHostZoomLevels);
   // Careful: The returned value could be NULL if the pref has never been set.
   if (host_zoom_dictionary != NULL) {
+    std::vector<std::string> keys_to_remove;
     for (base::DictionaryValue::Iterator i(*host_zoom_dictionary); !i.IsAtEnd();
          i.Advance()) {
       const std::string& host(i.key());
@@ -710,8 +663,30 @@ void ProfileImpl::InitHostZoomMap() {
 
       bool success = i.value().GetAsDouble(&zoom_level);
       DCHECK(success);
+
+      // Filter out A) the empty host, B) zoom levels equal to the default; and
+      // remember them, so that we can later erase them from Prefs.
+      // Values of type A and B could have been stored due to crbug.com/364399.
+      // Values of type B could further have been stored before the default zoom
+      // level was set to its current value. In either case, SetZoomLevelForHost
+      // will ignore type B values, thus, to have consistency with HostZoomMap's
+      // internal state, these values must also be removed from Prefs.
+      if (host.empty() ||
+          content::ZoomValuesEqual(zoom_level,
+                                   host_zoom_map->GetDefaultZoomLevel())) {
+        keys_to_remove.push_back(host);
+        continue;
+      }
+
       host_zoom_map->SetZoomLevelForHost(host, zoom_level);
     }
+
+    DictionaryPrefUpdate update(prefs_.get(), prefs::kPerHostZoomLevels);
+    base::DictionaryValue* host_zoom_dictionary = update.Get();
+    for (std::vector<std::string>::const_iterator it = keys_to_remove.begin();
+         it != keys_to_remove.end(); ++it) {
+      host_zoom_dictionary->RemoveWithoutPathExpansion(*it, NULL);
+    }
   }
 
   zoom_subscription_ = host_zoom_map->AddZoomLevelChangedCallback(
@@ -774,6 +749,10 @@ std::string ProfileImpl::GetProfileName() {
   return GetPrefs()->GetString(prefs::kGoogleServicesUsername);
 }
 
+Profile::ProfileType ProfileImpl::GetProfileType() const {
+  return REGULAR_PROFILE;
+}
+
 base::FilePath ProfileImpl::GetPath() const {
   return path_;
 }
@@ -878,7 +857,7 @@ void ProfileImpl::OnPrefsLoaded(bool success) {
         predictor_));
   }
 
-  SchedulePrefsFileVerification(GetPrefFilePath());
+  chrome_prefs::SchedulePrefsFilePathVerification(path_);
 
   ChromeVersionService::OnProfileLoaded(prefs_.get(), IsNewProfile());
   DoFinalInit();
@@ -936,16 +915,14 @@ PrefService* ProfileImpl::GetOffTheRecordPrefs() {
   return otr_prefs_.get();
 }
 
-base::FilePath ProfileImpl::GetPrefFilePath() {
-  return GetPrefFilePathFromProfilePath(path_);
-}
-
 net::URLRequestContextGetter* ProfileImpl::CreateRequestContext(
-    content::ProtocolHandlerMap* protocol_handlers) {
-  return io_data_
-      .CreateMainRequestContextGetter(protocol_handlers,
-                                      g_browser_process->local_state(),
-                                      g_browser_process->io_thread()).get();
+    content::ProtocolHandlerMap* protocol_handlers,
+    content::ProtocolHandlerScopedVector protocol_interceptors) {
+  return io_data_.CreateMainRequestContextGetter(
+      protocol_handlers,
+      protocol_interceptors.Pass(),
+      g_browser_process->local_state(),
+      g_browser_process->io_thread()).get();
 }
 
 net::URLRequestContextGetter* ProfileImpl::GetRequestContext() {
@@ -983,29 +960,31 @@ ProfileImpl::GetMediaRequestContextForStoragePartition(
       .GetIsolatedMediaRequestContextGetter(partition_path, in_memory).get();
 }
 
-void ProfileImpl::RequestMIDISysExPermission(
+void ProfileImpl::RequestMidiSysExPermission(
       int render_process_id,
       int render_view_id,
       int bridge_id,
       const GURL& requesting_frame,
-      const MIDISysExPermissionCallback& callback) {
-  ChromeMIDIPermissionContext* context =
-      ChromeMIDIPermissionContextFactory::GetForProfile(this);
-  context->RequestMIDISysExPermission(render_process_id,
+      bool user_gesture,
+      const MidiSysExPermissionCallback& callback) {
+  ChromeMidiPermissionContext* context =
+      ChromeMidiPermissionContextFactory::GetForProfile(this);
+  context->RequestMidiSysExPermission(render_process_id,
                                       render_view_id,
                                       bridge_id,
                                       requesting_frame,
+                                      user_gesture,
                                       callback);
 }
 
-void ProfileImpl::CancelMIDISysExPermissionRequest(
+void ProfileImpl::CancelMidiSysExPermissionRequest(
     int render_process_id,
     int render_view_id,
     int bridge_id,
     const GURL& requesting_frame) {
-  ChromeMIDIPermissionContext* context =
-      ChromeMIDIPermissionContextFactory::GetForProfile(this);
-  context->CancelMIDISysExPermissionRequest(
+  ChromeMidiPermissionContext* context =
+      ChromeMidiPermissionContextFactory::GetForProfile(this);
+  context->CancelMidiSysExPermissionRequest(
       render_process_id, render_view_id, bridge_id, requesting_frame);
 }
 
@@ -1054,16 +1033,20 @@ net::URLRequestContextGetter*
 ProfileImpl::CreateRequestContextForStoragePartition(
     const base::FilePath& partition_path,
     bool in_memory,
-    content::ProtocolHandlerMap* protocol_handlers) {
+    content::ProtocolHandlerMap* protocol_handlers,
+    content::ProtocolHandlerScopedVector protocol_interceptors) {
   return io_data_.CreateIsolatedAppRequestContextGetter(
-                      partition_path, in_memory, protocol_handlers).get();
+      partition_path,
+      in_memory,
+      protocol_handlers,
+      protocol_interceptors.Pass()).get();
 }
 
 net::SSLConfigService* ProfileImpl::GetSSLConfigService() {
   // If ssl_config_service_manager_ is null, this typically means that some
-  // BrowserContextKeyedService is trying to create a RequestContext at startup,
+  // KeyedService is trying to create a RequestContext at startup,
   // but SSLConfigServiceManager is not initialized until DoFinalInit() which is
-  // invoked after all BrowserContextKeyedServices have been initialized (see
+  // invoked after all KeyedServices have been initialized (see
   // http://crbug.com/171406).
   DCHECK(ssl_config_service_manager_) <<
       "SSLConfigServiceManager is not initialized yet";
@@ -1128,7 +1111,7 @@ void ProfileImpl::OnZoomLevelChanged(
   double level = change.zoom_level;
   DictionaryPrefUpdate update(prefs_.get(), prefs::kPerHostZoomLevels);
   base::DictionaryValue* host_zoom_dictionary = update.Get();
-  if (level == host_zoom_map->GetDefaultZoomLevel()) {
+  if (content::ZoomValuesEqual(level, host_zoom_map->GetDefaultZoomLevel())) {
     host_zoom_dictionary->RemoveWithoutPathExpansion(change.host, NULL);
   } else {
     host_zoom_dictionary->SetWithoutPathExpansion(
@@ -1220,7 +1203,8 @@ void ProfileImpl::ChangeAppLocale(
     GetPrefs()->SetString(prefs::kApplicationLocale, new_locale);
   local_state->SetString(prefs::kApplicationLocale, new_locale);
 
-  if (chromeos::UserManager::Get()->IsCurrentUserOwner())
+  if (chromeos::UserManager::Get()->GetOwnerEmail() ==
+      chromeos::UserManager::Get()->GetUserByProfile(this)->email())
     local_state->SetString(prefs::kOwnerLocale, new_locale);
 }
 
@@ -1232,10 +1216,9 @@ void ProfileImpl::OnLogin() {
 
 void ProfileImpl::InitChromeOSPreferences() {
   chromeos_preferences_.reset(new chromeos::Preferences());
-  bool is_primary_user = chromeos::UserManager::Get()->GetPrimaryUser() ==
-      chromeos::UserManager::Get()->GetUserByProfile(this);
-  chromeos_preferences_->Init(PrefServiceSyncable::FromProfile(this),
-                              is_primary_user);
+  chromeos_preferences_->Init(
+      PrefServiceSyncable::FromProfile(this),
+      chromeos::UserManager::Get()->GetUserByProfile(this));
 }
 
 #endif  // defined(OS_CHROMEOS)