summaryrefslogtreecommitdiffstats
path: root/chrome
diff options
context:
space:
mode:
authorivankr@chromium.org <ivankr@chromium.org@0039d316-1c4b-4281-b951-d872f2087c98>2012-12-14 17:00:58 +0000
committerivankr@chromium.org <ivankr@chromium.org@0039d316-1c4b-4281-b951-d872f2087c98>2012-12-14 17:00:58 +0000
commit102253f8f90c2182190a825ec5573081f17dc9a2 (patch)
tree67a5f14f723686dc16c74ffdf08d53520cc167a2 /chrome
parent565bb8d289a5b75331e189b4e813c8f2997b2ba3 (diff)
downloadchromium_src-102253f8f90c2182190a825ec5573081f17dc9a2.zip
chromium_src-102253f8f90c2182190a825ec5573081f17dc9a2.tar.gz
chromium_src-102253f8f90c2182190a825ec5573081f17dc9a2.tar.bz2
Remove the protector service.
BUG=165008 NOTRY=true Review URL: https://chromiumcodereview.appspot.com/11493003 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@173169 0039d316-1c4b-4281-b951-d872f2087c98
Diffstat (limited to 'chrome')
-rw-r--r--chrome/app/generated_resources.grd84
-rw-r--r--chrome/app/theme/default_100_percent/common/protector_home_alert.pngbin892 -> 0 bytes
-rw-r--r--chrome/app/theme/default_100_percent/common/protector_home_badge.pngbin352 -> 0 bytes
-rw-r--r--chrome/app/theme/default_100_percent/common/protector_home_menu.pngbin595 -> 0 bytes
-rw-r--r--chrome/app/theme/default_100_percent/common/protector_search_alert.pngbin945 -> 0 bytes
-rw-r--r--chrome/app/theme/default_100_percent/common/protector_search_badge.pngbin375 -> 0 bytes
-rw-r--r--chrome/app/theme/default_100_percent/common/protector_search_menu.pngbin648 -> 0 bytes
-rw-r--r--chrome/app/theme/default_100_percent/protector_home_alert.pngbin892 -> 0 bytes
-rw-r--r--chrome/app/theme/default_100_percent/protector_home_badge.pngbin352 -> 0 bytes
-rw-r--r--chrome/app/theme/default_100_percent/protector_home_menu.pngbin595 -> 0 bytes
-rw-r--r--chrome/app/theme/default_100_percent/protector_search_alert.pngbin945 -> 0 bytes
-rw-r--r--chrome/app/theme/default_100_percent/protector_search_badge.pngbin375 -> 0 bytes
-rw-r--r--chrome/app/theme/default_100_percent/protector_search_menu.pngbin648 -> 0 bytes
-rw-r--r--chrome/app/theme/default_200_percent/common/protector_home_alert.pngbin1491 -> 0 bytes
-rw-r--r--chrome/app/theme/default_200_percent/common/protector_home_badge.pngbin499 -> 0 bytes
-rw-r--r--chrome/app/theme/default_200_percent/common/protector_home_menu.pngbin872 -> 0 bytes
-rw-r--r--chrome/app/theme/default_200_percent/common/protector_search_alert.pngbin1888 -> 0 bytes
-rw-r--r--chrome/app/theme/default_200_percent/common/protector_search_badge.pngbin681 -> 0 bytes
-rw-r--r--chrome/app/theme/default_200_percent/common/protector_search_menu.pngbin1198 -> 0 bytes
-rw-r--r--chrome/app/theme/default_200_percent/protector_home_alert.pngbin1491 -> 0 bytes
-rw-r--r--chrome/app/theme/default_200_percent/protector_home_badge.pngbin499 -> 0 bytes
-rw-r--r--chrome/app/theme/default_200_percent/protector_home_menu.pngbin872 -> 0 bytes
-rw-r--r--chrome/app/theme/default_200_percent/protector_search_alert.pngbin1888 -> 0 bytes
-rw-r--r--chrome/app/theme/default_200_percent/protector_search_badge.pngbin681 -> 0 bytes
-rw-r--r--chrome/app/theme/default_200_percent/protector_search_menu.pngbin1198 -> 0 bytes
-rw-r--r--chrome/app/theme/theme_resources.grd7
-rw-r--r--chrome/browser/automation/testing_automation_provider.cc57
-rw-r--r--chrome/browser/automation/testing_automation_provider.h14
-rw-r--r--chrome/browser/extensions/extension_system_factory.cc7
-rw-r--r--chrome/browser/prefs/browser_prefs.cc10
-rw-r--r--chrome/browser/prefs/browser_prefs.h3
-rw-r--r--chrome/browser/prefs/session_startup_pref.cc33
-rw-r--r--chrome/browser/prefs/session_startup_pref.h7
-rw-r--r--chrome/browser/profiles/profile_dependency_manager.cc4
-rw-r--r--chrome/browser/profiles/profile_impl.cc2
-rw-r--r--chrome/browser/protector/base_prefs_change.cc56
-rw-r--r--chrome/browser/protector/base_prefs_change.h45
-rw-r--r--chrome/browser/protector/base_setting_change.cc76
-rw-r--r--chrome/browser/protector/base_setting_change.h164
-rw-r--r--chrome/browser/protector/composite_settings_change.cc111
-rw-r--r--chrome/browser/protector/composite_settings_change.h52
-rw-r--r--chrome/browser/protector/composite_settings_change_unittest.cc122
-rw-r--r--chrome/browser/protector/default_search_provider_change.cc433
-rw-r--r--chrome/browser/protector/default_search_provider_change_browsertest.cc677
-rw-r--r--chrome/browser/protector/histograms.cc62
-rw-r--r--chrome/browser/protector/histograms.h83
-rw-r--r--chrome/browser/protector/homepage_change.cc201
-rw-r--r--chrome/browser/protector/homepage_change_unittest.cc118
-rw-r--r--chrome/browser/protector/keys.cc13
-rw-r--r--chrome/browser/protector/keys.h17
-rw-r--r--chrome/browser/protector/mock_protector_service.cc34
-rw-r--r--chrome/browser/protector/mock_protector_service.h44
-rw-r--r--chrome/browser/protector/mock_setting_change.cc47
-rw-r--r--chrome/browser/protector/mock_setting_change.h46
-rw-r--r--chrome/browser/protector/prefs_backup_invalid_change.cc151
-rw-r--r--chrome/browser/protector/prefs_backup_invalid_change_unittest.cc77
-rw-r--r--chrome/browser/protector/protected_prefs_watcher.cc399
-rw-r--r--chrome/browser/protector/protected_prefs_watcher.h104
-rw-r--r--chrome/browser/protector/protected_prefs_watcher_unittest.cc291
-rw-r--r--chrome/browser/protector/protector_service.cc236
-rw-r--r--chrome/browser/protector/protector_service.h152
-rw-r--r--chrome/browser/protector/protector_service_browsertest.cc662
-rw-r--r--chrome/browser/protector/protector_service_factory.cc56
-rw-r--r--chrome/browser/protector/protector_service_factory.h42
-rw-r--r--chrome/browser/protector/protector_utils.cc47
-rw-r--r--chrome/browser/protector/protector_utils.h23
-rw-r--r--chrome/browser/protector/session_startup_change.cc231
-rw-r--r--chrome/browser/protector/session_startup_change_unittest.cc191
-rw-r--r--chrome/browser/protector/settings_change_global_error.cc238
-rw-r--r--chrome/browser/protector/settings_change_global_error.h109
-rw-r--r--chrome/browser/protector/settings_change_global_error_delegate.h39
-rw-r--r--chrome/browser/search_engines/search_engine_type.h3
-rw-r--r--chrome/browser/search_engines/template_url_service.cc53
-rw-r--r--chrome/browser/search_engines/util.cc21
-rw-r--r--chrome/browser/search_engines/util.h9
-rw-r--r--chrome/browser/ui/startup/startup_browser_creator_impl.cc67
-rw-r--r--chrome/browser/webdata/keyword_table.cc297
-rw-r--r--chrome/browser/webdata/keyword_table.h60
-rw-r--r--chrome/browser/webdata/keyword_table_unittest.cc119
-rw-r--r--chrome/browser/webdata/web_data_service.cc9
-rw-r--r--chrome/browser/webdata/web_data_service.h6
-rw-r--r--chrome/browser/webdata/web_data_service_unittest.cc9
-rw-r--r--chrome/browser/webdata/web_database.cc17
-rw-r--r--chrome/browser/webdata/web_database_migration_unittest.cc376
-rw-r--r--chrome/chrome_browser.gypi53
-rw-r--r--chrome/chrome_tests.gypi6
-rw-r--r--chrome/chrome_tests_unit.gypi14
-rw-r--r--chrome/common/chrome_switches.cc3
-rw-r--r--chrome/common/chrome_switches.h1
-rw-r--r--chrome/test/base/testing_profile.cc9
-rw-r--r--chrome/test/data/web_database/version_41.sql2
-rw-r--r--chrome/test/data/web_database/version_42.sql2
-rw-r--r--chrome/test/data/web_database/version_43.sql2
-rw-r--r--chrome/test/data/web_database/version_44_backup_corrupt.sql53
-rw-r--r--chrome/test/data/web_database/version_47.sql (renamed from chrome/test/data/web_database/version_46_backup_corrupt.sql)37
-rwxr-xr-xchrome/test/functional/protector.py750
-rwxr-xr-xchrome/test/pyautolib/pyauto.py46
97 files changed, 195 insertions, 7506 deletions
diff --git a/chrome/app/generated_resources.grd b/chrome/app/generated_resources.grd
index 7613848..11a42ea 100644
--- a/chrome/app/generated_resources.grd
+++ b/chrome/app/generated_resources.grd
@@ -1458,90 +1458,6 @@ Psst! Incognito mode <ph name="SHORTCUT_KEY">$1<ex>(Ctrl+Shift+N)</ex></ph> may
</message>
</if>
- <!-- Protector error messages -->
- <message name="IDS_SEARCH_ENGINE_CHANGE_TITLE" desc="The title of the bubble and the wrench menu item with a search engine change notification.">
- Attempted default search change
- </message>
- <message name="IDS_SEARCH_ENGINE_CHANGE_MESSAGE" desc="The text of the search engine change notification.">
- Arrr! Something tried to commandeer your default search setting!
- </message>
- <message name="IDS_SEARCH_ENGINE_CHANGE_NO_BACKUP_MESSAGE" desc="The text of the search engine change notification when the previous setting is lost.">
- Arrr! Something tried to commandeer your default search setting! We weren't sure what to do, so we set it to <ph name="PREPOPULATED_ENGINE">$1<ex>DefaultSearchEngine</ex></ph>.
- </message>
- <message name="IDS_KEEP_SEARCH_ENGINE" desc="The title of the button that confirms staying with the previous search engine setting.">
- Keep using <ph name="PREV_ENGINE">$1<ex>PreviousSearchEngine</ex></ph>
- </message>
- <message name="IDS_CHANGE_SEARCH_ENGINE" desc="The title of the button that accepts new default search engine setting.">
- Change to <ph name="NEW_ENGINE">$1<ex>NewSearchEngine</ex></ph>
- </message>
- <message name="IDS_CHANGE_SEARCH_ENGINE_NO_NAME" desc="The title of the button that accepts new default search engine setting when the search engine name is too long.">
- Change search setting
- </message>
- <message name="IDS_SELECT_SEARCH_ENGINE" desc="The title of the button that opens a settings page, allowing user to select the default search engine to use.">
- Select search setting...
- </message>
-
- <message name="IDS_HOMEPAGE_CHANGE_TITLE" desc="The title of the bubble and the wrench menu item with a home page change notification.">
- Attempted home page change
- </message>
- <message name="IDS_HOMEPAGE_CHANGE_BUBBLE_MESSAGE" desc="The text of the home page change notification.">
- Arrr! Something tried to commandeer your home page!
- </message>
- <message name="IDS_KEEP_HOMEPAGE" desc="The title of the button that confirms staying with the previous home page setting.">
- Keep using <ph name="PREV_HOMEPAGE">$1<ex>google.com</ex></ph>
- </message>
- <message name="IDS_KEEP_HOMEPAGE_NTP" desc="The title of the button that confirms staying with the previous home page setting, which is opening the New Tab page.">
- Keep using New Tab page
- </message>
- <message name="IDS_CHANGE_HOMEPAGE" desc="The title of the button that accepts new home page setting.">
- Change to <ph name="NEW_HOMEPAGE">$1<ex>google.com</ex></ph>
- </message>
- <message name="IDS_CHANGE_HOMEPAGE_NTP" desc="The title of the button that accepts new home page setting, which is opening the New Tab page.">
- Change to New Tab page
- </message>
- <message name="IDS_CHANGE_HOMEPAGE_NO_NAME" desc="The title of the button that accepts new home page setting when the home page title is too long.">
- Change home page
- </message>
-
- <message name="IDS_STARTUP_SETTINGS_CHANGE_TITLE" desc="The title of the bubble and the wrench menu item with a startup settings change notification.">
- Attempted startup settings change
- </message>
- <message name="IDS_STARTUP_SETTINGS_CHANGE_BUBBLE_MESSAGE" desc="The text of the startup settings change notification.">
- Arrr! Something tried to commandeer the pages you'd like to see at startup!
- </message>
- <message name="IDS_CHANGE_STARTUP_SETTINGS_RESTORE" desc="The title of the button that accepts new startup settings to restore the session. Must be kept short.">
- Change to restore open pages
- </message>
- <message name="IDS_CHANGE_STARTUP_SETTINGS_NTP" desc="The title of the button that accepts new startup settings to open the NTP. Must be kept short.">
- Change to New Tab Page
- </message>
- <message name="IDS_CHANGE_STARTUP_SETTINGS_URLS" desc="The title of the button that accepts new startup settings to open a specific page. Must be kept short.">
- Change to <ph name="URL">$1<ex>google.com</ex></ph>
- </message>
-
- <message name="IDS_SETTING_CHANGE_TITLE" desc="The title of the bubble and the wrench menu item with a generic settings change.">
- Attempted settings change
- </message>
- <message name="IDS_SETTING_CHANGE_BUBBLE_MESSAGE" desc="The text of the generic settings change notification.">
- Arrr! Something tried to commandeer your settings!
- </message>
- <message name="IDS_SETTING_CHANGE_NO_BACKUP_STARTUP_RESET_BUBBLE_MESSAGE" desc="The text of the generic settings change notification, additionally informing user that the startup settings have been reset to defaults.">
- Arrr! Something tried to commandeer your settings! We weren't sure what to do, so the startup page has been reset to the default.
- </message>
- <message name="IDS_EDIT_SETTINGS" desc="The title of the button that opens a settings page, allowing user to edit changed settings">
- Edit settings...
- </message>
-
- <message name="IDS_KEEP_SETTING" desc="The title of the button that confirms staying with the previous settings.">
- Keep my settings
- </message>
- <message name="IDS_CHANGE_SETTING" desc="The title of the button that confirms changing to the new settings, usually described by a domain name or search engine name.">
- Change to <ph name="NEW_SETTING_NAME">$1<ex>Awesome Site</ex></ph>
- </message>
- <message name="IDS_CHANGE_SETTING_NO_NAME" desc="The title of the button that confirms changing to the new settings.">
- Change settings
- </message>
-
<!-- Keywords -->
<message name="IDS_AUTOCOMPLETE_MATCH_DESCRIPTION_SEPARATOR" desc="The separator between a result in the autocomplete popup and its description.">
''' - '''
diff --git a/chrome/app/theme/default_100_percent/common/protector_home_alert.png b/chrome/app/theme/default_100_percent/common/protector_home_alert.png
deleted file mode 100644
index f0a20ad..0000000
--- a/chrome/app/theme/default_100_percent/common/protector_home_alert.png
+++ /dev/null
Binary files differ
diff --git a/chrome/app/theme/default_100_percent/common/protector_home_badge.png b/chrome/app/theme/default_100_percent/common/protector_home_badge.png
deleted file mode 100644
index 5b57927..0000000
--- a/chrome/app/theme/default_100_percent/common/protector_home_badge.png
+++ /dev/null
Binary files differ
diff --git a/chrome/app/theme/default_100_percent/common/protector_home_menu.png b/chrome/app/theme/default_100_percent/common/protector_home_menu.png
deleted file mode 100644
index 1151cc9..0000000
--- a/chrome/app/theme/default_100_percent/common/protector_home_menu.png
+++ /dev/null
Binary files differ
diff --git a/chrome/app/theme/default_100_percent/common/protector_search_alert.png b/chrome/app/theme/default_100_percent/common/protector_search_alert.png
deleted file mode 100644
index e8a1a68..0000000
--- a/chrome/app/theme/default_100_percent/common/protector_search_alert.png
+++ /dev/null
Binary files differ
diff --git a/chrome/app/theme/default_100_percent/common/protector_search_badge.png b/chrome/app/theme/default_100_percent/common/protector_search_badge.png
deleted file mode 100644
index a73cee0..0000000
--- a/chrome/app/theme/default_100_percent/common/protector_search_badge.png
+++ /dev/null
Binary files differ
diff --git a/chrome/app/theme/default_100_percent/common/protector_search_menu.png b/chrome/app/theme/default_100_percent/common/protector_search_menu.png
deleted file mode 100644
index 168c375..0000000
--- a/chrome/app/theme/default_100_percent/common/protector_search_menu.png
+++ /dev/null
Binary files differ
diff --git a/chrome/app/theme/default_100_percent/protector_home_alert.png b/chrome/app/theme/default_100_percent/protector_home_alert.png
deleted file mode 100644
index f0a20ad..0000000
--- a/chrome/app/theme/default_100_percent/protector_home_alert.png
+++ /dev/null
Binary files differ
diff --git a/chrome/app/theme/default_100_percent/protector_home_badge.png b/chrome/app/theme/default_100_percent/protector_home_badge.png
deleted file mode 100644
index 5b57927..0000000
--- a/chrome/app/theme/default_100_percent/protector_home_badge.png
+++ /dev/null
Binary files differ
diff --git a/chrome/app/theme/default_100_percent/protector_home_menu.png b/chrome/app/theme/default_100_percent/protector_home_menu.png
deleted file mode 100644
index 1151cc9..0000000
--- a/chrome/app/theme/default_100_percent/protector_home_menu.png
+++ /dev/null
Binary files differ
diff --git a/chrome/app/theme/default_100_percent/protector_search_alert.png b/chrome/app/theme/default_100_percent/protector_search_alert.png
deleted file mode 100644
index e8a1a68..0000000
--- a/chrome/app/theme/default_100_percent/protector_search_alert.png
+++ /dev/null
Binary files differ
diff --git a/chrome/app/theme/default_100_percent/protector_search_badge.png b/chrome/app/theme/default_100_percent/protector_search_badge.png
deleted file mode 100644
index a73cee0..0000000
--- a/chrome/app/theme/default_100_percent/protector_search_badge.png
+++ /dev/null
Binary files differ
diff --git a/chrome/app/theme/default_100_percent/protector_search_menu.png b/chrome/app/theme/default_100_percent/protector_search_menu.png
deleted file mode 100644
index 168c375..0000000
--- a/chrome/app/theme/default_100_percent/protector_search_menu.png
+++ /dev/null
Binary files differ
diff --git a/chrome/app/theme/default_200_percent/common/protector_home_alert.png b/chrome/app/theme/default_200_percent/common/protector_home_alert.png
deleted file mode 100644
index c6bbd7e..0000000
--- a/chrome/app/theme/default_200_percent/common/protector_home_alert.png
+++ /dev/null
Binary files differ
diff --git a/chrome/app/theme/default_200_percent/common/protector_home_badge.png b/chrome/app/theme/default_200_percent/common/protector_home_badge.png
deleted file mode 100644
index 5048e12..0000000
--- a/chrome/app/theme/default_200_percent/common/protector_home_badge.png
+++ /dev/null
Binary files differ
diff --git a/chrome/app/theme/default_200_percent/common/protector_home_menu.png b/chrome/app/theme/default_200_percent/common/protector_home_menu.png
deleted file mode 100644
index 3fea8be..0000000
--- a/chrome/app/theme/default_200_percent/common/protector_home_menu.png
+++ /dev/null
Binary files differ
diff --git a/chrome/app/theme/default_200_percent/common/protector_search_alert.png b/chrome/app/theme/default_200_percent/common/protector_search_alert.png
deleted file mode 100644
index 2cd02f8..0000000
--- a/chrome/app/theme/default_200_percent/common/protector_search_alert.png
+++ /dev/null
Binary files differ
diff --git a/chrome/app/theme/default_200_percent/common/protector_search_badge.png b/chrome/app/theme/default_200_percent/common/protector_search_badge.png
deleted file mode 100644
index 84949cc..0000000
--- a/chrome/app/theme/default_200_percent/common/protector_search_badge.png
+++ /dev/null
Binary files differ
diff --git a/chrome/app/theme/default_200_percent/common/protector_search_menu.png b/chrome/app/theme/default_200_percent/common/protector_search_menu.png
deleted file mode 100644
index 6f5009d..0000000
--- a/chrome/app/theme/default_200_percent/common/protector_search_menu.png
+++ /dev/null
Binary files differ
diff --git a/chrome/app/theme/default_200_percent/protector_home_alert.png b/chrome/app/theme/default_200_percent/protector_home_alert.png
deleted file mode 100644
index c6bbd7e..0000000
--- a/chrome/app/theme/default_200_percent/protector_home_alert.png
+++ /dev/null
Binary files differ
diff --git a/chrome/app/theme/default_200_percent/protector_home_badge.png b/chrome/app/theme/default_200_percent/protector_home_badge.png
deleted file mode 100644
index 5048e12..0000000
--- a/chrome/app/theme/default_200_percent/protector_home_badge.png
+++ /dev/null
Binary files differ
diff --git a/chrome/app/theme/default_200_percent/protector_home_menu.png b/chrome/app/theme/default_200_percent/protector_home_menu.png
deleted file mode 100644
index 3fea8be..0000000
--- a/chrome/app/theme/default_200_percent/protector_home_menu.png
+++ /dev/null
Binary files differ
diff --git a/chrome/app/theme/default_200_percent/protector_search_alert.png b/chrome/app/theme/default_200_percent/protector_search_alert.png
deleted file mode 100644
index 2cd02f8..0000000
--- a/chrome/app/theme/default_200_percent/protector_search_alert.png
+++ /dev/null
Binary files differ
diff --git a/chrome/app/theme/default_200_percent/protector_search_badge.png b/chrome/app/theme/default_200_percent/protector_search_badge.png
deleted file mode 100644
index 84949cc..0000000
--- a/chrome/app/theme/default_200_percent/protector_search_badge.png
+++ /dev/null
Binary files differ
diff --git a/chrome/app/theme/default_200_percent/protector_search_menu.png b/chrome/app/theme/default_200_percent/protector_search_menu.png
deleted file mode 100644
index 6f5009d..0000000
--- a/chrome/app/theme/default_200_percent/protector_search_menu.png
+++ /dev/null
Binary files differ
diff --git a/chrome/app/theme/theme_resources.grd b/chrome/app/theme/theme_resources.grd
index cbff574..0f7d4fd 100644
--- a/chrome/app/theme/theme_resources.grd
+++ b/chrome/app/theme/theme_resources.grd
@@ -317,9 +317,6 @@
<if expr="pp_ifdef('toolkit_views') or is_macosx">
<structure type="chrome_scaled_image" name="IDR_HOME" file="common/browser_home_normal.png" />
</if>
- <structure type="chrome_scaled_image" name="IDR_HOMEPAGE_CHANGE_ALERT" file="protector_home_alert.png" />
- <structure type="chrome_scaled_image" name="IDR_HOMEPAGE_CHANGE_BADGE" file="protector_home_badge.png" />
- <structure type="chrome_scaled_image" name="IDR_HOMEPAGE_CHANGE_MENU" file="protector_home_menu.png" />
<if expr="not pp_ifdef('toolkit_views') and not is_macosx">
<structure type="chrome_scaled_image" name="IDR_HOME_H" file="home_hover.png" />
<structure type="chrome_scaled_image" name="IDR_HOME_P" file="home_pressed.png" />
@@ -666,9 +663,7 @@
<structure type="chrome_scaled_image" name="IDR_SAD_FAVICON" file="common/favicon_sad_tab.png" />
<structure type="chrome_scaled_image" name="IDR_SAD_TAB" file="sadtab.png" />
<structure type="chrome_scaled_image" name="IDR_SAFEBROWSING_WARNING" file="safebrowsing_warning.png" />
- <structure type="chrome_scaled_image" name="IDR_SEARCH_ENGINE_CHANGE_ALERT" file="protector_search_alert.png" />
- <structure type="chrome_scaled_image" name="IDR_SEARCH_ENGINE_CHANGE_BADGE" file="protector_search_badge.png" />
- <structure type="chrome_scaled_image" name="IDR_SEARCH_ENGINE_CHANGE_MENU" file="protector_search_menu.png" />
+ <structure type="chrome_scaled_image" name="IDR_SCRIPT_BUBBLE" file="common/favicon_extensions.png" />
<if expr="pp_ifdef('enable_settings_app')">
<structure type="chrome_scaled_image" name="IDR_SETTINGS_APP_ICON_128" file="settings_app_icon_128.png" />
<structure type="chrome_scaled_image" name="IDR_SETTINGS_APP_ICON_16" file="settings_app_icon_16.png" />
diff --git a/chrome/browser/automation/testing_automation_provider.cc b/chrome/browser/automation/testing_automation_provider.cc
index 16e6c8b..2bcd2c4 100644
--- a/chrome/browser/automation/testing_automation_provider.cc
+++ b/chrome/browser/automation/testing_automation_provider.cc
@@ -80,9 +80,6 @@
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/profiles/profile_info_cache.h"
#include "chrome/browser/profiles/profile_manager.h"
-#include "chrome/browser/protector/protector_service.h"
-#include "chrome/browser/protector/protector_service_factory.h"
-#include "chrome/browser/protector/protector_utils.h"
#include "chrome/browser/search_engines/template_url.h"
#include "chrome/browser/search_engines/template_url_service.h"
#include "chrome/browser/search_engines/template_url_service_factory.h"
@@ -1909,13 +1906,6 @@ void TestingAutomationProvider::BuildJSONHandlerMaps() {
browser_handler_map_["PerformActionOnSearchEngine"] =
&TestingAutomationProvider::PerformActionOnSearchEngine;
-#if defined(ENABLE_PROTECTOR_SERVICE)
- browser_handler_map_["GetProtectorState"] =
- &TestingAutomationProvider::GetProtectorState;
- browser_handler_map_["PerformProtectorAction"] =
- &TestingAutomationProvider::PerformProtectorAction;
-#endif
-
browser_handler_map_["SetWindowDimensions"] =
&TestingAutomationProvider::SetWindowDimensions;
@@ -2899,53 +2889,6 @@ void TestingAutomationProvider::PerformActionOnSearchEngine(
}
}
-#if defined(ENABLE_PROTECTOR_SERVICE)
-// Sample json output: { "enabled": true,
-// "showing_change": false }
-void TestingAutomationProvider::GetProtectorState(
- Browser* browser,
- DictionaryValue* args,
- IPC::Message* reply_message) {
- protector::ProtectorService* protector_service =
- protector::ProtectorServiceFactory::GetForProfile(browser->profile());
- scoped_ptr<DictionaryValue> return_value(new DictionaryValue);
- return_value->SetBoolean("enabled", protector::IsEnabled());
- return_value->SetBoolean("showing_change",
- protector_service->IsShowingChange());
- AutomationJSONReply(this, reply_message).SendSuccess(return_value.get());
-}
-
-// Sample json inputs:
-// { "command": "PerformProtectorAction", "action": "apply_change" }
-// { "command": "PerformProtectorAction", "action": "discard_change" }
-void TestingAutomationProvider::PerformProtectorAction(
- Browser* browser,
- base::DictionaryValue* args,
- IPC::Message* reply_message) {
- protector::ProtectorService* protector_service =
- protector::ProtectorServiceFactory::GetForProfile(browser->profile());
- AutomationJSONReply reply(this, reply_message);
- if (!protector::IsEnabled()) {
- reply.SendError("Protector is disabled");
- return;
- }
- std::string action;
- if (!args->GetString("action", &action)) {
- reply.SendError("Missing 'action' value");
- return;
- }
- protector::BaseSettingChange* change =
- protector_service->GetLastChange();
- if (action == "apply_change")
- protector_service->ApplyChange(change, browser);
- else if (action == "discard_change")
- protector_service->DiscardChange(change, browser);
- else
- return reply.SendError("Invalid 'action' value");
- reply.SendSuccess(NULL);
-}
-#endif // defined(ENABLE_PROTECTOR_SERVICE)
-
// Sample json input: { "command": "GetLocalStatePrefsInfo" }
// Refer chrome/test/pyautolib/prefs_info.py for sample json output.
void TestingAutomationProvider::GetLocalStatePrefsInfo(
diff --git a/chrome/browser/automation/testing_automation_provider.h b/chrome/browser/automation/testing_automation_provider.h
index 6e6e9c97..ca5340c 100644
--- a/chrome/browser/automation/testing_automation_provider.h
+++ b/chrome/browser/automation/testing_automation_provider.h
@@ -380,20 +380,6 @@ class TestingAutomationProvider : public AutomationProvider,
base::DictionaryValue* args,
IPC::Message* reply_message);
-#if defined(ENABLE_PROTECTOR_SERVICE)
- // Get ProtectorService state.
- // Uses the JSON interface for input/output.
- void GetProtectorState(Browser* browser,
- base::DictionaryValue* args,
- IPC::Message* reply_message);
-
- // Perform a given action on the ProtectorService.
- // Uses the JSON interface for input/output.
- void PerformProtectorAction(Browser* browser,
- base::DictionaryValue* args,
- IPC::Message* reply_message);
-#endif
-
// Get info about preferences stored in Local State.
// Uses the JSON interface for input/output.
void GetLocalStatePrefsInfo(base::DictionaryValue* args,
diff --git a/chrome/browser/extensions/extension_system_factory.cc b/chrome/browser/extensions/extension_system_factory.cc
index 437509a..9cbf46b 100644
--- a/chrome/browser/extensions/extension_system_factory.cc
+++ b/chrome/browser/extensions/extension_system_factory.cc
@@ -9,7 +9,7 @@
#include "chrome/browser/extensions/extension_system.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/profiles/profile_dependency_manager.h"
-#include "chrome/browser/protector/protector_service_factory.h"
+#include "chrome/browser/search_engines/template_url_service_factory.h"
#include "chrome/browser/themes/theme_service_factory.h"
#include "chrome/browser/ui/global_error/global_error_service_factory.h"
@@ -37,10 +37,7 @@ ExtensionSystemSharedFactory::ExtensionSystemSharedFactory()
#if defined(ENABLE_THEMES)
DependsOn(ThemeServiceFactory::GetInstance());
#endif
-#if defined(ENABLE_PROTECTOR_SERVICE)
- // ProtectorService should be destroyed after us.
- DependsOn(protector::ProtectorServiceFactory::GetInstance());
-#endif
+ DependsOn(TemplateURLServiceFactory::GetInstance());
}
ExtensionSystemSharedFactory::~ExtensionSystemSharedFactory() {
diff --git a/chrome/browser/prefs/browser_prefs.cc b/chrome/browser/prefs/browser_prefs.cc
index 83fa77c..153d286 100644
--- a/chrome/browser/prefs/browser_prefs.cc
+++ b/chrome/browser/prefs/browser_prefs.cc
@@ -305,6 +305,16 @@ void RegisterUserPrefs(PrefService* user_prefs) {
#endif
}
+void MigrateUserPrefs(Profile* profile) {
+ // Cleanup old prefs.
+ static const char kBackupPref[] = "backup";
+ PrefService* prefs = profile->GetPrefs();
+ prefs->RegisterDictionaryPref(kBackupPref, new DictionaryValue(),
+ PrefService::UNSYNCABLE_PREF);
+ prefs->ClearPref(kBackupPref);
+ prefs->UnregisterPreference(kBackupPref);
+}
+
void MigrateBrowserPrefs(Profile* profile, PrefService* local_state) {
// Copy pref values which have been migrated to user_prefs from local_state,
// or remove them from local_state outright, if copying is not required.
diff --git a/chrome/browser/prefs/browser_prefs.h b/chrome/browser/prefs/browser_prefs.h
index 93219e7..158de13d 100644
--- a/chrome/browser/prefs/browser_prefs.h
+++ b/chrome/browser/prefs/browser_prefs.h
@@ -17,6 +17,9 @@ void RegisterUserPrefs(PrefService* user_prefs);
// Migrates prefs from |local_state| to |profile|'s pref store.
void MigrateBrowserPrefs(Profile* profile, PrefService* local_state);
+// Migrates prefs in |profile|'s pref store.
+void MigrateUserPrefs(Profile* profile);
+
} // namespace chrome
#endif // CHROME_BROWSER_PREFS_BROWSER_PREFS_H_
diff --git a/chrome/browser/prefs/session_startup_pref.cc b/chrome/browser/prefs/session_startup_pref.cc
index 5738b6e..cb421b6 100644
--- a/chrome/browser/prefs/session_startup_pref.cc
+++ b/chrome/browser/prefs/session_startup_pref.cc
@@ -12,18 +12,12 @@
#include "chrome/browser/prefs/pref_service.h"
#include "chrome/browser/prefs/scoped_user_pref_update.h"
#include "chrome/browser/profiles/profile.h"
-#include "chrome/browser/protector/protected_prefs_watcher.h"
-#include "chrome/browser/protector/protector_service.h"
-#include "chrome/browser/protector/protector_service_factory.h"
#include "chrome/common/pref_names.h"
#if defined(OS_MACOSX)
#include "chrome/browser/ui/cocoa/window_restore_utils.h"
#endif
-using protector::ProtectedPrefsWatcher;
-using protector::ProtectorServiceFactory;
-
namespace {
// Converts a SessionStartupPref::Type to an integer written to prefs.
@@ -235,33 +229,6 @@ SessionStartupPref::Type SessionStartupPref::PrefValueToType(int pref_value) {
}
}
-// static
-bool SessionStartupPref::DidStartupPrefChange(Profile* profile) {
- ProtectedPrefsWatcher* prefs_watcher =
- ProtectorServiceFactory::GetForProfile(profile)->GetPrefsWatcher();
- return prefs_watcher->DidPrefChange(prefs::kRestoreOnStartup) ||
- prefs_watcher->DidPrefChange(prefs::kURLsToRestoreOnStartup);
-}
-
-// static
-SessionStartupPref SessionStartupPref::GetStartupPrefBackup(Profile* profile) {
- protector::ProtectedPrefsWatcher* prefs_watcher =
- protector::ProtectorServiceFactory::GetForProfile(profile)->
- GetPrefsWatcher();
-
- int type;
- CHECK(prefs_watcher->GetBackupForPref(
- prefs::kRestoreOnStartup)->GetAsInteger(&type));
- SessionStartupPref backup_pref(PrefValueToType(type));
-
- const ListValue* url_list;
- CHECK(prefs_watcher->GetBackupForPref(
- prefs::kURLsToRestoreOnStartup)->GetAsList(&url_list));
- URLListToPref(url_list, &backup_pref);
-
- return backup_pref;
-}
-
SessionStartupPref::SessionStartupPref(Type type) : type(type) {}
SessionStartupPref::~SessionStartupPref() {}
diff --git a/chrome/browser/prefs/session_startup_pref.h b/chrome/browser/prefs/session_startup_pref.h
index 36c1fd5..878b3f3 100644
--- a/chrome/browser/prefs/session_startup_pref.h
+++ b/chrome/browser/prefs/session_startup_pref.h
@@ -71,13 +71,6 @@ struct SessionStartupPref {
// Converts an integer pref value to a SessionStartupPref::Type.
static SessionStartupPref::Type PrefValueToType(int pref_value);
- // Returns |true| if a change to startup type or URLS was detected by
- // ProtectorService.
- static bool DidStartupPrefChange(Profile* profile);
-
- // Returns the protected backup of startup type and URLS.
- static SessionStartupPref GetStartupPrefBackup(Profile* profile);
-
explicit SessionStartupPref(Type type);
~SessionStartupPref();
diff --git a/chrome/browser/profiles/profile_dependency_manager.cc b/chrome/browser/profiles/profile_dependency_manager.cc
index 652c0e1..fb357f2 100644
--- a/chrome/browser/profiles/profile_dependency_manager.cc
+++ b/chrome/browser/profiles/profile_dependency_manager.cc
@@ -52,7 +52,6 @@
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/profiles/profile_keyed_service.h"
#include "chrome/browser/profiles/profile_keyed_service_factory.h"
-#include "chrome/browser/protector/protector_service_factory.h"
#include "chrome/browser/search_engines/template_url_fetcher_factory.h"
#include "chrome/browser/search_engines/template_url_service_factory.h"
#include "chrome/browser/sessions/session_service_factory.h"
@@ -279,9 +278,6 @@ void ProfileDependencyManager::AssertFactoriesBuilt() {
prerender::PrerenderLinkManagerFactory::GetInstance();
ProfileSyncServiceFactory::GetInstance();
ProtocolHandlerRegistryFactory::GetInstance();
-#if defined(ENABLE_PROTECTOR_SERVICE)
- protector::ProtectorServiceFactory::GetInstance();
-#endif
#if defined(ENABLE_SESSION_SERVICE)
SessionServiceFactory::GetInstance();
#endif
diff --git a/chrome/browser/profiles/profile_impl.cc b/chrome/browser/profiles/profile_impl.cc
index 19c0ff8..7a2a57b 100644
--- a/chrome/browser/profiles/profile_impl.cc
+++ b/chrome/browser/profiles/profile_impl.cc
@@ -694,6 +694,8 @@ void ProfileImpl::OnPrefsLoaded(bool success) {
// TODO(mirandac): remove migration code after 6 months (crbug.com/69995).
if (g_browser_process->local_state())
chrome::MigrateBrowserPrefs(this, g_browser_process->local_state());
+ // TODO(ivankr): remove cleanup code eventually (crbug.com/165672).
+ chrome::MigrateUserPrefs(this);
// |kSessionExitType| was added after |kSessionExitedCleanly|. If the pref
// value is empty fallback to checking for |kSessionExitedCleanly|.
diff --git a/chrome/browser/protector/base_prefs_change.cc b/chrome/browser/protector/base_prefs_change.cc
deleted file mode 100644
index b7708b3..0000000
--- a/chrome/browser/protector/base_prefs_change.cc
+++ /dev/null
@@ -1,56 +0,0 @@
-// Copyright (c) 2012 The Chromium Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-#include "chrome/browser/protector/base_prefs_change.h"
-
-#include "base/bind.h"
-#include "chrome/browser/prefs/pref_service.h"
-#include "chrome/browser/profiles/profile.h"
-#include "chrome/browser/protector/protected_prefs_watcher.h"
-#include "chrome/browser/protector/protector_service.h"
-#include "chrome/browser/protector/protector_service_factory.h"
-#include "chrome/browser/protector/protector_utils.h"
-#include "chrome/common/chrome_notification_types.h"
-#include "content/public/browser/notification_service.h"
-
-namespace protector {
-
-BasePrefsChange::BasePrefsChange() {
-}
-
-BasePrefsChange::~BasePrefsChange() {
-}
-
-bool BasePrefsChange::Init(Profile* profile) {
- if (!BaseSettingChange::Init(profile))
- return false;
- pref_observer_.Init(profile->GetPrefs());
- return true;
-}
-
-void BasePrefsChange::InitWhenDisabled(Profile* profile) {
- // Forcibly set backup to match the actual settings so that no changes are
- // detected on future runs.
- ProtectorServiceFactory::GetForProfile(profile)->GetPrefsWatcher()->
- ForceUpdateBackup();
-}
-
-void BasePrefsChange::DismissOnPrefChange(const std::string& pref_name) {
- DCHECK(!pref_observer_.IsObserved(pref_name));
- pref_observer_.Add(pref_name.c_str(),
- base::Bind(&BasePrefsChange::OnPreferenceChanged,
- base::Unretained(this)));
-}
-
-void BasePrefsChange::IgnorePrefChanges() {
- pref_observer_.RemoveAll();
-}
-
-void BasePrefsChange::OnPreferenceChanged(const std::string& pref_name) {
- DCHECK(pref_observer_.IsObserved(pref_name));
- // Will delete this instance.
- ProtectorServiceFactory::GetForProfile(profile())->DismissChange(this);
-}
-
-} // namespace protector
diff --git a/chrome/browser/protector/base_prefs_change.h b/chrome/browser/protector/base_prefs_change.h
deleted file mode 100644
index 046b83a..0000000
--- a/chrome/browser/protector/base_prefs_change.h
+++ /dev/null
@@ -1,45 +0,0 @@
-// Copyright (c) 2012 The Chromium Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-#ifndef CHROME_BROWSER_PROTECTOR_BASE_PREFS_CHANGE_H_
-#define CHROME_BROWSER_PROTECTOR_BASE_PREFS_CHANGE_H_
-
-#include <string>
-
-#include "base/memory/scoped_ptr.h"
-#include "base/prefs/public/pref_change_registrar.h"
-#include "chrome/browser/protector/base_setting_change.h"
-
-namespace protector {
-
-// BaseSettingChange subclass for PrefService-managed settings changes.
-class BasePrefsChange : public BaseSettingChange {
- public:
- BasePrefsChange();
- virtual ~BasePrefsChange();
-
- // BaseSettingChange overrides:
- virtual bool Init(Profile* profile) OVERRIDE;
- virtual void InitWhenDisabled(Profile* profile) OVERRIDE;
-
- protected:
- // Marks |this| to be dismissed when |pref_name| is changed. Should only be
- // called after Init.
- void DismissOnPrefChange(const std::string& pref_name);
-
- // Ignores any further changes to prefs. No further DismissOnPrefChange calls
- // can be made.
- void IgnorePrefChanges();
-
- private:
- void OnPreferenceChanged(const std::string& pref_name);
-
- PrefChangeRegistrar pref_observer_;
-
- DISALLOW_COPY_AND_ASSIGN(BasePrefsChange);
-};
-
-} // namespace protector
-
-#endif // CHROME_BROWSER_PROTECTOR_BASE_PREFS_CHANGE_H_
diff --git a/chrome/browser/protector/base_setting_change.cc b/chrome/browser/protector/base_setting_change.cc
deleted file mode 100644
index aa6df39..0000000
--- a/chrome/browser/protector/base_setting_change.cc
+++ /dev/null
@@ -1,76 +0,0 @@
-// Copyright (c) 2012 The Chromium Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-#include "chrome/browser/protector/base_setting_change.h"
-#include "chrome/browser/protector/composite_settings_change.h"
-
-#include "base/logging.h"
-
-namespace protector {
-
-const size_t kDefaultSearchProviderChangeNamePriority = 100U;
-const size_t kSessionStartupChangeNamePriority = 50U;
-const size_t kHomepageChangeNamePriority = 10U;
-
-// static
-const size_t BaseSettingChange::kDefaultNamePriority = 0U;
-
-BaseSettingChange::BaseSettingChange()
- : profile_(NULL) {
-}
-
-BaseSettingChange::~BaseSettingChange() {
-}
-
-CompositeSettingsChange* BaseSettingChange::MergeWith(
- BaseSettingChange* other) {
- CompositeSettingsChange* composite_change = new CompositeSettingsChange();
- CHECK(composite_change->Init(profile_));
- composite_change->MergeWith(this);
- composite_change->MergeWith(other);
- return composite_change;
-}
-
-bool BaseSettingChange::Contains(const BaseSettingChange* other) const {
- // BaseSettingChange can only contain itself.
- return this == other;
-}
-
-bool BaseSettingChange::Init(Profile* profile) {
- DCHECK(profile && !profile_);
- profile_ = profile;
- return true;
-}
-
-void BaseSettingChange::InitWhenDisabled(Profile* profile) {
- DCHECK(profile && !profile_);
-}
-
-void BaseSettingChange::Apply(Browser* browser) {
-}
-
-void BaseSettingChange::Discard(Browser* browser) {
-}
-
-void BaseSettingChange::Timeout() {
-}
-
-BaseSettingChange::DisplayName BaseSettingChange::GetApplyDisplayName() const {
- return DisplayName(kDefaultNamePriority, string16());
-}
-
-GURL BaseSettingChange::GetNewSettingURL() const {
- return GURL();
-}
-
-bool BaseSettingChange::CanBeMerged() const {
- // By default change can be collapsed if it has a non-empty keyword.
- return !GetNewSettingURL().is_empty();
-}
-
-bool BaseSettingChange::IsUserVisible() const {
- return true;
-}
-
-} // namespace protector
diff --git a/chrome/browser/protector/base_setting_change.h b/chrome/browser/protector/base_setting_change.h
deleted file mode 100644
index 95daa76..0000000
--- a/chrome/browser/protector/base_setting_change.h
+++ /dev/null
@@ -1,164 +0,0 @@
-// Copyright (c) 2012 The Chromium Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-#ifndef CHROME_BROWSER_PROTECTOR_BASE_SETTING_CHANGE_H_
-#define CHROME_BROWSER_PROTECTOR_BASE_SETTING_CHANGE_H_
-
-#include <utility>
-
-#include "base/basictypes.h"
-#include "base/string16.h"
-#include "chrome/browser/ui/startup/startup_tab.h"
-#include "googleurl/src/gurl.h"
-
-class Browser;
-class Profile;
-class TemplateURL;
-struct SessionStartupPref;
-
-namespace protector {
-
-class CompositeSettingsChange;
-
-// Base class for setting change tracked by Protector.
-class BaseSettingChange {
- public:
- // Pair consisting of a display name representing either new or backup setting
- // and priority for it. Priority is used for composite changes, consisting
- // of multiple BaseSettingChange instances - the display name with the highest
- // priority is used.
- typedef std::pair<size_t, string16> DisplayName;
-
- // Default priority value.
- static const size_t kDefaultNamePriority;
-
- BaseSettingChange();
- virtual ~BaseSettingChange();
-
- // Merges |this| with |other| and returns a CompositeSettingsChange instance.
- // Returned instance takes ownership of |other|.
- // Init should not be called for the returned instance.
- // |this| may be another CompositeSettingsChange, in which case |other| is
- // simply added to it and |this| is returned. |other| cannot be
- // CompositeSettingsChange.
- virtual CompositeSettingsChange* MergeWith(BaseSettingChange* other);
-
- // Returns true if |this| is a result of merging some changes with |other|.
- virtual bool Contains(const BaseSettingChange* other) const;
-
- // Applies initial actions to the setting if needed. Must be called before
- // any other calls are made, including text getters.
- // Returns true if initialization was successful.
- // Associates this change with |profile| instance so overrides must call the
- // base method.
- virtual bool Init(Profile* profile);
-
- // Called instead of Init when ProtectorService is disabled. No other members
- // are called in that case.
- virtual void InitWhenDisabled(Profile* profile);
-
- // Persists new setting if needed. |browser| is the Browser instance from
- // which the user action originates.
- virtual void Apply(Browser* browser);
-
- // Restores old setting if needed. |browser| is the Browser instance from
- // which the user action originates.
- virtual void Discard(Browser* browser);
-
- // Indicates that user has ignored this change and timeout has passed.
- virtual void Timeout();
-
- // Returns the resource ID of the badge icon.
- virtual int GetBadgeIconID() const = 0;
-
- // Returns the resource ID for the menu item icon.
- virtual int GetMenuItemIconID() const = 0;
-
- // Returns the resource ID for bubble view icon.
- virtual int GetBubbleIconID() const = 0;
-
- // Returns the wrench menu item and bubble title.
- virtual string16 GetBubbleTitle() const = 0;
-
- // Returns the bubble message text.
- virtual string16 GetBubbleMessage() const = 0;
-
- // Returns text for the button to apply the change with |Apply|.
- // Returns empty string if no apply button should be shown.
- virtual string16 GetApplyButtonText() const = 0;
-
- // Returns text for the button to discard the change with |Discard|.
- virtual string16 GetDiscardButtonText() const = 0;
-
- // Returns the display name and priority for the new setting. If multiple
- // BaseSettingChange instances are merged into CompositeSettingsChange
- // instance, the display name with the highest priority will be used for the
- // Apply button (Discard button will have a generic caption in that case).
- // Returns an empty string in |second| if there is no specific representation
- // for new setting value and a generic string should be used.
- virtual DisplayName GetApplyDisplayName() const;
-
- // Returns a URL uniquely identifying new (to be applied) settings.
- // ProtectorService uses this URLs to decide whether to merge a change
- // with already existing active changes. The URL may be empty.
- virtual GURL GetNewSettingURL() const;
-
- // Returns true if this change can be merged with other changes.
- virtual bool CanBeMerged() const;
-
- // Returns |false| if this change is not user-visible. It won't be presented
- // to user on it's own then, but may be merged with other changes and applied
- // or discarded.
- virtual bool IsUserVisible() const;
-
- protected:
- // Profile instance we've been associated with by an |Init| call.
- Profile* profile() { return profile_; }
-
- private:
- Profile* profile_;
-
- DISALLOW_COPY_AND_ASSIGN(BaseSettingChange);
-};
-
-// Display name priorities of various change types:
-extern const size_t kDefaultSearchProviderChangeNamePriority;
-extern const size_t kSessionStartupChangeNamePriority;
-extern const size_t kHomepageChangeNamePriority;
-
-// TODO(ivankr): CompositeSettingChange that incapsulates multiple
-// BaseSettingChange instances.
-
-// Allocates and initializes BaseSettingChange implementation for default search
-// provider setting. Reports corresponding histograms. Both |actual| and
-// |backup| may be NULL if corresponding values are unknown or invalid.
-// |backup| will be owned by the returned |BaseSettingChange| instance. |actual|
-// is not owned and is safe to destroy after Protector::ShowChange has been
-// called for the returned instance.
-BaseSettingChange* CreateDefaultSearchProviderChange(TemplateURL* actual,
- TemplateURL* backup);
-
-// Allocates and initializes BaseSettingChange implementation for session
-// startup setting, including the pinned tabs. Reports corresponding histograms.
-BaseSettingChange* CreateSessionStartupChange(
- const SessionStartupPref& actual_startup_pref,
- const StartupTabs& actual_pinned_tabs,
- const SessionStartupPref& backup_startup_pref,
- const StartupTabs& backup_pinned_tabs);
-
-BaseSettingChange* CreateHomepageChange(
- const std::string& actual_homepage,
- bool actual_homepage_is_ntp,
- bool actual_show_homepage,
- const std::string& backup_homepage,
- bool backup_homepage_is_ntp,
- bool backup_show_homepage);
-
-// Allocates and initializes BaseSettingChange implementation for an unknown
-// preferences change with invalid backup.
-BaseSettingChange* CreatePrefsBackupInvalidChange();
-
-} // namespace protector
-
-#endif // CHROME_BROWSER_PROTECTOR_BASE_SETTING_CHANGE_H_
diff --git a/chrome/browser/protector/composite_settings_change.cc b/chrome/browser/protector/composite_settings_change.cc
deleted file mode 100644
index a907047..0000000
--- a/chrome/browser/protector/composite_settings_change.cc
+++ /dev/null
@@ -1,111 +0,0 @@
-// Copyright (c) 2012 The Chromium Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-#include "chrome/browser/protector/composite_settings_change.h"
-
-#include "grit/generated_resources.h"
-#include "ui/base/l10n/l10n_util.h"
-
-namespace protector {
-
-
-CompositeSettingsChange::CompositeSettingsChange() {
-}
-
-CompositeSettingsChange::~CompositeSettingsChange() {
-}
-
-CompositeSettingsChange* CompositeSettingsChange::MergeWith(
- BaseSettingChange* other) {
- DCHECK(profile());
- DCHECK(other);
- changes_.push_back(other);
- apply_names_.push(other->GetApplyDisplayName());
- return this;
-}
-
-bool CompositeSettingsChange::Contains(const BaseSettingChange* other) const {
- return this == other ||
- std::find(changes_.begin(), changes_.end(), other) != changes_.end();
-}
-
-// Apart from PrefsBackupInvalidChange, which should never appear with other
-// Preferences-related changes together, the Apply/Discard logic of change
-// classes does not overlap, so it's safe to call them in any order.
-
-void CompositeSettingsChange::Apply(Browser* browser) {
- DVLOG(1) << "Apply all changes";
- for (size_t i = 0; i < changes_.size(); ++i)
- changes_[i]->Apply(browser);
-}
-
-void CompositeSettingsChange::Discard(Browser* browser) {
- DVLOG(1) << "Discard all changes";
- for (size_t i = 0; i < changes_.size(); ++i)
- changes_[i]->Discard(browser);
-}
-
-void CompositeSettingsChange::Timeout() {
- DVLOG(1) << "Timeout all changes";
- for (size_t i = 0; i < changes_.size(); ++i)
- changes_[i]->Timeout();
-}
-
-int CompositeSettingsChange::GetBadgeIconID() const {
- DCHECK(changes_.size());
- // Use icons from the first change.
- // TODO(ivankr): need something better, maybe a special icon.
- return changes_[0]->GetBadgeIconID();
-}
-
-int CompositeSettingsChange::GetMenuItemIconID() const {
- DCHECK(changes_.size());
- return changes_[0]->GetMenuItemIconID();
-}
-
-int CompositeSettingsChange::GetBubbleIconID() const {
- DCHECK(changes_.size());
- return changes_[0]->GetBubbleIconID();
-}
-
-string16 CompositeSettingsChange::GetBubbleTitle() const {
- return l10n_util::GetStringUTF16(IDS_SETTING_CHANGE_TITLE);
-}
-
-string16 CompositeSettingsChange::GetBubbleMessage() const {
- // TODO(ivankr): indicate what kind of changes happened (i.e., "something
- // tried to change your search engine, startup pages, etc.").
- return l10n_util::GetStringUTF16(IDS_SETTING_CHANGE_BUBBLE_MESSAGE);
-}
-
-string16 CompositeSettingsChange::GetApplyButtonText() const {
- DCHECK(apply_names_.size());
- string16 apply_text = apply_names_.top().second;
- return apply_text.empty() ?
- l10n_util::GetStringUTF16(IDS_CHANGE_SETTING_NO_NAME) :
- l10n_util::GetStringFUTF16(IDS_CHANGE_SETTING, apply_text);
-}
-
-string16 CompositeSettingsChange::GetDiscardButtonText() const {
- return l10n_util::GetStringUTF16(IDS_KEEP_SETTING);
-}
-
-BaseSettingChange::DisplayName
-CompositeSettingsChange::GetApplyDisplayName() const {
- // CompositeSettingsChange should never be put inside another one.
- NOTREACHED();
- return BaseSettingChange::GetApplyDisplayName();
-}
-
-GURL CompositeSettingsChange::GetNewSettingURL() const {
- DCHECK(changes_.size());
- return changes_[0]->GetNewSettingURL();
-}
-
-bool CompositeSettingsChange::CanBeMerged() const {
- // We did that already, why not do it again.
- return true;
-}
-
-} // namespace protector
diff --git a/chrome/browser/protector/composite_settings_change.h b/chrome/browser/protector/composite_settings_change.h
deleted file mode 100644
index 86683d2..0000000
--- a/chrome/browser/protector/composite_settings_change.h
+++ /dev/null
@@ -1,52 +0,0 @@
-// Copyright (c) 2012 The Chromium Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-#ifndef CHROME_BROWSER_PROTECTOR_COMPOSITE_SETTINGS_CHANGE_H_
-#define CHROME_BROWSER_PROTECTOR_COMPOSITE_SETTINGS_CHANGE_H_
-
-#include <queue>
-
-#include "base/compiler_specific.h"
-#include "base/memory/scoped_vector.h"
-#include "chrome/browser/protector/base_setting_change.h"
-
-namespace protector {
-
-// Class for tracking multiple settings changes as a single change.
-class CompositeSettingsChange : public BaseSettingChange {
- public:
- CompositeSettingsChange();
- virtual ~CompositeSettingsChange();
-
- // BaseSettingChange overrides:
- virtual CompositeSettingsChange* MergeWith(BaseSettingChange* other) OVERRIDE;
- virtual bool Contains(const BaseSettingChange* other) const OVERRIDE;
- virtual void Apply(Browser* browser) OVERRIDE;
- virtual void Discard(Browser* browser) OVERRIDE;
- virtual void Timeout() OVERRIDE;
- virtual int GetBadgeIconID() const OVERRIDE;
- virtual int GetMenuItemIconID() const OVERRIDE;
- virtual int GetBubbleIconID() const OVERRIDE;
- virtual string16 GetBubbleTitle() const OVERRIDE;
- virtual string16 GetBubbleMessage() const OVERRIDE;
- virtual string16 GetApplyButtonText() const OVERRIDE;
- virtual string16 GetDiscardButtonText() const OVERRIDE;
- virtual DisplayName GetApplyDisplayName() const OVERRIDE;
- virtual GURL GetNewSettingURL() const OVERRIDE;
- virtual bool CanBeMerged() const OVERRIDE;
-
- private:
- // Vector with all merged changes.
- ScopedVector<BaseSettingChange> changes_;
-
- // Display names of merged changes, sorted by their priority. The name with
- // the highest priority is picked.
- std::priority_queue<DisplayName> apply_names_;
-
- DISALLOW_COPY_AND_ASSIGN(CompositeSettingsChange);
-};
-
-} // namespace protector
-
-#endif // CHROME_BROWSER_PROTECTOR_COMPOSITE_SETTINGS_CHANGE_H_
diff --git a/chrome/browser/protector/composite_settings_change_unittest.cc b/chrome/browser/protector/composite_settings_change_unittest.cc
deleted file mode 100644
index 56ac4f7..0000000
--- a/chrome/browser/protector/composite_settings_change_unittest.cc
+++ /dev/null
@@ -1,122 +0,0 @@
-// Copyright (c) 2012 The Chromium Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-#include "base/utf_string_conversions.h"
-#include "chrome/browser/protector/composite_settings_change.h"
-#include "chrome/browser/protector/mock_setting_change.h"
-#include "chrome/test/base/testing_profile.h"
-#include "testing/gtest/include/gtest/gtest.h"
-#include "grit/generated_resources.h"
-#include "ui/base/l10n/l10n_util.h"
-
-using ::testing::NiceMock;
-using ::testing::Return;
-
-namespace protector {
-
-namespace {
-
-string16 kTitle1 = ASCIIToUTF16("A");
-string16 kTitle2 = ASCIIToUTF16("B");
-string16 kTitle3 = ASCIIToUTF16("C");
-
-};
-
-class CompositeSettingsChangeTest : public testing::Test {
- protected:
- string16 GetApplyButtonText(const string16& apply_text) {
- return l10n_util::GetStringFUTF16(IDS_CHANGE_SETTING, apply_text);
- }
-
- TestingProfile profile_;
-};
-
-// Verify that MergeWith works and Apply/Discard/Timeout call same functions
-// of all merged changes.
-TEST_F(CompositeSettingsChangeTest, MergeWith) {
- // These instances will be owned by CompositeSettingsChange.
- MockSettingChange* change1 = new NiceMock<MockSettingChange>;
- MockSettingChange* change2 = new NiceMock<MockSettingChange>;
- MockSettingChange* change3 = new NiceMock<MockSettingChange>;
-
- EXPECT_CALL(*change1, MockInit(&profile_)).WillOnce(Return(true));
- ASSERT_TRUE(change1->Init(&profile_));
- EXPECT_CALL(*change2, MockInit(&profile_)).WillOnce(Return(true));
- ASSERT_TRUE(change2->Init(&profile_));
- EXPECT_CALL(*change3, MockInit(&profile_)).WillOnce(Return(true));
- ASSERT_TRUE(change3->Init(&profile_));
-
- // Compose 1st and 2nd changes together.
- scoped_ptr<CompositeSettingsChange> composite_change(
- change1->MergeWith(change2));
-
- EXPECT_TRUE(composite_change->Contains(change1));
- EXPECT_TRUE(composite_change->Contains(change2));
- EXPECT_FALSE(composite_change->Contains(change3));
- EXPECT_TRUE(composite_change->Contains(composite_change.get()));
-
- // Add third change.
- EXPECT_EQ(composite_change.get(), composite_change->MergeWith(change3));
-
- EXPECT_TRUE(composite_change->Contains(change1));
- EXPECT_TRUE(composite_change->Contains(change2));
- EXPECT_TRUE(composite_change->Contains(change3));
- EXPECT_TRUE(composite_change->Contains(composite_change.get()));
-
- // Apply/Discard/Timeout calls should be proxied to inner change instances:
- EXPECT_CALL(*change1, Apply(NULL));
- EXPECT_CALL(*change2, Apply(NULL));
- EXPECT_CALL(*change3, Apply(NULL));
- composite_change->Apply(NULL);
-
- EXPECT_CALL(*change1, Discard(NULL));
- EXPECT_CALL(*change2, Discard(NULL));
- EXPECT_CALL(*change3, Discard(NULL));
- composite_change->Discard(NULL);
-
- EXPECT_CALL(*change1, Timeout());
- EXPECT_CALL(*change2, Timeout());
- EXPECT_CALL(*change3, Timeout());
- composite_change->Timeout();
-}
-
-TEST_F(CompositeSettingsChangeTest, ApplyButtonText) {
- // These instances will be owned by CompositeSettingsChange.
- MockSettingChange* change1 = new NiceMock<MockSettingChange>;
- MockSettingChange* change2 = new NiceMock<MockSettingChange>;
- MockSettingChange* change3 = new NiceMock<MockSettingChange>;
-
- EXPECT_CALL(*change1, MockInit(&profile_)).WillOnce(Return(true));
- ASSERT_TRUE(change1->Init(&profile_));
- EXPECT_CALL(*change2, MockInit(&profile_)).WillOnce(Return(true));
- ASSERT_TRUE(change2->Init(&profile_));
- EXPECT_CALL(*change3, MockInit(&profile_)).WillOnce(Return(true));
- ASSERT_TRUE(change3->Init(&profile_));
-
- // |change1| has higher priority.
- EXPECT_CALL(*change1, GetApplyDisplayName()).WillOnce(
- Return(BaseSettingChange::DisplayName(10, kTitle1)));
- EXPECT_CALL(*change2, GetApplyDisplayName()).WillOnce(
- Return(BaseSettingChange::DisplayName(5, kTitle2)));
-
- scoped_ptr<CompositeSettingsChange> composite_change(
- change1->MergeWith(change2));
-
- EXPECT_EQ(GetApplyButtonText(kTitle1),
- composite_change->GetApplyButtonText());
-
- // |change3| has the highest priority now.
- EXPECT_CALL(*change3, GetApplyDisplayName()).WillOnce(
- Return(BaseSettingChange::DisplayName(15, kTitle3)));
- EXPECT_EQ(composite_change.get(), composite_change->MergeWith(change3));
-
- EXPECT_EQ(GetApplyButtonText(kTitle3),
- composite_change->GetApplyButtonText());
-
- GURL url1("example.com");
- EXPECT_CALL(*change1, GetNewSettingURL()).WillOnce(Return(url1));
- EXPECT_EQ(url1, composite_change->GetNewSettingURL());
-}
-
-} // namespace protector
diff --git a/chrome/browser/protector/default_search_provider_change.cc b/chrome/browser/protector/default_search_provider_change.cc
deleted file mode 100644
index d27e666..0000000
--- a/chrome/browser/protector/default_search_provider_change.cc
+++ /dev/null
@@ -1,433 +0,0 @@
-// Copyright (c) 2012 The Chromium Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-#include <algorithm>
-
-#include "base/basictypes.h"
-#include "base/compiler_specific.h"
-#include "base/logging.h"
-#include "base/memory/scoped_ptr.h"
-#include "base/metrics/histogram.h"
-#include "chrome/browser/profiles/profile.h"
-#include "chrome/browser/protector/base_setting_change.h"
-#include "chrome/browser/protector/histograms.h"
-#include "chrome/browser/protector/protector_service.h"
-#include "chrome/browser/protector/protector_service_factory.h"
-#include "chrome/browser/search_engines/template_url.h"
-#include "chrome/browser/search_engines/template_url_prepopulate_data.h"
-#include "chrome/browser/search_engines/template_url_service.h"
-#include "chrome/browser/search_engines/template_url_service_factory.h"
-#include "chrome/browser/search_engines/template_url_service_observer.h"
-#include "chrome/browser/webdata/keyword_table.h"
-#include "chrome/common/chrome_notification_types.h"
-#include "chrome/common/url_constants.h"
-#include "content/public/browser/notification_observer.h"
-#include "content/public/browser/notification_registrar.h"
-#include "content/public/browser/notification_service.h"
-#include "googleurl/src/gurl.h"
-#include "grit/chromium_strings.h"
-#include "grit/generated_resources.h"
-#include "grit/theme_resources.h"
-#include "ui/base/l10n/l10n_util.h"
-
-namespace protector {
-
-namespace {
-
-// Maximum length of the search engine name to be displayed.
-const size_t kMaxDisplayedNameLength = 16;
-
-// Matches TemplateURL with all fields set from the prepopulated data equal
-// to fields in another TemplateURL.
-class TemplateURLIsSame {
- public:
- // Creates a matcher based on |other|.
- explicit TemplateURLIsSame(const TemplateURL* other) : other_(other) {
- }
-
- // Returns true if both |other| and |url| are NULL or have same field values.
- bool operator()(const TemplateURL* url) {
- if (url == other_ )
- return true;
- if (!url || !other_)
- return false;
- return url->short_name() == other_->short_name() &&
- url->HasSameKeywordAs(*other_) &&
- url->url() == other_->url() &&
- url->suggestions_url() == other_->suggestions_url() &&
- url->instant_url() == other_->instant_url() &&
- url->safe_for_autoreplace() == other_->safe_for_autoreplace() &&
- url->favicon_url() == other_->favicon_url() &&
- url->show_in_default_list() == other_->show_in_default_list() &&
- url->input_encodings() == other_->input_encodings() &&
- url->prepopulate_id() == other_->prepopulate_id();
- }
-
- private:
- const TemplateURL* other_;
-};
-
-} // namespace
-
-// Default search engine change tracked by Protector.
-class DefaultSearchProviderChange : public BaseSettingChange,
- public TemplateURLServiceObserver,
- public content::NotificationObserver {
- public:
- DefaultSearchProviderChange(TemplateURL* new_search_provider,
- TemplateURL* backup_search_provider);
-
- // BaseSettingChange overrides:
- virtual bool Init(Profile* profile) OVERRIDE;
- virtual void InitWhenDisabled(Profile* profile) OVERRIDE;
- virtual void Apply(Browser* browser) OVERRIDE;
- virtual void Discard(Browser* browser) OVERRIDE;
- virtual void Timeout() OVERRIDE;
- virtual int GetBadgeIconID() const OVERRIDE;
- virtual int GetMenuItemIconID() const OVERRIDE;
- virtual int GetBubbleIconID() const OVERRIDE;
- virtual string16 GetBubbleTitle() const OVERRIDE;
- virtual string16 GetBubbleMessage() const OVERRIDE;
- virtual string16 GetApplyButtonText() const OVERRIDE;
- virtual string16 GetDiscardButtonText() const OVERRIDE;
- virtual DisplayName GetApplyDisplayName() const OVERRIDE;
- virtual GURL GetNewSettingURL() const OVERRIDE;
-
- private:
- virtual ~DefaultSearchProviderChange();
-
- // TemplateURLServiceObserver overrides:
- virtual void OnTemplateURLServiceChanged() OVERRIDE;
-
- // content::NotificationObserver overrides:
- virtual void Observe(int type,
- const content::NotificationSource& source,
- const content::NotificationDetails& details) OVERRIDE;
-
- // Sets the default search provider to |*search_provider|. If a matching
- // TemplateURL already exists, it is reused and |*search_provider| is reset.
- // Otherwise, adds |*search_provider| to keywords and releases it.
- // In both cases, |*search_provider| is NULL after this call.
- // Returns the new default search provider (either |*search_provider| or the
- // reused TemplateURL).
- const TemplateURL* SetDefaultSearchProvider(
- scoped_ptr<TemplateURL>* search_provider);
-
- // Returns true if |new_search_provider_| can be used as the default search
- // provider.
- bool NewSearchProviderValid() const;
-
- // Opens the Search engine settings page in a new tab.
- void OpenSearchEngineSettings(Browser* browser);
-
- // Returns the TemplateURLService instance for the Profile this change is
- // related to.
- TemplateURLService* GetTemplateURLService();
-
- // Histogram ID of the new search provider.
- int new_histogram_id_;
- // Indicates that the default search was restored to the prepopulated default
- // search engines.
- bool is_fallback_;
- // Indicates that the the prepopulated default search is the same as
- // |new_search_provider_|.
- bool fallback_is_new_;
- // ID of |new_search_provider_|.
- TemplateURLID new_id_;
- // The default search at the moment the change was detected. Will be used to
- // restore the new default search back if Apply is called. Will be set to
- // |NULL| if removed from the TemplateURLService.
- TemplateURL* new_search_provider_;
- // Default search provider set by Init for the period until user makes a
- // choice and either Apply or Discard is performed. Never is |NULL| during
- // that period since the change will dismiss itself if this provider gets
- // deleted or stops being the default.
- const TemplateURL* default_search_provider_;
- // Stores backup of the default search until it becomes owned by the
- // TemplateURLService or deleted.
- scoped_ptr<TemplateURL> backup_search_provider_;
- content::NotificationRegistrar registrar_;
-
- DISALLOW_COPY_AND_ASSIGN(DefaultSearchProviderChange);
-};
-
-DefaultSearchProviderChange::DefaultSearchProviderChange(
- TemplateURL* new_search_provider,
- TemplateURL* backup_search_provider)
- : new_histogram_id_(GetSearchProviderHistogramID(new_search_provider)),
- is_fallback_(false),
- fallback_is_new_(false),
- new_search_provider_(new_search_provider),
- default_search_provider_(NULL),
- backup_search_provider_(backup_search_provider) {
- if (backup_search_provider) {
- UMA_HISTOGRAM_ENUMERATION(
- kProtectorHistogramSearchProviderHijacked,
- new_histogram_id_,
- kProtectorMaxSearchProviderID);
- } else {
- UMA_HISTOGRAM_ENUMERATION(
- kProtectorHistogramSearchProviderCorrupt,
- new_histogram_id_,
- kProtectorMaxSearchProviderID);
- }
-}
-
-DefaultSearchProviderChange::~DefaultSearchProviderChange() {
- if (profile())
- GetTemplateURLService()->RemoveObserver(this);
-}
-
-bool DefaultSearchProviderChange::Init(Profile* profile) {
- if (!BaseSettingChange::Init(profile))
- return false;
-
- if (!backup_search_provider_.get() ||
- !backup_search_provider_->SupportsReplacement()) {
- // Fallback to a prepopulated default search provider, ignoring any
- // overrides in Prefs.
- backup_search_provider_.reset(
- TemplateURLPrepopulateData::GetPrepopulatedDefaultSearch(NULL));
- is_fallback_ = true;
- VLOG(1) << "Fallback search provider: "
- << backup_search_provider_->short_name();
- }
-
- default_search_provider_ = SetDefaultSearchProvider(&backup_search_provider_);
- DCHECK(default_search_provider_);
- // |backup_search_provider_| should be |NULL| since now.
- DCHECK(!backup_search_provider_.get());
- if (is_fallback_ && default_search_provider_ == new_search_provider_)
- fallback_is_new_ = true;
-
- int restored_histogram_id =
- GetSearchProviderHistogramID(default_search_provider_);
- UMA_HISTOGRAM_ENUMERATION(
- kProtectorHistogramSearchProviderRestored,
- restored_histogram_id,
- kProtectorMaxSearchProviderID);
-
- if (is_fallback_) {
- VLOG(1) << "Fallback to search provider: "
- << default_search_provider_->short_name();
- UMA_HISTOGRAM_ENUMERATION(
- kProtectorHistogramSearchProviderFallback,
- restored_histogram_id,
- kProtectorMaxSearchProviderID);
- }
-
- // Listen for the default search provider changes.
- GetTemplateURLService()->AddObserver(this);
-
- if (new_search_provider_) {
- // Listen for removal of |new_search_provider_|.
- new_id_ = new_search_provider_->id();
- registrar_.Add(
- this, chrome::NOTIFICATION_TEMPLATE_URL_REMOVED,
- content::Source<Profile>(profile->GetOriginalProfile()));
- }
-
- return true;
-}
-
-void DefaultSearchProviderChange::InitWhenDisabled(Profile* profile) {
- // The --no-protector case is handled in TemplateURLService internals.
- // TODO(ivankr): move it here.
- NOTREACHED();
-}
-
-void DefaultSearchProviderChange::Apply(Browser* browser) {
- UMA_HISTOGRAM_ENUMERATION(
- kProtectorHistogramSearchProviderApplied,
- new_histogram_id_,
- kProtectorMaxSearchProviderID);
-
- GetTemplateURLService()->RemoveObserver(this);
- if (NewSearchProviderValid()) {
- GetTemplateURLService()->SetDefaultSearchProvider(new_search_provider_);
- } else {
- // Open settings page in case the new setting is invalid.
- OpenSearchEngineSettings(browser);
- }
-}
-
-void DefaultSearchProviderChange::Discard(Browser* browser) {
- UMA_HISTOGRAM_ENUMERATION(
- kProtectorHistogramSearchProviderDiscarded,
- new_histogram_id_,
- kProtectorMaxSearchProviderID);
-
- GetTemplateURLService()->RemoveObserver(this);
- if (is_fallback_) {
- // Open settings page in case the old setting is invalid.
- OpenSearchEngineSettings(browser);
- }
- // Nothing to do otherwise since we have already set the search engine
- // to |old_id_| in |Init|.
-}
-
-void DefaultSearchProviderChange::Timeout() {
- UMA_HISTOGRAM_ENUMERATION(
- kProtectorHistogramSearchProviderTimeout,
- new_histogram_id_,
- kProtectorMaxSearchProviderID);
-}
-
-int DefaultSearchProviderChange::GetBadgeIconID() const {
- return IDR_SEARCH_ENGINE_CHANGE_BADGE;
-}
-
-int DefaultSearchProviderChange::GetMenuItemIconID() const {
- return IDR_SEARCH_ENGINE_CHANGE_MENU;
-}
-
-int DefaultSearchProviderChange::GetBubbleIconID() const {
- return IDR_SEARCH_ENGINE_CHANGE_ALERT;
-}
-
-string16 DefaultSearchProviderChange::GetBubbleTitle() const {
- return l10n_util::GetStringUTF16(IDS_SEARCH_ENGINE_CHANGE_TITLE);
-}
-
-string16 DefaultSearchProviderChange::GetBubbleMessage() const {
- if (is_fallback_) {
- return l10n_util::GetStringFUTF16(
- IDS_SEARCH_ENGINE_CHANGE_NO_BACKUP_MESSAGE,
- default_search_provider_->short_name());
- }
- return l10n_util::GetStringUTF16(IDS_SEARCH_ENGINE_CHANGE_MESSAGE);
-}
-
-string16 DefaultSearchProviderChange::GetApplyButtonText() const {
- if (NewSearchProviderValid()) {
- // If backup search engine is lost and fallback was made to the current
- // search provider then there is no need to show this button.
- if (fallback_is_new_)
- return string16();
- string16 name = new_search_provider_->short_name();
- return (name.length() > kMaxDisplayedNameLength) ?
- l10n_util::GetStringUTF16(IDS_CHANGE_SEARCH_ENGINE_NO_NAME) :
- l10n_util::GetStringFUTF16(IDS_CHANGE_SEARCH_ENGINE, name);
- }
- if (is_fallback_) {
- // Both settings are lost: don't show this button.
- return string16();
- }
- // New setting is lost, offer to go to settings.
- return l10n_util::GetStringUTF16(IDS_SELECT_SEARCH_ENGINE);
-}
-
-string16 DefaultSearchProviderChange::GetDiscardButtonText() const {
- if (!is_fallback_) {
- string16 name = default_search_provider_->short_name();
- return (name.length() > kMaxDisplayedNameLength) ?
- l10n_util::GetStringUTF16(IDS_KEEP_SETTING) :
- l10n_util::GetStringFUTF16(IDS_KEEP_SEARCH_ENGINE, name);
- }
- // Old setting is lost, offer to go to settings.
- return l10n_util::GetStringUTF16(IDS_SELECT_SEARCH_ENGINE);
-}
-
-BaseSettingChange::DisplayName
-DefaultSearchProviderChange::GetApplyDisplayName() const {
- if (NewSearchProviderValid() &&
- new_search_provider_->short_name().length() <= kMaxDisplayedNameLength) {
- return DisplayName(kDefaultSearchProviderChangeNamePriority,
- new_search_provider_->short_name());
- }
- // Return the default empty name.
- return BaseSettingChange::GetApplyDisplayName();
-}
-
-GURL DefaultSearchProviderChange::GetNewSettingURL() const {
- if (is_fallback_) {
- // Do not collide this change when fallback was made, since the message
- // and Discard behaviour is pretty different.
- return GURL();
- }
- if (!NewSearchProviderValid())
- return GURL();
- return TemplateURLService::GenerateSearchURL(new_search_provider_);
-}
-
-void DefaultSearchProviderChange::OnTemplateURLServiceChanged() {
- TemplateURLService* url_service = GetTemplateURLService();
- if (url_service->GetDefaultSearchProvider() != default_search_provider_) {
- VLOG(1) << "Default search provider has been changed by user";
- default_search_provider_ = NULL;
- url_service->RemoveObserver(this);
- // Will delete this DefaultSearchProviderChange instance.
- ProtectorServiceFactory::GetForProfile(profile())->DismissChange(this);
- }
-}
-
-void DefaultSearchProviderChange::Observe(
- int type,
- const content::NotificationSource& source,
- const content::NotificationDetails& details) {
- DCHECK(type == chrome::NOTIFICATION_TEMPLATE_URL_REMOVED);
- TemplateURLID id = *content::Details<TemplateURLID>(details).ptr();
- if (id == new_id_)
- new_search_provider_ = NULL;
- registrar_.Remove(this, type, source);
- // TODO(ivankr): should the change be dismissed as well? Probably not,
- // since this may happend due to Sync or whatever. In that case, if user
- // clicks on 'Change to...', the Search engine settings page will be opened.
-}
-
-const TemplateURL* DefaultSearchProviderChange::SetDefaultSearchProvider(
- scoped_ptr<TemplateURL>* search_provider) {
- TemplateURLService* url_service = GetTemplateURLService();
- TemplateURLService::TemplateURLVector urls = url_service->GetTemplateURLs();
- TemplateURL* new_default_provider = NULL;
-
- // Check if this provider already exists and add it otherwise.
- TemplateURLService::TemplateURLVector::const_iterator i =
- std::find_if(urls.begin(), urls.end(),
- TemplateURLIsSame(search_provider->get()));
- if (i != urls.end()) {
- VLOG(1) << "Provider already exists";
- new_default_provider = *i;
- search_provider->reset();
- } else {
- VLOG(1) << "No match, adding new provider";
- new_default_provider = search_provider->get();
- url_service->Add(search_provider->release());
- UMA_HISTOGRAM_ENUMERATION(
- kProtectorHistogramSearchProviderMissing,
- GetSearchProviderHistogramID(new_default_provider),
- kProtectorMaxSearchProviderID);
- }
-
- // TODO(ivankr): handle keyword conflicts with existing providers.
- DCHECK(new_default_provider);
- VLOG(1) << "Default search provider set to: "
- << new_default_provider->short_name();
- url_service->SetDefaultSearchProvider(new_default_provider);
- return new_default_provider;
-}
-
-bool DefaultSearchProviderChange::NewSearchProviderValid() const {
- return new_search_provider_ && new_search_provider_->SupportsReplacement();
-}
-
-void DefaultSearchProviderChange::OpenSearchEngineSettings(Browser* browser) {
- ProtectorServiceFactory::GetForProfile(profile())->OpenTab(
- GURL(std::string(chrome::kChromeUISettingsURL) +
- chrome::kSearchEnginesSubPage), browser);
-}
-
-TemplateURLService* DefaultSearchProviderChange::GetTemplateURLService() {
- TemplateURLService* url_service =
- TemplateURLServiceFactory::GetForProfile(profile());
- DCHECK(url_service);
- return url_service;
-}
-
-BaseSettingChange* CreateDefaultSearchProviderChange(TemplateURL* actual,
- TemplateURL* backup) {
- return new DefaultSearchProviderChange(actual, backup);
-}
-
-} // namespace protector
diff --git a/chrome/browser/protector/default_search_provider_change_browsertest.cc b/chrome/browser/protector/default_search_provider_change_browsertest.cc
deleted file mode 100644
index df839d4..0000000
--- a/chrome/browser/protector/default_search_provider_change_browsertest.cc
+++ /dev/null
@@ -1,677 +0,0 @@
-// Copyright (c) 2012 The Chromium Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-#include "base/memory/scoped_ptr.h"
-#include "base/metrics/histogram.h"
-#include "base/metrics/histogram_samples.h"
-#include "base/metrics/statistics_recorder.h"
-#include "base/message_loop.h"
-#include "base/utf_string_conversions.h"
-#include "chrome/browser/protector/base_setting_change.h"
-#include "chrome/browser/protector/histograms.h"
-#include "chrome/browser/protector/mock_protector_service.h"
-#include "chrome/browser/protector/protector_service_factory.h"
-#include "chrome/browser/search_engines/template_url.h"
-#include "chrome/browser/search_engines/template_url_prepopulate_data.h"
-#include "chrome/browser/search_engines/template_url_service.h"
-#include "chrome/browser/search_engines/template_url_service_factory.h"
-#include "chrome/browser/ui/browser.h"
-#include "chrome/common/url_constants.h"
-#include "chrome/test/base/in_process_browser_test.h"
-#include "chrome/test/base/ui_test_utils.h"
-#include "googleurl/src/gurl.h"
-#include "grit/generated_resources.h"
-#include "ui/base/l10n/l10n_util.h"
-
-using ::testing::Invoke;
-using ::testing::NiceMock;
-using ::testing::Return;
-
-namespace protector {
-
-namespace {
-
-// Keyword names and URLs used for testing.
-const string16 example_info = ASCIIToUTF16("Example.info");
-const string16 example_info_long = ASCIIToUTF16("ExampleSearchEngine.info");
-const std::string http_example_info = "http://example.info/?q={searchTerms}";
-const std::string http_example_info_no_search_terms =
- "http://example.net/";
-const std::string example_info_domain = "example.info";
-const string16 example_com = ASCIIToUTF16("Example.com");
-const string16 example_com_long = ASCIIToUTF16("ExampleSearchEngine.com");
-const std::string http_example_com = "http://example.com/?q={searchTerms}";
-const std::string http_example_com_no_search_terms =
- "http://example.com/";
-const std::string example_com_domain = "example.com";
-const string16 example_net = ASCIIToUTF16("Example.net");
-const std::string http_example_net = "http://example.net/?q={searchTerms}";
-const std::string example_domain = "example.net";
-
-const BaseSettingChange::DisplayName kNoDisplayName(
- BaseSettingChange::kDefaultNamePriority, string16());
-
-} // namespace
-
-class DefaultSearchProviderChangeTest : public InProcessBrowserTest {
- public:
- virtual void SetUpOnMainThread() OVERRIDE {
- Profile* profile = browser()->profile();
- mock_protector_service_ = MockProtectorService::BuildForProfile(profile);
-
- // Ensure that TemplateURLService is loaded.
- turl_service_ = TemplateURLServiceFactory::GetForProfile(profile);
- ui_test_utils::WaitForTemplateURLServiceToLoad(turl_service_);
-
- prepopulated_url_.reset(
- TemplateURLPrepopulateData::GetPrepopulatedDefaultSearch(NULL));
- }
-
- virtual void CleanUpOnMainThread() OVERRIDE {
- EXPECT_CALL(*mock_protector_service_, Shutdown());
- }
-
- TemplateURL* MakeTemplateURL(const string16& short_name,
- const string16& keyword,
- const std::string& url) {
- TemplateURLData data;
- data.short_name = short_name;
- data.SetKeyword(keyword);
- data.SetURL(url);
- return new TemplateURL(browser()->profile(), data);
- }
-
- TemplateURL* FindTemplateURL(const std::string& search_url) {
- TemplateURLService::TemplateURLVector urls =
- turl_service_->GetTemplateURLs();
- for (TemplateURLService::TemplateURLVector::const_iterator
- it = urls.begin(); it != urls.end(); ++it) {
- if ((*it)->url() == search_url)
- return *it;
- }
- return NULL;
- }
-
- void AddAndSetDefault(TemplateURL* turl) {
- turl_service_->Add(turl);
- turl_service_->SetDefaultSearchProvider(turl);
- }
-
- string16 GetBubbleMessage(const string16& short_name = string16()) {
- return short_name.empty() ?
- l10n_util::GetStringUTF16(IDS_SEARCH_ENGINE_CHANGE_MESSAGE) :
- l10n_util::GetStringFUTF16(IDS_SEARCH_ENGINE_CHANGE_NO_BACKUP_MESSAGE,
- short_name);
- }
-
- string16 GetChangeSearchButtonText(const string16& short_name = string16()) {
- return short_name.empty() ?
- l10n_util::GetStringUTF16(IDS_CHANGE_SEARCH_ENGINE_NO_NAME) :
- l10n_util::GetStringFUTF16(IDS_CHANGE_SEARCH_ENGINE, short_name);
- }
-
- string16 GetKeepSearchButtonText(const string16& short_name = string16()) {
- return short_name.empty() ?
- l10n_util::GetStringUTF16(IDS_KEEP_SETTING) :
- l10n_util::GetStringFUTF16(IDS_KEEP_SEARCH_ENGINE, short_name);
- }
-
- string16 GetOpenSettingsButtonText() {
- return l10n_util::GetStringUTF16(IDS_SELECT_SEARCH_ENGINE);
- }
-
- void ExpectSettingsOpened(const std::string& subpage) {
- GURL settings_url(chrome::kChromeUISettingsURL + subpage);
- EXPECT_CALL(*mock_protector_service_, OpenTab(settings_url, browser()));
- }
-
- void ExpectHistogramCount(const std::string& name,
- base::HistogramBase::Sample sample,
- base::Histogram::Count expected_count) {
- base::Histogram* histogram = base::StatisticsRecorder::FindHistogram(name);
- EXPECT_TRUE(histogram != NULL);
- scoped_ptr<base::HistogramSamples> samples(histogram->SnapshotSamples());
- EXPECT_EQ(expected_count, samples->GetCount(sample))
- << "Invalid histogram " << name << " count for sample: " << sample;
- }
-
- protected:
- MockProtectorService* mock_protector_service_;
- TemplateURLService* turl_service_;
- scoped_ptr<TemplateURL> prepopulated_url_;
-};
-
-// Tests below call both Apply and Discard on a single change instance.
-// This is test-only and should not be happening in real code.
-
-// |backup_url| in further test cases is owned by DefaultSearchProviderChange
-// instance, while other TemplateURLs are owned by TemplateURLService.
-
-IN_PROC_BROWSER_TEST_F(DefaultSearchProviderChangeTest, BackupValid) {
- // Most common case: current default search provider exists, backup is valid,
- // they are different.
- TemplateURL* backup_url =
- MakeTemplateURL(example_info, ASCIIToUTF16("a"), http_example_info);
- int backup_histogram_id = protector::GetSearchProviderHistogramID(backup_url);
- TemplateURL* current_url =
- MakeTemplateURL(example_com, ASCIIToUTF16("b"), http_example_com);
- int current_histogram_id =
- protector::GetSearchProviderHistogramID(current_url);
-
- Profile* profile = browser()->profile();
- turl_service_->Add(new TemplateURL(profile, backup_url->data()));
- AddAndSetDefault(current_url);
-
- scoped_ptr<BaseSettingChange> change(
- CreateDefaultSearchProviderChange(current_url, backup_url));
- ASSERT_TRUE(change.get());
- ASSERT_TRUE(change->Init(profile));
-
- // Verify that backup is active.
- EXPECT_EQ(FindTemplateURL(http_example_info),
- turl_service_->GetDefaultSearchProvider());
-
- // Verify histograms.
- ExpectHistogramCount(kProtectorHistogramSearchProviderHijacked,
- current_histogram_id, 1);
- ExpectHistogramCount(kProtectorHistogramSearchProviderRestored,
- backup_histogram_id, 1);
-
- // Verify text messages.
- EXPECT_EQ(GetBubbleMessage(), change->GetBubbleMessage());
- EXPECT_EQ(GetChangeSearchButtonText(example_com),
- change->GetApplyButtonText());
- EXPECT_EQ(GetKeepSearchButtonText(example_info),
- change->GetDiscardButtonText());
- EXPECT_EQ(example_com_domain, change->GetNewSettingURL().host());
- EXPECT_EQ(example_com, change->GetApplyDisplayName().second);
-
- // Discard does nothing - backup was already active.
- change->Discard(browser());
- EXPECT_EQ(FindTemplateURL(http_example_info),
- turl_service_->GetDefaultSearchProvider());
- ExpectHistogramCount(kProtectorHistogramSearchProviderDiscarded,
- current_histogram_id, 1);
-
- // Verify that Apply switches back to |current_url|.
- change->Apply(browser());
- EXPECT_EQ(FindTemplateURL(http_example_com),
- turl_service_->GetDefaultSearchProvider());
- ExpectHistogramCount(kProtectorHistogramSearchProviderApplied,
- current_histogram_id, 1);
-}
-
-IN_PROC_BROWSER_TEST_F(DefaultSearchProviderChangeTest, BackupValidLongNames) {
- // Verify that search provider names that are too long are not displayed.
- TemplateURL* backup_url =
- MakeTemplateURL(example_info, ASCIIToUTF16("a"), http_example_info);
- TemplateURL* backup_url_long =
- MakeTemplateURL(example_info_long, ASCIIToUTF16("a"), http_example_info);
- TemplateURL* current_url =
- MakeTemplateURL(example_com, ASCIIToUTF16("b"), http_example_com);
- TemplateURL* current_url_long =
- MakeTemplateURL(example_com_long, ASCIIToUTF16("b"), http_example_com);
-
- Profile* profile = browser()->profile();
- {
- // Backup name too long.
- turl_service_->Add(new TemplateURL(profile, backup_url_long->data()));
- AddAndSetDefault(current_url);
-
- scoped_ptr<BaseSettingChange> change(
- CreateDefaultSearchProviderChange(current_url, backup_url_long));
- ASSERT_TRUE(change.get());
- ASSERT_TRUE(change->Init(profile));
-
- // Verify text messages.
- EXPECT_EQ(GetBubbleMessage(), change->GetBubbleMessage());
- EXPECT_EQ(GetChangeSearchButtonText(example_com),
- change->GetApplyButtonText());
- EXPECT_EQ(GetKeepSearchButtonText(), change->GetDiscardButtonText());
- EXPECT_EQ(example_com_domain, change->GetNewSettingURL().host());
- EXPECT_EQ(example_com, change->GetApplyDisplayName().second);
- }
-
- {
- // Current name too long.
- turl_service_->Add(new TemplateURL(profile, backup_url->data()));
- AddAndSetDefault(current_url_long);
-
- scoped_ptr<BaseSettingChange> change(
- CreateDefaultSearchProviderChange(current_url_long, backup_url));
- ASSERT_TRUE(change.get());
- ASSERT_TRUE(change->Init(profile));
-
- // Verify text messages.
- EXPECT_EQ(GetBubbleMessage(), change->GetBubbleMessage());
- EXPECT_EQ(GetChangeSearchButtonText(), change->GetApplyButtonText());
- EXPECT_EQ(GetKeepSearchButtonText(example_info),
- change->GetDiscardButtonText());
- EXPECT_EQ(example_com_domain, change->GetNewSettingURL().host());
- EXPECT_EQ(kNoDisplayName, change->GetApplyDisplayName());
- }
-}
-
-IN_PROC_BROWSER_TEST_F(DefaultSearchProviderChangeTest, BackupInvalid) {
- // Backup is invalid, current search provider exists, fallback to the
- // prepopulated default search, which exists among keywords.
- int prepopulated_histogram_id =
- protector::GetSearchProviderHistogramID(prepopulated_url_.get());
- TemplateURL* current_url =
- MakeTemplateURL(example_com, ASCIIToUTF16("b"), http_example_com);
- int current_histogram_id =
- protector::GetSearchProviderHistogramID(current_url);
-
- AddAndSetDefault(current_url);
-
- // Prepopulated default search must exist.
- ASSERT_TRUE(FindTemplateURL(prepopulated_url_->url()));
-
- scoped_ptr<BaseSettingChange> change(
- CreateDefaultSearchProviderChange(current_url, NULL));
- ASSERT_TRUE(change.get());
- ASSERT_TRUE(change->Init(browser()->profile()));
-
- // Verify that the prepopulated default search is active.
- EXPECT_EQ(FindTemplateURL(prepopulated_url_->url()),
- turl_service_->GetDefaultSearchProvider());
-
- // Verify histograms.
- ExpectHistogramCount(kProtectorHistogramSearchProviderCorrupt,
- current_histogram_id, 1);
- ExpectHistogramCount(kProtectorHistogramSearchProviderRestored,
- prepopulated_histogram_id, 1);
- ExpectHistogramCount(kProtectorHistogramSearchProviderFallback,
- prepopulated_histogram_id, 1);
-
- // Verify text messages.
- EXPECT_EQ(GetBubbleMessage(prepopulated_url_->short_name()),
- change->GetBubbleMessage());
- EXPECT_EQ(GetChangeSearchButtonText(example_com),
- change->GetApplyButtonText());
- EXPECT_EQ(GetOpenSettingsButtonText(), change->GetDiscardButtonText());
-
- // Verify that search engine settings are opened by Discard.
- ExpectSettingsOpened(chrome::kSearchEnginesSubPage);
- change->Discard(browser());
- EXPECT_EQ(FindTemplateURL(prepopulated_url_->url()),
- turl_service_->GetDefaultSearchProvider());
-
- // Verify that Apply switches back to |current_url|.
- change->Apply(browser());
- EXPECT_EQ(FindTemplateURL(http_example_com),
- turl_service_->GetDefaultSearchProvider());
-}
-
-
-IN_PROC_BROWSER_TEST_F(DefaultSearchProviderChangeTest,
- BackupValidCannotBeDefault) {
- // Backup is a valid keyword but cannot be the default search provider (has no
- // search terms), current search provider exists, fallback to the prepopulated
- // default search, which exists among keywords.
- TemplateURL* backup_url =
- MakeTemplateURL(example_info, ASCIIToUTF16("a"),
- http_example_info_no_search_terms);
- int prepopulated_histogram_id =
- protector::GetSearchProviderHistogramID(prepopulated_url_.get());
- TemplateURL* current_url =
- MakeTemplateURL(example_com, ASCIIToUTF16("b"), http_example_com);
- int current_histogram_id =
- protector::GetSearchProviderHistogramID(current_url);
-
- AddAndSetDefault(current_url);
-
- // Prepopulated default search must exist.
- ASSERT_TRUE(FindTemplateURL(prepopulated_url_->url()));
-
- scoped_ptr<BaseSettingChange> change(
- CreateDefaultSearchProviderChange(current_url, backup_url));
- ASSERT_TRUE(change.get());
- ASSERT_TRUE(change->Init(browser()->profile()));
-
- // Verify that the prepopulated default search is active.
- EXPECT_EQ(FindTemplateURL(prepopulated_url_->url()),
- turl_service_->GetDefaultSearchProvider());
-
- // Verify histograms.
- ExpectHistogramCount(kProtectorHistogramSearchProviderHijacked,
- current_histogram_id, 1);
- ExpectHistogramCount(kProtectorHistogramSearchProviderRestored,
- prepopulated_histogram_id, 1);
- ExpectHistogramCount(kProtectorHistogramSearchProviderFallback,
- prepopulated_histogram_id, 1);
-
- // Verify text messages.
- EXPECT_EQ(GetBubbleMessage(prepopulated_url_->short_name()),
- change->GetBubbleMessage());
- EXPECT_EQ(GetChangeSearchButtonText(example_com),
- change->GetApplyButtonText());
- EXPECT_EQ(GetOpenSettingsButtonText(), change->GetDiscardButtonText());
-
- // Verify that search engine settings are opened by Discard.
- ExpectSettingsOpened(chrome::kSearchEnginesSubPage);
- change->Discard(browser());
- EXPECT_EQ(FindTemplateURL(prepopulated_url_->url()),
- turl_service_->GetDefaultSearchProvider());
-
- // Verify that Apply switches back to |current_url|.
- change->Apply(browser());
- EXPECT_EQ(FindTemplateURL(http_example_com),
- turl_service_->GetDefaultSearchProvider());
-}
-
-IN_PROC_BROWSER_TEST_F(DefaultSearchProviderChangeTest,
- BackupInvalidFallbackRemoved) {
- // Backup is invalid, current search provider exists, fallback to the
- // prepopulated default search, which was removed from keywords (will be
- // added).
- int prepopulated_histogram_id =
- protector::GetSearchProviderHistogramID(prepopulated_url_.get());
- TemplateURL* current_url =
- MakeTemplateURL(example_com, ASCIIToUTF16("b"), http_example_com);
- int current_histogram_id =
- protector::GetSearchProviderHistogramID(current_url);
-
- AddAndSetDefault(current_url);
-
- TemplateURL* prepopulated_default = FindTemplateURL(prepopulated_url_->url());
- // Prepopulated default search must exist, remove it.
- ASSERT_TRUE(prepopulated_default);
- turl_service_->Remove(prepopulated_default);
-
- scoped_ptr<BaseSettingChange> change(
- CreateDefaultSearchProviderChange(current_url, NULL));
- ASSERT_TRUE(change.get());
- ASSERT_TRUE(change->Init(browser()->profile()));
-
- // Verify that the prepopulated default search is active.
- EXPECT_EQ(FindTemplateURL(prepopulated_url_->url()),
- turl_service_->GetDefaultSearchProvider());
-
- // Verify histograms.
- ExpectHistogramCount(kProtectorHistogramSearchProviderCorrupt,
- current_histogram_id, 1);
- ExpectHistogramCount(kProtectorHistogramSearchProviderRestored,
- prepopulated_histogram_id, 1);
- ExpectHistogramCount(kProtectorHistogramSearchProviderFallback,
- prepopulated_histogram_id, 1);
- ExpectHistogramCount(kProtectorHistogramSearchProviderMissing,
- prepopulated_histogram_id, 1);
-
- // Verify text messages.
- EXPECT_EQ(GetBubbleMessage(prepopulated_url_->short_name()),
- change->GetBubbleMessage());
- EXPECT_EQ(GetChangeSearchButtonText(example_com),
- change->GetApplyButtonText());
- EXPECT_EQ(GetOpenSettingsButtonText(), change->GetDiscardButtonText());
- EXPECT_EQ(GURL(), change->GetNewSettingURL());
- EXPECT_EQ(example_com, change->GetApplyDisplayName().second);
-
- // Verify that search engine settings are opened by Discard.
- ExpectSettingsOpened(chrome::kSearchEnginesSubPage);
- change->Discard(browser());
- EXPECT_EQ(FindTemplateURL(prepopulated_url_->url()),
- turl_service_->GetDefaultSearchProvider());
-
- // Verify that Apply switches back to |current_url|.
- change->Apply(browser());
- EXPECT_EQ(FindTemplateURL(http_example_com),
- turl_service_->GetDefaultSearchProvider());
-}
-
-IN_PROC_BROWSER_TEST_F(DefaultSearchProviderChangeTest,
- BackupValidCurrentRemoved) {
- // Backup is valid, no current search provider.
- TemplateURL* backup_url =
- MakeTemplateURL(example_info, ASCIIToUTF16("a"), http_example_info);
- int backup_histogram_id = protector::GetSearchProviderHistogramID(backup_url);
-
- Profile* profile = browser()->profile();
- turl_service_->Add(new TemplateURL(profile, backup_url->data()));
- turl_service_->SetDefaultSearchProvider(NULL);
-
- scoped_ptr<BaseSettingChange> change(
- CreateDefaultSearchProviderChange(NULL, backup_url));
- ASSERT_TRUE(change.get());
- ASSERT_TRUE(change->Init(profile));
-
- // Verify that backup is active.
- EXPECT_EQ(FindTemplateURL(http_example_info),
- turl_service_->GetDefaultSearchProvider());
-
- // Verify histograms.
- ExpectHistogramCount(kProtectorHistogramSearchProviderHijacked,
- protector::GetSearchProviderHistogramID(NULL), 1);
- ExpectHistogramCount(kProtectorHistogramSearchProviderRestored,
- backup_histogram_id, 1);
-
- // Verify text messages.
- EXPECT_EQ(GetBubbleMessage(), change->GetBubbleMessage());
- EXPECT_EQ(GetOpenSettingsButtonText(), change->GetApplyButtonText());
- EXPECT_EQ(GetKeepSearchButtonText(example_info),
- change->GetDiscardButtonText());
- EXPECT_EQ(GURL(), change->GetNewSettingURL());
- EXPECT_EQ(kNoDisplayName, change->GetApplyDisplayName());
-
- // Discard does nothing - backup was already active.
- change->Discard(browser());
- EXPECT_EQ(FindTemplateURL(http_example_info),
- turl_service_->GetDefaultSearchProvider());
-
- // Verify that search engine settings are opened by Apply (no other changes).
- ExpectSettingsOpened(chrome::kSearchEnginesSubPage);
- change->Apply(browser());
- EXPECT_EQ(FindTemplateURL(http_example_info),
- turl_service_->GetDefaultSearchProvider());
-}
-
-IN_PROC_BROWSER_TEST_F(DefaultSearchProviderChangeTest,
- BackupValidCurrentCannotBeDefault) {
- // Backup is valid, current search provider has no search terms.
- TemplateURL* backup_url =
- MakeTemplateURL(example_info, ASCIIToUTF16("a"), http_example_info);
- int backup_histogram_id = protector::GetSearchProviderHistogramID(backup_url);
- TemplateURL* current_url =
- MakeTemplateURL(example_com, ASCIIToUTF16("b"),
- http_example_com_no_search_terms);
- int current_histogram_id =
- protector::GetSearchProviderHistogramID(current_url);
-
- Profile* profile = browser()->profile();
- turl_service_->Add(new TemplateURL(profile, backup_url->data()));
- // TODO(ivankr): this may become unsupported soon.
- AddAndSetDefault(current_url);
-
- scoped_ptr<BaseSettingChange> change(
- CreateDefaultSearchProviderChange(current_url, backup_url));
- ASSERT_TRUE(change.get());
- ASSERT_TRUE(change->Init(profile));
-
- // Verify that backup is active.
- EXPECT_EQ(FindTemplateURL(http_example_info),
- turl_service_->GetDefaultSearchProvider());
-
- // Verify histograms.
- ExpectHistogramCount(kProtectorHistogramSearchProviderHijacked,
- current_histogram_id, 1);
- ExpectHistogramCount(kProtectorHistogramSearchProviderRestored,
- backup_histogram_id, 1);
-
- // Verify text messages.
- EXPECT_EQ(GetBubbleMessage(), change->GetBubbleMessage());
- EXPECT_EQ(GetOpenSettingsButtonText(), change->GetApplyButtonText());
- EXPECT_EQ(GetKeepSearchButtonText(example_info),
- change->GetDiscardButtonText());
- EXPECT_EQ(GURL(), change->GetNewSettingURL());
- EXPECT_EQ(kNoDisplayName, change->GetApplyDisplayName());
-
- // Discard does nothing - backup was already active.
- change->Discard(browser());
- EXPECT_EQ(FindTemplateURL(http_example_info),
- turl_service_->GetDefaultSearchProvider());
-
- // Verify that search engine settings are opened by Apply (no other changes).
- ExpectSettingsOpened(chrome::kSearchEnginesSubPage);
- change->Apply(browser());
- EXPECT_EQ(FindTemplateURL(http_example_info),
- turl_service_->GetDefaultSearchProvider());
-}
-
-IN_PROC_BROWSER_TEST_F(DefaultSearchProviderChangeTest,
- BackupInvalidCurrentRemoved) {
- // Backup is invalid, no current search provider, fallback to the prepopulated
- // default search.
- int prepopulated_histogram_id =
- protector::GetSearchProviderHistogramID(prepopulated_url_.get());
- turl_service_->SetDefaultSearchProvider(NULL);
-
- scoped_ptr<BaseSettingChange> change(
- CreateDefaultSearchProviderChange(NULL, NULL));
- ASSERT_TRUE(change.get());
- ASSERT_TRUE(change->Init(browser()->profile()));
-
- // Verify that the prepopulated default search is active.
- EXPECT_EQ(FindTemplateURL(prepopulated_url_->url()),
- turl_service_->GetDefaultSearchProvider());
-
- // Verify histograms.
- ExpectHistogramCount(kProtectorHistogramSearchProviderCorrupt,
- protector::GetSearchProviderHistogramID(NULL), 1);
- ExpectHistogramCount(kProtectorHistogramSearchProviderRestored,
- prepopulated_histogram_id, 1);
- ExpectHistogramCount(kProtectorHistogramSearchProviderFallback,
- prepopulated_histogram_id, 1);
-
- // Verify text messages.
- EXPECT_EQ(GetBubbleMessage(prepopulated_url_->short_name()),
- change->GetBubbleMessage());
- EXPECT_EQ(string16(), change->GetApplyButtonText());
- EXPECT_EQ(GetOpenSettingsButtonText(), change->GetDiscardButtonText());
- EXPECT_EQ(GURL(), change->GetNewSettingURL());
- EXPECT_EQ(kNoDisplayName, change->GetApplyDisplayName());
-
- // Verify that search engine settings are opened by Discard.
- ExpectSettingsOpened(chrome::kSearchEnginesSubPage);
- change->Discard(browser());
- EXPECT_EQ(FindTemplateURL(prepopulated_url_->url()),
- turl_service_->GetDefaultSearchProvider());
-}
-
-IN_PROC_BROWSER_TEST_F(DefaultSearchProviderChangeTest,
- BackupInvalidFallbackSameAsCurrent) {
- // Backup is invalid, fallback to the prepopulated default search which is
- // same as the current search provider.
- int prepopulated_histogram_id =
- protector::GetSearchProviderHistogramID(prepopulated_url_.get());
- TemplateURL* current_url = turl_service_->GetDefaultSearchProvider();
-
- // Verify that current search provider is same as the prepopulated default.
- ASSERT_TRUE(current_url);
- ASSERT_EQ(current_url, FindTemplateURL(prepopulated_url_->url()));
-
- scoped_ptr<BaseSettingChange> change(
- CreateDefaultSearchProviderChange(current_url, NULL));
- ASSERT_TRUE(change.get());
- ASSERT_TRUE(change->Init(browser()->profile()));
-
- // Verify that the default search has not changed.
- EXPECT_EQ(current_url, turl_service_->GetDefaultSearchProvider());
-
- // Verify histograms.
- ExpectHistogramCount(kProtectorHistogramSearchProviderCorrupt,
- prepopulated_histogram_id, 1);
- ExpectHistogramCount(kProtectorHistogramSearchProviderRestored,
- prepopulated_histogram_id, 1);
- ExpectHistogramCount(kProtectorHistogramSearchProviderFallback,
- prepopulated_histogram_id, 1);
-
- // Verify text messages.
- EXPECT_EQ(GetBubbleMessage(prepopulated_url_->short_name()),
- change->GetBubbleMessage());
- EXPECT_EQ(string16(), change->GetApplyButtonText());
- EXPECT_EQ(GetOpenSettingsButtonText(), change->GetDiscardButtonText());
- EXPECT_EQ(GURL(), change->GetNewSettingURL());
- EXPECT_EQ(current_url->short_name(), change->GetApplyDisplayName().second);
-
- // Verify that search engine settings are opened by Discard.
- ExpectSettingsOpened(chrome::kSearchEnginesSubPage);
- change->Discard(browser());
- EXPECT_EQ(current_url, turl_service_->GetDefaultSearchProvider());
-}
-
-
-IN_PROC_BROWSER_TEST_F(DefaultSearchProviderChangeTest,
- DefaultSearchProviderChangedByUser) {
- // Default search provider is changed by user while the error is active.
- // Setup is the same as in BackupValid test case.
- TemplateURL* backup_url =
- MakeTemplateURL(example_info, ASCIIToUTF16("a"), http_example_info);
- TemplateURL* current_url =
- MakeTemplateURL(example_com, ASCIIToUTF16("b"), http_example_com);
- TemplateURL* new_url =
- MakeTemplateURL(example_net, ASCIIToUTF16("c"), http_example_net);
-
- Profile* profile = browser()->profile();
- turl_service_->Add(new TemplateURL(profile, backup_url->data()));
- AddAndSetDefault(current_url);
-
- scoped_ptr<BaseSettingChange> change(
- CreateDefaultSearchProviderChange(current_url, backup_url));
- ASSERT_TRUE(change.get());
- ASSERT_TRUE(change->Init(profile));
-
- // Verify that backup is active.
- EXPECT_EQ(FindTemplateURL(http_example_info),
- turl_service_->GetDefaultSearchProvider());
-
- // Verify that changing search provider externally dismissed the change.
- EXPECT_CALL(*mock_protector_service_, DismissChange(change.get()));
- AddAndSetDefault(new_url);
-}
-
-IN_PROC_BROWSER_TEST_F(DefaultSearchProviderChangeTest,
- CurrentSearchProviderRemovedByUser) {
- // Current search provider is removed by user while the error is active.
- // Setup is the same as in BackupValid test case.
- TemplateURL* backup_url =
- MakeTemplateURL(example_info, ASCIIToUTF16("a"), http_example_info);
- TemplateURL* current_url =
- MakeTemplateURL(example_com, ASCIIToUTF16("b"), http_example_com);
-
- Profile* profile = browser()->profile();
- turl_service_->Add(new TemplateURL(profile, backup_url->data()));
- AddAndSetDefault(current_url);
-
- scoped_ptr<BaseSettingChange> change(
- CreateDefaultSearchProviderChange(current_url, backup_url));
- ASSERT_TRUE(change.get());
- ASSERT_TRUE(change->Init(profile));
-
- // Verify that backup is active.
- EXPECT_EQ(FindTemplateURL(http_example_info),
- turl_service_->GetDefaultSearchProvider());
-
- turl_service_->Remove(current_url);
-
- // Verify that text messages altered after removing |current_url|.
- EXPECT_EQ(GetBubbleMessage(), change->GetBubbleMessage());
- EXPECT_EQ(GetOpenSettingsButtonText(), change->GetApplyButtonText());
- EXPECT_EQ(GetKeepSearchButtonText(example_info),
- change->GetDiscardButtonText());
- EXPECT_EQ(GURL(), change->GetNewSettingURL());
- EXPECT_EQ(kNoDisplayName, change->GetApplyDisplayName());
-
- // Verify that search engine settings are opened by Apply.
- ExpectSettingsOpened(chrome::kSearchEnginesSubPage);
- change->Apply(browser());
- EXPECT_EQ(FindTemplateURL(http_example_info),
- turl_service_->GetDefaultSearchProvider());
-
- // Discard does nothing - backup was already active.
- change->Discard(browser());
- EXPECT_EQ(FindTemplateURL(http_example_info),
- turl_service_->GetDefaultSearchProvider());
-}
-
-} // namespace protector
diff --git a/chrome/browser/protector/histograms.cc b/chrome/browser/protector/histograms.cc
deleted file mode 100644
index 761cbec..0000000
--- a/chrome/browser/protector/histograms.cc
+++ /dev/null
@@ -1,62 +0,0 @@
-// Copyright (c) 2012 The Chromium Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-#include "chrome/browser/protector/histograms.h"
-
-#include "base/memory/scoped_ptr.h"
-#include "chrome/browser/search_engines/template_url.h"
-#include "chrome/browser/search_engines/template_url_prepopulate_data.h"
-
-namespace protector {
-
-const char kProtectorHistogramDefaultSearchProvider[] =
- "Protector.DefaultSearchProvider";
-
-const char kProtectorHistogramPrefs[] =
- "Protector.Preferences";
-
-const char kProtectorHistogramSearchProviderApplied[] =
- "Protector.SearchProvider.Applied";
-const char kProtectorHistogramSearchProviderCorrupt[] =
- "Protector.SearchProvider.Corrupt";
-const char kProtectorHistogramSearchProviderDiscarded[] =
- "Protector.SearchProvider.Discarded";
-const char kProtectorHistogramSearchProviderFallback[] =
- "Protector.SearchProvider.Fallback";
-const char kProtectorHistogramSearchProviderHijacked[] =
- "Protector.SearchProvider.Hijacked";
-const char kProtectorHistogramSearchProviderMissing[] =
- "Protector.SearchProvider.Missing";
-const char kProtectorHistogramSearchProviderRestored[] =
- "Protector.SearchProvider.Restored";
-const char kProtectorHistogramSearchProviderTimeout[] =
- "Protector.SearchProvider.Timeout";
-
-const char kProtectorHistogramStartupSettingsApplied[] =
- "Protector.StartupSettings.Applied";
-const char kProtectorHistogramStartupSettingsChanged[] =
- "Protector.StartupSettings.Changed";
-const char kProtectorHistogramStartupSettingsDiscarded[] =
- "Protector.StartupSettings.Discarded";
-const char kProtectorHistogramStartupSettingsTimeout[] =
- "Protector.StartupSettings.Timeout";
-
-const char kProtectorHistogramHomepageApplied[] =
- "Protector.Homepage.Applied";
-const char kProtectorHistogramHomepageChanged[] =
- "Protector.Homepage.Changed";
-const char kProtectorHistogramHomepageDiscarded[] =
- "Protector.Homepage.Discarded";
-const char kProtectorHistogramHomepageTimeout[] =
- "Protector.Homepage.Timeout";
-
-const int kProtectorMaxSearchProviderID = SEARCH_ENGINE_MAX;
-
-int GetSearchProviderHistogramID(const TemplateURL* t_url) {
- return t_url ?
- TemplateURLPrepopulateData::GetEngineType(t_url->url()) :
- SEARCH_ENGINE_NONE;
-}
-
-} // namespace protector
diff --git a/chrome/browser/protector/histograms.h b/chrome/browser/protector/histograms.h
deleted file mode 100644
index c66878a..0000000
--- a/chrome/browser/protector/histograms.h
+++ /dev/null
@@ -1,83 +0,0 @@
-// Copyright (c) 2012 The Chromium Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-#ifndef CHROME_BROWSER_PROTECTOR_HISTOGRAMS_H_
-#define CHROME_BROWSER_PROTECTOR_HISTOGRAMS_H_
-
-class TemplateURL;
-
-namespace protector {
-
-// Histogram name to report protection errors for the default search
-// provider. Values are below.
-extern const char kProtectorHistogramDefaultSearchProvider[];
-
-// Histogram name to report protection errors for preferences. Values are below.
-extern const char kProtectorHistogramPrefs[];
-
-// Protector histogram values.
-enum ProtectorError {
- kProtectorErrorBackupInvalid,
- kProtectorErrorValueChanged,
- kProtectorErrorValueValid,
- kProtectorErrorValueValidZero,
- kProtectorErrorForcedUpdate,
- kProtectorErrorOverwrittenByMigration,
-
- // This is for convenience only, must always be the last.
- kProtectorErrorCount
-};
-
-// Histogram name to report when user accepts new default search provider.
-extern const char kProtectorHistogramSearchProviderApplied[];
-// Histogram name to report the default search provider when the backup is
-// invalid.
-extern const char kProtectorHistogramSearchProviderCorrupt[];
-// Histogram name to report when user keeps previous default search provider.
-extern const char kProtectorHistogramSearchProviderDiscarded[];
-// Histogram name to report the fallback default search provider when the
-// backup value is invalid or doesn't match an existing provider.
-extern const char kProtectorHistogramSearchProviderFallback[];
-// Histogram name to report the new default search provider when the backup is
-// valid and a change is detected.
-extern const char kProtectorHistogramSearchProviderHijacked[];
-// Histogram name to report when the prepopulated default search provider was
-// missing and has been added for fallback.
-extern const char kProtectorHistogramSearchProviderMissing[];
-// Histogram name to report the default search provider restored by Protector
-// before showing user the bubble.
-extern const char kProtectorHistogramSearchProviderRestored[];
-// Histogram name to report when user ignores search provider change.
-extern const char kProtectorHistogramSearchProviderTimeout[];
-
-// Histogram name to report when user accepts new startup settings.
-extern const char kProtectorHistogramStartupSettingsApplied[];
-// Histogram name to report the new startup settings when the backup is
-// valid and a change is detected.
-extern const char kProtectorHistogramStartupSettingsChanged[];
-// Histogram name to report when user keeps previous startup settings.
-extern const char kProtectorHistogramStartupSettingsDiscarded[];
-// Histogram name to report when user ignores startup settings change.
-extern const char kProtectorHistogramStartupSettingsTimeout[];
-
-// Histogram name to report when user accepts new homepage.
-extern const char kProtectorHistogramHomepageApplied[];
-// Histogram name to report the new homepage when the backup is valid and a
-// change is detected.
-extern const char kProtectorHistogramHomepageChanged[];
-// Histogram name to report when user keeps previous homepage.
-extern const char kProtectorHistogramHomepageDiscarded[];
-// Histogram name to report when user ignores homepage change.
-extern const char kProtectorHistogramHomepageTimeout[];
-
-// Maximum value of search provider index in histogram enums.
-extern const int kProtectorMaxSearchProviderID;
-
-// Returns index to be used in histograms for given search provider (which may
-// be NULL, in which case a special index will be returned).
-int GetSearchProviderHistogramID(const TemplateURL* turl);
-
-} // namespace protector
-
-#endif // CHROME_BROWSER_PROTECTOR_HISTOGRAMS_H_
diff --git a/chrome/browser/protector/homepage_change.cc b/chrome/browser/protector/homepage_change.cc
deleted file mode 100644
index 0614d06..0000000
--- a/chrome/browser/protector/homepage_change.cc
+++ /dev/null
@@ -1,201 +0,0 @@
-// Copyright (c) 2012 The Chromium Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-#include "base/basictypes.h"
-#include "base/metrics/histogram.h"
-#include "base/utf_string_conversions.h"
-#include "chrome/browser/prefs/pref_service.h"
-#include "chrome/browser/profiles/profile.h"
-#include "chrome/browser/protector/base_prefs_change.h"
-#include "chrome/browser/protector/histograms.h"
-#include "chrome/common/pref_names.h"
-#include "grit/chromium_strings.h"
-#include "grit/generated_resources.h"
-#include "grit/theme_resources.h"
-#include "ui/base/l10n/l10n_util.h"
-
-namespace protector {
-
-// Homepage change tracked by Protector.
-class HomepageChange : public BasePrefsChange {
- public:
- // Enum for reporting UMA statistics.
- enum HomepageType {
- HOMEPAGE_NTP = 0,
- HOMEPAGE_URL,
-
- // Must be the last value
- HOMEPAGE_TYPE_COUNT
- };
-
- HomepageChange(const std::string& actual_homepage,
- bool actual_homepage_is_ntp,
- bool actual_show_homepage,
- const std::string& backup_homepage,
- bool backup_homepage_is_ntp,
- bool backup_show_homepage);
-
- // BaseSettingChange overrides:
- virtual bool Init(Profile* profile) OVERRIDE;
- virtual void Apply(Browser* browser) OVERRIDE;
- virtual void Discard(Browser* browser) OVERRIDE;
- virtual void Timeout() OVERRIDE;
- virtual int GetBadgeIconID() const OVERRIDE;
- virtual int GetMenuItemIconID() const OVERRIDE;
- virtual int GetBubbleIconID() const OVERRIDE;
- virtual string16 GetBubbleTitle() const OVERRIDE;
- virtual string16 GetBubbleMessage() const OVERRIDE;
- virtual string16 GetApplyButtonText() const OVERRIDE;
- virtual string16 GetDiscardButtonText() const OVERRIDE;
- virtual DisplayName GetApplyDisplayName() const OVERRIDE;
- virtual GURL GetNewSettingURL() const OVERRIDE;
-
- private:
- virtual ~HomepageChange();
-
- const std::string new_homepage_;
- const std::string backup_homepage_;
- const bool new_homepage_is_ntp_;
- const bool backup_homepage_is_ntp_;
- const bool new_show_homepage_;
- const bool backup_show_homepage_;
- const HomepageType new_homepage_type_;
-
- DISALLOW_COPY_AND_ASSIGN(HomepageChange);
-};
-
-HomepageChange::HomepageChange(
- const std::string& actual_homepage,
- bool actual_homepage_is_ntp,
- bool actual_show_homepage,
- const std::string& backup_homepage,
- bool backup_homepage_is_ntp,
- bool backup_show_homepage)
- : new_homepage_(actual_homepage),
- backup_homepage_(backup_homepage),
- new_homepage_is_ntp_(actual_homepage_is_ntp),
- backup_homepage_is_ntp_(backup_homepage_is_ntp),
- new_show_homepage_(actual_show_homepage),
- backup_show_homepage_(backup_show_homepage),
- new_homepage_type_(actual_homepage_is_ntp ? HOMEPAGE_NTP : HOMEPAGE_URL) {
- UMA_HISTOGRAM_ENUMERATION(
- kProtectorHistogramHomepageChanged,
- new_homepage_type_,
- HOMEPAGE_TYPE_COUNT);
-}
-
-HomepageChange::~HomepageChange() {
-}
-
-bool HomepageChange::Init(Profile* profile) {
- if (!BasePrefsChange::Init(profile))
- return false;
- PrefService* prefs = profile->GetPrefs();
- prefs->SetString(prefs::kHomePage, backup_homepage_);
- prefs->SetBoolean(prefs::kHomePageIsNewTabPage, backup_homepage_is_ntp_);
- prefs->SetBoolean(prefs::kShowHomeButton, backup_show_homepage_);
- DismissOnPrefChange(prefs::kHomePage);
- DismissOnPrefChange(prefs::kHomePageIsNewTabPage);
- DismissOnPrefChange(prefs::kShowHomeButton);
- return true;
-}
-
-void HomepageChange::Apply(Browser* browser) {
- UMA_HISTOGRAM_ENUMERATION(
- kProtectorHistogramHomepageApplied,
- new_homepage_type_,
- HOMEPAGE_TYPE_COUNT);
- IgnorePrefChanges();
- PrefService* prefs = profile()->GetPrefs();
- prefs->SetString(prefs::kHomePage, new_homepage_);
- prefs->SetBoolean(prefs::kHomePageIsNewTabPage, new_homepage_is_ntp_);
- prefs->SetBoolean(prefs::kShowHomeButton, new_show_homepage_);
-}
-
-void HomepageChange::Discard(Browser* browser) {
- UMA_HISTOGRAM_ENUMERATION(
- kProtectorHistogramHomepageDiscarded,
- new_homepage_type_,
- HOMEPAGE_TYPE_COUNT);
- IgnorePrefChanges();
- // Nothing to do here since backup has already been made active by Init().
-}
-
-void HomepageChange::Timeout() {
- UMA_HISTOGRAM_ENUMERATION(
- kProtectorHistogramHomepageTimeout,
- new_homepage_type_,
- HOMEPAGE_TYPE_COUNT);
-}
-
-int HomepageChange::GetBadgeIconID() const {
- // Icons are the same for homepage and startup settings.
- return IDR_HOMEPAGE_CHANGE_BADGE;
-}
-
-int HomepageChange::GetMenuItemIconID() const {
- return IDR_HOMEPAGE_CHANGE_MENU;
-}
-
-int HomepageChange::GetBubbleIconID() const {
- return IDR_HOMEPAGE_CHANGE_ALERT;
-}
-
-string16 HomepageChange::GetBubbleTitle() const {
- return l10n_util::GetStringUTF16(IDS_HOMEPAGE_CHANGE_TITLE);
-}
-
-string16 HomepageChange::GetBubbleMessage() const {
- return l10n_util::GetStringUTF16(IDS_HOMEPAGE_CHANGE_BUBBLE_MESSAGE);
-}
-
-string16 HomepageChange::GetApplyButtonText() const {
- GURL homepage_url(GetNewSettingURL());
- return homepage_url.is_empty() ?
- l10n_util::GetStringUTF16(IDS_CHANGE_HOMEPAGE_NTP) :
- l10n_util::GetStringFUTF16(IDS_CHANGE_HOMEPAGE,
- UTF8ToUTF16(homepage_url.host()));
-}
-
-string16 HomepageChange::GetDiscardButtonText() const {
- GURL new_homepage_url(GetNewSettingURL());
- GURL backup_homepage_url;
- if (!backup_homepage_is_ntp_)
- backup_homepage_url = GURL(backup_homepage_);
- if (backup_homepage_url.host() == new_homepage_url.host()) {
- // Display a generic string if new setting looks the same as the backup (for
- // example, when homepage hasn't changed but 'show homepage button' has).
- return l10n_util::GetStringUTF16(IDS_KEEP_SETTING);
- }
- return backup_homepage_url.is_empty() ?
- l10n_util::GetStringUTF16(IDS_KEEP_HOMEPAGE_NTP) :
- l10n_util::GetStringFUTF16(IDS_KEEP_HOMEPAGE,
- UTF8ToUTF16(backup_homepage_url.host()));
-}
-
-BaseSettingChange::DisplayName HomepageChange::GetApplyDisplayName() const {
- GURL homepage_url(GetNewSettingURL());
- return homepage_url.is_empty() ?
- DisplayName(kDefaultNamePriority, string16()) :
- DisplayName(kHomepageChangeNamePriority,
- UTF8ToUTF16(homepage_url.host()));
-}
-
-GURL HomepageChange::GetNewSettingURL() const {
- return new_homepage_is_ntp_ ? GURL() : GURL(new_homepage_);
-}
-
-BaseSettingChange* CreateHomepageChange(
- const std::string& actual_homepage,
- bool actual_homepage_is_ntp,
- bool actual_show_homepage,
- const std::string& backup_homepage,
- bool backup_homepage_is_ntp,
- bool backup_show_homepage) {
- return new HomepageChange(
- actual_homepage, actual_homepage_is_ntp, actual_show_homepage,
- backup_homepage, backup_homepage_is_ntp, backup_show_homepage);
-}
-
-} // namespace protector
diff --git a/chrome/browser/protector/homepage_change_unittest.cc b/chrome/browser/protector/homepage_change_unittest.cc
deleted file mode 100644
index 001812d..0000000
--- a/chrome/browser/protector/homepage_change_unittest.cc
+++ /dev/null
@@ -1,118 +0,0 @@
-// Copyright (c) 2012 The Chromium Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-#include "base/memory/scoped_ptr.h"
-#include "base/utf_string_conversions.h"
-#include "base/values.h"
-#include "chrome/browser/prefs/pref_service.h"
-#include "chrome/browser/protector/base_setting_change.h"
-#include "chrome/common/pref_names.h"
-#include "chrome/test/base/testing_profile.h"
-#include "grit/generated_resources.h"
-#include "testing/gtest/include/gtest/gtest.h"
-#include "ui/base/l10n/l10n_util.h"
-
-namespace protector {
-
-namespace {
-
-std::string kHomepage1 = "http://google.com/";
-std::string kHomepage2 = "http://example.com/";
-
-}
-
-class HomepageChangeTest : public testing::Test {
- virtual void SetUp() OVERRIDE {
- prefs_ = profile_.GetPrefs();
- }
-
- protected:
- TestingProfile profile_;
- PrefService* prefs_;
-};
-
-TEST_F(HomepageChangeTest, InitAndApply) {
- prefs_->SetString(prefs::kHomePage, kHomepage1);
-
- // Create a change and apply it.
- scoped_ptr<BaseSettingChange> change(
- CreateHomepageChange(kHomepage1, false, true, kHomepage2, false, true));
- ASSERT_TRUE(change->Init(&profile_));
- // Setting is initially reverted to backup.
- EXPECT_EQ(kHomepage2, prefs_->GetString(prefs::kHomePage));
-
- change->Apply(NULL); // |browser| is unused.
- // New setting active now.
- EXPECT_EQ(kHomepage1, prefs_->GetString(prefs::kHomePage));
-}
-
-TEST_F(HomepageChangeTest, InitAndDiscard) {
- prefs_->SetString(prefs::kHomePage, kHomepage1);
-
- // Create a change and apply it.
- scoped_ptr<BaseSettingChange> change(
- CreateHomepageChange(kHomepage1, false, true, kHomepage2, false, true));
- ASSERT_TRUE(change->Init(&profile_));
- // Setting is initially reverted to backup.
- EXPECT_EQ(kHomepage2, prefs_->GetString(prefs::kHomePage));
-
- change->Discard(NULL); // |browser| is unused.
- // Nothing changed by Discard.
- EXPECT_EQ(kHomepage2, prefs_->GetString(prefs::kHomePage));
-}
-
-TEST_F(HomepageChangeTest, DiscardButtonCaptionsSameSetting) {
- // New and backup setting have the same URL (or both are NTP).
-
- // NTP can be represented both by an empty URL or a |homepage_is_ntp| flag.
- // NTP -> NTP.
- scoped_ptr<BaseSettingChange> change(
- CreateHomepageChange(kHomepage1, true, true, kHomepage2, true, true));
- ASSERT_TRUE(change->Init(&profile_));
- string16 generic_caption(l10n_util::GetStringUTF16(IDS_KEEP_SETTING));
- EXPECT_EQ(generic_caption, change->GetDiscardButtonText());
-
- // NTP -> NTP.
- change.reset(
- CreateHomepageChange("", false, true, kHomepage2, true, true));
- ASSERT_TRUE(change->Init(&profile_));
- EXPECT_EQ(generic_caption, change->GetDiscardButtonText());
-
- // NTP -> NTP.
- change.reset(
- CreateHomepageChange(kHomepage1, true, true, "", false, true));
- ASSERT_TRUE(change->Init(&profile_));
- EXPECT_EQ(generic_caption, change->GetDiscardButtonText());
-
- // kHomepage1 -> kHomepage1.
- change.reset(
- CreateHomepageChange(kHomepage1, false, true, kHomepage1, false, true));
- ASSERT_TRUE(change->Init(&profile_));
- EXPECT_EQ(generic_caption, change->GetDiscardButtonText());
-}
-
-TEST_F(HomepageChangeTest, DiscardButtonCaptionsDifferentSettings) {
- // New and backup settings differ.
-
- // NTP -> kHomepage2.
- scoped_ptr<BaseSettingChange> change(
- CreateHomepageChange(kHomepage1, true, true, kHomepage2, false, true));
- ASSERT_TRUE(change->Init(&profile_));
- string16 generic_caption(l10n_util::GetStringUTF16(IDS_KEEP_SETTING));
- EXPECT_NE(generic_caption, change->GetDiscardButtonText());
-
- // kHomepage1 -> NTP.
- change.reset(
- CreateHomepageChange(kHomepage1, false, true, kHomepage2, true, true));
- ASSERT_TRUE(change->Init(&profile_));
- EXPECT_NE(generic_caption, change->GetDiscardButtonText());
-
- // kHomepage1 -> kHomepage2.
- change.reset(
- CreateHomepageChange(kHomepage1, false, true, kHomepage2, false, true));
- ASSERT_TRUE(change->Init(&profile_));
- EXPECT_NE(generic_caption, change->GetDiscardButtonText());
-}
-
-} // namespace protector
diff --git a/chrome/browser/protector/keys.cc b/chrome/browser/protector/keys.cc
deleted file mode 100644
index 6f4630b..0000000
--- a/chrome/browser/protector/keys.cc
+++ /dev/null
@@ -1,13 +0,0 @@
-// Copyright (c) 2011 The Chromium Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-#include "chrome/browser/protector/keys.h"
-
-namespace protector {
-
-// When changing the key, be sure to add migration code to keep user's
-// settings safe.
-const char kProtectorSigningKey[] = "Please, don't change this Chrome setting";
-
-} // namespace protector
diff --git a/chrome/browser/protector/keys.h b/chrome/browser/protector/keys.h
deleted file mode 100644
index d40d703..0000000
--- a/chrome/browser/protector/keys.h
+++ /dev/null
@@ -1,17 +0,0 @@
-// Copyright (c) 2011 The Chromium Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-#ifndef CHROME_BROWSER_PROTECTOR_KEYS_H_
-#define CHROME_BROWSER_PROTECTOR_KEYS_H_
-
-namespace protector {
-
-// When changing the key, be sure to add migration code to keep user's
-// settings safe.
-extern const char kProtectorSigningKey[];
-
-} // namespace protector
-
-#endif // CHROME_BROWSER_PROTECTOR_KEYS_H_
-
diff --git a/chrome/browser/protector/mock_protector_service.cc b/chrome/browser/protector/mock_protector_service.cc
deleted file mode 100644
index a8caacb..0000000
--- a/chrome/browser/protector/mock_protector_service.cc
+++ /dev/null
@@ -1,34 +0,0 @@
-// Copyright (c) 2012 The Chromium Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-#include "chrome/browser/protector/mock_protector_service.h"
-
-#include "chrome/browser/protector/protector_service_factory.h"
-#include "googleurl/src/gurl.h"
-
-namespace protector {
-
-namespace {
-
-ProfileKeyedService* BuildMockProtectorService(Profile* profile) {
- return new MockProtectorService(profile);
-}
-
-} // namespace
-
-// static
-MockProtectorService* MockProtectorService::BuildForProfile(Profile* profile) {
- return static_cast<MockProtectorService*>(
- ProtectorServiceFactory::GetInstance()->SetTestingFactoryAndUse(
- profile, BuildMockProtectorService));
-}
-
-MockProtectorService::MockProtectorService(Profile* profile)
- : ProtectorService(profile) {
-}
-
-MockProtectorService::~MockProtectorService() {
-}
-
-} // namespace protector
diff --git a/chrome/browser/protector/mock_protector_service.h b/chrome/browser/protector/mock_protector_service.h
deleted file mode 100644
index 1babc62..0000000
--- a/chrome/browser/protector/mock_protector_service.h
+++ /dev/null
@@ -1,44 +0,0 @@
-// Copyright (c) 2012 The Chromium Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-#ifndef CHROME_BROWSER_PROTECTOR_MOCK_PROTECTOR_SERVICE_H_
-#define CHROME_BROWSER_PROTECTOR_MOCK_PROTECTOR_SERVICE_H_
-
-#include "chrome/browser/protector/protector_service.h"
-#include "testing/gmock/include/gmock/gmock.h"
-
-namespace protector {
-
-class MockProtectorService : public ProtectorService {
- public:
- // Creates and returns the MockProtectorService instance associated with
- // |profile|. Should be called before any calls to
- // ProtectorServiceFactory::GetForProfile are made, otherwise a (non-mocked)
- // ProtectorService instance will be associated with |profile|.
- static MockProtectorService* BuildForProfile(Profile* profile);
-
- explicit MockProtectorService(Profile* profile);
- virtual ~MockProtectorService();
-
- MOCK_METHOD1(ShowChange, void(BaseSettingChange*));
- MOCK_CONST_METHOD0(IsShowingChange, bool());
-
- MOCK_METHOD1(DismissChange, void(BaseSettingChange* change));
- MOCK_METHOD2(ApplyChange, void(BaseSettingChange* change, Browser*));
- MOCK_METHOD2(DiscardChange, void(BaseSettingChange* change, Browser*));
-
- MOCK_METHOD2(OpenTab, void(const GURL&, Browser*));
-
- MOCK_METHOD2(OnApplyChange, void(SettingsChangeGlobalError* error, Browser*));
- MOCK_METHOD2(OnDiscardChange, void(SettingsChangeGlobalError* error,
- Browser*));
- MOCK_METHOD1(OnDecisionTimeout, void(SettingsChangeGlobalError* error));
- MOCK_METHOD1(OnRemovedFromProfile, void(SettingsChangeGlobalError* error));
-
- MOCK_METHOD0(Shutdown, void());
-};
-
-} // namespace protector
-
-#endif // CHROME_BROWSER_PROTECTOR_MOCK_PROTECTOR_SERVICE_H_
diff --git a/chrome/browser/protector/mock_setting_change.cc b/chrome/browser/protector/mock_setting_change.cc
deleted file mode 100644
index aacd574..0000000
--- a/chrome/browser/protector/mock_setting_change.cc
+++ /dev/null
@@ -1,47 +0,0 @@
-// Copyright (c) 2012 The Chromium Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-#include "chrome/browser/protector/mock_setting_change.h"
-
-#include "base/utf_string_conversions.h"
-#include "grit/theme_resources.h"
-
-using ::testing::Return;
-
-namespace protector {
-
-MockSettingChange::MockSettingChange() {
- ON_CALL(*this, GetBadgeIconID()).WillByDefault(Return(IDR_UPDATE_BADGE4));
- ON_CALL(*this, GetMenuItemIconID()).WillByDefault(Return(IDR_UPDATE_MENU4));
- ON_CALL(*this, GetBubbleIconID()).WillByDefault(Return(IDR_INPUT_ALERT));
-
- ON_CALL(*this, GetBubbleTitle()).
- WillByDefault(Return(UTF8ToUTF16("Title")));
- ON_CALL(*this, GetBubbleMessage()).
- WillByDefault(Return(UTF8ToUTF16("Message")));
- ON_CALL(*this, GetApplyButtonText()).
- WillByDefault(Return(UTF8ToUTF16("Apply")));
- ON_CALL(*this, GetDiscardButtonText()).
- WillByDefault(Return(UTF8ToUTF16("Discard")));
-
- ON_CALL(*this, GetApplyDisplayName()).
- WillByDefault(Return(
- DisplayName(kDefaultNamePriority, UTF8ToUTF16("new settings"))));
-
- ON_CALL(*this, GetNewSettingURL()).WillByDefault(Return(GURL()));
- ON_CALL(*this, CanBeMerged()).WillByDefault(Return(false));
-
- ON_CALL(*this, IsUserVisible()).WillByDefault(Return(true));
-}
-
-MockSettingChange::~MockSettingChange() {
-}
-
-bool MockSettingChange::Init(Profile* profile) {
- if (!BaseSettingChange::Init(profile))
- return false;
- return MockInit(profile);
-}
-
-} // namespace protector
diff --git a/chrome/browser/protector/mock_setting_change.h b/chrome/browser/protector/mock_setting_change.h
deleted file mode 100644
index c05a7d8..0000000
--- a/chrome/browser/protector/mock_setting_change.h
+++ /dev/null
@@ -1,46 +0,0 @@
-// Copyright (c) 2012 The Chromium Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-#ifndef CHROME_BROWSER_PROTECTOR_MOCK_SETTING_CHANGE_H_
-#define CHROME_BROWSER_PROTECTOR_MOCK_SETTING_CHANGE_H_
-
-#include "base/compiler_specific.h"
-#include "chrome/browser/protector/base_setting_change.h"
-#include "testing/gmock/include/gmock/gmock.h"
-
-namespace protector {
-
-class MockSettingChange : public BaseSettingChange {
- public:
- MockSettingChange();
- virtual ~MockSettingChange();
-
- virtual bool Init(Profile* profile) OVERRIDE;
-
- MOCK_METHOD1(MockInit, bool(Profile* profile));
- MOCK_METHOD1(InitWhenDisabled, void(Profile*));
- MOCK_METHOD1(Apply, void(Browser*));
- MOCK_METHOD1(Discard, void(Browser*));
- MOCK_METHOD0(Timeout, void());
-
- MOCK_CONST_METHOD0(GetBadgeIconID, int());
- MOCK_CONST_METHOD0(GetMenuItemIconID, int());
- MOCK_CONST_METHOD0(GetBubbleIconID, int());
-
- MOCK_CONST_METHOD0(GetBubbleTitle, string16());
- MOCK_CONST_METHOD0(GetBubbleMessage, string16());
- MOCK_CONST_METHOD0(GetApplyButtonText, string16());
- MOCK_CONST_METHOD0(GetDiscardButtonText, string16());
-
- MOCK_CONST_METHOD0(GetApplyDisplayName, DisplayName());
-
- MOCK_CONST_METHOD0(GetNewSettingURL, GURL());
- MOCK_CONST_METHOD0(CanBeMerged, bool());
-
- MOCK_CONST_METHOD0(IsUserVisible, bool());
-};
-
-} // namespace protector
-
-#endif // CHROME_BROWSER_PROTECTOR_MOCK_SETTING_CHANGE_H_
diff --git a/chrome/browser/protector/prefs_backup_invalid_change.cc b/chrome/browser/protector/prefs_backup_invalid_change.cc
deleted file mode 100644
index e29edf7..0000000
--- a/chrome/browser/protector/prefs_backup_invalid_change.cc
+++ /dev/null
@@ -1,151 +0,0 @@
-// Copyright (c) 2012 The Chromium Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-#include "base/basictypes.h"
-#include "base/compiler_specific.h"
-#include "base/logging.h"
-#include "base/metrics/histogram.h"
-#include "base/utf_string_conversions.h"
-#include "chrome/browser/prefs/pref_service.h"
-#include "chrome/browser/prefs/session_startup_pref.h"
-#include "chrome/browser/profiles/profile.h"
-#include "chrome/browser/protector/base_prefs_change.h"
-#include "chrome/browser/protector/histograms.h"
-#include "chrome/browser/protector/protector_service.h"
-#include "chrome/browser/protector/protector_service_factory.h"
-#include "chrome/common/pref_names.h"
-#include "chrome/common/url_constants.h"
-#include "googleurl/src/gurl.h"
-#include "grit/chromium_strings.h"
-#include "grit/generated_resources.h"
-#include "grit/theme_resources.h"
-#include "ui/base/l10n/l10n_util.h"
-
-namespace protector {
-
-// Unknown change to Preferences with invalid backup.
-class PrefsBackupInvalidChange : public BasePrefsChange {
- public:
- PrefsBackupInvalidChange();
-
- // BasePrefsChange overrides:
- virtual bool Init(Profile* profile) OVERRIDE;
- virtual void InitWhenDisabled(Profile* profile) OVERRIDE;
- virtual void Apply(Browser* browser) OVERRIDE;
- virtual void Discard(Browser* browser) OVERRIDE;
- virtual void Timeout() OVERRIDE;
- virtual int GetBadgeIconID() const OVERRIDE;
- virtual int GetMenuItemIconID() const OVERRIDE;
- virtual int GetBubbleIconID() const OVERRIDE;
- virtual string16 GetBubbleTitle() const OVERRIDE;
- virtual string16 GetBubbleMessage() const OVERRIDE;
- virtual string16 GetApplyButtonText() const OVERRIDE;
- virtual string16 GetDiscardButtonText() const OVERRIDE;
- virtual bool CanBeMerged() const OVERRIDE;
-
- private:
- virtual ~PrefsBackupInvalidChange();
-
- // Applies default settings values when appropriate.
- void ApplyDefaults(Profile* profile);
-
- // True if session startup prefs have been reset.
- bool startup_pref_reset_;
-
- DISALLOW_COPY_AND_ASSIGN(PrefsBackupInvalidChange);
-};
-
-PrefsBackupInvalidChange::PrefsBackupInvalidChange()
- : startup_pref_reset_(false) {
-}
-
-PrefsBackupInvalidChange::~PrefsBackupInvalidChange() {
-}
-
-bool PrefsBackupInvalidChange::Init(Profile* profile) {
- if (!BasePrefsChange::Init(profile))
- return false;
- ApplyDefaults(profile);
- DismissOnPrefChange(prefs::kHomePageIsNewTabPage);
- DismissOnPrefChange(prefs::kHomePage);
- DismissOnPrefChange(prefs::kShowHomeButton);
- DismissOnPrefChange(prefs::kRestoreOnStartup);
- DismissOnPrefChange(prefs::kURLsToRestoreOnStartup);
- DismissOnPrefChange(prefs::kPinnedTabs);
- return true;
-}
-
-void PrefsBackupInvalidChange::InitWhenDisabled(Profile* profile) {
- // Nothing to do here since the backup has been already reset.
-}
-
-void PrefsBackupInvalidChange::Apply(Browser* browser) {
- NOTREACHED();
-}
-
-void PrefsBackupInvalidChange::Discard(Browser* browser) {
- // TODO(ivankr): highlight the protected prefs on the settings page
- // (http://crbug.com/119088).
- ProtectorServiceFactory::GetForProfile(profile())->OpenTab(
- GURL(chrome::kChromeUISettingsURL), browser);
-}
-
-void PrefsBackupInvalidChange::Timeout() {
-}
-
-int PrefsBackupInvalidChange::GetBadgeIconID() const {
- return IDR_UPDATE_BADGE4;
-}
-
-int PrefsBackupInvalidChange::GetMenuItemIconID() const {
- return IDR_UPDATE_MENU4;
-}
-
-int PrefsBackupInvalidChange::GetBubbleIconID() const {
- return IDR_INPUT_ALERT;
-}
-
-string16 PrefsBackupInvalidChange::GetBubbleTitle() const {
- return l10n_util::GetStringUTF16(IDS_SETTING_CHANGE_TITLE);
-}
-
-string16 PrefsBackupInvalidChange::GetBubbleMessage() const {
- return startup_pref_reset_ ?
- l10n_util::GetStringUTF16(
- IDS_SETTING_CHANGE_NO_BACKUP_STARTUP_RESET_BUBBLE_MESSAGE) :
- l10n_util::GetStringUTF16(IDS_SETTING_CHANGE_BUBBLE_MESSAGE);
-}
-
-string16 PrefsBackupInvalidChange::GetApplyButtonText() const {
- // Don't show this button.
- return string16();
-}
-
-string16 PrefsBackupInvalidChange::GetDiscardButtonText() const {
- return l10n_util::GetStringUTF16(IDS_EDIT_SETTINGS);
-}
-
-void PrefsBackupInvalidChange::ApplyDefaults(Profile* profile) {
- PrefService* prefs = profile->GetPrefs();
- SessionStartupPref startup_pref = SessionStartupPref::GetStartupPref(prefs);
- if (startup_pref.type != SessionStartupPref::LAST) {
- // If startup type is LAST, resetting it is dangerous (the whole previous
- // session will be lost).
- prefs->ClearPref(prefs::kRestoreOnStartup);
- startup_pref_reset_ = true;
- }
- prefs->ClearPref(prefs::kHomePageIsNewTabPage);
- prefs->ClearPref(prefs::kHomePage);
- prefs->ClearPref(prefs::kShowHomeButton);
-}
-
-bool PrefsBackupInvalidChange::CanBeMerged() const {
- return false;
-}
-
-BaseSettingChange* CreatePrefsBackupInvalidChange() {
- return new PrefsBackupInvalidChange();
-}
-
-} // namespace protector
diff --git a/chrome/browser/protector/prefs_backup_invalid_change_unittest.cc b/chrome/browser/protector/prefs_backup_invalid_change_unittest.cc
deleted file mode 100644
index e943873..0000000
--- a/chrome/browser/protector/prefs_backup_invalid_change_unittest.cc
+++ /dev/null
@@ -1,77 +0,0 @@
-// Copyright (c) 2012 The Chromium Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-#include "base/memory/scoped_ptr.h"
-#include "chrome/browser/prefs/pref_service.h"
-#include "chrome/browser/prefs/session_startup_pref.h"
-#include "chrome/browser/protector/base_setting_change.h"
-#include "chrome/common/pref_names.h"
-#include "chrome/test/base/testing_profile.h"
-#include "testing/gtest/include/gtest/gtest.h"
-
-#if defined(OS_MACOSX)
-#include "base/mac/mac_util.h"
-#endif
-
-namespace protector {
-
-namespace {
-
-const char kStartupUrl[] = "http://example.com/";
-
-} // namespace
-
-class PrefsBackupInvalidChangeTest : public testing::Test {
- protected:
- virtual void SetUp() OVERRIDE {
- // Make the tests independent of the Mac startup pref migration (see
- // SessionStartupPref::MigrateMacDefaultPrefIfNecessary).
- PrefService* prefs = profile_.GetPrefs();
- prefs->SetString(prefs::kProfileCreatedByVersion, "22.0.0.0.0");
- }
-
- TestingProfile profile_;
-};
-
-// Test that correct default values are applied by Init.
-TEST_F(PrefsBackupInvalidChangeTest, Defaults) {
- SessionStartupPref startup_pref(SessionStartupPref::URLS);
- startup_pref.urls.push_back(GURL(kStartupUrl));
- SessionStartupPref::SetStartupPref(&profile_, startup_pref);
-
- scoped_ptr<BaseSettingChange> change(CreatePrefsBackupInvalidChange());
- change->Init(&profile_);
-
- SessionStartupPref new_startup_pref =
- SessionStartupPref::GetStartupPref(&profile_);
- // Startup type should be reset to default.
- EXPECT_EQ(SessionStartupPref::GetDefaultStartupType(), new_startup_pref.type);
- // Startup URLs should be left unchanged.
- EXPECT_EQ(1UL, new_startup_pref.urls.size());
- EXPECT_EQ(std::string(kStartupUrl), new_startup_pref.urls[0].spec());
- // Homepage prefs are reset to defaults.
- PrefService* prefs = profile_.GetPrefs();
- EXPECT_FALSE(prefs->HasPrefPath(prefs::kHomePageIsNewTabPage));
- EXPECT_FALSE(prefs->HasPrefPath(prefs::kHomePage));
- EXPECT_FALSE(prefs->HasPrefPath(prefs::kShowHomeButton));
-}
-
-// Test that "restore last session" setting is not changed by Init.
-TEST_F(PrefsBackupInvalidChangeTest, DefaultsWithSessionRestore) {
- SessionStartupPref startup_pref(SessionStartupPref::LAST);
- startup_pref.urls.push_back(GURL(kStartupUrl));
- SessionStartupPref::SetStartupPref(&profile_, startup_pref);
-
- scoped_ptr<BaseSettingChange> change(CreatePrefsBackupInvalidChange());
- change->Init(&profile_);
-
- SessionStartupPref new_startup_pref =
- SessionStartupPref::GetStartupPref(&profile_);
- // Both startup type and startup URLs should be left unchanged.
- EXPECT_EQ(SessionStartupPref::LAST, new_startup_pref.type);
- EXPECT_EQ(1UL, new_startup_pref.urls.size());
- EXPECT_EQ(std::string(kStartupUrl), new_startup_pref.urls[0].spec());
-}
-
-} // namespace protector
diff --git a/chrome/browser/protector/protected_prefs_watcher.cc b/chrome/browser/protector/protected_prefs_watcher.cc
deleted file mode 100644
index 4c926db..0000000
--- a/chrome/browser/protector/protected_prefs_watcher.cc
+++ /dev/null
@@ -1,399 +0,0 @@
-// Copyright (c) 2012 The Chromium Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-#include "chrome/browser/protector/protected_prefs_watcher.h"
-
-#include "base/base64.h"
-#include "base/bind.h"
-#include "base/logging.h"
-#include "base/metrics/histogram.h"
-#include "base/stringprintf.h"
-#include "base/values.h"
-#include "chrome/browser/extensions/extension_prefs.h"
-#include "chrome/browser/prefs/pref_service.h"
-#include "chrome/browser/prefs/scoped_user_pref_update.h"
-#include "chrome/browser/prefs/session_startup_pref.h"
-#include "chrome/browser/profiles/profile.h"
-#include "chrome/browser/protector/histograms.h"
-#include "chrome/browser/protector/protector_utils.h"
-#include "chrome/common/chrome_notification_types.h"
-#include "chrome/common/pref_names.h"
-#include "content/public/browser/notification_service.h"
-
-using extensions::ExtensionPrefs;
-
-namespace protector {
-
-namespace {
-
-// Prefix added to names of backup entries.
-const char kBackupPrefsPrefix[] = "backup.";
-
-// Names of prefs that are backed up.
-const char* const kProtectedPrefNames[] = {
- prefs::kHomePage,
- prefs::kHomePageIsNewTabPage,
- prefs::kShowHomeButton,
- prefs::kRestoreOnStartup,
- prefs::kURLsToRestoreOnStartup,
- prefs::kPinnedTabs
-};
-
-// Backup pref names.
-const char kBackupHomePage[] = "backup.homepage";
-const char kBackupHomePageIsNewTabPage[] = "backup.homepage_is_newtabpage";
-const char kBackupShowHomeButton[] = "backup.browser.show_home_button";
-const char kBackupRestoreOnStartup[] = "backup.session.restore_on_startup";
-const char kBackupURLsToRestoreOnStartup[] =
- "backup.session.urls_to_restore_on_startup";
-const char kBackupPinnedTabs[] = "backup.pinned_tabs";
-
-// Special backup entries.
-const char kBackupExtensionsIDs[] = "backup.extensions.ids";
-const char kBackupSignature[] = "backup._signature";
-const char kBackupVersion[] = "backup._version";
-
-// Returns name of the backup entry for pref |pref_name|.
-std::string GetBackupNameFor(const std::string& pref_name) {
- return kBackupPrefsPrefix + pref_name;
-}
-
-// Appends a list of strings to |out|.
-void StringAppendStringList(const base::ListValue* list, std::string* out) {
- for (base::ListValue::const_iterator it = list->begin(); it != list->end();
- ++it) {
- std::string item;
- if (!(*it)->GetAsString(&item))
- NOTREACHED();
- base::StringAppendF(out, "|%s", item.c_str());
- }
-}
-
-// Appends a dictionary with string values to |out|.
-void StringAppendStringDictionary(const base::DictionaryValue* dict,
- std::string* out) {
- for (base::DictionaryValue::Iterator it(*dict); it.HasNext(); it.Advance()) {
- std::string value;
- if (!it.value().GetAsString(&value))
- NOTREACHED();
- base::StringAppendF(out, "|%s|%s", it.key().c_str(), value.c_str());
- }
-}
-
-void StringAppendBoolean(PrefService* prefs,
- const char* path,
- std::string* out) {
- if (prefs->HasPrefPath(path))
- base::StringAppendF(out, "|%d", prefs->GetBoolean(path) ? 1 : 0);
- else
- base::StringAppendF(out, "|");
-}
-
-void StringAppendInteger(PrefService* prefs,
- const char* path,
- std::string* out) {
- if (prefs->HasPrefPath(path))
- base::StringAppendF(out, "|%d", prefs->GetInteger(path));
- else
- base::StringAppendF(out, "|");
-}
-
-} // namespace
-
-// static
-const int ProtectedPrefsWatcher::kCurrentVersionNumber = 4;
-
-ProtectedPrefsWatcher::ProtectedPrefsWatcher(Profile* profile)
- : is_backup_valid_(true),
- profile_(profile) {
- // Perform necessary pref migrations before actually starting to observe
- // pref changes, otherwise the migration would affect the backup data as well.
- EnsurePrefsMigration();
-
- pref_observer_.Init(profile->GetPrefs());
- PrefChangeRegistrar::NamedChangeCallback callback = base::Bind(
- &ProtectedPrefsWatcher::OnPreferenceChanged, base::Unretained(this));
- pref_observer_.Add(prefs::kHomePageIsNewTabPage, callback);
- pref_observer_.Add(prefs::kHomePage, callback);
- pref_observer_.Add(prefs::kShowHomeButton, callback);
- // Session startup.
- pref_observer_.Add(prefs::kRestoreOnStartup, callback);
- pref_observer_.Add(prefs::kURLsToRestoreOnStartup, callback);
- // Pinned tabs.
- pref_observer_.Add(prefs::kPinnedTabs, callback);
- // Extensions.
- pref_observer_.Add(ExtensionPrefs::kExtensionsPref, callback);
-
- UpdateCachedPrefs();
- ValidateBackup();
- VLOG(1) << "Initialized pref watcher";
-}
-
-ProtectedPrefsWatcher::~ProtectedPrefsWatcher() {
-}
-
-// static
-void ProtectedPrefsWatcher::RegisterUserPrefs(PrefService* prefs) {
- prefs->RegisterStringPref(kBackupHomePage, "",
- PrefService::UNSYNCABLE_PREF);
- prefs->RegisterBooleanPref(kBackupHomePageIsNewTabPage, false,
- PrefService::UNSYNCABLE_PREF);
- prefs->RegisterBooleanPref(kBackupShowHomeButton, false,
- PrefService::UNSYNCABLE_PREF);
- prefs->RegisterIntegerPref(kBackupRestoreOnStartup, 0,
- PrefService::UNSYNCABLE_PREF);
- prefs->RegisterListPref(kBackupURLsToRestoreOnStartup,
- PrefService::UNSYNCABLE_PREF);
- prefs->RegisterListPref(kBackupPinnedTabs,
- PrefService::UNSYNCABLE_PREF);
- prefs->RegisterListPref(kBackupExtensionsIDs,
- PrefService::UNSYNCABLE_PREF);
- prefs->RegisterStringPref(kBackupSignature, "",
- PrefService::UNSYNCABLE_PREF);
- prefs->RegisterIntegerPref(kBackupVersion, 1,
- PrefService::UNSYNCABLE_PREF);
-}
-
-bool ProtectedPrefsWatcher::DidPrefChange(const std::string& path) const {
- std::string backup_path = GetBackupNameFor(path);
- PrefService* prefs = profile_->GetPrefs();
- const PrefService::Preference* new_pref = prefs->FindPreference(path.c_str());
- DCHECK(new_pref);
- const PrefService::Preference* backup_pref =
- profile_->GetPrefs()->FindPreference(backup_path.c_str());
- DCHECK(backup_pref);
- if (new_pref->IsDefaultValue())
- return !backup_pref->IsDefaultValue();
- if (!new_pref->IsUserControlled())
- return false;
- return !backup_pref->GetValue()->Equals(new_pref->GetValue());
-}
-
-const base::Value* ProtectedPrefsWatcher::GetBackupForPref(
- const std::string& path) const {
- if (!is_backup_valid_)
- return NULL;
- std::string backup_path = GetBackupNameFor(path);
- // These do not directly correspond to any real preference.
- DCHECK(backup_path != kBackupExtensionsIDs &&
- backup_path != kBackupSignature);
- PrefService* prefs = profile_->GetPrefs();
- // If backup is not set, return the default value of the actual pref.
- // TODO(ivankr): return NULL instead and handle appropriately in SettingChange
- // classes.
- if (!prefs->HasPrefPath(backup_path.c_str()))
- return prefs->GetDefaultPrefValue(path.c_str());
- const PrefService::Preference* backup_pref =
- profile_->GetPrefs()->FindPreference(backup_path.c_str());
- DCHECK(backup_pref);
- return backup_pref->GetValue();
-}
-
-void ProtectedPrefsWatcher::ForceUpdateBackup() {
- UMA_HISTOGRAM_ENUMERATION(
- kProtectorHistogramPrefs,
- kProtectorErrorForcedUpdate,
- kProtectorErrorCount);
- InitBackup();
-}
-
-void ProtectedPrefsWatcher::OnPreferenceChanged(const std::string& pref_name) {
- DCHECK(pref_observer_.IsObserved(pref_name));
- if (UpdateBackupEntry(pref_name))
- UpdateBackupSignature();
-}
-
-void ProtectedPrefsWatcher::EnsurePrefsMigration() {
- SessionStartupPref::MigrateIfNecessary(profile_->GetPrefs());
-}
-
-bool ProtectedPrefsWatcher::UpdateCachedPrefs() {
- // ExtensionService may not yet have been initialized, so using static method
- // exposed for this purpose.
- extensions::ExtensionIdList extension_ids =
- ExtensionPrefs::GetExtensionsFrom(profile_->GetPrefs());
- if (extension_ids == cached_extension_ids_)
- return false;
- cached_extension_ids_.swap(extension_ids);
- return true;
-}
-
-bool ProtectedPrefsWatcher::HasBackup() const {
- // TODO(ivankr): as soon as some irreversible change to Preferences happens,
- // add a condition that this change has occured as well (otherwise it's
- // possible to simply clear the "backup" dictionary to make settings
- // unprotected).
- return profile_->GetPrefs()->HasPrefPath(kBackupSignature);
-}
-
-void ProtectedPrefsWatcher::InitBackup() {
- PrefService* prefs = profile_->GetPrefs();
- for (size_t i = 0; i < arraysize(kProtectedPrefNames); ++i) {
- const base::Value* user_value =
- prefs->GetUserPrefValue(kProtectedPrefNames[i]);
- if (user_value)
- prefs->Set(GetBackupNameFor(kProtectedPrefNames[i]).c_str(), *user_value);
- }
- ListPrefUpdate extension_ids_update(prefs, kBackupExtensionsIDs);
- base::ListValue* extension_ids = extension_ids_update.Get();
- extension_ids->Clear();
- for (extensions::ExtensionIdList::const_iterator it =
- cached_extension_ids_.begin();
- it != cached_extension_ids_.end(); ++it) {
- extension_ids->Append(base::Value::CreateStringValue(*it));
- }
- prefs->SetInteger(kBackupVersion, kCurrentVersionNumber);
- UpdateBackupSignature();
-}
-
-void ProtectedPrefsWatcher::MigrateOldBackupIfNeeded() {
- PrefService* prefs = profile_->GetPrefs();
-
- int current_version = prefs->GetInteger(kBackupVersion);
- VLOG(1) << "Backup version: " << current_version;
- if (current_version == kCurrentVersionNumber)
- return;
-
- switch (current_version) {
- case 1: {
- // Add pinned tabs.
- const base::Value* pinned_tabs =
- prefs->GetUserPrefValue(prefs::kPinnedTabs);
- if (pinned_tabs)
- prefs->Set(kBackupPinnedTabs, *pinned_tabs);
- }
- // FALL THROUGH
-
- case 2:
- // SessionStartupPref migration.
- DCHECK(prefs->GetBoolean(prefs::kRestoreOnStartupMigrated));
- prefs->SetInteger(kBackupRestoreOnStartup,
- prefs->GetInteger(prefs::kRestoreOnStartup));
- prefs->Set(kBackupURLsToRestoreOnStartup,
- *prefs->GetList(prefs::kURLsToRestoreOnStartup));
- // FALL THROUGH
-
- case 3:
- // Reset to default values backup prefs whose actual prefs are not set.
- for (size_t i = 0; i < arraysize(kProtectedPrefNames); ++i) {
- if (!prefs->HasPrefPath(kProtectedPrefNames[i]))
- prefs->ClearPref(GetBackupNameFor(kProtectedPrefNames[i]).c_str());
- }
- // FALL THROUGH
- }
-
- prefs->SetInteger(kBackupVersion, kCurrentVersionNumber);
- UpdateBackupSignature();
-}
-
-bool ProtectedPrefsWatcher::UpdateBackupEntry(const std::string& path) {
- std::string backup_path = GetBackupNameFor(path);
- PrefService* prefs = profile_->GetPrefs();
- const PrefService::Preference* pref = prefs->FindPreference(path.c_str());
- if (path == ExtensionPrefs::kExtensionsPref) {
- // For changes in extension dictionary, do nothing if the IDs list remained
- // the same.
- if (!UpdateCachedPrefs())
- return false;
- ListPrefUpdate extension_ids_update(prefs, kBackupExtensionsIDs);
- base::ListValue* extension_ids = extension_ids_update.Get();
- extension_ids->Clear();
- for (extensions::ExtensionIdList::const_iterator it =
- cached_extension_ids_.begin();
- it != cached_extension_ids_.end(); ++it) {
- extension_ids->Append(base::Value::CreateStringValue(*it));
- }
- } else if (!prefs->HasPrefPath(path.c_str())) {
- // Preference has been removed, remove the backup as well.
- prefs->ClearPref(backup_path.c_str());
- } else if (!pref->IsUserControlled()) {
- return false;
- } else {
- prefs->Set(backup_path.c_str(), *pref->GetValue());
- }
- VLOG(1) << "Updated backup entry for: " << path;
- return true;
-}
-
-void ProtectedPrefsWatcher::UpdateBackupSignature() {
- PrefService* prefs = profile_->GetPrefs();
- std::string signed_data = GetSignatureData(prefs);
- DCHECK(!signed_data.empty());
- std::string signature = SignSetting(signed_data);
- DCHECK(!signature.empty());
- std::string signature_base64;
- if (!base::Base64Encode(signature, &signature_base64))
- NOTREACHED();
- prefs->SetString(kBackupSignature, signature_base64);
- // Schedule disk write on FILE thread as soon as possible.
- prefs->CommitPendingWrite();
- VLOG(1) << "Updated backup signature";
-}
-
-bool ProtectedPrefsWatcher::IsSignatureValid() const {
- DCHECK(HasBackup());
- PrefService* prefs = profile_->GetPrefs();
- std::string signed_data = GetSignatureData(prefs);
- DCHECK(!signed_data.empty());
- std::string signature;
- if (!base::Base64Decode(prefs->GetString(kBackupSignature), &signature))
- return false;
- return IsSettingValid(signed_data, signature);
-}
-
-void ProtectedPrefsWatcher::ValidateBackup() {
- if (!HasBackup()) {
- // Create initial backup entries and sign them.
- InitBackup();
- UMA_HISTOGRAM_ENUMERATION(
- kProtectorHistogramPrefs,
- kProtectorErrorValueValidZero,
- kProtectorErrorCount);
- } else if (IsSignatureValid()) {
- MigrateOldBackupIfNeeded();
- UMA_HISTOGRAM_ENUMERATION(
- kProtectorHistogramPrefs,
- kProtectorErrorValueValid,
- kProtectorErrorCount);
- } else {
- LOG(WARNING) << "Invalid backup signature";
- is_backup_valid_ = false;
- // The whole backup has been compromised, overwrite it.
- InitBackup();
- UMA_HISTOGRAM_ENUMERATION(
- kProtectorHistogramPrefs,
- kProtectorErrorBackupInvalid,
- kProtectorErrorCount);
- }
-}
-
-std::string ProtectedPrefsWatcher::GetSignatureData(PrefService* prefs) const {
- int current_version = prefs->GetInteger(kBackupVersion);
- // TODO(ivankr): replace this with some existing reliable serializer.
- // JSONWriter isn't a good choice because JSON formatting may change suddenly.
- std::string data = prefs->GetString(kBackupHomePage);
- StringAppendBoolean(prefs, kBackupHomePageIsNewTabPage, &data);
- StringAppendBoolean(prefs, kBackupShowHomeButton, &data);
- StringAppendInteger(prefs, kBackupRestoreOnStartup, &data);
- StringAppendStringList(prefs->GetList(kBackupURLsToRestoreOnStartup), &data);
- StringAppendStringList(prefs->GetList(kBackupExtensionsIDs), &data);
- if (current_version >= 2) {
- // Version itself is included only since version 2 since it wasn't there
- // in version 1.
- base::StringAppendF(&data, "|v%d", current_version);
- const base::ListValue* pinned_tabs = prefs->GetList(kBackupPinnedTabs);
- for (base::ListValue::const_iterator it = pinned_tabs->begin();
- it != pinned_tabs->end(); ++it) {
- const base::DictionaryValue* tab = NULL;
- if (!(*it)->GetAsDictionary(&tab)) {
- NOTREACHED();
- continue;
- }
- StringAppendStringDictionary(tab, &data);
- }
- }
- return data;
-}
-
-} // namespace protector
diff --git a/chrome/browser/protector/protected_prefs_watcher.h b/chrome/browser/protector/protected_prefs_watcher.h
deleted file mode 100644
index d6aaf44..0000000
--- a/chrome/browser/protector/protected_prefs_watcher.h
+++ /dev/null
@@ -1,104 +0,0 @@
-// Copyright (c) 2012 The Chromium Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-#ifndef CHROME_BROWSER_PROTECTOR_PROTECTED_PREFS_WATCHER_H_
-#define CHROME_BROWSER_PROTECTOR_PROTECTED_PREFS_WATCHER_H_
-
-#include <string>
-
-#include "base/basictypes.h"
-#include "base/memory/scoped_ptr.h"
-#include "base/prefs/public/pref_change_registrar.h"
-#include "chrome/browser/extensions/extension_prefs.h"
-
-class PrefService;
-class Profile;
-
-namespace base {
-class Value;
-}
-
-namespace protector {
-
-class ProtectedPrefsWatcher {
- public:
- // Current backup version.
- static const int kCurrentVersionNumber;
-
- explicit ProtectedPrefsWatcher(Profile* profile);
- virtual ~ProtectedPrefsWatcher();
-
- // Registers prefs on a new Profile instance.
- static void RegisterUserPrefs(PrefService* prefs);
-
- // Returns true if pref named |path| has changed and the backup is valid.
- bool DidPrefChange(const std::string& path) const;
-
- // Returns the backup value for pref named |path| or |NULL| if the pref is not
- // protected, does not exist or the backup is invalid. The returned Value
- // instance is owned by the PrefService.
- const base::Value* GetBackupForPref(const std::string& path) const;
-
- // Forces a valid backup, matching actual preferences (overwriting any
- // previous data). Should only be when protector service is disabled.
- void ForceUpdateBackup();
-
- // True if the backup was valid at the profile load time.
- bool is_backup_valid() { return is_backup_valid_; }
-
- private:
- friend class ProtectedPrefsWatcherTest;
-
- void OnPreferenceChanged(const std::string& pref_name);
-
- // Makes sure that all protected prefs have been migrated before starting to
- // observe them.
- void EnsurePrefsMigration();
-
- // Updates cached prefs from their actual values and returns |true| if there
- // were any changes.
- bool UpdateCachedPrefs();
-
- // Returns |false| if profile does not have a backup yet (needs to be
- // initialized).
- bool HasBackup() const;
-
- // Creates initial backup entries.
- void InitBackup();
-
- // Migrates backup if it is an older version.
- void MigrateOldBackupIfNeeded();
-
- // Updates the backup entry for |path| and returns |true| if the backup has
- // changed.
- bool UpdateBackupEntry(const std::string& path);
-
- // Perform a check that backup is valid and settings have not been modified.
- void ValidateBackup();
-
- // Returns |true| if backup signature is valid.
- bool IsSignatureValid() const;
-
- // Updates the backup signature.
- void UpdateBackupSignature();
-
- // Returns data to be signed as string.
- std::string GetSignatureData(PrefService* prefs) const;
-
- // Cached set of extension IDs. They are not changed as frequently
- extensions::ExtensionIdList cached_extension_ids_;
-
- PrefChangeRegistrar pref_observer_;
-
- // True if the backup was valid at the profile load time.
- bool is_backup_valid_;
-
- Profile* profile_;
-
- DISALLOW_COPY_AND_ASSIGN(ProtectedPrefsWatcher);
-};
-
-} // namespace protector
-
-#endif // CHROME_BROWSER_PROTECTOR_PROTECTED_PREFS_WATCHER_H_
diff --git a/chrome/browser/protector/protected_prefs_watcher_unittest.cc b/chrome/browser/protector/protected_prefs_watcher_unittest.cc
deleted file mode 100644
index ba7807c..0000000
--- a/chrome/browser/protector/protected_prefs_watcher_unittest.cc
+++ /dev/null
@@ -1,291 +0,0 @@
-// Copyright (c) 2012 The Chromium Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-#include "base/message_loop.h"
-#include "base/values.h"
-#include "chrome/browser/extensions/extension_pref_value_map.h"
-#include "chrome/browser/extensions/extension_pref_value_map_factory.h"
-#include "chrome/browser/extensions/extension_prefs.h"
-#include "chrome/browser/extensions/extension_service.h"
-#include "chrome/browser/prefs/pref_service.h"
-#include "chrome/browser/prefs/scoped_user_pref_update.h"
-#include "chrome/browser/protector/protected_prefs_watcher.h"
-#include "chrome/browser/protector/protector_service_factory.h"
-#include "chrome/browser/protector/protector_service.h"
-#include "chrome/common/extensions/extension_constants.h"
-#include "chrome/common/pref_names.h"
-#include "chrome/test/base/testing_profile.h"
-#include "content/public/test/test_browser_thread.h"
-#include "testing/gtest/include/gtest/gtest.h"
-
-namespace protector {
-
-namespace {
-
-const char kBackupSignature[] = "backup._signature";
-const char kNewHomePage[] = "http://example.com";
-
-}
-
-class ProtectedPrefsWatcherTest : public testing::Test {
- public:
- virtual void SetUp() OVERRIDE {
- prefs_watcher_ =
- ProtectorServiceFactory::GetForProfile(&profile_)->GetPrefsWatcher();
- prefs_ = profile_.GetPrefs();
- }
-
- bool IsSignatureValid() {
- return prefs_watcher_->IsSignatureValid();
- }
-
- bool HasBackup() {
- return prefs_watcher_->HasBackup();
- }
-
- void RevalidateBackup() {
- prefs_watcher_->ValidateBackup();
- }
-
- void ForceUpdateSignature(ProtectedPrefsWatcher* prefs_watcher) {
- prefs_watcher->UpdateBackupSignature();
- }
-
- protected:
- ProtectedPrefsWatcher* prefs_watcher_;
- TestingProfile profile_;
- PrefService* prefs_;
-};
-
-TEST_F(ProtectedPrefsWatcherTest, ValidOnCleanProfile) {
- EXPECT_TRUE(HasBackup());
- EXPECT_TRUE(prefs_watcher_->is_backup_valid());
-}
-
-TEST_F(ProtectedPrefsWatcherTest, ValidAfterPrefChange) {
- // Signature is still valid after a protected pref has been changed.
- base::StringValue new_homepage(kNewHomePage);
- EXPECT_NE(prefs_->GetString(prefs::kHomePage), kNewHomePage);
- EXPECT_FALSE(new_homepage.Equals(
- prefs_watcher_->GetBackupForPref(prefs::kHomePage)));
-
- prefs_->SetString(prefs::kHomePage, kNewHomePage);
-
- EXPECT_TRUE(HasBackup());
- EXPECT_TRUE(prefs_watcher_->is_backup_valid());
- EXPECT_EQ(prefs_->GetString(prefs::kHomePage), kNewHomePage);
- // Backup is updated accordingly.
- EXPECT_TRUE(new_homepage.Equals(
- prefs_watcher_->GetBackupForPref(prefs::kHomePage)));
-}
-
-TEST_F(ProtectedPrefsWatcherTest, InvalidSignature) {
- // Make backup invalid by changing one of its members directly.
- prefs_->SetString("backup.homepage", kNewHomePage);
- RevalidateBackup();
- EXPECT_TRUE(HasBackup());
- EXPECT_FALSE(prefs_watcher_->is_backup_valid());
- // No backup values available.
- EXPECT_FALSE(prefs_watcher_->GetBackupForPref(prefs::kHomePage));
-
- // Now change the corresponding protected prefernce: backup should be signed
- // again but still invalid.
- prefs_->SetString(prefs::kHomePage, kNewHomePage);
- EXPECT_TRUE(IsSignatureValid());
- EXPECT_FALSE(prefs_watcher_->is_backup_valid());
- EXPECT_FALSE(prefs_watcher_->GetBackupForPref(prefs::kHomePage));
-}
-
-TEST_F(ProtectedPrefsWatcherTest, ExtensionPrefChange) {
- // Changes to extensions data (but not to extension IDs) do not update
- // the backup and its signature.
- MessageLoopForUI message_loop;
- content::TestBrowserThread ui_thread(content::BrowserThread::UI,
- &message_loop);
-
- FilePath extensions_install_dir =
- profile_.GetPath().AppendASCII(ExtensionService::kInstallDirectoryName);
- scoped_ptr<extensions::ExtensionPrefs> extension_prefs =
- extensions::ExtensionPrefs::Create(
- profile_.GetPrefs(),
- extensions_install_dir,
- ExtensionPrefValueMapFactory::GetForProfile(&profile_),
- false); // extensions_disabled
- std::string sample_id = extension_misc::kWebStoreAppId;
- // Flip a pref value of an extension (this will actually add it to the list).
- extension_prefs->SetAppNotificationDisabled(
- sample_id, !extension_prefs->IsAppNotificationDisabled(sample_id));
-
- // Backup is still valid.
- EXPECT_TRUE(prefs_watcher_->is_backup_valid());
-
- // Make signature invalid by changing it directly.
- prefs_->SetString(kBackupSignature, "INVALID");
- EXPECT_FALSE(IsSignatureValid());
-
- // Flip another pref value of that extension.
- extension_prefs->SetExtensionRunning(
- sample_id, !extension_prefs->IsExtensionRunning(sample_id));
-
- // No changes to the backup and signature.
- EXPECT_FALSE(IsSignatureValid());
-
- // Blacklisting the extension does update the backup and signature.
- extension_prefs->SetExtensionBlacklisted(sample_id, true);
-
- EXPECT_TRUE(IsSignatureValid());
-}
-
-// Verify that version bigger than 1 is included in the signature.
-TEST_F(ProtectedPrefsWatcherTest, VersionIsSigned) {
- // Reset version to 1.
- prefs_->ClearPref("backup._version");
- // This should make the backup invalid.
- EXPECT_FALSE(IsSignatureValid());
-
- // "Migrate" the backup back to the latest version.
- RevalidateBackup();
-
- EXPECT_FALSE(prefs_watcher_->is_backup_valid());
- EXPECT_EQ(ProtectedPrefsWatcher::kCurrentVersionNumber,
- prefs_->GetInteger("backup._version"));
-}
-
-// Verify that backup for "pinned_tabs" is added during version 2 migration.
-TEST_F(ProtectedPrefsWatcherTest, MigrationToVersion2) {
- // Add a pinned tab.
- {
- ListPrefUpdate pinned_tabs_update(prefs_, prefs::kPinnedTabs);
- base::ListValue* pinned_tabs = pinned_tabs_update.Get();
- pinned_tabs->Clear();
- base::DictionaryValue* tab = new base::DictionaryValue;
- tab->SetString("url", "http://example.com/");
- pinned_tabs->Append(tab);
- }
- EXPECT_TRUE(prefs_watcher_->is_backup_valid());
-
- scoped_ptr<base::Value> pinned_tabs_copy(
- prefs_->GetList(prefs::kPinnedTabs)->DeepCopy());
-
- // Reset version to 1, remove "pinned_tabs" and overwrite the signature.
- // Store the old signature (without "pinned_tabs").
- prefs_->ClearPref("backup._version");
- prefs_->ClearPref("backup.pinned_tabs");
- ForceUpdateSignature(prefs_watcher_);
- EXPECT_TRUE(IsSignatureValid());
-
- // This will migrate backup to the latest version.
- RevalidateBackup();
-
- // Now the backup should be valid and "pinned_tabs" is added back.
- EXPECT_TRUE(prefs_watcher_->is_backup_valid());
- EXPECT_TRUE(pinned_tabs_copy->Equals(prefs_->GetList("backup.pinned_tabs")));
- EXPECT_TRUE(pinned_tabs_copy->Equals(prefs_->GetList(prefs::kPinnedTabs)));
- EXPECT_FALSE(prefs_watcher_->DidPrefChange(prefs::kPinnedTabs));
- EXPECT_EQ(ProtectedPrefsWatcher::kCurrentVersionNumber,
- prefs_->GetInteger("backup._version"));
-}
-
-// Verify that SessionStartupPref migration doesn't trigger Protector
-// (version 3 migration).
-TEST_F(ProtectedPrefsWatcherTest, MigrationToVersion3) {
- EXPECT_TRUE(prefs_watcher_->is_backup_valid());
-
- // Bring startup prefs to an old (pre-migration) version.
- prefs_->SetBoolean(prefs::kHomePageIsNewTabPage, false);
- prefs_->SetString(prefs::kHomePage, kNewHomePage);
- prefs_->ClearPref(prefs::kRestoreOnStartupMigrated);
-
- // Reset version to 2 and overwrite the signature.
- prefs_->SetInteger("backup._version", 2);
- ForceUpdateSignature(prefs_watcher_);
- EXPECT_TRUE(IsSignatureValid());
-
- // Take down the old instance and create a new ProtectedPrefsWatcher from
- // current prefs.
- ProtectorServiceFactory::GetForProfile(&profile_)->
- StopWatchingPrefsForTesting();
- scoped_ptr<ProtectedPrefsWatcher> prefs_watcher2(
- new ProtectedPrefsWatcher(&profile_));
- EXPECT_TRUE(prefs_watcher2->is_backup_valid());
-
- // Startup settings shouldn't be reported as changed.
- EXPECT_FALSE(prefs_watcher2->DidPrefChange(prefs::kRestoreOnStartup));
- EXPECT_FALSE(prefs_watcher2->DidPrefChange(prefs::kURLsToRestoreOnStartup));
- EXPECT_EQ(ProtectedPrefsWatcher::kCurrentVersionNumber,
- prefs_->GetInteger("backup._version"));
-}
-
-// Verify that migration to version 4 removes backups with default values.
-TEST_F(ProtectedPrefsWatcherTest, MigrationToVersion4) {
- EXPECT_TRUE(prefs_watcher_->is_backup_valid());
-
- prefs_->SetString(prefs::kHomePage, kNewHomePage);
- EXPECT_TRUE(prefs_->HasPrefPath("backup.homepage"));
-
- // Reset version to 3 and overwrite the signature.
- prefs_->SetInteger("backup._version", 3);
- ForceUpdateSignature(prefs_watcher_);
- EXPECT_TRUE(IsSignatureValid());
-
- ProtectorServiceFactory::GetForProfile(&profile_)->
- StopWatchingPrefsForTesting();
-
- // Restore |kHomePage| to default value.
- prefs_->ClearPref(prefs::kHomePage);
-
- scoped_ptr<ProtectedPrefsWatcher> prefs_watcher2(
- new ProtectedPrefsWatcher(&profile_));
- EXPECT_TRUE(prefs_watcher2->is_backup_valid());
-
- // Backup for |kHomePage| should now be restored to the default value, too.
- EXPECT_FALSE(prefs_->HasPrefPath("backup.homepage"));
- EXPECT_FALSE(prefs_watcher2->DidPrefChange(prefs::kHomePage));
- EXPECT_EQ(ProtectedPrefsWatcher::kCurrentVersionNumber,
- prefs_->GetInteger("backup._version"));
-}
-
-// Verify handling of default values of protected prefs.
-TEST_F(ProtectedPrefsWatcherTest, DefaultValues) {
- EXPECT_TRUE(prefs_watcher_->is_backup_valid());
-
- EXPECT_FALSE(prefs_->HasPrefPath(prefs::kHomePage));
- EXPECT_FALSE(prefs_watcher_->DidPrefChange(prefs::kHomePage));
- prefs_->SetString(prefs::kHomePage, kNewHomePage);
- EXPECT_FALSE(prefs_watcher_->DidPrefChange(prefs::kHomePage));
-
- ProtectorServiceFactory::GetForProfile(&profile_)->
- StopWatchingPrefsForTesting();
-
- // Restore |kHomePage| to default value.
- prefs_->ClearPref(prefs::kHomePage);
-
- scoped_ptr<ProtectedPrefsWatcher> prefs_watcher2(
- new ProtectedPrefsWatcher(&profile_));
- EXPECT_TRUE(prefs_watcher2->is_backup_valid());
- EXPECT_TRUE(prefs_watcher2->DidPrefChange(prefs::kHomePage));
-
- prefs_->ClearPref("backup.homepage");
- ForceUpdateSignature(prefs_watcher2.get());
-
- EXPECT_TRUE(prefs_watcher2->is_backup_valid());
- EXPECT_FALSE(prefs_watcher2->DidPrefChange(prefs::kHomePage));
-}
-
-TEST_F(ProtectedPrefsWatcherTest, CheckPrefNames) {
- // If any of these preference names change, add corresponding migration code
- // to ProtectedPrefsWatcher.
- // DO NOT simply fix these literals!
- EXPECT_EQ("homepage", std::string(prefs::kHomePage));
- EXPECT_EQ("homepage_is_newtabpage",
- std::string(prefs::kHomePageIsNewTabPage));
- EXPECT_EQ("browser.show_home_button", std::string(prefs::kShowHomeButton));
- EXPECT_EQ("session.restore_on_startup",
- std::string(prefs::kRestoreOnStartup));
- EXPECT_EQ("session.urls_to_restore_on_startup",
- std::string(prefs::kURLsToRestoreOnStartup));
- EXPECT_EQ("pinned_tabs", std::string(prefs::kPinnedTabs));
-}
-
-} // namespace protector
diff --git a/chrome/browser/protector/protector_service.cc b/chrome/browser/protector/protector_service.cc
deleted file mode 100644
index 2a44230..0000000
--- a/chrome/browser/protector/protector_service.cc
+++ /dev/null
@@ -1,236 +0,0 @@
-// Copyright (c) 2012 The Chromium Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-#include "chrome/browser/protector/protector_service.h"
-
-#include "base/logging.h"
-#include "chrome/browser/google/google_util.h"
-#include "chrome/browser/prefs/pref_service.h"
-#include "chrome/browser/protector/composite_settings_change.h"
-#include "chrome/browser/protector/keys.h"
-#include "chrome/browser/protector/protected_prefs_watcher.h"
-#include "chrome/browser/protector/protector_utils.h"
-#include "chrome/browser/protector/settings_change_global_error.h"
-#include "chrome/browser/ui/browser.h"
-#include "chrome/browser/ui/host_desktop.h"
-#include "chrome/browser/ui/singleton_tabs.h"
-#include "chrome/common/chrome_notification_types.h"
-#include "chrome/common/pref_names.h"
-#include "content/public/browser/notification_source.h"
-#include "net/base/registry_controlled_domains/registry_controlled_domain.h"
-
-namespace protector {
-
-namespace {
-
-// Returns true if changes with URLs |url1| and |url2| can be merged.
-bool CanMerge(const GURL& url1, const GURL& url2) {
- VLOG(1) << "Checking if can merge " << url1.spec() << " with " << url2.spec();
- // All Google URLs are considered the same one.
- if (google_util::IsGoogleHostname(url1.host(),
- google_util::DISALLOW_SUBDOMAIN)) {
- return google_util::IsGoogleHostname(url2.host(),
- google_util::DISALLOW_SUBDOMAIN);
- }
- // Otherwise URLs must have the same domain.
- return net::RegistryControlledDomainService::SameDomainOrHost(url1, url2);
-}
-
-} // namespace
-
-ProtectorService::ProtectorService(Profile* profile)
- : profile_(profile),
- has_active_change_(false) {
- // Start observing pref changes.
- prefs_watcher_.reset(new ProtectedPrefsWatcher(profile));
-}
-
-ProtectorService::~ProtectorService() {
- DCHECK(!IsShowingChange()); // Should have been dismissed by Shutdown.
-}
-
-void ProtectorService::ShowChange(BaseSettingChange* change) {
- DCHECK(change);
- // Change instance will either be owned by |this| or deleted after this call.
- scoped_ptr<BaseSettingChange> change_ptr(change);
-
- DVLOG(1) << "Init change";
- if (!protector::IsEnabled()) {
- change_ptr->InitWhenDisabled(profile_);
- return;
- } else if (!change_ptr->Init(profile_)) {
- LOG(WARNING) << "Error while initializing, dismissing change";
- return;
- }
-
- Item* item_to_merge_with = FindItemToMergeWith(change_ptr.get());
- if (item_to_merge_with) {
- // CompositeSettingsChange takes ownership of merged changes.
- BaseSettingChange* existing_change = item_to_merge_with->change.release();
- CompositeSettingsChange* merged_change =
- existing_change->MergeWith(change_ptr.release());
- item_to_merge_with->change.reset(merged_change);
- item_to_merge_with->was_merged = true;
- if (item_to_merge_with->error->GetBubbleView())
- item_to_merge_with->show_when_merged = true;
- // Remove old GlobalError instance. Later in OnRemovedFromProfile() a new
- // GlobalError instance will be created for the composite change.
- item_to_merge_with->error->RemoveFromProfile();
- } else if (change->IsUserVisible()) {
- Item new_item;
- SettingsChangeGlobalError* error =
- new SettingsChangeGlobalError(change_ptr.get(), this);
- new_item.error.reset(error);
- new_item.change.reset(change_ptr.release());
- items_.push_back(new_item);
- // Do not show the bubble immediately if another one is active.
- // TODO(robertshield): Add desktop context to protector, crbug.com/153771
- error->AddToProfile(profile_, !has_active_change_,
- chrome::HOST_DESKTOP_TYPE_NATIVE);
- has_active_change_ = true;
- } else {
- VLOG(1) << "Not showing a change because it's not user-visible.";
- }
-}
-
-bool ProtectorService::IsShowingChange() const {
- return !items_.empty();
-}
-
-void ProtectorService::ApplyChange(BaseSettingChange* change,
- Browser* browser) {
- change->Apply(browser);
- DismissChange(change);
-}
-
-void ProtectorService::DiscardChange(BaseSettingChange* change,
- Browser* browser) {
- change->Discard(browser);
- DismissChange(change);
-}
-
-void ProtectorService::DismissChange(BaseSettingChange* change) {
- Items::iterator item = std::find_if(items_.begin(), items_.end(),
- MatchItemByChange(change));
- DCHECK(item != items_.end());
- item->error->RemoveFromProfile();
-}
-
-void ProtectorService::OpenTab(const GURL& url, Browser* browser) {
- DCHECK(browser);
- chrome::ShowSingletonTab(browser, url);
-}
-
-ProtectedPrefsWatcher* ProtectorService::GetPrefsWatcher() {
- return prefs_watcher_.get();
-}
-
-void ProtectorService::StopWatchingPrefsForTesting() {
- prefs_watcher_.reset();
-}
-
-ProtectorService::Item* ProtectorService::FindItemToMergeWith(
- const BaseSettingChange* change) {
- if (!change->CanBeMerged())
- return NULL;
- GURL url = change->GetNewSettingURL();
- for (Items::iterator item = items_.begin(); item != items_.end(); item++) {
- if (item->change->CanBeMerged() &&
- CanMerge(url, item->change->GetNewSettingURL()))
- return &*item;
- }
- return NULL;
-}
-
-void ProtectorService::Shutdown() {
- while (IsShowingChange())
- items_[0].error->RemoveFromProfile();
-}
-
-void ProtectorService::OnApplyChange(SettingsChangeGlobalError* error,
- Browser* browser) {
- DVLOG(1) << "Apply change";
- error->change()->Apply(browser);
- has_active_change_ = false;
-}
-
-void ProtectorService::OnDiscardChange(SettingsChangeGlobalError* error,
- Browser* browser) {
- DVLOG(1) << "Discard change";
- error->change()->Discard(browser);
- has_active_change_ = false;
-}
-
-void ProtectorService::OnDecisionTimeout(SettingsChangeGlobalError* error) {
- DVLOG(1) << "Timeout";
- error->change()->Timeout();
-}
-
-void ProtectorService::OnRemovedFromProfile(SettingsChangeGlobalError* error) {
- Items::iterator item = std::find_if(items_.begin(), items_.end(),
- MatchItemByError(error));
- DCHECK(item != items_.end());
-
- if (item->was_merged) {
- bool show_new_error = !has_active_change_ || item->show_when_merged;
- item->was_merged = false;
- item->show_when_merged = false;
- // Item was merged with another change instance and error has been removed,
- // create a new one for the composite change.
- item->error.reset(new SettingsChangeGlobalError(item->change.get(), this));
- // TODO(robertshield): Add desktop context to protector, crbug.com/153771
- item->error->AddToProfile(profile_, show_new_error,
- chrome::HOST_DESKTOP_TYPE_NATIVE);
- has_active_change_ = true;
- return;
- }
-
- items_.erase(item);
-
- // If no other change is shown and there are changes that haven't been shown
- // yet, show the first one.
- if (!has_active_change_) {
- for (item = items_.begin(); item != items_.end(); ++item) {
- if (!item->error->HasShownBubbleView()) {
- // TODO(robertshield): Add desktop context to protector,
- // crbug.com/153771
- item->error->ShowBubble(chrome::HOST_DESKTOP_TYPE_NATIVE);
- has_active_change_ = true;
- return;
- }
- }
- }
-}
-
-BaseSettingChange* ProtectorService::GetLastChange() {
- return items_.empty() ? NULL : items_.back().change.get();
-}
-
-ProtectorService::Item::Item()
- : was_merged(false),
- show_when_merged(false) {
-}
-
-ProtectorService::Item::~Item() {
-}
-
-ProtectorService::MatchItemByChange::MatchItemByChange(
- const BaseSettingChange* other) : other_(other) {
-}
-
-bool ProtectorService::MatchItemByChange::operator()(
- const ProtectorService::Item& item) {
- return item.change->Contains(other_);
-}
-
-ProtectorService::MatchItemByError::MatchItemByError(
- const SettingsChangeGlobalError* other) : other_(other) {
-}
-
-bool ProtectorService::MatchItemByError::operator()(
- const ProtectorService::Item& item) {
- return other_ == item.error.get();
-}
-
-} // namespace protector
diff --git a/chrome/browser/protector/protector_service.h b/chrome/browser/protector/protector_service.h
deleted file mode 100644
index 7ad0b1f..0000000
--- a/chrome/browser/protector/protector_service.h
+++ /dev/null
@@ -1,152 +0,0 @@
-// Copyright (c) 2012 The Chromium Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-#ifndef CHROME_BROWSER_PROTECTOR_PROTECTOR_SERVICE_H_
-#define CHROME_BROWSER_PROTECTOR_PROTECTOR_SERVICE_H_
-
-#include <vector>
-
-#include "base/basictypes.h"
-#include "base/compiler_specific.h"
-#include "base/memory/linked_ptr.h"
-#include "base/memory/scoped_ptr.h"
-#include "base/sequenced_task_runner_helpers.h"
-#include "chrome/browser/profiles/profile_keyed_service.h"
-#include "chrome/browser/protector/base_setting_change.h"
-#include "chrome/browser/protector/settings_change_global_error_delegate.h"
-
-class GURL;
-class PrefService;
-class Profile;
-class TemplateURLService;
-
-namespace protector {
-
-class ProtectedPrefsWatcher;
-class SettingsChangeGlobalError;
-
-// Presents a SettingChange to user and handles possible user actions.
-class ProtectorService : public ProfileKeyedService,
- public SettingsChangeGlobalErrorDelegate {
- public:
- explicit ProtectorService(Profile* profile);
- virtual ~ProtectorService();
-
- // Shows global error about the specified change. Owns |change|. May be called
- // multiple times in which case subsequent bubbles will be displayed.
- virtual void ShowChange(BaseSettingChange* change);
-
- // Returns |true| if a change is currently active (shown by a ShowChange call
- // and not yet applied or discarded).
- virtual bool IsShowingChange() const;
-
- // Removes corresponding global error (including the bubbble if one is shown)
- // and deletes the change instance (without calling Apply or Discard on it).
- virtual void DismissChange(BaseSettingChange* change);
-
- // Persists |change| and removes corresponding global error. |browser| is the
- // Browser instance from which the user action originates.
- virtual void ApplyChange(BaseSettingChange* change, Browser* browser);
-
- // Discards |change| and removes corresponding global error. |browser| is the
- // Browser instance from which the user action originates.
- virtual void DiscardChange(BaseSettingChange* change, Browser* browser);
-
- // Opens a tab with specified URL in the browser window we've shown error
- // bubble for.
- virtual void OpenTab(const GURL& url, Browser* browser);
-
- // Returns the ProtectedPrefsWatcher instance for access to protected prefs
- // backup.
- ProtectedPrefsWatcher* GetPrefsWatcher();
-
- // Stops observing pref changes and updating the backup. Should be used in
- // tests only.
- void StopWatchingPrefsForTesting();
-
- // Returns the most recent change instance or NULL if there are no changes.
- BaseSettingChange* GetLastChange();
-
- // Returns the Profile instance for this service.
- Profile* profile() { return profile_; }
-
- private:
- friend class ProtectorServiceTest;
-
- // Each item consists of an error and corresponding change instance.
- // linked_ptr is used because Item instances are stored in a std::vector and
- // must be copyable.
- struct Item {
- Item();
- ~Item();
- linked_ptr<BaseSettingChange> change;
- linked_ptr<SettingsChangeGlobalError> error;
- // When true, this means |change| was merged with another instance and
- // |error| is in process of being removed from GlobalErrorService.
- bool was_merged;
- // Meaningful only when |was_merged| is true. In that case, true means that
- // the new merged GlobalError instance will be immediately shown.
- bool show_when_merged;
- };
-
- typedef std::vector<Item> Items;
-
- // Matches Item by |change| field.
- class MatchItemByChange {
- public:
- explicit MatchItemByChange(const BaseSettingChange* other);
-
- bool operator()(const Item& item);
-
- private:
- const BaseSettingChange* other_;
- };
-
- // Matches Item by |error| field.
- class MatchItemByError {
- public:
- explicit MatchItemByError(const SettingsChangeGlobalError* other);
-
- bool operator()(const Item& item);
-
- private:
- const SettingsChangeGlobalError* other_;
- };
-
- // Returns an Item instance whose change can be merged with |change|, if any.
- // Otherwise returns |NULL|. Provided that the merge strategy is transitive,
- // there can be only one such instance.
- Item* FindItemToMergeWith(const BaseSettingChange* change);
-
- // ProfileKeyedService implementation.
- virtual void Shutdown() OVERRIDE;
-
- // SettingsChangeGlobalErrorDelegate implementation.
- virtual void OnApplyChange(SettingsChangeGlobalError* error,
- Browser* browser) OVERRIDE;
- virtual void OnDiscardChange(SettingsChangeGlobalError* error,
- Browser* browser) OVERRIDE;
- virtual void OnDecisionTimeout(SettingsChangeGlobalError* error) OVERRIDE;
- virtual void OnRemovedFromProfile(SettingsChangeGlobalError* error) OVERRIDE;
-
- // Pointers to error bubble controllers and corresponding changes in the order
- // added.
- Items items_;
-
- // Profile which settings we are protecting.
- Profile* profile_;
-
- // True if there is a change that has been shown and not yet accepted or
- // discarded by user.
- bool has_active_change_;
-
- // Observes changes to protected prefs and updates the backup.
- scoped_ptr<ProtectedPrefsWatcher> prefs_watcher_;
-
- DISALLOW_COPY_AND_ASSIGN(ProtectorService);
-};
-
-} // namespace protector
-
-#endif // CHROME_BROWSER_PROTECTOR_PROTECTOR_SERVICE_H_
diff --git a/chrome/browser/protector/protector_service_browsertest.cc b/chrome/browser/protector/protector_service_browsertest.cc
deleted file mode 100644
index 66669e3..0000000
--- a/chrome/browser/protector/protector_service_browsertest.cc
+++ /dev/null
@@ -1,662 +0,0 @@
-// Copyright (c) 2012 The Chromium Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-#include "base/command_line.h"
-#include "base/memory/scoped_ptr.h"
-#include "base/message_loop.h"
-#include "chrome/app/chrome_command_ids.h"
-#include "chrome/browser/protector/mock_setting_change.h"
-#include "chrome/browser/protector/protector_service.h"
-#include "chrome/browser/protector/protector_service_factory.h"
-#include "chrome/browser/protector/settings_change_global_error.h"
-#include "chrome/browser/ui/browser.h"
-#include "chrome/browser/ui/global_error/global_error.h"
-#include "chrome/browser/ui/global_error/global_error_bubble_view_base.h"
-#include "chrome/browser/ui/global_error/global_error_service.h"
-#include "chrome/browser/ui/global_error/global_error_service_factory.h"
-#include "chrome/common/chrome_switches.h"
-#include "chrome/test/base/in_process_browser_test.h"
-#include "chrome/test/base/ui_test_utils.h"
-
-using ::testing::InvokeWithoutArgs;
-using ::testing::NiceMock;
-using ::testing::Return;
-
-namespace protector {
-
-class ProtectorServiceTest : public InProcessBrowserTest {
- public:
- virtual void SetUpCommandLine(CommandLine* command_line) OVERRIDE {
- // Make sure protector is enabled.
- command_line->AppendSwitch(switches::kProtector);
- }
-
- virtual void SetUpOnMainThread() OVERRIDE {
- protector_service_ =
- ProtectorServiceFactory::GetForProfile(browser()->profile());
- // ProtectService will own this change instance.
- mock_change_ = new NiceMock<MockSettingChange>();
- }
-
- protected:
- GlobalError* GetGlobalError(BaseSettingChange* change) {
- for (ProtectorService::Items::iterator item =
- protector_service_->items_.begin();
- item != protector_service_->items_.end(); item++) {
- if (item->change.get() == change)
- return item->error.get();
- }
- return NULL;
- }
-
- // Checks that |protector_service_| has an error instance corresponding to
- // |change| and that GlobalErrorService knows about it.
- bool IsGlobalErrorActive(BaseSettingChange* change) {
- GlobalError* error = GetGlobalError(change);
- if (!error)
- return false;
- if (!GlobalErrorServiceFactory::GetForProfile(browser()->profile())->
- GetGlobalErrorByMenuItemCommandID(error->MenuItemCommandID())) {
- return false;
- }
- return protector_service_->IsShowingChange();
- }
-
- ProtectorService* protector_service_;
- MockSettingChange* mock_change_;
-};
-
-IN_PROC_BROWSER_TEST_F(ProtectorServiceTest, ChangeInitError) {
- // Init fails and causes the change to be ignored.
- EXPECT_CALL(*mock_change_, MockInit(browser()->profile())).
- WillOnce(Return(false));
- protector_service_->ShowChange(mock_change_);
- EXPECT_FALSE(IsGlobalErrorActive(mock_change_));
- content::RunAllPendingInMessageLoop();
- EXPECT_FALSE(IsGlobalErrorActive(mock_change_));
- EXPECT_FALSE(protector_service_->GetLastChange());
-}
-
-IN_PROC_BROWSER_TEST_F(ProtectorServiceTest, ShowAndDismiss) {
- // Show the change and immediately dismiss it.
- EXPECT_CALL(*mock_change_, MockInit(browser()->profile())).
- WillOnce(Return(true));
- protector_service_->ShowChange(mock_change_);
- content::RunAllPendingInMessageLoop();
- EXPECT_TRUE(IsGlobalErrorActive(mock_change_));
- EXPECT_EQ(mock_change_, protector_service_->GetLastChange());
- protector_service_->DismissChange(mock_change_);
- content::RunAllPendingInMessageLoop();
- EXPECT_FALSE(IsGlobalErrorActive(mock_change_));
- EXPECT_FALSE(protector_service_->GetLastChange());
-}
-
-IN_PROC_BROWSER_TEST_F(ProtectorServiceTest, ShowAndApply) {
- // Show the change and apply it.
- EXPECT_CALL(*mock_change_, MockInit(browser()->profile())).
- WillOnce(Return(true));
- protector_service_->ShowChange(mock_change_);
- content::RunAllPendingInMessageLoop();
- EXPECT_TRUE(IsGlobalErrorActive(mock_change_));
- EXPECT_CALL(*mock_change_, Apply(browser()));
- protector_service_->ApplyChange(mock_change_, browser());
- content::RunAllPendingInMessageLoop();
- EXPECT_FALSE(IsGlobalErrorActive(mock_change_));
-}
-
-// ProtectorServiceTest.ShowAndApplyManually is timing out frequently on Win
-// bots. http://crbug.com/130590
-#if defined(OS_WIN)
-#define MAYBE_ShowAndApplyManually DISABLED_ShowAndApplyManually
-#else
-#define MAYBE_ShowAndApplyManually ShowAndApplyManually
-#endif
-
-IN_PROC_BROWSER_TEST_F(ProtectorServiceTest, MAYBE_ShowAndApplyManually) {
- // Show the change and apply it, mimicking a button click.
- EXPECT_CALL(*mock_change_, MockInit(browser()->profile())).
- WillOnce(Return(true));
- protector_service_->ShowChange(mock_change_);
- content::RunAllPendingInMessageLoop();
- EXPECT_TRUE(IsGlobalErrorActive(mock_change_));
- EXPECT_CALL(*mock_change_, Apply(browser()));
- // Pressing Cancel applies the change.
- GlobalError* error = GetGlobalError(mock_change_);
- ASSERT_TRUE(error);
- error->BubbleViewCancelButtonPressed(browser());
- error->GetBubbleView()->CloseBubbleView();
- content::RunAllPendingInMessageLoop();
- EXPECT_FALSE(IsGlobalErrorActive(mock_change_));
-}
-
-IN_PROC_BROWSER_TEST_F(ProtectorServiceTest, ShowAndDiscard) {
- // Show the change and discard it.
- EXPECT_CALL(*mock_change_, MockInit(browser()->profile())).
- WillOnce(Return(true));
- protector_service_->ShowChange(mock_change_);
- content::RunAllPendingInMessageLoop();
- EXPECT_TRUE(IsGlobalErrorActive(mock_change_));
- EXPECT_CALL(*mock_change_, Discard(browser()));
- protector_service_->DiscardChange(mock_change_, browser());
- content::RunAllPendingInMessageLoop();
- EXPECT_FALSE(IsGlobalErrorActive(mock_change_));
-}
-
-#if defined(OS_WIN)
-// http://crbug.com/141916
-#define MAYBE_ShowAndDiscardManually FLAKY_ShowAndDiscardManually
-#else
-#define MAYBE_ShowAndDiscardManually ShowAndDiscardManually
-#endif
-IN_PROC_BROWSER_TEST_F(ProtectorServiceTest, MAYBE_ShowAndDiscardManually) {
- // Show the change and discard it, mimicking a button click.
- EXPECT_CALL(*mock_change_, MockInit(browser()->profile())).
- WillOnce(Return(true));
- protector_service_->ShowChange(mock_change_);
- content::RunAllPendingInMessageLoop();
- EXPECT_TRUE(IsGlobalErrorActive(mock_change_));
- EXPECT_CALL(*mock_change_, Discard(browser()));
- // Pressing Apply discards the change.
- GlobalError* error = GetGlobalError(mock_change_);
- ASSERT_TRUE(error);
- error->BubbleViewAcceptButtonPressed(browser());
- error->GetBubbleView()->CloseBubbleView();
- content::RunAllPendingInMessageLoop();
- EXPECT_FALSE(IsGlobalErrorActive(mock_change_));
-}
-
-IN_PROC_BROWSER_TEST_F(ProtectorServiceTest, BubbleClosedInsideApply) {
- EXPECT_CALL(*mock_change_, MockInit(browser()->profile())).
- WillOnce(Return(true));
- protector_service_->ShowChange(mock_change_);
- content::RunAllPendingInMessageLoop();
- EXPECT_TRUE(IsGlobalErrorActive(mock_change_));
-
- GlobalError* error = GetGlobalError(mock_change_);
- ASSERT_TRUE(error);
- GlobalErrorBubbleViewBase* bubble_view = error->GetBubbleView();
- ASSERT_TRUE(bubble_view);
- EXPECT_CALL(*mock_change_, Apply(browser())).WillOnce(InvokeWithoutArgs(
- bubble_view, &GlobalErrorBubbleViewBase::CloseBubbleView));
- // Pressing Cancel applies the change.
- error->BubbleViewCancelButtonPressed(browser());
- content::RunAllPendingInMessageLoop();
- EXPECT_FALSE(IsGlobalErrorActive(mock_change_));
-}
-
-IN_PROC_BROWSER_TEST_F(ProtectorServiceTest, ShowMultipleChangesAndApply) {
- // Show the first change.
- EXPECT_CALL(*mock_change_, MockInit(browser()->profile())).
- WillOnce(Return(true));
- protector_service_->ShowChange(mock_change_);
- content::RunAllPendingInMessageLoop();
- EXPECT_TRUE(IsGlobalErrorActive(mock_change_));
- EXPECT_EQ(mock_change_, protector_service_->GetLastChange());
-
- // ProtectService will own this change instance as well.
- MockSettingChange* mock_change2 = new NiceMock<MockSettingChange>();
- // Show the second change.
- EXPECT_CALL(*mock_change2, MockInit(browser()->profile())).
- WillOnce(Return(true));
- EXPECT_CALL(*mock_change2, CanBeMerged()).WillRepeatedly(Return(false));
- protector_service_->ShowChange(mock_change2);
- content::RunAllPendingInMessageLoop();
- EXPECT_TRUE(IsGlobalErrorActive(mock_change_));
- EXPECT_TRUE(IsGlobalErrorActive(mock_change2));
- EXPECT_EQ(mock_change2, protector_service_->GetLastChange());
-
- // Apply the first change, the second should still be active.
- EXPECT_CALL(*mock_change_, Apply(browser()));
- protector_service_->ApplyChange(mock_change_, browser());
- content::RunAllPendingInMessageLoop();
- EXPECT_FALSE(IsGlobalErrorActive(mock_change_));
- EXPECT_TRUE(IsGlobalErrorActive(mock_change2));
- EXPECT_EQ(mock_change2, protector_service_->GetLastChange());
-
- // Finally apply the second change.
- EXPECT_CALL(*mock_change2, Apply(browser()));
- protector_service_->ApplyChange(mock_change2, browser());
- content::RunAllPendingInMessageLoop();
- EXPECT_FALSE(IsGlobalErrorActive(mock_change_));
- EXPECT_FALSE(IsGlobalErrorActive(mock_change2));
- EXPECT_FALSE(protector_service_->GetLastChange());
-}
-
-IN_PROC_BROWSER_TEST_F(ProtectorServiceTest,
- ShowMultipleChangesDismissAndApply) {
- // Show the first change.
- EXPECT_CALL(*mock_change_, MockInit(browser()->profile())).
- WillOnce(Return(true));
- protector_service_->ShowChange(mock_change_);
- content::RunAllPendingInMessageLoop();
- EXPECT_TRUE(IsGlobalErrorActive(mock_change_));
-
- // ProtectService will own this change instance as well.
- MockSettingChange* mock_change2 = new NiceMock<MockSettingChange>();
- // Show the second change.
- EXPECT_CALL(*mock_change2, MockInit(browser()->profile())).
- WillOnce(Return(true));
- EXPECT_CALL(*mock_change2, CanBeMerged()).WillRepeatedly(Return(false));
- protector_service_->ShowChange(mock_change2);
- content::RunAllPendingInMessageLoop();
- EXPECT_TRUE(IsGlobalErrorActive(mock_change_));
- EXPECT_TRUE(IsGlobalErrorActive(mock_change2));
-
- // Dismiss the first change, the second should still be active.
- protector_service_->DismissChange(mock_change_);
- content::RunAllPendingInMessageLoop();
- EXPECT_FALSE(IsGlobalErrorActive(mock_change_));
- EXPECT_TRUE(IsGlobalErrorActive(mock_change2));
-
- // Finally apply the second change.
- EXPECT_CALL(*mock_change2, Apply(browser()));
- protector_service_->ApplyChange(mock_change2, browser());
- content::RunAllPendingInMessageLoop();
- EXPECT_FALSE(IsGlobalErrorActive(mock_change_));
- EXPECT_FALSE(IsGlobalErrorActive(mock_change2));
-}
-
-IN_PROC_BROWSER_TEST_F(ProtectorServiceTest,
- ShowMultipleChangesAndApplyManually) {
- // Show the first change.
- EXPECT_CALL(*mock_change_, MockInit(browser()->profile())).
- WillOnce(Return(true));
- protector_service_->ShowChange(mock_change_);
- content::RunAllPendingInMessageLoop();
- EXPECT_TRUE(IsGlobalErrorActive(mock_change_));
-
- // The first bubble view has been displayed.
- GlobalError* error = GetGlobalError(mock_change_);
- ASSERT_TRUE(error);
- ASSERT_TRUE(error->HasShownBubbleView());
-
- // ProtectService will own this change instance as well.
- MockSettingChange* mock_change2 = new NiceMock<MockSettingChange>();
- // Show the second change.
- EXPECT_CALL(*mock_change2, MockInit(browser()->profile())).
- WillOnce(Return(true));
- EXPECT_CALL(*mock_change2, CanBeMerged()).WillRepeatedly(Return(false));
- protector_service_->ShowChange(mock_change2);
- content::RunAllPendingInMessageLoop();
- EXPECT_TRUE(IsGlobalErrorActive(mock_change_));
- EXPECT_TRUE(IsGlobalErrorActive(mock_change2));
-
- // The second bubble view hasn't been displayed because the first is still
- // shown.
- GlobalError* error2 = GetGlobalError(mock_change2);
- ASSERT_TRUE(error2);
- EXPECT_FALSE(error2->HasShownBubbleView());
-
- // Apply the first change, mimicking a button click; the second should still
- // be active.
- EXPECT_CALL(*mock_change_, Apply(browser()));
- error->BubbleViewCancelButtonPressed(browser());
- error->GetBubbleView()->CloseBubbleView();
- content::RunAllPendingInMessageLoop();
- EXPECT_FALSE(IsGlobalErrorActive(mock_change_));
- EXPECT_TRUE(IsGlobalErrorActive(mock_change2));
-
- // Now the second bubble view should be shown.
- ASSERT_TRUE(error2->HasShownBubbleView());
-
- // Finally apply the second change.
- EXPECT_CALL(*mock_change2, Apply(browser()));
- error2->BubbleViewCancelButtonPressed(browser());
- error2->GetBubbleView()->CloseBubbleView();
- content::RunAllPendingInMessageLoop();
- EXPECT_FALSE(IsGlobalErrorActive(mock_change_));
- EXPECT_FALSE(IsGlobalErrorActive(mock_change2));
-}
-
-IN_PROC_BROWSER_TEST_F(ProtectorServiceTest,
- ShowMultipleChangesAndApplyManuallyBeforeOther) {
- // Show the first change.
- EXPECT_CALL(*mock_change_, MockInit(browser()->profile())).
- WillOnce(Return(true));
- protector_service_->ShowChange(mock_change_);
- content::RunAllPendingInMessageLoop();
- EXPECT_TRUE(IsGlobalErrorActive(mock_change_));
-
- // The first bubble view has been displayed.
- GlobalError* error = GetGlobalError(mock_change_);
- ASSERT_TRUE(error);
- ASSERT_TRUE(error->HasShownBubbleView());
-
- // Apply the first change, mimicking a button click.
- EXPECT_CALL(*mock_change_, Apply(browser()));
- error->BubbleViewCancelButtonPressed(browser());
- error->GetBubbleView()->CloseBubbleView();
- content::RunAllPendingInMessageLoop();
- EXPECT_FALSE(IsGlobalErrorActive(mock_change_));
-
- // ProtectService will own this change instance as well.
- MockSettingChange* mock_change2 = new NiceMock<MockSettingChange>();
- // Show the second change.
- EXPECT_CALL(*mock_change2, MockInit(browser()->profile())).
- WillOnce(Return(true));
- EXPECT_CALL(*mock_change2, CanBeMerged()).WillRepeatedly(Return(false));
- protector_service_->ShowChange(mock_change2);
- content::RunAllPendingInMessageLoop();
- EXPECT_TRUE(IsGlobalErrorActive(mock_change2));
-
- // The second bubble view has been displayed.
- GlobalError* error2 = GetGlobalError(mock_change2);
- ASSERT_TRUE(error2);
- ASSERT_TRUE(error2->HasShownBubbleView());
-
- // Finally apply the second change.
- EXPECT_CALL(*mock_change2, Apply(browser()));
- error2->BubbleViewCancelButtonPressed(browser());
- error2->GetBubbleView()->CloseBubbleView();
- content::RunAllPendingInMessageLoop();
- EXPECT_FALSE(IsGlobalErrorActive(mock_change2));
-}
-
-IN_PROC_BROWSER_TEST_F(ProtectorServiceTest, ShowMultipleDifferentURLs) {
- GURL url1("http://example.com/");
- GURL url2("http://example.net/");
-
- // Show the first change with some non-empty URL.
- EXPECT_CALL(*mock_change_, MockInit(browser()->profile())).
- WillOnce(Return(true));
- EXPECT_CALL(*mock_change_, GetNewSettingURL()).WillRepeatedly(Return(url1));
- EXPECT_CALL(*mock_change_, CanBeMerged()).WillRepeatedly(Return(true));
- protector_service_->ShowChange(mock_change_);
- content::RunAllPendingInMessageLoop();
- EXPECT_TRUE(IsGlobalErrorActive(mock_change_));
- EXPECT_EQ(mock_change_, protector_service_->GetLastChange());
-
- // ProtectService will own this change instance as well.
- MockSettingChange* mock_change2 = new NiceMock<MockSettingChange>();
- // Show the second change with another non-empty URL.
- EXPECT_CALL(*mock_change2, MockInit(browser()->profile())).
- WillOnce(Return(true));
- EXPECT_CALL(*mock_change2, GetNewSettingURL()).WillRepeatedly(Return(url2));
- EXPECT_CALL(*mock_change2, CanBeMerged()).WillRepeatedly(Return(true));
- protector_service_->ShowChange(mock_change2);
- content::RunAllPendingInMessageLoop();
-
- // Both changes are shown separately, not composited.
- EXPECT_TRUE(IsGlobalErrorActive(mock_change_));
- EXPECT_TRUE(IsGlobalErrorActive(mock_change2));
- EXPECT_EQ(mock_change2, protector_service_->GetLastChange());
-
- protector_service_->DismissChange(mock_change_);
- protector_service_->DismissChange(mock_change2);
- content::RunAllPendingInMessageLoop();
- EXPECT_FALSE(protector_service_->GetLastChange());
-}
-
-IN_PROC_BROWSER_TEST_F(ProtectorServiceTest, ShowCompositeAndDismiss) {
- GURL url1("http://example.com/");
-
- // Show the first change.
- EXPECT_CALL(*mock_change_, MockInit(browser()->profile())).
- WillOnce(Return(true));
- EXPECT_CALL(*mock_change_, GetNewSettingURL()).WillRepeatedly(Return(url1));
- EXPECT_CALL(*mock_change_, CanBeMerged()).WillRepeatedly(Return(true));
- protector_service_->ShowChange(mock_change_);
- content::RunAllPendingInMessageLoop();
- EXPECT_TRUE(IsGlobalErrorActive(mock_change_));
- EXPECT_EQ(mock_change_, protector_service_->GetLastChange());
-
- // The first bubble view has been displayed.
- GlobalError* error = GetGlobalError(mock_change_);
- ASSERT_TRUE(error);
- EXPECT_TRUE(error->HasShownBubbleView());
-
- // ProtectService will own this change instance as well.
- MockSettingChange* mock_change2 = new NiceMock<MockSettingChange>();
- // Show the second change.
- EXPECT_CALL(*mock_change2, MockInit(browser()->profile())).
- WillOnce(Return(true));
- EXPECT_CALL(*mock_change2, GetNewSettingURL()).WillRepeatedly(Return(url1));
- EXPECT_CALL(*mock_change2, CanBeMerged()).WillRepeatedly(Return(true));
- protector_service_->ShowChange(mock_change2);
- content::RunAllPendingInMessageLoop();
-
- // Now ProtectorService should be showing a single composite change.
- EXPECT_FALSE(IsGlobalErrorActive(mock_change_));
- EXPECT_FALSE(IsGlobalErrorActive(mock_change2));
-
- BaseSettingChange* composite_change = protector_service_->GetLastChange();
- ASSERT_TRUE(composite_change);
- EXPECT_TRUE(IsGlobalErrorActive(composite_change));
-
- // The second (composite) bubble view has been displayed.
- GlobalError* error2 = GetGlobalError(composite_change);
- ASSERT_TRUE(error2);
- EXPECT_TRUE(error2->HasShownBubbleView());
-
- protector_service_->DismissChange(composite_change);
- content::RunAllPendingInMessageLoop();
- EXPECT_FALSE(IsGlobalErrorActive(composite_change));
- EXPECT_FALSE(protector_service_->GetLastChange());
-
- // Show the third change.
- MockSettingChange* mock_change3 = new NiceMock<MockSettingChange>();
- EXPECT_CALL(*mock_change3, MockInit(browser()->profile())).
- WillOnce(Return(true));
- EXPECT_CALL(*mock_change3, GetNewSettingURL()).WillRepeatedly(Return(url1));
- EXPECT_CALL(*mock_change3, CanBeMerged()).WillRepeatedly(Return(true));
- protector_service_->ShowChange(mock_change3);
- content::RunAllPendingInMessageLoop();
-
- // The third change should not be composed with the previous.
- EXPECT_TRUE(IsGlobalErrorActive(mock_change3));
- EXPECT_EQ(mock_change3, protector_service_->GetLastChange());
-
- protector_service_->DismissChange(mock_change3);
- content::RunAllPendingInMessageLoop();
- EXPECT_FALSE(IsGlobalErrorActive(mock_change3));
- EXPECT_FALSE(protector_service_->GetLastChange());
-}
-
-IN_PROC_BROWSER_TEST_F(ProtectorServiceTest, ShowCompositeAndOther) {
- GURL url1("http://example.com/");
- GURL url2("http://example.net/");
-
- // Show the first change.
- EXPECT_CALL(*mock_change_, MockInit(browser()->profile())).
- WillOnce(Return(true));
- EXPECT_CALL(*mock_change_, GetNewSettingURL()).WillRepeatedly(Return(url1));
- EXPECT_CALL(*mock_change_, CanBeMerged()).WillRepeatedly(Return(true));
- protector_service_->ShowChange(mock_change_);
- content::RunAllPendingInMessageLoop();
- EXPECT_TRUE(IsGlobalErrorActive(mock_change_));
- EXPECT_EQ(mock_change_, protector_service_->GetLastChange());
-
- // ProtectService will own this change instance as well.
- MockSettingChange* mock_change2 = new NiceMock<MockSettingChange>();
- // Show the second change.
- EXPECT_CALL(*mock_change2, MockInit(browser()->profile())).
- WillOnce(Return(true));
- EXPECT_CALL(*mock_change2, GetNewSettingURL()).WillRepeatedly(Return(url1));
- EXPECT_CALL(*mock_change2, CanBeMerged()).WillRepeatedly(Return(true));
- protector_service_->ShowChange(mock_change2);
- content::RunAllPendingInMessageLoop();
-
- // Now ProtectorService should be showing a single composite change.
- BaseSettingChange* composite_change = protector_service_->GetLastChange();
- ASSERT_TRUE(composite_change);
- EXPECT_TRUE(IsGlobalErrorActive(composite_change));
-
- // Show the third change, with the same URL as 1st and 2nd.
- MockSettingChange* mock_change3 = new NiceMock<MockSettingChange>();
- EXPECT_CALL(*mock_change3, MockInit(browser()->profile())).
- WillOnce(Return(true));
- EXPECT_CALL(*mock_change3, GetNewSettingURL()).WillRepeatedly(Return(url1));
- EXPECT_CALL(*mock_change3, CanBeMerged()).WillRepeatedly(Return(true));
- protector_service_->ShowChange(mock_change3);
- content::RunAllPendingInMessageLoop();
-
- // The third change should be composed with the previous.
- EXPECT_FALSE(IsGlobalErrorActive(mock_change3));
- EXPECT_EQ(composite_change, protector_service_->GetLastChange());
- EXPECT_TRUE(IsGlobalErrorActive(composite_change));
-
- // Show the 4th change, now with a different URL.
- MockSettingChange* mock_change4 = new NiceMock<MockSettingChange>();
- EXPECT_CALL(*mock_change4, MockInit(browser()->profile())).
- WillOnce(Return(true));
- EXPECT_CALL(*mock_change4, GetNewSettingURL()).WillRepeatedly(Return(url2));
- EXPECT_CALL(*mock_change4, CanBeMerged()).WillRepeatedly(Return(true));
- protector_service_->ShowChange(mock_change4);
- content::RunAllPendingInMessageLoop();
-
- // The 4th change is shown independently.
- EXPECT_TRUE(IsGlobalErrorActive(composite_change));
- EXPECT_TRUE(IsGlobalErrorActive(mock_change4));
- EXPECT_EQ(mock_change4, protector_service_->GetLastChange());
-
- protector_service_->DismissChange(composite_change);
- protector_service_->DismissChange(mock_change4);
- content::RunAllPendingInMessageLoop();
- EXPECT_FALSE(IsGlobalErrorActive(composite_change));
- EXPECT_FALSE(IsGlobalErrorActive(mock_change4));
- EXPECT_FALSE(protector_service_->GetLastChange());
-}
-
-IN_PROC_BROWSER_TEST_F(ProtectorServiceTest, ShowCompositeAndDismissSingle) {
- GURL url1("http://example.com/");
- GURL url2("http://example.net/");
-
- // Show the first change.
- EXPECT_CALL(*mock_change_, MockInit(browser()->profile())).
- WillOnce(Return(true));
- EXPECT_CALL(*mock_change_, GetNewSettingURL()).WillRepeatedly(Return(url1));
- EXPECT_CALL(*mock_change_, CanBeMerged()).WillRepeatedly(Return(true));
- protector_service_->ShowChange(mock_change_);
- content::RunAllPendingInMessageLoop();
- EXPECT_TRUE(IsGlobalErrorActive(mock_change_));
- EXPECT_EQ(mock_change_, protector_service_->GetLastChange());
-
- // ProtectService will own this change instance as well.
- MockSettingChange* mock_change2 = new NiceMock<MockSettingChange>();
- // Show the second change.
- EXPECT_CALL(*mock_change2, MockInit(browser()->profile())).
- WillOnce(Return(true));
- EXPECT_CALL(*mock_change2, GetNewSettingURL()).WillRepeatedly(Return(url1));
- EXPECT_CALL(*mock_change2, CanBeMerged()).WillRepeatedly(Return(true));
- protector_service_->ShowChange(mock_change2);
- content::RunAllPendingInMessageLoop();
-
- // Now ProtectorService should be showing a single composite change.
- EXPECT_FALSE(IsGlobalErrorActive(mock_change_));
- EXPECT_FALSE(IsGlobalErrorActive(mock_change2));
-
- BaseSettingChange* composite_change = protector_service_->GetLastChange();
- ASSERT_TRUE(composite_change);
- EXPECT_TRUE(IsGlobalErrorActive(composite_change));
-
- // Show the third change with a different URL.
- MockSettingChange* mock_change3 = new NiceMock<MockSettingChange>();
- EXPECT_CALL(*mock_change3, MockInit(browser()->profile())).
- WillOnce(Return(true));
- EXPECT_CALL(*mock_change3, GetNewSettingURL()).WillRepeatedly(Return(url2));
- EXPECT_CALL(*mock_change3, CanBeMerged()).WillRepeatedly(Return(true));
- protector_service_->ShowChange(mock_change3);
- content::RunAllPendingInMessageLoop();
-
- // The third change should not be composed with the previous.
- EXPECT_TRUE(IsGlobalErrorActive(mock_change3));
- EXPECT_TRUE(IsGlobalErrorActive(composite_change));
- EXPECT_EQ(mock_change3, protector_service_->GetLastChange());
-
- // Now dismiss the first change.
- protector_service_->DismissChange(mock_change_);
- content::RunAllPendingInMessageLoop();
-
- // This should effectively dismiss the whole composite change.
- EXPECT_FALSE(IsGlobalErrorActive(composite_change));
- EXPECT_TRUE(IsGlobalErrorActive(mock_change3));
- EXPECT_EQ(mock_change3, protector_service_->GetLastChange());
-
- protector_service_->DismissChange(mock_change3);
- content::RunAllPendingInMessageLoop();
- EXPECT_FALSE(IsGlobalErrorActive(mock_change3));
- EXPECT_FALSE(protector_service_->GetLastChange());
-}
-
-// Verifies that changes with different URLs but same domain are merged.
-IN_PROC_BROWSER_TEST_F(ProtectorServiceTest, SameDomainDifferentURLs) {
- GURL url1("http://www.example.com/abc");
- GURL url2("http://example.com/def");
-
- // Show the first change with some non-empty URL.
- EXPECT_CALL(*mock_change_, MockInit(browser()->profile())).
- WillOnce(Return(true));
- EXPECT_CALL(*mock_change_, GetNewSettingURL()).WillRepeatedly(Return(url1));
- EXPECT_CALL(*mock_change_, CanBeMerged()).WillRepeatedly(Return(true));
- protector_service_->ShowChange(mock_change_);
- content::RunAllPendingInMessageLoop();
- EXPECT_TRUE(IsGlobalErrorActive(mock_change_));
- EXPECT_EQ(mock_change_, protector_service_->GetLastChange());
-
- // ProtectService will own this change instance as well.
- MockSettingChange* mock_change2 = new NiceMock<MockSettingChange>();
- // Show the second change with another non-empty URL having same domain.
- EXPECT_CALL(*mock_change2, MockInit(browser()->profile())).
- WillOnce(Return(true));
- EXPECT_CALL(*mock_change2, GetNewSettingURL()).WillRepeatedly(Return(url2));
- EXPECT_CALL(*mock_change2, CanBeMerged()).WillRepeatedly(Return(true));
- protector_service_->ShowChange(mock_change2);
- content::RunAllPendingInMessageLoop();
-
- // Changes should be merged.
- EXPECT_FALSE(IsGlobalErrorActive(mock_change_));
- EXPECT_FALSE(IsGlobalErrorActive(mock_change2));
-
- BaseSettingChange* composite_change = protector_service_->GetLastChange();
- ASSERT_TRUE(composite_change);
- EXPECT_TRUE(IsGlobalErrorActive(composite_change));
-
- protector_service_->DismissChange(composite_change);
- content::RunAllPendingInMessageLoop();
- EXPECT_FALSE(IsGlobalErrorActive(composite_change));
- EXPECT_FALSE(protector_service_->GetLastChange());
-}
-
-// Verifies that changes with different Google URLs are merged.
-IN_PROC_BROWSER_TEST_F(ProtectorServiceTest, DifferentGoogleDomains) {
- GURL url1("http://www.google.com/search?q=");
- GURL url2("http://google.ru/search?q=");
-
- // Show the first change with some non-empty URL.
- EXPECT_CALL(*mock_change_, MockInit(browser()->profile())).
- WillOnce(Return(true));
- EXPECT_CALL(*mock_change_, GetNewSettingURL()).WillRepeatedly(Return(url1));
- EXPECT_CALL(*mock_change_, CanBeMerged()).WillRepeatedly(Return(true));
- protector_service_->ShowChange(mock_change_);
- content::RunAllPendingInMessageLoop();
- EXPECT_TRUE(IsGlobalErrorActive(mock_change_));
- EXPECT_EQ(mock_change_, protector_service_->GetLastChange());
-
- // ProtectService will own this change instance as well.
- MockSettingChange* mock_change2 = new NiceMock<MockSettingChange>();
- // Show the second change with another non-empty URL having same domain.
- EXPECT_CALL(*mock_change2, MockInit(browser()->profile())).
- WillOnce(Return(true));
- EXPECT_CALL(*mock_change2, GetNewSettingURL()).WillRepeatedly(Return(url2));
- EXPECT_CALL(*mock_change2, CanBeMerged()).WillRepeatedly(Return(true));
- protector_service_->ShowChange(mock_change2);
- content::RunAllPendingInMessageLoop();
-
- // Changes should be merged.
- EXPECT_FALSE(IsGlobalErrorActive(mock_change_));
- EXPECT_FALSE(IsGlobalErrorActive(mock_change2));
-
- BaseSettingChange* composite_change = protector_service_->GetLastChange();
- ASSERT_TRUE(composite_change);
- EXPECT_TRUE(IsGlobalErrorActive(composite_change));
-
- protector_service_->DismissChange(composite_change);
- content::RunAllPendingInMessageLoop();
- EXPECT_FALSE(IsGlobalErrorActive(composite_change));
- EXPECT_FALSE(protector_service_->GetLastChange());
-}
-
-// TODO(ivankr): Timeout test.
-
-} // namespace protector
diff --git a/chrome/browser/protector/protector_service_factory.cc b/chrome/browser/protector/protector_service_factory.cc
deleted file mode 100644
index 4d854e3dc..0000000
--- a/chrome/browser/protector/protector_service_factory.cc
+++ /dev/null
@@ -1,56 +0,0 @@
-// Copyright (c) 2012 The Chromium Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-#include "chrome/browser/protector/protector_service_factory.h"
-
-#include "chrome/browser/profiles/profile.h"
-#include "chrome/browser/profiles/profile_dependency_manager.h"
-#include "chrome/browser/protector/protected_prefs_watcher.h"
-#include "chrome/browser/protector/protector_service.h"
-#include "chrome/browser/search_engines/template_url_service_factory.h"
-
-namespace protector {
-
-// static
-ProtectorService* ProtectorServiceFactory::GetForProfile(Profile* profile) {
- return static_cast<ProtectorService*>(
- GetInstance()->GetServiceForProfile(profile, true));
-}
-
-// static
-ProtectorServiceFactory* ProtectorServiceFactory::GetInstance() {
- return Singleton<ProtectorServiceFactory>::get();
-}
-
-ProtectorServiceFactory::ProtectorServiceFactory()
- : ProfileKeyedServiceFactory("ProtectorService",
- ProfileDependencyManager::GetInstance()) {
- // Dependencies for the correct service shutdown order.
- DependsOn(GlobalErrorServiceFactory::GetInstance());
- DependsOn(TemplateURLServiceFactory::GetInstance());
-}
-
-ProtectorServiceFactory::~ProtectorServiceFactory() {
-}
-
-ProfileKeyedService* ProtectorServiceFactory::BuildServiceInstanceFor(
- Profile* profile) const {
- return new ProtectorService(profile);
-}
-
-void ProtectorServiceFactory::RegisterUserPrefs(PrefService* user_prefs) {
- ProtectedPrefsWatcher::RegisterUserPrefs(user_prefs);
-}
-
-bool ProtectorServiceFactory::ServiceIsCreatedWithProfile() const {
- // ProtectorService watches changes for protected prefs so it must be started
- // right with the profile creation.
- return true;
-}
-
-bool ProtectorServiceFactory::ServiceRedirectedInIncognito() const {
- return true;
-}
-
-} // namespace protector
diff --git a/chrome/browser/protector/protector_service_factory.h b/chrome/browser/protector/protector_service_factory.h
deleted file mode 100644
index 1f2c7e2..0000000
--- a/chrome/browser/protector/protector_service_factory.h
+++ /dev/null
@@ -1,42 +0,0 @@
-// Copyright (c) 2012 The Chromium Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-#ifndef CHROME_BROWSER_PROTECTOR_PROTECTOR_SERVICE_FACTORY_H_
-#define CHROME_BROWSER_PROTECTOR_PROTECTOR_SERVICE_FACTORY_H_
-
-#include "base/basictypes.h"
-#include "base/memory/singleton.h"
-#include "chrome/browser/profiles/profile_keyed_service_factory.h"
-#include "chrome/browser/ui/global_error/global_error_service_factory.h"
-
-namespace protector {
-
-class ProtectorService;
-
-class ProtectorServiceFactory : public ProfileKeyedServiceFactory {
- public:
- // Returns the ProtectorService instance for |profile|.
- static ProtectorService* GetForProfile(Profile* profile);
-
- static ProtectorServiceFactory* GetInstance();
-
- private:
- friend struct DefaultSingletonTraits<ProtectorServiceFactory>;
-
- ProtectorServiceFactory();
- virtual ~ProtectorServiceFactory();
-
- // ProfileKeyedServiceFactory implementation.
- virtual ProfileKeyedService* BuildServiceInstanceFor(
- Profile* profile) const OVERRIDE;
- virtual void RegisterUserPrefs(PrefService* user_prefs) OVERRIDE;
- virtual bool ServiceIsCreatedWithProfile() const OVERRIDE;
- virtual bool ServiceRedirectedInIncognito() const OVERRIDE;
-
- DISALLOW_COPY_AND_ASSIGN(ProtectorServiceFactory);
-};
-
-} // namespace protector
-
-#endif // CHROME_BROWSER_PROTECTOR_PROTECTOR_SERVICE_FACTORY_H_
diff --git a/chrome/browser/protector/protector_utils.cc b/chrome/browser/protector/protector_utils.cc
deleted file mode 100644
index 80adc39..0000000
--- a/chrome/browser/protector/protector_utils.cc
+++ /dev/null
@@ -1,47 +0,0 @@
-// Copyright (c) 2012 The Chromium Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-#include "chrome/browser/protector/protector_utils.h"
-
-#include <vector>
-
-#include "base/command_line.h"
-#include "base/logging.h"
-#include "chrome/browser/browser_process.h"
-#include "chrome/browser/protector/keys.h"
-#include "chrome/common/chrome_switches.h"
-#include "crypto/hmac.h"
-
-namespace protector {
-
-std::string SignSetting(const std::string& value) {
- crypto::HMAC hmac(crypto::HMAC::SHA256);
- if (!hmac.Init(kProtectorSigningKey)) {
- LOG(WARNING) << "Failed to initialize HMAC algorithm for signing";
- return std::string();
- }
-
- std::vector<unsigned char> digest(hmac.DigestLength());
- if (!hmac.Sign(value, &digest[0], digest.size())) {
- LOG(WARNING) << "Failed to sign setting";
- return std::string();
- }
-
- return std::string(&digest[0], &digest[0] + digest.size());
-}
-
-bool IsSettingValid(const std::string& value, const std::string& signature) {
- crypto::HMAC hmac(crypto::HMAC::SHA256);
- if (!hmac.Init(kProtectorSigningKey)) {
- LOG(WARNING) << "Failed to initialize HMAC algorithm for verification.";
- return false;
- }
- return hmac.Verify(value, signature);
-}
-
-bool IsEnabled() {
- return CommandLine::ForCurrentProcess()->HasSwitch(switches::kProtector);
-}
-
-} // namespace protector
diff --git a/chrome/browser/protector/protector_utils.h b/chrome/browser/protector/protector_utils.h
deleted file mode 100644
index 9b3dcd3..0000000
--- a/chrome/browser/protector/protector_utils.h
+++ /dev/null
@@ -1,23 +0,0 @@
-// Copyright (c) 2012 The Chromium Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-#ifndef CHROME_BROWSER_PROTECTOR_PROTECTOR_UTILS_H_
-#define CHROME_BROWSER_PROTECTOR_PROTECTOR_UTILS_H_
-
-#include <string>
-
-namespace protector {
-
-// Signs string value with protector's key.
-std::string SignSetting(const std::string& value);
-
-// Returns true if the signature is valid for the specified key.
-bool IsSettingValid(const std::string& value, const std::string& signature);
-
-// Whether the Protector feature is enabled.
-bool IsEnabled();
-
-} // namespace protector
-
-#endif // CHROME_BROWSER_PROTECTOR_PROTECTOR_UTILS_H_
diff --git a/chrome/browser/protector/session_startup_change.cc b/chrome/browser/protector/session_startup_change.cc
deleted file mode 100644
index 4a73756..0000000
--- a/chrome/browser/protector/session_startup_change.cc
+++ /dev/null
@@ -1,231 +0,0 @@
-// Copyright (c) 2012 The Chromium Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-#include "base/basictypes.h"
-#include "base/compiler_specific.h"
-#include "base/logging.h"
-#include "base/metrics/histogram.h"
-#include "base/utf_string_conversions.h"
-#include "chrome/browser/prefs/session_startup_pref.h"
-#include "chrome/browser/protector/base_prefs_change.h"
-#include "chrome/browser/protector/histograms.h"
-#include "chrome/browser/protector/protector_service.h"
-#include "chrome/browser/protector/protector_service_factory.h"
-#include "chrome/browser/ui/browser.h"
-#include "chrome/browser/ui/browser_navigator.h"
-#include "chrome/browser/ui/tabs/pinned_tab_codec.h"
-#include "chrome/browser/ui/tabs/tab_strip_model.h"
-#include "chrome/browser/ui/tabs/tab_strip_model.h"
-#include "chrome/common/pref_names.h"
-#include "grit/chromium_strings.h"
-#include "grit/generated_resources.h"
-#include "grit/theme_resources.h"
-#include "ui/base/l10n/l10n_util.h"
-
-namespace protector {
-
-// Session startup settings change tracked by Protector.
-class SessionStartupChange : public BasePrefsChange {
- public:
- SessionStartupChange(const SessionStartupPref& actual_startup_pref,
- const StartupTabs& actual_pinned_tabs,
- const SessionStartupPref& backup_startup_pref,
- const StartupTabs& backup_pinned_tabs);
-
- // BaseSettingChange overrides:
- virtual bool Init(Profile* profile) OVERRIDE;
- virtual void Apply(Browser* browser) OVERRIDE;
- virtual void Discard(Browser* browser) OVERRIDE;
- virtual void Timeout() OVERRIDE;
- virtual int GetBadgeIconID() const OVERRIDE;
- virtual int GetMenuItemIconID() const OVERRIDE;
- virtual int GetBubbleIconID() const OVERRIDE;
- virtual string16 GetBubbleTitle() const OVERRIDE;
- virtual string16 GetBubbleMessage() const OVERRIDE;
- virtual string16 GetApplyButtonText() const OVERRIDE;
- virtual string16 GetDiscardButtonText() const OVERRIDE;
- virtual DisplayName GetApplyDisplayName() const OVERRIDE;
- virtual GURL GetNewSettingURL() const OVERRIDE;
-
- private:
- virtual ~SessionStartupChange();
-
- // Returns the first URL that was added to the startup pages. Returns the
- // first startup URL if they haven't changed. Returns an empty URL if there
- // are no startup URLs.
- GURL GetFirstNewURL() const;
-
- // Opens all tabs in |tabs| and makes them pinned.
- void OpenPinnedTabs(Browser* browser, const StartupTabs& tabs);
-
- const SessionStartupPref new_startup_pref_;
- const SessionStartupPref backup_startup_pref_;
- const StartupTabs new_pinned_tabs_;
- const StartupTabs backup_pinned_tabs_;
-
- DISALLOW_COPY_AND_ASSIGN(SessionStartupChange);
-};
-
-SessionStartupChange::SessionStartupChange(
- const SessionStartupPref& actual_startup_pref,
- const StartupTabs& actual_pinned_tabs,
- const SessionStartupPref& backup_startup_pref,
- const StartupTabs& backup_pinned_tabs)
- : new_startup_pref_(actual_startup_pref),
- backup_startup_pref_(backup_startup_pref),
- new_pinned_tabs_(actual_pinned_tabs),
- backup_pinned_tabs_(backup_pinned_tabs) {
- UMA_HISTOGRAM_ENUMERATION(
- kProtectorHistogramStartupSettingsChanged,
- actual_startup_pref.type,
- SessionStartupPref::TYPE_COUNT);
-}
-
-SessionStartupChange::~SessionStartupChange() {
-}
-
-bool SessionStartupChange::Init(Profile* profile) {
- if (!BasePrefsChange::Init(profile))
- return false;
- SessionStartupPref::SetStartupPref(profile, backup_startup_pref_);
- PinnedTabCodec::WritePinnedTabs(profile, backup_pinned_tabs_);
- DismissOnPrefChange(prefs::kRestoreOnStartup);
- DismissOnPrefChange(prefs::kURLsToRestoreOnStartup);
- DismissOnPrefChange(prefs::kPinnedTabs);
- return true;
-}
-
-void SessionStartupChange::Apply(Browser* browser) {
- UMA_HISTOGRAM_ENUMERATION(
- kProtectorHistogramStartupSettingsApplied,
- new_startup_pref_.type,
- SessionStartupPref::TYPE_COUNT);
- IgnorePrefChanges();
- SessionStartupPref::SetStartupPref(profile(), new_startup_pref_);
- PinnedTabCodec::WritePinnedTabs(profile(), new_pinned_tabs_);
- OpenPinnedTabs(browser, new_pinned_tabs_);
-}
-
-void SessionStartupChange::Discard(Browser* browser) {
- UMA_HISTOGRAM_ENUMERATION(
- kProtectorHistogramStartupSettingsDiscarded,
- new_startup_pref_.type,
- SessionStartupPref::TYPE_COUNT);
- IgnorePrefChanges();
- // Nothing to do here since backup has already been made active by Init().
-}
-
-void SessionStartupChange::Timeout() {
- UMA_HISTOGRAM_ENUMERATION(
- kProtectorHistogramStartupSettingsTimeout,
- new_startup_pref_.type,
- SessionStartupPref::TYPE_COUNT);
-}
-
-int SessionStartupChange::GetBadgeIconID() const {
- // Icons are the same for homepage and startup settings.
- return IDR_HOMEPAGE_CHANGE_BADGE;
-}
-
-int SessionStartupChange::GetMenuItemIconID() const {
- return IDR_HOMEPAGE_CHANGE_MENU;
-}
-
-int SessionStartupChange::GetBubbleIconID() const {
- return IDR_HOMEPAGE_CHANGE_ALERT;
-}
-
-string16 SessionStartupChange::GetBubbleTitle() const {
- return l10n_util::GetStringUTF16(IDS_STARTUP_SETTINGS_CHANGE_TITLE);
-}
-
-string16 SessionStartupChange::GetBubbleMessage() const {
- return l10n_util::GetStringUTF16(IDS_STARTUP_SETTINGS_CHANGE_BUBBLE_MESSAGE);
-}
-
-string16 SessionStartupChange::GetApplyButtonText() const {
- if (new_startup_pref_.type == SessionStartupPref::LAST)
- return l10n_util::GetStringUTF16(IDS_CHANGE_STARTUP_SETTINGS_RESTORE);
-
- // Display the domain name of the first startup/pinned URL.
- string16 first_domain = UTF8ToUTF16(GetFirstNewURL().host());
- return first_domain.empty() ?
- l10n_util::GetStringUTF16(IDS_CHANGE_STARTUP_SETTINGS_NTP) :
- l10n_util::GetStringFUTF16(IDS_CHANGE_STARTUP_SETTINGS_URLS,
- first_domain);
-}
-
-string16 SessionStartupChange::GetDiscardButtonText() const {
- return l10n_util::GetStringUTF16(IDS_KEEP_SETTING);
-}
-
-BaseSettingChange::DisplayName
-SessionStartupChange::GetApplyDisplayName() const {
- string16 first_domain = UTF8ToUTF16(GetFirstNewURL().host());
- return first_domain.empty() ?
- BaseSettingChange::GetApplyDisplayName() :
- DisplayName(kSessionStartupChangeNamePriority, first_domain);
-}
-
-GURL SessionStartupChange::GetNewSettingURL() const {
- VLOG(1) << "HP URL: " << GetFirstNewURL().spec();
- return GetFirstNewURL();
-}
-
-GURL SessionStartupChange::GetFirstNewURL() const {
- if (new_startup_pref_.type == SessionStartupPref::LAST)
- return GURL();
-
- std::set<GURL> old_urls;
- if (backup_startup_pref_.type == SessionStartupPref::URLS) {
- old_urls.insert(backup_startup_pref_.urls.begin(),
- backup_startup_pref_.urls.end());
- }
- for (size_t i = 0; i < backup_pinned_tabs_.size(); ++i)
- old_urls.insert(backup_pinned_tabs_[i].url);
-
- std::vector<GURL> new_urls;
- if (new_startup_pref_.type == SessionStartupPref::URLS) {
- new_urls.insert(new_urls.end(), new_startup_pref_.urls.begin(),
- new_startup_pref_.urls.end());
- }
- for (size_t i = 0; i < new_pinned_tabs_.size(); ++i)
- new_urls.push_back(new_pinned_tabs_[i].url);
-
- if (new_urls.empty())
- return GURL();
-
- // First try to find a URL in new settings that is not present in backup.
- for (size_t i = 0; i < new_urls.size(); ++i) {
- if (!old_urls.count(new_urls[i]))
- return new_urls[i];
- }
- // Then fallback to the first of the current startup URLs - this means that
- // URLs themselves haven't changed.
- return new_urls[0];
-}
-
-void SessionStartupChange::OpenPinnedTabs(Browser* browser,
- const StartupTabs& tabs) {
- for (size_t i = 0; i < tabs.size(); ++i) {
- chrome::NavigateParams params(browser, tabs[i].url,
- content::PAGE_TRANSITION_AUTO_TOPLEVEL);
- params.disposition = NEW_BACKGROUND_TAB;
- params.tabstrip_index = -1;
- params.tabstrip_add_types = TabStripModel::ADD_PINNED;
- params.extension_app_id = tabs[i].app_id;
- chrome::Navigate(&params);
- }
-}
-
-BaseSettingChange* CreateSessionStartupChange(
- const SessionStartupPref& actual_startup_pref,
- const StartupTabs& actual_pinned_tabs,
- const SessionStartupPref& backup_startup_pref,
- const StartupTabs& backup_pinned_tabs) {
- return new SessionStartupChange(actual_startup_pref, actual_pinned_tabs,
- backup_startup_pref, backup_pinned_tabs);
-}
-
-} // namespace protector
diff --git a/chrome/browser/protector/session_startup_change_unittest.cc b/chrome/browser/protector/session_startup_change_unittest.cc
deleted file mode 100644
index 38de32c..0000000
--- a/chrome/browser/protector/session_startup_change_unittest.cc
+++ /dev/null
@@ -1,191 +0,0 @@
-// Copyright (c) 2012 The Chromium Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-#include "base/memory/scoped_ptr.h"
-#include "base/utf_string_conversions.h"
-#include "base/values.h"
-#include "chrome/browser/prefs/session_startup_pref.h"
-#include "chrome/browser/protector/base_setting_change.h"
-#include "chrome/browser/ui/startup/startup_tab.h"
-#include "chrome/test/base/testing_profile.h"
-#include "testing/gtest/include/gtest/gtest.h"
-#include "grit/generated_resources.h"
-#include "ui/base/l10n/l10n_util.h"
-
-namespace protector {
-
-namespace {
-
-const char kStartupUrl1[] = "http://google.com";
-const char kStartupUrl2[] = "http://example.com";
-const char kStartupUrl3[] = "http://example.org";
-const char kStartupHost1[] = "google.com";
-const char kStartupHost2[] = "example.com";
-const char kStartupHost3[] = "example.org";
-
-const BaseSettingChange::DisplayName kNoDisplayName(
- BaseSettingChange::kDefaultNamePriority, string16());
-
-} // namespace
-
-class SessionStartupChangeTest : public testing::Test {
- public:
- SessionStartupChangeTest()
- : initial_startup_pref_(SessionStartupPref::DEFAULT) {
- }
-
- virtual void SetUp() OVERRIDE {
- // Ensure initial session startup pref.
- SessionStartupPref::SetStartupPref(&profile_, initial_startup_pref_);
- }
-
- protected:
- TestingProfile profile_;
- SessionStartupPref initial_startup_pref_;
- StartupTabs empty_pinned_tabs_;
-};
-
-TEST_F(SessionStartupChangeTest, InitAndApply) {
- // Create a change and apply it.
- SessionStartupPref backup_startup_pref(SessionStartupPref::LAST);
- scoped_ptr<BaseSettingChange> change(
- CreateSessionStartupChange(initial_startup_pref_, empty_pinned_tabs_,
- backup_startup_pref, empty_pinned_tabs_));
- ASSERT_TRUE(change->Init(&profile_));
- // Setting is initially reverted to backup.
- EXPECT_EQ(SessionStartupPref::LAST,
- SessionStartupPref::GetStartupPref(&profile_).type);
- change->Apply(NULL); // |browser| is unused.
- // New setting active now.
- EXPECT_EQ(SessionStartupPref::DEFAULT,
- SessionStartupPref::GetStartupPref(&profile_).type);
-}
-
-TEST_F(SessionStartupChangeTest, InitAndDiscard) {
- // Create a change and discard it.
- SessionStartupPref backup_startup_pref(SessionStartupPref::LAST);
- scoped_ptr<BaseSettingChange> change(
- CreateSessionStartupChange(initial_startup_pref_, empty_pinned_tabs_,
- backup_startup_pref, empty_pinned_tabs_));
- ASSERT_TRUE(change->Init(&profile_));
- // Setting is initially reverted to backup.
- EXPECT_EQ(SessionStartupPref::LAST,
- SessionStartupPref::GetStartupPref(&profile_).type);
- change->Discard(NULL); // |browser| is unused.
- // Nothing changed by Discard.
- EXPECT_EQ(SessionStartupPref::LAST,
- SessionStartupPref::GetStartupPref(&profile_).type);
-}
-
-TEST_F(SessionStartupChangeTest, ApplyButtonCaptions) {
- // Apply button captions for "Open NTP" and "Open specific URLs" cases.
- string16 open_ntp_caption =
- l10n_util::GetStringUTF16(IDS_CHANGE_STARTUP_SETTINGS_NTP);
- string16 open_url1_etc_caption =
- l10n_util::GetStringFUTF16(IDS_CHANGE_STARTUP_SETTINGS_URLS,
- UTF8ToUTF16(GURL(kStartupUrl1).host()));
- string16 open_url2_etc_caption =
- l10n_util::GetStringFUTF16(IDS_CHANGE_STARTUP_SETTINGS_URLS,
- UTF8ToUTF16(GURL(kStartupUrl2).host()));
- string16 open_url3_etc_caption =
- l10n_util::GetStringFUTF16(IDS_CHANGE_STARTUP_SETTINGS_URLS,
- UTF8ToUTF16(GURL(kStartupUrl3).host()));
-
- // Open NTP.
- initial_startup_pref_.type = SessionStartupPref::DEFAULT;
- SessionStartupPref backup_startup_pref(SessionStartupPref::DEFAULT);
- scoped_ptr<BaseSettingChange> change(
- CreateSessionStartupChange(initial_startup_pref_, empty_pinned_tabs_,
- backup_startup_pref, empty_pinned_tabs_));
- ASSERT_TRUE(change->Init(&profile_));
- EXPECT_EQ(open_ntp_caption, change->GetApplyButtonText());
- EXPECT_EQ(GURL(), change->GetNewSettingURL());
- EXPECT_EQ(kNoDisplayName, change->GetApplyDisplayName());
-
- // Pinned tabs count as startup URLs as well.
- StartupTabs new_pinned_tabs;
- StartupTab pinned_tab;
- pinned_tab.url = GURL(kStartupUrl3);
- new_pinned_tabs.push_back(pinned_tab);
- change.reset(
- CreateSessionStartupChange(initial_startup_pref_, new_pinned_tabs,
- backup_startup_pref, empty_pinned_tabs_));
- ASSERT_TRUE(change->Init(&profile_));
- EXPECT_EQ(open_url3_etc_caption, change->GetApplyButtonText());
- EXPECT_EQ(GURL(kStartupUrl3), change->GetNewSettingURL());
- EXPECT_EQ(UTF8ToUTF16(kStartupHost3), change->GetApplyDisplayName().second);
-
- // "Open URLs" with no URLs is the same as "Open NTP".
- initial_startup_pref_.type = SessionStartupPref::URLS;
- change.reset(
- CreateSessionStartupChange(initial_startup_pref_, empty_pinned_tabs_,
- backup_startup_pref, empty_pinned_tabs_));
- ASSERT_TRUE(change->Init(&profile_));
- EXPECT_EQ(open_ntp_caption, change->GetApplyButtonText());
- EXPECT_EQ(GURL(), change->GetNewSettingURL());
- EXPECT_EQ(kNoDisplayName, change->GetApplyDisplayName());
-
- // Single URL.
- initial_startup_pref_.urls.push_back(GURL(kStartupUrl1));
- change.reset(
- CreateSessionStartupChange(initial_startup_pref_, empty_pinned_tabs_,
- backup_startup_pref, empty_pinned_tabs_));
- ASSERT_TRUE(change->Init(&profile_));
- EXPECT_EQ(open_url1_etc_caption, change->GetApplyButtonText());
- EXPECT_EQ(GURL(kStartupUrl1), change->GetNewSettingURL());
- EXPECT_EQ(UTF8ToUTF16(kStartupHost1), change->GetApplyDisplayName().second);
-
- // Multiple URLs: name of the first one used.
- initial_startup_pref_.urls.push_back(GURL(kStartupUrl2));
- change.reset(
- CreateSessionStartupChange(initial_startup_pref_, empty_pinned_tabs_,
- backup_startup_pref, empty_pinned_tabs_));
- ASSERT_TRUE(change->Init(&profile_));
- EXPECT_EQ(open_url1_etc_caption, change->GetApplyButtonText());
- EXPECT_EQ(GURL(kStartupUrl1), change->GetNewSettingURL());
- EXPECT_EQ(UTF8ToUTF16(kStartupHost1), change->GetApplyDisplayName().second);
-
- // Pinned tabs go after the startup URLs.
- change.reset(
- CreateSessionStartupChange(initial_startup_pref_, new_pinned_tabs,
- backup_startup_pref, empty_pinned_tabs_));
- ASSERT_TRUE(change->Init(&profile_));
- EXPECT_EQ(open_url1_etc_caption, change->GetApplyButtonText());
- EXPECT_EQ(GURL(kStartupUrl1), change->GetNewSettingURL());
- EXPECT_EQ(UTF8ToUTF16(kStartupHost1), change->GetApplyDisplayName().second);
-
- // Multiple URLs, the first present in both backup and new settings.
- backup_startup_pref.type = SessionStartupPref::URLS;
- backup_startup_pref.urls.push_back(GURL(kStartupUrl1));
- change.reset(
- CreateSessionStartupChange(initial_startup_pref_, empty_pinned_tabs_,
- backup_startup_pref, empty_pinned_tabs_));
- ASSERT_TRUE(change->Init(&profile_));
- EXPECT_EQ(open_url2_etc_caption, change->GetApplyButtonText());
- EXPECT_EQ(GURL(kStartupUrl2), change->GetNewSettingURL());
- EXPECT_EQ(UTF8ToUTF16(kStartupHost2), change->GetApplyDisplayName().second);
-
- // Multiple URLs, all present in both backup and new settings: the first one
- // is displayed in that case.
- backup_startup_pref.urls.push_back(GURL(kStartupUrl2));
- change.reset(
- CreateSessionStartupChange(initial_startup_pref_, empty_pinned_tabs_,
- backup_startup_pref, empty_pinned_tabs_));
- ASSERT_TRUE(change->Init(&profile_));
- EXPECT_EQ(open_url1_etc_caption, change->GetApplyButtonText());
- EXPECT_EQ(GURL(kStartupUrl1), change->GetNewSettingURL());
- EXPECT_EQ(UTF8ToUTF16(kStartupHost1), change->GetApplyDisplayName().second);
-
- // Multiple URLs, all present in both backup and new settings, new pinned tabs
- // added: the first pinned tab URL is used.
- change.reset(
- CreateSessionStartupChange(initial_startup_pref_, new_pinned_tabs,
- backup_startup_pref, empty_pinned_tabs_));
- ASSERT_TRUE(change->Init(&profile_));
- EXPECT_EQ(open_url3_etc_caption, change->GetApplyButtonText());
- EXPECT_EQ(GURL(kStartupUrl3), change->GetNewSettingURL());
- EXPECT_EQ(UTF8ToUTF16(kStartupHost3), change->GetApplyDisplayName().second);
-}
-
-} // namespace protector
diff --git a/chrome/browser/protector/settings_change_global_error.cc b/chrome/browser/protector/settings_change_global_error.cc
deleted file mode 100644
index 9ccf558..0000000
--- a/chrome/browser/protector/settings_change_global_error.cc
+++ /dev/null
@@ -1,238 +0,0 @@
-// Copyright (c) 2012 The Chromium Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-#include "chrome/browser/protector/settings_change_global_error.h"
-
-#include <bitset>
-
-#include "base/bind.h"
-#include "base/compiler_specific.h"
-#include "base/lazy_instance.h"
-#include "base/logging.h"
-#include "base/stl_util.h"
-#include "chrome/browser/platform_util.h"
-#include "chrome/browser/profiles/profile.h"
-#include "chrome/browser/protector/base_setting_change.h"
-#include "chrome/browser/protector/settings_change_global_error_delegate.h"
-#include "chrome/browser/ui/browser.h"
-#include "chrome/browser/ui/browser_finder.h"
-#include "chrome/browser/ui/browser_list.h"
-#include "chrome/browser/ui/browser_window.h"
-#include "chrome/browser/ui/global_error/global_error_service.h"
-#include "chrome/browser/ui/global_error/global_error_service_factory.h"
-#include "content/public/browser/browser_thread.h"
-
-using content::BrowserThread;
-
-namespace protector {
-
-namespace {
-
-// Timeout before the global error is removed (wrench menu item disappears).
-const int kMenuItemDisplayPeriodMs = 10*60*1000; // 10 min
-
-// Unset bits indicate available command IDs.
-static base::LazyInstance<
- std::bitset<IDC_SHOW_SETTINGS_CHANGE_LAST -
- IDC_SHOW_SETTINGS_CHANGE_FIRST + 1> > menu_ids =
- LAZY_INSTANCE_INITIALIZER;
-
-} // namespace
-
-SettingsChangeGlobalError::SettingsChangeGlobalError(
- BaseSettingChange* change,
- SettingsChangeGlobalErrorDelegate* delegate)
- : change_(change),
- delegate_(delegate),
- profile_(NULL),
- closed_by_button_(false),
- show_on_browser_activation_(false),
- ALLOW_THIS_IN_INITIALIZER_LIST(weak_factory_(this)),
- menu_id_(-1) {
- DCHECK(delegate_);
- for (int i = IDC_SHOW_SETTINGS_CHANGE_FIRST;
- i <= IDC_SHOW_SETTINGS_CHANGE_LAST; i++) {
- if (!menu_ids.Get()[i - IDC_SHOW_SETTINGS_CHANGE_FIRST]) {
- menu_id_ = i;
- menu_ids.Get().set(i - IDC_SHOW_SETTINGS_CHANGE_FIRST);
- break;
- }
- }
- DCHECK(menu_id_ >= 0) << "Out of command IDs for SettingsChangeGlobalError";
-}
-
-SettingsChangeGlobalError::~SettingsChangeGlobalError() {
- if (profile_)
- RemoveFromProfile();
- if (menu_id_ >= 0)
- menu_ids.Get().reset(menu_id_ - IDC_SHOW_SETTINGS_CHANGE_FIRST);
-}
-
-void SettingsChangeGlobalError::AddToProfile(
- Profile* profile,
- bool show_bubble,
- chrome::HostDesktopType desktop_type) {
- DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
- profile_ = profile;
- GlobalErrorServiceFactory::GetForProfile(profile_)->AddGlobalError(this);
- BrowserList::AddObserver(this);
- if (show_bubble) {
- ShowBubble(desktop_type);
- } else {
- // Start inactivity timer.
- BrowserThread::PostDelayedTask(
- BrowserThread::UI, FROM_HERE,
- base::Bind(&SettingsChangeGlobalError::OnInactiveTimeout,
- weak_factory_.GetWeakPtr()),
- base::TimeDelta::FromMilliseconds(kMenuItemDisplayPeriodMs));
- }
-}
-
-void SettingsChangeGlobalError::RemoveFromProfile() {
- DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
- if (profile_) {
- GlobalErrorServiceFactory::GetForProfile(profile_)->RemoveGlobalError(this);
- profile_ = NULL;
- }
- BrowserList::RemoveObserver(this);
- // This will delete |this|.
- delegate_->OnRemovedFromProfile(this);
-}
-
-void SettingsChangeGlobalError::ShowBubble(
- chrome::HostDesktopType desktop_type) {
- DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
- DCHECK(profile_);
- Browser* browser = browser::FindTabbedBrowser(profile_, true, desktop_type);
- if (browser)
- ShowBubbleInBrowser(browser);
-}
-
-bool SettingsChangeGlobalError::HasBadge() {
- return true;
-}
-
-int SettingsChangeGlobalError::GetBadgeResourceID() {
- return change_->GetBadgeIconID();
-}
-
-bool SettingsChangeGlobalError::HasMenuItem() {
- return true;
-}
-
-int SettingsChangeGlobalError::MenuItemCommandID() {
- return menu_id_;
-}
-
-string16 SettingsChangeGlobalError::MenuItemLabel() {
- return change_->GetBubbleTitle();
-}
-
-int SettingsChangeGlobalError::MenuItemIconResourceID() {
- return change_->GetMenuItemIconID();
-}
-
-void SettingsChangeGlobalError::ExecuteMenuItem(Browser* browser) {
- ShowBubbleInBrowser(browser);
-}
-
-bool SettingsChangeGlobalError::HasBubbleView() {
- return true;
-}
-
-int SettingsChangeGlobalError::GetBubbleViewIconResourceID() {
- return change_->GetBubbleIconID();
-}
-
-string16 SettingsChangeGlobalError::GetBubbleViewTitle() {
- return change_->GetBubbleTitle();
-}
-
-string16 SettingsChangeGlobalError::GetBubbleViewMessage() {
- return change_->GetBubbleMessage();
-}
-
-// The Accept and Revert buttons are swapped like the 'server' and 'client'
-// concepts in X11. Accept button (the default one) discards changes
-// (keeps using previous setting) while cancel button applies changes
-// (switches to the new setting). This is sick and blows my mind. - ivankr
-
-string16 SettingsChangeGlobalError::GetBubbleViewAcceptButtonLabel() {
- return change_->GetDiscardButtonText();
-}
-
-string16 SettingsChangeGlobalError::GetBubbleViewCancelButtonLabel() {
- return change_->GetApplyButtonText();
-}
-
-void SettingsChangeGlobalError::OnBubbleViewDidClose(Browser* browser) {
- // The bubble may be closed as the result of RemoveFromProfile call when
- // merging this error with another one.
- if (!profile_)
- return;
- if (!closed_by_button_) {
- BrowserThread::PostDelayedTask(
- BrowserThread::UI, FROM_HERE,
- base::Bind(&SettingsChangeGlobalError::OnInactiveTimeout,
- weak_factory_.GetWeakPtr()),
- base::TimeDelta::FromMilliseconds(kMenuItemDisplayPeriodMs));
-#if !defined(TOOLKIT_GTK)
- // TODO(ivankr): the logic for redisplaying bubble is disabled on Gtk, see
- // http://crbug.com/115719.
- if (browser->window() &&
- !platform_util::IsWindowActive(browser->window()->GetNativeWindow())) {
- // Bubble closed because the entire window lost activation, display
- // again when a window gets active.
- show_on_browser_activation_ = true;
- }
-#endif
- } else {
- RemoveFromProfile();
- }
-}
-
-void SettingsChangeGlobalError::BubbleViewAcceptButtonPressed(
- Browser* browser) {
- closed_by_button_ = true;
- delegate_->OnDiscardChange(this, browser);
-}
-
-void SettingsChangeGlobalError::BubbleViewCancelButtonPressed(
- Browser* browser) {
- closed_by_button_ = true;
- delegate_->OnApplyChange(this, browser);
-}
-
-void SettingsChangeGlobalError::OnBrowserSetLastActive(
- Browser* browser) {
- if (show_on_browser_activation_ && browser && browser->is_type_tabbed()) {
- // A tabbed browser window got activated, show the error bubble again.
- // Calling ShowBubble() immediately from here does not always work because
- // the old browser window may still have focus.
- // Multiple posted ShowBubble() calls are fine since the first successful
- // one will invalidate all the weak pointers.
- // Note that ShowBubble() will display the bubble in the last active browser
- // (which may not be |browser| at the moment ShowBubble() is executed).
- BrowserThread::PostTask(
- BrowserThread::UI, FROM_HERE,
- base::Bind(&SettingsChangeGlobalError::ShowBubble,
- weak_factory_.GetWeakPtr(),
- browser->host_desktop_type()));
- }
-}
-
-void SettingsChangeGlobalError::ShowBubbleInBrowser(Browser* browser) {
- show_on_browser_activation_ = false;
- // Cancel any previously posted tasks so that the global error
- // does not get removed on timeout while still showing the bubble.
- weak_factory_.InvalidateWeakPtrs();
- ShowBubbleView(browser);
-}
-
-void SettingsChangeGlobalError::OnInactiveTimeout() {
- delegate_->OnDecisionTimeout(this);
- RemoveFromProfile();
-}
-
-} // namespace protector
diff --git a/chrome/browser/protector/settings_change_global_error.h b/chrome/browser/protector/settings_change_global_error.h
deleted file mode 100644
index 7f537c1..0000000
--- a/chrome/browser/protector/settings_change_global_error.h
+++ /dev/null
@@ -1,109 +0,0 @@
-// Copyright (c) 2012 The Chromium Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-#ifndef CHROME_BROWSER_PROTECTOR_SETTINGS_CHANGE_GLOBAL_ERROR_H_
-#define CHROME_BROWSER_PROTECTOR_SETTINGS_CHANGE_GLOBAL_ERROR_H_
-
-#include "base/basictypes.h"
-#include "base/compiler_specific.h"
-#include "base/memory/weak_ptr.h"
-#include "chrome/app/chrome_command_ids.h"
-#include "chrome/browser/protector/base_setting_change.h"
-#include "chrome/browser/ui/browser_list_observer.h"
-#include "chrome/browser/ui/global_error/global_error.h"
-#include "chrome/browser/ui/host_desktop.h"
-
-class Browser;
-class Profile;
-
-namespace protector {
-
-class BaseSettingChange;
-class SettingsChangeGlobalErrorDelegate;
-
-// Global error about unwanted settings changes.
-class SettingsChangeGlobalError : public GlobalError,
- public chrome::BrowserListObserver {
- public:
- // Creates new global error about setting changes |change| which must not be
- // deleted until |delegate->OnRemovedFromProfile| is called. Uses |delegate|
- // to notify about user decision.
- SettingsChangeGlobalError(BaseSettingChange* change,
- SettingsChangeGlobalErrorDelegate* delegate);
- virtual ~SettingsChangeGlobalError();
-
- // Adds a global error to the given browser profile and shows a bubble
- // immediately on the desktop specified by |desktop_type| if |show_bubble| is
- // |true|.
- void AddToProfile(Profile* profile,
- bool show_bubble,
- chrome::HostDesktopType desktop_type);
-
- // Removes global error from its profile.
- void RemoveFromProfile();
-
- // Displays the bubble in the last active tabbed browser on the desktop
- // specified by |desktop_type|.
- void ShowBubble(chrome::HostDesktopType desktop_type);
-
- // Returns the change instance to which this error refers.
- BaseSettingChange* change() { return change_; }
-
- private:
- // GlobalError implementation.
- virtual bool HasBadge() OVERRIDE;
- virtual int GetBadgeResourceID() OVERRIDE;
- virtual bool HasMenuItem() OVERRIDE;
- virtual int MenuItemCommandID() OVERRIDE;
- virtual string16 MenuItemLabel() OVERRIDE;
- virtual int MenuItemIconResourceID() OVERRIDE;
- virtual void ExecuteMenuItem(Browser* browser) OVERRIDE;
- virtual bool HasBubbleView() OVERRIDE;
- virtual int GetBubbleViewIconResourceID() OVERRIDE;
- virtual string16 GetBubbleViewTitle() OVERRIDE;
- virtual string16 GetBubbleViewMessage() OVERRIDE;
- virtual string16 GetBubbleViewAcceptButtonLabel() OVERRIDE;
- virtual string16 GetBubbleViewCancelButtonLabel() OVERRIDE;
- virtual void OnBubbleViewDidClose(Browser* browser) OVERRIDE;
- virtual void BubbleViewAcceptButtonPressed(Browser* browser) OVERRIDE;
- virtual void BubbleViewCancelButtonPressed(Browser* browser) OVERRIDE;
-
- // chrome::BrowserListObserver implementation.
- virtual void OnBrowserAdded(Browser* browser) OVERRIDE {}
- virtual void OnBrowserRemoved(Browser* browser) OVERRIDE {}
- virtual void OnBrowserSetLastActive(Browser* browser) OVERRIDE;
-
- // Displays the bubble in |browser|'s window.
- void ShowBubbleInBrowser(Browser* browser);
-
- // Called when the wrench menu item has been displayed for enough time
- // without user interaction.
- void OnInactiveTimeout();
-
- // Change to show.
- BaseSettingChange* change_;
-
- // Delegate to notify about user actions.
- SettingsChangeGlobalErrorDelegate* delegate_;
-
- // Profile that we have been added to.
- Profile* profile_;
-
- // True if user has dismissed the bubble by clicking on one of the buttons.
- bool closed_by_button_;
-
- // True if the bubble has to be shown on the next browser window activation.
- bool show_on_browser_activation_;
-
- base::WeakPtrFactory<SettingsChangeGlobalError> weak_factory_;
-
- // Menu command ID assigned to |this| from the pool of available IDs.
- int menu_id_;
-
- DISALLOW_COPY_AND_ASSIGN(SettingsChangeGlobalError);
-};
-
-} // namespace protector
-
-#endif // CHROME_BROWSER_PROTECTOR_SETTINGS_CHANGE_GLOBAL_ERROR_H_
diff --git a/chrome/browser/protector/settings_change_global_error_delegate.h b/chrome/browser/protector/settings_change_global_error_delegate.h
deleted file mode 100644
index a2db3d2..0000000
--- a/chrome/browser/protector/settings_change_global_error_delegate.h
+++ /dev/null
@@ -1,39 +0,0 @@
-// Copyright (c) 2012 The Chromium Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-#ifndef CHROME_BROWSER_PROTECTOR_SETTINGS_CHANGE_GLOBAL_ERROR_DELEGATE_H_
-#define CHROME_BROWSER_PROTECTOR_SETTINGS_CHANGE_GLOBAL_ERROR_DELEGATE_H_
-
-#include "base/basictypes.h"
-
-class Browser;
-
-namespace protector {
-
-class SettingsChangeGlobalError;
-
-// Interface for notifications about settings change error bubble closing.
-class SettingsChangeGlobalErrorDelegate {
- public:
- virtual ~SettingsChangeGlobalErrorDelegate() {}
-
- // Called if user clicks "Apply change" button.
- virtual void OnApplyChange(SettingsChangeGlobalError* error,
- Browser* browser) = 0;
-
- // Called if user clicks "Discard change" button.
- virtual void OnDiscardChange(SettingsChangeGlobalError* error,
- Browser* browser) = 0;
-
- // Called if user clicked outside the bubble and timeout for its reshow
- // has passed.
- virtual void OnDecisionTimeout(SettingsChangeGlobalError* error) = 0;
-
- // Called when error is removed from profile so it's safe to delete it.
- virtual void OnRemovedFromProfile(SettingsChangeGlobalError* error) = 0;
-};
-
-} // namespace protector
-
-#endif // CHROME_BROWSER_PROTECTOR_SETTINGS_CHANGE_GLOBAL_ERROR_DELEGATE_H_
diff --git a/chrome/browser/search_engines/search_engine_type.h b/chrome/browser/search_engines/search_engine_type.h
index 088ce4c..6aea298 100644
--- a/chrome/browser/search_engines/search_engine_type.h
+++ b/chrome/browser/search_engines/search_engine_type.h
@@ -42,8 +42,7 @@ enum SearchEngineType {
SEARCH_ENGINE_WALLA,
SEARCH_ENGINE_ZOZNAM,
SEARCH_ENGINE_YAHOOQC,
- SEARCH_ENGINE_NONE, // Used by Protector. Putting it at the beginning would
- // corrupt UMA stats. Add new search engines below.
+ SEARCH_ENGINE_NONE, // Defunct. Deletion would corrupt UMA stats.
SEARCH_ENGINE_CONDUIT,
SEARCH_ENGINE_ALL_BY,
SEARCH_ENGINE_APORT,
diff --git a/chrome/browser/search_engines/template_url_service.cc b/chrome/browser/search_engines/template_url_service.cc
index 6a1072f..9730a09 100644
--- a/chrome/browser/search_engines/template_url_service.cc
+++ b/chrome/browser/search_engines/template_url_service.cc
@@ -24,10 +24,6 @@
#include "chrome/browser/net/url_fixer_upper.h"
#include "chrome/browser/prefs/pref_service.h"
#include "chrome/browser/profiles/profile.h"
-#include "chrome/browser/protector/base_setting_change.h"
-#include "chrome/browser/protector/protector_service.h"
-#include "chrome/browser/protector/protector_service_factory.h"
-#include "chrome/browser/protector/protector_utils.h"
#include "chrome/browser/rlz/rlz.h"
#include "chrome/browser/search_engines/search_host_to_urls_map.h"
#include "chrome/browser/search_engines/search_terms_data.h"
@@ -728,22 +724,6 @@ void TemplateURLService::OnWebDataServiceRequestDone(
LoadDefaultSearchProviderFromPrefs(&default_from_prefs,
&is_default_search_managed_);
- // Check if the default search provider has been changed in Web Data by
- // another program. No immediate action is performed because the default
- // search may be changed below by Sync which effectively undoes the hijacking.
- bool is_default_search_hijacked = false;
- TemplateURL* hijacked_default_search_provider = NULL;
- scoped_ptr<TemplateURL> backup_default_search_provider;
- // No check is required if the default search is managed.
- // |DidDefaultSearchProviderChange| must always be called because it will
- // take care of the unowned backup default search provider instance.
- if (DidDefaultSearchProviderChange(*result, profile_,
- &backup_default_search_provider) &&
- !is_default_search_managed_) {
- hijacked_default_search_provider = default_search_provider;
- is_default_search_hijacked = true;
- }
-
// Remove entries that were created because of policy as they may have
// changed since the database was saved.
RemoveProvidersCreatedByPolicy(&template_urls,
@@ -825,38 +805,7 @@ void TemplateURLService::OnWebDataServiceRequestDone(
if (new_resource_keyword_version)
service_->SetBuiltinKeywordVersion(new_resource_keyword_version);
- bool check_if_default_search_valid = !is_default_search_managed_;
-
- // Don't do anything if the default search provider has been changed since the
- // check at the beginning (overridden by Sync).
- if (is_default_search_hijacked &&
- default_search_provider_ == hijacked_default_search_provider) {
- // Put the #if defined(ENABLE_PROTECTOR_SERVICE) inside the 'if' block to
- // avoid 'unused-but-set-variable' error.
-#if defined(ENABLE_PROTECTOR_SERVICE)
- // The histograms should be reported even when Protector is disabled.
- scoped_ptr<protector::BaseSettingChange> change(
- protector::CreateDefaultSearchProviderChange(
- hijacked_default_search_provider,
- backup_default_search_provider.release()));
- if (protector::IsEnabled()) {
- protector::ProtectorService* protector_service =
- protector::ProtectorServiceFactory::GetForProfile(profile());
- DCHECK(protector_service);
- protector_service->ShowChange(change.release());
- } else {
- // Protector is turned off: set the current default search to itself
- // to update the backup and sign it. Otherwise, change will be reported
- // every time when keywords are loaded until a search provider is added.
- service_->SetDefaultSearchProvider(default_search_provider_);
- }
- // The default search provider sanity check makes no sense in this case
- // because ProtectorService is going to change default search eventually.
- check_if_default_search_valid = false;
-#endif
- }
-
- if (check_if_default_search_valid) {
+ if (!is_default_search_managed_) {
bool has_default_search_provider = default_search_provider_ != NULL &&
default_search_provider_->SupportsReplacement();
UMA_HISTOGRAM_BOOLEAN("Search.HasDefaultSearchProvider",
diff --git a/chrome/browser/search_engines/util.cc b/chrome/browser/search_engines/util.cc
index 7b0e611..4d0b6dc 100644
--- a/chrome/browser/search_engines/util.cc
+++ b/chrome/browser/search_engines/util.cc
@@ -309,24 +309,3 @@ bool DeDupeEncodings(std::vector<std::string>* encodings) {
encodings->swap(deduped_encodings);
return encodings->size() != deduped_encodings.size();
}
-
-bool DidDefaultSearchProviderChange(
- const WDTypedResult& result,
- Profile* profile,
- scoped_ptr<TemplateURL>* backup_default_search_provider) {
- DCHECK(backup_default_search_provider);
- DCHECK(!backup_default_search_provider->get());
- DCHECK_EQ(result.GetType(), KEYWORDS_RESULT);
-
- WDKeywordsResult keyword_result = reinterpret_cast<
- const WDResult<WDKeywordsResult>*>(&result)->GetValue();
-
- if (!keyword_result.did_default_search_provider_change)
- return false;
-
- if (keyword_result.backup_valid) {
- backup_default_search_provider->reset(new TemplateURL(profile,
- keyword_result.default_search_provider_backup));
- }
- return true;
-}
diff --git a/chrome/browser/search_engines/util.h b/chrome/browser/search_engines/util.h
index ebb4076..41a20df 100644
--- a/chrome/browser/search_engines/util.h
+++ b/chrome/browser/search_engines/util.h
@@ -50,15 +50,6 @@ void GetSearchProvidersUsingKeywordResult(
// any were found.
bool DeDupeEncodings(std::vector<std::string>* encodings);
-// Returns true if the default search provider setting has been changed or
-// corrupted. Returns the backup setting in |backup_default_search_provider|.
-// |*backup_default_search_provider| can be NULL if the original setting is
-// lost.
-bool DidDefaultSearchProviderChange(
- const WDTypedResult& result,
- Profile* profile,
- scoped_ptr<TemplateURL>* backup_default_search_provider);
-
// Removes (and deletes) TemplateURLs from |template_urls| and |service| if they
// have duplicate prepopulate ids. If |removed_keyword_guids| is not NULL, the
// Sync GUID of each item removed from the DB will be added to it. This is a
diff --git a/chrome/browser/ui/startup/startup_browser_creator_impl.cc b/chrome/browser/ui/startup/startup_browser_creator_impl.cc
index 2efffc5..30feec0 100644
--- a/chrome/browser/ui/startup/startup_browser_creator_impl.cc
+++ b/chrome/browser/ui/startup/startup_browser_creator_impl.cc
@@ -42,10 +42,6 @@
#include "chrome/browser/prefs/session_startup_pref.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/profiles/profile_io_data.h"
-#include "chrome/browser/protector/protected_prefs_watcher.h"
-#include "chrome/browser/protector/protector_service.h"
-#include "chrome/browser/protector/protector_service_factory.h"
-#include "chrome/browser/protector/protector_utils.h"
#include "chrome/browser/rlz/rlz.h"
#include "chrome/browser/sessions/session_restore.h"
#include "chrome/browser/sessions/session_service.h"
@@ -115,9 +111,6 @@
using content::ChildProcessSecurityPolicy;
using content::WebContents;
using extensions::Extension;
-using protector::ProtectedPrefsWatcher;
-using protector::ProtectorService;
-using protector::ProtectorServiceFactory;
extern bool in_synchronous_profile_launch;
@@ -362,10 +355,6 @@ bool StartupBrowserCreatorImpl::Launch(Profile* profile,
RecordLaunchModeHistogram(urls_to_open.empty() ?
LM_TO_BE_DECIDED : LM_WITH_URLS);
- // Notify user if the Preferences backup is invalid or changes to settings
- // affecting browser startup have been detected.
- CheckPreferencesBackup(profile);
-
ProcessLaunchURLs(process_startup, urls_to_open);
// If this is an app launch, but we didn't open an app window, it may
@@ -964,62 +953,6 @@ void StartupBrowserCreatorImpl::AddStartupURLs(
}
}
-void StartupBrowserCreatorImpl::CheckPreferencesBackup(Profile* profile) {
- ProtectorService* protector_service =
- ProtectorServiceFactory::GetForProfile(profile);
- ProtectedPrefsWatcher* prefs_watcher = protector_service->GetPrefsWatcher();
-
- // Check if backup is valid.
- if (!prefs_watcher->is_backup_valid()) {
- protector_service->ShowChange(protector::CreatePrefsBackupInvalidChange());
- // Further checks make no sense.
- return;
- }
-
- // Check for session startup (including pinned tabs) changes.
- if (SessionStartupPref::DidStartupPrefChange(profile) ||
- prefs_watcher->DidPrefChange(prefs::kPinnedTabs)) {
- LOG(WARNING) << "Session startup settings have changed";
- SessionStartupPref new_pref = SessionStartupPref::GetStartupPref(profile);
- StartupTabs new_tabs = PinnedTabCodec::ReadPinnedTabs(profile);
- const base::Value* tabs_backup =
- prefs_watcher->GetBackupForPref(prefs::kPinnedTabs);
- protector_service->ShowChange(protector::CreateSessionStartupChange(
- new_pref,
- new_tabs,
- SessionStartupPref::GetStartupPrefBackup(profile),
- PinnedTabCodec::ReadPinnedTabs(tabs_backup)));
- }
-
- // Check for homepage changes.
- if (prefs_watcher->DidPrefChange(prefs::kHomePage) ||
- prefs_watcher->DidPrefChange(prefs::kHomePageIsNewTabPage) ||
- prefs_watcher->DidPrefChange(prefs::kShowHomeButton)) {
- LOG(WARNING) << "Homepage has changed";
- PrefService* prefs = profile->GetPrefs();
- std::string backup_homepage;
- bool backup_homepage_is_ntp = false;
- bool backup_show_home_button = false;
- if (!prefs_watcher->GetBackupForPref(prefs::kHomePage)->
- GetAsString(&backup_homepage) ||
- !prefs_watcher->GetBackupForPref(prefs::kHomePageIsNewTabPage)->
- GetAsBoolean(&backup_homepage_is_ntp) ||
- !prefs_watcher->GetBackupForPref(prefs::kShowHomeButton)->
- GetAsBoolean(&backup_show_home_button)) {
- NOTREACHED();
- }
- protector_service->ShowChange(protector::CreateHomepageChange(
- // New:
- prefs->GetString(prefs::kHomePage),
- prefs->GetBoolean(prefs::kHomePageIsNewTabPage),
- prefs->GetBoolean(prefs::kShowHomeButton),
- // Backup:
- backup_homepage,
- backup_homepage_is_ntp,
- backup_show_home_button));
- }
-}
-
#if !defined(OS_WIN) || defined(USE_AURA)
// static
bool StartupBrowserCreatorImpl::OpenStartupURLsInExistingBrowser(
diff --git a/chrome/browser/webdata/keyword_table.cc b/chrome/browser/webdata/keyword_table.cc
index 6d3a064..0e2ea85 100644
--- a/chrome/browser/webdata/keyword_table.cc
+++ b/chrome/browser/webdata/keyword_table.cc
@@ -10,17 +10,12 @@
#include "base/json/json_writer.h"
#include "base/logging.h"
#include "base/memory/scoped_ptr.h"
-#include "base/metrics/histogram.h"
-#include "base/metrics/stats_counters.h"
#include "base/string_number_conversions.h"
#include "base/string_split.h"
#include "base/string_util.h"
-#include "base/stringprintf.h"
#include "base/utf_string_conversions.h"
#include "base/values.h"
#include "chrome/browser/history/history_database.h"
-#include "chrome/browser/protector/histograms.h"
-#include "chrome/browser/protector/protector_utils.h"
#include "chrome/browser/search_engines/search_terms_data.h"
#include "chrome/browser/search_engines/template_url.h"
#include "chrome/browser/search_engines/template_url_service.h"
@@ -34,10 +29,6 @@ using base::Time;
// static
const char KeywordTable::kDefaultSearchProviderKey[] =
"Default Search Provider ID";
-const char KeywordTable::kDefaultSearchIDBackupKey[] =
- "Default Search Provider ID Backup";
-const char KeywordTable::kBackupSignatureKey[] =
- "Default Search Provider ID Backup Signature";
namespace {
@@ -123,34 +114,32 @@ void BindURLToStatement(const TemplateURLData& data,
} // anonymous namespace
KeywordTable::KeywordTable(sql::Connection* db, sql::MetaTable* meta_table)
- : WebDatabaseTable(db, meta_table),
- backup_overwritten_(false) {
+ : WebDatabaseTable(db, meta_table) {
}
KeywordTable::~KeywordTable() {}
bool KeywordTable::Init() {
return db_->DoesTableExist("keywords") ||
- (db_->Execute("CREATE TABLE keywords ("
- "id INTEGER PRIMARY KEY,"
- "short_name VARCHAR NOT NULL,"
- "keyword VARCHAR NOT NULL,"
- "favicon_url VARCHAR NOT NULL,"
- "url VARCHAR NOT NULL,"
- "safe_for_autoreplace INTEGER,"
- "originating_url VARCHAR,"
- "date_created INTEGER DEFAULT 0,"
- "usage_count INTEGER DEFAULT 0,"
- "input_encodings VARCHAR,"
- "show_in_default_list INTEGER,"
- "suggest_url VARCHAR,"
- "prepopulate_id INTEGER DEFAULT 0,"
- "created_by_policy INTEGER DEFAULT 0,"
- "instant_url VARCHAR,"
- "last_modified INTEGER DEFAULT 0,"
- "sync_guid VARCHAR,"
- "alternate_urls VARCHAR)") &&
- UpdateBackupSignature(WebDatabase::kCurrentVersionNumber));
+ db_->Execute("CREATE TABLE keywords ("
+ "id INTEGER PRIMARY KEY,"
+ "short_name VARCHAR NOT NULL,"
+ "keyword VARCHAR NOT NULL,"
+ "favicon_url VARCHAR NOT NULL,"
+ "url VARCHAR NOT NULL,"
+ "safe_for_autoreplace INTEGER,"
+ "originating_url VARCHAR,"
+ "date_created INTEGER DEFAULT 0,"
+ "usage_count INTEGER DEFAULT 0,"
+ "input_encodings VARCHAR,"
+ "show_in_default_list INTEGER,"
+ "suggest_url VARCHAR,"
+ "prepopulate_id INTEGER DEFAULT 0,"
+ "created_by_policy INTEGER DEFAULT 0,"
+ "instant_url VARCHAR,"
+ "last_modified INTEGER DEFAULT 0,"
+ "sync_guid VARCHAR,"
+ "alternate_urls VARCHAR)");
}
bool KeywordTable::IsSyncable() {
@@ -164,7 +153,7 @@ bool KeywordTable::AddKeyword(const TemplateURLData& data) {
sql::Statement s(db_->GetUniqueStatement(query.c_str()));
BindURLToStatement(data, &s, 0, 1);
- return s.Run() && UpdateBackupSignature(WebDatabase::kCurrentVersionNumber);
+ return s.Run();
}
bool KeywordTable::RemoveKeyword(TemplateURLID id) {
@@ -173,7 +162,7 @@ bool KeywordTable::RemoveKeyword(TemplateURLID id) {
db_->GetUniqueStatement("DELETE FROM keywords WHERE id = ?"));
s.BindInt64(0, id);
- return s.Run() && UpdateBackupSignature(WebDatabase::kCurrentVersionNumber);
+ return s.Run();
}
bool KeywordTable::GetKeywords(Keywords* keywords) {
@@ -206,15 +195,11 @@ bool KeywordTable::UpdateKeyword(const TemplateURLData& data) {
"alternate_urls=? WHERE id=?"));
BindURLToStatement(data, &s, 17, 0); // "17" binds id() as the last item.
- return s.Run() && UpdateBackupSignature(WebDatabase::kCurrentVersionNumber);
+ return s.Run();
}
bool KeywordTable::SetDefaultSearchProviderID(int64 id) {
- // Added for http://crbug.com/116952.
- UMA_HISTOGRAM_COUNTS_100("Search.DefaultSearchProviderID",
- static_cast<int32>(id));
- return meta_table_->SetValue(kDefaultSearchProviderKey, id) &&
- UpdateBackupSignature(WebDatabase::kCurrentVersionNumber);
+ return meta_table_->SetValue(kDefaultSearchProviderKey, id);
}
int64 KeywordTable::GetDefaultSearchProviderID() {
@@ -223,83 +208,6 @@ int64 KeywordTable::GetDefaultSearchProviderID() {
return value;
}
-bool KeywordTable::GetDefaultSearchProviderBackup(TemplateURLData* backup) {
- if (!IsBackupSignatureValid(WebDatabase::kCurrentVersionNumber))
- return false;
-
- int64 backup_id = kInvalidTemplateURLID;
- if (!meta_table_->GetValue(kDefaultSearchIDBackupKey, &backup_id)) {
- LOG(ERROR) << "No default search id backup found.";
- return false;
- }
- std::string query("SELECT " + GetKeywordColumns() +
- " FROM keywords_backup WHERE id=?");
- sql::Statement s(db_->GetUniqueStatement(query.c_str()));
- s.BindInt64(0, backup_id);
-
- if (!s.Step()) {
- LOG_IF(ERROR, s.Succeeded())
- << "No default search provider with backup id.";
- return false;
- }
-
- if (!GetKeywordDataFromStatement(s, backup))
- return false;
-
- // ID has no meaning for the backup and should be kInvalidTemplateURLID in
- // case the TemplateURL will be added to keywords if missing.
- backup->id = kInvalidTemplateURLID;
- return true;
-}
-
-bool KeywordTable::DidDefaultSearchProviderChange() {
- if (!IsBackupSignatureValid(WebDatabase::kCurrentVersionNumber)) {
- UMA_HISTOGRAM_ENUMERATION(
- protector::kProtectorHistogramDefaultSearchProvider,
- protector::kProtectorErrorBackupInvalid,
- protector::kProtectorErrorCount);
- LOG(ERROR) << "Backup signature is invalid.";
- return true;
- }
-
- int64 backup_id = kInvalidTemplateURLID;
- meta_table_->GetValue(kDefaultSearchIDBackupKey, &backup_id);
- int64 current_id = GetDefaultSearchProviderID();
- if (backup_id == current_id) {
- // Either this is a new profile and both IDs are kInvalidTemplateURLID or
- // the search engines with the ids are equal.
- if (backup_id == kInvalidTemplateURLID) {
- UMA_HISTOGRAM_ENUMERATION(
- protector::kProtectorHistogramDefaultSearchProvider,
- backup_overwritten_ ?
- protector::kProtectorErrorOverwrittenByMigration :
- protector::kProtectorErrorValueValidZero,
- protector::kProtectorErrorCount);
- return false;
- }
- std::string backup_url;
- std::string current_url;
- if (GetKeywordAsString(backup_id, "keywords_backup", &backup_url) &&
- GetKeywordAsString(current_id, "keywords", &current_url) &&
- current_url == backup_url) {
- UMA_HISTOGRAM_ENUMERATION(
- protector::kProtectorHistogramDefaultSearchProvider,
- backup_overwritten_ ?
- protector::kProtectorErrorOverwrittenByMigration :
- protector::kProtectorErrorValueValid,
- protector::kProtectorErrorCount);
- return false;
- }
- }
-
- UMA_HISTOGRAM_ENUMERATION(
- protector::kProtectorHistogramDefaultSearchProvider,
- protector::kProtectorErrorValueChanged,
- protector::kProtectorErrorCount);
- LOG(WARNING) << "Default Search Provider has changed.";
- return true;
-}
-
bool KeywordTable::SetBuiltinKeywordVersion(int version) {
return meta_table_->SetValue(kBuiltinKeywordVersion, version);
}
@@ -377,10 +285,26 @@ bool KeywordTable::MigrateToVersion39AddSyncGUIDColumn() {
}
bool KeywordTable::MigrateToVersion44AddDefaultSearchProviderBackup() {
- if (IsBackupSignatureValid(44))
- return true;
- backup_overwritten_ = true;
- return UpdateBackupSignature(44);
+ sql::Transaction transaction(db_);
+ if (!transaction.Begin())
+ return false;
+
+ int64 default_search_id = GetDefaultSearchProviderID();
+ if (!meta_table_->SetValue("Default Search Provider ID Backup",
+ default_search_id))
+ return false;
+
+ // Backup of all keywords.
+ if (db_->DoesTableExist("keywords_backup") &&
+ !db_->Execute("DROP TABLE keywords_backup"))
+ return false;
+
+ std::string query("CREATE TABLE keywords_backup AS SELECT " +
+ ColumnsForVersion(44, false) + " FROM keywords ORDER BY id ASC");
+ if (!db_->Execute(query.c_str()))
+ return false;
+
+ return transaction.Commit();
}
bool KeywordTable::MigrateToVersion45RemoveLogoIDAndAutogenerateColumns() {
@@ -396,17 +320,11 @@ bool KeywordTable::MigrateToVersion45RemoveLogoIDAndAutogenerateColumns() {
if (!MigrateKeywordsTableForVersion45("keywords"))
return false;
- if (IsBackupSignatureValid(44)) {
- // Migrate the keywords backup table as well.
- if (!MigrateKeywordsTableForVersion45("keywords_backup") || !SignBackup(45))
- return false;
- } else {
- // Old backup was invalid; drop the table entirely, which will trigger the
- // protector code to prompt the user and recreate the table.
- if (db_->DoesTableExist("keywords_backup") &&
- !db_->Execute("DROP TABLE keywords_backup"))
- return false;
- }
+ // Migrate the keywords backup table as well.
+ if (!MigrateKeywordsTableForVersion45("keywords_backup") ||
+ !meta_table_->SetValue("Default Search Provider ID Backup Signature",
+ ""))
+ return false;
return transaction.Commit();
}
@@ -422,19 +340,27 @@ bool KeywordTable::MigrateToVersion47AddAlternateURLsColumn() {
"alternate_urls VARCHAR DEFAULT ''"))
return false;
- if (IsBackupSignatureValid(46)) {
- // Migrate the keywords backup table as well.
- if (!db_->Execute("ALTER TABLE keywords_backup ADD COLUMN "
- "alternate_urls VARCHAR DEFAULT ''") ||
- !SignBackup(47))
- return false;
- } else {
- // Old backup was invalid; drop the table entirely, which will trigger the
- // protector code to prompt the user and recreate the table.
- if (db_->DoesTableExist("keywords_backup") &&
- !db_->Execute("DROP TABLE keywords_backup"))
- return false;
- }
+ // Migrate the keywords backup table as well.
+ if (!db_->Execute("ALTER TABLE keywords_backup ADD COLUMN "
+ "alternate_urls VARCHAR DEFAULT ''") ||
+ !meta_table_->SetValue("Default Search Provider ID Backup Signature",
+ ""))
+ return false;
+
+ return transaction.Commit();
+}
+
+bool KeywordTable::MigrateToVersion48RemoveKeywordsBackup() {
+ sql::Transaction transaction(db_);
+ if (!transaction.Begin())
+ return false;
+
+ if (!meta_table_->DeleteKey("Default Search Provider ID Backup") ||
+ !meta_table_->DeleteKey("Default Search Provider ID Backup Signature"))
+ return false;
+
+ if (!db_->Execute("DROP TABLE keywords_backup"))
+ return false;
return transaction.Commit();
}
@@ -483,25 +409,6 @@ bool KeywordTable::GetKeywordDataFromStatement(const sql::Statement& s,
return true;
}
-bool KeywordTable::GetSignatureData(int table_version, std::string* backup) {
- DCHECK(backup);
-
- int64 backup_value = kInvalidTemplateURLID;
- if (!meta_table_->GetValue(kDefaultSearchIDBackupKey, &backup_value)) {
- LOG(ERROR) << "No backup id for signing.";
- return false;
- }
-
- std::string keywords_backup_data;
- if (!GetTableContents("keywords_backup", table_version,
- &keywords_backup_data)) {
- LOG(ERROR) << "Can't get keywords backup data";
- return false;
- }
- *backup = base::Int64ToString(backup_value) + keywords_backup_data;
- return true;
-}
-
bool KeywordTable::GetTableContents(const char* table_name,
int table_version,
std::string* contents) {
@@ -521,57 +428,6 @@ bool KeywordTable::GetTableContents(const char* table_name,
return s.Succeeded();
}
-bool KeywordTable::UpdateBackupSignature(int table_version) {
- sql::Transaction transaction(db_);
- if (!transaction.Begin())
- return false;
-
- int64 id = kInvalidTemplateURLID;
- if (!UpdateDefaultSearchProviderIDBackup(&id)) {
- LOG(ERROR) << "Failed to update default search id backup.";
- return false;
- }
-
- // Backup of all keywords.
- if (db_->DoesTableExist("keywords_backup") &&
- !db_->Execute("DROP TABLE keywords_backup"))
- return false;
-
- std::string query("CREATE TABLE keywords_backup AS SELECT " +
- ColumnsForVersion(table_version, false) +
- " FROM keywords ORDER BY id ASC");
- if (!db_->Execute(query.c_str())) {
- LOG(ERROR) << "Failed to create keywords_backup table.";
- return false;
- }
-
- return SignBackup(table_version) && transaction.Commit();
-}
-
-bool KeywordTable::SignBackup(int table_version) {
- std::string data_to_sign;
- if (!GetSignatureData(table_version, &data_to_sign)) {
- LOG(ERROR) << "No data to sign.";
- return false;
- }
-
- std::string signature = protector::SignSetting(data_to_sign);
- if (signature.empty()) {
- LOG(ERROR) << "Signature is empty";
- return false;
- }
-
- return meta_table_->SetValue(kBackupSignatureKey, signature);
-}
-
-bool KeywordTable::IsBackupSignatureValid(int table_version) {
- std::string signature;
- std::string signature_data;
- return meta_table_->GetValue(kBackupSignatureKey, &signature) &&
- GetSignatureData(table_version, &signature_data) &&
- protector::IsSettingValid(signature_data, signature);
-}
-
bool KeywordTable::GetKeywordAsString(TemplateURLID id,
const std::string& table_name,
std::string* result) {
@@ -594,19 +450,6 @@ bool KeywordTable::GetKeywordAsString(TemplateURLID id,
return true;
}
-bool KeywordTable::UpdateDefaultSearchProviderIDBackup(TemplateURLID* id) {
- DCHECK(id);
- int64 default_search_id = GetDefaultSearchProviderID();
- if (!meta_table_->SetValue(kDefaultSearchIDBackupKey,
- default_search_id)) {
- LOG(ERROR) << "Can't write default search id backup.";
- return false;
- }
-
- *id = default_search_id;
- return true;
-}
-
bool KeywordTable::MigrateKeywordsTableForVersion45(const std::string& name) {
// Create a new table without the columns we're dropping.
if (!db_->Execute("CREATE TABLE keywords_temp ("
diff --git a/chrome/browser/webdata/keyword_table.h b/chrome/browser/webdata/keyword_table.h
index ff1385a..9242ea2 100644
--- a/chrome/browser/webdata/keyword_table.h
+++ b/chrome/browser/webdata/keyword_table.h
@@ -54,28 +54,9 @@ class Statement;
// alternate_urls See TemplateURLData::alternate_urls. This was added
// in version 47.
//
-// keywords_backup The full copy of the |keywords| table. Added in
-// version 43. Must be in sync with |keywords|
-// table otherwise verification of default search
-// provider settings will fail.
-//
// This class also manages some fields in the |meta| table:
//
// Default Search Provider ID The id of the default search provider.
-// Default Search Provider ID Backup
-// Backup copy of the above for restoring it
-// in case the setting was hijacked or
-// corrupted. This was added in version 40.
-// Default Search Provider Backup Backup copy of the raw in |keywords|
-// with the default search provider ID to
-// restore all provider info. This was added
-// in version 42. Not used in 43.
-// Default Search Provider ID Backup Signature
-// The signature of backup data and
-// |keywords| table contents to be able to
-// verify the backup and understand when the
-// settings were changed. This was added
-// in version 40.
// Builtin Keyword Version The version of builtin keywords data.
//
class KeywordTable : public WebDatabaseTable {
@@ -85,12 +66,6 @@ class KeywordTable : public WebDatabaseTable {
// Constants exposed for the benefit of test code:
static const char kDefaultSearchProviderKey[];
- // Meta table key to store backup value for the default search provider id.
- static const char kDefaultSearchIDBackupKey[];
- // Meta table key to store backup value signature for the default search
- // provider. The default search provider ID and the |keywords_backup| table
- // are signed.
- static const char kBackupSignatureKey[];
KeywordTable(sql::Connection* db, sql::MetaTable* meta_table);
virtual ~KeywordTable();
@@ -118,15 +93,6 @@ class KeywordTable : public WebDatabaseTable {
bool SetDefaultSearchProviderID(int64 id);
int64 GetDefaultSearchProviderID();
- // If the default search provider backup is valid, returns true and copies the
- // backup into |backup|. Otherwise returns false.
- bool GetDefaultSearchProviderBackup(TemplateURLData* backup);
-
- // Returns true if the default search provider has been changed out from under
- // us. This can happen if another process modifies our database or the file
- // was corrupted.
- bool DidDefaultSearchProviderChange();
-
// Version of the built-in keywords.
bool SetBuiltinKeywordVersion(int version);
int GetBuiltinKeywordVersion();
@@ -146,9 +112,9 @@ class KeywordTable : public WebDatabaseTable {
bool MigrateToVersion44AddDefaultSearchProviderBackup();
bool MigrateToVersion45RemoveLogoIDAndAutogenerateColumns();
bool MigrateToVersion47AddAlternateURLsColumn();
+ bool MigrateToVersion48RemoveKeywordsBackup();
private:
- FRIEND_TEST_ALL_PREFIXES(KeywordTableTest, DefaultSearchProviderBackup);
FRIEND_TEST_ALL_PREFIXES(KeywordTableTest, GetTableContents);
FRIEND_TEST_ALL_PREFIXES(KeywordTableTest, GetTableContentsOrdering);
FRIEND_TEST_ALL_PREFIXES(KeywordTableTest, SanitizeURLs);
@@ -164,29 +130,12 @@ class KeywordTable : public WebDatabaseTable {
static bool GetKeywordDataFromStatement(const sql::Statement& s,
TemplateURLData* data);
- // Returns contents of |keywords_backup| table and default search provider
- // id backup as a string through |data|. Return value is true on success,
- // false otherwise.
- bool GetSignatureData(int table_version, std::string* data);
-
// Returns contents of selected table as a string in |contents| parameter.
// Returns true on success, false otherwise.
bool GetTableContents(const char* table_name,
int table_version,
std::string* contents);
- // Updates settings backup, signs it and stores the signature in the
- // database. Returns true on success.
- bool UpdateBackupSignature(int table_version);
-
- // Signs the backup table. This is a subset of what UpdateBackupSignature()
- // does.
- bool SignBackup(int table_version);
-
- // Checks the signature for the current settings backup. Returns true
- // if signature is valid, false otherwise.
- bool IsBackupSignatureValid(int table_version);
-
// Gets a string representation for keyword with id specified.
// Used to store its result in |meta| table or to compare with another
// keyword. Returns true on success, false otherwise.
@@ -194,17 +143,10 @@ class KeywordTable : public WebDatabaseTable {
const std::string& table_name,
std::string* result);
- // Updates default search provider id backup in |meta| table. Returns
- // true on success. The id is returned back via |id| parameter.
- bool UpdateDefaultSearchProviderIDBackup(TemplateURLID* id);
-
// Migrates table |name| (which should be either "keywords" or
// "keywords_backup") from version 44 to version 45.
bool MigrateKeywordsTableForVersion45(const std::string& name);
- // Whether the backup was overwritten during migration.
- bool backup_overwritten_;
-
DISALLOW_COPY_AND_ASSIGN(KeywordTable);
};
diff --git a/chrome/browser/webdata/keyword_table_unittest.cc b/chrome/browser/webdata/keyword_table_unittest.cc
index 0120530..d0ff9c0 100644
--- a/chrome/browser/webdata/keyword_table_unittest.cc
+++ b/chrome/browser/webdata/keyword_table_unittest.cc
@@ -133,115 +133,6 @@ TEST_F(KeywordTableTest, KeywordMisc) {
EXPECT_EQ(11, keyword_table->GetBuiltinKeywordVersion());
}
-TEST_F(KeywordTableTest, DefaultSearchProviderBackup) {
- // TODO(ivankr): suppress keyword_table.cc ERROR logs.
- WebDatabase db;
- ASSERT_EQ(sql::INIT_OK, db.Init(file_));
- KeywordTable* keyword_table = db.GetKeywordTable();
-
- EXPECT_EQ(kInvalidTemplateURLID, keyword_table->GetDefaultSearchProviderID());
-
- TemplateURLData keyword;
- keyword.short_name = ASCIIToUTF16("short_name");
- keyword.SetKeyword(ASCIIToUTF16("keyword"));
- keyword.SetURL("http://url/");
- keyword.suggestions_url = "url2";
- keyword.favicon_url = GURL("http://favicon.url/");
- keyword.show_in_default_list = true;
- keyword.safe_for_autoreplace = true;
- keyword.id = 1;
- EXPECT_TRUE(keyword_table->AddKeyword(keyword));
-
- EXPECT_TRUE(keyword_table->SetDefaultSearchProviderID(1));
- EXPECT_TRUE(keyword_table->IsBackupSignatureValid(
- WebDatabase::kCurrentVersionNumber));
- EXPECT_EQ(1, keyword_table->GetDefaultSearchProviderID());
-
- TemplateURLData backup;
- EXPECT_TRUE(keyword_table->GetDefaultSearchProviderBackup(&backup));
- // Backup URL should have an invalid ID.
- EXPECT_EQ(kInvalidTemplateURLID, backup.id);
- EXPECT_EQ(keyword.short_name, backup.short_name);
- EXPECT_EQ(keyword.keyword(), backup.keyword());
- EXPECT_EQ(keyword.url(), backup.url());
- EXPECT_EQ(keyword.favicon_url, backup.favicon_url);
- EXPECT_EQ(keyword.suggestions_url, backup.suggestions_url);
- EXPECT_EQ(keyword.show_in_default_list, backup.show_in_default_list);
- EXPECT_EQ(keyword.safe_for_autoreplace, backup.safe_for_autoreplace);
- EXPECT_FALSE(keyword_table->DidDefaultSearchProviderChange());
-
- // Change the actual setting.
- EXPECT_TRUE(keyword_table->meta_table_->SetValue(
- KeywordTable::kDefaultSearchProviderKey, 2));
- EXPECT_TRUE(keyword_table->IsBackupSignatureValid(
- WebDatabase::kCurrentVersionNumber));
- EXPECT_EQ(2, keyword_table->GetDefaultSearchProviderID());
-
- EXPECT_TRUE(keyword_table->GetDefaultSearchProviderBackup(&backup));
- EXPECT_EQ(kInvalidTemplateURLID, backup.id);
- EXPECT_EQ(keyword.short_name, backup.short_name);
- EXPECT_EQ(keyword.keyword(), backup.keyword());
- EXPECT_EQ(keyword.url(), backup.url());
- EXPECT_EQ(keyword.favicon_url, backup.favicon_url);
- EXPECT_EQ(keyword.suggestions_url, backup.suggestions_url);
- EXPECT_EQ(keyword.show_in_default_list, backup.show_in_default_list);
- EXPECT_EQ(keyword.safe_for_autoreplace, backup.safe_for_autoreplace);
- EXPECT_TRUE(keyword_table->DidDefaultSearchProviderChange());
-
- // Change the backup.
- EXPECT_TRUE(keyword_table->meta_table_->SetValue(
- KeywordTable::kDefaultSearchProviderKey, 1));
- EXPECT_TRUE(keyword_table->meta_table_->SetValue(
- KeywordTable::kDefaultSearchIDBackupKey, 2));
- EXPECT_FALSE(keyword_table->IsBackupSignatureValid(
- WebDatabase::kCurrentVersionNumber));
- EXPECT_EQ(1, keyword_table->GetDefaultSearchProviderID());
- EXPECT_FALSE(keyword_table->GetDefaultSearchProviderBackup(&backup));
- EXPECT_TRUE(keyword_table->DidDefaultSearchProviderChange());
-
- // Change the signature.
- EXPECT_TRUE(keyword_table->meta_table_->SetValue(
- KeywordTable::kDefaultSearchIDBackupKey, 1));
- EXPECT_TRUE(keyword_table->meta_table_->SetValue(
- KeywordTable::kBackupSignatureKey, std::string()));
- EXPECT_FALSE(keyword_table->IsBackupSignatureValid(
- WebDatabase::kCurrentVersionNumber));
- EXPECT_EQ(1, keyword_table->GetDefaultSearchProviderID());
- EXPECT_FALSE(keyword_table->GetDefaultSearchProviderBackup(&backup));
- EXPECT_TRUE(keyword_table->DidDefaultSearchProviderChange());
-
- // Change keywords.
- EXPECT_TRUE(keyword_table->UpdateBackupSignature(
- WebDatabase::kCurrentVersionNumber));
- sql::Statement remove_keyword(keyword_table->db_->GetUniqueStatement(
- "DELETE FROM keywords WHERE id=1"));
- EXPECT_TRUE(remove_keyword.Run());
- EXPECT_TRUE(keyword_table->IsBackupSignatureValid(
- WebDatabase::kCurrentVersionNumber));
- EXPECT_EQ(1, keyword_table->GetDefaultSearchProviderID());
-
- EXPECT_TRUE(keyword_table->GetDefaultSearchProviderBackup(&backup));
- EXPECT_EQ(kInvalidTemplateURLID, backup.id);
- EXPECT_EQ(keyword.short_name, backup.short_name);
- EXPECT_EQ(keyword.keyword(), backup.keyword());
- EXPECT_EQ(keyword.url(), backup.url());
- EXPECT_EQ(keyword.suggestions_url, backup.suggestions_url);
- EXPECT_EQ(keyword.favicon_url, backup.favicon_url);
- EXPECT_EQ(keyword.show_in_default_list, backup.show_in_default_list);
- EXPECT_EQ(keyword.safe_for_autoreplace, backup.safe_for_autoreplace);
- EXPECT_TRUE(keyword_table->DidDefaultSearchProviderChange());
-
- // Change keywords backup.
- sql::Statement remove_keyword_backup(keyword_table->db_->GetUniqueStatement(
- "DELETE FROM keywords_backup WHERE id=1"));
- EXPECT_TRUE(remove_keyword_backup.Run());
- EXPECT_FALSE(keyword_table->IsBackupSignatureValid(
- WebDatabase::kCurrentVersionNumber));
- EXPECT_EQ(1, keyword_table->GetDefaultSearchProviderID());
- EXPECT_FALSE(keyword_table->GetDefaultSearchProviderBackup(&backup));
- EXPECT_TRUE(keyword_table->DidDefaultSearchProviderChange());
-}
-
TEST_F(KeywordTableTest, GetTableContents) {
WebDatabase db;
ASSERT_EQ(sql::INIT_OK, db.Init(file_));
@@ -282,10 +173,6 @@ TEST_F(KeywordTableTest, GetTableContents) {
EXPECT_TRUE(keyword_table->GetTableContents("keywords",
WebDatabase::kCurrentVersionNumber, &contents));
EXPECT_EQ(kTestContents, contents);
-
- EXPECT_TRUE(keyword_table->GetTableContents("keywords_backup",
- WebDatabase::kCurrentVersionNumber, &contents));
- EXPECT_EQ(kTestContents, contents);
}
TEST_F(KeywordTableTest, GetTableContentsOrdering) {
@@ -329,10 +216,6 @@ TEST_F(KeywordTableTest, GetTableContentsOrdering) {
EXPECT_TRUE(keyword_table->GetTableContents("keywords",
WebDatabase::kCurrentVersionNumber, &contents));
EXPECT_EQ(kTestContents, contents);
-
- EXPECT_TRUE(keyword_table->GetTableContents("keywords_backup",
- WebDatabase::kCurrentVersionNumber, &contents));
- EXPECT_EQ(kTestContents, contents);
}
TEST_F(KeywordTableTest, UpdateKeyword) {
@@ -433,8 +316,6 @@ TEST_F(KeywordTableTest, SanitizeURLs) {
s.BindString16(0, string16());
s.BindInt64(1, 2000);
EXPECT_TRUE(s.Run());
- EXPECT_TRUE(keyword_table->UpdateBackupSignature(
- WebDatabase::kCurrentVersionNumber));
// GetKeywords() should erase the entry with the empty URL field.
EXPECT_TRUE(keyword_table->GetKeywords(&keywords));
diff --git a/chrome/browser/webdata/web_data_service.cc b/chrome/browser/webdata/web_data_service.cc
index e7b2839..48f9321 100644
--- a/chrome/browser/webdata/web_data_service.cc
+++ b/chrome/browser/webdata/web_data_service.cc
@@ -72,9 +72,7 @@ WDAppImagesResult::~WDAppImagesResult() {}
WDKeywordsResult::WDKeywordsResult()
: default_search_provider_id(0),
- builtin_keyword_version(0),
- backup_valid(false),
- did_default_search_provider_change(false) {
+ builtin_keyword_version(0) {
}
WDKeywordsResult::~WDKeywordsResult() {}
@@ -800,11 +798,6 @@ void WebDataService::GetKeywordsImpl(WebDataRequest* request) {
db_->GetKeywordTable()->GetDefaultSearchProviderID();
result.builtin_keyword_version =
db_->GetKeywordTable()->GetBuiltinKeywordVersion();
- result.did_default_search_provider_change =
- db_->GetKeywordTable()->DidDefaultSearchProviderChange();
- result.backup_valid = result.did_default_search_provider_change &&
- db_->GetKeywordTable()->GetDefaultSearchProviderBackup(
- &result.default_search_provider_backup);
request->SetResult(
new WDResult<WDKeywordsResult>(KEYWORDS_RESULT, result));
}
diff --git a/chrome/browser/webdata/web_data_service.h b/chrome/browser/webdata/web_data_service.h
index 2f29f29..fa412f8 100644
--- a/chrome/browser/webdata/web_data_service.h
+++ b/chrome/browser/webdata/web_data_service.h
@@ -90,12 +90,6 @@ struct WDKeywordsResult {
int64 default_search_provider_id;
// Version of the built-in keywords. A value of 0 indicates a first run.
int builtin_keyword_version;
- // Backup of the default search provider, and whether the backup is valid.
- bool backup_valid;
- TemplateURLData default_search_provider_backup;
- // Indicates if default search provider has been changed by something
- // other than user's action in the browser.
- bool did_default_search_provider_change;
};
class WebDataServiceConsumer;
diff --git a/chrome/browser/webdata/web_data_service_unittest.cc b/chrome/browser/webdata/web_data_service_unittest.cc
index af5201f..4477001 100644
--- a/chrome/browser/webdata/web_data_service_unittest.cc
+++ b/chrome/browser/webdata/web_data_service_unittest.cc
@@ -826,12 +826,3 @@ TEST_F(WebDataServiceTest, WebIntentsRemoveDefaultByServiceURL) {
ASSERT_EQ(1U, consumer.services_.size());
EXPECT_EQ(service_url_1.spec(), consumer.services_[0].service_url);
}
-
-TEST_F(WebDataServiceTest, DidDefaultSearchProviderChangeOnNewProfile) {
- KeywordsConsumer consumer;
- wds_->GetKeywords(&consumer);
- WaitUntilCalled();
- ASSERT_TRUE(consumer.load_succeeded);
- EXPECT_FALSE(consumer.keywords_result.did_default_search_provider_change);
- EXPECT_FALSE(consumer.keywords_result.backup_valid);
-}
diff --git a/chrome/browser/webdata/web_database.cc b/chrome/browser/webdata/web_database.cc
index cdf9d58..02c1f80 100644
--- a/chrome/browser/webdata/web_database.cc
+++ b/chrome/browser/webdata/web_database.cc
@@ -21,11 +21,11 @@
// corresponding changes must happen in the unit tests, and new migration test
// added. See |WebDatabaseMigrationTest::kCurrentTestedVersionNumber|.
// static
-const int WebDatabase::kCurrentVersionNumber = 47;
+const int WebDatabase::kCurrentVersionNumber = 48;
namespace {
-const int kCompatibleVersionNumber = 47;
+const int kCompatibleVersionNumber = 48;
// Change the version number and possibly the compatibility version of
// |meta_table_|.
@@ -158,9 +158,9 @@ sql::InitStatus WebDatabase::Init(const FilePath& db_name) {
}
sql::InitStatus WebDatabase::MigrateOldVersionsAsNeeded() {
- // Some malware tries to force protector to re-sign things by lowering the
- // version number, causing migration to fail. Ensure the version number is at
- // least as high as the compatible version number.
+ // Some malware used to lower the version number, causing migration to
+ // fail. Ensure the version number is at least as high as the compatible
+ // version number.
int current_version = std::max(meta_table_.GetVersionNumber(),
meta_table_.GetCompatibleVersionNumber());
if (current_version > meta_table_.GetVersionNumber())
@@ -350,6 +350,13 @@ sql::InitStatus WebDatabase::MigrateOldVersionsAsNeeded() {
ChangeVersion(&meta_table_, 47, true);
// FALL THROUGH
+ case 47:
+ if (!keyword_table_->MigrateToVersion48RemoveKeywordsBackup())
+ return FailedMigrationTo(48);
+
+ ChangeVersion(&meta_table_, 48, true);
+ // FALL THROUGH
+
// Add successive versions here. Each should set the version number and
// compatible version number as appropriate, then fall through to the next
// case.
diff --git a/chrome/browser/webdata/web_database_migration_unittest.cc b/chrome/browser/webdata/web_database_migration_unittest.cc
index 5cca55b..de4de08 100644
--- a/chrome/browser/webdata/web_database_migration_unittest.cc
+++ b/chrome/browser/webdata/web_database_migration_unittest.cc
@@ -125,6 +125,24 @@ void CreditCard32FromStatement(const sql::Statement& s,
*date_modified = s.ColumnInt64(5);
}
+void CheckHasBackupData(sql::MetaTable* meta_table) {
+ std::string value;
+ EXPECT_TRUE(meta_table->GetValue(
+ "Default Search Provider ID Backup", &value));
+ EXPECT_TRUE(meta_table->GetValue(
+ "Default Search Provider ID Backup Signature", &value));
+}
+
+void CheckNoBackupData(const sql::Connection& connection,
+ sql::MetaTable* meta_table) {
+ std::string value;
+ EXPECT_FALSE(meta_table->GetValue(
+ "Default Search Provider ID Backup", &value));
+ EXPECT_FALSE(meta_table->GetValue(
+ "Default Search Provider ID Backup Signature", &value));
+ EXPECT_FALSE(connection.DoesTableExist("keywords_backup"));
+}
+
} // anonymous namespace
// The WebDatabaseMigrationTest encapsulates testing of database migrations.
@@ -195,7 +213,7 @@ class WebDatabaseMigrationTest : public testing::Test {
DISALLOW_COPY_AND_ASSIGN(WebDatabaseMigrationTest);
};
-const int WebDatabaseMigrationTest::kCurrentTestedVersionNumber = 47;
+const int WebDatabaseMigrationTest::kCurrentTestedVersionNumber = 48;
void WebDatabaseMigrationTest::LoadDatabase(const FilePath::StringType& file) {
std::string contents;
@@ -1435,8 +1453,7 @@ TEST_F(WebDatabaseMigrationTest, MigrateVersion38ToCurrent) {
}
}
-// Tests that the backup field for the default search provider gets added to
-// the meta table of a version 39 database.
+// Tests that no backup data is added to a version 39 database.
TEST_F(WebDatabaseMigrationTest, MigrateVersion39ToCurrent) {
// This schema is taken from a build prior to the addition of the default
// search provider backup field to the meta table.
@@ -1456,84 +1473,7 @@ TEST_F(WebDatabaseMigrationTest, MigrateVersion39ToCurrent) {
EXPECT_TRUE(meta_table.GetValue(KeywordTable::kDefaultSearchProviderKey,
&default_search_provider_id));
- int64 default_search_provider_id_backup = 0;
- EXPECT_FALSE(meta_table.GetValue(KeywordTable::kDefaultSearchIDBackupKey,
- &default_search_provider_id_backup));
-
- std::string default_search_provider_id_backup_signature;
- EXPECT_FALSE(meta_table.GetValue(KeywordTable::kBackupSignatureKey,
- &default_search_provider_id_backup_signature));
- }
-
- // Load the database via the WebDatabase class and migrate the database to
- // the current version.
- {
- WebDatabase db;
- ASSERT_EQ(sql::INIT_OK, db.Init(GetDatabasePath()));
- ASSERT_FALSE(db.GetKeywordTable()->DidDefaultSearchProviderChange());
- }
-
- // Verify post-conditions. These are expectations for current version of the
- // database.
- {
- sql::Connection connection;
- ASSERT_TRUE(connection.Open(GetDatabasePath()));
- ASSERT_TRUE(sql::MetaTable::DoesTableExist(&connection));
-
- // Check version.
- EXPECT_EQ(kCurrentTestedVersionNumber, VersionFromConnection(&connection));
-
- sql::MetaTable meta_table;
- ASSERT_TRUE(meta_table.Init(&connection, kCurrentTestedVersionNumber,
- kCurrentTestedVersionNumber));
-
- int64 default_search_provider_id = 0;
- EXPECT_TRUE(meta_table.GetValue(KeywordTable::kDefaultSearchProviderKey,
- &default_search_provider_id));
-
- int64 default_search_provider_id_backup = 0;
- EXPECT_TRUE(meta_table.GetValue(KeywordTable::kDefaultSearchIDBackupKey,
- &default_search_provider_id_backup));
- EXPECT_EQ(default_search_provider_id, default_search_provider_id_backup);
-
- std::string default_search_provider_id_backup_signature;
- EXPECT_TRUE(meta_table.GetValue(KeywordTable::kBackupSignatureKey,
- &default_search_provider_id_backup_signature));
- }
-}
-
-#if !defined(GOOGLE_CHROME_BUILD)
-// Test that a valid backup is not overwritten during migration from version 39.
-// This is enabled on Chromium only because a valid signature is required for
-// this test, which makes it key-dependent.
-TEST_F(WebDatabaseMigrationTest, MigrateVersion39WithBackupToCurrent) {
- // This schema is taken from a build prior to the addition of the default
- // search provider backup field to the meta table.
- ASSERT_NO_FATAL_FAILURE(
- LoadDatabase(FILE_PATH_LITERAL("version_39_with_backup.sql")));
-
- // Verify pre-conditions. These are expectations for version 39 of the
- // database.
- {
- sql::Connection connection;
- ASSERT_TRUE(connection.Open(GetDatabasePath()));
- ASSERT_TRUE(sql::MetaTable::DoesTableExist(&connection));
-
- sql::MetaTable meta_table;
- ASSERT_TRUE(meta_table.Init(&connection, 39, 39));
-
- int64 default_search_provider_id = 0;
- EXPECT_TRUE(meta_table.GetValue(KeywordTable::kDefaultSearchProviderKey,
- &default_search_provider_id));
-
- int64 default_search_provider_id_backup = 0;
- EXPECT_TRUE(meta_table.GetValue(KeywordTable::kDefaultSearchIDBackupKey,
- &default_search_provider_id_backup));
- EXPECT_NE(default_search_provider_id, default_search_provider_id_backup);
-
- std::string default_search_provider_id_backup_signature;
- EXPECT_TRUE(meta_table.GetValue(KeywordTable::kBackupSignatureKey,
- &default_search_provider_id_backup_signature));
+ EXPECT_NO_FATAL_FAILURE(CheckNoBackupData(connection, &meta_table));
}
// Load the database via the WebDatabase class and migrate the database to
@@ -1541,8 +1481,6 @@ TEST_F(WebDatabaseMigrationTest, MigrateVersion39WithBackupToCurrent) {
{
WebDatabase db;
ASSERT_EQ(sql::INIT_OK, db.Init(GetDatabasePath()));
- // A change to the default search provider must be detected.
- ASSERT_TRUE(db.GetKeywordTable()->DidDefaultSearchProviderChange());
}
// Verify post-conditions. These are expectations for current version of the
@@ -1562,25 +1500,14 @@ TEST_F(WebDatabaseMigrationTest, MigrateVersion39WithBackupToCurrent) {
int64 default_search_provider_id = 0;
EXPECT_TRUE(meta_table.GetValue(KeywordTable::kDefaultSearchProviderKey,
&default_search_provider_id));
+ EXPECT_NE(0, default_search_provider_id);
- int64 default_search_provider_id_backup = 0;
- EXPECT_TRUE(meta_table.GetValue(KeywordTable::kDefaultSearchIDBackupKey,
- &default_search_provider_id_backup));
- EXPECT_NE(default_search_provider_id, default_search_provider_id_backup);
-
- std::string default_search_provider_id_backup_signature;
- EXPECT_TRUE(meta_table.GetValue(KeywordTable::kBackupSignatureKey,
- &default_search_provider_id_backup_signature));
+ EXPECT_NO_FATAL_FAILURE(CheckNoBackupData(connection, &meta_table));
}
}
-#endif // !defined(GOOGLE_CHROME_BUILD)
-// Tests that the backup field for the default search provider is rewritten
-// despite any value in the old version.
+// Tests that the backup data is removed from the database.
TEST_F(WebDatabaseMigrationTest, MigrateVersion40ToCurrent) {
- // This schema is taken from a build after the addition of the default
- // search provider backup field to the meta table. Due to crbug.com/101815
- // the signature was empty in all build between revisions 106214 and 108111.
ASSERT_NO_FATAL_FAILURE(LoadDatabase(FILE_PATH_LITERAL("version_40.sql")));
// Verify pre-conditions. These are expectations for version 40 of the
@@ -1597,14 +1524,7 @@ TEST_F(WebDatabaseMigrationTest, MigrateVersion40ToCurrent) {
EXPECT_TRUE(meta_table.GetValue(KeywordTable::kDefaultSearchProviderKey,
&default_search_provider_id));
- int64 default_search_provider_id_backup = 0;
- EXPECT_TRUE(meta_table.GetValue(KeywordTable::kDefaultSearchIDBackupKey,
- &default_search_provider_id_backup));
-
- std::string default_search_provider_id_backup_signature;
- EXPECT_TRUE(meta_table.GetValue(KeywordTable::kBackupSignatureKey,
- &default_search_provider_id_backup_signature));
- EXPECT_TRUE(default_search_provider_id_backup_signature.empty());
+ EXPECT_NO_FATAL_FAILURE(CheckHasBackupData(&meta_table));
}
// Load the database via the WebDatabase class and migrate the database to
@@ -1612,7 +1532,6 @@ TEST_F(WebDatabaseMigrationTest, MigrateVersion40ToCurrent) {
{
WebDatabase db;
ASSERT_EQ(sql::INIT_OK, db.Init(GetDatabasePath()));
- ASSERT_FALSE(db.GetKeywordTable()->DidDefaultSearchProviderChange());
}
// Verify post-conditions. These are expectations for current version of the
@@ -1634,20 +1553,11 @@ TEST_F(WebDatabaseMigrationTest, MigrateVersion40ToCurrent) {
&default_search_provider_id));
EXPECT_NE(0, default_search_provider_id);
- int64 default_search_provider_id_backup = 0;
- EXPECT_TRUE(meta_table.GetValue(KeywordTable::kDefaultSearchIDBackupKey,
- &default_search_provider_id_backup));
- EXPECT_EQ(default_search_provider_id, default_search_provider_id_backup);
-
- std::string default_search_provider_id_backup_signature;
- EXPECT_TRUE(meta_table.GetValue(KeywordTable::kBackupSignatureKey,
- &default_search_provider_id_backup_signature));
- EXPECT_FALSE(default_search_provider_id_backup_signature.empty());
+ EXPECT_NO_FATAL_FAILURE(CheckNoBackupData(connection, &meta_table));
}
}
-// Used to test that the default search provider was backed up and signed,
-// before the backup method was changed in version 43.
+// Tests that the backup data is removed from the database.
TEST_F(WebDatabaseMigrationTest, MigrateVersion41ToCurrent) {
ASSERT_NO_FATAL_FAILURE(LoadDatabase(FILE_PATH_LITERAL("version_41.sql")));
@@ -1665,14 +1575,7 @@ TEST_F(WebDatabaseMigrationTest, MigrateVersion41ToCurrent) {
EXPECT_TRUE(meta_table.GetValue(KeywordTable::kDefaultSearchProviderKey,
&default_search_provider_id));
- int64 default_search_provider_id_backup = 0;
- EXPECT_TRUE(meta_table.GetValue(KeywordTable::kDefaultSearchIDBackupKey,
- &default_search_provider_id_backup));
-
- std::string default_search_provider_id_backup_signature;
- EXPECT_TRUE(meta_table.GetValue(KeywordTable::kBackupSignatureKey,
- &default_search_provider_id_backup_signature));
- EXPECT_FALSE(default_search_provider_id_backup_signature.empty());
+ EXPECT_NO_FATAL_FAILURE(CheckHasBackupData(&meta_table));
}
// Load the database via the WebDatabase class and migrate the database to
@@ -1680,7 +1583,6 @@ TEST_F(WebDatabaseMigrationTest, MigrateVersion41ToCurrent) {
{
WebDatabase db;
ASSERT_EQ(sql::INIT_OK, db.Init(GetDatabasePath()));
- ASSERT_FALSE(db.GetKeywordTable()->DidDefaultSearchProviderChange());
}
// Verify post-conditions. These are expectations for current version of the
@@ -1702,19 +1604,11 @@ TEST_F(WebDatabaseMigrationTest, MigrateVersion41ToCurrent) {
&default_search_provider_id));
EXPECT_NE(0, default_search_provider_id);
- int64 default_search_provider_id_backup = 0;
- EXPECT_TRUE(meta_table.GetValue(KeywordTable::kDefaultSearchIDBackupKey,
- &default_search_provider_id_backup));
- EXPECT_EQ(default_search_provider_id, default_search_provider_id_backup);
-
- std::string default_search_provider_id_backup_signature;
- EXPECT_TRUE(meta_table.GetValue(KeywordTable::kBackupSignatureKey,
- &default_search_provider_id_backup_signature));
- EXPECT_FALSE(default_search_provider_id_backup_signature.empty());
+ EXPECT_NO_FATAL_FAILURE(CheckNoBackupData(connection, &meta_table));
}
}
-// Tests that all keywords are backed up and signed.
+// Tests that the backup data is removed from the database.
TEST_F(WebDatabaseMigrationTest, MigrateVersion42ToCurrent) {
ASSERT_NO_FATAL_FAILURE(LoadDatabase(FILE_PATH_LITERAL("version_42.sql")));
@@ -1732,14 +1626,7 @@ TEST_F(WebDatabaseMigrationTest, MigrateVersion42ToCurrent) {
EXPECT_TRUE(meta_table.GetValue(KeywordTable::kDefaultSearchProviderKey,
&default_search_provider_id));
- int64 default_search_provider_id_backup = 0;
- EXPECT_TRUE(meta_table.GetValue(KeywordTable::kDefaultSearchIDBackupKey,
- &default_search_provider_id_backup));
-
- std::string default_search_provider_id_backup_signature;
- EXPECT_TRUE(meta_table.GetValue(KeywordTable::kBackupSignatureKey,
- &default_search_provider_id_backup_signature));
- EXPECT_FALSE(default_search_provider_id_backup_signature.empty());
+ EXPECT_NO_FATAL_FAILURE(CheckHasBackupData(&meta_table));
EXPECT_FALSE(connection.DoesTableExist("keywords_backup"));
}
@@ -1749,7 +1636,6 @@ TEST_F(WebDatabaseMigrationTest, MigrateVersion42ToCurrent) {
{
WebDatabase db;
ASSERT_EQ(sql::INIT_OK, db.Init(GetDatabasePath()));
- ASSERT_FALSE(db.GetKeywordTable()->DidDefaultSearchProviderChange());
}
// Verify post-conditions. These are expectations for current version of the
@@ -1771,50 +1657,11 @@ TEST_F(WebDatabaseMigrationTest, MigrateVersion42ToCurrent) {
&default_search_provider_id));
EXPECT_NE(0, default_search_provider_id);
- int64 default_search_provider_id_backup = 0;
- EXPECT_TRUE(meta_table.GetValue(KeywordTable::kDefaultSearchIDBackupKey,
- &default_search_provider_id_backup));
- EXPECT_EQ(default_search_provider_id, default_search_provider_id_backup);
-
- std::string default_search_provider_id_backup_signature;
- EXPECT_TRUE(meta_table.GetValue(KeywordTable::kBackupSignatureKey,
- &default_search_provider_id_backup_signature));
- EXPECT_FALSE(default_search_provider_id_backup_signature.empty());
-
- EXPECT_TRUE(connection.DoesTableExist("keywords_backup"));
- std::string query("SELECT " + KeywordTable::GetKeywordColumns() +
- " FROM keywords_backup");
- sql::Statement s(connection.GetUniqueStatement(query.c_str()));
- ASSERT_TRUE(s.Step());
- EXPECT_EQ(2, s.ColumnInt(0));
- EXPECT_EQ("Google", s.ColumnString(1));
- EXPECT_EQ("google.com", s.ColumnString(2));
- EXPECT_EQ("http://www.google.com/favicon.ico", s.ColumnString(3));
- EXPECT_EQ("{google:baseURL}search?{google:RLZ}{google:acceptedSuggestion}"
- "{google:originalQueryForSuggestion}sourceid=chrome&"
- "ie={inputEncoding}&q={searchTerms}",
- s.ColumnString(4));
- EXPECT_TRUE(s.ColumnBool(5));
- EXPECT_EQ(std::string(), s.ColumnString(6));
- EXPECT_EQ(0, s.ColumnInt(7));
- EXPECT_EQ(0, s.ColumnInt(8));
- EXPECT_EQ("UTF-8", s.ColumnString(9));
- EXPECT_TRUE(s.ColumnBool(10));
- EXPECT_EQ("{google:baseSuggestURL}search?client=chrome&hl={language}&"
- "q={searchTerms}", s.ColumnString(11));
- EXPECT_EQ(1, s.ColumnInt(12));
- //EXPECT_EQ(false, s.ColumnBool(13));
- EXPECT_EQ("{google:baseURL}webhp?{google:RLZ}sourceid=chrome-instant&"
- "ie={inputEncoding}&ion=1{searchTerms}&nord=1",
- s.ColumnString(14));
- EXPECT_EQ(0, s.ColumnInt(15));
- EXPECT_EQ("{1234-5678-90AB-CDEF}", s.ColumnString(16));
-
- EXPECT_FALSE(s.Step());
+ EXPECT_NO_FATAL_FAILURE(CheckNoBackupData(connection, &meta_table));
}
}
-// Tests that the default search provider is backed up and signed.
+// Tests that the backup data is removed from the database.
TEST_F(WebDatabaseMigrationTest, MigrateVersion43ToCurrent) {
ASSERT_NO_FATAL_FAILURE(LoadDatabase(FILE_PATH_LITERAL("version_43.sql")));
@@ -1836,18 +1683,8 @@ TEST_F(WebDatabaseMigrationTest, MigrateVersion43ToCurrent) {
EXPECT_NE(default_search_provider_id, 0);
previous_default_search_provider_id = default_search_provider_id;
- int64 default_search_provider_id_backup = 0;
- EXPECT_TRUE(meta_table.GetValue(KeywordTable::kDefaultSearchIDBackupKey,
- &default_search_provider_id_backup));
- EXPECT_NE(default_search_provider_id_backup, 0);
-
- // Backup ID is invalid, signature is invalid as well.
- EXPECT_NE(default_search_provider_id, default_search_provider_id_backup);
-
- std::string default_search_provider_id_backup_signature;
- EXPECT_TRUE(meta_table.GetValue(KeywordTable::kBackupSignatureKey,
- &default_search_provider_id_backup_signature));
- EXPECT_FALSE(default_search_provider_id_backup_signature.empty());
+ EXPECT_NO_FATAL_FAILURE(CheckHasBackupData(&meta_table));
+ EXPECT_TRUE(connection.DoesTableExist("keywords_backup"));
}
// Load the database via the WebDatabase class and migrate the database to
@@ -1855,7 +1692,6 @@ TEST_F(WebDatabaseMigrationTest, MigrateVersion43ToCurrent) {
{
WebDatabase db;
ASSERT_EQ(sql::INIT_OK, db.Init(GetDatabasePath()));
- ASSERT_FALSE(db.GetKeywordTable()->DidDefaultSearchProviderChange());
}
// Verify post-conditions. These are expectations for current version of the
@@ -1880,25 +1716,12 @@ TEST_F(WebDatabaseMigrationTest, MigrateVersion43ToCurrent) {
// Default search provider ID should not change.
EXPECT_EQ(previous_default_search_provider_id, default_search_provider_id);
- int64 default_search_provider_id_backup = 0;
- EXPECT_TRUE(meta_table.GetValue(KeywordTable::kDefaultSearchIDBackupKey,
- &default_search_provider_id_backup));
- // Backup ID must be updated to match the old default search provider ID.
- EXPECT_EQ(default_search_provider_id, default_search_provider_id_backup);
-
- std::string default_search_provider_id_backup_signature;
- EXPECT_TRUE(meta_table.GetValue(KeywordTable::kBackupSignatureKey,
- &default_search_provider_id_backup_signature));
- EXPECT_FALSE(default_search_provider_id_backup_signature.empty());
+ EXPECT_NO_FATAL_FAILURE(CheckNoBackupData(connection, &meta_table));
}
}
-#if !defined(GOOGLE_CHROME_BUILD)
// Tests that the |autogenerate_keyword| and |logo_id| columns get removed from
// the keyword table schema for a version 45 database.
-//
-// This is enabled on Chromium only because a valid signature is required for
-// this test, which makes it key-dependent.
TEST_F(WebDatabaseMigrationTest, MigrateVersion44ToCurrent) {
ASSERT_NO_FATAL_FAILURE(LoadDatabase(FILE_PATH_LITERAL("version_44.sql")));
@@ -1921,77 +1744,6 @@ TEST_F(WebDatabaseMigrationTest, MigrateVersion44ToCurrent) {
{
WebDatabase db;
ASSERT_EQ(sql::INIT_OK, db.Init(GetDatabasePath()));
- ASSERT_FALSE(db.GetKeywordTable()->DidDefaultSearchProviderChange());
-
- // The backup table should match the keyword table.
- std::string keywords_contents;
- EXPECT_TRUE(db.GetKeywordTable()->GetTableContents("keywords",
- kCurrentTestedVersionNumber, &keywords_contents));
- std::string keywords_backup_contents;
- EXPECT_TRUE(db.GetKeywordTable()->GetTableContents("keywords_backup",
- kCurrentTestedVersionNumber, &keywords_backup_contents));
- EXPECT_EQ(keywords_contents, keywords_backup_contents);
- }
-
- // Verify post-conditions. These are expectations for current version of the
- // database.
- {
- sql::Connection connection;
- ASSERT_TRUE(connection.Open(GetDatabasePath()));
- ASSERT_TRUE(sql::MetaTable::DoesTableExist(&connection));
-
- // Check version.
- EXPECT_EQ(kCurrentTestedVersionNumber, VersionFromConnection(&connection));
-
- sql::MetaTable meta_table;
- ASSERT_TRUE(meta_table.Init(&connection, kCurrentTestedVersionNumber,
- kCurrentTestedVersionNumber));
-
- // We should have removed this obsolete key.
- std::string default_search_provider_backup;
- EXPECT_FALSE(meta_table.GetValue("Default Search Provider Backup",
- &default_search_provider_backup));
-
- // Two columns should have been removed.
- EXPECT_FALSE(connection.DoesColumnExist("keywords",
- "autogenerate_keyword"));
- EXPECT_FALSE(connection.DoesColumnExist("keywords", "logo_id"));
- }
-}
-#endif // !defined(GOOGLE_CHROME_BUILD)
-
-// Like MigrateVersion44ToCurrent above, but with a corrupt backup signature.
-// This should result in us dropping the backup table but successfully migrating
-// otherwise.
-//
-// Because this test doesn't rely on a valid signature, we can run it on
-// official builds as well.
-TEST_F(WebDatabaseMigrationTest, MigrateVersion44CorruptBackupToCurrent) {
- ASSERT_NO_FATAL_FAILURE(
- LoadDatabase(FILE_PATH_LITERAL("version_44_backup_corrupt.sql")));
-
- // Verify pre-conditions. These are expectations for version 44 of the
- // database.
- {
- sql::Connection connection;
- ASSERT_TRUE(connection.Open(GetDatabasePath()));
- ASSERT_TRUE(sql::MetaTable::DoesTableExist(&connection));
-
- sql::MetaTable meta_table;
- ASSERT_TRUE(meta_table.Init(&connection, 44, 44));
-
- ASSERT_TRUE(connection.DoesColumnExist("keywords", "autogenerate_keyword"));
- ASSERT_TRUE(connection.DoesColumnExist("keywords", "logo_id"));
- }
-
- // Load the database via the WebDatabase class and migrate the database to
- // the current version.
- {
- WebDatabase db;
- ASSERT_EQ(sql::INIT_OK, db.Init(GetDatabasePath()));
- // We should detect a "search provider change" as a side effect of dropping
- // the backup table.
- ASSERT_TRUE(db.GetKeywordTable()->DidDefaultSearchProviderChange());
}
// Verify post-conditions. These are expectations for current version of the
@@ -2018,8 +1770,8 @@ TEST_F(WebDatabaseMigrationTest, MigrateVersion44CorruptBackupToCurrent) {
"autogenerate_keyword"));
EXPECT_FALSE(connection.DoesColumnExist("keywords", "logo_id"));
- // The backup table should be gone.
- EXPECT_FALSE(connection.DoesTableExist("keywords_backup"));
+ // Backup data should have been removed.
+ EXPECT_NO_FATAL_FAILURE(CheckNoBackupData(connection, &meta_table));
}
}
@@ -2209,12 +1961,8 @@ TEST_F(WebDatabaseMigrationTest, MigrateVersion45CompatibleToCurrent) {
}
}
-#if !defined(GOOGLE_CHROME_BUILD)
// Tests that the |alternate_urls| column is added to the keyword table schema
// for a version 47 database.
-//
-// This is enabled on Chromium only because a valid signature is required for
-// this test, which makes it key-dependent.
TEST_F(WebDatabaseMigrationTest, MigrateVersion46ToCurrent) {
ASSERT_NO_FATAL_FAILURE(
LoadDatabase(FILE_PATH_LITERAL("version_46.sql")));
@@ -2239,7 +1987,6 @@ TEST_F(WebDatabaseMigrationTest, MigrateVersion46ToCurrent) {
{
WebDatabase db;
ASSERT_EQ(sql::INIT_OK, db.Init(GetDatabasePath()));
- ASSERT_FALSE(db.GetKeywordTable()->DidDefaultSearchProviderChange());
}
// Verify post-conditions. These are expectations for current version of the
@@ -2254,23 +2001,14 @@ TEST_F(WebDatabaseMigrationTest, MigrateVersion46ToCurrent) {
// A new column should have been created.
EXPECT_TRUE(connection.DoesColumnExist("keywords", "alternate_urls"));
- ASSERT_TRUE(connection.DoesColumnExist("keywords_backup",
- "alternate_urls"));
}
}
-#endif // !defined(GOOGLE_CHROME_BUILD)
-
-// Like MigrateVersion46ToCurrent above, but with a corrupt backup signature.
-// This should result in us dropping the backup table but successfully migrating
-// otherwise.
-//
-// Because this test doesn't rely on a valid signature, we can run it on
-// official builds as well.
-TEST_F(WebDatabaseMigrationTest, MigrateVersion46CorruptBackupToCurrent) {
- ASSERT_NO_FATAL_FAILURE(
- LoadDatabase(FILE_PATH_LITERAL("version_46_backup_corrupt.sql")));
- // Verify pre-conditions. These are expectations for version 46 of the
+// Tests that the backup data is removed from the database.
+TEST_F(WebDatabaseMigrationTest, MigrateVersion47ToCurrent) {
+ ASSERT_NO_FATAL_FAILURE(LoadDatabase(FILE_PATH_LITERAL("version_47.sql")));
+
+ // Verify pre-conditions. These are expectations for version 47 of the
// database.
{
sql::Connection connection;
@@ -2278,11 +2016,15 @@ TEST_F(WebDatabaseMigrationTest, MigrateVersion46CorruptBackupToCurrent) {
ASSERT_TRUE(sql::MetaTable::DoesTableExist(&connection));
sql::MetaTable meta_table;
- ASSERT_TRUE(meta_table.Init(&connection, 46, 46));
+ ASSERT_TRUE(meta_table.Init(&connection, 47, 47));
- ASSERT_FALSE(connection.DoesColumnExist("keywords", "alternate_urls"));
- ASSERT_FALSE(connection.DoesColumnExist("keywords_backup",
- "alternate_urls"));
+ int64 default_search_provider_id = 0;
+ EXPECT_TRUE(meta_table.GetValue(KeywordTable::kDefaultSearchProviderKey,
+ &default_search_provider_id));
+ EXPECT_NE(0, default_search_provider_id);
+
+ EXPECT_NO_FATAL_FAILURE(CheckHasBackupData(&meta_table));
+ EXPECT_TRUE(connection.DoesTableExist("keywords_backup"));
}
// Load the database via the WebDatabase class and migrate the database to
@@ -2290,9 +2032,6 @@ TEST_F(WebDatabaseMigrationTest, MigrateVersion46CorruptBackupToCurrent) {
{
WebDatabase db;
ASSERT_EQ(sql::INIT_OK, db.Init(GetDatabasePath()));
- // We should detect a "search provider change" as a side effect of dropping
- // the backup table.
- ASSERT_TRUE(db.GetKeywordTable()->DidDefaultSearchProviderChange());
}
// Verify post-conditions. These are expectations for current version of the
@@ -2305,10 +2044,15 @@ TEST_F(WebDatabaseMigrationTest, MigrateVersion46CorruptBackupToCurrent) {
// Check version.
EXPECT_EQ(kCurrentTestedVersionNumber, VersionFromConnection(&connection));
- // A new column should have been created.
- EXPECT_TRUE(connection.DoesColumnExist("keywords", "alternate_urls"));
+ sql::MetaTable meta_table;
+ ASSERT_TRUE(meta_table.Init(&connection, kCurrentTestedVersionNumber,
+ kCurrentTestedVersionNumber));
- // The backup table should be gone.
- EXPECT_FALSE(connection.DoesTableExist("keywords_backup"));
+ int64 default_search_provider_id = 0;
+ EXPECT_TRUE(meta_table.GetValue(KeywordTable::kDefaultSearchProviderKey,
+ &default_search_provider_id));
+ EXPECT_NE(0, default_search_provider_id);
+
+ EXPECT_NO_FATAL_FAILURE(CheckNoBackupData(connection, &meta_table));
}
}
diff --git a/chrome/chrome_browser.gypi b/chrome/chrome_browser.gypi
index fe2d190..dd40d7b 100644
--- a/chrome/chrome_browser.gypi
+++ b/chrome/chrome_browser.gypi
@@ -1628,31 +1628,6 @@
'browser/profiles/refcounted_profile_keyed_service_factory.cc',
'browser/profiles/refcounted_profile_keyed_service_factory.h',
'browser/profiles/storage_partition_descriptor.h',
- 'browser/protector/base_prefs_change.cc',
- 'browser/protector/base_prefs_change.h',
- 'browser/protector/base_setting_change.cc',
- 'browser/protector/base_setting_change.h',
- 'browser/protector/composite_settings_change.cc',
- 'browser/protector/composite_settings_change.h',
- 'browser/protector/default_search_provider_change.cc',
- 'browser/protector/histograms.cc',
- 'browser/protector/histograms.h',
- 'browser/protector/homepage_change.cc',
- 'browser/protector/keys.cc',
- 'browser/protector/keys.h',
- 'browser/protector/prefs_backup_invalid_change.cc',
- 'browser/protector/protected_prefs_watcher.cc',
- 'browser/protector/protected_prefs_watcher.h',
- 'browser/protector/protector_service.cc',
- 'browser/protector/protector_service.h',
- 'browser/protector/protector_service_factory.cc',
- 'browser/protector/protector_service_factory.h',
- 'browser/protector/protector_utils.cc',
- 'browser/protector/protector_utils.h',
- 'browser/protector/session_startup_change.cc',
- 'browser/protector/settings_change_global_error.cc',
- 'browser/protector/settings_change_global_error.h',
- 'browser/protector/settings_change_global_error_delegate.h',
'browser/remove_rows_table_model.h',
'browser/renderer_host/chrome_render_message_filter.cc',
'browser/renderer_host/chrome_render_message_filter.h',
@@ -2365,14 +2340,6 @@
'../native_client/src/trusted/service_runtime/service_runtime.gyp:sel',
],
}],
- ['branding=="Chrome"', {
- 'sources': [
- 'browser/protector/internal/keys_internal.cc',
- ],
- 'sources!': [
- 'browser/protector/keys.cc',
- ],
- }],
['debug_devtools==1', {
'defines': [
'DEBUG_DEVTOOLS=1',
@@ -2969,26 +2936,6 @@
'browser/web_resource/plugins_resource_service.h',
],
}],
- ['enable_protector_service==0', {
- 'sources!': [
- 'browser/protector/base_prefs_change.cc',
- 'browser/protector/base_prefs_change.h',
- 'browser/protector/base_setting_change.cc',
- 'browser/protector/base_setting_change.h',
- 'browser/protector/default_search_provider_change.cc',
- 'browser/protector/prefs_backup_invalid_change.cc',
- 'browser/protector/protected_prefs_watcher.cc',
- 'browser/protector/protected_prefs_watcher.h',
- 'browser/protector/protector_service.cc',
- 'browser/protector/protector_service.h',
- 'browser/protector/protector_service_factory.cc',
- 'browser/protector/protector_service_factory.h',
- 'browser/protector/session_startup_change.cc',
- 'browser/protector/settings_change_global_error.cc',
- 'browser/protector/settings_change_global_error.h',
- 'browser/protector/settings_change_global_error_delegate.h',
- ],
- }],
[ 'use_openssl==1', {
'sources!': [
'browser/importer/nss_decryptor.cc',
diff --git a/chrome/chrome_tests.gypi b/chrome/chrome_tests.gypi
index 81ce1d0..c2d28ed 100644
--- a/chrome/chrome_tests.gypi
+++ b/chrome/chrome_tests.gypi
@@ -1093,8 +1093,6 @@
'browser/process_singleton_browsertest.cc',
'browser/profiles/profile_browsertest.cc',
'browser/profiles/profile_manager_browsertest.cc',
- 'browser/protector/default_search_provider_change_browsertest.cc',
- 'browser/protector/protector_service_browsertest.cc',
'browser/referrer_policy_browsertest.cc',
'browser/renderer_host/render_process_host_chrome_browsertest.cc',
'browser/renderer_host/web_cache_manager_browsertest.cc',
@@ -1385,10 +1383,6 @@
'test/data/webui/certificate_viewer_ui_test-inl.h',
],
}, { # chromeos==1
- 'sources/': [
- # Protector is disabled on CrOS.
- ['exclude', '^browser/protector'],
- ],
'sources!': [
'browser/printing/cloud_print/test/cloud_print_policy_browsertest.cc',
'browser/printing/cloud_print/test/cloud_print_proxy_process_browsertest.cc',
diff --git a/chrome/chrome_tests_unit.gypi b/chrome/chrome_tests_unit.gypi
index c38b57c4..890cac7 100644
--- a/chrome/chrome_tests_unit.gypi
+++ b/chrome/chrome_tests_unit.gypi
@@ -151,10 +151,6 @@
'browser/prefs/mock_pref_change_callback.h',
'browser/prefs/pref_service_mock_builder.cc',
'browser/prefs/pref_service_mock_builder.h',
- 'browser/protector/mock_protector_service.cc',
- 'browser/protector/mock_protector_service.h',
- 'browser/protector/mock_setting_change.cc',
- 'browser/protector/mock_setting_change.h',
'browser/search_engines/template_url_service_test_util.cc',
'browser/search_engines/template_url_service_test_util.h',
'browser/sessions/session_service_test_helper.cc',
@@ -991,11 +987,6 @@
'browser/profiles/profile_info_util_unittest.cc',
'browser/profiles/profile_manager_unittest.cc',
'browser/profiles/profile_shortcut_manager_unittest_win.cc',
- 'browser/protector/composite_settings_change_unittest.cc',
- 'browser/protector/homepage_change_unittest.cc',
- 'browser/protector/prefs_backup_invalid_change_unittest.cc',
- 'browser/protector/protected_prefs_watcher_unittest.cc',
- 'browser/protector/session_startup_change_unittest.cc',
'browser/renderer_host/plugin_info_message_filter_unittest.cc',
'browser/renderer_host/web_cache_manager_unittest.cc',
'browser/resources/print_preview/data/measurement_system.js',
@@ -2195,11 +2186,6 @@
'browser/language_usage_metrics_unittest.cc',
],
}],
- ['enable_protector_service==0', {
- 'sources/': [
- ['exclude', '^browser/protector/'],
- ],
- }],
['toolkit_views==1', {
'dependencies': [
'../ui/views/views.gyp:views',
diff --git a/chrome/common/chrome_switches.cc b/chrome/common/chrome_switches.cc
index 3ab0746..fcb6d37 100644
--- a/chrome/common/chrome_switches.cc
+++ b/chrome/common/chrome_switches.cc
@@ -1082,9 +1082,6 @@ const char kPromoServerURL[] = "promo-server-url";
// Default is yes.
const char kPromptForExternalExtensions[] = "prompt-for-external-extensions";
-// Enables the Protector feature.
-const char kProtector[] = "protector";
-
// Forces proxy auto-detection.
const char kProxyAutoDetect[] = "proxy-auto-detect";
diff --git a/chrome/common/chrome_switches.h b/chrome/common/chrome_switches.h
index 8ba8f4e..b085c5f 100644
--- a/chrome/common/chrome_switches.h
+++ b/chrome/common/chrome_switches.h
@@ -290,7 +290,6 @@ extern const char kProfilingFlush[];
extern const char kProfilingOutputFile[];
extern const char kPromoServerURL[];
extern const char kPromptForExternalExtensions[];
-extern const char kProtector[];
extern const char kProxyAutoDetect[];
extern const char kProxyBypassList[];
extern const char kProxyPacUrl[];
diff --git a/chrome/test/base/testing_profile.cc b/chrome/test/base/testing_profile.cc
index ab118b7..1d2a6f6 100644
--- a/chrome/test/base/testing_profile.cc
+++ b/chrome/test/base/testing_profile.cc
@@ -41,7 +41,6 @@
#include "chrome/browser/prerender/prerender_manager.h"
#include "chrome/browser/profiles/profile_dependency_manager.h"
#include "chrome/browser/profiles/storage_partition_descriptor.h"
-#include "chrome/browser/protector/protector_service_factory.h"
#include "chrome/browser/search_engines/template_url_fetcher_factory.h"
#include "chrome/browser/speech/chrome_speech_recognition_preferences.h"
#include "chrome/browser/webdata/web_data_service.h"
@@ -555,14 +554,6 @@ policy::PolicyService* TestingProfile::GetPolicyService() {
}
void TestingProfile::SetPrefService(PrefService* prefs) {
-#if defined(ENABLE_PROTECTOR_SERVICE)
- // ProtectorService binds itself very closely to the PrefService at the moment
- // of Profile creation and watches pref changes to update their backup.
- // For tests that replace the PrefService after TestingProfile creation,
- // ProtectorService is disabled to prevent further invalid memory accesses.
- protector::ProtectorServiceFactory::GetInstance()->
- SetTestingFactory(this, NULL);
-#endif
prefs_.reset(prefs);
}
diff --git a/chrome/test/data/web_database/version_41.sql b/chrome/test/data/web_database/version_41.sql
index fd5c217..4804d16 100644
--- a/chrome/test/data/web_database/version_41.sql
+++ b/chrome/test/data/web_database/version_41.sql
@@ -5,7 +5,7 @@ INSERT INTO "meta" VALUES('version','41');
INSERT INTO "meta" VALUES('last_compatible_version','41');
INSERT INTO "meta" VALUES('Default Search Provider ID','2');
INSERT INTO "meta" VALUES('Default Search Provider ID Backup','2');
-INSERT INTO "meta" VALUES('Default Search Provider ID Backup Signature','Signature');
+INSERT INTO "meta" VALUES('Default Search Provider ID Backup Signature','');
INSERT INTO "meta" VALUES('Builtin Keyword Version','33');
CREATE TABLE keywords (id INTEGER PRIMARY KEY,short_name VARCHAR NOT NULL,keyword VARCHAR NOT NULL,favicon_url VARCHAR NOT NULL,url VARCHAR NOT NULL,show_in_default_list INTEGER,safe_for_autoreplace INTEGER,originating_url VARCHAR,date_created INTEGER DEFAULT 0,usage_count INTEGER DEFAULT 0,input_encodings VARCHAR,suggest_url VARCHAR,prepopulate_id INTEGER DEFAULT 0,autogenerate_keyword INTEGER DEFAULT 0,logo_id INTEGER DEFAULT 0,created_by_policy INTEGER DEFAULT 0,instant_url VARCHAR,last_modified INTEGER DEFAULT 0, sync_guid VARCHAR);
INSERT INTO "keywords" VALUES(2,'Google','google.com','http://www.google.com/favicon.ico','{google:baseURL}search?{google:RLZ}{google:acceptedSuggestion}{google:originalQueryForSuggestion}sourceid=chrome&ie={inputEncoding}&q={searchTerms}',1,1,'',0,0,'UTF-8','{google:baseSuggestURL}search?client=chrome&hl={language}&q={searchTerms}',1,1,6262,0,'{google:baseURL}webhp?{google:RLZ}sourceid=chrome-instant&ie={inputEncoding}&ion=1{searchTerms}&nord=1',0,'{1234-5678-90AB-CDEF}');
diff --git a/chrome/test/data/web_database/version_42.sql b/chrome/test/data/web_database/version_42.sql
index 5b85d55..01b9925 100644
--- a/chrome/test/data/web_database/version_42.sql
+++ b/chrome/test/data/web_database/version_42.sql
@@ -5,7 +5,7 @@ INSERT INTO "meta" VALUES('version','42');
INSERT INTO "meta" VALUES('last_compatible_version','42');
INSERT INTO "meta" VALUES('Default Search Provider ID','2');
INSERT INTO "meta" VALUES('Default Search Provider ID Backup','2');
-INSERT INTO "meta" VALUES('Default Search Provider ID Backup Signature','Signature');
+INSERT INTO "meta" VALUES('Default Search Provider ID Backup Signature','');
INSERT INTO "meta" VALUES('Default Search Provider Backup','2Googlegoogle.comhttp://www.google.com/favicon.ico{google:baseURL}search?{google:RLZ}{google:acceptedSuggestion}{google:originalQueryForSuggestion}sourceid=chrome&ie={inputEncoding}&q={searchTerms}100UTF-81{google:baseSuggestURL}search?client=chrome&hl={language}&q={searchTerms}1162620{google:baseURL}webhp?{google:RLZ}sourceid=chrome-instant&ie={inputEncoding}&ion=1{searchTerms}&nord=10{1234-5678-90AB-CDEF}');
INSERT INTO "meta" VALUES('Builtin Keyword Version','33');
CREATE TABLE keywords (id INTEGER PRIMARY KEY,short_name VARCHAR NOT NULL,keyword VARCHAR NOT NULL,favicon_url VARCHAR NOT NULL,url VARCHAR NOT NULL,show_in_default_list INTEGER,safe_for_autoreplace INTEGER,originating_url VARCHAR,date_created INTEGER DEFAULT 0,usage_count INTEGER DEFAULT 0,input_encodings VARCHAR,suggest_url VARCHAR,prepopulate_id INTEGER DEFAULT 0,autogenerate_keyword INTEGER DEFAULT 0,logo_id INTEGER DEFAULT 0,created_by_policy INTEGER DEFAULT 0,instant_url VARCHAR,last_modified INTEGER DEFAULT 0, sync_guid VARCHAR);
diff --git a/chrome/test/data/web_database/version_43.sql b/chrome/test/data/web_database/version_43.sql
index 68facbe..e0bcd54 100644
--- a/chrome/test/data/web_database/version_43.sql
+++ b/chrome/test/data/web_database/version_43.sql
@@ -5,7 +5,7 @@ INSERT INTO "meta" VALUES('version','43');
INSERT INTO "meta" VALUES('last_compatible_version','43');
INSERT INTO "meta" VALUES('Default Search Provider ID','2');
INSERT INTO "meta" VALUES('Default Search Provider ID Backup','3');
-INSERT INTO "meta" VALUES('Default Search Provider ID Backup Signature','Invalid signature');
+INSERT INTO "meta" VALUES('Default Search Provider ID Backup Signature','');
INSERT INTO "meta" VALUES('Builtin Keyword Version','37');
CREATE TABLE keywords (id INTEGER PRIMARY KEY,short_name VARCHAR NOT NULL,keyword VARCHAR NOT NULL,favicon_url VARCHAR NOT NULL,url VARCHAR NOT NULL,show_in_default_list INTEGER,safe_for_autoreplace INTEGER,originating_url VARCHAR,date_created INTEGER DEFAULT 0,usage_count INTEGER DEFAULT 0,input_encodings VARCHAR,suggest_url VARCHAR,prepopulate_id INTEGER DEFAULT 0,autogenerate_keyword INTEGER DEFAULT 0,logo_id INTEGER DEFAULT 0,created_by_policy INTEGER DEFAULT 0,instant_url VARCHAR,last_modified INTEGER DEFAULT 0, sync_guid VARCHAR);
INSERT INTO "keywords" VALUES(2,'Google','google.com','http://www.google.com/favicon.ico','{google:baseURL}search?{google:RLZ}{google:acceptedSuggestion}{google:originalQueryForSuggestion}sourceid=chrome&ie={inputEncoding}&q={searchTerms}',1,1,'',0,0,'UTF-8','{google:baseSuggestURL}search?client=chrome&hl={language}&q={searchTerms}',1,1,1234,0,'{google:baseURL}webhp?{google:RLZ}sourceid=chrome-instant&ie={inputEncoding}&ion=1{searchTerms}&nord=1',0,'{1234-5678-90AB-CDEF}');
diff --git a/chrome/test/data/web_database/version_44_backup_corrupt.sql b/chrome/test/data/web_database/version_44_backup_corrupt.sql
deleted file mode 100644
index 46eda48..0000000
--- a/chrome/test/data/web_database/version_44_backup_corrupt.sql
+++ /dev/null
@@ -1,53 +0,0 @@
-PRAGMA foreign_keys=OFF;
-BEGIN TRANSACTION;
-CREATE TABLE meta(key LONGVARCHAR NOT NULL UNIQUE PRIMARY KEY,value LONGVARCHAR);
-INSERT INTO "meta" VALUES('version','44');
-INSERT INTO "meta" VALUES('last_compatible_version','44');
-INSERT INTO "meta" VALUES('Default Search Provider ID Backup','0');
-INSERT INTO "meta" VALUES('Default Search Provider ID Backup Signature','0');
-CREATE TABLE keywords (id INTEGER PRIMARY KEY,short_name VARCHAR NOT NULL,keyword VARCHAR NOT NULL,favicon_url VARCHAR NOT NULL,url VARCHAR NOT NULL,show_in_default_list INTEGER,safe_for_autoreplace INTEGER,originating_url VARCHAR,date_created INTEGER DEFAULT 0,usage_count INTEGER DEFAULT 0,input_encodings VARCHAR,suggest_url VARCHAR,prepopulate_id INTEGER DEFAULT 0,autogenerate_keyword INTEGER DEFAULT 0,logo_id INTEGER DEFAULT 0,created_by_policy INTEGER DEFAULT 0,instant_url VARCHAR,last_modified INTEGER DEFAULT 0,sync_guid VARCHAR);
-CREATE TABLE keywords_backup(
- id INT,
- short_name TEXT,
- keyword TEXT,
- favicon_url TEXT,
- url TEXT,
- safe_for_autoreplace INT,
- originating_url TEXT,
- date_created INT,
- usage_count INT,
- input_encodings TEXT,
- show_in_default_list INT,
- suggest_url TEXT,
- prepopulate_id INT,
- autogenerate_keyword INT,
- logo_id INT,
- created_by_policy INT,
- instant_url TEXT,
- last_modified INT,
- sync_guid TEXT
-);
-CREATE TABLE autofill (name VARCHAR, value VARCHAR, value_lower VARCHAR, pair_id INTEGER PRIMARY KEY, count INTEGER DEFAULT 1);
-CREATE TABLE credit_cards ( guid VARCHAR PRIMARY KEY, name_on_card VARCHAR, expiration_month INTEGER, expiration_year INTEGER, card_number_encrypted BLOB, date_modified INTEGER NOT NULL DEFAULT 0);
-CREATE TABLE autofill_dates ( pair_id INTEGER DEFAULT 0, date_created INTEGER DEFAULT 0);
-CREATE TABLE autofill_profiles ( guid VARCHAR PRIMARY KEY, company_name VARCHAR, address_line_1 VARCHAR, address_line_2 VARCHAR, city VARCHAR, state VARCHAR, zipcode VARCHAR, country VARCHAR, country_code VARCHAR, date_modified INTEGER NOT NULL DEFAULT 0);
-CREATE TABLE autofill_profile_names ( guid VARCHAR, first_name VARCHAR, middle_name VARCHAR, last_name VARCHAR);
-CREATE TABLE autofill_profile_emails ( guid VARCHAR, email VARCHAR);
-CREATE TABLE autofill_profile_phones ( guid VARCHAR, type INTEGER DEFAULT 0, number VARCHAR);
-CREATE TABLE autofill_profiles_trash ( guid VARCHAR);
-CREATE TABLE logins (origin_url VARCHAR NOT NULL, action_url VARCHAR, username_element VARCHAR, username_value VARCHAR, password_element VARCHAR, password_value BLOB, submit_element VARCHAR, signon_realm VARCHAR NOT NULL,ssl_valid INTEGER NOT NULL,preferred INTEGER NOT NULL,date_created INTEGER NOT NULL,blacklisted_by_user INTEGER NOT NULL,scheme INTEGER NOT NULL,UNIQUE (origin_url, username_element, username_value, password_element, submit_element, signon_realm));
-CREATE TABLE ie7_logins (url_hash VARCHAR NOT NULL, password_value BLOB, date_created INTEGER NOT NULL,UNIQUE (url_hash));
-CREATE TABLE web_app_icons (url LONGVARCHAR,width int,height int,image BLOB, UNIQUE (url, width, height));
-CREATE TABLE web_apps (url LONGVARCHAR UNIQUE,has_all_images INTEGER NOT NULL);
-CREATE TABLE token_service (service VARCHAR PRIMARY KEY NOT NULL,encrypted_token BLOB);
-CREATE TABLE web_intents (service_url LONGVARCHAR,action VARCHAR,type VARCHAR,title LONGVARCHAR,disposition VARCHAR,UNIQUE (service_url, action, type));
-CREATE TABLE web_intents_defaults (action VARCHAR,type VARCHAR,url_pattern LONGVARCHAR,user_date INTEGER,suppression INTEGER,service_url LONGVARCHAR,UNIQUE (action, type, url_pattern));
-CREATE INDEX autofill_name ON autofill (name);
-CREATE INDEX autofill_name_value_lower ON autofill (name, value_lower);
-CREATE INDEX autofill_dates_pair_id ON autofill_dates (pair_id);
-CREATE INDEX logins_signon ON logins (signon_realm);
-CREATE INDEX ie7_logins_hash ON ie7_logins (url_hash);
-CREATE INDEX web_apps_url_index ON web_apps (url);
-CREATE INDEX web_intents_index ON web_intents (action);
-CREATE INDEX web_intents_default_index ON web_intents_defaults (action);
-COMMIT;
diff --git a/chrome/test/data/web_database/version_46_backup_corrupt.sql b/chrome/test/data/web_database/version_47.sql
index 8dcf7cb..aae06e8 100644
--- a/chrome/test/data/web_database/version_46_backup_corrupt.sql
+++ b/chrome/test/data/web_database/version_47.sql
@@ -1,12 +1,33 @@
PRAGMA foreign_keys=OFF;
BEGIN TRANSACTION;
CREATE TABLE meta(key LONGVARCHAR NOT NULL UNIQUE PRIMARY KEY, value LONGVARCHAR);
-INSERT INTO "meta" VALUES('Default Search Provider ID','0');
-INSERT INTO "meta" VALUES('version','46');
-INSERT INTO "meta" VALUES('last_compatible_version','46');
-INSERT INTO "meta" VALUES('Default Search Provider ID Backup','0');
+INSERT INTO "meta" VALUES('version','47');
+INSERT INTO "meta" VALUES('last_compatible_version','47');
+INSERT INTO "meta" VALUES('Builtin Keyword Version','46');
+INSERT INTO "meta" VALUES('Default Search Provider ID','2');
+INSERT INTO "meta" VALUES('Default Search Provider ID Backup','2');
INSERT INTO "meta" VALUES('Default Search Provider ID Backup Signature','');
-INSERT INTO "meta" VALUES('Builtin Keyword Version','39');
+CREATE TABLE keywords (id INTEGER PRIMARY KEY,short_name VARCHAR NOT NULL,keyword VARCHAR NOT NULL,favicon_url VARCHAR NOT NULL,url VARCHAR NOT NULL,safe_for_autoreplace INTEGER,originating_url VARCHAR,date_created INTEGER DEFAULT 0,usage_count INTEGER DEFAULT 0,input_encodings VARCHAR,show_in_default_list INTEGER,suggest_url VARCHAR,prepopulate_id INTEGER DEFAULT 0,created_by_policy INTEGER DEFAULT 0,instant_url VARCHAR,last_modified INTEGER DEFAULT 0,sync_guid VARCHAR,alternate_urls VARCHAR);
+CREATE TABLE keywords_backup(
+ id INT,
+ short_name TEXT,
+ keyword TEXT,
+ favicon_url TEXT,
+ url TEXT,
+ safe_for_autoreplace INT,
+ originating_url TEXT,
+ date_created INT,
+ usage_count INT,
+ input_encodings TEXT,
+ show_in_default_list INT,
+ suggest_url TEXT,
+ prepopulate_id INT,
+ created_by_policy INT,
+ instant_url TEXT,
+ last_modified INT,
+ sync_guid TEXT,
+ alternate_urls TEXT
+);
CREATE TABLE autofill (name VARCHAR, value VARCHAR, value_lower VARCHAR, pair_id INTEGER PRIMARY KEY, count INTEGER DEFAULT 1);
CREATE TABLE credit_cards ( guid VARCHAR PRIMARY KEY, name_on_card VARCHAR, expiration_month INTEGER, expiration_year INTEGER, card_number_encrypted BLOB, date_modified INTEGER NOT NULL DEFAULT 0);
CREATE TABLE autofill_dates ( pair_id INTEGER DEFAULT 0, date_created INTEGER DEFAULT 0);
@@ -18,10 +39,8 @@ CREATE TABLE autofill_profiles_trash ( guid VARCHAR);
CREATE TABLE web_app_icons (url LONGVARCHAR,width int,height int,image BLOB, UNIQUE (url, width, height));
CREATE TABLE web_apps (url LONGVARCHAR UNIQUE,has_all_images INTEGER NOT NULL);
CREATE TABLE token_service (service VARCHAR PRIMARY KEY NOT NULL,encrypted_token BLOB);
-CREATE TABLE web_intents (service_url LONGVARCHAR,action VARCHAR,type VARCHAR,title LONGVARCHAR,disposition VARCHAR,scheme VARCHAR,UNIQUE (service_url, action, type));
-CREATE TABLE web_intents_defaults (action VARCHAR,type VARCHAR,url_pattern LONGVARCHAR,user_date INTEGER,suppression INTEGER,service_url LONGVARCHAR,scheme VARCHAR,UNIQUE (action, type, url_pattern));
-CREATE TABLE keywords (id INTEGER PRIMARY KEY,short_name VARCHAR NOT NULL,keyword VARCHAR NOT NULL,favicon_url VARCHAR NOT NULL,url VARCHAR NOT NULL,safe_for_autoreplace INTEGER,originating_url VARCHAR,date_created INTEGER DEFAULT 0,usage_count INTEGER DEFAULT 0,input_encodings VARCHAR,show_in_default_list INTEGER,suggest_url VARCHAR,prepopulate_id INTEGER DEFAULT 0,created_by_policy INTEGER DEFAULT 0,instant_url VARCHAR,last_modified INTEGER DEFAULT 0,sync_guid VARCHAR);
-CREATE TABLE keywords_backup(id INT,short_name TEXT,keyword TEXT,favicon_url TEXT,url TEXT,safe_for_autoreplace INT,originating_url TEXT,date_created INT,usage_count INT,input_encodings TEXT,show_in_default_list INT,suggest_url TEXT,prepopulate_id INT,created_by_policy INT,instant_url TEXT,last_modified INT,sync_guid TEXT);
+CREATE TABLE web_intents ( service_url LONGVARCHAR, action VARCHAR, type VARCHAR, title LONGVARCHAR, disposition VARCHAR, scheme VARCHAR, UNIQUE (service_url, action, scheme, type));
+CREATE TABLE web_intents_defaults ( action VARCHAR, type VARCHAR, url_pattern LONGVARCHAR, user_date INTEGER, suppression INTEGER, service_url LONGVARCHAR, scheme VARCHAR, UNIQUE (action, scheme, type, url_pattern));
CREATE INDEX autofill_name ON autofill (name);
CREATE INDEX autofill_name_value_lower ON autofill (name, value_lower);
CREATE INDEX autofill_dates_pair_id ON autofill_dates (pair_id);
diff --git a/chrome/test/functional/protector.py b/chrome/test/functional/protector.py
deleted file mode 100755
index 65cc394..0000000
--- a/chrome/test/functional/protector.py
+++ /dev/null
@@ -1,750 +0,0 @@
-#!/usr/bin/env python
-# Copyright (c) 2012 The Chromium Authors. All rights reserved.
-# Use of this source code is governed by a BSD-style license that can be
-# found in the LICENSE file.
-
-import pyauto_functional # Must be imported first
-import pyauto
-import test_utils
-
-import json
-import logging
-import os
-
-
-class BaseProtectorTest(pyauto.PyUITest):
- """Base class for Protector test cases."""
-
- _DEFAULT_SEARCH_ID_KEY = 'Default Search Provider ID'
-
- # Possible values for session.restore_on_startup pref:
- _SESSION_STARTUP_HOMEPAGE = 0 # For migration testing only.
- _SESSION_STARTUP_LAST = 1
- _SESSION_STARTUP_URLS = 4
- _SESSION_STARTUP_NTP = 5
-
- def setUp(self):
- pyauto.PyUITest.setUp(self)
- # Get the profile path of the first profile.
- profiles = self.GetMultiProfileInfo()
- self.assertTrue(profiles['profiles'])
- self._profile_path = profiles['profiles'][0]['path']
- self.assertTrue(self._profile_path)
- # Set to the keyword of the new default search engine after a successful
- # _GetDefaultSearchEngine call.
- self._new_default_search_keyword = None
-
- def _IsEnabled(self):
- """Whether protector should be enabled for the test suite."""
- return True
-
- def ExtraChromeFlags(self):
- """Adds required Protector-related flags.
-
- Returns:
- A list of extra flags to pass to Chrome when it is launched.
- """
- return super(BaseProtectorTest, self).ExtraChromeFlags() + [
- '--protector' if self._IsEnabled() else '--no-protector'
- ]
-
- def _GetDefaultSearchEngine(self):
- """Returns the default search engine, if any; None otherwise.
-
- Returns:
- Dictionary describing the default search engine. See GetSearchEngineInfo
- for an example.
- """
- for search_engine in self.GetSearchEngineInfo():
- if search_engine['is_default']:
- return search_engine
- return None
-
- def _OpenDatabase(self, db_name):
- """Opens a given SQLite database in the default profile.
-
- Args:
- db_name: name of database file (relative to the profile directory).
-
- Returns:
- An sqlite3.Connection instance.
-
- Raises:
- ImportError if sqlite3 module is not found.
- """
- db_path = os.path.join(self._profile_path, db_name)
- logging.info('Opening DB: %s' % db_path)
- import sqlite3
- db_conn = sqlite3.connect(db_path)
- db_conn.isolation_level = None
- self.assertTrue(db_conn)
- return db_conn
-
- def _FetchSingleValue(self, conn, query, parameters=None):
- """Executes an SQL query that should select a single row with a single
- column and returns its value.
-
- Args:
- conn: sqlite3.Connection instance.
- query: SQL query (may contain placeholders).
- parameters: parameters to substitute for query.
-
- Returns:
- Value of the column fetched.
- """
- cursor = conn.cursor()
- cursor.execute(query, parameters)
- row = cursor.fetchone()
- self.assertTrue(row)
- self.assertEqual(1, len(row))
- return row[0]
-
- def _UpdateSingleRow(self, conn, query, parameters=None):
- """Executes an SQL query that should update a single row.
-
- Args:
- conn: sqlite3.Connection instance.
- query: SQL query (may contain placeholders).
- parameters: parameters to substitute for query.
- """
- cursor = conn.cursor()
- cursor.execute(query, parameters)
- self.assertEqual(1, cursor.rowcount)
-
- def _ChangeDefaultSearchEngine(self):
- """Replaces the default search engine in Web Data database with another one.
-
- Keywords of the new default search engine is saved to
- self._new_default_search_keyword.
- """
- web_database = self._OpenDatabase('Web Data')
- default_id = int(self._FetchSingleValue(
- web_database,
- 'SELECT value FROM meta WHERE key = ?',
- (self._DEFAULT_SEARCH_ID_KEY,)))
- self.assertTrue(default_id)
- new_default_id = int(self._FetchSingleValue(
- web_database,
- 'SELECT id FROM keywords WHERE id != ? LIMIT 1',
- (default_id,)))
- self.assertTrue(new_default_id)
- self.assertNotEqual(default_id, new_default_id)
- self._UpdateSingleRow(web_database,
- 'UPDATE meta SET value = ? WHERE key = ?',
- (new_default_id, self._DEFAULT_SEARCH_ID_KEY))
- self._new_default_search_keyword = self._FetchSingleValue(
- web_database,
- 'SELECT keyword FROM keywords WHERE id = ?',
- (new_default_id,))
- logging.info('Update default search ID: %d -> %d (%s)' %
- (default_id, new_default_id, self._new_default_search_keyword))
- web_database.close()
-
- def _LoadPreferences(self):
- """Reads the contents of Preferences file.
-
- Returns: dict() with user preferences as returned by PrefsInfo.Prefs().
- """
- prefs_path = os.path.join(self._profile_path, 'Preferences')
- logging.info('Opening prefs: %s' % prefs_path)
- with open(prefs_path) as f:
- return json.load(f)
-
- def _WritePreferences(self, prefs):
- """Writes new contents to the Preferences file.
-
- Args:
- prefs: dict() with new user preferences as returned by PrefsInfo.Prefs().
- """
- with open(os.path.join(self._profile_path, 'Preferences'), 'w') as f:
- json.dump(prefs, f)
-
- def _InvalidatePreferencesBackup(self):
- """Makes the Preferences backup invalid by clearing the signature."""
- prefs = self._LoadPreferences()
- prefs['backup']['_signature'] = 'INVALID'
- self._WritePreferences(prefs)
-
- def _ChangeSessionStartupPrefs(self, startup_type=None, startup_urls=None,
- homepage=None, delete_migrated_pref=False):
- """Changes the session startup type and the list of URLs to load on startup.
-
- Args:
- startup_type: int with one of _SESSION_STARTUP_* values. If startup_type
- is None, then it deletes the preference.
- startup_urls: list(str) with a list of URLs; if None, is left unchanged.
- homepage: unless None, the new value for homepage.
- delete_migrated_pref: Whether we should delete the preference which says
- we've already migrated the startup_type preference.
- """
- prefs = self._LoadPreferences()
- if startup_type is None:
- del prefs['session']['restore_on_startup']
- else:
- prefs['session']['restore_on_startup'] = startup_type
-
- if startup_urls is not None:
- prefs['session']['urls_to_restore_on_startup'] = startup_urls
- if homepage is not None:
- prefs['homepage'] = homepage
- prefs['homepage_is_newtabpage'] = False
- if delete_migrated_pref:
- del prefs['session']['restore_on_startup_migrated']
- self._WritePreferences(prefs)
-
- def _ChangePinnedTabsPrefs(self, pinned_tabs):
- """Changes the list of pinned tabs.
-
- Args:
- pinned_tabs: list(str) with a list of pinned tabs URLs.
- """
- prefs = self._LoadPreferences()
- prefs['pinned_tabs'] = []
- for tab in pinned_tabs:
- prefs['pinned_tabs'].append({'url': tab})
- self._WritePreferences(prefs)
-
- def _ChangeHomepage(self, homepage, homepage_is_ntp, show_homepage_button):
- """Changes homepage settings.
-
- Args:
- homepage: new homepage URL (str),
- homepage_is_ntp: whether homepage is NTP.
- show_homepage_button: whether homepage button is visible.
- """
- prefs = self._LoadPreferences()
- prefs['homepage'] = homepage
- prefs['homepage_is_newtabpage'] = homepage_is_ntp
- prefs['browser']['show_home_button'] = show_homepage_button
- self._WritePreferences(prefs)
-
- def _AssertTabsOpen(self, urls, pinned=None):
- """Asserts that exactly one window with the specified URLs is open.
-
- Args:
- urls: list of URLs of expected open tabs.
- pinned: if given, list of boolean values whether the corresponding tab is
- expected to be pinned or not.
- """
- info = self.GetBrowserInfo()
- self.assertEqual(1, len(info['windows'])) # one window
- self.assertEqual(urls, [tab['url'] for tab in info['windows'][0]['tabs']])
- if pinned:
- self.assertEqual(pinned,
- [tab['pinned'] for tab in info['windows'][0]['tabs']])
-
- def testNoChangeOnCleanProfile(self):
- """Test that no change is reported on a clean profile."""
- self.assertFalse(self.GetProtectorState()['showing_change'])
-
-
-class ProtectorSearchEngineTest(BaseProtectorTest):
- """Test suite for search engine change detection with Protector enabled."""
-
- def testDetectSearchEngineChangeAndApply(self):
- """Test for detecting and applying a default search engine change."""
- # Get current search engine.
- old_default_search = self._GetDefaultSearchEngine()
- self.assertTrue(old_default_search)
- # Close browser, change the search engine and start it again.
- self.RestartBrowser(clear_profile=False,
- pre_launch_hook=self._ChangeDefaultSearchEngine)
- # The change must be detected by Protector.
- self.assertTrue(self.GetProtectorState()['showing_change'])
- default_search = self._GetDefaultSearchEngine()
- # Protector must restore the old search engine.
- self.assertEqual(old_default_search, default_search)
- self.ApplyProtectorChange()
- # Now the search engine must have changed to the new one.
- default_search = self._GetDefaultSearchEngine()
- self.assertNotEqual(old_default_search, default_search)
- self.assertEqual(self._new_default_search_keyword,
- default_search['keyword'])
- # No longer showing the change.
- self.assertFalse(self.GetProtectorState()['showing_change'])
-
- def testDetectSearchEngineChangeAndDiscard(self):
- """Test for detecting and discarding a default search engine change."""
- # Get current search engine.
- old_default_search = self._GetDefaultSearchEngine()
- self.assertTrue(old_default_search)
- # Close browser, change the search engine and start it again.
- self.RestartBrowser(clear_profile=False,
- pre_launch_hook=self._ChangeDefaultSearchEngine)
- # The change must be detected by Protector.
- self.assertTrue(self.GetProtectorState()['showing_change'])
- default_search = self._GetDefaultSearchEngine()
- # Protector must restore the old search engine.
- self.assertEqual(old_default_search, default_search)
- self.DiscardProtectorChange()
- # Old search engine remains active.
- default_search = self._GetDefaultSearchEngine()
- self.assertEqual(old_default_search, default_search)
- # No longer showing the change.
- self.assertFalse(self.GetProtectorState()['showing_change'])
-
- def testSearchEngineChangeDismissedOnEdit(self):
- """Test that default search engine change is dismissed when default search
- engine is changed by user.
- """
- # Get current search engine.
- old_default_search = self._GetDefaultSearchEngine()
- self.assertTrue(old_default_search)
- # Close browser, change the search engine and start it again.
- self.RestartBrowser(clear_profile=False,
- pre_launch_hook=self._ChangeDefaultSearchEngine)
- # The change must be detected by Protector.
- self.assertTrue(self.GetProtectorState()['showing_change'])
- # Change default search engine.
- self.MakeSearchEngineDefault(self._new_default_search_keyword)
- # Change is successful.
- default_search = self._GetDefaultSearchEngine()
- self.assertEqual(self._new_default_search_keyword,
- default_search['keyword'])
- # No longer showing the change.
- self.assertFalse(self.GetProtectorState()['showing_change'])
- search_urls = [engine['url'] for engine in self.GetSearchEngineInfo()]
- # Verify there are no duplicate search engines:
- self.assertEqual(len(search_urls), len(set(search_urls)))
-
- def testSearchEngineChangeWithMultipleWindows(self):
- """Test that default search engine change is detected in multiple
- browser windows.
- """
- # Get current search engine.
- old_default_search = self._GetDefaultSearchEngine()
- self.assertTrue(old_default_search)
- # Close browser, change the search engine and start it again.
- self.RestartBrowser(clear_profile=False,
- pre_launch_hook=self._ChangeDefaultSearchEngine)
- # The change must be detected by Protector in first window
- self.OpenNewBrowserWindow(True)
- self.assertTrue(self.GetProtectorState(window_index=0)['showing_change'])
- # Open another Browser Window
- self.OpenNewBrowserWindow(True)
- # The change must be detected by Protector in second window
- self.assertTrue(self.GetProtectorState(window_index=1)['showing_change'])
-
- def testSearchEngineChangeDiscardedOnRelaunchingBrowser(self):
- """Verify that relaunching the browser while Protector is showing a change
- discards it.
- """
- # Get current search engine.
- old_default_search = self._GetDefaultSearchEngine()
- self.assertTrue(old_default_search)
- # Close browser, change the search engine and start it again.
- self.RestartBrowser(clear_profile=False,
- pre_launch_hook=self._ChangeDefaultSearchEngine)
- # The change must be detected by Protector.
- self.assertTrue(self.GetProtectorState()['showing_change'])
- default_search = self._GetDefaultSearchEngine()
- self.assertEqual(old_default_search, default_search)
- # After relaunching the browser, old search engine still must be active.
- self.RestartBrowser(clear_profile=False)
- default_search = self._GetDefaultSearchEngine()
- self.assertEqual(old_default_search, default_search)
- # No longer showing the change.
- self.assertFalse(self.GetProtectorState()['showing_change'])
-
-# TODO(ivankr): more hijacking cases (remove the current default search engine,
-# add new search engines to the list, invalidate backup, etc).
-
-
-class ProtectorPreferencesTest(BaseProtectorTest):
- """Generic test suite for Preferences protection."""
-
- def testPreferencesBackupInvalid(self):
- """Test for detecting invalid Preferences backup."""
- # Set startup prefs to open specific URLs.
- self.SetPrefs(pyauto.kRestoreOnStartup, self._SESSION_STARTUP_URLS)
- self.SetPrefs(pyauto.kURLsToRestoreOnStartup, ['http://www.google.com/'])
- self.RestartBrowser(
- clear_profile=False,
- pre_launch_hook=self._InvalidatePreferencesBackup)
- # The change must be detected by Protector.
- self.assertTrue(self.GetProtectorState()['showing_change'])
- # Startup settings are reset to default (NTP).
- self.assertEqual(self._SESSION_STARTUP_NTP,
- self.GetPrefsInfo().Prefs(pyauto.kRestoreOnStartup))
- # Verify that previous startup URL has not been opened.
- self._AssertTabsOpen(['chrome://newtab/'])
- # Click "Edit Settings...".
- self.DiscardProtectorChange()
- # Verify that a new tab with settings is opened.
- info = self.GetBrowserInfo()
- self._AssertTabsOpen(['chrome://newtab/', 'chrome://chrome/settings/'])
- # No longer showing the change.
- self.assertFalse(self.GetProtectorState()['showing_change'])
- self.RestartBrowser(clear_profile=False)
- # Not showing the change after a restart
- self.assertFalse(self.GetProtectorState()['showing_change'])
-
- def testPreferencesBackupInvalidRestoreLastSession(self):
- """Test that session restore setting is not reset if backup is invalid."""
- # Set startup prefs to restore the last session.
- self.SetPrefs(pyauto.kRestoreOnStartup, self._SESSION_STARTUP_LAST)
- previous_urls = ['chrome://version/', 'http://news.google.com/']
- self.NavigateToURL(previous_urls[0])
- for url in previous_urls[1:]:
- self.AppendTab(pyauto.GURL(url))
- self.RestartBrowser(
- clear_profile=False,
- pre_launch_hook=self._InvalidatePreferencesBackup)
- # The change must be detected by Protector.
- self.assertTrue(self.GetProtectorState()['showing_change'])
- # Startup settings are left unchanged.
- self.assertEqual(self._SESSION_STARTUP_LAST,
- self.GetPrefsInfo().Prefs(pyauto.kRestoreOnStartup))
- # Session has been restored.
- self._AssertTabsOpen(previous_urls)
-
- def testPreferencesBackupInvalidChangeDismissedOnEdit(self):
- """Test that editing protected prefs dismisses the invalid backup bubble."""
- self.RestartBrowser(
- clear_profile=False,
- pre_launch_hook=self._InvalidatePreferencesBackup)
- # The change must be detected by Protector.
- self.assertTrue(self.GetProtectorState()['showing_change'])
- # Change some protected setting manually.
- self.SetPrefs(pyauto.kHomePage, 'http://example.com/')
- # No longer showing the change.
- self.assertFalse(self.GetProtectorState()['showing_change'])
-
-
-class ProtectorSessionStartupTest(BaseProtectorTest):
- """Test suite for session startup changes detection with Protector enabled.
- """
- def testDetectSessionStartupChangeAndApply(self):
- """Test for detecting and applying a session startup pref change."""
- # Set startup prefs to restoring last open tabs.
- self.SetPrefs(pyauto.kRestoreOnStartup, self._SESSION_STARTUP_LAST)
- previous_urls = ['chrome://version/', 'http://news.google.com/']
- self.NavigateToURL(previous_urls[0])
- for url in previous_urls[1:]:
- self.AppendTab(pyauto.GURL(url))
- # Restart browser with startup prefs set to open google.com.
- self.RestartBrowser(
- clear_profile=False,
- pre_launch_hook=lambda: self._ChangeSessionStartupPrefs(
- self._SESSION_STARTUP_URLS,
- startup_urls=['http://www.google.com']))
- # The change must be detected by Protector.
- self.assertTrue(self.GetProtectorState()['showing_change'])
- # Protector must restore old preference values.
- self.assertEqual(self._SESSION_STARTUP_LAST,
- self.GetPrefsInfo().Prefs(pyauto.kRestoreOnStartup))
- # Verify that open tabs are consistent with restored prefs.
- self._AssertTabsOpen(previous_urls)
- self.ApplyProtectorChange()
- # Now the new preference values are active.
- self.assertEqual(self._SESSION_STARTUP_URLS,
- self.GetPrefsInfo().Prefs(pyauto.kRestoreOnStartup))
- # No longer showing the change.
- self.assertFalse(self.GetProtectorState()['showing_change'])
-
- def testDetectSessionStartupChangeAndDiscard(self):
- """Test for detecting and discarding a session startup pref change."""
- # Set startup prefs to restoring last open tabs.
- self.SetPrefs(pyauto.kRestoreOnStartup, self._SESSION_STARTUP_LAST)
- # Restart browser with startup prefs set to open google.com.
- self.RestartBrowser(
- clear_profile=False,
- pre_launch_hook=lambda: self._ChangeSessionStartupPrefs(
- self._SESSION_STARTUP_URLS,
- startup_urls=['http://www.google.com']))
- # The change must be detected by Protector.
- self.assertTrue(self.GetProtectorState()['showing_change'])
- # Old preference values restored.
- self.assertEqual(self._SESSION_STARTUP_LAST,
- self.GetPrefsInfo().Prefs(pyauto.kRestoreOnStartup))
- self.DiscardProtectorChange()
- # Old preference values are still active.
- self.assertEqual(self._SESSION_STARTUP_LAST,
- self.GetPrefsInfo().Prefs(pyauto.kRestoreOnStartup))
- # No longer showing the change.
- self.assertFalse(self.GetProtectorState()['showing_change'])
-
- def testSessionStartupChangeDismissedOnEdit(self):
- """Test for that editing startup prefs manually dismissed the change."""
- # Set startup prefs to restoring last open tabs.
- self.SetPrefs(pyauto.kRestoreOnStartup, self._SESSION_STARTUP_LAST)
- # Restart browser with startup prefs set to open google.com.
- self.RestartBrowser(
- clear_profile=False,
- pre_launch_hook=lambda: self._ChangeSessionStartupPrefs(
- self._SESSION_STARTUP_URLS,
- startup_urls=['http://www.google.com']))
- # The change must be detected by Protector.
- self.assertTrue(self.GetProtectorState()['showing_change'])
- # Change the setting manually.
- self.SetPrefs(pyauto.kRestoreOnStartup, self._SESSION_STARTUP_NTP)
- # No longer showing the change.
- self.assertFalse(self.GetProtectorState()['showing_change'])
-
- def testSessionStartupPrefMigrationFromHomepage(self):
- """Test migration from old session.restore_on_startup values (homepage)."""
- # Set startup prefs to restoring last open tabs.
- self.SetPrefs(pyauto.kRestoreOnStartup, self._SESSION_STARTUP_LAST)
- self.SetPrefs(pyauto.kURLsToRestoreOnStartup, [])
- new_homepage = 'http://www.google.com/'
- # Restart browser with startup prefs set to open homepage (google.com).
- self.RestartBrowser(
- clear_profile=False,
- pre_launch_hook=lambda: self._ChangeSessionStartupPrefs(
- self._SESSION_STARTUP_HOMEPAGE,
- homepage=new_homepage,
- delete_migrated_pref=True))
- # The change must be detected by Protector.
- self.assertTrue(self.GetProtectorState()['showing_change'])
- # Protector must restore old preference values.
- self.assertEqual(self._SESSION_STARTUP_LAST,
- self.GetPrefsInfo().Prefs(pyauto.kRestoreOnStartup))
- self.assertEqual([],
- self.GetPrefsInfo().Prefs(pyauto.kURLsToRestoreOnStartup))
- self.ApplyProtectorChange()
- # Now the new preference values are active.
- self.assertEqual(self._SESSION_STARTUP_URLS,
- self.GetPrefsInfo().Prefs(pyauto.kRestoreOnStartup))
- # Homepage migrated to the list of startup URLs.
- self.assertEqual([new_homepage],
- self.GetPrefsInfo().Prefs(pyauto.kURLsToRestoreOnStartup))
- # No longer showing the change.
- self.assertFalse(self.GetProtectorState()['showing_change'])
-
- def testSessionStartupPrefMigrationFromBlank(self):
- """Test migration from session.restore_on_startup being blank, as it would
- be for a user who had m18 or lower, and never changed that preference.
- """
- # Set startup prefs to restoring last open tabs.
- self.SetPrefs(pyauto.kRestoreOnStartup, self._SESSION_STARTUP_LAST)
- self.SetPrefs(pyauto.kURLsToRestoreOnStartup, [])
- # Set the homepage.
- new_homepage = 'http://www.google.com/'
- self.SetPrefs(pyauto.kHomePageIsNewTabPage, False)
- self.SetPrefs(pyauto.kHomePage, new_homepage)
- # Restart browser, clearing the 'restore on startup' pref, to simulate a
- # user coming from m18 and having left it on the default value.
- self.RestartBrowser(
- clear_profile=False,
- pre_launch_hook=lambda: self._ChangeSessionStartupPrefs(
- startup_type=None,
- delete_migrated_pref=True))
- # The change must be detected by Protector.
- self.assertTrue(self.GetProtectorState()['showing_change'])
- # Protector must restore old preference values.
- self.assertEqual(self._SESSION_STARTUP_LAST,
- self.GetPrefsInfo().Prefs(pyauto.kRestoreOnStartup))
- self.assertEqual([],
- self.GetPrefsInfo().Prefs(pyauto.kURLsToRestoreOnStartup))
- self.ApplyProtectorChange()
- # Now the new preference values are active.
- self.assertEqual(self._SESSION_STARTUP_URLS,
- self.GetPrefsInfo().Prefs(pyauto.kRestoreOnStartup))
- # Homepage migrated to the list of startup URLs.
- self.assertEqual([new_homepage],
- self.GetPrefsInfo().Prefs(pyauto.kURLsToRestoreOnStartup))
- # No longer showing the change.
- self.assertFalse(self.GetProtectorState()['showing_change'])
-
- def testSessionStartupPrefNoMigrationOnHomepageChange(self):
- """Test that when the user modifies their homepage in m19+, we don't do the
- preference migration.
- """
- # Initially, the default value is selected for kRestoreOnStartup.
- self.assertEqual(self._SESSION_STARTUP_NTP,
- self.GetPrefsInfo().Prefs(pyauto.kRestoreOnStartup))
- # Set the homepage, but leave kRestoreOnStartup unchanged.
- new_homepage = 'http://www.google.com/'
- self.SetPrefs(pyauto.kHomePageIsNewTabPage, False)
- self.SetPrefs(pyauto.kHomePage, new_homepage)
- # Restart browser.
- self.RestartBrowser(clear_profile=False)
- # Now the new preference values are active.
- self.assertEqual(self._SESSION_STARTUP_NTP,
- self.GetPrefsInfo().Prefs(pyauto.kRestoreOnStartup))
- # kURLsToRestoreOnStartup pref is unchanged.
- self.assertEqual([],
- self.GetPrefsInfo().Prefs(pyauto.kURLsToRestoreOnStartup))
- # No longer showing the change.
- self.assertFalse(self.GetProtectorState()['showing_change'])
-
- def testDetectPinnedTabsChangeAndApply(self):
- """Test for detecting and applying a change to pinned tabs."""
- pinned_urls = ['chrome://version/', 'chrome://credits/']
- self.RestartBrowser(
- clear_profile=False,
- pre_launch_hook=lambda: self._ChangePinnedTabsPrefs(pinned_urls))
- # The change must be detected by Protector.
- self.assertTrue(self.GetProtectorState()['showing_change'])
- # Protector must restore old preference values.
- self.assertEqual([],
- self.GetPrefsInfo().Prefs(pyauto.kPinnedTabs))
- # No pinned tabs are open, only NTP.
- info = self.GetBrowserInfo()
- self._AssertTabsOpen(['chrome://newtab/'])
- self.ApplyProtectorChange()
- # No longer showing the change.
- self.assertFalse(self.GetProtectorState()['showing_change'])
- # Pinned tabs should have been opened now in the correct order.
- self._AssertTabsOpen(pinned_urls + ['chrome://newtab/'],
- pinned=[True, True, False])
- self.RestartBrowser(clear_profile=False)
- # Not showing the change after a restart
- self.assertFalse(self.GetProtectorState()['showing_change'])
- # Same pinned tabs are open.
- self._AssertTabsOpen(pinned_urls + ['chrome://newtab/'],
- pinned=[True, True, False])
-
- def testDetectPinnedTabsChangeAndDiscard(self):
- """Test for detecting and discarding a change to pinned tabs."""
- pinned_url = 'chrome://version/'
- self.RestartBrowser(
- clear_profile=False,
- pre_launch_hook=lambda: self._ChangePinnedTabsPrefs([pinned_url]))
- # The change must be detected by Protector.
- self.assertTrue(self.GetProtectorState()['showing_change'])
- # Protector must restore old preference values.
- self.assertEqual([],
- self.GetPrefsInfo().Prefs(pyauto.kPinnedTabs))
- # No pinned tabs are open, only NTP.
- info = self.GetBrowserInfo()
- self._AssertTabsOpen(['chrome://newtab/'])
- self.DiscardProtectorChange()
- # No longer showing the change.
- self.assertFalse(self.GetProtectorState()['showing_change'])
- # Pinned tabs are not opened after another restart.
- self.RestartBrowser(clear_profile=False)
- self._AssertTabsOpen(['chrome://newtab/'])
- # Not showing the change after a restart.
- self.assertFalse(self.GetProtectorState()['showing_change'])
-
-
-class ProtectorHomepageTest(BaseProtectorTest):
- """Test suite for homepage changes with Protector enabled."""
-
- def testDetectHomepageChangeAndApply(self):
- """Test that homepage change is detected and can be applied."""
- previous_homepage = 'http://example.com/'
- new_homepage = 'http://example.info/'
- self.SetPrefs(pyauto.kHomePage, previous_homepage)
- self.SetPrefs(pyauto.kHomePageIsNewTabPage, False)
- self.SetPrefs(pyauto.kShowHomeButton, False)
- self.RestartBrowser(
- clear_profile=False,
- pre_launch_hook=lambda: self._ChangeHomepage(new_homepage, False, True))
- # The change must be detected by Protector.
- self.assertTrue(self.GetProtectorState()['showing_change'])
- # Protector must restore old preference values.
- self.assertEquals(previous_homepage,
- self.GetPrefsInfo().Prefs(pyauto.kHomePage))
- self.assertEquals(False, self.GetPrefsInfo().Prefs(pyauto.kShowHomeButton))
- self.ApplyProtectorChange()
- # Now new values are active.
- self.assertEquals(new_homepage, self.GetPrefsInfo().Prefs(pyauto.kHomePage))
- self.assertEquals(True, self.GetPrefsInfo().Prefs(pyauto.kShowHomeButton))
- # No longer showing the change
- self.assertFalse(self.GetProtectorState()['showing_change'])
-
- def testDetectHomepageChangeAndDiscard(self):
- """Test that homepage change is detected and can be discarded."""
- previous_homepage = 'http://example.com/'
- new_homepage = 'http://example.info/'
- self.SetPrefs(pyauto.kHomePage, previous_homepage)
- self.SetPrefs(pyauto.kHomePageIsNewTabPage, False)
- self.SetPrefs(pyauto.kShowHomeButton, False)
- self.RestartBrowser(
- clear_profile=False,
- pre_launch_hook=lambda: self._ChangeHomepage(new_homepage, False, True))
- # The change must be detected by Protector.
- self.assertTrue(self.GetProtectorState()['showing_change'])
- # Protector must restore old preference values.
- self.assertEquals(previous_homepage,
- self.GetPrefsInfo().Prefs(pyauto.kHomePage))
- self.assertEquals(False, self.GetPrefsInfo().Prefs(pyauto.kShowHomeButton))
- self.DiscardProtectorChange()
- # Nothing changed
- self.assertEquals(previous_homepage,
- self.GetPrefsInfo().Prefs(pyauto.kHomePage))
- self.assertEquals(False, self.GetPrefsInfo().Prefs(pyauto.kShowHomeButton))
- # No longer showing the change
- self.assertFalse(self.GetProtectorState()['showing_change'])
-
-
-class ProtectorDisabledTest(BaseProtectorTest):
- """Test suite for Protector in disabled state."""
-
- def _IsEnabled(self):
- """Overriden from BaseProtectorTest to disable Protector."""
- return False
-
- def testNoSearchEngineChangeReported(self):
- """Test that the default search engine change is neither reported to user
- nor reverted.
- """
- # Get current search engine.
- old_default_search = self._GetDefaultSearchEngine()
- self.assertTrue(old_default_search)
- # Close browser, change the search engine and start it again.
- self.RestartBrowser(clear_profile=False,
- pre_launch_hook=self._ChangeDefaultSearchEngine)
- # The change must not be reported by Protector.
- self.assertFalse(self.GetProtectorState()['showing_change'])
- default_search = self._GetDefaultSearchEngine()
- # The new search engine must be active.
- self.assertEqual(self._new_default_search_keyword,
- default_search['keyword'])
-
- def testNoPreferencesBackupInvalidReported(self):
- """Test that invalid Preferences backup is not reported."""
- self.SetPrefs(pyauto.kRestoreOnStartup, self._SESSION_STARTUP_URLS)
- new_url = 'chrome://version/'
- self.SetPrefs(pyauto.kURLsToRestoreOnStartup, [new_url])
- self.RestartBrowser(
- clear_profile=False,
- pre_launch_hook=self._InvalidatePreferencesBackup)
- # The change must not be reported by Protector.
- self.assertFalse(self.GetProtectorState()['showing_change'])
- # New preference values must be active.
- self.assertEqual(self._SESSION_STARTUP_URLS,
- self.GetPrefsInfo().Prefs(pyauto.kRestoreOnStartup))
- # Verify that open tabs are consistent with new prefs.
- self._AssertTabsOpen([new_url])
-
- def testNoSessionStartupChangeReported(self):
- """Test that the session startup change is neither reported nor reverted."""
- # Set startup prefs to restoring last open tabs.
- self.SetPrefs(pyauto.kRestoreOnStartup, self._SESSION_STARTUP_LAST)
- new_url = 'chrome://version/'
- self.NavigateToURL('http://www.google.com/')
- # Restart browser with startup prefs set to open google.com.
- self.RestartBrowser(
- clear_profile=False,
- pre_launch_hook=lambda: self._ChangeSessionStartupPrefs(
- self._SESSION_STARTUP_URLS,
- startup_urls=[new_url]))
- # The change must not be reported by Protector.
- self.assertFalse(self.GetProtectorState()['showing_change'])
- # New preference values must be active.
- self.assertEqual(self._SESSION_STARTUP_URLS,
- self.GetPrefsInfo().Prefs(pyauto.kRestoreOnStartup))
- # Verify that open tabs are consistent with new prefs.
- self._AssertTabsOpen([new_url])
-
- def testNoHomepageChangeReported(self):
- """Test that homepage change is neither reported nor reverted."""
- new_homepage = 'http://example.info/'
- self.SetPrefs(pyauto.kHomePage, 'http://example.com/')
- self.SetPrefs(pyauto.kHomePageIsNewTabPage, False)
- self.SetPrefs(pyauto.kShowHomeButton, False)
- self.RestartBrowser(
- clear_profile=False,
- pre_launch_hook=lambda: self._ChangeHomepage(new_homepage, False, True))
- # Not showing the change.
- self.assertFalse(self.GetProtectorState()['showing_change'])
- # New values must be active.
- self.assertEquals(new_homepage, self.GetPrefsInfo().Prefs(pyauto.kHomePage))
- self.assertEquals(True, self.GetPrefsInfo().Prefs(pyauto.kShowHomeButton))
-
-
-if __name__ == '__main__':
- pyauto_functional.Main()
diff --git a/chrome/test/pyautolib/pyauto.py b/chrome/test/pyautolib/pyauto.py
index c729533..31a6e52 100755
--- a/chrome/test/pyautolib/pyauto.py
+++ b/chrome/test/pyautolib/pyauto.py
@@ -2130,52 +2130,6 @@ class PyUITest(pyautolib.PyUITestBase, unittest.TestCase):
'action': 'default'}
self._GetResultFromJSONRequest(cmd_dict, windex=windex)
- def _EnsureProtectorCheck(self):
- """Ensure that Protector check for changed settings has been performed in
- the current browser session.
-
- No-op if Protector is disabled.
- """
- # Ensure that check for default search engine change has been performed.
- self._GetResultFromJSONRequest({'command': 'LoadSearchEngineInfo'})
-
- def GetProtectorState(self, window_index=0):
- """Returns current Protector state.
-
- This will trigger Protector's check for changed settings if it hasn't been
- performed yet.
-
- Args:
- window_index: The window index, default is 0.
-
- Returns:
- A dictionary.
- Example:
- { u'enabled': True,
- u'showing_change': False }
- """
- self._EnsureProtectorCheck()
- cmd_dict = {'command': 'GetProtectorState'}
- return self._GetResultFromJSONRequest(cmd_dict, windex=window_index)
-
- def ApplyProtectorChange(self):
- """Applies the change shown by Protector and closes the bubble.
-
- No-op if Protector is not showing any change.
- """
- cmd_dict = {'command': 'PerformProtectorAction',
- 'action': 'apply_change'}
- self._GetResultFromJSONRequest(cmd_dict)
-
- def DiscardProtectorChange(self):
- """Discards the change shown by Protector and closes the bubble.
-
- No-op if Protector is not showing any change.
- """
- cmd_dict = {'command': 'PerformProtectorAction',
- 'action': 'discard_change'}
- self._GetResultFromJSONRequest(cmd_dict)
-
def GetLocalStatePrefsInfo(self):
"""Return info about preferences.