diff --git a/DEPS b/DEPS index f31911a5..7c8e18d 100644 --- a/DEPS +++ b/DEPS
@@ -199,7 +199,7 @@ # Three lines of non-changing comments so that # the commit queue can handle CLs rolling Skia # and whatever else without interference from each other. - 'skia_revision': '0de76f72cd5ee7cfe33be3945e4a5651fee1331d', + 'skia_revision': '8716cfdc6abd9b935dc70553b9fbaecc351159ab', # Three lines of non-changing comments so that # the commit queue can handle CLs rolling V8 # and whatever else without interference from each other. @@ -211,7 +211,7 @@ # Three lines of non-changing comments so that # the commit queue can handle CLs rolling ANGLE # and whatever else without interference from each other. - 'angle_revision': 'a29ef6129501a14774387f23574d30459b70f9e6', + 'angle_revision': '74f7be6d1fd020a432dee63222fa090e4d8df651', # Three lines of non-changing comments so that # the commit queue can handle CLs rolling SwiftShader # and whatever else without interference from each other. @@ -278,7 +278,7 @@ # Three lines of non-changing comments so that # the commit queue can handle CLs rolling devtools-frontend # and whatever else without interference from each other. - 'devtools_frontend_revision': '38c465da95aac2db34c2f4ba6379fda21f60729d', + 'devtools_frontend_revision': '9bddd7c7e3259f00dcdedb3670a88283d058537a', # Three lines of non-changing comments so that # the commit queue can handle CLs rolling libprotobuf-mutator # and whatever else without interference from each other. @@ -490,7 +490,7 @@ 'packages': [ { 'package': 'chromium/chrome/test/data/autofill/captured_sites', - 'version': 'BwYBAduewvKw86DOg68idRc6lllWFGw6-waD6UVmR5YC', + 'version': '0pgUX3VESdjGKemtmjistv4nlStl7b-qTsNn71BLgc4C', } ], 'condition': 'checkout_chromium_autofill_test_dependencies', @@ -528,11 +528,6 @@ 'src/chrome/test/data/xr/webvr_info': Var('chromium_git') + '/external/github.com/toji/webvr.info.git' + '@' + 'c58ae99b9ff9e2aa4c524633519570bf33536248', - 'src/ios/third_party/earl_grey/src': { - 'url': Var('chromium_git') + '/external/github.com/google/EarlGrey.git' + '@' + 'ff524fb646253b0cbc05aa6d0b327b6b3ddd0385', - 'condition': 'checkout_ios', - }, - 'src/ios/third_party/earl_grey2/src': { 'url': Var('chromium_git') + '/external/github.com/google/EarlGrey.git' + '@' + '891b1b683a7ed73f98f8064672a95ca77060df42', 'condition': 'checkout_ios', @@ -910,7 +905,7 @@ }, 'src/third_party/depot_tools': - Var('chromium_git') + '/chromium/tools/depot_tools.git' + '@' + '3328717600c218891a689b07c5c73351d798f988', + Var('chromium_git') + '/chromium/tools/depot_tools.git' + '@' + '1f97007e75fafb56dcf2e7bc03773ef298165da5', 'src/third_party/devtools-frontend/src': Var('chromium_git') + '/devtools/devtools-frontend' + '@' + Var('devtools_frontend_revision'), @@ -1275,7 +1270,7 @@ }, 'src/third_party/perfetto': - Var('android_git') + '/platform/external/perfetto.git' + '@' + '83d683fdbb2c1f5e4a903c7cadd436b3b97ead20', + Var('android_git') + '/platform/external/perfetto.git' + '@' + '788d246c91b41900488b8ad7880ee697fb764052', 'src/third_party/perl': { 'url': Var('chromium_git') + '/chromium/deps/perl.git' + '@' + '6f3e5028eb65d0b4c5fdd792106ac4c84eee1eb3', @@ -1353,7 +1348,7 @@ 'packages': [ { 'package': 'fuchsia/third_party/aemu/linux-amd64', - 'version': '61Rwfk0JmouuWC4yQWa-1pV8JvQTA7D7Tx90QSI2JZ8C' + 'version': 'Yr5NEIwTKR3mWqMgyBvXHJh1-k2HFLVAwhJWM-sLfYMC' }, ], 'condition': 'host_os == "linux" and checkout_fuchsia', @@ -1511,7 +1506,7 @@ Var('chromium_git') + '/external/github.com/gpuweb/cts.git' + '@' + '66460536ee975a3e98931b7b40a661a63fd9cd57', 'src/third_party/webrtc': - Var('webrtc_git') + '/src.git' + '@' + '54b925cfc2cd7c2f8f83e8e484f281aa87b92dfc', + Var('webrtc_git') + '/src.git' + '@' + 'c5bdac64cf221b561c1678a59badfbeacd534d46', 'src/third_party/libgifcodec': Var('skia_git') + '/libgifcodec' + '@'+ Var('libgifcodec_revision'), @@ -1583,7 +1578,7 @@ Var('chromium_git') + '/v8/v8.git' + '@' + Var('v8_revision'), 'src-internal': { - 'url': 'https://chrome-internal.googlesource.com/chrome/src-internal.git@d27706fc5dbb9aaec695d27b2e97a7b60293c710', + 'url': 'https://chrome-internal.googlesource.com/chrome/src-internal.git@3e14048874f26ba523d584ac99a4cc263f72bb4a', 'condition': 'checkout_src_internal', },
diff --git a/PRESUBMIT.py b/PRESUBMIT.py index 4ffdadd..ae05fd3 100644 --- a/PRESUBMIT.py +++ b/PRESUBMIT.py
@@ -332,7 +332,6 @@ '^base/callback.h', # Intentional. '^base/cancelable_callback.h', # Intentional. '^chrome/browser/apps/guest_view/web_view_browsertest.cc', - '^chrome/browser/browsing_data/', '^chrome/browser/captive_portal/captive_portal_browsertest.cc', '^chrome/browser/device_identity/chromeos/device_oauth2_token_store_chromeos.cc', # pylint: disable=line-too-long '^chrome/browser/history/android/android_history_provider_service_unittest.cc', # pylint: disable=line-too-long @@ -342,16 +341,11 @@ '^chrome/browser/ntp_tiles/ntp_tiles_browsertest.cc', '^chrome/browser/page_load_metrics/observers/data_saver_site_breakdown_metrics_observer_browsertest.cc', # pylint: disable=line-too-long '^chrome/browser/payments/payment_manifest_parser_browsertest.cc', - '^chrome/browser/pdf/pdf_extension_test.cc', '^chrome/browser/plugins/', - '^chrome/browser/policy/', '^chrome/browser/portal/portal_browsertest.cc', - '^chrome/browser/prefs/profile_pref_store_manager_unittest.cc', '^chrome/browser/previews/', '^chrome/browser/profiling_host/profiling_process_host.cc', - '^chrome/browser/push_messaging/', '^chrome/browser/recovery/recovery_install_global_error.cc', - '^chrome/browser/resource_coordinator/', '^chrome/browser/resources/chromeos/accessibility/', '^chrome/browser/rlz/chrome_rlz_tracker_delegate.cc', '^chrome/browser/search_engines/', @@ -359,7 +353,6 @@ '^chrome/browser/site_isolation/site_per_process_text_input_browsertest.cc', '^chrome/browser/sync_file_system/', '^chrome/browser/web_applications/', - '^components/search_engines/', '^extensions/browser/', '^extensions/renderer/', '^media/blink/webmediaplayer_impl.cc', @@ -369,6 +362,50 @@ '^tools/gdb/gdb_chrome.py', # Intentional. )) +# Directories that contain deprecated CallbackList types. +# Find sub-directories from a given directory by running: +# for i in `find . -maxdepth 1 -type d|sort`; do +# echo "-- $i" +# (cd $i; git grep -nP 'base::CallbackList<'|wc -l) +# done +# +# TODO(crbug.com/1113007): Remove (or narrow the scope of) paths from this list +# when they have been converted to modern callback list types (OnceCallback, +# RepeatingCallback) in order to enable presubmit checks for them and prevent +# regressions. +_NOT_CONVERTED_TO_MODERN_CALLBACK_LIST = '|'.join(( + r'^chrome/browser/android/oom_intervention/near_oom_monitor\.h', + r'^chrome/browser/ash/account_manager/child_account_type_changed_user_data\.h', # pylint: disable=line-too-long + r'^chrome/browser/browser_switcher/', + r'^chrome/browser/chromeos/', + r'^chrome/browser/media/router/providers/cast/', + r'^chrome/brwoser/sessions/session_restore\.cc', + r'^chrome/browser/supervised_user/', + r'^chrome/browser/ui/', + r'^chromecast/external_mojo/external_service_support/', + r'^components/captive_portal/content/captive_portal_service\.h', + r'^components/keyed_service/core/keyed_service_shutdown_notifier\.h', + r'^components/media_router/browser/', + r'^components/ntp_tils/custom_links_manager_impl\.h', + r'^components/password_manager/core/browser/hash_password_manager\.h', + r'^components/suggestions/suggestions_service\.h', + r'^components/sync_device_info/', + r'^components/sync_sessions/session_sync_service_impl\.h', + r'^components/zoom/zoom_event_manager\.h', + r'^content/browser/host_zoom_map_impl\.h', + r'^content/browser/network_service_instance_impl\.h', + r'^content/browser/rendeer_host/render_process_host_impl\.cc', + r'^extensions/test/extension_test_notification_observer\.h', + r'^ios/chrome/browser/tabs/tab_parenting_global_observer\.h', + r'^ios/net/cookies/cookie_store_ios\.h', + r'^net/cookies/cookie_monster_change_dispatcher\.h', + r'^remoting/signaling/messaging_client\.h', + r'^services/device/battery/battery_status_service\.h', + r'^services/device/geolocation/', + r'^weblayer/browser/i18n_util\.cc', + r'^weblayer/public/cookie_manager\.h', +)) + # Format: Sequence of tuples containing: # * String pattern or, if starting with a slash, a regular expression. # * Sequence of strings to show when the pattern matches. @@ -822,6 +859,15 @@ (_NOT_CONVERTED_TO_MODERN_BIND_AND_CALLBACK,), ), ( + r'/\bbase::CallbackList<', + ( + 'Please use base::{Once,Repeating}CallbackList instead', + 'of base::CallbackList. (crbug.com/1113007)' + ), + False, + (_NOT_CONVERTED_TO_MODERN_CALLBACK_LIST,), + ), + ( r'/\bRunMessageLoop\b', ( 'RunMessageLoop is deprecated, use RunLoop instead.',
diff --git a/WATCHLISTS b/WATCHLISTS index 4146126..403c4202 100644 --- a/WATCHLISTS +++ b/WATCHLISTS
@@ -1913,8 +1913,8 @@ 'ui_strings': { 'filepath': 'chrome/app/generated_resources.grd'\ '|chrome/app/google_chrome_strings.grd'\ - '|chrome/android/java/strings/android_chrome_strings.grd'\ '|chrome/app/settings_strings.grdp'\ + '|chrome/browser/ui/android/strings/android_chrome_strings.grd'\ '|ios/chrome/app/strings/ios(_.+)*_strings.grd'\ '|ui/strings/ui_strings.grd', },
diff --git a/android_webview/browser/safe_browsing/aw_safe_browsing_allowlist_manager.h b/android_webview/browser/safe_browsing/aw_safe_browsing_allowlist_manager.h index 3ec0ffa..33ab054 100644 --- a/android_webview/browser/safe_browsing/aw_safe_browsing_allowlist_manager.h +++ b/android_webview/browser/safe_browsing/aw_safe_browsing_allowlist_manager.h
@@ -44,7 +44,7 @@ // The hostname with a leading dot means an exact match, otherwise subdomains // are also matched. This particular rule is similar to admiministration // policy format: -// https://www.chromium.org/administrators/url-blacklist-filter-format +// https://www.chromium.org/administrators/url-blocklist-filter-format // // The expected number of entries on the list should be 100s at most, however // the size is not enforced here. The list size can be enforced at
diff --git a/android_webview/glue/BUILD.gn b/android_webview/glue/BUILD.gn index 8c39259..5107ff1 100644 --- a/android_webview/glue/BUILD.gn +++ b/android_webview/glue/BUILD.gn
@@ -48,7 +48,6 @@ "java/src/com/android/webview/chromium/GlueApiHelperForQ.java", "java/src/com/android/webview/chromium/GlueApiHelperForR.java", "java/src/com/android/webview/chromium/GraphicsUtils.java", - "java/src/com/android/webview/chromium/MonochromeLibraryPreloader.java", "java/src/com/android/webview/chromium/PacProcessorImpl.java", "java/src/com/android/webview/chromium/SafeBrowsingResponseAdapter.java", "java/src/com/android/webview/chromium/ServiceWorkerClientAdapter.java", @@ -79,6 +78,7 @@ "java/src/com/android/webview/chromium/WebViewContentsClientAdapter.java", "java/src/com/android/webview/chromium/WebViewDatabaseAdapter.java", "java/src/com/android/webview/chromium/WebViewDelegateFactory.java", + "java/src/com/android/webview/chromium/WebViewLibraryPreloader.java", "java/src/com/android/webview/chromium/WebViewRenderProcessAdapter.java", "java/src/com/android/webview/chromium/WebViewRenderProcessClientAdapter.java", "java/src/com/android/webview/chromium/WebkitToSharedGlueConverter.java",
diff --git a/android_webview/glue/java/src/com/android/webview/chromium/MonochromeLibraryPreloader.java b/android_webview/glue/java/src/com/android/webview/chromium/MonochromeLibraryPreloader.java deleted file mode 100644 index b8e9f3cf..0000000 --- a/android_webview/glue/java/src/com/android/webview/chromium/MonochromeLibraryPreloader.java +++ /dev/null
@@ -1,22 +0,0 @@ -// Copyright 2016 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. - -package com.android.webview.chromium; - -import android.content.pm.ApplicationInfo; -import android.webkit.WebViewFactory; - -import org.chromium.base.library_loader.NativeLibraryPreloader; - -/** - * The library preloader for Monochrome for sharing native library's relro - * between Chrome and WebView. - */ -public class MonochromeLibraryPreloader extends NativeLibraryPreloader { - @Override - public int loadLibrary(ApplicationInfo appInfo) { - return WebViewFactory.loadWebViewNativeLibraryFromPackage( - appInfo.packageName, getClass().getClassLoader()); - } -}
diff --git a/android_webview/glue/java/src/com/android/webview/chromium/WebViewLibraryPreloader.java b/android_webview/glue/java/src/com/android/webview/chromium/WebViewLibraryPreloader.java new file mode 100644 index 0000000..a9518743 --- /dev/null +++ b/android_webview/glue/java/src/com/android/webview/chromium/WebViewLibraryPreloader.java
@@ -0,0 +1,21 @@ +// Copyright 2021 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. + +package com.android.webview.chromium; + +import android.webkit.WebViewFactory; + +import org.chromium.base.library_loader.NativeLibraryPreloader; + +/** + * The library preloader for Monochrome and Trichrome for sharing native library's relro + * between Chrome and WebView/WebLayer. + */ +public class WebViewLibraryPreloader extends NativeLibraryPreloader { + @Override + public int loadLibrary(String packageName) { + return WebViewFactory.loadWebViewNativeLibraryFromPackage( + packageName, getClass().getClassLoader()); + } +}
diff --git a/android_webview/nonembedded/BUILD.gn b/android_webview/nonembedded/BUILD.gn index 5663848..7c5119cd 100644 --- a/android_webview/nonembedded/BUILD.gn +++ b/android_webview/nonembedded/BUILD.gn
@@ -25,6 +25,7 @@ "//android_webview:android_webview_product_config_java", "//android_webview:common_aidl_java", "//android_webview:common_java", + "//android_webview/glue:glue_java", "//android_webview/proto:metrics_bridge_records_proto_java", "//base:base_java", "//base:jni_java",
diff --git a/android_webview/nonembedded/java/src/org/chromium/android_webview/nonembedded/WebViewApkApplication.java b/android_webview/nonembedded/java/src/org/chromium/android_webview/nonembedded/WebViewApkApplication.java index b580a323..ba08b2a 100644 --- a/android_webview/nonembedded/java/src/org/chromium/android_webview/nonembedded/WebViewApkApplication.java +++ b/android_webview/nonembedded/java/src/org/chromium/android_webview/nonembedded/WebViewApkApplication.java
@@ -8,6 +8,9 @@ import android.content.ComponentName; import android.content.Context; import android.content.pm.PackageManager; +import android.os.Build; + +import com.android.webview.chromium.WebViewLibraryPreloader; import org.chromium.android_webview.AwLocaleConfig; import org.chromium.android_webview.common.CommandLineUtil; @@ -70,6 +73,12 @@ UmaRecorderHolder.setAllowNativeUmaRecorder(false); UmaRecorderHolder.setNonNativeDelegate(new AwNonembeddedUmaRecorder()); } + + // Limit to N+ since external services were added in N. + if (!LibraryLoader.getInstance().isLoadedByZygote() + && Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) { + LibraryLoader.getInstance().setNativeLibraryPreloader(new WebViewLibraryPreloader()); + } } // Returns true if running in the "webview_apk" or "webview_service" process.
diff --git a/ash/BUILD.gn b/ash/BUILD.gn index 5db5a4a0..a098500 100644 --- a/ash/BUILD.gn +++ b/ash/BUILD.gn
@@ -700,6 +700,8 @@ "metrics/histogram_macros.h", "metrics/login_metrics_recorder.cc", "metrics/login_metrics_recorder.h", + "metrics/login_unlock_throughput_recorder.cc", + "metrics/login_unlock_throughput_recorder.h", "metrics/pip_uma.h", "metrics/pointer_metrics_recorder.cc", "metrics/pointer_metrics_recorder.h", @@ -1837,6 +1839,7 @@ # TODO(https://crbug.com/644355): Remove Shill dependencies. "//chromeos/dbus/shill", "//chromeos/dbus/system_clock", + "//chromeos/login/login_state", # TODO(https://crbug.com/644355): Remove Shill dependencies. "//chromeos/network", @@ -2456,6 +2459,8 @@ "//chromeos/dbus:test_support", "//chromeos/dbus/audio", "//chromeos/dbus/hammerd", + "//chromeos/dbus/hermes:hermes_clients", + "//chromeos/dbus/hermes:hermes_fakes", "//chromeos/dbus/power", "//chromeos/dbus/power:power_manager_proto", "//chromeos/dbus/services:test_support", @@ -2802,6 +2807,7 @@ "//chromeos/dbus/power", "//chromeos/dbus/power:power_manager_proto", "//chromeos/dbus/system_clock", + "//chromeos/login/login_state", # TODO(https://crbug.com/644355): Remove Shill dependencies. "//ash/keyboard/ui",
diff --git a/ash/frame/caption_buttons/frame_size_button_unittest.cc b/ash/frame/caption_buttons/frame_size_button_unittest.cc index 9f5015a..b787a53 100644 --- a/ash/frame/caption_buttons/frame_size_button_unittest.cc +++ b/ash/frame/caption_buttons/frame_size_button_unittest.cc
@@ -329,8 +329,8 @@ // - The state of all the caption buttons is reset. // - The icon displayed by all of the caption buttons is reset. TEST_F(FrameSizeButtonTest, ResetButtonsAfterClick) { - EXPECT_EQ(views::CAPTION_BUTTON_ICON_MINIMIZE, minimize_button()->GetIcon()); - EXPECT_EQ(views::CAPTION_BUTTON_ICON_CLOSE, close_button()->GetIcon()); + EXPECT_EQ(views::CAPTION_BUTTON_ICON_MINIMIZE, minimize_button()->icon()); + EXPECT_EQ(views::CAPTION_BUTTON_ICON_CLOSE, close_button()->icon()); EXPECT_TRUE(AllButtonsInNormalState()); // Pressing the size button should result in the size button being pressed and @@ -341,10 +341,8 @@ EXPECT_EQ(views::Button::STATE_NORMAL, minimize_button()->GetState()); EXPECT_EQ(views::Button::STATE_PRESSED, size_button()->GetState()); EXPECT_EQ(views::Button::STATE_NORMAL, close_button()->GetState()); - EXPECT_EQ(views::CAPTION_BUTTON_ICON_LEFT_SNAPPED, - minimize_button()->GetIcon()); - EXPECT_EQ(views::CAPTION_BUTTON_ICON_RIGHT_SNAPPED, - close_button()->GetIcon()); + EXPECT_EQ(views::CAPTION_BUTTON_ICON_LEFT_SNAPPED, minimize_button()->icon()); + EXPECT_EQ(views::CAPTION_BUTTON_ICON_RIGHT_SNAPPED, close_button()->icon()); // Dragging the mouse over the minimize button should hover the minimize // button and the minimize and close button icons should stay changed. @@ -352,10 +350,8 @@ EXPECT_EQ(views::Button::STATE_HOVERED, minimize_button()->GetState()); EXPECT_EQ(views::Button::STATE_PRESSED, size_button()->GetState()); EXPECT_EQ(views::Button::STATE_NORMAL, close_button()->GetState()); - EXPECT_EQ(views::CAPTION_BUTTON_ICON_LEFT_SNAPPED, - minimize_button()->GetIcon()); - EXPECT_EQ(views::CAPTION_BUTTON_ICON_RIGHT_SNAPPED, - close_button()->GetIcon()); + EXPECT_EQ(views::CAPTION_BUTTON_ICON_LEFT_SNAPPED, minimize_button()->icon()); + EXPECT_EQ(views::CAPTION_BUTTON_ICON_RIGHT_SNAPPED, close_button()->icon()); // Release the mouse, snapping the window left. generator->ReleaseLeftButton(); @@ -365,8 +361,8 @@ // None of the buttons should stay pressed and the buttons should have their // regular icons. EXPECT_TRUE(AllButtonsInNormalState()); - EXPECT_EQ(views::CAPTION_BUTTON_ICON_MINIMIZE, minimize_button()->GetIcon()); - EXPECT_EQ(views::CAPTION_BUTTON_ICON_CLOSE, close_button()->GetIcon()); + EXPECT_EQ(views::CAPTION_BUTTON_ICON_MINIMIZE, minimize_button()->icon()); + EXPECT_EQ(views::CAPTION_BUTTON_ICON_CLOSE, close_button()->icon()); // Repeat test but release button where it does not affect the window's state // because the code path is different. @@ -375,10 +371,8 @@ EXPECT_EQ(views::Button::STATE_NORMAL, minimize_button()->GetState()); EXPECT_EQ(views::Button::STATE_PRESSED, size_button()->GetState()); EXPECT_EQ(views::Button::STATE_NORMAL, close_button()->GetState()); - EXPECT_EQ(views::CAPTION_BUTTON_ICON_LEFT_SNAPPED, - minimize_button()->GetIcon()); - EXPECT_EQ(views::CAPTION_BUTTON_ICON_RIGHT_SNAPPED, - close_button()->GetIcon()); + EXPECT_EQ(views::CAPTION_BUTTON_ICON_LEFT_SNAPPED, minimize_button()->icon()); + EXPECT_EQ(views::CAPTION_BUTTON_ICON_RIGHT_SNAPPED, close_button()->icon()); const gfx::Rect work_area_bounds_in_screen = display::Screen::GetScreen()->GetPrimaryDisplay().work_area(); @@ -388,10 +382,8 @@ // any of the caption buttons. The minimize and close button icons should // be changed because the mouse is pressed. EXPECT_TRUE(AllButtonsInNormalState()); - EXPECT_EQ(views::CAPTION_BUTTON_ICON_LEFT_SNAPPED, - minimize_button()->GetIcon()); - EXPECT_EQ(views::CAPTION_BUTTON_ICON_RIGHT_SNAPPED, - close_button()->GetIcon()); + EXPECT_EQ(views::CAPTION_BUTTON_ICON_LEFT_SNAPPED, minimize_button()->icon()); + EXPECT_EQ(views::CAPTION_BUTTON_ICON_RIGHT_SNAPPED, close_button()->icon()); // Release the mouse. The window should stay snapped left. generator->ReleaseLeftButton(); @@ -401,15 +393,15 @@ // The buttons should stay unpressed and the buttons should now have their // regular icons. EXPECT_TRUE(AllButtonsInNormalState()); - EXPECT_EQ(views::CAPTION_BUTTON_ICON_MINIMIZE, minimize_button()->GetIcon()); - EXPECT_EQ(views::CAPTION_BUTTON_ICON_CLOSE, close_button()->GetIcon()); + EXPECT_EQ(views::CAPTION_BUTTON_ICON_MINIMIZE, minimize_button()->icon()); + EXPECT_EQ(views::CAPTION_BUTTON_ICON_CLOSE, close_button()->icon()); } // Test that the size button is pressed whenever the snap left/right buttons // are hovered. TEST_F(FrameSizeButtonTest, SizeButtonPressedWhenSnapButtonHovered) { - EXPECT_EQ(views::CAPTION_BUTTON_ICON_MINIMIZE, minimize_button()->GetIcon()); - EXPECT_EQ(views::CAPTION_BUTTON_ICON_CLOSE, close_button()->GetIcon()); + EXPECT_EQ(views::CAPTION_BUTTON_ICON_MINIMIZE, minimize_button()->icon()); + EXPECT_EQ(views::CAPTION_BUTTON_ICON_CLOSE, close_button()->icon()); EXPECT_TRUE(AllButtonsInNormalState()); // Pressing the size button should result in the size button being pressed and @@ -420,10 +412,8 @@ EXPECT_EQ(views::Button::STATE_NORMAL, minimize_button()->GetState()); EXPECT_EQ(views::Button::STATE_PRESSED, size_button()->GetState()); EXPECT_EQ(views::Button::STATE_NORMAL, close_button()->GetState()); - EXPECT_EQ(views::CAPTION_BUTTON_ICON_LEFT_SNAPPED, - minimize_button()->GetIcon()); - EXPECT_EQ(views::CAPTION_BUTTON_ICON_RIGHT_SNAPPED, - close_button()->GetIcon()); + EXPECT_EQ(views::CAPTION_BUTTON_ICON_LEFT_SNAPPED, minimize_button()->icon()); + EXPECT_EQ(views::CAPTION_BUTTON_ICON_RIGHT_SNAPPED, close_button()->icon()); // Dragging the mouse over the minimize button (snap left button) should hover // the minimize button and keep the size button pressed. @@ -481,8 +471,8 @@ // Test initial state. EXPECT_TRUE(window_state()->IsNormalStateType()); EXPECT_TRUE(AllButtonsInNormalState()); - EXPECT_EQ(views::CAPTION_BUTTON_ICON_MINIMIZE, minimize_button()->GetIcon()); - EXPECT_EQ(views::CAPTION_BUTTON_ICON_CLOSE, close_button()->GetIcon()); + EXPECT_EQ(views::CAPTION_BUTTON_ICON_MINIMIZE, minimize_button()->icon()); + EXPECT_EQ(views::CAPTION_BUTTON_ICON_CLOSE, close_button()->icon()); // Pressing the size button should swap the icons of the minimize and close // buttons to icons for snapping right and for snapping left respectively. @@ -493,8 +483,8 @@ EXPECT_EQ(views::Button::STATE_PRESSED, size_button()->GetState()); EXPECT_EQ(views::Button::STATE_NORMAL, close_button()->GetState()); EXPECT_EQ(views::CAPTION_BUTTON_ICON_RIGHT_SNAPPED, - minimize_button()->GetIcon()); - EXPECT_EQ(views::CAPTION_BUTTON_ICON_LEFT_SNAPPED, close_button()->GetIcon()); + minimize_button()->icon()); + EXPECT_EQ(views::CAPTION_BUTTON_ICON_LEFT_SNAPPED, close_button()->icon()); // Dragging over to the minimize button should press it. generator->MoveMouseTo(CenterPointInScreen(minimize_button())); @@ -510,8 +500,8 @@ // None of the buttons should stay pressed and the buttons should have their // regular icons. EXPECT_TRUE(AllButtonsInNormalState()); - EXPECT_EQ(views::CAPTION_BUTTON_ICON_MINIMIZE, minimize_button()->GetIcon()); - EXPECT_EQ(views::CAPTION_BUTTON_ICON_CLOSE, close_button()->GetIcon()); + EXPECT_EQ(views::CAPTION_BUTTON_ICON_MINIMIZE, minimize_button()->icon()); + EXPECT_EQ(views::CAPTION_BUTTON_ICON_CLOSE, close_button()->icon()); } namespace { @@ -528,8 +518,8 @@ } // namespace TEST_F(FrameSizeButtonNonResizableTest, NoSnap) { - EXPECT_EQ(views::CAPTION_BUTTON_ICON_MINIMIZE, minimize_button()->GetIcon()); - EXPECT_EQ(views::CAPTION_BUTTON_ICON_CLOSE, close_button()->GetIcon()); + EXPECT_EQ(views::CAPTION_BUTTON_ICON_MINIMIZE, minimize_button()->icon()); + EXPECT_EQ(views::CAPTION_BUTTON_ICON_CLOSE, close_button()->icon()); EXPECT_TRUE(AllButtonsInNormalState()); // Pressing the size button should result in the size button being pressed and @@ -541,8 +531,8 @@ EXPECT_EQ(views::Button::STATE_PRESSED, size_button()->GetState()); EXPECT_EQ(views::Button::STATE_NORMAL, close_button()->GetState()); - EXPECT_EQ(views::CAPTION_BUTTON_ICON_MINIMIZE, minimize_button()->GetIcon()); - EXPECT_EQ(views::CAPTION_BUTTON_ICON_CLOSE, close_button()->GetIcon()); + EXPECT_EQ(views::CAPTION_BUTTON_ICON_MINIMIZE, minimize_button()->icon()); + EXPECT_EQ(views::CAPTION_BUTTON_ICON_CLOSE, close_button()->icon()); } } // namespace ash
diff --git a/ash/frame/non_client_frame_view_ash_unittest.cc b/ash/frame/non_client_frame_view_ash_unittest.cc index 67093a9..c73a707 100644 --- a/ash/frame/non_client_frame_view_ash_unittest.cc +++ b/ash/frame/non_client_frame_view_ash_unittest.cc
@@ -178,7 +178,7 @@ EXPECT_TRUE(widget->IsActive()); // The paint state doesn't change till the next paint. ui::DrawWaiterForTest::WaitForCommit(widget->GetLayer()->GetCompositor()); - EXPECT_TRUE(test_api.size_button()->GetPaintAsActive()); + EXPECT_TRUE(test_api.size_button()->paint_as_active()); // Activate a different widget so the original one loses activation. std::unique_ptr<views::Widget> widget2 = @@ -187,7 +187,7 @@ ui::DrawWaiterForTest::WaitForCommit(widget->GetLayer()->GetCompositor()); EXPECT_FALSE(widget->IsActive()); - EXPECT_FALSE(test_api.size_button()->GetPaintAsActive()); + EXPECT_FALSE(test_api.size_button()->paint_as_active()); } // Verify that NonClientFrameViewAsh returns the correct minimum and maximum
diff --git a/ash/metrics/DEPS b/ash/metrics/DEPS new file mode 100644 index 0000000..d769769 --- /dev/null +++ b/ash/metrics/DEPS
@@ -0,0 +1,3 @@ +include_rules = [ + "+chromeos/login/login_state", +]
diff --git a/ash/metrics/login_unlock_throughput_recorder.cc b/ash/metrics/login_unlock_throughput_recorder.cc new file mode 100644 index 0000000..1436c68e --- /dev/null +++ b/ash/metrics/login_unlock_throughput_recorder.cc
@@ -0,0 +1,87 @@ +// Copyright 2020 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 "ash/metrics/login_unlock_throughput_recorder.h" + +#include "ash/public/cpp/metrics_util.h" +#include "ash/session/session_controller_impl.h" +#include "ash/shell.h" +#include "base/bind.h" +#include "base/metrics/histogram_functions.h" +#include "chromeos/login/login_state/login_state.h" +#include "ui/aura/window.h" +#include "ui/aura/window_tree_host.h" +#include "ui/compositor/total_animation_throughput_reporter.h" + +namespace ash { +namespace { + +void ReportLogin(const cc::FrameSequenceMetrics::CustomReportData& data) { + if (data.frames_expected) { + int smoothness = metrics_util::CalculateSmoothness(data); + int jank = metrics_util::CalculateJank(data); + + float refresh_rate = + Shell::GetPrimaryRootWindow()->GetHost()->compositor()->refresh_rate(); + int duration_ms = (1000.f / refresh_rate) * data.frames_expected; + base::UmaHistogramPercentage("Ash.LoginAnimation.Smoothness", smoothness); + base::UmaHistogramPercentage("Ash.LoginAnimation.Jank", jank); + // TODO(crbug.com/1143898): Deprecate this metrics once the login + // performance issue is resolved. + base::UmaHistogramCustomTimes( + "Ash.LoginAnimation.Duration", + base::TimeDelta::FromMilliseconds(duration_ms), + base::TimeDelta::FromMilliseconds(100), base::TimeDelta::FromSeconds(5), + 50); + } else { + LOG(WARNING) << "Zero frames expected in login animation throughput data"; + } +} + +void ReportUnlock(const cc::FrameSequenceMetrics::CustomReportData& data) { + if (data.frames_expected) { + int smoothness = metrics_util::CalculateSmoothness(data); + int jank = metrics_util::CalculateJank(data); + + base::UmaHistogramPercentage("Ash.UnlockAnimation.Smoothness", smoothness); + base::UmaHistogramPercentage("Ash.UnlockAnimation.Jank", jank); + } else { + LOG(WARNING) << "Zero frames expected in Unlock animation throughput data"; + } +} + +} // namespace + +LoginUnlockThroughputRecorder::LoginUnlockThroughputRecorder() { + Shell::Get()->session_controller()->AddObserver(this); + chromeos::LoginState::Get()->AddObserver(this); +} + +LoginUnlockThroughputRecorder::~LoginUnlockThroughputRecorder() { + Shell::Get()->session_controller()->RemoveObserver(this); + chromeos::LoginState::Get()->RemoveObserver(this); +} + +void LoginUnlockThroughputRecorder::OnLockStateChanged(bool locked) { + if (!locked && chromeos::LoginState::Get()->GetLoggedInUserType() == + chromeos::LoginState::LOGGED_IN_USER_REGULAR) { + auto* primary_root = Shell::GetPrimaryRootWindow(); + new ui::TotalAnimationThroughputReporter( + primary_root->GetHost()->compositor(), base::BindOnce(&ReportUnlock), + /*self_destruct=*/true); + } +} + +void LoginUnlockThroughputRecorder::LoggedInStateChanged() { + if (chromeos::LoginState::Get()->IsUserLoggedIn() && + chromeos::LoginState::Get()->GetLoggedInUserType() == + chromeos::LoginState::LOGGED_IN_USER_REGULAR) { + auto* primary_root = Shell::GetPrimaryRootWindow(); + new ui::TotalAnimationThroughputReporter( + primary_root->GetHost()->compositor(), base::BindOnce(&ReportLogin), + /*self_destruct=*/true); + } +} + +} // namespace ash
diff --git a/ash/metrics/login_unlock_throughput_recorder.h b/ash/metrics/login_unlock_throughput_recorder.h new file mode 100644 index 0000000..55b1d92 --- /dev/null +++ b/ash/metrics/login_unlock_throughput_recorder.h
@@ -0,0 +1,31 @@ +// Copyright 2020 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 ASH_METRICS_LOGIN_UNLOCK_THROUGHPUT_RECORDER_H_ +#define ASH_METRICS_LOGIN_UNLOCK_THROUGHPUT_RECORDER_H_ + +#include "ash/public/cpp/session/session_observer.h" +#include "chromeos/login/login_state/login_state.h" + +namespace ash { + +class LoginUnlockThroughputRecorder : public SessionObserver, + public chromeos::LoginState::Observer { + public: + LoginUnlockThroughputRecorder(); + LoginUnlockThroughputRecorder(const LoginUnlockThroughputRecorder&) = delete; + LoginUnlockThroughputRecorder& operator=( + const LoginUnlockThroughputRecorder&) = delete; + ~LoginUnlockThroughputRecorder() override; + + // ShellObserver: + void OnLockStateChanged(bool locked) override; + + // chromeos::LoginState::Observer: + void LoggedInStateChanged() override; +}; + +} // namespace ash + +#endif // ASH_METRICS_LOGIN_UNLOCK_THROUGHPUT_RECORDER_H_
diff --git a/ash/public/cpp/system_tray_client.h b/ash/public/cpp/system_tray_client.h index 07c0afc..a3ad2d8 100644 --- a/ash/public/cpp/system_tray_client.h +++ b/ash/public/cpp/system_tray_client.h
@@ -93,8 +93,10 @@ // (see onc_spec.md). TODO(stevenjb): Use NetworkType from onc.mojo (TBD). virtual void ShowNetworkCreate(const std::string& type) = 0; - // Opens the physical SIM cellular setup flow in OS Settings. - virtual void ShowSettingsCellularSetupPsimFlow() = 0; + // Opens the cellular setup flow in OS Settings. |show_psim_flow| indicates + // if we should navigate to the physical SIM setup flow or to the page that + // allows the user to select which flow they wish to enter (pSIM or eSIM). + virtual void ShowSettingsCellularSetup(bool show_psim_flow) = 0; // Shows the "add network" UI to create a third-party extension-backed VPN // connection (e.g. Cisco AnyConnect).
diff --git a/ash/public/cpp/test/test_system_tray_client.cc b/ash/public/cpp/test/test_system_tray_client.cc index e4b9f68..d51cb3a 100644 --- a/ash/public/cpp/test/test_system_tray_client.cc +++ b/ash/public/cpp/test/test_system_tray_client.cc
@@ -63,7 +63,7 @@ void TestSystemTrayClient::ShowNetworkCreate(const std::string& type) {} -void TestSystemTrayClient::ShowSettingsCellularSetupPsimFlow() {} +void TestSystemTrayClient::ShowSettingsCellularSetup(bool show_psim_flow) {} void TestSystemTrayClient::ShowThirdPartyVpnCreate( const std::string& extension_id) {}
diff --git a/ash/public/cpp/test/test_system_tray_client.h b/ash/public/cpp/test/test_system_tray_client.h index 9af7635..1af4de2 100644 --- a/ash/public/cpp/test/test_system_tray_client.h +++ b/ash/public/cpp/test/test_system_tray_client.h
@@ -43,7 +43,7 @@ void ShowEnterpriseInfo() override; void ShowNetworkConfigure(const std::string& network_id) override; void ShowNetworkCreate(const std::string& type) override; - void ShowSettingsCellularSetupPsimFlow() override; + void ShowSettingsCellularSetup(bool show_psim_flow) override; void ShowThirdPartyVpnCreate(const std::string& extension_id) override; void ShowArcVpnCreate(const std::string& app_id) override; void ShowNetworkSettings(const std::string& network_id) override;
diff --git a/ash/shell.cc b/ash/shell.cc index 1c0184c..8eb6b1e 100644 --- a/ash/shell.cc +++ b/ash/shell.cc
@@ -73,6 +73,7 @@ #include "ash/magnifier/partial_magnification_controller.h" #include "ash/media/media_controller_impl.h" #include "ash/media/media_notification_controller_impl.h" +#include "ash/metrics/login_unlock_throughput_recorder.h" #include "ash/multi_device_setup/multi_device_notification_presenter.h" #include "ash/policy/policy_recommendation_restorer.h" #include "ash/projector/projector_controller.h" @@ -592,6 +593,7 @@ Shell::~Shell() { TRACE_EVENT0("shutdown", "ash::Shell::Destructor"); + login_unlock_throughput_recorder_.reset(); hud_display::HUDDisplayView::Destroy(); @@ -905,6 +907,9 @@ PrefService* local_state, std::unique_ptr<keyboard::KeyboardUIFactory> keyboard_ui_factory, scoped_refptr<dbus::Bus> dbus_bus) { + login_unlock_throughput_recorder_ = + std::make_unique<LoginUnlockThroughputRecorder>(); + // Required by DetachableBaseHandler. chromeos::InitializeDBusClient<chromeos::HammerdClient>(dbus_bus.get());
diff --git a/ash/shell.h b/ash/shell.h index b576492..9b90cef 100644 --- a/ash/shell.h +++ b/ash/shell.h
@@ -137,6 +137,7 @@ class LockStateController; class LogoutConfirmationController; class LoginScreenController; +class LoginUnlockThroughputRecorder; class MagnificationController; class TabletModeController; class MediaControllerImpl; @@ -865,6 +866,9 @@ std::unique_ptr<MessageCenterController> message_center_controller_; + std::unique_ptr<LoginUnlockThroughputRecorder> + login_unlock_throughput_recorder_; + base::ObserverList<ShellObserver>::Unchecked shell_observers_; base::WeakPtrFactory<Shell> weak_factory_{this};
diff --git a/ash/system/accessibility/autoclick_menu_view.cc b/ash/system/accessibility/autoclick_menu_view.cc index 9d0166ec..8491555 100644 --- a/ash/system/accessibility/autoclick_menu_view.cc +++ b/ash/system/accessibility/autoclick_menu_view.cc
@@ -81,7 +81,7 @@ views::Builder<FloatingMenuButton>() .CopyAddressTo(&drag_button_) .SetID(static_cast<int>(ButtonId::kDragAndDrop)) - .SetVectorIcon(kAutoclickLeftClickIcon) + .SetVectorIcon(kAutoclickDragIcon) .SetTooltipText(l10n_util::GetStringUTF16( IDS_ASH_AUTOCLICK_OPTION_DRAG_AND_DROP)) .SetCallback(base::BindRepeating( @@ -91,7 +91,7 @@ views::Builder<FloatingMenuButton>() .CopyAddressTo(&scroll_button_) .SetID(static_cast<int>(ButtonId::kScroll)) - .SetVectorIcon(kAutoclickLeftClickIcon) + .SetVectorIcon(kAutoclickScrollIcon) .SetTooltipText(l10n_util::GetStringUTF16( IDS_ASH_AUTOCLICK_OPTION_SCROLL)) .SetCallback(base::BindRepeating( @@ -101,7 +101,7 @@ views::Builder<FloatingMenuButton>() .CopyAddressTo(&pause_button_) .SetID(static_cast<int>(ButtonId::kPause)) - .SetVectorIcon(kAutoclickLeftClickIcon) + .SetVectorIcon(kAutoclickPauseIcon) .SetTooltipText(l10n_util::GetStringUTF16( IDS_ASH_AUTOCLICK_OPTION_NO_ACTION)) .SetCallback(base::BindRepeating(
diff --git a/ash/system/network/cellular_setup_notifier.cc b/ash/system/network/cellular_setup_notifier.cc index 17d51e9..fa32df0 100644 --- a/ash/system/network/cellular_setup_notifier.cc +++ b/ash/system/network/cellular_setup_notifier.cc
@@ -7,10 +7,13 @@ #include "ash/public/cpp/ash_pref_names.h" #include "ash/public/cpp/network_config_service.h" #include "ash/public/cpp/notification_utils.h" +#include "ash/public/cpp/system_tray_client.h" #include "ash/session/session_controller_impl.h" #include "ash/shell.h" #include "ash/strings/grit/ash_strings.h" +#include "ash/system/model/system_tray_model.h" #include "base/timer/timer.h" +#include "components/onc/onc_constants.h" #include "components/prefs/pref_registry_simple.h" #include "components/vector_icons/vector_icons.h" #include "ui/base/l10n/l10n_util.h" @@ -38,7 +41,8 @@ } void OnCellularSetupNotificationClicked() { - // TODO(crbug.com/1093185) Handle the notification being clicked. + Shell::Get()->system_tray_model()->client()->ShowNetworkCreate( + ::onc::network_type::kCellular); } // Returns the value of kCanCellularSetupNotificationBeShown for the last active
diff --git a/ash/system/network/cellular_setup_notifier_unittest.cc b/ash/system/network/cellular_setup_notifier_unittest.cc index e0beb393..ac4e4f1d 100644 --- a/ash/system/network/cellular_setup_notifier_unittest.cc +++ b/ash/system/network/cellular_setup_notifier_unittest.cc
@@ -14,6 +14,7 @@ #include "base/test/scoped_feature_list.h" #include "base/timer/mock_timer.h" #include "chromeos/constants/chromeos_features.h" +#include "chromeos/dbus/hermes/hermes_clients.h" #include "chromeos/dbus/shill/shill_clients.h" #include "chromeos/network/network_cert_loader.h" #include "chromeos/network/network_handler.h" @@ -48,6 +49,7 @@ chromeos::NetworkCertLoader::Initialize(); chromeos::shill_clients::InitializeFakes(); + chromeos::hermes_clients::InitializeFakes(); chromeos::NetworkHandler::Initialize(); network_config_helper_ = std::make_unique< chromeos::network_config::CrosNetworkConfigTestHelper>(); @@ -68,6 +70,7 @@ AshTestBase::TearDown(); network_config_helper_.reset(); chromeos::NetworkHandler::Shutdown(); + chromeos::hermes_clients::Shutdown(); chromeos::shill_clients::Shutdown(); chromeos::NetworkCertLoader::Shutdown(); }
diff --git a/ash/test/DEPS b/ash/test/DEPS index 7e3b269..63f645b1 100644 --- a/ash/test/DEPS +++ b/ash/test/DEPS
@@ -9,5 +9,6 @@ "ash_test_helper\.cc": [ "+ash/host", "+chromeos/cryptohome", + "+chromeos/login/login_state", ], }
diff --git a/ash/test/ash_test_helper.cc b/ash/test/ash_test_helper.cc index 24fe44c..10d9fdf8 100644 --- a/ash/test/ash_test_helper.cc +++ b/ash/test/ash_test_helper.cc
@@ -35,6 +35,7 @@ #include "chromeos/audio/cras_audio_handler.h" #include "chromeos/dbus/audio/cras_audio_client.h" #include "chromeos/dbus/power/power_policy_controller.h" +#include "chromeos/login/login_state/login_state.h" #include "device/bluetooth/bluetooth_adapter_factory.h" #include "device/bluetooth/dbus/bluez_dbus_manager.h" #include "ui/aura/test/test_windows.h" @@ -153,6 +154,8 @@ // CompositorFrameSinkClient::ReclaimResources() base::RunLoop().RunUntilIdle(); + chromeos::LoginState::Shutdown(); + chromeos::CrasAudioHandler::Shutdown(); chromeos::CrasAudioClient::Shutdown(); @@ -228,6 +231,8 @@ if (!views::ViewsDelegate::GetInstance()) test_views_delegate_ = MakeTestViewsDelegate(); + chromeos::LoginState::Initialize(); + ambient_ash_test_helper_ = std::make_unique<AmbientAshTestHelper>(); ShellInitParams shell_init_params;
diff --git a/ash/wm/desks/expanded_state_new_desk_button.cc b/ash/wm/desks/expanded_state_new_desk_button.cc index 97d0479..2cb3b268 100644 --- a/ash/wm/desks/expanded_state_new_desk_button.cc +++ b/ash/wm/desks/expanded_state_new_desk_button.cc
@@ -116,15 +116,19 @@ /*compact=*/false); new_desk_button_->SetBoundsRect(new_desk_button_bounds); - const gfx::Size label_size = - bar_view_->mini_views()[0]->desk_name_view()->GetPreferredSize(); + const gfx::Size label_size = label_->GetPreferredSize(); + // Set the label to have the same height as the DeskNameView to keep them at + // the same horizotal level. Note, don't get the label's width from + // DeskNameView since desk's name is changeable, but this label here is not. + const int label_height = + bar_view_->mini_views()[0]->desk_name_view()->GetPreferredSize().height(); label_->SetBoundsRect(gfx::Rect( gfx::Point( (new_desk_button_bounds.width() - label_size.width()) / 2, new_desk_button_bounds.bottom() - bar_view_->mini_views()[0]->GetPreviewBorderInsets().bottom() + kNewDeskButtonAndNameSpacing), - label_size)); + gfx::Size(label_size.width(), label_height))); } void ExpandedStateNewDeskButton::UpdateButtonState() {
diff --git a/ash/wm/window_cycle/window_cycle_controller.cc b/ash/wm/window_cycle/window_cycle_controller.cc index e914756d..ee4c067 100644 --- a/ash/wm/window_cycle/window_cycle_controller.cc +++ b/ash/wm/window_cycle/window_cycle_controller.cc
@@ -321,26 +321,25 @@ } void WindowCycleController::OnAltTabModePrefChanged() { - if (!IsInteractiveAltTabModeAllowed()) + // Only update UI for alt-tab mode if the user is using alt-tab with the + // interactive alt-tab mode supported. + if (!IsInteractiveAltTabModeAllowed() || !IsCycling()) return; is_switching_mode_ = true; // Update the window cycle list. MaybeResetCycleList(); - // Update the highlighted window in the window cycle list. - // When user first press alt + tab, `HandleCycleForwardMRU` triggers - // `HandleCycleWindow(WindowCycleController::FORWARD)` since it considers - // the initial tab as forward cycling. Therefore, switching the mode - // should imitate the same forward cycling behavior after the cycle is reset. - HandleCycleWindow(WindowCycleController::FORWARD); + + // After the cycle is reset, imitate the same forward cycling behavior as + // starting alt-tab with `Step()`, which makes sure the correct window is + // selected and highlighted. + Step(WindowCycleController::FORWARD); // Update tab slider button UI. - if (window_cycle_list_) { - window_cycle_list_->OnModeChanged( - IsAltTabPerActiveDesk(), - WindowCycleTabSlider::ModeSwitchSource::USER_PREFS); - } + window_cycle_list_->OnModeChanged( + IsAltTabPerActiveDesk(), + WindowCycleTabSlider::ModeSwitchSource::USER_PREFS); is_switching_mode_ = false; }
diff --git a/base/allocator/partition_allocator/object_bitmap.h b/base/allocator/partition_allocator/object_bitmap.h index 680eb09..564e2256 100644 --- a/base/allocator/partition_allocator/object_bitmap.h +++ b/base/allocator/partition_allocator/object_bitmap.h
@@ -29,7 +29,8 @@ // allocated inside a page (serves as the granularity in the bitmap). template <size_t PageSize, size_t PageAlignment, size_t ObjectAlignment> class ObjectBitmap final { - static constexpr size_t kBitsPerCell = sizeof(uint8_t) * CHAR_BIT; + using CellType = uintptr_t; + static constexpr size_t kBitsPerCell = sizeof(CellType) * CHAR_BIT; static constexpr size_t kBitmapSize = (PageSize + ((kBitsPerCell * ObjectAlignment) - 1)) / (kBitsPerCell * ObjectAlignment); @@ -60,17 +61,17 @@ inline void Clear(); private: - std::atomic<uint8_t>& AsAtomicCell(size_t cell_index) { - return reinterpret_cast<std::atomic<uint8_t>&>(bitmap_[cell_index]); + std::atomic<CellType>& AsAtomicCell(size_t cell_index) { + return reinterpret_cast<std::atomic<CellType>&>(bitmap_[cell_index]); } - const std::atomic<uint8_t>& AsAtomicCell(size_t cell_index) const { - return reinterpret_cast<const std::atomic<uint8_t>&>(bitmap_[cell_index]); + const std::atomic<CellType>& AsAtomicCell(size_t cell_index) const { + return reinterpret_cast<const std::atomic<CellType>&>(bitmap_[cell_index]); } - inline uint8_t LoadCell(size_t cell_index) const; - inline std::pair<size_t, size_t> ObjectIndexAndBit(uintptr_t) const; + inline CellType LoadCell(size_t cell_index) const; + static constexpr std::pair<size_t, size_t> ObjectIndexAndBit(uintptr_t); - std::array<uint8_t, kBitmapSize> bitmap_; + std::array<CellType, kBitmapSize> bitmap_; }; template <size_t PageSize, size_t PageAlignment, size_t ObjectAlignment> @@ -89,7 +90,8 @@ size_t cell_index, object_bit; std::tie(cell_index, object_bit) = ObjectIndexAndBit(address); auto& cell = AsAtomicCell(cell_index); - cell.fetch_or(1 << object_bit, std::memory_order_relaxed); + cell.fetch_or(static_cast<CellType>(1) << object_bit, + std::memory_order_relaxed); } template <size_t PageSize, size_t PageAlignment, size_t ObjectAlignment> @@ -98,7 +100,8 @@ size_t cell_index, object_bit; std::tie(cell_index, object_bit) = ObjectIndexAndBit(address); auto& cell = AsAtomicCell(cell_index); - cell.fetch_and(~(1 << object_bit), std::memory_order_relaxed); + cell.fetch_and(~(static_cast<CellType>(1) << object_bit), + std::memory_order_relaxed); } template <size_t PageSize, size_t PageAlignment, size_t ObjectAlignment> @@ -106,19 +109,20 @@ uintptr_t address) const { size_t cell_index, object_bit; std::tie(cell_index, object_bit) = ObjectIndexAndBit(address); - return LoadCell(cell_index) & (1 << object_bit); + return LoadCell(cell_index) & (static_cast<CellType>(1) << object_bit); } template <size_t PageSize, size_t PageAlignment, size_t ObjectAlignment> -uint8_t ObjectBitmap<PageSize, PageAlignment, ObjectAlignment>::LoadCell( +typename ObjectBitmap<PageSize, PageAlignment, ObjectAlignment>::CellType +ObjectBitmap<PageSize, PageAlignment, ObjectAlignment>::LoadCell( size_t cell_index) const { return AsAtomicCell(cell_index).load(std::memory_order_relaxed); } template <size_t PageSize, size_t PageAlignment, size_t ObjectAlignment> -std::pair<size_t, size_t> +constexpr std::pair<size_t, size_t> ObjectBitmap<PageSize, PageAlignment, ObjectAlignment>::ObjectIndexAndBit( - uintptr_t address) const { + uintptr_t address) { const uintptr_t offset_in_page = address & kPageOffsetMask; const size_t object_number = offset_in_page / kObjectAlignment; const size_t cell_index = object_number / kBitsPerCell; @@ -134,7 +138,7 @@ // The bitmap (|this|) is allocated inside the page with |kPageAlignment|. const uintptr_t base = reinterpret_cast<uintptr_t>(this) & kPageBaseMask; for (size_t cell_index = 0; cell_index < kBitmapSize; ++cell_index) { - uint8_t value = LoadCell(cell_index); + CellType value = LoadCell(cell_index); while (value) { const int trailing_zeroes = base::bits::CountTrailingZeroBits(value); const size_t object_number = @@ -143,7 +147,7 @@ base + (kObjectAlignment * object_number); callback(object_address); // Clear current object bit in temporary value to advance iteration. - value &= ~(1 << trailing_zeroes); + value &= ~(static_cast<CellType>(1) << trailing_zeroes); } } }
diff --git a/base/allocator/partition_allocator/object_bitmap_unittest.cc b/base/allocator/partition_allocator/object_bitmap_unittest.cc index 35bbfc4..519b408 100644 --- a/base/allocator/partition_allocator/object_bitmap_unittest.cc +++ b/base/allocator/partition_allocator/object_bitmap_unittest.cc
@@ -15,6 +15,8 @@ namespace { using TestBitmap = ObjectBitmap<kSuperPageSize, kSuperPageSize, kAlignment>; +static_assert((kSuperPageSize / (kAlignment * CHAR_BIT)) == sizeof(TestBitmap), + "Bitmap size must only depend on object alignment"); class PageWithBitmap final { public: @@ -67,7 +69,7 @@ pos * kAlignment; } - uintptr_t LastIndex() const { + static constexpr uintptr_t LastIndex() { return TestBitmap::kMaxEntries - (sizeof(TestBitmap) / kAlignment) - 1; }
diff --git a/base/android/java/src/org/chromium/base/library_loader/LibraryLoader.java b/base/android/java/src/org/chromium/base/library_loader/LibraryLoader.java index 0f403f9..cb831cd 100644 --- a/base/android/java/src/org/chromium/base/library_loader/LibraryLoader.java +++ b/base/android/java/src/org/chromium/base/library_loader/LibraryLoader.java
@@ -479,27 +479,28 @@ * that it won't be (implicitly) called during library loading. */ public void preloadNow() { - preloadNowOverrideApplicationContext(ContextUtils.getApplicationContext()); + preloadNowOverridePackageName( + ContextUtils.getApplicationContext().getApplicationInfo().packageName); } /** * Similar to {@link #preloadNow}, but allows specifying app context to use. */ - public void preloadNowOverrideApplicationContext(Context appContext) { + public void preloadNowOverridePackageName(String packageName) { synchronized (mLock) { setLinkerImplementationIfNeededAlreadyLocked(); if (mUseChromiumLinker) return; - preloadAlreadyLocked(appContext.getApplicationInfo(), false /* inZygote */); + preloadAlreadyLocked(packageName, false /* inZygote */); } } @GuardedBy("mLock") - private void preloadAlreadyLocked(ApplicationInfo appInfo, boolean inZygote) { + private void preloadAlreadyLocked(String packageName, boolean inZygote) { try (TraceEvent te = TraceEvent.scoped("LibraryLoader.preloadAlreadyLocked")) { // Preloader uses system linker, we shouldn't preload if Chromium linker is used. assert !useChromiumLinker() || inZygote; if (mLibraryPreloader != null && !mLibraryPreloaderCalled) { - mLibraryPreloader.loadLibrary(appInfo); + mLibraryPreloader.loadLibrary(packageName); mLibraryPreloaderCalled = true; } } @@ -629,7 +630,7 @@ @SuppressLint("UnsafeDynamicallyLoadedCode") private void loadWithSystemLinkerAlreadyLocked(ApplicationInfo appInfo, boolean inZygote) { setEnvForNative(); - preloadAlreadyLocked(appInfo, inZygote); + preloadAlreadyLocked(appInfo.packageName, inZygote); // If the libraries are located in the zip file, assert that the device API level is M or // higher. On devices <=M, the libraries should always be loaded by LegacyLinker.
diff --git a/base/android/java/src/org/chromium/base/library_loader/NativeLibraryPreloader.java b/base/android/java/src/org/chromium/base/library_loader/NativeLibraryPreloader.java index 56f2cbc..18ede8c 100644 --- a/base/android/java/src/org/chromium/base/library_loader/NativeLibraryPreloader.java +++ b/base/android/java/src/org/chromium/base/library_loader/NativeLibraryPreloader.java
@@ -4,8 +4,6 @@ package org.chromium.base.library_loader; -import android.content.pm.ApplicationInfo; - /** * This is interface to preload the native library before calling System.loadLibrary. * @@ -13,8 +11,8 @@ * code to be run, because it can be called before Chromium command line is known. * It can however open the library via dlopen() or android_dlopen_ext() so that * dlopen() later called by System.loadLibrary() becomes a noop. This is what the - * only subclass (MonochromeLibraryPreloader) is doing. + * only subclass (WebViewLibraryPreloader) is doing. */ public abstract class NativeLibraryPreloader { - public abstract int loadLibrary(ApplicationInfo appInfo); + public abstract int loadLibrary(String packageName); }
diff --git a/base/android/java/src/org/chromium/base/process_launcher/ChildProcessConnection.java b/base/android/java/src/org/chromium/base/process_launcher/ChildProcessConnection.java index c5dee30..2ced884 100644 --- a/base/android/java/src/org/chromium/base/process_launcher/ChildProcessConnection.java +++ b/base/android/java/src/org/chromium/base/process_launcher/ChildProcessConnection.java
@@ -16,6 +16,7 @@ import androidx.annotation.Nullable; import androidx.annotation.VisibleForTesting; +import org.chromium.base.BuildInfo; import org.chromium.base.ChildBindingState; import org.chromium.base.Log; import org.chromium.base.MemoryPressureLevel; @@ -260,6 +261,8 @@ mFallbackServiceName = fallbackServiceName; mServiceBundle = serviceBundle != null ? serviceBundle : new Bundle(); mServiceBundle.putBoolean(ChildProcessConstants.EXTRA_BIND_TO_CALLER, bindToCaller); + mServiceBundle.putString(ChildProcessConstants.EXTRA_BROWSER_PACKAGE_NAME, + BuildInfo.getInstance().packageName); mBindToCaller = bindToCaller; mInstanceName = instanceName; mBindAsExternalService = bindAsExternalService;
diff --git a/base/android/java/src/org/chromium/base/process_launcher/ChildProcessConstants.java b/base/android/java/src/org/chromium/base/process_launcher/ChildProcessConstants.java index ec232d7..6826246 100644 --- a/base/android/java/src/org/chromium/base/process_launcher/ChildProcessConstants.java +++ b/base/android/java/src/org/chromium/base/process_launcher/ChildProcessConstants.java
@@ -24,4 +24,8 @@ // Key for the file descriptors that should be mapped in the child process. public static final String EXTRA_FILES = "org.chromium.base.process_launcher.extra.extraFiles"; + + // Key for the browser package name. + public static final String EXTRA_BROWSER_PACKAGE_NAME = + "org.chromium.base.process_launcher.extra.browser_package_name"; }
diff --git a/base/android/java/src/org/chromium/base/process_launcher/ChildProcessService.java b/base/android/java/src/org/chromium/base/process_launcher/ChildProcessService.java index 656b7d93c..e7ba01b1 100644 --- a/base/android/java/src/org/chromium/base/process_launcher/ChildProcessService.java +++ b/base/android/java/src/org/chromium/base/process_launcher/ChildProcessService.java
@@ -342,9 +342,16 @@ intent.getBooleanExtra(ChildProcessConstants.EXTRA_BIND_TO_CALLER, false); mServiceBound = true; mDelegate.onServiceBound(intent); + + String packageName = + intent.getStringExtra(ChildProcessConstants.EXTRA_BROWSER_PACKAGE_NAME); + if (packageName == null) { + packageName = getApplicationContext().getApplicationInfo().packageName; + } // Don't block bind() with any extra work, post it to the application thread instead. + final String preloadPackageName = packageName; new Handler(Looper.getMainLooper()) - .post(() -> mDelegate.preloadNativeLibrary(getApplicationContext())); + .post(() -> mDelegate.preloadNativeLibrary(preloadPackageName)); return mBinder; }
diff --git a/base/android/java/src/org/chromium/base/process_launcher/ChildProcessServiceDelegate.java b/base/android/java/src/org/chromium/base/process_launcher/ChildProcessServiceDelegate.java index f642365..42ef156 100644 --- a/base/android/java/src/org/chromium/base/process_launcher/ChildProcessServiceDelegate.java +++ b/base/android/java/src/org/chromium/base/process_launcher/ChildProcessServiceDelegate.java
@@ -42,9 +42,10 @@ * Called when the delegate should preload the native library. * Preloading is automatically done during library loading, but can also be called explicitly * to speed up the loading. See {@link LibraryLoader.preloadNow}. - * @param hostContext The host context the library should be preloaded with (i.e. Chrome). + * @param packageName The package name the library should be preloaded with (i.e. + * org.chromium.chrome). */ - void preloadNativeLibrary(Context hostContext); + void preloadNativeLibrary(String packageName); /** * Should return a map that associatesfile descriptors' IDs to keys.
diff --git a/base/callback_list.h b/base/callback_list.h index 97edd71..f9aeb8e 100644 --- a/base/callback_list.h +++ b/base/callback_list.h
@@ -345,9 +345,10 @@ using CallbackList = RepeatingCallbackList<Signature>; // Syntactic sugar to parallel that used for Callbacks. +// ClosureList explicitly not provided since it is not used, and CallbackList +// is deprecated. {Once,Repeating}ClosureList should instead be used. using OnceClosureList = OnceCallbackList<void()>; using RepeatingClosureList = RepeatingCallbackList<void()>; -using ClosureList = CallbackList<void()>; } // namespace base
diff --git a/base/fuchsia/filtered_service_directory.cc b/base/fuchsia/filtered_service_directory.cc index ac059066..dbff6b1 100644 --- a/base/fuchsia/filtered_service_directory.cc +++ b/base/fuchsia/filtered_service_directory.cc
@@ -11,7 +11,6 @@ #include "base/fuchsia/fuchsia_logging.h" namespace base { -namespace fuchsia { FilteredServiceDirectory::FilteredServiceDirectory( sys::ServiceDirectory* directory) @@ -40,5 +39,4 @@ dir_request.TakeChannel()); } -} // namespace fuchsia } // namespace base
diff --git a/base/fuchsia/filtered_service_directory.h b/base/fuchsia/filtered_service_directory.h index 2c52de18..d2fa303c 100644 --- a/base/fuchsia/filtered_service_directory.h +++ b/base/fuchsia/filtered_service_directory.h
@@ -17,7 +17,6 @@ #include "base/strings/string_piece.h" namespace base { -namespace fuchsia { // ServiceDirectory that uses the supplied sys::ServiceDirectory to satisfy // requests for only a restricted set of services. @@ -47,7 +46,14 @@ DISALLOW_COPY_AND_ASSIGN(FilteredServiceDirectory); }; +// TODO(crbug.com/1073821): Remove this block when out-of-tree callers have been +// changed to use the non-fuchsia-sub-namespace version. +namespace fuchsia { + +using FilteredServiceDirectory = ::base::FilteredServiceDirectory; + } // namespace fuchsia + } // namespace base #endif // BASE_FUCHSIA_FILTERED_SERVICE_DIRECTORY_H_
diff --git a/base/fuchsia/filtered_service_directory_unittest.cc b/base/fuchsia/filtered_service_directory_unittest.cc index f8267816..bcbd3ca1 100644 --- a/base/fuchsia/filtered_service_directory_unittest.cc +++ b/base/fuchsia/filtered_service_directory_unittest.cc
@@ -11,7 +11,6 @@ #include "testing/gtest/include/gtest/gtest.h" namespace base { -namespace fuchsia { class FilteredServiceDirectoryTest : public ServiceDirectoryTestBase { public: @@ -85,5 +84,4 @@ VerifyTestInterface(&stub, ZX_OK); } -} // namespace fuchsia } // namespace base
diff --git a/base/fuchsia/test_component_context_for_process.cc b/base/fuchsia/test_component_context_for_process.cc index f4ae62d..108e0e3 100644 --- a/base/fuchsia/test_component_context_for_process.cc +++ b/base/fuchsia/test_component_context_for_process.cc
@@ -25,7 +25,7 @@ // Set up |incoming_services_| to use the ServiceDirectory from the current // default ComponentContext to fetch services from. - context_services_ = std::make_unique<fuchsia::FilteredServiceDirectory>( + context_services_ = std::make_unique<FilteredServiceDirectory>( base::ComponentContextForProcess()->svc().get()); // Push all services from /svc to the test context if requested.
diff --git a/base/fuchsia/test_component_context_for_process.h b/base/fuchsia/test_component_context_for_process.h index 74f7ace3..e0ea7a99 100644 --- a/base/fuchsia/test_component_context_for_process.h +++ b/base/fuchsia/test_component_context_for_process.h
@@ -19,9 +19,7 @@ namespace base { -namespace fuchsia { class FilteredServiceDirectory; -} // namespace fuchsia // Replaces the process-global sys::ComponentContext (as returned by the // base::ComponentContextForProcess() function) with an empty instance which the @@ -106,7 +104,7 @@ private: std::unique_ptr<sys::ComponentContext> old_context_; - std::unique_ptr<fuchsia::FilteredServiceDirectory> context_services_; + std::unique_ptr<FilteredServiceDirectory> context_services_; std::unique_ptr<sys::ServiceDirectory> published_services_; };
diff --git a/base/fuchsia/test_component_context_for_process_unittest.cc b/base/fuchsia/test_component_context_for_process_unittest.cc index 32653c9..abe8d71 100644 --- a/base/fuchsia/test_component_context_for_process_unittest.cc +++ b/base/fuchsia/test_component_context_for_process_unittest.cc
@@ -72,7 +72,7 @@ TEST_F(TestComponentContextForProcessTest, InjectTestInterface) { // Publish a fake TestInterface for the process' ComponentContext to expose. - base::fuchsia::ScopedServiceBinding<testfidl::TestInterface> service_binding( + base::ScopedServiceBinding<testfidl::TestInterface> service_binding( test_context_.additional_services(), this); // Verify that the TestInterface is accessible & usable. @@ -81,7 +81,7 @@ TEST_F(TestComponentContextForProcessTest, PublishTestInterface) { // Publish TestInterface to the process' outgoing-directory. - base::fuchsia::ScopedServiceBinding<testfidl::TestInterface> service_binding( + base::ScopedServiceBinding<testfidl::TestInterface> service_binding( ComponentContextForProcess()->outgoing().get(), this); // Attempt to use the TestInterface from the outgoing-directory.
diff --git a/base/test/android/java/src/org/chromium/base/MultiprocessTestClientServiceDelegate.java b/base/test/android/java/src/org/chromium/base/MultiprocessTestClientServiceDelegate.java index bfb8d62b..c441538 100644 --- a/base/test/android/java/src/org/chromium/base/MultiprocessTestClientServiceDelegate.java +++ b/base/test/android/java/src/org/chromium/base/MultiprocessTestClientServiceDelegate.java
@@ -51,7 +51,7 @@ } @Override - public void preloadNativeLibrary(Context hostContext) { + public void preloadNativeLibrary(String packageName) { LibraryLoader.getInstance().preloadNow(); }
diff --git a/base/test/android/javatests/src/org/chromium/base/test/util/ApplicationTestUtils.java b/base/test/android/javatests/src/org/chromium/base/test/util/ApplicationTestUtils.java index e5bd8b9d..58988462 100644 --- a/base/test/android/javatests/src/org/chromium/base/test/util/ApplicationTestUtils.java +++ b/base/test/android/javatests/src/org/chromium/base/test/util/ApplicationTestUtils.java
@@ -94,11 +94,30 @@ * * @param activityClass The class type to wait for. * @param state The Activity {@link Stage} to wait for an activity of the right class type to - * reach. - * @param trigger The Runnable that will trigger the state change to wait for. + * reach. + * @param uiThreadTrigger The Runnable that will trigger the state change to wait for. The + * Runnable will be run on the UI thread */ public static <T extends Activity> T waitForActivityWithClass( - Class<? extends Activity> activityClass, Stage stage, Runnable trigger) { + Class<? extends Activity> activityClass, Stage stage, Runnable uiThreadTrigger) { + return waitForActivityWithClass(activityClass, stage, uiThreadTrigger, null); + } + + /** + * Waits for an activity of the specified class to reach the specified Activity {@link Stage}, + * triggered by running the provided trigger. + * + * @param activityClass The class type to wait for. + * @param state The Activity {@link Stage} to wait for an activity of the right class type to + * reach. + * @param uiThreadTrigger The Runnable that will trigger the state change to wait for, which + * will be run on the UI thread. + * @param backgroundThreadTrigger The Runnable that will trigger the state change to wait for, + * which will be run on the UI thread. + */ + public static <T extends Activity> T waitForActivityWithClass( + Class<? extends Activity> activityClass, Stage stage, Runnable uiThreadTrigger, + Runnable backgroundThreadTrigger) { ThreadUtils.assertOnBackgroundThread(); final CallbackHelper activityCallback = new CallbackHelper(); final AtomicReference<T> activityRef = new AtomicReference<>(); @@ -113,7 +132,10 @@ sMonitor.addLifecycleCallback(stateListener); try { - ThreadUtils.runOnUiThreadBlocking(() -> trigger.run()); + if (uiThreadTrigger != null) { + ThreadUtils.runOnUiThreadBlocking(() -> uiThreadTrigger.run()); + } + if (backgroundThreadTrigger != null) backgroundThreadTrigger.run(); activityCallback.waitForCallback("No Activity reached target state.", 0); T createdActivity = activityRef.get(); Assert.assertNotNull("Activity reference is null.", createdActivity);
diff --git a/base/util/memory_pressure/system_memory_pressure_evaluator_fuchsia_unittest.cc b/base/util/memory_pressure/system_memory_pressure_evaluator_fuchsia_unittest.cc index 3a3b47d7..4f1de52 100644 --- a/base/util/memory_pressure/system_memory_pressure_evaluator_fuchsia_unittest.cc +++ b/base/util/memory_pressure/system_memory_pressure_evaluator_fuchsia_unittest.cc
@@ -94,7 +94,7 @@ } TEST_F(SystemMemoryPressureEvaluatorFuchsiaTest, Basic) { - base::fuchsia::ScopedServiceBinding<::fuchsia::memorypressure::Provider> + base::ScopedServiceBinding<::fuchsia::memorypressure::Provider> publish_provider(test_context_.additional_services(), this); auto voter = std::make_unique<MockMemoryPressureVoter>();
diff --git a/build/fuchsia/linux.sdk.sha1 b/build/fuchsia/linux.sdk.sha1 index 9ce377c..71b7599 100644 --- a/build/fuchsia/linux.sdk.sha1 +++ b/build/fuchsia/linux.sdk.sha1
@@ -1 +1 @@ -0.20210129.0.1 +0.20210129.2.1
diff --git a/build/fuchsia/mac.sdk.sha1 b/build/fuchsia/mac.sdk.sha1 index 8d2959e..71b7599 100644 --- a/build/fuchsia/mac.sdk.sha1 +++ b/build/fuchsia/mac.sdk.sha1
@@ -1 +1 @@ -0.20210128.4.1 +0.20210129.2.1
diff --git a/chrome/android/BUILD.gn b/chrome/android/BUILD.gn index 5126b3e..713b3ea 100644 --- a/chrome/android/BUILD.gn +++ b/chrome/android/BUILD.gn
@@ -1268,6 +1268,7 @@ "//third_party/android_deps:espresso_java", "//third_party/android_deps:material_design_java", "//third_party/android_deps:protobuf_lite_runtime_java", + "//third_party/android_sdk:android_support_chromium_java", "//third_party/android_sdk:android_test_base_java", "//third_party/android_sdk:android_test_mock_java", "//third_party/android_sdk:android_test_runner_java",
diff --git a/chrome/android/expectations/monochrome_public_bundle.AndroidManifest.expected b/chrome/android/expectations/monochrome_public_bundle.AndroidManifest.expected index 5d7057e2..6aa1d7d8 100644 --- a/chrome/android/expectations/monochrome_public_bundle.AndroidManifest.expected +++ b/chrome/android/expectations/monochrome_public_bundle.AndroidManifest.expected
@@ -597,6 +597,7 @@ <activity # DIFF-ANCHOR: a1fac31f android:exported="true" android:label="@string/cablev2_activity_title" + android:launchMode="singleTop" android:name="org.chromium.chrome.browser.webauth.authenticator.CableAuthenticatorActivity" android:permission="com.google.android.gms.auth.cryptauth.permission.CABLEV2_SERVER_LINK" android:theme="@style/Theme.Chromium.Activity.Fullscreen">
diff --git a/chrome/android/expectations/trichrome_chrome_bundle.AndroidManifest.expected b/chrome/android/expectations/trichrome_chrome_bundle.AndroidManifest.expected index 0e102676..15c43c8 100644 --- a/chrome/android/expectations/trichrome_chrome_bundle.AndroidManifest.expected +++ b/chrome/android/expectations/trichrome_chrome_bundle.AndroidManifest.expected
@@ -570,6 +570,7 @@ <activity # DIFF-ANCHOR: a1fac31f android:exported="true" android:label="@string/cablev2_activity_title" + android:launchMode="singleTop" android:name="org.chromium.chrome.browser.webauth.authenticator.CableAuthenticatorActivity" android:permission="com.google.android.gms.auth.cryptauth.permission.CABLEV2_SERVER_LINK" android:theme="@style/Theme.Chromium.Activity.Fullscreen">
diff --git a/chrome/android/features/cablev2_authenticator/java/src/org/chromium/chrome/browser/webauth/authenticator/CableAuthenticator.java b/chrome/android/features/cablev2_authenticator/java/src/org/chromium/chrome/browser/webauth/authenticator/CableAuthenticator.java index 7435924..5eaede6 100644 --- a/chrome/android/features/cablev2_authenticator/java/src/org/chromium/chrome/browser/webauth/authenticator/CableAuthenticator.java +++ b/chrome/android/features/cablev2_authenticator/java/src/org/chromium/chrome/browser/webauth/authenticator/CableAuthenticator.java
@@ -86,6 +86,10 @@ private final CableAuthenticatorUI mUi; private final SingleThreadTaskRunner mTaskRunner; + // mHandle is the opaque ID returned by the native code to ensure that + // |stop| doesn't apply to a transaction that this instance didn't create. + private long mHandle; + public enum Result { REGISTER_OK, REGISTER_ERROR, @@ -109,17 +113,17 @@ if (accessory != null) { // USB mode can start immediately. - CableAuthenticatorJni.get().startUSB( + mHandle = CableAuthenticatorJni.get().startUSB( this, new USBHandler(context, mTaskRunner, accessory)); } if (isFcmNotification) { // The user tapped a notification that resulted from an FCM message. - CableAuthenticatorJni.get().onInteractionReady(this); + mHandle = CableAuthenticatorJni.get().onInteractionReady(this); } if (serverLink != null) { - CableAuthenticatorJni.get().startServerLink(this, serverLink); + mHandle = CableAuthenticatorJni.get().startServerLink(this, serverLink); } // Otherwise wait for a QR scan. @@ -447,8 +451,8 @@ */ void onQRCode(String value, boolean link) { assert mTaskRunner.belongsToCurrentThread(); - CableAuthenticatorJni.get().startQR(this, getName(), value, link); - // TODO: show the user an error if that returned false. + mHandle = CableAuthenticatorJni.get().startQR(this, getName(), value, link); + // TODO: show the user an error if that returned zero. // that indicates that the QR code was invalid. } @@ -464,7 +468,7 @@ void close() { assert mTaskRunner.belongsToCurrentThread(); - CableAuthenticatorJni.get().stop(); + CableAuthenticatorJni.get().stop(mHandle); } static String getName() { @@ -563,24 +567,27 @@ byte[] stateBytes); /** - * Called to instruct the C++ code to start a new transaction using |usbDevice|. + * Called to instruct the C++ code to start a new transaction using |usbDevice|. Returns an + * opaque value that can be passed to |stop| to cancel this transaction. */ - void startUSB(CableAuthenticator cableAuthenticator, USBHandler usbDevice); + long startUSB(CableAuthenticator cableAuthenticator, USBHandler usbDevice); /** * Called to instruct the C++ code to start a new transaction based on the contents of a QR * code. The given name will be transmitted to the peer in order to identify this device, it * should be human-meaningful. The qrUrl must be a caBLE URL, i.e. starting with - * "fido://c1/" + * "fido://c1/". Returns an opaque value that can be passed to |stop| to cancel this + * transaction. */ - boolean startQR(CableAuthenticator cableAuthenticator, String authenticatorName, - String qrUrl, boolean link); + long startQR(CableAuthenticator cableAuthenticator, String authenticatorName, String qrUrl, + boolean link); /** * Called to instruct the C++ code to start a new transaction based on the given link - * information which has been provided by the server. + * information which has been provided by the server. Returns an opaque value that can be + * passed to |stop| to cancel this transaction. */ - boolean startServerLink(CableAuthenticator cableAuthenticator, byte[] serverLinkData); + long startServerLink(CableAuthenticator cableAuthenticator, byte[] serverLinkData); /** * unlink causes the root secret to be rotated and the FCM token to be rotated. This @@ -593,13 +600,15 @@ /** * Called after the notification created by {@link showNotification} has been pressed and * the {@link CableAuthenticatorUI} Fragment is now in the foreground for showing UI. + * Returns an opaque value that can be passed to |stop| to cancel this transaction. */ - void onInteractionReady(CableAuthenticator cableAuthenticator); + long onInteractionReady(CableAuthenticator cableAuthenticator); /** - * Called to alert the C++ code to stop any ongoing transactions. + * Called to alert the C++ code to stop any ongoing transactions. Takes an opaque handle + * value that was returned by one of the |start*| functions or |onInteractionReady|. */ - void stop(); + void stop(long handle); /** * Called when a GCM message is received. The |event| argument is a pointer to a
diff --git a/chrome/android/features/cablev2_authenticator/native/cablev2_authenticator_android.cc b/chrome/android/features/cablev2_authenticator/native/cablev2_authenticator_android.cc index 62fe835..2616053 100644 --- a/chrome/android/features/cablev2_authenticator/native/cablev2_authenticator_android.cc +++ b/chrome/android/features/cablev2_authenticator/native/cablev2_authenticator_android.cc
@@ -166,6 +166,12 @@ // supported. struct GlobalData { JNIEnv* env = nullptr; + // instance_num is incremented for each new |Transaction| created and returned + // to Java to serve as a "handle". This prevents commands intended for a + // previous transaction getting applied to a replacement. The zero value is + // reserved so that functions can still return that to indicate an error. + jlong instance_num = 1; + std::array<uint8_t, device::cablev2::kRootSecretSize> root_secret; network::mojom::NetworkContext* network_context = nullptr; @@ -604,7 +610,7 @@ return ToJavaByteArray(env, serialized_state); } -static void JNI_CableAuthenticator_StartUSB( +static jlong JNI_CableAuthenticator_StartUSB( JNIEnv* env, const JavaParamRef<jobject>& cable_authenticator, const JavaParamRef<jobject>& usb_device) { @@ -622,9 +628,11 @@ std::make_unique<AndroidPlatform>(env, cable_authenticator), std::unique_ptr<device::cablev2::authenticator::Transport>( transport.release())); + + return ++global_data.instance_num; } -static jboolean JNI_CableAuthenticator_StartQR( +static jlong JNI_CableAuthenticator_StartQR( JNIEnv* env, const JavaParamRef<jobject>& cable_authenticator, const JavaParamRef<jstring>& authenticator_name, @@ -639,7 +647,7 @@ if (!decoded_qr) { FIDO_LOG(ERROR) << "Failed to decode QR: " << qr_string; RecordResult(CableV2MobileResult::kInvalidQR); - return false; + return 0; } if (!link) { @@ -654,10 +662,10 @@ decoded_qr->peer_identity, link ? global_data.registration->contact_id() : base::nullopt); - return true; + return ++global_data.instance_num; } -static jboolean JNI_CableAuthenticator_StartServerLink( +static jlong JNI_CableAuthenticator_StartServerLink( JNIEnv* env, const JavaParamRef<jobject>& cable_authenticator, const JavaParamRef<jbyteArray>& server_link_data_java) { @@ -671,7 +679,7 @@ if (!server_link_data) { FIDO_LOG(ERROR) << "Bad length server-link data length"; RecordResult(CableV2MobileResult::kInvalidServerLink); - return false; + return 0; } // Sending pairing information is disabled when doing a server-linked @@ -687,7 +695,7 @@ ->subspan<device::kP256X962Length, device::cablev2::kQRSecretSize>(), server_link_data->subspan<0, device::kP256X962Length>(), base::nullopt); - return true; + return ++global_data.instance_num; } static ScopedJavaLocalRef<jbyteArray> JNI_CableAuthenticator_Unlink( @@ -705,16 +713,21 @@ return ToJavaByteArray(env, serialized_state); } -static void JNI_CableAuthenticator_OnInteractionReady( +static jlong JNI_CableAuthenticator_OnInteractionReady( JNIEnv* env, const JavaParamRef<jobject>& cable_authenticator) { GlobalData& global_data = GetGlobalData(); std::move(global_data.interaction_ready_callback) .Run(ScopedJavaGlobalRef<jobject>(cable_authenticator)); + + return ++global_data.instance_num; } -static void JNI_CableAuthenticator_Stop(JNIEnv* env) { - ResetGlobalData(); +static void JNI_CableAuthenticator_Stop(JNIEnv* env, jlong instance_num) { + GlobalData& global_data = GetGlobalData(); + if (global_data.instance_num == instance_num) { + ResetGlobalData(); + } } static void JNI_CableAuthenticator_OnCloudMessage(
diff --git a/chrome/android/features/start_surface/internal/javatests/src/org/chromium/chrome/features/start_surface/InstantStartTest.java b/chrome/android/features/start_surface/internal/javatests/src/org/chromium/chrome/features/start_surface/InstantStartTest.java index 165294b..123e1bd 100644 --- a/chrome/android/features/start_surface/internal/javatests/src/org/chromium/chrome/features/start_surface/InstantStartTest.java +++ b/chrome/android/features/start_surface/internal/javatests/src/org/chromium/chrome/features/start_surface/InstantStartTest.java
@@ -8,6 +8,8 @@ import static androidx.test.espresso.Espresso.onView; import static androidx.test.espresso.action.ViewActions.click; +import static androidx.test.espresso.action.ViewActions.pressKey; +import static androidx.test.espresso.action.ViewActions.replaceText; import static androidx.test.espresso.assertion.ViewAssertions.doesNotExist; import static androidx.test.espresso.assertion.ViewAssertions.matches; import static androidx.test.espresso.matcher.ViewMatchers.isDisplayed; @@ -17,6 +19,7 @@ import static com.google.common.truth.Truth.assertThat; import static org.hamcrest.CoreMatchers.allOf; +import static org.hamcrest.CoreMatchers.equalTo; import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.CoreMatchers.not; import static org.hamcrest.Matchers.greaterThan; @@ -37,6 +40,7 @@ import android.support.test.filters.MediumTest; import android.text.TextUtils; import android.util.Base64; +import android.view.KeyEvent; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; @@ -48,6 +52,7 @@ import org.hamcrest.Description; import org.hamcrest.Matcher; +import org.hamcrest.MatcherAssert; import org.hamcrest.core.AllOf; import org.junit.Assert; import org.junit.Rule; @@ -118,6 +123,7 @@ import org.chromium.chrome.test.R; import org.chromium.chrome.test.util.ChromeRenderTestRule; import org.chromium.chrome.test.util.OmniboxTestUtils; +import org.chromium.chrome.test.util.OverviewModeBehaviorWatcher; import org.chromium.chrome.test.util.ViewUtils; import org.chromium.chrome.test.util.browser.Features; import org.chromium.chrome.test.util.browser.Features.DisableFeatures; @@ -1190,6 +1196,68 @@ mRenderTestRule.render(surface, "singlePane_MV"); } + @Test + @MediumTest + @Feature({"RenderTest"}) + @Restriction({UiRestriction.RESTRICTION_TYPE_PHONE}) + // clang-format off + @EnableFeatures({ChromeFeatureList.TAB_SWITCHER_ON_RETURN + "<Study,", + ChromeFeatureList.START_SURFACE_ANDROID + "<Study"}) + @CommandLineFlags.Add({ChromeSwitches.DISABLE_NATIVE_INITIALIZATION, + "force-fieldtrials=Study/Group", + IMMEDIATE_RETURN_PARAMS + + "/start_surface_variation/single" + + "/exclude_mv_tiles/true" + + "/thumbnail_aspect_ratio/1"}) + public void renderSingleAsHomepage_Landscape_TabSize() throws IOException{ + // clang-format on + startMainActivityFromLauncher(); + CriteriaHelper.pollUiThread( + () -> mActivityTestRule.getActivity().getLayoutManager().overviewVisible()); + + // Initializes native. + startAndWaitNativeInitialization(); + onViewWaiting( + allOf(withId(org.chromium.chrome.start_surface.R.id.feed_stream_recycler_view), + isDisplayed())); + + // Rotate to landscape mode. + mActivityTestRule.getActivity().setRequestedOrientation( + ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE); + CriteriaHelper.pollUiThread(() -> { + Criteria.checkThat( + mActivityTestRule.getActivity().getResources().getConfiguration().orientation, + is(ORIENTATION_LANDSCAPE)); + }); + + // Open a tab from search box. + MatcherAssert.assertThat( + mActivityTestRule.getActivity().getTabModelSelector().getCurrentModel().getCount(), + equalTo(0)); + OverviewModeBehaviorWatcher hideWatcher = + TabUiTestHelper.createOverviewHideWatcher(mActivityTestRule.getActivity()); + onView(withId(org.chromium.chrome.start_surface.R.id.search_box_text)) + .perform(replaceText("about:blank")); + onView(withId(org.chromium.chrome.start_surface.R.id.url_bar)) + .perform(pressKey(KeyEvent.KEYCODE_ENTER)); + hideWatcher.waitForBehavior(); + MatcherAssert.assertThat( + mActivityTestRule.getActivity().getTabModelSelector().getCurrentModel().getCount(), + equalTo(1)); + onView(withId(org.chromium.chrome.tab_ui.R.id.home_button)).perform(click()); + + // Wait for thumbnail to show. + CriteriaHelper.pollUiThread( + mActivityTestRule.getActivity().getLayoutManager()::overviewVisible); + RecyclerView recyclerView = + mActivityTestRule.getActivity().findViewById(R.id.tab_list_view); + CriteriaHelper.pollUiThread(() -> allCardsHaveThumbnail(recyclerView)); + + View surface = + mActivityTestRule.getActivity().findViewById(R.id.primary_tasks_surface_view); + mRenderTestRule.render(surface, "singlePane_landscape_tabSize"); + } + /** * Toggles the header and checks whether the header has the right status. *
diff --git a/chrome/android/java/AndroidManifest.xml b/chrome/android/java/AndroidManifest.xml index 2f79a93c..9d44cc4f 100644 --- a/chrome/android/java/AndroidManifest.xml +++ b/chrome/android/java/AndroidManifest.xml
@@ -849,7 +849,8 @@ android:theme="@style/Theme.Chromium.Activity.Fullscreen" android:label="@string/cablev2_activity_title" android:permission="com.google.android.gms.auth.cryptauth.permission.CABLEV2_SERVER_LINK" - android:exported="true"> + android:exported="true" + android:launchMode="singleTop"> <!-- This activity can be started by GMSCore, and is thus exported with a permission set, or can be started by the Android system in the case that a USB device is attached. -->
diff --git a/chrome/android/java/DEPS b/chrome/android/java/DEPS index e41acfa..d922a70 100644 --- a/chrome/android/java/DEPS +++ b/chrome/android/java/DEPS
@@ -66,10 +66,8 @@ # Special-case where monochrome composes chrome+webview "MonochromeApplication\.java": [ "+android_webview/nonembedded/java/src/org/chromium/android_webview/nonembedded/WebViewApkApplication.java", - "+android_webview/glue/java/src/com/android/webview/chromium/MonochromeLibraryPreloader.java", ], "SplitMonochromeApplication\.java": [ "+android_webview/nonembedded/java/src/org/chromium/android_webview/nonembedded/WebViewApkApplication.java", - "+android_webview/glue/java/src/com/android/webview/chromium/MonochromeLibraryPreloader.java", ], }
diff --git a/chrome/android/java/res/values/strings.xml b/chrome/android/java/res/values/strings.xml index 6be4feb..0876356 100644 --- a/chrome/android/java/res/values/strings.xml +++ b/chrome/android/java/res/values/strings.xml
@@ -8,7 +8,7 @@ <!-- DO NOT ADD STRINGS HERE. Android chrome strings now live in - chrome/android/java/strings/android_chrome_strings.grd + chrome/browser/ui/android/strings/android_chrome_strings.grd See http://www.chromium.org/developers/design-documents/ui-localization -->
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/base/SplitMonochromeApplication.java b/chrome/android/java/src/org/chromium/chrome/browser/base/SplitMonochromeApplication.java index 2b69423..e2d2960 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/base/SplitMonochromeApplication.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/base/SplitMonochromeApplication.java
@@ -6,10 +6,7 @@ import android.content.Context; -import com.android.webview.chromium.MonochromeLibraryPreloader; - import org.chromium.android_webview.nonembedded.WebViewApkApplication; -import org.chromium.base.library_loader.LibraryLoader; import org.chromium.base.library_loader.LibraryProcessType; import org.chromium.chrome.browser.version.ChromeVersionInfo; import org.chromium.content_public.browser.ChildProcessCreationParams; @@ -49,9 +46,6 @@ public static void initializeMonochromeProcessCommon(String packageName) { WebViewApkApplication.maybeInitProcessGlobals(); - if (!LibraryLoader.getInstance().isLoadedByZygote()) { - LibraryLoader.getInstance().setNativeLibraryPreloader(new MonochromeLibraryPreloader()); - } // ChildProcessCreationParams is only needed for browser process, though it is // created and set in all processes. We must set isExternalService to true for
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/metrics/LaunchCauseMetrics.java b/chrome/android/java/src/org/chromium/chrome/browser/metrics/LaunchCauseMetrics.java index 824f417..9e5328b 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/metrics/LaunchCauseMetrics.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/metrics/LaunchCauseMetrics.java
@@ -57,7 +57,8 @@ @IntDef({LaunchCause.OTHER, LaunchCause.CUSTOM_TAB, LaunchCause.TWA, LaunchCause.RECENTS, LaunchCause.RECENTS_OR_BACK, LaunchCause.FOREGROUND_WHEN_LOCKED, LaunchCause.MAIN_LAUNCHER_ICON, LaunchCause.MAIN_LAUNCHER_ICON_SHORTCUT, - LaunchCause.HOME_SCREEN_WIDGET, LaunchCause.OPEN_IN_BROWSER_FROM_MENU}) + LaunchCause.HOME_SCREEN_WIDGET, LaunchCause.OPEN_IN_BROWSER_FROM_MENU, + LaunchCause.EXTERNAL_SEARCH_ACTION_INTENT}) @Retention(RetentionPolicy.SOURCE) public @interface LaunchCause { int OTHER = 0; @@ -70,8 +71,9 @@ int MAIN_LAUNCHER_ICON_SHORTCUT = 7; int HOME_SCREEN_WIDGET = 8; int OPEN_IN_BROWSER_FROM_MENU = 9; + int EXTERNAL_SEARCH_ACTION_INTENT = 10; - int NUM_ENTRIES = 10; + int NUM_ENTRIES = 11; } /** @@ -258,6 +260,9 @@ case LaunchCause.OPEN_IN_BROWSER_FROM_MENU: launchCause = "OPEN_IN_BROWSER_FROM_MENU"; break; + case LaunchCause.EXTERNAL_SEARCH_ACTION_INTENT: + launchCause = "EXTERNAL_SEARCH_ACTION_INTENT"; + break; } Log.d(TAG, "Launch Cause: " + launchCause); }
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/metrics/TabbedActivityLaunchCauseMetrics.java b/chrome/android/java/src/org/chromium/chrome/browser/metrics/TabbedActivityLaunchCauseMetrics.java index 596bd04..f7f6203 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/metrics/TabbedActivityLaunchCauseMetrics.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/metrics/TabbedActivityLaunchCauseMetrics.java
@@ -6,10 +6,12 @@ import android.app.Activity; import android.content.Intent; +import android.speech.RecognizerResultsIntent; import org.chromium.base.IntentUtils; import org.chromium.chrome.browser.IntentHandler; import org.chromium.chrome.browser.ShortcutHelper; +import org.chromium.chrome.browser.searchwidget.SearchActivity; import org.chromium.chrome.browser.searchwidget.SearchWidgetProvider; import org.chromium.components.webapps.ShortcutSource; @@ -46,8 +48,19 @@ } if (IntentUtils.safeGetBooleanExtra( - launchIntent, SearchWidgetProvider.EXTRA_FROM_SEARCH_WIDGET, false)) { - return LaunchCause.HOME_SCREEN_WIDGET; + launchIntent, SearchActivity.EXTRA_FROM_SEARCH_ACTIVITY, false)) { + if (IntentUtils.safeGetBooleanExtra( + launchIntent, SearchWidgetProvider.EXTRA_FROM_SEARCH_WIDGET, false)) { + return LaunchCause.HOME_SCREEN_WIDGET; + } + // Intent came through the Search Activity but wasn't from the Search Widget, so + // probably came from LaunchIntentDispatcher#processWebSearchIntent, and no other + // installed apps could handle web search. + return LaunchCause.EXTERNAL_SEARCH_ACTION_INTENT; + } + + if (RecognizerResultsIntent.ACTION_VOICE_SEARCH_RESULTS.equals(launchIntent.getAction())) { + return LaunchCause.EXTERNAL_SEARCH_ACTION_INTENT; } // This is unlikely to be hit here (much more likely to see Open In Browser intents in
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/omnibox/SearchEngineLogoUtils.java b/chrome/android/java/src/org/chromium/chrome/browser/omnibox/SearchEngineLogoUtils.java index 039fb97..0a95467 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/omnibox/SearchEngineLogoUtils.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/omnibox/SearchEngineLogoUtils.java
@@ -126,7 +126,8 @@ public boolean shouldShowRoundedSearchEngineLogo(boolean isOffTheRecord) { return shouldShowSearchEngineLogo(isOffTheRecord) && ChromeFeatureList.isInitialized() && ChromeFeatureList.getFieldTrialParamByFeatureAsBoolean( - ChromeFeatureList.OMNIBOX_SEARCH_ENGINE_LOGO, ROUNDED_EDGES_VARIANT, false); + ChromeFeatureList.OMNIBOX_SEARCH_ENGINE_LOGO, ROUNDED_EDGES_VARIANT, + /* default= */ true); } /** Ignores the incognito state for instances where a caller would otherwise pass "false". */ @@ -143,7 +144,7 @@ return shouldShowSearchEngineLogo(isOffTheRecord) && ChromeFeatureList.getFieldTrialParamByFeatureAsBoolean( ChromeFeatureList.OMNIBOX_SEARCH_ENGINE_LOGO, LOUPE_EVERYWHERE_VARIANT, - false); + /* default= */ false); } /** @return Whether the status icon should be hidden when the LocationBar is unfocused. */
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/omnibox/suggestions/OmniboxSuggestionsDropdownAdapter.java b/chrome/android/java/src/org/chromium/chrome/browser/omnibox/suggestions/OmniboxSuggestionsDropdownAdapter.java index e4bcdf3..048d2d0 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/omnibox/suggestions/OmniboxSuggestionsDropdownAdapter.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/omnibox/suggestions/OmniboxSuggestionsDropdownAdapter.java
@@ -73,7 +73,9 @@ */ boolean setSelectedViewIndex(int index) { if (mLayoutManager == null) return false; - if (index < 0 || index >= getItemCount()) return false; + if (index != RecyclerView.NO_POSITION && (index < 0 || index >= getItemCount())) { + return false; + } View previousSelectedView = mLayoutManager.findViewByPosition(mSelectedItem); if (previousSelectedView != null) {
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/searchwidget/SearchActivity.java b/chrome/android/java/src/org/chromium/chrome/browser/searchwidget/SearchActivity.java index 62ee847..2430c0a 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/searchwidget/SearchActivity.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/searchwidget/SearchActivity.java
@@ -67,6 +67,9 @@ // Shared with other org.chromium.chrome.browser.searchwidget classes. protected static final String TAG = "searchwidget"; + public static final String EXTRA_FROM_SEARCH_ACTIVITY = + "org.chromium.chrome.browser.searchwidget.FROM_SEARCH_ACTIVITY"; + /** Notified about events happening inside a SearchActivity. */ public static class SearchActivityDelegate { /** @@ -418,6 +421,7 @@ if (isFromSearchWidget()) { intent.putExtra(SearchWidgetProvider.EXTRA_FROM_SEARCH_WIDGET, true); } + intent.putExtra(EXTRA_FROM_SEARCH_ACTIVITY, true); IntentHandler.addTrustedIntentExtras(intent); return intent;
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/webauth/authenticator/CableAuthenticatorActivity.java b/chrome/android/java/src/org/chromium/chrome/browser/webauth/authenticator/CableAuthenticatorActivity.java index 4a5d8dc..ca1ec7a 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/webauth/authenticator/CableAuthenticatorActivity.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/webauth/authenticator/CableAuthenticatorActivity.java
@@ -4,7 +4,6 @@ package org.chromium.chrome.browser.webauth.authenticator; -import android.annotation.SuppressLint; import android.app.ActivityManager; import android.content.Intent; import android.content.res.Resources; @@ -46,7 +45,6 @@ "org.chromium.chrome.browser.webauth.authenticator.ServerLink"; @Override - @SuppressLint("SetTextI18n") // TODO(BUG=1002262): translate protected void onCreate(Bundle savedInstanceState) { setTitle("Phone as a Security Key"); @@ -62,7 +60,13 @@ return; } - final Intent intent = getIntent(); + onNewIntent(getIntent()); + } + + @Override + protected void onNewIntent(Intent intent) { + super.onNewIntent(intent); + Bundle arguments; if (intent.getAction() != null && intent.getAction().equals(USB_ACCESSORY_ATTACHED)) { // This can be triggered by an implicit intent if a desktop
diff --git a/chrome/android/javatests/src/org/chromium/chrome/browser/metrics/TabbedActivityLaunchCauseMetricsTest.java b/chrome/android/javatests/src/org/chromium/chrome/browser/metrics/TabbedActivityLaunchCauseMetricsTest.java index d1068e0a..8d8193a 100644 --- a/chrome/android/javatests/src/org/chromium/chrome/browser/metrics/TabbedActivityLaunchCauseMetricsTest.java +++ b/chrome/android/javatests/src/org/chromium/chrome/browser/metrics/TabbedActivityLaunchCauseMetricsTest.java
@@ -4,10 +4,21 @@ package org.chromium.chrome.browser.metrics; +import static androidx.test.espresso.Espresso.onView; +import static androidx.test.espresso.action.ViewActions.click; +import static androidx.test.espresso.action.ViewActions.pressKey; +import static androidx.test.espresso.matcher.ViewMatchers.withId; + import android.app.Activity; +import android.app.SearchManager; +import android.content.Context; +import android.content.ContextWrapper; import android.content.Intent; +import android.content.pm.PackageManager; +import android.content.pm.ResolveInfo; import android.net.Uri; import android.support.test.runner.lifecycle.Stage; +import android.view.KeyEvent; import androidx.test.filters.MediumTest; @@ -17,6 +28,7 @@ import org.junit.Test; import org.junit.runner.RunWith; +import org.chromium.android.support.PackageManagerWrapper; import org.chromium.base.ActivityState; import org.chromium.base.ApplicationStatus; import org.chromium.base.ContextUtils; @@ -28,14 +40,20 @@ import org.chromium.base.test.util.Criteria; import org.chromium.base.test.util.CriteriaHelper; import org.chromium.base.test.util.ScalableTimeout; +import org.chromium.chrome.R; import org.chromium.chrome.browser.ChromeTabbedActivity; import org.chromium.chrome.browser.LauncherShortcutActivity; import org.chromium.chrome.browser.bookmarkswidget.BookmarkWidgetProxy; +import org.chromium.chrome.browser.document.ChromeLauncherActivity; import org.chromium.chrome.browser.flags.ChromeSwitches; +import org.chromium.chrome.browser.searchwidget.SearchActivity; import org.chromium.chrome.test.ChromeJUnit4ClassRunner; import org.chromium.chrome.test.ChromeTabbedActivityTestRule; import org.chromium.chrome.test.util.ChromeApplicationTestUtils; +import java.util.Collections; +import java.util.List; + /** * Integration tests for TabbedActivityLaunchCauseMetrics. */ @@ -140,4 +158,58 @@ Matchers.is(count)); }, ScalableTimeout.scaleTimeout(5000L), CriteriaHelper.DEFAULT_POLLING_INTERVAL); } + + private static class TestContext extends ContextWrapper { + public TestContext(Context baseContext) { + super(baseContext); + } + + @Override + public PackageManager getPackageManager() { + return new PackageManagerWrapper(super.getPackageManager()) { + @Override + public List<ResolveInfo> queryIntentActivities(Intent intent, int flags) { + if (intent.getAction().equals(Intent.ACTION_WEB_SEARCH)) { + return Collections.emptyList(); + } + + return TestContext.super.getPackageManager().queryIntentActivities( + intent, flags); + } + }; + } + } + + @Test + @MediumTest + public void testExternalSearchIntentNoResolvers() throws Throwable { + final int count = 1 + + histogramCountForValue( + LaunchCauseMetrics.LaunchCause.EXTERNAL_SEARCH_ACTION_INTENT); + final Context contextToRestore = ContextUtils.getApplicationContext(); + ContextUtils.initApplicationContextForTests(new TestContext(contextToRestore)); + + Intent intent = new Intent(Intent.ACTION_SEARCH); + intent.setClass(ContextUtils.getApplicationContext(), ChromeLauncherActivity.class); + intent.putExtra(SearchManager.QUERY, "about:blank"); + intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); + SearchActivity searchActivity = ApplicationTestUtils.waitForActivityWithClass( + SearchActivity.class, Stage.RESUMED, () -> contextToRestore.startActivity(intent)); + + onView(withId(R.id.url_bar)).perform(click()); + ChromeTabbedActivity cta = ApplicationTestUtils.waitForActivityWithClass( + ChromeTabbedActivity.class, Stage.CREATED, null, + () -> onView(withId(R.id.url_bar)).perform(pressKey(KeyEvent.KEYCODE_ENTER))); + + CriteriaHelper.pollInstrumentationThread(() -> { + Criteria.checkThat( + histogramCountForValue( + LaunchCauseMetrics.LaunchCause.EXTERNAL_SEARCH_ACTION_INTENT), + Matchers.is(count)); + }, ScalableTimeout.scaleTimeout(5000L), CriteriaHelper.DEFAULT_POLLING_INTERVAL); + + ApplicationTestUtils.finishActivity(cta); + ApplicationTestUtils.finishActivity(searchActivity); + ContextUtils.initApplicationContextForTests(contextToRestore); + } }
diff --git a/chrome/android/javatests/src/org/chromium/chrome/browser/metrics/TabbedActivityLaunchCauseMetricsUnitTest.java b/chrome/android/javatests/src/org/chromium/chrome/browser/metrics/TabbedActivityLaunchCauseMetricsUnitTest.java index 003f503..a8e7e4e 100644 --- a/chrome/android/javatests/src/org/chromium/chrome/browser/metrics/TabbedActivityLaunchCauseMetricsUnitTest.java +++ b/chrome/android/javatests/src/org/chromium/chrome/browser/metrics/TabbedActivityLaunchCauseMetricsUnitTest.java
@@ -7,6 +7,7 @@ import android.app.Activity; import android.content.Intent; import android.net.Uri; +import android.speech.RecognizerResultsIntent; import androidx.test.filters.SmallTest; @@ -108,4 +109,31 @@ RecordHistogram.getHistogramTotalCountForTesting( LaunchCauseMetrics.LAUNCH_CAUSE_HISTOGRAM)); } + + @Test + @SmallTest + public void testVoiceSearchResultsMetrics() throws Throwable { + int count = histogramCountForValue( + LaunchCauseMetrics.LaunchCause.EXTERNAL_SEARCH_ACTION_INTENT); + Intent intent = new Intent(RecognizerResultsIntent.ACTION_VOICE_SEARCH_RESULTS); + Mockito.when(mActivity.getIntent()).thenReturn(intent); + + TabbedActivityLaunchCauseMetrics metrics = new TabbedActivityLaunchCauseMetrics(mActivity); + + // Tests the case where Chrome is backgrounded either by the intent picker, or by + // cross-channel Open In Browser. + metrics.onReceivedIntent(); + metrics.recordLaunchCause(); + ++count; + Assert.assertEquals(count, + histogramCountForValue( + LaunchCauseMetrics.LaunchCause.EXTERNAL_SEARCH_ACTION_INTENT)); + + // Ensures we don't record this metric when Chrome has already recorded a launch. + metrics.onReceivedIntent(); + metrics.recordLaunchCause(); + Assert.assertEquals(count, + histogramCountForValue( + LaunchCauseMetrics.LaunchCause.EXTERNAL_SEARCH_ACTION_INTENT)); + } }
diff --git a/chrome/android/javatests/src/org/chromium/chrome/browser/omnibox/suggestions/mostvisited/MostVisitedTilesTest.java b/chrome/android/javatests/src/org/chromium/chrome/browser/omnibox/suggestions/mostvisited/MostVisitedTilesTest.java index 9627c7d..31ce50d 100644 --- a/chrome/android/javatests/src/org/chromium/chrome/browser/omnibox/suggestions/mostvisited/MostVisitedTilesTest.java +++ b/chrome/android/javatests/src/org/chromium/chrome/browser/omnibox/suggestions/mostvisited/MostVisitedTilesTest.java
@@ -23,7 +23,6 @@ import org.chromium.base.test.util.CommandLineFlags; import org.chromium.base.test.util.Criteria; import org.chromium.base.test.util.CriteriaHelper; -import org.chromium.base.test.util.DisabledTest; import org.chromium.chrome.R; import org.chromium.chrome.browser.ChromeTabbedActivity; import org.chromium.chrome.browser.flags.ChromeSwitches; @@ -207,7 +206,6 @@ @Test @MediumTest @EnableFeatures("OmniboxMostVisitedTiles") - @DisabledTest(message = "Test flaky: https://crbug.com/1152246") public void keyboardNavigation_highlightingNextTileUpdatesUrlBarText() throws InterruptedException { // Skip past the 'what-you-typed' suggestion. @@ -250,7 +248,6 @@ @Test @MediumTest @EnableFeatures("OmniboxMostVisitedTiles") - @DisabledTest(message = "Test flaky: https://crbug.com/1168660") public void keyboardNavigation_highlightAlwaysStartsWithFirstElement() throws InterruptedException { // Skip past the 'what-you-typed' suggestion.
diff --git a/chrome/android/junit/src/org/chromium/chrome/browser/omnibox/SearchEngineLogoUtilsUnitTest.java b/chrome/android/junit/src/org/chromium/chrome/browser/omnibox/SearchEngineLogoUtilsUnitTest.java index daec77e..3d81a8b 100644 --- a/chrome/android/junit/src/org/chromium/chrome/browser/omnibox/SearchEngineLogoUtilsUnitTest.java +++ b/chrome/android/junit/src/org/chromium/chrome/browser/omnibox/SearchEngineLogoUtilsUnitTest.java
@@ -5,7 +5,9 @@ package org.chromium.chrome.browser.omnibox; import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertTrue; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyInt; import static org.mockito.Mockito.doReturn; @@ -93,6 +95,7 @@ doReturn(false).when(mLocaleManager).needToCheckForSearchEnginePromo(); LocaleManager.setInstanceForTest(mLocaleManager); + doReturn(true).when(mBrowserStartupController).isFullBrowserStarted(); mSearchEngineLogoUtils = new SearchEngineLogoUtils(mBrowserStartupController); mSearchEngineLogoUtils.setFaviconHelperForTesting(mFaviconHelper); mSearchEngineLogoUtils.setRoundedIconGeneratorForTesting(mRoundedIconGenerator); @@ -105,6 +108,15 @@ } @Test + public void testDefaultEnabledBehavior() { + // Verify the default behavior of the feature being enabled matches expectations. + assertTrue(mSearchEngineLogoUtils.shouldShowRoundedSearchEngineLogo( + /* isOffTheRecord= */ false)); + assertFalse(mSearchEngineLogoUtils.shouldShowSearchLoupeEverywhere( + /* isOffTheRecord= */ false)); + } + + @Test public void recordEvent() { mSearchEngineLogoUtils.recordEvent( SearchEngineLogoUtils.Events.FETCH_NON_GOOGLE_LOGO_REQUEST);
diff --git a/chrome/app/settings_strings.grdp b/chrome/app/settings_strings.grdp index c04e4cd..a6633f0 100644 --- a/chrome/app/settings_strings.grdp +++ b/chrome/app/settings_strings.grdp
@@ -3175,12 +3175,6 @@ <message name="IDS_SETTINGS_RESET_CLEANUP_DETAILS_EXPLANATION" desc="Text that appears below the list of files, programs, and registry entries to be removed by Chrome as part of a cleanup process. 'privacy white paper' is a guide to Chrome's privacy policy and practices. In 'unwanted software protection,' the word 'unwanted' modifies 'software,' i.e. 'protection from unwanted software'."> Items not listed here will also be removed, if needed. Learn more about <a href="<ph name="URL">$1<ex>https://www.google.com/chrome/browser/privacy/whitepaper.html#unwantedsoftware</ex></ph>">unwanted software protection</a> in the Chrome privacy white paper. </message> - <message name="IDS_SETTINGS_RESET_CLEANUP_DETAILS_EXTENSIONS" desc="Introduces a bullet list containing the names of extensions to be removed by Chrome."> - Extensions to be removed: - </message> - <message name="IDS_SETTINGS_RESET_CLEANUP_DETAILS_EXTENSION_UNKNOWN" desc="Text for a list item among a list of extensions, where we could not determine the name of the extension being cleaned up."> - Unknown extension with ID <ph name="EXTENSION_ID">$1<ex>exampleextensionababababcdcdcdcd</ex></ph> - </message> <message name="IDS_SETTINGS_RESET_CLEANUP_DETAILS_FILES_AND_PROGRAMS" desc="Introduces a bullet list containing the names of files and programs to be quarantined by Chrome (i.e. removed from the original location, moved and archived in the Quarantine folder)."> Files and programs to be quarantined: </message>
diff --git a/chrome/browser/BUILD.gn b/chrome/browser/BUILD.gn index df7eb5f..0f0122a 100644 --- a/chrome/browser/BUILD.gn +++ b/chrome/browser/BUILD.gn
@@ -1200,32 +1200,12 @@ "policy/homepage_location_policy_handler.h", "policy/javascript_policy_handler.cc", "policy/javascript_policy_handler.h", - "policy/messaging_layer/encryption/encryption.cc", - "policy/messaging_layer/encryption/encryption.h", - "policy/messaging_layer/encryption/encryption_module.cc", - "policy/messaging_layer/encryption/encryption_module.h", - "policy/messaging_layer/encryption/verification.cc", - "policy/messaging_layer/encryption/verification.h", "policy/messaging_layer/public/report_client.cc", "policy/messaging_layer/public/report_client.h", "policy/messaging_layer/public/report_queue.cc", "policy/messaging_layer/public/report_queue.h", "policy/messaging_layer/public/report_queue_configuration.cc", "policy/messaging_layer/public/report_queue_configuration.h", - "policy/messaging_layer/storage/resources/disk_resource_impl.cc", - "policy/messaging_layer/storage/resources/disk_resource_impl.h", - "policy/messaging_layer/storage/resources/memory_resource_impl.cc", - "policy/messaging_layer/storage/resources/memory_resource_impl.h", - "policy/messaging_layer/storage/resources/resource_interface.cc", - "policy/messaging_layer/storage/resources/resource_interface.h", - "policy/messaging_layer/storage/storage.cc", - "policy/messaging_layer/storage/storage.h", - "policy/messaging_layer/storage/storage_configuration.cc", - "policy/messaging_layer/storage/storage_configuration.h", - "policy/messaging_layer/storage/storage_module.cc", - "policy/messaging_layer/storage/storage_module.h", - "policy/messaging_layer/storage/storage_queue.cc", - "policy/messaging_layer/storage/storage_queue.h", "policy/messaging_layer/upload/dm_server_upload_service.cc", "policy/messaging_layer/upload/dm_server_upload_service.h", "policy/messaging_layer/upload/record_handler_impl.cc", @@ -1234,20 +1214,10 @@ "policy/messaging_layer/upload/record_upload_request_builder.h", "policy/messaging_layer/upload/upload_client.cc", "policy/messaging_layer/upload/upload_client.h", - "policy/messaging_layer/util/backoff_settings.cc", - "policy/messaging_layer/util/backoff_settings.h", "policy/messaging_layer/util/get_cloud_policy_client.cc", "policy/messaging_layer/util/get_cloud_policy_client.h", "policy/messaging_layer/util/report_queue_manual_test_context.cc", "policy/messaging_layer/util/report_queue_manual_test_context.h", - "policy/messaging_layer/util/shared_queue.h", - "policy/messaging_layer/util/shared_vector.h", - "policy/messaging_layer/util/status.cc", - "policy/messaging_layer/util/status.h", - "policy/messaging_layer/util/status_macros.h", - "policy/messaging_layer/util/statusor.cc", - "policy/messaging_layer/util/statusor.h", - "policy/messaging_layer/util/task_runner_context.h", "policy/network_prediction_policy_handler.cc", "policy/network_prediction_policy_handler.h", "policy/profile_policy_connector.cc", @@ -1932,6 +1902,9 @@ "//components/payments/core", "//components/payments/core:error_strings", "//components/policy/proto", + "//components/reporting/util:shared_queue", + "//components/reporting/util:status_macros", + "//components/reporting/util:task_runner_context", "//components/safe_browsing:buildflags", "//components/services/storage/public/mojom", "//components/sync", @@ -1951,7 +1924,6 @@ ":ntp_background_proto", ":permissions_proto", ":resource_prefetch_predictor_proto", - ":status_proto", ":unexpire_flags", "//base:i18n", "//base/allocator:buildflags", @@ -2161,8 +2133,6 @@ "//components/policy/content/", "//components/policy/core/browser", "//components/policy/proto", - "//components/policy/proto:policy_record_constants", - "//components/policy/proto:reporting_record_proto", "//components/prefs", "//components/previews/content", "//components/previews/core", @@ -2176,6 +2146,14 @@ "//components/reading_list/core", "//components/reading_list/features:flags", "//components/renderer_context_menu", + "//components/reporting/encryption:encryption_module", + "//components/reporting/encryption:verification", + "//components/reporting/proto:record_constants", + "//components/reporting/proto:record_proto", + "//components/reporting/storage:storage_configuration", + "//components/reporting/storage:storage_module", + "//components/reporting/util:status", + "//components/reporting/util:status_proto", "//components/reputation/core", "//components/reputation/core:proto", "//components/resources", @@ -6737,8 +6715,14 @@ "//components/invalidation/impl:test_support", "//components/password_manager/core/browser:test_support", "//components/policy/core/browser:test_support", - "//components/policy/proto:reporting_record_proto", "//components/prefs:test_support", + "//components/reporting/proto:record_constants", + "//components/reporting/proto:record_proto", + "//components/reporting/storage:storage_module", + "//components/reporting/util:status", + "//components/reporting/util:status_macros", + "//components/reporting/util:status_proto", + "//components/reporting/util:task_runner_context", "//components/reputation/core", "//components/reputation/core:proto", "//components/safe_browsing/core:csd_proto", @@ -7024,11 +7008,6 @@ } } -proto_library("status_proto") { - sources = [ "policy/messaging_layer/util/status.proto" ] - generate_python = false -} - if (!is_android) { proto_library("cart_db_content_proto") { sources = [ "cart/cart_db_content.proto" ]
diff --git a/chrome/browser/DEPS b/chrome/browser/DEPS index 3ef86513..b84e12f20 100644 --- a/chrome/browser/DEPS +++ b/chrome/browser/DEPS
@@ -249,6 +249,7 @@ "+components/remote_cocoa/common", "+components/renderer_context_menu", "+components/reputation", + "+components/reporting", "+components/rlz", "+components/safe_browsing", "+components/safe_search_api",
diff --git a/chrome/browser/about_flags.cc b/chrome/browser/about_flags.cc index 236f29d..2d1d283 100644 --- a/chrome/browser/about_flags.cc +++ b/chrome/browser/about_flags.cc
@@ -6662,13 +6662,6 @@ flag_descriptions::kWindowNamingDescription, kOsAll, FEATURE_VALUE_TYPE(features::kWindowNaming)}, -#if defined(OS_MAC) - {"videotoolbox-vp9-decoding", - flag_descriptions::kVideoToolboxVp9DecodingName, - flag_descriptions::kVideoToolboxVp9DecodingDescription, kOsMac, - FEATURE_VALUE_TYPE(media::kVideoToolboxVp9Decoding)}, -#endif - #if defined(OS_ANDROID) {"messages-for-android-infrastructure", flag_descriptions::kMessagesForAndroidInfrastructureName,
diff --git a/chrome/browser/android/compositor/tab_content_manager.cc b/chrome/browser/android/compositor/tab_content_manager.cc index 64a36ce..de7b2c2 100644 --- a/chrome/browser/android/compositor/tab_content_manager.cc +++ b/chrome/browser/android/compositor/tab_content_manager.cc
@@ -386,20 +386,25 @@ const SkBitmap& bitmap) { ScopedJavaLocalRef<jobject> j_bitmap; if (!bitmap.isNull() && result) { - // In portrait mode, we want to show thumbnails in squares. - // Therefore, the thumbnail saved in portrait mode needs to be cropped to - // a square, or it would be vertically center-aligned, and the top would - // be hidden. - // It's fine to horizontally center-align thumbnail saved in landscape - // mode. + // We want to show thumbnails in a specific aspect ratio. Therefore, the + // thumbnail saved needs to be cropped to the target aspect ratio, otherwise + // it would be vertically center-aligned and the top would be hidden in + // portrait mode, or it would be shown in the wrong aspect ratio in + // landscape mode. int scale = need_downsampling ? 2 : 1; double aspect_ratio = base::GetFieldTrialParamByFeatureAsDouble( chrome::android::kTabGridLayoutAndroid, "thumbnail_aspect_ratio", 1.0); aspect_ratio = ThumbnailCache::clampAspectRatio(aspect_ratio, 0.5, 2.0); - SkIRect dest_subset = { - 0, 0, bitmap.width() / scale, - std::min(bitmap.height() / scale, - (int)(bitmap.width() / aspect_ratio / scale))}; + + int width = std::min(bitmap.width() / scale, + (int)(bitmap.height() * aspect_ratio / scale)); + int height = std::min(bitmap.height() / scale, + (int)(bitmap.width() / aspect_ratio / scale)); + // When cropping the thumbnails, we want to keep the top center portion. + int begin_x = (bitmap.width() / scale - width) / 2; + int end_x = begin_x + width; + SkIRect dest_subset = {begin_x, 0, end_x, height}; + j_bitmap = gfx::ConvertToJavaBitmap(skia::ImageOperations::Resize( bitmap, skia::ImageOperations::RESIZE_BETTER, bitmap.width() / scale, bitmap.height() / scale, dest_subset));
diff --git a/chrome/browser/ash/accessibility/spoken_feedback_browsertest.cc b/chrome/browser/ash/accessibility/spoken_feedback_browsertest.cc index 7a01fff7..b7d9ea87 100644 --- a/chrome/browser/ash/accessibility/spoken_feedback_browsertest.cc +++ b/chrome/browser/ash/accessibility/spoken_feedback_browsertest.cc
@@ -1142,7 +1142,8 @@ } // Tests basic behavior of the tutorial when signed in. -IN_PROC_BROWSER_TEST_P(SpokenFeedbackTest, Tutorial) { +// TODO(akihiroota): fix flakiness: http://crbug.com/1172390 +IN_PROC_BROWSER_TEST_P(SpokenFeedbackTest, DISABLED_Tutorial) { EnableChromeVox(); sm_.Call([this]() { ui_test_utils::NavigateToURL( @@ -1221,7 +1222,9 @@ sm_.Replay(); } -IN_PROC_BROWSER_TEST_F(OobeSpokenFeedbackTest, SpokenFeedbackTutorialInOobe) { +// TODO(akihiroota): fix flakiness: http://crbug.com/1172390 +IN_PROC_BROWSER_TEST_F(OobeSpokenFeedbackTest, + DISABLED_SpokenFeedbackTutorialInOobe) { ui_controls::EnableUIControls(); ASSERT_FALSE(AccessibilityManager::Get()->IsSpokenFeedbackEnabled()); AccessibilityManager::Get()->EnableSpokenFeedback(true);
diff --git a/chrome/browser/browsing_data/chrome_browsing_data_remover_delegate_unittest.cc b/chrome/browser/browsing_data/chrome_browsing_data_remover_delegate_unittest.cc index b0edc3f9..79cf01eb 100644 --- a/chrome/browser/browsing_data/chrome_browsing_data_remover_delegate_unittest.cc +++ b/chrome/browser/browsing_data/chrome_browsing_data_remover_delegate_unittest.cc
@@ -479,14 +479,14 @@ void SaveResultAndQuit(const favicon_base::FaviconRawBitmapResult& result) { got_favicon_ = result.is_valid(); got_expired_favicon_ = result.is_valid() && result.expired; - quit_closure_.Run(); + std::move(quit_closure_).Run(); } // For favicon requests. base::CancelableTaskTracker tracker_; bool got_favicon_ = false; bool got_expired_favicon_ = false; - base::Closure quit_closure_; + base::OnceClosure quit_closure_; // Owned by TestingProfile. history::HistoryService* history_service_ = nullptr;
diff --git a/chrome/browser/browsing_data/counters/cache_counter_browsertest.cc b/chrome/browser/browsing_data/counters/cache_counter_browsertest.cc index e9050f4..0b3d4e6 100644 --- a/chrome/browser/browsing_data/counters/cache_counter_browsertest.cc +++ b/chrome/browser/browsing_data/counters/cache_counter_browsertest.cc
@@ -157,8 +157,8 @@ CacheCounter counter(profile); counter.Init(profile->GetPrefs(), browsing_data::ClearBrowsingDataTab::ADVANCED, - base::Bind(&CacheCounterTest::CountingCallback, - base::Unretained(this))); + base::BindRepeating(&CacheCounterTest::CountingCallback, + base::Unretained(this))); counter.Restart(); WaitForCountingResult(); @@ -179,9 +179,10 @@ Profile* profile = browser()->profile(); CacheCounter counter(profile); - counter.Init( - profile->GetPrefs(), browsing_data::ClearBrowsingDataTab::ADVANCED, - base::Bind(&CacheCounterTest::CountingCallback, base::Unretained(this))); + counter.Init(profile->GetPrefs(), + browsing_data::ClearBrowsingDataTab::ADVANCED, + base::BindRepeating(&CacheCounterTest::CountingCallback, + base::Unretained(this))); counter.Restart(); WaitForCountingResult(); @@ -195,9 +196,10 @@ Profile* profile = browser()->profile(); CacheCounter counter(profile); - counter.Init( - profile->GetPrefs(), browsing_data::ClearBrowsingDataTab::ADVANCED, - base::Bind(&CacheCounterTest::CountingCallback, base::Unretained(this))); + counter.Init(profile->GetPrefs(), + browsing_data::ClearBrowsingDataTab::ADVANCED, + base::BindRepeating(&CacheCounterTest::CountingCallback, + base::Unretained(this))); content::BrowserContext::GetDefaultStoragePartition(browser()->profile()) ->GetNetworkContext() @@ -216,9 +218,10 @@ Profile* profile = browser()->profile(); CacheCounter counter(profile); - counter.Init( - profile->GetPrefs(), browsing_data::ClearBrowsingDataTab::ADVANCED, - base::Bind(&CacheCounterTest::CountingCallback, base::Unretained(this))); + counter.Init(profile->GetPrefs(), + browsing_data::ClearBrowsingDataTab::ADVANCED, + base::BindRepeating(&CacheCounterTest::CountingCallback, + base::Unretained(this))); SetCacheDeletionPref(true); // Test that changing the pref causes the counter to be restarted. If it @@ -233,9 +236,10 @@ Profile* profile = browser()->profile(); CacheCounter counter(profile); - counter.Init( - profile->GetPrefs(), browsing_data::ClearBrowsingDataTab::ADVANCED, - base::Bind(&CacheCounterTest::CountingCallback, base::Unretained(this))); + counter.Init(profile->GetPrefs(), + browsing_data::ClearBrowsingDataTab::ADVANCED, + base::BindRepeating(&CacheCounterTest::CountingCallback, + base::Unretained(this))); SetDeletionPeriodPref(browsing_data::TimePeriod::LAST_HOUR); WaitForCountingResult();
diff --git a/chrome/browser/browsing_data/counters/downloads_counter_browsertest.cc b/chrome/browser/browsing_data/counters/downloads_counter_browsertest.cc index d47879e..473f5ab0 100644 --- a/chrome/browser/browsing_data/counters/downloads_counter_browsertest.cc +++ b/chrome/browser/browsing_data/counters/downloads_counter_browsertest.cc
@@ -356,8 +356,8 @@ DownloadsCounter counter(profile); counter.Init(profile->GetPrefs(), browsing_data::ClearBrowsingDataTab::ADVANCED, - base::Bind(&DownloadsCounterTest::ResultCallback, - base::Unretained(this))); + base::BindRepeating(&DownloadsCounterTest::ResultCallback, + base::Unretained(this))); SetDeletionPeriodPref(browsing_data::TimePeriod::LAST_HOUR); EXPECT_EQ(2u, GetResult());
diff --git a/chrome/browser/browsing_data/counters/passwords_counter_browsertest.cc b/chrome/browser/browsing_data/counters/passwords_counter_browsertest.cc index c032387..9fcdf3a4 100644 --- a/chrome/browser/browsing_data/counters/passwords_counter_browsertest.cc +++ b/chrome/browser/browsing_data/counters/passwords_counter_browsertest.cc
@@ -162,9 +162,10 @@ AccountPasswordStoreFactory::GetForProfile( profile, ServiceAccessType::EXPLICIT_ACCESS), ProfileSyncServiceFactory::GetForProfile(profile)); - counter.Init( - profile->GetPrefs(), browsing_data::ClearBrowsingDataTab::ADVANCED, - base::Bind(&PasswordsCounterTest::Callback, base::Unretained(this))); + counter.Init(profile->GetPrefs(), + browsing_data::ClearBrowsingDataTab::ADVANCED, + base::BindRepeating(&PasswordsCounterTest::Callback, + base::Unretained(this))); counter.Restart(); WaitForCounting(); @@ -186,9 +187,10 @@ profile, ServiceAccessType::EXPLICIT_ACCESS), ProfileSyncServiceFactory::GetForProfile(profile)); - counter.Init( - profile->GetPrefs(), browsing_data::ClearBrowsingDataTab::ADVANCED, - base::Bind(&PasswordsCounterTest::Callback, base::Unretained(this))); + counter.Init(profile->GetPrefs(), + browsing_data::ClearBrowsingDataTab::ADVANCED, + base::BindRepeating(&PasswordsCounterTest::Callback, + base::Unretained(this))); counter.Restart(); WaitForCounting(); @@ -210,9 +212,10 @@ AccountPasswordStoreFactory::GetForProfile( profile, ServiceAccessType::EXPLICIT_ACCESS), ProfileSyncServiceFactory::GetForProfile(profile)); - counter.Init( - profile->GetPrefs(), browsing_data::ClearBrowsingDataTab::ADVANCED, - base::Bind(&PasswordsCounterTest::Callback, base::Unretained(this))); + counter.Init(profile->GetPrefs(), + browsing_data::ClearBrowsingDataTab::ADVANCED, + base::BindRepeating(&PasswordsCounterTest::Callback, + base::Unretained(this))); SetPasswordsDeletionPref(true); WaitForCounting(); @@ -232,9 +235,10 @@ AccountPasswordStoreFactory::GetForProfile( profile, ServiceAccessType::EXPLICIT_ACCESS), ProfileSyncServiceFactory::GetForProfile(profile)); - counter.Init( - profile->GetPrefs(), browsing_data::ClearBrowsingDataTab::ADVANCED, - base::Bind(&PasswordsCounterTest::Callback, base::Unretained(this))); + counter.Init(profile->GetPrefs(), + browsing_data::ClearBrowsingDataTab::ADVANCED, + base::BindRepeating(&PasswordsCounterTest::Callback, + base::Unretained(this))); counter.Restart(); WaitForCounting(); @@ -268,9 +272,10 @@ AccountPasswordStoreFactory::GetForProfile( profile, ServiceAccessType::EXPLICIT_ACCESS), ProfileSyncServiceFactory::GetForProfile(profile)); - counter.Init( - profile->GetPrefs(), browsing_data::ClearBrowsingDataTab::ADVANCED, - base::Bind(&PasswordsCounterTest::Callback, base::Unretained(this))); + counter.Init(profile->GetPrefs(), + browsing_data::ClearBrowsingDataTab::ADVANCED, + base::BindRepeating(&PasswordsCounterTest::Callback, + base::Unretained(this))); SetDeletionPeriodPref(browsing_data::TimePeriod::LAST_HOUR); WaitForCounting(); @@ -317,9 +322,10 @@ AccountPasswordStoreFactory::GetForProfile( profile, ServiceAccessType::EXPLICIT_ACCESS), ProfileSyncServiceFactory::GetForProfile(profile)); - counter.Init( - profile->GetPrefs(), browsing_data::ClearBrowsingDataTab::ADVANCED, - base::Bind(&PasswordsCounterTest::Callback, base::Unretained(this))); + counter.Init(profile->GetPrefs(), + browsing_data::ClearBrowsingDataTab::ADVANCED, + base::BindRepeating(&PasswordsCounterTest::Callback, + base::Unretained(this))); counter.Restart(); WaitForCounting();
diff --git a/chrome/browser/chrome_browser_application_mac.mm b/chrome/browser/chrome_browser_application_mac.mm index cc2a51e..dd91835 100644 --- a/chrome/browser/chrome_browser_application_mac.mm +++ b/chrome/browser/chrome_browser_application_mac.mm
@@ -4,8 +4,6 @@ #import "chrome/browser/chrome_browser_application_mac.h" -#include <dispatch/dispatch.h> - #include "base/check.h" #include "base/command_line.h" #include "base/mac/call_with_eh_frame.h" @@ -345,6 +343,8 @@ content::BrowserAccessibilityState::GetInstance(); if ([value intValue] == 1) accessibility_state->OnScreenReaderDetected(); + else + accessibility_state->DisableAccessibility(); } return [super accessibilitySetValue:value forAttribute:attribute]; } @@ -365,19 +365,4 @@ _observers.RemoveObserver(observer); } -- (NSAccessibilityRole)accessibilityRole { - // Our previous method of enabling a11y when the 'AXEnhancedUserInterface' - // attribute was set didn't work for the new VoiceControl system. After - // discussions with Apple, they recommended that we turn on a11y when an AT - // accesses the 'accessibilityRole' property. This works with VoiceControl, - // and should work with any other new ATs in the future. - static dispatch_once_t onceToken; - dispatch_once(&onceToken, ^{ - content::BrowserAccessibilityState* accessibility_state = - content::BrowserAccessibilityState::GetInstance(); - accessibility_state->OnScreenReaderDetected(); - }); - return [super accessibilityRole]; -} - @end
diff --git a/chrome/browser/chromeos/BUILD.gn b/chrome/browser/chromeos/BUILD.gn index d5b4fe55..58c01e0 100644 --- a/chrome/browser/chromeos/BUILD.gn +++ b/chrome/browser/chromeos/BUILD.gn
@@ -298,6 +298,8 @@ "//components/quirks", "//components/rappor", "//components/renderer_context_menu", + "//components/reporting/util:status", + "//components/reporting/util:task_runner_context", "//components/rlz", "//components/safe_browsing/core:csd_proto", "//components/safe_browsing/core/db:metadata_proto",
diff --git a/chrome/browser/chromeos/arc/session/arc_service_launcher.cc b/chrome/browser/chromeos/arc/session/arc_service_launcher.cc index 977df5c..a7d7a4df 100644 --- a/chrome/browser/chromeos/arc/session/arc_service_launcher.cc +++ b/chrome/browser/chromeos/arc/session/arc_service_launcher.cc
@@ -76,6 +76,7 @@ #include "components/arc/power/arc_power_bridge.h" #include "components/arc/property/arc_property_bridge.h" #include "components/arc/rotation_lock/arc_rotation_lock_bridge.h" +#include "components/arc/sensor/arc_iio_sensor_bridge.h" #include "components/arc/sensor/arc_sensor_bridge.h" #include "components/arc/session/arc_session.h" #include "components/arc/session/arc_session_runner.h" @@ -195,6 +196,7 @@ ArcFileSystemBridge::GetForBrowserContext(profile); ArcFileSystemMounter::GetForBrowserContext(profile); ArcFileSystemWatcherService::GetForBrowserContext(profile); + ArcIioSensorBridge::GetForBrowserContext(profile); ArcImeService::GetForBrowserContext(profile); ArcInputMethodManagerService::GetForBrowserContext(profile); ArcInstanceThrottle::GetForBrowserContext(profile);
diff --git a/chrome/browser/chromeos/policy/extension_install_event_log_manager_unittest.cc b/chrome/browser/chromeos/policy/extension_install_event_log_manager_unittest.cc index 23d03038..d42b525 100644 --- a/chrome/browser/chromeos/policy/extension_install_event_log_manager_unittest.cc +++ b/chrome/browser/chromeos/policy/extension_install_event_log_manager_unittest.cc
@@ -23,7 +23,6 @@ #include "chrome/browser/chromeos/policy/extension_install_event_log.h" #include "chrome/browser/chromeos/policy/install_event_log_util.h" #include "chrome/browser/policy/messaging_layer/public/mock_report_queue.h" -#include "chrome/browser/policy/messaging_layer/util/status.h" #include "chrome/browser/profiles/reporting_util.h" #include "chrome/test/base/testing_profile.h" #include "chromeos/system/fake_statistics_provider.h" @@ -31,6 +30,7 @@ #include "components/policy/core/common/cloud/realtime_reporting_job_configuration.h" #include "components/policy/proto/device_management_backend.pb.h" #include "components/prefs/pref_service.h" +#include "components/reporting/util/status.h" #include "content/public/test/browser_task_environment.h" #include "extensions/browser/quota_service.h" #include "testing/gmock/include/gmock/gmock.h"
diff --git a/chrome/browser/chromeos/policy/extension_install_event_log_uploader.h b/chrome/browser/chromeos/policy/extension_install_event_log_uploader.h index efa5e49..554c251 100644 --- a/chrome/browser/chromeos/policy/extension_install_event_log_uploader.h +++ b/chrome/browser/chromeos/policy/extension_install_event_log_uploader.h
@@ -12,9 +12,9 @@ #include "chrome/browser/chromeos/policy/install_event_log_uploader_base.h" #include "chrome/browser/policy/messaging_layer/public/report_client.h" #include "chrome/browser/policy/messaging_layer/public/report_queue.h" -#include "chrome/browser/policy/messaging_layer/util/status.h" -#include "chrome/browser/policy/messaging_layer/util/statusor.h" -#include "chrome/browser/policy/messaging_layer/util/task_runner_context.h" +#include "components/reporting/util/status.h" +#include "components/reporting/util/statusor.h" +#include "components/reporting/util/task_runner_context.h" namespace enterprise_management { class ExtensionInstallReportRequest;
diff --git a/chrome/browser/chromeos/policy/extension_install_event_log_uploader_unittest.cc b/chrome/browser/chromeos/policy/extension_install_event_log_uploader_unittest.cc index 8b58e88..9e3ca47 100644 --- a/chrome/browser/chromeos/policy/extension_install_event_log_uploader_unittest.cc +++ b/chrome/browser/chromeos/policy/extension_install_event_log_uploader_unittest.cc
@@ -19,12 +19,12 @@ #include "base/values.h" #include "chrome/browser/chromeos/policy/install_event_log_util.h" #include "chrome/browser/policy/messaging_layer/public/mock_report_queue.h" -#include "chrome/browser/policy/messaging_layer/util/status.h" #include "chrome/browser/profiles/reporting_util.h" #include "chromeos/system/fake_statistics_provider.h" #include "components/policy/core/common/cloud/mock_cloud_policy_client.h" #include "components/policy/core/common/cloud/realtime_reporting_job_configuration.h" #include "components/policy/proto/device_management_backend.pb.h" +#include "components/reporting/util/status.h" #include "content/public/test/browser_task_environment.h" #include "testing/gmock/include/gmock/gmock.h" #include "testing/gtest/include/gtest/gtest.h"
diff --git a/chrome/browser/chromeos/policy/lock_to_single_user_manager_unittest.cc b/chrome/browser/chromeos/policy/lock_to_single_user_manager_unittest.cc index c0cda28..e2f57f1c 100644 --- a/chrome/browser/chromeos/policy/lock_to_single_user_manager_unittest.cc +++ b/chrome/browser/chromeos/policy/lock_to_single_user_manager_unittest.cc
@@ -19,7 +19,6 @@ #include "chromeos/dbus/cryptohome/fake_cryptohome_client.h" #include "chromeos/dbus/dbus_thread_manager.h" #include "chromeos/dbus/fake_concierge_client.h" -#include "chromeos/login/login_state/login_state.h" #include "chromeos/login/session/session_termination_manager.h" #include "chromeos/settings/cros_settings_names.h" #include "components/account_id/account_id.h" @@ -45,7 +44,6 @@ arc::SetArcAvailableCommandLineForTesting( base::CommandLine::ForCurrentProcess()); - chromeos::LoginState::Initialize(); chromeos::CryptohomeClient::InitializeFake(); lock_to_single_user_manager_ = std::make_unique<LockToSingleUserManager>(); @@ -76,7 +74,6 @@ arc_service_manager_.reset(); BrowserWithTestWindowTest::TearDown(); chromeos::CryptohomeClient::Shutdown(); - chromeos::LoginState::Shutdown(); chromeos::DBusThreadManager::Shutdown(); }
diff --git a/chrome/browser/extensions/api/tabs/tabs_test.cc b/chrome/browser/extensions/api/tabs/tabs_test.cc index d566cbd..6c1120cc 100644 --- a/chrome/browser/extensions/api/tabs/tabs_test.cc +++ b/chrome/browser/extensions/api/tabs/tabs_test.cc
@@ -277,7 +277,8 @@ EXPECT_GE(GetTabId(utils::ToDictionary(tab0)), 0); } -IN_PROC_BROWSER_TEST_F(ExtensionTabsTest, GetAllWindows) { +// TODO(http://crbug.com/1172393): flaky on many bots +IN_PROC_BROWSER_TEST_F(ExtensionTabsTest, DISABLED_GetAllWindows) { const size_t NUM_WINDOWS = 5; std::set<int> window_ids; std::set<int> result_ids;
diff --git a/chrome/browser/flag_descriptions.cc b/chrome/browser/flag_descriptions.cc index 50172e5..54801412 100644 --- a/chrome/browser/flag_descriptions.cc +++ b/chrome/browser/flag_descriptions.cc
@@ -3718,10 +3718,6 @@ "Use Metal instead of OpenGL for rasterization (if out-of-process " "rasterization is enabled) and display (if the Skia renderer is enabled)"; -const char kVideoToolboxVp9DecodingName[] = "VideoToolbox VP9 Decoding"; -const char kVideoToolboxVp9DecodingDescription[] = - "Controls usage of VideoToolbox for hardware decoding of VP9 video."; - #endif // Chrome OS -------------------------------------------------------------------
diff --git a/chrome/browser/flag_descriptions.h b/chrome/browser/flag_descriptions.h index 4949df16..64efbf1 100644 --- a/chrome/browser/flag_descriptions.h +++ b/chrome/browser/flag_descriptions.h
@@ -2146,9 +2146,6 @@ extern const char kMetalName[]; extern const char kMetalDescription[]; -extern const char kVideoToolboxVp9DecodingName[]; -extern const char kVideoToolboxVp9DecodingDescription[]; - #endif // defined(OS_MAC) // Chrome OS ------------------------------------------------------------------
diff --git a/chrome/browser/optimization_guide/optimization_guide_keyed_service.cc b/chrome/browser/optimization_guide/optimization_guide_keyed_service.cc index acdaa6cc..ee74ba8 100644 --- a/chrome/browser/optimization_guide/optimization_guide_keyed_service.cc +++ b/chrome/browser/optimization_guide/optimization_guide_keyed_service.cc
@@ -202,7 +202,7 @@ navigation_data->set_registered_optimization_types( hints_manager_->registered_optimization_types()); navigation_data->set_registered_optimization_targets( - prediction_manager_->registered_optimization_targets()); + prediction_manager_->GetRegisteredOptimizationTargets()); } } @@ -216,7 +216,16 @@ void OptimizationGuideKeyedService::RegisterOptimizationTargets( const std::vector<optimization_guide::proto::OptimizationTarget>& optimization_targets) { - prediction_manager_->RegisterOptimizationTargets(optimization_targets); + std::vector<std::pair<optimization_guide::proto::OptimizationTarget, + base::Optional<optimization_guide::proto::Any>>> + optimization_targets_and_metadata; + for (optimization_guide::proto::OptimizationTarget optimization_target : + optimization_targets) { + optimization_targets_and_metadata.emplace_back( + std::make_pair(optimization_target, base::nullopt)); + } + prediction_manager_->RegisterOptimizationTargets( + optimization_targets_and_metadata); } void OptimizationGuideKeyedService::ShouldTargetNavigationAsync( @@ -237,9 +246,10 @@ void OptimizationGuideKeyedService::AddObserverForOptimizationTargetModel( optimization_guide::proto::OptimizationTarget optimization_target, + const base::Optional<optimization_guide::proto::Any>& model_metadata, optimization_guide::OptimizationTargetModelObserver* observer) { - prediction_manager_->AddObserverForOptimizationTargetModel( - optimization_target, observer); + prediction_manager_->AddObserverForOptimizationTargetModel( + optimization_target, model_metadata, observer); } void OptimizationGuideKeyedService::RemoveObserverForOptimizationTargetModel( @@ -317,7 +327,8 @@ void OptimizationGuideKeyedService::OverrideTargetModelFileForTesting( optimization_guide::proto::OptimizationTarget optimization_target, + const base::Optional<optimization_guide::proto::Any>& model_metadata, const base::FilePath& file_path) { - prediction_manager_->OverrideTargetModelFileForTesting(optimization_target, - file_path); + prediction_manager_->OverrideTargetModelFileForTesting( + optimization_target, model_metadata, file_path); }
diff --git a/chrome/browser/optimization_guide/optimization_guide_keyed_service.h b/chrome/browser/optimization_guide/optimization_guide_keyed_service.h index ed49ec8..088fb55c 100644 --- a/chrome/browser/optimization_guide/optimization_guide_keyed_service.h +++ b/chrome/browser/optimization_guide/optimization_guide_keyed_service.h
@@ -67,6 +67,7 @@ override; void AddObserverForOptimizationTargetModel( optimization_guide::proto::OptimizationTarget optimization_target, + const base::Optional<optimization_guide::proto::Any>& model_metadata, optimization_guide::OptimizationTargetModelObserver* observer) override; void RemoveObserverForOptimizationTargetModel( optimization_guide::proto::OptimizationTarget optimization_target, @@ -103,6 +104,7 @@ // testing purposes only. void OverrideTargetModelFileForTesting( optimization_guide::proto::OptimizationTarget optimization_target, + const base::Optional<optimization_guide::proto::Any>& model_metadata, const base::FilePath& file_path); private:
diff --git a/chrome/browser/optimization_guide/prediction/prediction_manager.cc b/chrome/browser/optimization_guide/prediction/prediction_manager.cc index b348a84e..80be34e 100644 --- a/chrome/browser/optimization_guide/prediction/prediction_manager.cc +++ b/chrome/browser/optimization_guide/prediction/prediction_manager.cc
@@ -283,21 +283,27 @@ } void PredictionManager::RegisterOptimizationTargets( - const std::vector<proto::OptimizationTarget>& optimization_targets) { + const std::vector< + std::pair<proto::OptimizationTarget, base::Optional<proto::Any>>>& + optimization_targets_and_metadata) { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); - if (optimization_targets.empty()) + if (optimization_targets_and_metadata.empty()) return; base::flat_set<proto::OptimizationTarget> new_optimization_targets; - for (const auto& optimization_target : optimization_targets) { + for (const auto& optimization_target_and_metadata : + optimization_targets_and_metadata) { + proto::OptimizationTarget optimization_target = + optimization_target_and_metadata.first; if (optimization_target == proto::OPTIMIZATION_TARGET_UNKNOWN) continue; - if (registered_optimization_targets_.find(optimization_target) != - registered_optimization_targets_.end()) { + if (registered_optimization_targets_and_metadata_.contains( + optimization_target)) { continue; } - registered_optimization_targets_.insert(optimization_target); + registered_optimization_targets_and_metadata_.emplace( + optimization_target_and_metadata); new_optimization_targets.insert(optimization_target); } @@ -308,7 +314,7 @@ // Only proceed if there are newly registered targets to load/fetch models and // features for. Otherwise, the registered targets will have models loaded // when the store was initialized. - if (new_optimization_targets.size() == 0) + if (new_optimization_targets.empty()) return; // If no fetch is scheduled, maybe schedule one. @@ -327,7 +333,11 @@ void PredictionManager::AddObserverForOptimizationTargetModel( proto::OptimizationTarget optimization_target, + const base::Optional<proto::Any>& model_metadata, OptimizationTargetModelObserver* observer) { + // TODO(crbug/1171871): Probably do not allow for multiple observers to be + // registered for the same optimization target. + registered_observers_for_optimization_targets_[optimization_target] .AddObserver(observer); @@ -336,10 +346,11 @@ optimization_target_prediction_model_file_map_.find(optimization_target); if (model_file_it != optimization_target_prediction_model_file_map_.end()) { observer->OnModelFileUpdated(optimization_target, + model_file_it->second->GetModelMetadata(), model_file_it->second->GetModelFilePath()); } - RegisterOptimizationTargets({optimization_target}); + RegisterOptimizationTargets({{optimization_target, model_metadata}}); } void PredictionManager::RemoveObserverForOptimizationTargetModel( @@ -448,7 +459,7 @@ const base::flat_map<proto::ClientModelFeature, float>& override_client_model_feature_values) { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); - if (model_features.size() == 0) + if (model_features.empty()) return {}; const base::flat_map<std::string, float>* host_model_features = nullptr; @@ -503,8 +514,10 @@ return *optimization_target_decision; } } - if (!registered_optimization_targets_.contains(optimization_target)) + if (!registered_optimization_targets_and_metadata_.contains( + optimization_target)) { return OptimizationTargetDecision::kUnknown; + } ScopedPredictionManagerModelStatusRecorder model_status_recorder( optimization_target); @@ -569,6 +582,16 @@ current_effective_connection_type_ = effective_connection_type; } +base::flat_set<proto::OptimizationTarget> +PredictionManager::GetRegisteredOptimizationTargets() const { + base::flat_set<proto::OptimizationTarget> optimization_targets; + for (const auto& optimization_target_and_metadata : + registered_optimization_targets_and_metadata_) { + optimization_targets.insert(optimization_target_and_metadata.first); + } + return optimization_targets; +} + PredictionModel* PredictionManager::GetPredictionModelForTesting( proto::OptimizationTarget optimization_target) const { auto it = optimization_target_prediction_model_map_.find(optimization_target); @@ -616,7 +639,7 @@ // Models and host model features should not be fetched if there are no // optimization targets registered. - if (registered_optimization_targets_.size() == 0) + if (registered_optimization_targets_and_metadata_.empty()) return; // Cancel all pending downloads since the server will probably give us new @@ -676,12 +699,17 @@ base_model_info.add_supported_model_types(proto::MODEL_TYPE_TFLITE_2_3_0); // For now, we will fetch for all registered optimization targets. - for (const auto& optimization_target : registered_optimization_targets_) { + for (const auto& optimization_target_and_metadata : + registered_optimization_targets_and_metadata_) { proto::ModelInfo model_info(base_model_info); - model_info.set_optimization_target(optimization_target); + model_info.set_optimization_target(optimization_target_and_metadata.first); + if (optimization_target_and_metadata.second.has_value()) { + *model_info.mutable_model_metadata() = + *optimization_target_and_metadata.second; + } - auto it = - optimization_target_prediction_model_map_.find(optimization_target); + auto it = optimization_target_prediction_model_map_.find( + optimization_target_and_metadata.first); if (it != optimization_target_prediction_model_map_.end()) model_info.set_version(it->second.get()->GetVersion()); @@ -802,7 +830,7 @@ base::BindOnce(&PredictionManager::OnPredictionModelsStored, ui_weak_ptr_factory_.GetWeakPtr())); - if (registered_optimization_targets_.contains( + if (registered_optimization_targets_and_metadata_.contains( model.model_info().optimization_target())) { OnLoadPredictionModel(std::make_unique<proto::PredictionModel>(model)); } @@ -810,6 +838,7 @@ void PredictionManager::NotifyObserversOfNewModelPath( proto::OptimizationTarget optimization_target, + const base::Optional<proto::Any>& model_metadata, const base::FilePath& file_path) const { auto observers_it = registered_observers_for_optimization_targets_.find(optimization_target); @@ -817,7 +846,7 @@ return; for (auto& observer : observers_it->second) - observer.OnModelFileUpdated(optimization_target, file_path); + observer.OnModelFileUpdated(optimization_target, model_metadata, file_path); } void PredictionManager::OnPredictionModelsStored() { @@ -850,7 +879,7 @@ store_is_ready_ = true; // Only load host model features if there are optimization targets registered. - if (registered_optimization_targets_.empty()) + if (registered_optimization_targets_and_metadata_.empty()) return; // The store is ready so start loading host model features and the models for @@ -890,7 +919,7 @@ // Load the prediction models for all the registered optimization targets now // that it is not blocked by loading the host model features. - LoadPredictionModels(registered_optimization_targets_); + LoadPredictionModels(GetRegisteredOptimizationTargets()); } void PredictionManager::LoadPredictionModels( @@ -958,7 +987,7 @@ return false; if (!model.has_model()) return false; - if (!registered_optimization_targets_.contains( + if (!registered_optimization_targets_and_metadata_.contains( model.model_info().optimization_target())) { return false; } @@ -1035,6 +1064,7 @@ FROM_HERE, base::BindOnce(&PredictionManager::NotifyObserversOfNewModelPath, ui_weak_ptr_factory_.GetWeakPtr(), optimization_target, + prediction_model_file->GetModelMetadata(), prediction_model_file->GetModelFilePath())); optimization_target_prediction_model_file_map_.insert_or_assign( @@ -1090,7 +1120,7 @@ break; } } - if (model_features_for_host.size() == 0) + if (model_features_for_host.empty()) return false; host_model_features_cache_.Put(host_model_features.host(), model_features_for_host); @@ -1211,12 +1241,17 @@ void PredictionManager::OverrideTargetModelFileForTesting( proto::OptimizationTarget optimization_target, + const base::Optional<proto::Any>& model_metadata, const base::FilePath& file_path) { proto::PredictionModel prediction_model; prediction_model.mutable_model_info()->set_version(1); prediction_model.mutable_model_info()->set_optimization_target( optimization_target); SetFilePathInPredictionModel(file_path, &prediction_model); + if (model_metadata.has_value()) { + *prediction_model.mutable_model_info()->mutable_model_metadata() = + *model_metadata; + } std::unique_ptr<PredictionModelFile> prediction_model_file = PredictionModelFile::Create(prediction_model); DCHECK(prediction_model_file); @@ -1224,7 +1259,7 @@ optimization_target_prediction_model_file_map_.insert_or_assign( optimization_target, std::move(prediction_model_file)); - NotifyObserversOfNewModelPath(optimization_target, file_path); + NotifyObserversOfNewModelPath(optimization_target, model_metadata, file_path); } } // namespace optimization_guide
diff --git a/chrome/browser/optimization_guide/prediction/prediction_manager.h b/chrome/browser/optimization_guide/prediction/prediction_manager.h index 49b1f73..9c4c82fe 100644 --- a/chrome/browser/optimization_guide/prediction/prediction_manager.h +++ b/chrome/browser/optimization_guide/prediction/prediction_manager.h
@@ -79,7 +79,9 @@ // Register the optimization targets that may have ShouldTargetNavigation // requested by consumers of the Optimization Guide. void RegisterOptimizationTargets( - const std::vector<proto::OptimizationTarget>& optimization_targets); + const std::vector< + std::pair<proto::OptimizationTarget, base::Optional<proto::Any>>>& + optimization_targets_and_metadata); // Adds an observer for updates to the model for |optimization_target|. // @@ -87,6 +89,7 @@ // Machine Learning Service for inference. void AddObserverForOptimizationTargetModel( proto::OptimizationTarget optimization_target, + const base::Optional<proto::Any>& model_metadata, OptimizationTargetModelObserver* observer); // Removes an observer for updates to the model for |optimization_target|. @@ -149,10 +152,8 @@ } // Return the optimization targets that are registered. - base::flat_set<optimization_guide::proto::OptimizationTarget> - registered_optimization_targets() const { - return registered_optimization_targets_; - } + base::flat_set<proto::OptimizationTarget> GetRegisteredOptimizationTargets() + const; // Override |clock_| for testing. void SetClockForTesting(const base::Clock* clock); @@ -171,6 +172,7 @@ // For testing purposes only. void OverrideTargetModelFileForTesting( proto::OptimizationTarget optimization_target, + const base::Optional<proto::Any>& model_metadata, const base::FilePath& file_path); // PredictionModelDownloadObserver: @@ -348,6 +350,7 @@ // updated to |file_path|. void NotifyObserversOfNewModelPath( proto::OptimizationTarget optimization_target, + const base::Optional<proto::Any>& model_metadata, const base::FilePath& file_path) const; // A map of optimization target to the prediction model capable of making @@ -361,9 +364,10 @@ std::unique_ptr<PredictionModelFile>> optimization_target_prediction_model_file_map_; - // The set of optimization targets that have been registered with the - // prediction manager. - base::flat_set<proto::OptimizationTarget> registered_optimization_targets_; + // The map from optimization targets to feature-provided metadata that have + // been registered with the prediction manager. + base::flat_map<proto::OptimizationTarget, base::Optional<proto::Any>> + registered_optimization_targets_and_metadata_; // The map from optimization target to observers that have been registered to // receive model updates from the prediction manager.
diff --git a/chrome/browser/optimization_guide/prediction/prediction_manager_browsertest.cc b/chrome/browser/optimization_guide/prediction/prediction_manager_browsertest.cc index aff6928..dc474994 100644 --- a/chrome/browser/optimization_guide/prediction/prediction_manager_browsertest.cc +++ b/chrome/browser/optimization_guide/prediction/prediction_manager_browsertest.cc
@@ -930,6 +930,7 @@ } void OnModelFileUpdated(proto::OptimizationTarget optimization_target, + const base::Optional<proto::Any>& model_metadata, const base::FilePath& file_path) override { if (file_received_callback_) std::move(file_received_callback_).Run(optimization_target, file_path); @@ -963,7 +964,7 @@ OptimizationGuideKeyedServiceFactory::GetForProfile(browser()->profile()) ->AddObserverForOptimizationTargetModel( proto::OPTIMIZATION_TARGET_PAINFUL_PAGE_LOAD, - model_file_observer_.get()); + /*model_metadata=*/base::nullopt, model_file_observer_.get()); } private:
diff --git a/chrome/browser/optimization_guide/prediction/prediction_manager_unittest.cc b/chrome/browser/optimization_guide/prediction/prediction_manager_unittest.cc index 8c81c43e..343e076 100644 --- a/chrome/browser/optimization_guide/prediction/prediction_manager_unittest.cc +++ b/chrome/browser/optimization_guide/prediction/prediction_manager_unittest.cc
@@ -169,24 +169,28 @@ : public OptimizationTargetModelObserver { public: void OnModelFileUpdated(proto::OptimizationTarget optimization_target, + const base::Optional<proto::Any>& model_metadata, const base::FilePath& file_path) override { - last_received_paths_[optimization_target] = file_path; + last_received_models_[optimization_target] = + std::make_pair(model_metadata, file_path); } - base::Optional<base::FilePath> last_received_path_for_target( + base::Optional<std::pair<base::Optional<proto::Any>, base::FilePath>> + last_received_model_for_target( proto::OptimizationTarget optimization_target) { - auto file_it = last_received_paths_.find(optimization_target); - if (file_it == last_received_paths_.end()) + auto model_it = last_received_models_.find(optimization_target); + if (model_it == last_received_models_.end()) return base::nullopt; - return file_it->second; + return model_it->second; } // Resets the state of the observer. - void Reset() { last_received_paths_.clear(); } + void Reset() { last_received_models_.clear(); } private: - base::flat_map<proto::OptimizationTarget, base::FilePath> - last_received_paths_; + base::flat_map<proto::OptimizationTarget, + std::pair<base::Optional<proto::Any>, base::FilePath>> + last_received_models_; }; class FakePredictionModelDownloadManager @@ -289,10 +293,28 @@ model_info.optimization_target())) { return false; } + auto it = expected_metadata_.find(model_info.optimization_target()); + if (model_info.has_model_metadata() != (it != expected_metadata_.end())) + return false; + if (model_info.has_model_metadata()) { + proto::Any expected_metadata = it->second; + if (model_info.model_metadata().type_url() != + expected_metadata.type_url()) { + return false; + } + if (model_info.model_metadata().value() != expected_metadata.value()) + return false; + } } return true; } + void SetExpectedModelMetadataForOptimizationTarget( + proto::OptimizationTarget optimization_target, + const proto::Any& model_metadata) { + expected_metadata_[optimization_target] = model_metadata; + } + bool models_fetched() { return models_fetched_; } size_t hosts_fetched() { return count_hosts_fetched_; } @@ -301,6 +323,7 @@ size_t count_hosts_fetched_ = 0; // The desired behavior of the TestPredictionModelFetcher. PredictionModelFetcherEndState fetch_state_; + base::flat_map<proto::OptimizationTarget, proto::Any> expected_metadata_; }; class TestOptimizationGuideStore : public OptimizationGuideStore { @@ -621,7 +644,7 @@ kFetchSuccessWithModelsAndHostsModelFeatures)); prediction_manager()->RegisterOptimizationTargets( - {proto::OPTIMIZATION_TARGET_PAINFUL_PAGE_LOAD}); + {{proto::OPTIMIZATION_TARGET_PAINFUL_PAGE_LOAD, base::nullopt}}); SetStoreInitialized(); EXPECT_FALSE(prediction_model_fetcher()->models_fetched()); @@ -644,7 +667,7 @@ kFetchSuccessWithModelsAndHostsModelFeatures)); prediction_manager()->RegisterOptimizationTargets( - {proto::OPTIMIZATION_TARGET_PAINFUL_PAGE_LOAD}); + {{proto::OPTIMIZATION_TARGET_PAINFUL_PAGE_LOAD, base::nullopt}}); SetStoreInitialized(); EXPECT_TRUE(prediction_model_fetcher()->models_fetched()); @@ -692,10 +715,14 @@ prediction_manager()->SetPredictionModelFetcherForTesting( BuildTestPredictionModelFetcher( PredictionModelFetcherEndState::kFetchSuccessWithEmptyResponse)); + proto::Any model_metadata; + model_metadata.set_type_url("whatever"); + prediction_model_fetcher()->SetExpectedModelMetadataForOptimizationTarget( + proto::OPTIMIZATION_TARGET_PAINFUL_PAGE_LOAD, model_metadata); FakeOptimizationTargetModelObserver observer; prediction_manager()->AddObserverForOptimizationTargetModel( - proto::OPTIMIZATION_TARGET_PAINFUL_PAGE_LOAD, &observer); + proto::OPTIMIZATION_TARGET_PAINFUL_PAGE_LOAD, model_metadata, &observer); SetStoreInitialized(/* load_models= */ false, /* load_host_model_features= */ false, /* have_models_in_store= */ false); @@ -721,10 +748,10 @@ proto::OPTIMIZATION_TARGET_PAINFUL_PAGE_LOAD), 0); - EXPECT_TRUE(prediction_manager()->registered_optimization_targets().contains( + EXPECT_TRUE(prediction_manager()->GetRegisteredOptimizationTargets().contains( proto::OPTIMIZATION_TARGET_PAINFUL_PAGE_LOAD)); EXPECT_FALSE(observer - .last_received_path_for_target( + .last_received_model_for_target( proto::OPTIMIZATION_TARGET_PAINFUL_PAGE_LOAD) .has_value()); @@ -732,6 +759,7 @@ model_info.set_optimization_target( proto::OPTIMIZATION_TARGET_PAINFUL_PAGE_LOAD); model_info.set_version(1); + model_info.mutable_model_metadata()->set_type_url("sometypeurl"); // Ensure observer is hooked up. proto::PredictionModel model1; @@ -740,16 +768,17 @@ prediction_manager()->OnModelReady(model1); RunUntilIdle(); - EXPECT_EQ(observer - .last_received_path_for_target( - proto::OPTIMIZATION_TARGET_PAINFUL_PAGE_LOAD) - ->BaseName() - .value(), + base::Optional<std::pair<base::Optional<proto::Any>, base::FilePath>> + received_model = observer.last_received_model_for_target( + proto::OPTIMIZATION_TARGET_PAINFUL_PAGE_LOAD); + EXPECT_EQ(received_model->first->type_url(), "sometypeurl"); + EXPECT_EQ(received_model->second.BaseName().value(), FILE_PATH_LITERAL("whatever")); - // Now remove observer. + // Now remove and reset observer. prediction_manager()->RemoveObserverForOptimizationTargetModel( proto::OPTIMIZATION_TARGET_PAINFUL_PAGE_LOAD, &observer); + observer.Reset(); proto::PredictionModel model2; *model2.mutable_model_info() = model_info; model2.mutable_model_info()->set_version(2); @@ -759,12 +788,10 @@ // Last received path should not have been updated since the observer was // removed. - EXPECT_EQ(observer - .last_received_path_for_target( - proto::OPTIMIZATION_TARGET_PAINFUL_PAGE_LOAD) - ->BaseName() - .value(), - FILE_PATH_LITERAL("whatever")); + EXPECT_FALSE(observer + .last_received_model_for_target( + proto::OPTIMIZATION_TARGET_PAINFUL_PAGE_LOAD) + .has_value()); } TEST_F(PredictionManagerTest, @@ -776,7 +803,8 @@ FakeOptimizationTargetModelObserver observer1; prediction_manager()->AddObserverForOptimizationTargetModel( - proto::OPTIMIZATION_TARGET_PAINFUL_PAGE_LOAD, &observer1); + proto::OPTIMIZATION_TARGET_PAINFUL_PAGE_LOAD, + /*model_metadata=*/base::nullopt, &observer1); SetStoreInitialized(/* load_models= */ false, /* load_host_model_features= */ false, /* have_models_in_store= */ false); @@ -794,22 +822,23 @@ RunUntilIdle(); EXPECT_EQ(observer1 - .last_received_path_for_target( + .last_received_model_for_target( proto::OPTIMIZATION_TARGET_PAINFUL_PAGE_LOAD) - ->BaseName() + ->second.BaseName() .value(), FILE_PATH_LITERAL("whatever")); // Now, register a new observer. FakeOptimizationTargetModelObserver observer2; prediction_manager()->AddObserverForOptimizationTargetModel( - proto::OPTIMIZATION_TARGET_PAINFUL_PAGE_LOAD, &observer2); + proto::OPTIMIZATION_TARGET_PAINFUL_PAGE_LOAD, + /*model_metadata=*/base::nullopt, &observer2); // Observer2 should receive a notification for the current model path. EXPECT_EQ(observer2 - .last_received_path_for_target( + .last_received_model_for_target( proto::OPTIMIZATION_TARGET_PAINFUL_PAGE_LOAD) - ->BaseName() + ->second.BaseName() .value(), FILE_PATH_LITERAL("whatever")); } @@ -826,7 +855,7 @@ CreatePredictionManager(); prediction_manager()->RegisterOptimizationTargets( - {proto::OPTIMIZATION_TARGET_PAINFUL_PAGE_LOAD}); + {{proto::OPTIMIZATION_TARGET_PAINFUL_PAGE_LOAD, base::nullopt}}); EXPECT_EQ(OptimizationTargetDecision::kModelNotAvailableOnClient, prediction_manager()->ShouldTargetNavigation( @@ -868,7 +897,7 @@ PredictionModelFetcherEndState::kFetchSuccessWithEmptyResponse)); prediction_manager()->RegisterOptimizationTargets( - {proto::OPTIMIZATION_TARGET_PAINFUL_PAGE_LOAD}); + {{proto::OPTIMIZATION_TARGET_PAINFUL_PAGE_LOAD, base::nullopt}}); SetStoreInitialized(); EXPECT_TRUE(prediction_model_fetcher()->models_fetched()); @@ -918,7 +947,7 @@ PredictionModelFetcherEndState::kFetchFailed)); prediction_manager()->RegisterOptimizationTargets( - {proto::OPTIMIZATION_TARGET_PAINFUL_PAGE_LOAD}); + {{proto::OPTIMIZATION_TARGET_PAINFUL_PAGE_LOAD, base::nullopt}}); std::unique_ptr<proto::GetModelsResponse> get_models_response = BuildGetModelsResponse({} /* hosts */, {} /* client features */); @@ -951,7 +980,7 @@ PredictionModelFetcherEndState::kFetchFailed)); prediction_manager()->RegisterOptimizationTargets( - {proto::OPTIMIZATION_TARGET_PAINFUL_PAGE_LOAD}); + {{proto::OPTIMIZATION_TARGET_PAINFUL_PAGE_LOAD, base::nullopt}}); // Seed the PredictionManager with a prediction model with a higher version // to try to be updated. @@ -996,7 +1025,8 @@ FakeOptimizationTargetModelObserver observer; prediction_manager()->AddObserverForOptimizationTargetModel( - proto::OPTIMIZATION_TARGET_PAINFUL_PAGE_LOAD, &observer); + proto::OPTIMIZATION_TARGET_PAINFUL_PAGE_LOAD, + /*model_metadata=*/base::nullopt, &observer); proto::PredictionModel model; model.mutable_model_info()->set_optimization_target( @@ -1007,7 +1037,7 @@ RunUntilIdle(); EXPECT_TRUE(observer - .last_received_path_for_target( + .last_received_model_for_target( proto::OPTIMIZATION_TARGET_PAINFUL_PAGE_LOAD) .has_value()); @@ -1019,7 +1049,7 @@ // The observer should not have received an update. EXPECT_FALSE(observer - .last_received_path_for_target( + .last_received_model_for_target( proto::OPTIMIZATION_TARGET_PAINFUL_PAGE_LOAD) .has_value()); @@ -1044,7 +1074,7 @@ kFetchSuccessWithModelsAndHostsModelFeatures)); prediction_manager()->RegisterOptimizationTargets( - {proto::OPTIMIZATION_TARGET_PAINFUL_PAGE_LOAD}); + {{proto::OPTIMIZATION_TARGET_PAINFUL_PAGE_LOAD, base::nullopt}}); SetStoreInitialized(); EXPECT_TRUE(prediction_model_fetcher()->models_fetched()); @@ -1088,7 +1118,7 @@ kFetchSuccessWithModelsAndHostsModelFeatures)); prediction_manager()->RegisterOptimizationTargets( - {proto::OPTIMIZATION_TARGET_PAINFUL_PAGE_LOAD}); + {{proto::OPTIMIZATION_TARGET_PAINFUL_PAGE_LOAD, base::nullopt}}); SetStoreInitialized(); EXPECT_TRUE(prediction_model_fetcher()->models_fetched()); @@ -1133,7 +1163,7 @@ kFetchSuccessWithModelsAndHostsModelFeatures)); prediction_manager()->RegisterOptimizationTargets( - {proto::OPTIMIZATION_TARGET_PAINFUL_PAGE_LOAD}); + {{proto::OPTIMIZATION_TARGET_PAINFUL_PAGE_LOAD, base::nullopt}}); SetStoreInitialized(); EXPECT_TRUE(prediction_model_fetcher()->models_fetched()); @@ -1178,7 +1208,7 @@ prediction_model_download_manager()->SetAvailableForDownloads(false); prediction_manager()->RegisterOptimizationTargets( - {proto::OPTIMIZATION_TARGET_PAINFUL_PAGE_LOAD}); + {{proto::OPTIMIZATION_TARGET_PAINFUL_PAGE_LOAD, base::nullopt}}); SetStoreInitialized(); EXPECT_FALSE(prediction_model_fetcher()->models_fetched()); @@ -1207,7 +1237,7 @@ task_environment()->GetMainThreadTaskRunner())); prediction_manager()->RegisterOptimizationTargets( - {proto::OPTIMIZATION_TARGET_PAINFUL_PAGE_LOAD}); + {{proto::OPTIMIZATION_TARGET_PAINFUL_PAGE_LOAD, base::nullopt}}); SetStoreInitialized(); EXPECT_TRUE(prediction_model_fetcher()->models_fetched()); @@ -1245,7 +1275,7 @@ kFetchSuccessWithModelsAndHostsModelFeatures)); prediction_manager()->RegisterOptimizationTargets( - {proto::OPTIMIZATION_TARGET_PAINFUL_PAGE_LOAD}); + {{proto::OPTIMIZATION_TARGET_PAINFUL_PAGE_LOAD, base::nullopt}}); SetStoreInitialized(); EXPECT_TRUE(prediction_model_fetcher()->models_fetched()); @@ -1305,7 +1335,7 @@ kFetchSuccessWithModelsAndHostsModelFeatures)); prediction_manager()->RegisterOptimizationTargets( - {proto::OPTIMIZATION_TARGET_PAINFUL_PAGE_LOAD}); + {{proto::OPTIMIZATION_TARGET_PAINFUL_PAGE_LOAD, base::nullopt}}); SetStoreInitialized(); EXPECT_TRUE(prediction_model_fetcher()->models_fetched()); @@ -1357,7 +1387,7 @@ PredictionModelFetcherEndState::kFetchSuccessWithEmptyResponse)); prediction_manager()->RegisterOptimizationTargets( - {proto::OPTIMIZATION_TARGET_PAINFUL_PAGE_LOAD}); + {{proto::OPTIMIZATION_TARGET_PAINFUL_PAGE_LOAD, base::nullopt}}); SetStoreInitialized(/* load_models= */ false, /* load_host_model_features= */ true, @@ -1394,7 +1424,7 @@ PredictionModelFetcherEndState::kFetchSuccessWithEmptyResponse)); prediction_manager()->RegisterOptimizationTargets( - {proto::OPTIMIZATION_TARGET_PAINFUL_PAGE_LOAD}); + {{proto::OPTIMIZATION_TARGET_PAINFUL_PAGE_LOAD, base::nullopt}}); SetStoreInitialized(/* load_models= */ false, /* load_host_model_features= */ true, @@ -1434,13 +1464,12 @@ PredictionModelFetcherEndState::kFetchSuccessWithEmptyResponse)); prediction_manager()->RegisterOptimizationTargets( - {proto::OPTIMIZATION_TARGET_PAINFUL_PAGE_LOAD}); + {{proto::OPTIMIZATION_TARGET_PAINFUL_PAGE_LOAD, base::nullopt}}); - - EXPECT_EQ(OptimizationTargetDecision::kModelNotAvailableOnClient, - prediction_manager()->ShouldTargetNavigation( - navigation_handle.get(), - proto::OPTIMIZATION_TARGET_PAINFUL_PAGE_LOAD, {})); + EXPECT_EQ(OptimizationTargetDecision::kModelNotAvailableOnClient, + prediction_manager()->ShouldTargetNavigation( + navigation_handle.get(), + proto::OPTIMIZATION_TARGET_PAINFUL_PAGE_LOAD, {})); histogram_tester.ExpectBucketCount( "OptimizationGuide.ShouldTargetNavigation.PredictionModelStatus", @@ -1526,7 +1555,7 @@ CreatePredictionManager(); prediction_manager()->RegisterOptimizationTargets( - {proto::OPTIMIZATION_TARGET_PAINFUL_PAGE_LOAD}); + {{proto::OPTIMIZATION_TARGET_PAINFUL_PAGE_LOAD, base::nullopt}}); SetStoreInitialized(); histogram_tester.ExpectUniqueSample( "OptimizationGuide.PredictionModelLoadedVersion.PainfulPageLoad", 1, 1); @@ -1575,7 +1604,7 @@ PredictionModelFetcherEndState::kFetchFailed)); prediction_manager()->RegisterOptimizationTargets( - {proto::OPTIMIZATION_TARGET_PAINFUL_PAGE_LOAD}); + {{proto::OPTIMIZATION_TARGET_PAINFUL_PAGE_LOAD, base::nullopt}}); EXPECT_FALSE(prediction_model_fetcher()->models_fetched()); EXPECT_FALSE(models_and_features_store()->WasModelLoaded()); @@ -1613,7 +1642,7 @@ PredictionModelFetcherEndState::kFetchFailed)); prediction_manager()->RegisterOptimizationTargets( - {proto::OPTIMIZATION_TARGET_PAINFUL_PAGE_LOAD}); + {{proto::OPTIMIZATION_TARGET_PAINFUL_PAGE_LOAD, base::nullopt}}); SetStoreInitialized(); std::unique_ptr<proto::GetModelsResponse> get_models_response = @@ -1650,7 +1679,7 @@ PredictionModelFetcherEndState::kFetchFailed)); prediction_manager()->RegisterOptimizationTargets( - {proto::OPTIMIZATION_TARGET_PAINFUL_PAGE_LOAD}); + {{proto::OPTIMIZATION_TARGET_PAINFUL_PAGE_LOAD, base::nullopt}}); SetStoreInitialized(); @@ -1687,7 +1716,7 @@ PredictionModelFetcherEndState::kFetchFailed)); prediction_manager()->RegisterOptimizationTargets( - {proto::OPTIMIZATION_TARGET_PAINFUL_PAGE_LOAD}); + {{proto::OPTIMIZATION_TARGET_PAINFUL_PAGE_LOAD, base::nullopt}}); SetStoreInitialized(); @@ -1714,7 +1743,7 @@ PredictionModelFetcherEndState::kFetchFailed)); prediction_manager()->RegisterOptimizationTargets( - {proto::OPTIMIZATION_TARGET_PAINFUL_PAGE_LOAD}); + {{proto::OPTIMIZATION_TARGET_PAINFUL_PAGE_LOAD, base::nullopt}}); SetStoreInitialized(); std::unique_ptr<proto::GetModelsResponse> get_models_response = @@ -1740,7 +1769,7 @@ PredictionModelFetcherEndState::kFetchFailed)); prediction_manager()->RegisterOptimizationTargets( - {proto::OPTIMIZATION_TARGET_PAINFUL_PAGE_LOAD}); + {{proto::OPTIMIZATION_TARGET_PAINFUL_PAGE_LOAD, base::nullopt}}); SetStoreInitialized(); @@ -1769,7 +1798,7 @@ PredictionModelFetcherEndState::kFetchFailed)); prediction_manager()->RegisterOptimizationTargets( - {proto::OPTIMIZATION_TARGET_PAINFUL_PAGE_LOAD}); + {{proto::OPTIMIZATION_TARGET_PAINFUL_PAGE_LOAD, base::nullopt}}); SetStoreInitialized(); std::unique_ptr<proto::GetModelsResponse> get_models_response = @@ -1797,7 +1826,7 @@ PredictionModelFetcherEndState::kFetchFailed)); prediction_manager()->RegisterOptimizationTargets( - {proto::OPTIMIZATION_TARGET_PAINFUL_PAGE_LOAD}); + {{proto::OPTIMIZATION_TARGET_PAINFUL_PAGE_LOAD, base::nullopt}}); SetStoreInitialized(); std::unique_ptr<proto::GetModelsResponse> get_models_response = @@ -1827,7 +1856,7 @@ PredictionModelFetcherEndState::kFetchFailed)); prediction_manager()->RegisterOptimizationTargets( - {proto::OPTIMIZATION_TARGET_PAINFUL_PAGE_LOAD}); + {{proto::OPTIMIZATION_TARGET_PAINFUL_PAGE_LOAD, base::nullopt}}); SetStoreInitialized(); std::vector<std::string> hosts; @@ -1858,7 +1887,7 @@ kFetchSuccessWithModelsAndHostsModelFeatures)); prediction_manager()->RegisterOptimizationTargets( - {proto::OPTIMIZATION_TARGET_PAINFUL_PAGE_LOAD}); + {{proto::OPTIMIZATION_TARGET_PAINFUL_PAGE_LOAD, base::nullopt}}); SetStoreInitialized(); @@ -1881,7 +1910,7 @@ PredictionModelFetcherEndState::kFetchFailed)); prediction_manager()->RegisterOptimizationTargets( - {proto::OPTIMIZATION_TARGET_PAINFUL_PAGE_LOAD}); + {{proto::OPTIMIZATION_TARGET_PAINFUL_PAGE_LOAD, base::nullopt}}); SetStoreInitialized(); std::unique_ptr<proto::GetModelsResponse> get_models_response = @@ -1960,7 +1989,7 @@ PredictionModelFetcherEndState::kFetchFailed)); prediction_manager()->RegisterOptimizationTargets( - {proto::OPTIMIZATION_TARGET_PAINFUL_PAGE_LOAD}); + {{proto::OPTIMIZATION_TARGET_PAINFUL_PAGE_LOAD, base::nullopt}}); SetStoreInitialized(); @@ -2017,7 +2046,7 @@ PredictionModelFetcherEndState::kFetchFailed)); prediction_manager()->RegisterOptimizationTargets( - {proto::OPTIMIZATION_TARGET_PAINFUL_PAGE_LOAD}); + {{proto::OPTIMIZATION_TARGET_PAINFUL_PAGE_LOAD, base::nullopt}}); SetStoreInitialized(); @@ -2086,7 +2115,7 @@ PredictionModelFetcherEndState::kFetchFailed)); prediction_manager()->RegisterOptimizationTargets( - {proto::OPTIMIZATION_TARGET_PAINFUL_PAGE_LOAD}); + {{proto::OPTIMIZATION_TARGET_PAINFUL_PAGE_LOAD, base::nullopt}}); SetStoreInitialized(); @@ -2151,7 +2180,7 @@ BuildTestPredictionModelFetcher( PredictionModelFetcherEndState::kFetchFailed)); prediction_manager()->RegisterOptimizationTargets( - {proto::OPTIMIZATION_TARGET_PAINFUL_PAGE_LOAD}); + {{proto::OPTIMIZATION_TARGET_PAINFUL_PAGE_LOAD, base::nullopt}}); EXPECT_FALSE(models_and_features_store()->WasHostModelFeaturesLoaded()); EXPECT_FALSE(models_and_features_store()->WasModelLoaded()); EXPECT_FALSE(prediction_manager()->GetHostModelFeaturesForHost("foo.com")); @@ -2183,7 +2212,7 @@ EXPECT_FALSE(models_and_features_store()->WasModelLoaded()); EXPECT_FALSE(prediction_manager()->GetHostModelFeaturesForHost("foo.com")); prediction_manager()->RegisterOptimizationTargets( - {proto::OPTIMIZATION_TARGET_PAINFUL_PAGE_LOAD}); + {{proto::OPTIMIZATION_TARGET_PAINFUL_PAGE_LOAD, base::nullopt}}); RunUntilIdle(); EXPECT_TRUE(models_and_features_store()->WasHostModelFeaturesLoaded()); @@ -2208,7 +2237,7 @@ PredictionModelFetcherEndState::kFetchFailed)); prediction_manager()->RegisterOptimizationTargets( - {proto::OPTIMIZATION_TARGET_PAINFUL_PAGE_LOAD}); + {{proto::OPTIMIZATION_TARGET_PAINFUL_PAGE_LOAD, base::nullopt}}); SetStoreInitialized(); EXPECT_FALSE(prediction_model_fetcher()->models_fetched()); @@ -2239,7 +2268,7 @@ kFetchSuccessWithModelsAndHostsModelFeatures)); prediction_manager()->RegisterOptimizationTargets( - {proto::OPTIMIZATION_TARGET_PAINFUL_PAGE_LOAD}); + {{proto::OPTIMIZATION_TARGET_PAINFUL_PAGE_LOAD, base::nullopt}}); SetStoreInitialized(); EXPECT_FALSE(prediction_model_fetcher()->models_fetched());
diff --git a/chrome/browser/pdf/pdf_extension_test.cc b/chrome/browser/pdf/pdf_extension_test.cc index 6abdb3c..2228548 100644 --- a/chrome/browser/pdf/pdf_extension_test.cc +++ b/chrome/browser/pdf/pdf_extension_test.cc
@@ -1471,9 +1471,8 @@ WebContents* guest_contents = nullptr; content::BrowserPluginGuestManager* guest_manager = contents->GetBrowserContext()->GetGuestManager(); - guest_manager->ForEachGuest(contents, - base::Bind(&RetrieveGuestContents, - &guest_contents)); + guest_manager->ForEachGuest( + contents, base::BindRepeating(&RetrieveGuestContents, &guest_contents)); ASSERT_TRUE(guest_contents); ui::AXTreeUpdate ax_tree = GetAccessibilityTreeSnapshot(guest_contents); @@ -1493,9 +1492,8 @@ WebContents* guest_contents = nullptr; content::BrowserPluginGuestManager* guest_manager = contents->GetBrowserContext()->GetGuestManager(); - guest_manager->ForEachGuest(contents, - base::Bind(&RetrieveGuestContents, - &guest_contents)); + guest_manager->ForEachGuest( + contents, base::BindRepeating(&RetrieveGuestContents, &guest_contents)); ASSERT_TRUE(guest_contents); ui::AXTreeUpdate ax_tree = GetAccessibilityTreeSnapshot(guest_contents); @@ -2477,7 +2475,8 @@ content::BrowserPluginGuestManager* guest_manager = embedder_contents->GetBrowserContext()->GetGuestManager(); ASSERT_NO_FATAL_FAILURE(guest_manager->ForEachGuest( - embedder_contents, base::Bind(&GetGuestCallback, &guest_contents))); + embedder_contents, + base::BindRepeating(&GetGuestCallback, &guest_contents))); ASSERT_NE(nullptr, guest_contents); content::WaitForHitTestData(guest_contents); @@ -2530,7 +2529,8 @@ content::BrowserPluginGuestManager* guest_manager = embedder_contents->GetBrowserContext()->GetGuestManager(); ASSERT_NO_FATAL_FAILURE(guest_manager->ForEachGuest( - embedder_contents, base::Bind(&GetGuestCallback, &guest_contents))); + embedder_contents, + base::BindRepeating(&GetGuestCallback, &guest_contents))); ASSERT_NE(nullptr, guest_contents); content::WaitForHitTestData(guest_contents);
diff --git a/chrome/browser/policy/chrome_browser_policy_connector.cc b/chrome/browser/policy/chrome_browser_policy_connector.cc index 68551a2..7770ca2 100644 --- a/chrome/browser/policy/chrome_browser_policy_connector.cc +++ b/chrome/browser/policy/chrome_browser_policy_connector.cc
@@ -73,7 +73,7 @@ } // namespace ChromeBrowserPolicyConnector::ChromeBrowserPolicyConnector() - : BrowserPolicyConnector(base::Bind(&BuildHandlerList)) { + : BrowserPolicyConnector(base::BindRepeating(&BuildHandlerList)) { #if !defined(OS_ANDROID) && !BUILDFLAG(IS_CHROMEOS_ASH) chrome_browser_cloud_management_controller_ = std::make_unique<ChromeBrowserCloudManagementController>(
diff --git a/chrome/browser/policy/cloud/cloud_policy_browsertest.cc b/chrome/browser/policy/cloud/cloud_policy_browsertest.cc index 7e17e098..c92f21ba 100644 --- a/chrome/browser/policy/cloud/cloud_policy_browsertest.cc +++ b/chrome/browser/policy/cloud/cloud_policy_browsertest.cc
@@ -323,8 +323,7 @@ const PolicyMap& previous, const PolicyMap& current) override { if (!on_policy_updated_.is_null()) { - on_policy_updated_.Run(); - on_policy_updated_.Reset(); + std::move(on_policy_updated_).Run(); } } @@ -333,7 +332,7 @@ base::ScopedTempDir temp_dir_; std::unique_ptr<LocalPolicyTestServer> test_server_; base::FilePath user_policy_key_file_; - base::Closure on_policy_updated_; + base::OnceClosure on_policy_updated_; }; IN_PROC_BROWSER_TEST_F(CloudPolicyTest, FetchPolicy) {
diff --git a/chrome/browser/policy/cloud/device_management_service_browsertest.cc b/chrome/browser/policy/cloud/device_management_service_browsertest.cc index 8216f87a..a6533ff 100644 --- a/chrome/browser/policy/cloud/device_management_service_browsertest.cc +++ b/chrome/browser/policy/cloud/device_management_service_browsertest.cc
@@ -139,8 +139,8 @@ std::make_unique<FakeJobConfiguration>( service_.get(), type, kClientID, critical, std::move(auth_data), oauth_token, GetFactory(), - base::Bind(&DeviceManagementServiceIntegrationTest::OnJobDone, - base::Unretained(this)), + base::BindOnce(&DeviceManagementServiceIntegrationTest::OnJobDone, + base::Unretained(this)), base::DoNothing(), base::DoNothing()); config->SetRequestPayload(payload); return service_->CreateJob(std::move(config));
diff --git a/chrome/browser/policy/configuration_policy_handler_list_factory.cc b/chrome/browser/policy/configuration_policy_handler_list_factory.cc index 7b4eae5d..30ff1224 100644 --- a/chrome/browser/policy/configuration_policy_handler_list_factory.cc +++ b/chrome/browser/policy/configuration_policy_handler_list_factory.cc
@@ -1381,8 +1381,9 @@ const Schema& chrome_schema) { std::unique_ptr<ConfigurationPolicyHandlerList> handlers( new ConfigurationPolicyHandlerList( - base::Bind(&PopulatePolicyHandlerParameters), - base::Bind(&GetChromePolicyDetails), AreFuturePoliciesSupported())); + base::BindRepeating(&PopulatePolicyHandlerParameters), + base::BindRepeating(&GetChromePolicyDetails), + AreFuturePoliciesSupported())); for (size_t i = 0; i < base::size(kSimplePolicyMap); ++i) { handlers->AddHandler(std::make_unique<SimplePolicyHandler>( kSimplePolicyMap[i].policy_name, kSimplePolicyMap[i].preference_path, @@ -1903,7 +1904,7 @@ extensions::pref_names::kAllowedInstallSites)); handlers->AddHandler(std::make_unique<StringMappingListPolicyHandler>( key::kExtensionAllowedTypes, extensions::pref_names::kAllowedTypes, - base::Bind(GetExtensionAllowedTypesMap))); + base::BindRepeating(GetExtensionAllowedTypesMap))); handlers->AddHandler( std::make_unique<extensions::ExtensionSettingsPolicyHandler>( chrome_schema));
diff --git a/chrome/browser/policy/extension_policy_browsertest.cc b/chrome/browser/policy/extension_policy_browsertest.cc index 8893af1..19b8408 100644 --- a/chrome/browser/policy/extension_policy_browsertest.cc +++ b/chrome/browser/policy/extension_policy_browsertest.cc
@@ -87,12 +87,12 @@ // Called when an additional profile has been created. // The created profile is stored in *|out_created_profile|. void OnProfileInitialized(Profile** out_created_profile, - const base::Closure& closure, + base::RunLoop* run_loop, Profile* profile, Profile::CreateStatus status) { if (status == Profile::CREATE_STATUS_INITIALIZED) { *out_created_profile = profile; - closure.Run(); + run_loop->Quit(); } } namespace { @@ -149,7 +149,7 @@ void RegisterURLReplacingHandler(net::EmbeddedTestServer* test_server, const std::string& match_path, const base::FilePath& template_file) { - test_server->RegisterRequestHandler(base::Bind( + test_server->RegisterRequestHandler(base::BindRepeating( [](net::EmbeddedTestServer* test_server, const std::string& match_path, const base::FilePath& template_file, const net::test_server::HttpRequest& request) @@ -2175,8 +2175,7 @@ base::RunLoop run_loop; profile_manager->CreateProfileAsync( path_profile, - base::BindRepeating(&policy::OnProfileInitialized, &profile, - run_loop.QuitClosure()), + base::BindRepeating(&policy::OnProfileInitialized, &profile, &run_loop), base::string16(), std::string()); // Run the message loop to allow profile creation to take place; the loop is
diff --git a/chrome/browser/policy/messaging_layer/public/mock_report_queue.h b/chrome/browser/policy/messaging_layer/public/mock_report_queue.h index 088a534..d991f30 100644 --- a/chrome/browser/policy/messaging_layer/public/mock_report_queue.h +++ b/chrome/browser/policy/messaging_layer/public/mock_report_queue.h
@@ -8,8 +8,8 @@ #include "base/callback.h" #include "base/values.h" #include "chrome/browser/policy/messaging_layer/public/report_queue.h" -#include "chrome/browser/policy/messaging_layer/util/status.h" -#include "components/policy/proto/record.pb.h" +#include "components/reporting/proto/record.pb.h" +#include "components/reporting/util/status.h" #include "testing/gmock/include/gmock/gmock.h" #include "third_party/protobuf/src/google/protobuf/message_lite.h"
diff --git a/chrome/browser/policy/messaging_layer/public/report_client.cc b/chrome/browser/policy/messaging_layer/public/report_client.cc index bf0bc262..44c1bc3 100644 --- a/chrome/browser/policy/messaging_layer/public/report_client.cc +++ b/chrome/browser/policy/messaging_layer/public/report_client.cc
@@ -19,18 +19,27 @@ #include "base/task/post_task.h" #include "build/chromeos_buildflags.h" #include "chrome/browser/net/system_network_context_manager.h" -#include "chrome/browser/policy/messaging_layer/encryption/verification.h" #include "chrome/browser/policy/messaging_layer/public/report_queue.h" #include "chrome/browser/policy/messaging_layer/public/report_queue_configuration.h" -#include "chrome/browser/policy/messaging_layer/storage/storage_configuration.h" -#include "chrome/browser/policy/messaging_layer/storage/storage_module.h" #include "chrome/browser/policy/messaging_layer/util/get_cloud_policy_client.h" -#include "chrome/browser/policy/messaging_layer/util/status.h" -#include "chrome/browser/policy/messaging_layer/util/status_macros.h" -#include "chrome/browser/policy/messaging_layer/util/statusor.h" -#include "chrome/browser/policy/messaging_layer/util/task_runner_context.h" +#include "chrome/browser/profiles/profile_manager.h" +#include "chrome/browser/signin/identity_manager_factory.h" #include "chrome/common/chrome_paths.h" -#include "components/policy/proto/record.pb.h" +#include "components/enterprise/browser/controller/browser_dm_token_storage.h" +#include "components/policy/core/common/cloud/cloud_policy_client_registration_helper.h" +#include "components/policy/core/common/cloud/cloud_policy_manager.h" +#include "components/policy/core/common/cloud/device_management_service.h" +#include "components/policy/core/common/cloud/machine_level_user_cloud_policy_manager.h" +#include "components/policy/core/common/cloud/user_cloud_policy_manager.h" +#include "components/reporting/encryption/verification.h" +#include "components/reporting/proto/record.pb.h" +#include "components/reporting/storage/storage_configuration.h" +#include "components/reporting/storage/storage_module.h" +#include "components/reporting/util/status.h" +#include "components/reporting/util/status_macros.h" +#include "components/reporting/util/statusor.h" +#include "components/reporting/util/task_runner_context.h" +#include "components/signin/public/identity_manager/identity_manager.h" #include "content/public/browser/browser_task_traits.h" #include "content/public/browser/browser_thread.h"
diff --git a/chrome/browser/policy/messaging_layer/public/report_client.h b/chrome/browser/policy/messaging_layer/public/report_client.h index aae3452..a724f45c 100644 --- a/chrome/browser/policy/messaging_layer/public/report_client.h +++ b/chrome/browser/policy/messaging_layer/public/report_client.h
@@ -13,12 +13,12 @@ #include "base/memory/singleton.h" #include "chrome/browser/policy/messaging_layer/public/report_queue.h" #include "chrome/browser/policy/messaging_layer/public/report_queue_configuration.h" -#include "chrome/browser/policy/messaging_layer/storage/storage_module.h" #include "chrome/browser/policy/messaging_layer/upload/upload_client.h" -#include "chrome/browser/policy/messaging_layer/util/shared_queue.h" -#include "chrome/browser/policy/messaging_layer/util/statusor.h" -#include "chrome/browser/policy/messaging_layer/util/task_runner_context.h" -#include "components/policy/proto/record.pb.h" +#include "components/reporting//proto/record.pb.h" +#include "components/reporting/storage/storage_module.h" +#include "components/reporting/util/shared_queue.h" +#include "components/reporting/util/statusor.h" +#include "components/reporting/util/task_runner_context.h" namespace reporting {
diff --git a/chrome/browser/policy/messaging_layer/public/report_client_unittest.cc b/chrome/browser/policy/messaging_layer/public/report_client_unittest.cc index 1df510fc0..4c3ef9a 100644 --- a/chrome/browser/policy/messaging_layer/public/report_client_unittest.cc +++ b/chrome/browser/policy/messaging_layer/public/report_client_unittest.cc
@@ -13,12 +13,12 @@ #include "build/chromeos_buildflags.h" #include "chrome/browser/policy/messaging_layer/public/report_queue.h" #include "chrome/browser/policy/messaging_layer/public/report_queue_configuration.h" -#include "chrome/browser/policy/messaging_layer/util/status.h" -#include "chrome/browser/policy/messaging_layer/util/status_macros.h" -#include "chrome/browser/policy/messaging_layer/util/statusor.h" #include "components/policy/core/common/cloud/dm_token.h" #include "components/policy/core/common/cloud/mock_cloud_policy_client.h" -#include "components/policy/proto/record_constants.pb.h" +#include "components/reporting/proto/record_constants.pb.h" +#include "components/reporting/util/status.h" +#include "components/reporting/util/status_macros.h" +#include "components/reporting/util/statusor.h" #include "content/public/browser/browser_task_traits.h" #include "content/public/browser/browser_thread.h" #include "content/public/test/browser_task_environment.h"
diff --git a/chrome/browser/policy/messaging_layer/public/report_queue.cc b/chrome/browser/policy/messaging_layer/public/report_queue.cc index a9e1ec0..ababa09 100644 --- a/chrome/browser/policy/messaging_layer/public/report_queue.cc +++ b/chrome/browser/policy/messaging_layer/public/report_queue.cc
@@ -20,15 +20,15 @@ #include "base/task/thread_pool.h" #include "base/time/time.h" #include "base/values.h" -#include "chrome/browser/policy/messaging_layer/encryption/encryption_module.h" #include "chrome/browser/policy/messaging_layer/public/report_queue_configuration.h" -#include "chrome/browser/policy/messaging_layer/storage/storage_module.h" -#include "chrome/browser/policy/messaging_layer/util/status.h" -#include "chrome/browser/policy/messaging_layer/util/status_macros.h" -#include "chrome/browser/policy/messaging_layer/util/statusor.h" #include "components/policy/core/common/cloud/dm_token.h" -#include "components/policy/proto/record.pb.h" -#include "components/policy/proto/record_constants.pb.h" +#include "components/reporting/encryption/encryption_module.h" +#include "components/reporting/proto/record.pb.h" +#include "components/reporting/proto/record_constants.pb.h" +#include "components/reporting/storage/storage_module.h" +#include "components/reporting/util/status.h" +#include "components/reporting/util/status_macros.h" +#include "components/reporting/util/statusor.h" namespace reporting {
diff --git a/chrome/browser/policy/messaging_layer/public/report_queue.h b/chrome/browser/policy/messaging_layer/public/report_queue.h index 5ac95a8..d77025c 100644 --- a/chrome/browser/policy/messaging_layer/public/report_queue.h +++ b/chrome/browser/policy/messaging_layer/public/report_queue.h
@@ -16,11 +16,11 @@ #include "base/sequenced_task_runner.h" #include "base/values.h" #include "chrome/browser/policy/messaging_layer/public/report_queue_configuration.h" -#include "chrome/browser/policy/messaging_layer/storage/storage_module.h" -#include "chrome/browser/policy/messaging_layer/util/status.h" -#include "chrome/browser/policy/messaging_layer/util/statusor.h" -#include "components/policy/proto/record.pb.h" -#include "components/policy/proto/record_constants.pb.h" +#include "components/reporting/proto/record.pb.h" +#include "components/reporting/proto/record_constants.pb.h" +#include "components/reporting/storage/storage_module.h" +#include "components/reporting/util/status.h" +#include "components/reporting/util/statusor.h" #include "third_party/protobuf/src/google/protobuf/message_lite.h" namespace reporting {
diff --git a/chrome/browser/policy/messaging_layer/public/report_queue_configuration.cc b/chrome/browser/policy/messaging_layer/public/report_queue_configuration.cc index bac77ef..0520e2e 100644 --- a/chrome/browser/policy/messaging_layer/public/report_queue_configuration.cc +++ b/chrome/browser/policy/messaging_layer/public/report_queue_configuration.cc
@@ -8,11 +8,11 @@ #include "base/bind.h" #include "base/memory/ptr_util.h" -#include "chrome/browser/policy/messaging_layer/util/status.h" -#include "chrome/browser/policy/messaging_layer/util/status_macros.h" -#include "chrome/browser/policy/messaging_layer/util/statusor.h" #include "components/policy/core/common/cloud/dm_token.h" -#include "components/policy/proto/record_constants.pb.h" +#include "components/reporting/proto/record_constants.pb.h" +#include "components/reporting/util/status.h" +#include "components/reporting/util/status_macros.h" +#include "components/reporting/util/statusor.h" namespace reporting {
diff --git a/chrome/browser/policy/messaging_layer/public/report_queue_configuration.h b/chrome/browser/policy/messaging_layer/public/report_queue_configuration.h index f6aca45..a6b9aef 100644 --- a/chrome/browser/policy/messaging_layer/public/report_queue_configuration.h +++ b/chrome/browser/policy/messaging_layer/public/report_queue_configuration.h
@@ -9,10 +9,10 @@ #include <utility> #include "base/callback.h" -#include "chrome/browser/policy/messaging_layer/util/status.h" -#include "chrome/browser/policy/messaging_layer/util/statusor.h" #include "components/policy/core/common/cloud/dm_token.h" -#include "components/policy/proto/record_constants.pb.h" +#include "components/reporting/proto/record_constants.pb.h" +#include "components/reporting/util/status.h" +#include "components/reporting/util/statusor.h" namespace reporting {
diff --git a/chrome/browser/policy/messaging_layer/public/report_queue_configuration_unittest.cc b/chrome/browser/policy/messaging_layer/public/report_queue_configuration_unittest.cc index 419d0bba..c43094d 100644 --- a/chrome/browser/policy/messaging_layer/public/report_queue_configuration_unittest.cc +++ b/chrome/browser/policy/messaging_layer/public/report_queue_configuration_unittest.cc
@@ -8,9 +8,9 @@ #include "base/bind.h" #include "base/callback.h" -#include "chrome/browser/policy/messaging_layer/util/statusor.h" #include "components/policy/core/common/cloud/dm_token.h" -#include "components/policy/proto/record_constants.pb.h" +#include "components/reporting/proto/record_constants.pb.h" +#include "components/reporting/util/statusor.h" #include "testing/gmock/include/gmock/gmock.h" #include "testing/gtest/include/gtest/gtest.h"
diff --git a/chrome/browser/policy/messaging_layer/public/report_queue_unittest.cc b/chrome/browser/policy/messaging_layer/public/report_queue_unittest.cc index a15c5ed..abf0397 100644 --- a/chrome/browser/policy/messaging_layer/public/report_queue_unittest.cc +++ b/chrome/browser/policy/messaging_layer/public/report_queue_unittest.cc
@@ -17,13 +17,13 @@ #include "base/values.h" #include "chrome/browser/policy/messaging_layer/proto/test.pb.h" #include "chrome/browser/policy/messaging_layer/public/report_queue_configuration.h" -#include "chrome/browser/policy/messaging_layer/storage/storage_module.h" -#include "chrome/browser/policy/messaging_layer/storage/test_storage_module.h" -#include "chrome/browser/policy/messaging_layer/util/status.h" -#include "chrome/browser/policy/messaging_layer/util/status_macros.h" -#include "chrome/browser/policy/messaging_layer/util/statusor.h" #include "components/policy/core/common/cloud/dm_token.h" -#include "components/policy/proto/record_constants.pb.h" +#include "components/reporting/proto/record_constants.pb.h" +#include "components/reporting/storage/storage_module.h" +#include "components/reporting/storage/test_storage_module.h" +#include "components/reporting/util/status.h" +#include "components/reporting/util/status_macros.h" +#include "components/reporting/util/statusor.h" #include "content/public/test/browser_task_environment.h" #include "testing/gmock/include/gmock/gmock.h" #include "testing/gtest/include/gtest/gtest.h"
diff --git a/chrome/browser/policy/messaging_layer/upload/dm_server_upload_service.cc b/chrome/browser/policy/messaging_layer/upload/dm_server_upload_service.cc index f422a30..3641661 100644 --- a/chrome/browser/policy/messaging_layer/upload/dm_server_upload_service.cc +++ b/chrome/browser/policy/messaging_layer/upload/dm_server_upload_service.cc
@@ -11,17 +11,16 @@ #include "base/task/post_task.h" #include "base/task_runner.h" #include "chrome/browser/policy/messaging_layer/upload/record_handler_impl.h" -#include "chrome/browser/policy/messaging_layer/util/backoff_settings.h" -#include "chrome/browser/policy/messaging_layer/util/status.h" -#include "chrome/browser/policy/messaging_layer/util/status_macros.h" -#include "chrome/browser/policy/messaging_layer/util/statusor.h" -#include "chrome/browser/policy/messaging_layer/util/task_runner_context.h" #include "chrome/browser/profiles/profile.h" #include "chrome/browser/profiles/profile_manager.h" #include "components/policy/core/common/cloud/cloud_policy_client.h" #include "components/policy/core/common/cloud/user_cloud_policy_manager.h" -#include "components/policy/proto/record.pb.h" -#include "components/policy/proto/record_constants.pb.h" +#include "components/reporting/proto/record.pb.h" +#include "components/reporting/proto/record_constants.pb.h" +#include "components/reporting/util/status.h" +#include "components/reporting/util/status_macros.h" +#include "components/reporting/util/statusor.h" +#include "components/reporting/util/task_runner_context.h" #include "content/public/browser/browser_task_traits.h" #include "content/public/browser/browser_thread.h" @@ -223,13 +222,14 @@ } void DmServerUploadService::UploadCompletion( - StatusOr<SequencingInformation> upload_result) const { + CompletionResponse upload_result) const { if (!upload_result.ok()) { LOG(WARNING) << upload_result.status(); return; } - upload_cb_.Run(upload_result.ValueOrDie()); + upload_cb_.Run(upload_result.ValueOrDie().sequencing_information, + upload_result.ValueOrDie().force_confirm); } CloudPolicyClient* DmServerUploadService::GetClient() {
diff --git a/chrome/browser/policy/messaging_layer/upload/dm_server_upload_service.h b/chrome/browser/policy/messaging_layer/upload/dm_server_upload_service.h index de3f296..87bf7c6 100644 --- a/chrome/browser/policy/messaging_layer/upload/dm_server_upload_service.h +++ b/chrome/browser/policy/messaging_layer/upload/dm_server_upload_service.h
@@ -13,13 +13,13 @@ #include "base/task_runner.h" #include "build/build_config.h" #include "build/chromeos_buildflags.h" -#include "chrome/browser/policy/messaging_layer/util/status.h" -#include "chrome/browser/policy/messaging_layer/util/status_macros.h" -#include "chrome/browser/policy/messaging_layer/util/statusor.h" -#include "chrome/browser/policy/messaging_layer/util/task_runner_context.h" #include "components/policy/core/common/cloud/cloud_policy_client.h" -#include "components/policy/proto/record.pb.h" -#include "components/policy/proto/record_constants.pb.h" +#include "components/reporting/proto/record.pb.h" +#include "components/reporting/proto/record_constants.pb.h" +#include "components/reporting/util/status.h" +#include "components/reporting/util/status_macros.h" +#include "components/reporting/util/statusor.h" +#include "components/reporting/util/task_runner_context.h" #include "net/base/backoff_entry.h" #if BUILDFLAG(IS_CHROMEOS_ASH) @@ -40,16 +40,24 @@ class DmServerUploadService { public: // ReportSuccessfulUploadCallback is used to pass server responses back to - // the owner of |this|. + // the owner of |this| (the respone consists of sequencing information and + // force_confirm flag). using ReportSuccessfulUploadCallback = - base::RepeatingCallback<void(SequencingInformation)>; + base::RepeatingCallback<void(SequencingInformation, + /*force_confirm*/ bool)>; // ReceivedEncryptionKeyCallback is called if server attached encryption key // to the response. using EncryptionKeyAttachedCallback = base::RepeatingCallback<void(SignedEncryptionInfo)>; - using CompletionResponse = StatusOr<SequencingInformation>; + // Successful response consists of Sequencing information that may be + // accompanied with force_confirm flag. + struct SuccessfulUploadResponse { + SequencingInformation sequencing_information; + bool force_confirm; + }; + using CompletionResponse = StatusOr<SuccessfulUploadResponse>; using CompletionCallback = base::OnceCallback<void(CompletionResponse)>; @@ -180,7 +188,7 @@ base::OnceCallback<void(StatusOr<std::unique_ptr<DmServerUploadService>>)> created_cb); - void UploadCompletion(StatusOr<SequencingInformation>) const; + void UploadCompletion(CompletionResponse upload_result) const; policy::CloudPolicyClient* GetClient();
diff --git a/chrome/browser/policy/messaging_layer/upload/dm_server_upload_service_unittest.cc b/chrome/browser/policy/messaging_layer/upload/dm_server_upload_service_unittest.cc index 02b18a800f..737c766 100644 --- a/chrome/browser/policy/messaging_layer/upload/dm_server_upload_service_unittest.cc +++ b/chrome/browser/policy/messaging_layer/upload/dm_server_upload_service_unittest.cc
@@ -5,6 +5,7 @@ #include "chrome/browser/policy/messaging_layer/upload/dm_server_upload_service.h" #include <memory> +#include <tuple> #include <utility> #include <vector> @@ -12,11 +13,11 @@ #include "base/strings/string_number_conversions.h" #include "base/task_runner.h" #include "base/test/task_environment.h" -#include "chrome/browser/policy/messaging_layer/util/shared_vector.h" -#include "chrome/browser/policy/messaging_layer/util/status.h" #include "chrome/test/base/testing_profile.h" #include "components/policy/core/browser/browser_policy_connector.h" #include "components/policy/core/common/cloud/mock_cloud_policy_client.h" +#include "components/reporting/util/shared_vector.h" +#include "components/reporting/util/status.h" #include "content/public/test/browser_task_environment.h" #include "testing/gtest/include/gtest/gtest.h" @@ -143,7 +144,9 @@ DmServerUploadService::EncryptionKeyAttachedCallback&)); }; -class DmServerUploaderTest : public ::testing::TestWithParam<bool> { +class DmServerUploaderTest : public ::testing::TestWithParam< + ::testing::tuple</*need_encryption_key*/ bool, + /*force_confirm*/ bool>> { public: DmServerUploaderTest() : sequenced_task_runner_(base::ThreadPool::CreateSequencedTaskRunner({})), @@ -151,7 +154,9 @@ records_(std::make_unique<std::vector<EncryptedRecord>>()) {} protected: - bool need_encryption_key() const { return GetParam(); } + bool need_encryption_key() const { return std::get<0>(GetParam()); } + + bool force_confirm() const { return std::get<1>(GetParam()); } content::BrowserTaskEnvironment task_envrionment_{ base::test::TaskEnvironment::TimeSource::MOCK_TIME}; @@ -170,16 +175,20 @@ // Add an empty record. records_->emplace_back(); + const bool force_confirm_flag = force_confirm(); EXPECT_CALL(*handler_, HandleRecords_(_, _, _, _)) .WillOnce(WithArgs<0, 2, 3>( - Invoke([](bool need_encryption_key, - DmServerUploadService::CompletionCallback& callback, - DmServerUploadService::EncryptionKeyAttachedCallback& - encryption_key_attached_cb) { + Invoke([&force_confirm_flag]( + bool need_encryption_key, + DmServerUploadService::CompletionCallback& callback, + DmServerUploadService::EncryptionKeyAttachedCallback& + encryption_key_attached_cb) { if (need_encryption_key) { encryption_key_attached_cb.Run(SignedEncryptionInfo()); } - std::move(callback).Run(SequencingInformation()); + std::move(callback).Run( + DmServerUploadService::SuccessfulUploadResponse{ + .force_confirm = force_confirm_flag}); }))); StrictMock<TestEncryptionKeyAttached> encryption_key_attached; @@ -217,16 +226,20 @@ records_->push_back(std::move(encrypted_record)); } + const bool force_confirm_flag = force_confirm(); EXPECT_CALL(*handler_, HandleRecords_(_, _, _, _)) .WillOnce(WithArgs<0, 2, 3>( - Invoke([](bool need_encryption_key, - DmServerUploadService::CompletionCallback& callback, - DmServerUploadService::EncryptionKeyAttachedCallback& - encryption_key_attached_cb) { + Invoke([&force_confirm_flag]( + bool need_encryption_key, + DmServerUploadService::CompletionCallback& callback, + DmServerUploadService::EncryptionKeyAttachedCallback& + encryption_key_attached_cb) { if (need_encryption_key) { encryption_key_attached_cb.Run(SignedEncryptionInfo()); } - std::move(callback).Run(SequencingInformation()); + std::move(callback).Run( + DmServerUploadService::SuccessfulUploadResponse{ + .force_confirm = force_confirm_flag}); }))); StrictMock<TestEncryptionKeyAttached> encryption_key_attached; @@ -325,9 +338,11 @@ callback_waiter.Wait(); } -INSTANTIATE_TEST_SUITE_P(NeedOrNoNeedKey, - DmServerUploaderTest, - testing::Bool()); +INSTANTIATE_TEST_SUITE_P( + NeedOrNoNeedKey, + DmServerUploaderTest, + ::testing::Combine(/*need_encryption_key*/ ::testing::Bool(), + /*force_confirm*/ ::testing::Bool())); } // namespace } // namespace reporting
diff --git a/chrome/browser/policy/messaging_layer/upload/record_handler_impl.cc b/chrome/browser/policy/messaging_layer/upload/record_handler_impl.cc index 6b2e8da..000f435 100644 --- a/chrome/browser/policy/messaging_layer/upload/record_handler_impl.cc +++ b/chrome/browser/policy/messaging_layer/upload/record_handler_impl.cc
@@ -20,15 +20,15 @@ #include "base/values.h" #include "chrome/browser/policy/messaging_layer/upload/dm_server_upload_service.h" #include "chrome/browser/policy/messaging_layer/upload/record_upload_request_builder.h" -#include "chrome/browser/policy/messaging_layer/util/status.h" -#include "chrome/browser/policy/messaging_layer/util/status_macros.h" -#include "chrome/browser/policy/messaging_layer/util/statusor.h" -#include "chrome/browser/policy/messaging_layer/util/task_runner_context.h" #include "chrome/browser/profiles/profile_manager.h" #include "chrome/browser/profiles/reporting_util.h" #include "components/policy/core/common/cloud/cloud_policy_client.h" -#include "components/policy/proto/record.pb.h" -#include "components/policy/proto/record_constants.pb.h" +#include "components/reporting/proto/record.pb.h" +#include "components/reporting/proto/record_constants.pb.h" +#include "components/reporting/util/status.h" +#include "components/reporting/util/status_macros.h" +#include "components/reporting/util/statusor.h" +#include "components/reporting/util/task_runner_context.h" #include "content/public/browser/browser_task_traits.h" #include "content/public/browser/browser_thread.h" @@ -116,6 +116,9 @@ // Set for the highest record being uploaded. base::Optional<SequencingInformation> highest_sequencing_information_; + + // Set to |true| if force_confirm flag is present. |false| by default. + bool force_confirm_{false}; }; RecordHandlerImpl::ReportUploader::ReportUploader( @@ -210,7 +213,10 @@ void RecordHandlerImpl::ReportUploader::HandleFailedUpload() { if (highest_sequencing_information_.has_value()) { - Complete(std::move(highest_sequencing_information_.value())); + Complete(DmServerUploadService::SuccessfulUploadResponse{ + .sequencing_information = + std::move(highest_sequencing_information_.value()), + .force_confirm = force_confirm_}); return; } @@ -225,6 +231,8 @@ // "failedUploadedRecord": ... // SequencingInformation proto // "failureStatus": ... // Status proto // } + // "forceConfirm": true // if present, flag that lastSucceedUploadedRecord + // // is to be accepted unconditionally by client // "encryptionSettings": ... // EncryptionSettings proto // } const base::Value* last_succeed_uploaded_record = @@ -241,6 +249,12 @@ } } + // Handle forceConfirm flag, if present. + const auto force_confirm_flag = last_response_.FindBoolKey("forceConfirm"); + if (force_confirm_flag.has_value() && force_confirm_flag.value()) { + force_confirm_ = true; + } + // Handle the encryption settings. // Note: server can attach it to response regardless of whether // the response indicates success or failure, and whether the client @@ -273,7 +287,7 @@ // Check if a record was unprocessable on the server. const base::Value* failed_uploaded_record = last_response_.FindDictPath( "firstFailedUploadedRecord.failedUploadedRecord"); - if (failed_uploaded_record != nullptr) { + if (!force_confirm_ && failed_uploaded_record != nullptr) { // The record we uploaded previously was unprocessable by the server, if the // record was after the current |highest_sequencing_information_| we should // return a gap record. A gap record consists of an EncryptedRecord with @@ -299,7 +313,10 @@ // No more records to process. Return the highest_sequencing_information_ if // available. if (highest_sequencing_information_.has_value()) { - Complete(highest_sequencing_information_.value()); + Complete(DmServerUploadService::SuccessfulUploadResponse{ + .sequencing_information = + std::move(highest_sequencing_information_.value()), + .force_confirm = force_confirm_}); return; }
diff --git a/chrome/browser/policy/messaging_layer/upload/record_handler_impl.h b/chrome/browser/policy/messaging_layer/upload/record_handler_impl.h index 4b928f2..d7ebce731 100644 --- a/chrome/browser/policy/messaging_layer/upload/record_handler_impl.h +++ b/chrome/browser/policy/messaging_layer/upload/record_handler_impl.h
@@ -16,13 +16,13 @@ #include "base/task_runner.h" #include "base/values.h" #include "chrome/browser/policy/messaging_layer/upload/dm_server_upload_service.h" -#include "chrome/browser/policy/messaging_layer/util/shared_queue.h" -#include "chrome/browser/policy/messaging_layer/util/status.h" -#include "chrome/browser/policy/messaging_layer/util/status_macros.h" -#include "chrome/browser/policy/messaging_layer/util/statusor.h" -#include "chrome/browser/policy/messaging_layer/util/task_runner_context.h" #include "components/policy/core/common/cloud/cloud_policy_client.h" -#include "components/policy/proto/record.pb.h" +#include "components/reporting/proto/record.pb.h" +#include "components/reporting/util/shared_queue.h" +#include "components/reporting/util/status.h" +#include "components/reporting/util/status_macros.h" +#include "components/reporting/util/statusor.h" +#include "components/reporting/util/task_runner_context.h" namespace reporting {
diff --git a/chrome/browser/policy/messaging_layer/upload/record_handler_impl_unittest.cc b/chrome/browser/policy/messaging_layer/upload/record_handler_impl_unittest.cc index 6025b67..eae8702 100644 --- a/chrome/browser/policy/messaging_layer/upload/record_handler_impl_unittest.cc +++ b/chrome/browser/policy/messaging_layer/upload/record_handler_impl_unittest.cc
@@ -4,6 +4,8 @@ #include "chrome/browser/policy/messaging_layer/upload/record_handler_impl.h" +#include <tuple> + #include "base/base64.h" #include "base/json/json_writer.h" #include "base/optional.h" @@ -15,15 +17,15 @@ #include "base/test/task_environment.h" #include "base/values.h" #include "chrome/browser/policy/messaging_layer/upload/dm_server_upload_service.h" -#include "chrome/browser/policy/messaging_layer/util/status.h" -#include "chrome/browser/policy/messaging_layer/util/status_macros.h" -#include "chrome/browser/policy/messaging_layer/util/statusor.h" -#include "chrome/browser/policy/messaging_layer/util/task_runner_context.h" #include "components/policy/core/common/cloud/cloud_policy_client.h" #include "components/policy/core/common/cloud/dm_token.h" #include "components/policy/core/common/cloud/mock_cloud_policy_client.h" -#include "components/policy/proto/record.pb.h" -#include "components/policy/proto/record_constants.pb.h" +#include "components/reporting/proto/record.pb.h" +#include "components/reporting/proto/record_constants.pb.h" +#include "components/reporting/util/status.h" +#include "components/reporting/util/status_macros.h" +#include "components/reporting/util/statusor.h" +#include "components/reporting/util/task_runner_context.h" #include "content/public/test/browser_task_environment.h" #include "testing/gtest/include/gtest/gtest.h" @@ -43,16 +45,21 @@ namespace reporting { namespace { -MATCHER_P(ValueEqualsProto, +MATCHER_P(ResponseEquals, expected, - "Compares StatusOr<MessageLite> to expected MessageLite") { + "Compares StatusOr<response> to expected response") { if (!arg.ok()) { return false; } - if (arg.ValueOrDie().GetTypeName() != expected.GetTypeName()) { + if (arg.ValueOrDie().sequencing_information.GetTypeName() != + expected.sequencing_information.GetTypeName()) { return false; } - return arg.ValueOrDie().SerializeAsString() == expected.SerializeAsString(); + if (arg.ValueOrDie().sequencing_information.SerializeAsString() != + expected.sequencing_information.SerializeAsString()) { + return false; + } + return arg.ValueOrDie().force_confirm == expected.force_confirm; } MATCHER_P(StatusOrErrorCodeEquals, @@ -160,12 +167,18 @@ // steps and tests require the response from the server to be accurate, ASSERTS // that the |request| must be valid, and on a valid request updates |response|. void SucceedResponseFromRequest(const base::Value& request, + bool force_confirm_by_server, base::Value& response) { base::Value seq_info{base::Value::Type::DICTIONARY}; RetrieveFinalSequencingInformation(request, seq_info); response.SetPath("lastSucceedUploadedRecord", std::move(seq_info)); - // If attach_encryption_settings it true, process that. + // If force_confirm is true, process that. + if (force_confirm_by_server) { + response.SetPath("forceConfirm", base::Value(true)); + } + + // If attach_encryption_settings is true, process that. auto encryption_settings_result = BuildEncryptionSettingsFromRequest(request); if (encryption_settings_result.has_value()) { response.SetPath("encryptionSettings", @@ -205,7 +218,9 @@ } } -class RecordHandlerImplTest : public ::testing::TestWithParam<bool> { +class RecordHandlerImplTest : public ::testing::TestWithParam< + ::testing::tuple</*need_encryption_key*/ bool, + /*force_confirm*/ bool>> { public: RecordHandlerImplTest() : client_(std::make_unique<policy::MockCloudPolicyClient>()) {} @@ -216,7 +231,9 @@ policy::DMToken::CreateValidTokenForTesting("FAKE_DM_TOKEN").value()); } - bool need_encryption_key() const { return GetParam(); } + bool need_encryption_key() const { return std::get<0>(GetParam()); } + + bool force_confirm() const { return std::get<1>(GetParam()); } content::BrowserTaskEnvironment task_environment_; @@ -247,15 +264,17 @@ static constexpr int64_t kNumTestRecords = 10; static constexpr int64_t kGenerationId = 1234; auto test_records = BuildTestRecordsVector(kNumTestRecords, kGenerationId); + const auto force_confirm_by_server = force_confirm(); TestCallbackWaiter client_waiter; EXPECT_CALL(*client_, UploadEncryptedReport(_, _, _)) .WillOnce(WithArgs<0, 2>( - Invoke([&client_waiter]( + Invoke([&client_waiter, &force_confirm_by_server]( base::Value request, policy::CloudPolicyClient::ResponseCallback callback) { base::Value response{base::Value::Type::DICTIONARY}; - SucceedResponseFromRequest(request, response); + SucceedResponseFromRequest(request, force_confirm_by_server, + response); std::move(callback).Run(std::move(response)); client_waiter.Signal(); }))); @@ -274,7 +293,10 @@ EXPECT_CALL( responder, - Call(ValueEqualsProto(test_records->back().sequencing_information()))) + Call(ResponseEquals(DmServerUploadService::SuccessfulUploadResponse{ + .sequencing_information = + test_records->back().sequencing_information(), + .force_confirm = force_confirm()}))) .WillOnce(Invoke([&responder_waiter]() { responder_waiter.Signal(); })); auto encryption_key_attached_callback = @@ -335,6 +357,7 @@ static constexpr int64_t kNumTestRecords = 10; static constexpr int64_t kGenerationId = 1234; auto test_records = BuildTestRecordsVector(kNumTestRecords, kGenerationId); + const auto force_confirm_by_server = force_confirm(); // Once for failure, and once for gap. TestCallbackWaiterWithCounter client_waiter{2}; @@ -352,11 +375,12 @@ }))); EXPECT_CALL(*client_, UploadEncryptedReport(_, _, _)) .WillOnce(WithArgs<0, 2>( - Invoke([&client_waiter]( + Invoke([&client_waiter, &force_confirm_by_server]( base::Value request, policy::CloudPolicyClient::ResponseCallback callback) { base::Value response{base::Value::Type::DICTIONARY}; - SucceedResponseFromRequest(request, response); + SucceedResponseFromRequest(request, force_confirm_by_server, + response); std::move(callback).Run(std::move(response)); client_waiter.Signal(); }))); @@ -366,8 +390,10 @@ TestCompletionResponder responder; EXPECT_CALL( responder, - Call(ValueEqualsProto( - (*test_records)[kNumTestRecords - 1].sequencing_information()))) + Call(ResponseEquals(DmServerUploadService::SuccessfulUploadResponse{ + .sequencing_information = + (*test_records)[kNumTestRecords - 1].sequencing_information(), + .force_confirm = force_confirm()}))) .WillOnce(Invoke([&responder_waiter]() { responder_waiter.Signal(); })); StrictMock<TestEncryptionKeyAttached> encryption_key_attached; @@ -418,7 +444,7 @@ EXPECT_CALL( responder, - Call(Property(&StatusOr<SequencingInformation>::status, + Call(Property(&DmServerUploadService::CompletionResponse::status, Property(&Status::error_code, Eq(error::INTERNAL))))) .WillOnce(Invoke([&responder_waiter]() { responder_waiter.Signal(); })); @@ -438,8 +464,10 @@ responder_waiter.Wait(); } -INSTANTIATE_TEST_SUITE_P(NeedOrNoNeedKey, - RecordHandlerImplTest, - testing::Bool()); +INSTANTIATE_TEST_SUITE_P( + NeedOrNoNeedKey, + RecordHandlerImplTest, + ::testing::Combine(/*need_encryption_key*/ ::testing::Bool(), + /*force_confirm*/ ::testing::Bool())); } // namespace } // namespace reporting
diff --git a/chrome/browser/policy/messaging_layer/upload/record_upload_request_builder.cc b/chrome/browser/policy/messaging_layer/upload/record_upload_request_builder.cc index 3182d08..c0775354 100644 --- a/chrome/browser/policy/messaging_layer/upload/record_upload_request_builder.cc +++ b/chrome/browser/policy/messaging_layer/upload/record_upload_request_builder.cc
@@ -12,8 +12,8 @@ #include "base/strings/string_piece.h" #include "base/strings/string_util.h" #include "base/values.h" -#include "components/policy/proto/record.pb.h" -#include "components/policy/proto/record_constants.pb.h" +#include "components/reporting/proto/record.pb.h" +#include "components/reporting/proto/record_constants.pb.h" namespace reporting {
diff --git a/chrome/browser/policy/messaging_layer/upload/record_upload_request_builder.h b/chrome/browser/policy/messaging_layer/upload/record_upload_request_builder.h index 2f44ff0..ee64f6f7 100644 --- a/chrome/browser/policy/messaging_layer/upload/record_upload_request_builder.h +++ b/chrome/browser/policy/messaging_layer/upload/record_upload_request_builder.h
@@ -10,7 +10,7 @@ #include "base/optional.h" #include "base/strings/string_piece.h" #include "base/values.h" -#include "components/policy/proto/record.pb.h" +#include "components/reporting/proto/record.pb.h" namespace reporting {
diff --git a/chrome/browser/policy/messaging_layer/upload/upload_client.cc b/chrome/browser/policy/messaging_layer/upload/upload_client.cc index 31d37d48..5b16a76 100644 --- a/chrome/browser/policy/messaging_layer/upload/upload_client.cc +++ b/chrome/browser/policy/messaging_layer/upload/upload_client.cc
@@ -6,10 +6,10 @@ #include "base/memory/ptr_util.h" #include "chrome/browser/policy/messaging_layer/upload/dm_server_upload_service.h" -#include "chrome/browser/policy/messaging_layer/util/status.h" -#include "chrome/browser/policy/messaging_layer/util/status_macros.h" -#include "chrome/browser/policy/messaging_layer/util/statusor.h" #include "components/policy/core/common/cloud/cloud_policy_client.h" +#include "components/reporting/util/status.h" +#include "components/reporting/util/status_macros.h" +#include "components/reporting/util/statusor.h" #include "components/user_manager/user_manager.h" #include "content/public/browser/browser_context.h" #include "content/public/browser/storage_partition.h"
diff --git a/chrome/browser/policy/messaging_layer/upload/upload_client.h b/chrome/browser/policy/messaging_layer/upload/upload_client.h index 2b6ece59..b9ece7ed 100644 --- a/chrome/browser/policy/messaging_layer/upload/upload_client.h +++ b/chrome/browser/policy/messaging_layer/upload/upload_client.h
@@ -11,10 +11,10 @@ #include "base/task/post_task.h" #include "base/task_runner.h" #include "chrome/browser/policy/messaging_layer/upload/dm_server_upload_service.h" -#include "chrome/browser/policy/messaging_layer/util/status.h" -#include "chrome/browser/policy/messaging_layer/util/statusor.h" #include "components/policy/core/common/cloud/cloud_policy_client.h" -#include "components/policy/proto/record.pb.h" +#include "components/reporting/proto/record.pb.h" +#include "components/reporting/util/status.h" +#include "components/reporting/util/statusor.h" namespace reporting { @@ -22,9 +22,10 @@ class UploadClient { public: // ReportSuccessfulUploadCallback is used to pass server responses back to - // the owner of |this|. + // the owner of |this| (the respone consists of sequencing information and + // forceConfirm flag). using ReportSuccessfulUploadCallback = - base::RepeatingCallback<void(SequencingInformation)>; + DmServerUploadService::ReportSuccessfulUploadCallback; // ReceivedEncryptionKeyCallback is called if server attached encryption key // to the response.
diff --git a/chrome/browser/policy/messaging_layer/upload/upload_client_unittest.cc b/chrome/browser/policy/messaging_layer/upload/upload_client_unittest.cc index 667a511f..89cdbb8 100644 --- a/chrome/browser/policy/messaging_layer/upload/upload_client_unittest.cc +++ b/chrome/browser/policy/messaging_layer/upload/upload_client_unittest.cc
@@ -4,6 +4,8 @@ #include "chrome/browser/policy/messaging_layer/upload/upload_client.h" +#include <tuple> + #include "base/base64.h" #include "base/bind.h" #include "base/files/file_path.h" @@ -17,8 +19,8 @@ #include "components/account_id/account_id.h" #include "components/policy/core/common/cloud/dm_token.h" #include "components/policy/core/common/cloud/mock_cloud_policy_client.h" -#include "components/policy/proto/record.pb.h" -#include "components/policy/proto/record_constants.pb.h" +#include "components/reporting/proto/record.pb.h" +#include "components/reporting/proto/record_constants.pb.h" #include "content/public/browser/browser_task_traits.h" #include "content/public/browser/browser_thread.h" #include "content/public/test/browser_task_environment.h" @@ -36,6 +38,7 @@ using ::policy::MockCloudPolicyClient; using ::testing::_; using ::testing::AllOf; +using ::testing::Eq; using ::testing::Gt; using ::testing::Invoke; using ::testing::InvokeArgument; @@ -98,8 +101,11 @@ virtual void Signal() { run_loop_->Quit(); } void CompleteExpectSequencingInformation(SequencingInformation expected, - SequencingInformation info) { + bool expected_force_confirm, + SequencingInformation info, + bool force_confirm) { EXPECT_THAT(info, EqualsProto(expected)); + EXPECT_THAT(force_confirm, Eq(expected_force_confirm)); Signal(); } @@ -132,7 +138,8 @@ // Helper function composes JSON represented as base::Value from Sequencing // information in request. base::Value ValueFromSucceededSequencingInfo( - const base::Optional<base::Value> request) { + const base::Optional<base::Value> request, + bool force_confirm_flag) { EXPECT_TRUE(request.has_value()); EXPECT_TRUE(request.value().is_dict()); base::Value response(base::Value::Type::DICTIONARY); @@ -154,6 +161,11 @@ EXPECT_TRUE(seq_info != nullptr); response.SetPath("lastSucceedUploadedRecord", seq_info->Clone()); + // If forceConfirm confirm is expected, set it. + if (force_confirm_flag) { + response.SetPath("forceConfirm", base::Value(true)); + } + // If attach_encryption_settings it true, process that. const auto attach_encryption_settings = request.value().FindBoolKey("attachEncryptionSettings"); @@ -174,7 +186,9 @@ return response; } -class UploadClientTest : public ::testing::TestWithParam<bool> { +class UploadClientTest : public ::testing::TestWithParam< + ::testing::tuple</*need_encryption_key*/ bool, + /*force_confirm*/ bool>> { public: UploadClientTest() = default; @@ -205,7 +219,9 @@ #endif // BUILDFLAG(IS_CHROMEOS_ASH) } - bool need_encryption_key() const { return GetParam(); } + bool need_encryption_key() const { return std::get<0>(GetParam()); } + + bool force_confirm() const { return std::get<1>(GetParam()); } content::BrowserTaskEnvironment task_envrionment_; #if BUILDFLAG(IS_CHROMEOS_ASH) @@ -264,12 +280,15 @@ policy::DMToken::CreateValidTokenForTesting("FAKE_DM_TOKEN").value()); TestCallbackWaiter waiter; + const bool force_confirm_flag = force_confirm(); EXPECT_CALL(*client, UploadEncryptedReport(_, _, _)) - .WillOnce(WithArgs<0, 2>(Invoke( - [&waiter](base::Value request, - policy::CloudPolicyClient::ResponseCallback response_cb) { + .WillOnce(WithArgs<0, 2>( + Invoke([&waiter, &force_confirm_flag]( + base::Value request, + policy::CloudPolicyClient::ResponseCallback response_cb) { std::move(response_cb) - .Run(ValueFromSucceededSequencingInfo(std::move(request))); + .Run(ValueFromSucceededSequencingInfo(std::move(request), + force_confirm_flag)); base::ThreadPool::PostTask( FROM_HERE, {base::TaskPriority::BEST_EFFORT}, base::BindOnce(&TestCallbackWaiter::Signal, @@ -281,7 +300,7 @@ base::BindRepeating( &TestCallbackWaiter::CompleteExpectSequencingInformation, base::Unretained(&completion_callback_waiter), - records->back().sequencing_information()); + records->back().sequencing_information(), force_confirm()); TestEvent<StatusOr<std::unique_ptr<UploadClient>>> e; UploadClient::Create(client.get(), completion_cb, encryption_key_attached_cb, @@ -298,7 +317,11 @@ completion_callback_waiter.Wait(); } -INSTANTIATE_TEST_SUITE_P(NeedOrNoNeedKey, UploadClientTest, testing::Bool()); +INSTANTIATE_TEST_SUITE_P( + NeedOrNoNeedKey, + UploadClientTest, + ::testing::Combine(/*need_encryption_key*/ ::testing::Bool(), + /*force_confirm*/ ::testing::Bool())); } // namespace } // namespace reporting
diff --git a/chrome/browser/policy/messaging_layer/util/get_cloud_policy_client.cc b/chrome/browser/policy/messaging_layer/util/get_cloud_policy_client.cc index 24f4f538..d2c90ef 100644 --- a/chrome/browser/policy/messaging_layer/util/get_cloud_policy_client.cc +++ b/chrome/browser/policy/messaging_layer/util/get_cloud_policy_client.cc
@@ -9,8 +9,6 @@ #include "build/build_config.h" #include "chrome/browser/browser_process.h" #include "chrome/browser/browser_process_platform_part.h" -#include "chrome/browser/policy/messaging_layer/util/status.h" -#include "chrome/browser/policy/messaging_layer/util/statusor.h" #include "chrome/browser/profiles/profile_manager.h" #include "chrome/browser/signin/identity_manager_factory.h" #include "components/policy/core/common/cloud/cloud_policy_client.h" @@ -19,6 +17,8 @@ #include "components/policy/core/common/cloud/device_management_service.h" #include "components/policy/core/common/cloud/machine_level_user_cloud_policy_manager.h" #include "components/policy/core/common/cloud/user_cloud_policy_manager.h" +#include "components/reporting/util/status.h" +#include "components/reporting/util/statusor.h" #include "components/signin/public/identity_manager/identity_manager.h" #include "content/public/browser/browser_task_traits.h" #include "content/public/browser/browser_thread.h"
diff --git a/chrome/browser/policy/messaging_layer/util/get_cloud_policy_client.h b/chrome/browser/policy/messaging_layer/util/get_cloud_policy_client.h index 5251bd1..707034b 100644 --- a/chrome/browser/policy/messaging_layer/util/get_cloud_policy_client.h +++ b/chrome/browser/policy/messaging_layer/util/get_cloud_policy_client.h
@@ -6,8 +6,8 @@ #define CHROME_BROWSER_POLICY_MESSAGING_LAYER_UTIL_GET_CLOUD_POLICY_CLIENT_H_ #include "base/callback.h" -#include "chrome/browser/policy/messaging_layer/util/statusor.h" #include "components/policy/core/common/cloud/cloud_policy_client.h" +#include "components/reporting/util/statusor.h" namespace reporting {
diff --git a/chrome/browser/policy/messaging_layer/util/report_queue_manual_test_context.cc b/chrome/browser/policy/messaging_layer/util/report_queue_manual_test_context.cc index 84b05bf..c524667 100644 --- a/chrome/browser/policy/messaging_layer/util/report_queue_manual_test_context.cc +++ b/chrome/browser/policy/messaging_layer/util/report_queue_manual_test_context.cc
@@ -14,11 +14,11 @@ #include "chrome/browser/policy/messaging_layer/public/report_client.h" #include "chrome/browser/policy/messaging_layer/public/report_queue.h" #include "chrome/browser/policy/messaging_layer/public/report_queue_configuration.h" -#include "chrome/browser/policy/messaging_layer/util/status.h" -#include "chrome/browser/policy/messaging_layer/util/task_runner_context.h" #include "chrome/browser/profiles/profile_manager.h" #include "components/policy/core/common/cloud/dm_token.h" -#include "components/policy/proto/record_constants.pb.h" +#include "components/reporting/proto/record_constants.pb.h" +#include "components/reporting/util/status.h" +#include "components/reporting/util/task_runner_context.h" #include "content/public/browser/browser_task_traits.h" #include "content/public/browser/browser_thread.h"
diff --git a/chrome/browser/policy/messaging_layer/util/report_queue_manual_test_context.h b/chrome/browser/policy/messaging_layer/util/report_queue_manual_test_context.h index f205037..ecdf187 100644 --- a/chrome/browser/policy/messaging_layer/util/report_queue_manual_test_context.h +++ b/chrome/browser/policy/messaging_layer/util/report_queue_manual_test_context.h
@@ -9,10 +9,10 @@ #include "base/sequenced_task_runner.h" #include "base/time/time.h" #include "chrome/browser/policy/messaging_layer/public/report_queue.h" -#include "chrome/browser/policy/messaging_layer/util/status.h" -#include "chrome/browser/policy/messaging_layer/util/task_runner_context.h" #include "components/policy/core/common/cloud/dm_token.h" -#include "components/policy/proto/record_constants.pb.h" +#include "components/reporting/proto/record_constants.pb.h" +#include "components/reporting/util/status.h" +#include "components/reporting/util/task_runner_context.h" namespace reporting {
diff --git a/chrome/browser/policy/messaging_layer/util/report_queue_manual_test_context_unittest.cc b/chrome/browser/policy/messaging_layer/util/report_queue_manual_test_context_unittest.cc index ea5b5e6..0807081 100644 --- a/chrome/browser/policy/messaging_layer/util/report_queue_manual_test_context_unittest.cc +++ b/chrome/browser/policy/messaging_layer/util/report_queue_manual_test_context_unittest.cc
@@ -9,9 +9,9 @@ #include "chrome/browser/policy/dm_token_utils.h" #include "chrome/browser/policy/messaging_layer/public/mock_report_queue.h" #include "chrome/browser/policy/messaging_layer/public/report_queue.h" -#include "chrome/browser/policy/messaging_layer/util/status.h" #include "components/policy/core/common/cloud/dm_token.h" -#include "components/policy/proto/record_constants.pb.h" +#include "components/reporting/proto/record_constants.pb.h" +#include "components/reporting/util/status.h" #include "content/public/test/browser_task_environment.h" #include "testing/gmock/include/gmock/gmock.h" #include "testing/gtest/include/gtest/gtest.h"
diff --git a/chrome/browser/policy/policy_browsertest.cc b/chrome/browser/policy/policy_browsertest.cc index 20c0194..13c4aa2 100644 --- a/chrome/browser/policy/policy_browsertest.cc +++ b/chrome/browser/policy/policy_browsertest.cc
@@ -791,7 +791,7 @@ nullptr); UpdateProviderPolicy(policies); - embedded_test_server()->RegisterRequestHandler(base::Bind( + embedded_test_server()->RegisterRequestHandler(base::BindRepeating( &NetworkTimePolicyTest::CountingRequestHandler, base::Unretained(this))); ASSERT_TRUE(embedded_test_server()->Start()); g_browser_process->network_time_tracker()->SetTimeServerURLForTesting(
diff --git a/chrome/browser/policy/policy_network_browsertest.cc b/chrome/browser/policy/policy_network_browsertest.cc index 8b9fc9e..e0395ce 100644 --- a/chrome/browser/policy/policy_network_browsertest.cc +++ b/chrome/browser/policy/policy_network_browsertest.cc
@@ -75,12 +75,12 @@ // Called when an additional profile has been created. // The created profile is stored in *|out_created_profile|. void OnProfileInitialized(Profile** out_created_profile, - const base::Closure& closure, + base::RunLoop* run_loop, Profile* profile, Profile::CreateStatus status) { if (status == Profile::CREATE_STATUS_INITIALIZED) { *out_created_profile = profile; - closure.Run(); + run_loop->Quit(); } } @@ -371,8 +371,7 @@ base::RunLoop run_loop; profile_manager->CreateProfileAsync( path_profile, - base::BindRepeating(&OnProfileInitialized, &profile_2_, - run_loop.QuitClosure()), + base::BindRepeating(&OnProfileInitialized, &profile_2_, &run_loop), base::string16(), std::string()); // Run the message loop to allow profile creation to take place; the loop is
diff --git a/chrome/browser/portal/portal_browsertest.cc b/chrome/browser/portal/portal_browsertest.cc index ce80dae..8718725 100644 --- a/chrome/browser/portal/portal_browsertest.cc +++ b/chrome/browser/portal/portal_browsertest.cc
@@ -131,11 +131,7 @@ browser()->tab_strip_model()->GetActiveWebContents(), nullptr)); } -// TODO(mcnee): Disabled due to the initial fix for this causing a regression. -// See https://crbug.com/1076696 . Investigate the cause of this regression and -// re-enable. -IN_PROC_BROWSER_TEST_F(PortalBrowserTest, - DISABLED_HttpBasicAuthenticationInPortal) { +IN_PROC_BROWSER_TEST_F(PortalBrowserTest, HttpBasicAuthenticationInPortal) { ASSERT_TRUE(embedded_test_server()->Start()); GURL url(embedded_test_server()->GetURL("/title1.html")); ui_test_utils::NavigateToURL(browser(), url);
diff --git a/chrome/browser/prefs/browser_prefs.cc b/chrome/browser/prefs/browser_prefs.cc index 45b39cb..7d0ebb1 100644 --- a/chrome/browser/prefs/browser_prefs.cc +++ b/chrome/browser/prefs/browser_prefs.cc
@@ -347,6 +347,7 @@ #include "chromeos/components/local_search_service/search_metrics_reporter.h" #include "chromeos/components/quick_answers/public/cpp/quick_answers_prefs.h" #include "chromeos/constants/chromeos_switches.h" +#include "chromeos/network/cellular_esim_profile_handler_impl.h" #include "chromeos/network/fast_transition_observer.h" #include "chromeos/network/network_metadata_store.h" #include "chromeos/network/proxy/proxy_config_handler.h" @@ -721,6 +722,7 @@ chromeos::ArcKioskAppManager::RegisterPrefs(registry); chromeos::AudioDevicesPrefHandlerImpl::RegisterPrefs(registry); chromeos::cert_provisioning::RegisterLocalStatePrefs(registry); + chromeos::CellularESimProfileHandlerImpl::RegisterLocalStatePrefs(registry); chromeos::ChromeUserManagerImpl::RegisterPrefs(registry); chromeos::CupsPrintersManager::RegisterLocalStatePrefs(registry); chromeos::DemoModeDetector::RegisterPrefs(registry);
diff --git a/chrome/browser/prefs/profile_pref_store_manager_unittest.cc b/chrome/browser/prefs/profile_pref_store_manager_unittest.cc index aff4bd1..1c627556 100644 --- a/chrome/browser/prefs/profile_pref_store_manager_unittest.cc +++ b/chrome/browser/prefs/profile_pref_store_manager_unittest.cc
@@ -10,6 +10,7 @@ #include <utility> #include <vector> +#include "base/callback.h" #include "base/compiler_specific.h" #include "base/files/file_enumerator.h" #include "base/files/file_util.h" @@ -99,14 +100,14 @@ void OnPrefValueChanged(const std::string& key) override {} void OnInitializationCompleted(bool succeeded) override { - if (!stop_waiting_.is_null()) { + if (stop_waiting_) { std::move(stop_waiting_).Run(); } } private: scoped_refptr<PersistentPrefStore> pref_store_; - base::Closure stop_waiting_; + base::OnceClosure stop_waiting_; DISALLOW_COPY_AND_ASSIGN(PrefStoreReadObserver); };
diff --git a/chrome/browser/profiles/profile_manager.cc b/chrome/browser/profiles/profile_manager.cc index 701ecf8a..5b983a9 100644 --- a/chrome/browser/profiles/profile_manager.cc +++ b/chrome/browser/profiles/profile_manager.cc
@@ -7,6 +7,7 @@ #include <stdint.h> #include <map> +#include <numeric> #include <set> #include <string> #include <utility> @@ -381,6 +382,12 @@ } #endif // !defined(OS_ANDROID) +int GetTotalRefCount(const std::map<ProfileKeepAliveOrigin, int>& keep_alives) { + return std::accumulate( + keep_alives.begin(), keep_alives.end(), 0, + [](int acc, const auto& pair) { return acc + pair.second; }); +} + } // namespace ProfileManager::ProfileManager(const base::FilePath& user_data_dir) @@ -1320,7 +1327,15 @@ DCHECK(!profile->IsOffTheRecord()); ProfileInfo* info = GetProfileInfoByPath(profile->GetPath()); - DCHECK(info); + if (!info) { + // Can be null in unit tests, when the Profile was not created via + // ProfileManager. + return; + } + + DCHECK_NE(0, GetTotalRefCount(info->keep_alives)) + << "AddKeepAlive() on a soon-to-be-deleted Profile is not allowed"; + info->keep_alives[origin]++; int& waiting_for_first_browser_window = @@ -1329,6 +1344,9 @@ waiting_for_first_browser_window != 0) { waiting_for_first_browser_window = 0; } + + VLOG(1) << "AddKeepAlive(" << profile->GetDebugName() << ", " << origin + << "). refcount=" << GetTotalRefCount(info->keep_alives); } void ProfileManager::RemoveKeepAlive(const Profile* profile, @@ -1341,16 +1359,25 @@ DCHECK(!profile->IsOffTheRecord()); ProfileInfo* info = GetProfileInfoByPath(profile->GetPath()); - DCHECK(info); + if (!info) { + // Can be null in unit tests, when the Profile was not created via + // ProfileManager. + return; + } + DCHECK(base::Contains(info->keep_alives, origin)); info->keep_alives[origin]--; DCHECK_LE(0, info->keep_alives[origin]); + int total_refcount = GetTotalRefCount(info->keep_alives); + VLOG(1) << "RemoveKeepAlive(" << profile->GetDebugName() << ", " << origin + << "). refcount=" << total_refcount; + #if !defined(OS_ANDROID) && !BUILDFLAG(IS_CHROMEOS_ASH) - bool is_zero_refcount = base::ranges::all_of( - info->keep_alives, [](const auto& entry) { return entry.second == 0; }); - if (is_zero_refcount) + if (total_refcount == 0) { + VLOG(1) << "Deleting profile " << profile->GetDebugName(); RemoveProfile(profile->GetPath()); + } #endif // !defined(OS_ANDROID) && !BUILDFLAG(IS_CHROMEOS_ASH) }
diff --git a/chrome/browser/push_messaging/budget_database_unittest.cc b/chrome/browser/push_messaging/budget_database_unittest.cc index edc60fac..7449d82 100644 --- a/chrome/browser/push_messaging/budget_database_unittest.cc +++ b/chrome/browser/push_messaging/budget_database_unittest.cc
@@ -43,9 +43,9 @@ db_(&profile_), origin_(url::Origin::Create(GURL(kTestOrigin))) {} - void WriteBudgetComplete(base::Closure run_loop_closure, bool success) { + void WriteBudgetComplete(base::OnceClosure run_loop_closure, bool success) { success_ = success; - run_loop_closure.Run(); + std::move(run_loop_closure).Run(); } // Spend budget for the origin. @@ -60,11 +60,11 @@ return success_; } - void GetBudgetDetailsComplete(base::Closure run_loop_closure, + void GetBudgetDetailsComplete(base::OnceClosure run_loop_closure, std::vector<BudgetState> predictions) { success_ = !predictions.empty(); prediction_.swap(predictions); - run_loop_closure.Run(); + std::move(run_loop_closure).Run(); } // Get the full set of budget predictions for the origin.
diff --git a/chrome/browser/push_messaging/push_messaging_browsertest.cc b/chrome/browser/push_messaging/push_messaging_browsertest.cc index 8d4f119..75d6259 100644 --- a/chrome/browser/push_messaging/push_messaging_browsertest.cc +++ b/chrome/browser/push_messaging/push_messaging_browsertest.cc
@@ -118,7 +118,7 @@ return application_server_key; } -void LegacyRegisterCallback(const base::Closure& done_callback, +void LegacyRegisterCallback(base::OnceClosure done_callback, std::string* out_registration_id, gcm::GCMClient::Result* out_result, const std::string& registration_id, @@ -127,10 +127,10 @@ *out_registration_id = registration_id; if (out_result) *out_result = result; - done_callback.Run(); + std::move(done_callback).Run(); } -void DidRegister(base::Closure done_callback, +void DidRegister(base::OnceClosure done_callback, const std::string& registration_id, const GURL& endpoint, const base::Optional<base::Time>& expiration_time, @@ -139,15 +139,15 @@ blink::mojom::PushRegistrationStatus status) { EXPECT_EQ(blink::mojom::PushRegistrationStatus::SUCCESS_FROM_PUSH_SERVICE, status); - done_callback.Run(); + std::move(done_callback).Run(); } -void InstanceIDResultCallback(base::Closure done_callback, +void InstanceIDResultCallback(base::OnceClosure done_callback, instance_id::InstanceID::Result* out_result, instance_id::InstanceID::Result result) { DCHECK(out_result); *out_result = result; - done_callback.Run(); + std::move(done_callback).Run(); } } // namespace @@ -340,11 +340,11 @@ // To be called when delivery of a push message has finished. The |run_loop| // will be told to quit after |messages_required| messages were received. void OnDeliveryFinished(std::vector<size_t>* number_of_notifications_shown, - const base::Closure& done_closure) { + base::OnceClosure done_closure) { DCHECK(number_of_notifications_shown); number_of_notifications_shown->push_back(GetNotificationCount()); - done_closure.Run(); + std::move(done_closure).Run(); } PushMessagingServiceImpl* push_service() const { return push_service_; } @@ -1878,7 +1878,7 @@ { base::RunLoop run_loop; - push_service()->SetMessageCallbackForTesting(base::Bind( + push_service()->SetMessageCallbackForTesting(base::BindRepeating( &PushMessagingBrowserTest::OnDeliveryFinished, base::Unretained(this), &number_of_notifications_shown, base::BarrierClosure(2 /* num_closures */, run_loop.QuitClosure()))); @@ -1916,7 +1916,7 @@ ASSERT_EQ("true - is controlled", script_result); base::RunLoop run_loop; - base::Closure quit_barrier = + base::RepeatingClosure quit_barrier = base::BarrierClosure(2 /* num_closures */, run_loop.QuitClosure()); push_service()->SetMessageCallbackForTesting(quit_barrier); notification_tester_->SetNotificationAddedClosure(quit_barrier);
diff --git a/chrome/browser/push_messaging/push_messaging_service_impl.cc b/chrome/browser/push_messaging/push_messaging_service_impl.cc index 3378152..0802555 100644 --- a/chrome/browser/push_messaging/push_messaging_service_impl.cc +++ b/chrome/browser/push_messaging/push_messaging_service_impl.cc
@@ -623,7 +623,7 @@ } void PushMessagingServiceImpl::SetMessageCallbackForTesting( - const base::Closure& callback) { + const base::RepeatingClosure& callback) { message_callback_for_testing_ = callback; } @@ -1154,12 +1154,12 @@ DecreasePushSubscriptionCount(1, false /* was_pending */); if (!unsubscribe_callback_for_testing_.is_null()) - unsubscribe_callback_for_testing_.Run(); + std::move(unsubscribe_callback_for_testing_).Run(); } void PushMessagingServiceImpl::SetUnsubscribeCallbackForTesting( - const base::Closure& callback) { - unsubscribe_callback_for_testing_ = callback; + base::OnceClosure callback) { + unsubscribe_callback_for_testing_ = std::move(callback); } // DidDeleteServiceWorkerRegistration methods ----------------------------------
diff --git a/chrome/browser/push_messaging/push_messaging_service_impl.h b/chrome/browser/push_messaging/push_messaging_service_impl.h index c085beb..6f1be3d 100644 --- a/chrome/browser/push_messaging/push_messaging_service_impl.h +++ b/chrome/browser/push_messaging/push_messaging_service_impl.h
@@ -174,8 +174,8 @@ void OnRefreshFinished( const PushMessagingAppIdentifier& app_identifier) override; - void SetMessageCallbackForTesting(const base::Closure& callback); - void SetUnsubscribeCallbackForTesting(const base::Closure& callback); + void SetMessageCallbackForTesting(const base::RepeatingClosure& callback); + void SetUnsubscribeCallbackForTesting(base::OnceClosure callback); void SetInvalidationCallbackForTesting(base::OnceClosure callback); void SetContentSettingChangedCallbackForTesting( base::RepeatingClosure callback); @@ -391,10 +391,10 @@ // Callback to be invoked when a message has been dispatched. Enables tests to // observe message delivery before it's dispatched to the Service Worker. using MessageDispatchedCallback = - base::Callback<void(const std::string& app_id, - const GURL& origin, - int64_t service_worker_registration_id, - base::Optional<std::string> payload)>; + base::RepeatingCallback<void(const std::string& app_id, + const GURL& origin, + int64_t service_worker_registration_id, + base::Optional<std::string> payload)>; void SetMessageDispatchedCallbackForTesting( const MessageDispatchedCallback& callback) { @@ -409,11 +409,11 @@ int push_subscription_count_; int pending_push_subscription_count_; - base::Closure message_callback_for_testing_; - base::Closure unsubscribe_callback_for_testing_; - base::Closure content_setting_changed_callback_for_testing_; - base::Closure service_worker_unregistered_callback_for_testing_; - base::Closure service_worker_database_wiped_callback_for_testing_; + base::RepeatingClosure message_callback_for_testing_; + base::OnceClosure unsubscribe_callback_for_testing_; + base::RepeatingClosure content_setting_changed_callback_for_testing_; + base::RepeatingClosure service_worker_unregistered_callback_for_testing_; + base::RepeatingClosure service_worker_database_wiped_callback_for_testing_; base::OnceClosure remove_expired_subscriptions_callback_for_testing_; base::OnceClosure invalidation_callback_for_testing_;
diff --git a/chrome/browser/push_messaging/push_messaging_service_unittest.cc b/chrome/browser/push_messaging/push_messaging_service_unittest.cc index f547ef31..6966e2f8 100644 --- a/chrome/browser/push_messaging/push_messaging_service_unittest.cc +++ b/chrome/browser/push_messaging/push_messaging_service_unittest.cc
@@ -114,7 +114,7 @@ base::Optional<base::Time>* expiration_time_out, std::vector<uint8_t>* p256dh_out, std::vector<uint8_t>* auth_out, - base::Closure done_callback, + base::OnceClosure done_callback, const std::string& registration_id, const GURL& endpoint, const base::Optional<base::Time>& expiration_time, @@ -130,7 +130,7 @@ *p256dh_out = p256dh; *auth_out = auth; - done_callback.Run(); + std::move(done_callback).Run(); } // Callback to use when observing messages dispatched by the push service.
diff --git a/chrome/browser/resource_coordinator/tab_load_tracker_test_support.cc b/chrome/browser/resource_coordinator/tab_load_tracker_test_support.cc index 7df485ae..506f9672 100644 --- a/chrome/browser/resource_coordinator/tab_load_tracker_test_support.cc +++ b/chrome/browser/resource_coordinator/tab_load_tracker_test_support.cc
@@ -102,7 +102,7 @@ return; if (AllContentsReachedState()) { wait_successful_ = true; - run_loop_quit_closure_.Run(); + std::move(run_loop_quit_closure_).Run(); } } @@ -122,7 +122,7 @@ wait_successful_ = AllContentsReachedState(); #endif // defined(OS_ANDROID) } - run_loop_quit_closure_.Run(); + std::move(run_loop_quit_closure_).Run(); } private: @@ -138,7 +138,7 @@ // stops being tracked (is destroyed) before encountering the desired state. bool wait_successful_; - base::Closure run_loop_quit_closure_; + base::OnceClosure run_loop_quit_closure_; DISALLOW_COPY_AND_ASSIGN(WaitForLoadingStateHelper); };
diff --git a/chrome/browser/resource_coordinator/tab_manager_browsertest.cc b/chrome/browser/resource_coordinator/tab_manager_browsertest.cc index 2371ce8..78ab431 100644 --- a/chrome/browser/resource_coordinator/tab_manager_browsertest.cc +++ b/chrome/browser/resource_coordinator/tab_manager_browsertest.cc
@@ -333,8 +333,9 @@ // Select the first tab. It should reload. WindowedNotificationObserver reload1( content::NOTIFICATION_NAV_ENTRY_COMMITTED, - base::Bind(&ObserveNavEntryCommitted, - embedded_test_server()->GetURL("a.com", "/title1.html"))); + base::BindRepeating( + &ObserveNavEntryCommitted, + embedded_test_server()->GetURL("a.com", "/title1.html"))); chrome::SelectNumberedTab(browser(), 0); reload1.Wait(); // Make sure the FindBarController gets the right WebContents. @@ -348,8 +349,9 @@ // Select the third tab. It should reload. WindowedNotificationObserver reload2( content::NOTIFICATION_NAV_ENTRY_COMMITTED, - base::Bind(&ObserveNavEntryCommitted, - embedded_test_server()->GetURL("a.com", "/title3.html"))); + base::BindRepeating( + &ObserveNavEntryCommitted, + embedded_test_server()->GetURL("a.com", "/title3.html"))); chrome::SelectNumberedTab(browser(), 2); reload2.Wait(); EXPECT_EQ(2, tsm()->active_index()); @@ -363,16 +365,18 @@ EXPECT_FALSE(chrome::CanGoForward(browser())); WindowedNotificationObserver back1( content::NOTIFICATION_NAV_ENTRY_COMMITTED, - base::Bind(&ObserveNavEntryCommitted, - embedded_test_server()->GetURL("a.com", "/title2.html"))); + base::BindRepeating( + &ObserveNavEntryCommitted, + embedded_test_server()->GetURL("a.com", "/title2.html"))); chrome::GoBack(browser(), WindowOpenDisposition::CURRENT_TAB); back1.Wait(); EXPECT_TRUE(chrome::CanGoBack(browser())); EXPECT_TRUE(chrome::CanGoForward(browser())); WindowedNotificationObserver back2( content::NOTIFICATION_NAV_ENTRY_COMMITTED, - base::Bind(&ObserveNavEntryCommitted, - embedded_test_server()->GetURL("a.com", "/title1.html"))); + base::BindRepeating( + &ObserveNavEntryCommitted, + embedded_test_server()->GetURL("a.com", "/title1.html"))); chrome::GoBack(browser(), WindowOpenDisposition::CURRENT_TAB); back2.Wait(); EXPECT_FALSE(chrome::CanGoBack(browser()));
diff --git a/chrome/browser/resources/chromeos/accessibility/accessibility_common/magnifier/magnifier_test.js b/chrome/browser/resources/chromeos/accessibility/accessibility_common/magnifier/magnifier_test.js index af88108..07790995 100644 --- a/chrome/browser/resources/chromeos/accessibility/accessibility_common/magnifier/magnifier_test.js +++ b/chrome/browser/resources/chromeos/accessibility/accessibility_common/magnifier/magnifier_test.js
@@ -66,35 +66,38 @@ } }; -TEST_F('MagnifierE2ETest', 'MovesScreenMagnifierToFocusedElement', function() { - const site = ` +// Flaky: http://crbug.com/1171635 +TEST_F( + 'MagnifierE2ETest', 'DISABLED_MovesScreenMagnifierToFocusedElement', + function() { + const site = ` <button id="apple">Apple</button><br /> <button id="banana" style="margin-top: 400px">Banana</button> `; - this.runWithLoadedTree(site, async function(root) { - const magnifier = accessibilityCommon.getMagnifierForTest(); - magnifier.setIsInitializingForTest(false); + this.runWithLoadedTree(site, async function(root) { + const magnifier = accessibilityCommon.getMagnifierForTest(); + magnifier.setIsInitializingForTest(false); - const apple = root.find({attributes: {name: 'Apple'}}); - const banana = root.find({attributes: {name: 'Banana'}}); + const apple = root.find({attributes: {name: 'Apple'}}); + const banana = root.find({attributes: {name: 'Banana'}}); - // Focus and move magnifier to apple. - apple.focus(); + // Focus and move magnifier to apple. + apple.focus(); - // Verify magnifier bounds contains apple, but not banana. - let bounds = await this.getNextMagnifierBounds(); - assertTrue(RectUtil.contains(bounds, apple.location)); - assertFalse(RectUtil.contains(bounds, banana.location)); + // Verify magnifier bounds contains apple, but not banana. + let bounds = await this.getNextMagnifierBounds(); + assertTrue(RectUtil.contains(bounds, apple.location)); + assertFalse(RectUtil.contains(bounds, banana.location)); - // Focus and move magnifier to banana. - banana.focus(); + // Focus and move magnifier to banana. + banana.focus(); - // Verify magnifier bounds contains banana, but not apple. - bounds = await this.getNextMagnifierBounds(); - assertFalse(RectUtil.contains(bounds, apple.location)); - assertTrue(RectUtil.contains(bounds, banana.location)); - }); -}); + // Verify magnifier bounds contains banana, but not apple. + bounds = await this.getNextMagnifierBounds(); + assertFalse(RectUtil.contains(bounds, apple.location)); + assertTrue(RectUtil.contains(bounds, banana.location)); + }); + }); // Disabled - flaky: https://crbug.com/1145612 TEST_F( @@ -137,8 +140,10 @@ }); +// Flaky: http://crbug.com/1171750 TEST_F( - 'MagnifierE2ETest', 'MovesScreenMagnifierToActiveDescendant', function() { + 'MagnifierE2ETest', 'DISABLED_MovesScreenMagnifierToActiveDescendant', + function() { const site = ` <span tabindex="1">Top</span> <div id="group" role="group" style="width: 200px"
diff --git a/chrome/browser/resources/chromeos/accessibility/chromevox/learn_mode/learn_mode_test.js b/chrome/browser/resources/chromeos/accessibility/chromevox/learn_mode/learn_mode_test.js index 8b8bf4bc..86781ce 100644 --- a/chrome/browser/resources/chromeos/accessibility/chromevox/learn_mode/learn_mode_test.js +++ b/chrome/browser/resources/chromeos/accessibility/chromevox/learn_mode/learn_mode_test.js
@@ -89,7 +89,9 @@ } }; -TEST_F('ChromeVoxLearnModeTest', 'KeyboardInput', function() { +// TODO(crbug.com/1128926, crbug.com/1172387): +// Test times out flakily. +TEST_F('ChromeVoxLearnModeTest', 'DISABLED_KeyboardInput', function() { this.runOnLearnModePage((mockFeedback, evt) => { // Press Search+Right. mockFeedback.call(doKeyDown({keyCode: KeyCode.SEARCH, metaKey: true}))
diff --git a/chrome/browser/resources/chromeos/accessibility/chromevox/options/options_test.js b/chrome/browser/resources/chromeos/accessibility/chromevox/options/options_test.js index ee28c9c..9c177b3 100644 --- a/chrome/browser/resources/chromeos/accessibility/chromevox/options/options_test.js +++ b/chrome/browser/resources/chromeos/accessibility/chromevox/options/options_test.js
@@ -69,16 +69,10 @@ }); }); -// TODO(crbug.com/1128926): Test times out flakily in MSAN builds. -TEST_F_WITH_PREAMBLE( - ` -#if defined(MEMORY_SANITIZER) -#define MAYBE_PunctuationEchoSelect DISABLED_PunctuationEchoSelect -#else -#define MAYBE_PunctuationEchoSelect PunctuationEchoSelect -#endif -`, - 'ChromeVoxOptionsTest', 'MAYBE_PunctuationEchoSelect', function() { +// TODO(crbug.com/1128926, crbug.com/1172387): +// Test times out flakily. +TEST_F( + 'ChromeVoxOptionsTest', 'DISABLED_PunctuationEchoSelect', function() { this.runOnOptionsPage((mockFeedback, evt) => { const PUNCTUATION_ECHO_NONE = '0'; const PUNCTUATION_ECHO_SOME = '1'; @@ -123,7 +117,9 @@ }); }); -TEST_F('ChromeVoxOptionsTest', 'SmartStickyMode', function() { +// TODO(crbug.com/1128926, crbug.com/1172387): +// Test times out flakily. +TEST_F('ChromeVoxOptionsTest', 'DISABLED_SmartStickyMode', function() { this.runOnOptionsPage((mockFeedback, evt) => { const smartStickyModeCheckbox = evt.target.find({ role: chrome.automation.RoleType.CHECK_BOX, @@ -150,16 +146,11 @@ .replay(); }); }); -// TODO(crbug.com/1169396): Test times out or crashes flakily in MSAN builds. -TEST_F_WITH_PREAMBLE( - ` -#if defined(MEMORY_SANITIZER) -#define MAYBE_UsePitchChanges DISABLED_UsePitchChanges -#else -#define MAYBE_UsePitchChanges UsePitchChanges -#endif -`, - 'ChromeVoxOptionsTest', 'MAYBE_UsePitchChanges', function() { + +// TODO(crbug.com/1169396, crbug.com/1172387): +// Test times out or crashes flakily. +TEST_F( + 'ChromeVoxOptionsTest', 'DISABLED_UsePitchChanges', function() { this.runOnOptionsPage((mockFeedback, evt) => { const pitchChangesCheckbox = evt.target.find({ role: chrome.automation.RoleType.CHECK_BOX,
diff --git a/chrome/browser/resources/chromeos/edu_coexistence/edu_coexistence_css.html b/chrome/browser/resources/chromeos/edu_coexistence/edu_coexistence_css.html index 3fe3f64a..3dce954 100644 --- a/chrome/browser/resources/chromeos/edu_coexistence/edu_coexistence_css.html +++ b/chrome/browser/resources/chromeos/edu_coexistence/edu_coexistence_css.html
@@ -110,6 +110,11 @@ width: 100%; } + span[slot='main'] { + display: flex; + height: 100%; + } + edu-coexistence-button[button-type='back'] { margin-inline-start: auto; }
diff --git a/chrome/browser/resources/chromeos/edu_coexistence/edu_coexistence_template.html b/chrome/browser/resources/chromeos/edu_coexistence/edu_coexistence_template.html index 7645f9a4..4e3c23bb 100644 --- a/chrome/browser/resources/chromeos/edu_coexistence/edu_coexistence_template.html +++ b/chrome/browser/resources/chromeos/edu_coexistence/edu_coexistence_template.html
@@ -55,6 +55,11 @@ background: var(--background-gradient-180); } + .main { + height: 100%; + width: 100%; + } + .footer { align-items: center; display: flex;
diff --git a/chrome/browser/resources/chromeos/edu_coexistence/edu_coexistence_ui.html b/chrome/browser/resources/chromeos/edu_coexistence/edu_coexistence_ui.html index a5192b4..c1ce484 100644 --- a/chrome/browser/resources/chromeos/edu_coexistence/edu_coexistence_ui.html +++ b/chrome/browser/resources/chromeos/edu_coexistence/edu_coexistence_ui.html
@@ -1,10 +1,38 @@ <style include="edu-coexistence-css"> + paper-spinner-lite { + --spinner-size: 38px; + display: none; + height: var(--spinner-size); + margin-bottom: 28px; + width: var(--spinner-size); + } + + paper-spinner-lite[active] { + display: inline-block; + } + + .spinner-container { + align-items: center; + display: flex; + flex-direction: column; + height: 100%; + justify-content: center; + width: 100%; + } </style> <edu-coexistence-template> <span slot="main"> <webview id="signinFrame" hidden$="[[loading_]]" class="signin-frame" - allowscaling></webview> + allowscaling></webview> + <div class ="spinner-container" hidden$="[[!loading_]]"> + <paper-spinner-lite class="spinner" active="[[loading_]]"> + </paper-spinner-lite> + <div id="comment" aria-live="polite" + aria-label$="$i18n{loadingMessage}"> + $i18n{loadingMessage} + </div> + </div> </span> <span slot="buttons"> <div class="buttons-layout" hidden$="[[!showGaiaButtons_]]">
diff --git a/chrome/browser/resources/chromeos/edu_coexistence/edu_coexistence_ui.js b/chrome/browser/resources/chromeos/edu_coexistence/edu_coexistence_ui.js index 7c72bfb..da470e3 100644 --- a/chrome/browser/resources/chromeos/edu_coexistence/edu_coexistence_ui.js +++ b/chrome/browser/resources/chromeos/edu_coexistence/edu_coexistence_ui.js
@@ -6,6 +6,7 @@ import './edu_coexistence_template.js'; import './edu_coexistence_button.js'; import './gaia_action_buttons.js'; +import 'chrome://resources/polymer/v3_0/paper-spinner/paper-spinner-lite.js'; import {WebUIListenerBehavior} from 'chrome://resources/js/web_ui_listener_behavior.m.js'; import {html, Polymer} from 'chrome://resources/polymer/v3_0/polymer/polymer_bundled.min.js';
diff --git a/chrome/browser/resources/settings/chrome_cleanup_page/chrome_cleanup_page.html b/chrome/browser/resources/settings/chrome_cleanup_page/chrome_cleanup_page.html index dcf56121..e8a667b 100644 --- a/chrome/browser/resources/settings/chrome_cleanup_page/chrome_cleanup_page.html +++ b/chrome/browser/resources/settings/chrome_cleanup_page/chrome_cleanup_page.html
@@ -75,13 +75,6 @@ items-to-show="[[ getListEntriesFromStrings_(scannerResults_.registryKeys)]]"> </items-to-remove-list> - <items-to-remove-list - id="extensions-list" - hidden="[[!hasExtensionsToShow_]]" - title="$i18n{chromeCleanupDetailsExtensions}" - items-to-show="[[ - getListEntriesFromStrings_(scannerResults_.extensions)]]"> - </items-to-remove-list> <div class="cr-row continuation"> <div class="secondary"> $i18nRaw{chromeCleanupDetailsExplanation}
diff --git a/chrome/browser/resources/settings/chrome_cleanup_page/chrome_cleanup_page.js b/chrome/browser/resources/settings/chrome_cleanup_page/chrome_cleanup_page.js index 12908225..5b42b1e 100644 --- a/chrome/browser/resources/settings/chrome_cleanup_page/chrome_cleanup_page.js +++ b/chrome/browser/resources/settings/chrome_cleanup_page/chrome_cleanup_page.js
@@ -114,7 +114,6 @@ * @typedef {{ * files: Array<ChromeCleanupFilePath>, * registryKeys: Array<string>, - * extensions: Array<string>, * }} */ let ChromeCleanerScannerResults; @@ -230,7 +229,7 @@ scannerResults_: { type: Array, value() { - return {'files': [], 'registryKeys': [], 'extensions': []}; + return {'files': [], 'registryKeys': []}; }, }, @@ -246,12 +245,6 @@ computed: 'computeHasRegistryKeysToShow_(scannerResults_)', }, - /** @private */ - hasExtensionsToShow_: { - type: Boolean, - computed: 'computeHasExtensionsToShow_(scannerResults_)', - }, - /** @private {chrome.settingsPrivate.PrefObject} */ logsUploadPref_: { type: Object, @@ -282,8 +275,7 @@ }, /** @private {!ChromeCleanerScannerResults} */ - emptyChromeCleanerScannerResults_: - {'files': [], 'registryKeys': [], 'extensions': []}, + emptyChromeCleanerScannerResults_: {'files': [], 'registryKeys': []}, /** @private {?ChromeCleanupProxy} */ browserProxy_: null, @@ -386,18 +378,6 @@ }, /** - * Returns true if user-initiated cleanups are enabled and there are - * extensions to show to the user. - * @param {!ChromeCleanerScannerResults} scannerResults The cleanup - * items to be presented to the user. - * @return {boolean} - * @private - */ - computeHasExtensionsToShow_(scannerResults) { - return scannerResults.extensions.length > 0; - }, - - /** * Listener of event 'chrome-cleanup-on-idle'. * @param {string} idleReason * @private @@ -626,8 +606,7 @@ this.browserProxy_ .getItemsToRemovePluralString( this.scannerResults_.files.length + - this.scannerResults_.registryKeys.length + - this.scannerResults_.extensions.length) + this.scannerResults_.registryKeys.length) .then(setShowItemsLabel); },
diff --git a/chrome/browser/resources/settings/chromeos/BUILD.gn b/chrome/browser/resources/settings/chromeos/BUILD.gn index 522c77d0..7edeb30 100644 --- a/chrome/browser/resources/settings/chromeos/BUILD.gn +++ b/chrome/browser/resources/settings/chromeos/BUILD.gn
@@ -451,6 +451,7 @@ "chromeos/personalization_page/change_picture_browser_proxy.m.js", "chromeos/personalization_page/personalization_page.m.js", "chromeos/personalization_page/wallpaper_browser_proxy.m.js", + "chromeos/personalization_page/wallpaper_subpage.m.js", "chromeos/pref_to_setting_metric_converter.m.js", "chromeos/route_origin_behavior.m.js", "controls/controlled_button.m.js", @@ -942,6 +943,8 @@ "chromeos/personalization_page/personalization_page.js", "chromeos/personalization_page/wallpaper_browser_proxy.html", "chromeos/personalization_page/wallpaper_browser_proxy.js", + "chromeos/personalization_page/wallpaper_subpage.js", + "chromeos/personalization_page/wallpaper_subpage.html", "chromeos/pref_to_setting_metric_converter.html", "chromeos/pref_to_setting_metric_converter.js", "chromeos/route_origin_behavior.html",
diff --git a/chrome/browser/resources/settings/chromeos/os_route.js b/chrome/browser/resources/settings/chromeos/os_route.js index fe3c317e..1957c2e 100644 --- a/chrome/browser/resources/settings/chromeos/os_route.js +++ b/chrome/browser/resources/settings/chromeos/os_route.js
@@ -163,6 +163,8 @@ r.CHANGE_PICTURE = createSubpage( r.PERSONALIZATION, mojom.CHANGE_PICTURE_SUBPAGE_PATH, Subpage.kChangePicture); + r.WALLPAPER = createSubpage( + r.PERSONALIZATION, mojom.WALLPAPER_SUBPAGE_PATH, Subpage.kWallpaper); r.AMBIENT_MODE = createSubpage( r.PERSONALIZATION, mojom.AMBIENT_MODE_SUBPAGE_PATH, Subpage.kAmbientMode);
diff --git a/chrome/browser/resources/settings/chromeos/os_settings_routes.js b/chrome/browser/resources/settings/chromeos/os_settings_routes.js index 5b1378c..c22d680 100644 --- a/chrome/browser/resources/settings/chromeos/os_settings_routes.js +++ b/chrome/browser/resources/settings/chromeos/os_settings_routes.js
@@ -86,6 +86,7 @@ * STYLUS: !settings.Route, * SYNC: !settings.Route, * SYNC_ADVANCED: !settings.Route, + * WALLPAPER: !settings.Route, * }} */ /* #export */ let OsSettingsRoutes;
diff --git a/chrome/browser/resources/settings/chromeos/personalization_page/BUILD.gn b/chrome/browser/resources/settings/chromeos/personalization_page/BUILD.gn index 4baa1ca0..d02040ba 100644 --- a/chrome/browser/resources/settings/chromeos/personalization_page/BUILD.gn +++ b/chrome/browser/resources/settings/chromeos/personalization_page/BUILD.gn
@@ -12,6 +12,7 @@ ":change_picture", ":change_picture_browser_proxy", ":personalization_page", + ":wallpaper_subpage", ] } @@ -57,6 +58,13 @@ externs_list = [ "$externs_path/chrome_send.js" ] } +js_library("wallpaper_subpage") { + deps = [ + ":wallpaper_browser_proxy", + "//ui/webui/resources/js:cr", + ] +} + js_type_check("closure_compile_module") { is_polymer3 = true deps = [ @@ -64,6 +72,7 @@ ":change_picture_browser_proxy.m", ":personalization_page.m", ":wallpaper_browser_proxy.m", + ":wallpaper_subpage.m", ] } @@ -118,11 +127,21 @@ extra_deps = [ ":modulize" ] } +js_library("wallpaper_subpage.m") { + sources = [ "$root_gen_dir/chrome/browser/resources/settings/chromeos/personalization_page/wallpaper_subpage.m.js" ] + deps = [ + ":wallpaper_browser_proxy.m", + "//third_party/polymer/v3_0/components-chromium/polymer:polymer_bundled", + ] + extra_deps = [ ":wallpaper_subpage_module" ] +} + group("polymer3_elements") { public_deps = [ ":change_picture_module", ":modulize", ":personalization_page_module", + ":wallpaper_subpage_module", ] } @@ -147,6 +166,15 @@ auto_imports = os_settings_auto_imports } +polymer_modulizer("wallpaper_subpage") { + js_file = "wallpaper_subpage.js" + html_file = "wallpaper_subpage.html" + html_type = "dom-module" + migrated_imports = os_settings_migrated_imports + namespace_rewrites = os_settings_namespace_rewrites + auto_imports = os_settings_auto_imports +} + js_modulizer("modulize") { input_files = [ "change_picture_browser_proxy.js",
diff --git a/chrome/browser/resources/settings/chromeos/personalization_page/personalization_page.html b/chrome/browser/resources/settings/chromeos/personalization_page/personalization_page.html index 65a24021..543573b 100644 --- a/chrome/browser/resources/settings/chromeos/personalization_page/personalization_page.html +++ b/chrome/browser/resources/settings/chromeos/personalization_page/personalization_page.html
@@ -13,6 +13,7 @@ <link rel="import" href="../../settings_page/settings_subpage.html"> <link rel="import" href="../../settings_shared_css.html"> <link rel="import" href="wallpaper_browser_proxy.html"> +<link rel="import" href="wallpaper_subpage.html"> <dom-module id="settings-personalization-page"> <template> @@ -25,18 +26,27 @@ on-click="navigateToChangePicture_" role-description="$i18n{subpageArrowRoleDescription}"> </cr-link-row> - <cr-link-row class="hr" id="wallpaperButton" - hidden="[[!showWallpaperRow_]]" - on-click="openWallpaperManager_" label="$i18n{setWallpaper}" - sub-label="$i18n{openWallpaperApp}" - disabled="[[isWallpaperPolicyControlled_]]" external - deep-link-focus-id$="[[Setting.kOpenWallpaper]]"> - <template is="dom-if" if="[[isWallpaperPolicyControlled_]]"> - <cr-policy-indicator id="wallpaperPolicyIndicator" - indicator-type="devicePolicy"> - </cr-policy-indicator> - </template> - </cr-link-row> + <template is="dom-if" if="[[!isWallpaperWebUIEnabled_]]"> + <cr-link-row class="hr" id="wallpaperButton" + hidden="[[!showWallpaperRow_]]" + on-click="openWallpaperManager_" label="$i18n{setWallpaper}" + sub-label="$i18n{openWallpaperApp}" + disabled="[[isWallpaperPolicyControlled_]]" external + deep-link-focus-id$="[[Setting.kOpenWallpaper]]"> + <template is="dom-if" if="[[isWallpaperPolicyControlled_]]"> + <cr-policy-indicator id="wallpaperPolicyIndicator" + indicator-type="devicePolicy"> + </cr-policy-indicator> + </template> + </cr-link-row> + </template> + <template is="dom-if" if="[[isWallpaperWebUIEnabled_]]"> + <cr-link-row class="hr" id="wallpaperRow" + hidden="[[!showWallpaperRow_]]" on-click="navigateToWallpaper_" + label="$i18n{setWallpaper}" + role-description="i18n{subpageArrowRoleDescription}"> + </cr-link-row> + </template> <!-- Ambient mode --> <template is="dom-if" if="[[isAmbientModeEnabled_]]"> @@ -60,6 +70,17 @@ </settings-subpage> </template> + <template is="dom-if" if="[[isWallpaperWebUIEnabled_]]"> + <template is="dom-if" route-path="/wallpaper"> + <settings-subpage + associated-control="[[$$('#wallpaperRow')]]" + page-title="$i18n{setWallpaper}"> + <settings-wallpaper-page> + </settings-wallpaper-page> + </settings-subpage> + </template> + </template> + <template is="dom-if" if="[[isAmbientModeEnabled_]]"> <template is="dom-if" route-path="/ambientMode"> <settings-subpage
diff --git a/chrome/browser/resources/settings/chromeos/personalization_page/personalization_page.js b/chrome/browser/resources/settings/chromeos/personalization_page/personalization_page.js index 42288a50..437d1c4 100644 --- a/chrome/browser/resources/settings/chromeos/personalization_page/personalization_page.js +++ b/chrome/browser/resources/settings/chromeos/personalization_page/personalization_page.js
@@ -36,6 +36,16 @@ readOnly: true, }, + /** @private */ + isWallpaperWebUIEnabled_: { + type: Boolean, + value() { + return loadTimeData.getBoolean('isWallpaperWebUIEnabled') && + this.showWallpaperRow_; + }, + readOnly: true, + }, + /** @private {!Map<string, string>} */ focusConfig_: { type: Object, @@ -107,6 +117,11 @@ }, /** @private */ + navigateToWallpaper_() { + settings.Router.getInstance().navigateTo(settings.routes.WALLPAPER); + }, + + /** @private */ navigateToAmbientMode_() { settings.Router.getInstance().navigateTo(settings.routes.AMBIENT_MODE); },
diff --git a/chrome/browser/resources/settings/chromeos/personalization_page/wallpaper_subpage.html b/chrome/browser/resources/settings/chromeos/personalization_page/wallpaper_subpage.html new file mode 100644 index 0000000..204a483 --- /dev/null +++ b/chrome/browser/resources/settings/chromeos/personalization_page/wallpaper_subpage.html
@@ -0,0 +1,14 @@ +<link rel="import" href="chrome://resources/html/polymer.html"> + +<link rel="import" href="chrome://resources/cr_elements/shared_style_css.html"> +<link rel="import" href="chrome://resources/cr_elements/shared_vars_css.html"> +<link rel="import" href="../personalization_page/wallpaper_browser_proxy.html"> +<link rel="import" href="../../settings_shared_css.html"> + +<dom-module id="settings-wallpaper-page"> + <template> + <style include="cr-shared-style settings-shared"> + </style> + </template> + <script src="wallpaper_subpage.js"></script> +</dom-module>
diff --git a/chrome/browser/resources/settings/chromeos/personalization_page/wallpaper_subpage.js b/chrome/browser/resources/settings/chromeos/personalization_page/wallpaper_subpage.js new file mode 100644 index 0000000..5f23582 --- /dev/null +++ b/chrome/browser/resources/settings/chromeos/personalization_page/wallpaper_subpage.js
@@ -0,0 +1,25 @@ +// Copyright 2021 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. + +/** + * @fileoverview 'settings-wallpaper-page' is the settings sub-page containing + * wallpaper settings. + */ +Polymer({ + is: 'settings-wallpaper-page', + + behaviors: [], + + properties: {}, + + /** @private {?settings.WallpaperBrowserProxy} */ + browserProxy_: null, + + /** @override */ + created() { + this.browserProxy_ = settings.WallpaperBrowserProxyImpl.getInstance(); + }, + + ready() {}, +});
diff --git a/chrome/browser/resources/tab_search/app.js b/chrome/browser/resources/tab_search/app.js index 3d28fb4..502117d 100644 --- a/chrome/browser/resources/tab_search/app.js +++ b/chrome/browser/resources/tab_search/app.js
@@ -127,11 +127,10 @@ ], }); - // TODO(tluk): The listener should provide the data needed to update the - // WebUI without having to make another round trip request to the Browser. const callbackRouter = this.apiProxy_.getCallbackRouter(); this.listenerIds_.push( - callbackRouter.tabsChanged.addListener(() => this.updateTabs_()), + callbackRouter.tabsChanged.addListener( + profileTabs => this.openTabsChanged_(profileTabs.windows)), callbackRouter.tabUpdated.addListener(tab => this.onTabUpdated_(tab)), callbackRouter.tabsRemoved.addListener( tabIds => this.onTabsRemoved_(tabIds)));
diff --git a/chrome/browser/safe_browsing/chrome_cleaner/BUILD.gn b/chrome/browser/safe_browsing/chrome_cleaner/BUILD.gn index da10407..c921fef 100644 --- a/chrome/browser/safe_browsing/chrome_cleaner/BUILD.gn +++ b/chrome/browser/safe_browsing/chrome_cleaner/BUILD.gn
@@ -58,7 +58,6 @@ # TODO(crbug.com/925153): Break dependency cycles with //chrome/browser ":public", "//chrome/browser:browser_process", - "//chrome/browser/extensions", "//chrome/browser/profiles:profile", "//chrome/browser/safe_browsing", "//chrome/browser/ui", @@ -67,12 +66,10 @@ "//components/chrome_cleaner/public/constants", "//components/chrome_cleaner/public/proto", "//components/component_updater", - "//components/crx_file", "//components/pref_registry", "//components/prefs", "//components/safe_browsing/core/common:safe_browsing_prefs", "//content/public/browser", - "//extensions/browser", "//third_party/protobuf:protobuf_lite", ] }
diff --git a/chrome/browser/safe_browsing/chrome_cleaner/chrome_cleaner_controller_impl_win.cc b/chrome/browser/safe_browsing/chrome_cleaner/chrome_cleaner_controller_impl_win.cc index 196b4b1..90a31775 100644 --- a/chrome/browser/safe_browsing/chrome_cleaner/chrome_cleaner_controller_impl_win.cc +++ b/chrome/browser/safe_browsing/chrome_cleaner/chrome_cleaner_controller_impl_win.cc
@@ -46,7 +46,6 @@ #include "components/safe_browsing/core/common/safe_browsing_prefs.h" #include "content/public/browser/browser_task_traits.h" #include "content/public/browser/browser_thread.h" -#include "extensions/browser/extension_registry.h" #include "net/http/http_status_code.h" #include "ui/base/window_open_disposition.h" @@ -467,7 +466,6 @@ void ChromeCleanerControllerImpl::ReplyWithUserResponse( Profile* profile, - extensions::ExtensionService* extension_service, UserResponse user_response) { DCHECK_CALLED_ON_VALID_THREAD(thread_checker_); @@ -485,8 +483,6 @@ RecordCleanerLogsAcceptanceHistogram(true); new_state = State::kCleaning; delegate_->TagForResetting(profile); - extension_service_ = extension_service; - extension_registry_ = extensions::ExtensionRegistry::Get(profile); break; case UserResponse::kAcceptedWithoutLogs: acceptance = PromptUserResponse::ACCEPTED_WITHOUT_LOGS; @@ -494,8 +490,6 @@ RecordCleanerLogsAcceptanceHistogram(false); new_state = State::kCleaning; delegate_->TagForResetting(profile); - extension_service_ = extension_service; - extension_registry_ = extensions::ExtensionRegistry::Get(profile); break; case UserResponse::kDenied: // Fallthrough case UserResponse::kDismissed: @@ -615,8 +609,7 @@ : ChromeCleanerRunner::ChromeMetricsStatus::kDisabled; ChromeCleanerRunner::RunChromeCleanerAndReplyWithExitCode( - extension_service_, extension_registry_, executable_path, - *reporter_invocation_, metrics_status, + executable_path, *reporter_invocation_, metrics_status, base::BindOnce(&ChromeCleanerControllerImpl::WeakOnPromptUser, weak_factory_.GetWeakPtr()), base::BindOnce(&ChromeCleanerControllerImpl::OnConnectionClosed, @@ -654,7 +647,6 @@ DCHECK_EQ(State::kScanning, state()); DCHECK(scanner_results_.files_to_delete().empty()); DCHECK(scanner_results_.registry_keys().empty()); - DCHECK(scanner_results_.extension_ids().empty()); DCHECK(!prompt_user_reply_callback_); DCHECK(!time_scanning_started_.is_null());
diff --git a/chrome/browser/safe_browsing/chrome_cleaner/chrome_cleaner_controller_impl_win.h b/chrome/browser/safe_browsing/chrome_cleaner/chrome_cleaner_controller_impl_win.h index 50553905..51cb14c 100644 --- a/chrome/browser/safe_browsing/chrome_cleaner/chrome_cleaner_controller_impl_win.h +++ b/chrome/browser/safe_browsing/chrome_cleaner/chrome_cleaner_controller_impl_win.h
@@ -19,10 +19,6 @@ #include "chrome/browser/safe_browsing/chrome_cleaner/chrome_prompt_actions_win.h" #include "components/component_updater/component_updater_service.h" -namespace extensions { -class ExtensionRegistry; -} - namespace safe_browsing { // Delegate class that provides services to the ChromeCleanerController class @@ -74,7 +70,6 @@ void OnSwReporterReady(SwReporterInvocationSequence&& invocations) override; void Scan(const SwReporterInvocation& reporter_invocation) override; void ReplyWithUserResponse(Profile* profile, - extensions::ExtensionService* extension_service, UserResponse user_response) override; void Reboot() override; bool IsAllowedByPolicy() override; @@ -129,9 +124,6 @@ // Pointer to either real_delegate_ or one set by tests. ChromeCleanerControllerDelegate* delegate_; - extensions::ExtensionService* extension_service_ = nullptr; - extensions::ExtensionRegistry* extension_registry_ = nullptr; - State state_ = State::kIdle; // Whether Cleanup is powered by an external partner. bool powered_by_partner_ = false;
diff --git a/chrome/browser/safe_browsing/chrome_cleaner/chrome_cleaner_controller_impl_win_unittest.cc b/chrome/browser/safe_browsing/chrome_cleaner/chrome_cleaner_controller_impl_win_unittest.cc index b13d186..36441726 100644 --- a/chrome/browser/safe_browsing/chrome_cleaner/chrome_cleaner_controller_impl_win_unittest.cc +++ b/chrome/browser/safe_browsing/chrome_cleaner/chrome_cleaner_controller_impl_win_unittest.cc
@@ -15,10 +15,8 @@ #include "base/run_loop.h" #include "base/task/post_task.h" #include "base/test/multiprocess_test.h" -#include "base/test/scoped_feature_list.h" #include "base/threading/thread_task_runner_handle.h" #include "build/build_config.h" -#include "chrome/browser/extensions/extension_service_test_base.h" #include "chrome/browser/metrics/chrome_metrics_service_accessor.h" #include "chrome/browser/profiles/profile.h" #include "chrome/browser/profiles/profile_manager.h" @@ -53,8 +51,6 @@ using ::testing::Values; using ::testing::ValuesIn; using CrashPoint = MockChromeCleanerProcess::CrashPoint; -using ExtensionCleaningFeatureStatus = - MockChromeCleanerProcess::ExtensionCleaningFeatureStatus; using IdleReason = ChromeCleanerController::IdleReason; using ItemsReporting = MockChromeCleanerProcess::ItemsReporting; using PromptUserResponse = chrome_cleaner::PromptUserResponse; @@ -231,8 +227,6 @@ typedef std::tuple<CleanerProcessStatus, CrashPoint, UwsFoundStatus, - ExtensionCleaningFeatureStatus, - ItemsReporting, ItemsReporting, UserResponse> ChromeCleanerControllerTestParams; @@ -240,34 +234,20 @@ // Test fixture that runs a mock Chrome Cleaner process in various // configurations and mocks the user's response. class ChromeCleanerControllerTest - : public testing::WithParamInterface<ChromeCleanerControllerTestParams>, + : public ::testing::TestWithParam<ChromeCleanerControllerTestParams>, public ChromeCleanerRunnerTestDelegate, - public ChromeCleanerControllerDelegate, - public extensions::ExtensionServiceTestBase { + public ChromeCleanerControllerDelegate { public: ChromeCleanerControllerTest() = default; ~ChromeCleanerControllerTest() override {} void SetUp() override { std::tie(process_status_, crash_point_, uws_found_status_, - extension_cleaning_feature_status_, registry_keys_reporting_, - extensions_reporting_, user_response_) = GetParam(); - - std::vector<base::Feature> enabled_features; - std::vector<base::Feature> disabled_features; - if (extension_cleaning_feature_status_ == - ExtensionCleaningFeatureStatus::kEnabled) { - enabled_features.push_back(kChromeCleanupExtensionsFeature); - } else { - disabled_features.push_back(kChromeCleanupExtensionsFeature); - } - features_.InitWithFeatures(enabled_features, disabled_features); - - InitializeEmptyExtensionService(); + registry_keys_reporting_, user_response_) = GetParam(); cleaner_process_options_.SetReportedResults( uws_found_status_ != UwsFoundStatus::kNoUwsFound, - registry_keys_reporting_, extensions_reporting_); + registry_keys_reporting_); cleaner_process_options_.set_reboot_required( uws_found_status_ == UwsFoundStatus::kUwsFoundRebootRequired); cleaner_process_options_.set_crash_point(crash_point_); @@ -390,17 +370,6 @@ registry_keys_reporting_ == ItemsReporting::kReported; } - bool ExpectedExtensionsReported() { - if (extension_cleaning_feature_status_ == - ExtensionCleaningFeatureStatus::kDisabled) { - // Extensions should not be shown to the user even if the cleaner process - // reports them, because they cannot be cleaned. - return false; - } - return ExpectedOnInfectedCalled() && - extensions_reporting_ == ItemsReporting::kReported; - } - bool ExpectedPromptAccepted() { return user_response_ == UserResponse::kAcceptedWithLogs || user_response_ == UserResponse::kAcceptedWithoutLogs; @@ -460,12 +429,12 @@ } protected: + content::BrowserTaskEnvironment task_environment_; + CleanerProcessStatus process_status_; MockChromeCleanerProcess::CrashPoint crash_point_; UwsFoundStatus uws_found_status_; - ExtensionCleaningFeatureStatus extension_cleaning_feature_status_; ItemsReporting registry_keys_reporting_; - ItemsReporting extensions_reporting_; ChromeCleanerController::UserResponse user_response_; MockChromeCleanerProcess::Options cleaner_process_options_; @@ -478,8 +447,6 @@ std::vector<Profile*> profiles_to_reset_if_tagged_; bool reboot_flow_started_ = false; - - base::test::ScopedFeatureList features_; }; MULTIPROCESS_TEST_MAIN(MockChromeCleanerProcessMain) { @@ -492,8 +459,7 @@ } TEST_P(ChromeCleanerControllerTest, WithMockCleanerProcess) { - TestingProfileManager profile_manager(TestingBrowserProcess::GetGlobal(), - &testing_local_state_); + TestingProfileManager profile_manager(TestingBrowserProcess::GetGlobal()); ASSERT_TRUE(profile_manager.SetUp()); constexpr char kTestProfileName1[] = "Test 1"; @@ -504,8 +470,6 @@ Profile* profile2 = profile_manager.CreateTestingProfile(kTestProfileName2); ASSERT_TRUE(profile2); - MockChromeCleanerProcess::AddMockExtensionsToProfile(profile1); - const int num_profiles = profile_manager.profile_manager()->GetNumberOfProfiles(); ASSERT_EQ(2, num_profiles); @@ -535,8 +499,8 @@ EXPECT_CALL(mock_observer_, OnInfected(_, _)) .WillOnce(DoAll(SaveArg<1>(&scanner_results_on_infected), InvokeWithoutArgs([this, profile1]() { - controller_->ReplyWithUserResponse( - profile1, service(), user_response_); + controller_->ReplyWithUserResponse(profile1, + user_response_); }))); } else { EXPECT_CALL(mock_observer_, OnInfected(_, _)).Times(0); @@ -589,15 +553,6 @@ scanner_results_on_cleaning.registry_keys(), UnorderedElementsAreArray(scanner_results_on_infected.registry_keys())); } - EXPECT_EQ(!scanner_results_on_infected.extension_ids().empty(), - ExpectedExtensionsReported()); - EXPECT_EQ(!scanner_results_on_cleaning.extension_ids().empty(), - ExpectedExtensionsReported() && ExpectedOnCleaningCalled()); - if (!scanner_results_on_cleaning.extension_ids().empty()) { - EXPECT_THAT( - scanner_results_on_cleaning.extension_ids(), - UnorderedElementsAreArray(scanner_results_on_infected.extension_ids())); - } EXPECT_EQ(ExpectedRebootFlowStarted(), reboot_flow_started_); @@ -640,11 +595,6 @@ ValuesIn(kCrashPointsAfterStartup), Values(UwsFoundStatus::kUwsFoundRebootRequired, UwsFoundStatus::kUwsFoundNoRebootRequired), - Values(ExtensionCleaningFeatureStatus::kEnabled, - ExtensionCleaningFeatureStatus::kDisabled), - Values(ItemsReporting::kUnsupported, - ItemsReporting::kNotReported, - ItemsReporting::kReported), Values(ItemsReporting::kUnsupported, ItemsReporting::kNotReported, ItemsReporting::kReported), @@ -660,8 +610,6 @@ Combine(Values(CleanerProcessStatus::kFetchSuccessValidProcess), ValuesIn(kCrashPointsAfterStartup), Values(UwsFoundStatus::kUwsFoundRebootRequired), - Values(ExtensionCleaningFeatureStatus::kEnabled), - Values(ItemsReporting::kReported), Values(ItemsReporting::kReported), Values(UserResponse::kDenied, UserResponse::kDismissed)), chrome_cleaner::GetParamNameForTest()); @@ -676,8 +624,6 @@ Combine(Values(CleanerProcessStatus::kFetchSuccessValidProcess), ValuesIn(kCrashPointsAfterStartup), Values(UwsFoundStatus::kNoUwsFound), - Values(ExtensionCleaningFeatureStatus::kDisabled), - Values(ItemsReporting::kNotReported), Values(ItemsReporting::kNotReported), Values(UserResponse::kDismissed)), chrome_cleaner::GetParamNameForTest()); @@ -691,8 +637,6 @@ Combine(Values(CleanerProcessStatus::kFetchFailure), Values(CrashPoint::kNone), Values(UwsFoundStatus::kNoUwsFound), - Values(ExtensionCleaningFeatureStatus::kDisabled), - Values(ItemsReporting::kUnsupported), Values(ItemsReporting::kUnsupported), Values(UserResponse::kAcceptedWithLogs)), chrome_cleaner::GetParamNameForTest()); @@ -710,8 +654,6 @@ // doesn't matter. Values(CrashPoint::kOnStartup), Values(UwsFoundStatus::kNoUwsFound), - Values(ExtensionCleaningFeatureStatus::kDisabled), - Values(ItemsReporting::kUnsupported), Values(ItemsReporting::kUnsupported), Values(UserResponse::kAcceptedWithLogs)), chrome_cleaner::GetParamNameForTest());
diff --git a/chrome/browser/safe_browsing/chrome_cleaner/chrome_cleaner_controller_win.h b/chrome/browser/safe_browsing/chrome_cleaner/chrome_cleaner_controller_win.h index b518a96..1183741c 100644 --- a/chrome/browser/safe_browsing/chrome_cleaner/chrome_cleaner_controller_win.h +++ b/chrome/browser/safe_browsing/chrome_cleaner/chrome_cleaner_controller_win.h
@@ -18,10 +18,6 @@ class Profile; -namespace extensions { -class ExtensionService; -} - namespace safe_browsing { // These values are used to send UMA information and are replicated in the @@ -194,7 +190,6 @@ // "Cleanup" button multiple times. virtual void ReplyWithUserResponse( Profile* profile, - extensions::ExtensionService* extension_service, UserResponse user_response) = 0; // If the controller is in the kRebootRequired state, initiates a reboot of
diff --git a/chrome/browser/safe_browsing/chrome_cleaner/chrome_cleaner_dialog_controller_impl_win.cc b/chrome/browser/safe_browsing/chrome_cleaner/chrome_cleaner_dialog_controller_impl_win.cc index cee3e572..93bdafe 100644 --- a/chrome/browser/safe_browsing/chrome_cleaner/chrome_cleaner_dialog_controller_impl_win.cc +++ b/chrome/browser/safe_browsing/chrome_cleaner/chrome_cleaner_dialog_controller_impl_win.cc
@@ -7,7 +7,6 @@ #include "base/metrics/histogram_macros.h" #include "base/metrics/user_metrics.h" #include "base/metrics/user_metrics_action.h" -#include "chrome/browser/extensions/extension_service.h" #include "chrome/browser/profiles/profile.h" #include "chrome/browser/safe_browsing/chrome_cleaner/chrome_cleaner_navigation_util_win.h" #include "chrome/browser/safe_browsing/chrome_cleaner/srt_field_trial_win.h" @@ -16,7 +15,6 @@ #include "chrome/browser/ui/browser_list.h" #include "components/component_updater/pref_names.h" #include "components/prefs/pref_service.h" -#include "extensions/browser/extension_system.h" #include "ui/base/window_open_disposition.h" namespace safe_browsing { @@ -87,11 +85,8 @@ Profile* profile = browser_->profile(); - extensions::ExtensionService* extension_service = - extensions::ExtensionSystem::Get(profile)->extension_service(); - cleaner_controller_->ReplyWithUserResponse( - profile, extension_service, + profile, logs_enabled ? ChromeCleanerController::UserResponse::kAcceptedWithLogs : ChromeCleanerController::UserResponse::kAcceptedWithoutLogs); @@ -109,12 +104,8 @@ Profile* profile = browser_->profile(); - extensions::ExtensionService* extension_service = - extensions::ExtensionSystem::Get(profile)->extension_service(); - cleaner_controller_->ReplyWithUserResponse( - profile, extension_service, - ChromeCleanerController::UserResponse::kDenied); + profile, ChromeCleanerController::UserResponse::kDenied); OnInteractionDone(); } @@ -127,12 +118,8 @@ Profile* profile = browser_->profile(); - extensions::ExtensionService* extension_service = - extensions::ExtensionSystem::Get(profile)->extension_service(); - cleaner_controller_->ReplyWithUserResponse( - profile, extension_service, - ChromeCleanerController::UserResponse::kDismissed); + profile, ChromeCleanerController::UserResponse::kDismissed); OnInteractionDone(); }
diff --git a/chrome/browser/safe_browsing/chrome_cleaner/chrome_cleaner_runner_win.cc b/chrome/browser/safe_browsing/chrome_cleaner/chrome_cleaner_runner_win.cc index f9013d1..33cbdbd 100644 --- a/chrome/browser/safe_browsing/chrome_cleaner/chrome_cleaner_runner_win.cc +++ b/chrome/browser/safe_browsing/chrome_cleaner/chrome_cleaner_runner_win.cc
@@ -47,8 +47,6 @@ // static void ChromeCleanerRunner::RunChromeCleanerAndReplyWithExitCode( - extensions::ExtensionService* extension_service, - extensions::ExtensionRegistry* extension_registry, const base::FilePath& cleaner_executable_path, const SwReporterInvocation& reporter_invocation, ChromeMetricsStatus metrics_status, @@ -62,11 +60,7 @@ std::move(on_process_done), std::move(task_runner))); auto launch_and_wait = base::BindOnce( &ChromeCleanerRunner::LaunchAndWaitForExitOnBackgroundThread, - cleaner_runner, - // base::Unretained is safe because these are long-running services that - // will outlive ChromeCleanerRunner. - base::Unretained(extension_service), - base::Unretained(extension_registry)); + cleaner_runner); auto process_done = base::BindOnce(&ChromeCleanerRunner::OnProcessDone, cleaner_runner); base::ThreadPool::PostTaskAndReplyWithResult( @@ -157,15 +151,12 @@ } ChromeCleanerRunner::ProcessStatus -ChromeCleanerRunner::LaunchAndWaitForExitOnBackgroundThread( - extensions::ExtensionService* extension_service, - extensions::ExtensionRegistry* extension_registry) { +ChromeCleanerRunner::LaunchAndWaitForExitOnBackgroundThread() { TRACE_EVENT0("safe_browsing", "ChromeCleanerRunner::LaunchAndWaitForExitOnBackgroundThread"); auto on_connection_closed = base::BindOnce( &ChromeCleanerRunner::OnConnectionClosed, base::RetainedRef(this)); auto actions = std::make_unique<ChromePromptActions>( - extension_service, extension_registry, base::BindOnce(&ChromeCleanerRunner::OnPromptUser, base::RetainedRef(this)));
diff --git a/chrome/browser/safe_browsing/chrome_cleaner/chrome_cleaner_runner_win.h b/chrome/browser/safe_browsing/chrome_cleaner/chrome_cleaner_runner_win.h index 71e96f7..46319fd3 100644 --- a/chrome/browser/safe_browsing/chrome_cleaner/chrome_cleaner_runner_win.h +++ b/chrome/browser/safe_browsing/chrome_cleaner/chrome_cleaner_runner_win.h
@@ -20,11 +20,6 @@ struct LaunchOptions; } // namespace base -namespace extensions { -class ExtensionRegistry; -class ExtensionService; -} // namespace extensions - namespace safe_browsing { class ChromeCleanerScannerResults; @@ -103,13 +98,8 @@ // callbacks. Finally, when the Chrome Cleaner process terminates, a // ProcessStatus is passed along to |on_process_done|. // - // This IPC interface needs the |extension_service| in order to disable - // extensions that the Cleaner process wants to disable. - // // See ChromePromptChannel for more details of the IPC interface. static void RunChromeCleanerAndReplyWithExitCode( - extensions::ExtensionService* extension_service, - extensions::ExtensionRegistry* extension_registry, const base::FilePath& cleaner_executable_path, const SwReporterInvocation& reporter_invocation, ChromeMetricsStatus metrics_status, @@ -144,9 +134,7 @@ ProcessDoneCallback on_process_done, scoped_refptr<base::SequencedTaskRunner> task_runner); - ProcessStatus LaunchAndWaitForExitOnBackgroundThread( - extensions::ExtensionService* extension_service, - extensions::ExtensionRegistry* extension_registry); + ProcessStatus LaunchAndWaitForExitOnBackgroundThread(); // Invokes the on_process_done_ callback, which should handle the results of // a full cleaner execution whose outcome is given by |launch_status|. This
diff --git a/chrome/browser/safe_browsing/chrome_cleaner/chrome_cleaner_runner_win_unittest.cc b/chrome/browser/safe_browsing/chrome_cleaner/chrome_cleaner_runner_win_unittest.cc index e696b18..5566592 100644 --- a/chrome/browser/safe_browsing/chrome_cleaner/chrome_cleaner_runner_win_unittest.cc +++ b/chrome/browser/safe_browsing/chrome_cleaner/chrome_cleaner_runner_win_unittest.cc
@@ -21,8 +21,6 @@ #include "chrome/browser/safe_browsing/chrome_cleaner/srt_field_trial_win.h" #include "chrome/browser/ui/webui/settings/chrome_cleanup_handler_win.h" #include "chrome/test/base/testing_browser_process.h" -#include "chrome/test/base/testing_profile.h" -#include "chrome/test/base/testing_profile_manager.h" #include "components/chrome_cleaner/public/constants/constants.h" #include "components/chrome_cleaner/test/test_name_helper.h" #include "content/public/test/browser_task_environment.h" @@ -39,8 +37,6 @@ using ::testing::UnorderedElementsAreArray; using ::testing::Values; using ChromeMetricsStatus = ChromeCleanerRunner::ChromeMetricsStatus; -using ExtensionCleaningFeatureStatus = - MockChromeCleanerProcess::ExtensionCleaningFeatureStatus; using PromptUserResponse = chrome_cleaner::PromptUserResponse; using UwsFoundStatus = MockChromeCleanerProcess::UwsFoundStatus; @@ -109,8 +105,6 @@ reporter_invocation.set_chrome_prompt(chrome_prompt_); ChromeCleanerRunner::RunChromeCleanerAndReplyWithExitCode( - /*extension_service=*/nullptr, - /*extension_registry=*/nullptr, base::FilePath(FILE_PATH_LITERAL("cleaner.exe")), reporter_invocation, metrics_status_, base::BindOnce(&ChromeCleanerRunnerSimpleTest::OnPromptUser, @@ -223,8 +217,6 @@ Bool())); typedef std::tuple<UwsFoundStatus, - ExtensionCleaningFeatureStatus, - MockChromeCleanerProcess::ItemsReporting, MockChromeCleanerProcess::ItemsReporting, MockChromeCleanerProcess::CrashPoint, PromptUserResponse::PromptAcceptance> @@ -236,41 +228,22 @@ : public testing::TestWithParam<ChromeCleanerRunnerTestParams>, public ChromeCleanerRunnerTestDelegate { public: - ChromeCleanerRunnerTest() - : profile_manager_(TestingBrowserProcess::GetGlobal()) {} - ~ChromeCleanerRunnerTest() override {} + ChromeCleanerRunnerTest() = default; + ~ChromeCleanerRunnerTest() override = default; void SetUp() override { - // Set up the testing profile, so chrome_cleaner_scanner_results_win can get - // the extensions registry from it. - ASSERT_TRUE(profile_manager_.SetUp()); - testing_profile_ = profile_manager_.CreateTestingProfile("Profile 1"); - MockChromeCleanerProcess::AddMockExtensionsToProfile(testing_profile_); - UwsFoundStatus uws_found_state; MockChromeCleanerProcess::ItemsReporting registry_keys_reporting; - MockChromeCleanerProcess::ItemsReporting extensions_reporting; MockChromeCleanerProcess::CrashPoint crash_point; - std::tie(uws_found_state, extension_cleaning_feature_status_, - registry_keys_reporting, extensions_reporting, crash_point, + std::tie(uws_found_state, registry_keys_reporting, crash_point, prompt_acceptance_to_send_) = GetParam(); ASSERT_FALSE(uws_found_state == UwsFoundStatus::kNoUwsFound && prompt_acceptance_to_send_ != PromptUserResponse::DENIED); - std::vector<base::Feature> enabled_features; - std::vector<base::Feature> disabled_features; - if (extension_cleaning_feature_status_ == - ExtensionCleaningFeatureStatus::kEnabled) { - enabled_features.push_back(kChromeCleanupExtensionsFeature); - } else { - disabled_features.push_back(kChromeCleanupExtensionsFeature); - } - features_.InitWithFeatures(enabled_features, disabled_features); - cleaner_process_options_.SetReportedResults( - uws_found_state != UwsFoundStatus::kNoUwsFound, registry_keys_reporting, - extensions_reporting); + uws_found_state != UwsFoundStatus::kNoUwsFound, + registry_keys_reporting); cleaner_process_options_.set_reboot_required( uws_found_state == UwsFoundStatus::kUwsFoundRebootRequired); cleaner_process_options_.set_crash_point(crash_point); @@ -283,8 +256,6 @@ void CallRunChromeCleaner() { base::CommandLine command_line(base::CommandLine::NO_PROGRAM); ChromeCleanerRunner::RunChromeCleanerAndReplyWithExitCode( - /*extension_service=*/nullptr, - /*extension_registry=*/nullptr, base::FilePath(FILE_PATH_LITERAL("cleaner.exe")), SwReporterInvocation(command_line), ChromeMetricsStatus::kDisabled, base::BindOnce(&ChromeCleanerRunnerTest::OnPromptUser, @@ -350,15 +321,12 @@ protected: content::BrowserTaskEnvironment task_environment_; - TestingProfileManager profile_manager_; - TestingProfile* testing_profile_; base::RunLoop run_loop_; MockChromeCleanerProcess::Options cleaner_process_options_; PromptUserResponse::PromptAcceptance prompt_acceptance_to_send_ = PromptUserResponse::UNSPECIFIED; - ExtensionCleaningFeatureStatus extension_cleaning_feature_status_; // Set by OnProcessDone(). ChromeCleanerRunner::ProcessStatus process_status_; @@ -369,8 +337,6 @@ bool on_prompt_user_called_ = false; bool on_connection_closed_called_ = false; bool on_process_done_called_ = false; - - base::test::ScopedFeatureList features_; }; MULTIPROCESS_TEST_MAIN(MockChromeCleanerProcessMain) { @@ -424,20 +390,6 @@ } else { EXPECT_TRUE(received_scanner_results_.registry_keys().empty()); } - - std::set<base::string16> extension_names; - settings::ChromeCleanupHandler::GetExtensionNamesFromIds( - testing_profile_, received_scanner_results_.extension_ids(), - &extension_names); - if (cleaner_process_options_.extension_ids() && - extension_cleaning_feature_status_ == - ExtensionCleaningFeatureStatus::kEnabled) { - EXPECT_THAT(extension_names, - UnorderedElementsAreArray( - *cleaner_process_options_.expected_extension_names())); - } else { - EXPECT_TRUE(extension_names.empty()); - } } EXPECT_EQ(process_status_.launch_status, @@ -451,11 +403,6 @@ NoUwsFound, ChromeCleanerRunnerTest, Combine(Values(UwsFoundStatus::kNoUwsFound), - // When no UwS is found we don't care about extension removel. - Values(ExtensionCleaningFeatureStatus::kDisabled), - Values(MockChromeCleanerProcess::ItemsReporting::kUnsupported, - MockChromeCleanerProcess::ItemsReporting::kNotReported, - MockChromeCleanerProcess::ItemsReporting::kReported), Values(MockChromeCleanerProcess::ItemsReporting::kUnsupported, MockChromeCleanerProcess::ItemsReporting::kNotReported, MockChromeCleanerProcess::ItemsReporting::kReported), @@ -468,9 +415,6 @@ ChromeCleanerRunnerTest, Combine( Values(UwsFoundStatus::kNoUwsFound), - // When no UwS is found we don't care about extension removel. - Values(ExtensionCleaningFeatureStatus::kDisabled), - Values(MockChromeCleanerProcess::ItemsReporting::kReported), Values(MockChromeCleanerProcess::ItemsReporting::kReported), Values(MockChromeCleanerProcess::CrashPoint::kOnStartup, MockChromeCleanerProcess::CrashPoint::kAfterConnection, @@ -484,11 +428,6 @@ ChromeCleanerRunnerTest, Combine(Values(UwsFoundStatus::kUwsFoundRebootRequired, UwsFoundStatus::kUwsFoundNoRebootRequired), - Values(ExtensionCleaningFeatureStatus::kEnabled, - ExtensionCleaningFeatureStatus::kDisabled), - Values(MockChromeCleanerProcess::ItemsReporting::kUnsupported, - MockChromeCleanerProcess::ItemsReporting::kNotReported, - MockChromeCleanerProcess::ItemsReporting::kReported), Values(MockChromeCleanerProcess::ItemsReporting::kUnsupported, MockChromeCleanerProcess::ItemsReporting::kNotReported, MockChromeCleanerProcess::ItemsReporting::kReported), @@ -503,8 +442,6 @@ ChromeCleanerRunnerTest, Combine( Values(UwsFoundStatus::kUwsFoundRebootRequired), - Values(ExtensionCleaningFeatureStatus::kDisabled), - Values(MockChromeCleanerProcess::ItemsReporting::kReported), Values(MockChromeCleanerProcess::ItemsReporting::kReported), Values(MockChromeCleanerProcess::CrashPoint::kOnStartup, MockChromeCleanerProcess::CrashPoint::kAfterConnection,
diff --git a/chrome/browser/safe_browsing/chrome_cleaner/chrome_cleaner_scanner_results_win.cc b/chrome/browser/safe_browsing/chrome_cleaner/chrome_cleaner_scanner_results_win.cc index ba24639a..a8cc92b 100644 --- a/chrome/browser/safe_browsing/chrome_cleaner/chrome_cleaner_scanner_results_win.cc +++ b/chrome/browser/safe_browsing/chrome_cleaner/chrome_cleaner_scanner_results_win.cc
@@ -10,17 +10,13 @@ ChromeCleanerScannerResults::ChromeCleanerScannerResults( const FileCollection& files_to_delete, - const RegistryKeyCollection& registry_keys, - const ExtensionCollection& extension_ids) - : files_to_delete_(files_to_delete), - registry_keys_(registry_keys), - extension_ids_(extension_ids) {} + const RegistryKeyCollection& registry_keys) + : files_to_delete_(files_to_delete), registry_keys_(registry_keys) {} ChromeCleanerScannerResults::ChromeCleanerScannerResults( const ChromeCleanerScannerResults& other) : files_to_delete_(other.files_to_delete_), - registry_keys_(other.registry_keys_), - extension_ids_(other.extension_ids_) {} + registry_keys_(other.registry_keys_) {} ChromeCleanerScannerResults::~ChromeCleanerScannerResults() = default; @@ -28,7 +24,6 @@ const ChromeCleanerScannerResults& other) { files_to_delete_ = other.files_to_delete_; registry_keys_ = other.registry_keys_; - extension_ids_ = other.extension_ids_; return *this; }
diff --git a/chrome/browser/safe_browsing/chrome_cleaner/chrome_cleaner_scanner_results_win.h b/chrome/browser/safe_browsing/chrome_cleaner/chrome_cleaner_scanner_results_win.h index d4011c1..1561e85 100644 --- a/chrome/browser/safe_browsing/chrome_cleaner/chrome_cleaner_scanner_results_win.h +++ b/chrome/browser/safe_browsing/chrome_cleaner/chrome_cleaner_scanner_results_win.h
@@ -18,12 +18,10 @@ public: using FileCollection = std::set<base::FilePath>; using RegistryKeyCollection = std::set<base::string16>; - using ExtensionCollection = std::set<base::string16>; ChromeCleanerScannerResults(); ChromeCleanerScannerResults(const FileCollection& files_to_delete, - const RegistryKeyCollection& registry_keys, - const ExtensionCollection& extension_ids); + const RegistryKeyCollection& registry_keys); ChromeCleanerScannerResults(const ChromeCleanerScannerResults& other); ~ChromeCleanerScannerResults(); @@ -32,12 +30,10 @@ const FileCollection& files_to_delete() const { return files_to_delete_; } const RegistryKeyCollection& registry_keys() const { return registry_keys_; } - const ExtensionCollection& extension_ids() const { return extension_ids_; } private: FileCollection files_to_delete_; RegistryKeyCollection registry_keys_; - ExtensionCollection extension_ids_; }; } // namespace safe_browsing
diff --git a/chrome/browser/safe_browsing/chrome_cleaner/chrome_prompt_actions_win.cc b/chrome/browser/safe_browsing/chrome_cleaner/chrome_prompt_actions_win.cc index aa3a5eb0..c360515 100644 --- a/chrome/browser/safe_browsing/chrome_cleaner/chrome_prompt_actions_win.cc +++ b/chrome/browser/safe_browsing/chrome_cleaner/chrome_prompt_actions_win.cc
@@ -4,30 +4,15 @@ #include "chrome/browser/safe_browsing/chrome_cleaner/chrome_prompt_actions_win.h" -#include <algorithm> -#include <string> #include <utility> #include "base/check.h" -#include "base/containers/contains.h" -#include "base/feature_list.h" -#include "base/strings/utf_string_conversions.h" -#include "chrome/browser/extensions/extension_service.h" #include "chrome/browser/safe_browsing/chrome_cleaner/chrome_cleaner_scanner_results_win.h" -#include "chrome/browser/safe_browsing/chrome_cleaner/srt_field_trial_win.h" -#include "components/crx_file/id_util.h" -#include "extensions/browser/extension_registry.h" -#include "extensions/browser/uninstall_reason.h" namespace safe_browsing { -ChromePromptActions::ChromePromptActions( - extensions::ExtensionService* extension_service, - extensions::ExtensionRegistry* extension_registry, - PromptUserCallback on_prompt_user) - : extension_service_(extension_service), - extension_registry_(extension_registry), - on_prompt_user_(std::move(on_prompt_user)) { +ChromePromptActions::ChromePromptActions(PromptUserCallback on_prompt_user) + : on_prompt_user_(std::move(on_prompt_user)) { DCHECK(on_prompt_user_); } @@ -36,69 +21,19 @@ void ChromePromptActions::PromptUser( const std::vector<base::FilePath>& files_to_delete, const base::Optional<std::vector<base::string16>>& registry_keys, - const base::Optional<std::vector<base::string16>>& extension_ids, PromptUserReplyCallback callback) { using FileCollection = ChromeCleanerScannerResults::FileCollection; using RegistryKeyCollection = ChromeCleanerScannerResults::RegistryKeyCollection; - using ExtensionCollection = ChromeCleanerScannerResults::ExtensionCollection; DCHECK(on_prompt_user_); - if (base::FeatureList::IsEnabled(kChromeCleanupExtensionsFeature) && - extension_ids) { - extension_ids_ = extension_ids.value(); - } else { - extension_ids_.clear(); - } - ChromeCleanerScannerResults scanner_results( FileCollection(files_to_delete.begin(), files_to_delete.end()), registry_keys ? RegistryKeyCollection(registry_keys->begin(), registry_keys->end()) - : RegistryKeyCollection(), - extension_ids_.empty() - ? ExtensionCollection() - : ExtensionCollection(extension_ids_.begin(), extension_ids_.end())); - + : RegistryKeyCollection()); std::move(on_prompt_user_) .Run(std::move(scanner_results), std::move(callback)); } -// The |extensions_ids| passed to this function are a subset of the -// |extension_ids| passed to PromptUser because the extensions are not all -// disabled at the same time. -bool ChromePromptActions::DisableExtensions( - const std::vector<base::string16>& extension_ids) { - if (extension_service_ == nullptr || extension_ids_.empty()) { - return false; - } - // Clear the stored extension_ids by moving it onto this stack frame, - // so subsequent calls will fail. - std::vector<base::string16> verified_extension_ids{}; - extension_ids_.swap(verified_extension_ids); - bool ids_are_valid = std::all_of( - extension_ids.begin(), extension_ids.end(), - [this, &verified_extension_ids](const base::string16& id) { - std::string id_utf8 = base::UTF16ToUTF8(id); - return crx_file::id_util::IdIsValid(id_utf8) && - base::Contains(verified_extension_ids, id) && - extension_registry_->GetInstalledExtension(id_utf8) != nullptr; - }); - if (!ids_are_valid) { - return false; - } - - // This only uninstalls extensions that have been displayed to the user on - // the cleanup page. - extensions::UninstallReason reason = - extensions::UNINSTALL_REASON_USER_INITIATED; - bool result = true; - for (const base::string16& extension_id : extension_ids) { - result = extension_service_->UninstallExtension( - base::UTF16ToUTF8(extension_id), reason, nullptr) && - result; - } - return result; -} - } // namespace safe_browsing
diff --git a/chrome/browser/safe_browsing/chrome_cleaner/chrome_prompt_actions_win.h b/chrome/browser/safe_browsing/chrome_cleaner/chrome_prompt_actions_win.h index 9e04c657..58c2502 100644 --- a/chrome/browser/safe_browsing/chrome_cleaner/chrome_prompt_actions_win.h +++ b/chrome/browser/safe_browsing/chrome_cleaner/chrome_prompt_actions_win.h
@@ -5,8 +5,6 @@ #ifndef CHROME_BROWSER_SAFE_BROWSING_CHROME_CLEANER_CHROME_PROMPT_ACTIONS_WIN_H_ #define CHROME_BROWSER_SAFE_BROWSING_CHROME_CLEANER_CHROME_PROMPT_ACTIONS_WIN_H_ -#include <ostream> -#include <set> #include <vector> #include "base/callback.h" @@ -15,11 +13,6 @@ #include "base/strings/string16.h" #include "components/chrome_cleaner/public/proto/chrome_prompt.pb.h" -namespace extensions { -class ExtensionRegistry; -class ExtensionService; -} // namespace extensions - namespace safe_browsing { class ChromeCleanerScannerResults; @@ -43,13 +36,9 @@ base::OnceCallback<void(ChromeCleanerScannerResults&&, PromptUserReplyCallback)>; - // Initializes the actions to use |extension_service| to disable extensions - // when the DisableExtensions method is called, and the |on_prompt_user| - // callback to display the prompt when the PromptUser method is called. - // |extension_registry| is used to query if an extension is installed. - ChromePromptActions(extensions::ExtensionService* extension_service, - extensions::ExtensionRegistry* extension_registry, - PromptUserCallback on_prompt_user); + // Initializes the actions to use the |on_prompt_user| callback to display + // the prompt when the PromptUser method is called. + explicit ChromePromptActions(PromptUserCallback on_prompt_user); ~ChromePromptActions(); // Calls the PromptUserCallback to show the prompt. |reply_callback| will be @@ -57,32 +46,15 @@ void PromptUser( const std::vector<base::FilePath>& files_to_delete, const base::Optional<std::vector<base::string16>>& registry_keys, - const base::Optional<std::vector<base::string16>>& extension_ids, PromptUserReplyCallback reply_callback); - // Deletes the given |extension_ids|. Returns false on an error, including if - // not all |extension_ids| were displayed to the user in the last PromptUser - // call. - bool DisableExtensions(const std::vector<base::string16>& extension_ids); - private: ChromePromptActions(const ChromePromptActions& other) = delete; ChromePromptActions& operator=(const ChromePromptActions& other) = delete; - // Extension service used to implement DisableExtensions. This can be null if - // no ExtensionService is available, otherwise it is a long-running service - // that will outlive ChromePromptActions. - extensions::ExtensionService* extension_service_; - - // The ExtensionRegistry instance for the current profile. This is a long- - // lived object that will outlive ChromePromptActions. - extensions::ExtensionRegistry* extension_registry_; - // Callback that will be invoked when PromptUser is called to display the // prompt. PromptUserCallback on_prompt_user_; - - std::vector<base::string16> extension_ids_; }; } // namespace safe_browsing
diff --git a/chrome/browser/safe_browsing/chrome_cleaner/chrome_prompt_channel_win.cc b/chrome/browser/safe_browsing/chrome_cleaner/chrome_prompt_channel_win.cc index f6c26fa23..bd26733 100644 --- a/chrome/browser/safe_browsing/chrome_cleaner/chrome_prompt_channel_win.cc +++ b/chrome/browser/safe_browsing/chrome_cleaner/chrome_prompt_channel_win.cc
@@ -31,7 +31,6 @@ #include "base/win/windows_types.h" #include "components/chrome_cleaner/public/constants/constants.h" #include "components/chrome_cleaner/public/constants/result_codes.h" -#include "extensions/browser/extension_system.h" namespace safe_browsing { @@ -299,12 +298,11 @@ channel, chrome_prompt_request.prompt_user())); break; case ChromePromptRequest::kRemoveExtensions: - task_runner->PostTask( - FROM_HERE, - base::BindOnce(&ChromePromptChannel::HandleRemoveExtensionsRequest, - channel, chrome_prompt_request.remove_extensions())); - break; - case ChromePromptRequest::kCloseConnection: { + LOG(ERROR) << "Received deprecated RemoveExtensions request"; + WriteStatusErrorCodeToHistogram(ErrorCategory::kCustomError, + CustomErrors::kDeprecatedRequest); + return; + case ChromePromptRequest::kCloseConnection: // Normal exit: do not kill the cleaner. OnConnectionClosed will still // be called. kill_cleaner_on_error.ReplaceClosure(base::DoNothing()); @@ -315,7 +313,6 @@ FROM_HERE, base::BindOnce(&ChromePromptChannel::CloseHandles, channel)); return; - } default: LOG(ERROR) << "Read unknown request"; @@ -516,22 +513,11 @@ optional_registry_keys = registry_keys; } - base::Optional<std::vector<base::string16>> optional_extension_ids; if (request.extension_ids_size()) { - std::vector<base::string16> extension_ids; - extension_ids.reserve(request.extension_ids_size()); - for (const std::string& extension_id : request.extension_ids()) { - base::string16 extension_id_utf16; - if (!base::UTF8ToUTF16(extension_id.c_str(), extension_id.size(), - &extension_id_utf16)) { - LOG(ERROR) << "Undisplayable extension id in PromptUserRequest."; - WriteStatusErrorCodeToHistogram(ErrorCategory::kCustomError, - CustomErrors::kUndisplayableExtension); - return; - } - extension_ids.push_back(extension_id_utf16); - } - optional_extension_ids = extension_ids; + LOG(ERROR) << "PromptUserRequest included deprecated extension_ids."; + WriteStatusErrorCodeToHistogram(ErrorCategory::kCustomError, + CustomErrors::kDeprecatedFieldInRequest); + return; } // No error occurred. @@ -549,39 +535,7 @@ }, task_runner_, weak_factory_.GetWeakPtr()); actions_->PromptUser(files_to_delete, optional_registry_keys, - optional_extension_ids, std::move(response_callback)); -} - -void ChromePromptChannel::HandleRemoveExtensionsRequest( - const chrome_cleaner::RemoveExtensionsRequest& request) { - DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); - base::ScopedClosureRunner error_handler(base::BindOnce( - &ChromePromptChannel::CloseHandles, base::Unretained(this))); - - // extension_ids are mandatory. - if (!request.extension_ids_size()) { - LOG(ERROR) << "Bad RemoveExtensionsRequest"; - return; - } - - std::vector<base::string16> extension_ids; - extension_ids.reserve(request.extension_ids_size()); - for (const std::string& extension_id : request.extension_ids()) { - base::string16 extension_id_utf16; - if (!base::UTF8ToUTF16(extension_id.c_str(), extension_id.size(), - &extension_id_utf16)) { - LOG(ERROR) << "Unusable extension id in RemoveExtensionsReqest."; - return; - } - extension_ids.push_back(extension_id_utf16); - } - - // No error occurred. - error_handler.ReplaceClosure(base::DoNothing()); - - chrome_cleaner::RemoveExtensionsResponse response; - response.set_success(actions_->DisableExtensions(extension_ids)); - WriteResponseMessage(response); + std::move(response_callback)); } void ChromePromptChannel::SendPromptUserResponse(
diff --git a/chrome/browser/safe_browsing/chrome_cleaner/chrome_prompt_channel_win.h b/chrome/browser/safe_browsing/chrome_cleaner/chrome_prompt_channel_win.h index 5069a59..0254fcc 100644 --- a/chrome/browser/safe_browsing/chrome_cleaner/chrome_prompt_channel_win.h +++ b/chrome/browser/safe_browsing/chrome_cleaner/chrome_prompt_channel_win.h
@@ -82,7 +82,9 @@ kRequestUnknownField = 7, kUndisplayableFilePath = 8, kUndisplayableRegistryKey = 9, - kUndisplayableExtension = 10, + DEPRECATED_kUndisplayableExtension = 10, + kDeprecatedRequest = 11, + kDeprecatedFieldInRequest = 12, }; static int32_t GetErrorCodeInt(ErrorCategory category, @@ -150,10 +152,6 @@ void HandlePromptUserRequest( const chrome_cleaner::PromptUserRequest& request); - // Handles |request| and sends a RemoveExtensionsResponse in reply. - void HandleRemoveExtensionsRequest( - const chrome_cleaner::RemoveExtensionsRequest& request); - // Closes request_read_handle_ and request_write_handle_, which will trigger // an error handler in ServiceChromePromptRequests. void CloseHandles();
diff --git a/chrome/browser/safe_browsing/chrome_cleaner/chrome_prompt_channel_win_unittest.cc b/chrome/browser/safe_browsing/chrome_cleaner/chrome_prompt_channel_win_unittest.cc index 0a34ff2e..1432146 100644 --- a/chrome/browser/safe_browsing/chrome_cleaner/chrome_prompt_channel_win_unittest.cc +++ b/chrome/browser/safe_browsing/chrome_cleaner/chrome_prompt_channel_win_unittest.cc
@@ -78,8 +78,6 @@ new ChromePromptChannel( /*on_connection_closed=*/run_loop_.QuitClosure(), std::make_unique<ChromePromptActions>( - /*extension_service=*/nullptr, - /*extension_registry=*/nullptr, /*on_prompt_user=*/base::DoNothing()), task_runner), base::OnTaskRunnerDeleter(task_runner));
diff --git a/chrome/browser/safe_browsing/chrome_cleaner/mock_chrome_cleaner_controller_win.h b/chrome/browser/safe_browsing/chrome_cleaner/mock_chrome_cleaner_controller_win.h index 3995291..6e6567f 100644 --- a/chrome/browser/safe_browsing/chrome_cleaner/mock_chrome_cleaner_controller_win.h +++ b/chrome/browser/safe_browsing/chrome_cleaner/mock_chrome_cleaner_controller_win.h
@@ -5,7 +5,6 @@ #ifndef CHROME_BROWSER_SAFE_BROWSING_CHROME_CLEANER_MOCK_CHROME_CLEANER_CONTROLLER_WIN_H_ #define CHROME_BROWSER_SAFE_BROWSING_CHROME_CLEANER_MOCK_CHROME_CLEANER_CONTROLLER_WIN_H_ -#include "chrome/browser/extensions/extension_service.h" #include "chrome/browser/safe_browsing/chrome_cleaner/chrome_cleaner_controller_win.h" #include "testing/gmock/include/gmock/gmock.h" @@ -34,8 +33,7 @@ MOCK_METHOD1(RequestUserInitiatedScan, void(Profile*)); MOCK_METHOD1(MockedOnSwReporterReady, void(SwReporterInvocationSequence&)); MOCK_METHOD1(Scan, void(const safe_browsing::SwReporterInvocation&)); - MOCK_METHOD3(ReplyWithUserResponse, - void(Profile*, extensions::ExtensionService*, UserResponse)); + MOCK_METHOD2(ReplyWithUserResponse, void(Profile*, UserResponse)); MOCK_METHOD0(Reboot, void()); MOCK_METHOD0(IsAllowedByPolicy, bool()); MOCK_METHOD1(IsReportingManagedByPolicy, bool(Profile*));
diff --git a/chrome/browser/safe_browsing/chrome_cleaner/mock_chrome_cleaner_process_win.cc b/chrome/browser/safe_browsing/chrome_cleaner/mock_chrome_cleaner_process_win.cc index 3c5fdc82..90f837a 100644 --- a/chrome/browser/safe_browsing/chrome_cleaner/mock_chrome_cleaner_process_win.cc +++ b/chrome/browser/safe_browsing/chrome_cleaner/mock_chrome_cleaner_process_win.cc
@@ -32,13 +32,9 @@ #include "base/win/win_util.h" #include "build/branding_buildflags.h" #include "build/build_config.h" -#include "chrome/browser/profiles/profile.h" #include "chrome/grit/generated_resources.h" #include "components/chrome_cleaner/public/constants/constants.h" #include "components/chrome_cleaner/public/proto/chrome_prompt.pb.h" -#include "extensions/browser/extension_registry.h" -#include "extensions/common/extension.h" -#include "extensions/common/manifest.h" #include "testing/gmock/include/gmock/gmock.h" #include "testing/gtest/include/gtest/gtest.h" #include "ui/base/l10n/l10n_util.h" @@ -56,7 +52,6 @@ constexpr char kUwsFoundSwitch[] = "mock-uws-found"; constexpr char kRebootRequiredSwitch[] = "mock-reboot-required"; constexpr char kRegistryKeysReportingSwitch[] = "registry-keys-reporting"; -constexpr char kExtensionsReportingSwitch[] = "extensions-reporting"; constexpr char kExpectedUserResponseSwitch[] = "mock-expected-user-response"; // MockCleanerResults @@ -109,11 +104,6 @@ prompt_user->add_registry_keys(base::UTF16ToUTF8(key)); } } - if (options_.extension_ids().has_value()) { - for (const base::string16& id : options_.extension_ids().value()) { - prompt_user->add_extension_ids(base::UTF16ToUTF8(id)); - } - } if (!WriteMessage(request.SerializeAsString())) return; @@ -204,58 +194,8 @@ base::win::ScopedHandle write_handle_; }; -scoped_refptr<extensions::Extension> CreateExtension(const base::string16& name, - const base::string16& id, - std::string* error) { - base::DictionaryValue manifest; - manifest.SetKey("name", base::Value(name)); - manifest.SetKey("version", base::Value("0")); - manifest.SetKey("manifest_version", base::Value(2)); - - return extensions::Extension::Create(base::FilePath(), - extensions::Manifest::INTERNAL, manifest, - 0, base::UTF16ToUTF8(id), error); -} - } // namespace -const base::char16 MockChromeCleanerProcess::kInstalledExtensionId1[] = - L"aaaabbbbccccddddeeeeffffgggghhhh"; -const base::char16 MockChromeCleanerProcess::kInstalledExtensionName1[] = - L"Some Extension"; -const base::char16 MockChromeCleanerProcess::kInstalledExtensionId2[] = - L"ababababcdcdcdcdefefefefghghghgh"; -const base::char16 MockChromeCleanerProcess::kInstalledExtensionName2[] = - L"Another Extension"; -const base::char16 MockChromeCleanerProcess::kUnknownExtensionId[] = - L"unexpectedextensionidabcdefghijk"; - -// static -void MockChromeCleanerProcess::AddMockExtensionsToProfile(Profile* profile) { - extensions::ExtensionRegistry* extension_registry = - extensions::ExtensionRegistry::Get(profile); - scoped_refptr<extensions::Extension> extension; - std::string error; - - extension = - CreateExtension(MockChromeCleanerProcess::kInstalledExtensionName1, - MockChromeCleanerProcess::kInstalledExtensionId1, &error); - if (extension && error.empty()) { - extension_registry->AddEnabled(extension); - } else { - LOG(ERROR) << "Error creating mock extension: " << error; - } - - extension = - CreateExtension(MockChromeCleanerProcess::kInstalledExtensionName2, - MockChromeCleanerProcess::kInstalledExtensionId2, &error); - if (extension && error.empty()) { - extension_registry->AddEnabled(extension); - } else { - LOG(ERROR) << "Error creating mock extension: " << error; - } -} - // static bool MockChromeCleanerProcess::Options::FromCommandLine( const base::CommandLine& command_line, @@ -270,20 +210,9 @@ return false; } - int extensions_reporting_int = -1; - if (!base::StringToInt( - command_line.GetSwitchValueASCII(kExtensionsReportingSwitch), - &extensions_reporting_int) || - extensions_reporting_int < 0 || - extensions_reporting_int >= - static_cast<int>(ItemsReporting::kNumItemsReporting)) { - return false; - } - options->SetReportedResults( command_line.HasSwitch(kUwsFoundSwitch), - static_cast<ItemsReporting>(registry_keys_reporting_int), - static_cast<ItemsReporting>(extensions_reporting_int)); + static_cast<ItemsReporting>(registry_keys_reporting_int)); options->set_reboot_required(command_line.HasSwitch(kRebootRequiredSwitch)); if (command_line.HasSwitch(kCrashPointSwitch)) { @@ -332,22 +261,18 @@ MockChromeCleanerProcess::Options::Options(const Options& other) : files_to_delete_(other.files_to_delete_), registry_keys_(other.registry_keys_), - extension_ids_(other.extension_ids_), reboot_required_(other.reboot_required_), crash_point_(other.crash_point_), registry_keys_reporting_(other.registry_keys_reporting_), - extensions_reporting_(other.extensions_reporting_), expected_user_response_(other.expected_user_response_) {} MockChromeCleanerProcess::Options& MockChromeCleanerProcess::Options::operator=( const Options& other) { files_to_delete_ = other.files_to_delete_; registry_keys_ = other.registry_keys_; - extension_ids_ = other.extension_ids_; reboot_required_ = other.reboot_required_; crash_point_ = other.crash_point_; registry_keys_reporting_ = other.registry_keys_reporting_; - extensions_reporting_ = other.extensions_reporting_; expected_user_response_ = other.expected_user_response_; return *this; } @@ -371,9 +296,6 @@ command_line->AppendSwitchASCII( kRegistryKeysReportingSwitch, base::NumberToString(static_cast<int>(registry_keys_reporting()))); - command_line->AppendSwitchASCII( - kExtensionsReportingSwitch, - base::NumberToString(static_cast<int>(extensions_reporting()))); if (expected_user_response() != PromptUserResponse::UNSPECIFIED) { command_line->AppendSwitchASCII( @@ -384,8 +306,7 @@ void MockChromeCleanerProcess::Options::SetReportedResults( bool has_files_to_remove, - ItemsReporting registry_keys_reporting, - ItemsReporting extensions_reporting) { + ItemsReporting registry_keys_reporting) { if (!has_files_to_remove) files_to_delete_.clear(); if (has_files_to_remove) { @@ -424,48 +345,6 @@ default: NOTREACHED(); } - - extensions_reporting_ = extensions_reporting; - switch (extensions_reporting) { - case ItemsReporting::kUnsupported: - // Defined as an optional object in which an extensions vector is not - // present. - extension_ids_ = base::Optional<std::vector<base::string16>>(); - expected_extension_names_ = base::Optional<std::vector<base::string16>>(); - break; - - case ItemsReporting::kNotReported: - // Defined as an optional object in which an empty extensions vector is - // present. - extension_ids_ = - base::Optional<std::vector<base::string16>>(base::in_place); - expected_extension_names_ = - base::Optional<std::vector<base::string16>>(base::in_place); - break; - - case ItemsReporting::kReported: - // Defined as an optional object in which a non-empty extensions vector is - // present. - extension_ids_ = base::Optional<std::vector<base::string16>>({ - kInstalledExtensionId1, kInstalledExtensionId2, kUnknownExtensionId, - }); -// Scanner results only fetches extension names on Windows Chrome build. -#if defined(OS_WIN) && BUILDFLAG(GOOGLE_CHROME_BRANDING) - expected_extension_names_ = base::Optional<std::vector<base::string16>>({ - kInstalledExtensionName1, kInstalledExtensionName2, - l10n_util::GetStringFUTF16( - IDS_SETTINGS_RESET_CLEANUP_DETAILS_EXTENSION_UNKNOWN, - kUnknownExtensionId), - }); -#else - expected_extension_names_ = - base::Optional<std::vector<base::string16>>(base::in_place); -#endif - break; - - default: - NOTREACHED(); - } } int MockChromeCleanerProcess::Options::ExpectedExitCode( @@ -555,12 +434,6 @@ return out << "UwS" << static_cast<int>(status); } -std::ostream& operator<<( - std::ostream& out, - MockChromeCleanerProcess::ExtensionCleaningFeatureStatus status) { - return out << "Ext" << static_cast<int>(status); -} - std::ostream& operator<<(std::ostream& out, ItemsReporting items_reporting) { return out << "Items" << static_cast<int>(items_reporting); }
diff --git a/chrome/browser/safe_browsing/chrome_cleaner/mock_chrome_cleaner_process_win.h b/chrome/browser/safe_browsing/chrome_cleaner/mock_chrome_cleaner_process_win.h index 3a4c28d..acf2241 100644 --- a/chrome/browser/safe_browsing/chrome_cleaner/mock_chrome_cleaner_process_win.h +++ b/chrome/browser/safe_browsing/chrome_cleaner/mock_chrome_cleaner_process_win.h
@@ -13,8 +13,6 @@ #include "base/strings/string16.h" #include "chrome/browser/safe_browsing/chrome_cleaner/chrome_prompt_actions_win.h" -class Profile; - namespace base { class CommandLine; } // namespace base @@ -45,7 +43,7 @@ kNumCrashPoints, }; - // Indicates if a category of items (e.g. registry keys, extensions) to be + // Indicates if a category of items (e.g. registry keys) to be // removed/changed will be sent from the cleaner process. enum class ItemsReporting { // Simulation of an older cleaner version that doesn't support sending @@ -65,11 +63,6 @@ kUwsFoundNoRebootRequired, }; - enum class ExtensionCleaningFeatureStatus { - kEnabled, - kDisabled, - }; - static constexpr int kInternalTestFailureExitCode = 100001; static constexpr int kDeliberateCrashExitCode = 100002; static constexpr int kNothingFoundExitCode = 2; @@ -77,14 +70,6 @@ static constexpr int kRebootRequiredExitCode = 15; static constexpr int kRebootNotRequiredExitCode = 0; - static const base::char16 kInstalledExtensionId1[]; - static const base::char16 kInstalledExtensionName1[]; - static const base::char16 kInstalledExtensionId2[]; - static const base::char16 kInstalledExtensionName2[]; - static const base::char16 kUnknownExtensionId[]; - - static void AddMockExtensionsToProfile(Profile* profile); - class Options { public: static bool FromCommandLine(const base::CommandLine& command_line, @@ -98,8 +83,7 @@ void AddSwitchesToCommandLine(base::CommandLine* command_line) const; void SetReportedResults(bool has_files_to_remove, - ItemsReporting registry_keys_reporting, - ItemsReporting extensions_reporting); + ItemsReporting registry_keys_reporting); const std::vector<base::FilePath>& files_to_delete() const { return files_to_delete_; @@ -107,14 +91,6 @@ const base::Optional<std::vector<base::string16>>& registry_keys() const { return registry_keys_; } - const base::Optional<std::vector<base::string16>>& extension_ids() const { - return extension_ids_; - } - - const base::Optional<std::vector<base::string16>>& - expected_extension_names() const { - return expected_extension_names_; - } void set_reboot_required(bool reboot_required) { reboot_required_ = reboot_required; @@ -139,22 +115,15 @@ return registry_keys_reporting_; } - ItemsReporting extensions_reporting() const { - return extensions_reporting_; - } - int ExpectedExitCode(chrome_cleaner::PromptUserResponse::PromptAcceptance received_prompt_acceptance) const; private: std::vector<base::FilePath> files_to_delete_; base::Optional<std::vector<base::string16>> registry_keys_; - base::Optional<std::vector<base::string16>> extension_ids_; - base::Optional<std::vector<base::string16>> expected_extension_names_; bool reboot_required_ = false; CrashPoint crash_point_ = CrashPoint::kNone; ItemsReporting registry_keys_reporting_ = ItemsReporting::kUnsupported; - ItemsReporting extensions_reporting_ = ItemsReporting::kUnsupported; chrome_cleaner::PromptUserResponse::PromptAcceptance expected_user_response_ = chrome_cleaner::PromptUserResponse::UNSPECIFIED; @@ -190,10 +159,6 @@ std::ostream& operator<<( std::ostream& out, - MockChromeCleanerProcess::ExtensionCleaningFeatureStatus status); - -std::ostream& operator<<( - std::ostream& out, MockChromeCleanerProcess::ItemsReporting items_reporting); } // namespace safe_browsing
diff --git a/chrome/browser/safe_browsing/chrome_cleaner/srt_delete_extension_win_unittest.cc b/chrome/browser/safe_browsing/chrome_cleaner/srt_delete_extension_win_unittest.cc deleted file mode 100644 index 7b386b2d..0000000 --- a/chrome/browser/safe_browsing/chrome_cleaner/srt_delete_extension_win_unittest.cc +++ /dev/null
@@ -1,264 +0,0 @@ -// Copyright 2018 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/safe_browsing/chrome_cleaner/chrome_prompt_actions_win.h" - -#include <vector> - -#include "base/callback_helpers.h" -#include "base/feature_list.h" -#include "base/location.h" -#include "base/macros.h" -#include "base/sequenced_task_runner.h" -#include "base/strings/string16.h" -#include "base/strings/string_number_conversions.h" -#include "base/strings/utf_string_conversions.h" -#include "base/test/scoped_feature_list.h" -#include "chrome/browser/extensions/extension_service.h" -#include "chrome/browser/extensions/extension_service_test_base.h" -#include "chrome/browser/extensions/test_extension_service.h" -#include "chrome/browser/safe_browsing/chrome_cleaner/srt_field_trial_win.h" -#include "content/public/test/browser_task_environment.h" -#include "extensions/browser/extension_registry.h" -#include "extensions/browser/mock_extension_system.h" -#include "extensions/common/extension.h" -#include "extensions/common/extension_builder.h" -#include "extensions/common/extension_set.h" -#include "testing/gtest/include/gtest/gtest.h" - -namespace safe_browsing { - -class ExtensionDeletionTest : public extensions::ExtensionServiceTestBase { - public: - ~ExtensionDeletionTest() override = default; - - void SetUp() override { - const std::vector<base::Feature> enabled_features = GetEnabledFeatures(); - const std::vector<base::Feature> disabled_features = GetDisabledFeatures(); - - scoped_feature_list_.InitWithFeatures(enabled_features, disabled_features); - - ExtensionServiceTestBase::SetUp(); - } - - protected: - // Protected constructor to make this class abstract. Following - // implementations will be explicit about the feature flag state. - ExtensionDeletionTest() { InitializeEmptyExtensionService(); } - - // Hooks to set up feature flags. - virtual const std::vector<base::Feature> GetEnabledFeatures() const { - return {}; - } - - virtual const std::vector<base::Feature> GetDisabledFeatures() const { - return {}; - } - - // Creates some extension IDs and registers them in the service. - std::vector<base::string16> PopulateExtensionIds( - bool installExtensions = true) { - std::vector<base::string16> extension_ids{}; - extensions::ExtensionService* extension_service = this->service(); - for (int i = 40; i < 43; i++) { - scoped_refptr<const extensions::Extension> extension = - extensions::ExtensionBuilder(base::NumberToString(i)) - .SetManifestKey("version", "1") - .Build(); - auto id = extension->id(); - extension_ids.push_back(base::UTF8ToUTF16(id)); - if (installExtensions) { - extension_service->AddExtension(extension.get()); - extension_service->EnableExtension(id); - } - } - - return extension_ids; - } - - private: - base::test::ScopedFeatureList scoped_feature_list_; - DISALLOW_COPY_AND_ASSIGN(ExtensionDeletionTest); -}; - -class ExtensionDeletionEnabledTest : public ExtensionDeletionTest { - public: - ExtensionDeletionEnabledTest() = default; - ~ExtensionDeletionEnabledTest() override = default; - - protected: - const std::vector<base::Feature> GetEnabledFeatures() const override { - return {kChromeCleanupExtensionsFeature}; - } - - private: - DISALLOW_COPY_AND_ASSIGN(ExtensionDeletionEnabledTest); -}; - -class ExtensionDeletionDisabledTest : public ExtensionDeletionTest { - public: - ExtensionDeletionDisabledTest() = default; - ~ExtensionDeletionDisabledTest() override = default; - - protected: - const std::vector<base::Feature> GetDisabledFeatures() const override { - return {kChromeCleanupExtensionsFeature}; - } - - private: - DISALLOW_COPY_AND_ASSIGN(ExtensionDeletionDisabledTest); -}; - -TEST_F(ExtensionDeletionEnabledTest, DisableExtensionTest) { - std::vector<base::string16> extension_ids = PopulateExtensionIds(); - extensions::ExtensionService* extension_service = this->service(); - extensions::ExtensionRegistry* extension_registry = registry(); - - ChromePromptActions chrome_prompt(extension_service, extension_registry, - base::DoNothing()); - chrome_prompt.PromptUser({}, {}, extension_ids, base::DoNothing()); - std::vector<base::string16> extensions_to_disable{extension_ids[0]}; - EXPECT_TRUE(chrome_prompt.DisableExtensions(extensions_to_disable)); - EXPECT_EQ(extension_registry->GetInstalledExtension( - base::UTF16ToUTF8(extension_ids[0])), - nullptr); - EXPECT_NE(extension_registry->GetInstalledExtension( - base::UTF16ToUTF8(extension_ids[1])), - nullptr); - EXPECT_NE(extension_registry->GetInstalledExtension( - base::UTF16ToUTF8(extension_ids[2])), - nullptr); - - ChromePromptActions chrome_prompt2(extension_service, extension_registry, - base::DoNothing()); - chrome_prompt2.PromptUser({}, {}, extension_ids, base::DoNothing()); - extensions_to_disable = {extension_ids[2], extension_ids[1]}; - EXPECT_TRUE(chrome_prompt2.DisableExtensions(extensions_to_disable)); - EXPECT_EQ(extension_registry->GetInstalledExtension( - base::UTF16ToUTF8(extension_ids[0])), - nullptr); - EXPECT_EQ(extension_registry->GetInstalledExtension( - base::UTF16ToUTF8(extension_ids[1])), - nullptr); - EXPECT_EQ(extension_registry->GetInstalledExtension( - base::UTF16ToUTF8(extension_ids[2])), - nullptr); -} - -TEST_F(ExtensionDeletionEnabledTest, CantDeleteNonPromptedExtensions) { - std::vector<base::string16> extension_ids = PopulateExtensionIds(); - extensions::ExtensionService* extension_service = this->service(); - extensions::ExtensionRegistry* extension_registry = registry(); - - // Call DisableExtensions without prompting. - std::vector<base::string16> extensions_to_disable{extension_ids[0]}; - ChromePromptActions chrome_prompt(extension_service, extension_registry, - base::DoNothing()); - EXPECT_FALSE(chrome_prompt.DisableExtensions(extensions_to_disable)); - EXPECT_NE(extension_registry->GetInstalledExtension( - base::UTF16ToUTF8(extension_ids[0])), - nullptr); - EXPECT_NE(extension_registry->GetInstalledExtension( - base::UTF16ToUTF8(extension_ids[1])), - nullptr); - EXPECT_NE(extension_registry->GetInstalledExtension( - base::UTF16ToUTF8(extension_ids[2])), - nullptr); - - ChromePromptActions chrome_prompt2(extension_service, extension_registry, - base::DoNothing()); - EXPECT_FALSE(chrome_prompt2.DisableExtensions(extension_ids)); - EXPECT_NE(extension_registry->GetInstalledExtension( - base::UTF16ToUTF8(extension_ids[0])), - nullptr); - EXPECT_NE(extension_registry->GetInstalledExtension( - base::UTF16ToUTF8(extension_ids[1])), - nullptr); - EXPECT_NE(extension_registry->GetInstalledExtension( - base::UTF16ToUTF8(extension_ids[2])), - nullptr); - - // Prompt for an extension but try to disable different ones. - ChromePromptActions chrome_prompt3(extension_service, extension_registry, - base::DoNothing()); - chrome_prompt3.PromptUser({}, {}, {{extension_ids[2]}}, base::DoNothing()); - EXPECT_FALSE( - chrome_prompt3.DisableExtensions({extension_ids[0], extension_ids[1]})); - EXPECT_NE(extension_registry->GetInstalledExtension( - base::UTF16ToUTF8(extension_ids[0])), - nullptr); - EXPECT_NE(extension_registry->GetInstalledExtension( - base::UTF16ToUTF8(extension_ids[1])), - nullptr); - EXPECT_NE(extension_registry->GetInstalledExtension( - base::UTF16ToUTF8(extension_ids[2])), - nullptr); -} - -TEST_F(ExtensionDeletionEnabledTest, EmptyDeletionTest) { - std::vector<base::string16> extension_ids = PopulateExtensionIds(); - extensions::ExtensionService* extension_service = this->service(); - extensions::ExtensionRegistry* extension_registry = registry(); - - ChromePromptActions chrome_prompt(extension_service, extension_registry, - base::DoNothing()); - chrome_prompt.PromptUser({}, {}, extension_ids, base::DoNothing()); - EXPECT_TRUE(chrome_prompt.DisableExtensions({})); - EXPECT_TRUE(extension_service->IsExtensionEnabled( - base::UTF16ToUTF8(extension_ids[0]))); - EXPECT_TRUE(extension_service->IsExtensionEnabled( - base::UTF16ToUTF8(extension_ids[1]))); - EXPECT_TRUE(extension_service->IsExtensionEnabled( - base::UTF16ToUTF8(extension_ids[2]))); -} - -TEST_F(ExtensionDeletionEnabledTest, BadlyFormattedDeletionTest) { - std::vector<base::string16> extension_ids = PopulateExtensionIds(); - extensions::ExtensionService* extension_service = this->service(); - extensions::ExtensionRegistry* extension_registry = registry(); - - ChromePromptActions chrome_prompt(extension_service, extension_registry, - base::DoNothing()); - EXPECT_FALSE(chrome_prompt.DisableExtensions({L"bad-extension-id"})); - EXPECT_FALSE(chrome_prompt.DisableExtensions({L""})); - EXPECT_FALSE( - chrome_prompt.DisableExtensions({L"🤷☝¯\\_(ツ)_/¯✌🤷"})); -} - -TEST_F(ExtensionDeletionEnabledTest, NotInstalledExtensionTest) { - // Don't actually install the extension - std::vector<base::string16> extension_ids = PopulateExtensionIds(false); - extensions::ExtensionService* extension_service = this->service(); - extensions::ExtensionRegistry* extension_registry = registry(); - - ChromePromptActions chrome_prompt(extension_service, extension_registry, - base::DoNothing()); - chrome_prompt.PromptUser({}, {}, extension_ids, base::DoNothing()); - EXPECT_FALSE(chrome_prompt.DisableExtensions(extension_ids)); -} - -TEST_F(ExtensionDeletionDisabledTest, CannotDisableExtensionTest) { - std::vector<base::string16> extension_ids = PopulateExtensionIds(); - extensions::ExtensionService* extension_service = this->service(); - extensions::ExtensionRegistry* extension_registry = registry(); - - ChromePromptActions chrome_prompt(extension_service, extension_registry, - base::DoNothing()); - chrome_prompt.PromptUser({}, {}, extension_ids, base::DoNothing()); - std::vector<base::string16> extensions_to_disable{extension_ids[0]}; - EXPECT_FALSE(chrome_prompt.DisableExtensions(extensions_to_disable)); - - // Even if we called disable, the extension doesn't get disabled. - EXPECT_NE(extension_registry->GetInstalledExtension( - base::UTF16ToUTF8(extension_ids[0])), - nullptr); - EXPECT_NE(extension_registry->GetInstalledExtension( - base::UTF16ToUTF8(extension_ids[1])), - nullptr); - EXPECT_NE(extension_registry->GetInstalledExtension( - base::UTF16ToUTF8(extension_ids[2])), - nullptr); -} - -} // namespace safe_browsing
diff --git a/chrome/browser/safe_browsing/chrome_cleaner/srt_field_trial_win.cc b/chrome/browser/safe_browsing/chrome_cleaner/srt_field_trial_win.cc index 3e1657f4..86f6dc7 100644 --- a/chrome/browser/safe_browsing/chrome_cleaner/srt_field_trial_win.cc +++ b/chrome/browser/safe_browsing/chrome_cleaner/srt_field_trial_win.cc
@@ -39,9 +39,6 @@ const base::Feature kChromeCleanupDistributionFeature{ "ChromeCleanupDistribution", base::FEATURE_DISABLED_BY_DEFAULT}; -const base::Feature kChromeCleanupExtensionsFeature{ - "ChromeCleanupExtensions", base::FEATURE_DISABLED_BY_DEFAULT}; - const base::Feature kResetShortcutsFeature{"ChromeCleanupResetShortcuts", base::FEATURE_DISABLED_BY_DEFAULT};
diff --git a/chrome/browser/safe_browsing/chrome_cleaner/srt_field_trial_win.h b/chrome/browser/safe_browsing/chrome_cleaner/srt_field_trial_win.h index b9534e5..5a896930 100644 --- a/chrome/browser/safe_browsing/chrome_cleaner/srt_field_trial_win.h +++ b/chrome/browser/safe_browsing/chrome_cleaner/srt_field_trial_win.h
@@ -60,10 +60,6 @@ // versions will be downloaded. When not enabled, default versions will be used. extern const base::Feature kChromeCleanupDistributionFeature; -// Extensions cleanup feature. When enabled, Chrome Cleaner will prompt users -// for, and cleanup, bad extensions. -extern const base::Feature kChromeCleanupExtensionsFeature; - // Reset shortcuts feature. When enabled, Chrome Cleaner will reset all Chrome // shortcuts for the current Windows users. extern const base::Feature kResetShortcutsFeature;
diff --git a/chrome/browser/safe_browsing/client_side_detection_service_unittest.cc b/chrome/browser/safe_browsing/client_side_detection_service_unittest.cc index dcd2e92..8f975a4 100644 --- a/chrome/browser/safe_browsing/client_side_detection_service_unittest.cc +++ b/chrome/browser/safe_browsing/client_side_detection_service_unittest.cc
@@ -12,7 +12,6 @@ #include "base/bind.h" #include "base/callback.h" -#include "base/containers/queue.h" #include "base/macros.h" #include "base/metrics/field_trial.h" #include "base/run_loop.h" @@ -135,15 +134,11 @@ response_data, net_error); } - int GetNumReports(base::queue<base::Time>* report_times) { - return csd_service_->GetNumReports(report_times); - } - bool OverPhishingReportLimit() { return csd_service_->OverPhishingReportLimit(); } - base::queue<base::Time>& GetPhishingReportTimes() { + std::deque<base::Time>& GetPhishingReportTimes() { return csd_service_->phishing_report_times_; } @@ -279,12 +274,12 @@ base::Time after = base::Time::Now(); // Check that we have recorded all 3 requests within the correct time range. - base::queue<base::Time>& report_times = GetPhishingReportTimes(); + std::deque<base::Time>& report_times = GetPhishingReportTimes(); EXPECT_EQ(5U, report_times.size()); EXPECT_TRUE(OverPhishingReportLimit()); while (!report_times.empty()) { base::Time time = report_times.back(); - report_times.pop(); + report_times.pop_back(); EXPECT_LE(before, time); EXPECT_GE(after, time); } @@ -302,15 +297,14 @@ csd_service_ = std::make_unique<ClientSideDetectionService>( std::make_unique<ClientSideDetectionServiceDelegate>(profile_)); - base::queue<base::Time>& report_times = GetPhishingReportTimes(); base::Time now = base::Time::Now(); base::TimeDelta twenty_five_hours = base::TimeDelta::FromHours(25); - report_times.push(now - twenty_five_hours); - report_times.push(now - twenty_five_hours); - report_times.push(now); - report_times.push(now); + csd_service_->AddPhishingReport(now - twenty_five_hours); + csd_service_->AddPhishingReport(now - twenty_five_hours); + csd_service_->AddPhishingReport(now); + csd_service_->AddPhishingReport(now); - EXPECT_EQ(2, GetNumReports(&report_times)); + EXPECT_EQ(2, csd_service_->GetPhishingNumReports()); EXPECT_FALSE(OverPhishingReportLimit()); }
diff --git a/chrome/browser/safe_browsing/threat_details_unittest.cc b/chrome/browser/safe_browsing/threat_details_unittest.cc index 5c1706fc..92e12b8 100644 --- a/chrome/browser/safe_browsing/threat_details_unittest.cc +++ b/chrome/browser/safe_browsing/threat_details_unittest.cc
@@ -515,7 +515,7 @@ ->NavigateAndCommit(GURL(kLandingURL)); UnsafeResource resource; - InitResource(SB_THREAT_TYPE_URL_PHISHING, ThreatSource::DATA_SAVER, + InitResource(SB_THREAT_TYPE_URL_PHISHING, ThreatSource::LOCAL_PVER4, true /* is_subresource */, GURL(kThreatURL), &resource); resource.original_url = GURL(kOriginalLandingURL); @@ -533,7 +533,7 @@ ClientSafeBrowsingReportRequest expected; expected.set_type(ClientSafeBrowsingReportRequest::URL_PHISHING); expected.mutable_client_properties()->set_url_api_type( - ClientSafeBrowsingReportRequest::FLYWHEEL); + ClientSafeBrowsingReportRequest::PVER4_NATIVE); expected.set_url(kThreatURL); expected.set_page_url(kLandingURL); expected.set_referrer_url("");
diff --git a/chrome/browser/sessions/session_restore_browsertest.cc b/chrome/browser/sessions/session_restore_browsertest.cc index c32c244..698356a 100644 --- a/chrome/browser/sessions/session_restore_browsertest.cc +++ b/chrome/browser/sessions/session_restore_browsertest.cc
@@ -531,7 +531,6 @@ #endif // BUILDFLAG(IS_CHROMEOS_ASH) // Creates a tabbed browser and popup and makes sure we restore both. -// NOTE: If this flakes, please disable and update https://crbug.com/1166756. IN_PROC_BROWSER_TEST_F(SessionRestoreTest, NormalAndPopup) { // Open a popup. Browser* popup = CreateBrowserForPopup(browser()->profile()); @@ -1396,11 +1395,8 @@ // Verifies that launching with no previous session to a url which closes itself // results in no session being restored on the next launch. // Regression test for http://crbug.com/1052096 -// Flaky: -// - Bulk-disabled for arm64 bot stabilization: https://crbug.com/1154345 -// - Disabled for all platforms: https://crbug.com/1158715 IN_PROC_BROWSER_TEST_F(SessionRestoreTest, - DISABLED_AutoClosedSingleTabDoesNotGetRestored) { + AutoClosedSingleTabDoesNotGetRestored) { Profile* profile = browser()->profile(); std::unique_ptr<ScopedKeepAlive> keep_alive(new ScopedKeepAlive( KeepAliveOrigin::SESSION_RESTORE, KeepAliveRestartOption::DISABLED)); @@ -1419,16 +1415,22 @@ // Create a new browser by navigating to the test page. GURL url = ui_test_utils::GetTestUrl( - base::FilePath().AppendASCII("session_restore"), - base::FilePath().AppendASCII("close_onload.html")); + base::FilePath(base::FilePath::kCurrentDirectory), + base::FilePath(FILE_PATH_LITERAL("title1.html"))); NavigateParams params(profile, url, ui::PAGE_TRANSITION_LINK); Navigate(¶ms); + restore_observer.Wait(); + ASSERT_EQ(1u, BrowserList::GetInstance()->size()); + ui_test_utils::BrowserChangeObserver browser_removed_observer( params.browser, ui_test_utils::BrowserChangeObserver::ChangeType::kRemoved); - restore_observer.Wait(); + // Have the page trigger closing the browser. + ASSERT_TRUE( + content::ExecJs(params.browser->tab_strip_model()->GetActiveWebContents(), + "window.open('', '_self').close()")); // Wait for the browser to close as a result of the single tab closing // itself.
diff --git a/chrome/browser/thumbnail/cc/thumbnail_cache.cc b/chrome/browser/thumbnail/cc/thumbnail_cache.cc index f2a87b86..a9757d2 100644 --- a/chrome/browser/thumbnail/cc/thumbnail_cache.cc +++ b/chrome/browser/thumbnail/cc/thumbnail_cache.cc
@@ -720,18 +720,23 @@ double jpeg_aspect_ratio, SkBitmap bitmap, base::OnceCallback<void(std::vector<uint8_t>)> post_processing_task) { - // In portrait mode, we want to show thumbnails in squares. - // Therefore, the thumbnail saved in portrait mode needs to be cropped to - // a square, or it would be vertically center-aligned, and the top would - // be hidden. - // It's fine to horizontally center-align thumbnail saved in landscape - // mode. + // We want to show thumbnails in a specific aspect ratio. Therefore, the + // thumbnail saved needs to be cropped to the target aspect ratio, otherwise + // it would be vertically center-aligned and the top would be hidden in + // portrait mode, or it would be shown in the wrong aspect ratio in + // landscape mode. int scale = 2; double aspect_ratio = clampAspectRatio(jpeg_aspect_ratio, 0.5, 2.0); - SkIRect dest_subset = { - 0, 0, bitmap.width() / scale, - std::min(bitmap.height() / scale, - (int)(bitmap.width() / scale / aspect_ratio))}; + + int width = std::min(bitmap.width() / scale, + (int)(bitmap.height() * aspect_ratio / scale)); + int height = std::min(bitmap.height() / scale, + (int)(bitmap.width() / aspect_ratio / scale)); + // When cropping the thumbnails, we want to keep the top center portion. + int begin_x = (bitmap.width() / scale - width) / 2; + int end_x = begin_x + width; + SkIRect dest_subset = {begin_x, 0, end_x, height}; + SkBitmap result_bitmap = skia::ImageOperations::Resize( bitmap, skia::ImageOperations::RESIZE_BETTER, bitmap.width() / scale, bitmap.height() / scale, dest_subset);
diff --git a/chrome/browser/translate/translate_model_service_browsertest.cc b/chrome/browser/translate/translate_model_service_browsertest.cc index 2a6b365..7984dfe 100644 --- a/chrome/browser/translate/translate_model_service_browsertest.cc +++ b/chrome/browser/translate/translate_model_service_browsertest.cc
@@ -158,7 +158,7 @@ OptimizationGuideKeyedServiceFactory::GetForProfile(browser()->profile()) ->OverrideTargetModelFileForTesting( optimization_guide::proto::OPTIMIZATION_TARGET_LANGUAGE_DETECTION, - model_file_path()); + /*model_metadata=*/base::nullopt, model_file_path()); RetryForHistogramUntilCountReached( &histogram_tester, @@ -193,7 +193,7 @@ OptimizationGuideKeyedServiceFactory::GetForProfile(browser()->profile()) ->OverrideTargetModelFileForTesting( optimization_guide::proto::OPTIMIZATION_TARGET_LANGUAGE_DETECTION, - model_file_path()); + /*model_metadata=*/base::nullopt, model_file_path()); RetryForHistogramUntilCountReached( &histogram_tester, @@ -211,7 +211,7 @@ OptimizationGuideKeyedServiceFactory::GetForProfile(browser()->profile()) ->OverrideTargetModelFileForTesting( optimization_guide::proto::OPTIMIZATION_TARGET_LANGUAGE_DETECTION, - base::FilePath()); + /*model_metadata=*/base::nullopt, base::FilePath()); RetryForHistogramUntilCountReached( &histogram_tester,
diff --git a/chrome/browser/ui/ash/network/network_state_notifier_unittest.cc b/chrome/browser/ui/ash/network/network_state_notifier_unittest.cc index 99bf7cc2..72eac31 100644 --- a/chrome/browser/ui/ash/network/network_state_notifier_unittest.cc +++ b/chrome/browser/ui/ash/network/network_state_notifier_unittest.cc
@@ -15,7 +15,6 @@ #include "chromeos/dbus/shill/shill_clients.h" #include "chromeos/dbus/shill/shill_device_client.h" #include "chromeos/dbus/shill/shill_service_client.h" -#include "chromeos/login/login_state/login_state.h" #include "chromeos/network/network_connect.h" #include "chromeos/network/network_handler.h" #include "testing/platform_test.h" @@ -65,7 +64,6 @@ void SetUp() override { BrowserWithTestWindowTest::SetUp(); - LoginState::Initialize(); shill_clients::InitializeFakes(); SetupDefaultShillState(); NetworkHandler::Initialize(); @@ -77,7 +75,6 @@ void TearDown() override { NetworkConnect::Shutdown(); network_connect_delegate_.reset(); - LoginState::Shutdown(); NetworkHandler::Shutdown(); shill_clients::Shutdown(); BrowserWithTestWindowTest::TearDown();
diff --git a/chrome/browser/ui/ash/system_tray_client.cc b/chrome/browser/ui/ash/system_tray_client.cc index 9b5cc59..9e71a19 100644 --- a/chrome/browser/ui/ash/system_tray_client.cc +++ b/chrome/browser/ui/ash/system_tray_client.cc
@@ -383,6 +383,10 @@ void SystemTrayClient::ShowNetworkCreate(const std::string& type) { if (type == ::onc::network_type::kCellular) { + if (chromeos::features::IsCellularActivationUiEnabled()) { + ShowSettingsCellularSetup(/*show_psim_flow=*/false); + return; + } const chromeos::NetworkState* cellular = chromeos::NetworkHandler::Get() ->network_state_handler() @@ -395,11 +399,12 @@ chromeos::InternetConfigDialog::ShowDialogForNetworkType(type); } -void SystemTrayClient::ShowSettingsCellularSetupPsimFlow() { +void SystemTrayClient::ShowSettingsCellularSetup(bool show_psim_flow) { // TODO(crbug.com/1093185) Add metrics action recorder std::string page = chromeos::settings::mojom::kCellularNetworksSubpagePath; page += "&showCellularSetup=true"; - page += "&showPsimFlow=true"; + if (show_psim_flow) + page += "&showPsimFlow=true"; ShowSettingsSubPageForActiveUser(page); } @@ -458,7 +463,7 @@ // should open cellular setup dialogs' psim flow if the device has // |kUpdatedCellularActivationUi| feature enabled and is a non-activated // cellular network - ShowSettingsCellularSetupPsimFlow(); + ShowSettingsCellularSetup(/*show_psim_flow=*/true); return; }
diff --git a/chrome/browser/ui/ash/system_tray_client.h b/chrome/browser/ui/ash/system_tray_client.h index 141e3f7..8fbd329 100644 --- a/chrome/browser/ui/ash/system_tray_client.h +++ b/chrome/browser/ui/ash/system_tray_client.h
@@ -75,7 +75,7 @@ void ShowEnterpriseInfo() override; void ShowNetworkConfigure(const std::string& network_id) override; void ShowNetworkCreate(const std::string& type) override; - void ShowSettingsCellularSetupPsimFlow() override; + void ShowSettingsCellularSetup(bool show_psim_flow) override; void ShowThirdPartyVpnCreate(const std::string& extension_id) override; void ShowArcVpnCreate(const std::string& app_id) override; void ShowNetworkSettings(const std::string& network_id) override;
diff --git a/chrome/browser/ui/user_manager.cc b/chrome/browser/ui/user_manager.cc index 46e1ed3b..32a3c09 100644 --- a/chrome/browser/ui/user_manager.cc +++ b/chrome/browser/ui/user_manager.cc
@@ -4,21 +4,7 @@ #include "chrome/browser/ui/user_manager.h" -#include "base/bind.h" -#include "components/guest_view/browser/guest_view_manager.h" - -namespace { - -bool AddToSet(std::set<content::WebContents*>* content_set, - content::WebContents* web_contents) { - content_set->insert(web_contents); - return false; -} - -} // namespace - -UserManagerProfileDialog::BaseDialogDelegate::BaseDialogDelegate() - : guest_web_contents_(nullptr) {} +UserManagerProfileDialog::BaseDialogDelegate::BaseDialogDelegate() = default; bool UserManagerProfileDialog::BaseDialogDelegate::HandleContextMenu( content::RenderFrameHost* render_frame_host, @@ -26,24 +12,3 @@ // Ignores context menu. return true; } - -void UserManagerProfileDialog::BaseDialogDelegate::LoadingStateChanged( - content::WebContents* source, - bool to_different_document) { - if (source->IsLoading() || guest_web_contents_) - return; - - // Try to find the embedded WebView and manage its WebContents. The WebView - // may not be found in the initial page load since it loads asynchronously. - std::set<content::WebContents*> content_set; - guest_view::GuestViewManager* manager = - guest_view::GuestViewManager::FromBrowserContext( - source->GetBrowserContext()); - if (manager) - manager->ForEachGuest(source, base::BindRepeating(&AddToSet, &content_set)); - DCHECK_LE(content_set.size(), 1U); - if (!content_set.empty()) { - guest_web_contents_ = *content_set.begin(); - guest_web_contents_->SetDelegate(this); - } -}
diff --git a/chrome/browser/ui/user_manager.h b/chrome/browser/ui/user_manager.h index 22fd9d1..2c7c0e5 100644 --- a/chrome/browser/ui/user_manager.h +++ b/chrome/browser/ui/user_manager.h
@@ -97,22 +97,15 @@ class BaseDialogDelegate : public content::WebContentsDelegate { public: BaseDialogDelegate(); + BaseDialogDelegate(const BaseDialogDelegate&) = delete; + BaseDialogDelegate& operator=(const BaseDialogDelegate&) = delete; // content::WebContentsDelegate: bool HandleContextMenu(content::RenderFrameHost* render_frame_host, const content::ContextMenuParams& params) override; - // content::WebContentsDelegate: - void LoadingStateChanged(content::WebContents* source, - bool to_different_document) override; - protected: virtual void CloseDialog() = 0; - - // WebContents of the embedded WebView. - content::WebContents* guest_web_contents_; - - DISALLOW_COPY_AND_ASSIGN(BaseDialogDelegate); }; };
diff --git a/chrome/browser/ui/views/frame/browser_non_client_frame_view_chromeos_browsertest.cc b/chrome/browser/ui/views/frame/browser_non_client_frame_view_chromeos_browsertest.cc index 596ae19..b0c3f2e 100644 --- a/chrome/browser/ui/views/frame/browser_non_client_frame_view_chromeos_browsertest.cc +++ b/chrome/browser/ui/views/frame/browser_non_client_frame_view_chromeos_browsertest.cc
@@ -1254,11 +1254,11 @@ SetUpWebApp(); chromeos::FrameCaptionButtonContainerView::TestApi test( GetFrameViewAsh(browser_view_)->caption_button_container_); - EXPECT_TRUE(test.size_button()->GetPaintAsActive()); + EXPECT_TRUE(test.size_button()->paint_as_active()); EXPECT_TRUE(GetPaintingAsActive()); browser_view_->GetWidget()->Deactivate(); - EXPECT_FALSE(test.size_button()->GetPaintAsActive()); + EXPECT_FALSE(test.size_button()->paint_as_active()); EXPECT_FALSE(GetPaintingAsActive()); }
diff --git a/chrome/browser/ui/views/frame/opaque_browser_frame_view.cc b/chrome/browser/ui/views/frame/opaque_browser_frame_view.cc index cf693e98..103b692 100644 --- a/chrome/browser/ui/views/frame/opaque_browser_frame_view.cc +++ b/chrome/browser/ui/views/frame/opaque_browser_frame_view.cc
@@ -508,7 +508,7 @@ button->GetClassName()); views::FrameCaptionButton* frame_caption_button = static_cast<views::FrameCaptionButton*>(button); - frame_caption_button->SetPaintAsActive(active); + frame_caption_button->set_paint_as_active(active); frame_caption_button->SetBackgroundColor(frame_color); } } @@ -541,7 +541,7 @@ const gfx::VectorIcon& icon_image) { views::FrameCaptionButton* button = new views::FrameCaptionButton( views::Button::PressedCallback(), icon_type, ht_component); - button->SetImage(button->GetIcon(), views::FrameCaptionButton::ANIMATE_NO, + button->SetImage(button->icon(), views::FrameCaptionButton::ANIMATE_NO, icon_image); return button; }
diff --git a/chrome/browser/ui/views/frame/opaque_browser_frame_view_layout.cc b/chrome/browser/ui/views/frame/opaque_browser_frame_view_layout.cc index c788b1c..ccb1dba 100644 --- a/chrome/browser/ui/views/frame/opaque_browser_frame_view_layout.cc +++ b/chrome/browser/ui/views/frame/opaque_browser_frame_view_layout.cc
@@ -441,7 +441,7 @@ views::kCaptionButtonInkDropDefaultCornerRadius); button_size = gfx::Size(views::kCaptionButtonWidth, height); button->SetPreferredSize(button_size); - static_cast<views::FrameCaptionButton*>(button)->SetInkDropCornerRadius( + static_cast<views::FrameCaptionButton*>(button)->set_ink_drop_corner_radius( corner_radius); } else if (delegate_->GetFrameButtonStyle() == OpaqueBrowserFrameViewLayoutDelegate::FrameButtonStyle::
diff --git a/chrome/browser/ui/views/location_bar/icon_label_bubble_view.cc b/chrome/browser/ui/views/location_bar/icon_label_bubble_view.cc index 77b3730..612f3d3 100644 --- a/chrome/browser/ui/views/location_bar/icon_label_bubble_view.cc +++ b/chrome/browser/ui/views/location_bar/icon_label_bubble_view.cc
@@ -160,6 +160,7 @@ auto alert_view = std::make_unique<views::AXVirtualView>(); alert_view->GetCustomData().role = ax::mojom::Role::kAlert; + alert_view->GetCustomData().AddState(ax::mojom::State::kInvisible); alert_virtual_view_ = alert_view.get(); GetViewAccessibility().AddVirtualChildView(std::move(alert_view)); } @@ -480,6 +481,8 @@ // which serves to announce it. This is done unconditionally here if there // is text because the animation is intended to draw attention to the // instance anyway. + alert_virtual_view_->GetCustomData().RemoveState( + ax::mojom::State::kInvisible); alert_virtual_view_->GetCustomData().SetName(label); alert_virtual_view_->NotifyAccessibilityEvent(ax::mojom::Event::kAlert); } @@ -491,6 +494,8 @@ void IconLabelBubbleView::AnimateOut() { if (label()->GetVisible()) { label()->SetVisible(false); + alert_virtual_view_->GetCustomData().AddState(ax::mojom::State::kInvisible); + alert_virtual_view_->NotifyAccessibilityEvent(ax::mojom::Event::kHide); HideAnimation(); } }
diff --git a/chrome/browser/ui/webui/chromeos/cellular_setup/cellular_setup_dialog_launcher.cc b/chrome/browser/ui/webui/chromeos/cellular_setup/cellular_setup_dialog_launcher.cc index 53bfd91..191e0385d 100644 --- a/chrome/browser/ui/webui/chromeos/cellular_setup/cellular_setup_dialog_launcher.cc +++ b/chrome/browser/ui/webui/chromeos/cellular_setup/cellular_setup_dialog_launcher.cc
@@ -14,7 +14,7 @@ void OpenCellularSetupDialog(const std::string& cellular_network_guid) { if (chromeos::features::IsCellularActivationUiEnabled()) - SystemTrayClient::Get()->ShowSettingsCellularSetupPsimFlow(); + SystemTrayClient::Get()->ShowSettingsCellularSetup(/*show_psim_flow=*/true); else MobileSetupDialog::ShowByNetworkId(cellular_network_guid); }
diff --git a/chrome/browser/ui/webui/print_preview/print_preview_handler_chromeos_unittest.cc b/chrome/browser/ui/webui/print_preview/print_preview_handler_chromeos_unittest.cc index 7e6a59c0..bb8bef69 100644 --- a/chrome/browser/ui/webui/print_preview/print_preview_handler_chromeos_unittest.cc +++ b/chrome/browser/ui/webui/print_preview/print_preview_handler_chromeos_unittest.cc
@@ -140,12 +140,12 @@ private: content::BrowserTaskEnvironment task_environment_; - std::unique_ptr<TestingProfile> profile_; - std::unique_ptr<content::TestWebUI> web_ui_; - std::unique_ptr<content::WebContents> preview_web_contents_; - PrintPreviewHandlerChromeOS* handler_; base::test::ScopedFeatureList scoped_feature_list_; + std::unique_ptr<TestingProfile> profile_; std::unique_ptr<TestPrintServersManager> print_servers_manager_; + std::unique_ptr<content::WebContents> preview_web_contents_; + std::unique_ptr<content::TestWebUI> web_ui_; + PrintPreviewHandlerChromeOS* handler_; DISALLOW_COPY_AND_ASSIGN(PrintPreviewHandlerChromeOSTest); };
diff --git a/chrome/browser/ui/webui/settings/chrome_cleanup_handler_win.cc b/chrome/browser/ui/webui/settings/chrome_cleanup_handler_win.cc index 37f8b05..848db95e 100644 --- a/chrome/browser/ui/webui/settings/chrome_cleanup_handler_win.cc +++ b/chrome/browser/ui/webui/settings/chrome_cleanup_handler_win.cc
@@ -5,6 +5,7 @@ #include "chrome/browser/ui/webui/settings/chrome_cleanup_handler_win.h" #include <memory> +#include <set> #include <string> #include <utility> @@ -15,13 +16,11 @@ #include "base/metrics/user_metrics.h" #include "base/metrics/user_metrics_action.h" #include "base/strings/string16.h" -#include "base/strings/utf_string_conversions.h" #include "base/synchronization/lock.h" #include "base/values.h" #include "build/branding_buildflags.h" #include "build/build_config.h" #include "chrome/browser/browser_process.h" -#include "chrome/browser/extensions/extension_service.h" #include "chrome/browser/profiles/profile.h" #include "chrome/browser/safe_browsing/chrome_cleaner/chrome_cleaner_controller_win.h" #include "chrome/grit/generated_resources.h" @@ -30,8 +29,6 @@ #include "content/public/browser/web_contents.h" #include "content/public/browser/web_ui.h" #include "content/public/browser/web_ui_message_handler.h" -#include "extensions/browser/extension_registry.h" -#include "extensions/browser/extension_system.h" #include "ui/base/l10n/l10n_util.h" using safe_browsing::ChromeCleanerController; @@ -71,10 +68,6 @@ GetFilesAsListStorage(scanner_results.files_to_delete())); value.SetList("registryKeys", GetStringSetAsListStorage(scanner_results.registry_keys())); - std::set<base::string16> extensions; - ChromeCleanupHandler::GetExtensionNamesFromIds( - profile, scanner_results.extension_ids(), &extensions); - value.SetList("extensions", GetStringSetAsListStorage(extensions)); return value; } @@ -115,28 +108,6 @@ controller_->RemoveObserver(this); } -// static -void ChromeCleanupHandler::GetExtensionNamesFromIds( - Profile* profile, - const std::set<base::string16>& extension_ids, - std::set<base::string16>* extension_names) { -#if BUILDFLAG(GOOGLE_CHROME_BRANDING) - extensions::ExtensionRegistry* extension_registry = - extensions::ExtensionRegistry::Get(profile); - for (const base::string16& extension_id : extension_ids) { - const extensions::Extension* extension = - extension_registry->GetInstalledExtension( - base::UTF16ToUTF8(extension_id)); - if (extension) { - extension_names->insert(base::UTF8ToUTF16(extension->name())); - } else { - extension_names->insert(l10n_util::GetStringFUTF16( - IDS_SETTINGS_RESET_CLEANUP_DETAILS_EXTENSION_UNKNOWN, extension_id)); - } - } -#endif -} - void ChromeCleanupHandler::RegisterMessages() { web_ui()->RegisterMessageCallback( "registerChromeCleanerObserver", @@ -269,11 +240,8 @@ base::RecordAction( base::UserMetricsAction("SoftwareReporter.CleanupWebui_StartCleanup")); - extensions::ExtensionService* extension_service = - extensions::ExtensionSystem::Get(profile_)->extension_service(); - controller_->ReplyWithUserResponse( - profile_, extension_service, + profile_, allow_logs_upload ? ChromeCleanerController::UserResponse::kAcceptedWithLogs : ChromeCleanerController::UserResponse::kAcceptedWithoutLogs);
diff --git a/chrome/browser/ui/webui/settings/chrome_cleanup_handler_win.h b/chrome/browser/ui/webui/settings/chrome_cleanup_handler_win.h index 5f966e8f..c942bc27 100644 --- a/chrome/browser/ui/webui/settings/chrome_cleanup_handler_win.h +++ b/chrome/browser/ui/webui/settings/chrome_cleanup_handler_win.h
@@ -5,11 +5,8 @@ #ifndef CHROME_BROWSER_UI_WEBUI_SETTINGS_CHROME_CLEANUP_HANDLER_WIN_H_ #define CHROME_BROWSER_UI_WEBUI_SETTINGS_CHROME_CLEANUP_HANDLER_WIN_H_ -#include <set> - #include "base/files/file_path.h" #include "base/macros.h" -#include "base/strings/string16.h" #include "chrome/browser/safe_browsing/chrome_cleaner/chrome_cleaner_controller_win.h" #include "chrome/browser/safe_browsing/chrome_cleaner/chrome_cleaner_scanner_results_win.h" #include "chrome/browser/ui/webui/settings/settings_page_ui_handler.h" @@ -31,15 +28,6 @@ explicit ChromeCleanupHandler(Profile* profile); ~ChromeCleanupHandler() override; - // Retrieves extension names for |extension_ids| from |profile|'s extension - // registry and adds them to |extension_names|. If a name cannot be found for - // an extension ID, instead adds a translated string stating the item is an - // unknown extension ID. - static void GetExtensionNamesFromIds( - Profile* profile, - const std::set<base::string16>& extension_ids, - std::set<base::string16>* extension_names); - // SettingsPageUIHandler implementation. void RegisterMessages() override; void OnJavascriptAllowed() override;
diff --git a/chrome/browser/ui/webui/settings/chrome_cleanup_handler_win_unittest.cc b/chrome/browser/ui/webui/settings/chrome_cleanup_handler_win_unittest.cc deleted file mode 100644 index cff17fb..0000000 --- a/chrome/browser/ui/webui/settings/chrome_cleanup_handler_win_unittest.cc +++ /dev/null
@@ -1,56 +0,0 @@ -// Copyright 2018 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/ui/webui/settings/chrome_cleanup_handler_win.h" - -#include "build/branding_buildflags.h" -#include "chrome/browser/safe_browsing/chrome_cleaner/mock_chrome_cleaner_process_win.h" -#include "chrome/grit/generated_resources.h" -#include "chrome/test/base/testing_browser_process.h" -#include "chrome/test/base/testing_profile.h" -#include "chrome/test/base/testing_profile_manager.h" -#include "content/public/test/browser_task_environment.h" -#include "testing/gmock/include/gmock/gmock.h" -#include "testing/gtest/include/gtest/gtest.h" -#include "ui/base/l10n/l10n_util.h" - -namespace settings { - -using safe_browsing::MockChromeCleanerProcess; - -TEST(ChromeCleanupHandlerTest, GetExtensionsNamesFromIds) { - content::BrowserTaskEnvironment task_environment_; - TestingProfileManager profile_manager_(TestingBrowserProcess::GetGlobal()); - - // Set up the testing profile to get the extensions registry from it. - ASSERT_TRUE(profile_manager_.SetUp()); - TestingProfile* testing_profile_ = - profile_manager_.CreateTestingProfile("DummyProfile"); - MockChromeCleanerProcess::AddMockExtensionsToProfile(testing_profile_); - - std::set<base::string16> test_ids = { - MockChromeCleanerProcess::kInstalledExtensionId1, - MockChromeCleanerProcess::kInstalledExtensionId2, - MockChromeCleanerProcess::kUnknownExtensionId, - }; - - std::set<base::string16> expected_names = { -#if BUILDFLAG(GOOGLE_CHROME_BRANDING) - // Extension names are only available in Google-branded builds. - MockChromeCleanerProcess::kInstalledExtensionName1, - MockChromeCleanerProcess::kInstalledExtensionName2, - l10n_util::GetStringFUTF16( - IDS_SETTINGS_RESET_CLEANUP_DETAILS_EXTENSION_UNKNOWN, - MockChromeCleanerProcess::kUnknownExtensionId), -#endif - }; - - std::set<base::string16> actual_names; - ChromeCleanupHandler::GetExtensionNamesFromIds(testing_profile_, test_ids, - &actual_names); - - EXPECT_THAT(actual_names, testing::ContainerEq(expected_names)); -} - -} // namespace settings
diff --git a/chrome/browser/ui/webui/settings/chromeos/constants/routes.mojom b/chrome/browser/ui/webui/settings/chromeos/constants/routes.mojom index 4cc604f..94db45d 100644 --- a/chrome/browser/ui/webui/settings/chromeos/constants/routes.mojom +++ b/chrome/browser/ui/webui/settings/chromeos/constants/routes.mojom
@@ -80,6 +80,7 @@ // Note: Value 502 was for deprecated kAmbientModePhotos. Do not reuse. kAmbientModeGooglePhotosAlbum = 503, kAmbientModeArtGalleryAlbum = 504, + kWallpaper = 505, // Search and Assistant section. kAssistant = 600, @@ -186,6 +187,7 @@ // Personalization section. const string kPersonalizationSectionPath = "personalization"; const string kChangePictureSubpagePath = "changePicture"; +const string kWallpaperSubpagePath = "wallpaper"; const string kAmbientModeSubpagePath = "ambientMode"; const string kAmbientModeGooglePhotosAlbumSubpagePath = "ambientMode/photos?topicSource=0";
diff --git a/chrome/browser/ui/webui/settings/chromeos/constants/routes_util.cc b/chrome/browser/ui/webui/settings/chromeos/constants/routes_util.cc index 341704d..ee84976 100644 --- a/chrome/browser/ui/webui/settings/chromeos/constants/routes_util.cc +++ b/chrome/browser/ui/webui/settings/chromeos/constants/routes_util.cc
@@ -61,6 +61,7 @@ // Personalization section. chromeos::settings::mojom::kPersonalizationSectionPath, chromeos::settings::mojom::kChangePictureSubpagePath, + chromeos::settings::mojom::kWallpaperSubpagePath, chromeos::settings::mojom::kAmbientModeSubpagePath, // Search and Assistant section.
diff --git a/chrome/browser/ui/webui/settings/chromeos/personalization_section.cc b/chrome/browser/ui/webui/settings/chromeos/personalization_section.cc index fa5ccfd..0412c9c4 100644 --- a/chrome/browser/ui/webui/settings/chromeos/personalization_section.cc +++ b/chrome/browser/ui/webui/settings/chromeos/personalization_section.cc
@@ -12,6 +12,7 @@ #include "chrome/browser/profiles/profile.h" #include "chrome/browser/ui/webui/settings/chromeos/ambient_mode_handler.h" #include "chrome/browser/ui/webui/settings/chromeos/change_picture_handler.h" +#include "chrome/browser/ui/webui/settings/chromeos/constants/routes.mojom-forward.h" #include "chrome/browser/ui/webui/settings/chromeos/os_settings_features_util.h" #include "chrome/browser/ui/webui/settings/chromeos/search/search_tag_registry.h" #include "chrome/browser/ui/webui/settings/chromeos/wallpaper_handler.h" @@ -41,14 +42,6 @@ {.section = mojom::Section::kPersonalization}, {IDS_OS_SETTINGS_TAG_PERSONALIZATION_ALT1, IDS_OS_SETTINGS_TAG_PERSONALIZATION_ALT2, SearchConcept::kAltTagEnd}}, - {IDS_OS_SETTINGS_TAG_CHANGE_WALLPAPER, - mojom::kPersonalizationSectionPath, - mojom::SearchResultIcon::kWallpaper, - mojom::SearchResultDefaultRank::kMedium, - mojom::SearchResultType::kSetting, - {.setting = mojom::Setting::kOpenWallpaper}, - {IDS_OS_SETTINGS_TAG_CHANGE_WALLPAPER_ALT1, - IDS_OS_SETTINGS_TAG_CHANGE_WALLPAPER_ALT2, SearchConcept::kAltTagEnd}}, {IDS_OS_SETTINGS_TAG_CHANGE_DEVICE_ACCOUNT_IMAGE, mojom::kChangePictureSubpagePath, mojom::SearchResultIcon::kAvatar, @@ -64,6 +57,34 @@ return *tags; } +const std::vector<SearchConcept>& GetWallpaperChromeAppSearchConcepts() { + static const base::NoDestructor<std::vector<SearchConcept>> tags( + {{IDS_OS_SETTINGS_TAG_CHANGE_WALLPAPER, + mojom::kPersonalizationSectionPath, + mojom::SearchResultIcon::kWallpaper, + mojom::SearchResultDefaultRank::kMedium, + mojom::SearchResultType::kSetting, + {.setting = mojom::Setting::kOpenWallpaper}, + {IDS_OS_SETTINGS_TAG_CHANGE_WALLPAPER_ALT1, + IDS_OS_SETTINGS_TAG_CHANGE_WALLPAPER_ALT2, + SearchConcept::kAltTagEnd}}}); + return *tags; +} + +const std::vector<SearchConcept>& GetWallpaperWebUISearchConcepts() { + static const base::NoDestructor<std::vector<SearchConcept>> tags( + {{IDS_OS_SETTINGS_TAG_CHANGE_WALLPAPER, + mojom::kWallpaperSubpagePath, + mojom::SearchResultIcon::kWallpaper, + mojom::SearchResultDefaultRank::kMedium, + mojom::SearchResultType::kSubpage, + {.subpage = mojom::Subpage::kWallpaper}, + {IDS_OS_SETTINGS_TAG_CHANGE_WALLPAPER_ALT1, + IDS_OS_SETTINGS_TAG_CHANGE_WALLPAPER_ALT2, + SearchConcept::kAltTagEnd}}}); + return *tags; +} + const std::vector<SearchConcept>& GetAmbientModeSearchConcepts() { static const base::NoDestructor<std::vector<SearchConcept>> tags({ {IDS_OS_SETTINGS_TAG_AMBIENT_MODE, @@ -152,6 +173,11 @@ SearchTagRegistry::ScopedTagUpdater updater = registry()->StartUpdate(); updater.AddSearchTags(GetPersonalizationSearchConcepts()); + if (chromeos::features::IsWallpaperWebUIEnabled()) + updater.AddSearchTags(GetWallpaperWebUISearchConcepts()); + else + updater.AddSearchTags(GetWallpaperChromeAppSearchConcepts()); + if (IsAmbientModeAllowed()) { updater.AddSearchTags(GetAmbientModeSearchConcepts()); @@ -249,6 +275,9 @@ l10n_util::GetStringFUTF16( IDS_OS_SETTINGS_AMBIENT_MODE_ALBUMS_SUBPAGE_GOOGLE_PHOTOS_NO_ALBUM, base::UTF8ToUTF16(GetGooglePhotosURL().spec()))); + + html_source->AddBoolean("isWallpaperWebUIEnabled", + chromeos::features::IsWallpaperWebUIEnabled()); } void PersonalizationSection::AddHandlers(content::WebUI* web_ui) { @@ -299,6 +328,12 @@ generator->RegisterNestedSetting(mojom::Setting::kChangeDeviceAccountImage, mojom::Subpage::kChangePicture); + // Wallpaper. + generator->RegisterTopLevelSubpage( + IDS_OS_SETTINGS_SET_WALLPAPER, mojom::Subpage::kWallpaper, + mojom::SearchResultIcon::kWallpaper, + mojom::SearchResultDefaultRank::kMedium, mojom::kWallpaperSubpagePath); + // Ambient mode. generator->RegisterTopLevelSubpage( IDS_OS_SETTINGS_AMBIENT_MODE_TITLE, mojom::Subpage::kAmbientMode,
diff --git a/chrome/browser/ui/webui/settings/settings_localized_strings_provider.cc b/chrome/browser/ui/webui/settings/settings_localized_strings_provider.cc index 9e65213a..1f71da5 100644 --- a/chrome/browser/ui/webui/settings/settings_localized_strings_provider.cc +++ b/chrome/browser/ui/webui/settings/settings_localized_strings_provider.cc
@@ -472,8 +472,6 @@ static constexpr webui::LocalizedString kLocalizedStrings[] = { {"chromeCleanupPageTitle", IDS_SETTINGS_RESET_CLEAN_UP_COMPUTER_PAGE_TITLE}, - {"chromeCleanupDetailsExtensions", - IDS_SETTINGS_RESET_CLEANUP_DETAILS_EXTENSIONS}, {"chromeCleanupDetailsFilesAndPrograms", IDS_SETTINGS_RESET_CLEANUP_DETAILS_FILES_AND_PROGRAMS}, {"chromeCleanupDetailsRegistryEntries",
diff --git a/chrome/browser/ui/webui/signin/inline_login_ui.cc b/chrome/browser/ui/webui/signin/inline_login_ui.cc index b4c1085a..d50206e3 100644 --- a/chrome/browser/ui/webui/signin/inline_login_ui.cc +++ b/chrome/browser/ui/webui/signin/inline_login_ui.cc
@@ -105,6 +105,7 @@ IDS_EDU_COEXISTENCE_ERROR_HEADING); source->AddLocalizedString("eduCoexistenceErrorDescription", IDS_EDU_COEXISTENCE_ERROR_DESCRIPTION); + source->AddLocalizedString("loadingMessage", IDS_LOGIN_GAIA_LOADING_MESSAGE); } #endif // BUILDFLAG(IS_CHROMEOS_ASH)
diff --git a/chrome/browser/ui/webui/tab_search/tab_search.mojom b/chrome/browser/ui/webui/tab_search/tab_search.mojom index 4447b14..e1721ec 100644 --- a/chrome/browser/ui/webui/tab_search/tab_search.mojom +++ b/chrome/browser/ui/webui/tab_search/tab_search.mojom
@@ -104,12 +104,17 @@ // WebUI-side handler for requests from the browser. interface Page { - // Callback when any tabs in the current profile are - // selected/inserted/moved/replaced - TabsChanged(); + // Called when we require a full refresh of the JS's tab list data structures. + // Typically used when tabs in the current profile are deleted, inserted, + // moved or replaced. + // `profile_tabs` is a collection of all open tabs in the current profile. + // This is always populated with at least 1 (the currently active) tab. + TabsChanged(ProfileTabs profile_tabs); - // Callback when a tab is updated within the same web contents. - // e.g. url, title or favicon changed. + // Called when a tab's data has changed and we need only issue an update for + // that specific tab in the JS's data structures. Typically used for url, + // title, or favicon changes. `tab` is always populated with the latest data + // for the affected tab. TabUpdated(Tab tab); // Callback when tabs are removed.
diff --git a/chrome/browser/ui/webui/tab_search/tab_search_page_handler.cc b/chrome/browser/ui/webui/tab_search/tab_search_page_handler.cc index 00ef1a4..78b8f19 100644 --- a/chrome/browser/ui/webui/tab_search/tab_search_page_handler.cc +++ b/chrome/browser/ui/webui/tab_search/tab_search_page_handler.cc
@@ -84,20 +84,7 @@ void TabSearchPageHandler::GetProfileTabs(GetProfileTabsCallback callback) { TRACE_EVENT0("browser", "webui_metric:TabSearchPageHandler:GetProfileTabs"); - auto profile_tabs = tab_search::mojom::ProfileTabs::New(); - for (auto* browser : *BrowserList::GetInstance()) { - if (!ShouldTrackBrowser(browser)) - continue; - TabStripModel* tab_strip_model = browser->tab_strip_model(); - auto window_tabs = tab_search::mojom::WindowTabs::New(); - window_tabs->active = (browser == browser_); - for (int i = 0; i < tab_strip_model->count(); ++i) { - window_tabs->tabs.push_back( - GetTabData(tab_strip_model, tab_strip_model->GetWebContentsAt(i), i)); - } - profile_tabs->windows.push_back(std::move(window_tabs)); - } - + auto profile_tabs = CreateProfileTabs(); // On first run record the number of windows and tabs open for the given // profile. if (!sent_initial_payload_) { @@ -167,6 +154,23 @@ embedder->ShowUI(); } +tab_search::mojom::ProfileTabsPtr TabSearchPageHandler::CreateProfileTabs() { + auto profile_tabs = tab_search::mojom::ProfileTabs::New(); + for (auto* browser : *BrowserList::GetInstance()) { + if (!ShouldTrackBrowser(browser)) + continue; + TabStripModel* tab_strip_model = browser->tab_strip_model(); + auto window_tabs = tab_search::mojom::WindowTabs::New(); + window_tabs->active = (browser == browser_); + for (int i = 0; i < tab_strip_model->count(); ++i) { + window_tabs->tabs.push_back( + GetTabData(tab_strip_model, tab_strip_model->GetWebContentsAt(i), i)); + } + profile_tabs->windows.push_back(std::move(window_tabs)); + } + return profile_tabs; +} + tab_search::mojom::TabPtr TabSearchPageHandler::GetTabData( TabStripModel* tab_strip_model, content::WebContents* contents, @@ -241,7 +245,7 @@ } void TabSearchPageHandler::NotifyTabsChanged() { - page_->TabsChanged(); + page_->TabsChanged(CreateProfileTabs()); debounce_timer_->Stop(); }
diff --git a/chrome/browser/ui/webui/tab_search/tab_search_page_handler.h b/chrome/browser/ui/webui/tab_search/tab_search_page_handler.h index 55475d3..cac89c2 100644 --- a/chrome/browser/ui/webui/tab_search/tab_search_page_handler.h +++ b/chrome/browser/ui/webui/tab_search/tab_search_page_handler.h
@@ -80,6 +80,8 @@ int index; }; + tab_search::mojom::ProfileTabsPtr CreateProfileTabs(); + tab_search::mojom::TabPtr GetTabData(TabStripModel* tab_strip_model, content::WebContents* contents, int index);
diff --git a/chrome/browser/ui/webui/tab_search/tab_search_page_handler_unittest.cc b/chrome/browser/ui/webui/tab_search/tab_search_page_handler_unittest.cc index 038544e..2fb919ca 100644 --- a/chrome/browser/ui/webui/tab_search/tab_search_page_handler_unittest.cc +++ b/chrome/browser/ui/webui/tab_search/tab_search_page_handler_unittest.cc
@@ -50,7 +50,7 @@ } mojo::Receiver<tab_search::mojom::Page> receiver_{this}; - MOCK_METHOD0(TabsChanged, void()); + MOCK_METHOD1(TabsChanged, void(tab_search::mojom::ProfileTabsPtr)); MOCK_METHOD1(TabUpdated, void(tab_search::mojom::TabPtr)); MOCK_METHOD1(TabsRemoved, void(const std::vector<int32_t>& tab_ids)); }; @@ -201,7 +201,7 @@ AddTabWithTitle(browser1(), GURL(kTabUrl2), kTabName2); AddTabWithTitle(browser1(), GURL(kTabUrl1), kTabName1); - EXPECT_CALL(page_, TabsChanged()).Times(1); + EXPECT_CALL(page_, TabsChanged(_)).Times(1); EXPECT_CALL(page_, TabUpdated(_)).Times(2); EXPECT_CALL(page_, TabsRemoved(_)).Times(2); handler()->mock_debounce_timer()->Fire(); @@ -270,7 +270,7 @@ // TabsChanged() and TabsChanged() is only called when the page handler's // timer fires. TEST_F(TabSearchPageHandlerTest, TabsChanged) { - EXPECT_CALL(page_, TabsChanged()).Times(3); + EXPECT_CALL(page_, TabsChanged(_)).Times(3); EXPECT_CALL(page_, TabUpdated(_)).Times(1); EXPECT_CALL(page_, TabsRemoved(_)).Times(3); FireTimer(); // Will call TabsChanged(). @@ -301,7 +301,7 @@ // Ensure that tab model changes in a browser with a different profile // will not call TabsChanged(). TEST_F(TabSearchPageHandlerTest, TabsNotChanged) { - EXPECT_CALL(page_, TabsChanged()).Times(1); + EXPECT_CALL(page_, TabsChanged(_)).Times(1); EXPECT_CALL(page_, TabUpdated(_)).Times(0); FireTimer(); // Will call TabsChanged(). ASSERT_FALSE(IsTimerRunning()); @@ -320,7 +320,7 @@ // Verify tab update event is called correctly with data TEST_F(TabSearchPageHandlerTest, TabUpdated) { - EXPECT_CALL(page_, TabsChanged()).Times(1); + EXPECT_CALL(page_, TabsChanged(_)).Times(1); EXPECT_CALL(page_, TabUpdated(Truly(VerifyTabUpdated))).Times(1); EXPECT_CALL(page_, TabsRemoved(_)).Times(1); AddTabWithTitle(browser1(), GURL(kTabUrl1), kTabName1); @@ -339,7 +339,7 @@ int tab_id = extensions::ExtensionTabUtil::GetTabId( browser2()->tab_strip_model()->GetWebContentsAt(0)); - EXPECT_CALL(page_, TabsChanged()).Times(1); + EXPECT_CALL(page_, TabsChanged(_)).Times(1); EXPECT_CALL(page_, TabUpdated(_)).Times(1); EXPECT_CALL(page_, TabsRemoved(_)).Times(3); handler()->CloseTab(tab_id);
diff --git a/chrome/browser/upgrade_detector/directory_monitor.cc b/chrome/browser/upgrade_detector/directory_monitor.cc index 8ed7f02f..b78d20ab 100644 --- a/chrome/browser/upgrade_detector/directory_monitor.cc +++ b/chrome/browser/upgrade_detector/directory_monitor.cc
@@ -28,6 +28,8 @@ namespace { +// Temporarily disabled for macOS due to https://crbug.com/1156603. +#if !defined(OS_MAC) base::FilePath GetDefaultMonitorLocation() { #if defined(OS_MAC) return base::mac::OuterBundlePath(); @@ -35,6 +37,7 @@ return base::PathService::CheckedGet(base::DIR_EXE); #endif } +#endif // !defined(OS_MAC) } // namespace @@ -81,5 +84,10 @@ // static std::unique_ptr<InstalledVersionMonitor> InstalledVersionMonitor::Create() { +#if defined(OS_MAC) + // Temporarily disabled for macOS due to https://crbug.com/1156603. + return nullptr; +#else return std::make_unique<DirectoryMonitor>(GetDefaultMonitorLocation()); +#endif }
diff --git a/chrome/browser/upgrade_detector/installed_version_poller.cc b/chrome/browser/upgrade_detector/installed_version_poller.cc index 3202016..50f1412 100644 --- a/chrome/browser/upgrade_detector/installed_version_poller.cc +++ b/chrome/browser/upgrade_detector/installed_version_poller.cc
@@ -149,8 +149,11 @@ DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); DCHECK(!monitor_); monitor_ = std::move(monitor); - monitor_->Start(base::BindRepeating(&InstalledVersionPoller::OnMonitorResult, - weak_ptr_factory_.GetWeakPtr())); + if (monitor_) { + monitor_->Start( + base::BindRepeating(&InstalledVersionPoller::OnMonitorResult, + weak_ptr_factory_.GetWeakPtr())); + } } void InstalledVersionPoller::OnMonitorResult(bool error) {
diff --git a/chrome/build/linux.pgo.txt b/chrome/build/linux.pgo.txt index dfdc410..0ca6c7c 100644 --- a/chrome/build/linux.pgo.txt +++ b/chrome/build/linux.pgo.txt
@@ -1 +1 @@ -chrome-linux-master-1611921495-ba7667374208b3a83dd8ca6e3c0f0a4cd502ad08.profdata +chrome-linux-master-1611942760-225517f4752eab7b8db6519da072612feb64407a.profdata
diff --git a/chrome/build/mac.pgo.txt b/chrome/build/mac.pgo.txt index d4bdda1ca..d63bcf2 100644 --- a/chrome/build/mac.pgo.txt +++ b/chrome/build/mac.pgo.txt
@@ -1 +1 @@ -chrome-mac-master-1611921495-a125f0559c0526a49535d419c6ce26bcf5564d80.profdata +chrome-mac-master-1611942760-77b02ae3511caec0c1927117f17121d23c32c3c4.profdata
diff --git a/chrome/build/win32.pgo.txt b/chrome/build/win32.pgo.txt index a46ee92b..b2eec64 100644 --- a/chrome/build/win32.pgo.txt +++ b/chrome/build/win32.pgo.txt
@@ -1 +1 @@ -chrome-win32-master-1611932315-ff9dd12149f86ba33197cabf070dee6871e6ddcb.profdata +chrome-win32-master-1611942760-604769b247cab480f3e8e3e7b707fc2ba1005f47.profdata
diff --git a/chrome/build/win64.pgo.txt b/chrome/build/win64.pgo.txt index 2f17359..24acf98 100644 --- a/chrome/build/win64.pgo.txt +++ b/chrome/build/win64.pgo.txt
@@ -1 +1 @@ -chrome-win64-master-1611932315-ee573c60f56530b4ed85c5a9fac62b39ca63e384.profdata +chrome-win64-master-1611942760-e79331dca2e2d4b4c9533797064c61a3407ebaaa.profdata
diff --git a/chrome/common/url_constants.cc b/chrome/common/url_constants.cc index a38bc79..42ae565 100644 --- a/chrome/common/url_constants.cc +++ b/chrome/common/url_constants.cc
@@ -292,7 +292,7 @@ #if BUILDFLAG(IS_CHROMEOS_ASH) "https://support.google.com/chromebook/?p=enhanced_playback"; #elif defined(OS_ANDROID) -// Keep in sync with chrome/android/java/strings/android_chrome_strings.grd +// Keep in sync with chrome/browser/ui/android/strings/android_chrome_strings.grd "https://support.google.com/chrome/?p=mobile_protected_content"; #endif
diff --git a/chrome/test/BUILD.gn b/chrome/test/BUILD.gn index 8a173de..2871981 100644 --- a/chrome/test/BUILD.gn +++ b/chrome/test/BUILD.gn
@@ -3639,33 +3639,14 @@ "../browser/policy/file_selection_dialogs_policy_handler_unittest.cc", "../browser/policy/homepage_location_policy_handler_unittest.cc", "../browser/policy/javascript_policy_handler_unittest.cc", - "../browser/policy/messaging_layer/encryption/decryption.cc", - "../browser/policy/messaging_layer/encryption/decryption.h", - "../browser/policy/messaging_layer/encryption/encryption_module_unittest.cc", - "../browser/policy/messaging_layer/encryption/encryption_unittest.cc", - "../browser/policy/messaging_layer/encryption/test_encryption_module.cc", - "../browser/policy/messaging_layer/encryption/test_encryption_module.h", - "../browser/policy/messaging_layer/encryption/verification_unittest.cc", "../browser/policy/messaging_layer/public/report_client_unittest.cc", "../browser/policy/messaging_layer/public/report_queue_configuration_unittest.cc", "../browser/policy/messaging_layer/public/report_queue_unittest.cc", - "../browser/policy/messaging_layer/storage/resources/resource_interface_unittest.cc", - "../browser/policy/messaging_layer/storage/storage_queue_stress_test.cc", - "../browser/policy/messaging_layer/storage/storage_queue_unittest.cc", - "../browser/policy/messaging_layer/storage/storage_unittest.cc", - "../browser/policy/messaging_layer/storage/test_storage_module.cc", - "../browser/policy/messaging_layer/storage/test_storage_module.h", "../browser/policy/messaging_layer/upload/dm_server_upload_service_unittest.cc", "../browser/policy/messaging_layer/upload/record_handler_impl_unittest.cc", "../browser/policy/messaging_layer/upload/record_upload_request_builder_unittest.cc", "../browser/policy/messaging_layer/upload/upload_client_unittest.cc", "../browser/policy/messaging_layer/util/report_queue_manual_test_context_unittest.cc", - "../browser/policy/messaging_layer/util/shared_queue_unittest.cc", - "../browser/policy/messaging_layer/util/shared_vector_unittest.cc", - "../browser/policy/messaging_layer/util/status_macros_unittest.cc", - "../browser/policy/messaging_layer/util/status_unittest.cc", - "../browser/policy/messaging_layer/util/statusor_unittest.cc", - "../browser/policy/messaging_layer/util/task_runner_context_unittest.cc", "../browser/policy/profile_policy_connector_unittest.cc", "../browser/policy/webusb_allow_devices_for_urls_policy_handler_unittest.cc", "../browser/predictors/autocomplete_action_predictor_table_unittest.cc", @@ -4207,6 +4188,7 @@ "//components/page_load_metrics/browser:test_support", "//components/page_load_metrics/common:test_support", "//components/query_tiles:unit_tests", + "//components/reporting/storage:test_support", "//components/resources", "//components/safe_browsing:buildflags", "//components/safe_browsing/content/password_protection:mock_password_protection", @@ -4779,7 +4761,6 @@ "../browser/safe_browsing/chrome_cleaner/mock_chrome_cleaner_process_win.cc", "../browser/safe_browsing/chrome_cleaner/mock_chrome_cleaner_process_win.h", "../browser/safe_browsing/chrome_cleaner/reporter_runner_win_unittest.cc", - "../browser/safe_browsing/chrome_cleaner/srt_delete_extension_win_unittest.cc", "../browser/safe_browsing/chrome_cleaner/srt_field_trial_win_unittest.cc", "../browser/task_manager/sampling/shared_sampler_win_unittest.cc", "../utility/importer/edge_database_reader_unittest_win.cc", @@ -5517,12 +5498,6 @@ ] } - if (is_win) { - sources += [ - "../browser/ui/webui/settings/chrome_cleanup_handler_win_unittest.cc", - ] - } - if (enable_autofill_assistant_api) { sources += [ "../browser/extensions/api/autofill_assistant_private/extension_access_token_fetcher_unittest.cc" ] }
diff --git a/chrome/test/android/javatests/src/org/chromium/chrome/test/pagecontroller/README.md b/chrome/test/android/javatests/src/org/chromium/chrome/test/pagecontroller/README.md index e9b9505..64ff8b1b 100644 --- a/chrome/test/android/javatests/src/org/chromium/chrome/test/pagecontroller/README.md +++ b/chrome/test/android/javatests/src/org/chromium/chrome/test/pagecontroller/README.md
@@ -153,7 +153,7 @@ - Search the strings grd file with [search_strings.py](https://cs.chromium.org/chromium/src/tools/android/pagecontroller/search_strings.py). - [android_chrome_strings.grd](https://cs.chromium.org/chromium/src/chrome/android/java/strings/android_chrome_strings.grd) contains the list of strings used in Clank. + [android_chrome_strings.grd](https://cs.chromium.org/chromium/src/chrome/browser/ui/android/strings/android_chrome_strings.grd) contains the list of strings used in Clank. The entries are transformed into android strings using the name attribute by dropping the IDS_ prefix and converting the rest into lower case. For example: IDS_MENU_BOOKMARKS -> R.string.menu_bookmarks. There may be several string matching what's displayed but with different ids, be sure to read the "desc" field in the grd file and also the java source code for the UI to pick the right one. - The Clank java source code: [src/chrome/android/java/src/org/chromium/chrome/browser/](https://cs.chromium.org/chromium/src/chrome/android/java/src/org/chromium/chrome/browser/)
diff --git a/chrome/test/data/autofill/captured_sites/testcases.json b/chrome/test/data/autofill/captured_sites/testcases.json index 674caee..f8723ec 100644 --- a/chrome/test/data/autofill/captured_sites/testcases.json +++ b/chrome/test/data/autofill/captured_sites/testcases.json
@@ -13,7 +13,7 @@ { "site_name": "apple" }, { "site_name": "autoanything" }, { "site_name": "avon" }, - { "site_name": "barnes_and_noble", "disabled":true, "bug_number":984664 }, + { "site_name": "barnes_and_noble" }, { "site_name": "bath_and_body_works" }, { "site_name": "beachbody" }, { "site_name": "bed_bath_beyond" },
diff --git a/chrome/test/data/session_restore/close_onload.html b/chrome/test/data/session_restore/close_onload.html deleted file mode 100644 index 27e3476..0000000 --- a/chrome/test/data/session_restore/close_onload.html +++ /dev/null
@@ -1,11 +0,0 @@ -<!DOCTYPE html> -<html> -<body onload="closeWin()"> -<script> -function closeWin() { - - window.open('', '_self').close(); -} -</script> -</body> -</html> \ No newline at end of file
diff --git a/chrome/test/data/webui/cr_components/chromeos/cellular_setup/esim_flow_ui_test.js b/chrome/test/data/webui/cr_components/chromeos/cellular_setup/esim_flow_ui_test.js index bc2ce55d..d5c5f5e 100644 --- a/chrome/test/data/webui/cr_components/chromeos/cellular_setup/esim_flow_ui_test.js +++ b/chrome/test/data/webui/cr_components/chromeos/cellular_setup/esim_flow_ui_test.js
@@ -72,6 +72,22 @@ return confirmationCodeInput; } + async function assertFinalPageAndPressDoneButton(shouldBeShowingError) { + assertSelectedPage(cellular_setup.ESimPageName.FINAL, finalPage); + assertEquals(!!finalPage.$$('.error'), shouldBeShowingError); + assertEquals( + cellularSetup.ButtonState.ENABLED, eSimPage.buttonState.forward); + assertEquals(eSimPage.forwardButtonLabel, 'Done'); + let exitCellularSetupEventFired = false; + eSimPage.addEventListener('exit-cellular-setup', () => { + exitCellularSetupEventFired = true; + }); + eSimPage.navigateForward(); + + await flushAsync(); + assertTrue(exitCellularSetupEventFired); + } + suite('No eSIM profiles flow', function() { let euicc; @@ -120,7 +136,7 @@ await flushAsync(); // Should go to final page. - assertSelectedPage(cellular_setup.ESimPageName.FINAL, finalPage); + await assertFinalPageAndPressDoneButton(false); }); test('Valid confirmation code', async function() { @@ -143,7 +159,7 @@ await flushAsync(); // Should go to final page. - assertSelectedPage(cellular_setup.ESimPageName.FINAL, finalPage); + await assertFinalPageAndPressDoneButton(false); }); test('Invalid confirmation code', async function() { @@ -220,8 +236,7 @@ await flushAsync(); // Should go directly to final page. - assertSelectedPage(cellular_setup.ESimPageName.FINAL, finalPage); - assertFalse(!!finalPage.$$('.error')); + await assertFinalPageAndPressDoneButton(false); }); test('Unsuccessful install', async function() { @@ -235,8 +250,7 @@ await flushAsync(); // Should go directly to final page. - assertSelectedPage(cellular_setup.ESimPageName.FINAL, finalPage); - assertTrue(!!finalPage.$$('.error')); + await assertFinalPageAndPressDoneButton(true); }); test('Valid confirmation code', async function() { @@ -261,7 +275,7 @@ await flushAsync(); // Should go to final page. - assertSelectedPage(cellular_setup.ESimPageName.FINAL, finalPage); + await assertFinalPageAndPressDoneButton(false); }); test('Invalid confirmation code', async function() { @@ -359,7 +373,7 @@ await flushAsync(); // Should now be at the final page. - assertSelectedPage(cellular_setup.ESimPageName.FINAL, finalPage); + await assertFinalPageAndPressDoneButton(false); }); test( @@ -425,8 +439,7 @@ await flushAsync(); // Should now be at the final page. - assertSelectedPage(cellular_setup.ESimPageName.FINAL, finalPage); - assertFalse(!!finalPage.$$('.error')); + await assertFinalPageAndPressDoneButton(false); }); test('Select profile with valid confirmation code flow', async function() { @@ -456,7 +469,7 @@ await flushAsync(); // Should go to final page. - assertSelectedPage(cellular_setup.ESimPageName.FINAL, finalPage); + await assertFinalPageAndPressDoneButton(false); }); test(
diff --git a/chrome/test/data/webui/cr_components/chromeos/cellular_setup/psim_flow_ui_test.js b/chrome/test/data/webui/cr_components/chromeos/cellular_setup/psim_flow_ui_test.js index 5c4c499..a516e856 100644 --- a/chrome/test/data/webui/cr_components/chromeos/cellular_setup/psim_flow_ui_test.js +++ b/chrome/test/data/webui/cr_components/chromeos/cellular_setup/psim_flow_ui_test.js
@@ -10,6 +10,7 @@ // #import {setCellularSetupRemoteForTesting} from 'chrome://resources/cr_components/chromeos/cellular_setup/mojo_interface_provider.m.js'; // #import {flush, Polymer} from 'chrome://resources/polymer/v3_0/polymer/polymer_bundled.min.js'; // #import {assertTrue} from '../../../chai_assert.js'; +// #import {ButtonState} from 'chrome://resources/cr_components/chromeos/cellular_setup/cellular_types.m.js'; // #import {FakeCellularSetupDelegate} from './fake_cellular_setup_delegate.m.js'; // #import {FakeCarrierPortalHandlerRemote, FakeCellularSetupRemote} from './fake_cellular_setup_remote.m.js'; // clang-format on @@ -26,7 +27,7 @@ /** @type {?chromeos.cellularSetup.mojom.ActivationDelegateReceiver} */ let cellularActivationDelegate = null; - function flushAsync() { + async function flushAsync() { Polymer.dom.flush(); // Use setTimeout to wait for the next macrotask. return new Promise(resolve => setTimeout(resolve)); @@ -53,13 +54,25 @@ assertTrue(!!ironPage); }); - test('forward navigation test', function() { + test('forward navigation and finish cellular setup test', async function() { pSimPage.state_ = cellularSetup.PSimUIState.WAITING_FOR_PORTAL_TO_LOAD; Polymer.dom.flush(); pSimPage.navigateForward(); assertTrue( pSimPage.state_ === cellularSetup.PSimUIState.WAITING_FOR_ACTIVATION_TO_FINISH); + + assertEquals( + cellularSetup.ButtonState.ENABLED, pSimPage.buttonState.forward); + assertEquals(pSimPage.forwardButtonLabel, 'Done'); + let exitCellularSetupEventFired = false; + pSimPage.addEventListener('exit-cellular-setup', () => { + exitCellularSetupEventFired = true; + }); + pSimPage.navigateForward(); + + await flushAsync(); + assertTrue(exitCellularSetupEventFired); }); test('Carrier title on provisioning page', async () => {
diff --git a/chrome/test/data/webui/settings/chrome_cleanup_page_test.js b/chrome/test/data/webui/settings/chrome_cleanup_page_test.js index 65171af9..1f56ac2 100644 --- a/chrome/test/data/webui/settings/chrome_cleanup_page_test.js +++ b/chrome/test/data/webui/settings/chrome_cleanup_page_test.js
@@ -86,23 +86,16 @@ const exactSizeRegistryKeysList = ['key 1', 'key 2', 'key 3', 'key 4']; const longRegistryKeysList = ['key 1', 'key 2', 'key 3', 'key 4', 'key 5', 'key 6']; -const shortExtensionList = ['ext 1', 'ext 2']; -const exactSizeExtensionList = ['ext 1', 'ext 2', 'ext 3', 'ext 4']; -const longExtensionList = - ['ext 1', 'ext 2', 'ext 3', 'ext 4', 'ext 5', 'ext 6']; const fileLists = [[], shortFileList, exactSizeFileList, longFileList]; const registryKeysLists = [ [], shortRegistryKeysList, exactSizeRegistryKeysList, longRegistryKeysList ]; -const extensionLists = - [[], shortExtensionList, exactSizeExtensionList, longExtensionList]; const descriptors = ['No', 'Few', 'ExactSize', 'Many']; const defaultScannerResults = { 'files': shortFileList, 'registryKeys': shortRegistryKeysList, - 'extensions': shortExtensionList, }; /** @@ -152,13 +145,11 @@ /** * @param {!Array} files The list of files to be cleaned. * @param {!Array} registryKeys The list of registry entries to be cleaned. - * @param {!Array} extensions The list of extensions to be cleaned. */ -function startCleanupFromInfected(files, registryKeys, extensions) { +function startCleanupFromInfected(files, registryKeys) { const scannerResults = { 'files': files, 'registryKeys': registryKeys, - 'extensions': extensions }; updateReportingEnabledPref(false); @@ -188,18 +179,6 @@ assertTrue(registryKeysListContainer.hidden); } - const extensionsListContainer = chromeCleanupPage.$$('#extensions-list'); - assertTrue(!!extensionsListContainer); - if (extensions.length > 0) { - assertFalse(extensionsListContainer.hidden); - assertTrue(!!extensionsListContainer); - validateVisibleItemsList(extensions, extensionsListContainer); - validateHighlightSuffix( - extensions, extensionsListContainer, false /* expectSuffix */); - } else { - assertTrue(extensionsListContainer.hidden); - } - const actionButton = chromeCleanupPage.$$('#action-button'); assertTrue(!!actionButton); actionButton.click(); @@ -442,20 +421,14 @@ for (let file_index = 0; file_index < fileLists.length; file_index++) { for (let registry_index = 0; registry_index < registryKeysLists.length; registry_index++) { - for (let extension_index = 0; extension_index < extensionLists.length; - extension_index++) { - const testName = 'startCleanupFromInfected_' + descriptors[file_index] + - 'Files' + descriptors[registry_index] + 'RegistryKeys' + - descriptors[extension_index] + 'Extensions'; - const fileList = fileLists[file_index]; - const registryKeysList = registryKeysLists[registry_index]; - const extensionList = extensionLists[extension_index]; + const testName = 'startCleanupFromInfected_' + descriptors[file_index] + + 'Files' + descriptors[registry_index] + 'RegistryKeys'; + const fileList = fileLists[file_index]; + const registryKeysList = registryKeysLists[registry_index]; - test(testName, function() { - return startCleanupFromInfected( - fileList, registryKeysList, extensionList); - }); - } + test(testName, function() { + return startCleanupFromInfected(fileList, registryKeysList); + }); } }
diff --git a/chrome/test/data/webui/settings/chromeos/personalization_page_test.js b/chrome/test/data/webui/settings/chromeos/personalization_page_test.js index fd1ccbb..5577125e 100644 --- a/chrome/test/data/webui/settings/chromeos/personalization_page_test.js +++ b/chrome/test/data/webui/settings/chromeos/personalization_page_test.js
@@ -52,6 +52,7 @@ setup(function() { WallpaperBrowserProxy = new settings.TestWallpaperBrowserProxy(); settings.WallpaperBrowserProxyImpl.instance_ = WallpaperBrowserProxy; + loadTimeData.overrideValues({isWallpaperWebUIEnabled: false}); createPersonalizationPage(); }); @@ -66,7 +67,7 @@ // the page to be recreated. createPersonalizationPage(); await WallpaperBrowserProxy.whenCalled('isWallpaperPolicyControlled'); - const button = personalizationPage.$.wallpaperButton; + const button = personalizationPage.$$('#wallpaperButton'); assertTrue(!!button); assertFalse(button.disabled); button.click(); @@ -99,7 +100,8 @@ settings.Router.getInstance().navigateTo( settings.routes.PERSONALIZATION, params); - const deepLinkElement = personalizationPage.$.wallpaperButton.$$('#icon'); + const deepLinkElement = + personalizationPage.$$('#wallpaperButton').$$('#icon'); await test_util.waitAfterNextRender(deepLinkElement); assertEquals( deepLinkElement, getDeepActiveElement(), @@ -115,6 +117,19 @@ settings.Router.getInstance().getCurrentRoute()); }); + suite('wallpaperSubpage', function() { + setup(function() { + loadTimeData.overrideValues({isWallpaperWebUIEnabled: true}); + createPersonalizationPage(); + }); + + test('wallpaperSettingVisible', function() { + personalizationPage.showWallpaperRow_ = false; + Polymer.dom.flush(); + assertTrue(personalizationPage.$$('#wallpaperRow').hidden); + }); + }); + test('ambientMode', function() { const isGuest = loadTimeData.getBoolean('isGuest'); const isAmbientModeEnabled = loadTimeData.getBoolean('isAmbientModeEnabled');
diff --git a/chrome/test/data/webui/tab_search/tab_search_app_test.js b/chrome/test/data/webui/tab_search/tab_search_app_test.js index c5c4394..467602b 100644 --- a/chrome/test/data/webui/tab_search/tab_search_app_test.js +++ b/chrome/test/data/webui/tab_search/tab_search_app_test.js
@@ -196,8 +196,7 @@ test('refresh on tabs changed', async () => { await setupTest(sampleData()); verifyTabIds(queryRows(), [1, 5, 6, 2, 3, 4]); - testProxy.setProfileTabs({windows: []}); - testProxy.getCallbackRouterRemote().tabsChanged(); + testProxy.getCallbackRouterRemote().tabsChanged({windows: []}); await flushTasks(); verifyTabIds(queryRows(), []); assertEquals(-1, tabSearchApp.getSelectedIndex()); @@ -212,14 +211,13 @@ keyDownOn(searchField, 0, [], 'ArrowDown'); assertEquals(1, tabSearchApp.getSelectedIndex()); - testProxy.setProfileTabs({windows: [testData.windows[0]]}); - testProxy.getCallbackRouterRemote().tabsChanged(); + testProxy.getCallbackRouterRemote().tabsChanged( + {windows: [testData.windows[0]]}); await flushTasks(); assertEquals(1, tabSearchApp.getSelectedIndex()); - testProxy.setProfileTabs( + testProxy.getCallbackRouterRemote().tabsChanged( {windows: [{active: true, tabs: [testData.windows[0].tabs[0]]}]}); - testProxy.getCallbackRouterRemote().tabsChanged(); await flushTasks(); assertEquals(0, tabSearchApp.getSelectedIndex()); }); @@ -237,7 +235,7 @@ tabId: 1, title: 'Example', url: 'https://example.com', - lastActiveTimeTicks: {internalValue: BigInt(1)}, + lastActiveTimeTicks: {internalValue: BigInt(5)}, }); testProxy.getCallbackRouterRemote().tabUpdated(updatedTab); await flushTasks();
diff --git a/chrome/test/data/webui/tab_search/tab_search_test_data.js b/chrome/test/data/webui/tab_search/tab_search_test_data.js index 198ddb10..d39a7e0 100644 --- a/chrome/test/data/webui/tab_search/tab_search_test_data.js +++ b/chrome/test/data/webui/tab_search/tab_search_test_data.js
@@ -13,18 +13,21 @@ tabId: 1, title: 'Google', url: 'https://www.google.com', + lastActiveTimeTicks: {internalValue: BigInt(5)}, }, { index: 1, tabId: 5, title: 'Amazon', url: 'https://www.amazon.com', + lastActiveTimeTicks: {internalValue: BigInt(4)}, }, { index: 2, tabId: 6, title: 'Apple', url: 'https://www.apple.com', + lastActiveTimeTicks: {internalValue: BigInt(3)}, }, ], }, @@ -36,18 +39,21 @@ tabId: 2, title: 'Bing', url: 'https://www.bing.com/', + lastActiveTimeTicks: {internalValue: BigInt(2)}, }, { index: 1, tabId: 3, title: 'Yahoo', url: 'https://www.yahoo.com', + lastActiveTimeTicks: {internalValue: BigInt(1)}, }, { index: 2, tabId: 4, title: 'Apple', url: 'https://www.apple.com/', + lastActiveTimeTicks: {internalValue: BigInt(0)}, }, ], }
diff --git a/chromecast/crash/fuchsia/cast_crash_storage_impl_fuchsia_unittest.cc b/chromecast/crash/fuchsia/cast_crash_storage_impl_fuchsia_unittest.cc index 42889e3..4a4e715 100644 --- a/chromecast/crash/fuchsia/cast_crash_storage_impl_fuchsia_unittest.cc +++ b/chromecast/crash/fuchsia/cast_crash_storage_impl_fuchsia_unittest.cc
@@ -32,9 +32,9 @@ outgoing_directory_->GetOrCreateDirectory("svc")->Serve( fuchsia::io::OPEN_RIGHT_READABLE | fuchsia::io::OPEN_RIGHT_WRITABLE, channel.TakeChannel()); - binding_ = std::make_unique<base::fuchsia::ScopedServiceBinding< - fuchsia::feedback::ComponentDataRegister>>(outgoing_directory_.get(), - this); + binding_ = std::make_unique< + base::ScopedServiceBinding<fuchsia::feedback::ComponentDataRegister>>( + outgoing_directory_.get(), this); } fuchsia::feedback::ComponentData GetLatest() { @@ -51,8 +51,8 @@ private: std::unique_ptr<sys::OutgoingDirectory> outgoing_directory_; - std::unique_ptr<base::fuchsia::ScopedServiceBinding< - fuchsia::feedback::ComponentDataRegister>> + std::unique_ptr< + base::ScopedServiceBinding<fuchsia::feedback::ComponentDataRegister>> binding_; fuchsia::feedback::ComponentData component_data_;
diff --git a/chromecast/system/reboot/reboot_fuchsia_test.cc b/chromecast/system/reboot/reboot_fuchsia_test.cc index e14be42..8cf0087 100644 --- a/chromecast/system/reboot/reboot_fuchsia_test.cc +++ b/chromecast/system/reboot/reboot_fuchsia_test.cc
@@ -111,8 +111,7 @@ ADD_FAILURE() << "NotImplemented_: " << name; } - base::fuchsia::ScopedServiceBinding< - fuchsia::hardware::power::statecontrol::Admin> + base::ScopedServiceBinding<fuchsia::hardware::power::statecontrol::Admin> binding_; StateControlRebootReason last_reboot_reason_; }; @@ -135,7 +134,7 @@ ADD_FAILURE() << "NotImplemented_: " << name; } - base::fuchsia::ScopedServiceBinding<fuchsia::feedback::LastRebootInfoProvider> + base::ScopedServiceBinding<fuchsia::feedback::LastRebootInfoProvider> binding_; fuchsia::feedback::LastReboot last_reboot_; };
diff --git a/chromeos/constants/chromeos_features.cc b/chromeos/constants/chromeos_features.cc index 0d59dc5..a9f5c3c1 100644 --- a/chromeos/constants/chromeos_features.cc +++ b/chromeos/constants/chromeos_features.cc
@@ -537,7 +537,7 @@ // Allows print servers to be selected when beyond a specified limit. const base::Feature kPrintServerScaling{"PrintServerScaling", - base::FEATURE_DISABLED_BY_DEFAULT}; + base::FEATURE_ENABLED_BY_DEFAULT}; // Controls whether to enable projector. const base::Feature kProjector{"Projector", base::FEATURE_DISABLED_BY_DEFAULT};
diff --git a/chromeos/constants/chromeos_pref_names.cc b/chromeos/constants/chromeos_pref_names.cc index 90a7d8c..06905ba5 100644 --- a/chromeos/constants/chromeos_pref_names.cc +++ b/chromeos/constants/chromeos_pref_names.cc
@@ -23,6 +23,10 @@ const char kEmojiSuggestionEnterpriseAllowed[] = "assistive_input.emoji_suggestion.enterprise_allowed"; +// Pref which stores a list of eSIM profiles. Each entry in the list is created +// by serializing a CellularESimProfile. +const char kESimProfilesPrefName[] = "cros.network.esim_profiles"; + // A dictionary pref to hold the mute setting for all the currently known // audio devices. const char kAudioDevicesMute[] = "settings.audio.devices.mute";
diff --git a/chromeos/constants/chromeos_pref_names.h b/chromeos/constants/chromeos_pref_names.h index 273ebe6..3af932e 100644 --- a/chromeos/constants/chromeos_pref_names.h +++ b/chromeos/constants/chromeos_pref_names.h
@@ -15,6 +15,8 @@ COMPONENT_EXPORT(CHROMEOS_CONSTANTS) extern const char kAssistPersonalInfoEnabled[]; COMPONENT_EXPORT(CHROMEOS_CONSTANTS) +extern const char kESimProfilesPrefName[]; +COMPONENT_EXPORT(CHROMEOS_CONSTANTS) extern const char kEmojiSuggestionEnabled[]; COMPONENT_EXPORT(CHROMEOS_CONSTANTS) extern const char kEmojiSuggestionEnterpriseAllowed[];
diff --git a/chromeos/network/BUILD.gn b/chromeos/network/BUILD.gn index 57ed16a..a045f653 100644 --- a/chromeos/network/BUILD.gn +++ b/chromeos/network/BUILD.gn
@@ -15,6 +15,7 @@ "//base:i18n", "//chromeos/constants", "//chromeos/dbus:common", + "//chromeos/dbus/hermes", "//chromeos/dbus/permission_broker", "//chromeos/dbus/shill", "//chromeos/login/login_state", @@ -40,6 +41,10 @@ "auto_connect_handler.h", "cellular_esim_profile.cc", "cellular_esim_profile.h", + "cellular_esim_profile_handler.cc", + "cellular_esim_profile_handler.h", + "cellular_esim_profile_handler_impl.cc", + "cellular_esim_profile_handler_impl.h", "cellular_inhibitor.cc", "cellular_inhibitor.h", "cellular_metrics_logger.cc", @@ -224,6 +229,8 @@ "//chromeos:test_utils", "//chromeos/constants", "//chromeos/dbus:test_support", + "//chromeos/dbus/hermes:hermes_clients", + "//chromeos/dbus/hermes:hermes_fakes", "//chromeos/dbus/permission_broker", "//chromeos/login/login_state", "//components/onc", @@ -242,6 +249,7 @@ ] sources = [ "auto_connect_handler_unittest.cc", + "cellular_esim_profile_handler_impl_unittest.cc", "cellular_esim_profile_unittest.cc", "cellular_inhibitor_unittest.cc", "cellular_metrics_logger_unittest.cc",
diff --git a/chromeos/network/cellular_esim_profile_handler.cc b/chromeos/network/cellular_esim_profile_handler.cc new file mode 100644 index 0000000..9fb9620 --- /dev/null +++ b/chromeos/network/cellular_esim_profile_handler.cc
@@ -0,0 +1,28 @@ +// Copyright 2021 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 "chromeos/network/cellular_esim_profile_handler.h" + +#include "chromeos/network/cellular_esim_profile.h" + +namespace chromeos { + +CellularESimProfileHandler::CellularESimProfileHandler() = default; + +CellularESimProfileHandler::~CellularESimProfileHandler() = default; + +void CellularESimProfileHandler::AddObserver(Observer* observer) { + observer_list_.AddObserver(observer); +} + +void CellularESimProfileHandler::RemoveObserver(Observer* observer) { + observer_list_.RemoveObserver(observer); +} + +void CellularESimProfileHandler::NotifyESimProfileListUpdated() { + for (auto& observer : observer_list_) + observer.OnESimProfileListUpdated(); +} + +} // namespace chromeos
diff --git a/chromeos/network/cellular_esim_profile_handler.h b/chromeos/network/cellular_esim_profile_handler.h new file mode 100644 index 0000000..0c2b49a --- /dev/null +++ b/chromeos/network/cellular_esim_profile_handler.h
@@ -0,0 +1,59 @@ +// Copyright 2021 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 CHROMEOS_NETWORK_CELLULAR_ESIM_PROFILE_HANDLER_H_ +#define CHROMEOS_NETWORK_CELLULAR_ESIM_PROFILE_HANDLER_H_ + +#include <vector> + +#include "base/component_export.h" +#include "base/observer_list.h" +#include "base/observer_list_types.h" +#include "chromeos/network/cellular_esim_profile.h" +#include "components/prefs/pref_service.h" + +class PrefService; + +namespace chromeos { + +// Source of truth for which eSIM profiles are available on this device. +class COMPONENT_EXPORT(CHROMEOS_NETWORK) CellularESimProfileHandler { + public: + class Observer : public base::CheckedObserver { + public: + ~Observer() override = default; + + // Invoked when an eSIM profile is added, removed, or updated. + virtual void OnESimProfileListUpdated() = 0; + }; + + CellularESimProfileHandler(const CellularESimProfileHandler&) = delete; + CellularESimProfileHandler& operator=(const CellularESimProfileHandler&) = + delete; + virtual ~CellularESimProfileHandler(); + + virtual void Init() = 0; + + // Returns a list of the known cellular eSIM profiles fetched from Hermes. + // Note that this function returns cached values if an eSIM slot is not active + // (e.g., if ModemManager is currently pointed to a pSIM slot). + virtual std::vector<CellularESimProfile> GetESimProfiles() = 0; + + virtual void SetDevicePrefs(PrefService* device_prefs) = 0; + + void AddObserver(Observer* observer); + void RemoveObserver(Observer* observer); + + protected: + CellularESimProfileHandler(); + + void NotifyESimProfileListUpdated(); + + private: + base::ObserverList<Observer> observer_list_; +}; + +} // namespace chromeos + +#endif // CHROMEOS_NETWORK_CELLULAR_ESIM_PROFILE_HANDLER_H_
diff --git a/chromeos/network/cellular_esim_profile_handler_impl.cc b/chromeos/network/cellular_esim_profile_handler_impl.cc new file mode 100644 index 0000000..e6ddd0c --- /dev/null +++ b/chromeos/network/cellular_esim_profile_handler_impl.cc
@@ -0,0 +1,194 @@ +// Copyright 2021 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 "chromeos/network/cellular_esim_profile_handler_impl.h" + +#include <algorithm> +#include <iterator> + +#include "base/component_export.h" +#include "base/containers/flat_set.h" +#include "base/strings/utf_string_conversions.h" +#include "base/values.h" +#include "chromeos/constants/chromeos_pref_names.h" +#include "chromeos/network/network_event_log.h" +#include "components/prefs/pref_registry_simple.h" + +namespace chromeos { +namespace { + +base::flat_set<dbus::ObjectPath> GetProfilePathsFromEuicc( + HermesEuiccClient::Properties* euicc_properties) { + base::flat_set<dbus::ObjectPath> profile_paths; + + for (const dbus::ObjectPath& path : + euicc_properties->installed_carrier_profiles().value()) { + profile_paths.insert(path); + } + for (const dbus::ObjectPath& path : + euicc_properties->pending_carrier_profiles().value()) { + profile_paths.insert(path); + } + + return profile_paths; +} + +CellularESimProfile::State FromProfileState(hermes::profile::State state) { + switch (state) { + case hermes::profile::State::kPending: + return CellularESimProfile::State::kPending; + case hermes::profile::State::kInactive: + return CellularESimProfile::State::kInactive; + case hermes::profile::State::kActive: + return CellularESimProfile::State::kActive; + default: + NOTREACHED() << "Unexpected Hermes profile state: " << state; + return CellularESimProfile::State::kInactive; + } +} + +std::vector<CellularESimProfile> GenerateProfilesFromEuicc( + const dbus::ObjectPath& euicc_path) { + std::vector<CellularESimProfile> profiles; + + HermesEuiccClient::Properties* euicc_properties = + HermesEuiccClient::Get()->GetProperties(euicc_path); + std::string eid = euicc_properties->eid().value(); + + for (const dbus::ObjectPath& profile_path : + GetProfilePathsFromEuicc(euicc_properties)) { + HermesProfileClient::Properties* profile_properties = + HermesProfileClient::Get()->GetProperties(profile_path); + profiles.emplace_back( + FromProfileState(profile_properties->state().value()), eid, + profile_properties->iccid().value(), + base::UTF8ToUTF16(profile_properties->name().value()), + base::UTF8ToUTF16(profile_properties->nick_name().value()), + base::UTF8ToUTF16(profile_properties->service_provider().value()), + profile_properties->activation_code().value()); + } + + return profiles; +} + +std::vector<CellularESimProfile> GenerateProfilesFromHermes() { + std::vector<CellularESimProfile> profiles; + + for (const dbus::ObjectPath& euicc_path : + HermesManagerClient::Get()->GetAvailableEuiccs()) { + std::vector<CellularESimProfile> profiles_from_euicc = + GenerateProfilesFromEuicc(euicc_path); + std::copy(profiles_from_euicc.begin(), profiles_from_euicc.end(), + std::back_inserter(profiles)); + } + + return profiles; +} + +} // namespace + +// static +void CellularESimProfileHandlerImpl::RegisterLocalStatePrefs( + PrefRegistrySimple* registry) { + registry->RegisterListPref(prefs::kESimProfilesPrefName); +} + +CellularESimProfileHandlerImpl::CellularESimProfileHandlerImpl() = default; + +CellularESimProfileHandlerImpl::~CellularESimProfileHandlerImpl() { + HermesManagerClient::Get()->RemoveObserver(this); + HermesEuiccClient::Get()->RemoveObserver(this); + HermesProfileClient::Get()->RemoveObserver(this); +} + +void CellularESimProfileHandlerImpl::Init() { + HermesManagerClient::Get()->AddObserver(this); + HermesEuiccClient::Get()->AddObserver(this); + HermesProfileClient::Get()->AddObserver(this); +} + +std::vector<CellularESimProfile> +CellularESimProfileHandlerImpl::GetESimProfiles() { + // Profiles are stored in prefs. + if (!device_prefs_) + return std::vector<CellularESimProfile>(); + + const base::ListValue* profiles_list = + device_prefs_->GetList(prefs::kESimProfilesPrefName); + if (!profiles_list) { + NET_LOG(ERROR) << "eSIM profiles pref is not a list"; + return std::vector<CellularESimProfile>(); + } + + std::vector<CellularESimProfile> profiles; + for (const base::Value& value : profiles_list->GetList()) { + const base::DictionaryValue* dict; + if (!value.GetAsDictionary(&dict)) { + NET_LOG(ERROR) << "List item from eSIM profiles pref is not a dictionary"; + continue; + } + + base::Optional<CellularESimProfile> profile = + CellularESimProfile::FromDictionaryValue(*dict); + if (!profile) { + NET_LOG(ERROR) << "Unable to deserialize eSIM profile: " << *dict; + continue; + } + + profiles.push_back(*profile); + } + return profiles; +} + +void CellularESimProfileHandlerImpl::SetDevicePrefs(PrefService* device_prefs) { + device_prefs_ = device_prefs; + UpdateProfilesFromHermes(); +} + +void CellularESimProfileHandlerImpl::OnAvailableEuiccListChanged() { + UpdateProfilesFromHermes(); +} + +void CellularESimProfileHandlerImpl::OnEuiccPropertyChanged( + const dbus::ObjectPath& euicc_path, + const std::string& property_name) { + UpdateProfilesFromHermes(); +} + +void CellularESimProfileHandlerImpl::OnCarrierProfilePropertyChanged( + const dbus::ObjectPath& carrier_profile_path, + const std::string& property_name) { + UpdateProfilesFromHermes(); +} + +void CellularESimProfileHandlerImpl::UpdateProfilesFromHermes() { + // Profiles are stored in prefs. + if (!device_prefs_) + return; + + std::vector<CellularESimProfile> profiles_from_hermes = + GenerateProfilesFromHermes(); + + // Ignore empty profile lists provided by Hermes, since this represents either + // (1) a temporary state during startup, or (2) not actually having any eSIMs. + if (profiles_from_hermes.empty()) + return; + + std::vector<CellularESimProfile> profiles_before_fetch = GetESimProfiles(); + + // If nothing has changed since the last update, do not update prefs or notify + // observers of a change. + if (profiles_from_hermes == profiles_before_fetch) + return; + + // Store the updated list of profiles in prefs. + base::Value list(base::Value::Type::LIST); + for (const auto& profile : profiles_from_hermes) + list.Append(profile.ToDictionaryValue()); + device_prefs_->Set(prefs::kESimProfilesPrefName, std::move(list)); + + NotifyESimProfileListUpdated(); +} + +} // namespace chromeos
diff --git a/chromeos/network/cellular_esim_profile_handler_impl.h b/chromeos/network/cellular_esim_profile_handler_impl.h new file mode 100644 index 0000000..35a0937 --- /dev/null +++ b/chromeos/network/cellular_esim_profile_handler_impl.h
@@ -0,0 +1,60 @@ +// Copyright 2021 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 CHROMEOS_NETWORK_CELLULAR_ESIM_PROFILE_HANDLER_IMPL_H_ +#define CHROMEOS_NETWORK_CELLULAR_ESIM_PROFILE_HANDLER_IMPL_H_ + +#include "base/component_export.h" +#include "chromeos/dbus/hermes/hermes_euicc_client.h" +#include "chromeos/dbus/hermes/hermes_manager_client.h" +#include "chromeos/dbus/hermes/hermes_profile_client.h" +#include "chromeos/network/cellular_esim_profile_handler.h" + +class PrefService; +class PrefRegistrySimple; + +namespace chromeos { + +class COMPONENT_EXPORT(CHROMEOS_NETWORK) CellularESimProfileHandlerImpl + : public CellularESimProfileHandler, + public HermesManagerClient::Observer, + public HermesEuiccClient::Observer, + public HermesProfileClient::Observer { + public: + CellularESimProfileHandlerImpl(); + CellularESimProfileHandlerImpl(const CellularESimProfileHandlerImpl&) = + delete; + CellularESimProfileHandlerImpl& operator=( + const CellularESimProfileHandlerImpl&) = delete; + ~CellularESimProfileHandlerImpl() override; + + static void RegisterLocalStatePrefs(PrefRegistrySimple* registry); + + private: + // CellularESimProfileHandler: + void Init() override; + std::vector<CellularESimProfile> GetESimProfiles() override; + void SetDevicePrefs(PrefService* device_prefs) override; + + // HermesManagerClient::Observer: + void OnAvailableEuiccListChanged() override; + + // HermesEuiccClient::Observer: + void OnEuiccPropertyChanged(const dbus::ObjectPath& euicc_path, + const std::string& property_name) override; + + // HermesProfileClient::Observer: + void OnCarrierProfilePropertyChanged( + const dbus::ObjectPath& carrier_profile_path, + const std::string& property_name) override; + + void UpdateProfilesFromHermes(); + + // Initialized to null and set once SetDevicePrefs() is called. + PrefService* device_prefs_ = nullptr; +}; + +} // namespace chromeos + +#endif // CHROMEOS_NETWORK_CELLULAR_ESIM_PROFILE_HANDLER_IMPL_H_
diff --git a/chromeos/network/cellular_esim_profile_handler_impl_unittest.cc b/chromeos/network/cellular_esim_profile_handler_impl_unittest.cc new file mode 100644 index 0000000..440108d9 --- /dev/null +++ b/chromeos/network/cellular_esim_profile_handler_impl_unittest.cc
@@ -0,0 +1,227 @@ +// Copyright 2021 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 "chromeos/network/cellular_esim_profile_handler_impl.h" + +#include <memory> + +#include "base/run_loop.h" +#include "base/strings/stringprintf.h" +#include "base/test/task_environment.h" +#include "chromeos/dbus/hermes/hermes_clients.h" +#include "chromeos/dbus/hermes/hermes_euicc_client.h" +#include "chromeos/dbus/hermes/hermes_manager_client.h" +#include "chromeos/dbus/shill/fake_shill_device_client.h" +#include "chromeos/dbus/shill/shill_clients.h" +#include "components/prefs/testing_pref_service.h" +#include "testing/gtest/include/gtest/gtest.h" +#include "third_party/cros_system_api/dbus/shill/dbus-constants.h" + +namespace chromeos { +namespace { + +const char kDefaultCellularDevicePath[] = "stub_cellular_device"; +const char kTestEuiccBasePath[] = "/org/chromium/Hermes/Euicc/"; +const char kTestBaseEid[] = "12345678901234567890123456789012"; + +std::string CreateTestEuiccPath(int euicc_num) { + return base::StringPrintf("%s%d", kTestEuiccBasePath, euicc_num); +} + +std::string CreateTestEid(int euicc_num) { + return base::StringPrintf("%s%d", kTestBaseEid, euicc_num); +} + +class FakeObserver : public CellularESimProfileHandler::Observer { + public: + FakeObserver() = default; + ~FakeObserver() override = default; + + size_t num_updates() const { return num_updates_; } + + // CellularESimProfileHandler::Observer: + void OnESimProfileListUpdated() override { ++num_updates_; } + + private: + size_t num_updates_ = 0u; +}; + +} // namespace + +class CellularESimProfileHandlerImplTest : public testing::Test { + protected: + CellularESimProfileHandlerImplTest() = default; + ~CellularESimProfileHandlerImplTest() override = default; + + // testing::Test: + void SetUp() override { + CellularESimProfileHandlerImpl::RegisterLocalStatePrefs( + device_prefs_.registry()); + + shill_clients::InitializeFakes(); + hermes_clients::InitializeFakes(); + + ShillDeviceClient::Get()->GetTestInterface()->AddDevice( + kDefaultCellularDevicePath, shill::kTypeCellular, "cellular1"); + } + + void TearDown() override { + handler_->RemoveObserver(&observer_); + handler_.reset(); + hermes_clients::Shutdown(); + shill_clients::Shutdown(); + } + + void Init() { + if (handler_) + handler_->RemoveObserver(&observer_); + + handler_ = std::make_unique<CellularESimProfileHandlerImpl>(); + handler_->AddObserver(&observer_); + + handler_->Init(); + } + + void SetDevicePrefs(bool set_to_null = false) { + handler_->SetDevicePrefs(set_to_null ? nullptr : &device_prefs_); + } + + void AddEuicc(int euicc_num) { + HermesManagerClient::Get()->GetTestInterface()->AddEuicc( + dbus::ObjectPath(CreateTestEuiccPath(euicc_num)), + CreateTestEid(euicc_num), true); + base::RunLoop().RunUntilIdle(); + } + + dbus::ObjectPath AddProfile(int euicc_num, + hermes::profile::State state, + const std::string& activation_code) { + dbus::ObjectPath path = + HermesEuiccClient::Get()->GetTestInterface()->AddFakeCarrierProfile( + dbus::ObjectPath(CreateTestEuiccPath(euicc_num)), state, + activation_code, /*service_only=*/false); + base::RunLoop().RunUntilIdle(); + return path; + } + + std::vector<CellularESimProfile> GetESimProfiles() { + return handler_->GetESimProfiles(); + } + + size_t NumObserverEvents() const { return observer_.num_updates(); } + + private: + base::test::SingleThreadTaskEnvironment task_environment_; + TestingPrefServiceSimple device_prefs_; + FakeObserver observer_; + + std::unique_ptr<CellularESimProfileHandler> handler_; +}; + +TEST_F(CellularESimProfileHandlerImplTest, NoEuicc) { + // No EUICCs exist, so no profiles should exist. + Init(); + EXPECT_TRUE(GetESimProfiles().empty()); + + // Set prefs; no profiles should exist. + SetDevicePrefs(); + EXPECT_TRUE(GetESimProfiles().empty()); + + // Unset prefs; no profiles should exist. + SetDevicePrefs(/*set_to_null=*/true); + EXPECT_TRUE(GetESimProfiles().empty()); + + EXPECT_EQ(0u, NumObserverEvents()); +} + +TEST_F(CellularESimProfileHandlerImplTest, EuiccWithNoProfiles) { + AddEuicc(/*euicc_num=*/1); + + // No profiles were added to the EUICC. + Init(); + EXPECT_TRUE(GetESimProfiles().empty()); + + // Set prefs; no profiles should exist. + SetDevicePrefs(); + EXPECT_TRUE(GetESimProfiles().empty()); + + // Unset prefs; no profiles should exist. + SetDevicePrefs(/*set_to_null=*/true); + EXPECT_TRUE(GetESimProfiles().empty()); + + EXPECT_EQ(0u, NumObserverEvents()); +} + +TEST_F(CellularESimProfileHandlerImplTest, EuiccWithProfiles) { + AddEuicc(/*euicc_num=*/1); + dbus::ObjectPath path1 = AddProfile( + /*euicc_num=*/1, hermes::profile::State::kPending, + /*activation_code=*/"code1"); + dbus::ObjectPath path2 = AddProfile( + /*euicc_num=*/1, hermes::profile::State::kActive, + /*activation_code=*/"code2"); + + // Prefs not yet set. + Init(); + EXPECT_TRUE(GetESimProfiles().empty()); + + // Set prefs; the profiles added should be available. + SetDevicePrefs(); + EXPECT_EQ(1u, NumObserverEvents()); + + std::vector<CellularESimProfile> profiles = GetESimProfiles(); + EXPECT_EQ(2u, profiles.size()); + EXPECT_EQ(CellularESimProfile::State::kPending, profiles[0].state()); + EXPECT_EQ("code1", profiles[0].activation_code()); + EXPECT_EQ(CellularESimProfile::State::kActive, profiles[1].state()); + EXPECT_EQ("code2", profiles[1].activation_code()); + + // Update profile properties; GetESimProfiles() should return the new values. + HermesProfileClient::Properties* profile_properties1 = + HermesProfileClient::Get()->GetProperties(dbus::ObjectPath(path1)); + profile_properties1->state().ReplaceValue(hermes::profile::kInactive); + HermesProfileClient::Properties* profile_properties2 = + HermesProfileClient::Get()->GetProperties(dbus::ObjectPath(path2)); + profile_properties2->state().ReplaceValue(hermes::profile::kPending); + base::RunLoop().RunUntilIdle(); + EXPECT_EQ(2u, NumObserverEvents()); + + profiles = GetESimProfiles(); + EXPECT_EQ(2u, profiles.size()); + EXPECT_EQ(CellularESimProfile::State::kInactive, profiles[0].state()); + EXPECT_EQ(CellularESimProfile::State::kPending, profiles[1].state()); + + // Unset prefs; no profiles should exist. + SetDevicePrefs(/*set_to_null=*/true); + EXPECT_TRUE(GetESimProfiles().empty()); +} + +TEST_F(CellularESimProfileHandlerImplTest, Persistent) { + Init(); + SetDevicePrefs(); + EXPECT_TRUE(GetESimProfiles().empty()); + + // Add a EUICC and profile; should be available. + AddEuicc(/*euicc_num=*/1); + AddProfile(/*euicc_num=*/1, hermes::profile::State::kPending, + /*activation_code=*/"code1"); + EXPECT_EQ(1u, GetESimProfiles().size()); + EXPECT_EQ(1u, NumObserverEvents()); + + // Delete the old handler and create a new one; the new one will end up using + // the same PrefService as the old one. + Init(); + + // Remove EUICC; this simulates a temporary state at startup when Hermes would + // not yet have provided EUICC information. + HermesEuiccClient::Get()->GetTestInterface()->ClearEuicc( + dbus::ObjectPath(CreateTestEuiccPath(/*euicc_num=*/1))); + + // Set prefs; the handler should read from the old prefs and should still have + // a profile available. + SetDevicePrefs(); + EXPECT_EQ(1u, GetESimProfiles().size()); +} + +} // namespace chromeos
diff --git a/chromeos/network/network_connection_handler_impl.cc b/chromeos/network/network_connection_handler_impl.cc index 0a3aad43..7a1a266 100644 --- a/chromeos/network/network_connection_handler_impl.cc +++ b/chromeos/network/network_connection_handler_impl.cc
@@ -670,14 +670,15 @@ // Notify the user that the connect failed, clear the queued network, and // clear the connect_requested flag for the NetworkState. + std::string queued_connect_service_path = queued_connect_->service_path; NET_LOG(ERROR) << "Certificate load timeout: " - << NetworkPathId(queued_connect_->service_path); + << NetworkPathId(queued_connect_service_path); InvokeConnectErrorCallback(queued_connect_->service_path, std::move(queued_connect_->error_callback), kErrorCertLoadTimeout); queued_connect_.reset(); network_state_handler_->SetNetworkConnectRequested( - queued_connect_->service_path, false); + queued_connect_service_path, false); } void NetworkConnectionHandlerImpl::ConnectToQueuedNetwork() {
diff --git a/chromeos/network/network_connection_handler_impl_unittest.cc b/chromeos/network/network_connection_handler_impl_unittest.cc index 21d738e..acd9190 100644 --- a/chromeos/network/network_connection_handler_impl_unittest.cc +++ b/chromeos/network/network_connection_handler_impl_unittest.cc
@@ -133,9 +133,7 @@ class NetworkConnectionHandlerImplTest : public testing::Test { public: - NetworkConnectionHandlerImplTest() - : task_environment_(base::test::TaskEnvironment::MainThreadType::UI) {} - + NetworkConnectionHandlerImplTest() = default; ~NetworkConnectionHandlerImplTest() override = default; void SetUp() override { @@ -330,6 +328,10 @@ ->AddGloballyProhibitedTechnology(shill::kTypeVPN); } + void AdvanceClock(base::TimeDelta time_delta) { + task_environment_.FastForwardBy(time_delta); + } + NetworkStateHandler* network_state_handler() { return helper_.network_state_handler(); } @@ -344,7 +346,8 @@ } private: - base::test::TaskEnvironment task_environment_; + base::test::TaskEnvironment task_environment_{ + base::test::TaskEnvironment::TimeSource::MOCK_TIME}; NetworkStateTestHelper helper_{false /* use_default_devices_and_services */}; std::unique_ptr<NetworkConfigurationHandler> network_config_handler_; std::unique_ptr<NetworkConnectionHandler> network_connection_handler_; @@ -555,6 +558,33 @@ } TEST_F(NetworkConnectionHandlerImplTest, + ConnectWithCertificateRequestedBeforeCertsAreLoaded_NeverLoaded) { + const base::TimeDelta kMaxCertLoadTimeSeconds = + base::TimeDelta::FromSeconds(15); + + scoped_refptr<net::X509Certificate> cert = ImportTestClientCert(); + ASSERT_TRUE(cert.get()); + + SetupPolicy(base::StringPrintf(kPolicyWithCertPatternTemplate, + cert->subject().common_name.c_str()), + base::DictionaryValue(), // no global config + true); // load as user policy + + Connect(ServicePathFromGuid("wifi4")); + + // Connect request came before the cert loader loaded certificates, so the + // connect request should have been throttled until the certificates are + // loaded. + EXPECT_EQ("", GetResultAndReset()); + + AdvanceClock(kMaxCertLoadTimeSeconds); + + // The result should indicate a certificate load timeout. + EXPECT_EQ(NetworkConnectionHandler::kErrorCertLoadTimeout, + GetResultAndReset()); +} + +TEST_F(NetworkConnectionHandlerImplTest, NetworkConnectionHandlerDisconnectSuccess) { std::string wifi1_service_path = ConfigureService(kConfigWifi1Connected); ASSERT_FALSE(wifi1_service_path.empty());
diff --git a/chromeos/network/network_handler.cc b/chromeos/network/network_handler.cc index 39b2bdd4..24326e1f 100644 --- a/chromeos/network/network_handler.cc +++ b/chromeos/network/network_handler.cc
@@ -5,7 +5,9 @@ #include "chromeos/network/network_handler.h" #include "base/threading/thread_task_runner_handle.h" +#include "chromeos/constants/chromeos_features.h" #include "chromeos/network/auto_connect_handler.h" +#include "chromeos/network/cellular_esim_profile_handler_impl.h" #include "chromeos/network/cellular_inhibitor.h" #include "chromeos/network/cellular_metrics_logger.h" #include "chromeos/network/client_cert_resolver.h" @@ -35,7 +37,10 @@ : task_runner_(base::ThreadTaskRunnerHandle::Get()) { network_state_handler_.reset(new NetworkStateHandler()); network_device_handler_.reset(new NetworkDeviceHandlerImpl()); - cellular_inhibitor_.reset(new CellularInhibitor()); + if (features::IsCellularActivationUiEnabled()) { + cellular_esim_profile_handler_.reset(new CellularESimProfileHandlerImpl()); + cellular_inhibitor_.reset(new CellularInhibitor()); + } network_profile_handler_.reset(new NetworkProfileHandler()); network_configuration_handler_.reset(new NetworkConfigurationHandler()); managed_network_configuration_handler_.reset( @@ -61,8 +66,11 @@ void NetworkHandler::Init() { network_state_handler_->InitShillPropertyHandler(); network_device_handler_->Init(network_state_handler_.get()); - cellular_inhibitor_->Init(network_state_handler_.get(), - network_device_handler_.get()); + if (features::IsCellularActivationUiEnabled()) { + cellular_esim_profile_handler_->Init(); + cellular_inhibitor_->Init(network_state_handler_.get(), + network_device_handler_.get()); + } network_profile_handler_->Init(); network_configuration_handler_->Init(network_state_handler_.get(), network_device_handler_.get()); @@ -123,6 +131,8 @@ void NetworkHandler::InitializePrefServices( PrefService* logged_in_profile_prefs, PrefService* device_prefs) { + if (features::IsCellularActivationUiEnabled()) + cellular_esim_profile_handler_->SetDevicePrefs(device_prefs); ui_proxy_config_service_.reset(new UIProxyConfigService( logged_in_profile_prefs, device_prefs, network_state_handler_.get(), network_profile_handler_.get())); @@ -135,6 +145,8 @@ } void NetworkHandler::ShutdownPrefServices() { + if (features::IsCellularActivationUiEnabled()) + cellular_esim_profile_handler_->SetDevicePrefs(nullptr); ui_proxy_config_service_.reset(); network_metadata_store_.reset(); }
diff --git a/chromeos/network/network_handler.h b/chromeos/network/network_handler.h index 39e70ef..aa2cc223 100644 --- a/chromeos/network/network_handler.h +++ b/chromeos/network/network_handler.h
@@ -17,6 +17,7 @@ namespace chromeos { class AutoConnectHandler; +class CellularESimProfileHandler; class CellularInhibitor; class CellularMetricsLogger; class ClientCertResolver; @@ -77,6 +78,7 @@ // explicit so that classes can be constructed explicitly in tests without // NetworkHandler. AutoConnectHandler* auto_connect_handler(); + CellularESimProfileHandler* cellular_esim_profile_handler(); CellularInhibitor* cellular_inhibitor(); NetworkStateHandler* network_state_handler(); NetworkDeviceHandler* network_device_handler(); @@ -105,6 +107,7 @@ scoped_refptr<base::SingleThreadTaskRunner> task_runner_; std::unique_ptr<NetworkStateHandler> network_state_handler_; std::unique_ptr<NetworkDeviceHandlerImpl> network_device_handler_; + std::unique_ptr<CellularESimProfileHandler> cellular_esim_profile_handler_; std::unique_ptr<CellularInhibitor> cellular_inhibitor_; std::unique_ptr<NetworkProfileHandler> network_profile_handler_; std::unique_ptr<NetworkConfigurationHandler> network_configuration_handler_;
diff --git a/chromeos/services/assistant/BUILD.gn b/chromeos/services/assistant/BUILD.gn index e7f618f6..8f322b1 100644 --- a/chromeos/services/assistant/BUILD.gn +++ b/chromeos/services/assistant/BUILD.gn
@@ -79,6 +79,8 @@ "assistant_settings_impl.h", "libassistant_service_host_impl.cc", "libassistant_service_host_impl.h", + "media_host.cc", + "media_host.h", "media_session/assistant_media_session.cc", "media_session/assistant_media_session.h", "platform/audio_device_owner.cc",
diff --git a/chromeos/services/assistant/assistant_manager_service_impl.cc b/chromeos/services/assistant/assistant_manager_service_impl.cc index 9d3ecb1..a9d2040e 100644 --- a/chromeos/services/assistant/assistant_manager_service_impl.cc +++ b/chromeos/services/assistant/assistant_manager_service_impl.cc
@@ -35,7 +35,7 @@ #include "chromeos/dbus/util/version_loader.h" #include "chromeos/services/assistant/assistant_device_settings_delegate.h" #include "chromeos/services/assistant/libassistant_service_host_impl.h" -#include "chromeos/services/assistant/media_session/assistant_media_session.h" +#include "chromeos/services/assistant/media_host.h" #include "chromeos/services/assistant/platform_api_impl.h" #include "chromeos/services/assistant/proxy/conversation_controller_proxy.h" #include "chromeos/services/assistant/proxy/service_controller_proxy.h" @@ -56,8 +56,6 @@ #include "libassistant/shared/internal_api/assistant_manager_delegate.h" #include "libassistant/shared/internal_api/assistant_manager_internal.h" #include "libassistant/shared/public/assistant_manager.h" -#include "libassistant/shared/public/media_manager.h" -#include "services/media_session/public/mojom/media_session.mojom.h" #include "services/network/public/cpp/shared_url_loader_factory.h" #include "ui/accessibility/mojom/ax_assistant_structure.mojom.h" #include "ui/base/l10n/l10n_util.h" @@ -72,11 +70,7 @@ return; \ } -using assistant_client::ActionModule; -using assistant_client::MediaStatus; using media_session::mojom::MediaSessionAction; -using media_session::mojom::MediaSessionInfo; -using media_session::mojom::MediaSessionInfoPtr; using Resolution = assistant_client::ConversationStateListener::Resolution; using CommunicationErrorType = chromeos::assistant::AssistantManagerService::CommunicationErrorType; @@ -89,15 +83,6 @@ static bool is_first_init = true; -constexpr char kIntentActionView[] = "android.intent.action.VIEW"; - -constexpr char kNextTrackClientOp[] = "media.NEXT"; -constexpr char kPauseTrackClientOp[] = "media.PAUSE"; -constexpr char kPlayMediaClientOp[] = "media.PLAY_MEDIA"; -constexpr char kPrevTrackClientOp[] = "media.PREVIOUS"; -constexpr char kResumeTrackClientOp[] = "media.RESUME"; -constexpr char kStopTrackClientOp[] = "media.STOP"; - constexpr char kAndroidSettingsAppPackage[] = "com.android.settings"; ash::AssistantTimerState GetTimerState(assistant_client::Timer::State state) { @@ -245,8 +230,7 @@ base::Optional<std::string> s3_server_uri_override, base::Optional<std::string> device_id_override, std::unique_ptr<LibassistantServiceHost> libassistant_service_host) - : media_session_(std::make_unique<AssistantMediaSession>(this)), - action_module_(std::make_unique<action::CrosActionModule>( + : action_module_(std::make_unique<action::CrosActionModule>( this, features::IsAppSupportEnabled(), features::IsWaitSchedulingEnabled())), @@ -255,6 +239,8 @@ assistant_proxy_(std::make_unique<AssistantProxy>()), context_(context), delegate_(std::move(delegate)), + media_host_(std::make_unique<MediaHost>(AssistantClient::Get(), + &interaction_subscribers_)), speech_recognition_observer_( std::make_unique<SpeechRecognitionObserverWrapper>( &interaction_subscribers_)), @@ -264,7 +250,7 @@ ShouldPutLogsInHomeDirectory())), weak_factory_(this) { platform_api_ = delegate_->CreatePlatformApi( - media_session_.get(), + &media_host_->media_session(), assistant_proxy_->background_thread().task_runner()); if (libassistant_service_host) { @@ -292,13 +278,6 @@ settings_delegate_ = std::make_unique<AssistantDeviceSettingsDelegate>(context); - - mojo::Remote<media_session::mojom::MediaControllerManager> - media_controller_manager; - AssistantClient::Get()->RequestMediaControllerManager( - media_controller_manager.BindNewPipeAndPassReceiver()); - media_controller_manager->CreateActiveMediaController( - media_controller_.BindNewPipeAndPassReceiver()); } AssistantManagerServiceImpl::~AssistantManagerServiceImpl() { @@ -344,7 +323,7 @@ if (!assistant_state()->settings_enabled().value() && assistant_manager()) assistant_manager()->ResetAllDataAndShutdown(); - media_controller_observer_receiver_.reset(); + media_host_->Stop(); scoped_app_list_event_subscriber_.Reset(); service_controller().Stop(); } @@ -368,45 +347,6 @@ action_module_->SetAmbientModeEnabled(enabled); } -void AssistantManagerServiceImpl::RegisterFallbackMediaHandler() { - // This is a callback from LibAssistant, it is async from LibAssistant thread. - // It is possible that when it reaches here, the assistant_manager has - // been stopped. - if (!assistant_manager_internal()) - return; - - // Register handler for media actions. - assistant_manager_internal()->RegisterFallbackMediaHandler( - [this](std::string action_name, std::string media_action_args_proto) { - if (action_name == kPlayMediaClientOp) { - OnPlayMedia(media_action_args_proto); - } else { - OnMediaControlAction(action_name, media_action_args_proto); - } - }); -} - -void AssistantManagerServiceImpl::AddMediaControllerObserver() { - if (!features::IsMediaSessionIntegrationEnabled()) - return; - - if (media_controller_observer_receiver_.is_bound()) - return; - - media_controller_->AddObserver( - media_controller_observer_receiver_.BindNewPipeAndPassRemote()); -} - -void AssistantManagerServiceImpl::RemoveMediaControllerObserver() { - if (!features::IsMediaSessionIntegrationEnabled()) - return; - - if (!media_controller_observer_receiver_.is_bound()) - return; - - media_controller_observer_receiver_.reset(); -} - void AssistantManagerServiceImpl::RegisterAlarmsTimersListener() { if (!assistant_manager_internal()) return; @@ -449,6 +389,7 @@ void AssistantManagerServiceImpl::EnableListening(bool enable) { if (!assistant_manager()) return; + // TODO(jeroendh): add EnableListening() to ServiceController. assistant_manager()->EnableListening(enable); } @@ -465,13 +406,7 @@ void AssistantManagerServiceImpl::SetAssistantContextEnabled(bool enable) { DCHECK(GetState() == State::RUNNING); - if (enable) { - AddMediaControllerObserver(); - } else { - RemoveMediaControllerObserver(); - ResetMediaState(); - } - + media_host_->SetRelatedInfoEnabled(enable); display_controller().SetRelatedInfoEnabled(enable); } @@ -508,18 +443,12 @@ void AssistantManagerServiceImpl::UpdateInternalMediaPlayerStatus( MediaSessionAction action) { - if (!assistant_manager()) - return; - auto* media_manager = assistant_manager()->GetMediaManager(); - if (!media_manager) - return; - switch (action) { case MediaSessionAction::kPause: - media_manager->Pause(); + media_host_->PauseInternalMediaPlayer(); break; case MediaSessionAction::kPlay: - media_manager->Resume(); + media_host_->ResumeInternalMediaPlayer(); break; case MediaSessionAction::kPreviousTrack: case MediaSessionAction::kNextTrack: @@ -900,74 +829,6 @@ [](auto) {}); } -void AssistantManagerServiceImpl::OnOpenMediaAndroidIntent( - const std::string& play_media_args_proto, - AndroidAppInfo* app_info) { - DCHECK(main_task_runner()->RunsTasksInCurrentSequence()); - - // Handle android media playback intent. - app_info->action = kIntentActionView; - if (app_info->intent.empty()) { - std::string url = GetAndroidIntentUrlFromMediaArgs(play_media_args_proto); - if (!url.empty()) - app_info->intent = url; - } - for (auto& it : interaction_subscribers_) { - bool success = it.OnOpenAppResponse(*app_info); - HandleLaunchMediaIntentResponse(success); - } -} - -void AssistantManagerServiceImpl::OnPlayMedia( - const std::string& play_media_args_proto) { - ENSURE_MAIN_THREAD(&AssistantManagerServiceImpl::OnPlayMedia, - play_media_args_proto); - - std::unique_ptr<AndroidAppInfo> app_info = - GetAppInfoFromMediaArgs(play_media_args_proto); - if (app_info) { - OnOpenMediaAndroidIntent(play_media_args_proto, app_info.get()); - } else { - std::string url = GetWebUrlFromMediaArgs(play_media_args_proto); - // Fallack to web URL. - if (!url.empty()) - OnOpenUrl(url, /*in_background=*/false); - } -} - -void AssistantManagerServiceImpl::OnMediaControlAction( - const std::string& action_name, - const std::string& media_action_args_proto) { - ENSURE_MAIN_THREAD(&AssistantManagerServiceImpl::OnMediaControlAction, - action_name, media_action_args_proto); - - if (action_name == kPauseTrackClientOp) { - media_controller_->Suspend(); - return; - } - - if (action_name == kResumeTrackClientOp) { - media_controller_->Resume(); - return; - } - - if (action_name == kNextTrackClientOp) { - media_controller_->NextTrack(); - return; - } - - if (action_name == kPrevTrackClientOp) { - media_controller_->PreviousTrack(); - return; - } - - if (action_name == kStopTrackClientOp) { - media_controller_->Suspend(); - return; - } - // TODO(llin): Handle media.SEEK_RELATIVE. -} - void AssistantManagerServiceImpl::OnRespondingStarted(bool is_error_response) { ENSURE_MAIN_THREAD(&AssistantManagerServiceImpl::OnRespondingStarted, is_error_response); @@ -1065,12 +926,6 @@ return service_controller().IsStarted(); } -void AssistantManagerServiceImpl::HandleLaunchMediaIntentResponse( - bool app_opened) { - // TODO(llin): Handle the response. - NOTIMPLEMENTED(); -} - // This method runs on the LibAssistant thread. // This method is triggered as the callback of libassistant bootup checkin. void AssistantManagerServiceImpl::OnStartFinished() { @@ -1097,13 +952,9 @@ SyncDeviceAppsStatus(); - RegisterFallbackMediaHandler(); - SetAssistantContextEnabled(assistant_state()->IsScreenContextAllowed()); - auto* media_manager = assistant_manager()->GetMediaManager(); - if (media_manager) - media_manager->AddListener(this); + media_host_->Start(assistant_manager_internal()); RegisterAlarmsTimersListener(); @@ -1124,29 +975,6 @@ display_controller().SetAndroidAppList(std::move(filtered_apps_info)); } -void AssistantManagerServiceImpl::OnPlaybackStateChange( - const MediaStatus& status) { - media_session_->NotifyMediaSessionMetadataChanged(status); -} - -void AssistantManagerServiceImpl::MediaSessionInfoChanged( - MediaSessionInfoPtr info) { - media_session_info_ptr_ = std::move(info); - UpdateMediaState(); -} - -void AssistantManagerServiceImpl::MediaSessionMetadataChanged( - const base::Optional<media_session::MediaMetadata>& metadata) { - media_metadata_ = std::move(metadata); - UpdateMediaState(); -} - -void AssistantManagerServiceImpl::MediaSessionChanged( - const base::Optional<base::UnguessableToken>& request_id) { - if (request_id.has_value()) - media_session_audio_focus_id_ = std::move(request_id.value()); -} - // TODO(dmblack): Handle non-firing (e.g. paused or scheduled) timers. void AssistantManagerServiceImpl::OnAlarmTimerStateChanged() { ENSURE_MAIN_THREAD(&AssistantManagerServiceImpl::OnAlarmTimerStateChanged); @@ -1315,70 +1143,6 @@ conversation_controller_proxy().SendAssistantFeedback(assistant_feedback); } -void AssistantManagerServiceImpl::UpdateMediaState() { - if (media_session_info_ptr_) { - if (media_session_info_ptr_->is_sensitive) { - // Do not update media state if the session is considered to be sensitive - // (off the record profile). - return; - } - - if (media_session_info_ptr_->state == - MediaSessionInfo::SessionState::kSuspended && - media_session_info_ptr_->playback_state == - media_session::mojom::MediaPlaybackState::kPlaying) { - // It is an intermediate state caused by some providers override the - // playback state. We considered it as invalid and skip reporting the - // state. - return; - } - } - - // MediaSession Integrated providers (include the libassistant internal - // media provider) will trigger media state change event. Only update the - // external media status if the state changes is triggered by external - // providers. - if (media_session_->internal_audio_focus_id() == - media_session_audio_focus_id_) { - return; - } - - MediaStatus media_status; - - // Set media metadata. - if (media_metadata_.has_value()) { - media_status.metadata.title = - base::UTF16ToUTF8(media_metadata_.value().title); - } - - // Set playback state. - media_status.playback_state = MediaStatus::IDLE; - if (media_session_info_ptr_ && - media_session_info_ptr_->state != - MediaSessionInfo::SessionState::kInactive) { - switch (media_session_info_ptr_->playback_state) { - case media_session::mojom::MediaPlaybackState::kPlaying: - media_status.playback_state = MediaStatus::PLAYING; - break; - case media_session::mojom::MediaPlaybackState::kPaused: - media_status.playback_state = MediaStatus::PAUSED; - break; - } - } - - auto* media_manager = assistant_manager()->GetMediaManager(); - if (media_manager) - media_manager->SetExternalPlaybackState(media_status); -} - -void AssistantManagerServiceImpl::ResetMediaState() { - auto* media_manager = assistant_manager()->GetMediaManager(); - if (media_manager) { - MediaStatus media_status; - media_manager->SetExternalPlaybackState(media_status); - } -} - std::string AssistantManagerServiceImpl::NewPendingInteraction( AssistantInteractionType interaction_type, AssistantQuerySource source,
diff --git a/chromeos/services/assistant/assistant_manager_service_impl.h b/chromeos/services/assistant/assistant_manager_service_impl.h index d2aed8b0..7b3d0e2 100644 --- a/chromeos/services/assistant/assistant_manager_service_impl.h +++ b/chromeos/services/assistant/assistant_manager_service_impl.h
@@ -33,12 +33,9 @@ #include "libassistant/shared/internal_api/assistant_manager_delegate.h" #include "libassistant/shared/public/conversation_state_listener.h" #include "libassistant/shared/public/device_state_listener.h" -#include "libassistant/shared/public/media_manager.h" #include "mojo/public/cpp/bindings/receiver.h" #include "mojo/public/cpp/bindings/remote.h" #include "services/device/public/mojom/battery_monitor.mojom.h" -#include "services/media_session/public/mojom/media_controller.mojom.h" -#include "services/media_session/public/mojom/media_session.mojom.h" #include "ui/accessibility/ax_assistant_structure.h" #include "ui/accessibility/mojom/ax_assistant_structure.mojom.h" @@ -60,12 +57,12 @@ namespace chromeos { namespace assistant { -class AssistantMediaSession; class AssistantDeviceSettingsDelegate; class AssistantManagerServiceDelegate; class AssistantProxy; class AudioInputHost; class CrosPlatformApi; +class MediaHost; class ServiceContext; class ServiceControllerProxy; class SpeechRecognitionObserverWrapper; @@ -107,8 +104,6 @@ public assistant_client::ConversationStateListener, public assistant_client::AssistantManagerDelegate, public assistant_client::DeviceStateListener, - public assistant_client::MediaManager::Listener, - public media_session::mojom::MediaControllerObserver, public AppListEventSubscriber { public: // |service| owns this class and must outlive this class. @@ -217,23 +212,6 @@ assistant_client::AssistantManagerInternal* assistant_manager_internal(); void SetMicState(bool mic_open); - // assistant_client::MediaManager::Listener overrides: - void OnPlaybackStateChange( - const assistant_client::MediaStatus& status) override; - - // media_session::mojom::MediaControllerObserver overrides: - void MediaSessionInfoChanged( - media_session::mojom::MediaSessionInfoPtr info) override; - void MediaSessionMetadataChanged( - const base::Optional<media_session::MediaMetadata>& metadata) override; - void MediaSessionActionsChanged( - const std::vector<media_session::mojom::MediaSessionAction>& action) - override {} - void MediaSessionChanged( - const base::Optional<base::UnguessableToken>& request_id) override; - void MediaSessionPositionChanged( - const base::Optional<media_session::MediaPosition>& position) override {} - // Get the action module for testing. action::CrosActionModule* action_module_for_testing() { return action_module_.get(); @@ -247,21 +225,11 @@ void PostInitAssistant(); bool IsServiceStarted() const; - void HandleLaunchMediaIntentResponse(bool app_opened); - void OnAlarmTimerStateChanged(); void OnModifySettingsAction(const std::string& modify_setting_args_proto); - void OnOpenMediaAndroidIntent(const std::string& play_media_args_proto, - AndroidAppInfo* app_info); - void OnPlayMedia(const std::string& play_media_args_proto); - void OnMediaControlAction(const std::string& action_name, - const std::string& media_action_args_proto); void OnDeviceAppsEnabled(bool enabled); - void RegisterFallbackMediaHandler(); - void AddMediaControllerObserver(); - void RemoveMediaControllerObserver(); void RegisterAlarmsTimersListener(); void FillServerExperimentIds(std::vector<std::string>* server_experiment_ids); @@ -275,9 +243,6 @@ // be sent back in the second round (recorded as kDeviceAction). void RecordQueryResponseTypeUMA(); - void UpdateMediaState(); - void ResetMediaState(); - std::string NewPendingInteraction(AssistantInteractionType interaction_type, AssistantQuerySource source, const std::string& query); @@ -309,7 +274,6 @@ void SetStateAndInformObservers(State new_state); State state_ = State::STOPPED; - std::unique_ptr<AssistantMediaSession> media_session_; std::unique_ptr<CrosPlatformApi> platform_api_; std::unique_ptr<action::CrosActionModule> action_module_; std::unique_ptr<AssistantSettingsImpl> assistant_settings_; @@ -318,7 +282,6 @@ std::unique_ptr<AudioInputHost> audio_input_host_; base::ObserverList<AssistantInteractionSubscriber> interaction_subscribers_; - mojo::Remote<media_session::mojom::MediaController> media_controller_; // Owned by the parent |Service| which will destroy |this| before |context_|. ServiceContext* const context_; @@ -326,6 +289,7 @@ std::unique_ptr<AssistantManagerServiceDelegate> delegate_; std::unique_ptr<LibassistantServiceHost> libassistant_service_host_; std::unique_ptr<AssistantDeviceSettingsDelegate> settings_delegate_; + std::unique_ptr<MediaHost> media_host_; std::unique_ptr<SpeechRecognitionObserverWrapper> speech_recognition_observer_; @@ -343,18 +307,6 @@ bool receive_inline_response_ = false; std::string receive_url_response_; - mojo::Receiver<media_session::mojom::MediaControllerObserver> - media_controller_observer_receiver_{this}; - - // Info associated to the active media session. - media_session::mojom::MediaSessionInfoPtr media_session_info_ptr_; - // The metadata for the active media session. It can be null to be reset, e.g. - // the media that was being played has been stopped. - base::Optional<media_session::MediaMetadata> media_metadata_ = base::nullopt; - - base::UnguessableToken media_session_audio_focus_id_ = - base::UnguessableToken::Null(); - // Configuration passed to libassistant. ServiceControllerProxy::BootupConfigPtr bootup_config_;
diff --git a/chromeos/services/assistant/assistant_manager_service_impl_unittest.cc b/chromeos/services/assistant/assistant_manager_service_impl_unittest.cc index d5c0efd3..4d1e517 100644 --- a/chromeos/services/assistant/assistant_manager_service_impl_unittest.cc +++ b/chromeos/services/assistant/assistant_manager_service_impl_unittest.cc
@@ -195,11 +195,15 @@ base::MakeRefCounted<network::WeakWrapperSharedURLLoaderFactory>( &url_loader_factory_); + alarm_timer_controller_ = + std::make_unique<NiceMock<AssistantAlarmTimerControllerMock>>(); + service_context_ = std::make_unique<FakeServiceContext>(); service_context_ ->set_main_task_runner(task_environment().GetMainThreadTaskRunner()) .set_power_manager_client(PowerManagerClient::Get()) - .set_assistant_state(&assistant_state_); + .set_assistant_state(&assistant_state_) + .set_assistant_alarm_timer_controller(alarm_timer_controller_.get()); CreateAssistantManagerServiceImpl(); } @@ -253,6 +257,21 @@ return assistant_manager_service_->action_module_for_testing(); } + // Replace the |AssistantAlarmTimerControllerMock| with a |StrictMock|. + void UseStrictAlarmTimerControllerMock() { + // We can not have 2 instances of |AssistantAlarmTimerController| at the + // same time, so we must destroy the current version first. + alarm_timer_controller_ = nullptr; + alarm_timer_controller_ = + std::make_unique<StrictMock<AssistantAlarmTimerControllerMock>>(); + fake_service_context()->set_assistant_alarm_timer_controller( + alarm_timer_controller_.get()); + } + + AssistantAlarmTimerControllerMock& alarm_timer_controller_mock() { + return *alarm_timer_controller_; + } + base::test::TaskEnvironment& task_environment() { return task_environment_; } void Start() { @@ -260,6 +279,15 @@ /*enable_hotword=*/false); } + // Start Libassistant, and wait until it is running. + void StartAndWaitForRunning() { + Start(); + WaitForState(AssistantManagerService::STARTED); + + fake_assistant_manager()->device_state_listener()->OnStartFinished(); + WaitForState(AssistantManagerService::RUNNING); + } + void RunUntilIdle() { // First ensure our mojom thread is finished. background_thread().FlushForTesting(); @@ -346,6 +374,7 @@ std::unique_ptr<FakeLibassistantV1Api> libassistant_v1_api_{ std::make_unique<FakeLibassistantV1Api>(assistant_manager_.get())}; + std::unique_ptr<AssistantAlarmTimerControllerMock> alarm_timer_controller_; std::unique_ptr<FakeServiceContext> service_context_; network::TestURLLoaderFactory url_loader_factory_; @@ -382,10 +411,6 @@ TEST_F(AssistantManagerServiceImplTest, StateShouldBecomeRunningAfterLibassistantSignalsOnStartFinished) { - NiceMock<AssistantAlarmTimerControllerMock> alarm_timer_controller; - fake_service_context()->set_assistant_alarm_timer_controller( - &alarm_timer_controller); - Start(); WaitForState(AssistantManagerService::STARTED); @@ -506,10 +531,10 @@ TEST_F(AssistantManagerServiceImplTest, ShouldPauseMediaManagerOnPause) { StrictMock<MockMediaManager> mock; + EXPECT_CALL(mock, AddListener); fake_assistant_manager()->SetMediaManager(&mock); - Start(); - WaitForState(AssistantManagerService::STARTED); + StartAndWaitForRunning(); EXPECT_CALL(mock, Pause); @@ -519,10 +544,10 @@ TEST_F(AssistantManagerServiceImplTest, ShouldResumeMediaManagerOnPlay) { StrictMock<MockMediaManager> mock; + EXPECT_CALL(mock, AddListener); fake_assistant_manager()->SetMediaManager(&mock); - Start(); - WaitForState(AssistantManagerService::STARTED); + StartAndWaitForRunning(); EXPECT_CALL(mock, Resume); @@ -539,10 +564,10 @@ }; StrictMock<MockMediaManager> mock; + EXPECT_CALL(mock, AddListener); fake_assistant_manager()->SetMediaManager(&mock); - Start(); - WaitForState(AssistantManagerService::STARTED); + StartAndWaitForRunning(); for (auto action : unsupported_media_session_actions) { // If this is not ignored, |mock| will complain about an uninterested call. @@ -599,10 +624,6 @@ TEST_F(AssistantManagerServiceImplTest, ShouldFireStateObserverWhenLibAssistantSignalsOnStartFinished) { - NiceMock<AssistantAlarmTimerControllerMock> alarm_timer_controller; - fake_service_context()->set_assistant_alarm_timer_controller( - &alarm_timer_controller); - Start(); WaitForState(AssistantManagerService::STARTED); @@ -654,6 +675,7 @@ TEST_F(AssistantManagerServiceImplTest, ShouldNotifyAlarmTimerControllerOfOnlyRingingTimersInV1) { + UseStrictAlarmTimerControllerMock(); base::test::ScopedFeatureList scoped_feature_list; scoped_feature_list.InitAndDisableFeature(features::kAssistantTimersV2); @@ -661,11 +683,7 @@ WaitForState(AssistantManagerService::STARTED); assistant_manager_service()->OnStartFinished(); - StrictMock<AssistantAlarmTimerControllerMock> alarm_timer_controller; - fake_service_context()->set_assistant_alarm_timer_controller( - &alarm_timer_controller); - - EXPECT_CALL(alarm_timer_controller, OnTimerStateChanged) + EXPECT_CALL(alarm_timer_controller_mock(), OnTimerStateChanged) .WillOnce(Invoke([](auto timers) { ASSERT_EQ(1u, timers.size()); EXPECT_EQ(ash::AssistantTimerState::kFired, timers[0]->state); @@ -689,23 +707,20 @@ TEST_F(AssistantManagerServiceImplTest, ShouldNotifyAlarmTimerControllerOfAnyTimersInV2) { + UseStrictAlarmTimerControllerMock(); base::test::ScopedFeatureList scoped_feature_list; scoped_feature_list.InitAndEnableFeature(features::kAssistantTimersV2); - StrictMock<AssistantAlarmTimerControllerMock> alarm_timer_controller; - fake_service_context()->set_assistant_alarm_timer_controller( - &alarm_timer_controller); - // We expect OnTimerStateChanged() to be invoked when starting LibAssistant. - EXPECT_CALL(alarm_timer_controller, OnTimerStateChanged).Times(1); + EXPECT_CALL(alarm_timer_controller_mock(), OnTimerStateChanged).Times(1); Start(); WaitForState(AssistantManagerService::STARTED); assistant_manager_service()->OnStartFinished(); - testing::Mock::VerifyAndClearExpectations(&alarm_timer_controller); + testing::Mock::VerifyAndClearExpectations(&alarm_timer_controller_mock()); - EXPECT_CALL(alarm_timer_controller, OnTimerStateChanged) + EXPECT_CALL(alarm_timer_controller_mock(), OnTimerStateChanged) .WillOnce(Invoke([](auto timers) { ASSERT_EQ(3u, timers.size()); EXPECT_EQ(ash::AssistantTimerState::kScheduled, timers[0]->state); @@ -731,7 +746,7 @@ TEST_F(AssistantManagerServiceImplTest, ShouldNotifyAlarmTimerControllerOfTimersWhenStartingLibAssistantInV2) { - // Enable timers V2. + UseStrictAlarmTimerControllerMock(); base::test::ScopedFeatureList scoped_feature_list; scoped_feature_list.InitAndEnableFeature(features::kAssistantTimersV2); @@ -740,14 +755,9 @@ AddTimerEvent(&events, assistant_client::Timer::State::SCHEDULED); fake_alarm_timer_manager()->SetAllEvents(std::move(events)); - // Bind AssistantAlarmTimerController. - StrictMock<AssistantAlarmTimerControllerMock> alarm_timer_controller; - fake_service_context()->set_assistant_alarm_timer_controller( - &alarm_timer_controller); - // Expect |timers| to be sent to AssistantAlarmTimerController. Verify // AssistantAlarmTimerController is notified of the scheduled timer. - EXPECT_CALL(alarm_timer_controller, OnTimerStateChanged) + EXPECT_CALL(alarm_timer_controller_mock(), OnTimerStateChanged) .WillOnce(Invoke([](auto timers) { ASSERT_EQ(1u, timers.size()); EXPECT_EQ(ash::AssistantTimerState::kScheduled, timers[0]->state);
diff --git a/chromeos/services/assistant/fake_assistant_manager_service_impl.cc b/chromeos/services/assistant/fake_assistant_manager_service_impl.cc index 6f8953d0..45a1899 100644 --- a/chromeos/services/assistant/fake_assistant_manager_service_impl.cc +++ b/chromeos/services/assistant/fake_assistant_manager_service_impl.cc
@@ -71,9 +71,7 @@ } void FakeAssistantManagerServiceImpl::UpdateInternalMediaPlayerStatus( - MediaSessionAction action) { - action_ = action; -} + MediaSessionAction action) {} void FakeAssistantManagerServiceImpl::StartEditReminderInteraction( const std::string& client_id) {}
diff --git a/chromeos/services/assistant/fake_assistant_manager_service_impl.h b/chromeos/services/assistant/fake_assistant_manager_service_impl.h index b521f72..a67c72e 100644 --- a/chromeos/services/assistant/fake_assistant_manager_service_impl.h +++ b/chromeos/services/assistant/fake_assistant_manager_service_impl.h
@@ -86,9 +86,6 @@ // Return the Gaia ID that was passed to |SetUser|. base::Optional<std::string> gaia_id() { return gaia_id_; } - // Return the current media session action. - const MediaSessionAction& media_session_action() { return action_; } - private: // Send out a |AssistantStateObserver::OnStateChange(state)| event if we are // transitioning from a prior state to a later state. @@ -99,7 +96,6 @@ base::Optional<std::string> access_token_; FakeAssistantSettingsImpl assistant_settings_; base::ObserverList<StateObserver> state_observers_; - MediaSessionAction action_ = MediaSessionAction::kPause; DISALLOW_COPY_AND_ASSIGN(FakeAssistantManagerServiceImpl); };
diff --git a/chromeos/services/assistant/media_host.cc b/chromeos/services/assistant/media_host.cc new file mode 100644 index 0000000..281cc9a --- /dev/null +++ b/chromeos/services/assistant/media_host.cc
@@ -0,0 +1,395 @@ +// Copyright 2021 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 "chromeos/services/assistant/media_host.h" + +#include "base/notreached.h" +#include "base/strings/utf_string_conversions.h" +#include "base/threading/sequenced_task_runner_handle.h" +#include "chromeos/assistant/internal/internal_util.h" +#include "chromeos/services/assistant/assistant_manager_service_impl.h" +#include "chromeos/services/assistant/media_session/assistant_media_session.h" +#include "chromeos/services/assistant/public/cpp/assistant_client.h" +#include "chromeos/services/assistant/public/cpp/features.h" +#include "chromeos/services/assistant/public/cpp/migration/libassistant_v1_api.h" +#include "libassistant/shared/internal_api/assistant_manager_internal.h" +#include "libassistant/shared/public/assistant_manager.h" + +// A macro which ensures we are running on the main thread. +#define ENSURE_MAIN_THREAD(method, ...) \ + if (!main_task_runner_->RunsTasksInCurrentSequence()) { \ + main_task_runner_->PostTask( \ + FROM_HERE, \ + base::BindOnce(method, weak_factory_.GetWeakPtr(), ##__VA_ARGS__)); \ + return; \ + } + +namespace chromeos { +namespace assistant { + +namespace { +using assistant_client::MediaStatus; +using media_session::mojom::MediaSessionAction; +using media_session::mojom::MediaSessionInfo; +using media_session::mojom::MediaSessionInfoPtr; + +constexpr char kNextTrackClientOp[] = "media.NEXT"; +constexpr char kPauseTrackClientOp[] = "media.PAUSE"; +constexpr char kPlayMediaClientOp[] = "media.PLAY_MEDIA"; +constexpr char kPrevTrackClientOp[] = "media.PREVIOUS"; +constexpr char kResumeTrackClientOp[] = "media.RESUME"; +constexpr char kStopTrackClientOp[] = "media.STOP"; + +constexpr char kIntentActionView[] = "android.intent.action.VIEW"; +} // namespace + +//////////////////////////////////////////////////////////////////////////////// +// MediaHost::ChromeosMediaStateObserver +//////////////////////////////////////////////////////////////////////////////// + +// Helper class that will observe media changes on ChromeOS and sync them to +// |MediaHost::UpdateMediaState| (which will sync them to +// Libassistant). +class MediaHost::ChromeosMediaStateObserver + : public media_session::mojom::MediaControllerObserver { + public: + explicit ChromeosMediaStateObserver(MediaHost* parent) : parent_(parent) { + DCHECK(parent_); + } + ChromeosMediaStateObserver(const ChromeosMediaStateObserver&) = delete; + ChromeosMediaStateObserver& operator=(const ChromeosMediaStateObserver&) = + delete; + ~ChromeosMediaStateObserver() override = default; + + mojo::PendingRemote<MediaControllerObserver> BindNewPipeAndPassRemote() { + return media_controller_observer_receiver_.BindNewPipeAndPassRemote(); + } + + private: + // media_session::mojom::MediaControllerObserver overrides: + void MediaSessionInfoChanged( + media_session::mojom::MediaSessionInfoPtr info) override { + media_session_info_ptr_ = std::move(info); + UpdateMediaState(); + } + void MediaSessionMetadataChanged( + const base::Optional<media_session::MediaMetadata>& metadata) override { + media_metadata_ = std::move(metadata); + UpdateMediaState(); + } + void MediaSessionActionsChanged( + const std::vector<media_session::mojom::MediaSessionAction>& action) + override {} + void MediaSessionChanged( + const base::Optional<base::UnguessableToken>& request_id) override { + if (request_id.has_value()) + media_session_audio_focus_id_ = std::move(request_id.value()); + } + void MediaSessionPositionChanged( + const base::Optional<media_session::MediaPosition>& position) override {} + + void UpdateMediaState() { + if (media_session_info_ptr_) { + if (media_session_info_ptr_->is_sensitive) { + // Do not update media state if the session is considered to be + // sensitive (off the record profile). + return; + } + + if (media_session_info_ptr_->state == + MediaSessionInfo::SessionState::kSuspended && + media_session_info_ptr_->playback_state == + media_session::mojom::MediaPlaybackState::kPlaying) { + // It is an intermediate state caused by some providers override the + // playback state. We considered it as invalid and skip reporting the + // state. + return; + } + } + + MediaStatus media_status; + + // Set media metadata. + if (media_metadata_.has_value()) { + media_status.metadata.title = + base::UTF16ToUTF8(media_metadata_.value().title); + } + + // Set playback state. + media_status.playback_state = MediaStatus::IDLE; + if (media_session_info_ptr_ && + media_session_info_ptr_->state != + MediaSessionInfo::SessionState::kInactive) { + switch (media_session_info_ptr_->playback_state) { + case media_session::mojom::MediaPlaybackState::kPlaying: + media_status.playback_state = MediaStatus::PLAYING; + break; + case media_session::mojom::MediaPlaybackState::kPaused: + media_status.playback_state = MediaStatus::PAUSED; + break; + } + } + + parent_->UpdateMediaState(media_session_audio_focus_id_, media_status); + } + + MediaHost* const parent_; + mojo::Receiver<media_session::mojom::MediaControllerObserver> + media_controller_observer_receiver_{this}; + + // Info associated to the active media session. + media_session::mojom::MediaSessionInfoPtr media_session_info_ptr_; + // The metadata for the active media session. It can be null to be reset, + // e.g. the media that was being played has been stopped. + base::Optional<media_session::MediaMetadata> media_metadata_ = base::nullopt; + + base::UnguessableToken media_session_audio_focus_id_ = + base::UnguessableToken::Null(); +}; + +//////////////////////////////////////////////////////////////////////////////// +// MediaHost::LibassistantMediaStateObserver +//////////////////////////////////////////////////////////////////////////////// + +// Helper class that will observe media changes in Libassisstant and sync them +// to either |MediaHost::interaction_subscribers_|, +// |MediaHost::media_controller_| or +// |MediaHost::media_session_|. +class MediaHost::LibassistantMediaStateObserver + : public assistant_client::MediaManager::Listener { + public: + explicit LibassistantMediaStateObserver( + MediaHost* parent, + assistant_client::AssistantManagerInternal* assistant_manager_internal) + : parent_(parent), + main_task_runner_(base::SequencedTaskRunnerHandle::Get()) { + // Register handler for media actions. + assistant_manager_internal->RegisterFallbackMediaHandler( + [this](std::string action_name, std::string media_action_args_proto) { + HandleMediaAction(action_name, media_action_args_proto); + }); + } + + LibassistantMediaStateObserver(const LibassistantMediaStateObserver&) = + delete; + LibassistantMediaStateObserver& operator=( + const LibassistantMediaStateObserver&) = delete; + ~LibassistantMediaStateObserver() override = default; + + private: + // Called from the Libassistant thread. + void HandleMediaAction(std::string action_name, + std::string media_action_args_proto) { + ENSURE_MAIN_THREAD(&LibassistantMediaStateObserver::HandleMediaAction, + action_name, media_action_args_proto); + if (action_name == kPlayMediaClientOp) + OnPlayMedia(media_action_args_proto); + else + OnMediaControlAction(action_name, media_action_args_proto); + } + + void OnPlayMedia(const std::string& play_media_args_proto) { + std::unique_ptr<AndroidAppInfo> app_info = + GetAppInfoFromMediaArgs(play_media_args_proto); + if (app_info) { + OnOpenMediaAndroidIntent(play_media_args_proto, app_info.get()); + } else { + std::string url = GetWebUrlFromMediaArgs(play_media_args_proto); + // Fallback to web URL. + if (!url.empty()) + OnOpenUrl(url, /*in_background=*/false); + } + } + + void OnOpenMediaAndroidIntent( + const std::string& play_media_args_proto, + AndroidAppInfo* app_info) { // Handle android media playback intent. + app_info->action = kIntentActionView; + if (app_info->intent.empty()) { + std::string url = GetAndroidIntentUrlFromMediaArgs(play_media_args_proto); + if (!url.empty()) + app_info->intent = url; + } + for (auto& it : interaction_subscribers()) { + bool success = it.OnOpenAppResponse(*app_info); + HandleLaunchMediaIntentResponse(success); + } + } + + void HandleLaunchMediaIntentResponse(bool app_opened) { + // TODO(llin): Handle the response. + NOTIMPLEMENTED(); + } + + void OnOpenUrl(const std::string& url, bool in_background) { + const GURL gurl = GURL(url); + + for (auto& it : interaction_subscribers()) + it.OnOpenUrlResponse(gurl, in_background); + } + + void OnMediaControlAction(const std::string& action_name, + const std::string& media_action_args_proto) { + if (action_name == kPauseTrackClientOp) { + media_controller().Suspend(); + return; + } + + if (action_name == kResumeTrackClientOp) { + media_controller().Resume(); + return; + } + + if (action_name == kNextTrackClientOp) { + media_controller().NextTrack(); + return; + } + + if (action_name == kPrevTrackClientOp) { + media_controller().PreviousTrack(); + return; + } + + if (action_name == kStopTrackClientOp) { + media_controller().Suspend(); + return; + } + // TODO(llin): Handle media.SEEK_RELATIVE. + } + + // assistant_client::MediaManager::Listener overrides: + void OnPlaybackStateChange( + const assistant_client::MediaStatus& status) override { + ENSURE_MAIN_THREAD( + &MediaHost::LibassistantMediaStateObserver::OnPlaybackStateChange, + status); + + parent_->media_session_->NotifyMediaSessionMetadataChanged(status); + } + + const base::ObserverList<AssistantInteractionSubscriber>& + interaction_subscribers() { + return *parent_->interaction_subscribers_; + } + + media_session::mojom::MediaController& media_controller() { + return *parent_->media_controller_; + } + + MediaHost* const parent_; + + scoped_refptr<base::SequencedTaskRunner> main_task_runner_; + + base::WeakPtrFactory<LibassistantMediaStateObserver> weak_factory_{this}; +}; + +//////////////////////////////////////////////////////////////////////////////// +// MediaHost +//////////////////////////////////////////////////////////////////////////////// + +MediaHost::MediaHost(AssistantClient* assistant_client, + const base::ObserverList<AssistantInteractionSubscriber>* + interaction_subscribers) + : interaction_subscribers_(interaction_subscribers), + media_session_(std::make_unique<AssistantMediaSession>(this)) { + DCHECK(assistant_client); + + mojo::Remote<media_session::mojom::MediaControllerManager> + media_controller_manager; + assistant_client->RequestMediaControllerManager( + media_controller_manager.BindNewPipeAndPassReceiver()); + media_controller_manager->CreateActiveMediaController( + media_controller_.BindNewPipeAndPassReceiver()); +} + +MediaHost::~MediaHost() { + Stop(); +} + +void MediaHost::Start( + assistant_client::AssistantManagerInternal* assistant_manager_internal) { + DCHECK(assistant_manager()); + + libassistant_media_state_observer_ = + std::make_unique<LibassistantMediaStateObserver>( + this, assistant_manager_internal); + + if (media_manager()) + media_manager()->AddListener(libassistant_media_state_observer_.get()); +} + +void MediaHost::Stop() { + libassistant_media_state_observer_ = nullptr; + StopObservingMediaController(); +} + +void MediaHost::ResumeInternalMediaPlayer() { + if (media_manager()) + media_manager()->Resume(); +} + +void MediaHost::PauseInternalMediaPlayer() { + if (media_manager()) + media_manager()->Pause(); +} + +void MediaHost::SetRelatedInfoEnabled(bool enable) { + if (enable) { + StartObservingMediaController(); + } else { + StopObservingMediaController(); + ResetMediaState(); + } +} + +assistant_client::MediaManager* MediaHost::media_manager() { + if (!assistant_manager()) + return nullptr; + return assistant_manager()->GetMediaManager(); +} + +void MediaHost::UpdateMediaState(const base::UnguessableToken& media_session_id, + const MediaStatus& media_status) { + // MediaSession Integrated providers (include the libassistant internal + // media provider) will trigger media state change event. Only update the + // external media status if the state changes is triggered by external + // providers. + if (media_session_->internal_audio_focus_id() == media_session_id) { + return; + } + + if (media_manager()) + media_manager()->SetExternalPlaybackState(media_status); +} + +void MediaHost::ResetMediaState() { + if (media_manager()) { + media_manager()->SetExternalPlaybackState(MediaStatus{}); + } +} + +void MediaHost::StartObservingMediaController() { + if (!features::IsMediaSessionIntegrationEnabled()) + return; + + if (chromeos_media_state_observer_) + return; + + chromeos_media_state_observer_ = + std::make_unique<ChromeosMediaStateObserver>(this); + media_controller_->AddObserver( + chromeos_media_state_observer_->BindNewPipeAndPassRemote()); +} + +void MediaHost::StopObservingMediaController() { + chromeos_media_state_observer_.reset(); +} + +assistant_client::AssistantManager* MediaHost::assistant_manager() { + auto* api = LibassistantV1Api::Get(); + return api ? api->assistant_manager() : nullptr; +} + +} // namespace assistant +} // namespace chromeos
diff --git a/chromeos/services/assistant/media_host.h b/chromeos/services/assistant/media_host.h new file mode 100644 index 0000000..81cc1f8 --- /dev/null +++ b/chromeos/services/assistant/media_host.h
@@ -0,0 +1,98 @@ +// Copyright 2021 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 CHROMEOS_SERVICES_ASSISTANT_MEDIA_HOST_H_ +#define CHROMEOS_SERVICES_ASSISTANT_MEDIA_HOST_H_ + +#include "base/component_export.h" +#include "base/unguessable_token.h" +#include "mojo/public/cpp/bindings/receiver.h" +#include "mojo/public/cpp/bindings/remote.h" +#include "services/media_session/public/mojom/media_controller.mojom.h" +#include "services/media_session/public/mojom/media_session.mojom.h" + +namespace assistant_client { +class AssistantManager; +class AssistantManagerInternal; +class MediaManager; +struct MediaStatus; +} // namespace assistant_client + +namespace chromeos { +namespace assistant { + +class AssistantClient; +class AssistantInteractionSubscriber; +class AssistantManagerServiceImpl; +class AssistantMediaSession; + +// Handles all media related interactions with Libassistant, which can broadly +// be separated in 2 responsibilities: +// 1) Let Libassistant know about the currently playing media. +// 1) Let Libassistant control media (start/stop/open spotify). +class COMPONENT_EXPORT(ASSISTANT_SERVICE) MediaHost { + public: + MediaHost(AssistantClient* assistant_client, + const base::ObserverList<AssistantInteractionSubscriber>* + interaction_subscribers); + MediaHost(const MediaHost&) = delete; + MediaHost& operator=(const MediaHost&) = delete; + ~MediaHost(); + + mojo::PendingReceiver<media_session::mojom::MediaController> + BindMediaControllerAndPassPendingReceiver(); + + // Start handling media. + void Start( + assistant_client::AssistantManagerInternal* assistant_manager_internal); + + // Stop handling media. + void Stop(); + + // Pause/resume playback of Libassistant media player (which plays podcasts + // and news). + void ResumeInternalMediaPlayer(); + void PauseInternalMediaPlayer(); + + // Called when the user allows/disallows related info. + // We only observe the current playing audio when related info is allowed. + void SetRelatedInfoEnabled(bool enable); + + AssistantMediaSession& media_session() { return *media_session_; } + + private: + class LibassistantMediaStateObserver; + class ChromeosMediaStateObserver; + + assistant_client::MediaManager* media_manager(); + + void UpdateMediaState(const base::UnguessableToken& media_session_id, + const assistant_client::MediaStatus& media_status); + void ResetMediaState(); + + void StartObservingMediaController(); + void StopObservingMediaController(); + + assistant_client::AssistantManager* assistant_manager(); + + // Owned by our parent |AssistantManagerServiceImpl|. + const base::ObserverList<AssistantInteractionSubscriber>* const + interaction_subscribers_; + + std::unique_ptr<AssistantMediaSession> media_session_; + mojo::Remote<media_session::mojom::MediaController> media_controller_; + + // Helper class that will observe media changes on ChromeOS and sync them + // to Libassistant. + std::unique_ptr<ChromeosMediaStateObserver> chromeos_media_state_observer_; + // Helper class that will observe media changes in Libassistant and + // sync/apply them in ChromeOS. + std::unique_ptr<LibassistantMediaStateObserver> + libassistant_media_state_observer_; +}; + +} // namespace assistant +} // namespace chromeos + +#endif // CHROMEOS_SERVICES_ASSISTANT_MEDIA_HOST_H_
diff --git a/chromeos/services/assistant/media_session/assistant_media_session.cc b/chromeos/services/assistant/media_session/assistant_media_session.cc index 3ac393ed..ac88332 100644 --- a/chromeos/services/assistant/media_session/assistant_media_session.cc +++ b/chromeos/services/assistant/media_session/assistant_media_session.cc
@@ -9,7 +9,7 @@ #include "base/bind.h" #include "base/memory/scoped_refptr.h" #include "base/strings/utf_string_conversions.h" -#include "chromeos/services/assistant/assistant_manager_service.h" +#include "chromeos/services/assistant/media_host.h" #include "chromeos/services/assistant/public/cpp/assistant_client.h" #include "services/media_session/public/cpp/features.h" @@ -35,10 +35,8 @@ } // namespace -AssistantMediaSession::AssistantMediaSession( - AssistantManagerService* assistant_manager_service) - : assistant_manager_service_(assistant_manager_service), - main_task_runner_(base::SequencedTaskRunnerHandle::Get()) {} +AssistantMediaSession::AssistantMediaSession(MediaHost* host) + : host_(host), main_task_runner_(base::SequencedTaskRunnerHandle::Get()) {} AssistantMediaSession::~AssistantMediaSession() { AbandonAudioFocusIfNeeded(); @@ -81,16 +79,14 @@ return; SetAudioFocusInfo(MediaSessionInfo::SessionState::kSuspended, audio_focus_type_); - assistant_manager_service_->UpdateInternalMediaPlayerStatus( - media_session::mojom::MediaSessionAction::kPause); + host_->PauseInternalMediaPlayer(); } void AssistantMediaSession::Resume(SuspendType suspend_type) { if (!IsSessionStateSuspended()) return; SetAudioFocusInfo(MediaSessionInfo::SessionState::kActive, audio_focus_type_); - assistant_manager_service_->UpdateInternalMediaPlayerStatus( - media_session::mojom::MediaSessionAction::kPlay); + host_->ResumeInternalMediaPlayer(); } void AssistantMediaSession::RequestAudioFocus(AudioFocusType audio_focus_type) {
diff --git a/chromeos/services/assistant/media_session/assistant_media_session.h b/chromeos/services/assistant/media_session/assistant_media_session.h index d848c9d9..bfbb37f 100644 --- a/chromeos/services/assistant/media_session/assistant_media_session.h +++ b/chromeos/services/assistant/media_session/assistant_media_session.h
@@ -24,7 +24,7 @@ namespace chromeos { namespace assistant { -class AssistantManagerService; +class MediaHost; // MediaSession manages the media session and audio focus for Assistant. // MediaSession allows clients to observe its changes via MediaSessionObserver, @@ -32,8 +32,7 @@ class COMPONENT_EXPORT(ASSISTANT_SERVICE) AssistantMediaSession : public media_session::mojom::MediaSession { public: - explicit AssistantMediaSession( - AssistantManagerService* assistant_manager_service); + explicit AssistantMediaSession(MediaHost* host); ~AssistantMediaSession() override; // media_session.mojom.MediaSession overrides: @@ -105,7 +104,7 @@ // The current metadata associated with the current media session. media_session::MediaMetadata metadata_; - AssistantManagerService* const assistant_manager_service_; + MediaHost* const host_; scoped_refptr<base::SequencedTaskRunner> main_task_runner_; // Binding for Mojo pointer to |this| held by AudioFocusManager.
diff --git a/chromeos/services/assistant/media_session/assistant_media_session_unittest.cc b/chromeos/services/assistant/media_session/assistant_media_session_unittest.cc index da1dc95..bbbd90d 100644 --- a/chromeos/services/assistant/media_session/assistant_media_session_unittest.cc +++ b/chromeos/services/assistant/media_session/assistant_media_session_unittest.cc
@@ -7,30 +7,52 @@ #include <memory> #include "base/test/task_environment.h" -#include "chromeos/services/assistant/fake_assistant_manager_service_impl.h" +#include "chromeos/assistant/internal/test_support/fake_assistant_manager.h" +#include "chromeos/assistant/internal/test_support/fake_assistant_manager_internal.h" +#include "chromeos/services/assistant/media_host.h" +#include "chromeos/services/assistant/public/cpp/assistant_client.h" +#include "chromeos/services/assistant/public/cpp/migration/libassistant_v1_api.h" +#include "chromeos/services/assistant/test_support/mock_media_manager.h" #include "chromeos/services/assistant/test_support/scoped_assistant_client.h" +#include "testing/gmock/include/gmock/gmock.h" #include "testing/gtest/include/gtest/gtest.h" namespace chromeos { namespace assistant { +namespace { + using media_session::mojom::MediaSession; using media_session::mojom::MediaSessionAction; using media_session::mojom::MediaSessionInfo; +class FakeLibassistantV1Api : public LibassistantV1Api { + public: + explicit FakeLibassistantV1Api(FakeAssistantManager* assistant_manager) + : LibassistantV1Api(assistant_manager, + &assistant_manager->assistant_manager_internal()) {} +}; + +} // namespace + class AssistantMediaSessionTest : public testing::Test { public: AssistantMediaSessionTest() - : assistant_media_session_(std::make_unique<AssistantMediaSession>( - &fake_assistant_manager_service_impl_)) {} + : media_host_(AssistantClient::Get(), + /*interaction_subscribers=*/nullptr), + assistant_media_session_(&media_host_) {} ~AssistantMediaSessionTest() override = default; AssistantMediaSession* assistant_media_session() { - return assistant_media_session_.get(); + return &assistant_media_session_; } - FakeAssistantManagerServiceImpl* assistant_manager_service() { - return &fake_assistant_manager_service_impl_; + MediaHost& media_host() { return media_host_; } + + void StartMediaHost(MockMediaManager& media_manager_mock) { + assistant_manager_.SetMediaManager(&media_manager_mock); + EXPECT_CALL(media_manager_mock, AddListener); + media_host().Start(&assistant_manager_.assistant_manager_internal()); } private: @@ -38,9 +60,11 @@ // other class members. base::test::SingleThreadTaskEnvironment task_environment_; - std::unique_ptr<AssistantMediaSession> assistant_media_session_; - ScopedAssistantClient fake_client_; - FakeAssistantManagerServiceImpl fake_assistant_manager_service_impl_; + ScopedAssistantClient client; + MediaHost media_host_; + FakeAssistantManager assistant_manager_; + FakeLibassistantV1Api libassistant_v1_api_{&assistant_manager_}; + AssistantMediaSession assistant_media_session_; }; TEST_F(AssistantMediaSessionTest, ShouldUpdateSessionStateOnStartStopDucking) { @@ -53,20 +77,23 @@ TEST_F(AssistantMediaSessionTest, ShouldUpdateSessionStateAndSendActionOnSuspendResumePlaying) { + testing::StrictMock<MockMediaManager> media_manager; + StartMediaHost(media_manager); + + // Suspend. + EXPECT_CALL(media_manager, Pause); assistant_media_session()->Suspend(MediaSession::SuspendType::kSystem); EXPECT_TRUE(assistant_media_session()->IsSessionStateSuspended()); - EXPECT_EQ(assistant_manager_service()->media_session_action(), - MediaSessionAction::kPause); + // Then resume. + EXPECT_CALL(media_manager, Resume); assistant_media_session()->Resume(MediaSession::SuspendType::kSystem); EXPECT_TRUE(assistant_media_session()->IsSessionStateActive()); - EXPECT_EQ(assistant_manager_service()->media_session_action(), - MediaSessionAction::kPlay); + // And pause again. + EXPECT_CALL(media_manager, Pause); assistant_media_session()->Suspend(MediaSession::SuspendType::kSystem); EXPECT_TRUE(assistant_media_session()->IsSessionStateSuspended()); - EXPECT_EQ(assistant_manager_service()->media_session_action(), - MediaSessionAction::kPause); } } // namespace assistant
diff --git a/chromeos/services/assistant/platform/audio_output_provider_impl_unittest.cc b/chromeos/services/assistant/platform/audio_output_provider_impl_unittest.cc index 3ec5270..917cca33 100644 --- a/chromeos/services/assistant/platform/audio_output_provider_impl_unittest.cc +++ b/chromeos/services/assistant/platform/audio_output_provider_impl_unittest.cc
@@ -14,6 +14,7 @@ #include "base/test/task_environment.h" #include "base/threading/thread.h" #include "chromeos/services/assistant/fake_assistant_manager_service_impl.h" +#include "chromeos/services/assistant/media_host.h" #include "chromeos/services/assistant/media_session/assistant_media_session.h" #include "chromeos/services/assistant/test_support/scoped_assistant_client.h" #include "libassistant/shared/public/platform_audio_output.h" @@ -80,22 +81,22 @@ DISALLOW_COPY_AND_ASSIGN(FakeAudioOutputDelegate); }; -class AudioDeviceOwnerTest : public testing::Test { +class AssistantAudioDeviceOwnerTest : public testing::Test { public: - AudioDeviceOwnerTest() + AssistantAudioDeviceOwnerTest() : task_env_( base::test::TaskEnvironment::MainThreadType::DEFAULT, base::test::TaskEnvironment::ThreadPoolExecutionMode::QUEUED) {} - ~AudioDeviceOwnerTest() override { task_env_.RunUntilIdle(); } + ~AssistantAudioDeviceOwnerTest() override { task_env_.RunUntilIdle(); } private: base::test::TaskEnvironment task_env_; - DISALLOW_COPY_AND_ASSIGN(AudioDeviceOwnerTest); + DISALLOW_COPY_AND_ASSIGN(AssistantAudioDeviceOwnerTest); }; -TEST_F(AudioDeviceOwnerTest, BufferFilling) { +TEST_F(AssistantAudioDeviceOwnerTest, BufferFilling) { FakeAudioOutputDelegate delegate; auto audio_bus = media::AudioBus::Create(2, 4480); assistant_client::OutputStreamFormat format{ @@ -107,8 +108,9 @@ delegate.set_num_of_bytes_to_fill(200); delegate.Reset(); ScopedAssistantClient client; - FakeAssistantManagerServiceImpl assistant_manager_service; - AssistantMediaSession media_session(&assistant_manager_service); + MediaHost media_host(AssistantClient::Get(), + /*interaction_subscribers=*/nullptr); + AssistantMediaSession media_session(&media_host); auto owner = std::make_unique<AudioDeviceOwner>( base::SequencedTaskRunnerHandle::Get(),
diff --git a/chromeos/ui/frame/caption_buttons/frame_caption_button_container_view.cc b/chromeos/ui/frame/caption_buttons/frame_caption_button_container_view.cc index b0b1c56..9066c264 100644 --- a/chromeos/ui/frame/caption_buttons/frame_caption_button_container_view.cc +++ b/chromeos/ui/frame/caption_buttons/frame_caption_button_container_view.cc
@@ -224,17 +224,17 @@ views::FrameCaptionButton* buttons[] = {menu_button_, minimize_button_, size_button_, close_button_}; for (size_t i = 0; i < base::size(buttons); ++i) { - if (buttons[i]->GetIcon() == icon) + if (buttons[i]->icon() == icon) buttons[i]->SetImage(icon, views::FrameCaptionButton::ANIMATE_NO, icon_definition); } } void FrameCaptionButtonContainerView::SetPaintAsActive(bool paint_as_active) { - menu_button_->SetPaintAsActive(paint_as_active); - minimize_button_->SetPaintAsActive(paint_as_active); - size_button_->SetPaintAsActive(paint_as_active); - close_button_->SetPaintAsActive(paint_as_active); + menu_button_->set_paint_as_active(paint_as_active); + minimize_button_->set_paint_as_active(paint_as_active); + size_button_->set_paint_as_active(paint_as_active); + close_button_->set_paint_as_active(paint_as_active); SchedulePaint(); } @@ -389,7 +389,7 @@ // The early return is dependent on |animate| because callers use // SetButtonIcon() with ANIMATE_NO to progress |button|'s crossfade animation // to the end. - if (button->GetIcon() == icon && + if (button->icon() == icon && (animate == ANIMATE_YES || !button->IsAnimatingImageSwap())) { return; }
diff --git a/chromeos/ui/frame/caption_buttons/frame_size_button.cc b/chromeos/ui/frame/caption_buttons/frame_size_button.cc index 67801d37..f0b1b6e9 100644 --- a/chromeos/ui/frame/caption_buttons/frame_size_button.cc +++ b/chromeos/ui/frame/caption_buttons/frame_size_button.cc
@@ -44,7 +44,7 @@ SnapDirection GetSnapDirection(const views::FrameCaptionButton* to_hover) { if (to_hover) { - switch (to_hover->GetIcon()) { + switch (to_hover->icon()) { case views::CAPTION_BUTTON_ICON_LEFT_SNAPPED: return SnapDirection::kLeft; case views::CAPTION_BUTTON_ICON_RIGHT_SNAPPED: @@ -272,8 +272,8 @@ views::View::ConvertPointToScreen(this, &event_location_in_screen); const views::FrameCaptionButton* closest_button = delegate_->GetButtonClosestTo(event_location_in_screen); - if ((closest_button->GetIcon() == views::CAPTION_BUTTON_ICON_LEFT_SNAPPED || - closest_button->GetIcon() == views::CAPTION_BUTTON_ICON_RIGHT_SNAPPED) && + if ((closest_button->icon() == views::CAPTION_BUTTON_ICON_LEFT_SNAPPED || + closest_button->icon() == views::CAPTION_BUTTON_ICON_RIGHT_SNAPPED) && HitTestButton(closest_button, event_location_in_screen)) { return closest_button; }
diff --git a/chromeos/ui/frame/frame_header.cc b/chromeos/ui/frame/frame_header.cc index b3d54a90..c9e234a 100644 --- a/chromeos/ui/frame/frame_header.cc +++ b/chromeos/ui/frame/frame_header.cc
@@ -237,7 +237,7 @@ caption_button_container_->SetPaintAsActive(paint_as_active); if (back_button_) - back_button_->SetPaintAsActive(paint_as_active); + back_button_->set_paint_as_active(paint_as_active); UpdateCaptionButtonColors(); }
diff --git a/components/BUILD.gn b/components/BUILD.gn index 734bef68..ae7f1f3 100644 --- a/components/BUILD.gn +++ b/components/BUILD.gn
@@ -133,6 +133,9 @@ "//components/query_parser:unit_tests", "//components/rappor:unit_tests", "//components/reading_list/core:unit_tests", + "//components/reporting/encryption:unit_tests", + "//components/reporting/storage:unit_tests", + "//components/reporting/util:unit_tests", "//components/reputation/core:unit_tests", "//components/safe_search_api:unit_tests", "//components/scheduling_metrics:unit_tests", @@ -289,6 +292,10 @@ "//components/policy/content:unit_tests", "//components/previews/content:unit_tests", "//components/query_tiles:unit_tests", + + # TODO(chromium:1169835) components/reporting/storage/resources:unit_tests + # can't be run on iOS until they are updated. + "//components/reporting/storage/resources:unit_tests", "//components/safe_browsing/content/password_protection:password_protection_unittest", "//components/safe_browsing/content/triggers:unit_tests", "//components/safe_browsing/content/web_ui:unit_tests",
diff --git a/components/about_ui/credit_utils.cc b/components/about_ui/credit_utils.cc index 6df8365..ace1a0f 100644 --- a/components/about_ui/credit_utils.cc +++ b/components/about_ui/credit_utils.cc
@@ -18,7 +18,6 @@ IDR_ABOUT_UI_CREDITS_HTML); if (include_scripts) { response += - "\n<script src=\"chrome://resources/js/cr.js\"></script>\n" "<script src=\"chrome://credits/credits.js\"></script>\n"; } response += "</body>\n</html>";
diff --git a/components/about_ui/resources/about_credits.js b/components/about_ui/resources/about_credits.js index 7a2538a..6a98945 100644 --- a/components/about_ui/resources/about_credits.js +++ b/components/about_ui/resources/about_credits.js
@@ -9,19 +9,19 @@ /* eslint-enable no-restricted-properties */ document.addEventListener('DOMContentLoaded', function() { - if (cr.isChromeOS) { - const keyboardUtils = document.createElement('script'); + // <if expr="chromeos"> + const keyboardUtils = document.createElement('script'); - const staticUrlPolicy = trustedTypes.createPolicy( - 'credits-static', - {createScriptURL: () => 'chrome://credits/keyboard_utils.js'}); + const staticUrlPolicy = trustedTypes.createPolicy( + 'credits-static', + {createScriptURL: () => 'chrome://credits/keyboard_utils.js'}); - // TODO(Jun.Kokatsu@microsoft.com): remove an empty string argument - // once supported. - // https://github.com/w3c/webappsec-trusted-types/issues/278 - keyboardUtils.src = staticUrlPolicy.createScriptURL(''); - document.body.appendChild(keyboardUtils); - } + // TODO(Jun.Kokatsu@microsoft.com): remove an empty string argument + // once supported. + // https://github.com/w3c/webappsec-trusted-types/issues/278 + keyboardUtils.src = staticUrlPolicy.createScriptURL(''); + document.body.appendChild(keyboardUtils); + // </if> $('print-link').hidden = false; $('print-link').onclick = function() {
diff --git a/components/arc/BUILD.gn b/components/arc/BUILD.gn index b7d387b..17bf253 100644 --- a/components/arc/BUILD.gn +++ b/components/arc/BUILD.gn
@@ -73,6 +73,8 @@ "property/arc_property_bridge.h", "rotation_lock/arc_rotation_lock_bridge.cc", "rotation_lock/arc_rotation_lock_bridge.h", + "sensor/arc_iio_sensor_bridge.cc", + "sensor/arc_iio_sensor_bridge.h", "sensor/arc_sensor_bridge.cc", "sensor/arc_sensor_bridge.h", "storage_manager/arc_storage_manager.cc", @@ -100,6 +102,7 @@ "//ash/public/cpp", "//base", "//chromeos/audio", + "//chromeos/components/sensors:sensors", "//chromeos/constants", "//chromeos/cryptohome", "//chromeos/dbus", @@ -254,6 +257,7 @@ "//ash/public/cpp/external_arc", "//base", "//chromeos/components/sensors:buildflags", + "//chromeos/components/sensors/mojom", "//chromeos/constants", "//chromeos/cryptohome", "//chromeos/dbus:common",
diff --git a/components/arc/DEPS b/components/arc/DEPS index e5db5e1..0ffc244 100644 --- a/components/arc/DEPS +++ b/components/arc/DEPS
@@ -1,5 +1,6 @@ include_rules = [ "+ash/public/cpp", + "+chromeos/components/sensors", "+chromeos/constants", "+chromeos/cryptohome", "+chromeos/dbus",
diff --git a/components/arc/mojom/BUILD.gn b/components/arc/mojom/BUILD.gn index 5784d111..2cebdec 100644 --- a/components/arc/mojom/BUILD.gn +++ b/components/arc/mojom/BUILD.gn
@@ -32,6 +32,7 @@ "disk_quota.mojom", "enterprise_reporting.mojom", "file_system.mojom", + "iio_sensor.mojom", "ime.mojom", "input_method_manager.mojom", "intent_common.mojom", @@ -75,6 +76,7 @@ ":media", ":notifications", ":oemcrypto", + "//chromeos/components/sensors/mojom:mojom", "//components/payments/mojom:mojom", "//media/capture/video/chromeos/mojom:cros_camera", "//mojo/public/mojom/base",
diff --git a/components/arc/mojom/arc_bridge.mojom b/components/arc/mojom/arc_bridge.mojom index 4a6f6bd..183f218f 100644 --- a/components/arc/mojom/arc_bridge.mojom +++ b/components/arc/mojom/arc_bridge.mojom
@@ -23,6 +23,7 @@ import "components/arc/mojom/disk_quota.mojom"; import "components/arc/mojom/enterprise_reporting.mojom"; import "components/arc/mojom/file_system.mojom"; +import "components/arc/mojom/iio_sensor.mojom"; import "components/arc/mojom/ime.mojom"; import "components/arc/mojom/input_method_manager.mojom"; import "components/arc/mojom/intent_helper.mojom"; @@ -59,9 +60,9 @@ import "components/arc/mojom/wake_lock.mojom"; import "components/arc/mojom/wallpaper.mojom"; -// Next MinVersion: 54 +// Next MinVersion: 55 // Deprecated method IDs: 101, 105, 121 -// Next method ID: 159 +// Next method ID: 160 interface ArcBridgeHost { // Keep the entries alphabetical. In order to do so without breaking // compatibility with the ARC instance, explicitly assign each interface a @@ -142,6 +143,10 @@ [MinVersion=13] OnFileSystemInstanceReady@119( pending_remote<FileSystemInstance> instance_remote); + // Notifies Chrome that the IioSensorInstance interface is ready. + [MinVersion=54] OnIioSensorInstanceReady@159( + pending_remote<IioSensorInstance> instance_remote); + // Notifies Chrome that the ImeInstance interface is ready. [MinVersion=3] OnImeInstanceReady@110( pending_remote<ImeInstance> instance_remote);
diff --git a/components/arc/mojom/iio_sensor.mojom b/components/arc/mojom/iio_sensor.mojom new file mode 100644 index 0000000..f4685107 --- /dev/null +++ b/components/arc/mojom/iio_sensor.mojom
@@ -0,0 +1,23 @@ +// Copyright 2020 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. + +module arc.mojom; + +import "chromeos/components/sensors/mojom/cros_sensor_service.mojom"; + +// Chrome implements this interface to handle requests from ARC +// to iioservice. +// Next method ID: 1 +interface IioSensorHost { + // Registers Sensor HAL client. + RegisterSensorHalClient@0( + pending_remote<chromeos.sensors.mojom.SensorHalClient> client); +}; + +// ARC implements this interface to interact with chrome. +// Next method ID: 1 +interface IioSensorInstance { + // Establishes full-duplex communication with the host. + Init@0(pending_remote<IioSensorHost> host_remote) => (); +};
diff --git a/components/arc/mojom/sensor.mojom b/components/arc/mojom/sensor.mojom index 57733174..5978fcc 100644 --- a/components/arc/mojom/sensor.mojom +++ b/components/arc/mojom/sensor.mojom
@@ -18,4 +18,4 @@ interface SensorInstance { // Establishes full-duplex communication with the host. Init@0(pending_remote<SensorHost> host_ptr) => (); -}; \ No newline at end of file +};
diff --git a/components/arc/sensor/arc_iio_sensor_bridge.cc b/components/arc/sensor/arc_iio_sensor_bridge.cc new file mode 100644 index 0000000..96052cb --- /dev/null +++ b/components/arc/sensor/arc_iio_sensor_bridge.cc
@@ -0,0 +1,61 @@ +// Copyright 2020 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 "components/arc/sensor/arc_iio_sensor_bridge.h" + +#include <utility> + +#include "base/memory/singleton.h" +#include "chromeos/components/sensors/sensor_hal_dispatcher.h" +#include "components/arc/arc_browser_context_keyed_service_factory_base.h" +#include "components/arc/session/arc_bridge_service.h" + +namespace arc { + +namespace { + +// Singleton factory for ArcIioSensorBridge. +class ArcIioSensorBridgeFactory + : public internal::ArcBrowserContextKeyedServiceFactoryBase< + ArcIioSensorBridge, + ArcIioSensorBridgeFactory> { + public: + // Factory name used by ArcBrowserContextKeyedServiceFactoryBase. + static constexpr const char* kName = "ArcIioSensorBridgeFactory"; + + static ArcIioSensorBridgeFactory* GetInstance() { + return base::Singleton<ArcIioSensorBridgeFactory>::get(); + } + + private: + friend base::DefaultSingletonTraits<ArcIioSensorBridgeFactory>; + ArcIioSensorBridgeFactory() = default; + ~ArcIioSensorBridgeFactory() override = default; +}; + +} // namespace + +// static +ArcIioSensorBridge* ArcIioSensorBridge::GetForBrowserContext( + content::BrowserContext* context) { + return ArcIioSensorBridgeFactory::GetForBrowserContext(context); +} + +ArcIioSensorBridge::ArcIioSensorBridge(content::BrowserContext* context, + ArcBridgeService* bridge_service) + : arc_bridge_service_(bridge_service) { + arc_bridge_service_->iio_sensor()->SetHost(this); +} + +ArcIioSensorBridge::~ArcIioSensorBridge() { + arc_bridge_service_->iio_sensor()->SetHost(nullptr); +} + +void ArcIioSensorBridge::RegisterSensorHalClient( + mojo::PendingRemote<chromeos::sensors::mojom::SensorHalClient> remote) { + chromeos::sensors::SensorHalDispatcher::GetInstance()->RegisterClient( + std::move(remote)); +} + +} // namespace arc
diff --git a/components/arc/sensor/arc_iio_sensor_bridge.h b/components/arc/sensor/arc_iio_sensor_bridge.h new file mode 100644 index 0000000..343a827 --- /dev/null +++ b/components/arc/sensor/arc_iio_sensor_bridge.h
@@ -0,0 +1,44 @@ +// Copyright 2020 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 COMPONENTS_ARC_SENSOR_ARC_IIO_SENSOR_BRIDGE_H_ +#define COMPONENTS_ARC_SENSOR_ARC_IIO_SENSOR_BRIDGE_H_ + +#include "components/arc/mojom/iio_sensor.mojom.h" +#include "components/keyed_service/core/keyed_service.h" + +namespace content { +class BrowserContext; +} // namespace content + +namespace arc { + +class ArcBridgeService; + +// This class handles Sensor-related requests from the ARC container. +class ArcIioSensorBridge : public KeyedService, public mojom::IioSensorHost { + public: + // Returns singleton instance for the given BrowserContext, + // or nullptr if the browser |context| is not allowed to use ARC. + static ArcIioSensorBridge* GetForBrowserContext( + content::BrowserContext* context); + + ArcIioSensorBridge(content::BrowserContext* context, + ArcBridgeService* bridge_service); + ~ArcIioSensorBridge() override; + ArcIioSensorBridge(const ArcIioSensorBridge&) = delete; + ArcIioSensorBridge& operator=(const ArcIioSensorBridge&) = delete; + + // mojom::IioSensorHost overrides: + void RegisterSensorHalClient( + mojo::PendingRemote<chromeos::sensors::mojom::SensorHalClient> remote) + override; + + private: + ArcBridgeService* const arc_bridge_service_; // Owned by ArcServiceManager. +}; + +} // namespace arc + +#endif // COMPONENTS_ARC_SENSOR_ARC_IIO_SENSOR_BRIDGE_H_
diff --git a/components/arc/session/arc_bridge_host_impl.cc b/components/arc/session/arc_bridge_host_impl.cc index fd8516d..e0ac110 100644 --- a/components/arc/session/arc_bridge_host_impl.cc +++ b/components/arc/session/arc_bridge_host_impl.cc
@@ -11,6 +11,7 @@ #include "ash/public/cpp/message_center/arc_notifications_host_initializer.h" #include "base/bind.h" #include "base/callback_helpers.h" +#include "chromeos/components/sensors/mojom/cros_sensor_service.mojom.h" #include "components/arc/mojom/accessibility_helper.mojom.h" #include "components/arc/mojom/adbd.mojom.h" #include "components/arc/mojom/app.mojom.h" @@ -201,6 +202,12 @@ OnInstanceReady(arc_bridge_service_->ime(), std::move(ime_remote)); } +void ArcBridgeHostImpl::OnIioSensorInstanceReady( + mojo::PendingRemote<mojom::IioSensorInstance> iio_sensor_remote) { + OnInstanceReady(arc_bridge_service_->iio_sensor(), + std::move(iio_sensor_remote)); +} + void ArcBridgeHostImpl::OnInputMethodManagerInstanceReady( mojo::PendingRemote<mojom::InputMethodManagerInstance> input_method_manager_remote) {
diff --git a/components/arc/session/arc_bridge_host_impl.h b/components/arc/session/arc_bridge_host_impl.h index 753bdf1..714675e 100644 --- a/components/arc/session/arc_bridge_host_impl.h +++ b/components/arc/session/arc_bridge_host_impl.h
@@ -85,6 +85,8 @@ enterprise_reporting_remote) override; void OnFileSystemInstanceReady(mojo::PendingRemote<mojom::FileSystemInstance> file_system_remote) override; + void OnIioSensorInstanceReady( + mojo::PendingRemote<mojom::IioSensorInstance> iio_sensor_remote) override; void OnImeInstanceReady( mojo::PendingRemote<mojom::ImeInstance> ime_remote) override; void OnInputMethodManagerInstanceReady(
diff --git a/components/arc/session/arc_bridge_service.cc b/components/arc/session/arc_bridge_service.cc index 35b5f37..5f41961 100644 --- a/components/arc/session/arc_bridge_service.cc +++ b/components/arc/session/arc_bridge_service.cc
@@ -25,6 +25,7 @@ #include "components/arc/mojom/disk_quota.mojom.h" #include "components/arc/mojom/enterprise_reporting.mojom.h" #include "components/arc/mojom/file_system.mojom.h" +#include "components/arc/mojom/iio_sensor.mojom.h" #include "components/arc/mojom/ime.mojom.h" #include "components/arc/mojom/input_method_manager.mojom.h" #include "components/arc/mojom/intent_helper.mojom.h"
diff --git a/components/arc/session/arc_bridge_service.h b/components/arc/session/arc_bridge_service.h index be9a027..e1669b5c 100644 --- a/components/arc/session/arc_bridge_service.h +++ b/components/arc/session/arc_bridge_service.h
@@ -49,6 +49,8 @@ class EnterpriseReportingInstance; class FileSystemHost; class FileSystemInstance; +class IioSensorHost; +class IioSensorInstance; class ImeHost; class ImeInstance; class InputMethodManagerHost; @@ -205,6 +207,10 @@ file_system() { return &file_system_; } + ConnectionHolder<mojom::IioSensorInstance, mojom::IioSensorHost>* + iio_sensor() { + return &iio_sensor_; + } ConnectionHolder<mojom::ImeInstance, mojom::ImeHost>* ime() { return &ime_; } ConnectionHolder<mojom::InputMethodManagerInstance, mojom::InputMethodManagerHost>* @@ -335,6 +341,7 @@ enterprise_reporting_; ConnectionHolder<mojom::FileSystemInstance, mojom::FileSystemHost> file_system_; + ConnectionHolder<mojom::IioSensorInstance, mojom::IioSensorHost> iio_sensor_; ConnectionHolder<mojom::ImeInstance, mojom::ImeHost> ime_; ConnectionHolder<mojom::InputMethodManagerInstance, mojom::InputMethodManagerHost>
diff --git a/components/arc/test/fake_arc_bridge_host.cc b/components/arc/test/fake_arc_bridge_host.cc index 2eaf96f6..7021929 100644 --- a/components/arc/test/fake_arc_bridge_host.cc +++ b/components/arc/test/fake_arc_bridge_host.cc
@@ -127,6 +127,9 @@ void FakeArcBridgeHost::OnFileSystemInstanceReady( mojo::PendingRemote<mojom::FileSystemInstance> file_system_remote) {} +void FakeArcBridgeHost::OnIioSensorInstanceReady( + mojo::PendingRemote<mojom::IioSensorInstance> iio_sensor_remote) {} + void FakeArcBridgeHost::OnImeInstanceReady( mojo::PendingRemote<mojom::ImeInstance> ime_remote) {}
diff --git a/components/arc/test/fake_arc_bridge_host.h b/components/arc/test/fake_arc_bridge_host.h index 0a0ad41..0f49853 100644 --- a/components/arc/test/fake_arc_bridge_host.h +++ b/components/arc/test/fake_arc_bridge_host.h
@@ -64,6 +64,8 @@ enterprise_reporting_remote) override; void OnFileSystemInstanceReady(mojo::PendingRemote<mojom::FileSystemInstance> file_system_remote) override; + void OnIioSensorInstanceReady( + mojo::PendingRemote<mojom::IioSensorInstance> iio_sensor_remote) override; void OnImeInstanceReady( mojo::PendingRemote<mojom::ImeInstance> ime_remote) override; void OnInputMethodManagerInstanceReady(
diff --git a/components/chrome_cleaner/public/proto/chrome_prompt.proto b/components/chrome_cleaner/public/proto/chrome_prompt.proto index de5500d2..755649a 100644 --- a/components/chrome_cleaner/public/proto/chrome_prompt.proto +++ b/components/chrome_cleaner/public/proto/chrome_prompt.proto
@@ -38,6 +38,7 @@ // List of IDs of extensions that will be removed by the Chrome Cleanup tool. // These are 32-character extension ID's. + // TODO(crbug.com/981388): Deprecate and remove this field. repeated string extension_ids = 3; // After deserializing, Chrome must check if @@ -66,12 +67,14 @@ } // Tells Chrome to remove the given extensions. +// TODO(crbug.com/981388): Deprecate and remove this request. message RemoveExtensionsRequest { repeated string extension_ids = 1; } // Tells the Chrome Cleanup tool whether Chrome successfully removed all // extensions. +// TODO(crbug.com/981388): Deprecate and remove this response. message RemoveExtensionsResponse { // Missing |success| will cause Chrome Cleanup to exit with an error. optional bool success = 1;
diff --git a/components/constrained_window/BUILD.gn b/components/constrained_window/BUILD.gn index b351d85..d8b713ca 100644 --- a/components/constrained_window/BUILD.gn +++ b/components/constrained_window/BUILD.gn
@@ -16,7 +16,6 @@ ] deps = [ - "//components/guest_view/browser", "//components/web_modal", "//content/public/browser", "//ui/display",
diff --git a/components/constrained_window/DEPS b/components/constrained_window/DEPS index b20c3ce..74864f33f 100644 --- a/components/constrained_window/DEPS +++ b/components/constrained_window/DEPS
@@ -1,5 +1,4 @@ include_rules = [ - "+components/guest_view/browser", "+components/web_modal", "+content/public/browser", "+ui/aura",
diff --git a/components/constrained_window/constrained_window_views.cc b/components/constrained_window/constrained_window_views.cc index 43a1fdf..157d813 100644 --- a/components/constrained_window/constrained_window_views.cc +++ b/components/constrained_window/constrained_window_views.cc
@@ -12,7 +12,6 @@ #include "base/no_destructor.h" #include "build/build_config.h" #include "components/constrained_window/constrained_window_views_client.h" -#include "components/guest_view/browser/guest_view_base.h" #include "components/web_modal/web_contents_modal_dialog_host.h" #include "components/web_modal/web_contents_modal_dialog_manager.h" #include "components/web_modal/web_contents_modal_dialog_manager_delegate.h" @@ -165,10 +164,7 @@ content::WebContents* GetTopLevelWebContents( content::WebContents* initiator_web_contents) { - // TODO(mcnee): Investigate why |WebContents::GetResponsibleWebContents| may - // return the wrong contents here. - return guest_view::GuestViewBase::GetTopLevelWebContents( - initiator_web_contents); + return initiator_web_contents->GetResponsibleWebContents(); } views::Widget* ShowWebModalDialogViews(
diff --git a/components/download/internal/common/download_utils.cc b/components/download/internal/common/download_utils.cc index 452f1e1f..2bdaf7d 100644 --- a/components/download/internal/common/download_utils.cc +++ b/components/download/internal/common/download_utils.cc
@@ -284,6 +284,7 @@ request->referrer = params->referrer(); request->referrer_policy = params->referrer_policy(); request->is_main_frame = true; + request->update_first_party_url_on_redirect = true; // Downloads should be treated as navigations from Fetch spec perspective. // See also:
diff --git a/components/exo/client_controlled_shell_surface.cc b/components/exo/client_controlled_shell_surface.cc index ea9b1a9a..b2457f1 100644 --- a/components/exo/client_controlled_shell_surface.cc +++ b/components/exo/client_controlled_shell_surface.cc
@@ -508,13 +508,6 @@ pending_top_inset_height_ = height; } -void ClientControlledShellSurface::SetResizeOutset(int outset) { - TRACE_EVENT1("exo", "ClientControlledShellSurface::SetResizeOutset", "outset", - outset); - // Deprecated. - NOTREACHED(); -} - void ClientControlledShellSurface::OnWindowStateChangeEvent( chromeos::WindowStateType current_state, chromeos::WindowStateType next_state) {
diff --git a/components/exo/client_controlled_shell_surface.h b/components/exo/client_controlled_shell_surface.h index 62f9c4a..ebffd1c 100644 --- a/components/exo/client_controlled_shell_surface.h +++ b/components/exo/client_controlled_shell_surface.h
@@ -168,9 +168,6 @@ // Set top inset for surface. void SetTopInset(int height); - // Set resize outset for surface. - void SetResizeOutset(int outset); - // Sends the request to change the zoom level to the client. void ChangeZoomLevel(ZoomChange change);
diff --git a/components/exo/shell_surface_util.cc b/components/exo/shell_surface_util.cc index e3124ce..93abef8 100644 --- a/components/exo/shell_surface_util.cc +++ b/components/exo/shell_surface_util.cc
@@ -136,10 +136,6 @@ return id; } -bool IsShellMainSurfaceKey(const void* key) { - return kMainSurfaceKey == key; -} - void SetShellMainSurface(ui::PropertyHandler* property_handler, Surface* surface) { property_handler->SetProperty(kMainSurfaceKey, surface);
diff --git a/components/exo/shell_surface_util.h b/components/exo/shell_surface_util.h index d3e9dd6..5dde84c 100644 --- a/components/exo/shell_surface_util.h +++ b/components/exo/shell_surface_util.h
@@ -57,9 +57,6 @@ const base::Optional<int32_t> GetShellClientAccessibilityId( aura::Window* window); -// Returns true if the given key is the shell main surface key -bool IsShellMainSurfaceKey(const void* key); - // Sets the main surface to the property handler. void SetShellMainSurface(ui::PropertyHandler* property_handler, Surface* surface);
diff --git a/components/exo/wayland/zcr_remote_shell.cc b/components/exo/wayland/zcr_remote_shell.cc index 7f99c31..db53e07 100644 --- a/components/exo/wayland/zcr_remote_shell.cc +++ b/components/exo/wayland/zcr_remote_shell.cc
@@ -290,14 +290,14 @@ int32_t y, int32_t width, int32_t height) { - NOTIMPLEMENTED(); + NOTREACHED(); } void remote_surface_set_rectangular_shadow_background_opacity_DEPRECATED( wl_client* client, wl_resource* resource, wl_fixed_t opacity) { - NOTIMPLEMENTED(); + NOTREACHED(); } void remote_surface_set_title(wl_client* client, @@ -391,14 +391,14 @@ GetUserDataAs<ClientControlledShellSurface>(resource)->SetAlwaysOnTop(false); } -void remote_surface_ack_configure(wl_client* client, - wl_resource* resource, - uint32_t serial) { - // DEPRECATED +void remote_surface_ack_configure_DEPRECATED(wl_client* client, + wl_resource* resource, + uint32_t serial) { + NOTREACHED(); } -void remote_surface_move(wl_client* client, wl_resource* resource) { - // DEPRECATED +void remote_surface_move_DEPRECATED(wl_client* client, wl_resource* resource) { + NOTREACHED(); } void remote_surface_set_window_type(wl_client* client, @@ -425,15 +425,17 @@ } } -void remote_surface_resize(wl_client* client, wl_resource* resource) { +void remote_surface_resize_DEPRECATED(wl_client* client, + wl_resource* resource) { // DEPRECATED + NOTREACHED(); } -void remote_surface_set_resize_outset(wl_client* client, - wl_resource* resource, - int32_t outset) { - GetUserDataAs<ClientControlledShellSurface>(resource)->SetResizeOutset( - outset); +void remote_surface_set_resize_outset_DEPRECATED(wl_client* client, + wl_resource* resource, + int32_t outset) { + // DEPRECATED + NOTREACHED(); } void remote_surface_start_move(wl_client* client, @@ -661,12 +663,12 @@ remote_surface_set_systemui_visibility, remote_surface_set_always_on_top, remote_surface_unset_always_on_top, - remote_surface_ack_configure, - remote_surface_move, + remote_surface_ack_configure_DEPRECATED, + remote_surface_move_DEPRECATED, remote_surface_set_orientation, remote_surface_set_window_type, - remote_surface_resize, - remote_surface_set_resize_outset, + remote_surface_resize_DEPRECATED, + remote_surface_set_resize_outset_DEPRECATED, remote_surface_start_move, remote_surface_set_can_maximize, remote_surface_unset_can_maximize,
diff --git a/components/external_intents/android/java/src/org/chromium/components/external_intents/ExternalNavigationHandler.java b/components/external_intents/android/java/src/org/chromium/components/external_intents/ExternalNavigationHandler.java index f4f38ad..1abcabc3 100644 --- a/components/external_intents/android/java/src/org/chromium/components/external_intents/ExternalNavigationHandler.java +++ b/components/external_intents/android/java/src/org/chromium/components/external_intents/ExternalNavigationHandler.java
@@ -62,7 +62,6 @@ import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; -import java.net.URISyntaxException; import java.util.ArrayList; import java.util.HashSet; import java.util.Iterator; @@ -221,7 +220,7 @@ int NUM_ENTRIES = 3; } - + /** * Packages information about the result of a check of whether we should override URL loading. */ @@ -1450,7 +1449,7 @@ Intent intent; try { intent = Intent.parseUri(url, Intent.URI_INTENT_SCHEME); - } catch (URISyntaxException ex) { + } catch (Exception ex) { // Ignore the error. Log.w(TAG, "Bad URI %s", url, ex); return false;
diff --git a/components/external_intents/android/javatests/src/org/chromium/components/external_intents/ExternalNavigationHandlerTest.java b/components/external_intents/android/javatests/src/org/chromium/components/external_intents/ExternalNavigationHandlerTest.java index 97e2ce2..b56186e 100644 --- a/components/external_intents/android/javatests/src/org/chromium/components/external_intents/ExternalNavigationHandlerTest.java +++ b/components/external_intents/android/javatests/src/org/chromium/components/external_intents/ExternalNavigationHandlerTest.java
@@ -1934,6 +1934,24 @@ .size()); } + @Test + @SmallTest + public void testExceptions() { + // Test that we don't crash under various bad intent URIs. + String numberFormatException = "intent://foo#Intent;scheme=https;i.FOO=0.1;end"; + String uriSyntaxException = "intent://foo#Intent;scheme=https;invalid=asdf;end"; + String indexOutOfBoundsException = "intent://foo#Intent;scheme=https;c.%;end"; + + checkUrl(numberFormatException).expecting(OverrideUrlLoadingResultType.NO_OVERRIDE, IGNORE); + checkUrl(uriSyntaxException).expecting(OverrideUrlLoadingResultType.NO_OVERRIDE, IGNORE); + checkUrl(indexOutOfBoundsException) + .expecting(OverrideUrlLoadingResultType.NO_OVERRIDE, IGNORE); + + Assert.assertFalse(mUrlHandler.canExternalAppHandleUrl(numberFormatException)); + Assert.assertFalse(mUrlHandler.canExternalAppHandleUrl(uriSyntaxException)); + Assert.assertFalse(mUrlHandler.canExternalAppHandleUrl(indexOutOfBoundsException)); + } + private static List<ResolveInfo> makeResolveInfos(ResolveInfo... infos) { return Arrays.asList(infos); }
diff --git a/components/optimization_guide/content/optimization_guide_decider.h b/components/optimization_guide/content/optimization_guide_decider.h index 58c99a6..8159f3f 100644 --- a/components/optimization_guide/content/optimization_guide_decider.h +++ b/components/optimization_guide/content/optimization_guide_decider.h
@@ -75,6 +75,7 @@ // Machine Learning Service for inference. virtual void AddObserverForOptimizationTargetModel( proto::OptimizationTarget optimization_target, + const base::Optional<proto::Any>& model_metadata, OptimizationTargetModelObserver* observer) = 0; // Removes an observer for updates to the model for |optimization_target|.
diff --git a/components/optimization_guide/content/test_optimization_guide_decider.cc b/components/optimization_guide/content/test_optimization_guide_decider.cc index e821c8c..6afedb0f 100644 --- a/components/optimization_guide/content/test_optimization_guide_decider.cc +++ b/components/optimization_guide/content/test_optimization_guide_decider.cc
@@ -36,6 +36,7 @@ void TestOptimizationGuideDecider::AddObserverForOptimizationTargetModel( optimization_guide::proto::OptimizationTarget optimization_target, + const base::Optional<proto::Any>& model_metadata, optimization_guide::OptimizationTargetModelObserver* observer) {} void TestOptimizationGuideDecider::RemoveObserverForOptimizationTargetModel(
diff --git a/components/optimization_guide/content/test_optimization_guide_decider.h b/components/optimization_guide/content/test_optimization_guide_decider.h index 7a904a6..6f452e0 100644 --- a/components/optimization_guide/content/test_optimization_guide_decider.h +++ b/components/optimization_guide/content/test_optimization_guide_decider.h
@@ -31,6 +31,7 @@ OptimizationGuideTargetDecisionCallback callback) override; void AddObserverForOptimizationTargetModel( proto::OptimizationTarget optimization_target, + const base::Optional<proto::Any>& model_metadata, OptimizationTargetModelObserver* observer) override; void RemoveObserverForOptimizationTargetModel( proto::OptimizationTarget optimization_target,
diff --git a/components/optimization_guide/core/optimization_target_model_observer.h b/components/optimization_guide/core/optimization_target_model_observer.h index 4858971a..cb8b90f4 100644 --- a/components/optimization_guide/core/optimization_target_model_observer.h +++ b/components/optimization_guide/core/optimization_target_model_observer.h
@@ -7,6 +7,7 @@ #include "base/files/file_path.h" #include "base/observer_list_types.h" +#include "base/optional.h" #include "components/optimization_guide/proto/models.pb.h" namespace optimization_guide { @@ -17,12 +18,15 @@ public: // Invoked when a model for |optimization_target| has been updated. It is // guaranteed that this method will only be invoked for targets that |this| - // is added as an observer for. + // is added as an observer for. |model_metadata| will contain metadata that + // the server has attached to this model, if applicable. // // When this observer is first added, it will call this function with the // file path it already has on device, if applicable. - virtual void OnModelFileUpdated(proto::OptimizationTarget optimization_target, - const base::FilePath& file_path) = 0; + virtual void OnModelFileUpdated( + proto::OptimizationTarget optimization_target, + const base::Optional<proto::Any>& model_metadata, + const base::FilePath& file_path) = 0; }; } // namespace optimization_guide
diff --git a/components/optimization_guide/core/prediction_model_file.cc b/components/optimization_guide/core/prediction_model_file.cc index f21ec85..c2ebdb2 100644 --- a/components/optimization_guide/core/prediction_model_file.cc +++ b/components/optimization_guide/core/prediction_model_file.cc
@@ -6,13 +6,16 @@ #include "base/memory/ptr_util.h" #include "components/optimization_guide/core/optimization_guide_util.h" -#include "components/optimization_guide/proto/models.pb.h" namespace optimization_guide { -PredictionModelFile::PredictionModelFile(const base::FilePath& model_file_path, - const int64_t version) - : model_file_path_(model_file_path), version_(version) {} +PredictionModelFile::PredictionModelFile( + const base::FilePath& model_file_path, + const int64_t version, + const base::Optional<proto::Any>& model_metadata) + : model_file_path_(model_file_path), + version_(version), + model_metadata_(model_metadata) {} PredictionModelFile::~PredictionModelFile() = default; @@ -26,9 +29,13 @@ if (!model.model_info().has_version()) return nullptr; + base::Optional<proto::Any> model_metadata; + if (model.model_info().has_model_metadata()) + model_metadata = model.model_info().model_metadata(); + // Private ctor, so we can't use std::make_unique. - return base::WrapUnique( - new PredictionModelFile(*model_file_path, model.model_info().version())); + return base::WrapUnique(new PredictionModelFile( + *model_file_path, model.model_info().version(), model_metadata)); } base::FilePath PredictionModelFile::GetModelFilePath() const { @@ -39,4 +46,8 @@ return version_; } +base::Optional<proto::Any> PredictionModelFile::GetModelMetadata() const { + return model_metadata_; +} + } // namespace optimization_guide
diff --git a/components/optimization_guide/core/prediction_model_file.h b/components/optimization_guide/core/prediction_model_file.h index d0489d4..4dbd35ca 100644 --- a/components/optimization_guide/core/prediction_model_file.h +++ b/components/optimization_guide/core/prediction_model_file.h
@@ -8,13 +8,11 @@ #include <memory> #include "base/files/file_path.h" +#include "base/optional.h" +#include "components/optimization_guide/proto/models.pb.h" namespace optimization_guide { -namespace proto { -class PredictionModel; -} // namespace proto - // Encapsulates information about a file containing a prediction model. class PredictionModelFile { public: @@ -31,11 +29,17 @@ // Returns the file path where the model file is stored. base::FilePath GetModelFilePath() const; + // Returns the metadata that the server provided specific to this model, if + // applicable. + base::Optional<proto::Any> GetModelMetadata() const; + private: PredictionModelFile(const base::FilePath& model_file_path, - const int64_t version); + const int64_t version, + const base::Optional<proto::Any>& model_metadata); base::FilePath model_file_path_; int64_t version_; + base::Optional<proto::Any> model_metadata_; }; } // namespace optimization_guide
diff --git a/components/policy/core/browser/BUILD.gn b/components/policy/core/browser/BUILD.gn index f33b4c6..8d5486fb 100644 --- a/components/policy/core/browser/BUILD.gn +++ b/components/policy/core/browser/BUILD.gn
@@ -54,6 +54,7 @@ "//components/keyed_service/core", "//components/pref_registry", "//components/prefs", + "//components/reporting/proto:record_proto", "//components/strings", "//components/url_formatter", "//components/url_matcher",
diff --git a/components/policy/core/browser/DEPS b/components/policy/core/browser/DEPS index f0c8590..ee4f23e 100644 --- a/components/policy/core/browser/DEPS +++ b/components/policy/core/browser/DEPS
@@ -2,6 +2,7 @@ "+components/google/core", "+components/pref_registry", "+components/proxy_config", + "+components/reporting", "+components/strings/grit/components_strings.h", "+components/url_formatter", "+components/url_matcher",
diff --git a/components/policy/core/browser/url_blocklist_manager.h b/components/policy/core/browser/url_blocklist_manager.h index eb7b9577..d1713d7c 100644 --- a/components/policy/core/browser/url_blocklist_manager.h +++ b/components/policy/core/browser/url_blocklist_manager.h
@@ -53,7 +53,7 @@ // URLs matching one of the |filters| will be blocked. The filter format is // documented at - // http://www.chromium.org/administrators/url-blacklist-filter-format. + // http://www.chromium.org/administrators/url-blocklist-filter-format. void Block(const base::ListValue* filters); // URLs matching one of the |filters| will be allowed. If a URL is both
diff --git a/components/policy/core/browser/url_util_unittest.cc b/components/policy/core/browser/url_util_unittest.cc index 79d7155..1ce8a330 100644 --- a/components/policy/core/browser/url_util_unittest.cc +++ b/components/policy/core/browser/url_util_unittest.cc
@@ -458,7 +458,7 @@ TEST(URLUtilTest, BasicCoverage) { // Tests to cover the documentation from - // http://www.chromium.org/administrators/url-blacklist-filter-format + // http://www.chromium.org/administrators/url-blocklist-filter-format // [scheme://][.]host[:port][/path][@query] // Scheme can be http, https, ftp, chrome, etc. This field is optional, and
diff --git a/components/policy/core/common/BUILD.gn b/components/policy/core/common/BUILD.gn index e262fb3d..d397b6d 100644 --- a/components/policy/core/common/BUILD.gn +++ b/components/policy/core/common/BUILD.gn
@@ -164,8 +164,8 @@ ":common_constants", "//components/policy:generated", "//components/policy/proto", - "//components/policy/proto:policy_record_constants", - "//components/policy/proto:reporting_record_proto", + "//components/reporting/proto:record_constants", + "//components/reporting/proto:record_proto", ] deps = [ @@ -377,8 +377,8 @@ "//components/account_id", "//components/policy:generated", "//components/policy/proto", - "//components/policy/proto:policy_record_constants", - "//components/policy/proto:reporting_record_proto", + "//components/reporting/proto:record_constants", + "//components/reporting/proto:record_proto", "//components/strings", "//crypto", "//net",
diff --git a/components/policy/core/common/DEPS b/components/policy/core/common/DEPS index ef4d3b8c..f20c930a 100644 --- a/components/policy/core/common/DEPS +++ b/components/policy/core/common/DEPS
@@ -4,6 +4,7 @@ "+chromeos/startup", "+chromeos/system", "+components/account_id", + "+components/reporting", "-components/policy/core/browser", "+components/strings", "+extensions/buildflags",
diff --git a/components/policy/core/common/cloud/encrypted_reporting_job_configuration.cc b/components/policy/core/common/cloud/encrypted_reporting_job_configuration.cc index 69062241..2a4e9e8 100644 --- a/components/policy/core/common/cloud/encrypted_reporting_job_configuration.cc +++ b/components/policy/core/common/cloud/encrypted_reporting_job_configuration.cc
@@ -8,7 +8,7 @@ #include "base/strings/string_number_conversions.h" #include "base/strings/string_util.h" #include "components/policy/core/common/cloud/cloud_policy_client.h" -#include "components/policy/proto/record_constants.pb.h" +#include "components/reporting/proto/record_constants.pb.h" #include "services/network/public/cpp/shared_url_loader_factory.h" namespace policy {
diff --git a/components/policy/core/common/cloud/encrypted_reporting_job_configuration.h b/components/policy/core/common/cloud/encrypted_reporting_job_configuration.h index c9472ca..daeab3b 100644 --- a/components/policy/core/common/cloud/encrypted_reporting_job_configuration.h +++ b/components/policy/core/common/cloud/encrypted_reporting_job_configuration.h
@@ -16,7 +16,7 @@ #include "components/policy/core/common/cloud/device_management_service.h" #include "components/policy/core/common/cloud/reporting_job_configuration_base.h" #include "components/policy/policy_export.h" -#include "components/policy/proto/record_constants.pb.h" +#include "components/reporting/proto/record_constants.pb.h" namespace policy {
diff --git a/components/policy/core/common/cloud/encrypted_reporting_job_configuration_unittest.cc b/components/policy/core/common/cloud/encrypted_reporting_job_configuration_unittest.cc index 8a3bbb34..a1a049d 100644 --- a/components/policy/core/common/cloud/encrypted_reporting_job_configuration_unittest.cc +++ b/components/policy/core/common/cloud/encrypted_reporting_job_configuration_unittest.cc
@@ -16,7 +16,7 @@ #include "components/policy/core/common/cloud/dm_auth.h" #include "components/policy/core/common/cloud/mock_cloud_policy_client.h" #include "components/policy/core/common/cloud/mock_device_management_service.h" -#include "components/policy/proto/record_constants.pb.h" +#include "components/reporting/proto/record_constants.pb.h" #include "components/version_info/version_info.h" #include "testing/gmock/include/gmock/gmock.h" #include "testing/gtest/include/gtest/gtest.h"
diff --git a/components/policy/core/common/cloud/mock_cloud_policy_client.h b/components/policy/core/common/cloud/mock_cloud_policy_client.h index 1c62296..dfc60e3 100644 --- a/components/policy/core/common/cloud/mock_cloud_policy_client.h +++ b/components/policy/core/common/cloud/mock_cloud_policy_client.h
@@ -13,7 +13,7 @@ #include "base/threading/thread_task_runner_handle.h" #include "components/policy/core/common/cloud/cloud_policy_client.h" #include "components/policy/core/common/cloud/device_management_service.h" -#include "components/policy/proto/record.pb.h" +#include "components/reporting/proto/record.pb.h" #include "testing/gmock/include/gmock/gmock.h" namespace network {
diff --git a/components/policy/proto/BUILD.gn b/components/policy/proto/BUILD.gn index 72600eb..4981800 100644 --- a/components/policy/proto/BUILD.gn +++ b/components/policy/proto/BUILD.gn
@@ -14,33 +14,6 @@ public_deps = [ ":proto_internal" ] } -# Record constants for use with the reporting messaging library. -proto_library("policy_record_constants") { - visibility = [ - ":reporting_record_proto", - ":reporting_record_proto_gen", - "//chrome/browser:browser", - "//components/policy/*", - ] - sources = [ "record_constants.proto" ] - - proto_out_dir = "components/policy/proto" -} - -# Record definitions for reporting. -proto_library("reporting_record_proto") { - visibility = [ - "//chrome/browser:browser", - "//chrome/browser:test_support", - "//components/policy/*", - ] - sources = [ "record.proto" ] - - deps = [ ":policy_record_constants" ] - - proto_out_dir = "components/policy/proto" -} - proto_library("policy_common_definitions_compile_proto") { visibility = [ ":proto_internal",
diff --git a/components/policy/proto/OWNERS b/components/policy/proto/OWNERS deleted file mode 100644 index 35e4b15..0000000 --- a/components/policy/proto/OWNERS +++ /dev/null
@@ -1,2 +0,0 @@ -per-file record*=zatrudo@google.com -per-file record*=lbaraz@chromium.org
diff --git a/components/policy/resources/policy_templates.json b/components/policy/resources/policy_templates.json index d81143a..3edc82d 100644 --- a/components/policy/resources/policy_templates.json +++ b/components/policy/resources/policy_templates.json
@@ -3959,7 +3959,7 @@ If this policy isn't set, all downloads where the file type is in <ph name="AUTO_OPEN_FILE_TYPES_POLICY_NAME">AutoOpenFileTypes</ph> will automatically open. - A URL pattern has to be formatted according to https://www.chromium.org/administrators/url-blacklist-filter-format.''', + A URL pattern has to be formatted according to https://www.chromium.org/administrators/url-blocklist-filter-format.''', }, { 'name': 'AutoLaunchProtocolsFromOrigins', @@ -3996,7 +3996,7 @@ If this policy is not set, no protocols can launch without a prompt by default. Users may opt out of prompts on a per-protocol/per-site basis unless the <ph name="EXTERNAL_PROTOCOL_DIALOG_SHOW_ALWAYS_OPEN_CHECKBOX_POLICY_NAME">ExternalProtocolDialogShowAlwaysOpenCheckbox</ph> policy is set to Disabled. This policy has no impact on per-protocol/per-site prompt exemptions set by users. - The origin matching patterns use a similar format to those for the '<ph name="URL_BLOCKLIST_POLICY_NAME">URLBlocklist</ph>' policy, which are documented at http://www.chromium.org/administrators/url-blacklist-filter-format. + The origin matching patterns use a similar format to those for the '<ph name="URL_BLOCKLIST_POLICY_NAME">URLBlocklist</ph>' policy, which are documented at http://www.chromium.org/administrators/url-blocklist-filter-format. However, origin matching patterns for this policy cannot contain "/path" or "@query" elements. Any pattern that does contain a "/path" or "@query" element will be ignored.''', }, @@ -8232,7 +8232,7 @@ 'tags': ['filtering'], 'desc': '''This policy is deprecated, please use the '<ph name="URL_BLOCKLIST_POLICY_NAME">URLBlocklist</ph>' policy instead. - Setting the policy prevents webpages with prohibited URLs from loading. It provides a list of URL patterns that specify forbidden URLs. Leaving the policy unset means no URLs are prohibited in the browser. Format the URL pattern according to this format ( https://www.chromium.org/administrators/url-blacklist-filter-format ). Up to 1,000 exceptions can be defined in <ph name="URL_ALLOWLIST_POLICY_NAME">URLAllowlist</ph>. + Setting the policy prevents webpages with prohibited URLs from loading. It provides a list of URL patterns that specify forbidden URLs. Leaving the policy unset means no URLs are prohibited in the browser. Format the URL pattern according to this format ( https://www.chromium.org/administrators/url-blocklist-filter-format ). Up to 1,000 exceptions can be defined in <ph name="URL_ALLOWLIST_POLICY_NAME">URLAllowlist</ph>. From <ph name="PRODUCT_NAME">$1<ex>Google Chrome</ex></ph> version 73, you can block javascript://* URLs. However, it affects only JavaScript entered in the address bar (or, for example, bookmarklets). In-page JavaScript URLs with dynamically loaded data aren't subject to this policy. For example, if you block example.com/abc, then example.com can still load example.com/abc using XMLHTTPRequest. @@ -8264,7 +8264,7 @@ 'tags': [], 'desc': '''This policy is deprecated, please use the '<ph name="URL_ALLOWLIST_POLICY_NAME">URLAllowlist</ph>' policy instead. - Setting the policy provides access to the listed URLs, as exceptions to the URL blocklist. See that policy's description for the format of entries of this list. For example, setting <ph name="URL_BLOCKLIST_POLICY_NAME">URLBlocklist</ph> to * will block all requests, and you can use this policy to allow access to a limited list of URLs. Use it to open exceptions to certain schemes, subdomains of other domains, ports, or specific paths, using the format specified at ( https://www.chromium.org/administrators/url-blacklist-filter-format ). The most specific filter determines if a URL is blocked or allowed. The allowlist takes precedence over blocklist. This policy is limited to 1,000 entries. + Setting the policy provides access to the listed URLs, as exceptions to the URL blocklist. See that policy's description for the format of entries of this list. For example, setting <ph name="URL_BLOCKLIST_POLICY_NAME">URLBlocklist</ph> to * will block all requests, and you can use this policy to allow access to a limited list of URLs. Use it to open exceptions to certain schemes, subdomains of other domains, ports, or specific paths, using the format specified at ( https://www.chromium.org/administrators/url-blocklist-filter-format ). The most specific filter determines if a URL is blocked or allowed. The allowlist takes precedence over blocklist. This policy is limited to 1,000 entries. This policy also allows enabling the automatic invocation by the browser of external application registered as protocol handlers for the listed protocols like "tel:" or "ssh:". @@ -8296,7 +8296,7 @@ 'id': 736, 'caption': '''Block access to a list of URLs''', 'tags': ['filtering'], - 'desc': '''Setting the policy prevents webpages with prohibited URLs from loading. It provides a list of URL patterns that specify forbidden URLs. Leaving the policy unset means no URLs are prohibited in the browser. Format the URL pattern according to this format ( https://www.chromium.org/administrators/url-blacklist-filter-format ). Up to 1,000 exceptions can be defined in <ph name="URL_ALLOWLIST_POLICY_NAME">URLAllowlist</ph>. + 'desc': '''Setting the policy prevents webpages with prohibited URLs from loading. It provides a list of URL patterns that specify forbidden URLs. Leaving the policy unset means no URLs are prohibited in the browser. Format the URL pattern according to this format ( https://www.chromium.org/administrators/url-blocklist-filter-format ). Up to 1,000 exceptions can be defined in <ph name="URL_ALLOWLIST_POLICY_NAME">URLAllowlist</ph>. From <ph name="PRODUCT_NAME">$1<ex>Google Chrome</ex></ph> version 73, you can block javascript://* URLs. However, it affects only JavaScript entered in the address bar (or, for example, bookmarklets). In-page JavaScript URLs with dynamically loaded data aren't subject to this policy. For example, if you block example.com/abc, then example.com can still load example.com/abc using XMLHTTPRequest. @@ -8326,7 +8326,7 @@ 'id': 737, 'caption': '''Allow access to a list of URLs''', 'tags': [], - 'desc': '''Setting the policy provides access to the listed URLs, as exceptions to <ph name="URL_BLOCKLIST_POLICY_NAME">URLBlocklist</ph>. See that policy's description for the format of entries of this list. For example, setting <ph name="URL_BLOCKLIST_POLICY_NAME">URLBlocklist</ph> to * will block all requests, and you can use this policy to allow access to a limited list of URLs. Use it to open exceptions to certain schemes, subdomains of other domains, ports, or specific paths, using the format specified at ( https://www.chromium.org/administrators/url-blacklist-filter-format ). The most specific filter determines if a URL is blocked or allowed. The <ph name="URL_ALLOWLIST_POLICY_NAME">URLAllowlist</ph> policy takes precedence over <ph name="URL_BLOCKLIST_POLICY_NAME">URLBlocklist</ph>. This policy is limited to 1,000 entries. + 'desc': '''Setting the policy provides access to the listed URLs, as exceptions to <ph name="URL_BLOCKLIST_POLICY_NAME">URLBlocklist</ph>. See that policy's description for the format of entries of this list. For example, setting <ph name="URL_BLOCKLIST_POLICY_NAME">URLBlocklist</ph> to * will block all requests, and you can use this policy to allow access to a limited list of URLs. Use it to open exceptions to certain schemes, subdomains of other domains, ports, or specific paths, using the format specified at ( https://www.chromium.org/administrators/url-blocklist-filter-format ). The most specific filter determines if a URL is blocked or allowed. The <ph name="URL_ALLOWLIST_POLICY_NAME">URLAllowlist</ph> policy takes precedence over <ph name="URL_BLOCKLIST_POLICY_NAME">URLBlocklist</ph>. This policy is limited to 1,000 entries. This policy also allows enabling the automatic invocation by the browser of external application registered as protocol handlers for the listed protocols like "tel:" or "ssh:". @@ -14250,7 +14250,7 @@ Leaving the policy unset means that if certificates requiring disclosure through Certificate Transparency aren't disclosed, then <ph name="PRODUCT_NAME">$1<ex>Google Chrome</ex></ph> doesn't trust those certificates. - A URL pattern follows this format ( https://www.chromium.org/administrators/url-blacklist-filter-format ). However, because the validity of certificates for a given hostname is independent of the scheme, port, or path, <ph name="PRODUCT_NAME">$1<ex>Google Chrome</ex></ph> only considers the hostname portion of the URL. Wildcard hosts aren't supported.''', + A URL pattern follows this format ( https://www.chromium.org/administrators/url-blocklist-filter-format ). However, because the validity of certificates for a given hostname is independent of the scheme, port, or path, <ph name="PRODUCT_NAME">$1<ex>Google Chrome</ex></ph> only considers the hostname portion of the URL. Wildcard hosts aren't supported.''', }, { 'name': 'CertificateTransparencyEnforcementDisabledForCas', @@ -24026,7 +24026,7 @@ Notes: - PRIVACY_SCREEN restriction doesn't block the ability to turn on privacy screen, but enforces it when the restriction class is set to BLOCK. - Destinations cannot be empty in case one of the restrictions is CLIPBOARD, but they don't make any difference for the remaining restrictions. - - Format the URL patterns according to this format ( https://www.chromium.org/administrators/url-blacklist-filter-format ). + - Format the URL patterns according to this format ( https://www.chromium.org/administrators/url-blocklist-filter-format ). If the policy is left not set, no restrictions will be applied.''', },
diff --git a/components/reporting/OWNERS b/components/reporting/OWNERS new file mode 100644 index 0000000..9160064 --- /dev/null +++ b/components/reporting/OWNERS
@@ -0,0 +1,3 @@ +lbaraz@chromium.com +zatrudo@google.com +
diff --git a/components/reporting/README.md b/components/reporting/README.md new file mode 100644 index 0000000..8c8e9dd7 --- /dev/null +++ b/components/reporting/README.md
@@ -0,0 +1,16 @@ +The Encrypted Reporting Pipeline (ERP) provides a universal method for upload of +data for enterprise customers. + +The code structure looks like this: +Chrome: + - //components/reporting + Code shared between Chrome and Chrome OS. + - //chrome/browser/policy/messaging_layer + Code that lives only in the browser, primary interfaces for reporting data + such as ReportQueue and ReportQueueConfiguration. +Chrome OS: + - //platform2/missived + Daemon for encryption and storage of reports. + +If you'd like to begin using ERP within Chrome please check the comment in +[//chrome/browser/policy/messaging_layer/public/report_client.h](https:://chromium.googlesource.com/chromium/src/+/master/chrome/browser/policy/messaging_layer/public/report_client.h#25).
diff --git a/components/reporting/encryption/BUILD.gn b/components/reporting/encryption/BUILD.gn new file mode 100644 index 0000000..c1b13212 --- /dev/null +++ b/components/reporting/encryption/BUILD.gn
@@ -0,0 +1,108 @@ +# Copyright 2021 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("//build/config/features.gni") + +static_library("encryption_module") { + sources = [ + "encryption_module.cc", + "encryption_module.h", + ] + deps = [ + ":encryption", + "//base", + "//components/reporting/proto:record_proto", + "//components/reporting/util:status", + ] +} + +static_library("encryption") { + sources = [ + "encryption.cc", + "encryption.h", + ] + deps = [ + "//base", + "//components/reporting/proto:record_proto", + "//components/reporting/util:status", + "//crypto", + "//crypto:platform", + "//third_party/boringssl", + ] +} + +static_library("decryption") { + sources = [ + "decryption.cc", + "decryption.h", + ] + deps = [ + ":encryption", + "//base", + "//components/reporting/proto:record_proto", + "//components/reporting/util:status", + "//crypto", + "//crypto:platform", + "//third_party/boringssl", + ] +} + +static_library("verification") { + sources = [ + "verification.cc", + "verification.h", + ] + deps = [ + "//base", + "//components/reporting/util:status", + "//third_party/boringssl", + ] +} + +static_library("test_support") { + testonly = true + sources = [ + "test_encryption_module.cc", + "test_encryption_module.h", + ] + deps = [ + ":decryption", + ":encryption", + ":encryption_module", + ":verification", + "//base", + "//base/test:test_support", + "//components/reporting/proto:record_proto", + "//components/reporting/util:status", + "//components/reporting/util:status_macros", + "//testing/gmock", + "//testing/gtest", + "//third_party/boringssl:boringssl", + ] +} + +# All unit tests are built as part of the //components:components_unittests +# target and must be one targets named "unit_tests". +source_set("unit_tests") { + testonly = true + sources = [ + "encryption_module_unittest.cc", + "verification_unittest.cc", + ] + deps = [ + ":decryption", + ":encryption", + ":encryption_module", + ":test_support", + ":verification", + "//base", + "//base/test:test_support", + "//components/reporting/proto:record_proto", + "//components/reporting/util:status", + "//components/reporting/util:status_macros", + "//testing/gmock", + "//testing/gtest", + "//third_party/boringssl:boringssl", + ] +}
diff --git a/components/reporting/encryption/DEPS b/components/reporting/encryption/DEPS new file mode 100644 index 0000000..f4cb4c0 --- /dev/null +++ b/components/reporting/encryption/DEPS
@@ -0,0 +1,5 @@ +include_rules = [ + "+base", + "+crypto", + "+third_party/boringssl/src/include", +]
diff --git a/chrome/browser/policy/messaging_layer/encryption/decryption.cc b/components/reporting/encryption/decryption.cc similarity index 96% rename from chrome/browser/policy/messaging_layer/encryption/decryption.cc rename to components/reporting/encryption/decryption.cc index d0300166..9efa787 100644 --- a/chrome/browser/policy/messaging_layer/encryption/decryption.cc +++ b/components/reporting/encryption/decryption.cc
@@ -2,6 +2,8 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. +#include "components/reporting/encryption/decryption.h" + #include <limits> #include <string> @@ -14,10 +16,9 @@ #include "base/strings/string_piece.h" #include "base/task/post_task.h" #include "base/task_runner.h" -#include "chrome/browser/policy/messaging_layer/encryption/decryption.h" -#include "chrome/browser/policy/messaging_layer/encryption/encryption.h" -#include "chrome/browser/policy/messaging_layer/util/status.h" -#include "chrome/browser/policy/messaging_layer/util/statusor.h" +#include "components/reporting/encryption/encryption.h" +#include "components/reporting/util/status.h" +#include "components/reporting/util/statusor.h" #include "crypto/aead.h" #include "crypto/openssl_util.h" #include "third_party/boringssl/src/include/openssl/curve25519.h"
diff --git a/chrome/browser/policy/messaging_layer/encryption/decryption.h b/components/reporting/encryption/decryption.h similarity index 90% rename from chrome/browser/policy/messaging_layer/encryption/decryption.h rename to components/reporting/encryption/decryption.h index 97ec7f5..97c91c06 100644 --- a/chrome/browser/policy/messaging_layer/encryption/decryption.h +++ b/components/reporting/encryption/decryption.h
@@ -2,8 +2,8 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#ifndef CHROME_BROWSER_POLICY_MESSAGING_LAYER_ENCRYPTION_DECRYPTION_H_ -#define CHROME_BROWSER_POLICY_MESSAGING_LAYER_ENCRYPTION_DECRYPTION_H_ +#ifndef COMPONENTS_REPORTING_ENCRYPTION_DECRYPTION_H_ +#define COMPONENTS_REPORTING_ENCRYPTION_DECRYPTION_H_ #include <string> @@ -15,9 +15,9 @@ #include "base/strings/string_piece.h" #include "base/threading/thread.h" #include "base/threading/thread_task_runner_handle.h" -#include "chrome/browser/policy/messaging_layer/encryption/encryption.h" -#include "chrome/browser/policy/messaging_layer/util/status.h" -#include "chrome/browser/policy/messaging_layer/util/statusor.h" +#include "components/reporting/encryption/encryption.h" +#include "components/reporting/util/status.h" +#include "components/reporting/util/statusor.h" namespace reporting { @@ -115,4 +115,4 @@ } // namespace reporting -#endif // CHROME_BROWSER_POLICY_MESSAGING_LAYER_ENCRYPTION_DECRYPTION_H_ +#endif // COMPONENTS_REPORTING_ENCRYPTION_DECRYPTION_H_
diff --git a/chrome/browser/policy/messaging_layer/encryption/encryption.cc b/components/reporting/encryption/encryption.cc similarity index 97% rename from chrome/browser/policy/messaging_layer/encryption/encryption.cc rename to components/reporting/encryption/encryption.cc index 1e505cb5..e880dcc5 100644 --- a/chrome/browser/policy/messaging_layer/encryption/encryption.cc +++ b/components/reporting/encryption/encryption.cc
@@ -2,7 +2,7 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#include "chrome/browser/policy/messaging_layer/encryption/encryption.h" +#include "components/reporting/encryption/encryption.h" #include <string> #include <utility> @@ -16,8 +16,8 @@ #include "base/strings/string_number_conversions.h" #include "base/task/post_task.h" #include "base/task_runner.h" -#include "chrome/browser/policy/messaging_layer/util/status.h" -#include "chrome/browser/policy/messaging_layer/util/statusor.h" +#include "components/reporting/util/status.h" +#include "components/reporting/util/statusor.h" #include "crypto/aead.h" #include "crypto/openssl_util.h" #include "third_party/boringssl/src/include/openssl/curve25519.h"
diff --git a/chrome/browser/policy/messaging_layer/encryption/encryption.h b/components/reporting/encryption/encryption.h similarity index 91% rename from chrome/browser/policy/messaging_layer/encryption/encryption.h rename to components/reporting/encryption/encryption.h index f673319d..eea82c3 100644 --- a/chrome/browser/policy/messaging_layer/encryption/encryption.h +++ b/components/reporting/encryption/encryption.h
@@ -2,8 +2,8 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#ifndef CHROME_BROWSER_POLICY_MESSAGING_LAYER_ENCRYPTION_ENCRYPTION_H_ -#define CHROME_BROWSER_POLICY_MESSAGING_LAYER_ENCRYPTION_ENCRYPTION_H_ +#ifndef COMPONENTS_REPORTING_ENCRYPTION_ENCRYPTION_H_ +#define COMPONENTS_REPORTING_ENCRYPTION_ENCRYPTION_H_ #include <string> #include <utility> @@ -13,9 +13,9 @@ #include "base/memory/scoped_refptr.h" #include "base/optional.h" #include "base/strings/string_piece.h" -#include "chrome/browser/policy/messaging_layer/util/status.h" -#include "chrome/browser/policy/messaging_layer/util/statusor.h" -#include "components/policy/proto/record.pb.h" +#include "components/reporting/proto/record.pb.h" +#include "components/reporting/util/status.h" +#include "components/reporting/util/statusor.h" namespace reporting { @@ -114,4 +114,4 @@ } // namespace reporting -#endif // CHROME_BROWSER_POLICY_MESSAGING_LAYER_ENCRYPTION_ENCRYPTION_H_ +#endif // COMPONENTS_REPORTING_ENCRYPTION_ENCRYPTION_H_
diff --git a/chrome/browser/policy/messaging_layer/encryption/encryption_module.cc b/components/reporting/encryption/encryption_module.cc similarity index 93% rename from chrome/browser/policy/messaging_layer/encryption/encryption_module.cc rename to components/reporting/encryption/encryption_module.cc index 1dbc1a3..3b7d4ad9 100644 --- a/chrome/browser/policy/messaging_layer/encryption/encryption_module.cc +++ b/components/reporting/encryption/encryption_module.cc
@@ -2,7 +2,7 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#include "chrome/browser/policy/messaging_layer/encryption/encryption_module.h" +#include "components/reporting/encryption/encryption_module.h" #include <atomic> @@ -11,9 +11,9 @@ #include "base/feature_list.h" #include "base/strings/string_piece.h" #include "base/task/thread_pool.h" -#include "chrome/browser/policy/messaging_layer/util/status.h" -#include "chrome/browser/policy/messaging_layer/util/statusor.h" -#include "components/policy/proto/record.pb.h" +#include "components/reporting/proto/record.pb.h" +#include "components/reporting/util/status.h" +#include "components/reporting/util/statusor.h" namespace reporting {
diff --git a/chrome/browser/policy/messaging_layer/encryption/encryption_module.h b/components/reporting/encryption/encryption_module.h similarity index 81% rename from chrome/browser/policy/messaging_layer/encryption/encryption_module.h rename to components/reporting/encryption/encryption_module.h index ba1b3547..3782ad0 100644 --- a/chrome/browser/policy/messaging_layer/encryption/encryption_module.h +++ b/components/reporting/encryption/encryption_module.h
@@ -2,18 +2,18 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#ifndef CHROME_BROWSER_POLICY_MESSAGING_LAYER_ENCRYPTION_ENCRYPTION_MODULE_H_ -#define CHROME_BROWSER_POLICY_MESSAGING_LAYER_ENCRYPTION_ENCRYPTION_MODULE_H_ +#ifndef COMPONENTS_REPORTING_ENCRYPTION_ENCRYPTION_MODULE_H_ +#define COMPONENTS_REPORTING_ENCRYPTION_ENCRYPTION_MODULE_H_ #include <atomic> #include "base/callback.h" #include "base/memory/ref_counted.h" #include "base/strings/string_piece.h" -#include "chrome/browser/policy/messaging_layer/encryption/encryption.h" -#include "chrome/browser/policy/messaging_layer/util/status.h" -#include "chrome/browser/policy/messaging_layer/util/statusor.h" -#include "components/policy/proto/record.pb.h" +#include "components/reporting/encryption/encryption.h" +#include "components/reporting/proto/record.pb.h" +#include "components/reporting/util/status.h" +#include "components/reporting/util/statusor.h" namespace reporting { @@ -68,4 +68,4 @@ } // namespace reporting -#endif // CHROME_BROWSER_POLICY_MESSAGING_LAYER_ENCRYPTION_ENCRYPTION_MODULE_H_ +#endif // COMPONENTS_REPORTING_ENCRYPTION_ENCRYPTION_MODULE_H_
diff --git a/chrome/browser/policy/messaging_layer/encryption/encryption_module_unittest.cc b/components/reporting/encryption/encryption_module_unittest.cc similarity index 94% rename from chrome/browser/policy/messaging_layer/encryption/encryption_module_unittest.cc rename to components/reporting/encryption/encryption_module_unittest.cc index 6b47eaa..b21ce2a 100644 --- a/chrome/browser/policy/messaging_layer/encryption/encryption_module_unittest.cc +++ b/components/reporting/encryption/encryption_module_unittest.cc
@@ -2,7 +2,7 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#include "chrome/browser/policy/messaging_layer/encryption/encryption_module.h" +#include "components/reporting/encryption/encryption_module.h" #include "base/bind.h" #include "base/containers/flat_map.h" @@ -13,12 +13,12 @@ #include "base/test/scoped_feature_list.h" #include "base/test/task_environment.h" #include "base/time/time.h" -#include "chrome/browser/policy/messaging_layer/encryption/decryption.h" -#include "chrome/browser/policy/messaging_layer/encryption/encryption.h" -#include "chrome/browser/policy/messaging_layer/util/status.h" -#include "chrome/browser/policy/messaging_layer/util/status_macros.h" -#include "chrome/browser/policy/messaging_layer/util/statusor.h" -#include "components/policy/proto/record.pb.h" +#include "components/reporting/encryption/decryption.h" +#include "components/reporting/encryption/encryption.h" +#include "components/reporting/proto/record.pb.h" +#include "components/reporting/util/status.h" +#include "components/reporting/util/status_macros.h" +#include "components/reporting/util/statusor.h" #include "testing/gmock/include/gmock/gmock.h" #include "testing/gtest/include/gtest/gtest.h" #include "third_party/boringssl/src/include/openssl/curve25519.h" @@ -489,18 +489,18 @@ public_value_strings.size()); for (size_t i = 0; i < public_value_strings.size(); ++i) { base::ThreadPool::PostTask( - FROM_HERE, base::BindOnce( - [](base::StringPiece private_key_string, - base::StringPiece public_key_string, - scoped_refptr<Decryptor> decryptor, - base::OnceCallback<void( - StatusOr<Encryptor::PublicKeyId>)> done_cb) { - decryptor->RecordKeyPair(private_key_string, - public_key_string, - std::move(done_cb)); - }, - private_key_strings[i], public_value_strings[i], - decryptor_, record_results[i].cb())); + FROM_HERE, + base::BindOnce( + [](base::StringPiece private_key_string, + base::StringPiece public_key_string, + scoped_refptr<Decryptor> decryptor, + base::OnceCallback<void(StatusOr<Encryptor::PublicKeyId>)> + done_cb) { + decryptor->RecordKeyPair(private_key_string, public_key_string, + std::move(done_cb)); + }, + private_key_strings[i], public_value_strings[i], decryptor_, + record_results[i].cb())); } // Verify registration success. for (auto& record_result : record_results) {
diff --git a/chrome/browser/policy/messaging_layer/encryption/encryption_unittest.cc b/components/reporting/encryption/encryption_unittest.cc similarity index 94% rename from chrome/browser/policy/messaging_layer/encryption/encryption_unittest.cc rename to components/reporting/encryption/encryption_unittest.cc index bec001f..061c11d 100644 --- a/chrome/browser/policy/messaging_layer/encryption/encryption_unittest.cc +++ b/components/reporting/encryption/encryption_unittest.cc
@@ -2,7 +2,7 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#include "chrome/browser/policy/messaging_layer/encryption/encryption.h" +#include "components/reporting/encryption/encryption.h" #include "base/bind.h" #include "base/containers/flat_map.h" @@ -12,11 +12,11 @@ #include "base/synchronization/waitable_event.h" #include "base/test/task_environment.h" #include "base/time/time.h" -#include "chrome/browser/policy/messaging_layer/encryption/decryption.h" -#include "chrome/browser/policy/messaging_layer/util/status.h" -#include "chrome/browser/policy/messaging_layer/util/status_macros.h" -#include "chrome/browser/policy/messaging_layer/util/statusor.h" -#include "components/policy/proto/record.pb.h" +#include "components/reporting/encryption/decryption.h" +#include "components/reporting/proto/record.pb.h" +#include "components/reporting/util/status.h" +#include "components/reporting/util/status_macros.h" +#include "components/reporting/util/statusor.h" #include "testing/gmock/include/gmock/gmock.h" #include "testing/gtest/include/gtest/gtest.h" #include "third_party/boringssl/src/include/openssl/curve25519.h" @@ -517,18 +517,18 @@ public_value_strings.size()); for (size_t i = 0; i < public_value_strings.size(); ++i) { base::ThreadPool::PostTask( - FROM_HERE, base::BindOnce( - [](base::StringPiece private_key_string, - base::StringPiece public_key_string, - scoped_refptr<Decryptor> decryptor, - base::OnceCallback<void( - StatusOr<Encryptor::PublicKeyId>)> done_cb) { - decryptor->RecordKeyPair(private_key_string, - public_key_string, - std::move(done_cb)); - }, - private_key_strings[i], public_value_strings[i], - decryptor_, record_results[i].cb())); + FROM_HERE, + base::BindOnce( + [](base::StringPiece private_key_string, + base::StringPiece public_key_string, + scoped_refptr<Decryptor> decryptor, + base::OnceCallback<void(StatusOr<Encryptor::PublicKeyId>)> + done_cb) { + decryptor->RecordKeyPair(private_key_string, public_key_string, + std::move(done_cb)); + }, + private_key_strings[i], public_value_strings[i], decryptor_, + record_results[i].cb())); } // Verify registration success. for (auto& record_result : record_results) {
diff --git a/chrome/browser/policy/messaging_layer/encryption/test_encryption_module.cc b/components/reporting/encryption/test_encryption_module.cc similarity index 81% rename from chrome/browser/policy/messaging_layer/encryption/test_encryption_module.cc rename to components/reporting/encryption/test_encryption_module.cc index 34e2a43..3af2425f6 100644 --- a/chrome/browser/policy/messaging_layer/encryption/test_encryption_module.cc +++ b/components/reporting/encryption/test_encryption_module.cc
@@ -2,13 +2,13 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#include "chrome/browser/policy/messaging_layer/encryption/test_encryption_module.h" +#include "components/reporting/encryption/test_encryption_module.h" #include "base/callback.h" #include "base/strings/string_piece.h" -#include "chrome/browser/policy/messaging_layer/encryption/encryption.h" -#include "chrome/browser/policy/messaging_layer/util/statusor.h" -#include "components/policy/proto/record.pb.h" +#include "components/reporting/encryption/encryption.h" +#include "components/reporting/proto/record.pb.h" +#include "components/reporting/util/statusor.h" using ::testing::Invoke;
diff --git a/chrome/browser/policy/messaging_layer/encryption/test_encryption_module.h b/components/reporting/encryption/test_encryption_module.h similarity index 69% rename from chrome/browser/policy/messaging_layer/encryption/test_encryption_module.h rename to components/reporting/encryption/test_encryption_module.h index 3e88e533..498d15a 100644 --- a/chrome/browser/policy/messaging_layer/encryption/test_encryption_module.h +++ b/components/reporting/encryption/test_encryption_module.h
@@ -2,15 +2,15 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#ifndef CHROME_BROWSER_POLICY_MESSAGING_LAYER_ENCRYPTION_TEST_ENCRYPTION_MODULE_H_ -#define CHROME_BROWSER_POLICY_MESSAGING_LAYER_ENCRYPTION_TEST_ENCRYPTION_MODULE_H_ +#ifndef COMPONENTS_REPORTING_ENCRYPTION_TEST_ENCRYPTION_MODULE_H_ +#define COMPONENTS_REPORTING_ENCRYPTION_TEST_ENCRYPTION_MODULE_H_ #include "base/callback.h" #include "base/strings/string_piece.h" -#include "chrome/browser/policy/messaging_layer/encryption/encryption.h" -#include "chrome/browser/policy/messaging_layer/public/report_queue.h" -#include "chrome/browser/policy/messaging_layer/util/statusor.h" -#include "components/policy/proto/record.pb.h" +#include "components/reporting/encryption/encryption.h" +#include "components/reporting/encryption/encryption_module.h" +#include "components/reporting/proto/record.pb.h" +#include "components/reporting/util/statusor.h" #include "testing/gmock/include/gmock/gmock.h" #include "testing/gtest/include/gtest/gtest.h" @@ -43,4 +43,4 @@ } // namespace test } // namespace reporting -#endif // CHROME_BROWSER_POLICY_MESSAGING_LAYER_ENCRYPTION_TEST_ENCRYPTION_MODULE_H_ +#endif // COMPONENTS_REPORTING_ENCRYPTION_TEST_ENCRYPTION_MODULE_H_
diff --git a/chrome/browser/policy/messaging_layer/encryption/verification.cc b/components/reporting/encryption/verification.cc similarity index 93% rename from chrome/browser/policy/messaging_layer/encryption/verification.cc rename to components/reporting/encryption/verification.cc index 2bd4b82..5e5bcfd 100644 --- a/chrome/browser/policy/messaging_layer/encryption/verification.cc +++ b/components/reporting/encryption/verification.cc
@@ -2,9 +2,9 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#include "chrome/browser/policy/messaging_layer/encryption/verification.h" +#include "components/reporting/encryption/verification.h" -#include "chrome/browser/policy/messaging_layer/util/status.h" +#include "components/reporting/util/status.h" #include "third_party/boringssl/src/include/openssl/curve25519.h" namespace reporting {
diff --git a/chrome/browser/policy/messaging_layer/encryption/verification.h b/components/reporting/encryption/verification.h similarity index 80% rename from chrome/browser/policy/messaging_layer/encryption/verification.h rename to components/reporting/encryption/verification.h index 607bfbe..0b3d3d1b 100644 --- a/chrome/browser/policy/messaging_layer/encryption/verification.h +++ b/components/reporting/encryption/verification.h
@@ -2,13 +2,13 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#ifndef CHROME_BROWSER_POLICY_MESSAGING_LAYER_ENCRYPTION_VERIFICATION_H_ -#define CHROME_BROWSER_POLICY_MESSAGING_LAYER_ENCRYPTION_VERIFICATION_H_ +#ifndef COMPONENTS_REPORTING_ENCRYPTION_VERIFICATION_H_ +#define COMPONENTS_REPORTING_ENCRYPTION_VERIFICATION_H_ #include <string> #include "base/strings/string_piece.h" -#include "chrome/browser/policy/messaging_layer/util/status.h" +#include "components/reporting/util/status.h" namespace reporting { @@ -35,4 +35,4 @@ }; } // namespace reporting -#endif // CHROME_BROWSER_POLICY_MESSAGING_LAYER_ENCRYPTION_VERIFICATION_H_ +#endif // COMPONENTS_REPORTING_ENCRYPTION_VERIFICATION_H_
diff --git a/chrome/browser/policy/messaging_layer/encryption/verification_unittest.cc b/components/reporting/encryption/verification_unittest.cc similarity index 98% rename from chrome/browser/policy/messaging_layer/encryption/verification_unittest.cc rename to components/reporting/encryption/verification_unittest.cc index 8475848c..8fb8a4e 100644 --- a/chrome/browser/policy/messaging_layer/encryption/verification_unittest.cc +++ b/components/reporting/encryption/verification_unittest.cc
@@ -2,7 +2,7 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#include "chrome/browser/policy/messaging_layer/encryption/verification.h" +#include "components/reporting/encryption/verification.h" #include "testing/gmock/include/gmock/gmock.h" #include "testing/gtest/include/gtest/gtest.h"
diff --git a/components/reporting/proto/BUILD.gn b/components/reporting/proto/BUILD.gn new file mode 100644 index 0000000..9eb8f80a --- /dev/null +++ b/components/reporting/proto/BUILD.gn
@@ -0,0 +1,22 @@ +# Copyright 2021 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("//third_party/libprotobuf-mutator/fuzzable_proto_library.gni") +import("//third_party/protobuf/proto_library.gni") + +# Record constants for use with the reporting messaging library. +proto_library("record_constants") { + sources = [ "record_constants.proto" ] + + proto_out_dir = "components/reporting/proto" +} + +# Record definitions for reporting. +proto_library("record_proto") { + sources = [ "record.proto" ] + + deps = [ ":record_constants" ] + + proto_out_dir = "components/reporting/proto" +}
diff --git a/components/policy/proto/record.proto b/components/reporting/proto/record.proto similarity index 100% rename from components/policy/proto/record.proto rename to components/reporting/proto/record.proto
diff --git a/components/policy/proto/record_constants.proto b/components/reporting/proto/record_constants.proto similarity index 100% rename from components/policy/proto/record_constants.proto rename to components/reporting/proto/record_constants.proto
diff --git a/components/reporting/storage/BUILD.gn b/components/reporting/storage/BUILD.gn new file mode 100644 index 0000000..26690b1 --- /dev/null +++ b/components/reporting/storage/BUILD.gn
@@ -0,0 +1,132 @@ +# Copyright 2021 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("//build/config/features.gni") + +static_library("storage_configuration") { + sources = [ + "storage_configuration.cc", + "storage_configuration.h", + ] + + deps = [ "//base" ] +} + +static_library("storage_queue") { + sources = [ + "storage_queue.cc", + "storage_queue.h", + ] + + deps = [ + ":storage_configuration", + "//base", + "//components/reporting/encryption:encryption_module", + "//components/reporting/encryption:verification", + "//components/reporting/proto:record_constants", + "//components/reporting/proto:record_proto", + "//components/reporting/storage/resources:resource_interface", + "//components/reporting/util:status", + "//components/reporting/util:status_macros", + "//components/reporting/util:task_runner_context", + "//crypto", + "//third_party/protobuf:protobuf_lite", + ] +} + +static_library("storage") { + sources = [ + "storage.cc", + "storage.h", + ] + + public_deps = [ ":storage_configuration" ] + + deps = [ + ":storage_queue", + "//base", + "//components/reporting/encryption:encryption_module", + "//components/reporting/encryption:verification", + "//components/reporting/proto:record_constants", + "//components/reporting/proto:record_proto", + "//components/reporting/util:status", + "//components/reporting/util:status_macros", + "//components/reporting/util:task_runner_context", + "//third_party/boringssl", + "//third_party/protobuf:protobuf_lite", + ] +} + +static_library("storage_module") { + sources = [ + "storage_module.cc", + "storage_module.h", + ] + + public_deps = [ ":storage_configuration" ] + + deps = [ + ":storage", + "//base", + "//components/reporting/encryption:encryption_module", + "//components/reporting/proto:record_constants", + "//components/reporting/proto:record_proto", + "//components/reporting/util:status", + ] +} + +static_library("test_support") { + testonly = true + sources = [ + "test_storage_module.cc", + "test_storage_module.h", + ] + public_deps = [ + ":storage", + ":storage_configuration", + ":storage_module", + ":storage_queue", + "//components/reporting/proto:record_constants", + "//components/reporting/proto:record_proto", + "//components/reporting/util:status", + ] + deps = [ + "//base", + "//crypto", + "//testing/gmock", + "//testing/gtest", + "//third_party/boringssl", + ] +} + +# All unit tests are built as part of the //components:components_unittests +# target and must be one targets named "unit_tests". +source_set("unit_tests") { + testonly = true + sources = [ + "storage_queue_stress_test.cc", + "storage_queue_unittest.cc", + "storage_unittest.cc", + ] + deps = [ + ":storage", + ":storage_configuration", + ":storage_module", + ":storage_queue", + ":test_support", + "//base", + "//base/test:test_support", + "//components/reporting/encryption:decryption", + "//components/reporting/encryption:encryption", + "//components/reporting/encryption:test_support", + "//components/reporting/proto:record_proto", + "//components/reporting/storage/resources:resource_interface", + "//components/reporting/util:status", + "//components/reporting/util:status_macros", + "//crypto", + "//testing/gmock", + "//testing/gtest", + "//third_party/boringssl", + ] +}
diff --git a/components/reporting/storage/DEPS b/components/reporting/storage/DEPS new file mode 100644 index 0000000..75318e7 --- /dev/null +++ b/components/reporting/storage/DEPS
@@ -0,0 +1,7 @@ +include_rules = [ + "+base", + "+crypto", + "+third_party/protobuf", + "+third_party/boringssl/src/include", +] +
diff --git a/components/reporting/storage/resources/BUILD.gn b/components/reporting/storage/resources/BUILD.gn new file mode 100644 index 0000000..69410be --- /dev/null +++ b/components/reporting/storage/resources/BUILD.gn
@@ -0,0 +1,34 @@ +# Copyright 2021 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("//build/config/features.gni") + +static_library("resource_interface") { + visibility = [ "//components/reporting/storage/*" ] + sources = [ + "disk_resource_impl.cc", + "disk_resource_impl.h", + "memory_resource_impl.cc", + "memory_resource_impl.h", + "resource_interface.cc", + "resource_interface.h", + ] + + deps = [ "//base" ] +} + +# All unit tests are built as part of the //components:components_unittests +# target and must be one targets named "unit_tests". +# TODO(chromium:1169835) These tests can't be run on iOS until they are updated. +source_set("unit_tests") { + testonly = true + sources = [ "resource_interface_unittest.cc" ] + deps = [ + ":resource_interface", + "//base", + "//base/test:test_support", + "//testing/gmock", + "//testing/gtest", + ] +}
diff --git a/chrome/browser/policy/messaging_layer/storage/resources/disk_resource_impl.cc b/components/reporting/storage/resources/disk_resource_impl.cc similarity index 92% rename from chrome/browser/policy/messaging_layer/storage/resources/disk_resource_impl.cc rename to components/reporting/storage/resources/disk_resource_impl.cc index 482433f..c8ca7b4 100644 --- a/chrome/browser/policy/messaging_layer/storage/resources/disk_resource_impl.cc +++ b/components/reporting/storage/resources/disk_resource_impl.cc
@@ -2,7 +2,7 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#include "chrome/browser/policy/messaging_layer/storage/resources/disk_resource_impl.h" +#include "components/reporting/storage/resources/disk_resource_impl.h" #include <atomic> #include <cstdint>
diff --git a/chrome/browser/policy/messaging_layer/storage/resources/disk_resource_impl.h b/components/reporting/storage/resources/disk_resource_impl.h similarity index 70% rename from chrome/browser/policy/messaging_layer/storage/resources/disk_resource_impl.h rename to components/reporting/storage/resources/disk_resource_impl.h index 6e0e4ea..927fff1 100644 --- a/chrome/browser/policy/messaging_layer/storage/resources/disk_resource_impl.h +++ b/components/reporting/storage/resources/disk_resource_impl.h
@@ -2,13 +2,13 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#ifndef CHROME_BROWSER_POLICY_MESSAGING_LAYER_STORAGE_RESOURCES_DISK_RESOURCE_IMPL_H_ -#define CHROME_BROWSER_POLICY_MESSAGING_LAYER_STORAGE_RESOURCES_DISK_RESOURCE_IMPL_H_ +#ifndef COMPONENTS_REPORTING_STORAGE_RESOURCES_DISK_RESOURCE_IMPL_H_ +#define COMPONENTS_REPORTING_STORAGE_RESOURCES_DISK_RESOURCE_IMPL_H_ #include <atomic> #include <cstdint> -#include "chrome/browser/policy/messaging_layer/storage/resources/resource_interface.h" +#include "components/reporting/storage/resources/resource_interface.h" namespace reporting { @@ -34,4 +34,4 @@ } // namespace reporting -#endif // CHROME_BROWSER_POLICY_MESSAGING_LAYER_STORAGE_RESOURCES_DISK_RESOURCE_IMPL_H_ +#endif // COMPONENTS_REPORTING_STORAGE_RESOURCES_DISK_RESOURCE_IMPL_H_
diff --git a/chrome/browser/policy/messaging_layer/storage/resources/memory_resource_impl.cc b/components/reporting/storage/resources/memory_resource_impl.cc similarity index 92% rename from chrome/browser/policy/messaging_layer/storage/resources/memory_resource_impl.cc rename to components/reporting/storage/resources/memory_resource_impl.cc index 41c1e13..7d59caa 100644 --- a/chrome/browser/policy/messaging_layer/storage/resources/memory_resource_impl.cc +++ b/components/reporting/storage/resources/memory_resource_impl.cc
@@ -2,7 +2,7 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#include "chrome/browser/policy/messaging_layer/storage/resources/memory_resource_impl.h" +#include "components/reporting/storage/resources/memory_resource_impl.h" #include <atomic> #include <cstdint>
diff --git a/chrome/browser/policy/messaging_layer/storage/resources/memory_resource_impl.h b/components/reporting/storage/resources/memory_resource_impl.h similarity index 70% rename from chrome/browser/policy/messaging_layer/storage/resources/memory_resource_impl.h rename to components/reporting/storage/resources/memory_resource_impl.h index db927f0..c8cd965f 100644 --- a/chrome/browser/policy/messaging_layer/storage/resources/memory_resource_impl.h +++ b/components/reporting/storage/resources/memory_resource_impl.h
@@ -2,13 +2,13 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#ifndef CHROME_BROWSER_POLICY_MESSAGING_LAYER_STORAGE_RESOURCES_MEMORY_RESOURCE_IMPL_H_ -#define CHROME_BROWSER_POLICY_MESSAGING_LAYER_STORAGE_RESOURCES_MEMORY_RESOURCE_IMPL_H_ +#ifndef COMPONENTS_REPORTING_STORAGE_RESOURCES_MEMORY_RESOURCE_IMPL_H_ +#define COMPONENTS_REPORTING_STORAGE_RESOURCES_MEMORY_RESOURCE_IMPL_H_ #include <atomic> #include <cstdint> -#include "chrome/browser/policy/messaging_layer/storage/resources/resource_interface.h" +#include "components/reporting/storage/resources/resource_interface.h" namespace reporting { @@ -34,4 +34,4 @@ } // namespace reporting -#endif // CHROME_BROWSER_POLICY_MESSAGING_LAYER_STORAGE_RESOURCES_MEMORY_RESOURCE_IMPL_H_ +#endif // COMPONENTS_REPORTING_STORAGE_RESOURCES_MEMORY_RESOURCE_IMPL_H_
diff --git a/chrome/browser/policy/messaging_layer/storage/resources/resource_interface.cc b/components/reporting/storage/resources/resource_interface.cc similarity index 90% rename from chrome/browser/policy/messaging_layer/storage/resources/resource_interface.cc rename to components/reporting/storage/resources/resource_interface.cc index 7be8410..57e97c39 100644 --- a/chrome/browser/policy/messaging_layer/storage/resources/resource_interface.cc +++ b/components/reporting/storage/resources/resource_interface.cc
@@ -2,9 +2,9 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#include <cstdint> +#include "components/reporting/storage/resources/resource_interface.h" -#include "chrome/browser/policy/messaging_layer/storage/resources/resource_interface.h" +#include <cstdint> namespace reporting {
diff --git a/chrome/browser/policy/messaging_layer/storage/resources/resource_interface.h b/components/reporting/storage/resources/resource_interface.h similarity index 88% rename from chrome/browser/policy/messaging_layer/storage/resources/resource_interface.h rename to components/reporting/storage/resources/resource_interface.h index 3e1840b..a2b30299 100644 --- a/chrome/browser/policy/messaging_layer/storage/resources/resource_interface.h +++ b/components/reporting/storage/resources/resource_interface.h
@@ -2,8 +2,8 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#ifndef CHROME_BROWSER_POLICY_MESSAGING_LAYER_STORAGE_RESOURCES_RESOURCE_INTERFACE_H_ -#define CHROME_BROWSER_POLICY_MESSAGING_LAYER_STORAGE_RESOURCES_RESOURCE_INTERFACE_H_ +#ifndef COMPONENTS_REPORTING_STORAGE_RESOURCES_RESOURCE_INTERFACE_H_ +#define COMPONENTS_REPORTING_STORAGE_RESOURCES_RESOURCE_INTERFACE_H_ #include <cstdint> @@ -75,4 +75,4 @@ } // namespace reporting -#endif // CHROME_BROWSER_POLICY_MESSAGING_LAYER_STORAGE_RESOURCES_RESOURCE_INTERFACE_H_ +#endif // COMPONENTS_REPORTING_STORAGE_RESOURCES_RESOURCE_INTERFACE_H_
diff --git a/chrome/browser/policy/messaging_layer/storage/resources/resource_interface_unittest.cc b/components/reporting/storage/resources/resource_interface_unittest.cc similarity index 97% rename from chrome/browser/policy/messaging_layer/storage/resources/resource_interface_unittest.cc rename to components/reporting/storage/resources/resource_interface_unittest.cc index 46bbf94..90bddcf 100644 --- a/chrome/browser/policy/messaging_layer/storage/resources/resource_interface_unittest.cc +++ b/components/reporting/storage/resources/resource_interface_unittest.cc
@@ -4,7 +4,7 @@ #include <cstdint> -#include "chrome/browser/policy/messaging_layer/storage/resources/resource_interface.h" +#include "components/reporting/storage/resources/resource_interface.h" #include "base/task/post_task.h" #include "base/task_runner.h"
diff --git a/chrome/browser/policy/messaging_layer/storage/storage.cc b/components/reporting/storage/storage.cc similarity index 96% rename from chrome/browser/policy/messaging_layer/storage/storage.cc rename to components/reporting/storage/storage.cc index 40100a0..193ae24 100644 --- a/chrome/browser/policy/messaging_layer/storage/storage.cc +++ b/components/reporting/storage/storage.cc
@@ -2,7 +2,7 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#include "chrome/browser/policy/messaging_layer/storage/storage.h" +#include "components/reporting/storage/storage.h" #include <cstdint> #include <utility> @@ -22,15 +22,15 @@ #include "base/task_runner.h" #include "base/threading/thread.h" #include "base/threading/thread_task_runner_handle.h" -#include "chrome/browser/policy/messaging_layer/encryption/encryption_module.h" -#include "chrome/browser/policy/messaging_layer/encryption/verification.h" -#include "chrome/browser/policy/messaging_layer/storage/storage_configuration.h" -#include "chrome/browser/policy/messaging_layer/storage/storage_queue.h" -#include "chrome/browser/policy/messaging_layer/util/status.h" -#include "chrome/browser/policy/messaging_layer/util/status_macros.h" -#include "chrome/browser/policy/messaging_layer/util/statusor.h" -#include "chrome/browser/policy/messaging_layer/util/task_runner_context.h" -#include "components/policy/proto/record.pb.h" +#include "components/reporting/encryption/encryption_module.h" +#include "components/reporting/encryption/verification.h" +#include "components/reporting/proto/record.pb.h" +#include "components/reporting/storage/storage_configuration.h" +#include "components/reporting/storage/storage_queue.h" +#include "components/reporting/util/status.h" +#include "components/reporting/util/status_macros.h" +#include "components/reporting/util/statusor.h" +#include "components/reporting/util/task_runner_context.h" #include "third_party/boringssl/src/include/openssl/curve25519.h" #include "third_party/protobuf/src/google/protobuf/io/zero_copy_stream_impl.h"
diff --git a/chrome/browser/policy/messaging_layer/storage/storage.h b/components/reporting/storage/storage.h similarity index 87% rename from chrome/browser/policy/messaging_layer/storage/storage.h rename to components/reporting/storage/storage.h index 620bf4f..edce0c2b 100644 --- a/chrome/browser/policy/messaging_layer/storage/storage.h +++ b/components/reporting/storage/storage.h
@@ -2,8 +2,8 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#ifndef CHROME_BROWSER_POLICY_MESSAGING_LAYER_STORAGE_STORAGE_H_ -#define CHROME_BROWSER_POLICY_MESSAGING_LAYER_STORAGE_STORAGE_H_ +#ifndef COMPONENTS_REPORTING_STORAGE_STORAGE_H_ +#define COMPONENTS_REPORTING_STORAGE_STORAGE_H_ #include <map> #include <memory> @@ -16,13 +16,13 @@ #include "base/memory/ref_counted.h" #include "base/memory/scoped_refptr.h" #include "base/strings/string_piece.h" -#include "chrome/browser/policy/messaging_layer/encryption/encryption_module.h" -#include "chrome/browser/policy/messaging_layer/storage/storage_configuration.h" -#include "chrome/browser/policy/messaging_layer/storage/storage_queue.h" -#include "chrome/browser/policy/messaging_layer/util/status.h" -#include "chrome/browser/policy/messaging_layer/util/statusor.h" -#include "components/policy/proto/record.pb.h" -#include "components/policy/proto/record_constants.pb.h" +#include "components/reporting/encryption/encryption_module.h" +#include "components/reporting/proto/record.pb.h" +#include "components/reporting/proto/record_constants.pb.h" +#include "components/reporting/storage/storage_configuration.h" +#include "components/reporting/storage/storage_queue.h" +#include "components/reporting/util/status.h" +#include "components/reporting/util/statusor.h" namespace reporting { @@ -131,4 +131,4 @@ } // namespace reporting -#endif // CHROME_BROWSER_POLICY_MESSAGING_LAYER_STORAGE_STORAGE_H_ +#endif // COMPONENTS_REPORTING_STORAGE_STORAGE_H_
diff --git a/chrome/browser/policy/messaging_layer/storage/storage_configuration.cc b/components/reporting/storage/storage_configuration.cc similarity index 84% rename from chrome/browser/policy/messaging_layer/storage/storage_configuration.cc rename to components/reporting/storage/storage_configuration.cc index 96dfe382..df4fc36b 100644 --- a/chrome/browser/policy/messaging_layer/storage/storage_configuration.cc +++ b/components/reporting/storage/storage_configuration.cc
@@ -2,7 +2,7 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#include "chrome/browser/policy/messaging_layer/storage/storage_configuration.h" +#include "components/reporting/storage/storage_configuration.h" namespace reporting {
diff --git a/chrome/browser/policy/messaging_layer/storage/storage_configuration.h b/components/reporting/storage/storage_configuration.h similarity index 95% rename from chrome/browser/policy/messaging_layer/storage/storage_configuration.h rename to components/reporting/storage/storage_configuration.h index d47296a7..834d3ff 100644 --- a/chrome/browser/policy/messaging_layer/storage/storage_configuration.h +++ b/components/reporting/storage/storage_configuration.h
@@ -2,8 +2,8 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#ifndef CHROME_BROWSER_POLICY_MESSAGING_LAYER_STORAGE_STORAGE_CONFIGURATION_H_ -#define CHROME_BROWSER_POLICY_MESSAGING_LAYER_STORAGE_STORAGE_CONFIGURATION_H_ +#ifndef COMPONENTS_REPORTING_STORAGE_STORAGE_CONFIGURATION_H_ +#define COMPONENTS_REPORTING_STORAGE_STORAGE_CONFIGURATION_H_ #include <string> @@ -142,4 +142,4 @@ } // namespace reporting -#endif // CHROME_BROWSER_POLICY_MESSAGING_LAYER_STORAGE_STORAGE_CONFIGURATION_H_ +#endif // COMPONENTS_REPORTING_STORAGE_STORAGE_CONFIGURATION_H_
diff --git a/chrome/browser/policy/messaging_layer/storage/storage_module.cc b/components/reporting/storage/storage_module.cc similarity index 74% rename from chrome/browser/policy/messaging_layer/storage/storage_module.cc rename to components/reporting/storage/storage_module.cc index 095c1ac..3e751142 100644 --- a/chrome/browser/policy/messaging_layer/storage/storage_module.cc +++ b/components/reporting/storage/storage_module.cc
@@ -2,6 +2,8 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. +#include "components/reporting/storage/storage_module.h" + #include <memory> #include <utility> @@ -9,14 +11,13 @@ #include "base/callback.h" #include "base/containers/span.h" #include "base/memory/ptr_util.h" -#include "chrome/browser/policy/messaging_layer/encryption/encryption_module.h" -#include "chrome/browser/policy/messaging_layer/storage/storage.h" -#include "chrome/browser/policy/messaging_layer/storage/storage_configuration.h" -#include "chrome/browser/policy/messaging_layer/storage/storage_module.h" -#include "chrome/browser/policy/messaging_layer/util/status.h" -#include "chrome/browser/policy/messaging_layer/util/statusor.h" -#include "components/policy/proto/record.pb.h" -#include "components/policy/proto/record_constants.pb.h" +#include "components/reporting/encryption/encryption_module.h" +#include "components/reporting/proto/record.pb.h" +#include "components/reporting/proto/record_constants.pb.h" +#include "components/reporting/storage/storage.h" +#include "components/reporting/storage/storage_configuration.h" +#include "components/reporting/util/status.h" +#include "components/reporting/util/statusor.h" namespace reporting { @@ -30,12 +31,11 @@ storage_->Write(priority, std::move(record), std::move(callback)); } -void StorageModule::ReportSuccess( - SequencingInformation sequencing_information) { +void StorageModule::ReportSuccess(SequencingInformation sequencing_information, + bool force) { storage_->Confirm( sequencing_information.priority(), sequencing_information.sequencing_id(), - /*force=*/false, // TODO(b/176997912): deliver it from ReportClient. - base::BindOnce([](Status status) { + force, base::BindOnce([](Status status) { if (!status.ok()) { LOG(ERROR) << "Unable to confirm record deletion: " << status; }
diff --git a/chrome/browser/policy/messaging_layer/storage/storage_module.h b/components/reporting/storage/storage_module.h similarity index 74% rename from chrome/browser/policy/messaging_layer/storage/storage_module.h rename to components/reporting/storage/storage_module.h index f115d06a..bea5f0e 100644 --- a/chrome/browser/policy/messaging_layer/storage/storage_module.h +++ b/components/reporting/storage/storage_module.h
@@ -2,21 +2,21 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#ifndef CHROME_BROWSER_POLICY_MESSAGING_LAYER_STORAGE_STORAGE_MODULE_H_ -#define CHROME_BROWSER_POLICY_MESSAGING_LAYER_STORAGE_STORAGE_MODULE_H_ +#ifndef COMPONENTS_REPORTING_STORAGE_STORAGE_MODULE_H_ +#define COMPONENTS_REPORTING_STORAGE_STORAGE_MODULE_H_ #include <utility> #include "base/callback.h" #include "base/memory/ref_counted.h" #include "base/memory/scoped_refptr.h" -#include "chrome/browser/policy/messaging_layer/encryption/encryption_module.h" -#include "chrome/browser/policy/messaging_layer/storage/storage.h" -#include "chrome/browser/policy/messaging_layer/storage/storage_configuration.h" -#include "chrome/browser/policy/messaging_layer/util/status.h" -#include "chrome/browser/policy/messaging_layer/util/statusor.h" -#include "components/policy/proto/record.pb.h" -#include "components/policy/proto/record_constants.pb.h" +#include "components/reporting/encryption/encryption_module.h" +#include "components/reporting/proto/record.pb.h" +#include "components/reporting/proto/record_constants.pb.h" +#include "components/reporting/storage/storage.h" +#include "components/reporting/storage/storage_configuration.h" +#include "components/reporting/util/status.h" +#include "components/reporting/util/statusor.h" namespace reporting { @@ -42,7 +42,11 @@ // Once a record has been successfully uploaded, the sequencing information // can be passed back to the StorageModule here for record deletion. - virtual void ReportSuccess(SequencingInformation sequencing_information); + // If |force| is false (which is used in most cases), |sequencing_information| + // only affects Storage if no higher sequeincing was confirmed before; + // otherwise it is accepted unconditionally. + virtual void ReportSuccess(SequencingInformation sequencing_information, + bool force); // If the server attached signed encryption key to the response, it needs to // be paased here. @@ -72,4 +76,4 @@ } // namespace reporting -#endif // CHROME_BROWSER_POLICY_MESSAGING_LAYER_STORAGE_STORAGE_MODULE_H_ +#endif // COMPONENTS_REPORTING_STORAGE_STORAGE_MODULE_H_
diff --git a/chrome/browser/policy/messaging_layer/storage/storage_queue.cc b/components/reporting/storage/storage_queue.cc similarity index 98% rename from chrome/browser/policy/messaging_layer/storage/storage_queue.cc rename to components/reporting/storage/storage_queue.cc index 1b4e92a..6bfd046 100644 --- a/chrome/browser/policy/messaging_layer/storage/storage_queue.cc +++ b/components/reporting/storage/storage_queue.cc
@@ -2,7 +2,7 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#include "chrome/browser/policy/messaging_layer/storage/storage_queue.h" +#include "components/reporting/storage/storage_queue.h" #include <algorithm> #include <cstring> @@ -34,14 +34,14 @@ #include "base/strings/string_util.h" #include "base/task/post_task.h" #include "base/task_runner.h" -#include "chrome/browser/policy/messaging_layer/encryption/encryption_module.h" -#include "chrome/browser/policy/messaging_layer/storage/resources/resource_interface.h" -#include "chrome/browser/policy/messaging_layer/storage/storage_configuration.h" -#include "chrome/browser/policy/messaging_layer/util/status.h" -#include "chrome/browser/policy/messaging_layer/util/status_macros.h" -#include "chrome/browser/policy/messaging_layer/util/statusor.h" -#include "chrome/browser/policy/messaging_layer/util/task_runner_context.h" -#include "components/policy/proto/record.pb.h" +#include "components/reporting/encryption/encryption_module.h" +#include "components/reporting/proto/record.pb.h" +#include "components/reporting/storage/resources/resource_interface.h" +#include "components/reporting/storage/storage_configuration.h" +#include "components/reporting/util/status.h" +#include "components/reporting/util/status_macros.h" +#include "components/reporting/util/statusor.h" +#include "components/reporting/util/task_runner_context.h" #include "crypto/random.h" #include "crypto/sha2.h" #include "third_party/protobuf/src/google/protobuf/io/zero_copy_stream_impl_lite.h"
diff --git a/chrome/browser/policy/messaging_layer/storage/storage_queue.h b/components/reporting/storage/storage_queue.h similarity index 96% rename from chrome/browser/policy/messaging_layer/storage/storage_queue.h rename to components/reporting/storage/storage_queue.h index 13eecdd4..80a955e6 100644 --- a/chrome/browser/policy/messaging_layer/storage/storage_queue.h +++ b/components/reporting/storage/storage_queue.h
@@ -2,8 +2,8 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#ifndef CHROME_BROWSER_POLICY_MESSAGING_LAYER_STORAGE_STORAGE_QUEUE_H_ -#define CHROME_BROWSER_POLICY_MESSAGING_LAYER_STORAGE_STORAGE_QUEUE_H_ +#ifndef COMPONENTS_REPORTING_STORAGE_STORAGE_QUEUE_H_ +#define COMPONENTS_REPORTING_STORAGE_STORAGE_QUEUE_H_ #include <list> #include <map> @@ -24,11 +24,11 @@ #include "base/threading/thread.h" #include "base/threading/thread_task_runner_handle.h" #include "base/timer/timer.h" -#include "chrome/browser/policy/messaging_layer/encryption/encryption_module.h" -#include "chrome/browser/policy/messaging_layer/storage/storage_configuration.h" -#include "chrome/browser/policy/messaging_layer/util/status.h" -#include "chrome/browser/policy/messaging_layer/util/statusor.h" -#include "components/policy/proto/record.pb.h" +#include "components/reporting/encryption/encryption_module.h" +#include "components/reporting/proto/record.pb.h" +#include "components/reporting/storage/storage_configuration.h" +#include "components/reporting/util/status.h" +#include "components/reporting/util/statusor.h" namespace reporting { @@ -375,4 +375,4 @@ } // namespace reporting -#endif // CHROME_BROWSER_POLICY_MESSAGING_LAYER_STORAGE_STORAGE_QUEUE_H_ +#endif // COMPONENTS_REPORTING_STORAGE_STORAGE_QUEUE_H_
diff --git a/chrome/browser/policy/messaging_layer/storage/storage_queue_stress_test.cc b/components/reporting/storage/storage_queue_stress_test.cc similarity index 95% rename from chrome/browser/policy/messaging_layer/storage/storage_queue_stress_test.cc rename to components/reporting/storage/storage_queue_stress_test.cc index 46a8c328..0e08d4e 100644 --- a/chrome/browser/policy/messaging_layer/storage/storage_queue_stress_test.cc +++ b/components/reporting/storage/storage_queue_stress_test.cc
@@ -2,7 +2,7 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#include "chrome/browser/policy/messaging_layer/storage/storage_queue.h" +#include "components/reporting/storage/storage_queue.h" #include <cstdint> #include <initializer_list> @@ -18,12 +18,12 @@ #include "base/strings/string_number_conversions.h" #include "base/synchronization/waitable_event.h" #include "base/test/task_environment.h" -#include "chrome/browser/policy/messaging_layer/encryption/test_encryption_module.h" -#include "chrome/browser/policy/messaging_layer/storage/resources/resource_interface.h" -#include "chrome/browser/policy/messaging_layer/storage/storage_configuration.h" -#include "chrome/browser/policy/messaging_layer/util/status.h" -#include "chrome/browser/policy/messaging_layer/util/statusor.h" -#include "components/policy/proto/record.pb.h" +#include "components/reporting/encryption/test_encryption_module.h" +#include "components/reporting/proto/record.pb.h" +#include "components/reporting/storage/resources/resource_interface.h" +#include "components/reporting/storage/storage_configuration.h" +#include "components/reporting/util/status.h" +#include "components/reporting/util/statusor.h" #include "crypto/sha2.h" #include "testing/gmock/include/gmock/gmock.h" #include "testing/gtest/include/gtest/gtest.h"
diff --git a/chrome/browser/policy/messaging_layer/storage/storage_queue_unittest.cc b/components/reporting/storage/storage_queue_unittest.cc similarity index 98% rename from chrome/browser/policy/messaging_layer/storage/storage_queue_unittest.cc rename to components/reporting/storage/storage_queue_unittest.cc index b5b7c43..25cdd29 100644 --- a/chrome/browser/policy/messaging_layer/storage/storage_queue_unittest.cc +++ b/components/reporting/storage/storage_queue_unittest.cc
@@ -2,7 +2,7 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#include "chrome/browser/policy/messaging_layer/storage/storage_queue.h" +#include "components/reporting/storage/storage_queue.h" #include <cstdint> #include <initializer_list> @@ -16,12 +16,12 @@ #include "base/strings/strcat.h" #include "base/strings/string_number_conversions.h" #include "base/test/task_environment.h" -#include "chrome/browser/policy/messaging_layer/encryption/test_encryption_module.h" -#include "chrome/browser/policy/messaging_layer/storage/resources/resource_interface.h" -#include "chrome/browser/policy/messaging_layer/storage/storage_configuration.h" -#include "chrome/browser/policy/messaging_layer/util/status.h" -#include "chrome/browser/policy/messaging_layer/util/statusor.h" -#include "components/policy/proto/record.pb.h" +#include "components/reporting/encryption/test_encryption_module.h" +#include "components/reporting/proto/record.pb.h" +#include "components/reporting/storage/resources/resource_interface.h" +#include "components/reporting/storage/storage_configuration.h" +#include "components/reporting/util/status.h" +#include "components/reporting/util/statusor.h" #include "crypto/sha2.h" #include "testing/gmock/include/gmock/gmock.h" #include "testing/gtest/include/gtest/gtest.h"
diff --git a/chrome/browser/policy/messaging_layer/storage/storage_unittest.cc b/components/reporting/storage/storage_unittest.cc similarity index 97% rename from chrome/browser/policy/messaging_layer/storage/storage_unittest.cc rename to components/reporting/storage/storage_unittest.cc index f003713..cd1c646 100644 --- a/chrome/browser/policy/messaging_layer/storage/storage_unittest.cc +++ b/components/reporting/storage/storage_unittest.cc
@@ -2,7 +2,7 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#include "chrome/browser/policy/messaging_layer/storage/storage.h" +#include "components/reporting/storage/storage.h" #include <cstdint> #include <tuple> @@ -15,16 +15,16 @@ #include "base/strings/string_number_conversions.h" #include "base/test/scoped_feature_list.h" #include "base/test/task_environment.h" -#include "chrome/browser/policy/messaging_layer/encryption/decryption.h" -#include "chrome/browser/policy/messaging_layer/encryption/encryption.h" -#include "chrome/browser/policy/messaging_layer/encryption/test_encryption_module.h" -#include "chrome/browser/policy/messaging_layer/storage/resources/resource_interface.h" -#include "chrome/browser/policy/messaging_layer/storage/storage_configuration.h" -#include "chrome/browser/policy/messaging_layer/util/status.h" -#include "chrome/browser/policy/messaging_layer/util/status_macros.h" -#include "chrome/browser/policy/messaging_layer/util/statusor.h" -#include "components/policy/proto/record.pb.h" -#include "components/policy/proto/record_constants.pb.h" +#include "components/reporting/encryption/decryption.h" +#include "components/reporting/encryption/encryption.h" +#include "components/reporting/encryption/test_encryption_module.h" +#include "components/reporting/proto/record.pb.h" +#include "components/reporting/proto/record_constants.pb.h" +#include "components/reporting/storage/resources/resource_interface.h" +#include "components/reporting/storage/storage_configuration.h" +#include "components/reporting/util/status.h" +#include "components/reporting/util/status_macros.h" +#include "components/reporting/util/statusor.h" #include "crypto/sha2.h" #include "testing/gmock/include/gmock/gmock.h" #include "testing/gtest/include/gtest/gtest.h"
diff --git a/chrome/browser/policy/messaging_layer/storage/test_storage_module.cc b/components/reporting/storage/test_storage_module.cc similarity index 82% rename from chrome/browser/policy/messaging_layer/storage/test_storage_module.cc rename to components/reporting/storage/test_storage_module.cc index f27f17d6..8ea9fd7 100644 --- a/chrome/browser/policy/messaging_layer/storage/test_storage_module.cc +++ b/components/reporting/storage/test_storage_module.cc
@@ -2,14 +2,14 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#include "chrome/browser/policy/messaging_layer/storage/test_storage_module.h" +#include "components/reporting/storage/test_storage_module.h" #include <utility> #include "base/callback.h" -#include "chrome/browser/policy/messaging_layer/public/report_queue.h" -#include "components/policy/proto/record.pb.h" -#include "components/policy/proto/record_constants.pb.h" +#include "components/reporting/proto/record.pb.h" +#include "components/reporting/proto/record_constants.pb.h" +#include "components/reporting/storage/storage_module.h" #include "testing/gmock/include/gmock/gmock.h" #include "testing/gtest/include/gtest/gtest.h"
diff --git a/chrome/browser/policy/messaging_layer/storage/test_storage_module.h b/components/reporting/storage/test_storage_module.h similarity index 77% rename from chrome/browser/policy/messaging_layer/storage/test_storage_module.h rename to components/reporting/storage/test_storage_module.h index 94b6e188..51c1e47 100644 --- a/chrome/browser/policy/messaging_layer/storage/test_storage_module.h +++ b/components/reporting/storage/test_storage_module.h
@@ -2,16 +2,16 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#ifndef CHROME_BROWSER_POLICY_MESSAGING_LAYER_STORAGE_TEST_STORAGE_MODULE_H_ -#define CHROME_BROWSER_POLICY_MESSAGING_LAYER_STORAGE_TEST_STORAGE_MODULE_H_ +#ifndef COMPONENTS_REPORTING_STORAGE_TEST_STORAGE_MODULE_H_ +#define COMPONENTS_REPORTING_STORAGE_TEST_STORAGE_MODULE_H_ #include <utility> #include "base/callback.h" #include "base/optional.h" -#include "chrome/browser/policy/messaging_layer/public/report_queue.h" -#include "components/policy/proto/record.pb.h" -#include "components/policy/proto/record_constants.pb.h" +#include "components/reporting/proto/record.pb.h" +#include "components/reporting/proto/record_constants.pb.h" +#include "components/reporting/storage/storage_module.h" #include "testing/gmock/include/gmock/gmock.h" #include "testing/gtest/include/gtest/gtest.h" @@ -54,4 +54,4 @@ } // namespace test } // namespace reporting -#endif // CHROME_BROWSER_POLICY_MESSAGING_LAYER_STORAGE_TEST_STORAGE_MODULE_H_ +#endif // COMPONENTS_REPORTING_STORAGE_TEST_STORAGE_MODULE_H_
diff --git a/components/reporting/util/BUILD.gn b/components/reporting/util/BUILD.gn new file mode 100644 index 0000000..421347fd6 --- /dev/null +++ b/components/reporting/util/BUILD.gn
@@ -0,0 +1,92 @@ +# Copyright 2021 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("//build/config/features.gni") +import("//third_party/libprotobuf-mutator/fuzzable_proto_library.gni") +import("//third_party/protobuf/proto_library.gni") + +static_library("backoff_settings") { + sources = [ + "backoff_settings.cc", + "backoff_settings.h", + ] + + deps = [ "//net" ] +} + +source_set("shared_vector") { + sources = [ "shared_vector.h" ] + deps = [ + ":status", + "//base", + ] +} + +proto_library("status_proto") { + visibility = [ + "//chrome/browser:browser", + "//chrome/browser:test_support", + "//components/reporting/*", + ] + + sources = [ "status.proto" ] + + proto_out_dir = "components/reporting/util" +} + +static_library("status") { + sources = [ + "status.cc", + "status.h", + "statusor.cc", + "statusor.h", + ] + public_deps = [ ":status_proto" ] + deps = [ "//base" ] +} + +source_set("shared_queue") { + sources = [ "shared_queue.h" ] + deps = [ + ":status", + "//base", + ] +} + +source_set("status_macros") { + sources = [ "status_macros.h" ] + + deps = [ ":status" ] +} + +source_set("task_runner_context") { + sources = [ "task_runner_context.h" ] + + deps = [ "//base" ] +} + +# All unit tests are built as part of the //components:components_unittests +# target. +source_set("unit_tests") { + testonly = true + sources = [ + "shared_queue_unittest.cc", + "shared_vector_unittest.cc", + "status_macros_unittest.cc", + "status_unittest.cc", + "statusor_unittest.cc", + ] + deps = [ + ":shared_queue", + ":shared_vector", + ":status", + ":status_macros", + ":status_proto", + ":task_runner_context", + "//base", + "//base/test:test_support", + "//testing/gmock", + "//testing/gtest", + ] +}
diff --git a/components/reporting/util/DEPS b/components/reporting/util/DEPS new file mode 100644 index 0000000..68bee72 --- /dev/null +++ b/components/reporting/util/DEPS
@@ -0,0 +1,4 @@ +include_rules = [ + "+base", + "+net/base/backoff_entry.h", +]
diff --git a/chrome/browser/policy/messaging_layer/util/backoff_settings.cc b/components/reporting/util/backoff_settings.cc similarity index 93% rename from chrome/browser/policy/messaging_layer/util/backoff_settings.cc rename to components/reporting/util/backoff_settings.cc index 2e8040f5..adbd62b 100644 --- a/chrome/browser/policy/messaging_layer/util/backoff_settings.cc +++ b/components/reporting/util/backoff_settings.cc
@@ -2,7 +2,7 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#include "chrome/browser/policy/messaging_layer/util/backoff_settings.h" +#include "components/reporting/util/backoff_settings.h" #include <memory>
diff --git a/chrome/browser/policy/messaging_layer/util/backoff_settings.h b/components/reporting/util/backoff_settings.h similarity index 72% rename from chrome/browser/policy/messaging_layer/util/backoff_settings.h rename to components/reporting/util/backoff_settings.h index dc3560b..5facb24f 100644 --- a/chrome/browser/policy/messaging_layer/util/backoff_settings.h +++ b/components/reporting/util/backoff_settings.h
@@ -2,8 +2,8 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#ifndef CHROME_BROWSER_POLICY_MESSAGING_LAYER_UTIL_BACKOFF_SETTINGS_H_ -#define CHROME_BROWSER_POLICY_MESSAGING_LAYER_UTIL_BACKOFF_SETTINGS_H_ +#ifndef COMPONENTS_REPORTING_UTIL_BACKOFF_SETTINGS_H_ +#define COMPONENTS_REPORTING_UTIL_BACKOFF_SETTINGS_H_ #include <memory> @@ -19,4 +19,4 @@ } // namespace reporting -#endif // CHROME_BROWSER_POLICY_MESSAGING_LAYER_UTIL_BACKOFF_SETTINGS_H_ +#endif // COMPONENTS_REPORTING_UTIL_BACKOFF_SETTINGS_H_
diff --git a/chrome/browser/policy/messaging_layer/util/shared_queue.h b/components/reporting/util/shared_queue.h similarity index 90% rename from chrome/browser/policy/messaging_layer/util/shared_queue.h rename to components/reporting/util/shared_queue.h index 6738062..923b2e7 100644 --- a/chrome/browser/policy/messaging_layer/util/shared_queue.h +++ b/components/reporting/util/shared_queue.h
@@ -2,8 +2,8 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#ifndef CHROME_BROWSER_POLICY_MESSAGING_LAYER_UTIL_SHARED_QUEUE_H_ -#define CHROME_BROWSER_POLICY_MESSAGING_LAYER_UTIL_SHARED_QUEUE_H_ +#ifndef COMPONENTS_REPORTING_UTIL_SHARED_QUEUE_H_ +#define COMPONENTS_REPORTING_UTIL_SHARED_QUEUE_H_ #include <utility> @@ -12,8 +12,8 @@ #include "base/sequenced_task_runner.h" #include "base/task/task_traits.h" #include "base/task/thread_pool.h" -#include "chrome/browser/policy/messaging_layer/util/status.h" -#include "chrome/browser/policy/messaging_layer/util/statusor.h" +#include "components/reporting/util/status.h" +#include "components/reporting/util/statusor.h" namespace reporting { @@ -96,4 +96,4 @@ } // namespace reporting -#endif // CHROME_BROWSER_POLICY_MESSAGING_LAYER_UTIL_SHARED_QUEUE_H_ +#endif // COMPONENTS_REPORTING_UTIL_SHARED_QUEUE_H_
diff --git a/chrome/browser/policy/messaging_layer/util/shared_queue_unittest.cc b/components/reporting/util/shared_queue_unittest.cc similarity index 95% rename from chrome/browser/policy/messaging_layer/util/shared_queue_unittest.cc rename to components/reporting/util/shared_queue_unittest.cc index db09bee..b0a3a3d 100644 --- a/chrome/browser/policy/messaging_layer/util/shared_queue_unittest.cc +++ b/components/reporting/util/shared_queue_unittest.cc
@@ -2,7 +2,7 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#include "chrome/browser/policy/messaging_layer/util/shared_queue.h" +#include "components/reporting/util/shared_queue.h" #include "base/callback_helpers.h" #include "base/sequenced_task_runner.h" @@ -10,8 +10,8 @@ #include "base/task/task_traits.h" #include "base/task/thread_pool.h" #include "base/test/task_environment.h" -#include "chrome/browser/policy/messaging_layer/util/status.h" -#include "chrome/browser/policy/messaging_layer/util/statusor.h" +#include "components/reporting/util/status.h" +#include "components/reporting/util/statusor.h" #include "testing/gtest/include/gtest/gtest.h"
diff --git a/chrome/browser/policy/messaging_layer/util/shared_vector.h b/components/reporting/util/shared_vector.h similarity index 95% rename from chrome/browser/policy/messaging_layer/util/shared_vector.h rename to components/reporting/util/shared_vector.h index 94bd699..9f86509 100644 --- a/chrome/browser/policy/messaging_layer/util/shared_vector.h +++ b/components/reporting/util/shared_vector.h
@@ -2,8 +2,8 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#ifndef CHROME_BROWSER_POLICY_MESSAGING_LAYER_UTIL_SHARED_VECTOR_H_ -#define CHROME_BROWSER_POLICY_MESSAGING_LAYER_UTIL_SHARED_VECTOR_H_ +#ifndef COMPONENTS_REPORTING_UTIL_SHARED_VECTOR_H_ +#define COMPONENTS_REPORTING_UTIL_SHARED_VECTOR_H_ #include <utility> @@ -16,8 +16,8 @@ #include "base/sequenced_task_runner.h" #include "base/task/task_traits.h" #include "base/task/thread_pool.h" -#include "chrome/browser/policy/messaging_layer/util/status.h" -#include "chrome/browser/policy/messaging_layer/util/statusor.h" +#include "components/reporting/util/status.h" +#include "components/reporting/util/statusor.h" namespace reporting { @@ -196,4 +196,4 @@ } // namespace reporting -#endif // CHROME_BROWSER_POLICY_MESSAGING_LAYER_UTIL_SHARED_VECTOR_H_ +#endif // COMPONENTS_REPORTING_UTIL_SHARED_VECTOR_H_
diff --git a/chrome/browser/policy/messaging_layer/util/shared_vector_unittest.cc b/components/reporting/util/shared_vector_unittest.cc similarity index 98% rename from chrome/browser/policy/messaging_layer/util/shared_vector_unittest.cc rename to components/reporting/util/shared_vector_unittest.cc index 7a3fbeb3..0e56e14 100644 --- a/chrome/browser/policy/messaging_layer/util/shared_vector_unittest.cc +++ b/components/reporting/util/shared_vector_unittest.cc
@@ -2,7 +2,7 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#include "chrome/browser/policy/messaging_layer/util/shared_vector.h" +#include "components/reporting/util/shared_vector.h" #include "base/bind.h" #include "base/callback.h"
diff --git a/chrome/browser/policy/messaging_layer/util/status.cc b/components/reporting/util/status.cc similarity index 95% rename from chrome/browser/policy/messaging_layer/util/status.cc rename to components/reporting/util/status.cc index 5559374..418f1ef9 100644 --- a/chrome/browser/policy/messaging_layer/util/status.cc +++ b/components/reporting/util/status.cc
@@ -2,7 +2,7 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#include "chrome/browser/policy/messaging_layer/util/status.h" +#include "components/reporting/util/status.h" #include <stdio.h> #include <ostream> @@ -11,7 +11,7 @@ #include "base/no_destructor.h" #include "base/strings/strcat.h" -#include "chrome/browser/policy/messaging_layer/util/status.pb.h" +#include "components/reporting/util/status.pb.h" namespace reporting { namespace error {
diff --git a/chrome/browser/policy/messaging_layer/util/status.h b/components/reporting/util/status.h similarity index 90% rename from chrome/browser/policy/messaging_layer/util/status.h rename to components/reporting/util/status.h index 5c143c5..c0a000d 100644 --- a/chrome/browser/policy/messaging_layer/util/status.h +++ b/components/reporting/util/status.h
@@ -2,8 +2,8 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#ifndef CHROME_BROWSER_POLICY_MESSAGING_LAYER_UTIL_STATUS_H_ -#define CHROME_BROWSER_POLICY_MESSAGING_LAYER_UTIL_STATUS_H_ +#ifndef COMPONENTS_REPORTING_UTIL_STATUS_H_ +#define COMPONENTS_REPORTING_UTIL_STATUS_H_ #include <cstdint> #include <iosfwd> @@ -11,7 +11,7 @@ #include "base/compiler_specific.h" #include "base/strings/string_piece.h" -#include "chrome/browser/policy/messaging_layer/util/status.pb.h" +#include "components/reporting/util/status.pb.h" namespace reporting { namespace error { @@ -90,4 +90,4 @@ } // namespace reporting -#endif // CHROME_BROWSER_POLICY_MESSAGING_LAYER_UTIL_STATUS_H_ +#endif // COMPONENTS_REPORTING_UTIL_STATUS_H_
diff --git a/chrome/browser/policy/messaging_layer/util/status.proto b/components/reporting/util/status.proto similarity index 100% rename from chrome/browser/policy/messaging_layer/util/status.proto rename to components/reporting/util/status.proto
diff --git a/chrome/browser/policy/messaging_layer/util/status_macros.h b/components/reporting/util/status_macros.h similarity index 90% rename from chrome/browser/policy/messaging_layer/util/status_macros.h rename to components/reporting/util/status_macros.h index 36e03f67..6830b88 100644 --- a/chrome/browser/policy/messaging_layer/util/status_macros.h +++ b/components/reporting/util/status_macros.h
@@ -2,11 +2,11 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#ifndef CHROME_BROWSER_POLICY_MESSAGING_LAYER_UTIL_STATUS_MACROS_H_ -#define CHROME_BROWSER_POLICY_MESSAGING_LAYER_UTIL_STATUS_MACROS_H_ +#ifndef COMPONENTS_REPORTING_UTIL_STATUS_MACROS_H_ +#define COMPONENTS_REPORTING_UTIL_STATUS_MACROS_H_ -#include "chrome/browser/policy/messaging_layer/util/status.h" -#include "chrome/browser/policy/messaging_layer/util/statusor.h" +#include "components/reporting/util/status.h" +#include "components/reporting/util/statusor.h" namespace reporting { @@ -78,4 +78,4 @@ } // namespace reporting -#endif // CHROME_BROWSER_POLICY_MESSAGING_LAYER_UTIL_STATUS_MACROS_H_ +#endif // COMPONENTS_REPORTING_UTIL_STATUS_MACROS_H_
diff --git a/chrome/browser/policy/messaging_layer/util/status_macros_unittest.cc b/components/reporting/util/status_macros_unittest.cc similarity index 96% rename from chrome/browser/policy/messaging_layer/util/status_macros_unittest.cc rename to components/reporting/util/status_macros_unittest.cc index 1c9c8c2..7a6b321 100644 --- a/chrome/browser/policy/messaging_layer/util/status_macros_unittest.cc +++ b/components/reporting/util/status_macros_unittest.cc
@@ -2,14 +2,14 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#include "chrome/browser/policy/messaging_layer/util/status_macros.h" +#include "components/reporting/util/status_macros.h" #include <stdio.h> #include "base/bind.h" #include "base/callback.h" -#include "chrome/browser/policy/messaging_layer/util/status.h" -#include "chrome/browser/policy/messaging_layer/util/statusor.h" +#include "components/reporting/util/status.h" +#include "components/reporting/util/statusor.h" #include "testing/gtest/include/gtest/gtest.h" namespace reporting {
diff --git a/chrome/browser/policy/messaging_layer/util/status_unittest.cc b/components/reporting/util/status_unittest.cc similarity index 97% rename from chrome/browser/policy/messaging_layer/util/status_unittest.cc rename to components/reporting/util/status_unittest.cc index 278e61c..2ba3b3d 100644 --- a/chrome/browser/policy/messaging_layer/util/status_unittest.cc +++ b/components/reporting/util/status_unittest.cc
@@ -2,12 +2,12 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#include "chrome/browser/policy/messaging_layer/util/status.h" +#include "components/reporting/util/status.h" #include <stdio.h> #include "base/logging.h" -#include "chrome/browser/policy/messaging_layer/util/status.pb.h" +#include "components/reporting/util/status.pb.h" #include "testing/gmock/include/gmock/gmock.h" #include "testing/gtest/include/gtest/gtest.h"
diff --git a/chrome/browser/policy/messaging_layer/util/statusor.cc b/components/reporting/util/statusor.cc similarity index 93% rename from chrome/browser/policy/messaging_layer/util/statusor.cc rename to components/reporting/util/statusor.cc index 0d08c7c..5bf2e3f 100644 --- a/chrome/browser/policy/messaging_layer/util/statusor.cc +++ b/components/reporting/util/statusor.cc
@@ -2,7 +2,7 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#include "chrome/browser/policy/messaging_layer/util/statusor.h" +#include "components/reporting/util/statusor.h" #include "base/logging.h" #include "base/no_destructor.h"
diff --git a/chrome/browser/policy/messaging_layer/util/statusor.h b/components/reporting/util/statusor.h similarity index 97% rename from chrome/browser/policy/messaging_layer/util/statusor.h rename to components/reporting/util/statusor.h index 0f81dc03..5044da9 100644 --- a/chrome/browser/policy/messaging_layer/util/statusor.h +++ b/components/reporting/util/statusor.h
@@ -53,8 +53,8 @@ // } // -#ifndef CHROME_BROWSER_POLICY_MESSAGING_LAYER_UTIL_STATUSOR_H_ -#define CHROME_BROWSER_POLICY_MESSAGING_LAYER_UTIL_STATUSOR_H_ +#ifndef COMPONENTS_REPORTING_UTIL_STATUSOR_H_ +#define COMPONENTS_REPORTING_UTIL_STATUSOR_H_ #include <new> #include <string> @@ -64,7 +64,7 @@ #include "base/compiler_specific.h" #include "base/logging.h" #include "base/optional.h" -#include "chrome/browser/policy/messaging_layer/util/status.h" +#include "components/reporting/util/status.h" namespace reporting { @@ -304,4 +304,4 @@ } // namespace reporting -#endif // CHROME_BROWSER_POLICY_MESSAGING_LAYER_UTIL_STATUSOR_H_ +#endif // COMPONENTS_REPORTING_UTIL_STATUSOR_H_
diff --git a/chrome/browser/policy/messaging_layer/util/statusor_unittest.cc b/components/reporting/util/statusor_unittest.cc similarity index 96% rename from chrome/browser/policy/messaging_layer/util/statusor_unittest.cc rename to components/reporting/util/statusor_unittest.cc index 948af2f5..38736fe 100644 --- a/chrome/browser/policy/messaging_layer/util/statusor_unittest.cc +++ b/components/reporting/util/statusor_unittest.cc
@@ -2,7 +2,7 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#include "chrome/browser/policy/messaging_layer/util/statusor.h" +#include "components/reporting/util/statusor.h" #include <errno.h> #include <algorithm> @@ -13,6 +13,7 @@ #include "base/memory/ref_counted.h" #include "base/memory/scoped_refptr.h" +#include "testing/gtest/include/gtest/gtest-death-test.h" #include "testing/gtest/include/gtest/gtest.h" namespace reporting { @@ -275,11 +276,11 @@ TEST(StatusOr, TestAbort) { StatusOr<int> thing1(Status(error::UNKNOWN, "Unknown")); int v1; - EXPECT_DEATH(v1 = thing1.ValueOrDie(), ""); + EXPECT_DEATH_IF_SUPPORTED(v1 = thing1.ValueOrDie(), ""); StatusOr<std::unique_ptr<int>> thing2(Status(error::UNKNOWN, "Unknown")); std::unique_ptr<int> v2; - EXPECT_DEATH(v2 = std::move(thing2.ValueOrDie()), ""); + EXPECT_DEATH_IF_SUPPORTED(v2 = std::move(thing2.ValueOrDie()), ""); } } // namespace } // namespace reporting
diff --git a/chrome/browser/policy/messaging_layer/util/task_runner_context.h b/components/reporting/util/task_runner_context.h similarity index 95% rename from chrome/browser/policy/messaging_layer/util/task_runner_context.h rename to components/reporting/util/task_runner_context.h index 40de7ef..8c97ad1f 100644 --- a/chrome/browser/policy/messaging_layer/util/task_runner_context.h +++ b/components/reporting/util/task_runner_context.h
@@ -2,8 +2,8 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#ifndef CHROME_BROWSER_POLICY_MESSAGING_LAYER_UTIL_TASK_RUNNER_CONTEXT_H_ -#define CHROME_BROWSER_POLICY_MESSAGING_LAYER_UTIL_TASK_RUNNER_CONTEXT_H_ +#ifndef COMPONENTS_REPORTING_UTIL_TASK_RUNNER_CONTEXT_H_ +#define COMPONENTS_REPORTING_UTIL_TASK_RUNNER_CONTEXT_H_ #include <utility> @@ -172,4 +172,4 @@ } // namespace reporting -#endif // CHROME_BROWSER_POLICY_MESSAGING_LAYER_UTIL_TASK_RUNNER_CONTEXT_H_ +#endif // COMPONENTS_REPORTING_UTIL_TASK_RUNNER_CONTEXT_H_
diff --git a/chrome/browser/policy/messaging_layer/util/task_runner_context_unittest.cc b/components/reporting/util/task_runner_context_unittest.cc similarity index 98% rename from chrome/browser/policy/messaging_layer/util/task_runner_context_unittest.cc rename to components/reporting/util/task_runner_context_unittest.cc index 695395a9..ff93922 100644 --- a/chrome/browser/policy/messaging_layer/util/task_runner_context_unittest.cc +++ b/components/reporting/util/task_runner_context_unittest.cc
@@ -2,7 +2,7 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#include "chrome/browser/policy/messaging_layer/util/task_runner_context.h" +#include "components/reporting/util/task_runner_context.h" #include <functional> #include <memory> @@ -16,8 +16,8 @@ #include "base/synchronization/waitable_event.h" #include "base/test/task_environment.h" #include "base/threading/sequenced_task_runner_handle.h" -#include "chrome/browser/policy/messaging_layer/util/status.h" -#include "chrome/browser/policy/messaging_layer/util/statusor.h" +#include "components/reporting/util/status.h" +#include "components/reporting/util/statusor.h" #include "testing/gmock/include/gmock/gmock.h" #include "testing/gtest/include/gtest/gtest.h"
diff --git a/components/resources/OWNERS b/components/resources/OWNERS index 2696822..2caca1ff 100644 --- a/components/resources/OWNERS +++ b/components/resources/OWNERS
@@ -1,3 +1,4 @@ +per-file about_ui_resources.grdp=file://ui/webui/PLATFORM_OWNERS per-file android_system_error_page_resources.grdp=file://components/android_system_error_page/OWNERS per-file autofill*=file://components/autofill/OWNERS per-file content_suggestions*=file://components/ntp_snippets/OWNERS
diff --git a/components/resources/about_ui_resources.grdp b/components/resources/about_ui_resources.grdp index ad9aefc..236e09f 100644 --- a/components/resources/about_ui_resources.grdp +++ b/components/resources/about_ui_resources.grdp
@@ -1,5 +1,5 @@ <?xml version="1.0" encoding="utf-8"?> <grit-part> <include name="IDR_ABOUT_UI_CREDITS_HTML" file="${about_credits_file}" compress="brotli" use_base_dir="false" type="BINDATA" /> - <include name="IDR_ABOUT_UI_CREDITS_JS" file="../about_ui/resources/about_credits.js" type="BINDATA" compress="brotli" /> + <include name="IDR_ABOUT_UI_CREDITS_JS" file="../about_ui/resources/about_credits.js" preprocess="true" type="BINDATA" compress="brotli" /> </grit-part>
diff --git a/components/safe_browsing/content/base_blocking_page.cc b/components/safe_browsing/content/base_blocking_page.cc index c19ec22..9b70a148 100644 --- a/components/safe_browsing/content/base_blocking_page.cc +++ b/components/safe_browsing/content/base_blocking_page.cc
@@ -182,8 +182,6 @@ std::string BaseBlockingPage::GetExtraMetricsSuffix( const UnsafeResourceList& unsafe_resources) { switch (unsafe_resources[0].threat_source) { - case safe_browsing::ThreatSource::DATA_SAVER: - return "from_data_saver"; case safe_browsing::ThreatSource::REMOTE: case safe_browsing::ThreatSource::LOCAL_PVER3: // REMOTE and LOCAL_PVER3 can be distinguished in the logs
diff --git a/components/safe_browsing/content/browser/client_side_detection_service.cc b/components/safe_browsing/content/browser/client_side_detection_service.cc index 39cef21..4b49f4f 100644 --- a/components/safe_browsing/content/browser/client_side_detection_service.cc +++ b/components/safe_browsing/content/browser/client_side_detection_service.cc
@@ -292,7 +292,7 @@ client_phishing_reports_[loader_ptr] = std::move(info); // Record that we made a request - phishing_report_times_.push(base::Time::Now()); + AddPhishingReport(base::Time::Now()); } void ClientSideDetectionService::HandlePhishingVerdict( @@ -380,21 +380,40 @@ } int ClientSideDetectionService::GetPhishingNumReports() { - return GetNumReports(&phishing_report_times_); + return phishing_report_times_.size(); } -int ClientSideDetectionService::GetNumReports( - base::queue<base::Time>* report_times) { +void ClientSideDetectionService::AddPhishingReport(base::Time timestamp) { + phishing_report_times_.push_back(timestamp); + base::Time cutoff = base::Time::Now() - base::TimeDelta::FromDays(kReportsIntervalDays); // Erase items older than cutoff because we will never care about them again. - while (!report_times->empty() && report_times->front() < cutoff) { - report_times->pop(); + while (!phishing_report_times_.empty() && + phishing_report_times_.front() < cutoff) { + phishing_report_times_.pop_front(); } - // Return the number of elements that are above the cutoff. - return report_times->size(); + if (!delegate_ || !delegate_->GetPrefs()) + return; + + base::ListValue time_list; + for (const base::Time& timestamp : phishing_report_times_) + time_list.Append(base::Value(timestamp.ToDoubleT())); + delegate_->GetPrefs()->Set(prefs::kSafeBrowsingCsdPingTimestamps, time_list); +} + +void ClientSideDetectionService::LoadPhishingReportTimesFromPrefs() { + if (!delegate_ || !delegate_->GetPrefs()) + return; + + phishing_report_times_.clear(); + for (const base::Value& timestamp : + *delegate_->GetPrefs()->GetList(prefs::kSafeBrowsingCsdPingTimestamps)) { + phishing_report_times_.push_back( + base::Time::FromDoubleT(timestamp.GetDouble())); + } } // static
diff --git a/components/safe_browsing/content/browser/client_side_detection_service.h b/components/safe_browsing/content/browser/client_side_detection_service.h index 782173b1..6a468674 100644 --- a/components/safe_browsing/content/browser/client_side_detection_service.h +++ b/components/safe_browsing/content/browser/client_side_detection_service.h
@@ -201,9 +201,12 @@ // Get the number of phishing reports that we have sent over kReportsInterval. int GetPhishingNumReports(); - // Get the number of reports that we have sent over kReportsInterval, and - // trims off the old elements. - int GetNumReports(base::queue<base::Time>* report_times); + // Adds a phishing report to |phishing_report_times_| and stores the result in + // prefs. + void AddPhishingReport(base::Time timestamp); + + // Populates |phishing_report_times_| with the data stored in local prefs. + void LoadPhishingReportTimesFromPrefs(); // Returns the URL that will be used for phishing requests. static GURL GetClientReportUrl(const std::string& report_url); @@ -235,8 +238,7 @@ // Timestamp of when we sent a phishing request. Used to limit the number // of phishing requests that we send in a day. - // TODO(gcasto): Serialize this so that it doesn't reset on browser restart. - base::queue<base::Time> phishing_report_times_; + std::deque<base::Time> phishing_report_times_; // The URLLoaderFactory we use to issue network requests. scoped_refptr<network::SharedURLLoaderFactory> url_loader_factory_;
diff --git a/components/safe_browsing/content/browser/threat_details.cc b/components/safe_browsing/content/browser/threat_details.cc index 9d747d5..a6eecd9 100644 --- a/components/safe_browsing/content/browser/threat_details.cc +++ b/components/safe_browsing/content/browser/threat_details.cc
@@ -181,8 +181,6 @@ CSBRR::SafeBrowsingUrlApiType GetUrlApiTypeForThreatSource( safe_browsing::ThreatSource source) { switch (source) { - case safe_browsing::ThreatSource::DATA_SAVER: - return CSBRR::FLYWHEEL; case safe_browsing::ThreatSource::LOCAL_PVER3: return CSBRR::PVER3_NATIVE; case safe_browsing::ThreatSource::LOCAL_PVER4: @@ -194,9 +192,8 @@ case safe_browsing::ThreatSource::UNKNOWN: case safe_browsing::ThreatSource::CLIENT_SIDE_DETECTION: case safe_browsing::ThreatSource::PASSWORD_PROTECTION_SERVICE: - break; + return CSBRR::SAFE_BROWSING_URL_API_TYPE_UNSPECIFIED; } - return CSBRR::SAFE_BROWSING_URL_API_TYPE_UNSPECIFIED; } void TrimElements(const std::set<int> target_ids,
diff --git a/components/safe_browsing/core/common/safe_browsing_prefs.cc b/components/safe_browsing/core/common/safe_browsing_prefs.cc index 20ad038..7d972c3 100644 --- a/components/safe_browsing/core/common/safe_browsing_prefs.cc +++ b/components/safe_browsing/core/common/safe_browsing_prefs.cc
@@ -67,6 +67,8 @@ } // namespace namespace prefs { +const char kSafeBrowsingCsdPingTimestamps[] = + "safebrowsing.csd_ping_timestamps"; const char kSafeBrowsingEnabled[] = "safebrowsing.enabled"; const char kSafeBrowsingEnhanced[] = "safebrowsing.enhanced"; const char kSafeBrowsingEnterpriseRealTimeUrlCheckMode[] = @@ -187,6 +189,7 @@ } void RegisterProfilePrefs(PrefRegistrySimple* registry) { + registry->RegisterListPref(prefs::kSafeBrowsingCsdPingTimestamps); registry->RegisterBooleanPref(prefs::kSafeBrowsingScoutReportingEnabled, false); registry->RegisterBooleanPref(
diff --git a/components/safe_browsing/core/common/safe_browsing_prefs.h b/components/safe_browsing/core/common/safe_browsing_prefs.h index 765312d..c89d9d6 100644 --- a/components/safe_browsing/core/common/safe_browsing_prefs.h +++ b/components/safe_browsing/core/common/safe_browsing_prefs.h
@@ -19,6 +19,9 @@ class GURL; namespace prefs { +// A list of times at which CSD pings were sent. +extern const char kSafeBrowsingCsdPingTimestamps[]; + // Boolean that is true when SafeBrowsing is enabled. extern const char kSafeBrowsingEnabled[];
diff --git a/components/safe_browsing/core/db/hit_report.h b/components/safe_browsing/core/db/hit_report.h index d03c3413..d2ee5bc 100644 --- a/components/safe_browsing/core/db/hit_report.h +++ b/components/safe_browsing/core/db/hit_report.h
@@ -16,7 +16,6 @@ // What service classified this threat as unsafe. enum class ThreatSource { UNKNOWN, - DATA_SAVER, // From the Data Reduction service. LOCAL_PVER3, // From LocalSafeBrowsingDatabaseManager, protocol v3 LOCAL_PVER4, // From V4LocalDatabaseManager, protocol v4 REMOTE, // From RemoteSafeBrowsingDatabaseManager
diff --git a/components/safe_browsing/core/ping_manager.cc b/components/safe_browsing/core/ping_manager.cc index 86e9eeb..92a12b7 100644 --- a/components/safe_browsing/core/ping_manager.cc +++ b/components/safe_browsing/core/ping_manager.cc
@@ -168,9 +168,6 @@ std::string threat_source = "none"; switch (hit_report.threat_source) { - case safe_browsing::ThreatSource::DATA_SAVER: - threat_source = "ds"; - break; case safe_browsing::ThreatSource::REMOTE: threat_source = "rem"; break;
diff --git a/components/safe_browsing/core/ping_manager_unittest.cc b/components/safe_browsing/core/ping_manager_unittest.cc index a454d09..0d30c600 100644 --- a/components/safe_browsing/core/ping_manager_unittest.cc +++ b/components/safe_browsing/core/ping_manager_unittest.cc
@@ -71,7 +71,7 @@ { HitReport hp(base_hp); hp.threat_type = SB_THREAT_TYPE_URL_PHISHING; - hp.threat_source = ThreatSource::DATA_SAVER; + hp.threat_source = ThreatSource::LOCAL_PVER4; hp.is_subresource = false; hp.extended_reporting_level = SBER_LEVEL_LEGACY; hp.is_metrics_reporting_active = true; @@ -83,14 +83,14 @@ "&ext=1&evts=phishblhit&" "evtd=http%3A%2F%2Fmalicious.url.com%2F&" "evtr=http%3A%2F%2Fpage.url.com%2F&evhr=http%3A%2F%2Freferrer." - "url.com%2F&evtb=0&src=ds&m=1", + "url.com%2F&evtb=0&src=l4&m=1", ping_manager()->SafeBrowsingHitUrl(hp).spec()); } { HitReport hp(base_hp); hp.threat_type = SB_THREAT_TYPE_URL_PHISHING; - hp.threat_source = ThreatSource::DATA_SAVER; + hp.threat_source = ThreatSource::LOCAL_PVER4; hp.is_subresource = false; hp.extended_reporting_level = SBER_LEVEL_SCOUT; hp.is_metrics_reporting_active = true; @@ -102,7 +102,7 @@ "&ext=2&enh=1&evts=phishblhit&" "evtd=http%3A%2F%2Fmalicious.url.com%2F&" "evtr=http%3A%2F%2Fpage.url.com%2F&evhr=http%3A%2F%2Freferrer." - "url.com%2F&evtb=0&src=ds&m=1", + "url.com%2F&evtb=0&src=l4&m=1", ping_manager()->SafeBrowsingHitUrl(hp).spec()); }
diff --git a/components/safe_browsing/core/proto/csd.proto b/components/safe_browsing/core/proto/csd.proto index 02f0d5a..11d3589 100644 --- a/components/safe_browsing/core/proto/csd.proto +++ b/components/safe_browsing/core/proto/csd.proto
@@ -1348,7 +1348,8 @@ // https://developer.android.com/training/safetynet/safebrowsing.html ANDROID_SAFETYNET = 3; // Flywheel (data compression service). - FLYWHEEL = 4; + // Deprecated as of 2021-1. Data saver has been completely turned down. + FLYWHEEL = 4 [deprecated = true]; // Safe Browsing real time API. REAL_TIME = 5; }
diff --git a/components/search_engines/default_search_manager.cc b/components/search_engines/default_search_manager.cc index 82f5878..28c6f03f 100644 --- a/components/search_engines/default_search_manager.cc +++ b/components/search_engines/default_search_manager.cc
@@ -87,12 +87,12 @@ pref_change_registrar_.Init(pref_service_); pref_change_registrar_.Add( kDefaultSearchProviderDataPrefName, - base::Bind(&DefaultSearchManager::OnDefaultSearchPrefChanged, - base::Unretained(this))); + base::BindRepeating(&DefaultSearchManager::OnDefaultSearchPrefChanged, + base::Unretained(this))); pref_change_registrar_.Add( prefs::kSearchProviderOverrides, - base::Bind(&DefaultSearchManager::OnOverridesPrefChanged, - base::Unretained(this))); + base::BindRepeating(&DefaultSearchManager::OnOverridesPrefChanged, + base::Unretained(this))); } LoadPrepopulatedDefaultSearch(); LoadDefaultSearchEngineFromPrefs();
diff --git a/components/search_engines/default_search_manager.h b/components/search_engines/default_search_manager.h index 5e4c6daa..8c3f400 100644 --- a/components/search_engines/default_search_manager.h +++ b/components/search_engines/default_search_manager.h
@@ -75,7 +75,8 @@ FROM_POLICY, }; - typedef base::Callback<void(const TemplateURLData*, Source)> ObserverCallback; + using ObserverCallback = + base::RepeatingCallback<void(const TemplateURLData*, Source)>; DefaultSearchManager(PrefService* pref_service, const ObserverCallback& change_observer);
diff --git a/components/search_engines/keyword_web_data_service.cc b/components/search_engines/keyword_web_data_service.cc index 265bbdd..4f2de437 100644 --- a/components/search_engines/keyword_web_data_service.cc +++ b/components/search_engines/keyword_web_data_service.cc
@@ -122,17 +122,17 @@ CommitQueuedOperations(); return wdbs_->ScheduleDBTaskWithResult( - FROM_HERE, base::Bind(&GetKeywordsImpl), consumer); + FROM_HERE, base::BindOnce(&GetKeywordsImpl), consumer); } void KeywordWebDataService::SetDefaultSearchProviderID(TemplateURLID id) { wdbs_->ScheduleDBTask(FROM_HERE, - base::Bind(&SetDefaultSearchProviderIDImpl, id)); + base::BindOnce(&SetDefaultSearchProviderIDImpl, id)); } void KeywordWebDataService::SetBuiltinKeywordVersion(int version) { wdbs_->ScheduleDBTask(FROM_HERE, - base::Bind(&SetBuiltinKeywordVersionImpl, version)); + base::BindOnce(&SetBuiltinKeywordVersionImpl, version)); } void KeywordWebDataService::ShutdownOnUISequence() { @@ -167,8 +167,9 @@ void KeywordWebDataService::CommitQueuedOperations() { if (!queued_keyword_operations_.empty()) { - wdbs_->ScheduleDBTask(FROM_HERE, base::Bind(&PerformKeywordOperationsImpl, - queued_keyword_operations_)); + wdbs_->ScheduleDBTask(FROM_HERE, + base::BindOnce(&PerformKeywordOperationsImpl, + queued_keyword_operations_)); queued_keyword_operations_.clear(); } timer_.Stop();
diff --git a/components/search_engines/template_url_service.cc b/components/search_engines/template_url_service.cc index bbc95e49..2af4aa1 100644 --- a/components/search_engines/template_url_service.cc +++ b/components/search_engines/template_url_service.cc
@@ -278,7 +278,7 @@ std::unique_ptr<SearchTermsData> search_terms_data, const scoped_refptr<KeywordWebDataService>& web_data_service, std::unique_ptr<TemplateURLServiceClient> client, - const base::Closure& dsp_change_callback) + const base::RepeatingClosure& dsp_change_callback) : prefs_(prefs), search_terms_data_(std::move(search_terms_data)), web_data_service_(web_data_service), @@ -563,12 +563,12 @@ void TemplateURLService::RemoveAutoGeneratedBetween(base::Time created_after, base::Time created_before) { - RemoveAutoGeneratedForUrlsBetween(base::Callback<bool(const GURL&)>(), - created_after, created_before); + RemoveAutoGeneratedForUrlsBetween(base::NullCallback(), created_after, + created_before); } void TemplateURLService::RemoveAutoGeneratedForUrlsBetween( - const base::Callback<bool(const GURL&)>& url_filter, + const base::RepeatingCallback<bool(const GURL&)>& url_filter, base::Time created_after, base::Time created_before) { Scoper scoper(this); @@ -1453,7 +1453,7 @@ pref_change_registrar_.Init(prefs_); pref_change_registrar_.Add( prefs::kSyncedDefaultSearchProviderGUID, - base::Bind( + base::BindRepeating( &TemplateURLService::OnSyncedDefaultSearchProviderGUIDChanged, base::Unretained(this))); }
diff --git a/components/search_engines/template_url_service.h b/components/search_engines/template_url_service.h index cdc5f5a..c4a56815b 100644 --- a/components/search_engines/template_url_service.h +++ b/components/search_engines/template_url_service.h
@@ -14,6 +14,7 @@ #include <utility> #include <vector> +#include "base/callback.h" #include "base/callback_list.h" #include "base/gtest_prod_util.h" #include "base/macros.h" @@ -225,7 +226,7 @@ // range and match |url_filter|. If |url_filter| is_null(), deletes all // auto-generated keywords in the range. void RemoveAutoGeneratedForUrlsBetween( - const base::Callback<bool(const GURL&)>& url_filter, + const base::RepeatingCallback<bool(const GURL&)>& url_filter, base::Time created_after, base::Time created_before);
diff --git a/components/translate/content/browser/translate_model_service.cc b/components/translate/content/browser/translate_model_service.cc index 410825f0..eaba528 100644 --- a/components/translate/content/browser/translate_model_service.cc +++ b/components/translate/content/browser/translate_model_service.cc
@@ -35,7 +35,8 @@ const scoped_refptr<base::SequencedTaskRunner>& background_task_runner) : opt_guide_(opt_guide), background_task_runner_(background_task_runner) { opt_guide_->AddObserverForOptimizationTargetModel( - optimization_guide::proto::OPTIMIZATION_TARGET_LANGUAGE_DETECTION, this); + optimization_guide::proto::OPTIMIZATION_TARGET_LANGUAGE_DETECTION, + /*model_metadata=*/base::nullopt, this); } TranslateModelService::~TranslateModelService() = default; @@ -48,6 +49,7 @@ void TranslateModelService::OnModelFileUpdated( optimization_guide::proto::OptimizationTarget optimization_target, + const base::Optional<optimization_guide::proto::Any>& model_metadata, const base::FilePath& file_path) { DCHECK_CURRENTLY_ON(content::BrowserThread::UI); if (optimization_target !=
diff --git a/components/translate/content/browser/translate_model_service.h b/components/translate/content/browser/translate_model_service.h index 2e2c889..0853a71 100644 --- a/components/translate/content/browser/translate_model_service.h +++ b/components/translate/content/browser/translate_model_service.h
@@ -41,6 +41,7 @@ // optimization_guide::OptimizationTargetModelObserver implementation: void OnModelFileUpdated( optimization_guide::proto::OptimizationTarget optimization_target, + const base::Optional<optimization_guide::proto::Any>& model_metadata, const base::FilePath& file_path) override; // Invokes |callback| with a language detection model file when it is
diff --git a/components/url_formatter/spoof_checks/idn_spoof_checker.cc b/components/url_formatter/spoof_checks/idn_spoof_checker.cc index 9a81860..c798cb4 100644 --- a/components/url_formatter/spoof_checks/idn_spoof_checker.cc +++ b/components/url_formatter/spoof_checks/idn_spoof_checker.cc
@@ -574,7 +574,10 @@ } Skeletons IDNSpoofChecker::GetSkeletons(base::StringPiece16 hostname) const { - return skeleton_generator_->GetSkeletons(hostname); + // skeleton_generator_ may be null if uspoof_open fails. It's unclear why this + // happens, see crbug.com/1169079. + return skeleton_generator_ ? skeleton_generator_->GetSkeletons(hostname) + : Skeletons(); } TopDomainEntry IDNSpoofChecker::LookupSkeletonInTopDomains(
diff --git a/content/browser/accessibility/accessibility_event_recorder.cc b/content/browser/accessibility/accessibility_event_recorder.cc index 1cbc0df..9bd490a 100644 --- a/content/browser/accessibility/accessibility_event_recorder.cc +++ b/content/browser/accessibility/accessibility_event_recorder.cc
@@ -14,8 +14,6 @@ BrowserAccessibilityManager* manager) : manager_(manager) {} -AccessibilityEventRecorder::~AccessibilityEventRecorder() = default; - #if !defined(OS_WIN) && !defined(OS_MAC) && !BUILDFLAG(USE_ATK) // static std::unique_ptr<AccessibilityEventRecorder> AccessibilityEventRecorder::Create( @@ -40,10 +38,4 @@ } #endif -void AccessibilityEventRecorder::OnEvent(const std::string& event) { - event_logs_.push_back(event); - if (callback_) - callback_.Run(event); -} - } // namespace content
diff --git a/content/browser/accessibility/accessibility_event_recorder.h b/content/browser/accessibility/accessibility_event_recorder.h index 41b9758..da7cafad 100644 --- a/content/browser/accessibility/accessibility_event_recorder.h +++ b/content/browser/accessibility/accessibility_event_recorder.h
@@ -9,18 +9,14 @@ #include <string> #include <vector> -#include "base/callback.h" -#include "base/callback_helpers.h" #include "base/macros.h" #include "base/process/process_handle.h" #include "content/common/content_export.h" +#include "ui/accessibility/platform/inspect/ax_event_recorder.h" #include "ui/accessibility/platform/inspect/ax_inspect.h" namespace content { -using AccessibilityEventCallback = - base::RepeatingCallback<void(const std::string&)>; - using ui::AXTreeSelector; class BrowserAccessibilityManager; @@ -40,7 +36,7 @@ // each platform does most of the work. // // As currently designed, there should only be one instance of this class. -class CONTENT_EXPORT AccessibilityEventRecorder { +class CONTENT_EXPORT AccessibilityEventRecorder : public ui::AXEventRecorder { public: // Construct the right platform-specific subclass. static std::unique_ptr<AccessibilityEventRecorder> Create( @@ -61,34 +57,11 @@ static std::vector<TestPass> GetTestPasses(); AccessibilityEventRecorder(BrowserAccessibilityManager* manager); - virtual ~AccessibilityEventRecorder(); - - void set_only_web_events(bool only_web_events) { - only_web_events_ = only_web_events; - } - - void ListenToEvents(AccessibilityEventCallback callback) { - callback_ = std::move(callback); - } - - void StopListeningToEvents() { callback_ = base::NullCallback(); } - - // Called to ensure the event recorder has finished recording async events. - virtual void FlushAsyncEvents() {} - - // Access the vector of human-readable event logs, one string per event. - const std::vector<std::string>& event_logs() { return event_logs_; } protected: - void OnEvent(const std::string& event); - BrowserAccessibilityManager* const manager_; - bool only_web_events_ = false; private: - std::vector<std::string> event_logs_; - AccessibilityEventCallback callback_; - DISALLOW_COPY_AND_ASSIGN(AccessibilityEventRecorder); };
diff --git a/content/browser/accessibility/dump_accessibility_events_browsertest.cc b/content/browser/accessibility/dump_accessibility_events_browsertest.cc index 8f932dc..55cdfe4e 100644 --- a/content/browser/accessibility/dump_accessibility_events_browsertest.cc +++ b/content/browser/accessibility/dump_accessibility_events_browsertest.cc
@@ -108,7 +108,7 @@ if (run_until.empty()) return true; - std::vector<std::string> event_logs = event_recorder.event_logs(); + std::vector<std::string> event_logs = event_recorder.EventLogs(); LOG(ERROR) << "=== IsRecordingComplete#2 Logs size=" << event_logs.size(); for (size_t i = 0; i < event_logs.size(); ++i) @@ -143,7 +143,7 @@ std::unique_ptr<AccessibilityEventRecorder> event_recorder = event_recorder_factory_( web_contents->GetRootBrowserAccessibilityManager(), pid, {}); - event_recorder->set_only_web_events(true); + event_recorder->SetOnlyWebEvents(true); waiter.reset(new AccessibilityNotificationWaiter( shell()->web_contents(), ui::kAXModeComplete, ax::mojom::Event::kNone)); @@ -188,7 +188,7 @@ // Dump the event logs, running them through any filters specified // in the HTML file. event_recorder->FlushAsyncEvents(); - std::vector<std::string> event_logs = event_recorder->event_logs(); + std::vector<std::string> event_logs = event_recorder->EventLogs(); // Sort the logs so that results are predictable. There are too many // nondeterministic things that affect the exact order of events fired,
diff --git a/content/browser/android/content_url_loader_factory.cc b/content/browser/android/content_url_loader_factory.cc index 3cf5a8e4..518dc8b 100644 --- a/content/browser/android/content_url_loader_factory.cc +++ b/content/browser/android/content_url_loader_factory.cc
@@ -177,9 +177,12 @@ net::ERR_REQUEST_RANGE_NOT_SATISFIABLE); } - mojo::DataPipe pipe(kDefaultContentUrlPipeSize); - if (!pipe.consumer_handle.is_valid()) + mojo::ScopedDataPipeProducerHandle producer_handle; + mojo::ScopedDataPipeConsumerHandle consumer_handle; + if (mojo::CreateDataPipe(kDefaultContentUrlPipeSize, producer_handle, + consumer_handle) != MOJO_RESULT_OK) { return CompleteWithFailure(std::move(client), net::ERR_FAILED); + } base::File file = base::OpenContentUriForRead(path); if (!file.IsValid()) { @@ -225,7 +228,7 @@ } client->OnReceiveResponse(std::move(head)); - client->OnStartLoadingResponseBody(std::move(pipe.consumer_handle)); + client->OnStartLoadingResponseBody(std::move(consumer_handle)); client_ = std::move(client); if (total_bytes_to_send == 0) { @@ -241,8 +244,8 @@ data_source->SetRange(first_byte_to_send, first_byte_to_send + total_bytes_to_send); - data_producer_ = std::make_unique<mojo::DataPipeProducer>( - std::move(pipe.producer_handle)); + data_producer_ = + std::make_unique<mojo::DataPipeProducer>(std::move(producer_handle)); data_producer_->Write(std::move(data_source), base::BindOnce(&ContentURLLoader::OnFileWritten, base::Unretained(this)));
diff --git a/content/browser/blob_storage/blob_internals_url_loader.cc b/content/browser/blob_storage/blob_internals_url_loader.cc index c30afb23..031612c 100644 --- a/content/browser/blob_storage/blob_internals_url_loader.cc +++ b/content/browser/blob_storage/blob_internals_url_loader.cc
@@ -28,20 +28,24 @@ std::string output = storage::ViewBlobInternalsJob::GenerateHTML( blob_storage_context->context()); - mojo::DataPipe data_pipe(output.size()); + mojo::ScopedDataPipeProducerHandle producer_handle; + mojo::ScopedDataPipeConsumerHandle consumer_handle; + CHECK_EQ( + mojo::CreateDataPipe(output.size(), producer_handle, consumer_handle), + MOJO_RESULT_OK); void* buffer = nullptr; uint32_t num_bytes = output.size(); - MojoResult result = data_pipe.producer_handle->BeginWriteData( + MojoResult result = producer_handle->BeginWriteData( &buffer, &num_bytes, MOJO_WRITE_DATA_FLAG_NONE); CHECK_EQ(result, MOJO_RESULT_OK); CHECK_EQ(num_bytes, output.size()); memcpy(buffer, output.c_str(), output.size()); - result = data_pipe.producer_handle->EndWriteData(num_bytes); + result = producer_handle->EndWriteData(num_bytes); CHECK_EQ(result, MOJO_RESULT_OK); - client->OnStartLoadingResponseBody(std::move(data_pipe.consumer_handle)); + client->OnStartLoadingResponseBody(std::move(consumer_handle)); network::URLLoaderCompletionStatus status(net::OK); status.encoded_data_length = output.size(); status.encoded_body_length = output.size();
diff --git a/content/browser/devtools/devtools_url_loader_interceptor.cc b/content/browser/devtools/devtools_url_loader_interceptor.cc index f45f6c3..68ef9ab1 100644 --- a/content/browser/devtools/devtools_url_loader_interceptor.cc +++ b/content/browser/devtools/devtools_url_loader_interceptor.cc
@@ -1168,13 +1168,16 @@ // but just in case... DCHECK_LE(body_size, UINT32_MAX) << "Response bodies larger than " << UINT32_MAX << " are not supported"; - mojo::DataPipe pipe(body_size); + mojo::ScopedDataPipeProducerHandle producer_handle; + mojo::ScopedDataPipeConsumerHandle consumer_handle; + CHECK_EQ(mojo::CreateDataPipe(body_size, producer_handle, consumer_handle), + MOJO_RESULT_OK); uint32_t num_bytes = body_size; - MojoResult res = pipe.producer_handle->WriteData( + MojoResult res = producer_handle->WriteData( body->front() + offset, &num_bytes, MOJO_WRITE_DATA_FLAG_NONE); DCHECK_EQ(0u, res); DCHECK_EQ(num_bytes, body_size); - client_->OnStartLoadingResponseBody(std::move(pipe.consumer_handle)); + client_->OnStartLoadingResponseBody(std::move(consumer_handle)); } if (response_metadata_->transfer_size) client_->OnTransferSizeUpdated(response_metadata_->transfer_size);
diff --git a/content/browser/download/download_browsertest.cc b/content/browser/download/download_browsertest.cc index 257e3754..b0542886 100644 --- a/content/browser/download/download_browsertest.cc +++ b/content/browser/download/download_browsertest.cc
@@ -67,6 +67,7 @@ #include "content/test/test_content_browser_client.h" #include "net/base/filename_util.h" #include "net/dns/mock_host_resolver.h" +#include "net/test/embedded_test_server/controllable_http_response.h" #include "net/test/embedded_test_server/embedded_test_server.h" #include "net/test/embedded_test_server/http_request.h" #include "net/test/embedded_test_server/http_response.h" @@ -954,6 +955,8 @@ real_host); host_resolver()->AddRule(TestDownloadHttpResponse::kTestDownloadHostName, real_host); + host_resolver()->AddRule("a.test", "127.0.0.1"); + host_resolver()->AddRule("b.test", "127.0.0.1"); } void SetUpCommandLine(base::CommandLine* command_line) override { @@ -3542,30 +3545,38 @@ ASSERT_TRUE(http_origin.ShutdownAndWaitUntilComplete()); } -// Check that the cookie policy is correctly updated when downloading a file -// that redirects cross origin. -IN_PROC_BROWSER_TEST_F(DownloadContentTest, CookiePolicy) { - net::EmbeddedTestServer origin_one; - net::EmbeddedTestServer origin_two; +// Check that the site-for-cookies is correctly updated when downloading a file +// that redirects cross site, by verifying that a SameSite cookie can be set +// following a cross-site redirect. +// (It is not enough to redirect across origins with the same host but different +// port numbers, because cookies do not respect ports.) +IN_PROC_BROWSER_TEST_F(DownloadContentTest, UpdateSiteForCookies) { + net::EmbeddedTestServer site_a; + net::EmbeddedTestServer site_b; - // |url| redirects to a different origin |download| which tries to set a - // cookie. - base::StringPairs cookie_header; - cookie_header.push_back( - std::make_pair(std::string("Set-Cookie"), std::string("A=B"))); - origin_one.RegisterRequestHandler(CreateBasicResponseHandler( - "/foo", net::HTTP_OK, cookie_header, "application/octet-stream", "abcd")); - ASSERT_TRUE(origin_one.Start()); + base::StringPairs cookie_headers; + cookie_headers.push_back(std::make_pair(std::string("Set-Cookie"), + std::string("A=lax; SameSite=Lax"))); + cookie_headers.push_back(std::make_pair( + std::string("Set-Cookie"), std::string("B=strict; SameSite=Strict"))); - origin_two.RegisterRequestHandler( - CreateRedirectHandler("/bar", origin_one.GetURL("/foo"))); - ASSERT_TRUE(origin_two.Start()); + // This will request a URL on b.test, which redirects to a url that sets the + // cookies on a.test. + site_a.RegisterRequestHandler(CreateBasicResponseHandler( + "/sets-samesite-cookies", net::HTTP_OK, cookie_headers, + "application/octet-stream", "abcd")); + ASSERT_TRUE(site_a.Start()); + site_b.RegisterRequestHandler( + CreateRedirectHandler("/redirected-download", + site_a.GetURL("a.test", "/sets-samesite-cookies"))); + ASSERT_TRUE(site_b.Start()); // Download the file. SetupEnsureNoPendingDownloads(); std::unique_ptr<download::DownloadUrlParameters> download_parameters( DownloadRequestUtils::CreateDownloadForWebContentsMainFrame( - shell()->web_contents(), origin_two.GetURL("/bar"), + shell()->web_contents(), + site_b.GetURL("b.test", "/redirected-download"), TRAFFIC_ANNOTATION_FOR_TESTS)); std::unique_ptr<DownloadTestObserver> observer(CreateWaiter(shell(), 1)); DownloadManagerForShell(shell())->DownloadUrl(std::move(download_parameters)); @@ -3579,10 +3590,10 @@ ASSERT_EQ(1u, downloads.size()); ASSERT_EQ(download::DownloadItem::COMPLETE, downloads[0]->GetState()); - // Check that the cookies were correctly set. - EXPECT_EQ("A=B", + // Check that the cookies were correctly set on a.test. + EXPECT_EQ("A=lax; B=strict", content::GetCookies(shell()->web_contents()->GetBrowserContext(), - origin_one.GetURL("/"))); + site_a.GetURL("a.test", "/"))); } // A filename suggestion specified via a @download attribute should not be @@ -4716,27 +4727,19 @@ // Test fixture for loading MHTML. class MhtmlLoadingTest : public DownloadContentTest { protected: - void SetUpOnMainThread() override { - DownloadContentTest::SetUpOnMainThread(); - - // Allows loading the MHTML, instead of downloading it. - new_client_.set_allowed_rendering_mhtml_over_http(true); - old_client_ = SetBrowserClientForTesting(&new_client_); + // Return an URL for loading a local test file. + GURL GetFileURL(const base::FilePath::CharType* file_path) { + base::FilePath path; + CHECK(base::PathService::Get(base::DIR_SOURCE_ROOT, &path)); + path = path.Append(GetTestDataFilePath()); + path = path.Append(file_path); + return GURL(FILE_PATH_LITERAL("file:") + path.value()); } - - void TearDownOnMainThread() override { - SetBrowserClientForTesting(old_client_); - DownloadContentTest::TearDownOnMainThread(); - } - - private: - DownloadTestContentBrowserClient new_client_; - ContentBrowserClient* old_client_; }; -IN_PROC_BROWSER_TEST_F(MhtmlLoadingTest, AllowRenderMultipartRelatedPage) { - // .mhtml file is mapped to "multipart/related" by the test server. - GURL url = embedded_test_server()->GetURL("/download/hello.mhtml"); +IN_PROC_BROWSER_TEST_F(MhtmlLoadingTest, + AllowRenderMultipartRelatedPageFromFile) { + GURL url = GetFileURL(FILE_PATH_LITERAL("download/hello.mhtml")); auto observer = std::make_unique<content::TestNavigationObserver>(url); observer->WatchExistingWebContents(); observer->StartWatchingNewWebContents(); @@ -4746,9 +4749,8 @@ observer->WaitForNavigationFinished(); } -IN_PROC_BROWSER_TEST_F(MhtmlLoadingTest, AllowRenderMessageRfc822Page) { - // .mht file is mapped to "message/rfc822" by the test server. - GURL url = embedded_test_server()->GetURL("/download/test.mht"); +IN_PROC_BROWSER_TEST_F(MhtmlLoadingTest, AllowRenderMessageRfc822PageFromFile) { + GURL url = GetFileURL(FILE_PATH_LITERAL("download/test.mht")); auto observer = std::make_unique<content::TestNavigationObserver>(url); observer->WatchExistingWebContents(); observer->StartWatchingNewWebContents(); @@ -4758,4 +4760,72 @@ observer->WaitForNavigationFinished(); } +IN_PROC_BROWSER_TEST_F(MhtmlLoadingTest, + DisallowRenderMultipartRelatedPageFromHTTP) { + net::EmbeddedTestServer server; + net::test_server::ControllableHttpResponse response(&server, "/"); + EXPECT_TRUE(server.Start()); + std::unique_ptr<DownloadTestObserver> observer(CreateWaiter(shell(), 1)); + + GURL url = server.GetURL(kOrigin, "/"); + + shell()->LoadURL(url); + + response.WaitForRequest(); + response.Send(net::HTTP_OK, "multipart/related"); + response.Done(); + + observer->WaitForFinished(); + EXPECT_EQ( + 1u, observer->NumDownloadsSeenInState(download::DownloadItem::COMPLETE)); +} + +IN_PROC_BROWSER_TEST_F(MhtmlLoadingTest, + DisallowRenderMessageRfc822PageFromHTTP) { + net::EmbeddedTestServer server; + net::test_server::ControllableHttpResponse response(&server, "/"); + EXPECT_TRUE(server.Start()); + std::unique_ptr<DownloadTestObserver> observer(CreateWaiter(shell(), 1)); + + GURL url = server.GetURL(kOrigin, "/"); + + shell()->LoadURL(url); + + response.WaitForRequest(); + response.Send(net::HTTP_OK, "message/rfc822"); + response.Done(); + + observer->WaitForFinished(); + EXPECT_EQ( + 1u, observer->NumDownloadsSeenInState(download::DownloadItem::COMPLETE)); +} + +// Regression test for https://crbug.com/1171765 +IN_PROC_BROWSER_TEST_F(MhtmlLoadingTest, DisallowRenderMessageRfc822Iframe) { + net::EmbeddedTestServer server; + net::test_server::ControllableHttpResponse main_response(&server, "/main"); + net::test_server::ControllableHttpResponse sub_response(&server, "/sub"); + EXPECT_TRUE(server.Start()); + + std::unique_ptr<DownloadTestObserver> observer(CreateWaiter(shell(), 1)); + + GURL main_url = server.GetURL(kOrigin, "/main"); + GURL sub_url = server.GetURL(kOrigin, "/sub"); + + shell()->LoadURL(main_url); + + main_response.WaitForRequest(); + main_response.Send(net::HTTP_OK, "text/html", + "<iframe src='./sub'></iframe>"); + main_response.Done(); + + sub_response.WaitForRequest(); + sub_response.Send(net::HTTP_OK, "message/rfc822"); + sub_response.Done(); + + observer->WaitForFinished(); + EXPECT_EQ( + 1u, observer->NumDownloadsSeenInState(download::DownloadItem::COMPLETE)); +} + } // namespace content
diff --git a/content/browser/loader/cross_site_document_blocking_browsertest.cc b/content/browser/loader/cross_site_document_blocking_browsertest.cc index fbc123c..2c0fa39 100644 --- a/content/browser/loader/cross_site_document_blocking_browsertest.cc +++ b/content/browser/loader/cross_site_document_blocking_browsertest.cc
@@ -387,14 +387,17 @@ if (status.error_code == net::OK) { original_client_->OnReceiveResponse(std::move(response_head)); - mojo::DataPipe empty_data_pipe(response_body.size() + 1); - original_client_->OnStartLoadingResponseBody( - std::move(empty_data_pipe.consumer_handle)); + mojo::ScopedDataPipeProducerHandle producer_handle; + mojo::ScopedDataPipeConsumerHandle consumer_handle; + ASSERT_EQ(mojo::CreateDataPipe(response_body.size() + 1, producer_handle, + consumer_handle), + MOJO_RESULT_OK); + original_client_->OnStartLoadingResponseBody(std::move(consumer_handle)); uint32_t num_bytes = response_body.size(); - EXPECT_EQ(MOJO_RESULT_OK, empty_data_pipe.producer_handle->WriteData( - response_body.data(), &num_bytes, - MOJO_WRITE_DATA_FLAG_ALL_OR_NONE)); + EXPECT_EQ(MOJO_RESULT_OK, + producer_handle->WriteData(response_body.data(), &num_bytes, + MOJO_WRITE_DATA_FLAG_ALL_OR_NONE)); } original_client_->OnComplete(status);
diff --git a/content/browser/loader/file_url_loader_factory.cc b/content/browser/loader/file_url_loader_factory.cc index f6a3e6f..73a4ef5 100644 --- a/content/browser/loader/file_url_loader_factory.cc +++ b/content/browser/loader/file_url_loader_factory.cc
@@ -218,8 +218,10 @@ return; } - mojo::DataPipe pipe(kDefaultFileUrlPipeSize); - if (!pipe.consumer_handle.is_valid()) { + mojo::ScopedDataPipeProducerHandle producer_handle; + mojo::ScopedDataPipeConsumerHandle consumer_handle; + if (mojo::CreateDataPipe(kDefaultFileUrlPipeSize, producer_handle, + consumer_handle) != MOJO_RESULT_OK) { client->OnComplete(network::URLLoaderCompletionStatus(net::ERR_FAILED)); return; } @@ -229,14 +231,14 @@ head->charset = "utf-8"; head->response_type = response_type; client->OnReceiveResponse(std::move(head)); - client->OnStartLoadingResponseBody(std::move(pipe.consumer_handle)); + client->OnStartLoadingResponseBody(std::move(consumer_handle)); client_ = std::move(client); lister_ = std::make_unique<net::DirectoryLister>(path_, this); lister_->Start(); - data_producer_ = std::make_unique<mojo::DataPipeProducer>( - std::move(pipe.producer_handle)); + data_producer_ = + std::make_unique<mojo::DataPipeProducer>(std::move(producer_handle)); } void OnMojoDisconnct() { @@ -556,8 +558,10 @@ } #endif // defined(OS_WIN) - mojo::DataPipe pipe(kDefaultFileUrlPipeSize); - if (!pipe.consumer_handle.is_valid()) { + mojo::ScopedDataPipeProducerHandle producer_handle; + mojo::ScopedDataPipeConsumerHandle consumer_handle; + if (mojo::CreateDataPipe(kDefaultFileUrlPipeSize, producer_handle, + consumer_handle) != MOJO_RESULT_OK) { OnClientComplete(net::ERR_FAILED, std::move(observer)); return; } @@ -641,9 +645,9 @@ static_cast<uint32_t>(initial_read_size - first_byte_to_send), static_cast<uint32_t>(total_bytes_to_send)); const uint32_t expected_write_size = write_size; - MojoResult result = pipe.producer_handle->WriteData( - &initial_read_buffer[first_byte_to_send], &write_size, - MOJO_WRITE_DATA_FLAG_NONE); + MojoResult result = + producer_handle->WriteData(&initial_read_buffer[first_byte_to_send], + &write_size, MOJO_WRITE_DATA_FLAG_NONE); if (result != MOJO_RESULT_OK || write_size != expected_write_size) { OnFileWritten(std::move(observer), result); return; @@ -675,7 +679,7 @@ head->mime_type); } client_->OnReceiveResponse(std::move(head)); - client_->OnStartLoadingResponseBody(std::move(pipe.consumer_handle)); + client_->OnStartLoadingResponseBody(std::move(consumer_handle)); if (total_bytes_to_send == 0) { // There's definitely no more data, so we're already done. @@ -691,8 +695,8 @@ if (observer) observer->OnSeekComplete(first_byte_to_send); - data_producer_ = std::make_unique<mojo::DataPipeProducer>( - std::move(pipe.producer_handle)); + data_producer_ = + std::make_unique<mojo::DataPipeProducer>(std::move(producer_handle)); data_producer_->Write(std::make_unique<mojo::FilteredDataSource>( std::move(file_data_source), std::move(observer)), base::BindOnce(&FileURLLoader::OnFileWritten,
diff --git a/content/browser/renderer_host/navigation_request.cc b/content/browser/renderer_host/navigation_request.cc index 0bdf973..040a95d 100644 --- a/content/browser/renderer_host/navigation_request.cc +++ b/content/browser/renderer_host/navigation_request.cc
@@ -2354,7 +2354,7 @@ // MHTML document can't be framed into non-MHTML document (and vice versa). // The full page must load from the MHTML archive or none of it. - if (is_mhtml_archive && !IsInMainFrame()) { + if (is_mhtml_archive && !IsInMainFrame() && response_should_be_rendered_) { OnRequestFailedInternal( network::URLLoaderCompletionStatus(net::ERR_BLOCKED_BY_RESPONSE), false /* skip_throttles */, base::nullopt /* error_page_contnet */, @@ -2373,6 +2373,8 @@ common_params_->url, common_params_->referrer->url, network_isolation_key); if (coop_requires_blocking) { + // TODO(https://crbug.com/1172169): Investigate what must be done in case of + // a download. OnRequestFailedInternal( network::URLLoaderCompletionStatus(*coop_requires_blocking), false /* skip_throttles */, base::nullopt /* error_page_content */, @@ -2385,6 +2387,8 @@ const base::Optional<network::mojom::BlockedByResponseReason> coep_requires_blocking = EnforceCOEP(); if (coep_requires_blocking) { + // TODO(https://crbug.com/1172169): Investigate what must be done in case of + // a download. OnRequestFailedInternal( network::URLLoaderCompletionStatus(*coep_requires_blocking), false /* skip_throttles */, base::nullopt /* error_page_content */, @@ -2430,6 +2434,8 @@ coep_reporter->QueueNavigationReport(redirect_chain_[0], /*report_only=*/false); } + // TODO(https://crbug.com/1172169): Investigate what must be done in + // case of a download. OnRequestFailedInternal(network::URLLoaderCompletionStatus( network::mojom::BlockedByResponseReason:: kCoepFrameResourceNeedsCoepHeader),
diff --git a/content/browser/service_worker/service_worker_main_resource_loader_unittest.cc b/content/browser/service_worker/service_worker_main_resource_loader_unittest.cc index 772afca5..b331a64f 100644 --- a/content/browser/service_worker/service_worker_main_resource_loader_unittest.cc +++ b/content/browser/service_worker/service_worker_main_resource_loader_unittest.cc
@@ -761,10 +761,12 @@ // Construct the Stream to respond with. const char kResponseBody[] = "Here is sample text for the Stream."; mojo::Remote<blink::mojom::ServiceWorkerStreamCallback> stream_callback; - mojo::DataPipe data_pipe; + mojo::ScopedDataPipeProducerHandle producer_handle; + mojo::ScopedDataPipeConsumerHandle consumer_handle; + ASSERT_EQ(mojo::CreateDataPipe(nullptr, producer_handle, consumer_handle), + MOJO_RESULT_OK); service_worker_->RespondWithStream( - stream_callback.BindNewPipeAndPassReceiver(), - std::move(data_pipe.consumer_handle)); + stream_callback.BindNewPipeAndPassReceiver(), std::move(consumer_handle)); // Perform the request. StartRequest(CreateRequest()); @@ -778,12 +780,12 @@ // Write the body stream. uint32_t written_bytes = sizeof(kResponseBody) - 1; - MojoResult mojo_result = data_pipe.producer_handle->WriteData( + MojoResult mojo_result = producer_handle->WriteData( kResponseBody, &written_bytes, MOJO_WRITE_DATA_FLAG_NONE); ASSERT_EQ(MOJO_RESULT_OK, mojo_result); EXPECT_EQ(sizeof(kResponseBody) - 1, written_bytes); stream_callback->OnCompleted(); - data_pipe.producer_handle.reset(); + producer_handle.reset(); client_.RunUntilComplete(); EXPECT_EQ(net::OK, client_.completion_status().error_code); @@ -809,10 +811,12 @@ // Construct the Stream to respond with. const char kResponseBody[] = "Here is sample text for the Stream."; mojo::Remote<blink::mojom::ServiceWorkerStreamCallback> stream_callback; - mojo::DataPipe data_pipe; + mojo::ScopedDataPipeProducerHandle producer_handle; + mojo::ScopedDataPipeConsumerHandle consumer_handle; + ASSERT_EQ(mojo::CreateDataPipe(nullptr, producer_handle, consumer_handle), + MOJO_RESULT_OK); service_worker_->RespondWithStream( - stream_callback.BindNewPipeAndPassReceiver(), - std::move(data_pipe.consumer_handle)); + stream_callback.BindNewPipeAndPassReceiver(), std::move(consumer_handle)); // Perform the request. StartRequest(CreateRequest()); @@ -824,12 +828,12 @@ // Start writing the body stream, then abort before finishing. uint32_t written_bytes = sizeof(kResponseBody) - 1; - MojoResult mojo_result = data_pipe.producer_handle->WriteData( + MojoResult mojo_result = producer_handle->WriteData( kResponseBody, &written_bytes, MOJO_WRITE_DATA_FLAG_NONE); ASSERT_EQ(MOJO_RESULT_OK, mojo_result); EXPECT_EQ(sizeof(kResponseBody) - 1, written_bytes); stream_callback->OnAborted(); - data_pipe.producer_handle.reset(); + producer_handle.reset(); client_.RunUntilComplete(); EXPECT_EQ(net::ERR_ABORTED, client_.completion_status().error_code); @@ -859,10 +863,12 @@ // Construct the Stream to respond with. const char kResponseBody[] = "Here is sample text for the Stream."; mojo::Remote<blink::mojom::ServiceWorkerStreamCallback> stream_callback; - mojo::DataPipe data_pipe; + mojo::ScopedDataPipeProducerHandle producer_handle; + mojo::ScopedDataPipeConsumerHandle consumer_handle; + ASSERT_EQ(mojo::CreateDataPipe(nullptr, producer_handle, consumer_handle), + MOJO_RESULT_OK); service_worker_->RespondWithStream( - stream_callback.BindNewPipeAndPassReceiver(), - std::move(data_pipe.consumer_handle)); + stream_callback.BindNewPipeAndPassReceiver(), std::move(consumer_handle)); // Perform the request. StartRequest(CreateRequest()); @@ -875,11 +881,11 @@ // Start writing the body stream, then break the Mojo connection to the loader // before finishing. uint32_t written_bytes = sizeof(kResponseBody) - 1; - MojoResult mojo_result = data_pipe.producer_handle->WriteData( + MojoResult mojo_result = producer_handle->WriteData( kResponseBody, &written_bytes, MOJO_WRITE_DATA_FLAG_NONE); ASSERT_EQ(MOJO_RESULT_OK, mojo_result); EXPECT_EQ(sizeof(kResponseBody) - 1, written_bytes); - EXPECT_TRUE(data_pipe.producer_handle.is_valid()); + EXPECT_TRUE(producer_handle.is_valid()); loader_remote_.reset(); base::RunLoop().RunUntilIdle(); @@ -887,13 +893,12 @@ // on connection error, the URLLoaderClient still exists. In this test, it is // |client_| which owns the data pipe, so it's still valid to write data to // it. - mojo_result = data_pipe.producer_handle->WriteData( - kResponseBody, &written_bytes, MOJO_WRITE_DATA_FLAG_NONE); + mojo_result = producer_handle->WriteData(kResponseBody, &written_bytes, + MOJO_WRITE_DATA_FLAG_NONE); // TODO(falken): This should probably be an error. EXPECT_EQ(MOJO_RESULT_OK, mojo_result); client_.RunUntilComplete(); - EXPECT_FALSE(data_pipe.consumer_handle.is_valid()); EXPECT_EQ(net::ERR_ABORTED, client_.completion_status().error_code); // Timing histograms shouldn't be recorded on cancel.
diff --git a/content/browser/speech/speech_recognition_engine_unittest.cc b/content/browser/speech/speech_recognition_engine_unittest.cc index 95784822..fb0a3b28 100644 --- a/content/browser/speech/speech_recognition_engine_unittest.cc +++ b/content/browser/speech/speech_recognition_engine_unittest.cc
@@ -567,10 +567,14 @@ net::HttpUtil::AssembleRawHeaders(headers)); downstream_request->client->OnReceiveResponse(std::move(head)); - mojo::DataPipe data_pipe; + mojo::ScopedDataPipeProducerHandle producer_handle; + mojo::ScopedDataPipeConsumerHandle consumer_handle; + ASSERT_EQ(mojo::CreateDataPipe(nullptr, producer_handle, consumer_handle), + MOJO_RESULT_OK); + downstream_request->client->OnStartLoadingResponseBody( - std::move(data_pipe.consumer_handle)); - downstream_data_pipe_ = std::move(data_pipe.producer_handle); + std::move(consumer_handle)); + downstream_data_pipe_ = std::move(producer_handle); } void SpeechRecognitionEngineTest::ProvideMockProtoResultDownstream( @@ -719,10 +723,12 @@ element.As<network::DataElementChunkedDataPipe>() .ReleaseChunkedDataPipeGetter()); } - mojo::DataPipe data_pipe; - chunked_data_pipe_getter_->StartReading( - std::move(data_pipe.producer_handle)); - upstream_data_pipe_ = std::move(data_pipe.consumer_handle); + mojo::ScopedDataPipeProducerHandle producer_handle; + mojo::ScopedDataPipeConsumerHandle consumer_handle; + EXPECT_EQ(mojo::CreateDataPipe(nullptr, producer_handle, consumer_handle), + MOJO_RESULT_OK); + chunked_data_pipe_getter_->StartReading(std::move(producer_handle)); + upstream_data_pipe_ = std::move(consumer_handle); } EXPECT_TRUE(upstream_data_pipe_.is_valid());
diff --git a/content/browser/speech/speech_recognizer_impl_unittest.cc b/content/browser/speech/speech_recognizer_impl_unittest.cc index c31e3ff..c2f3cd24 100644 --- a/content/browser/speech/speech_recognizer_impl_unittest.cc +++ b/content/browser/speech/speech_recognizer_impl_unittest.cc
@@ -421,7 +421,10 @@ // full recording to complete. const size_t kNumChunks = 5; mojo::Remote<network::mojom::ChunkedDataPipeGetter> chunked_data_pipe_getter; - mojo::DataPipe data_pipe; + mojo::ScopedDataPipeProducerHandle producer_handle; + mojo::ScopedDataPipeConsumerHandle consumer_handle; + ASSERT_EQ(mojo::CreateDataPipe(nullptr, producer_handle, consumer_handle), + MOJO_RESULT_OK); for (size_t i = 0; i < kNumChunks; ++i) { Capture(audio_bus_.get()); @@ -439,8 +442,7 @@ chunked_data_pipe_getter.Bind( element.As<network::DataElementChunkedDataPipe>() .ReleaseChunkedDataPipeGetter()); - chunked_data_pipe_getter->StartReading( - std::move(data_pipe.producer_handle)); + chunked_data_pipe_getter->StartReading(std::move(producer_handle)); } std::string data; @@ -449,11 +451,11 @@ const void* buffer; uint32_t num_bytes; - MojoResult result = data_pipe.consumer_handle->BeginReadData( + MojoResult result = consumer_handle->BeginReadData( &buffer, &num_bytes, MOJO_READ_DATA_FLAG_NONE); if (result == MOJO_RESULT_OK) { data.append(static_cast<const char*>(buffer), num_bytes); - data_pipe.consumer_handle->EndReadData(num_bytes); + consumer_handle->EndReadData(num_bytes); continue; } if (result == MOJO_RESULT_SHOULD_WAIT) {
diff --git a/content/browser/web_contents/web_contents_impl.cc b/content/browser/web_contents/web_contents_impl.cc index 510dbf5..ccd3d2a 100644 --- a/content/browser/web_contents/web_contents_impl.cc +++ b/content/browser/web_contents/web_contents_impl.cc
@@ -209,9 +209,6 @@ namespace content { -using AccessibilityEventCallback = - base::RepeatingCallback<void(const std::string&)>; - namespace { const int kMinimumDelayBetweenLoadingUpdatesMS = 100; @@ -4007,7 +4004,7 @@ void WebContentsImpl::RecordAccessibilityEvents( bool start_recording, - base::Optional<AccessibilityEventCallback> callback) { + base::Optional<ui::AXEventCallback> callback) { OPTIONAL_TRACE_EVENT0("content", "WebContentsImpl::RecordAccessibilityEvents"); // Only pass a callback to RecordAccessibilityEvents when starting to record. @@ -4819,7 +4816,8 @@ OPTIONAL_TRACE_EVENT1("content", "WebContentsImpl::DidChooseColorInColorChooser", "color", color); - color_chooser_->DidChooseColorInColorChooser(color); + if (color_chooser_) + color_chooser_->DidChooseColorInColorChooser(color); } void WebContentsImpl::DidEndColorChooser() { @@ -5839,13 +5837,14 @@ SkColor color, std::vector<blink::mojom::ColorSuggestionPtr> suggestions) { OPTIONAL_TRACE_EVENT0("content", "WebContentsImpl::OpenColorChooser"); + color_chooser_.reset(); + content::ColorChooser* new_color_chooser = delegate_ ? delegate_->OpenColorChooser(this, color, suggestions) : nullptr; if (!new_color_chooser) return; - color_chooser_.reset(); color_chooser_ = std::make_unique<ColorChooser>( new_color_chooser, std::move(chooser_receiver), std::move(client)); }
diff --git a/content/browser/web_contents/web_contents_impl.h b/content/browser/web_contents/web_contents_impl.h index 0751d0c2..5ce573c 100644 --- a/content/browser/web_contents/web_contents_impl.h +++ b/content/browser/web_contents/web_contents_impl.h
@@ -27,7 +27,6 @@ #include "base/values.h" #include "build/build_config.h" #include "components/download/public/common/download_url_parameters.h" -#include "content/browser/accessibility/accessibility_event_recorder.h" #include "content/browser/media/audio_stream_monitor.h" #include "content/browser/media/forwarding_audio_stream_factory.h" #include "content/browser/renderer_host/frame_tree.h" @@ -75,6 +74,7 @@ #include "third_party/blink/public/mojom/page/display_cutout.mojom.h" #include "third_party/blink/public/mojom/page/page_visibility_state.mojom.h" #include "ui/accessibility/ax_mode.h" +#include "ui/accessibility/platform/inspect/ax_event_recorder.h" #include "ui/base/dragdrop/mojom/drag_drop_types.mojom-forward.h" #include "ui/base/page_transition_types.h" #include "ui/gfx/geometry/rect_f.h" @@ -143,9 +143,6 @@ class PepperPlaybackObserver; #endif -using AccessibilityEventCallback = - base::RepeatingCallback<void(const std::string&)>; - // CreatedWindow holds the WebContentsImpl and target url between IPC calls to // CreateNewWindow and ShowCreatedWindow. struct CONTENT_EXPORT CreatedWindow { @@ -629,7 +626,7 @@ std::vector<ui::AXPropertyFilter> property_filters) override; void RecordAccessibilityEvents( bool start_recording, - base::Optional<AccessibilityEventCallback> callback) override; + base::Optional<ui::AXEventCallback> callback) override; device::mojom::GeolocationContext* GetGeolocationContext() override; device::mojom::WakeLockContext* GetWakeLockContext() override; #if defined(OS_ANDROID) @@ -1945,7 +1942,7 @@ // is created, and broadcast to all frames when it changes. ui::AXMode accessibility_mode_; - std::unique_ptr<content::AccessibilityEventRecorder> event_recorder_; + std::unique_ptr<ui::AXEventRecorder> event_recorder_; // Monitors power levels for audio streams associated with this WebContents. AudioStreamMonitor audio_stream_monitor_;
diff --git a/content/browser/web_package/signed_exchange_cert_fetcher_unittest.cc b/content/browser/web_package/signed_exchange_cert_fetcher_unittest.cc index 612d5d5f..e4ae19a 100644 --- a/content/browser/web_package/signed_exchange_cert_fetcher_unittest.cc +++ b/content/browser/web_package/signed_exchange_cert_fetcher_unittest.cc
@@ -204,9 +204,13 @@ static mojo::ScopedDataPipeConsumerHandle CreateTestDataFilledDataPipe() { auto message = CreateTestData(); - mojo::DataPipe data_pipe(message.size()); - CHECK(mojo::BlockingCopyFromString(message, data_pipe.producer_handle)); - return std::move(data_pipe.consumer_handle); + mojo::ScopedDataPipeProducerHandle producer_handle; + mojo::ScopedDataPipeConsumerHandle consumer_handle; + EXPECT_EQ( + mojo::CreateDataPipe(message.size(), producer_handle, consumer_handle), + MOJO_RESULT_OK); + CHECK(mojo::BlockingCopyFromString(message, producer_handle)); + return consumer_handle; } static net::SHA256HashValue GetTestDataCertFingerprint256() { @@ -303,15 +307,19 @@ scoped_refptr<net::X509Certificate> certificate = ImportTestCert(); const std::string message = CreateCertMessage(CreateCertMessageFromCert(*certificate)); - mojo::DataPipe data_pipe(message.size() / 2 + 1); + mojo::ScopedDataPipeProducerHandle producer_handle; + mojo::ScopedDataPipeConsumerHandle consumer_handle; + ASSERT_EQ(mojo::CreateDataPipe(message.size() / 2 + 1, producer_handle, + consumer_handle), + MOJO_RESULT_OK); ASSERT_TRUE(mojo::BlockingCopyFromString( - message.substr(0, message.size() / 2), data_pipe.producer_handle)); + message.substr(0, message.size() / 2), producer_handle)); mock_loader_factory_.client_remote()->OnStartLoadingResponseBody( - std::move(data_pipe.consumer_handle)); + std::move(consumer_handle)); RunUntilIdle(); ASSERT_TRUE(mojo::BlockingCopyFromString(message.substr(message.size() / 2), - data_pipe.producer_handle)); - data_pipe.producer_handle.reset(); + producer_handle)); + producer_handle.reset(); mock_loader_factory_.client_remote()->OnComplete( network::URLLoaderCompletionStatus(net::OK)); RunUntilIdle(); @@ -356,11 +364,15 @@ std::unique_ptr<SignedExchangeCertFetcher> fetcher = CreateFetcherAndStart(url_, false /* force_fetch */); CallOnReceiveResponse(); - mojo::DataPipe data_pipe(message.size()); - CHECK(mojo::BlockingCopyFromString(message, data_pipe.producer_handle)); - data_pipe.producer_handle.reset(); + mojo::ScopedDataPipeProducerHandle producer_handle; + mojo::ScopedDataPipeConsumerHandle consumer_handle; + ASSERT_EQ( + mojo::CreateDataPipe(message.size(), producer_handle, consumer_handle), + MOJO_RESULT_OK); + CHECK(mojo::BlockingCopyFromString(message, producer_handle)); + producer_handle.reset(); mock_loader_factory_.client_remote()->OnStartLoadingResponseBody( - std::move(data_pipe.consumer_handle)); + std::move(consumer_handle)); mock_loader_factory_.client_remote()->OnComplete( network::URLLoaderCompletionStatus(net::OK)); RunUntilIdle(); @@ -380,11 +392,15 @@ std::unique_ptr<SignedExchangeCertFetcher> fetcher = CreateFetcherAndStart(url_, false /* force_fetch */); CallOnReceiveResponse(); - mojo::DataPipe data_pipe(message.size()); - CHECK(mojo::BlockingCopyFromString(message, data_pipe.producer_handle)); - data_pipe.producer_handle.reset(); + mojo::ScopedDataPipeProducerHandle producer_handle; + mojo::ScopedDataPipeConsumerHandle consumer_handle; + ASSERT_EQ( + mojo::CreateDataPipe(message.size(), producer_handle, consumer_handle), + MOJO_RESULT_OK); + CHECK(mojo::BlockingCopyFromString(message, producer_handle)); + producer_handle.reset(); mock_loader_factory_.client_remote()->OnStartLoadingResponseBody( - std::move(data_pipe.consumer_handle)); + std::move(consumer_handle)); mock_loader_factory_.client_remote()->OnComplete( network::URLLoaderCompletionStatus(net::OK)); RunUntilIdle(); @@ -404,15 +420,19 @@ std::unique_ptr<SignedExchangeCertFetcher> fetcher = CreateFetcherAndStart(url_, false /* force_fetch */); CallOnReceiveResponse(); - mojo::DataPipe data_pipe(message.size() / 2 + 1); + mojo::ScopedDataPipeProducerHandle producer_handle; + mojo::ScopedDataPipeConsumerHandle consumer_handle; + ASSERT_EQ(mojo::CreateDataPipe(message.size() / 2 + 1, producer_handle, + consumer_handle), + MOJO_RESULT_OK); ASSERT_TRUE(mojo::BlockingCopyFromString( - message.substr(0, message.size() / 2), data_pipe.producer_handle)); + message.substr(0, message.size() / 2), producer_handle)); mock_loader_factory_.client_remote()->OnStartLoadingResponseBody( - std::move(data_pipe.consumer_handle)); + std::move(consumer_handle)); RunUntilIdle(); ASSERT_TRUE(mojo::BlockingCopyFromString(message.substr(message.size() / 2), - data_pipe.producer_handle)); - data_pipe.producer_handle.reset(); + producer_handle)); + producer_handle.reset(); mock_loader_factory_.client_remote()->OnComplete( network::URLLoaderCompletionStatus(net::OK)); RunUntilIdle(); @@ -437,11 +457,15 @@ response_head->content_length = message.size(); mock_loader_factory_.client_remote()->OnReceiveResponse( std::move(response_head)); - mojo::DataPipe data_pipe(message.size()); - CHECK(mojo::BlockingCopyFromString(message, data_pipe.producer_handle)); - data_pipe.producer_handle.reset(); + mojo::ScopedDataPipeProducerHandle producer_handle; + mojo::ScopedDataPipeConsumerHandle consumer_handle; + ASSERT_EQ( + mojo::CreateDataPipe(message.size(), producer_handle, consumer_handle), + MOJO_RESULT_OK); + CHECK(mojo::BlockingCopyFromString(message, producer_handle)); + producer_handle.reset(); mock_loader_factory_.client_remote()->OnStartLoadingResponseBody( - std::move(data_pipe.consumer_handle)); + std::move(consumer_handle)); mock_loader_factory_.client_remote()->OnComplete( network::URLLoaderCompletionStatus(net::OK)); RunUntilIdle(); @@ -501,11 +525,15 @@ CreateFetcherAndStart(url_, false /* force_fetch */); CallOnReceiveResponse(); const std::string message = CreateCertMessage("Invalid Cert Data"); - mojo::DataPipe data_pipe(message.size()); - CHECK(mojo::BlockingCopyFromString(message, data_pipe.producer_handle)); - data_pipe.producer_handle.reset(); + mojo::ScopedDataPipeProducerHandle producer_handle; + mojo::ScopedDataPipeConsumerHandle consumer_handle; + ASSERT_EQ( + mojo::CreateDataPipe(message.size(), producer_handle, consumer_handle), + MOJO_RESULT_OK); + CHECK(mojo::BlockingCopyFromString(message, producer_handle)); + producer_handle.reset(); mock_loader_factory_.client_remote()->OnStartLoadingResponseBody( - std::move(data_pipe.consumer_handle)); + std::move(consumer_handle)); mock_loader_factory_.client_remote()->OnComplete( network::URLLoaderCompletionStatus(net::OK)); RunUntilIdle(); @@ -522,11 +550,15 @@ const std::string message = "Invalid cert message"; - mojo::DataPipe data_pipe(message.size()); - CHECK(mojo::BlockingCopyFromString(message, data_pipe.producer_handle)); - data_pipe.producer_handle.reset(); + mojo::ScopedDataPipeProducerHandle producer_handle; + mojo::ScopedDataPipeConsumerHandle consumer_handle; + ASSERT_EQ( + mojo::CreateDataPipe(message.size(), producer_handle, consumer_handle), + MOJO_RESULT_OK); + CHECK(mojo::BlockingCopyFromString(message, producer_handle)); + producer_handle.reset(); mock_loader_factory_.client_remote()->OnStartLoadingResponseBody( - std::move(data_pipe.consumer_handle)); + std::move(consumer_handle)); mock_loader_factory_.client_remote()->OnComplete( network::URLLoaderCompletionStatus(net::OK)); @@ -679,16 +711,20 @@ scoped_refptr<net::X509Certificate> certificate = ImportTestCert(); const std::string message = CreateCertMessage(CreateCertMessageFromCert(*certificate)); - mojo::DataPipe data_pipe(message.size() / 2 + 1); + mojo::ScopedDataPipeProducerHandle producer_handle; + mojo::ScopedDataPipeConsumerHandle consumer_handle; + ASSERT_EQ(mojo::CreateDataPipe(message.size() / 2 + 1, producer_handle, + consumer_handle), + MOJO_RESULT_OK); ASSERT_TRUE(mojo::BlockingCopyFromString( - message.substr(0, message.size() / 2), data_pipe.producer_handle)); + message.substr(0, message.size() / 2), producer_handle)); mock_loader_factory_.client_remote()->OnStartLoadingResponseBody( - std::move(data_pipe.consumer_handle)); + std::move(consumer_handle)); RunUntilIdle(); fetcher.reset(); RunUntilIdle(); ASSERT_TRUE(mojo::BlockingCopyFromString(message.substr(message.size() / 2), - data_pipe.producer_handle)); + producer_handle)); RunUntilIdle(); EXPECT_FALSE(callback_called_); @@ -702,14 +738,18 @@ scoped_refptr<net::X509Certificate> certificate = ImportTestCert(); const std::string message = CreateCertMessage(CreateCertMessageFromCert(*certificate)); - mojo::DataPipe data_pipe(message.size()); - CHECK(mojo::BlockingCopyFromString(message, data_pipe.producer_handle)); + mojo::ScopedDataPipeProducerHandle producer_handle; + mojo::ScopedDataPipeConsumerHandle consumer_handle; + ASSERT_EQ( + mojo::CreateDataPipe(message.size(), producer_handle, consumer_handle), + MOJO_RESULT_OK); + CHECK(mojo::BlockingCopyFromString(message, producer_handle)); mock_loader_factory_.client_remote()->OnStartLoadingResponseBody( - std::move(data_pipe.consumer_handle)); + std::move(consumer_handle)); RunUntilIdle(); CloseClientPipe(); RunUntilIdle(); - data_pipe.producer_handle.reset(); + producer_handle.reset(); fetcher.reset(); RunUntilIdle(); @@ -749,15 +789,19 @@ scoped_refptr<net::X509Certificate> certificate = ImportTestCert(); const std::string message = CreateCertMessage(CreateCertMessageFromCert(*certificate)); - mojo::DataPipe data_pipe(message.size() / 2 + 1); + mojo::ScopedDataPipeProducerHandle producer_handle; + mojo::ScopedDataPipeConsumerHandle consumer_handle; + ASSERT_EQ(mojo::CreateDataPipe(message.size() / 2 + 1, producer_handle, + consumer_handle), + MOJO_RESULT_OK); ASSERT_TRUE(mojo::BlockingCopyFromString( - message.substr(0, message.size() / 2), data_pipe.producer_handle)); + message.substr(0, message.size() / 2), producer_handle)); mock_loader_factory_.client_remote()->OnStartLoadingResponseBody( - std::move(data_pipe.consumer_handle)); + std::move(consumer_handle)); RunUntilIdle(); CloseClientPipe(); RunUntilIdle(); - data_pipe.producer_handle.reset(); + producer_handle.reset(); RunUntilIdle(); EXPECT_TRUE(callback_called_); // SignedExchangeCertFetcher receives a truncated cert cbor. @@ -772,14 +816,18 @@ scoped_refptr<net::X509Certificate> certificate = ImportTestCert(); const std::string message = CreateCertMessage(CreateCertMessageFromCert(*certificate)); - mojo::DataPipe data_pipe(message.size()); - CHECK(mojo::BlockingCopyFromString(message, data_pipe.producer_handle)); + mojo::ScopedDataPipeProducerHandle producer_handle; + mojo::ScopedDataPipeConsumerHandle consumer_handle; + ASSERT_EQ( + mojo::CreateDataPipe(message.size(), producer_handle, consumer_handle), + MOJO_RESULT_OK); + CHECK(mojo::BlockingCopyFromString(message, producer_handle)); mock_loader_factory_.client_remote()->OnStartLoadingResponseBody( - std::move(data_pipe.consumer_handle)); + std::move(consumer_handle)); RunUntilIdle(); CloseClientPipe(); RunUntilIdle(); - data_pipe.producer_handle.reset(); + producer_handle.reset(); RunUntilIdle(); EXPECT_TRUE(callback_called_);
diff --git a/content/browser/webkit_browsertest.cc b/content/browser/webkit_browsertest.cc index dd63893e..51dad13f 100644 --- a/content/browser/webkit_browsertest.cc +++ b/content/browser/webkit_browsertest.cc
@@ -38,12 +38,14 @@ std::string body = "some data\r\n"; uint32_t bytes_written = body.size(); - mojo::DataPipe data_pipe(body.size()); + mojo::ScopedDataPipeProducerHandle producer_handle; + mojo::ScopedDataPipeConsumerHandle consumer_handle; + CHECK_EQ(mojo::CreateDataPipe(body.size(), producer_handle, consumer_handle), + MOJO_RESULT_OK); CHECK_EQ(MOJO_RESULT_OK, - data_pipe.producer_handle->WriteData( - body.data(), &bytes_written, MOJO_WRITE_DATA_FLAG_ALL_OR_NONE)); - params->client->OnStartLoadingResponseBody( - std::move(data_pipe.consumer_handle)); + producer_handle->WriteData(body.data(), &bytes_written, + MOJO_WRITE_DATA_FLAG_ALL_OR_NONE)); + params->client->OnStartLoadingResponseBody(std::move(consumer_handle)); params->client->OnComplete( network::URLLoaderCompletionStatus(net::ERR_CONNECTION_ABORTED));
diff --git a/content/public/android/java/src/org/chromium/content/app/ContentChildProcessServiceDelegate.java b/content/public/android/java/src/org/chromium/content/app/ContentChildProcessServiceDelegate.java index cbeb21b..7893319372 100644 --- a/content/public/android/java/src/org/chromium/content/app/ContentChildProcessServiceDelegate.java +++ b/content/public/android/java/src/org/chromium/content/app/ContentChildProcessServiceDelegate.java
@@ -78,11 +78,11 @@ } @Override - public void preloadNativeLibrary(Context hostContext) { + public void preloadNativeLibrary(String packageName) { // This function can be called before command line is set. That is fine because // preloading explicitly doesn't run any Chromium code, see NativeLibraryPreloader // for more info. - LibraryLoader.getInstance().preloadNowOverrideApplicationContext(hostContext); + LibraryLoader.getInstance().preloadNowOverridePackageName(packageName); } @Override
diff --git a/content/renderer/loader/navigation_body_loader_unittest.cc b/content/renderer/loader/navigation_body_loader_unittest.cc index d751ec5..32f2db4 100644 --- a/content/renderer/loader/navigation_body_loader_unittest.cc +++ b/content/renderer/loader/navigation_body_loader_unittest.cc
@@ -41,8 +41,13 @@ } void CreateBodyLoader() { - data_pipe_ = std::make_unique<mojo::DataPipe>(CreateDataPipeOptions()); - writer_ = std::move(data_pipe_->producer_handle); + mojo::ScopedDataPipeProducerHandle producer_handle; + mojo::ScopedDataPipeConsumerHandle consumer_handle; + MojoCreateDataPipeOptions options = CreateDataPipeOptions(); + ASSERT_EQ(mojo::CreateDataPipe(&options, producer_handle, consumer_handle), + MOJO_RESULT_OK); + + writer_ = std::move(producer_handle); auto endpoints = network::mojom::URLLoaderClientEndpoints::New(); endpoints->url_loader_client = client_remote_.BindNewPipeAndPassReceiver(); blink::WebNavigationParams navigation_params; @@ -50,8 +55,8 @@ auto commit_params = CreateCommitNavigationParams(); NavigationBodyLoader::FillNavigationParamsResponseAndBodyLoader( std::move(common_params), std::move(commit_params), /*request_id=*/1, - network::mojom::URLResponseHead::New(), - std::move(data_pipe_->consumer_handle), std::move(endpoints), + network::mojom::URLResponseHead::New(), std::move(consumer_handle), + std::move(endpoints), blink::scheduler::GetSingleThreadTaskRunnerForTesting(), /*render_frame_impl=*/nullptr, /*is_main_frame=*/true, &navigation_params); @@ -154,7 +159,6 @@ static const MojoWriteDataFlags kNone = MOJO_WRITE_DATA_FLAG_NONE; mojo::Remote<network::mojom::URLLoaderClient> client_remote_; std::unique_ptr<blink::WebNavigationBodyLoader> loader_; - std::unique_ptr<mojo::DataPipe> data_pipe_; mojo::ScopedDataPipeProducerHandle writer_; base::RunLoop run_loop_;
diff --git a/content/renderer/loader/resource_dispatcher_unittest.cc b/content/renderer/loader/resource_dispatcher_unittest.cc index 96c82036..7220b1b 100644 --- a/content/renderer/loader/resource_dispatcher_unittest.cc +++ b/content/renderer/loader/resource_dispatcher_unittest.cc
@@ -261,16 +261,20 @@ // The wrapper eats all messages until RequestComplete message is sent. CallOnReceiveResponse(client.get()); - mojo::DataPipe data_pipe(DataPipeOptions()); - client->OnStartLoadingResponseBody(std::move(data_pipe.consumer_handle)); + mojo::ScopedDataPipeProducerHandle producer_handle; + mojo::ScopedDataPipeConsumerHandle consumer_handle; + auto options = DataPipeOptions(); + ASSERT_EQ(mojo::CreateDataPipe(&options, producer_handle, consumer_handle), + MOJO_RESULT_OK); + client->OnStartLoadingResponseBody(std::move(consumer_handle)); uint32_t size = strlen(kTestPageContents); - auto result = data_pipe.producer_handle->WriteData(kTestPageContents, &size, - MOJO_WRITE_DATA_FLAG_NONE); + auto result = producer_handle->WriteData(kTestPageContents, &size, + MOJO_WRITE_DATA_FLAG_NONE); ASSERT_EQ(result, MOJO_RESULT_OK); ASSERT_EQ(size, strlen(kTestPageContents)); - data_pipe.producer_handle.reset(); + producer_handle.reset(); base::RunLoop().RunUntilIdle(); @@ -307,14 +311,18 @@ dispatcher()->set_delegate(&delegate); CallOnReceiveResponse(client.get()); - mojo::DataPipe data_pipe(DataPipeOptions()); - client->OnStartLoadingResponseBody(std::move(data_pipe.consumer_handle)); + mojo::ScopedDataPipeProducerHandle producer_handle; + mojo::ScopedDataPipeConsumerHandle consumer_handle; + auto options = DataPipeOptions(); + ASSERT_EQ(mojo::CreateDataPipe(&options, producer_handle, consumer_handle), + MOJO_RESULT_OK); + client->OnStartLoadingResponseBody(std::move(consumer_handle)); uint32_t size = strlen(kTestPageContents); - auto result = data_pipe.producer_handle->WriteData(kTestPageContents, &size, - MOJO_WRITE_DATA_FLAG_NONE); + auto result = producer_handle->WriteData(kTestPageContents, &size, + MOJO_WRITE_DATA_FLAG_NONE); ASSERT_EQ(result, MOJO_RESULT_OK); ASSERT_EQ(size, strlen(kTestPageContents)); - data_pipe.producer_handle.reset(); + producer_handle.reset(); base::RunLoop().RunUntilIdle(); EXPECT_FALSE(peer_context.received_response); @@ -433,9 +441,12 @@ base::Time() + base::TimeDelta::FromSeconds(99); client->OnReceiveResponse(std::move(response_head)); - mojo::DataPipe pipe; - client->OnStartLoadingResponseBody(std::move(pipe.consumer_handle)); - pipe.producer_handle.reset(); // The response is empty. + mojo::ScopedDataPipeProducerHandle producer_handle; + mojo::ScopedDataPipeConsumerHandle consumer_handle; + ASSERT_EQ(mojo::CreateDataPipe(nullptr, producer_handle, consumer_handle), + MOJO_RESULT_OK); + client->OnStartLoadingResponseBody(std::move(consumer_handle)); + producer_handle.reset(); // The response is empty. network::URLLoaderCompletionStatus status; status.completion_time = completion_time;
diff --git a/content/renderer/service_worker/service_worker_subresource_loader_unittest.cc b/content/renderer/service_worker/service_worker_subresource_loader_unittest.cc index 3b8c008..2565cd5 100644 --- a/content/renderer/service_worker/service_worker_subresource_loader_unittest.cc +++ b/content/renderer/service_worker/service_worker_subresource_loader_unittest.cc
@@ -208,20 +208,23 @@ *out_string = std::string(element.As<network::DataElementBytes>().AsStringPiece()); } else if (element.type() == network::DataElement::Tag::kDataPipe) { - // Read the content into |data_pipe|. - mojo::DataPipe data_pipe; + // Read the content into |producer_handle|. + mojo::ScopedDataPipeProducerHandle producer_handle; + mojo::ScopedDataPipeConsumerHandle consumer_handle; + ASSERT_EQ(mojo::CreateDataPipe(nullptr, producer_handle, consumer_handle), + MOJO_RESULT_OK); + mojo::Remote<network::mojom::DataPipeGetter> remote( element.As<network::DataElementDataPipe>().ReleaseDataPipeGetter()); base::RunLoop run_loop; remote->Read( - std::move(data_pipe.producer_handle), + std::move(producer_handle), base::BindOnce([](base::OnceClosure quit_closure, int32_t status, uint64_t size) { std::move(quit_closure).Run(); }, run_loop.QuitClosure())); run_loop.Run(); // Copy the content to |out_string|. - mojo::BlockingCopyToString(std::move(data_pipe.consumer_handle), - out_string); + mojo::BlockingCopyToString(std::move(consumer_handle), out_string); } else { NOTREACHED(); } @@ -923,10 +926,12 @@ // Construct the Stream to respond with. const char kResponseBody[] = "Here is sample text for the Stream."; mojo::Remote<blink::mojom::ServiceWorkerStreamCallback> stream_callback; - mojo::DataPipe data_pipe; + mojo::ScopedDataPipeProducerHandle producer_handle; + mojo::ScopedDataPipeConsumerHandle consumer_handle; + ASSERT_EQ(mojo::CreateDataPipe(nullptr, producer_handle, consumer_handle), + MOJO_RESULT_OK); fake_controller_.RespondWithStream( - stream_callback.BindNewPipeAndPassReceiver(), - std::move(data_pipe.consumer_handle)); + stream_callback.BindNewPipeAndPassReceiver(), std::move(consumer_handle)); fake_controller_.SetResponseSource( network::mojom::FetchResponseSource::kNetwork); @@ -949,12 +954,12 @@ // Write the body stream. uint32_t written_bytes = sizeof(kResponseBody) - 1; - MojoResult mojo_result = data_pipe.producer_handle->WriteData( + MojoResult mojo_result = producer_handle->WriteData( kResponseBody, &written_bytes, MOJO_WRITE_DATA_FLAG_NONE); ASSERT_EQ(MOJO_RESULT_OK, mojo_result); EXPECT_EQ(sizeof(kResponseBody) - 1, written_bytes); stream_callback->OnCompleted(); - data_pipe.producer_handle.reset(); + producer_handle.reset(); client->RunUntilComplete(); EXPECT_EQ(net::OK, client->completion_status().error_code); @@ -987,10 +992,12 @@ // Construct the Stream to respond with. const char kResponseBody[] = "Here is sample text for the Stream."; mojo::Remote<blink::mojom::ServiceWorkerStreamCallback> stream_callback; - mojo::DataPipe data_pipe; + mojo::ScopedDataPipeProducerHandle producer_handle; + mojo::ScopedDataPipeConsumerHandle consumer_handle; + ASSERT_EQ(mojo::CreateDataPipe(nullptr, producer_handle, consumer_handle), + MOJO_RESULT_OK); fake_controller_.RespondWithStream( - stream_callback.BindNewPipeAndPassReceiver(), - std::move(data_pipe.consumer_handle)); + stream_callback.BindNewPipeAndPassReceiver(), std::move(consumer_handle)); mojo::Remote<network::mojom::URLLoaderFactory> factory = CreateSubresourceLoaderFactory(); @@ -1008,12 +1015,12 @@ // Start writing the body stream, then abort before finishing. uint32_t written_bytes = sizeof(kResponseBody) - 1; - MojoResult mojo_result = data_pipe.producer_handle->WriteData( + MojoResult mojo_result = producer_handle->WriteData( kResponseBody, &written_bytes, MOJO_WRITE_DATA_FLAG_NONE); ASSERT_EQ(MOJO_RESULT_OK, mojo_result); EXPECT_EQ(sizeof(kResponseBody) - 1, written_bytes); stream_callback->OnAborted(); - data_pipe.producer_handle.reset(); + producer_handle.reset(); client->RunUntilComplete(); EXPECT_EQ(net::ERR_ABORTED, client->completion_status().error_code); @@ -1294,10 +1301,12 @@ // Give the final response. const char kResponseBody[] = "Here is sample text for the Stream."; mojo::Remote<blink::mojom::ServiceWorkerStreamCallback> stream_callback; - mojo::DataPipe data_pipe; + mojo::ScopedDataPipeProducerHandle producer_handle; + mojo::ScopedDataPipeConsumerHandle consumer_handle; + ASSERT_EQ(mojo::CreateDataPipe(nullptr, producer_handle, consumer_handle), + MOJO_RESULT_OK); fake_controller_.RespondWithStream( - stream_callback.BindNewPipeAndPassReceiver(), - std::move(data_pipe.consumer_handle)); + stream_callback.BindNewPipeAndPassReceiver(), std::move(consumer_handle)); loader->FollowRedirect({}, {}, {}, base::nullopt); client->RunUntilResponseReceived(); @@ -1307,12 +1316,12 @@ // Write the body stream. uint32_t written_bytes = sizeof(kResponseBody) - 1; - MojoResult mojo_result = data_pipe.producer_handle->WriteData( + MojoResult mojo_result = producer_handle->WriteData( kResponseBody, &written_bytes, MOJO_WRITE_DATA_FLAG_NONE); ASSERT_EQ(MOJO_RESULT_OK, mojo_result); EXPECT_EQ(sizeof(kResponseBody) - 1, written_bytes); stream_callback->OnCompleted(); - data_pipe.producer_handle.reset(); + producer_handle.reset(); client->RunUntilComplete(); EXPECT_EQ(net::OK, client->completion_status().error_code);
diff --git a/content/shell/android/shell_apk/src/org/chromium/content_shell_apk/TestChildProcessService.java b/content/shell/android/shell_apk/src/org/chromium/content_shell_apk/TestChildProcessService.java index f427c2d..39b8337 100644 --- a/content/shell/android/shell_apk/src/org/chromium/content_shell_apk/TestChildProcessService.java +++ b/content/shell/android/shell_apk/src/org/chromium/content_shell_apk/TestChildProcessService.java
@@ -74,7 +74,7 @@ } @Override - public void preloadNativeLibrary(Context hostContext) { + public void preloadNativeLibrary(String packageName) { LibraryLoader.getInstance().preloadNow(); }
diff --git a/content/test/data/accessibility/html/form-validation-message-after-hide-timeout-expected-blink.txt b/content/test/data/accessibility/html/form-validation-message-after-hide-timeout-expected-blink.txt index c96e722..897a67d 100644 --- a/content/test/data/accessibility/html/form-validation-message-after-hide-timeout-expected-blink.txt +++ b/content/test/data/accessibility/html/form-validation-message-after-hide-timeout-expected-blink.txt
@@ -1,4 +1,5 @@ rootWebArea +++alert invisible containerLiveRelevant='additions' containerLiveStatus='assertive' liveRelevant='additions' liveStatus='assertive' containerLiveAtomic=true containerLiveBusy=false liveAtomic=true ++genericContainer ignored ++++genericContainer ignored ++++++form @@ -9,5 +10,4 @@ ++++++++++genericContainer ++++++++genericContainer ++++++++++staticText name='ready' -++++++++++++inlineTextBox name='ready' -++alert invisible containerLiveRelevant='additions' containerLiveStatus='assertive' liveRelevant='additions' liveStatus='assertive' containerLiveAtomic=true containerLiveBusy=false liveAtomic=true +++++++++++++inlineTextBox name='ready' \ No newline at end of file
diff --git a/content/test/data/accessibility/html/form-validation-message-expected-blink.txt b/content/test/data/accessibility/html/form-validation-message-expected-blink.txt index 82f739dec..eb960a7 100644 --- a/content/test/data/accessibility/html/form-validation-message-expected-blink.txt +++ b/content/test/data/accessibility/html/form-validation-message-expected-blink.txt
@@ -1,4 +1,5 @@ rootWebArea +++alert containerLiveRelevant='additions' containerLiveStatus='assertive' name='Please enter pet name' liveRelevant='additions' liveStatus='assertive' containerLiveAtomic=true containerLiveBusy=false liveAtomic=true ++genericContainer ignored ++++genericContainer ignored ++++++form @@ -6,5 +7,4 @@ ++++++++++staticText name='Pet name:' ++++++++++++inlineTextBox name='Pet name:' ++++++++textField required name='Pet name:' errormessageId=alert invalidState=true -++++++++++genericContainer -++alert containerLiveRelevant='additions' containerLiveStatus='assertive' name='Please enter pet name' liveRelevant='additions' liveStatus='assertive' containerLiveAtomic=true containerLiveBusy=false liveAtomic=true +++++++++++genericContainer \ No newline at end of file
diff --git a/content/test/data/accessibility/html/form-validation-message-expected-mac.txt b/content/test/data/accessibility/html/form-validation-message-expected-mac.txt index f67b883..fb6c02d 100644 --- a/content/test/data/accessibility/html/form-validation-message-expected-mac.txt +++ b/content/test/data/accessibility/html/form-validation-message-expected-mac.txt
@@ -1,6 +1,6 @@ AXWebArea +++AXGroup AXSubrole=AXApplicationAlert AXDescription='Please enter pet name' ++AXGroup ++++AXGroup ++++++AXStaticText AXValue='Pet name:' -++++AXTextField AXTitle='Pet name:' -++AXGroup AXSubrole=AXApplicationAlert AXDescription='Please enter pet name' +++++AXTextField AXTitle='Pet name:' \ No newline at end of file
diff --git a/content/test/data/accessibility/html/form-validation-message-expected-uia-win.txt b/content/test/data/accessibility/html/form-validation-message-expected-uia-win.txt index 4e33eb6..41c6a062 100644 --- a/content/test/data/accessibility/html/form-validation-message-expected-uia-win.txt +++ b/content/test/data/accessibility/html/form-validation-message-expected-uia-win.txt
@@ -1,6 +1,6 @@ Document +++Text Name='Please enter pet name' ++Group IsControlElement=false ++++Text ++++++Text Name='Pet name:' -++++Edit Name='Pet name:' IsRequiredForForm=true -++Text Name='Please enter pet name' +++++Edit Name='Pet name:' IsRequiredForForm=true \ No newline at end of file
diff --git a/content/test/data/accessibility/html/form-validation-message-expected-win.txt b/content/test/data/accessibility/html/form-validation-message-expected-win.txt index de9c8af7..4e130ed1 100644 --- a/content/test/data/accessibility/html/form-validation-message-expected-win.txt +++ b/content/test/data/accessibility/html/form-validation-message-expected-win.txt
@@ -1,6 +1,6 @@ ROLE_SYSTEM_DOCUMENT READONLY FOCUSABLE n_relations=0 +++ROLE_SYSTEM_ALERT name='Please enter pet name' n_relations=1 ++IA2_ROLE_FORM n_relations=0 ++++IA2_ROLE_LABEL n_relations=1 ++++++ROLE_SYSTEM_STATICTEXT name='Pet name:' n_relations=0 -++++ROLE_SYSTEM_TEXT name='Pet name:' FOCUSABLE IA2_STATE_INVALID_ENTRY IA2_STATE_REQUIRED n_relations=2 -++ROLE_SYSTEM_ALERT name='Please enter pet name' n_relations=1 +++++ROLE_SYSTEM_TEXT name='Pet name:' FOCUSABLE IA2_STATE_INVALID_ENTRY IA2_STATE_REQUIRED n_relations=2 \ No newline at end of file
diff --git a/content/web_test/renderer/web_frame_test_proxy.cc b/content/web_test/renderer/web_frame_test_proxy.cc index f094a565..6a7633a4 100644 --- a/content/web_test/renderer/web_frame_test_proxy.cc +++ b/content/web_test/renderer/web_frame_test_proxy.cc
@@ -20,6 +20,7 @@ #include "third_party/blink/public/web/web_frame_widget.h" #include "third_party/blink/public/web/web_local_frame.h" #include "third_party/blink/public/web/web_plugin_params.h" +#include "third_party/blink/public/web/web_print_params.h" #include "third_party/blink/public/web/web_testing_support.h" #include "third_party/blink/public/web/web_view.h" @@ -213,6 +214,18 @@ } } + void ScriptedPrint(bool user_initiated) override { + // This is using the main frame for the size, but maybe it should be using + // the frame's size. + blink::WebSize page_size_in_pixels = + frame_proxy()->GetLocalRootWebFrameWidget()->Size(); + if (page_size_in_pixels.IsEmpty()) + return; + blink::WebPrintParams print_params(page_size_in_pixels); + render_frame()->GetWebFrame()->PrintBegin(print_params, blink::WebNode()); + render_frame()->GetWebFrame()->PrintEnd(); + } + WebViewTestProxy* web_view_test_proxy_; DISALLOW_COPY_AND_ASSIGN(TestRenderFrameObserver); };
diff --git a/content/web_test/renderer/web_view_test_proxy.cc b/content/web_test/renderer/web_view_test_proxy.cc index 15a9306..c135a4c0 100644 --- a/content/web_test/renderer/web_view_test_proxy.cc +++ b/content/web_test/renderer/web_view_test_proxy.cc
@@ -16,7 +16,6 @@ #include "third_party/blink/public/platform/web_url_request.h" #include "third_party/blink/public/web/web_frame.h" #include "third_party/blink/public/web/web_local_frame.h" -#include "third_party/blink/public/web/web_print_params.h" #include "third_party/blink/public/web/web_settings.h" #include "third_party/blink/public/web/web_view.h" @@ -35,18 +34,6 @@ test_runner_->RemoveRenderView(this); } -void WebViewTestProxy::PrintPage(blink::WebLocalFrame* frame) { - // This is using the main frame for the size, but maybe it should be using the - // frame's size. - blink::WebSize page_size_in_pixels = - GetMainRenderFrame()->GetLocalRootWebFrameWidget()->Size(); - if (page_size_in_pixels.IsEmpty()) - return; - blink::WebPrintParams print_params(page_size_in_pixels); - frame->PrintBegin(print_params, blink::WebNode()); - frame->PrintEnd(); -} - void WebViewTestProxy::Reset() { accessibility_controller_.Reset(); // |text_input_controller_| doesn't have any state to reset.
diff --git a/content/web_test/renderer/web_view_test_proxy.h b/content/web_test/renderer/web_view_test_proxy.h index e1845fb7..8e63172 100644 --- a/content/web_test/renderer/web_view_test_proxy.h +++ b/content/web_test/renderer/web_view_test_proxy.h
@@ -59,9 +59,6 @@ const mojom::CreateViewParams& params, TestRunner* test_runner); - // WebViewClient implementation. - void PrintPage(blink::WebLocalFrame* frame) override; - TestRunner* GetTestRunner() { return test_runner_; } AccessibilityController* accessibility_controller() { return &accessibility_controller_;
diff --git a/device/BUILD.gn b/device/BUILD.gn index f76417e..4cfd1a0 100644 --- a/device/BUILD.gn +++ b/device/BUILD.gn
@@ -99,6 +99,7 @@ "bluetooth/bluetooth_task_manager_win_unittest.cc", "bluetooth/test/bluetooth_test_win.cc", "bluetooth/test/bluetooth_test_win.h", + "gamepad/wgi_data_fetcher_win_unittest.cc", ] }
diff --git a/device/gamepad/BUILD.gn b/device/gamepad/BUILD.gn index 939ecc6..fdc7c7f1 100644 --- a/device/gamepad/BUILD.gn +++ b/device/gamepad/BUILD.gn
@@ -176,6 +176,17 @@ "//device/gamepad/public/cpp:shared_with_blink", "//third_party/blink/public:blink_headers", ] + + if (is_win) { + sources += [ + "test_support/fake_igamepad.cc", + "test_support/fake_igamepad.h", + "test_support/fake_igamepad_statics.cc", + "test_support/fake_igamepad_statics.h", + "test_support/fake_ro_get_activation_factory.cc", + "test_support/fake_ro_get_activation_factory.h", + ] + } } if (is_android) {
diff --git a/device/gamepad/test_support/fake_igamepad.cc b/device/gamepad/test_support/fake_igamepad.cc new file mode 100644 index 0000000..fb4673ce --- /dev/null +++ b/device/gamepad/test_support/fake_igamepad.cc
@@ -0,0 +1,32 @@ +// Copyright 2021 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 "device/gamepad/test_support/fake_igamepad.h" + +#include "base/notreached.h" + +namespace device { + +FakeIGamepad::FakeIGamepad() = default; +FakeIGamepad::~FakeIGamepad() = default; + +HRESULT WINAPI +FakeIGamepad::get_Vibration(ABI::Windows::Gaming::Input::GamepadVibration*) { + NOTIMPLEMENTED(); + return E_NOTIMPL; +} + +HRESULT WINAPI +FakeIGamepad::put_Vibration(ABI::Windows::Gaming::Input::GamepadVibration) { + NOTIMPLEMENTED(); + return E_NOTIMPL; +} + +HRESULT WINAPI +FakeIGamepad::GetCurrentReading(ABI::Windows::Gaming::Input::GamepadReading*) { + NOTIMPLEMENTED(); + return E_NOTIMPL; +} + +} // namespace device
diff --git a/device/gamepad/test_support/fake_igamepad.h b/device/gamepad/test_support/fake_igamepad.h new file mode 100644 index 0000000..6b12c37 --- /dev/null +++ b/device/gamepad/test_support/fake_igamepad.h
@@ -0,0 +1,37 @@ +// Copyright 2021 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 DEVICE_GAMEPAD_TEST_SUPPORT_FAKE_IGAMEPAD_H_ +#define DEVICE_GAMEPAD_TEST_SUPPORT_FAKE_IGAMEPAD_H_ + +#include <Windows.Gaming.Input.h> +#include <wrl.h> + +namespace device { + +class FakeIGamepad final + : public Microsoft::WRL::RuntimeClass< + Microsoft::WRL::RuntimeClassFlags< + Microsoft::WRL::WinRt | Microsoft::WRL::InhibitRoOriginateError>, + ABI::Windows::Gaming::Input::IGamepad> { + public: + FakeIGamepad(); + FakeIGamepad(const FakeIGamepad&) = delete; + FakeIGamepad& operator=(const FakeIGamepad&) = delete; + + // ABI::Windows::Gaming::Input::IGamepad fake implementation. + HRESULT WINAPI + get_Vibration(ABI::Windows::Gaming::Input::GamepadVibration*) override; + HRESULT WINAPI + put_Vibration(ABI::Windows::Gaming::Input::GamepadVibration) override; + HRESULT WINAPI + GetCurrentReading(ABI::Windows::Gaming::Input::GamepadReading*) override; + + private: + ~FakeIGamepad() final; +}; + +} // namespace device + +#endif // DEVICE_GAMEPAD_TEST_SUPPORT_FAKE_IGAMEPAD_H_
diff --git a/device/gamepad/test_support/fake_igamepad_statics.cc b/device/gamepad/test_support/fake_igamepad_statics.cc new file mode 100644 index 0000000..762465d --- /dev/null +++ b/device/gamepad/test_support/fake_igamepad_statics.cc
@@ -0,0 +1,112 @@ +// Copyright 2021 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 "device/gamepad/test_support/fake_igamepad_statics.h" + +#include "base/notreached.h" + +namespace device { + +FakeIGamepadStatics::FakeIGamepadStatics() = default; + +FakeIGamepadStatics::~FakeIGamepadStatics() = default; + +// static +FakeIGamepadStatics* FakeIGamepadStatics::GetInstance() { + static FakeIGamepadStatics* instance; + if (!instance) + instance = Microsoft::WRL::Make<FakeIGamepadStatics>().Detach(); + return instance; +} + +HRESULT WINAPI FakeIGamepadStatics::add_GamepadAdded( + ABI::Windows::Foundation::IEventHandler< + ABI::Windows::Gaming::Input::Gamepad*>* event_handler, + EventRegistrationToken* token) { + if (add_gamepad_added_status_ != S_OK) + return add_gamepad_added_status_; + + token->value = next_event_registration_token_++; + + auto ret = gamepad_added_event_handler_map_.insert( + {token->value, + Microsoft::WRL::ComPtr<ABI::Windows::Foundation::IEventHandler< + ABI::Windows::Gaming::Input::Gamepad*>>{event_handler}}); + if (ret.second) + return S_OK; + return E_FAIL; +} + +HRESULT WINAPI FakeIGamepadStatics::add_GamepadRemoved( + ABI::Windows::Foundation::IEventHandler< + ABI::Windows::Gaming::Input::Gamepad*>* event_handler, + EventRegistrationToken* token) { + if (add_gamepad_removed_status_ != S_OK) + return add_gamepad_removed_status_; + + token->value = next_event_registration_token_++; + + auto ret = gamepad_removed_event_handler_map_.insert( + {token->value, + Microsoft::WRL::ComPtr<ABI::Windows::Foundation::IEventHandler< + ABI::Windows::Gaming::Input::Gamepad*>>{event_handler}}); + if (ret.second) + return S_OK; + return E_FAIL; +} + +HRESULT WINAPI +FakeIGamepadStatics::remove_GamepadAdded(EventRegistrationToken token) { + NOTIMPLEMENTED(); + return E_NOTIMPL; +} + +HRESULT WINAPI +FakeIGamepadStatics::remove_GamepadRemoved(EventRegistrationToken token) { + NOTIMPLEMENTED(); + return E_NOTIMPL; +} + +HRESULT WINAPI FakeIGamepadStatics::get_Gamepads( + ABI::Windows::Foundation::Collections::IVectorView< + ABI::Windows::Gaming::Input::Gamepad*>** value) { + NOTIMPLEMENTED(); + return E_NOTIMPL; +} + +void FakeIGamepadStatics::SimulateGamepadAdded( + const Microsoft::WRL::ComPtr<ABI::Windows::Gaming::Input::IGamepad>& + gamepad_to_add) { + // Iterate through |gamepad_added_event_handler_map_| invoking each + // callback with |gamepad_to_add|. + for (const auto& entry : gamepad_added_event_handler_map_) + entry.second->Invoke(this, gamepad_to_add.Get()); +} + +void FakeIGamepadStatics::SimulateGamepadRemoved( + const Microsoft::WRL::ComPtr<ABI::Windows::Gaming::Input::IGamepad>& + gamepad_to_remove) { + // Iterate through |gamepad_removed_event_handler_map_| invoking each + // callback with |gamepad_to_remove|. + for (const auto& entry : gamepad_removed_event_handler_map_) + entry.second->Invoke(this, gamepad_to_remove.Get()); +} + +void FakeIGamepadStatics::SetAddGamepadAddedStatus(HRESULT value) { + add_gamepad_added_status_ = value; +} + +void FakeIGamepadStatics::SetAddGamepadRemovedStatus(HRESULT value) { + add_gamepad_removed_status_ = value; +} + +size_t FakeIGamepadStatics::GetGamepadAddedEventHandlerCount() const { + return gamepad_added_event_handler_map_.size(); +} + +size_t FakeIGamepadStatics::GetGamepadRemovedEventHandlerCount() const { + return gamepad_removed_event_handler_map_.size(); +} + +} // namespace device
diff --git a/device/gamepad/test_support/fake_igamepad_statics.h b/device/gamepad/test_support/fake_igamepad_statics.h new file mode 100644 index 0000000..68aa85a77 --- /dev/null +++ b/device/gamepad/test_support/fake_igamepad_statics.h
@@ -0,0 +1,86 @@ +// Copyright 2021 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 DEVICE_GAMEPAD_TEST_SUPPORT_FAKE_IGAMEPAD_STATICS_H_ +#define DEVICE_GAMEPAD_TEST_SUPPORT_FAKE_IGAMEPAD_STATICS_H_ + +#include <Windows.Gaming.Input.h> +#include <wrl.h> + +#include <map> + +#include "base/containers/flat_map.h" + +namespace device { + +class FakeIGamepadStatics final + : public Microsoft::WRL::RuntimeClass< + Microsoft::WRL::RuntimeClassFlags< + Microsoft::WRL::WinRt | Microsoft::WRL::InhibitRoOriginateError>, + ABI::Windows::Gaming::Input::IGamepadStatics> { + public: + FakeIGamepadStatics(); + + FakeIGamepadStatics(const FakeIGamepadStatics&) = delete; + FakeIGamepadStatics& operator=(const FakeIGamepadStatics&) = delete; + + static FakeIGamepadStatics* GetInstance(); + + // ABI::Windows::Gaming::Input::IGamepadStatics fake implementation. + HRESULT WINAPI + add_GamepadAdded(ABI::Windows::Foundation::IEventHandler< + ABI::Windows::Gaming::Input::Gamepad*>* value, + EventRegistrationToken* token) final; + HRESULT WINAPI + add_GamepadRemoved(ABI::Windows::Foundation::IEventHandler< + ABI::Windows::Gaming::Input::Gamepad*>* value, + EventRegistrationToken* token) final; + HRESULT WINAPI remove_GamepadAdded(EventRegistrationToken token) final; + HRESULT WINAPI remove_GamepadRemoved(EventRegistrationToken token) final; + HRESULT WINAPI + get_Gamepads(ABI::Windows::Foundation::Collections::IVectorView< + ABI::Windows::Gaming::Input::Gamepad*>** value) final; + + // Adds a fake gamepad to simulate a gamepad connection operation for test. + void SimulateGamepadAdded( + const Microsoft::WRL::ComPtr<ABI::Windows::Gaming::Input::IGamepad>& + gamepad_to_add); + + // Uses a fake gamepad to simulate a gamepad disconnection operation for test. + void SimulateGamepadRemoved( + const Microsoft::WRL::ComPtr<ABI::Windows::Gaming::Input::IGamepad>& + gamepad_to_remove); + + // Sets |add_gamepad_added_status_| and |add_gamepad_removed_status_| to test + // Windows.Gaming.Input error handling logics in tests. + void SetAddGamepadAddedStatus(HRESULT value); + void SetAddGamepadRemovedStatus(HRESULT value); + + size_t GetGamepadAddedEventHandlerCount() const; + size_t GetGamepadRemovedEventHandlerCount() const; + + private: + typedef base::flat_map< + int64_t /* event_registration_token */, + Microsoft::WRL::ComPtr<ABI::Windows::Foundation::IEventHandler< + ABI::Windows::Gaming::Input::Gamepad*>>> + EventHandlerMap; + + ~FakeIGamepadStatics() final; + + int64_t next_event_registration_token_ = 0; + + // Status variable to direct tests to test Windows.Gaming.Input error + // handling. If set to E_FAIL, add_GamepadAdded and add_GamepadRemoved would + // return E_FAIL error code directly. + HRESULT add_gamepad_added_status_ = S_OK; + HRESULT add_gamepad_removed_status_ = S_OK; + + EventHandlerMap gamepad_added_event_handler_map_; + EventHandlerMap gamepad_removed_event_handler_map_; +}; + +} // namespace device + +#endif // DEVICE_GAMEPAD_TEST_SUPPORT_FAKE_IGAMEPAD_STATICS_H_
diff --git a/device/gamepad/test_support/fake_ro_get_activation_factory.cc b/device/gamepad/test_support/fake_ro_get_activation_factory.cc new file mode 100644 index 0000000..ad71f5f --- /dev/null +++ b/device/gamepad/test_support/fake_ro_get_activation_factory.cc
@@ -0,0 +1,42 @@ +// Copyright 2021 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 <wrl.h> +#include <wrl/event.h> + +#include "base/notreached.h" +#include "base/strings/string16.h" +#include "base/strings/string_piece.h" +#include "base/win/scoped_hstring.h" +#include "device/gamepad/test_support/fake_igamepad_statics.h" +#include "device/gamepad/test_support/fake_ro_get_activation_factory.h" + +namespace device { + +HRESULT FakeRoGetActivationFactory(HSTRING class_id, + const IID& iid, + void** out_factory) { + base::win::ScopedHString class_id_hstring(class_id); + + if (class_id_hstring.Get() != RuntimeClass_Windows_Gaming_Input_Gamepad) + return E_NOTIMPL; + + Microsoft::WRL::ComPtr<FakeIGamepadStatics> gamepad_statics = + FakeIGamepadStatics::GetInstance(); + *out_factory = gamepad_statics.Detach(); + + if (*out_factory == nullptr) { + NOTIMPLEMENTED(); + return E_NOTIMPL; + } + return S_OK; +} + +HRESULT FakeRoGetActivationFactoryToTestErrorHandling(HSTRING class_id, + const IID& iid, + void** out_factory) { + return E_FAIL; +} + +} // namespace device
diff --git a/device/gamepad/test_support/fake_ro_get_activation_factory.h b/device/gamepad/test_support/fake_ro_get_activation_factory.h new file mode 100644 index 0000000..4d64dc18 --- /dev/null +++ b/device/gamepad/test_support/fake_ro_get_activation_factory.h
@@ -0,0 +1,28 @@ +// Copyright 2021 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 DEVICE_GAMEPAD_TEST_SUPPORT_FAKE_RO_GET_ACTIVATION_FACTORY_H_ +#define DEVICE_GAMEPAD_TEST_SUPPORT_FAKE_RO_GET_ACTIVATION_FACTORY_H_ + +#include <hstring.h> +#include <inspectable.h> +#include <roapi.h> +#include <windef.h> + +namespace device { + +// Fake implementation of base::win::RoGetActivationFactory for test. +HRESULT FakeRoGetActivationFactory(HSTRING class_id, + const IID& iid, + void** out_factory); + +// Fake implementation of base::win::RoGetActivationFactory to test +// corresponding error handling. +HRESULT FakeRoGetActivationFactoryToTestErrorHandling(HSTRING class_id, + const IID& iid, + void** out_factory); + +} // namespace device + +#endif // DEVICE_GAMEPAD_TEST_SUPPORT_FAKE_RO_GET_ACTIVATION_FACTORY_H_
diff --git a/device/gamepad/wgi_data_fetcher_win.cc b/device/gamepad/wgi_data_fetcher_win.cc index 59a385f0..dbf62ad 100644 --- a/device/gamepad/wgi_data_fetcher_win.cc +++ b/device/gamepad/wgi_data_fetcher_win.cc
@@ -4,9 +4,20 @@ #include "device/gamepad/wgi_data_fetcher_win.h" +#include <wrl/event.h> + +#include "base/win/core_winrt_util.h" +#include "base/win/hstring_reference.h" +#include "base/win/scoped_hstring.h" + namespace device { -WgiDataFetcherWin::WgiDataFetcherWin() = default; +using GamepadPlugAndPlayHandler = ABI::Windows::Foundation::IEventHandler< + ABI::Windows::Gaming::Input::Gamepad*>; + +WgiDataFetcherWin::WgiDataFetcherWin() { + get_activation_factory_function_ = &base::win::RoGetActivationFactory; +} WgiDataFetcherWin::~WgiDataFetcherWin() = default; @@ -14,6 +25,121 @@ return Factory::static_source(); } -void WgiDataFetcherWin::GetGamepadData(bool devices_changed_hint) {} +void WgiDataFetcherWin::OnAddedToProvider() { + if (!base::win::HStringReference::ResolveCoreWinRTStringDelayload()) { + initialization_state_ = + InitializationState::kCoreWinrtStringDelayLoadFailed; + return; + } + + HRESULT hr = get_activation_factory_function_( + base::win::HStringReference(RuntimeClass_Windows_Gaming_Input_Gamepad) + .Get(), + IID_PPV_ARGS(&gamepad_statics_)); + if (FAILED(hr)) { + initialization_state_ = InitializationState::kRoGetActivationFactoryFailed; + return; + } + + EventRegistrationToken added_event_token; + hr = gamepad_statics_->add_GamepadAdded( + Microsoft::WRL::Callback<GamepadPlugAndPlayHandler>( + this, &WgiDataFetcherWin::OnGamepadAdded) + .Get(), + &added_event_token); + if (FAILED(hr)) { + initialization_state_ = InitializationState::kAddGamepadAddedFailed; + return; + } + + EventRegistrationToken removed_event_token; + hr = gamepad_statics_->add_GamepadRemoved( + Microsoft::WRL::Callback<GamepadPlugAndPlayHandler>( + this, &WgiDataFetcherWin::OnGamepadRemoved) + .Get(), + &removed_event_token); + if (FAILED(hr)) { + initialization_state_ = InitializationState::kAddGamepadRemovedFailed; + return; + } + + initialization_state_ = InitializationState::kInitialized; +} + +void WgiDataFetcherWin::SetGetActivationFunctionForTesting( + GetActivationFactoryFunction value) { + get_activation_factory_function_ = value; +} + +HRESULT WgiDataFetcherWin::OnGamepadAdded( + IInspectable* /* sender */, + ABI::Windows::Gaming::Input::IGamepad* gamepad) { + if (initialization_state_ != InitializationState::kInitialized) + return S_OK; + + int source_id = next_source_id_++; + PadState* state = GetPadState(source_id); + if (!state) + return S_OK; + state->is_initialized = true; + Gamepad& pad = state->data; + pad.connected = true; + pad.vibration_actuator.type = GamepadHapticActuatorType::kDualRumble; + pad.vibration_actuator.not_null = false; + pad.mapping = GamepadMapping::kStandard; + gamepads_.push_back({source_id, gamepad}); + return S_OK; +} + +HRESULT WgiDataFetcherWin::OnGamepadRemoved( + IInspectable* /* sender */, + ABI::Windows::Gaming::Input::IGamepad* gamepad) { + if (initialization_state_ != InitializationState::kInitialized) + return S_OK; + + auto gamepad_it = + std::find_if(gamepads_.begin(), gamepads_.end(), + [=](const WindowsGamingInputControllerMapping& mapping) { + return mapping.gamepad.Get() == gamepad; + }); + + if (gamepad_it != gamepads_.end()) { + PadState* state = GetPadState(gamepad_it->source_id); + if (!state) + return S_OK; + state->source = GAMEPAD_SOURCE_NONE; + gamepads_.erase(gamepad_it); + } + return S_OK; +} + +void WgiDataFetcherWin::GetGamepadData(bool devices_changed_hint) { + // TODO(https://crbug.com/1105671): Implement the WgiDataFetcherWin + // and add corresponding tests +} + +const std::vector<WgiDataFetcherWin::WindowsGamingInputControllerMapping>& +WgiDataFetcherWin::GetGamepadsForTesting() const { + return gamepads_; +} + +WgiDataFetcherWin::InitializationState +WgiDataFetcherWin::GetInitializationState() const { + return initialization_state_; +} + +WgiDataFetcherWin::WindowsGamingInputControllerMapping:: + WindowsGamingInputControllerMapping( + int input_source_id, + Microsoft::WRL::ComPtr<ABI::Windows::Gaming::Input::IGamepad> + input_gamepad) + : source_id(input_source_id), gamepad(input_gamepad) {} + +WgiDataFetcherWin::WindowsGamingInputControllerMapping:: + ~WindowsGamingInputControllerMapping() = default; + +WgiDataFetcherWin::WindowsGamingInputControllerMapping:: + WindowsGamingInputControllerMapping( + const WindowsGamingInputControllerMapping& other) = default; } // namespace device
diff --git a/device/gamepad/wgi_data_fetcher_win.h b/device/gamepad/wgi_data_fetcher_win.h index 9b90273..fde8b21 100644 --- a/device/gamepad/wgi_data_fetcher_win.h +++ b/device/gamepad/wgi_data_fetcher_win.h
@@ -7,23 +7,87 @@ #include "device/gamepad/gamepad_data_fetcher.h" +#include <Windows.Gaming.Input.h> +#include <wrl/event.h> + namespace device { -class WgiDataFetcherWin : public GamepadDataFetcher { +class DEVICE_GAMEPAD_EXPORT WgiDataFetcherWin final + : public GamepadDataFetcher { public: - typedef GamepadDataFetcherFactoryImpl<WgiDataFetcherWin, - GAMEPAD_SOURCE_WIN_WGI> - Factory; + struct WindowsGamingInputControllerMapping { + public: + WindowsGamingInputControllerMapping( + int input_source_id, + Microsoft::WRL::ComPtr<ABI::Windows::Gaming::Input::IGamepad> + input_gamepad); + WindowsGamingInputControllerMapping( + const WindowsGamingInputControllerMapping& other); + ~WindowsGamingInputControllerMapping(); + + int source_id; + Microsoft::WRL::ComPtr<ABI::Windows::Gaming::Input::IGamepad> gamepad; + }; + + enum class InitializationState { + kUninitialized, + kInitialized, + kAddGamepadAddedFailed, + kAddGamepadRemovedFailed, + kRoGetActivationFactoryFailed, + kCoreWinrtStringDelayLoadFailed, + }; + + using Factory = + GamepadDataFetcherFactoryImpl<WgiDataFetcherWin, GAMEPAD_SOURCE_WIN_WGI>; + + // Define test hooks to use a fake WinRT RoGetActivationFactory + // implementation to avoid dependencies on the OS for WGI testing. + using GetActivationFactoryFunction = HRESULT (*)(HSTRING class_id, + const IID& iid, + void** out_factory); WgiDataFetcherWin(); WgiDataFetcherWin(const WgiDataFetcherWin&) = delete; WgiDataFetcherWin& operator=(const WgiDataFetcherWin&) = delete; ~WgiDataFetcherWin() override; - GamepadSource source() override; - // GamepadDataFetcher implementation. + GamepadSource source() override; + void OnAddedToProvider() override; void GetGamepadData(bool devices_changed_hint) override; + + // Set fake ActivationFunction for test to avoid dependencies on the OS API. + void SetGetActivationFunctionForTesting(GetActivationFactoryFunction value); + + const std::vector<WindowsGamingInputControllerMapping>& + GetGamepadsForTesting() const; + + InitializationState GetInitializationState() const; + + private: + // Set the state of the new connected gamepad to initialized, update + // gamepad state connection status, and add a new controller mapping for + // |gamepad| to |gamepads_|. + HRESULT OnGamepadAdded(IInspectable* /* sender */, + ABI::Windows::Gaming::Input::IGamepad* gamepad); + + // Remove the gamepad from the connected WGI gamepad list. + HRESULT OnGamepadRemoved(IInspectable* /* sender */, + ABI::Windows::Gaming::Input::IGamepad* gamepad); + + int next_source_id_ = 0; + InitializationState initialization_state_ = + InitializationState::kUninitialized; + + std::vector<WindowsGamingInputControllerMapping> gamepads_; + + Microsoft::WRL::ComPtr<ABI::Windows::Gaming::Input::IGamepadStatics> + gamepad_statics_; + + GetActivationFactoryFunction get_activation_factory_function_; + + SEQUENCE_CHECKER(sequence_checker_); }; } // namespace device
diff --git a/device/gamepad/wgi_data_fetcher_win_unittest.cc b/device/gamepad/wgi_data_fetcher_win_unittest.cc new file mode 100644 index 0000000..6f5f7c78 --- /dev/null +++ b/device/gamepad/wgi_data_fetcher_win_unittest.cc
@@ -0,0 +1,134 @@ +// Copyright 2021 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 "device/gamepad/wgi_data_fetcher_win.h" + +#include "base/run_loop.h" +#include "base/threading/thread.h" +#include "base/win/scoped_hstring.h" +#include "device/gamepad/gamepad_provider.h" +#include "device/gamepad/test_support/fake_igamepad.h" +#include "device/gamepad/test_support/fake_igamepad_statics.h" +#include "device/gamepad/test_support/fake_ro_get_activation_factory.h" +#include "services/device/device_service_test_base.h" +#include "testing/gtest/include/gtest/gtest.h" + +namespace device { + +class WgiDataFetcherWinTest : public DeviceServiceTestBase { + public: + WgiDataFetcherWinTest() = default; + ~WgiDataFetcherWinTest() override = default; + + void SetUpTestEnv( + WgiDataFetcherWin::GetActivationFactoryFunction activation_factory) { + EXPECT_TRUE(base::win::ScopedHString::ResolveCoreWinRTStringDelayload()); + auto fetcher = std::make_unique<WgiDataFetcherWin>(); + fetcher->SetGetActivationFunctionForTesting(activation_factory); + fetcher_ = fetcher.get(); + + // Initialize provider to retrieve pad state. + auto polling_thread = std::make_unique<base::Thread>("polling thread"); + polling_thread_ = polling_thread.get(); + provider_ = std::make_unique<GamepadProvider>( + /*connection_change_client=*/nullptr, std::move(fetcher), + std::move(polling_thread)); + + RunUntilIdle(); + } + + void RunUntilIdle() { + base::RunLoop().RunUntilIdle(); + polling_thread_->FlushForTesting(); + } + + WgiDataFetcherWin& fetcher() const { return *fetcher_; } + + private: + WgiDataFetcherWin* fetcher_; + base::Thread* polling_thread_; + std::unique_ptr<GamepadProvider> provider_; +}; + +TEST_F(WgiDataFetcherWinTest, AddAndRemoveWgiGamepad) { + SetUpTestEnv(&FakeRoGetActivationFactory); + + // Check initial number of connected gamepad and WGI initialization status. + EXPECT_EQ(fetcher().GetInitializationState(), + device::WgiDataFetcherWin::InitializationState::kInitialized); + EXPECT_TRUE(fetcher().GetGamepadsForTesting().empty()); + + const auto fake_gamepad = Microsoft::WRL::Make<FakeIGamepad>(); + auto* fake_gamepad_statics = FakeIGamepadStatics::GetInstance(); + + // Check that the event handlers were added. + EXPECT_EQ(fake_gamepad_statics->GetGamepadAddedEventHandlerCount(), 1u); + EXPECT_EQ(fake_gamepad_statics->GetGamepadRemovedEventHandlerCount(), 1u); + + // Add a simulated WGI device. + fake_gamepad_statics->SimulateGamepadAdded(fake_gamepad); + + // Check size of connected gamepad list and ensure gamepad state + // is initialized correctly. + EXPECT_EQ(fetcher().GetGamepadsForTesting().size(), 1u); + PadState* state = fetcher().GetPadState( + fetcher().GetGamepadsForTesting().front().source_id); + EXPECT_TRUE(state->is_initialized); + Gamepad& pad = state->data; + EXPECT_TRUE(pad.connected); + EXPECT_FALSE(pad.vibration_actuator.not_null); + + // Remove the device. + fake_gamepad_statics->SimulateGamepadRemoved(fake_gamepad); + + // Check that the device was removed. + EXPECT_TRUE(fetcher().GetGamepadsForTesting().empty()); +} + +TEST_F(WgiDataFetcherWinTest, VerifyGamepadAddedErrorHandling) { + FakeIGamepadStatics* fake_gamepad_statics = + FakeIGamepadStatics::GetInstance(); + + // Let fake gamepad statics add_GamepadAdded return failure code to + // test error handling. + fake_gamepad_statics->SetAddGamepadAddedStatus(E_FAIL); + + SetUpTestEnv(&FakeRoGetActivationFactory); + + // Check WGI initialization status. + EXPECT_EQ( + fetcher().GetInitializationState(), + device::WgiDataFetcherWin::InitializationState::kAddGamepadAddedFailed); + fake_gamepad_statics->SetAddGamepadAddedStatus(S_OK); +} + +TEST_F(WgiDataFetcherWinTest, VerifyGamepadRemovedErrorHandling) { + FakeIGamepadStatics* fake_gamepad_statics = + FakeIGamepadStatics::GetInstance(); + + // Let fake gamepad statics add_GamepadRemoved return failure code to + // test error handling. + fake_gamepad_statics->SetAddGamepadRemovedStatus(E_FAIL); + + SetUpTestEnv(&FakeRoGetActivationFactory); + + // Check WGI initialization status. + EXPECT_EQ( + fetcher().GetInitializationState(), + device::WgiDataFetcherWin::InitializationState::kAddGamepadRemovedFailed); + fake_gamepad_statics->SetAddGamepadRemovedStatus(S_OK); +} + +TEST_F(WgiDataFetcherWinTest, VerifyRoGetActivationFactoryErrorHandling) { + // Let fake RoGetActivationFactory return failure code to + // test error handling. + SetUpTestEnv(&FakeRoGetActivationFactoryToTestErrorHandling); + + // Check WGI initialization status. + EXPECT_EQ(fetcher().GetInitializationState(), + device::WgiDataFetcherWin::InitializationState:: + kRoGetActivationFactoryFailed); +} + +} // namespace device
diff --git a/docs/android_dynamic_feature_modules.md b/docs/android_dynamic_feature_modules.md index 3e5dd23..7bdf050 100644 --- a/docs/android_dynamic_feature_modules.md +++ b/docs/android_dynamic_feature_modules.md
@@ -580,8 +580,8 @@ lang="am" type="android" /> <!-- List output file for all other supported languages. See - //chrome/android/java/strings/android_chrome_strings.grd for the full - list. --> + //chrome/browser/ui/android/strings/android_chrome_strings.grd for the + full list. --> ... </outputs> <translations>
diff --git a/docs/android_native_libraries.md b/docs/android_native_libraries.md index 902c685..8a5062d 100644 --- a/docs/android_native_libraries.md +++ b/docs/android_native_libraries.md
@@ -186,7 +186,7 @@ * For Android N-P: * The OS maintains a RELRO file on disk with the contents of the GNU_RELRO segment. * All Android apps that contain a WebView load `libmonochrome.so` at the same virtual address and apply RELRO sharing against the memory-mapped RELRO file. - * Chrome uses `MonochromeLibraryPreloader` to call into the same WebView library loading code. + * Chrome uses `WebViewLibraryPreloader` to call into the same WebView library loading code. * When Monochrome is the WebView provider, `libmonochrome.so` is loaded with the system's cached RELRO's applied. * `System.loadLibrary()` is called afterwards. * When Monochrome is the WebView provider, this only calls JNI_OnLoad, since the library is already loaded. Otherwise, this loads the library and no RELRO sharing occurs.
diff --git a/docs/ozone_overview.md b/docs/ozone_overview.md index 3c0546ea0..96a6176 100644 --- a/docs/ozone_overview.md +++ b/docs/ozone_overview.md
@@ -306,6 +306,21 @@ use_gtk=true ``` +Running some test suites requires a Wayland server. If you're not +running one you can use a locally compiled version of Weston. This is +what the build bots do. Add this to your gn args: + +``` shell +use_bundled_weston = true +``` + +Then run the xvfb.py wrapper script and tell it to start Weston: + +``` shell +cd out/debug # or your out directory +../../testing/xvfb.py --use-weston --no-xvfb ./views_unittests --ozone-platform=wayland --enable-features=UseOzonePlatform +``` + Feel free to discuss with us on freenode.net, `#ozone-wayland` channel or on `ozone-dev`, or on `#ozone-wayland-x11` channel in [chromium slack](https://www.chromium.org/developers/slack).
diff --git a/docs/testing/code_coverage.md b/docs/testing/code_coverage.md index 48db5f9..a97ed21 100644 --- a/docs/testing/code_coverage.md +++ b/docs/testing/code_coverage.md
@@ -124,7 +124,8 @@ The [coverage script] automates the process described below and provides a one-stop service to generate code coverage reports locally in just one command. -This script is currently supported on Linux, Mac, iOS and ChromeOS platforms. +This script is currently supported on Android, Linux, Mac, iOS and ChromeOS +platforms. Here is an example usage: @@ -185,7 +186,8 @@ profiles. To limit the number of raw profiles, `%Nm` pattern in `LLVM_PROFILE_FILE` environment variable is used to run tests in multi-process mode, where `N` is the number of raw profiles. With `N = 4`, the total size of -the raw profiles are limited to a few gigabytes. +the raw profiles are limited to a few gigabytes. (If working on Android, the +.profraw files will be located in ./out/coverage/coverage by default.) ``` $ export LLVM_PROFILE_FILE="out/report/crypto_unittests.%4m.profraw" @@ -233,6 +235,9 @@ out/coverage/crypto_unittests ``` +If creating a report for Android, the -object arg would be the lib.unstripped +file, ie out/coverage/lib.unstripped/libcrypto_unittests__library.so + For more information on how to use llvm-cov, please refer to the [guide]. ## Contacts
diff --git a/docs/ui/views/class_splitting.md b/docs/ui/views/class_splitting.md index acf3c94..fd62da8 100644 --- a/docs/ui/views/class_splitting.md +++ b/docs/ui/views/class_splitting.md
@@ -107,7 +107,7 @@ std::unique_ptr<View> MakeContentsView(); std::unique_ptr<DialogDelegate> MakeDialogDelegate(); - base::CallbackList::Subscription model_subscription_; + base::CallbackListSubscription model_subscription_; std::unique_ptr<DialogDelegate> delegate_; @@ -283,5 +283,5 @@ Note that instances of `MyDialog` are not owned by anyone now, which is bad. If the class still needs to exist at all, give it ownership semantics; otherwise, it may be possible to refactor the `MyDialog` class away entirely - into a single function that creates the `DialogDelegate` and `View` members, + into a single function that creates the `DialogDelegate` and `View` members, sets up the `Widget`, and returns.
diff --git a/fuchsia/base/agent_impl.h b/fuchsia/base/agent_impl.h index 389efb30..918282cd 100644 --- a/fuchsia/base/agent_impl.h +++ b/fuchsia/base/agent_impl.h
@@ -126,7 +126,7 @@ const CreateComponentStateCallback create_component_state_callback_; // Binds this Agent implementation into the |outgoing_directory|. - base::fuchsia::ScopedServiceBinding<::fuchsia::modular::Agent> agent_binding_; + base::ScopedServiceBinding<::fuchsia::modular::Agent> agent_binding_; // Owns the ComponentState instances for each connected component. base::flat_map<std::string, std::unique_ptr<ComponentStateBase>>
diff --git a/fuchsia/base/agent_impl_unittests.cc b/fuchsia/base/agent_impl_unittests.cc index f6a95df..9033219 100644 --- a/fuchsia/base/agent_impl_unittests.cc +++ b/fuchsia/base/agent_impl_unittests.cc
@@ -53,8 +53,7 @@ protected: AccumulatingTestInterfaceImpl service_; - base::fuchsia::ScopedServiceBinding<base::testfidl::TestInterface> - service_binding_; + base::ScopedServiceBinding<base::testfidl::TestInterface> service_binding_; }; class KeepAliveComponentState : public AccumulatorComponentState {
diff --git a/fuchsia/base/fake_component_context.h b/fuchsia/base/fake_component_context.h index 43beae2..b7af731 100644 --- a/fuchsia/base/fake_component_context.h +++ b/fuchsia/base/fake_component_context.h
@@ -43,8 +43,7 @@ void NotImplemented_(const std::string& name) override; private: - base::fuchsia::ScopedServiceBinding<fuchsia::modular::ComponentContext> - binding_; + base::ScopedServiceBinding<fuchsia::modular::ComponentContext> binding_; const std::string component_url_; sys::OutgoingDirectory* const outgoing_directory_; fuchsia::sys::ServiceProviderPtr agent_services_;
diff --git a/fuchsia/base/legacymetrics_client_unittest.cc b/fuchsia/base/legacymetrics_client_unittest.cc index 5c04f24..7f0978d 100644 --- a/fuchsia/base/legacymetrics_client_unittest.cc +++ b/fuchsia/base/legacymetrics_client_unittest.cc
@@ -99,10 +99,10 @@ GetLegacyMetricsDeltas(); } - std::unique_ptr<base::fuchsia::ScopedSingleClientServiceBinding< + std::unique_ptr<base::ScopedSingleClientServiceBinding< fuchsia::legacymetrics::MetricsRecorder>> MakeServiceBinding() { - return std::make_unique<base::fuchsia::ScopedSingleClientServiceBinding< + return std::make_unique<base::ScopedSingleClientServiceBinding< fuchsia::legacymetrics::MetricsRecorder>>( test_context_.additional_services(), &test_recorder_); } @@ -136,7 +136,7 @@ base::test::TaskEnvironment task_environment_; base::TestComponentContextForProcess test_context_; TestMetricsRecorder test_recorder_; - std::unique_ptr<base::fuchsia::ScopedSingleClientServiceBinding< + std::unique_ptr<base::ScopedSingleClientServiceBinding< fuchsia::legacymetrics::MetricsRecorder>> service_binding_; LegacyMetricsClient client_;
diff --git a/fuchsia/base/lifecycle_impl.h b/fuchsia/base/lifecycle_impl.h index ef8c79d..caf0ade3 100644 --- a/fuchsia/base/lifecycle_impl.h +++ b/fuchsia/base/lifecycle_impl.h
@@ -29,8 +29,7 @@ void Terminate() override; private: - const base::fuchsia::ScopedServiceBinding<::fuchsia::modular::Lifecycle> - binding_; + const base::ScopedServiceBinding<::fuchsia::modular::Lifecycle> binding_; base::OnceClosure on_terminate_;
diff --git a/fuchsia/engine/browser/frame_impl.cc b/fuchsia/engine/browser/frame_impl.cc index 3219179..610495f 100644 --- a/fuchsia/engine/browser/frame_impl.cc +++ b/fuchsia/engine/browser/frame_impl.cc
@@ -265,12 +265,12 @@ fidl::InterfaceRequest<fuchsia::web::Frame> frame_request) : web_contents_(std::move(web_contents)), context_(context), - console_log_tag_(params.has_debug_name() - ? params.debug_name() - : std::string()), + console_log_tag_(params.has_debug_name() ? params.debug_name() + : std::string()), params_for_popups_(std::move(params)), navigation_controller_(web_contents_.get()), url_request_rewrite_rules_manager_(web_contents_.get()), + permission_controller_(web_contents_.get()), binding_(this, std::move(frame_request)), media_blocker_(web_contents_.get()), theme_manager_(web_contents_.get()) {
diff --git a/fuchsia/engine/browser/frame_permission_controller.cc b/fuchsia/engine/browser/frame_permission_controller.cc index 13fdf8d..5cd674e 100644 --- a/fuchsia/engine/browser/frame_permission_controller.cc +++ b/fuchsia/engine/browser/frame_permission_controller.cc
@@ -5,6 +5,7 @@ #include "fuchsia/engine/browser/frame_permission_controller.h" #include "base/check_op.h" +#include "content/public/browser/web_contents.h" #include "url/origin.h" using PermissionStatus = blink::mojom::PermissionStatus; @@ -20,6 +21,22 @@ constexpr PermissionStatus kDefaultPerOriginStatus = PermissionStatus::ASK; +// Converts from |url|'s actual origin to the "canonical origin" that should +// be used for the purpose of requesting permissions. +const url::Origin& GetCanonicalOrigin(PermissionType permission, + const url::Origin& requesting_origin, + const url::Origin& embedding_origin) { + // Logic in this function should match the logic in + // permissions::PermissionManager::GetCanonicalOrigin(). Currently it always + // returns embedding origin, which is correct for all permissions supported by + // WebEngine (AUDIO_CAPTURE, VIDEO_CAPTURE, PROTECTED_MEDIA_IDENTIFIER, + // DURABLE_STORAGE). + // + // TODO(crbug.com/1063094): Update this function when other permissions are + // added. + return embedding_origin; +} + } // namespace FramePermissionController::PermissionSet::PermissionSet( @@ -36,12 +53,26 @@ FramePermissionController::PermissionSet::operator=( const PermissionSet& other) = default; -FramePermissionController::FramePermissionController() = default; +FramePermissionController::FramePermissionController( + content::WebContents* web_contents) + : web_contents_(web_contents) {} + FramePermissionController::~FramePermissionController() = default; void FramePermissionController::SetPermissionState(PermissionType permission, const url::Origin& origin, PermissionStatus state) { + // Currently only the following permissions are supported by WebEngine. Others + // may not be handled correctly by this class. + // + // TODO(crbug.com/1063094): This check is necessary mainly because + // GetCanonicalOrigin() may not work correctly for other permission. See + // comemnts in GetCanonicalOrigin(). Remove it once that issue is resolved. + DCHECK(permission == content::PermissionType::AUDIO_CAPTURE || + permission == content::PermissionType::VIDEO_CAPTURE || + permission == content::PermissionType::PROTECTED_MEDIA_IDENTIFIER || + permission == content::PermissionType::DURABLE_STORAGE); + auto it = per_origin_permissions_.find(origin); if (it == per_origin_permissions_.end()) { // Don't create a PermissionSet for |origin| if |state| is set to the @@ -68,23 +99,26 @@ PermissionStatus FramePermissionController::GetPermissionState( PermissionType permission, - const url::Origin& origin) { - PermissionSet effective = GetEffectivePermissionsForOrigin(origin); + const url::Origin& requesting_origin) { + url::Origin embedding_origin = + url::Origin::Create(web_contents_->GetLastCommittedURL()); + const url::Origin& canonical_origin = + GetCanonicalOrigin(permission, requesting_origin, embedding_origin); + + PermissionSet effective = GetEffectivePermissionsForOrigin(canonical_origin); return effective.permission_states[GetPermissionIndex(permission)]; } void FramePermissionController::RequestPermissions( const std::vector<PermissionType>& permissions, - const url::Origin& origin, + const url::Origin& requesting_origin, bool user_gesture, base::OnceCallback<void(const std::vector<PermissionStatus>&)> callback) { std::vector<PermissionStatus> result; result.reserve(permissions.size()); - PermissionSet effective = GetEffectivePermissionsForOrigin(origin); for (auto& permission : permissions) { - result.push_back( - effective.permission_states[GetPermissionIndex(permission)]); + result.push_back(GetPermissionState(permission, requesting_origin)); } std::move(callback).Run(result);
diff --git a/fuchsia/engine/browser/frame_permission_controller.h b/fuchsia/engine/browser/frame_permission_controller.h index 6c155be..527dd080 100644 --- a/fuchsia/engine/browser/frame_permission_controller.h +++ b/fuchsia/engine/browser/frame_permission_controller.h
@@ -15,13 +15,18 @@ namespace url { class Origin; -} +} // namespace url + +namespace content { +class WebContents; +} // namespace content // FramePermissionController is responsible for web permissions state for a // fuchsia.web.Frame instance. class FramePermissionController { public: - FramePermissionController(); + // |web_contents| must outlive FramePermissionController. + explicit FramePermissionController(content::WebContents* web_contents); ~FramePermissionController(); FramePermissionController(FramePermissionController&) = delete; @@ -41,10 +46,10 @@ blink::mojom::PermissionStatus state); // Returns current permission state of the specified |permission| and - // |origin|. + // |requesting_origin|. blink::mojom::PermissionStatus GetPermissionState( content::PermissionType permission, - const url::Origin& origin); + const url::Origin& requesting_origin); // Requests permission state for the specified |permissions|. When the request // is resolved, the |callback| is called with a list of status values, one for @@ -55,7 +60,7 @@ // fuchsia.web.PermissionManager protocol and use it to request permissions. void RequestPermissions( const std::vector<content::PermissionType>& permissions, - const url::Origin& origin, + const url::Origin& requesting_origin, bool user_gesture, base::OnceCallback< void(const std::vector<blink::mojom::PermissionStatus>&)> callback); @@ -80,6 +85,8 @@ // to ASK for specific origins. PermissionSet GetEffectivePermissionsForOrigin(const url::Origin& origin); + content::WebContents* const web_contents_; + base::flat_map<url::Origin, PermissionSet> per_origin_permissions_; PermissionSet default_permissions_{blink::mojom::PermissionStatus::DENIED}; };
diff --git a/fuchsia/engine/browser/theme_manager_browsertest.cc b/fuchsia/engine/browser/theme_manager_browsertest.cc index 4cf5c09d..ac47ed01 100644 --- a/fuchsia/engine/browser/theme_manager_browsertest.cc +++ b/fuchsia/engine/browser/theme_manager_browsertest.cc
@@ -120,8 +120,7 @@ void NotImplemented_(const std::string&) final {} base::Optional<base::TestComponentContextForProcess> component_context_; - base::Optional< - base::fuchsia::ScopedServiceBinding<fuchsia::settings::Display>> + base::Optional<base::ScopedServiceBinding<fuchsia::settings::Display>> display_binding_; cr_fuchsia::TestNavigationListener navigation_listener_; fuchsia::web::NavigationControllerPtr controller_;
diff --git a/fuchsia/engine/context_provider_main.cc b/fuchsia/engine/context_provider_main.cc index a01aac7..88b4b04 100644 --- a/fuchsia/engine/context_provider_main.cc +++ b/fuchsia/engine/context_provider_main.cc
@@ -62,9 +62,9 @@ // Publish the ContextProvider and Debug services. sys::OutgoingDirectory* const directory = base::ComponentContextForProcess()->outgoing().get(); - base::fuchsia::ScopedServiceBinding<fuchsia::web::ContextProvider> binding( + base::ScopedServiceBinding<fuchsia::web::ContextProvider> binding( directory, &context_provider); - base::fuchsia::ScopedServiceBinding<fuchsia::web::Debug> debug_binding( + base::ScopedServiceBinding<fuchsia::web::Debug> debug_binding( directory->debug_dir(), &context_provider); // Publish version information for this component to Inspect.
diff --git a/fuchsia/engine/web_engine_integration_test_base.cc b/fuchsia/engine/web_engine_integration_test_base.cc index 1f69f2d..513953a8 100644 --- a/fuchsia/engine/web_engine_integration_test_base.cc +++ b/fuchsia/engine/web_engine_integration_test_base.cc
@@ -78,7 +78,7 @@ fuchsia::web::CreateContextParams WebEngineIntegrationTestBase::ContextParamsWithFilteredServiceDirectory() { filtered_service_directory_ = - std::make_unique<base::fuchsia::FilteredServiceDirectory>( + std::make_unique<base::FilteredServiceDirectory>( base::ComponentContextForProcess()->svc().get()); fidl::InterfaceHandle<fuchsia::io::Directory> svc_dir; filtered_service_directory_->ConnectClient(svc_dir.NewRequest());
diff --git a/fuchsia/engine/web_engine_integration_test_base.h b/fuchsia/engine/web_engine_integration_test_base.h index e0e2718e..3846477 100644 --- a/fuchsia/engine/web_engine_integration_test_base.h +++ b/fuchsia/engine/web_engine_integration_test_base.h
@@ -106,8 +106,7 @@ std::unique_ptr<fidl::Binding<fuchsia::web::NavigationEventListener>> navigation_listener_binding_; - std::unique_ptr<base::fuchsia::FilteredServiceDirectory> - filtered_service_directory_; + std::unique_ptr<base::FilteredServiceDirectory> filtered_service_directory_; }; #endif // FUCHSIA_ENGINE_WEB_ENGINE_INTEGRATION_TEST_BASE_H_
diff --git a/fuchsia/http/http_service_main.cc b/fuchsia/http/http_service_main.cc index 6df26c0..d367a2e 100644 --- a/fuchsia/http/http_service_main.cc +++ b/fuchsia/http/http_service_main.cc
@@ -27,8 +27,8 @@ sys::OutgoingDirectory* outgoing_directory = base::ComponentContextForProcess()->outgoing().get(); HttpServiceImpl http_service; - base::fuchsia::ScopedServiceBinding<::fuchsia::net::oldhttp::HttpService> - binding(outgoing_directory, &http_service); + base::ScopedServiceBinding<::fuchsia::net::oldhttp::HttpService> binding( + outgoing_directory, &http_service); base::RunLoop run_loop;
diff --git a/fuchsia/http/http_service_unittest.cc b/fuchsia/http/http_service_unittest.cc index 020538a..d8408d88 100644 --- a/fuchsia/http/http_service_unittest.cc +++ b/fuchsia/http/http_service_unittest.cc
@@ -135,6 +135,26 @@ << response.error->description; } +void CheckQueryStatus(const oldhttp::URLLoaderPtr& url_loader, + bool is_loading, + int expected_network_error) { + base::RunLoop run_loop; + url_loader->QueryStatus([&run_loop, &is_loading, &expected_network_error]( + oldhttp::URLLoaderStatus status) { + EXPECT_EQ(status.is_loading, is_loading); + if (status.is_loading || expected_network_error == net::OK) { + EXPECT_FALSE(status.error); + } else { + EXPECT_TRUE(status.error); + if (status.error) { + EXPECT_EQ(status.error->code, expected_network_error); + } + } + run_loop.Quit(); + }); + run_loop.Run(); +} + void CheckResponseStream(const oldhttp::URLResponse& response, const std::string& expected_response) { EXPECT_TRUE(response.body->is_stream()); @@ -235,6 +255,7 @@ CheckResponseError(url_response(), net::OK); EXPECT_EQ(url_response().status_code, 200u); CheckResponseStream(url_response(), "hello"); + CheckQueryStatus(url_loader, false, net::OK); } // Check a basic end-to-end request resolution with the response being @@ -252,6 +273,7 @@ CheckResponseError(url_response(), net::OK); EXPECT_EQ(url_response().status_code, 200u); CheckResponseBuffer(url_response(), "hello"); + CheckQueryStatus(url_loader, false, net::OK); } // Check network request headers are received properly. @@ -277,6 +299,7 @@ {"X-Multiple-Entries", "b"}, }; CheckResponseHeaders(url_response(), &expected_headers); + CheckQueryStatus(url_loader, false, net::OK); } // Check duplicate network request headers are received properly. @@ -304,6 +327,7 @@ {"X-Multiple-Entries", "b"}, }; CheckResponseHeaders(url_response(), &expected_headers); + CheckQueryStatus(url_loader, false, net::OK); } // Check a request with automatic redirect resolution is handled properly. @@ -323,6 +347,7 @@ ASSERT_TRUE(url_response().url.has_value()); EXPECT_EQ(url_response().url.value(), http_test_server()->GetURL("/with-headers.html").spec()); + CheckQueryStatus(url_loader, false, net::OK); } // Check a request with manual redirect resolution is handled properly. @@ -345,6 +370,7 @@ EXPECT_EQ(url_response().status_code, 302u); EXPECT_EQ(url_response().url.value_or(""), request_url); EXPECT_EQ(url_response().redirect_url.value_or(""), final_url); + CheckQueryStatus(url_loader, true, net::OK); base::RunLoop run_loop; url_loader->FollowRedirect( @@ -354,6 +380,7 @@ run_loop.Quit(); }); run_loop.Run(); + CheckQueryStatus(url_loader, false, net::OK); } // Check HTTP error codes are properly populated. @@ -372,6 +399,7 @@ ExecuteRequest(url_loader, std::move(request)); CheckResponseError(url_response(), net::OK); EXPECT_EQ(url_response().status_code, 404u); + CheckQueryStatus(url_loader, false, net::OK); } // Check network error codes are properly populated. @@ -386,6 +414,7 @@ ExecuteRequest(url_loader, std::move(request)); CheckResponseError(url_response(), net::ERR_INVALID_URL); + CheckQueryStatus(url_loader, false, net::ERR_INVALID_URL); } // Ensure the service can handle multiple concurrent requests. @@ -441,13 +470,7 @@ ExecuteRequest(url_loader, std::move(request)); CheckResponseError(url_response(), net::OK); EXPECT_EQ(url_response().status_code, 200u); - - base::RunLoop run_loop; - url_loader->QueryStatus([&run_loop](oldhttp::URLLoaderStatus status) { - EXPECT_TRUE(status.is_loading); - run_loop.Quit(); - }); - run_loop.Run(); + CheckQueryStatus(url_loader, true, net::OK); } // Check the response error is properly set if the server disconnects early. @@ -462,4 +485,23 @@ ExecuteRequest(url_loader, std::move(request)); CheckResponseError(url_response(), net::ERR_EMPTY_RESPONSE); + CheckQueryStatus(url_loader, false, net::ERR_EMPTY_RESPONSE); +} + +// Checks the QueryStatus gets set properly if an error occurs after the +// response has started being processed. +TEST_F(HttpServiceTest, ContentLengthTooLong) { + oldhttp::URLLoaderPtr url_loader; + http_service()->CreateURLLoader(url_loader.NewRequest()); + + oldhttp::URLRequest request; + request.url = + http_test_server()->GetURL("/content-length-too-long.html").spec(); + request.method = "GET"; + request.response_body_mode = oldhttp::ResponseBodyMode::STREAM; + + ExecuteRequest(url_loader, std::move(request)); + CheckResponseError(url_response(), net::OK); + CheckResponseStream(url_response(), "hello"); + CheckQueryStatus(url_loader, false, net::ERR_CONTENT_LENGTH_MISMATCH); }
diff --git a/fuchsia/http/testdata/content-length-too-long.html b/fuchsia/http/testdata/content-length-too-long.html new file mode 100644 index 0000000..b6fc4c6 --- /dev/null +++ b/fuchsia/http/testdata/content-length-too-long.html
@@ -0,0 +1 @@ +hello \ No newline at end of file
diff --git a/fuchsia/http/testdata/content-length-too-long.html.mock-http-headers b/fuchsia/http/testdata/content-length-too-long.html.mock-http-headers new file mode 100644 index 0000000..3b6537e6 --- /dev/null +++ b/fuchsia/http/testdata/content-length-too-long.html.mock-http-headers
@@ -0,0 +1,3 @@ +HTTP/1.1 200 OK +Content-Type: text/html +Content-Length: 9001
diff --git a/fuchsia/http/url_loader_impl.cc b/fuchsia/http/url_loader_impl.cc index 75c3e7d..47a3e82 100644 --- a/fuchsia/http/url_loader_impl.cc +++ b/fuchsia/http/url_loader_impl.cc
@@ -176,12 +176,14 @@ // Start the request. net_request_->Start(); + is_loading_ = true; } void URLLoaderImpl::FollowRedirect(Callback callback) { if (!net_request_ || auto_follow_redirects_ || !net_request_->is_redirecting()) { callback(BuildResponse(net::ERR_INVALID_HANDLE)); + return; } done_callback_ = std::move(callback); @@ -192,15 +194,10 @@ void URLLoaderImpl::QueryStatus(QueryStatusCallback callback) { oldhttp::URLLoaderStatus status; - if (!net_request_) { - status.is_loading = false; - } else if (net_request_->is_pending() || net_request_->is_redirecting()) { - status.is_loading = true; - } else { - status.is_loading = false; + status.is_loading = is_loading_; + if (net_request_ && !is_loading_) { status.error = BuildError(net_error_); } - callback(std::move(status)); } @@ -250,6 +247,7 @@ // Return early if the request failed. if (net_error_ != net::OK) { + is_loading_ = false; std::move(done_callback_)(BuildResponse(net_error_)); return; } @@ -260,11 +258,13 @@ zx::socket read_socket; zx_status_t result = zx::socket::create(0, &read_socket, &write_socket_); if (result != ZX_OK) { + is_loading_ = false; + net_error_ = net::ERR_INSUFFICIENT_RESOURCES; ZX_DLOG(WARNING, result) << "zx_socket_create"; - std::move(done_callback_)(BuildResponse(net::ERR_INSUFFICIENT_RESOURCES)); + std::move(done_callback_)(BuildResponse(net_error_)); return; } - oldhttp::URLResponse response = BuildResponse(net::OK); + oldhttp::URLResponse response = BuildResponse(net_error_); response.body = oldhttp::URLBody::New(); response.body->set_stream(std::move(read_socket)); std::move(done_callback_)(std::move(response)); @@ -311,6 +311,9 @@ bool URLLoaderImpl::WriteResponseBytes(int result) { if (result < 0) { + is_loading_ = false; + net_error_ = result; + // Signal read error back to the client. if (write_socket_) { DCHECK(response_body_mode_ == oldhttp::ResponseBodyMode::STREAM || @@ -328,6 +331,8 @@ if (result == 0) { // Read complete. + is_loading_ = false; + if (write_socket_) { DCHECK(response_body_mode_ == oldhttp::ResponseBodyMode::STREAM || response_body_mode_ == @@ -344,8 +349,8 @@ response.body = std::move(body); std::move(done_callback_)(std::move(response)); } else { - std::move(done_callback_)( - BuildResponse(net::ERR_INSUFFICIENT_RESOURCES)); + net_error_ = net::ERR_INSUFFICIENT_RESOURCES; + std::move(done_callback_)(BuildResponse(net_error_)); } } return false; @@ -370,6 +375,8 @@ // Something went wrong, attempt to shut down the socket and close it. ZX_DLOG(WARNING, status) << "zx_socket_write"; write_socket_ = zx::socket(); + is_loading_ = false; + net_error_ = net::ERR_FAILED; return false; } } else {
diff --git a/fuchsia/http/url_loader_impl.h b/fuchsia/http/url_loader_impl.h index 61ecb489..c8dfef6 100644 --- a/fuchsia/http/url_loader_impl.h +++ b/fuchsia/http/url_loader_impl.h
@@ -92,6 +92,9 @@ // manually handle redirects. bool auto_follow_redirects_; + // Set to true when the URLRequest is loading. + bool is_loading_ = false; + // Populated from the FIDL URLRequest. Indicates how the response body should // be populated. ::fuchsia::net::oldhttp::ResponseBodyMode response_body_mode_;
diff --git a/fuchsia/runners/cast/cast_runner.cc b/fuchsia/runners/cast/cast_runner.cc index 60ef0dd..8354759 100644 --- a/fuchsia/runners/cast/cast_runner.cc +++ b/fuchsia/runners/cast/cast_runner.cc
@@ -215,8 +215,7 @@ } const std::unique_ptr<base::StartupContext> startup_context_; - const base::fuchsia::ScopedServiceBinding<fuchsia::web::FrameHost> - frame_host_binding_; + const base::ScopedServiceBinding<fuchsia::web::FrameHost> frame_host_binding_; fidl::Binding<fuchsia::sys::ComponentController> binding_{this}; base::WeakPtrFactory<const sys::ServiceDirectory> weak_incoming_services_; @@ -271,7 +270,7 @@ base::OnceCallback<bool()> delete_persistent_data_; std::unique_ptr<base::StartupContext> startup_context_; - const base::fuchsia::ScopedServiceBinding<chromium::cast::DataReset> + const base::ScopedServiceBinding<chromium::cast::DataReset> data_reset_handler_binding_; fidl::Binding<fuchsia::sys::ComponentController> binding_{this}; }; @@ -280,14 +279,13 @@ CastRunner::CastRunner(bool is_headless) : is_headless_(is_headless), - main_services_(std::make_unique<base::fuchsia::FilteredServiceDirectory>( + main_services_(std::make_unique<base::FilteredServiceDirectory>( base::ComponentContextForProcess()->svc().get())), main_context_(std::make_unique<WebContentRunner>( base::BindRepeating(&CastRunner::GetMainContextParams, base::Unretained(this)))), - isolated_services_( - std::make_unique<base::fuchsia::FilteredServiceDirectory>( - base::ComponentContextForProcess()->svc().get())) { + isolated_services_(std::make_unique<base::FilteredServiceDirectory>( + base::ComponentContextForProcess()->svc().get())) { // Delete persisted data staged for deletion during the previous run. DeleteStagedForDeletionDirectoryIfExists();
diff --git a/fuchsia/runners/cast/cast_runner.h b/fuchsia/runners/cast/cast_runner.h index e92b9dc..a58e546 100644 --- a/fuchsia/runners/cast/cast_runner.h +++ b/fuchsia/runners/cast/cast_runner.h
@@ -25,9 +25,7 @@ #include "fuchsia/runners/cast/pending_cast_component.h" namespace base { -namespace fuchsia { class FilteredServiceDirectory; -} // namespace fuchsia } // namespace base class WebContentRunner; @@ -124,11 +122,10 @@ // Holds the main fuchsia.web.Context used to host CastComponents. // Note that although |main_context_| is actually a WebContentRunner, that is // only being used to maintain the Context for the hosted components. - const std::unique_ptr<base::fuchsia::FilteredServiceDirectory> main_services_; + const std::unique_ptr<base::FilteredServiceDirectory> main_services_; const std::unique_ptr<WebContentRunner> main_context_; - const std::unique_ptr<base::fuchsia::FilteredServiceDirectory> - isolated_services_; + const std::unique_ptr<base::FilteredServiceDirectory> isolated_services_; // Holds fuchsia.web.Contexts used to host isolated components. base::flat_set<std::unique_ptr<WebContentRunner>, base::UniquePtrComparator>
diff --git a/fuchsia/runners/cast/cast_runner_integration_test.cc b/fuchsia/runners/cast/cast_runner_integration_test.cc index 55690db6..aa563a8 100644 --- a/fuchsia/runners/cast/cast_runner_integration_test.cc +++ b/fuchsia/runners/cast/cast_runner_integration_test.cc
@@ -205,17 +205,16 @@ } protected: - const base::fuchsia::ScopedServiceBinding< - chromium::cast::ApplicationConfigManager> + const base::ScopedServiceBinding<chromium::cast::ApplicationConfigManager> app_config_binding_; - const base::fuchsia::ScopedServiceBinding<chromium::cast::ApiBindings> + const base::ScopedServiceBinding<chromium::cast::ApiBindings> bindings_manager_binding_; - base::Optional<base::fuchsia::ScopedServiceBinding< + base::Optional<base::ScopedServiceBinding< chromium::cast::UrlRequestRewriteRulesProvider>> url_request_rules_provider_binding_; FakeApplicationContext application_context_; - const base::fuchsia::ScopedServiceBinding<chromium::cast::ApplicationContext> + const base::ScopedServiceBinding<chromium::cast::ApplicationContext> context_binding_; base::OnceClosure on_delete_; }; @@ -563,7 +562,7 @@ // Incoming service directory, ComponentContext and per-component state. sys::OutgoingDirectory component_services_; - base::fuchsia::ScopedServiceBinding<chromium::cast::ApplicationConfigManager> + base::ScopedServiceBinding<chromium::cast::ApplicationConfigManager> app_config_manager_binding_; std::unique_ptr<cr_fuchsia::FakeComponentContext> component_context_; fuchsia::sys::ComponentControllerPtr component_controller_;
diff --git a/fuchsia/runners/cast/main.cc b/fuchsia/runners/cast/main.cc index c299481..24d788e 100644 --- a/fuchsia/runners/cast/main.cc +++ b/fuchsia/runners/cast/main.cc
@@ -66,8 +66,8 @@ command_line->HasSwitch(kForceHeadlessForTestsSwitch) || GetConfigBool(kHeadlessConfigKey); CastRunner runner(enable_headless); - base::fuchsia::ScopedServiceBinding<fuchsia::sys::Runner> binding( - outgoing_directory, &runner); + base::ScopedServiceBinding<fuchsia::sys::Runner> binding(outgoing_directory, + &runner); if (command_line->HasSwitch(kDisableVulkanForTestsSwitch)) { runner.set_disable_vulkan_for_test(); // IN-TEST
diff --git a/fuchsia/runners/common/web_component.cc b/fuchsia/runners/common/web_component.cc index 73b7ad60..b477066 100644 --- a/fuchsia/runners/common/web_component.cc +++ b/fuchsia/runners/common/web_component.cc
@@ -93,7 +93,7 @@ // Publish outgoing services and start serving component's outgoing // directory. view_provider_binding_ = std::make_unique< - base::fuchsia::ScopedServiceBinding<fuchsia::ui::app::ViewProvider>>( + base::ScopedServiceBinding<fuchsia::ui::app::ViewProvider>>( startup_context()->component_context()->outgoing().get(), this); lifecycle_ = std::make_unique<cr_fuchsia::LifecycleImpl>( startup_context()->component_context()->outgoing().get(),
diff --git a/fuchsia/runners/common/web_component.h b/fuchsia/runners/common/web_component.h index 97cd53b..31dbc7c 100644 --- a/fuchsia/runners/common/web_component.h +++ b/fuchsia/runners/common/web_component.h
@@ -120,8 +120,7 @@ fuchsia::modular::ModuleContextPtr module_context_; // Objects used for binding and exporting the ViewProvider service. - std::unique_ptr< - base::fuchsia::ScopedServiceBinding<fuchsia::ui::app::ViewProvider>> + std::unique_ptr<base::ScopedServiceBinding<fuchsia::ui::app::ViewProvider>> view_provider_binding_; // Termination reason and exit-code to be reported via the
diff --git a/fuchsia/runners/web/main.cc b/fuchsia/runners/web/main.cc index 477360c..5a985b1 100644 --- a/fuchsia/runners/web/main.cc +++ b/fuchsia/runners/web/main.cc
@@ -71,7 +71,7 @@ base::BindRepeating(&GetContextParams); WebContentRunner runner(std::move(get_context_params_callback)); - base::fuchsia::ScopedServiceBinding<fuchsia::sys::Runner> binding( + base::ScopedServiceBinding<fuchsia::sys::Runner> binding( base::ComponentContextForProcess()->outgoing().get(), &runner); base::ComponentContextForProcess()->outgoing()->ServeFromStartupInfo();
diff --git a/fuchsia/runners/web/web_runner_smoke_test.cc b/fuchsia/runners/web/web_runner_smoke_test.cc index bd38e2c..68c5130 100644 --- a/fuchsia/runners/web/web_runner_smoke_test.cc +++ b/fuchsia/runners/web/web_runner_smoke_test.cc
@@ -199,7 +199,7 @@ MockModuleContext module_context; EXPECT_CALL(module_context, RemoveSelfFromStory); - base::fuchsia::ScopedServiceBinding<fuchsia::modular::ModuleContext> binding( + base::ScopedServiceBinding<fuchsia::modular::ModuleContext> binding( &outgoing_directory_, &module_context); launch_info.additional_services->names.emplace_back( fuchsia::modular::ModuleContext::Name_);
diff --git a/google_apis/BUILD.gn b/google_apis/BUILD.gn index bb74e013..fddf591 100644 --- a/google_apis/BUILD.gn +++ b/google_apis/BUILD.gn
@@ -66,7 +66,10 @@ config("key_defines") { defines = [] - if (is_chrome_branded || use_official_google_api_keys) { + + # TODO(crbug.com/1171510): Refactor so use_official_google_api_keys can be + # used for Fuchsia. + if (!is_fuchsia && (is_chrome_branded || use_official_google_api_keys)) { defines += [ "USE_OFFICIAL_GOOGLE_API_KEYS=1" ] } if (google_api_key != "") {
diff --git a/gpu/command_buffer/tests/webgpu_test.cc b/gpu/command_buffer/tests/webgpu_test.cc index 58f8e24..0c85d44e 100644 --- a/gpu/command_buffer/tests/webgpu_test.cc +++ b/gpu/command_buffer/tests/webgpu_test.cc
@@ -39,7 +39,8 @@ WebGPUTest::~WebGPUTest() = default; bool WebGPUTest::WebGPUSupported() const { - // crbug.com(941685): Vulkan driver crashes on Linux FYI Release (AMD R7 240). + // TODO(crbug.com/1172447): Re-enable on AMD when the RX 5500 XT issues are + // resolved. // Win7 does not support WebGPU if (GPUTestBotConfig::CurrentConfigMatches("Linux AMD") || GPUTestBotConfig::CurrentConfigMatches("Win7")) {
diff --git a/infra/config/generated/commit-queue.cfg b/infra/config/generated/commit-queue.cfg index 5f1aeed..56ee2a3 100644 --- a/infra/config/generated/commit-queue.cfg +++ b/infra/config/generated/commit-queue.cfg
@@ -1002,7 +1002,12 @@ } builders { name: "chromium/try/linux-cfm-rel" - includable_only: true + location_regexp: ".+/[+]/chromeos/components/chromebox_for_meetings/.+" + location_regexp: ".+/[+]/chromeos/dbus/chromebox_for_meetings/.+" + location_regexp: ".+/[+]/chromeos/services/chromebox_for_meetings/.+" + location_regexp: ".+/[+]/chrome/browser/chromeos/chromebox_for_meetings/.+" + location_regexp_exclude: ".+/[+]/docs/.+" + location_regexp_exclude: ".+/[+]/infra/config/.+" } builders { name: "chromium/try/linux-chromeos-compile-dbg"
diff --git a/infra/config/generated/cq-builders.md b/infra/config/generated/cq-builders.md index 71d3b3c..0596a92 100644 --- a/infra/config/generated/cq-builders.md +++ b/infra/config/generated/cq-builders.md
@@ -253,6 +253,14 @@ * [`//third_party/blink/renderer/core/svg/.+`](https://cs.chromium.org/chromium/src/third_party/blink/renderer/core/svg/) * [`//third_party/blink/renderer/platform/graphics/.+`](https://cs.chromium.org/chromium/src/third_party/blink/renderer/platform/graphics/) +* [linux-cfm-rel](https://ci.chromium.org/p/chromium/builders/try/linux-cfm-rel) ([definition](https://cs.chromium.org/search?q=package:%5Echromium$+file:/cq.star$+-file:/beta/+-file:/stable/+linux-cfm-rel)) ([matching builders](https://cs.chromium.org/search?q=+file:trybots.py+linux-cfm-rel)) + + Path regular expressions: + * [`//chromeos/components/chromebox_for_meetings/.+`](https://cs.chromium.org/chromium/src/chromeos/components/chromebox_for_meetings/) + * [`//chromeos/dbus/chromebox_for_meetings/.+`](https://cs.chromium.org/chromium/src/chromeos/dbus/chromebox_for_meetings/) + * [`//chromeos/services/chromebox_for_meetings/.+`](https://cs.chromium.org/chromium/src/chromeos/services/chromebox_for_meetings/) + * [`//chrome/browser/chromeos/chromebox_for_meetings/.+`](https://cs.chromium.org/chromium/src/chrome/browser/chromeos/chromebox_for_meetings/) + * [linux_chromium_dbg_ng](https://ci.chromium.org/p/chromium/builders/try/linux_chromium_dbg_ng) ([definition](https://cs.chromium.org/search?q=package:%5Echromium$+file:/cq.star$+-file:/beta/+-file:/stable/+linux_chromium_dbg_ng)) ([matching builders](https://cs.chromium.org/search?q=+file:trybots.py+linux_chromium_dbg_ng)) Path regular expressions:
diff --git a/infra/config/generated/cr-buildbucket.cfg b/infra/config/generated/cr-buildbucket.cfg index dba0cd5..2ec7eea 100644 --- a/infra/config/generated/cr-buildbucket.cfg +++ b/infra/config/generated/cr-buildbucket.cfg
@@ -26484,6 +26484,64 @@ } } builders { + name: "rts-model-packager" + swarming_host: "chromium-swarm.appspot.com" + swarming_tags: "vpython:native-python-wrapper" + dimensions: "builderless:1" + dimensions: "cores:8" + dimensions: "cpu:x86-64" + dimensions: "os:Ubuntu-16.04" + dimensions: "pool:luci.chromium.ci" + dimensions: "ssd:0" + exe { + cipd_package: "infra/recipe_bundles/chromium.googlesource.com/chromium/tools/build" + cipd_version: "refs/heads/master" + cmd: "luciexe" + } + properties: "{\"$build/goma\":{\"use_luci_auth\":true},\"$kitchen\":{\"devshell\":true,\"git_auth\":true},\"$recipe_engine/isolated\":{\"server\":\"https://isolateserver.appspot.com\"},\"builder_group\":\"chromium.packager\",\"recipe\":\"chromium_rts/create_model\"}" + execution_timeout_secs: 3600 + build_numbers: YES + service_account: "chromium-cipd-builder@chops-service-accounts.iam.gserviceaccount.com" + experiments { + key: "chromium.resultdb.result_sink" + value: 100 + } + experiments { + key: "chromium.resultdb.result_sink.gtests_local" + value: 100 + } + experiments { + key: "chromium.resultdb.result_sink.junit_tests" + value: 100 + } + experiments { + key: "luci.use_realms" + value: 100 + } + resultdb { + enable: true + bq_exports { + project: "luci-resultdb" + dataset: "chromium" + table: "ci_test_results" + test_results {} + } + bq_exports { + project: "luci-resultdb" + dataset: "chromium" + table: "gpu_ci_test_results" + test_results { + predicate { + test_id_regexp: "ninja://(chrome/test:|content/test:fuchsia_)telemetry_gpu_integration_test/.+" + } + } + } + history_options { + use_invocation_timestamp: true + } + } + } + builders { name: "win-angle-chromium-x64-builder" swarming_host: "chromium-swarm.appspot.com" swarming_tags: "vpython:native-python-wrapper"
diff --git a/infra/config/generated/luci-milo.cfg b/infra/config/generated/luci-milo.cfg index b9a4d03..a5b4e928 100644 --- a/infra/config/generated/luci-milo.cfg +++ b/infra/config/generated/luci-milo.cfg
@@ -9216,6 +9216,11 @@ category: "android" short_name: "sdk" } + builders { + name: "buildbucket/luci.chromium.ci/rts-model-packager" + category: "rts" + short_name: "create-model" + } header { oncalls { name: "Chromium"
diff --git a/infra/config/generated/luci-scheduler.cfg b/infra/config/generated/luci-scheduler.cfg index 61dd0ec..81de1fc 100644 --- a/infra/config/generated/luci-scheduler.cfg +++ b/infra/config/generated/luci-scheduler.cfg
@@ -6058,6 +6058,17 @@ } } job { + id: "rts-model-packager" + realm: "ci" + schedule: "0 10 * * *" + acl_sets: "ci" + buildbucket { + server: "cr-buildbucket.appspot.com" + bucket: "luci.chromium.ci" + builder: "rts-model-packager" + } +} +job { id: "win-angle-chromium-x64-builder" realm: "ci" acl_sets: "ci" @@ -6998,6 +7009,10 @@ acls { granted_to: "group:all" } + acls { + role: TRIGGERER + granted_to: "group:project-chromium-scheduler-triggerers" + } } acl_sets { name: "findit"
diff --git a/infra/config/generated/realms.cfg b/infra/config/generated/realms.cfg index 3769c50f..15ac798 100644 --- a/infra/config/generated/realms.cfg +++ b/infra/config/generated/realms.cfg
@@ -72,6 +72,10 @@ principals: "group:project-chromium-ci-schedulers" } bindings { + role: "role/scheduler.triggerer" + principals: "group:project-chromium-scheduler-triggerers" + } + bindings { role: "role/swarming.taskTriggerer" principals: "user:chromium-ci-builder@chops-service-accounts.iam.gserviceaccount.com" principals: "user:findit-for-me@appspot.gserviceaccount.com"
diff --git a/infra/config/recipes.star b/infra/config/recipes.star index 4e452823..fa78486 100644 --- a/infra/config/recipes.star +++ b/infra/config/recipes.star
@@ -94,6 +94,11 @@ ) build_recipe( + name = "recipe:chromium_rts/create_model", + use_bbagent = True, +) + +build_recipe( name = "recipe:chromium_trybot", )
diff --git a/infra/config/subprojects/chromium/ci.star b/infra/config/subprojects/chromium/ci.star index 32eb9d50..a5afc97 100644 --- a/infra/config/subprojects/chromium/ci.star +++ b/infra/config/subprojects/chromium/ci.star
@@ -50,6 +50,10 @@ roles = acl.BUILDBUCKET_OWNER, groups = "google/luci-task-force@google.com", ), + acl.entry( + roles = acl.SCHEDULER_TRIGGERER, + groups = "project-chromium-scheduler-triggerers", + ), ], ) @@ -5688,3 +5692,15 @@ goma_jobs = goma.jobs.J150, main_console_view = "main", ) + +ci.cipd_builder( + name = "rts-model-packager", + console_view_entry = consoles.console_view_entry( + category = "rts", + short_name = "create-model", + ), + executable = "recipe:chromium_rts/create_model", + schedule = "0 10 * * *", # at 2 AM PST, once a day. + triggered_by = [], + execution_timeout = time.hour, +)
diff --git a/infra/config/subprojects/chromium/try.star b/infra/config/subprojects/chromium/try.star index f28a072..a722975 100644 --- a/infra/config/subprojects/chromium/try.star +++ b/infra/config/subprojects/chromium/try.star
@@ -727,6 +727,14 @@ try_.chromium_chromiumos_builder( name = "linux-cfm-rel", + tryjob = try_.job( + location_regexp = [ + ".+/[+]/chromeos/components/chromebox_for_meetings/.+", + ".+/[+]/chromeos/dbus/chromebox_for_meetings/.+", + ".+/[+]/chromeos/services/chromebox_for_meetings/.+", + ".+/[+]/chrome/browser/chromeos/chromebox_for_meetings/.+", + ], + ), ) try_.chromium_dawn_builder(
diff --git a/ios/chrome/browser/ui/content_suggestions/content_suggestions_header_view_controller.h b/ios/chrome/browser/ui/content_suggestions/content_suggestions_header_view_controller.h index e4f23ba1..424e382 100644 --- a/ios/chrome/browser/ui/content_suggestions/content_suggestions_header_view_controller.h +++ b/ios/chrome/browser/ui/content_suggestions/content_suggestions_header_view_controller.h
@@ -59,10 +59,6 @@ // omnibox. - (void)focusFakebox; -// Returns the height of the content suggestions header, not including the -// omnibox. -- (CGFloat)heightAboveFakeOmnibox; - @end #endif // IOS_CHROME_BROWSER_UI_CONTENT_SUGGESTIONS_CONTENT_SUGGESTIONS_HEADER_VIEW_CONTROLLER_H_
diff --git a/ios/chrome/browser/ui/content_suggestions/content_suggestions_header_view_controller.mm b/ios/chrome/browser/ui/content_suggestions/content_suggestions_header_view_controller.mm index e9285e4..e6631520 100644 --- a/ios/chrome/browser/ui/content_suggestions/content_suggestions_header_view_controller.mm +++ b/ios/chrome/browser/ui/content_suggestions/content_suggestions_header_view_controller.mm
@@ -148,14 +148,6 @@ [self.accessibilityButton removeObserver:self forKeyPath:@"highlighted"]; } -- (CGFloat)heightAboveFakeOmnibox { - return self.view.frame.size.height - - ntp_header::kFakeOmniboxScrolledToTopMargin - - self.fakeOmnibox.frame.size.height - - ToolbarExpandedHeight( - [UIApplication sharedApplication].preferredContentSizeCategory); -} - #pragma mark - ContentSuggestionsHeaderControlling - (void)updateFakeOmniboxForOffset:(CGFloat)offset
diff --git a/ios/chrome/browser/ui/content_suggestions/content_suggestions_layout.h b/ios/chrome/browser/ui/content_suggestions/content_suggestions_layout.h index f633589..3a248198 100644 --- a/ios/chrome/browser/ui/content_suggestions/content_suggestions_layout.h +++ b/ios/chrome/browser/ui/content_suggestions/content_suggestions_layout.h
@@ -7,6 +7,8 @@ #import <MaterialComponents/MDCCollectionViewFlowLayout.h> +@protocol NewTabPageOmniboxPositioning; + // Layout used for ContentSuggestions. It makes sure the collection is high // enough to be scrolled up to the point the fake omnibox is hidden. For size // classes other than RegularXRegular, this layout makes sure the fake omnibox @@ -23,6 +25,9 @@ // view. @property(nonatomic, weak) UICollectionView* parentCollectionView; +// Provides information relating to the fake omnibox size. +@property(nonatomic, weak) id<NewTabPageOmniboxPositioning> omniboxPositioner; + // Whether or not the user has scrolled into the feed, transferring ownership of // the omnibox to allow it to stick to the top of the NTP. @property(nonatomic, assign) BOOL isScrolledIntoFeed;
diff --git a/ios/chrome/browser/ui/content_suggestions/content_suggestions_layout.mm b/ios/chrome/browser/ui/content_suggestions/content_suggestions_layout.mm index a66da461..97ed601 100644 --- a/ios/chrome/browser/ui/content_suggestions/content_suggestions_layout.mm +++ b/ios/chrome/browser/ui/content_suggestions/content_suggestions_layout.mm
@@ -7,6 +7,7 @@ #import "ios/chrome/browser/ui/content_suggestions/content_suggestions_collection_utils.h" #import "ios/chrome/browser/ui/ntp/new_tab_page_feature.h" #import "ios/chrome/browser/ui/ntp/new_tab_page_header_constants.h" +#import "ios/chrome/browser/ui/ntp/new_tab_page_omnibox_positioning.h" #import "ios/chrome/browser/ui/toolbar/public/toolbar_utils.h" #import "ios/chrome/browser/ui/util/ui_util.h" #import "ios/chrome/browser/ui/util/uikit_ui_util.h" @@ -136,15 +137,17 @@ // Keep the header in front of all other views. attributes.zIndex = NSIntegerMax; - // Prevent the fake omnibox from scrolling up off of the screen. - CGFloat topSafeArea = IsRefactoredNTP() && [self isFeedVisible] - ? self.parentCollectionView.safeAreaInsets.top - : self.collectionView.safeAreaInsets.top; + // TODO(crbug.com/1114792): Remove this and only use omniboxPositioner after + // refactoring is complete. CGFloat minY = headerHeight - ntp_header::kFakeOmniboxScrolledToTopMargin - ToolbarExpandedHeight( [UIApplication sharedApplication].preferredContentSizeCategory) - - topSafeArea; + self.collectionView.safeAreaInsets.top; + + if (IsRefactoredNTP() && [self isFeedVisible]) { + minY = [self.omniboxPositioner stickyOmniboxHeight]; + } // TODO(crbug.com/1114792): Remove mentioned of "refactored" from the // variable name once this launches. BOOL hasScrolledIntoRefactoredDiscoverFeed =
diff --git a/ios/chrome/browser/ui/ntp/BUILD.gn b/ios/chrome/browser/ui/ntp/BUILD.gn index d12c79b..e78ebbcc 100644 --- a/ios/chrome/browser/ui/ntp/BUILD.gn +++ b/ios/chrome/browser/ui/ntp/BUILD.gn
@@ -9,6 +9,7 @@ "new_tab_page_controller_delegate.h", "new_tab_page_header_constants.h", "new_tab_page_header_constants.mm", + "new_tab_page_omnibox_positioning.h", ] configs += [ "//build/config/compiler:enable_arc" ] public_deps = [ ":feature_flags" ]
diff --git a/ios/chrome/browser/ui/ntp/new_tab_page_content_delegate.h b/ios/chrome/browser/ui/ntp/new_tab_page_content_delegate.h index 5989b555..1d9bd7a3 100644 --- a/ios/chrome/browser/ui/ntp/new_tab_page_content_delegate.h +++ b/ios/chrome/browser/ui/ntp/new_tab_page_content_delegate.h
@@ -11,10 +11,6 @@ // Reloads content suggestions collection view. - (void)reloadContentSuggestions; -// Returns the height of the content suggestions header, not including the -// omnibox. -- (CGFloat)heightAboveFakeOmnibox; - @end #endif // IOS_CHROME_BROWSER_UI_NTP_NEW_TAB_PAGE_CONTENT_DELEGATE_H_
diff --git a/ios/chrome/browser/ui/ntp/new_tab_page_coordinator.mm b/ios/chrome/browser/ui/ntp/new_tab_page_coordinator.mm index 7f7ab56..20b019d4 100644 --- a/ios/chrome/browser/ui/ntp/new_tab_page_coordinator.mm +++ b/ios/chrome/browser/ui/ntp/new_tab_page_coordinator.mm
@@ -441,11 +441,6 @@ [self.contentSuggestionsCoordinator reload]; } -- (CGFloat)heightAboveFakeOmnibox { - return [self.contentSuggestionsCoordinator - .headerController heightAboveFakeOmnibox]; -} - #pragma mark - Private // YES if we're using the refactored NTP and the Discover Feed is visible.
diff --git a/ios/chrome/browser/ui/ntp/new_tab_page_omnibox_positioning.h b/ios/chrome/browser/ui/ntp/new_tab_page_omnibox_positioning.h new file mode 100644 index 0000000..f8a7cb05 --- /dev/null +++ b/ios/chrome/browser/ui/ntp/new_tab_page_omnibox_positioning.h
@@ -0,0 +1,16 @@ +// Copyright 2021 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 IOS_CHROME_BROWSER_UI_NTP_NEW_TAB_PAGE_OMNIBOX_POSITIONING_H_ +#define IOS_CHROME_BROWSER_UI_NTP_NEW_TAB_PAGE_OMNIBOX_POSITIONING_H_ + +// Protocol for information relating to the NTP's fake omnibox. +@protocol NewTabPageOmniboxPositioning + +// Returns the height of the fake omnibox to stick to the top of the NTP. +- (CGFloat)stickyOmniboxHeight; + +@end + +#endif // IOS_CHROME_BROWSER_UI_NTP_NEW_TAB_PAGE_OMNIBOX_POSITIONING_H_
diff --git a/ios/chrome/browser/ui/ntp/new_tab_page_view_controller.mm b/ios/chrome/browser/ui/ntp/new_tab_page_view_controller.mm index 6042370..d6e35a9 100644 --- a/ios/chrome/browser/ui/ntp/new_tab_page_view_controller.mm +++ b/ios/chrome/browser/ui/ntp/new_tab_page_view_controller.mm
@@ -12,6 +12,8 @@ #import "ios/chrome/browser/ui/content_suggestions/ntp_home_constant.h" #import "ios/chrome/browser/ui/ntp/discover_feed_wrapper_view_controller.h" #import "ios/chrome/browser/ui/ntp/new_tab_page_content_delegate.h" +#import "ios/chrome/browser/ui/ntp/new_tab_page_header_constants.h" +#import "ios/chrome/browser/ui/ntp/new_tab_page_omnibox_positioning.h" #import "ios/chrome/browser/ui/overscroll_actions/overscroll_actions_controller.h" #import "ios/chrome/browser/ui/toolbar/public/toolbar_utils.h" #import "ios/chrome/browser/ui/util/named_guide.h" @@ -29,12 +31,9 @@ // it look smooth). Otherwise, the omnibox hides beneath the feed before // changing ownership. const CGFloat kOffsetToPinOmnibox = 100; -// Offset so the FakeOmnibox owned by this ViewController completely covers the -// top of the screen. -const CGFloat kFakeOmniboxTopOffset = 3; } -@interface NewTabPageViewController () +@interface NewTabPageViewController () <NewTabPageOmniboxPositioning> // View controller representing the NTP content suggestions. These suggestions // include the most visited site tiles, the shortcut tiles, the fake omnibox and @@ -177,6 +176,7 @@ self.contentSuggestionsViewController.collectionView .collectionViewLayout); _contentSuggestionsLayout.isScrolledIntoFeed = self.isScrolledIntoFeed; + _contentSuggestionsLayout.omniboxPositioner = self; } - (void)viewDidLayoutSubviews { @@ -359,6 +359,20 @@ return self.discoverFeedWrapperViewController.feedCollectionView; } +#pragma mark - NewTabPageOmniboxPositioning + +- (CGFloat)stickyOmniboxHeight { + // Takes the height of the entire header and subtracts the margin to stick the + // fake omnibox. Adjusts this for the device by further subtracting the + // toolbar height and safe area insets. + return self.headerController.view.frame.size.height - + ntp_header::kFakeOmniboxScrolledToTopMargin - + ToolbarExpandedHeight( + [UIApplication sharedApplication].preferredContentSizeCategory) - + self.discoverFeedWrapperViewController.feedCollectionView + .safeAreaInsets.top; +} + #pragma mark - Private // Enables or disables overscroll actions. @@ -389,9 +403,7 @@ [self.headerController.view.topAnchor constraintEqualToAnchor:self.discoverFeedWrapperViewController.view .topAnchor - constant:-([self.ntpContentDelegate - heightAboveFakeOmnibox]) - - kFakeOmniboxTopOffset], + constant:-[self stickyOmniboxHeight]], [self.headerController.view.leadingAnchor constraintEqualToAnchor:self.discoverFeedWrapperViewController.view .leadingAnchor],
diff --git a/ios/chrome/browser/ui/overlays/infobar_modal/translate/translate_infobar_modal_overlay_mediator.mm b/ios/chrome/browser/ui/overlays/infobar_modal/translate/translate_infobar_modal_overlay_mediator.mm index 2954cc5..869fcac 100644 --- a/ios/chrome/browser/ui/overlays/infobar_modal/translate/translate_infobar_modal_overlay_mediator.mm +++ b/ios/chrome/browser/ui/overlays/infobar_modal/translate/translate_infobar_modal_overlay_mediator.mm
@@ -377,7 +377,8 @@ kEnableTranslateButtonPrefKey : @(translateButtonEnabled), kUpdateLanguageBeforeTranslatePrefKey : @(updateLanguageBeforeTranslate), kEnableAndDisplayShowOriginalButtonPrefKey : @(currentStepAfterTranslate), - kShouldAlwaysTranslatePrefKey : @(self.config->is_translatable_language()), + kShouldAlwaysTranslatePrefKey : + @(self.config->is_always_translate_enabled()), kDisplayNeverTranslateLanguagePrefKey : @(currentStepBeforeTranslate), kDisplayNeverTranslateSiteButtonPrefKey : @(currentStepBeforeTranslate), kIsTranslatableLanguagePrefKey : @(self.config->is_translatable_language()),
diff --git a/ios/chrome/browser/ui/overlays/infobar_modal/translate/translate_infobar_modal_overlay_mediator_unittest.mm b/ios/chrome/browser/ui/overlays/infobar_modal/translate/translate_infobar_modal_overlay_mediator_unittest.mm index 17080710..73e8df4d 100644 --- a/ios/chrome/browser/ui/overlays/infobar_modal/translate/translate_infobar_modal_overlay_mediator_unittest.mm +++ b/ios/chrome/browser/ui/overlays/infobar_modal/translate/translate_infobar_modal_overlay_mediator_unittest.mm
@@ -99,7 +99,7 @@ EXPECT_TRUE(consumer.enableTranslateActionButton); EXPECT_FALSE(consumer.updateLanguageBeforeTranslate); EXPECT_FALSE(consumer.displayShowOriginalButton); - EXPECT_TRUE(consumer.shouldAlwaysTranslate); + EXPECT_FALSE(consumer.shouldAlwaysTranslate); EXPECT_TRUE(consumer.shouldDisplayNeverTranslateLanguageButton); EXPECT_TRUE(consumer.isTranslatableLanguage); EXPECT_TRUE(consumer.shouldDisplayNeverTranslateSiteButton);
diff --git a/ios/chrome/browser/ui/tab_switcher/tab_grid/tab_grid_coordinator.mm b/ios/chrome/browser/ui/tab_switcher/tab_grid/tab_grid_coordinator.mm index 7435fa4..459051d1 100644 --- a/ios/chrome/browser/ui/tab_switcher/tab_grid/tab_grid_coordinator.mm +++ b/ios/chrome/browser/ui/tab_switcher/tab_grid/tab_grid_coordinator.mm
@@ -243,6 +243,11 @@ completion:(ProceduralBlock)completion { DCHECK(viewController || (IsThumbStripEnabled() && self.bvcContainer)); + if (shouldCloseTabGrid) { + // Record when the tab switcher is dismissed. + base::RecordAction(base::UserMetricsAction("MobileTabGridExited")); + } + // If thumb strip is enabled, this will always be true except during initial // setup before the BVC container has been created. if (IsThumbStripEnabled() && self.bvcContainer) { @@ -254,9 +259,6 @@ [self.baseViewController contentWillDisappearAnimated:YES]; [self.thumbStripCoordinator.panHandler setState:ViewRevealState::Hidden animated:YES]; - - // Record when the tab switcher is dismissed. - base::RecordAction(base::UserMetricsAction("MobileTabGridExited")); } if (completion) { completion();
diff --git a/ios/google_internal/frameworks/chrome_internal_dynamic_framework.arm64.zip.sha1 b/ios/google_internal/frameworks/chrome_internal_dynamic_framework.arm64.zip.sha1 index d21582d..3795db2 100644 --- a/ios/google_internal/frameworks/chrome_internal_dynamic_framework.arm64.zip.sha1 +++ b/ios/google_internal/frameworks/chrome_internal_dynamic_framework.arm64.zip.sha1
@@ -1 +1 @@ -40d2d7ce9f2430bb26be334ea4d769ea6c514a7b \ No newline at end of file +cae82670fbcc71219ec2facf0f93c26f766d88a3 \ No newline at end of file
diff --git a/ios/google_internal/frameworks/chrome_internal_dynamic_framework.x64.zip.sha1 b/ios/google_internal/frameworks/chrome_internal_dynamic_framework.x64.zip.sha1 index 4cad2861e..d8ab75b 100644 --- a/ios/google_internal/frameworks/chrome_internal_dynamic_framework.x64.zip.sha1 +++ b/ios/google_internal/frameworks/chrome_internal_dynamic_framework.x64.zip.sha1
@@ -1 +1 @@ -25e895d442c24e70f243dca08af9db00db47f4c8 \ No newline at end of file +a37faa26a48f8c65b53879d49fcf86fba45d549c \ No newline at end of file
diff --git a/ios/google_internal/frameworks/chrome_sso_internal_dynamic_framework.arm64.zip.sha1 b/ios/google_internal/frameworks/chrome_sso_internal_dynamic_framework.arm64.zip.sha1 index a6a7fe3..48790ea8 100644 --- a/ios/google_internal/frameworks/chrome_sso_internal_dynamic_framework.arm64.zip.sha1 +++ b/ios/google_internal/frameworks/chrome_sso_internal_dynamic_framework.arm64.zip.sha1
@@ -1 +1 @@ -f6b4d62833b501b2bcd67fb8cc54c06cf0bbdfa4 \ No newline at end of file +41c0adff05cf9ab7c83dab4edec8c4f41023b66e \ No newline at end of file
diff --git a/ios/google_internal/frameworks/chrome_sso_internal_dynamic_framework.x64.zip.sha1 b/ios/google_internal/frameworks/chrome_sso_internal_dynamic_framework.x64.zip.sha1 index 768e796b..6bd0239 100644 --- a/ios/google_internal/frameworks/chrome_sso_internal_dynamic_framework.x64.zip.sha1 +++ b/ios/google_internal/frameworks/chrome_sso_internal_dynamic_framework.x64.zip.sha1
@@ -1 +1 @@ -95a21066439cf6e6d8cdc099fab016cfd7ad1310 \ No newline at end of file +53effb27fc7e834e59c7ef96cdf79fbae509f382 \ No newline at end of file
diff --git a/ios/google_internal/frameworks/remoting_dogfood_internal_dynamic_framework.arm64.zip.sha1 b/ios/google_internal/frameworks/remoting_dogfood_internal_dynamic_framework.arm64.zip.sha1 index dadd74b..1940e1c 100644 --- a/ios/google_internal/frameworks/remoting_dogfood_internal_dynamic_framework.arm64.zip.sha1 +++ b/ios/google_internal/frameworks/remoting_dogfood_internal_dynamic_framework.arm64.zip.sha1
@@ -1 +1 @@ -297ad59eb705fc8ffd620bd8693aad4a4b0b2a66 \ No newline at end of file +68bd29df395eb1c061eb6e26c5f1c76d4d99f7b2 \ No newline at end of file
diff --git a/ios/google_internal/frameworks/remoting_dogfood_internal_dynamic_framework.x64.zip.sha1 b/ios/google_internal/frameworks/remoting_dogfood_internal_dynamic_framework.x64.zip.sha1 index 3726b7c..5bd914b 100644 --- a/ios/google_internal/frameworks/remoting_dogfood_internal_dynamic_framework.x64.zip.sha1 +++ b/ios/google_internal/frameworks/remoting_dogfood_internal_dynamic_framework.x64.zip.sha1
@@ -1 +1 @@ -f9f953f35c90b30d80f0dee6f8c1e5bb9251fbb7 \ No newline at end of file +770164018ebbbf8fa66d8c0d0ffae7ef5854f9e5 \ No newline at end of file
diff --git a/ios/google_internal/frameworks/remoting_internal_dynamic_framework.arm64.zip.sha1 b/ios/google_internal/frameworks/remoting_internal_dynamic_framework.arm64.zip.sha1 index 93ae8d2..4710cd8 100644 --- a/ios/google_internal/frameworks/remoting_internal_dynamic_framework.arm64.zip.sha1 +++ b/ios/google_internal/frameworks/remoting_internal_dynamic_framework.arm64.zip.sha1
@@ -1 +1 @@ -7731abbc222b0e1f9091b9484ae1da2824e02820 \ No newline at end of file +53fe4f5366b6af2173962768088676d4e7be7283 \ No newline at end of file
diff --git a/ios/google_internal/frameworks/remoting_internal_dynamic_framework.x64.zip.sha1 b/ios/google_internal/frameworks/remoting_internal_dynamic_framework.x64.zip.sha1 index ff4922a..adde03d 100644 --- a/ios/google_internal/frameworks/remoting_internal_dynamic_framework.x64.zip.sha1 +++ b/ios/google_internal/frameworks/remoting_internal_dynamic_framework.x64.zip.sha1
@@ -1 +1 @@ -4329f70db57d283d9b0f6c4223705ff86e6f1a66 \ No newline at end of file +c7dab75a521dd05d42a464a7f9955caf1dbf7272 \ No newline at end of file
diff --git a/ios/google_internal/frameworks/web_view_shell_internal_dynamic_framework.arm64.zip.sha1 b/ios/google_internal/frameworks/web_view_shell_internal_dynamic_framework.arm64.zip.sha1 index 2e679c4..26d879e 100644 --- a/ios/google_internal/frameworks/web_view_shell_internal_dynamic_framework.arm64.zip.sha1 +++ b/ios/google_internal/frameworks/web_view_shell_internal_dynamic_framework.arm64.zip.sha1
@@ -1 +1 @@ -6f163dc7805473ed0cb06e02ea80661b11363bdc \ No newline at end of file +c926f04517fef7e1b9b69892a0a64c5cf8701aa3 \ No newline at end of file
diff --git a/ios/google_internal/frameworks/web_view_shell_internal_dynamic_framework.x64.zip.sha1 b/ios/google_internal/frameworks/web_view_shell_internal_dynamic_framework.x64.zip.sha1 index be7d6638..bf8f69cde 100644 --- a/ios/google_internal/frameworks/web_view_shell_internal_dynamic_framework.x64.zip.sha1 +++ b/ios/google_internal/frameworks/web_view_shell_internal_dynamic_framework.x64.zip.sha1
@@ -1 +1 @@ -ff5e67369219efc46098808ac508ada672a8e3f1 \ No newline at end of file +4a94bb6104c3a54ff35afaffbe23b76f673cf9ad \ No newline at end of file
diff --git a/ios/third_party/earl_grey/Info.plist b/ios/third_party/earl_grey/Info.plist deleted file mode 100644 index 3124a94..0000000 --- a/ios/third_party/earl_grey/Info.plist +++ /dev/null
@@ -1,20 +0,0 @@ -<?xml version="1.0" encoding="UTF-8"?> -<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd"> -<plist version="1.0"> -<dict> - <key>CFBundleVersion</key> - <string>1.0</string> - <key>CFBundleSignature</key> - <string>????</string> - <key>CFBundlePackageType</key> - <string>FMWK</string> - <key>CFBundleInfoDictionaryVersion</key> - <string>6.0</string> - <key>CFBundleIdentifier</key> - <string>${IOS_BUNDLE_ID_PREFIX}.test.${EXECUTABLE_NAME:rfc1034identifier}</string> - <key>CFBundleExecutable</key> - <string>${EXECUTABLE_NAME}</string> - <key>CFBundleDevelopmentRegion</key> - <string>English</string> -</dict> -</plist>
diff --git a/ios/third_party/earl_grey/LICENSE b/ios/third_party/earl_grey/LICENSE deleted file mode 100644 index 4e58d90..0000000 --- a/ios/third_party/earl_grey/LICENSE +++ /dev/null
@@ -1,598 +0,0 @@ - - Apache License - Version 2.0, January 2004 - http://www.apache.org/licenses/ - - TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION - - 1. Definitions. - - "License" shall mean the terms and conditions for use, reproduction, - and distribution as defined by Sections 1 through 9 of this document. - - "Licensor" shall mean the copyright owner or entity authorized by - the copyright owner that is granting the License. - - "Legal Entity" shall mean the union of the acting entity and all - other entities that control, are controlled by, or are under common - control with that entity. For the purposes of this definition, - "control" means (i) the power, direct or indirect, to cause the - direction or management of such entity, whether by contract or - otherwise, or (ii) ownership of fifty percent (50%) or more of the - outstanding shares, or (iii) beneficial ownership of such entity. - - "You" (or "Your") shall mean an individual or Legal Entity - exercising permissions granted by this License. - - "Source" form shall mean the preferred form for making modifications, - including but not limited to software source code, documentation - source, and configuration files. - - "Object" form shall mean any form resulting from mechanical - transformation or translation of a Source form, including but - not limited to compiled object code, generated documentation, - and conversions to other media types. - - "Work" shall mean the work of authorship, whether in Source or - Object form, made available under the License, as indicated by a - copyright notice that is included in or attached to the work - (an example is provided in the Appendix below). - - "Derivative Works" shall mean any work, whether in Source or Object - form, that is based on (or derived from) the Work and for which the - editorial revisions, annotations, elaborations, or other modifications - represent, as a whole, an original work of authorship. For the purposes - of this License, Derivative Works shall not include works that remain - separable from, or merely link (or bind by name) to the interfaces of, - the Work and Derivative Works thereof. - - "Contribution" shall mean any work of authorship, including - the original version of the Work and any modifications or additions - to that Work or Derivative Works thereof, that is intentionally - submitted to Licensor for inclusion in the Work by the copyright owner - or by an individual or Legal Entity authorized to submit on behalf of - the copyright owner. For the purposes of this definition, "submitted" - means any form of electronic, verbal, or written communication sent - to the Licensor or its representatives, including but not limited to - communication on electronic mailing lists, source code control systems, - and issue tracking systems that are managed by, or on behalf of, the - Licensor for the purpose of discussing and improving the Work, but - excluding communication that is conspicuously marked or otherwise - designated in writing by the copyright owner as "Not a Contribution." - - "Contributor" shall mean Licensor and any individual or Legal Entity - on behalf of whom a Contribution has been received by Licensor and - subsequently incorporated within the Work. - - 2. Grant of Copyright License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - copyright license to reproduce, prepare Derivative Works of, - publicly display, publicly perform, sublicense, and distribute the - Work and such Derivative Works in Source or Object form. - - 3. Grant of Patent License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - (except as stated in this section) patent license to make, have made, - use, offer to sell, sell, import, and otherwise transfer the Work, - where such license applies only to those patent claims licensable - by such Contributor that are necessarily infringed by their - Contribution(s) alone or by combination of their Contribution(s) - with the Work to which such Contribution(s) was submitted. If You - institute patent litigation against any entity (including a - cross-claim or counterclaim in a lawsuit) alleging that the Work - or a Contribution incorporated within the Work constitutes direct - or contributory patent infringement, then any patent licenses - granted to You under this License for that Work shall terminate - as of the date such litigation is filed. - - 4. Redistribution. You may reproduce and distribute copies of the - Work or Derivative Works thereof in any medium, with or without - modifications, and in Source or Object form, provided that You - meet the following conditions: - - (a) You must give any other recipients of the Work or - Derivative Works a copy of this License; and - - (b) You must cause any modified files to carry prominent notices - stating that You changed the files; and - - (c) You must retain, in the Source form of any Derivative Works - that You distribute, all copyright, patent, trademark, and - attribution notices from the Source form of the Work, - excluding those notices that do not pertain to any part of - the Derivative Works; and - - (d) If the Work includes a "NOTICE" text file as part of its - distribution, then any Derivative Works that You distribute must - include a readable copy of the attribution notices contained - within such NOTICE file, excluding those notices that do not - pertain to any part of the Derivative Works, in at least one - of the following places: within a NOTICE text file distributed - as part of the Derivative Works; within the Source form or - documentation, if provided along with the Derivative Works; or, - within a display generated by the Derivative Works, if and - wherever such third-party notices normally appear. The contents - of the NOTICE file are for informational purposes only and - do not modify the License. You may add Your own attribution - notices within Derivative Works that You distribute, alongside - or as an addendum to the NOTICE text from the Work, provided - that such additional attribution notices cannot be construed - as modifying the License. - - You may add Your own copyright statement to Your modifications and - may provide additional or different license terms and conditions - for use, reproduction, or distribution of Your modifications, or - for any such Derivative Works as a whole, provided Your use, - reproduction, and distribution of the Work otherwise complies with - the conditions stated in this License. - - 5. Submission of Contributions. Unless You explicitly state otherwise, - any Contribution intentionally submitted for inclusion in the Work - by You to the Licensor shall be under the terms and conditions of - this License, without any additional terms or conditions. - Notwithstanding the above, nothing herein shall supersede or modify - the terms of any separate license agreement you may have executed - with Licensor regarding such Contributions. - - 6. Trademarks. This License does not grant permission to use the trade - names, trademarks, service marks, or product names of the Licensor, - except as required for reasonable and customary use in describing the - origin of the Work and reproducing the content of the NOTICE file. - - 7. Disclaimer of Warranty. Unless required by applicable law or - agreed to in writing, Licensor provides the Work (and each - Contributor provides its Contributions) on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or - implied, including, without limitation, any warranties or conditions - of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A - PARTICULAR PURPOSE. You are solely responsible for determining the - appropriateness of using or redistributing the Work and assume any - risks associated with Your exercise of permissions under this License. - - 8. Limitation of Liability. In no event and under no legal theory, - whether in tort (including negligence), contract, or otherwise, - unless required by applicable law (such as deliberate and grossly - negligent acts) or agreed to in writing, shall any Contributor be - liable to You for damages, including any direct, indirect, special, - incidental, or consequential damages of any character arising as a - result of this License or out of the use or inability to use the - Work (including but not limited to damages for loss of goodwill, - work stoppage, computer failure or malfunction, or any and all - other commercial damages or losses), even if such Contributor - has been advised of the possibility of such damages. - - 9. Accepting Warranty or Additional Liability. While redistributing - the Work or Derivative Works thereof, You may choose to offer, - and charge a fee for, acceptance of support, warranty, indemnity, - or other liability obligations and/or rights consistent with this - License. However, in accepting such obligations, You may act only - on Your own behalf and on Your sole responsibility, not on behalf - of any other Contributor, and only if You agree to indemnify, - defend, and hold each Contributor harmless for any liability - incurred by, or claims asserted against, such Contributor by reason - of your accepting any such warranty or additional liability. - - END OF TERMS AND CONDITIONS - - APPENDIX: How to apply the Apache License to your work. - - To apply the Apache License to your work, attach the following - boilerplate notice, with the fields enclosed by brackets "[]" - replaced with your own identifying information. (Don't include - the brackets!) The text should be enclosed in the appropriate - comment syntax for the file format. We also recommend that a - file or class name and description of purpose be included on the - same "printed page" as the copyright notice for easier - identification within third-party archives. - - Copyright [yyyy] [name of copyright owner] - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - --------------------------------------------------------------------------------------------- - -Attribution 4.0 International - -======================================================================= - -Creative Commons Corporation ("Creative Commons") is not a law firm and -does not provide legal services or legal advice. Distribution of -Creative Commons public licenses does not create a lawyer-client or -other relationship. Creative Commons makes its licenses and related -information available on an "as-is" basis. Creative Commons gives no -warranties regarding its licenses, any material licensed under their -terms and conditions, or any related information. Creative Commons -disclaims all liability for damages resulting from their use to the -fullest extent possible. - -Using Creative Commons Public Licenses - -Creative Commons public licenses provide a standard set of terms and -conditions that creators and other rights holders may use to share -original works of authorship and other material subject to copyright -and certain other rights specified in the public license below. The -following considerations are for informational purposes only, are not -exhaustive, and do not form part of our licenses. - - Considerations for licensors: Our public licenses are - intended for use by those authorized to give the public - permission to use material in ways otherwise restricted by - copyright and certain other rights. Our licenses are - irrevocable. Licensors should read and understand the terms - and conditions of the license they choose before applying it. - Licensors should also secure all rights necessary before - applying our licenses so that the public can reuse the - material as expected. Licensors should clearly mark any - material not subject to the license. This includes other CC- - licensed material, or material used under an exception or - limitation to copyright. More considerations for licensors: - wiki.creativecommons.org/Considerations_for_licensors - - Considerations for the public: By using one of our public - licenses, a licensor grants the public permission to use the - licensed material under specified terms and conditions. If - the licensor's permission is not necessary for any reason--for - example, because of any applicable exception or limitation to - copyright--then that use is not regulated by the license. Our - licenses grant only permissions under copyright and certain - other rights that a licensor has authority to grant. Use of - the licensed material may still be restricted for other - reasons, including because others have copyright or other - rights in the material. A licensor may make special requests, - such as asking that all changes be marked or described. - Although not required by our licenses, you are encouraged to - respect those requests where reasonable. More_considerations - for the public: - wiki.creativecommons.org/Considerations_for_licensees - -======================================================================= - -Creative Commons Attribution 4.0 International Public License - -By exercising the Licensed Rights (defined below), You accept and agree -to be bound by the terms and conditions of this Creative Commons -Attribution 4.0 International Public License ("Public License"). To the -extent this Public License may be interpreted as a contract, You are -granted the Licensed Rights in consideration of Your acceptance of -these terms and conditions, and the Licensor grants You such rights in -consideration of benefits the Licensor receives from making the -Licensed Material available under these terms and conditions. - - -Section 1 -- Definitions. - - a. Adapted Material means material subject to Copyright and Similar - Rights that is derived from or based upon the Licensed Material - and in which the Licensed Material is translated, altered, - arranged, transformed, or otherwise modified in a manner requiring - permission under the Copyright and Similar Rights held by the - Licensor. For purposes of this Public License, where the Licensed - Material is a musical work, performance, or sound recording, - Adapted Material is always produced where the Licensed Material is - synched in timed relation with a moving image. - - b. Adapter's License means the license You apply to Your Copyright - and Similar Rights in Your contributions to Adapted Material in - accordance with the terms and conditions of this Public License. - - c. Copyright and Similar Rights means copyright and/or similar rights - closely related to copyright including, without limitation, - performance, broadcast, sound recording, and Sui Generis Database - Rights, without regard to how the rights are labeled or - categorized. For purposes of this Public License, the rights - specified in Section 2(b)(1)-(2) are not Copyright and Similar - Rights. - - d. Effective Technological Measures means those measures that, in the - absence of proper authority, may not be circumvented under laws - fulfilling obligations under Article 11 of the WIPO Copyright - Treaty adopted on December 20, 1996, and/or similar international - agreements. - - e. Exceptions and Limitations means fair use, fair dealing, and/or - any other exception or limitation to Copyright and Similar Rights - that applies to Your use of the Licensed Material. - - f. Licensed Material means the artistic or literary work, database, - or other material to which the Licensor applied this Public - License. - - g. Licensed Rights means the rights granted to You subject to the - terms and conditions of this Public License, which are limited to - all Copyright and Similar Rights that apply to Your use of the - Licensed Material and that the Licensor has authority to license. - - h. Licensor means the individual(s) or entity(ies) granting rights - under this Public License. - - i. Share means to provide material to the public by any means or - process that requires permission under the Licensed Rights, such - as reproduction, public display, public performance, distribution, - dissemination, communication, or importation, and to make material - available to the public including in ways that members of the - public may access the material from a place and at a time - individually chosen by them. - - j. Sui Generis Database Rights means rights other than copyright - resulting from Directive 96/9/EC of the European Parliament and of - the Council of 11 March 1996 on the legal protection of databases, - as amended and/or succeeded, as well as other essentially - equivalent rights anywhere in the world. - - k. You means the individual or entity exercising the Licensed Rights - under this Public License. Your has a corresponding meaning. - - -Section 2 -- Scope. - - a. License grant. - - 1. Subject to the terms and conditions of this Public License, - the Licensor hereby grants You a worldwide, royalty-free, - non-sublicensable, non-exclusive, irrevocable license to - exercise the Licensed Rights in the Licensed Material to: - - a. reproduce and Share the Licensed Material, in whole or - in part; and - - b. produce, reproduce, and Share Adapted Material. - - 2. Exceptions and Limitations. For the avoidance of doubt, where - Exceptions and Limitations apply to Your use, this Public - License does not apply, and You do not need to comply with - its terms and conditions. - - 3. Term. The term of this Public License is specified in Section - 6(a). - - 4. Media and formats; technical modifications allowed. The - Licensor authorizes You to exercise the Licensed Rights in - all media and formats whether now known or hereafter created, - and to make technical modifications necessary to do so. The - Licensor waives and/or agrees not to assert any right or - authority to forbid You from making technical modifications - necessary to exercise the Licensed Rights, including - technical modifications necessary to circumvent Effective - Technological Measures. For purposes of this Public License, - simply making modifications authorized by this Section 2(a) - (4) never produces Adapted Material. - - 5. Downstream recipients. - - a. Offer from the Licensor -- Licensed Material. Every - recipient of the Licensed Material automatically - receives an offer from the Licensor to exercise the - Licensed Rights under the terms and conditions of this - Public License. - - b. No downstream restrictions. You may not offer or impose - any additional or different terms or conditions on, or - apply any Effective Technological Measures to, the - Licensed Material if doing so restricts exercise of the - Licensed Rights by any recipient of the Licensed - Material. - - 6. No endorsement. Nothing in this Public License constitutes or - may be construed as permission to assert or imply that You - are, or that Your use of the Licensed Material is, connected - with, or sponsored, endorsed, or granted official status by, - the Licensor or others designated to receive attribution as - provided in Section 3(a)(1)(A)(i). - - b. Other rights. - - 1. Moral rights, such as the right of integrity, are not - licensed under this Public License, nor are publicity, - privacy, and/or other similar personality rights; however, to - the extent possible, the Licensor waives and/or agrees not to - assert any such rights held by the Licensor to the limited - extent necessary to allow You to exercise the Licensed - Rights, but not otherwise. - - 2. Patent and trademark rights are not licensed under this - Public License. - - 3. To the extent possible, the Licensor waives any right to - collect royalties from You for the exercise of the Licensed - Rights, whether directly or through a collecting society - under any voluntary or waivable statutory or compulsory - licensing scheme. In all other cases the Licensor expressly - reserves any right to collect such royalties. - - -Section 3 -- License Conditions. - -Your exercise of the Licensed Rights is expressly made subject to the -following conditions. - - a. Attribution. - - 1. If You Share the Licensed Material (including in modified - form), You must: - - a. retain the following if it is supplied by the Licensor - with the Licensed Material: - - i. identification of the creator(s) of the Licensed - Material and any others designated to receive - attribution, in any reasonable manner requested by - the Licensor (including by pseudonym if - designated); - - ii. a copyright notice; - - iii. a notice that refers to this Public License; - - iv. a notice that refers to the disclaimer of - warranties; - - v. a URI or hyperlink to the Licensed Material to the - extent reasonably practicable; - - b. indicate if You modified the Licensed Material and - retain an indication of any previous modifications; and - - c. indicate the Licensed Material is licensed under this - Public License, and include the text of, or the URI or - hyperlink to, this Public License. - - 2. You may satisfy the conditions in Section 3(a)(1) in any - reasonable manner based on the medium, means, and context in - which You Share the Licensed Material. For example, it may be - reasonable to satisfy the conditions by providing a URI or - hyperlink to a resource that includes the required - information. - - 3. If requested by the Licensor, You must remove any of the - information required by Section 3(a)(1)(A) to the extent - reasonably practicable. - - 4. If You Share Adapted Material You produce, the Adapter's - License You apply must not prevent recipients of the Adapted - Material from complying with this Public License. - - -Section 4 -- Sui Generis Database Rights. - -Where the Licensed Rights include Sui Generis Database Rights that -apply to Your use of the Licensed Material: - - a. for the avoidance of doubt, Section 2(a)(1) grants You the right - to extract, reuse, reproduce, and Share all or a substantial - portion of the contents of the database; - - b. if You include all or a substantial portion of the database - contents in a database in which You have Sui Generis Database - Rights, then the database in which You have Sui Generis Database - Rights (but not its individual contents) is Adapted Material; and - - c. You must comply with the conditions in Section 3(a) if You Share - all or a substantial portion of the contents of the database. - -For the avoidance of doubt, this Section 4 supplements and does not -replace Your obligations under this Public License where the Licensed -Rights include other Copyright and Similar Rights. - - -Section 5 -- Disclaimer of Warranties and Limitation of Liability. - - a. UNLESS OTHERWISE SEPARATELY UNDERTAKEN BY THE LICENSOR, TO THE - EXTENT POSSIBLE, THE LICENSOR OFFERS THE LICENSED MATERIAL AS-IS - AND AS-AVAILABLE, AND MAKES NO REPRESENTATIONS OR WARRANTIES OF - ANY KIND CONCERNING THE LICENSED MATERIAL, WHETHER EXPRESS, - IMPLIED, STATUTORY, OR OTHER. THIS INCLUDES, WITHOUT LIMITATION, - WARRANTIES OF TITLE, MERCHANTABILITY, FITNESS FOR A PARTICULAR - PURPOSE, NON-INFRINGEMENT, ABSENCE OF LATENT OR OTHER DEFECTS, - ACCURACY, OR THE PRESENCE OR ABSENCE OF ERRORS, WHETHER OR NOT - KNOWN OR DISCOVERABLE. WHERE DISCLAIMERS OF WARRANTIES ARE NOT - ALLOWED IN FULL OR IN PART, THIS DISCLAIMER MAY NOT APPLY TO YOU. - - b. TO THE EXTENT POSSIBLE, IN NO EVENT WILL THE LICENSOR BE LIABLE - TO YOU ON ANY LEGAL THEORY (INCLUDING, WITHOUT LIMITATION, - NEGLIGENCE) OR OTHERWISE FOR ANY DIRECT, SPECIAL, INDIRECT, - INCIDENTAL, CONSEQUENTIAL, PUNITIVE, EXEMPLARY, OR OTHER LOSSES, - COSTS, EXPENSES, OR DAMAGES ARISING OUT OF THIS PUBLIC LICENSE OR - USE OF THE LICENSED MATERIAL, EVEN IF THE LICENSOR HAS BEEN - ADVISED OF THE POSSIBILITY OF SUCH LOSSES, COSTS, EXPENSES, OR - DAMAGES. WHERE A LIMITATION OF LIABILITY IS NOT ALLOWED IN FULL OR - IN PART, THIS LIMITATION MAY NOT APPLY TO YOU. - - c. The disclaimer of warranties and limitation of liability provided - above shall be interpreted in a manner that, to the extent - possible, most closely approximates an absolute disclaimer and - waiver of all liability. - - -Section 6 -- Term and Termination. - - a. This Public License applies for the term of the Copyright and - Similar Rights licensed here. However, if You fail to comply with - this Public License, then Your rights under this Public License - terminate automatically. - - b. Where Your right to use the Licensed Material has terminated under - Section 6(a), it reinstates: - - 1. automatically as of the date the violation is cured, provided - it is cured within 30 days of Your discovery of the - violation; or - - 2. upon express reinstatement by the Licensor. - - For the avoidance of doubt, this Section 6(b) does not affect any - right the Licensor may have to seek remedies for Your violations - of this Public License. - - c. For the avoidance of doubt, the Licensor may also offer the - Licensed Material under separate terms or conditions or stop - distributing the Licensed Material at any time; however, doing so - will not terminate this Public License. - - d. Sections 1, 5, 6, 7, and 8 survive termination of this Public - License. - - -Section 7 -- Other Terms and Conditions. - - a. The Licensor shall not be bound by any additional or different - terms or conditions communicated by You unless expressly agreed. - - b. Any arrangements, understandings, or agreements regarding the - Licensed Material not stated herein are separate from and - independent of the terms and conditions of this Public License. - - -Section 8 -- Interpretation. - - a. For the avoidance of doubt, this Public License does not, and - shall not be interpreted to, reduce, limit, restrict, or impose - conditions on any use of the Licensed Material that could lawfully - be made without permission under this Public License. - - b. To the extent possible, if any provision of this Public License is - deemed unenforceable, it shall be automatically reformed to the - minimum extent necessary to make it enforceable. If the provision - cannot be reformed, it shall be severed from this Public License - without affecting the enforceability of the remaining terms and - conditions. - - c. No term or condition of this Public License will be waived and no - failure to comply consented to unless expressly agreed to by the - Licensor. - - d. Nothing in this Public License constitutes or may be interpreted - as a limitation upon, or waiver of, any privileges and immunities - that apply to the Licensor or You, including from the legal - processes of any jurisdiction or authority. - - -======================================================================= - -Creative Commons is not a party to its public licenses. -Notwithstanding, Creative Commons may elect to apply one of its public -licenses to material it publishes and in those instances will be -considered the "Licensor." Except for the limited purpose of indicating -that material is shared under a Creative Commons public license or as -otherwise permitted by the Creative Commons policies published at -creativecommons.org/policies, Creative Commons does not authorize the -use of the trademark "Creative Commons" or any other trademark or logo -of Creative Commons without its prior written consent including, -without limitation, in connection with any unauthorized modifications -to any of its public licenses or any other arrangements, -understandings, or agreements concerning use of licensed material. For -the avoidance of doubt, this paragraph does not form part of the public -licenses. - -Creative Commons may be contacted at creativecommons.org.
diff --git a/ios/third_party/earl_grey/OWNERS b/ios/third_party/earl_grey/OWNERS deleted file mode 100644 index ff2123f..0000000 --- a/ios/third_party/earl_grey/OWNERS +++ /dev/null
@@ -1,2 +0,0 @@ -justincohen@chromium.org -rohitrao@chromium.org
diff --git a/ios/third_party/earl_grey/README.chromium b/ios/third_party/earl_grey/README.chromium deleted file mode 100644 index 2d2f5f5..0000000 --- a/ios/third_party/earl_grey/README.chromium +++ /dev/null
@@ -1,11 +0,0 @@ -Name: EarlGrey -Short Name: EarlGrey -URL: https://github.com/google/EarlGrey -Version: 1.14.0 -License: Apache 2.0 -License File: NOT_SHIPPED -Security Critical: no - -Description: -EarlGrey is an iOS UI Automation framework that enables you to -write clear, concise tests.
diff --git a/jingle/glue/network_service_async_socket_unittest.cc b/jingle/glue/network_service_async_socket_unittest.cc index b14b90b..c550eb2 100644 --- a/jingle/glue/network_service_async_socket_unittest.cc +++ b/jingle/glue/network_service_async_socket_unittest.cc
@@ -152,16 +152,21 @@ void Connect(mojo::PendingRemote<network::mojom::SocketObserver> observer, network::mojom::ProxyResolvingSocketFactory:: CreateProxyResolvingSocketCallback callback) { - mojo::DataPipe send_pipe; - mojo::DataPipe receive_pipe; + mojo::ScopedDataPipeProducerHandle send_producer_handle; + ASSERT_EQ( + mojo::CreateDataPipe(nullptr, send_producer_handle, send_pipe_handle_), + MOJO_RESULT_OK); + + mojo::ScopedDataPipeConsumerHandle receive_consumer_handle; + ASSERT_EQ(mojo::CreateDataPipe(nullptr, receive_pipe_handle_, + receive_consumer_handle), + MOJO_RESULT_OK); observer_.Bind(std::move(observer)); - receive_pipe_handle_ = std::move(receive_pipe.producer_handle); - send_pipe_handle_ = std::move(send_pipe.consumer_handle); std::move(callback).Run(net::OK, base::nullopt, base::nullopt, - std::move(receive_pipe.consumer_handle), - std::move(send_pipe.producer_handle)); + std::move(receive_consumer_handle), + std::move(send_producer_handle)); } void RunEvents(std::vector<Event>&& events);
diff --git a/media/base/media_switches.cc b/media/base/media_switches.cc index bef7fd9a7..1fa2824 100644 --- a/media/base/media_switches.cc +++ b/media/base/media_switches.cc
@@ -721,9 +721,6 @@ // This feature only has any effect if kAVFoundationCaptureV2 is also enabled. const base::Feature MEDIA_EXPORT kAVFoundationCaptureV2ZeroCopy{ "AVFoundationCaptureV2ZeroCopy", base::FEATURE_ENABLED_BY_DEFAULT}; - -const base::Feature MEDIA_EXPORT kVideoToolboxVp9Decoding{ - "VideoToolboxVp9Decoding", base::FEATURE_DISABLED_BY_DEFAULT}; #endif // defined(OS_MAC) #if BUILDFLAG(IS_CHROMEOS_ASH)
diff --git a/media/base/media_switches.h b/media/base/media_switches.h index ea9f5d0..f57c021 100644 --- a/media/base/media_switches.h +++ b/media/base/media_switches.h
@@ -239,7 +239,6 @@ #if defined(OS_MAC) MEDIA_EXPORT extern const base::Feature kAVFoundationCaptureV2; MEDIA_EXPORT extern const base::Feature kAVFoundationCaptureV2ZeroCopy; -MEDIA_EXPORT extern const base::Feature kVideoToolboxVp9Decoding; #endif #if BUILDFLAG(IS_CHROMEOS_ASH)
diff --git a/media/cast/net/udp_packet_pipe_unittest.cc b/media/cast/net/udp_packet_pipe_unittest.cc index d02b465..69ca2d1 100644 --- a/media/cast/net/udp_packet_pipe_unittest.cc +++ b/media/cast/net/udp_packet_pipe_unittest.cc
@@ -26,11 +26,13 @@ class UdpPacketPipeTest : public ::testing::Test { public: UdpPacketPipeTest() { - mojo::DataPipe data_pipe(kDefaultDataPipeCapacityBytes); - writer_ = std::make_unique<UdpPacketPipeWriter>( - std::move(data_pipe.producer_handle)); - reader_ = std::make_unique<UdpPacketPipeReader>( - std::move(data_pipe.consumer_handle)); + mojo::ScopedDataPipeProducerHandle producer_handle; + mojo::ScopedDataPipeConsumerHandle consumer_handle; + CHECK_EQ(mojo::CreateDataPipe(kDefaultDataPipeCapacityBytes, + producer_handle, consumer_handle), + MOJO_RESULT_OK); + writer_ = std::make_unique<UdpPacketPipeWriter>(std::move(producer_handle)); + reader_ = std::make_unique<UdpPacketPipeReader>(std::move(consumer_handle)); } ~UdpPacketPipeTest() override = default;
diff --git a/media/cast/net/udp_transport_unittest.cc b/media/cast/net/udp_transport_unittest.cc index aa65563..0946281a 100644 --- a/media/cast/net/udp_transport_unittest.cc +++ b/media/cast/net/udp_transport_unittest.cc
@@ -139,9 +139,12 @@ recv_transport_->StartReceiving( packet_receiver_on_receiver.packet_receiver()); - mojo::DataPipe data_pipe(5); - send_transport_->StartSending(std::move(data_pipe.consumer_handle)); - UdpPacketPipeWriter writer(std::move(data_pipe.producer_handle)); + mojo::ScopedDataPipeProducerHandle producer_handle; + mojo::ScopedDataPipeConsumerHandle consumer_handle; + ASSERT_EQ(mojo::CreateDataPipe(5, producer_handle, consumer_handle), + MOJO_RESULT_OK); + send_transport_->StartSending(std::move(consumer_handle)); + UdpPacketPipeWriter writer(std::move(producer_handle)); base::MockCallback<base::OnceClosure> done_callback; EXPECT_CALL(done_callback, Run()).Times(1); writer.Write(new base::RefCountedData<Packet>(packet), done_callback.Get());
diff --git a/media/fuchsia/audio/fake_audio_consumer.h b/media/fuchsia/audio/fake_audio_consumer.h index c42469a..da1fcefb8 100644 --- a/media/fuchsia/audio/fake_audio_consumer.h +++ b/media/fuchsia/audio/fake_audio_consumer.h
@@ -156,8 +156,7 @@ // Not-implemented handler for SessionAudioConsumerFactory_TestBase. void NotImplemented_(const std::string& name) final; - base::fuchsia::ScopedServiceBinding< - fuchsia::media::SessionAudioConsumerFactory> + base::ScopedServiceBinding<fuchsia::media::SessionAudioConsumerFactory> binding_; std::vector<std::unique_ptr<FakeAudioConsumer>> audio_consumers_;
diff --git a/media/gpu/mac/vt_video_decode_accelerator_mac.cc b/media/gpu/mac/vt_video_decode_accelerator_mac.cc index 22fa4dc..70fa685 100644 --- a/media/gpu/mac/vt_video_decode_accelerator_mac.cc +++ b/media/gpu/mac/vt_video_decode_accelerator_mac.cc
@@ -1723,8 +1723,6 @@ continue; if (!base::mac::IsAtLeastOS11()) continue; - if (!base::FeatureList::IsEnabled(kVideoToolboxVp9Decoding)) - continue; if (__builtin_available(macOS 10.13, *)) { if ((supported_profile == VP9PROFILE_PROFILE0 || supported_profile == VP9PROFILE_PROFILE2) &&
diff --git a/media/mojo/common/mojo_data_pipe_read_write_unittest.cc b/media/mojo/common/mojo_data_pipe_read_write_unittest.cc index b4978d1..69bad8b 100644 --- a/media/mojo/common/mojo_data_pipe_read_write_unittest.cc +++ b/media/mojo/common/mojo_data_pipe_read_write_unittest.cc
@@ -26,12 +26,14 @@ public: MojoDataPipeReadWrite( uint32_t data_pipe_capacity_bytes = kDefaultDataPipeCapacityBytes) { - mojo::DataPipe data_pipe(data_pipe_capacity_bytes); + mojo::ScopedDataPipeProducerHandle producer_handle; + mojo::ScopedDataPipeConsumerHandle consumer_handle; + CHECK_EQ(mojo::CreateDataPipe(data_pipe_capacity_bytes, producer_handle, + consumer_handle), + MOJO_RESULT_OK); - writer_ = std::make_unique<MojoDataPipeWriter>( - std::move(data_pipe.producer_handle)); - reader_ = std::make_unique<MojoDataPipeReader>( - std::move(data_pipe.consumer_handle)); + writer_ = std::make_unique<MojoDataPipeWriter>(std::move(producer_handle)); + reader_ = std::make_unique<MojoDataPipeReader>(std::move(consumer_handle)); } void WriteAndRead(const uint8_t* buffer,
diff --git a/media/remoting/courier_renderer.cc b/media/remoting/courier_renderer.cc index c7d32b9c..ac1dbba 100644 --- a/media/remoting/courier_renderer.cc +++ b/media/remoting/courier_renderer.cc
@@ -123,24 +123,14 @@ ::media::DemuxerStream* video_demuxer_stream = media_resource_->GetFirstStream(DemuxerStream::VIDEO); - // Create audio mojo data pipe handles if audio is available. - std::unique_ptr<mojo::DataPipe> audio_data_pipe; - if (audio_demuxer_stream) { - audio_data_pipe = base::WrapUnique(DemuxerStreamAdapter::CreateDataPipe()); - } - - // Create video mojo data pipe handles if video is available. - std::unique_ptr<mojo::DataPipe> video_data_pipe; - if (video_demuxer_stream) { - video_data_pipe = base::WrapUnique(DemuxerStreamAdapter::CreateDataPipe()); - } - // Establish remoting data pipe connection using main thread. + uint32_t data_pipe_capacity = + DemuxerStreamAdapter::kMojoDataPipeCapacityInBytes; main_task_runner_->PostTask( FROM_HERE, base::BindOnce( - &RendererController::StartDataPipe, controller_, - std::move(audio_data_pipe), std::move(video_data_pipe), + &RendererController::StartDataPipe, controller_, data_pipe_capacity, + audio_demuxer_stream, video_demuxer_stream, base::BindOnce(&CourierRenderer::OnDataPipeCreatedOnMainThread, media_task_runner_, weak_factory_.GetWeakPtr(), rpc_broker_)));
diff --git a/media/remoting/demuxer_stream_adapter.cc b/media/remoting/demuxer_stream_adapter.cc index 63b7b9d..d9e3e50 100644 --- a/media/remoting/demuxer_stream_adapter.cc +++ b/media/remoting/demuxer_stream_adapter.cc
@@ -22,13 +22,6 @@ namespace media { namespace remoting { -// static -mojo::DataPipe* DemuxerStreamAdapter::CreateDataPipe() { - // Capacity in bytes for Mojo data pipe. - constexpr int kMojoDataPipeCapacityInBytes = 512 * 1024; - return new mojo::DataPipe(kMojoDataPipeCapacityInBytes); -} - DemuxerStreamAdapter::DemuxerStreamAdapter( scoped_refptr<base::SingleThreadTaskRunner> main_task_runner, scoped_refptr<base::SingleThreadTaskRunner> media_task_runner,
diff --git a/media/remoting/demuxer_stream_adapter.h b/media/remoting/demuxer_stream_adapter.h index e2e1324..56436cf 100644 --- a/media/remoting/demuxer_stream_adapter.h +++ b/media/remoting/demuxer_stream_adapter.h
@@ -44,6 +44,9 @@ public: using ErrorCallback = base::OnceCallback<void(StopTrigger)>; + // The capacity in bytes for the Mojo data pipes used with this class. + static constexpr uint32_t kMojoDataPipeCapacityInBytes = 512 * 1024; + // |main_task_runner|: Task runner to post RPC message on main thread // |media_task_runner|: Task runner to run whole class on media thread. // |name|: Demuxer stream name. For troubleshooting purposes. @@ -96,10 +99,6 @@ // pipe. bool is_data_pending() const { return !pending_frame_.empty(); } - // Creates a Mojo data pipe configured appropriately for use with a - // DemuxerStreamAdapter. - static mojo::DataPipe* CreateDataPipe(); - private: friend class MockDemuxerStreamAdapter;
diff --git a/media/remoting/renderer_controller.cc b/media/remoting/renderer_controller.cc index 72738bd8..ae3e46b 100644 --- a/media/remoting/renderer_controller.cc +++ b/media/remoting/renderer_controller.cc
@@ -219,16 +219,30 @@ } #endif -void RendererController::StartDataPipe( - std::unique_ptr<mojo::DataPipe> audio_data_pipe, - std::unique_ptr<mojo::DataPipe> video_data_pipe, - DataPipeStartCallback done_callback) { +void RendererController::StartDataPipe(uint32_t data_pipe_capacity, + bool audio, + bool video, + DataPipeStartCallback done_callback) { DCHECK(thread_checker_.CalledOnValidThread()); DCHECK(!done_callback.is_null()); - bool audio = audio_data_pipe != nullptr; - bool video = video_data_pipe != nullptr; - if (!audio && !video) { + bool ok = audio || video; + + mojo::ScopedDataPipeProducerHandle audio_producer_handle; + mojo::ScopedDataPipeConsumerHandle audio_consumer_handle; + if (ok && audio) { + ok &= mojo::CreateDataPipe(data_pipe_capacity, audio_producer_handle, + audio_consumer_handle) == MOJO_RESULT_OK; + } + + mojo::ScopedDataPipeProducerHandle video_producer_handle; + mojo::ScopedDataPipeConsumerHandle video_consumer_handle; + if (ok && video) { + ok &= mojo::CreateDataPipe(data_pipe_capacity, video_producer_handle, + video_consumer_handle) == MOJO_RESULT_OK; + } + + if (!ok) { LOG(ERROR) << "No audio nor video to establish data pipe"; std::move(done_callback) .Run(mojo::NullRemote(), mojo::NullRemote(), @@ -236,23 +250,18 @@ mojo::ScopedDataPipeProducerHandle()); return; } + mojo::PendingRemote<mojom::RemotingDataStreamSender> audio_stream_sender; mojo::PendingRemote<mojom::RemotingDataStreamSender> video_stream_sender; remoter_->StartDataStreams( - audio ? std::move(audio_data_pipe->consumer_handle) - : mojo::ScopedDataPipeConsumerHandle(), - video ? std::move(video_data_pipe->consumer_handle) - : mojo::ScopedDataPipeConsumerHandle(), + std::move(audio_consumer_handle), std::move(video_consumer_handle), audio ? audio_stream_sender.InitWithNewPipeAndPassReceiver() : mojo::NullReceiver(), video ? video_stream_sender.InitWithNewPipeAndPassReceiver() : mojo::NullReceiver()); std::move(done_callback) .Run(std::move(audio_stream_sender), std::move(video_stream_sender), - audio ? std::move(audio_data_pipe->producer_handle) - : mojo::ScopedDataPipeProducerHandle(), - video ? std::move(video_data_pipe->producer_handle) - : mojo::ScopedDataPipeProducerHandle()); + std::move(audio_producer_handle), std::move(video_producer_handle)); } void RendererController::OnMetadataChanged(const PipelineMetadata& metadata) {
diff --git a/media/remoting/renderer_controller.h b/media/remoting/renderer_controller.h index 2bdc4d8..4bcc0e1 100644 --- a/media/remoting/renderer_controller.h +++ b/media/remoting/renderer_controller.h
@@ -80,8 +80,13 @@ mojo::PendingRemote<mojom::RemotingDataStreamSender> video, mojo::ScopedDataPipeProducerHandle audio_handle, mojo::ScopedDataPipeProducerHandle video_handle)>; - void StartDataPipe(std::unique_ptr<mojo::DataPipe> audio_data_pipe, - std::unique_ptr<mojo::DataPipe> video_data_pipe, + // Creates up to two data pipes with a byte capacity of |data_pipe_capacity|: + // one for audio if |audio| is true and one for |video| if video is true. The + // controller then starts processing the consumer ends of the data pipes, + // with the producer ends supplied to the |done_callback|. + void StartDataPipe(uint32_t data_pipe_capacity, + bool audio, + bool video, DataPipeStartCallback done_callback); #if BUILDFLAG(ENABLE_MEDIA_REMOTING_RPC)
diff --git a/net/dns/README.md b/net/dns/README.md index 4f88fea..f59dde44 100644 --- a/net/dns/README.md +++ b/net/dns/README.md
@@ -261,10 +261,6 @@ `net::HostResolverProc` may be replaced by a chain of test implementations to override behavior. -Data collected specifically for this source: - -* "Net.DNS.SecureDnsTaskFailure.FallbackProcTask.Error" - #### DNS `net::HostResolverSource::DNS` @@ -318,7 +314,6 @@ * "Net.DNS.SecureDnsTask.DnsModeAutomatic.FailureTime" * "Net.DNS.SecureDnsTask.ErrorBeforeFallback.Fast" * "Net.DNS.SecureDnsTask.ErrorBeforeFallback.Slow" -* "Net.DNS.SecureDnsTaskFailure.FallbackDnsTask.Error" #### MULTICAST_DNS
diff --git a/net/dns/host_resolver_manager.cc b/net/dns/host_resolver_manager.cc index 90e82c9..5f5f079 100644 --- a/net/dns/host_resolver_manager.cc +++ b/net/dns/host_resolver_manager.cc
@@ -1619,7 +1619,6 @@ num_occupied_job_slots_(0), dispatcher_(nullptr), dns_task_error_(OK), - is_secure_dns_task_error_(false), tick_clock_(tick_clock), start_time_(base::TimeTicks()), net_log_( @@ -1774,7 +1773,6 @@ if (has_proc_fallback) { KillDnsTask(); dns_task_error_ = OK; - is_secure_dns_task_error_ = false; RunNextTask(); } else if (!fallback_only) { CompleteRequestsWithError(error); @@ -2006,21 +2004,10 @@ const AddressList& addr_list) { DCHECK(proc_task_); - if (dns_task_error_ != OK) { - // If a secure DNS task previously failed and fell back to a ProcTask - // without issuing an insecure DNS task in between, record what happened - // to the fallback ProcTask. - if (is_secure_dns_task_error_) { - base::UmaHistogramSparse( - "Net.DNS.SecureDnsTaskFailure.FallbackProcTask.Error", - std::abs(net_error)); - } - + if (dns_task_error_ != OK && net_error == OK) { // This ProcTask was a fallback resolution after a failed insecure // DnsTask. - if (net_error == OK) { - resolver_->OnFallbackResolve(dns_task_error_); - } + resolver_->OnFallbackResolve(dns_task_error_); } if (ContainsIcannNameCollisionIp(addr_list)) @@ -2137,7 +2124,6 @@ completion_results_.push_back({failure_results, ttl, secure}); dns_task_error_ = failure_results.error(); - is_secure_dns_task_error_ = secure; KillDnsTask(); RunNextTask(); } @@ -2149,14 +2135,6 @@ bool secure) override { DCHECK(dns_task_); - // If a secure DNS task previously failed, record what happened to the - // fallback insecure DNS task. - if (dns_task_error_ != OK && is_secure_dns_task_error_) { - base::UmaHistogramSparse( - "Net.DNS.SecureDnsTaskFailure.FallbackDnsTask.Error", - std::abs(results.error())); - } - base::TimeDelta duration = tick_clock_->NowTicks() - start_time; if (results.error() != OK) { OnDnsTaskFailure(dns_task_->AsWeakPtr(), duration, results, secure); @@ -2494,10 +2472,6 @@ // Result of DnsTask. int dns_task_error_; - // Whether the error in |dns_task_error_| corresponds to an insecure or - // secure DnsTask. - bool is_secure_dns_task_error_; - const base::TickClock* tick_clock_; base::TimeTicks start_time_;
diff --git a/pdf/BUILD.gn b/pdf/BUILD.gn index 559f30afc..53804c0 100644 --- a/pdf/BUILD.gn +++ b/pdf/BUILD.gn
@@ -283,6 +283,7 @@ ":ppapi_migration", "//base", "//cc/paint", + "//content/public/renderer", "//gin", "//ppapi/cpp:objects", # TODO(crbug.com/1114263): PDFEngine::Client only. "//third_party/blink/public:blink_headers",
diff --git a/pdf/DEPS b/pdf/DEPS index ef18de0d..a0ac9d1 100644 --- a/pdf/DEPS +++ b/pdf/DEPS
@@ -1,5 +1,6 @@ include_rules = [ "+cc/paint", + "+content/public/renderer/v8_value_converter.h", "+gin/handle.h", "+gin/public", "+gin/object_template_builder.h",
diff --git a/pdf/out_of_process_instance.cc b/pdf/out_of_process_instance.cc index c23b5732..63c1258 100644 --- a/pdf/out_of_process_instance.cc +++ b/pdf/out_of_process_instance.cc
@@ -212,9 +212,6 @@ // Rotation (Page -> Plugin) constexpr char kJSRotateClockwiseType[] = "rotateClockwise"; constexpr char kJSRotateCounterclockwiseType[] = "rotateCounterclockwise"; -// Toggle two-up view (Page -> Plugin) -constexpr char kJSSetTwoUpViewType[] = "setTwoUpView"; -constexpr char kJSEnableTwoUpView[] = "enableTwoUpView"; // Display annotations (Page -> Plugin) constexpr char kJSDisplayAnnotationsType[] = "displayAnnotations"; constexpr char kJSDisplayAnnotations[] = "display"; @@ -731,8 +728,6 @@ RotateCounterclockwise(); } else if (type == kJSSetReadOnlyType) { HandleSetReadOnlyMessage(dict); - } else if (type == kJSSetTwoUpViewType) { - HandleSetTwoUpViewMessage(dict); } else if (type == kJSDisplayAnnotationsType) { HandleDisplayAnnotations(dict); } else if (type == kJSSelectAllType) { @@ -752,7 +747,7 @@ } else if (type == kJSGetThumbnailType) { HandleGetThumbnailMessage(dict); } else { - NOTREACHED(); + PdfViewPluginBase::HandleMessage(ValueFromVar(message)); } } @@ -1927,16 +1922,6 @@ engine()->SetReadOnly(dict.Get(pp::Var(kJSEnableReadOnly)).AsBool()); } -void OutOfProcessInstance::HandleSetTwoUpViewMessage( - const pp::VarDictionary& dict) { - if (!dict.Get(pp::Var(kJSEnableTwoUpView)).is_bool()) { - NOTREACHED(); - return; - } - - engine()->SetTwoUpView(dict.Get(pp::Var(kJSEnableTwoUpView)).AsBool()); -} - void OutOfProcessInstance::HandleUpdateScrollMessage( const pp::VarDictionary& dict) { if (!dict.Get(pp::Var(kJSUpdateScrollX)).is_number() ||
diff --git a/pdf/out_of_process_instance.h b/pdf/out_of_process_instance.h index b4ee0a4..47bc261 100644 --- a/pdf/out_of_process_instance.h +++ b/pdf/out_of_process_instance.h
@@ -203,7 +203,6 @@ void HandleSaveAttachmentMessage(const pp::VarDictionary& dict); void HandleSaveMessage(const pp::VarDictionary& dict); void HandleSetReadOnlyMessage(const pp::VarDictionary& dict); - void HandleSetTwoUpViewMessage(const pp::VarDictionary& dict); void HandleUpdateScrollMessage(const pp::VarDictionary& dict); void HandleViewportMessage(const pp::VarDictionary& dict);
diff --git a/pdf/pdf_view_plugin_base.cc b/pdf/pdf_view_plugin_base.cc index b30b313..9ea8e77 100644 --- a/pdf/pdf_view_plugin_base.cc +++ b/pdf/pdf_view_plugin_base.cc
@@ -13,7 +13,12 @@ #include "base/auto_reset.h" #include "base/bind.h" #include "base/callback.h" +#include "base/check.h" +#include "base/containers/fixed_flat_map.h" #include "base/memory/weak_ptr.h" +#include "base/notreached.h" +#include "base/optional.h" +#include "base/values.h" #include "pdf/pdfium/pdfium_engine.h" #include "pdf/ppapi_migration/url_loader.h" #include "ui/gfx/geometry/rect.h" @@ -41,6 +46,28 @@ return background_color_; } +void PdfViewPluginBase::HandleMessage(const base::Value& message) { + using MessageHandler = void (PdfViewPluginBase::*)(const base::Value&); + static constexpr auto kMessageHandlers = + base::MakeFixedFlatMap<base::StringPiece, MessageHandler>({ + {"setTwoUpView", &PdfViewPluginBase::HandleSetTwoUpViewMessage}, + }); + + const std::string* type = message.FindStringKey("type"); + CHECK(type); + + // TODO(crbug.com/1109796): Use `fixed_flat_map<>::at()` when migration is + // complete to CHECK out-of-bounds lookups. + const auto* it = kMessageHandlers.find(*type); + if (it == kMessageHandlers.end()) { + NOTIMPLEMENTED() << message; + return; + } + + MessageHandler handler = it->second; + (this->*handler)(message); +} + void PdfViewPluginBase::OnPaint(const std::vector<gfx::Rect>& paint_rects, std::vector<PaintReadyRect>* ready, std::vector<gfx::Rect>* pending) { @@ -153,4 +180,8 @@ OnGeometryChanged(old_zoom, device_scale_); } +void PdfViewPluginBase::HandleSetTwoUpViewMessage(const base::Value& message) { + engine()->SetTwoUpView(message.FindBoolKey("enableTwoUpView").value()); +} + } // namespace chrome_pdf
diff --git a/pdf/pdf_view_plugin_base.h b/pdf/pdf_view_plugin_base.h index 3bc517e..bbbec26 100644 --- a/pdf/pdf_view_plugin_base.h +++ b/pdf/pdf_view_plugin_base.h
@@ -18,6 +18,10 @@ #include "third_party/skia/include/core/SkBitmap.h" #include "ui/gfx/geometry/rect.h" +namespace base { +class Value; +} // namespace base + namespace chrome_pdf { class PDFiumEngine; @@ -81,6 +85,9 @@ virtual void DidOpenPreview(std::unique_ptr<UrlLoader> loader, int32_t result) = 0; + // Handles `postMessage()` calls from the embedder. + void HandleMessage(const base::Value& message); + // Paints the given invalid area of the plugin to the given graphics device. // PaintManager::Client::OnPaint() should be its only caller. virtual void DoPaint(const std::vector<gfx::Rect>& paint_rects, @@ -166,6 +173,9 @@ } private: + // Message handlers. + void HandleSetTwoUpViewMessage(const base::Value& message); + std::unique_ptr<PDFiumEngine> engine_; PaintManager paint_manager_{this};
diff --git a/pdf/pdf_view_web_plugin.cc b/pdf/pdf_view_web_plugin.cc index 9a04886..d3af46d6 100644 --- a/pdf/pdf_view_web_plugin.cc +++ b/pdf/pdf_view_web_plugin.cc
@@ -378,7 +378,7 @@ } void PdfViewWebPlugin::OnMessage(const base::Value& message) { - NOTIMPLEMENTED() << message; + PdfViewPluginBase::HandleMessage(message); } base::WeakPtr<PdfViewPluginBase> PdfViewWebPlugin::GetWeakPtr() {
diff --git a/pdf/post_message_receiver.cc b/pdf/post_message_receiver.cc index 88ab8db..1e978f81e 100644 --- a/pdf/post_message_receiver.cc +++ b/pdf/post_message_receiver.cc
@@ -4,6 +4,7 @@ #include "pdf/post_message_receiver.h" +#include <memory> #include <utility> #include "base/bind.h" @@ -12,6 +13,7 @@ #include "base/notreached.h" #include "base/sequenced_task_runner.h" #include "base/values.h" +#include "content/public/renderer/v8_value_converter.h" #include "gin/handle.h" #include "gin/object_template_builder.h" #include "gin/public/wrapper_info.h" @@ -29,7 +31,7 @@ base::WeakPtr<Client> client, scoped_refptr<base::SequencedTaskRunner> client_task_runner) { return gin::CreateHandle( - isolate, new PostMessageReceiver(std::move(client), + isolate, new PostMessageReceiver(isolate, std::move(client), std::move(client_task_runner))) .ToV8() .As<v8::Object>(); @@ -38,9 +40,11 @@ PostMessageReceiver::~PostMessageReceiver() = default; PostMessageReceiver::PostMessageReceiver( + v8::Isolate* isolate, base::WeakPtr<Client> client, scoped_refptr<base::SequencedTaskRunner> client_task_runner) - : client_(std::move(client)), + : isolate_(isolate), + client_(std::move(client)), client_task_runner_(std::move(client_task_runner)) {} gin::ObjectTemplateBuilder PostMessageReceiver::GetObjectTemplateBuilder( @@ -53,14 +57,29 @@ return "ChromePdfPostMessageReceiver"; } +std::unique_ptr<base::Value> PostMessageReceiver::ConvertMessage( + v8::Local<v8::Value> message) { + if (!v8_value_converter_) + v8_value_converter_ = content::V8ValueConverter::Create(); + + return v8_value_converter_->FromV8Value(message, + isolate_->GetCurrentContext()); +} + void PostMessageReceiver::PostMessage(v8::Local<v8::Value> message) { if (!client_) return; - NOTIMPLEMENTED_LOG_ONCE(); + std::unique_ptr<base::Value> converted_message = ConvertMessage(message); + if (!converted_message) { + NOTREACHED() << "The PDF Viewer UI should not be sending messages that " + "cannot be converted."; + return; + } - client_task_runner_->PostTask( - FROM_HERE, base::BindOnce(&Client::OnMessage, client_, base::Value())); + client_task_runner_->PostTask(FROM_HERE, + base::BindOnce(&Client::OnMessage, client_, + std::move(*converted_message))); } } // namespace chrome_pdf
diff --git a/pdf/post_message_receiver.h b/pdf/post_message_receiver.h index 729128aa..ca4daebd 100644 --- a/pdf/post_message_receiver.h +++ b/pdf/post_message_receiver.h
@@ -5,6 +5,8 @@ #ifndef PDF_POST_MESSAGE_RECEIVER_H_ #define PDF_POST_MESSAGE_RECEIVER_H_ +#include <memory> + #include "base/memory/scoped_refptr.h" #include "base/memory/weak_ptr.h" #include "gin/public/wrapper_info.h" @@ -16,6 +18,10 @@ class Value; } // namespace base +namespace content { +class V8ValueConverter; +} // namespace content + namespace gin { class ObjectTemplateBuilder; } // namespace gin @@ -57,6 +63,7 @@ private: PostMessageReceiver( + v8::Isolate* isolate, base::WeakPtr<Client> client, scoped_refptr<base::SequencedTaskRunner> client_task_runner); @@ -65,9 +72,16 @@ v8::Isolate* isolate) override; const char* GetTypeName() override; + // Converts `message` so it can be consumed by `client_`. + std::unique_ptr<base::Value> ConvertMessage(v8::Local<v8::Value> message); + // Implements the `postMessage()` method called by the embedder. void PostMessage(v8::Local<v8::Value> message); + std::unique_ptr<content::V8ValueConverter> v8_value_converter_; + + v8::Isolate* isolate_; + base::WeakPtr<Client> client_; scoped_refptr<base::SequencedTaskRunner> client_task_runner_;
diff --git a/sandbox/policy/fuchsia/sandbox_policy_fuchsia.cc b/sandbox/policy/fuchsia/sandbox_policy_fuchsia.cc index 23c5bca9..1ea75f7 100644 --- a/sandbox/policy/fuchsia/sandbox_policy_fuchsia.cc +++ b/sandbox/policy/fuchsia/sandbox_policy_fuchsia.cc
@@ -165,9 +165,8 @@ const SandboxConfig* config = GetConfigForSandboxType(type_); if (config && !(config->features & kUseServiceDirectoryOverride)) { service_directory_task_runner_ = base::ThreadTaskRunnerHandle::Get(); - service_directory_ = - std::make_unique<base::fuchsia::FilteredServiceDirectory>( - base::ComponentContextForProcess()->svc().get()); + service_directory_ = std::make_unique<base::FilteredServiceDirectory>( + base::ComponentContextForProcess()->svc().get()); for (const char* service_name : kDefaultServices) { service_directory_->AddService(service_name); }
diff --git a/sandbox/policy/fuchsia/sandbox_policy_fuchsia.h b/sandbox/policy/fuchsia/sandbox_policy_fuchsia.h index c544dc9..ba37001 100644 --- a/sandbox/policy/fuchsia/sandbox_policy_fuchsia.h +++ b/sandbox/policy/fuchsia/sandbox_policy_fuchsia.h
@@ -14,13 +14,9 @@ #include "sandbox/policy/sandbox_type.h" namespace base { +class FilteredServiceDirectory; struct LaunchOptions; class SequencedTaskRunner; - -namespace fuchsia { -class FilteredServiceDirectory; -} // namespace fuchsia - } // namespace base namespace sandbox { @@ -48,7 +44,7 @@ SandboxType type_; // Services directory used for the /svc namespace of the child process. - std::unique_ptr<base::fuchsia::FilteredServiceDirectory> service_directory_; + std::unique_ptr<base::FilteredServiceDirectory> service_directory_; fidl::InterfaceHandle<::fuchsia::io::Directory> service_directory_client_; scoped_refptr<base::SequencedTaskRunner> service_directory_task_runner_;
diff --git a/testing/buildbot/chromium.android.fyi.json b/testing/buildbot/chromium.android.fyi.json index f1ecfa1..910c618de 100644 --- a/testing/buildbot/chromium.android.fyi.json +++ b/testing/buildbot/chromium.android.fyi.json
@@ -163,12 +163,12 @@ "--test-runner-outdir", ".", "--client-outdir", - "../../weblayer_instrumentation_test_M87/out/Release", + "../../weblayer_instrumentation_test_M88/out/Release", "--implementation-outdir", ".", "--test-expectations", "../../weblayer/browser/android/javatests/skew/expectations.txt", - "--client-version=87", + "--client-version=88", "--gs-results-bucket=chromium-result-details", "--recover-devices", "--avd-config=../../tools/android/avd/proto/generic_android29.textpb" @@ -178,11 +178,11 @@ "--bucket", "chromium-result-details", "--test-name", - "weblayer_instrumentation_test_versions_apk_Client Tests For 87.0.4280.152" + "weblayer_instrumentation_test_versions_apk_Client Library Tests For 88.0.4324.141" ], "script": "//build/android/pylib/results/presentation/test_results_presentation.py" }, - "name": "weblayer_instrumentation_test_versions_apk_Client Tests For 87.0.4280.152", + "name": "weblayer_instrumentation_test_versions_apk_Client Library Tests For 88.0.4324.141", "resultdb": { "enable": true }, @@ -191,8 +191,8 @@ "cipd_packages": [ { "cipd_package": "chromium/testing/weblayer-x86", - "location": "weblayer_instrumentation_test_M87", - "revision": "version:87.0.4280.152" + "location": "weblayer_instrumentation_test_M88", + "revision": "version:88.0.4324.141" }, { "cipd_package": "infra/tools/luci/logdog/butler/${platform}", @@ -242,12 +242,12 @@ "--test-runner-outdir", ".", "--client-outdir", - "../../weblayer_instrumentation_test_M88/out/Release", + "../../weblayer_instrumentation_test_M87/out/Release", "--implementation-outdir", ".", "--test-expectations", "../../weblayer/browser/android/javatests/skew/expectations.txt", - "--client-version=88", + "--client-version=87", "--gs-results-bucket=chromium-result-details", "--recover-devices", "--avd-config=../../tools/android/avd/proto/generic_android29.textpb" @@ -257,11 +257,11 @@ "--bucket", "chromium-result-details", "--test-name", - "weblayer_instrumentation_test_versions_apk_Client Tests For 88.0.4324.118" + "weblayer_instrumentation_test_versions_apk_Client Tests For 87.0.4280.152" ], "script": "//build/android/pylib/results/presentation/test_results_presentation.py" }, - "name": "weblayer_instrumentation_test_versions_apk_Client Tests For 88.0.4324.118", + "name": "weblayer_instrumentation_test_versions_apk_Client Tests For 87.0.4280.152", "resultdb": { "enable": true }, @@ -270,8 +270,8 @@ "cipd_packages": [ { "cipd_package": "chromium/testing/weblayer-x86", - "location": "weblayer_instrumentation_test_M88", - "revision": "version:88.0.4324.118" + "location": "weblayer_instrumentation_test_M87", + "revision": "version:87.0.4280.152" }, { "cipd_package": "infra/tools/luci/logdog/butler/${platform}", @@ -402,10 +402,10 @@ "--client-outdir", ".", "--implementation-outdir", - "../../weblayer_instrumentation_test_M87/out/Release", + "../../weblayer_instrumentation_test_M88/out/Release", "--test-expectations", "../../weblayer/browser/android/javatests/skew/expectations.txt", - "--impl-version=87", + "--impl-version=88", "--gs-results-bucket=chromium-result-details", "--recover-devices", "--avd-config=../../tools/android/avd/proto/generic_android29.textpb" @@ -415,11 +415,11 @@ "--bucket", "chromium-result-details", "--test-name", - "weblayer_instrumentation_test_versions_apk_Implementation Tests For 87.0.4280.152" + "weblayer_instrumentation_test_versions_apk_Implementation Library Tests For 88.0.4324.141" ], "script": "//build/android/pylib/results/presentation/test_results_presentation.py" }, - "name": "weblayer_instrumentation_test_versions_apk_Implementation Tests For 87.0.4280.152", + "name": "weblayer_instrumentation_test_versions_apk_Implementation Library Tests For 88.0.4324.141", "resultdb": { "enable": true }, @@ -428,8 +428,8 @@ "cipd_packages": [ { "cipd_package": "chromium/testing/weblayer-x86", - "location": "weblayer_instrumentation_test_M87", - "revision": "version:87.0.4280.152" + "location": "weblayer_instrumentation_test_M88", + "revision": "version:88.0.4324.141" }, { "cipd_package": "infra/tools/luci/logdog/butler/${platform}", @@ -481,10 +481,10 @@ "--client-outdir", ".", "--implementation-outdir", - "../../weblayer_instrumentation_test_M88/out/Release", + "../../weblayer_instrumentation_test_M87/out/Release", "--test-expectations", "../../weblayer/browser/android/javatests/skew/expectations.txt", - "--impl-version=88", + "--impl-version=87", "--gs-results-bucket=chromium-result-details", "--recover-devices", "--avd-config=../../tools/android/avd/proto/generic_android29.textpb" @@ -494,11 +494,11 @@ "--bucket", "chromium-result-details", "--test-name", - "weblayer_instrumentation_test_versions_apk_Implementation Tests For 88.0.4324.118" + "weblayer_instrumentation_test_versions_apk_Implementation Tests For 87.0.4280.152" ], "script": "//build/android/pylib/results/presentation/test_results_presentation.py" }, - "name": "weblayer_instrumentation_test_versions_apk_Implementation Tests For 88.0.4324.118", + "name": "weblayer_instrumentation_test_versions_apk_Implementation Tests For 87.0.4280.152", "resultdb": { "enable": true }, @@ -507,8 +507,8 @@ "cipd_packages": [ { "cipd_package": "chromium/testing/weblayer-x86", - "location": "weblayer_instrumentation_test_M88", - "revision": "version:88.0.4324.118" + "location": "weblayer_instrumentation_test_M87", + "revision": "version:87.0.4280.152" }, { "cipd_package": "infra/tools/luci/logdog/butler/${platform}", @@ -641,12 +641,12 @@ "--test-runner-outdir", ".", "--client-outdir", - "../../weblayer_instrumentation_test_M87/out/Release", + "../../weblayer_instrumentation_test_M88/out/Release", "--implementation-outdir", ".", "--test-expectations", "../../weblayer/browser/android/javatests/skew/expectations.txt", - "--client-version=87", + "--client-version=88", "--gs-results-bucket=chromium-result-details", "--recover-devices", "--avd-config=../../tools/android/avd/proto/generic_android23.textpb" @@ -656,11 +656,11 @@ "--bucket", "chromium-result-details", "--test-name", - "weblayer_instrumentation_test_versions_apk_Client Tests For 87.0.4280.152" + "weblayer_instrumentation_test_versions_apk_Client Library Tests For 88.0.4324.141" ], "script": "//build/android/pylib/results/presentation/test_results_presentation.py" }, - "name": "weblayer_instrumentation_test_versions_apk_Client Tests For 87.0.4280.152", + "name": "weblayer_instrumentation_test_versions_apk_Client Library Tests For 88.0.4324.141", "resultdb": { "enable": true }, @@ -669,8 +669,8 @@ "cipd_packages": [ { "cipd_package": "chromium/testing/weblayer-x86", - "location": "weblayer_instrumentation_test_M87", - "revision": "version:87.0.4280.152" + "location": "weblayer_instrumentation_test_M88", + "revision": "version:88.0.4324.141" }, { "cipd_package": "infra/tools/luci/logdog/butler/${platform}", @@ -720,12 +720,12 @@ "--test-runner-outdir", ".", "--client-outdir", - "../../weblayer_instrumentation_test_M88/out/Release", + "../../weblayer_instrumentation_test_M87/out/Release", "--implementation-outdir", ".", "--test-expectations", "../../weblayer/browser/android/javatests/skew/expectations.txt", - "--client-version=88", + "--client-version=87", "--gs-results-bucket=chromium-result-details", "--recover-devices", "--avd-config=../../tools/android/avd/proto/generic_android23.textpb" @@ -735,11 +735,11 @@ "--bucket", "chromium-result-details", "--test-name", - "weblayer_instrumentation_test_versions_apk_Client Tests For 88.0.4324.118" + "weblayer_instrumentation_test_versions_apk_Client Tests For 87.0.4280.152" ], "script": "//build/android/pylib/results/presentation/test_results_presentation.py" }, - "name": "weblayer_instrumentation_test_versions_apk_Client Tests For 88.0.4324.118", + "name": "weblayer_instrumentation_test_versions_apk_Client Tests For 87.0.4280.152", "resultdb": { "enable": true }, @@ -748,8 +748,8 @@ "cipd_packages": [ { "cipd_package": "chromium/testing/weblayer-x86", - "location": "weblayer_instrumentation_test_M88", - "revision": "version:88.0.4324.118" + "location": "weblayer_instrumentation_test_M87", + "revision": "version:87.0.4280.152" }, { "cipd_package": "infra/tools/luci/logdog/butler/${platform}", @@ -880,10 +880,10 @@ "--client-outdir", ".", "--implementation-outdir", - "../../weblayer_instrumentation_test_M87/out/Release", + "../../weblayer_instrumentation_test_M88/out/Release", "--test-expectations", "../../weblayer/browser/android/javatests/skew/expectations.txt", - "--impl-version=87", + "--impl-version=88", "--gs-results-bucket=chromium-result-details", "--recover-devices", "--avd-config=../../tools/android/avd/proto/generic_android23.textpb" @@ -893,11 +893,11 @@ "--bucket", "chromium-result-details", "--test-name", - "weblayer_instrumentation_test_versions_apk_Implementation Tests For 87.0.4280.152" + "weblayer_instrumentation_test_versions_apk_Implementation Library Tests For 88.0.4324.141" ], "script": "//build/android/pylib/results/presentation/test_results_presentation.py" }, - "name": "weblayer_instrumentation_test_versions_apk_Implementation Tests For 87.0.4280.152", + "name": "weblayer_instrumentation_test_versions_apk_Implementation Library Tests For 88.0.4324.141", "resultdb": { "enable": true }, @@ -906,8 +906,8 @@ "cipd_packages": [ { "cipd_package": "chromium/testing/weblayer-x86", - "location": "weblayer_instrumentation_test_M87", - "revision": "version:87.0.4280.152" + "location": "weblayer_instrumentation_test_M88", + "revision": "version:88.0.4324.141" }, { "cipd_package": "infra/tools/luci/logdog/butler/${platform}", @@ -959,10 +959,10 @@ "--client-outdir", ".", "--implementation-outdir", - "../../weblayer_instrumentation_test_M88/out/Release", + "../../weblayer_instrumentation_test_M87/out/Release", "--test-expectations", "../../weblayer/browser/android/javatests/skew/expectations.txt", - "--impl-version=88", + "--impl-version=87", "--gs-results-bucket=chromium-result-details", "--recover-devices", "--avd-config=../../tools/android/avd/proto/generic_android23.textpb" @@ -972,11 +972,11 @@ "--bucket", "chromium-result-details", "--test-name", - "weblayer_instrumentation_test_versions_apk_Implementation Tests For 88.0.4324.118" + "weblayer_instrumentation_test_versions_apk_Implementation Tests For 87.0.4280.152" ], "script": "//build/android/pylib/results/presentation/test_results_presentation.py" }, - "name": "weblayer_instrumentation_test_versions_apk_Implementation Tests For 88.0.4324.118", + "name": "weblayer_instrumentation_test_versions_apk_Implementation Tests For 87.0.4280.152", "resultdb": { "enable": true }, @@ -985,8 +985,8 @@ "cipd_packages": [ { "cipd_package": "chromium/testing/weblayer-x86", - "location": "weblayer_instrumentation_test_M88", - "revision": "version:88.0.4324.118" + "location": "weblayer_instrumentation_test_M87", + "revision": "version:87.0.4280.152" }, { "cipd_package": "infra/tools/luci/logdog/butler/${platform}", @@ -1182,12 +1182,12 @@ "--test-runner-outdir", ".", "--client-outdir", - "../../weblayer_instrumentation_test_M87/out/Release", + "../../weblayer_instrumentation_test_M88/out/Release", "--implementation-outdir", ".", "--test-expectations", "../../weblayer/browser/android/javatests/skew/expectations.txt", - "--client-version=87", + "--client-version=88", "--gs-results-bucket=chromium-result-details", "--recover-devices", "--avd-config=../../tools/android/avd/proto/generic_android27.textpb" @@ -1197,11 +1197,11 @@ "--bucket", "chromium-result-details", "--test-name", - "weblayer_instrumentation_test_versions_apk_Client Tests For 87.0.4280.152" + "weblayer_instrumentation_test_versions_apk_Client Library Tests For 88.0.4324.141" ], "script": "//build/android/pylib/results/presentation/test_results_presentation.py" }, - "name": "weblayer_instrumentation_test_versions_apk_Client Tests For 87.0.4280.152", + "name": "weblayer_instrumentation_test_versions_apk_Client Library Tests For 88.0.4324.141", "resultdb": { "enable": true }, @@ -1210,8 +1210,8 @@ "cipd_packages": [ { "cipd_package": "chromium/testing/weblayer-x86", - "location": "weblayer_instrumentation_test_M87", - "revision": "version:87.0.4280.152" + "location": "weblayer_instrumentation_test_M88", + "revision": "version:88.0.4324.141" }, { "cipd_package": "infra/tools/luci/logdog/butler/${platform}", @@ -1261,12 +1261,12 @@ "--test-runner-outdir", ".", "--client-outdir", - "../../weblayer_instrumentation_test_M88/out/Release", + "../../weblayer_instrumentation_test_M87/out/Release", "--implementation-outdir", ".", "--test-expectations", "../../weblayer/browser/android/javatests/skew/expectations.txt", - "--client-version=88", + "--client-version=87", "--gs-results-bucket=chromium-result-details", "--recover-devices", "--avd-config=../../tools/android/avd/proto/generic_android27.textpb" @@ -1276,11 +1276,11 @@ "--bucket", "chromium-result-details", "--test-name", - "weblayer_instrumentation_test_versions_apk_Client Tests For 88.0.4324.118" + "weblayer_instrumentation_test_versions_apk_Client Tests For 87.0.4280.152" ], "script": "//build/android/pylib/results/presentation/test_results_presentation.py" }, - "name": "weblayer_instrumentation_test_versions_apk_Client Tests For 88.0.4324.118", + "name": "weblayer_instrumentation_test_versions_apk_Client Tests For 87.0.4280.152", "resultdb": { "enable": true }, @@ -1289,8 +1289,8 @@ "cipd_packages": [ { "cipd_package": "chromium/testing/weblayer-x86", - "location": "weblayer_instrumentation_test_M88", - "revision": "version:88.0.4324.118" + "location": "weblayer_instrumentation_test_M87", + "revision": "version:87.0.4280.152" }, { "cipd_package": "infra/tools/luci/logdog/butler/${platform}", @@ -1421,10 +1421,10 @@ "--client-outdir", ".", "--implementation-outdir", - "../../weblayer_instrumentation_test_M87/out/Release", + "../../weblayer_instrumentation_test_M88/out/Release", "--test-expectations", "../../weblayer/browser/android/javatests/skew/expectations.txt", - "--impl-version=87", + "--impl-version=88", "--gs-results-bucket=chromium-result-details", "--recover-devices", "--avd-config=../../tools/android/avd/proto/generic_android27.textpb" @@ -1434,11 +1434,11 @@ "--bucket", "chromium-result-details", "--test-name", - "weblayer_instrumentation_test_versions_apk_Implementation Tests For 87.0.4280.152" + "weblayer_instrumentation_test_versions_apk_Implementation Library Tests For 88.0.4324.141" ], "script": "//build/android/pylib/results/presentation/test_results_presentation.py" }, - "name": "weblayer_instrumentation_test_versions_apk_Implementation Tests For 87.0.4280.152", + "name": "weblayer_instrumentation_test_versions_apk_Implementation Library Tests For 88.0.4324.141", "resultdb": { "enable": true }, @@ -1447,8 +1447,8 @@ "cipd_packages": [ { "cipd_package": "chromium/testing/weblayer-x86", - "location": "weblayer_instrumentation_test_M87", - "revision": "version:87.0.4280.152" + "location": "weblayer_instrumentation_test_M88", + "revision": "version:88.0.4324.141" }, { "cipd_package": "infra/tools/luci/logdog/butler/${platform}", @@ -1500,10 +1500,10 @@ "--client-outdir", ".", "--implementation-outdir", - "../../weblayer_instrumentation_test_M88/out/Release", + "../../weblayer_instrumentation_test_M87/out/Release", "--test-expectations", "../../weblayer/browser/android/javatests/skew/expectations.txt", - "--impl-version=88", + "--impl-version=87", "--gs-results-bucket=chromium-result-details", "--recover-devices", "--avd-config=../../tools/android/avd/proto/generic_android27.textpb" @@ -1513,11 +1513,11 @@ "--bucket", "chromium-result-details", "--test-name", - "weblayer_instrumentation_test_versions_apk_Implementation Tests For 88.0.4324.118" + "weblayer_instrumentation_test_versions_apk_Implementation Tests For 87.0.4280.152" ], "script": "//build/android/pylib/results/presentation/test_results_presentation.py" }, - "name": "weblayer_instrumentation_test_versions_apk_Implementation Tests For 88.0.4324.118", + "name": "weblayer_instrumentation_test_versions_apk_Implementation Tests For 87.0.4280.152", "resultdb": { "enable": true }, @@ -1526,8 +1526,8 @@ "cipd_packages": [ { "cipd_package": "chromium/testing/weblayer-x86", - "location": "weblayer_instrumentation_test_M88", - "revision": "version:88.0.4324.118" + "location": "weblayer_instrumentation_test_M87", + "revision": "version:87.0.4280.152" }, { "cipd_package": "infra/tools/luci/logdog/butler/${platform}", @@ -1723,12 +1723,12 @@ "--test-runner-outdir", ".", "--client-outdir", - "../../weblayer_instrumentation_test_M87/out/Release", + "../../weblayer_instrumentation_test_M88/out/Release", "--implementation-outdir", ".", "--test-expectations", "../../weblayer/browser/android/javatests/skew/expectations.txt", - "--client-version=87", + "--client-version=88", "--gs-results-bucket=chromium-result-details", "--recover-devices", "--avd-config=../../tools/android/avd/proto/generic_android28.textpb" @@ -1738,11 +1738,11 @@ "--bucket", "chromium-result-details", "--test-name", - "weblayer_instrumentation_test_versions_apk_Client Tests For 87.0.4280.152" + "weblayer_instrumentation_test_versions_apk_Client Library Tests For 88.0.4324.141" ], "script": "//build/android/pylib/results/presentation/test_results_presentation.py" }, - "name": "weblayer_instrumentation_test_versions_apk_Client Tests For 87.0.4280.152", + "name": "weblayer_instrumentation_test_versions_apk_Client Library Tests For 88.0.4324.141", "resultdb": { "enable": true }, @@ -1751,8 +1751,8 @@ "cipd_packages": [ { "cipd_package": "chromium/testing/weblayer-x86", - "location": "weblayer_instrumentation_test_M87", - "revision": "version:87.0.4280.152" + "location": "weblayer_instrumentation_test_M88", + "revision": "version:88.0.4324.141" }, { "cipd_package": "infra/tools/luci/logdog/butler/${platform}", @@ -1802,12 +1802,12 @@ "--test-runner-outdir", ".", "--client-outdir", - "../../weblayer_instrumentation_test_M88/out/Release", + "../../weblayer_instrumentation_test_M87/out/Release", "--implementation-outdir", ".", "--test-expectations", "../../weblayer/browser/android/javatests/skew/expectations.txt", - "--client-version=88", + "--client-version=87", "--gs-results-bucket=chromium-result-details", "--recover-devices", "--avd-config=../../tools/android/avd/proto/generic_android28.textpb" @@ -1817,11 +1817,11 @@ "--bucket", "chromium-result-details", "--test-name", - "weblayer_instrumentation_test_versions_apk_Client Tests For 88.0.4324.118" + "weblayer_instrumentation_test_versions_apk_Client Tests For 87.0.4280.152" ], "script": "//build/android/pylib/results/presentation/test_results_presentation.py" }, - "name": "weblayer_instrumentation_test_versions_apk_Client Tests For 88.0.4324.118", + "name": "weblayer_instrumentation_test_versions_apk_Client Tests For 87.0.4280.152", "resultdb": { "enable": true }, @@ -1830,8 +1830,8 @@ "cipd_packages": [ { "cipd_package": "chromium/testing/weblayer-x86", - "location": "weblayer_instrumentation_test_M88", - "revision": "version:88.0.4324.118" + "location": "weblayer_instrumentation_test_M87", + "revision": "version:87.0.4280.152" }, { "cipd_package": "infra/tools/luci/logdog/butler/${platform}", @@ -1962,10 +1962,10 @@ "--client-outdir", ".", "--implementation-outdir", - "../../weblayer_instrumentation_test_M87/out/Release", + "../../weblayer_instrumentation_test_M88/out/Release", "--test-expectations", "../../weblayer/browser/android/javatests/skew/expectations.txt", - "--impl-version=87", + "--impl-version=88", "--gs-results-bucket=chromium-result-details", "--recover-devices", "--avd-config=../../tools/android/avd/proto/generic_android28.textpb" @@ -1975,11 +1975,11 @@ "--bucket", "chromium-result-details", "--test-name", - "weblayer_instrumentation_test_versions_apk_Implementation Tests For 87.0.4280.152" + "weblayer_instrumentation_test_versions_apk_Implementation Library Tests For 88.0.4324.141" ], "script": "//build/android/pylib/results/presentation/test_results_presentation.py" }, - "name": "weblayer_instrumentation_test_versions_apk_Implementation Tests For 87.0.4280.152", + "name": "weblayer_instrumentation_test_versions_apk_Implementation Library Tests For 88.0.4324.141", "resultdb": { "enable": true }, @@ -1988,8 +1988,8 @@ "cipd_packages": [ { "cipd_package": "chromium/testing/weblayer-x86", - "location": "weblayer_instrumentation_test_M87", - "revision": "version:87.0.4280.152" + "location": "weblayer_instrumentation_test_M88", + "revision": "version:88.0.4324.141" }, { "cipd_package": "infra/tools/luci/logdog/butler/${platform}", @@ -2041,10 +2041,10 @@ "--client-outdir", ".", "--implementation-outdir", - "../../weblayer_instrumentation_test_M88/out/Release", + "../../weblayer_instrumentation_test_M87/out/Release", "--test-expectations", "../../weblayer/browser/android/javatests/skew/expectations.txt", - "--impl-version=88", + "--impl-version=87", "--gs-results-bucket=chromium-result-details", "--recover-devices", "--avd-config=../../tools/android/avd/proto/generic_android28.textpb" @@ -2054,11 +2054,11 @@ "--bucket", "chromium-result-details", "--test-name", - "weblayer_instrumentation_test_versions_apk_Implementation Tests For 88.0.4324.118" + "weblayer_instrumentation_test_versions_apk_Implementation Tests For 87.0.4280.152" ], "script": "//build/android/pylib/results/presentation/test_results_presentation.py" }, - "name": "weblayer_instrumentation_test_versions_apk_Implementation Tests For 88.0.4324.118", + "name": "weblayer_instrumentation_test_versions_apk_Implementation Tests For 87.0.4280.152", "resultdb": { "enable": true }, @@ -2067,8 +2067,8 @@ "cipd_packages": [ { "cipd_package": "chromium/testing/weblayer-x86", - "location": "weblayer_instrumentation_test_M88", - "revision": "version:88.0.4324.118" + "location": "weblayer_instrumentation_test_M87", + "revision": "version:87.0.4280.152" }, { "cipd_package": "infra/tools/luci/logdog/butler/${platform}",
diff --git a/testing/buildbot/chromium.android.json b/testing/buildbot/chromium.android.json index bac99255..8e97140a8 100644 --- a/testing/buildbot/chromium.android.json +++ b/testing/buildbot/chromium.android.json
@@ -28295,106 +28295,6 @@ { "args": [ "--gs-results-bucket=chromium-result-details", - "--recover-devices" - ], - "isolate_profile_data": true, - "merge": { - "args": [ - "--bucket", - "chromium-result-details", - "--test-name", - "chrome_modern_public_bundle_fake_modules_smoke_test" - ], - "script": "//build/android/pylib/results/presentation/test_results_presentation.py" - }, - "resultdb": { - "enable": true - }, - "swarming": { - "can_use_on_swarming_builders": true, - "cipd_packages": [ - { - "cipd_package": "infra/tools/luci/logdog/butler/${platform}", - "location": "bin", - "revision": "git_revision:ff387eadf445b24c935f1cf7d6ddd279f8a6b04c" - } - ], - "dimension_sets": [ - { - "device_os": "MMB29Q", - "device_os_type": "userdebug", - "device_type": "bullhead", - "os": "Android" - } - ], - "output_links": [ - { - "link": [ - "https://luci-logdog.appspot.com/v/?s", - "=android%2Fswarming%2Flogcats%2F", - "${TASK_ID}%2F%2B%2Funified_logcats" - ], - "name": "shard #${SHARD_INDEX} logcats" - } - ], - "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" - }, - "test": "chrome_modern_public_bundle_fake_modules_smoke_test", - "test_id_prefix": "ninja://chrome/android:chrome_modern_public_bundle_fake_modules_smoke_test/" - }, - { - "args": [ - "--gs-results-bucket=chromium-result-details", - "--recover-devices" - ], - "isolate_profile_data": true, - "merge": { - "args": [ - "--bucket", - "chromium-result-details", - "--test-name", - "chrome_modern_public_bundle_smoke_test" - ], - "script": "//build/android/pylib/results/presentation/test_results_presentation.py" - }, - "resultdb": { - "enable": true - }, - "swarming": { - "can_use_on_swarming_builders": true, - "cipd_packages": [ - { - "cipd_package": "infra/tools/luci/logdog/butler/${platform}", - "location": "bin", - "revision": "git_revision:ff387eadf445b24c935f1cf7d6ddd279f8a6b04c" - } - ], - "dimension_sets": [ - { - "device_os": "MMB29Q", - "device_os_type": "userdebug", - "device_type": "bullhead", - "os": "Android" - } - ], - "output_links": [ - { - "link": [ - "https://luci-logdog.appspot.com/v/?s", - "=android%2Fswarming%2Flogcats%2F", - "${TASK_ID}%2F%2B%2Funified_logcats" - ], - "name": "shard #${SHARD_INDEX} logcats" - } - ], - "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" - }, - "test": "chrome_modern_public_bundle_smoke_test", - "test_id_prefix": "ninja://chrome/android:chrome_modern_public_bundle_smoke_test/" - }, - { - "args": [ - "--gs-results-bucket=chromium-result-details", "--recover-devices", "--git-revision=${got_revision}" ], @@ -31227,6 +31127,139 @@ "--bucket", "chromium-result-details", "--test-name", + "webkit_unit_tests" + ], + "script": "//build/android/pylib/results/presentation/test_results_presentation.py" + }, + "name": "webkit_unit_tests", + "resultdb": { + "enable": true + }, + "swarming": { + "can_use_on_swarming_builders": true, + "cipd_packages": [ + { + "cipd_package": "infra/tools/luci/logdog/butler/${platform}", + "location": "bin", + "revision": "git_revision:ff387eadf445b24c935f1cf7d6ddd279f8a6b04c" + } + ], + "dimension_sets": [ + { + "cpu": "x86-64", + "device_os": null, + "device_type": null, + "machine_type": "n1-standard-4", + "os": "Ubuntu-16.04", + "pool": "chromium.tests.avd" + } + ], + "named_caches": [ + { + "name": "avd_generic_android23", + "path": ".android" + }, + { + "name": "system_images_android_23_google_apis_x86", + "path": ".emulator_sdk" + } + ], + "output_links": [ + { + "link": [ + "https://luci-logdog.appspot.com/v/?s", + "=android%2Fswarming%2Flogcats%2F", + "${TASK_ID}%2F%2B%2Funified_logcats" + ], + "name": "shard #${SHARD_INDEX} logcats" + } + ], + "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com", + "shards": 4 + }, + "test": "blink_unittests", + "test_id_prefix": "ninja://third_party/blink/renderer/controller:blink_unittests/" + }, + { + "args": [ + "--gs-results-bucket=chromium-result-details", + "--recover-devices", + "--avd-config=../../tools/android/avd/proto/generic_android23.textpb", + "--git-revision=${got_revision}" + ], + "experiment_percentage": 100, + "merge": { + "args": [ + "--bucket", + "chromium-result-details", + "--test-name", + "chrome_java_test_wpr_tests" + ], + "script": "//build/android/pylib/results/presentation/test_results_presentation.py" + }, + "precommit_args": [ + "--gerrit-issue=${patch_issue}", + "--gerrit-patchset=${patch_set}", + "--buildbucket-id=${buildbucket_build_id}" + ], + "resultdb": { + "enable": true + }, + "swarming": { + "can_use_on_swarming_builders": true, + "cipd_packages": [ + { + "cipd_package": "infra/tools/luci/logdog/butler/${platform}", + "location": "bin", + "revision": "git_revision:ff387eadf445b24c935f1cf7d6ddd279f8a6b04c" + } + ], + "dimension_sets": [ + { + "cpu": "x86-64", + "device_os": null, + "device_type": null, + "machine_type": "n1-standard-4", + "os": "Ubuntu-16.04", + "pool": "chromium.tests.avd" + } + ], + "named_caches": [ + { + "name": "avd_generic_android23", + "path": ".android" + }, + { + "name": "system_images_android_23_google_apis_x86", + "path": ".emulator_sdk" + } + ], + "output_links": [ + { + "link": [ + "https://luci-logdog.appspot.com/v/?s", + "=android%2Fswarming%2Flogcats%2F", + "${TASK_ID}%2F%2B%2Funified_logcats" + ], + "name": "shard #${SHARD_INDEX} logcats" + } + ], + "service_account": "chrome-gpu-gold@chops-service-accounts.iam.gserviceaccount.com" + }, + "test": "chrome_java_test_wpr_tests", + "test_id_prefix": "ninja://chrome/test/android:chrome_java_test_wpr_tests/" + }, + { + "args": [ + "--gs-results-bucket=chromium-result-details", + "--recover-devices", + "--avd-config=../../tools/android/avd/proto/generic_android23.textpb" + ], + "merge": { + "args": [ + "--bucket", + "chromium-result-details", + "--test-name", "chrome_modern_public_bundle_fake_modules_smoke_test" ], "script": "//build/android/pylib/results/presentation/test_results_presentation.py" @@ -31284,7 +31317,6 @@ "--recover-devices", "--avd-config=../../tools/android/avd/proto/generic_android23.textpb" ], - "experiment_percentage": 100, "merge": { "args": [ "--bucket", @@ -32580,130 +32612,6 @@ "args": [ "--gs-results-bucket=chromium-result-details", "--recover-devices", - "--avd-config=../../tools/android/avd/proto/generic_android23.textpb" - ], - "merge": { - "args": [ - "--bucket", - "chromium-result-details", - "--test-name", - "chrome_modern_public_bundle_fake_modules_smoke_test" - ], - "script": "//build/android/pylib/results/presentation/test_results_presentation.py" - }, - "resultdb": { - "enable": true - }, - "swarming": { - "can_use_on_swarming_builders": true, - "cipd_packages": [ - { - "cipd_package": "infra/tools/luci/logdog/butler/${platform}", - "location": "bin", - "revision": "git_revision:ff387eadf445b24c935f1cf7d6ddd279f8a6b04c" - } - ], - "dimension_sets": [ - { - "cpu": "x86-64", - "device_os": null, - "device_type": null, - "machine_type": "n1-standard-4", - "os": "Ubuntu-16.04", - "pool": "chromium.tests.avd" - } - ], - "named_caches": [ - { - "name": "avd_generic_android23", - "path": ".android" - }, - { - "name": "system_images_android_23_google_apis_x86", - "path": ".emulator_sdk" - } - ], - "output_links": [ - { - "link": [ - "https://luci-logdog.appspot.com/v/?s", - "=android%2Fswarming%2Flogcats%2F", - "${TASK_ID}%2F%2B%2Funified_logcats" - ], - "name": "shard #${SHARD_INDEX} logcats" - } - ], - "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" - }, - "test": "chrome_modern_public_bundle_fake_modules_smoke_test", - "test_id_prefix": "ninja://chrome/android:chrome_modern_public_bundle_fake_modules_smoke_test/" - }, - { - "args": [ - "--gs-results-bucket=chromium-result-details", - "--recover-devices", - "--avd-config=../../tools/android/avd/proto/generic_android23.textpb" - ], - "merge": { - "args": [ - "--bucket", - "chromium-result-details", - "--test-name", - "chrome_modern_public_bundle_smoke_test" - ], - "script": "//build/android/pylib/results/presentation/test_results_presentation.py" - }, - "resultdb": { - "enable": true - }, - "swarming": { - "can_use_on_swarming_builders": true, - "cipd_packages": [ - { - "cipd_package": "infra/tools/luci/logdog/butler/${platform}", - "location": "bin", - "revision": "git_revision:ff387eadf445b24c935f1cf7d6ddd279f8a6b04c" - } - ], - "dimension_sets": [ - { - "cpu": "x86-64", - "device_os": null, - "device_type": null, - "machine_type": "n1-standard-4", - "os": "Ubuntu-16.04", - "pool": "chromium.tests.avd" - } - ], - "named_caches": [ - { - "name": "avd_generic_android23", - "path": ".android" - }, - { - "name": "system_images_android_23_google_apis_x86", - "path": ".emulator_sdk" - } - ], - "output_links": [ - { - "link": [ - "https://luci-logdog.appspot.com/v/?s", - "=android%2Fswarming%2Flogcats%2F", - "${TASK_ID}%2F%2B%2Funified_logcats" - ], - "name": "shard #${SHARD_INDEX} logcats" - } - ], - "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" - }, - "test": "chrome_modern_public_bundle_smoke_test", - "test_id_prefix": "ninja://chrome/android:chrome_modern_public_bundle_smoke_test/" - }, - { - "args": [ - "--gs-results-bucket=chromium-result-details", - "--recover-devices", "--avd-config=../../tools/android/avd/proto/generic_android23.textpb", "--git-revision=${got_revision}", "--test-launcher-filter-file=../../testing/buildbot/filters/android.emulator_m.chrome_public_test_apk.filter"
diff --git a/testing/buildbot/chromium.dawn.json b/testing/buildbot/chromium.dawn.json index 2b3541f..5c378ea7 100644 --- a/testing/buildbot/chromium.dawn.json +++ b/testing/buildbot/chromium.dawn.json
@@ -194,6 +194,7 @@ "--driver-logging", "--jobs=1", "--order=natural", + "--additional-driver-flag=--disable-dawn-features=disallow_unsafe_apis", "--additional-driver-flag=--use-gpu-in-tests", "--no-xvfb", "--additional-driver-flag=--enable-features=UseSkiaRenderer,Vulkan" @@ -228,6 +229,7 @@ "--jobs=1", "--order=natural", "--additional-driver-flag=--enable-dawn-backend-validation", + "--additional-driver-flag=--disable-dawn-features=disallow_unsafe_apis", "--additional-driver-flag=--use-gpu-in-tests", "--no-xvfb", "--additional-driver-flag=--enable-features=UseSkiaRenderer,Vulkan" @@ -449,6 +451,7 @@ "--driver-logging", "--jobs=1", "--order=natural", + "--additional-driver-flag=--disable-dawn-features=disallow_unsafe_apis", "--additional-driver-flag=--use-gpu-in-tests", "--no-xvfb", "--additional-driver-flag=--enable-features=UseSkiaRenderer,Vulkan" @@ -483,6 +486,7 @@ "--jobs=1", "--order=natural", "--additional-driver-flag=--enable-dawn-backend-validation", + "--additional-driver-flag=--disable-dawn-features=disallow_unsafe_apis", "--additional-driver-flag=--use-gpu-in-tests", "--no-xvfb", "--additional-driver-flag=--enable-features=UseSkiaRenderer,Vulkan" @@ -704,6 +708,7 @@ "--driver-logging", "--jobs=1", "--order=natural", + "--additional-driver-flag=--disable-dawn-features=disallow_unsafe_apis", "--additional-driver-flag=--use-gpu-in-tests", "--no-xvfb", "--additional-driver-flag=--enable-features=UseSkiaRenderer,Vulkan" @@ -738,6 +743,7 @@ "--jobs=1", "--order=natural", "--additional-driver-flag=--enable-dawn-backend-validation", + "--additional-driver-flag=--disable-dawn-features=disallow_unsafe_apis", "--additional-driver-flag=--use-gpu-in-tests", "--no-xvfb", "--additional-driver-flag=--enable-features=UseSkiaRenderer,Vulkan" @@ -959,6 +965,7 @@ "--driver-logging", "--jobs=1", "--order=natural", + "--additional-driver-flag=--disable-dawn-features=disallow_unsafe_apis", "--additional-driver-flag=--use-gpu-in-tests", "--no-xvfb", "--additional-driver-flag=--enable-features=UseSkiaRenderer,Vulkan" @@ -993,6 +1000,7 @@ "--jobs=1", "--order=natural", "--additional-driver-flag=--enable-dawn-backend-validation", + "--additional-driver-flag=--disable-dawn-features=disallow_unsafe_apis", "--additional-driver-flag=--use-gpu-in-tests", "--no-xvfb", "--additional-driver-flag=--enable-features=UseSkiaRenderer,Vulkan" @@ -1216,6 +1224,7 @@ "--driver-logging", "--jobs=1", "--order=natural", + "--additional-driver-flag=--disable-dawn-features=disallow_unsafe_apis", "--additional-driver-flag=--use-gpu-in-tests", "--platform=mac-mac10.13" ], @@ -1250,6 +1259,7 @@ "--jobs=1", "--order=natural", "--additional-driver-flag=--enable-dawn-backend-validation", + "--additional-driver-flag=--disable-dawn-features=disallow_unsafe_apis", "--additional-driver-flag=--use-gpu-in-tests", "--platform=mac-mac10.13" ], @@ -1457,6 +1467,7 @@ "--driver-logging", "--jobs=1", "--order=natural", + "--additional-driver-flag=--disable-dawn-features=disallow_unsafe_apis", "--additional-driver-flag=--use-gpu-in-tests", "--platform=mac-mac10.13" ], @@ -1489,6 +1500,7 @@ "--jobs=1", "--order=natural", "--additional-driver-flag=--enable-dawn-backend-validation", + "--additional-driver-flag=--disable-dawn-features=disallow_unsafe_apis", "--additional-driver-flag=--use-gpu-in-tests", "--platform=mac-mac10.13" ], @@ -1708,6 +1720,7 @@ "--driver-logging", "--jobs=1", "--order=natural", + "--additional-driver-flag=--disable-dawn-features=disallow_unsafe_apis", "--additional-driver-flag=--use-gpu-in-tests", "--platform=mac-mac10.13" ], @@ -1742,6 +1755,7 @@ "--jobs=1", "--order=natural", "--additional-driver-flag=--enable-dawn-backend-validation", + "--additional-driver-flag=--disable-dawn-features=disallow_unsafe_apis", "--additional-driver-flag=--use-gpu-in-tests", "--platform=mac-mac10.13" ], @@ -1949,6 +1963,7 @@ "--driver-logging", "--jobs=1", "--order=natural", + "--additional-driver-flag=--disable-dawn-features=disallow_unsafe_apis", "--additional-driver-flag=--use-gpu-in-tests", "--platform=mac-mac10.13" ], @@ -1981,6 +1996,7 @@ "--jobs=1", "--order=natural", "--additional-driver-flag=--enable-dawn-backend-validation", + "--additional-driver-flag=--disable-dawn-features=disallow_unsafe_apis", "--additional-driver-flag=--use-gpu-in-tests", "--platform=mac-mac10.13" ], @@ -2198,6 +2214,7 @@ "--driver-logging", "--jobs=1", "--order=natural", + "--additional-driver-flag=--disable-dawn-features=disallow_unsafe_apis", "--additional-driver-flag=--use-gpu-in-tests", "--target=Release_x64" ], @@ -2420,6 +2437,7 @@ "--driver-logging", "--jobs=1", "--order=natural", + "--additional-driver-flag=--disable-dawn-features=disallow_unsafe_apis", "--additional-driver-flag=--use-gpu-in-tests", "--target=Release_x64" ], @@ -2453,6 +2471,7 @@ "--jobs=1", "--order=natural", "--additional-driver-flag=--enable-dawn-backend-validation", + "--additional-driver-flag=--disable-dawn-features=disallow_unsafe_apis", "--additional-driver-flag=--use-gpu-in-tests", "--target=Release_x64" ], @@ -2667,6 +2686,7 @@ "--driver-logging", "--jobs=1", "--order=natural", + "--additional-driver-flag=--disable-dawn-features=disallow_unsafe_apis", "--additional-driver-flag=--use-gpu-in-tests", "--target=Release_x64" ], @@ -2700,6 +2720,7 @@ "--jobs=1", "--order=natural", "--additional-driver-flag=--enable-dawn-backend-validation", + "--additional-driver-flag=--disable-dawn-features=disallow_unsafe_apis", "--additional-driver-flag=--use-gpu-in-tests", "--target=Release_x64" ], @@ -2915,6 +2936,7 @@ "--driver-logging", "--jobs=1", "--order=natural", + "--additional-driver-flag=--disable-dawn-features=disallow_unsafe_apis", "--additional-driver-flag=--use-gpu-in-tests", "--target=Release_x64" ], @@ -2948,6 +2970,7 @@ "--jobs=1", "--order=natural", "--additional-driver-flag=--enable-dawn-backend-validation", + "--additional-driver-flag=--disable-dawn-features=disallow_unsafe_apis", "--additional-driver-flag=--use-gpu-in-tests", "--target=Release_x64" ], @@ -3162,6 +3185,7 @@ "--driver-logging", "--jobs=1", "--order=natural", + "--additional-driver-flag=--disable-dawn-features=disallow_unsafe_apis", "--additional-driver-flag=--use-gpu-in-tests", "--target=Release_x64" ], @@ -3195,6 +3219,7 @@ "--jobs=1", "--order=natural", "--additional-driver-flag=--enable-dawn-backend-validation", + "--additional-driver-flag=--disable-dawn-features=disallow_unsafe_apis", "--additional-driver-flag=--use-gpu-in-tests", "--target=Release_x64" ], @@ -3412,6 +3437,7 @@ "--driver-logging", "--jobs=1", "--order=natural", + "--additional-driver-flag=--disable-dawn-features=disallow_unsafe_apis", "--additional-driver-flag=--use-gpu-in-tests" ], "isolate_name": "webgpu_blink_web_tests", @@ -3444,6 +3470,7 @@ "--jobs=1", "--order=natural", "--additional-driver-flag=--enable-dawn-backend-validation", + "--additional-driver-flag=--disable-dawn-features=disallow_unsafe_apis", "--additional-driver-flag=--use-gpu-in-tests" ], "isolate_name": "webgpu_blink_web_tests", @@ -3657,6 +3684,7 @@ "--driver-logging", "--jobs=1", "--order=natural", + "--additional-driver-flag=--disable-dawn-features=disallow_unsafe_apis", "--additional-driver-flag=--use-gpu-in-tests" ], "isolate_name": "webgpu_blink_web_tests", @@ -3689,6 +3717,7 @@ "--jobs=1", "--order=natural", "--additional-driver-flag=--enable-dawn-backend-validation", + "--additional-driver-flag=--disable-dawn-features=disallow_unsafe_apis", "--additional-driver-flag=--use-gpu-in-tests" ], "isolate_name": "webgpu_blink_web_tests", @@ -3903,6 +3932,7 @@ "--driver-logging", "--jobs=1", "--order=natural", + "--additional-driver-flag=--disable-dawn-features=disallow_unsafe_apis", "--additional-driver-flag=--use-gpu-in-tests" ], "isolate_name": "webgpu_blink_web_tests", @@ -3935,6 +3965,7 @@ "--jobs=1", "--order=natural", "--additional-driver-flag=--enable-dawn-backend-validation", + "--additional-driver-flag=--disable-dawn-features=disallow_unsafe_apis", "--additional-driver-flag=--use-gpu-in-tests" ], "isolate_name": "webgpu_blink_web_tests", @@ -4148,6 +4179,7 @@ "--driver-logging", "--jobs=1", "--order=natural", + "--additional-driver-flag=--disable-dawn-features=disallow_unsafe_apis", "--additional-driver-flag=--use-gpu-in-tests" ], "isolate_name": "webgpu_blink_web_tests", @@ -4180,6 +4212,7 @@ "--jobs=1", "--order=natural", "--additional-driver-flag=--enable-dawn-backend-validation", + "--additional-driver-flag=--disable-dawn-features=disallow_unsafe_apis", "--additional-driver-flag=--use-gpu-in-tests" ], "isolate_name": "webgpu_blink_web_tests",
diff --git a/testing/buildbot/test_suite_exceptions.pyl b/testing/buildbot/test_suite_exceptions.pyl index 1e17a93..63ffada 100644 --- a/testing/buildbot/test_suite_exceptions.pyl +++ b/testing/buildbot/test_suite_exceptions.pyl
@@ -713,21 +713,25 @@ }, }, }, - # TODO(crbug.com/1127110): Remove experimental once it works fine. - 'chrome_modern_public_bundle_fake_modules_smoke_test': { + 'chrome_java_test_wpr_tests': { + # TODO(crbug.com/1127110): Remove experimental once it works fine. 'modifications': { 'android-marshmallow-x86-rel': { 'experiment_percentage': 100, }, }, }, - # TODO(crbug.com/1127110): Remove experimental once it works fine. + 'chrome_modern_public_bundle_fake_modules_smoke_test': { + 'remove_from': [ + # Runs on android-marshmallow-x86-rel already (crbug.com/1127110) + 'android-marshmallow-arm64-rel', + ], + }, 'chrome_modern_public_bundle_smoke_test': { - 'modifications': { - 'android-marshmallow-x86-rel': { - 'experiment_percentage': 100, - }, - }, + 'remove_from': [ + # Runs on android-marshmallow-x86-rel already (crbug.com/1127110) + 'android-marshmallow-arm64-rel', + ], }, 'chrome_public_smoke_test': { 'remove_from': [ @@ -2712,6 +2716,10 @@ 'hard_timeout': 1200, }, }, + # TODO(crbug.com/1127110): Remove experimental once it works fine. + 'android-marshmallow-x86-rel': { + 'experiment_percentage': 100, + }, 'linux-blink-heap-concurrent-marking-tsan-rel': { 'swarming': { 'shards': 2,
diff --git a/testing/buildbot/test_suites.pyl b/testing/buildbot/test_suites.pyl index a83e0ae..ea53c75 100644 --- a/testing/buildbot/test_suites.pyl +++ b/testing/buildbot/test_suites.pyl
@@ -103,6 +103,14 @@ # Test suites will be gradually moved from android_marshmallow_wpr_gtests # to this one, when there are more GCE capacity. 'android_marshmallow_emulator_gtests': { + # Tests from android_wpr_record_replay_tests + 'chrome_java_test_wpr_tests': { + 'mixins': [ + 'chrome-gpu-gold-service-account', + 'skia_gold_test', + ], + }, + # Tests from android_modern_smoke_tests 'chrome_modern_public_bundle_fake_modules_smoke_test': {}, 'chrome_modern_public_bundle_smoke_test': {}, @@ -110,11 +118,20 @@ # Tests from android_smoke_tests 'chrome_public_smoke_test': {}, + # Tests from chromium_gtests_for_devices_with_graphical_output 'unit_tests': { 'android_swarming': { 'shards': 2, }, }, + + # Tests from chromium_gtests + 'webkit_unit_tests':{ + 'test': 'blink_unittests', + 'android_swarming': { + 'shards': 4, + }, + }, }, 'android_modern_smoke_tests': { @@ -3591,6 +3608,8 @@ '--jobs=1', '--order=natural', '--additional-driver-flag=--enable-dawn-backend-validation', + # Make Dawn allow "Unsafe APIs" so they can be tested with the WebGPU CTS. + '--additional-driver-flag=--disable-dawn-features=disallow_unsafe_apis', # We need this flag to initialize ANGLE so that we can explicitly tell # Dawn which ANGLE adapter Chromium is using. This will help match the test # usage to be the same as the browser. @@ -3631,6 +3650,8 @@ # TODO(crbug.com/953991): Solve this and remove the workaround. '--jobs=1', '--order=natural', + # Make Dawn allow "Unsafe APIs" so they can be tested with the WebGPU CTS. + '--additional-driver-flag=--disable-dawn-features=disallow_unsafe_apis', # We need this flag to initialize ANGLE so that we can explicitly tell # Dawn which ANGLE adapter Chromium is using. This will help match the test # usage to be the same as the browser. @@ -5201,7 +5222,6 @@ # android_marshmallow_wpr_gtests + android_marshmallow_emulator_gtests) # is android_wpr_record_replay_tests 'android_marshmallow_wpr_gtests': [ - 'android_modern_smoke_tests', 'android_specific_chromium_gtests', # Already includes gl_gtests. 'android_wpr_record_replay_tests', # only enabled on Marshmallow 'chromium_gtests',
diff --git a/testing/buildbot/variants.pyl b/testing/buildbot/variants.pyl index 0295dfbd..9c65a7a 100644 --- a/testing/buildbot/variants.pyl +++ b/testing/buildbot/variants.pyl
@@ -344,13 +344,13 @@ '../../weblayer/browser/android/javatests/skew/expectations.txt', '--impl-version=88', ], - 'identifier': 'Implementation Tests For 88.0.4324.118', + 'identifier': 'Implementation Library Tests For 88.0.4324.141', 'swarming': { 'cipd_packages': [ { 'cipd_package': 'chromium/testing/weblayer-x86', 'location': 'weblayer_instrumentation_test_M88', - 'revision': 'version:88.0.4324.118', + 'revision': 'version:88.0.4324.141', } ], }, @@ -416,13 +416,13 @@ '../../weblayer/browser/android/javatests/skew/expectations.txt', '--impl-version=88', ], - 'identifier': 'Implementation Tests For 88.0.4324.118', + 'identifier': 'Implementation Library Tests For 88.0.4324.141', 'swarming': { 'cipd_packages': [ { 'cipd_package': 'chromium/testing/weblayer-x86', 'location': 'weblayer_instrumentation_test_M88', - 'revision': 'version:88.0.4324.118', + 'revision': 'version:88.0.4324.141', } ], }, @@ -488,13 +488,13 @@ '../../weblayer/browser/android/javatests/skew/expectations.txt', '--client-version=88', ], - 'identifier': 'Client Tests For 88.0.4324.118', + 'identifier': 'Client Library Tests For 88.0.4324.141', 'swarming': { 'cipd_packages': [ { 'cipd_package': 'chromium/testing/weblayer-x86', 'location': 'weblayer_instrumentation_test_M88', - 'revision': 'version:88.0.4324.118', + 'revision': 'version:88.0.4324.141', } ], },
diff --git a/testing/libfuzzer/fuzzers/BUILD.gn b/testing/libfuzzer/fuzzers/BUILD.gn index 54842f1..28faaa4 100644 --- a/testing/libfuzzer/fuzzers/BUILD.gn +++ b/testing/libfuzzer/fuzzers/BUILD.gn
@@ -63,18 +63,14 @@ fuzzer_test("url_parse_proto_fuzzer") { sources = [ "url_parse_proto_fuzzer.cc" ] deps = [ - ":url_proto", "//base", "//base:i18n", + "//testing/libfuzzer/proto:url_proto", "//third_party/libprotobuf-mutator", "//url:url", ] } -proto_library("url_proto") { - sources = [ "url.proto" ] -} - fuzzer_test("usrsctp_fuzzer") { sources = [ "usrsctp_fuzzer.cc" ] deps = [ "//third_party/usrsctp" ]
diff --git a/testing/libfuzzer/fuzzers/url.proto b/testing/libfuzzer/fuzzers/url.proto deleted file mode 100644 index 9148a0d..0000000 --- a/testing/libfuzzer/fuzzers/url.proto +++ /dev/null
@@ -1,94 +0,0 @@ -// Copyright 2017 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. - -// This file contains the definition of the Url protobuf used in the -// url_parse_proto_fuzzer that is meant to serve as an example for future -// Chromium fuzzers that use libprotobuf-mutator. -// We will consider the format of a URL for this fuzzer, to be -// [scheme:][//[user[:password]@]host[:port]][/path][?query][#value] -// There may be some URLs Chromium treats as valid that this syntax does not -// capture. However, we will ignore them for the sake of simplicity. -// It is recommended to read this file in conjunction with -// convert_protobuf_to_string() in url_parse_proto_fuzzer.cc as logic in this -// function is sometimes used to ensure that the Url Protocol Buffer obeys the -// syntax we have defined for URLs. Though reading it is completely unecessary -// for understand this fuzzer, we have roughly followed RFC 3986 -// (https://tools.ietf.org/html/rfc3986) which defines the syntax of URIs (which -// URLs are a subset of). - -syntax = "proto2"; - -package url_parse_proto_fuzzer; - -// Here we define the format for a Url Protocol Buffer. This will be passed to -// our fuzzer function. -message Url { - // If there is a scheme, then it must be followed by a colon. A scheme is in - // practice not required in a URL. Therefore, we will define the scheme as - // optional but ensure it is followed by a colon in our conversion code if it - // is included. - optional string scheme = 1; - - enum Slash { - NONE = 0; // Seperate path segments using "" - FORWARD = 1; // Seperate path segments using / - BACKWARD = 2; // Seperate path segments using \ - } - // The syntax rules of the two slashes that precede the host in a URL are - // surprisingly complex. They are not required, even if a scheme is included - // (http:example.com is treated as valid), and are valid even if a scheme is - // not included (//example.com is treated as file:///example.com). They can - // even be backslashes (http:\\example.com and http\/example.com are both - // valid) and there can be any number of them (http:/example.com and - // http://////example.com are both valid). - // We will therefore define slashes as a list of enum values (repeated Slash). - // In our conversion code, this will be read to append the appropriate kind and - // appropriate number of slashes to the URL. - repeated Slash slashes = 2 [packed=true]; - - - // The [user:password@] part of the URL shown above is called the userinfo. - // Userinfo is not mandatory, but if it is included in a URL, then it must - // contain a string called user. There is another optional field in userinfo - // called the password. If a password is included, the user must be separated - // from it by ":". In either case, the userinfo must be separated from the - // host by "@". A URL must have a host if it has a userinfo. - // These requirements will be ensured by the conversion code. - message Userinfo { - required string user = 1; - optional string password = 2; - } - optional Userinfo userinfo = 3; - - // Hosts, like most else in our Url definition, are optional (there are - // are URLs such as data URLs that do not have hosts). - optional string host = 4; - - // ports are unsigned integers between 1-2^16. The closest type to this in the - // proto2 format is uint32. Also if a port number is specified it must be - // preceded by a colon (consider "google.com80" 80 will be interpreted as part - // of the host). The conversion code will ensure this is the case. - optional uint32 port = 5; - - // The rules for the path are somewhat complex. A path is not required, - // however if it follows a port or host, it must start with "/" according - // to the RFC, though Chromium accepts "\" as it converts all backslashes to - // slashes. It does not need to start with "/" if there is no host (in data - // URLs for example). Thus we will define path as a repeated string where each - // member contains a segment of the path and will be preceded by the - // path_separator. The one exception to this is for the first segment if - // path_seperator == NONE and there is a non empty path and host, then the - // first segment will be preceeded by "/". - repeated string path = 6; - required Slash path_separator = 7 [default = FORWARD]; - - // A query must preceded by "?". This will be ensured in the conversion - // code. Queries can have many components which the converter will separate - // using "&", as is the convention. - repeated string query = 8; - - // A fragment must preceded by "#". This will be ensured in the conversion - // code. - optional string fragment = 9; -}
diff --git a/testing/libfuzzer/fuzzers/url_parse_proto_fuzzer.cc b/testing/libfuzzer/fuzzers/url_parse_proto_fuzzer.cc index a70d2a39..f8c0f66 100644 --- a/testing/libfuzzer/fuzzers/url_parse_proto_fuzzer.cc +++ b/testing/libfuzzer/fuzzers/url_parse_proto_fuzzer.cc
@@ -17,7 +17,7 @@ // function. #include "third_party/libprotobuf-mutator/src/src/libfuzzer/libfuzzer_macro.h" // Header information about the Protocol Buffer Url class. -#include "testing/libfuzzer/fuzzers/url.pb.h" +#include "testing/libfuzzer/proto/url.pb.h" // The code using TestCase is copied from url_parse_fuzzer.cc struct TestCase { @@ -34,11 +34,11 @@ protobuf_mutator::protobuf::LogSilencer log_silencer; std::string Slash_to_string(int slash) { - if (slash == url_parse_proto_fuzzer::Url::NONE) + if (slash == url_proto::Url::NONE) return ""; - if (slash == url_parse_proto_fuzzer::Url::FORWARD) + if (slash == url_proto::Url::FORWARD) return "/"; - if (slash == url_parse_proto_fuzzer::Url::BACKWARD) { + if (slash == url_proto::Url::BACKWARD) { return "\\"; } assert(false && "Received unexpected value for slash"); @@ -50,7 +50,7 @@ // Since protobuf is a relatively simple format, fuzzing targets that do not // accept protobufs (such as this one) will require code to convert from // protobuf to the accepted format (string in this case). -std::string protobuf_to_string(const url_parse_proto_fuzzer::Url& url) { +std::string protobuf_to_string(const url_proto::Url& url) { // Build url_string piece by piece from url and then return it. std::string url_string = std::string(""); @@ -126,7 +126,7 @@ // typical libFuzzer based fuzzers. It is passed our Url protobuf object that // was mutated by libFuzzer, converts it to a string and then feeds it to url() // for fuzzing. -DEFINE_BINARY_PROTO_FUZZER(const url_parse_proto_fuzzer::Url& url_protobuf) { +DEFINE_BINARY_PROTO_FUZZER(const url_proto::Url& url_protobuf) { std::string url_string = protobuf_to_string(url_protobuf); // Allow native input to be retrieved easily.
diff --git a/testing/libfuzzer/libprotobuf-mutator.md b/testing/libfuzzer/libprotobuf-mutator.md index 51d0a033..94d7d28 100644 --- a/testing/libfuzzer/libprotobuf-mutator.md +++ b/testing/libfuzzer/libprotobuf-mutator.md
@@ -28,10 +28,10 @@ must write code that converts data from a protobuf-based format that represents the grammar to a format the target accepts. url_parse_proto_fuzzer is a working example of this and is commented extensively. Readers may wish to consult its -code, which is located in `testing/libfuzzer/fuzzers/url_parse_proto_fuzzer.cc`, -and `testing/libfuzzer/fuzzers/url.proto`. Its build configuration can be found -in `testing/libfuzzer/fuzzers/BUILD.gn`. We also provide a walkthrough on how to -do this in the section after the next. +code, which is located in `testing/libfuzzer/fuzzers/url_parse_proto_fuzzer.cc` +and `testing/libfuzzer/proto/url.proto`. Its build configuration can be found +in `testing/libfuzzer/fuzzers/BUILD.gn` and `testing/libfuzzer/proto/BUILD.gn`. +We also provide a walkthrough on how to do this in the section after the next. * Fuzzing targets that accept more than one argument (such as data and flags). In this case, you can define each argument as its own field in your protobuf definition. @@ -135,7 +135,7 @@ } ``` -See `testing/libfuzzer/fuzzers/url.proto` for an example of this in practice. +See `testing/libfuzzer/proto/url.proto` for an example of this in practice. That example has extensive comments on URL syntax and how that influenced the definition of the Url message. @@ -163,7 +163,7 @@ // if it doesn't accept protobufs. std::string native_input = convert_to_native_input(my_proto_format); - // You should provide a way to easily retreive the native input for + // You should provide a way to easily retrieve the native input for // a given protobuf input. This is useful for debugging and for seeing // the inputs that cause targeted_function to crash (which is the reason we // are here!). Note how this is done before targeted_function is called @@ -178,20 +178,21 @@ This is very similar to the same step in writing a standard libFuzzer fuzzer. The only real differences are accepting protobufs rather than raw data and -converting them to the desired format. Conversion code can't really be explored -in this guide since it is format-specific. However, a good example of conversion -code (and a fuzz target) can be found in -`testing/libfuzzer/fuzzers/url_parse_proto_fuzzer.cc`. That example thoroughly -documents how it converts the Url protobuf message into a real URL string. -A good convention is printing the native input when the `LPM_DUMP_NATIVE_INPUT` -env variable is set. This will make it easy to retreive the actual input that -causes the code to crash instead of the protobuf version of it (eg you can get -the URL string that causes an input to crash rather than a protobuf). Since it -is only a convention it is strongly recommended even though it isn't necessary. -You don't need to do this if the native input of targeted_function is protobufs. -Beware that printing a newline can make the output invalid for some formats. In -this case you should use `fflush(0)` since otherwise the program may crash -before native_input is actually printed. +converting them to the desired format. Conversion code can't really be +explored in this guide since it is format-specific. However, a good example +of conversion code (and a fuzz target) can be found in +`testing/libfuzzer/fuzzers/url_parse_proto_fuzzer.cc`. That example +thoroughly documents how it converts the Url protobuf message into a real URL +string. A good convention is printing the native input when the +`LPM_DUMP_NATIVE_INPUT` env variable is set. This will make it easy to +retrieve the actual input that causes the code to crash instead of the +protobuf version of it (e.g. you can get the URL string that causes an input +to crash rather than a protobuf). Since it is only a convention it is +strongly recommended even though it isn't necessary. You don't need to do +this if the native input of targeted_function is protobufs. Beware that +printing a newline can make the output invalid for some formats. In this case +you should use `fflush(0)` since otherwise the program may crash before +native_input is actually printed. ### Define the GN Target
diff --git a/testing/libfuzzer/proto/BUILD.gn b/testing/libfuzzer/proto/BUILD.gn index 97161d15..3815649 100644 --- a/testing/libfuzzer/proto/BUILD.gn +++ b/testing/libfuzzer/proto/BUILD.gn
@@ -38,6 +38,19 @@ all_dependent_configs = [ "//testing/libfuzzer:no_clusterfuzz" ] } } + +source_set("url_proto_converter") { + sources = [ + "url_proto_converter.cc", + "url_proto_converter.h", + ] + deps = [ ":url_proto" ] +} + proto_library("skia_image_filter_proto") { sources = [ "skia_image_filter.proto" ] } + +proto_library("url_proto") { + sources = [ "url.proto" ] +}
diff --git a/testing/libfuzzer/proto/url.proto b/testing/libfuzzer/proto/url.proto new file mode 100644 index 0000000..41a004c --- /dev/null +++ b/testing/libfuzzer/proto/url.proto
@@ -0,0 +1,92 @@ +// Copyright 2017 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. + +// This file contains the definition of the Url protobuf used in the +// url_parse_proto_fuzzer that is meant to serve as an example for future +// Chromium fuzzers that use libprotobuf-mutator. We will consider the format of +// a URL for this fuzzer, to be +// [scheme:][//[user[:password]@]host[:port]][/path][?query][#value] There may +// be some URLs Chromium treats as valid that this syntax does not capture. +// However, we will ignore them for the sake of simplicity. It is recommended to +// read this file in conjunction with Convert() in url_proto_converter.cc as +// logic in this function is sometimes used to ensure that the Url Protocol +// Buffer obeys the syntax we have defined for URLs. Though reading it is +// completely unnecessary for understanding this fuzzer, we have roughly +// followed RFC 3986 (https://tools.ietf.org/html/rfc3986) which defines the +// syntax of URIs (which URLs are a subset of). + +syntax = "proto2"; + +package url_proto; + +// Here we define the format for a Url Protocol Buffer. This will be passed to +// our fuzzer function. +message Url { + // If there is a scheme, then it must be followed by a colon. A scheme is in + // practice not required in a URL. Therefore, we will define the scheme as + // optional but ensure it is followed by a colon in our conversion code if it + // is included. + optional string scheme = 1; + + enum Slash { + NONE = 0; // Separate path segments using "" + FORWARD = 1; // Separate path segments using / + BACKWARD = 2; // Separate path segments using \ + } + // The syntax rules of the two slashes that precede the host in a URL are + // surprisingly complex. They are not required, even if a scheme is included + // (http:example.com is treated as valid), and are valid even if a scheme is + // not included (//example.com is treated as file:///example.com). They can + // even be backslashes (http:\\example.com and http\/example.com are both + // valid) and there can be any number of them (http:/example.com and + // http://////example.com are both valid). + // We will therefore define slashes as a list of enum values (repeated + // Slash). In our conversion code, this will be read to append the + // appropriate kind and appropriate number of slashes to the URL. + repeated Slash slashes = 2 [packed = true]; + + // The [user:password@] part of the URL shown above is called the userinfo. + // Userinfo is not mandatory, but if it is included in a URL, then it must + // contain a string called user. There is another optional field in userinfo + // called the password. If a password is included, the user must be + // separated from it by ":". In either case, the userinfo must be separated + // from the host by "@". A URL must have a host if it has a userinfo. These + // requirements will be ensured by the conversion code. + message Userinfo { + required string user = 1; + optional string password = 2; + } + optional Userinfo userinfo = 3; + + // Hosts, like most else in our Url definition, are optional (there are + // are URLs such as data URLs that do not have hosts). + optional string host = 4; + + // Ports are unsigned integers between 1-2^16. The closest type to this in + // the proto2 format is uint32. Also if a port number is specified it must + // be preceded by a colon (consider "google.com80" 80 will be interpreted as + // part of the host). The conversion code will ensure this is the case. + optional uint32 port = 5; + + // The rules for the path are somewhat complex. A path is not required, + // however if it follows a port or host, it must start with "/" according + // to the RFC, though Chromium accepts "\" as it converts all backslashes to + // slashes. It does not need to start with "/" if there is no host (in data + // URLs for example). Thus we will define path as a repeated string where + // each member contains a segment of the path and will be preceded by the + // path_separator. The one exception to this is for the first segment if + // path_seperator == NONE and there is a non empty path and host, then the + // first segment will be preceded by "/". + repeated string path = 6; + required Slash path_separator = 7 [default = FORWARD]; + + // A query must preceded by "?". This will be ensured in the conversion + // code. Queries can have many components which the converter will separate + // using "&", as is the convention. + repeated string query = 8; + + // A fragment must preceded by "#". This will be ensured in the conversion + // code. + optional string fragment = 9; + }
diff --git a/testing/libfuzzer/proto/url_proto_converter.cc b/testing/libfuzzer/proto/url_proto_converter.cc new file mode 100644 index 0000000..117189b --- /dev/null +++ b/testing/libfuzzer/proto/url_proto_converter.cc
@@ -0,0 +1,102 @@ +// Copyright 2021 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 <assert.h> +#include <stdlib.h> +#include <string> + +#include "testing/libfuzzer/proto/url.pb.h" + +namespace url_proto { + +namespace { + +std::string SlashToString(int slash) { + if (slash == url_proto::Url::NONE) + return ""; + if (slash == url_proto::Url::FORWARD) + return "/"; + if (slash == url_proto::Url::BACKWARD) { + return "\\"; + } + assert(false && "Received unexpected value for slash"); + // Silence compiler warning about not returning in non-void function. + return ""; +} + +} // namespace + +std::string Convert(const url_proto::Url& url) { + // Build url_string piece by piece from url and then return it. + std::string url_string = std::string(""); + + if (url.has_scheme()) { // Get the scheme if Url has it. + // Append the scheme to the url. This may be empty. Then append a colon + // which is mandatory if there is a scheme. + url_string += url.scheme() + ":"; + } + + // Just append the slashes without doing validation, since it would be too + // complex. libFuzzer will hopefully figure out good values. + for (const int slash : url.slashes()) + url_string += SlashToString(slash); + + // Get host. This is simple since hosts are simply strings according to our + // definition. + if (url.has_host()) { + // Get userinfo if libFuzzer set it. Ensure that user is separated + // from the password by ":" (if a password is included) and that userinfo is + // separated from the host by "@". + if (url.has_userinfo()) { + url_string += url.userinfo().user(); + if (url.userinfo().has_password()) { + url_string += ":"; + url_string += url.userinfo().password(); + } + url_string += "@"; + } + url_string += url.host(); + + // As explained in url.proto, if libFuzzer included a port in url ensure + // that it is preceded by the host and then ":". + if (url.has_port()) + // Convert url.port() from an unsigned 32 bit int before appending it. + url_string += ":" + std::to_string(url.port()); + } + + // Append the path segments to the url, with each segment separated by + // the path_separator. + bool first_segment = true; + std::string path_separator = SlashToString(url.path_separator()); + for (const std::string& path_segment : url.path()) { + // There does not need to be a path, but if there is a path and a host, + // ensure the path begins with "/". + if (url.has_host() && first_segment) { + url_string += "/" + path_segment; + first_segment = false; + } else + url_string += path_separator + path_segment; + } + + // Queries must be started by "?". If libFuzzer included a query in url, + // ensure that it is preceded by "?". Also separate query components with + // ampersands as is the convention. + bool first_component = true; + for (const std::string& query_component : url.query()) { + if (first_component) { + url_string += "?" + query_component; + first_component = false; + } else + url_string += "&" + query_component; + } + + // Fragments must be started by "#". If libFuzzer included a fragment + // in url, ensure that it is preceded by "#". + if (url.has_fragment()) + url_string += "#" + url.fragment(); + + return url_string; +} + +} // namespace url_proto
diff --git a/testing/libfuzzer/proto/url_proto_converter.h b/testing/libfuzzer/proto/url_proto_converter.h new file mode 100644 index 0000000..50a47328 --- /dev/null +++ b/testing/libfuzzer/proto/url_proto_converter.h
@@ -0,0 +1,20 @@ +// Copyright 2021 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 TESTING_LIBFUZZER_PROTO_URL_PROTO_CONVERTER_H_ +#define TESTING_LIBFUZZER_PROTO_URL_PROTO_CONVERTER_H_ + +#include "testing/libfuzzer/proto/url.pb.h" + +namespace url_proto { + +// Converts a URL in Protocol Buffer format to a url in string format. +// Since protobuf is a relatively simple format, fuzzing targets that do not +// accept protobufs (such as this one) will require code to convert from +// protobuf to the accepted format (string in this case). +std::string Convert(const url_proto::Url& url); + +} // namespace url_proto + +#endif // TESTING_LIBFUZZER_PROTO_URL_PROTO_CONVERTER_H_
diff --git a/testing/variations/fieldtrial_testing_config.json b/testing/variations/fieldtrial_testing_config.json index 71ebb80..a0aa27d 100644 --- a/testing/variations/fieldtrial_testing_config.json +++ b/testing/variations/fieldtrial_testing_config.json
@@ -5784,6 +5784,28 @@ ] } ], + "SCTAuditingPhase1": [ + { + "platforms": [ + "chromeos", + "chromeos_lacros", + "linux", + "mac", + "windows" + ], + "experiments": [ + { + "name": "Enabled_20200129", + "params": { + "sampling_rate": "0.0001" + }, + "enable_features": [ + "SCTAuditing" + ] + } + ] + } + ], "SRTPromptFieldTrial": [ { "platforms": [ @@ -7153,21 +7175,6 @@ ] } ], - "VideoToolboxVp9Decoding": [ - { - "platforms": [ - "mac" - ], - "experiments": [ - { - "name": "Enabled", - "enable_features": [ - "VideoToolboxVp9Decoding" - ] - } - ] - } - ], "VideoTutorialChromeIntroStudy": [ { "platforms": [
diff --git a/third_party/android_deps/buildSrc/src/main/groovy/BuildConfigGenerator.groovy b/third_party/android_deps/buildSrc/src/main/groovy/BuildConfigGenerator.groovy index 2a4edd7a..b7c5be84 100644 --- a/third_party/android_deps/buildSrc/src/main/groovy/BuildConfigGenerator.groovy +++ b/third_party/android_deps/buildSrc/src/main/groovy/BuildConfigGenerator.groovy
@@ -4,6 +4,7 @@ import groovy.json.JsonOutput import org.gradle.api.DefaultTask +import org.gradle.api.Project import org.gradle.api.tasks.TaskAction import java.util.regex.Pattern @@ -48,6 +49,11 @@ 'org_hamcrest_hamcrest_library': '//third_party/hamcrest:hamcrest_library_java', ] + // Prefixes of autorolled libraries in //third_party/android_deps_autorolled. + public static final def AUTOROLLED_LIB_PREFIXES = [ ] + + public static final def AUTOROLLED_REPO_PATH = 'third_party/android_deps_autorolled' + /** * Directory where the artifacts will be downloaded and where files will be generated. * Note: this path is specified as relative to the chromium source root, and must be normalised @@ -96,7 +102,11 @@ skipLicenses = skipLicenses || project.hasProperty("skipLicenses") useDedicatedAndroidxDir |= project.hasProperty("useDedicatedAndroidxDir") - def graph = new ChromiumDepGraph(project: project, skipLicenses: skipLicenses) + def subprojects = new HashSet<Project>() + subprojects.add(project) + subprojects.addAll(project.subprojects) + def graph = new ChromiumDepGraph(projects: subprojects, logger: project.logger, + skipLicenses: skipLicenses) def normalisedRepoPath = normalisePath(repositoryPath) // 1. Parse the dependency data @@ -107,10 +117,7 @@ def downloadExecutor = Executors.newCachedThreadPool() def downloadTasks = [] graph.dependencies.values().each { dependency -> - if (excludeDependency(dependency)) { - return - } - if (useDedicatedAndroidxDir && dependency.id.startsWith("androidx_")) { + if (excludeDependency(dependency) || computeJavaGroupForwardingTarget(dependency) != null) { return } logger.debug "Processing ${dependency.name}: \n${jsonDump(dependency)}" @@ -190,11 +197,12 @@ } def targetName = translateTargetName(dependency.id) + "_java" - if (useDedicatedAndroidxDir && targetName.startsWith("androidx_")) { + def javaGroupTarget = computeJavaGroupForwardingTarget(dependency) + if (javaGroupTarget != null) { assert dependency.extension == 'jar' || dependency.extension == 'aar' sb.append(""" java_group("${targetName}") { - deps = [ \"//third_party/androidx:${targetName}\" ] + deps = [ \"${javaGroupTarget}\" ] """.stripIndent()) if (dependency.testOnly) sb.append(" testonly = true\n") sb.append("}\n\n") @@ -592,10 +600,8 @@ } depGraph.dependencies.values().sort(dependencyComparator).each { dependency -> - if (excludeDependency(dependency)) { - return - } - if (useDedicatedAndroidxDir && dependency.id.startsWith("androidx_")) { + if (excludeDependency(dependency) || + computeJavaGroupForwardingTarget(dependency) != null) { return } def depPath = "${DOWNLOAD_DIRECTORY_NAME}/${dependency.id}" @@ -634,9 +640,41 @@ } public boolean excludeDependency(ChromiumDepGraph.DependencyDescription dependency) { - def onlyAndroidx = (repositoryPath == "third_party/androidx") - return dependency.exclude || EXISTING_LIBS.get(dependency.id) != null || - (onlyAndroidx && !dependency.id.startsWith("androidx_")) + if (dependency.exclude || EXISTING_LIBS.get(dependency.id) != null) { + return true + } + if (repositoryPath == "third_party/androidx") { + return !dependency.id.startsWith("androidx_") + } + if (repositoryPath == AUTOROLLED_REPO_PATH) { + def targetName = translateTargetName(dependency.id) + "_java" + return !isTargetAutorolled(targetName) + } + return false + } + + /** + * If |dependency| should be a java_group(), returns target to forward to. Returns null + * otherwise. + */ + public String computeJavaGroupForwardingTarget(ChromiumDepGraph.DependencyDescription dependency) { + def targetName = translateTargetName(dependency.id) + "_java" + if (useDedicatedAndroidxDir && targetName.startsWith("androidx_")) { + return "//third_party/androidx:${targetName}" + } + if (repositoryPath != AUTOROLLED_REPO_PATH && isTargetAutorolled(targetName)) { + return "//${AUTOROLLED_REPO_PATH}:${targetName}" + } + return null + } + + private boolean isTargetAutorolled(targetName) { + for (autorolledLibPrefix in AUTOROLLED_LIB_PREFIXES) { + if (targetName.startsWith(autorolledLibPrefix)) { + return true + } + } + return false } private String normalisePath(String pathRelativeToChromiumRoot) {
diff --git a/third_party/android_deps/buildSrc/src/main/groovy/ChromiumDepGraph.groovy b/third_party/android_deps/buildSrc/src/main/groovy/ChromiumDepGraph.groovy index 59cf59a..d29689c7 100644 --- a/third_party/android_deps/buildSrc/src/main/groovy/ChromiumDepGraph.groovy +++ b/third_party/android_deps/buildSrc/src/main/groovy/ChromiumDepGraph.groovy
@@ -10,6 +10,7 @@ import org.gradle.api.artifacts.ResolvedModuleVersion import org.gradle.api.artifacts.component.ComponentIdentifier import org.gradle.api.artifacts.result.ResolvedArtifactResult +import org.gradle.api.logging.Logger import org.gradle.maven.MavenModule import org.gradle.maven.MavenPomArtifact @@ -313,29 +314,37 @@ licenseName: "MIT"), ] - Project project + Project[] projects + Logger logger boolean skipLicenses void collectDependencies() { - def compileConfig = project.configurations.getByName('compile').resolvedConfiguration - def compileListenableFutureConfig = project.configurations.getByName( - 'compileListenableFuture').resolvedConfiguration - def buildCompileConfig = project.configurations.getByName('buildCompile').resolvedConfiguration - def testCompileConfig = project.configurations.getByName('testCompile').resolvedConfiguration - def androidTestCompileConfig = project.configurations.getByName( - 'androidTestCompile').resolvedConfiguration - List<String> topLevelIds = [] Set<ResolvedConfiguration> deps = [] - deps += compileConfig.firstLevelModuleDependencies - deps += compileListenableFutureConfig.firstLevelModuleDependencies - deps += buildCompileConfig.firstLevelModuleDependencies - deps += testCompileConfig.firstLevelModuleDependencies - deps += androidTestCompileConfig.firstLevelModuleDependencies - - compileListenableFutureConfig.firstLevelModuleDependencies.each { dependency -> - lowerVersionOverride.add(makeModuleId(dependency.module)) + Set<ResolvedDependency> firstLevelModuleDependencies = [] + Map<String, List<ResolvedArtifact>> resolvedArtifacts = new HashMap<>() + String[] configNames = [ + 'compile', + 'compileListenableFuture', + 'buildCompile', + 'testCompile', + 'androidTestCompile' + ] + for (Project project : projects) { + for (String configName : configNames) { + def config = project.configurations.getByName(configName).resolvedConfiguration + deps += config.firstLevelModuleDependencies + if (!resolvedArtifacts.containsKey(configName)) { + resolvedArtifacts[configName] = [] + } + resolvedArtifacts[configName].addAll(config.resolvedArtifacts) + } } + resolvedArtifacts['compileListenableFuture'].each { artifact -> + lowerVersionOverride.add(makeModuleId(artifact)) + } + + List<String> topLevelIds = [] deps.each { dependency -> topLevelIds.add(makeModuleId(dependency.module)) collectDependenciesInternal(dependency) @@ -343,29 +352,29 @@ topLevelIds.each { id -> dependencies.get(id).visible = true } - testCompileConfig.resolvedArtifacts.each { artifact -> + resolvedArtifacts['testCompile'].each { artifact -> def id = makeModuleId(artifact) def dep = dependencies.get(id) assert dep != null : "No dependency collected for artifact ${artifact.name}" dep.testOnly = true } - androidTestCompileConfig.resolvedArtifacts.each { artifact -> + resolvedArtifacts['androidTestCompile'].each { artifact -> def dep = dependencies.get(makeModuleId(artifact)) assert dep != null : "No dependency collected for artifact ${artifact.name}" dep.supportsAndroid = true dep.testOnly = true } - buildCompileConfig.resolvedArtifacts.each { artifact -> + resolvedArtifacts['buildCompile'].each { artifact -> def id = makeModuleId(artifact) def dep = dependencies.get(id) assert dep != null : "No dependency collected for artifact ${artifact.name}" dep.testOnly = false } - def compileResolvedArtifacts = compileConfig.resolvedArtifacts - compileResolvedArtifacts += compileListenableFutureConfig.resolvedArtifacts + def compileResolvedArtifacts = resolvedArtifacts['compile'] + compileResolvedArtifacts += resolvedArtifacts['compileListenableFuture'] compileResolvedArtifacts.each { artifact -> def id = makeModuleId(artifact) def dep = dependencies.get(id) @@ -381,19 +390,24 @@ if (dep != null) { dep.isShipped = fallbackProperties.isShipped } else { - project.logger.warn("PROPERTY_OVERRIDES has stale dep: " + id) + logger.warn("PROPERTY_OVERRIDES has stale dep: " + id) } } } } private ResolvedArtifactResult getPomFromArtifact(ComponentIdentifier componentId) { - def component = project.dependencies.createArtifactResolutionQuery() - .forComponents(componentId) - .withArtifacts(MavenModule, MavenPomArtifact) - .execute() - .resolvedComponents[0] - return component.getArtifacts(MavenPomArtifact)[0] + for (Project project : projects) { + def component = project.dependencies.createArtifactResolutionQuery() + .forComponents(componentId) + .withArtifacts(MavenModule, MavenPomArtifact) + .execute() + .resolvedComponents[0] + if (component != null) { + return component.getArtifacts(MavenPomArtifact)[0] + } + } + return null } private void collectDependenciesInternal(ResolvedDependency dependency) { @@ -504,7 +518,7 @@ private customizeDep(DependencyDescription dep) { if (dep.id?.startsWith("com_google_android_")) { - project.logger.debug("Using Android license for ${dep.id}") + logger.debug("Using Android license for ${dep.id}") dep.licenseUrl = "" // This should match fetch_all._ANDROID_SDK_LICENSE_PATH. dep.licensePath = "licenses/Android_SDK_License-December_9_2016.txt" @@ -514,7 +528,7 @@ } else if (dep.id?.startsWith("com_google_firebase_")) { // Use proper Android license file. if (dep.licenseUrl?.equals("https://developer.android.com/studio/terms.html")) { - project.logger.debug("Using Android license for ${dep.id}") + logger.debug("Using Android license for ${dep.id}") dep.licenseUrl = "" dep.licensePath = "licenses/Android_SDK_License-December_9_2016.txt" } @@ -523,7 +537,7 @@ dep.url = "https://firebase.google.com" } } else if (dep.licenseUrl?.equals("http://openjdk.java.net/legal/gplv2+ce.html")) { - project.logger.debug("Detected GPL v2 /w classpath license for ${dep.id}") + logger.debug("Detected GPL v2 /w classpath license for ${dep.id}") // This avoids using html in a LICENSE file. dep.licenseUrl = "" dep.licenseName = "GPL v2 with the classpath exception" @@ -532,7 +546,7 @@ def fallbackProperties = PROPERTY_OVERRIDES.get(dep.id) if (fallbackProperties != null) { - project.logger.debug("Using fallback properties for ${dep.id}") + logger.debug("Using fallback properties for ${dep.id}") if (fallbackProperties.description != null) { dep.description = fallbackProperties.description }
diff --git a/third_party/android_deps/fetch_all.py b/third_party/android_deps/fetch_all.py index 8ebeebf..f611f115 100755 --- a/third_party/android_deps/fetch_all.py +++ b/third_party/android_deps/fetch_all.py
@@ -66,8 +66,9 @@ # Relative to _PRIMARY_ANDROID_DEPS_DIR. _PRIMARY_ANDROID_DEPS_FILES = [ 'buildSrc', - 'vulnerability_supressions.xml', 'licenses', + 'settings.gradle.template', + 'vulnerability_supressions.xml', ] # Git-controlled files needed by and updated by this tool. @@ -76,6 +77,7 @@ os.path.join('..', '..', 'DEPS'), _BUILD_GN, _ADDITIONAL_README_PATHS, + 'subprojects.txt', ] # If this file exists in an aar file then it is appended to LICENSE @@ -266,18 +268,62 @@ _RE_CIPD_PACKAGE = re.compile('package: (\S*)') +def _ParseSubprojects(subproject_path): + """Parses listing of subproject build.gradle files. Returns list of paths.""" + if not os.path.exists(subproject_path): + return None + + subprojects = [] + for subproject in open(subproject_path): + subproject = subproject.strip() + if subproject and not subproject.startswith('#'): + subprojects.append(subproject) + return subprojects + + +def _GenerateSettingsGradle(subproject_dirs, settings_template_path, + settings_out_path): + """Generates settings file by replacing "{{subproject_dirs}}" string in template. + + Args: + subproject_dirs: List of subproject directories to substitute into template. + settings_template_path: Path of template file to substitute into. + settings_out_path: Path of output settings.gradle file. + """ + with open(settings_template_path) as f: + template_content = f.read() + + subproject_dirs_str = '' + if subproject_dirs: + subproject_dirs_str = '\'' + '\',\''.join(subproject_dirs) + '\'' + + template_content = template_content.replace('{{subproject_dirs}}', + subproject_dirs_str) + with open(settings_out_path, 'w') as f: + f.write(template_content) + + +def _BuildGradleCmd(build_android_deps_dir, task): + cmd = [ + _GRADLEW, '-b', + os.path.join(build_android_deps_dir, _BUILD_GRADLE), '--stacktrace', + task + ] + settings_gradle_path = os.path.join(build_android_deps_dir, + 'settings.gradle') + if os.path.exists(settings_gradle_path): + cmd += ['-c', os.path.abspath(settings_gradle_path)] + return cmd + + def _CheckVulnerabilities(build_android_deps_dir, report_dst): logging.warning('Running Gradle dependencyCheckAnalyze. This may take a ' 'few minutes the first time.') # Separate command from main gradle command so that we can provide specific # diagnostics in case of failure of this step. - gradle_cmd = [ - _GRADLEW, - '-b', - os.path.join(build_android_deps_dir, _BUILD_GRADLE), - 'dependencyCheckAnalyze', - ] + gradle_cmd = _BuildGradleCmd(build_android_deps_dir, + 'dependencyCheckAnalyze') report_src = os.path.join(build_android_deps_dir, 'build', 'reports') if os.path.exists(report_dst): @@ -499,6 +545,23 @@ _CUSTOM_ANDROID_DEPS_FILES, src_path_must_exist=is_primary_android_deps) + subprojects = _ParseSubprojects( + os.path.join(args.android_deps_dir, 'subprojects.txt')) + if subprojects: + subproject_dirs = [] + for (index, subproject) in enumerate(subprojects): + subproject_dir = 'subproject{}'.format(index) + Copy(args.android_deps_dir, [subproject], + build_android_deps_dir, + [os.path.join(subproject_dir, 'build.gradle')]) + subproject_dirs.append(subproject_dir) + + _GenerateSettingsGradle( + subproject_dirs, + os.path.join(args.android_deps_dir, + 'settings.gradle.template'), + os.path.join(build_android_deps_dir, 'settings.gradle')) + if not args.ignore_vulnerabilities: report_dst = os.path.join(args.android_deps_dir, 'vulnerability_reports') @@ -509,13 +572,7 @@ # This gradle command generates the new DEPS and BUILD.gn files, it can # also handle special cases. # Edit BuildConfigGenerator.groovy#addSpecialTreatment for such cases. - gradle_cmd = [ - _GRADLEW, - '-b', - os.path.join(build_android_deps_dir, _BUILD_GRADLE), - 'setupRepository', - '--stacktrace', - ] + gradle_cmd = _BuildGradleCmd(build_android_deps_dir, 'setupRepository') if debug: gradle_cmd.append('--debug') if args.ignore_licenses:
diff --git a/third_party/android_deps/settings.gradle.template b/third_party/android_deps/settings.gradle.template new file mode 100644 index 0000000..e0639d0 --- /dev/null +++ b/third_party/android_deps/settings.gradle.template
@@ -0,0 +1,17 @@ +// Copyright 2021 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. + +def subprojectDirs = [{{subproject_dirs}}] + +def subprojects = new HashMap<String, String>() +def i = 1 +subprojectDirs.each { subprojectDir -> + def subprojectName = 'subproject' + i + subprojects.put(subprojectName, subprojectDir) + include(subprojectName) +} + +rootProject.children.each { prj -> + prj.projectDir = new File(subprojects[prj.name]) +}
diff --git a/third_party/android_deps/subprojects.txt b/third_party/android_deps/subprojects.txt new file mode 100644 index 0000000..6c14bc3 --- /dev/null +++ b/third_party/android_deps/subprojects.txt
@@ -0,0 +1,15 @@ +# Copyright 2021 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. + +# This file contains a list of gradle projects which have dependencies on +# libraries defined in this gradle project. The paths should be relative to +# --android-deps-dir . + +# RATIONALE +# In order to pick a version of a library which is compatible with all of the +# targets which depend on it (including targets in other gradle projects) the +# 'setupRepository' task needs to be aware of all gradle projects with targets +# which depend on libraries defined in this gradle project. + +# *** START OF LIST ***
diff --git a/third_party/android_deps_autorolled/.gitignore b/third_party/android_deps_autorolled/.gitignore new file mode 100644 index 0000000..728790e7 --- /dev/null +++ b/third_party/android_deps_autorolled/.gitignore
@@ -0,0 +1,10 @@ +.gradle/ +.idea/ +.settings/ +local.properties + +# Following will be fetched via CIPD. +/BUILD.gn +/additional_readme_paths.json +/build.gradle +/libs/
diff --git a/third_party/android_deps_autorolled/OWNERS b/third_party/android_deps_autorolled/OWNERS new file mode 100644 index 0000000..4be75b6 --- /dev/null +++ b/third_party/android_deps_autorolled/OWNERS
@@ -0,0 +1,7 @@ +# This restriction is in place so that new third-party libraries go through +# full third-party review: +# https://chromium.googlesource.com/chromium/src.git/+/master/docs/adding_to_third_party.md#Get-a-review +set noparent +file://third_party/OWNERS + +per-file fetch_all_androidx.py=file://third_party/android_deps/OWNERS
diff --git a/third_party/android_deps_autorolled/README.chromium b/third_party/android_deps_autorolled/README.chromium new file mode 100644 index 0000000..6ce557ad --- /dev/null +++ b/third_party/android_deps_autorolled/README.chromium
@@ -0,0 +1,31 @@ +Name: Android Deps Autorolled Repository +Short Name: android_deps_autorolled +Version: 1 +License: Refer to additional_readme_paths.json +License Android Compatible: yes +License File: NOT_SHIPPED +Security Critical: no + +Description: +A gradle-specified repository for autorolled Android and java dependencies. + +Local Modifications: +Everything directly here is chromium code, and third_party code lives under +`libs`, where each library has its own README.chromium and LICENSE: + +``` +third_party/android_deps_autorolled +├── .gitignore (hand written) +├── additional_license_paths.json (generated) +├── BUILD.gn (partly generated) +├── libs (generated) +│ ├── dependency_group_name_and_version +│ │ ├── dependency_name_and_version.jar (third_party) +│ │ ├── LICENSE (third_party) +│ │ └── README.chromium (generated) +│ └── other_dependency_group_name_and_version +│ ├── other_dependency_name_and_version.jar (third_party) +│ ├── LICENSE (third_party) +│ └── README.chromium (generated) +└── README.chromium (hand written) +```
diff --git a/third_party/android_deps_autorolled/build.gradle.template b/third_party/android_deps_autorolled/build.gradle.template new file mode 100644 index 0000000..b7298d4 --- /dev/null +++ b/third_party/android_deps_autorolled/build.gradle.template
@@ -0,0 +1,47 @@ +// Copyright 2018 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. + +apply plugin: ChromiumPlugin + +buildscript { + repositories { + maven { + url "https://plugins.gradle.org/m2/" + } + } +} + +repositories { + maven { + // Maven central according to + // https://maven.apache.org/guides/mini/guide-mirror-settings.html + url 'https://repo.maven.apache.org/maven2' + } +} + +dependencies { + // Note about the configuration names: they are defined in buildSrc/ChromiumPlugin + + // Upstream guava introduced versions with -android suffix starting with version + // 22 to remove incompatible code with android. Thus we keep two jars, one for + // the full guava and one that supports android. + compile "com.google.guava:guava:{{guava_version}}-android" + + // buildCompile targets have supports_android = false. + buildCompile "com.google.guava:guava:{{guava_version}}-jre" + + compile "com.google.guava:failureaccess:1.0.1" + + // Dedicated configuration to avoid using higher version number. The 9999 version is empty. + compileListenableFuture "com.google.guava:listenablefuture:1.0" +} + +task setUpRepository(type: BuildConfigGenerator) { + // Paths are relative to the chromium source root. + repositoryPath 'third_party/android_deps_autorolled' + chromiumSourceRoot '../..' + cipdBucket 'chromium' + internalTargetVisibility = [ '//third_party/android_deps:*', ':*' ] + ignoreDEPS = true +}
diff --git a/third_party/android_deps_autorolled/fetch_all_autorolled.py b/third_party/android_deps_autorolled/fetch_all_autorolled.py new file mode 100755 index 0000000..e824336 --- /dev/null +++ b/third_party/android_deps_autorolled/fetch_all_autorolled.py
@@ -0,0 +1,153 @@ +#!/usr/bin/env python3 + +# Copyright 2021 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. +"""A script to generate build.gradle from template and run fetch_all.py + +More specifically, to generate build.gradle: + - It downloads the gradle metadata for guava and parses the file to determine + the latest guava version. + - It replaces {{guava_version}} in build.gralde.template with the latest guava + version. +""" + +import os +import re +import shutil +import subprocess +import tempfile +import urllib +from urllib import request +from xml.etree import ElementTree + +_AUTOROLLED_PATH = os.path.normpath(os.path.join(__file__, '..')) + +_GUAVA_MAVEN_METADATA_XML_URL = 'https://repo.maven.apache.org/maven2/com/google/guava/guava/maven-metadata.xml' + +_FETCH_ALL_PATH = os.path.normpath( + os.path.join(_AUTOROLLED_PATH, '..', 'android_deps', 'fetch_all.py')) + + +def _download_and_compute_latest_guava_version(): + """Downloads gradle metadata for guava. Returns latest guava version.""" + metadata_xml_response = request.urlopen(_GUAVA_MAVEN_METADATA_XML_URL) + xml_tree = ElementTree.fromstring(metadata_xml_response.read()) + latest_version = xml_tree.find('versioning/latest') + + match = re.match(r'([0-9]*\.[0-9]*).*', latest_version.text) + version = match.group(1) + + jre_version = version + '-jre' + android_version = version + '-android' + version_jre_path = 'versioning/versions/version[.=\'' + jre_version + '\']' + version_android_path = 'versioning/versions/version[.=\'' + android_version + '\']' + if xml_tree.find(version_jre_path) == None or xml_tree.find(version_android_path) == None: + raise Exception('{} or {} version not found in {}.'.format(jre_version, android_version, _GUAVA_MAVEN_METADATA_XML_URL)) + + return version + + +def _process_build_gradle(guava_version): + """Generates build.gradle from template. + + Args: + guava_version: Latest guava version. + """ + template_path = os.path.join(_AUTOROLLED_PATH, 'build.gradle.template') + with open(template_path) as f: + template_content = f.read() + + out_path = os.path.join(_AUTOROLLED_PATH, 'build.gradle') + with open(out_path, 'w') as f: + out = template_content.replace('{{guava_version}}', guava_version) + f.write(out) + + +def _extract_files_from_yaml(yaml_path): + """Extracts '- file' file listings from yaml file.""" + out = None + with open(yaml_path, 'r') as f: + for line in f.readlines(): + line = line.rstrip('\n') + if line == 'data:': + out = [] + continue + if out is not None: + if not line.startswith('- file:'): + raise Exception( + '{} has unsupported attributes. Only \'- file\' is supported' + .format(yaml_path)) + out.append(line.rsplit(' ', 1)[1]) + + if not out: + raise Exception('{} does not have \'data\' section.'.format(yaml_path)) + return out + + +def _write_cipd_yaml(libs_dir, cipd_yaml_path): + """Writes cipd.yaml file at the passed-in path.""" + + lib_dirs = os.listdir(libs_dir) + if not lib_dirs: + raise Exception('No generated libraries in {}'.format(libs_dir)) + + data_files = ['BUILD.gn', 'additional_readme_paths.json'] + for lib_dir in lib_dirs: + abs_lib_dir = os.path.join(libs_dir, lib_dir) + autorolled_rel_lib_dir = os.path.relpath(abs_lib_dir, _AUTOROLLED_PATH) + if not os.path.isdir(abs_lib_dir): + continue + lib_files = os.listdir(abs_lib_dir) + if not 'cipd.yaml' in lib_files: + continue + + if not 'README.chromium' in lib_files: + raise Exception('README.chromium not in {}'.format(abs_lib_dir)) + if not 'LICENSE' in lib_files: + raise Exception('LICENSE not in {}'.format(abs_lib_dir)) + data_files.append(os.path.join(autorolled_rel_lib_dir, + 'README.chromium')) + data_files.append(os.path.join(autorolled_rel_lib_dir, 'LICENSE')) + + _rel_extracted_files = _extract_files_from_yaml( + os.path.join(abs_lib_dir, 'cipd.yaml')) + data_files.extend( + os.path.join(autorolled_rel_lib_dir, f) + for f in _rel_extracted_files) + + contents = [ + '# Copyright 2021 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.', + 'package: chromium/third_party/android_deps_autorolled', 'description: android_deps_autorolled', + 'data:' + ] + contents.extend('- file: ' + f for f in data_files) + + with open(cipd_yaml_path, 'w') as out: + out.write('\n'.join(contents)) + + +def main(): + libs_dir = os.path.join(_AUTOROLLED_PATH, 'libs') + + # Let recipe delete contents of lib directory because it has API to retry + # directory deletion if the first deletion attempt does not work. + if os.path.exists(libs_dir) and os.listdir(libs_dir): + raise Exception('Recipe did not empty \'libs\' directory.') + + guava_version = _download_and_compute_latest_guava_version() + _process_build_gradle(guava_version) + + fetch_all_cmd = [ + _FETCH_ALL_PATH, '--android-deps-dir', _AUTOROLLED_PATH, + '--ignore-vulnerabilities' + ] + subprocess.run(fetch_all_cmd, check=True) + + _write_cipd_yaml(libs_dir, os.path.join(_AUTOROLLED_PATH, 'cipd.yaml')) + + +if __name__ == '__main__': + main()
diff --git a/third_party/blink/perf_tests/resources/runner.js b/third_party/blink/perf_tests/resources/runner.js index d50257a..50455728 100644 --- a/third_party/blink/perf_tests/resources/runner.js +++ b/third_party/blink/perf_tests/resources/runner.js
@@ -136,6 +136,16 @@ finish(); } + PerfTestRunner.assert_true = function (cond,text) { + if (cond) + return; + PerfTestRunner.logFatalError(text); + } + + PerfTestRunner.assert_false = function (cond,text) { + PerfTestRunner.assert_true(!cond,text); + } + PerfTestRunner.formatException = function (text, exception) { return "Got an exception while " + text + " with name=" + exception.name + @@ -382,7 +392,6 @@ PerfTestRunner.measureValue = function (test) { PerfTestRunner.unit = test.unit; - PerfTestRunner.bufferedLog = true; start(test, zeroTimeoutScheduler, measureTimeOnce); }
diff --git a/third_party/blink/perf_tests/shadow_dom/resources/declarative.js b/third_party/blink/perf_tests/shadow_dom/resources/declarative.js index bfa783f..29648a9 100644 --- a/third_party/blink/perf_tests/shadow_dom/resources/declarative.js +++ b/third_party/blink/perf_tests/shadow_dom/resources/declarative.js
@@ -1,16 +1,24 @@ (function() { - function getSnippet(useShadowDom,innerContent) { + const lightDomElementName = 'x-elemnt'; // Must have the same length as 'template' + function getSnippet(useShadowDom,innerContent,lightDomDuplicates) { innerContent = innerContent ?? '<span><!--This is the leaf node--></span>'; - let openTag = useShadowDom ? '<template shadowroot=open>' : '<x-elemnt shadowroot=open>'; - let closeTag = useShadowDom ? '</template>' : '</x-elemnt>'; + lightDomDuplicates = lightDomDuplicates ?? 1; + PerfTestRunner.assert_true(!useShadowDom || lightDomDuplicates === 1,'Only light dom content can use duplicates'); + let openTag = useShadowDom ? '<template shadowroot=open>' : `<${lightDomElementName} shadowroot=open>`; + let closeTag = useShadowDom ? '</template>' : `</${lightDomElementName}>`; let hiddenLightDomContent = useShadowDom ? '<span>Some non-slotted light dom content</span>' : '<!-- Some hidden light-dom content here -->'; - return `<div class="host">${openTag}${innerContent}<span><!--Shadow content here--></span>${closeTag}${hiddenLightDomContent}</div>`; + let extraCopies = ''; + while (lightDomDuplicates>1) { + extraCopies += `${openTag}${closeTag}`; + --lightDomDuplicates; + } + return `<div class="host">${extraCopies}${openTag}${innerContent}<span><!--Shadow content here--></span>${closeTag}${hiddenLightDomContent}</div>`; } - function getShadowMarkup(useShadowDom, depth, copies) { - let snippet = getSnippet(useShadowDom); - for (let d=1;d<depth;++d) { - snippet = getSnippet(useShadowDom, snippet); + function getShadowMarkup(useShadowDom, depth, copies, lightDomDuplicates) { + let snippet = undefined; + for (let d=0;d<depth;++d) { + snippet = getSnippet(useShadowDom, snippet, lightDomDuplicates); } let html = '<!DOCTYPE html><body>'; for(let i=0;i<copies;++i) { @@ -19,9 +27,9 @@ return html; } - const dom_parser = new DOMParser(); + const domParser = new DOMParser(); function parseHtml(html) { - return dom_parser.parseFromString(html, 'text/html', {includeShadowRoots: true}); + return domParser.parseFromString(html, 'text/html', {includeShadowRoots: true}); } function measureParse(html) { @@ -31,7 +39,7 @@ } function parseAndAppend(parent, html) { - const fragment = dom_parser.parseFromString(html, 'text/html', {includeShadowRoots: true}); + const fragment = domParser.parseFromString(html, 'text/html', {includeShadowRoots: true}); parent.replaceChildren(...fragment.body.childNodes); } @@ -43,18 +51,17 @@ } // Do some double-checks that things are working: - if (!HTMLTemplateElement.prototype.hasOwnProperty("shadowRoot")) { - PerfTestRunner.logFatalError('Declarative Shadow DOM not enabled/supported'); + function testParse(html) { + const test_div = document.createElement('div'); + measureParseAndAppend(test_div, html); + return test_div; } - const test_div = document.createElement('div'); - measureParseAndAppend(test_div, getShadowMarkup(true, 1, 1)); - const first_host = test_div.firstChild; - if (!first_host.shadowRoot) { - PerfTestRunner.logFatalError('Declarative Shadow DOM not detected'); - } - if (getShadowMarkup(true, 5, 6).length !== getShadowMarkup(false, 5, 6).length) { - PerfTestRunner.logFatalError('Shadow and light DOM content should have identical length'); - } + PerfTestRunner.assert_true(HTMLTemplateElement.prototype.hasOwnProperty("shadowRoot"),'Declarative Shadow DOM not enabled/supported'); + PerfTestRunner.assert_true(testParse(getShadowMarkup(true, 1, 1)).firstChild.shadowRoot,'Declarative Shadow DOM not detected'); + PerfTestRunner.assert_true(getShadowMarkup(true, 5, 6).length === getShadowMarkup(false, 5, 6).length,'Shadow and light DOM content should have identical length'); + const light1 = testParse(getShadowMarkup(false, 5, 6, /*lightDomDuplicates=*/1)).querySelectorAll(lightDomElementName).length; + const light2 = testParse(getShadowMarkup(false, 5, 6, /*lightDomDuplicates=*/2)).querySelectorAll(lightDomElementName).length; + PerfTestRunner.assert_true(light1*2 === light2,"The lightDomDuplicates parameter isn't working"); window.parseHtml = parseHtml; window.measureParse = measureParse;
diff --git a/third_party/blink/perf_tests/shadow_dom/shadow-dom-overhead.html b/third_party/blink/perf_tests/shadow_dom/shadow-dom-overhead.html index ef8588ad..f34cea2 100644 --- a/third_party/blink/perf_tests/shadow_dom/shadow-dom-overhead.html +++ b/third_party/blink/perf_tests/shadow_dom/shadow-dom-overhead.html
@@ -1,28 +1,61 @@ <!DOCTYPE html> <body> -<pre id="log">Measurement in progress...</pre> +<pre id="log"></pre> <script src="../resources/runner.js"></script> -<script src="resources/declarative.js"></script> +<script src="resources/declarative.js"></script> <script> -const depth = 4; +/* +This test tries to measure the overhead associated with parsing and +attaching one shadow root to the tree, as compared to an "ordinary" +element. To measure this, we make three timing measurements: + + t1 = A + (b + d)x + t2 = A + (c + d)x + t3 = A + (2b + d)x + +where: + A = fixed overhead associated with parsing and tree building + b = per light-dom "ordinary" node time + c = per shadow root time + d = per "other element" node time. This is the other elements, e.g. <span> + and <!-- comment --> nodes, mixed in with the test markup. To solve + for the percent overhead, we need this to be non-zero (see below). + x = number of repeats of the test block, per run of the test. + +we want to solve for: + (c/b - 1) = percent overhead, per shadow root + +So: + (t2 - t1)/x = c - b = (c/b - 1)b + (t3 - t1)/x = b + (c/b - 1) = (t2-t1)/(t3-t1) = percent overhead +*/ + +const depth = 6; const copies = 100; -const iterations = 100; const shadowHtml = getShadowMarkup(true, depth, copies); -const lightDomHtml = getShadowMarkup(false, depth, copies); +const lightDomHtml1 = getShadowMarkup(false, depth, copies, /*lightDomDuplicates=*/1); +const lightDomHtml2 = getShadowMarkup(false, depth, copies, /*lightDomDuplicates=*/2); PerfTestRunner.measureValue({ - description: 'This benchmark tests declarative Shadow DOM attachment', + description: 'This benchmark tests the overhead of declarative Shadow DOM', unit: 'percent', run: function() { let total_overhead = 0; - for (let i = 0; i < iterations; i++) { - const shadow_time = measureParse(shadowHtml); - const light_dom_time = measureParse(lightDomHtml); - total_overhead += shadow_time / light_dom_time; + let total_samples = 0; + for (let i = 0; i < 100; i++) { + const t1 = measureParse(lightDomHtml1); + const t2 = measureParse(shadowHtml); + const t3 = measureParse(lightDomHtml2); + if (t2 > t1 && t3 > t1) { + total_overhead += (t2-t1) / (t3-t1); + ++total_samples; + } } + PerfTestRunner.assert_true(total_samples>3,'Too many skipped measurements'); // The result is the total overhead, in *percent*, *per shadow root*. - return 100*(total_overhead/iterations-1)/depth/copies; + return 100*total_overhead/total_samples; } }); </script>
diff --git a/third_party/blink/renderer/bindings/generated_in_modules.gni b/third_party/blink/renderer/bindings/generated_in_modules.gni index 06a5e19..bc19cf60 100644 --- a/third_party/blink/renderer/bindings/generated_in_modules.gni +++ b/third_party/blink/renderer/bindings/generated_in_modules.gni
@@ -31,6 +31,8 @@ "$root_gen_dir/third_party/blink/renderer/bindings/modules/v8/v8_lock_granted_callback.h", "$root_gen_dir/third_party/blink/renderer/bindings/modules/v8/v8_media_session_action_handler.cc", "$root_gen_dir/third_party/blink/renderer/bindings/modules/v8/v8_media_session_action_handler.h", + "$root_gen_dir/third_party/blink/renderer/bindings/modules/v8/v8_modal_close_watcher.cc", + "$root_gen_dir/third_party/blink/renderer/bindings/modules/v8/v8_modal_close_watcher.h", "$root_gen_dir/third_party/blink/renderer/bindings/modules/v8/v8_navigator_user_media_error_callback.cc", "$root_gen_dir/third_party/blink/renderer/bindings/modules/v8/v8_navigator_user_media_error_callback.h", "$root_gen_dir/third_party/blink/renderer/bindings/modules/v8/v8_navigator_user_media_success_callback.cc",
diff --git a/third_party/blink/renderer/bindings/idl_in_modules.gni b/third_party/blink/renderer/bindings/idl_in_modules.gni index de7a1ae..7c9718d 100644 --- a/third_party/blink/renderer/bindings/idl_in_modules.gni +++ b/third_party/blink/renderer/bindings/idl_in_modules.gni
@@ -395,6 +395,7 @@ "//third_party/blink/renderer/modules/mediastream/navigator_media_stream.idl", "//third_party/blink/renderer/modules/mediastream/navigator_user_media.idl", "//third_party/blink/renderer/modules/mediastream/overconstrained_error.idl", + "//third_party/blink/renderer/modules/modalclosewatcher/modal_close_watcher.idl", "//third_party/blink/renderer/modules/native_io/native_io_file.idl", "//third_party/blink/renderer/modules/native_io/native_io_file_manager.idl", "//third_party/blink/renderer/modules/native_io/native_io_file_sync.idl",
diff --git a/third_party/blink/renderer/core/BUILD.gn b/third_party/blink/renderer/core/BUILD.gn index f20764b..23a1207 100644 --- a/third_party/blink/renderer/core/BUILD.gn +++ b/third_party/blink/renderer/core/BUILD.gn
@@ -1345,7 +1345,6 @@ "layout/line/abstract_inline_text_box_test.cc", "layout/line/inline_text_box_test.cc", "layout/line/line_orientation_utils_test.cc", - "layout/list_marker_test.cc", "layout/map_coordinates_test.cc", "layout/min_max_size_test.cc", "layout/multi_column_fragmentainer_group_test.cc",
diff --git a/third_party/blink/renderer/core/css/counter_style.cc b/third_party/blink/renderer/core/css/counter_style.cc index 7562dcc..51a70d8 100644 --- a/third_party/blink/renderer/core/css/counter_style.cc +++ b/third_party/blink/renderer/core/css/counter_style.cc
@@ -388,8 +388,6 @@ } String CounterStyle::GenerateRepresentation(int value) const { - DCHECK(!IsDirty()); - if (pad_length_ > kCounterLengthLimit) return GenerateFallbackRepresentation(value);
diff --git a/third_party/blink/renderer/core/css/counter_style_map.cc b/third_party/blink/renderer/core/css/counter_style_map.cc index 352cd22..f5063351 100644 --- a/third_party/blink/renderer/core/css/counter_style_map.cc +++ b/third_party/blink/renderer/core/css/counter_style_map.cc
@@ -82,21 +82,12 @@ } void CounterStyleMap::AddCounterStyles(const RuleSet& rule_set) { - if (!rule_set.CounterStyleRules().size()) - return; - for (StyleRuleCounterStyle* rule : rule_set.CounterStyleRules()) { CounterStyle* counter_style = CounterStyle::Create(*rule); if (!counter_style) continue; - AtomicString name = rule->GetName(); - if (CounterStyle* replaced = counter_styles_.at(name)) - replaced->SetIsDirty(); counter_styles_.Set(rule->GetName(), counter_style); } - - if (owner_document_) - owner_document_->GetStyleEngine().MarkCounterStylesNeedUpdate(); } CounterStyleMap* CounterStyleMap::GetAncestorMap() const { @@ -273,15 +264,9 @@ } void CounterStyleMap::Dispose() { - if (!counter_styles_.size()) - return; - for (CounterStyle* counter_style : counter_styles_.Values()) counter_style->SetIsDirty(); counter_styles_.clear(); - - if (owner_document_) - owner_document_->GetStyleEngine().MarkCounterStylesNeedUpdate(); } void CounterStyleMap::Trace(Visitor* visitor) const {
diff --git a/third_party/blink/renderer/core/css/style_engine.cc b/third_party/blink/renderer/core/css/style_engine.cc index dd570c4e..63c8414 100644 --- a/third_party/blink/renderer/core/css/style_engine.cc +++ b/third_party/blink/renderer/core/css/style_engine.cc
@@ -542,17 +542,11 @@ } if (RuntimeEnabledFeatures::CSSAtRuleCounterStyleEnabled()) { - // TODO(crbug.com/687225): We initialize the predefined counter styles here. - // Moving the initialization to other places causes test failures, which - // needs investigation and fixing. - CounterStyleMap::GetUACounterStyleMap(); - - if (counter_styles_need_update_) { - CounterStyleMap::MarkAllDirtyCounterStyles(GetDocument(), - active_tree_scopes_); - CounterStyleMap::ResolveAllReferences(GetDocument(), active_tree_scopes_); - counter_styles_need_update_ = false; - } + // TODO(crbug.com/687225): Add a flag to indicate whether counter styles + // need updates, so that we don't update them every time. + CounterStyleMap::MarkAllDirtyCounterStyles(GetDocument(), + active_tree_scopes_); + CounterStyleMap::ResolveAllReferences(GetDocument(), active_tree_scopes_); } probe::ActiveStyleSheetsUpdated(document_); @@ -864,7 +858,6 @@ root->MarkSubtreeNeedsStyleRecalcForFontUpdates(); } - // TODO(xiaochengh): Move layout invalidation after style update. if (LayoutView* layout_view = GetDocument().GetLayoutView()) { TRACE_EVENT0("blink", "LayoutObject::InvalidateSubtreeForFontUpdates"); layout_view->InvalidateSubtreeLayoutForFontUpdates(); @@ -876,13 +869,6 @@ GetDocument().ScheduleLayoutTreeUpdateIfNeeded(); } -void StyleEngine::MarkCounterStylesNeedUpdate() { - counter_styles_need_update_ = true; - if (LayoutView* layout_view = GetDocument().GetLayoutView()) - layout_view->SetNeedsMarkerOrCounterUpdate(); - GetDocument().ScheduleLayoutTreeUpdateIfNeeded(); -} - void StyleEngine::FontsNeedUpdate(FontSelector*, FontInvalidationReason) { if (!GetDocument().IsActive()) return; @@ -1586,7 +1572,7 @@ EnsureUserCounterStyleMap().AddCounterStyles(*it->second); } - MarkCounterStylesNeedUpdate(); + // TODO(crbug.com/687225): Trigger style/Layout invalidations. } if (changed_rule_flags & (kPropertyRules | kScrollTimelineRules)) { @@ -1652,8 +1638,7 @@ if (changed_rule_flags & kKeyframesRules) ScopedStyleResolver::KeyframesRulesAdded(tree_scope); - if (changed_rule_flags & kCounterStyleRules) - MarkCounterStylesNeedUpdate(); + // TODO(crbug.com/687725): Style/layout invalidation for counter style rules. if ((changed_rule_flags & kPropertyRules) || rebuild_at_property_registry) { // @property rules are (for now) ignored in shadow trees, per spec.
diff --git a/third_party/blink/renderer/core/css/style_engine.h b/third_party/blink/renderer/core/css/style_engine.h index 16f6c6c2..3e534ba 100644 --- a/third_party/blink/renderer/core/css/style_engine.h +++ b/third_party/blink/renderer/core/css/style_engine.h
@@ -377,8 +377,6 @@ void MarkFontsNeedUpdate(); void InvalidateStyleAndLayoutForFontUpdates(); - void MarkCounterStylesNeedUpdate(); - StyleRuleKeyframes* KeyframeStylesForAnimation( const AtomicString& animation_name); StyleRuleScrollTimeline* FindScrollTimelineRule(const AtomicString& name); @@ -601,7 +599,6 @@ bool in_dom_removal_{false}; bool viewport_style_dirty_{false}; bool fonts_need_update_{false}; - bool counter_styles_need_update_{false}; // Set to true if we allow marking style dirty from style recalc. Ideally, we // should get rid of this, but we keep track of where we allow it with
diff --git a/third_party/blink/renderer/core/dom/document.cc b/third_party/blink/renderer/core/dom/document.cc index 2e837a5..6470fe3 100644 --- a/third_party/blink/renderer/core/dom/document.cc +++ b/third_party/blink/renderer/core/dom/document.cc
@@ -2461,7 +2461,7 @@ PropagateStyleToViewport(); - GetLayoutView()->UpdateMarkersAndCountersAfterStyleChange(); + View()->UpdateCountersAfterStyleChange(); GetLayoutView()->RecalcLayoutOverflow(); DCHECK(!NeedsStyleRecalc());
diff --git a/third_party/blink/renderer/core/events/event_type_names.json5 b/third_party/blink/renderer/core/events/event_type_names.json5 index 8a2f4be..dcc00853d 100644 --- a/third_party/blink/renderer/core/events/event_type_names.json5 +++ b/third_party/blink/renderer/core/events/event_type_names.json5
@@ -44,12 +44,13 @@ "backgroundfetchclick", "backgroundfetchfail", "backgroundfetchsuccess", - "beforematch", + "beforeclose", "beforecopy", "beforecreatepolicy", "beforecut", "beforeinput", "beforeinstallprompt", + "beforematch", "beforepaste", "beforeprint", "beforeunload",
diff --git a/third_party/blink/renderer/core/frame/local_frame_view.cc b/third_party/blink/renderer/core/frame/local_frame_view.cc index 0e493f4a..a5814bb3 100644 --- a/third_party/blink/renderer/core/frame/local_frame_view.cc +++ b/third_party/blink/renderer/core/frame/local_frame_view.cc
@@ -579,6 +579,12 @@ } } +void LocalFrameView::UpdateCountersAfterStyleChange() { + auto* layout_view = GetLayoutView(); + DCHECK(layout_view); + layout_view->UpdateCounters(); +} + void LocalFrameView::CountObjectsNeedingLayout(unsigned& needs_layout_objects, unsigned& total_objects, bool& is_subtree) {
diff --git a/third_party/blink/renderer/core/frame/local_frame_view.h b/third_party/blink/renderer/core/frame/local_frame_view.h index bbff09c..055d99f2 100644 --- a/third_party/blink/renderer/core/frame/local_frame_view.h +++ b/third_party/blink/renderer/core/frame/local_frame_view.h
@@ -255,6 +255,8 @@ bool GetIntrinsicSizingInfo(IntrinsicSizingInfo&) const override; bool HasIntrinsicSizingInfo() const override; + void UpdateCountersAfterStyleChange(); + void Dispose() override; void PropagateFrameRects() override; void InvalidateAllCustomScrollbarsOnActiveChanged();
diff --git a/third_party/blink/renderer/core/html/html_table_col_element.cc b/third_party/blink/renderer/core/html/html_table_col_element.cc index ab93e21..911cddeb 100644 --- a/third_party/blink/renderer/core/html/html_table_col_element.cc +++ b/third_party/blink/renderer/core/html/html_table_col_element.cc
@@ -71,7 +71,7 @@ } else if (params.name == html_names::kWidthAttr) { if (!params.new_value.IsEmpty()) { if (GetLayoutObject() && GetLayoutObject()->IsLayoutTableCol()) { - auto* col = To<LayoutTableCol>(GetLayoutObject()); + auto* col = To<LayoutBox>(GetLayoutObject()); int new_width = Width().ToInt(); if (new_width != col->Size().Width()) { col->SetNeedsLayoutAndIntrinsicWidthsRecalcAndFullPaintInvalidation(
diff --git a/third_party/blink/renderer/core/inspector/inspector_trace_events.cc b/third_party/blink/renderer/core/inspector/inspector_trace_events.cc index a588a2e..9d8847c 100644 --- a/third_party/blink/renderer/core/inspector/inspector_trace_events.cc +++ b/third_party/blink/renderer/core/inspector/inspector_trace_events.cc
@@ -719,7 +719,6 @@ const char kChildChanged[] = "Child changed"; const char kListValueChange[] = "List value change"; const char kListStyleTypeChange[] = "List style type change"; -const char kCounterStyleChange[] = "Counter style change"; const char kImageChanged[] = "Image changed"; const char kLineBoxesChanged[] = "Line boxes changed"; const char kSliderValueChanged[] = "Slider value changed";
diff --git a/third_party/blink/renderer/core/inspector/inspector_trace_events.h b/third_party/blink/renderer/core/inspector/inspector_trace_events.h index a9b75306..757e45a 100644 --- a/third_party/blink/renderer/core/inspector/inspector_trace_events.h +++ b/third_party/blink/renderer/core/inspector/inspector_trace_events.h
@@ -240,7 +240,6 @@ extern const char kChildChanged[]; extern const char kListValueChange[]; extern const char kListStyleTypeChange[]; -extern const char kCounterStyleChange[]; extern const char kImageChanged[]; extern const char kLineBoxesChanged[]; extern const char kSliderValueChanged[];
diff --git a/third_party/blink/renderer/core/layout/layout_counter.cc b/third_party/blink/renderer/core/layout/layout_counter.cc index e3738559..67164bb 100644 --- a/third_party/blink/renderer/core/layout/layout_counter.cc +++ b/third_party/blink/renderer/core/layout/layout_counter.cc
@@ -674,7 +674,7 @@ maps.erase(maps_iterator); owner.SetHasCounterNodeMap(false); if (owner.View()) - owner.View()->SetNeedsMarkerOrCounterUpdate(); + owner.View()->SetNeedsCounterUpdate(); } void LayoutCounter::DestroyCounterNode(LayoutObject& owner,
diff --git a/third_party/blink/renderer/core/layout/layout_image.cc b/third_party/blink/renderer/core/layout/layout_image.cc index 6d3575cb..f0bdc8d 100644 --- a/third_party/blink/renderer/core/layout/layout_image.cc +++ b/third_party/blink/renderer/core/layout/layout_image.cc
@@ -155,24 +155,17 @@ bool LayoutImage::NeedsLayoutOnIntrinsicSizeChange() const { NOT_DESTROYED(); - // If the actual area occupied by the image has changed and it is not - // constrained by style then a layout is required. - bool image_size_is_constrained = - StyleRef().LogicalWidth().IsSpecified() && - StyleRef().LogicalHeight().IsSpecified() && - !HasAutoHeightOrContainingBlockWithAutoHeight( - kDontRegisterPercentageDescendant); - if (!image_size_is_constrained) - return true; // Flex layout algorithm uses the intrinsic image width/height even if // width/height are specified. if (IsFlexItemIncludingNG()) return true; - // FIXME: We only need to recompute the containing block's preferred size if - // the containing block's size depends on the image's size (i.e., the - // container uses shrink-to-fit sizing). There's no easy way to detect that - // shrink-to-fit is needed, always force a layout. - return HasRelativeLogicalWidth(); + + const auto& style = StyleRef(); + bool is_fixed_sized = + style.LogicalWidth().IsFixed() && style.LogicalHeight().IsFixed() && + (style.LogicalMinWidth().IsFixed() || style.LogicalMinWidth().IsAuto()) && + (style.LogicalMaxWidth().IsFixed() || style.LogicalMaxWidth().IsNone()); + return !is_fixed_sized; } void LayoutImage::InvalidatePaintAndMarkForLayoutIfNeeded(
diff --git a/third_party/blink/renderer/core/layout/layout_list_item.cc b/third_party/blink/renderer/core/layout/layout_list_item.cc index b8bb7ecc..027b7ef 100644 --- a/third_party/blink/renderer/core/layout/layout_list_item.cc +++ b/third_party/blink/renderer/core/layout/layout_list_item.cc
@@ -28,7 +28,6 @@ #include "third_party/blink/renderer/core/html/html_olist_element.h" #include "third_party/blink/renderer/core/layout/layout_list_marker.h" #include "third_party/blink/renderer/core/layout/layout_outside_list_marker.h" -#include "third_party/blink/renderer/core/layout/layout_view.h" #include "third_party/blink/renderer/core/layout/list_marker.h" #include "third_party/blink/renderer/core/paint/list_item_painter.h" #include "third_party/blink/renderer/core/paint/paint_layer.h" @@ -44,14 +43,6 @@ SetConsumesSubtreeChangeNotification(); RegisterSubtreeChangeListenerOnDescendants(true); - View()->AddLayoutListItem(); -} - -void LayoutListItem::WillBeDestroyed() { - NOT_DESTROYED(); - if (View()) - View()->RemoveLayoutListItem(); - LayoutBlockFlow::WillBeDestroyed(); } void LayoutListItem::StyleDidChange(StyleDifference diff, @@ -94,27 +85,6 @@ } } -void LayoutListItem::UpdateCounterStyle() { - NOT_DESTROYED(); - - if (!StyleRef().GetListStyleType() || - StyleRef().GetListStyleType()->IsCounterStyleReferenceValid( - GetDocument())) { - return; - } - - LayoutObject* marker = Marker(); - if (!marker) - return; - - if (auto* legacy_marker = DynamicTo<LayoutListMarker>(marker)) { - legacy_marker->CounterStyleChanged(); - return; - } - - ListMarker::Get(marker)->CounterStyleChanged(*marker); -} - void LayoutListItem::InsertedIntoTree() { NOT_DESTROYED(); LayoutBlockFlow::InsertedIntoTree();
diff --git a/third_party/blink/renderer/core/layout/layout_list_item.h b/third_party/blink/renderer/core/layout/layout_list_item.h index d5e56c3..a7fdeeaa 100644 --- a/third_party/blink/renderer/core/layout/layout_list_item.h +++ b/third_party/blink/renderer/core/layout/layout_list_item.h
@@ -58,8 +58,6 @@ void UpdateMarkerTextIfNeeded(); - void UpdateCounterStyle(); - private: bool IsOfType(LayoutObjectType type) const override { NOT_DESTROYED(); @@ -84,8 +82,6 @@ void AddLayoutOverflowFromChildren() override; - void WillBeDestroyed() override; - void AlignMarkerInBlockDirection(); bool PrepareForBlockDirectionAlign(const LayoutObject*);
diff --git a/third_party/blink/renderer/core/layout/layout_list_marker.cc b/third_party/blink/renderer/core/layout/layout_list_marker.cc index 4cbdc40..e226c75 100644 --- a/third_party/blink/renderer/core/layout/layout_list_marker.cc +++ b/third_party/blink/renderer/core/layout/layout_list_marker.cc
@@ -87,14 +87,6 @@ layout_invalidation_reason::kListStyleTypeChange); } -void LayoutListMarker::CounterStyleChanged() { - NOT_DESTROYED(); - if (IsImage()) - return; - SetNeedsLayoutAndIntrinsicWidthsRecalcAndFullPaintInvalidation( - layout_invalidation_reason::kCounterStyleChange); -} - void LayoutListMarker::UpdateMarkerImageIfNeeded(StyleImage* image) { NOT_DESTROYED(); if (image_ != image) { @@ -354,7 +346,8 @@ const ListStyleTypeData* list_style_data = StyleRef().GetListStyleType(); DCHECK(list_style_data); DCHECK(list_style_data->IsCounterStyle()); - return list_style_data->GetCounterStyle(GetDocument()); + return GetDocument().GetStyleEngine().FindCounterStyleAcrossScopes( + list_style_data->GetCounterStyleName(), list_style_data->GetTreeScope()); } bool LayoutListMarker::IsInside() const {
diff --git a/third_party/blink/renderer/core/layout/layout_list_marker.h b/third_party/blink/renderer/core/layout/layout_list_marker.h index 6042c09..5104a2b 100644 --- a/third_party/blink/renderer/core/layout/layout_list_marker.h +++ b/third_party/blink/renderer/core/layout/layout_list_marker.h
@@ -117,7 +117,6 @@ void UpdateMarkerImageIfNeeded(StyleImage* image); void ListStyleTypeChanged(); - void CounterStyleChanged(); String text_; Persistent<StyleImage> image_;
diff --git a/third_party/blink/renderer/core/layout/layout_object.cc b/third_party/blink/renderer/core/layout/layout_object.cc index f446fdc..96153f3 100644 --- a/third_party/blink/renderer/core/layout/layout_object.cc +++ b/third_party/blink/renderer/core/layout/layout_object.cc
@@ -3027,7 +3027,7 @@ return; } LayoutCounter::LayoutObjectStyleChanged(*this, old_style, *new_style); - View()->SetNeedsMarkerOrCounterUpdate(); + View()->SetNeedsCounterUpdate(); } PhysicalRect LayoutObject::ViewRect() const {
diff --git a/third_party/blink/renderer/core/layout/layout_shift_tracker.cc b/third_party/blink/renderer/core/layout/layout_shift_tracker.cc index 70adf18..8607a90 100644 --- a/third_party/blink/renderer/core/layout/layout_shift_tracker.cc +++ b/third_party/blink/renderer/core/layout/layout_shift_tracker.cc
@@ -526,9 +526,10 @@ SubmitPerformanceEntry(score_delta, had_recent_input); - TRACE_EVENT_INSTANT2("loading", "LayoutShift", TRACE_EVENT_SCOPE_THREAD, - "data", PerFrameTraceData(score_delta, had_recent_input), - "frame", ToTraceValue(&frame)); + TRACE_EVENT_INSTANT2( + "loading", "LayoutShift", TRACE_EVENT_SCOPE_THREAD, "data", + PerFrameTraceData(score_delta, weighted_score_delta, had_recent_input), + "frame", ToTraceValue(&frame)); if (ShouldLog(frame)) { VLOG(1) << "in " << (frame.IsMainFrame() ? "" : "subframe ") @@ -615,9 +616,11 @@ std::unique_ptr<TracedValue> LayoutShiftTracker::PerFrameTraceData( double score_delta, + double weighted_score_delta, bool input_detected) const { auto value = std::make_unique<TracedValue>(); value->SetDouble("score", score_delta); + value->SetDouble("weighted_score_delta", weighted_score_delta); value->SetDouble("cumulative_score", score_); value->SetDouble("overall_max_distance", overall_max_distance_); value->SetDouble("frame_max_distance", frame_max_distance_);
diff --git a/third_party/blink/renderer/core/layout/layout_shift_tracker.h b/third_party/blink/renderer/core/layout/layout_shift_tracker.h index 63d03f71..5b0c973 100644 --- a/third_party/blink/renderer/core/layout/layout_shift_tracker.h +++ b/third_party/blink/renderer/core/layout/layout_shift_tracker.h
@@ -150,6 +150,7 @@ void ReportShift(double score_delta, double weighted_score_delta); void TimerFired(TimerBase*) {} std::unique_ptr<TracedValue> PerFrameTraceData(double score_delta, + double weighted_score_delta, bool input_detected) const; void AttributionsToTracedValue(TracedValue&) const; double SubframeWeightingFactor() const;
diff --git a/third_party/blink/renderer/core/layout/layout_table_col.h b/third_party/blink/renderer/core/layout/layout_table_col.h index 58140fe..8e6074b 100644 --- a/third_party/blink/renderer/core/layout/layout_table_col.h +++ b/third_party/blink/renderer/core/layout/layout_table_col.h
@@ -130,7 +130,7 @@ template <> struct DowncastTraits<LayoutTableCol> { static bool AllowFrom(const LayoutObject& object) { - return object.IsLayoutTableCol(); + return object.IsLayoutTableCol() && !object.IsLayoutNGObject(); } };
diff --git a/third_party/blink/renderer/core/layout/layout_view.cc b/third_party/blink/renderer/core/layout/layout_view.cc index 74d67fa..c21e406 100644 --- a/third_party/blink/renderer/core/layout/layout_view.cc +++ b/third_party/blink/renderer/core/layout/layout_view.cc
@@ -43,8 +43,6 @@ #include "third_party/blink/renderer/core/layout/layout_counter.h" #include "third_party/blink/renderer/core/layout/layout_embedded_content.h" #include "third_party/blink/renderer/core/layout/layout_geometry_map.h" -#include "third_party/blink/renderer/core/layout/layout_list_item.h" -#include "third_party/blink/renderer/core/layout/ng/list/layout_ng_list_item.h" #include "third_party/blink/renderer/core/layout/svg/layout_svg_root.h" #include "third_party/blink/renderer/core/layout/view_fragmentation_context.h" #include "third_party/blink/renderer/core/page/chrome_client.h" @@ -958,25 +956,19 @@ return CompositingReason::kNone; } -void LayoutView::UpdateMarkersAndCountersAfterStyleChange() { +void LayoutView::UpdateCounters() { NOT_DESTROYED(); - if (!needs_marker_counter_update_) + if (!needs_counter_update_) return; - needs_marker_counter_update_ = false; - if (!HasLayoutCounters() && !HasLayoutListItems()) + needs_counter_update_ = false; + if (!HasLayoutCounters()) return; for (LayoutObject* layout_object = this; layout_object; layout_object = layout_object->NextInPreOrder()) { - if (auto* list_item = DynamicTo<LayoutListItem>(layout_object)) { - list_item->UpdateCounterStyle(); - } else if (auto* ng_list_item = - DynamicTo<LayoutNGListItem>(layout_object)) { - ng_list_item->UpdateCounterStyle(); - } else if (auto* counter = DynamicTo<LayoutCounter>(layout_object)) { + if (auto* counter = DynamicTo<LayoutCounter>(layout_object)) counter->UpdateCounter(); - } } }
diff --git a/third_party/blink/renderer/core/layout/layout_view.h b/third_party/blink/renderer/core/layout/layout_view.h index a8b21ba..51d607f 100644 --- a/third_party/blink/renderer/core/layout/layout_view.h +++ b/third_party/blink/renderer/core/layout/layout_view.h
@@ -246,12 +246,11 @@ // FIXME: This is a work around because the current implementation of counters // requires walking the entire tree repeatedly and most pages don't actually // use either feature so we shouldn't take the performance hit when not - // needed. Long term we should rewrite the counter code. - // TODO(xiaochengh): Or do we keep it as is? + // needed. Long term we should rewrite the counter and quotes code. void AddLayoutCounter() { NOT_DESTROYED(); layout_counter_count_++; - SetNeedsMarkerOrCounterUpdate(); + SetNeedsCounterUpdate(); } void RemoveLayoutCounter() { NOT_DESTROYED(); @@ -262,25 +261,11 @@ NOT_DESTROYED(); return layout_counter_count_; } - void AddLayoutListItem() { + void SetNeedsCounterUpdate() { NOT_DESTROYED(); - layout_list_item_count_++; - SetNeedsMarkerOrCounterUpdate(); + needs_counter_update_ = true; } - void RemoveLayoutListItem() { - NOT_DESTROYED(); - DCHECK_GT(layout_list_item_count_, 0u); - layout_list_item_count_--; - } - bool HasLayoutListItems() { - NOT_DESTROYED(); - return layout_list_item_count_; - } - void SetNeedsMarkerOrCounterUpdate() { - NOT_DESTROYED(); - needs_marker_counter_update_ = true; - } - void UpdateMarkersAndCountersAfterStyleChange(); + void UpdateCounters(); bool BackgroundIsKnownToBeOpaqueInRect( const PhysicalRect& local_rect) const override; @@ -393,9 +378,8 @@ scoped_refptr<IntervalArena> interval_arena_; LayoutQuote* layout_quote_head_; - unsigned layout_counter_count_ = 0; - unsigned layout_list_item_count_ = 0; - bool needs_marker_counter_update_ = false; + unsigned layout_counter_count_; + bool needs_counter_update_ = false; unsigned hit_test_count_; unsigned hit_test_cache_hits_;
diff --git a/third_party/blink/renderer/core/layout/list_marker.cc b/third_party/blink/renderer/core/layout/list_marker.cc index c1c7be0d..7ab6db2a 100644 --- a/third_party/blink/renderer/core/layout/list_marker.cc +++ b/third_party/blink/renderer/core/layout/list_marker.cc
@@ -93,7 +93,8 @@ return 0; } -// If the value of ListStyleType changed, we need to update the marker text. +// If the value of ListStyleType changed, we need to the marker text has been +// updated. void ListMarker::ListStyleTypeChanged(LayoutObject& marker) { DCHECK_EQ(Get(&marker), this); if (marker_text_type_ == kNotText || marker_text_type_ == kUnresolved) @@ -104,17 +105,6 @@ layout_invalidation_reason::kListStyleTypeChange); } -// If the @counter-style in use has changed, we need to update the marker text. -void ListMarker::CounterStyleChanged(LayoutObject& marker) { - DCHECK_EQ(Get(&marker), this); - if (marker_text_type_ == kNotText || marker_text_type_ == kUnresolved) - return; - - marker_text_type_ = kUnresolved; - marker.SetNeedsLayoutAndIntrinsicWidthsRecalcAndFullPaintInvalidation( - layout_invalidation_reason::kCounterStyleChange); -} - void ListMarker::OrdinalValueChanged(LayoutObject& marker) { DCHECK_EQ(Get(&marker), this); if (marker_text_type_ == kOrdinalValue) { @@ -430,7 +420,9 @@ DCHECK(RuntimeEnabledFeatures::CSSAtRuleCounterStyleEnabled()); DCHECK(style.GetListStyleType()); DCHECK(style.GetListStyleType()->IsCounterStyle()); - return style.GetListStyleType()->GetCounterStyle(document); + const ListStyleTypeData& list_style_data = *style.GetListStyleType(); + return document.GetStyleEngine().FindCounterStyleAcrossScopes( + list_style_data.GetCounterStyleName(), list_style_data.GetTreeScope()); } ListMarker::ListStyleCategory ListMarker::GetListStyleCategory(
diff --git a/third_party/blink/renderer/core/layout/list_marker.h b/third_party/blink/renderer/core/layout/list_marker.h index e9ed1b3..1f3fd85 100644 --- a/third_party/blink/renderer/core/layout/list_marker.h +++ b/third_party/blink/renderer/core/layout/list_marker.h
@@ -94,7 +94,6 @@ void ListStyleTypeChanged(LayoutObject&); void OrdinalValueChanged(LayoutObject&); - void CounterStyleChanged(LayoutObject&); int ListItemValue(const LayoutObject&) const;
diff --git a/third_party/blink/renderer/core/layout/list_marker_test.cc b/third_party/blink/renderer/core/layout/list_marker_test.cc deleted file mode 100644 index aa70c9a..0000000 --- a/third_party/blink/renderer/core/layout/list_marker_test.cc +++ /dev/null
@@ -1,312 +0,0 @@ -// Copyright 2021 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 "third_party/blink/renderer/core/layout/list_marker.h" - -#include "third_party/blink/renderer/core/layout/ng/list/layout_ng_list_item.h" -#include "third_party/blink/renderer/core/layout/ng/ng_layout_test.h" - -namespace blink { - -// We don't test legacy layout because it's deprecated, and we don't want to -// complicate the test with the legacy LayoutListMarker here. -class ListMarkerTest : public NGLayoutTest { - protected: - LayoutObject* GetMarker(const char* list_item_id) { - LayoutNGListItem* list_item = - To<LayoutNGListItem>(GetLayoutObjectByElementId(list_item_id)); - return list_item->Marker(); - } - - LayoutObject* GetMarker(TreeScope& scope, const char* list_item_id) { - Element* list_item = scope.getElementById(list_item_id); - return To<LayoutNGListItem>(list_item->GetLayoutObject())->Marker(); - } - - String GetMarkerText(TreeScope& scope, const char* list_item_id) { - return To<LayoutText>(GetMarker(scope, list_item_id)->SlowFirstChild()) - ->GetText(); - } - - String GetMarkerText(const char* list_item_id) { - return GetMarkerText(GetDocument(), list_item_id); - } - - void AddCounterStyle(const AtomicString& name, const String& descriptors) { - StringBuilder declaration; - declaration.Append("@counter-style "); - declaration.Append(name); - declaration.Append("{"); - declaration.Append(descriptors); - declaration.Append("}"); - Element* sheet = GetDocument().CreateElementForBinding("style"); - sheet->setInnerHTML(declaration.ToString()); - GetDocument().body()->appendChild(sheet); - } -}; - -TEST_F(ListMarkerTest, AddCounterStyle) { - GetDocument().body()->setInnerHTML(R"HTML( - <style> - @counter-style foo { - system: fixed; - symbols: W X Y Z; - } - </style> - <ol> - <li id="decimal" style="list-style-type: decimal"></li> - <li id="foo" style="list-style-type: foo"></li> - <li id="bar" style="list-style-type: bar"></li> - </ol> - )HTML"); - UpdateAllLifecyclePhasesForTest(); - - EXPECT_EQ("1. ", GetMarkerText("decimal")); - EXPECT_EQ("X. ", GetMarkerText("foo")); - EXPECT_EQ("3. ", GetMarkerText("bar")); - - // Add @counter-style 'bar'. Should not affect 'decimal' and 'foo'. - AddCounterStyle("bar", "system: fixed; symbols: A B C;"); - GetDocument().UpdateStyleAndLayoutTree(); - - EXPECT_FALSE(GetMarker("decimal")->NeedsLayout()); - EXPECT_FALSE(GetMarker("foo")->NeedsLayout()); - EXPECT_TRUE(GetMarker("bar")->NeedsLayout()); - - UpdateAllLifecyclePhasesForTest(); - EXPECT_EQ("1. ", GetMarkerText("decimal")); - EXPECT_EQ("X. ", GetMarkerText("foo")); - EXPECT_EQ("C. ", GetMarkerText("bar")); -} - -TEST_F(ListMarkerTest, RemoveCounterStyle) { - GetDocument().body()->setInnerHTML(R"HTML( - <style id="foo-sheet"> - @counter-style foo { - system: fixed; - symbols: W X Y Z; - } - </style> - <ol> - <li id="decimal" style="list-style-type: decimal"></li> - <li id="foo" style="list-style-type: foo"></li> - </ol> - )HTML"); - UpdateAllLifecyclePhasesForTest(); - - EXPECT_EQ("1. ", GetMarkerText("decimal")); - EXPECT_EQ("X. ", GetMarkerText("foo")); - - // Remove @counter-style 'foo'. Should not affect 'decimal'. - GetElementById("foo-sheet")->remove(); - GetDocument().UpdateStyleAndLayoutTree(); - - EXPECT_FALSE(GetMarker("decimal")->NeedsLayout()); - EXPECT_TRUE(GetMarker("foo")->NeedsLayout()); - - UpdateAllLifecyclePhasesForTest(); - EXPECT_EQ("1. ", GetMarkerText("decimal")); - EXPECT_EQ("2. ", GetMarkerText("foo")); -} - -TEST_F(ListMarkerTest, OverridePredefinedCounterStyle) { - GetDocument().body()->setInnerHTML(R"HTML( - <ol> - <li id="decimal" style="list-style-type: decimal"></li> - <li id="upper-roman" style="list-style-type: upper-roman"></li> - </ol> - )HTML"); - UpdateAllLifecyclePhasesForTest(); - - EXPECT_EQ("1. ", GetMarkerText("decimal")); - EXPECT_EQ("II. ", GetMarkerText("upper-roman")); - - // Override 'upper-roman'. Should not affect 'decimal'. - AddCounterStyle("upper-roman", "system: fixed; symbols: A B C;"); - GetDocument().UpdateStyleAndLayoutTree(); - - EXPECT_FALSE(GetMarker("decimal")->NeedsLayout()); - EXPECT_TRUE(GetMarker("upper-roman")->NeedsLayout()); - - UpdateAllLifecyclePhasesForTest(); - EXPECT_EQ("1. ", GetMarkerText("decimal")); - EXPECT_EQ("B. ", GetMarkerText("upper-roman")); -} - -TEST_F(ListMarkerTest, RemoveOverrideOfPredefinedCounterStyle) { - GetDocument().body()->setInnerHTML(R"HTML( - <style id="to-remove"> - @counter-style upper-roman { - system: fixed; - symbols: A B C; - } - </style> - <ol> - <li id="decimal" style="list-style-type: decimal"></li> - <li id="upper-roman" style="list-style-type: upper-roman"></li> - </ol> - )HTML"); - UpdateAllLifecyclePhasesForTest(); - - EXPECT_EQ("1. ", GetMarkerText("decimal")); - EXPECT_EQ("B. ", GetMarkerText("upper-roman")); - - // Remove override of 'upper-roman'. Should not affect 'decimal'. - GetElementById("to-remove")->remove(); - GetDocument().UpdateStyleAndLayoutTree(); - - EXPECT_FALSE(GetMarker("decimal")->NeedsLayout()); - EXPECT_TRUE(GetMarker("upper-roman")->NeedsLayout()); - - UpdateAllLifecyclePhasesForTest(); - EXPECT_EQ("1. ", GetMarkerText("decimal")); - EXPECT_EQ("II. ", GetMarkerText("upper-roman")); -} - -TEST_F(ListMarkerTest, OverrideSameScopeCounterStyle) { - GetDocument().body()->setInnerHTML(R"HTML( - <style> - @counter-style foo { - system: fixed; - symbols: W X Y Z; - } - </style> - <ol> - <li id="decimal" style="list-style-type: decimal"></li> - <li id="foo" style="list-style-type: foo"></li> - </ol> - )HTML"); - UpdateAllLifecyclePhasesForTest(); - - EXPECT_EQ("1. ", GetMarkerText("decimal")); - EXPECT_EQ("X. ", GetMarkerText("foo")); - - // Override 'foo'. Should not affect 'decimal'. - AddCounterStyle("foo", "system: fixed; symbols: A B C;"); - GetDocument().UpdateStyleAndLayoutTree(); - - EXPECT_FALSE(GetMarker("decimal")->NeedsLayout()); - EXPECT_TRUE(GetMarker("foo")->NeedsLayout()); - - UpdateAllLifecyclePhasesForTest(); - EXPECT_EQ("1. ", GetMarkerText("decimal")); - EXPECT_EQ("B. ", GetMarkerText("foo")); -} - -TEST_F(ListMarkerTest, RemoveOverrideOfSameScopeCounterStyle) { - GetDocument().body()->setInnerHTML(R"HTML( - <style> - @counter-style foo { - system: fixed; - symbols: W X Y Z; - } - </style> - <style id="to-remove"> - @counter-style foo { - system: fixed; - symbols: A B C; - } - </style> - <ol> - <li id="decimal" style="list-style-type: decimal"></li> - <li id="foo" style="list-style-type: foo"></li> - </ol> - )HTML"); - UpdateAllLifecyclePhasesForTest(); - - EXPECT_EQ("1. ", GetMarkerText("decimal")); - EXPECT_EQ("B. ", GetMarkerText("foo")); - - // Remove the override of 'foo'. Should not affect 'decimal'. - GetElementById("to-remove")->remove(); - GetDocument().UpdateStyleAndLayoutTree(); - - EXPECT_FALSE(GetMarker("decimal")->NeedsLayout()); - EXPECT_TRUE(GetMarker("foo")->NeedsLayout()); - - UpdateAllLifecyclePhasesForTest(); - EXPECT_EQ("1. ", GetMarkerText("decimal")); - EXPECT_EQ("X. ", GetMarkerText("foo")); -} - -TEST_F(ListMarkerTest, ModifyShadowDOMWithOwnCounterStyles) { - GetDocument().body()->setInnerHTML(R"HTML( - <style> - @counter-style foo { - system: fixed; - symbols: W X Y Z; - } - </style> - <ol> - <li id="decimal" style="list-style-type: decimal"></li> - <li id="foo" style="list-style-type: foo"></li> - </ol> - <div id="host1"></div> - <div id="host2"></div> - )HTML"); - UpdateAllLifecyclePhasesForTest(); - - EXPECT_EQ("1. ", GetMarkerText("decimal")); - EXPECT_EQ("X. ", GetMarkerText("foo")); - - // Attach a shadow tree with counter styles. Shouldn't affect anything outside - ShadowRoot& shadow1 = - GetElementById("host1")->AttachShadowRootInternal(ShadowRootType::kOpen); - shadow1.setInnerHTML(R"HTML( - <style> - @counter-style foo { - system: fixed; - symbols: A B C; - } - </style> - <ol> - <li id="shadow-foo" style="list-style-type: foo"></li> - </ol> - )HTML"); - GetDocument().UpdateStyleAndLayoutTree(); - EXPECT_FALSE(GetMarker("decimal")->NeedsLayout()); - EXPECT_FALSE(GetMarker("foo")->NeedsLayout()); - UpdateAllLifecyclePhasesForTest(); - EXPECT_EQ("1. ", GetMarkerText("decimal")); - EXPECT_EQ("X. ", GetMarkerText("foo")); - EXPECT_EQ("A. ", GetMarkerText(shadow1, "shadow-foo")); - - // Attach another shadow tree with counter styles. Shouldn't affect anything - // outside. - ShadowRoot& shadow2 = - GetElementById("host2")->AttachShadowRootInternal(ShadowRootType::kOpen); - shadow2.setInnerHTML(R"HTML( - <style> - @counter-style foo { - system: fixed; - symbols: D E F; - } - </style> - <ol> - <li id="shadow-foo" style="list-style-type: foo"></li> - </ol> - )HTML"); - GetDocument().UpdateStyleAndLayoutTree(); - EXPECT_FALSE(GetMarker("decimal")->NeedsLayout()); - EXPECT_FALSE(GetMarker("foo")->NeedsLayout()); - EXPECT_FALSE(GetMarker(shadow1, "shadow-foo")->NeedsLayout()); - UpdateAllLifecyclePhasesForTest(); - EXPECT_EQ("1. ", GetMarkerText("decimal")); - EXPECT_EQ("X. ", GetMarkerText("foo")); - EXPECT_EQ("A. ", GetMarkerText(shadow1, "shadow-foo")); - EXPECT_EQ("D. ", GetMarkerText(shadow2, "shadow-foo")); - - // Remove one of the shadow trees. Shouldn't affect anything outside. - GetElementById("host1")->remove(); - GetDocument().UpdateStyleAndLayoutTree(); - EXPECT_FALSE(GetMarker("decimal")->NeedsLayout()); - EXPECT_FALSE(GetMarker("foo")->NeedsLayout()); - EXPECT_FALSE(GetMarker(shadow2, "shadow-foo")->NeedsLayout()); - UpdateAllLifecyclePhasesForTest(); - EXPECT_EQ("1. ", GetMarkerText("decimal")); - EXPECT_EQ("X. ", GetMarkerText("foo")); - EXPECT_EQ("D. ", GetMarkerText(shadow2, "shadow-foo")); -} - -} // namespace blink
diff --git a/third_party/blink/renderer/core/layout/ng/list/layout_ng_list_item.cc b/third_party/blink/renderer/core/layout/ng/list/layout_ng_list_item.cc index 60eadd0e..ff8111a 100644 --- a/third_party/blink/renderer/core/layout/ng/list/layout_ng_list_item.cc +++ b/third_party/blink/renderer/core/layout/ng/list/layout_ng_list_item.cc
@@ -4,7 +4,6 @@ #include "third_party/blink/renderer/core/layout/ng/list/layout_ng_list_item.h" -#include "third_party/blink/renderer/core/layout/layout_view.h" #include "third_party/blink/renderer/core/layout/list_marker.h" namespace blink { @@ -15,14 +14,6 @@ SetConsumesSubtreeChangeNotification(); RegisterSubtreeChangeListenerOnDescendants(true); - View()->AddLayoutListItem(); -} - -void LayoutNGListItem::WillBeDestroyed() { - NOT_DESTROYED(); - if (View()) - View()->RemoveLayoutListItem(); - LayoutNGBlockFlow::WillBeDestroyed(); } bool LayoutNGListItem::IsOfType(LayoutObjectType type) const { @@ -64,21 +55,6 @@ } } -void LayoutNGListItem::UpdateCounterStyle() { - if (!StyleRef().GetListStyleType() || - StyleRef().GetListStyleType()->IsCounterStyleReferenceValid( - GetDocument())) { - return; - } - - LayoutObject* marker = Marker(); - ListMarker* list_marker = ListMarker::Get(marker); - if (!list_marker) - return; - - list_marker->CounterStyleChanged(*marker); -} - void LayoutNGListItem::OrdinalValueChanged() { LayoutObject* marker = Marker(); if (ListMarker* list_marker = ListMarker::Get(marker))
diff --git a/third_party/blink/renderer/core/layout/ng/list/layout_ng_list_item.h b/third_party/blink/renderer/core/layout/ng/list/layout_ng_list_item.h index ebef26d1..02ddf45e 100644 --- a/third_party/blink/renderer/core/layout/ng/list/layout_ng_list_item.h +++ b/third_party/blink/renderer/core/layout/ng/list/layout_ng_list_item.h
@@ -26,7 +26,6 @@ } void UpdateMarkerTextIfNeeded(); - void UpdateCounterStyle(); void OrdinalValueChanged(); void WillCollectInlines() override; @@ -42,7 +41,6 @@ void WillBeRemovedFromTree() override; void StyleDidChange(StyleDifference, const ComputedStyle* old_style) override; void SubtreeDidChange() final; - void WillBeDestroyed() override; ListItemOrdinal ordinal_; };
diff --git a/third_party/blink/renderer/core/loader/document_loader.cc b/third_party/blink/renderer/core/loader/document_loader.cc index ea5f820f..576556861 100644 --- a/third_party/blink/renderer/core/loader/document_loader.cc +++ b/third_party/blink/renderer/core/loader/document_loader.cc
@@ -341,9 +341,7 @@ data_buffer_(SharedBuffer::Create()), devtools_navigation_token_(params_->devtools_navigation_token), had_sticky_activation_(params_->is_user_activated), - had_transient_activation_( - LocalFrame::HasTransientUserActivation(frame_) || - params_->had_transient_activation), + had_transient_activation_(params_->had_transient_activation), is_browser_initiated_(params_->is_browser_initiated), was_discarded_(params_->was_discarded), loading_srcdoc_(url_.IsAboutSrcdocURL()),
diff --git a/third_party/blink/renderer/core/resize_observer/resize_observer.idl b/third_party/blink/renderer/core/resize_observer/resize_observer.idl index 6537789..c6d0c24 100644 --- a/third_party/blink/renderer/core/resize_observer/resize_observer.idl +++ b/third_party/blink/renderer/core/resize_observer/resize_observer.idl
@@ -13,7 +13,7 @@ ActiveScriptWrappable ] interface ResizeObserver { [CallWith=ScriptState, MeasureAs=ResizeObserver_Constructor] constructor(ResizeObserverCallback callback); - [RuntimeEnabled=ResizeObserverUpdates] void observe(Element target, ResizeObserverOptions options); + void observe(Element target, ResizeObserverOptions options); void observe(Element target); void unobserve(Element target); void disconnect();
diff --git a/third_party/blink/renderer/core/resize_observer/resize_observer_entry.cc b/third_party/blink/renderer/core/resize_observer/resize_observer_entry.cc index 41216d9..fac588a7 100644 --- a/third_party/blink/renderer/core/resize_observer/resize_observer_entry.cc +++ b/third_party/blink/renderer/core/resize_observer/resize_observer_entry.cc
@@ -30,21 +30,18 @@ LayoutSize(svg_graphics_element->GetBBox().Size()); content_rect_ = DOMRectReadOnly::FromFloatRect( FloatRect(FloatPoint(), FloatSize(bounding_box_size))); - if (RuntimeEnabledFeatures::ResizeObserverUpdatesEnabled()) { - ResizeObserverSize* size = ResizeObserverSize::Create( - bounding_box_size.Width(), bounding_box_size.Height()); - content_box_size_.push_back(size); - border_box_size_.push_back(size); - bounding_box_size.Scale(style.EffectiveZoom()); - FloatSize snapped_device_pixel_content_box = - ResizeObserverUtilities::ComputeSnappedDevicePixelContentBox( - bounding_box_size, layout_object, style); - ResizeObserverSize* device_pixel_content_box_size = - ResizeObserverSize::Create( - snapped_device_pixel_content_box.Width(), - snapped_device_pixel_content_box.Height()); - device_pixel_content_box_size_.push_back(device_pixel_content_box_size); - } + ResizeObserverSize* size = ResizeObserverSize::Create( + bounding_box_size.Width(), bounding_box_size.Height()); + content_box_size_.push_back(size); + border_box_size_.push_back(size); + bounding_box_size.Scale(style.EffectiveZoom()); + FloatSize snapped_device_pixel_content_box = + ResizeObserverUtilities::ComputeSnappedDevicePixelContentBox( + bounding_box_size, layout_object, style); + ResizeObserverSize* device_pixel_content_box_size = + ResizeObserverSize::Create(snapped_device_pixel_content_box.Width(), + snapped_device_pixel_content_box.Height()); + device_pixel_content_box_size_.push_back(device_pixel_content_box_size); } else if (layout_object->IsBox()) { LayoutBox* layout_box = target->GetLayoutBox(); LayoutRect content_rect( @@ -53,42 +50,37 @@ content_rect_ = ResizeObserverUtilities::ZoomAdjustedLayoutRect(content_rect, style); - if (RuntimeEnabledFeatures::ResizeObserverUpdatesEnabled()) { - FloatSize content_box = ResizeObserverUtilities::ComputeZoomAdjustedBox( - ResizeObserverBoxOptions::ContentBox, layout_object, style); - FloatSize border_box = ResizeObserverUtilities::ComputeZoomAdjustedBox( - ResizeObserverBoxOptions::BorderBox, layout_object, style); - FloatSize device_pixel_content_box = - ResizeObserverUtilities::ComputeZoomAdjustedBox( - ResizeObserverBoxOptions::DevicePixelContentBox, layout_object, - style); + FloatSize content_box = ResizeObserverUtilities::ComputeZoomAdjustedBox( + ResizeObserverBoxOptions::ContentBox, layout_object, style); + FloatSize border_box = ResizeObserverUtilities::ComputeZoomAdjustedBox( + ResizeObserverBoxOptions::BorderBox, layout_object, style); + FloatSize device_pixel_content_box = + ResizeObserverUtilities::ComputeZoomAdjustedBox( + ResizeObserverBoxOptions::DevicePixelContentBox, layout_object, + style); - ResizeObserverSize* device_pixel_content_box_size = - ResizeObserverSize::Create(device_pixel_content_box.Width(), - device_pixel_content_box.Height()); - ResizeObserverSize* content_box_size = ResizeObserverSize::Create( - content_box.Width(), content_box.Height()); - ResizeObserverSize* border_box_size = - ResizeObserverSize::Create(border_box.Width(), border_box.Height()); + ResizeObserverSize* device_pixel_content_box_size = + ResizeObserverSize::Create(device_pixel_content_box.Width(), + device_pixel_content_box.Height()); + ResizeObserverSize* content_box_size = + ResizeObserverSize::Create(content_box.Width(), content_box.Height()); + ResizeObserverSize* border_box_size = + ResizeObserverSize::Create(border_box.Width(), border_box.Height()); - content_box_size_.push_back(content_box_size); - border_box_size_.push_back(border_box_size); - device_pixel_content_box_size_.push_back(device_pixel_content_box_size); - } + content_box_size_.push_back(content_box_size); + border_box_size_.push_back(border_box_size); + device_pixel_content_box_size_.push_back(device_pixel_content_box_size); } } if (!content_rect_) content_rect_ = DOMRectReadOnly::FromFloatRect( FloatRect(FloatPoint(LayoutPoint()), FloatSize(LayoutSize()))); - if (RuntimeEnabledFeatures::ResizeObserverUpdatesEnabled()) { - if (content_box_size_.size() == 0) - content_box_size_.push_back(ResizeObserverSize::Create(0, 0)); - if (border_box_size_.size() == 0) - border_box_size_.push_back(ResizeObserverSize::Create(0, 0)); - if (device_pixel_content_box_size_.size() == 0) { - device_pixel_content_box_size_.push_back( - ResizeObserverSize::Create(0, 0)); - } + if (content_box_size_.size() == 0) + content_box_size_.push_back(ResizeObserverSize::Create(0, 0)); + if (border_box_size_.size() == 0) + border_box_size_.push_back(ResizeObserverSize::Create(0, 0)); + if (device_pixel_content_box_size_.size() == 0) { + device_pixel_content_box_size_.push_back(ResizeObserverSize::Create(0, 0)); } }
diff --git a/third_party/blink/renderer/core/resize_observer/resize_observer_entry.idl b/third_party/blink/renderer/core/resize_observer/resize_observer_entry.idl index 4a4006c..398060e 100644 --- a/third_party/blink/renderer/core/resize_observer/resize_observer_entry.idl +++ b/third_party/blink/renderer/core/resize_observer/resize_observer_entry.idl
@@ -8,7 +8,7 @@ interface ResizeObserverEntry { readonly attribute Element target; readonly attribute DOMRectReadOnly contentRect; - [RuntimeEnabled=ResizeObserverUpdates] readonly attribute FrozenArray<ResizeObserverSize> contentBoxSize; - [RuntimeEnabled=ResizeObserverUpdates] readonly attribute FrozenArray<ResizeObserverSize> borderBoxSize; - [RuntimeEnabled=ResizeObserverUpdates] readonly attribute FrozenArray<ResizeObserverSize> devicePixelContentBoxSize; + readonly attribute FrozenArray<ResizeObserverSize> contentBoxSize; + readonly attribute FrozenArray<ResizeObserverSize> borderBoxSize; + readonly attribute FrozenArray<ResizeObserverSize> devicePixelContentBoxSize; };
diff --git a/third_party/blink/renderer/core/resize_observer/resize_observer_size.idl b/third_party/blink/renderer/core/resize_observer/resize_observer_size.idl index d043025..774a7d2 100644 --- a/third_party/blink/renderer/core/resize_observer/resize_observer_size.idl +++ b/third_party/blink/renderer/core/resize_observer/resize_observer_size.idl
@@ -5,8 +5,7 @@ // https://drafts.csswg.org/resize-observer-1/#resizeobserversize [ - Exposed=Window, - RuntimeEnabled=ResizeObserverUpdates + Exposed=Window ] interface ResizeObserverSize { readonly attribute unrestricted double inlineSize; readonly attribute unrestricted double blockSize;
diff --git a/third_party/blink/renderer/core/style/list_style_type_data.cc b/third_party/blink/renderer/core/style/list_style_type_data.cc index 16c299e..92f22d2 100644 --- a/third_party/blink/renderer/core/style/list_style_type_data.cc +++ b/third_party/blink/renderer/core/style/list_style_type_data.cc
@@ -4,10 +4,7 @@ #include "third_party/blink/renderer/core/style/list_style_type_data.h" -#include "third_party/blink/renderer/core/css/counter_style.h" #include "third_party/blink/renderer/core/css/css_value_id_mappings.h" -#include "third_party/blink/renderer/core/css/style_engine.h" -#include "third_party/blink/renderer/core/dom/document.h" #include "third_party/blink/renderer/core/dom/tree_scope.h" #include "third_party/blink/renderer/core/style/content_data.h" #include "third_party/blink/renderer/platform/runtime_enabled_features.h" @@ -47,7 +44,6 @@ void ListStyleTypeData::Trace(Visitor* visitor) const { visitor->Trace(tree_scope_); - visitor->Trace(counter_style_); } // static @@ -77,31 +73,4 @@ return CounterStyleNameToDeprecatedEnum(ListStyle()); } -bool ListStyleTypeData::IsCounterStyleReferenceValid(Document& document) const { - if (!IsCounterStyle()) { - DCHECK(!counter_style_); - return true; - } - - if (!counter_style_ || counter_style_->IsDirty()) - return false; - - // Even if the referenced counter style is clean, it may still be stale if new - // counter styles have been inserted, in which case the same (scope, name) now - // refers to a different counter style. So we make an extra lookup to verify. - return counter_style_ == - &document.GetStyleEngine().FindCounterStyleAcrossScopes( - GetCounterStyleName(), GetTreeScope()); -} - -const CounterStyle& ListStyleTypeData::GetCounterStyle( - Document& document) const { - DCHECK(IsCounterStyle()); - if (!IsCounterStyleReferenceValid(document)) { - counter_style_ = document.GetStyleEngine().FindCounterStyleAcrossScopes( - GetCounterStyleName(), GetTreeScope()); - } - return *counter_style_; -} - } // namespace blink
diff --git a/third_party/blink/renderer/core/style/list_style_type_data.h b/third_party/blink/renderer/core/style/list_style_type_data.h index 118f7985..3922b29 100644 --- a/third_party/blink/renderer/core/style/list_style_type_data.h +++ b/third_party/blink/renderer/core/style/list_style_type_data.h
@@ -11,8 +11,6 @@ namespace blink { -class CounterStyle; -class Document; class TreeScope; class ListStyleTypeData final : public GarbageCollected<ListStyleTypeData> { @@ -57,10 +55,6 @@ const TreeScope* GetTreeScope() const { return tree_scope_; } - // TODO(crbug.com/687225): Try not to pass a Document, which is cumbersome. - bool IsCounterStyleReferenceValid(Document&) const; - const CounterStyle& GetCounterStyle(Document&) const; - EListStyleType ToDeprecatedListStyleTypeEnum() const; private: @@ -69,10 +63,6 @@ // The tree scope for looking up the custom counter style name Member<const TreeScope> tree_scope_; - - // The CounterStyle that we are using. The reference is updated on demand. - // Note: this is NOT part of the computed value of 'list-style-type'. - mutable Member<const CounterStyle> counter_style_; }; } // namespace blink
diff --git a/third_party/blink/renderer/modules/BUILD.gn b/third_party/blink/renderer/modules/BUILD.gn index 55e15af..a1744c3 100644 --- a/third_party/blink/renderer/modules/BUILD.gn +++ b/third_party/blink/renderer/modules/BUILD.gn
@@ -130,7 +130,7 @@ "//third_party/blink/renderer/modules/mediasource", "//third_party/blink/renderer/modules/mediastream", "//third_party/blink/renderer/modules/media", - "//third_party/blink/renderer/modules/webrtc", + "//third_party/blink/renderer/modules/modalclosewatcher", "//third_party/blink/renderer/modules/native_io", "//third_party/blink/renderer/modules/navigatorcontentutils", "//third_party/blink/renderer/modules/netinfo", @@ -168,6 +168,7 @@ "//third_party/blink/renderer/modules/webgpu", "//third_party/blink/renderer/modules/webid", "//third_party/blink/renderer/modules/webmidi", + "//third_party/blink/renderer/modules/webrtc", "//third_party/blink/renderer/modules/webshare", "//third_party/blink/renderer/modules/websockets", "//third_party/blink/renderer/modules/webtransport",
diff --git a/third_party/blink/renderer/modules/accessibility/ax_node_object.cc b/third_party/blink/renderer/modules/accessibility/ax_node_object.cc index c09f88f..9abe035 100644 --- a/third_party/blink/renderer/modules/accessibility/ax_node_object.cc +++ b/third_party/blink/renderer/modules/accessibility/ax_node_object.cc
@@ -3168,10 +3168,13 @@ } void AXNodeObject::AddValidationMessageChild() { - if (IsWebArea()) { - AddChildAndCheckIncluded( - AXObjectCache().ValidationMessageObjectIfInvalid()); - } + DCHECK(IsWebArea()) << "Validation message must be child of root"; + // First child requirement enables easy checking to see if a children changed + // event is needed in AXObjectCacheImpl::ValidationMessageObjectIfInvalid(). + DCHECK_EQ(children_.size(), 0U) + << "Validation message must be the first child"; + AddChildAndCheckIncluded(AXObjectCache().ValidationMessageObjectIfInvalid( + /* suppress children changed, already processing that */ false)); } void AXNodeObject::AddImageMapChildren() { @@ -3277,6 +3280,12 @@ return; } + // If validation message exists, always make it the first child of the root, + // to enable easy checking of whether it's a known child of the root. + if (IsWebArea()) + AddValidationMessageChild(); + CHECK_ATTACHED(); + if (IsHtmlTable()) AddTableChildren(); else if (ShouldUseLayoutObjectTraversalForChildren()) @@ -3291,9 +3300,6 @@ AddImageMapChildren(); CHECK_ATTACHED(); - AddValidationMessageChild(); - CHECK_ATTACHED(); - AddAccessibleNodeChildren(); CHECK_ATTACHED(); @@ -3896,7 +3902,7 @@ if (this != AXObjectCache().FocusedObject()) return nullptr; - return AXObjectCache().ValidationMessageObjectIfInvalid(); + return AXObjectCache().ValidationMessageObjectIfInvalid(true); } // According to the standard, the figcaption should only be the first or
diff --git a/third_party/blink/renderer/modules/accessibility/ax_object.cc b/third_party/blink/renderer/modules/accessibility/ax_object.cc index b54520f..452c154 100644 --- a/third_party/blink/renderer/modules/accessibility/ax_object.cc +++ b/third_party/blink/renderer/modules/accessibility/ax_object.cc
@@ -1811,7 +1811,9 @@ cached_live_region_root_ = nullptr; } else { // Is a live region root if this or an ancestor is a live region. - DCHECK(parent_); + DCHECK(parent_) << "No parent and not a document, node=" << GetNode(); + if (!parent_) + return; cached_live_region_root_ = IsLiveRegionRoot() ? const_cast<AXObject*>(this) : parent_->LiveRegionRoot(); } @@ -3310,7 +3312,9 @@ AXObject* AXObject::ChildAtIncludingIgnored(int index) const { DCHECK_GE(index, 0); - DCHECK_LT(index, ChildCountIncludingIgnored()); + DCHECK_LE(index, ChildCountIncludingIgnored()); + if (index >= ChildCountIncludingIgnored()) + return nullptr; return ChildrenIncludingIgnored()[index]; }
diff --git a/third_party/blink/renderer/modules/accessibility/ax_object_cache_impl.cc b/third_party/blink/renderer/modules/accessibility/ax_object_cache_impl.cc index 1e918e6..6d8aeb1f 100644 --- a/third_party/blink/renderer/modules/accessibility/ax_object_cache_impl.cc +++ b/third_party/blink/renderer/modules/accessibility/ax_object_cache_impl.cc
@@ -2133,22 +2133,25 @@ if (validation_message_axid_) { message_ax_object = ObjectFromAXID(validation_message_axid_); } - if (!message_ax_object) { + if (message_ax_object) { + DCHECK(!message_ax_object->IsDetached()); + message_ax_object->SetParent(Root()); // Reattach to parent (root). + } else { message_ax_object = MakeGarbageCollected<AXValidationMessage>(*this); DCHECK(message_ax_object); // Cache the validation message container for reuse. validation_message_axid_ = AssociateAXID(message_ax_object); - message_ax_object->Init(Root()); // Validation message alert object is a child of the document, as not all // form controls can have a child. Also, there are form controls such as // listbox that technically can have children, but they are probably not // expected to have alerts within AT client code. - ChildrenChanged(document_); + message_ax_object->Init(Root()); } return message_ax_object; } -AXObject* AXObjectCacheImpl::ValidationMessageObjectIfInvalid() { +AXObject* AXObjectCacheImpl::ValidationMessageObjectIfInvalid( + bool notify_children_changed) { Element* focused_element = document_->FocusedElement(); if (focused_element) { ListedElement* form_control = ListedElement::From(*focused_element); @@ -2169,8 +2172,14 @@ AOMRelationProperty::kErrorMessage); if (!override_native_validation_message) { AXObject* message = GetOrCreateValidationMessageObject(); - if (message && !was_validation_message_already_created) + DCHECK(message); + DCHECK(!message->IsDetached()); + if (notify_children_changed && + Root()->FirstChildIncludingIgnored() != message) { + // Only notify children changed if not already processing new root + // children, and the root doesn't already have this child. ChildrenChanged(document_); + } return message; } } @@ -2217,7 +2226,8 @@ << "Unclean document at lifecycle " << document->Lifecycle().ToString(); #endif // DCHECK_IS_ON() - AXObject* message_ax_object = ValidationMessageObjectIfInvalid(); + AXObject* message_ax_object = ValidationMessageObjectIfInvalid( + /* Fire children changed on root if it gains message child */ true); if (message_ax_object) MarkAXObjectDirty(message_ax_object, false); // May be invisible now.
diff --git a/third_party/blink/renderer/modules/accessibility/ax_object_cache_impl.h b/third_party/blink/renderer/modules/accessibility/ax_object_cache_impl.h index 74f3c1b4..a75280a 100644 --- a/third_party/blink/renderer/modules/accessibility/ax_object_cache_impl.h +++ b/third_party/blink/renderer/modules/accessibility/ax_object_cache_impl.h
@@ -282,8 +282,9 @@ // granted, it only applies to the next event received. void RequestAOMEventListenerPermission(); - // For built-in HTML form validation messages. - AXObject* ValidationMessageObjectIfInvalid(); + // For built-in HTML form validation messages. Set notify_children_changed to + // true if not already processing changed children. + AXObject* ValidationMessageObjectIfInvalid(bool notify_children_changed); WebAXAutofillState GetAutofillState(AXID id) const; void SetAutofillState(AXID id, WebAXAutofillState state);
diff --git a/third_party/blink/renderer/modules/event_target_modules_names.json5 b/third_party/blink/renderer/modules/event_target_modules_names.json5 index 5ba2efe30..e0bcc950 100644 --- a/third_party/blink/renderer/modules/event_target_modules_names.json5 +++ b/third_party/blink/renderer/modules/event_target_modules_names.json5
@@ -34,6 +34,7 @@ "MediaDevices", "MediaStream", "MediaStreamTrack", + "ModalCloseWatcher", "RTCDTMFSender", "RTCDataChannel", "RTCDtlsTransport",
diff --git a/third_party/blink/renderer/modules/modalclosewatcher/BUILD.gn b/third_party/blink/renderer/modules/modalclosewatcher/BUILD.gn new file mode 100644 index 0000000..9f3262a --- /dev/null +++ b/third_party/blink/renderer/modules/modalclosewatcher/BUILD.gn
@@ -0,0 +1,12 @@ +# Copyright 2021 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("//third_party/blink/renderer/modules/modules.gni") + +blink_modules_sources("modalclosewatcher") { + sources = [ + "modal_close_watcher.cc", + "modal_close_watcher.h", + ] +}
diff --git a/third_party/blink/renderer/modules/modalclosewatcher/OWNERS b/third_party/blink/renderer/modules/modalclosewatcher/OWNERS new file mode 100644 index 0000000..dec8dab --- /dev/null +++ b/third_party/blink/renderer/modules/modalclosewatcher/OWNERS
@@ -0,0 +1,2 @@ +japhet@chromium.org +domenic@chromium.org
diff --git a/third_party/blink/renderer/modules/modalclosewatcher/idls.gni b/third_party/blink/renderer/modules/modalclosewatcher/idls.gni new file mode 100644 index 0000000..7f81363 --- /dev/null +++ b/third_party/blink/renderer/modules/modalclosewatcher/idls.gni
@@ -0,0 +1,5 @@ +# Copyright 2021 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. + +modules_idl_files = [ "modal_close_watcher.idl" ]
diff --git a/third_party/blink/renderer/modules/modalclosewatcher/modal_close_watcher.cc b/third_party/blink/renderer/modules/modalclosewatcher/modal_close_watcher.cc new file mode 100644 index 0000000..dcb117d --- /dev/null +++ b/third_party/blink/renderer/modules/modalclosewatcher/modal_close_watcher.cc
@@ -0,0 +1,119 @@ +// Copyright 2021 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 "third_party/blink/renderer/modules/modalclosewatcher/modal_close_watcher.h" + +#include "third_party/blink/renderer/core/dom/events/event.h" +#include "third_party/blink/renderer/core/events/keyboard_event.h" +#include "third_party/blink/renderer/core/frame/local_dom_window.h" +#include "third_party/blink/renderer/modules/event_target_modules.h" +#include "third_party/blink/renderer/platform/keyboard_codes.h" + +namespace blink { + +const char ModalCloseWatcher::WatcherStack::kSupplementName[] = + "ModalCloseWatcher::WatcherStack"; + +ModalCloseWatcher::WatcherStack& ModalCloseWatcher::WatcherStack::From( + LocalDOMWindow& window) { + auto* stack = Supplement<LocalDOMWindow>::From<WatcherStack>(window); + if (!stack) { + stack = MakeGarbageCollected<WatcherStack>(window); + Supplement<LocalDOMWindow>::ProvideTo(window, stack); + } + return *stack; +} + +ModalCloseWatcher::WatcherStack::WatcherStack(LocalDOMWindow& window) + : Supplement<LocalDOMWindow>(window) {} + +void ModalCloseWatcher::WatcherStack::Add(ModalCloseWatcher* watcher) { + if (watchers_.IsEmpty()) { + GetSupplementable()->addEventListener(event_type_names::kKeyup, this); + } + watchers_.insert(watcher); +} + +void ModalCloseWatcher::WatcherStack::Remove(ModalCloseWatcher* watcher) { + watchers_.erase(watcher); + if (watchers_.IsEmpty()) { + GetSupplementable()->removeEventListener(event_type_names::kKeyup, this); + } +} + +void ModalCloseWatcher::WatcherStack::Trace(Visitor* visitor) const { + NativeEventListener::Trace(visitor); + Supplement<LocalDOMWindow>::Trace(visitor); + visitor->Trace(watchers_); +} + +void ModalCloseWatcher::WatcherStack::Invoke(ExecutionContext*, Event* e) { + DCHECK(!watchers_.IsEmpty()); + KeyboardEvent* event = To<KeyboardEvent>(e); + if (event->isTrusted() && event->keyCode() == VKEY_ESCAPE) + Signal(); +} + +ModalCloseWatcher* ModalCloseWatcher::Create(ScriptState* script_state, + ExceptionState& exception_state) { + LocalDOMWindow* window = LocalDOMWindow::From(script_state); + WatcherStack& stack = WatcherStack::From(*window); + if (stack.HasActiveWatcher() && + !LocalFrame::HasTransientUserActivation(window->GetFrame())) { + exception_state.ThrowDOMException( + DOMExceptionCode::kNotAllowedError, + "Creating more than one ModalCloseWatcher at a time requires a user " + "activation."); + return nullptr; + } + + ModalCloseWatcher* watcher = MakeGarbageCollected<ModalCloseWatcher>(window); + stack.Add(watcher); + return watcher; +} + +ModalCloseWatcher::ModalCloseWatcher(LocalDOMWindow* window) + : ExecutionContextClient(window) {} + +void ModalCloseWatcher::signalClosed() { + if (IsClosed() || dispatching_beforeclose_) + return; + Event& before_close_event = + *Event::CreateCancelable(event_type_names::kBeforeclose); + { + base::AutoReset<bool> scoped_committing(&dispatching_beforeclose_, true); + DispatchEvent(before_close_event); + } + if (before_close_event.defaultPrevented()) { + state_ = State::kModal; + // TODO(japhet): Make an async dialog here. + } + Close(); +} + +void ModalCloseWatcher::Close() { + if (IsClosed()) + return; + WatcherStack::From(*DomWindow()).Remove(this); + state_ = State::kClosed; + DispatchEvent(*Event::Create(event_type_names::kClose)); +} + +void ModalCloseWatcher::destroy() { + if (IsClosed()) + return; + WatcherStack::From(*DomWindow()).Remove(this); + state_ = State::kClosed; +} + +const AtomicString& ModalCloseWatcher::InterfaceName() const { + return event_target_names::kModalCloseWatcher; +} + +void ModalCloseWatcher::Trace(Visitor* visitor) const { + EventTargetWithInlineData::Trace(visitor); + ExecutionContextClient::Trace(visitor); +} + +} // namespace blink
diff --git a/third_party/blink/renderer/modules/modalclosewatcher/modal_close_watcher.h b/third_party/blink/renderer/modules/modalclosewatcher/modal_close_watcher.h new file mode 100644 index 0000000..fdefc2c --- /dev/null +++ b/third_party/blink/renderer/modules/modalclosewatcher/modal_close_watcher.h
@@ -0,0 +1,76 @@ +// Copyright 2021 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 THIRD_PARTY_BLINK_RENDERER_MODULES_MODALCLOSEWATCHER_MODAL_CLOSE_WATCHER_H_ +#define THIRD_PARTY_BLINK_RENDERER_MODULES_MODALCLOSEWATCHER_MODAL_CLOSE_WATCHER_H_ + +#include "third_party/blink/renderer/core/dom/events/event_target.h" +#include "third_party/blink/renderer/core/dom/events/native_event_listener.h" +#include "third_party/blink/renderer/core/execution_context/execution_context_lifecycle_observer.h" +#include "third_party/blink/renderer/platform/heap/collection_support/heap_linked_hash_set.h" +#include "third_party/blink/renderer/platform/supplementable.h" + +namespace blink { + +class ModalCloseWatcher final : public EventTargetWithInlineData, + public ExecutionContextClient { + DEFINE_WRAPPERTYPEINFO(); + + public: + static ModalCloseWatcher* Create(ScriptState*, ExceptionState&); + explicit ModalCloseWatcher(LocalDOMWindow*); + void Trace(Visitor*) const override; + + bool IsClosed() const { return state_ == State::kClosed; } + + void signalClosed(); + void destroy(); + + DEFINE_ATTRIBUTE_EVENT_LISTENER(beforeclose, kBeforeclose) + DEFINE_ATTRIBUTE_EVENT_LISTENER(close, kClose) + + // EventTargetWithInlineData overrides: + const AtomicString& InterfaceName() const final; + ExecutionContext* GetExecutionContext() const final { + return ExecutionContextClient::GetExecutionContext(); + } + + private: + void Close(); + + // If multiple ModalCloseWatchers are active in a given window, they form a + // stack, and a close signal will pop the top watcher. If the stack is empty, + // the first ModalCloseWatcher is "free", but creating a new + // ModalCloseWatcher when the stack is non-empty requires a user activation. + class WatcherStack final : public NativeEventListener, + public Supplement<LocalDOMWindow> { + public: + static const char kSupplementName[]; + + static WatcherStack& From(LocalDOMWindow&); + explicit WatcherStack(LocalDOMWindow&); + + void Add(ModalCloseWatcher*); + void Remove(ModalCloseWatcher*); + bool HasActiveWatcher() { return !watchers_.IsEmpty(); } + + void Trace(Visitor*) const final; + + private: + // NativeEventListener override: + void Invoke(ExecutionContext*, Event*) final; + + void Signal() { watchers_.back()->signalClosed(); } + + HeapLinkedHashSet<Member<ModalCloseWatcher>> watchers_; + }; + + enum class State { kActive, kModal, kClosed }; + State state_ = State::kActive; + bool dispatching_beforeclose_ = false; +}; + +} // namespace blink + +#endif // THIRD_PARTY_BLINK_RENDERER_MODULES_MODALCLOSEWATCHER_MODAL_CLOSE_WATCHER_H_
diff --git a/third_party/blink/renderer/modules/modalclosewatcher/modal_close_watcher.idl b/third_party/blink/renderer/modules/modalclosewatcher/modal_close_watcher.idl new file mode 100644 index 0000000..25c4581 --- /dev/null +++ b/third_party/blink/renderer/modules/modalclosewatcher/modal_close_watcher.idl
@@ -0,0 +1,16 @@ +// Copyright 2021 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. + +[ + Exposed=Window, + RuntimeEnabled=ModalCloseWatcher +] interface ModalCloseWatcher { + [CallWith=ScriptState, RaisesException] constructor(); + + void signalClosed(); + void destroy(); + + attribute EventHandler onbeforeclose; + attribute EventHandler onclose; +};
diff --git a/third_party/blink/renderer/modules/modules_idl_files.gni b/third_party/blink/renderer/modules/modules_idl_files.gni index e7828a8..f756c807 100644 --- a/third_party/blink/renderer/modules/modules_idl_files.gni +++ b/third_party/blink/renderer/modules/modules_idl_files.gni
@@ -96,6 +96,7 @@ "//third_party/blink/renderer/modules/mediasession/idls.gni", "//third_party/blink/renderer/modules/mediasource/idls.gni", "//third_party/blink/renderer/modules/mediastream/idls.gni", + "//third_party/blink/renderer/modules/modalclosewatcher/idls.gni", "//third_party/blink/renderer/modules/native_io/idls.gni", "//third_party/blink/renderer/modules/navigatorcontentutils/idls.gni", "//third_party/blink/renderer/modules/netinfo/idls.gni",
diff --git a/third_party/blink/renderer/platform/heap/v8_wrapper/thread_state.cc b/third_party/blink/renderer/platform/heap/v8_wrapper/thread_state.cc index 5bf91c1..16802b9 100644 --- a/third_party/blink/renderer/platform/heap/v8_wrapper/thread_state.cc +++ b/third_party/blink/renderer/platform/heap/v8_wrapper/thread_state.cc
@@ -19,13 +19,13 @@ ThreadState::main_thread_state_storage_[sizeof(ThreadState)]; // static -ThreadState* ThreadState::AttachMainThread(v8::CppHeap& cpp_heap) { - return new (main_thread_state_storage_) ThreadState(cpp_heap); +ThreadState* ThreadState::AttachMainThread() { + return new (main_thread_state_storage_) ThreadState(); } // static -ThreadState* ThreadState::AttachCurrentThread(v8::CppHeap& cpp_heap) { - return new ThreadState(cpp_heap); +ThreadState* ThreadState::AttachCurrentThread() { + return new ThreadState(); } // static @@ -35,10 +35,7 @@ delete state; } -ThreadState::ThreadState(v8::CppHeap& cpp_heap) - : allocation_handle_(cpp_heap.GetAllocationHandle()), - cpp_heap_(cpp_heap), - thread_id_(CurrentThread()) {} +ThreadState::ThreadState() : thread_id_(CurrentThread()) {} ThreadState::~ThreadState() { DCHECK(!IsMainThread()); @@ -46,7 +43,7 @@ } void ThreadState::RunTerminationGC() { - cpp_heap_.Terminate(); + cpp_heap_->Terminate(); } void ThreadState::NotifyGarbageCollection() {
diff --git a/third_party/blink/renderer/platform/heap/v8_wrapper/thread_state.h b/third_party/blink/renderer/platform/heap/v8_wrapper/thread_state.h index 0d1d9e0..f9b8af2 100644 --- a/third_party/blink/renderer/platform/heap/v8_wrapper/thread_state.h +++ b/third_party/blink/renderer/platform/heap/v8_wrapper/thread_state.h
@@ -12,6 +12,7 @@ #include "third_party/blink/renderer/platform/wtf/hash_set.h" #include "third_party/blink/renderer/platform/wtf/thread_specific.h" #include "third_party/blink/renderer/platform/wtf/threading.h" +#include "v8-profiler.h" #include "v8/include/cppgc/prefinalizer.h" #include "v8/include/v8-cppgc.h" #include "v8/include/v8.h" @@ -24,6 +25,10 @@ class AllocationHandle; } // namespace cppgc +namespace v8 { +class EmbedderGraph; +} // namespace v8 + namespace blink { #define USING_PRE_FINALIZER(Class, PreFinalizer) \ @@ -52,6 +57,10 @@ class ThreadStateFor; class ThreadState; +using V8BuildEmbedderGraphCallback = void (*)(v8::Isolate*, + v8::EmbedderGraph*, + void*); + // Used to observe garbage collection events. The observer is imprecise wrt. to // garbage collection internals, i.e., it is not guaranteed that a garbage // collection is already finished. The observer guarantees that a full garbage @@ -83,21 +92,28 @@ } // Attaches a ThreadState to the main-thread. - static ThreadState* AttachMainThread(v8::CppHeap&); + static ThreadState* AttachMainThread(); // Attaches a ThreadState to the currently running thread. Must not be the // main thread and must be called after AttachMainThread(). - static ThreadState* AttachCurrentThread(v8::CppHeap&); + static ThreadState* AttachCurrentThread(); static void DetachCurrentThread(); + void AttachToIsolate(v8::Isolate* isolate, V8BuildEmbedderGraphCallback) { + isolate_ = isolate; + cpp_heap_ = isolate->GetCppHeap(); + allocation_handle_ = &cpp_heap_->GetAllocationHandle(); + } + + void DetachFromIsolate() { + // No-op for the library implementation. + // TODO(1056170): Remove when removing Oilpan from Blink. + } + ALWAYS_INLINE cppgc::AllocationHandle& allocation_handle() const { - return allocation_handle_; + return *allocation_handle_; } - ALWAYS_INLINE v8::CppHeap& cpp_heap() const { return cpp_heap_; } - ALWAYS_INLINE v8::Isolate* GetIsolate() const { - // TODO(1056170): Refer to cpp_heap_ once getter for v8::Isolate is - // implemented. - return nullptr; - } + ALWAYS_INLINE v8::CppHeap& cpp_heap() const { return *cpp_heap_; } + ALWAYS_INLINE v8::Isolate* GetIsolate() const { return isolate_; } // Forced garbage collection for testing: // @@ -108,11 +124,6 @@ // TODO(1056170): Implement. } - void DetachFromIsolate() { - // No-op for the library implementation. - // TODO(1056170): Remove when removing Oilpan from Blink. - } - void RunTerminationGC(); void SafePoint(BlinkGC::StackState) { @@ -140,8 +151,9 @@ // Handle is the most frequently accessed field as it is required for // MakeGarbageCollected(). - cppgc::AllocationHandle& allocation_handle_; - v8::CppHeap& cpp_heap_; + cppgc::AllocationHandle* allocation_handle_ = nullptr; + v8::CppHeap* cpp_heap_ = nullptr; + v8::Isolate* isolate_ = nullptr; base::PlatformThreadId thread_id_; size_t gc_age_ = 0; WTF::HashSet<BlinkGCObserver*> observers_;
diff --git a/third_party/blink/renderer/platform/runtime_enabled_features.json5 b/third_party/blink/renderer/platform/runtime_enabled_features.json5 index 9251097..621dd6a 100644 --- a/third_party/blink/renderer/platform/runtime_enabled_features.json5 +++ b/third_party/blink/renderer/platform/runtime_enabled_features.json5
@@ -1315,6 +1315,10 @@ name: "MobileLayoutTheme", }, { + name: "ModalCloseWatcher", + status: "test", + }, + { name: "ModuleServiceWorker", status: "test", }, @@ -1696,10 +1700,6 @@ status: "stable", }, { - name: "ResizeObserverUpdates", - status: "stable", - }, - { name: "RestrictAutomaticLazyFrameLoadingToDataSaver", depends_on: ["AutomaticLazyFrameLoading"], status: "stable",
diff --git a/third_party/blink/web_tests/FlagExpectations/force-renderer-accessibility b/third_party/blink/web_tests/FlagExpectations/force-renderer-accessibility index 0f57f25..005c496 100644 --- a/third_party/blink/web_tests/FlagExpectations/force-renderer-accessibility +++ b/third_party/blink/web_tests/FlagExpectations/force-renderer-accessibility
@@ -51,7 +51,6 @@ fast/events/touch/compositor-touch-hit-rects-animation.html [ Crash ] fast/events/touch/gesture/gesture-tap-frame-move.html [ Crash ] fast/forms/select-popup/popup-menu-update-from-element.html [ Crash ] -fast/forms/validation-message-crash.html [ Crash ] html/details_summary/details-add-summary.html [ Crash ] http/tests/devtools/console/console-big-array.js [ Crash ] http/tests/devtools/console/console-dir-es6.js [ Crash ]
diff --git a/third_party/blink/web_tests/NeverFixTests b/third_party/blink/web_tests/NeverFixTests index 6a7da0a..897727cd 100644 --- a/third_party/blink/web_tests/NeverFixTests +++ b/third_party/blink/web_tests/NeverFixTests
@@ -181,9 +181,6 @@ # aren't critical to run in this mode. virtual/threaded/printing/setPrinting.html [ Skip ] virtual/threaded/printing/width-overflow.html [ Skip ] - -# See crbug.com/522326 -external/wpt/html/obsolete/requirements-for-implementations/the-marquee-element-0/marquee-events.html [ Skip ] # We don't allow to access external hosts in layout tests. external/wpt/html/the-xhtml-syntax/parsing-xhtml-documents/support/xhtml-mathml-dtd-entity.htm [ Skip ]
diff --git a/third_party/blink/web_tests/TestExpectations b/third_party/blink/web_tests/TestExpectations index 2dac7575..fcc6d61 100644 --- a/third_party/blink/web_tests/TestExpectations +++ b/third_party/blink/web_tests/TestExpectations
@@ -2737,18 +2737,10 @@ crbug.com/626703 external/wpt/css/css-writing-modes/writing-mode-vlr-001-manual.html [ Skip ] crbug.com/626703 external/wpt/css/css-writing-modes/writing-mode-vlr-008-manual.html [ Skip ] crbug.com/626703 external/wpt/css/css-writing-modes/writing-mode-vlr-table-002-manual.html [ Skip ] -crbug.com/626703 external/wpt/css/css-sizing/image-min-max-content-intrinsic-size-change-001.html [ Failure ] crbug.com/626703 external/wpt/xhr/event-readystatechange-loaded.any.worker.html [ Timeout Failure ] -crbug.com/626703 external/wpt/css/css-sizing/image-min-max-content-intrinsic-size-change-003.html [ Failure ] -crbug.com/626703 external/wpt/css/css-sizing/image-min-max-content-intrinsic-size-change-002.html [ Failure ] -crbug.com/626703 external/wpt/css/css-sizing/image-min-max-content-intrinsic-size-change-006.html [ Failure ] -crbug.com/626703 external/wpt/css/css-sizing/image-min-max-content-intrinsic-size-change-004.html [ Failure ] -crbug.com/626703 external/wpt/css/css-sizing/image-min-max-content-intrinsic-size-change-007.html [ Failure ] crbug.com/626703 external/wpt/css/css-text/text-transform/text-transform-multiple-001.html [ Failure ] crbug.com/626703 external/wpt/css/css-lists/li-value-counter-reset-001.html [ Failure ] crbug.com/626703 external/wpt/xhr/event-readystatechange-loaded.any.html [ Timeout Failure ] -crbug.com/626703 external/wpt/css/css-sizing/image-min-max-content-intrinsic-size-change-005.html [ Failure ] -crbug.com/626703 external/wpt/css/css-sizing/image-min-max-content-intrinsic-size-change-008.html [ Failure ] crbug.com/626703 external/wpt/css/css-text/overflow-wrap/overflow-wrap-normal-keep-all-001.html [ Failure ] crbug.com/626703 external/wpt/html/semantics/embedded-content/media-elements/src_object_blob.html [ Timeout ] crbug.com/626703 external/wpt/css/css-lists/list-item-definition.html [ Failure ] @@ -5729,6 +5721,9 @@ crbug.com/893869 css3/masking/mask-repeat-space-padding.html [ Failure Pass ] crbug.com/1155125 [ Linux ] http/tests/history/replacestate-post-to-get-2.html [ Pass Timeout ] +# V8 roll +crbug.com/961059 fast/workers/worker-shared-asm-buffer.html [ Pass Failure ] + # DevTools roll crbug.com/1134103 http/tests/devtools/unit/view-location.js [ Skip ] @@ -5739,3 +5734,6 @@ crbug.com/1171331 [ Mac ] tables/mozilla_expected_failures/bugs/bug89315.html [ Failure Pass ] crbug.com/1168785 [ Mac ] virtual/threaded-prefer-compositing/fast/scrolling/autoscroll-latch-clicked-node-if-parent-unscrollable.html [ Timeout ] + +# Sheriff 2021-01-29 +crbug.com/1172437 [ Win10 ] svg/hixie/perf/004.xml [ Timeout Pass ] \ No newline at end of file
diff --git a/third_party/blink/web_tests/android/ChromiumWPTExpectations b/third_party/blink/web_tests/android/ChromiumWPTExpectations index 3be40b2..ff76c20 100644 --- a/third_party/blink/web_tests/android/ChromiumWPTExpectations +++ b/third_party/blink/web_tests/android/ChromiumWPTExpectations
@@ -2587,7 +2587,6 @@ crbug.com/1050754 external/wpt/html/interaction/focus/focus-02.html [ Failure ] crbug.com/1050754 external/wpt/html/interaction/focus/sequential-focus-navigation-and-the-tabindex-attribute/focus-tabindex-order.html [ Failure ] crbug.com/1050754 external/wpt/html/interaction/focus/the-autofocus-attribute/update-the-rendering.html [ Failure ] -crbug.com/1050754 external/wpt/html/obsolete/requirements-for-implementations/the-marquee-element-0/marquee-events.html [ Timeout ] crbug.com/1050754 external/wpt/html/rendering/dimension-attributes.html [ Failure Pass ] crbug.com/1050754 external/wpt/html/rendering/non-replaced-elements/flow-content-0/dialog.html [ Failure ] crbug.com/1050754 external/wpt/html/rendering/non-replaced-elements/form-controls/button-style.html [ Failure Pass ]
diff --git a/third_party/blink/web_tests/android/WeblayerWPTExpectations b/third_party/blink/web_tests/android/WeblayerWPTExpectations index 6e7d1a27a..f065d32f 100644 --- a/third_party/blink/web_tests/android/WeblayerWPTExpectations +++ b/third_party/blink/web_tests/android/WeblayerWPTExpectations
@@ -2547,7 +2547,6 @@ crbug.com/1050754 external/wpt/html/interaction/focus/sequential-focus-navigation-and-the-tabindex-attribute/focus-tabindex-order.html [ Failure ] crbug.com/1050754 external/wpt/html/interaction/focus/the-autofocus-attribute/same-origin-autofocus.html [ Failure Pass ] crbug.com/1050754 external/wpt/html/interaction/focus/the-autofocus-attribute/update-the-rendering.html [ Failure ] -crbug.com/1050754 external/wpt/html/obsolete/requirements-for-implementations/the-marquee-element-0/marquee-events.html [ Timeout ] crbug.com/1050754 external/wpt/html/rendering/dimension-attributes.html [ Failure Pass ] crbug.com/1050754 external/wpt/html/rendering/non-replaced-elements/flow-content-0/dialog.html [ Failure ] crbug.com/1050754 external/wpt/html/rendering/non-replaced-elements/form-controls/button-style.html [ Failure Pass ]
diff --git a/third_party/blink/web_tests/android/WebviewWPTExpectations b/third_party/blink/web_tests/android/WebviewWPTExpectations index 71b0714..64b021b2 100644 --- a/third_party/blink/web_tests/android/WebviewWPTExpectations +++ b/third_party/blink/web_tests/android/WebviewWPTExpectations
@@ -2746,7 +2746,6 @@ crbug.com/1050754 external/wpt/html/interaction/focus/the-autofocus-attribute/same-origin-autofocus.html [ Failure ] crbug.com/1050754 external/wpt/html/interaction/focus/the-autofocus-attribute/spin-by-blocking-style-sheet.html [ Timeout ] crbug.com/1050754 external/wpt/html/interaction/focus/the-autofocus-attribute/update-the-rendering.html [ Failure ] -crbug.com/1050754 external/wpt/html/obsolete/requirements-for-implementations/the-marquee-element-0/marquee-events.html [ Timeout ] crbug.com/1050754 external/wpt/html/rendering/dimension-attributes.html [ Failure Pass ] crbug.com/1050754 external/wpt/html/rendering/non-replaced-elements/flow-content-0/dialog.html [ Failure ] crbug.com/1050754 external/wpt/html/rendering/non-replaced-elements/form-controls/button-style.html [ Failure Pass ]
diff --git a/third_party/blink/web_tests/external/WPT_BASE_MANIFEST_8.json b/third_party/blink/web_tests/external/WPT_BASE_MANIFEST_8.json index 30001eec..ccf0be9 100644 --- a/third_party/blink/web_tests/external/WPT_BASE_MANIFEST_8.json +++ b/third_party/blink/web_tests/external/WPT_BASE_MANIFEST_8.json
@@ -9914,13 +9914,6 @@ null, {} ] - ], - "single-touch-manual.html": [ - "1b47a64c157ac64f5760ebc0ad2fd114773cdea3", - [ - null, - {} - ] ] }, "uievents": { @@ -244090,7 +244083,7 @@ [] ], "TAOResponse.py": [ - "908b68861ae8262a18e083b026d14591d1e0206e", + "c25ccc03cb36a3d24409a4b3e6364d38f3a49305", [] ], "all_resource_types.htm": [ @@ -362846,8 +362839,8 @@ ] }, "the-marquee-element-0": { - "marquee-events.html": [ - "0d20c5102f17148ff3e5d1115e9a3fcfc7770bb3", + "marquee-events-historical.html": [ + "5780b90f04869ce4d14be864bda6ec93a2902ab5", [ null, {} @@ -376655,7 +376648,7 @@ ] ], "tasks.window.js": [ - "1588f2f889227f68acba9fb1f02494ba0f80a4bd", + "887adcb7393ee3bf3acfcba1a6a7d820f0ebb6ff", [ "html/webappapis/dynamic-markup-insertion/opening-the-input-stream/tasks.window.html", {} @@ -380356,6 +380349,13 @@ {} ] ], + "opacity-nonzero-to-zero.html": [ + "a5f3d213a2dd6d2f7639440dadd55dcc724f0075", + [ + null, + {} + ] + ], "opacity-zero-layout-and-visible.html": [ "af81ff2a625908a2686e6987e1a86409ff7eba07", [ @@ -380502,6 +380502,13 @@ {} ] ], + "transform-above-perspective-dynamic.html": [ + "fea65ca56ad6bbca11c5eece6fa7a059668ecb31", + [ + null, + {} + ] + ], "transform-change.html": [ "fd9657a71455629f856e53b8fa20aec1a3008e73", [ @@ -380536,6 +380543,13 @@ null, {} ] + ], + "visible-to-hidden.html": [ + "e30231f7fe8e7af505a88d97ccad0b2e35ef3e90", + [ + null, + {} + ] ] }, "lifecycle": { @@ -405136,8 +405150,8 @@ {} ] ], - "TAO-null-opaque-origin.sub.html": [ - "0a457637c5165481bf7a3bd1cbf023e9c07be751", + "TAO-null-opaque-origin.html": [ + "6548a7b9ad437407eaded2c6efc4974dec242ecd", [ null, {} @@ -420297,6 +420311,15 @@ } ] ], + "single-touch.html": [ + "a067bc13801928caf1bfc873a80208db4b9b0bbd", + [ + null, + { + "testdriver": true + } + ] + ], "touch-globaleventhandler-interface.html": [ "cb640444fa0b752c90d10fc73d32892facfb7dcf", [
diff --git a/third_party/blink/web_tests/external/wpt/html/obsolete/requirements-for-implementations/the-marquee-element-0/marquee-events-historical.html b/third_party/blink/web_tests/external/wpt/html/obsolete/requirements-for-implementations/the-marquee-element-0/marquee-events-historical.html new file mode 100644 index 0000000..5780b90 --- /dev/null +++ b/third_party/blink/web_tests/external/wpt/html/obsolete/requirements-for-implementations/the-marquee-element-0/marquee-events-historical.html
@@ -0,0 +1,32 @@ +<!DOCTYPE html> +<meta charset="utf-8"> +<title>Marquee events must not be implemented</title> +<link rel="help" href="https://html.spec.whatwg.org/multipage/multipage/obsolete.html#the-marquee-element"> +<link rel="help" href="https://github.com/whatwg/html/pull/6343"> +<script src="/resources/testharness.js"></script> +<script src="/resources/testharnessreport.js"></script> + +<div id="log"></div> +<marquee width="1" behavior="alternate"> </marquee> +<marquee width="1"> </marquee> +<marquee width="1" loop="2" behavior="alternate"> </marquee> +<marquee width="1" loop="2"> </marquee> + +<script> +test(() => { + assert_false("onstart" in HTMLMarqueeElement.prototype, "onstart"); + assert_false("onfinish" in HTMLMarqueeElement.prototype, "onfinish"); + assert_false("onbounce" in HTMLMarqueeElement.prototype, "onbounce"); +}, "Event handler IDL attributes must not be implemented"); + +// Because we use width="1" they will bounce and finish really fast +async_test(t => { + for (const m of document.querySelectorAll("marquee")) { + m.addEventListener("start", t.unreached_func(`start: ${m.outerHTML}`)); + m.addEventListener("finish", t.unreached_func(`finish: ${m.outerHTML}`)); + m.addEventListener("bounce", t.unreached_func(`bounce: ${m.outerHTML}`)); + } + + t.step_timeout(() => t.done(), 100); +}, "No events must be fired, at least during the first 100 ms"); +</script>
diff --git a/third_party/blink/web_tests/external/wpt/html/obsolete/requirements-for-implementations/the-marquee-element-0/marquee-events.html b/third_party/blink/web_tests/external/wpt/html/obsolete/requirements-for-implementations/the-marquee-element-0/marquee-events.html deleted file mode 100644 index 0d20c51..0000000 --- a/third_party/blink/web_tests/external/wpt/html/obsolete/requirements-for-implementations/the-marquee-element-0/marquee-events.html +++ /dev/null
@@ -1,71 +0,0 @@ -<!DOCTYPE html> -<meta charset="utf-8"> -<title>HTML Test: marquee-events</title> -<link rel="author" title="Intel" href="http://www.intel.com/"> -<link rel="help" href="https://html.spec.whatwg.org/multipage/multipage/obsolete.html#the-marquee-element"> -<script src="/resources/testharness.js"></script> -<script src="/resources/testharnessreport.js"></script> -<div id="log"></div> -<marquee id="test1" loop="2" width="1" behavior="alternate"> </marquee> -<marquee id="test2" loop="2" width="1"> </marquee> -<script> - var mq; - var t_start = async_test("marquee_events_start"); - var t_finish = async_test("marquee_events_finish"); - var t_bounce = async_test("marquee_events_bounce"); - var t_bounce2 = async_test("marquee_events_bounce2"); - var timeStamp = []; - var bounced = false; - - setup(function() { - mq = document.getElementById("test1"); - mq2 = document.getElementById("test2"); - }); - - mq.addEventListener("start", function(evt) { - t_start.step(function() { - timeStamp.push(evt.timeStamp); - assert_true(evt.isTrusted, "The onstart event is created by UA, it must be trusted."); - assert_equals(timeStamp.length, 1, "The onstart event should be fired firstly."); - assert_false(evt.bubbles, "The bubbles property of onstart event should be false."); - assert_false(evt.cancelable, "The cancelable property of onstart event should be false."); - assert_true(evt instanceof Event, "The onstart event must be the instance of Event interface."); - }); - t_start.done(); - }); - - mq.addEventListener("finish", function(evt) { - t_finish.step(function() { - timeStamp.push(evt.timeStamp); - assert_true(evt.isTrusted, "The onfinish event is created by UA, it must be trusted."); - assert_equals(timeStamp.length, 3, "The onfinish event should be fired lastly."); - assert_false(evt.bubbles, "The bubbles property of onfinish event should be false."); - assert_false(evt.cancelable, "The cancelable property of onfinish event should be false."); - assert_true(evt instanceof Event, "The onfinish event must be the instance of Event interface."); - }); - t_finish.done(); - }); - - mq.addEventListener("bounce", function(evt) { - t_bounce.step(function() { - timeStamp.push(evt.timeStamp); - assert_true(evt.isTrusted, "The onbounce event is created by UA, it must be trusted."); - assert_equals(timeStamp.length, 2, "The onbounce event should be fired secondly."); - assert_false(evt.bubbles, "The bubbles property of onbounce event should be false."); - assert_false(evt.cancelable, "The cancelable property of onbounce event should be false."); - assert_true(evt instanceof Event, "The onbounce event must be the instance of Event interface."); - }); - t_bounce.done(); - }); - - mq2.addEventListener("bounce", function(evt) { - bounced = true; - }); - - mq2.addEventListener("finish", function(evt) { - t_bounce2.step(function () { - assert_false(bounced, "The onbounce event should not be fired."); - }); - t_bounce2.done(); - }); -</script>
diff --git a/third_party/blink/web_tests/external/wpt/html/webappapis/dynamic-markup-insertion/opening-the-input-stream/tasks.window.js b/third_party/blink/web_tests/external/wpt/html/webappapis/dynamic-markup-insertion/opening-the-input-stream/tasks.window.js index 1588f2f..887adcb 100644 --- a/third_party/blink/web_tests/external/wpt/html/webappapis/dynamic-markup-insertion/opening-the-input-stream/tasks.window.js +++ b/third_party/blink/web_tests/external/wpt/html/webappapis/dynamic-markup-insertion/opening-the-input-stream/tasks.window.js
@@ -104,10 +104,3 @@ frame.contentWindow.onunhandledrejection = listener; window.onunhandledrejection = listener; }); - -taskTest("marquee start", (t, frame, open) => { - const doc = frame.contentDocument; - const marquee = doc.body.appendChild(doc.createElement("marquee")); - open(frame.contentDocument); - marquee.addEventListener("start", t.step_func_done()); -});
diff --git a/third_party/blink/web_tests/external/wpt/screen_enumeration/isExtended.tentative.https.window.js b/third_party/blink/web_tests/external/wpt/screen_enumeration/isExtended.tentative.https.window.js new file mode 100644 index 0000000..3c814ae3 --- /dev/null +++ b/third_party/blink/web_tests/external/wpt/screen_enumeration/isExtended.tentative.https.window.js
@@ -0,0 +1,11 @@ +// META: global=window +'use strict'; + +promise_test(async t => { + assert_equals(typeof self.screen.isExtended, 'boolean'); +}, 'screen.isExtended is present'); + +promise_test(async t => { + let iframe = document.body.appendChild(document.createElement('iframe')); + assert_equals(typeof iframe.contentWindow.screen.isExtended, 'boolean'); +}, 'screen.isExtended is present for attached iframes');
diff --git a/third_party/blink/web_tests/webexposed/global-interface-listing-expected.txt b/third_party/blink/web_tests/webexposed/global-interface-listing-expected.txt index c64875a..f9b1866 100644 --- a/third_party/blink/web_tests/webexposed/global-interface-listing-expected.txt +++ b/third_party/blink/web_tests/webexposed/global-interface-listing-expected.txt
@@ -5295,6 +5295,15 @@ method constructor method item method namedItem +interface ModalCloseWatcher + attribute @@toStringTag + getter onbeforeclose + getter onclose + method constructor + method destroy + method signalClosed + setter onbeforeclose + setter onclose interface Mojo static method bindInterface static method createDataPipe
diff --git a/third_party/blink/web_tests/wpt_internal/modal-close-watcher/basic.html b/third_party/blink/web_tests/wpt_internal/modal-close-watcher/basic.html new file mode 100644 index 0000000..2fd4b38 --- /dev/null +++ b/third_party/blink/web_tests/wpt_internal/modal-close-watcher/basic.html
@@ -0,0 +1,194 @@ +<!doctype html> +<script src="/resources/testharness.js"></script> +<script src="/resources/testharnessreport.js"></script> +<script src="/resources/testdriver.js"></script> +<script src="/resources/testdriver-vendor.js"></script> +<script src="/resources/testdriver-actions.js"></script> + +<div id='d' style='height: 100px; width: 100px'></div> +<script> +const ESC = '\u001B'; + +test(() => { + let watcher = new ModalCloseWatcher(); + let onbeforeclose_called = false; + let onclose_called = false; + watcher.onbeforeclose = e => { + assert_equals(e.constructor, Event); + assert_true(e.cancelable); + assert_false(e.bubbles); + onbeforeclose_called = true; + } + watcher.onclose = e => { + assert_equals(e.constructor, Event); + assert_false(e.cancelable); + assert_false(e.bubbles); + onclose_called = true; + } + + watcher.signalClosed(); + + assert_true(onbeforeclose_called); + assert_true(onclose_called); +}, "signalClose"); + +test(() => { + let watcher = new ModalCloseWatcher(); + let onbeforeclose_called = false; + let onclose_called = false; + watcher.onbeforeclose = () => onbeforeclose_called = true; + watcher.onclose = () => onclose_called = true; + + watcher.destroy(); + watcher.signalClosed(); + + assert_false(onbeforeclose_called); + assert_false(onclose_called); +}, "destroy then signalClose"); + +test(() => { + let watcher = new ModalCloseWatcher(); + let onbeforeclose_call_count_ = 0; + let onclose_call_count_ = 0; + watcher.onbeforeclose = () => onbeforeclose_call_count_++; + watcher.onclose = () => onclose_call_count_++; + + watcher.signalClosed(); + watcher.destroy(); + assert_equals(onbeforeclose_call_count_, 1); + assert_equals(onclose_call_count_, 1); +}, "signalClose then destroy"); + +promise_test(async t => { + let watcher = new ModalCloseWatcher(); + let onbeforeclose_called = false; + let onclose_called = false; + watcher.onbeforeclose = () => onbeforeclose_called = true; + watcher.onclose = () => onclose_called = true; + + await test_driver.send_keys(document.getElementById('d'), ESC); + + assert_true(onbeforeclose_called); + assert_true(onclose_called); +}, "close via escape key"); + +promise_test(async t => { + let watcher = new ModalCloseWatcher(); + let onbeforeclose_called = false; + let onclose_called = false; + watcher.onbeforeclose = () => onbeforeclose_called = true; + watcher.onclose = () => onclose_called = true; + + watcher.destroy(); + await test_driver.send_keys(document.getElementById('d'), ESC); + + assert_false(onbeforeclose_called); + assert_false(onclose_called); +}, "destroy then close via escape key"); + +promise_test(async t => { + let watcher = new ModalCloseWatcher(); + let onbeforeclose_call_count_ = 0; + let onclose_call_count_ = 0; + watcher.onbeforeclose = () => onbeforeclose_call_count_++; + watcher.onclose = () => onclose_call_count_++; + + await test_driver.send_keys(document.getElementById('d'), ESC); + watcher.destroy(); + + assert_equals(onbeforeclose_call_count_, 1); + assert_equals(onclose_call_count_, 1); +}, "close via escape key then destroy"); + +test(t => { + let watcher = new ModalCloseWatcher(); + let onbeforeclose_called = false; + let onclose_called = false; + watcher.onbeforeclose = () => onbeforeclose_called = true; + watcher.onclose = () => onclose_called = true; + + t.add_cleanup(() => watcher.destroy()); + + let keydown = new KeyboardEvent('keydown', {'key': 'Escape', 'keyCode': 27}); + window.dispatchEvent(keydown); + let keyup = new KeyboardEvent('keyup', {'key': 'Escape', 'keyCode': 27}); + window.dispatchEvent(keyup); + + assert_false(onbeforeclose_called); + assert_false(onclose_called); +}, "close via synthesized escape key should not work"); + +test(t => { + let watcher = new ModalCloseWatcher(); + t.add_cleanup(() => watcher.destroy()); + assert_throws_dom("NotAllowedError", () => new ModalCloseWatcher()); +}, "Multiple ModalCloseWatchers require a user activation."); + +promise_test(async t => { + let watcher1 = new ModalCloseWatcher(); + let watcher1_closed = false; + watcher1.onclose = () => watcher1_closed = true; + let watcher2 = null; + let watcher2_closed = false; + + await test_driver.bless("create second ModalCloseWater", () => { + watcher2 = new ModalCloseWatcher(); + watcher2.onclose = () => watcher2_closed = true; + }); + + await test_driver.send_keys(document.getElementById('d'), ESC); + + assert_false(watcher1_closed); + assert_true(watcher2_closed); + + await test_driver.send_keys(document.getElementById('d'), ESC); + + assert_true(watcher1_closed); +}, "Multiple ModalCloseWatchers work as a stack if secondary watchers are created with a user activation."); + +test(t => { + let watcher = new ModalCloseWatcher(); + watcher.destroy(); + let watcher2 = new ModalCloseWatcher(); + t.add_cleanup(() => watcher2.destroy()); +}, "destroying a free ModalCloseWatcher allows a new one to be created without a user activation."); + +test(t => { + let watcher = new ModalCloseWatcher(); + watcher.signalClosed(); + let watcher2 = new ModalCloseWatcher(); + t.add_cleanup(() => watcher2.destroy()); +}, "signalClose()ing a free ModalCloseWatcher allows a new one to be created without a user activation."); + +promise_test(async t => { + let watcher = new ModalCloseWatcher(); + await test_driver.send_keys(document.getElementById('d'), ESC); + let watcher2 = new ModalCloseWatcher(); + t.add_cleanup(() => watcher2.destroy()); +}, "Closing a free ModalCloseWatcher via the escape key allows a new one to be created without a user activation."); + +test(t => { + let watcher = new ModalCloseWatcher(); + watcher.onbeforeclose = () => { watcher.destroy(); } + watcher.onclose = t.unreached_func("onclose"); + watcher.signalClosed(); +}, "destroy inside onbeforeclose"); + +test(t => { + let watcher = new ModalCloseWatcher(); + watcher.onclose = () => { watcher.destroy(); } + watcher.signalClosed(); +}, "destroy inside onclose is benign"); + +test(t => { + let watcher = new ModalCloseWatcher(); + watcher.onbeforeclose = () => { watcher.signalClosed(); } + watcher.signalClosed(); +}, "signalClose inside onbeforeclose should not trigger an infinite loop"); + +test(t => { + let watcher = new ModalCloseWatcher(); + watcher.onclose = () => { watcher.signalClosed(); } + watcher.signalClosed(); +}, "signalClose inside onclose should not trigger an infinite loop"); +</script>
diff --git a/third_party/fdlibm/BUILD.gn b/third_party/fdlibm/BUILD.gn new file mode 100644 index 0000000..9c70cbd --- /dev/null +++ b/third_party/fdlibm/BUILD.gn
@@ -0,0 +1,12 @@ +# Copyright 2020 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. + +source_set("fdlibm") { + sources = [ + "ieee754.cc", + "ieee754.h", + "overflowing-math.h", + ] + deps = [ "//base" ] +}
diff --git a/third_party/fdlibm/DEPS b/third_party/fdlibm/DEPS new file mode 100644 index 0000000..a94f56d77 --- /dev/null +++ b/third_party/fdlibm/DEPS
@@ -0,0 +1,6 @@ +include_rules = [ + "+base/bit_cast.h", + "+base/compiler_specific.h", + "+base/macros.h", + "+build/build_config.h", +]
diff --git a/third_party/fdlibm/DIR_METADATA b/third_party/fdlibm/DIR_METADATA new file mode 100644 index 0000000..1ee4b38 --- /dev/null +++ b/third_party/fdlibm/DIR_METADATA
@@ -0,0 +1,3 @@ +monorail { + component: "Blink>WebAudio" +}
diff --git a/third_party/fdlibm/LICENSE b/third_party/fdlibm/LICENSE new file mode 100644 index 0000000..b54cb52 --- /dev/null +++ b/third_party/fdlibm/LICENSE
@@ -0,0 +1,6 @@ +Copyright (C) 1993-2004 by Sun Microsystems, Inc. All rights reserved. + +Developed at SunSoft, a Sun Microsystems, Inc. business. +Permission to use, copy, modify, and distribute this +software is freely granted, provided that this notice +is preserved.
diff --git a/third_party/fdlibm/OWNERS b/third_party/fdlibm/OWNERS new file mode 100644 index 0000000..da724767 --- /dev/null +++ b/third_party/fdlibm/OWNERS
@@ -0,0 +1,7 @@ +hongchan@chromium.org +rtoy@chromium.org + +# ***************************************************************************** +# If this file is changed, make sure to update the watchlist in v8/WATCHLISTS, +# which checks for changes in the upstream files. +# *****************************************************************************
diff --git a/third_party/fdlibm/README.chromium b/third_party/fdlibm/README.chromium new file mode 100644 index 0000000..7132faf --- /dev/null +++ b/third_party/fdlibm/README.chromium
@@ -0,0 +1,27 @@ +Name: V8 fork of fdlibm +URL: source.chromium.org/chromium/chromium/src/+/master:v8/src/base/ieee754.cc +Revision: c512d6173f33c6b8301d3fba9384edc9fc1f9e45 +Version: 0 +Security Critical: yes +License: fdlibm license +License Android Compatible: yes + +Description: +The V8 project has a math library implementation, v8/src/base/ieee754.cc, +derived from significant Google, Inc. changes to the NetBSD version of fdlibm. +This library is a copy of that V8 library intended for use in Chromium. + +This library may be useful when mathematical consistency across OS platforms is +desired. + +The initial commit is not a pristine import -- the patch in the chromium/ +subdirectory documents the changes made to the original sources. This patch was +produced via `git format-patch` and can be applied using `git am`. + +Changes from V8 upstream: +- Changed namespace to fdlibm. +- Alter //v8/src/base usage to use Chromium //base equivalents. +- Implement 32-bit float functions (sinf(), etc.) by calling the 64-bit + versions. +- Format the code. +- Remove MSVC code, which is not supported by Chromium anymore.
diff --git a/third_party/fdlibm/chromium/0001-Import-a-copy-of-V8-s-fdlibm-fork-into-Chromium-thir.patch b/third_party/fdlibm/chromium/0001-Import-a-copy-of-V8-s-fdlibm-fork-into-Chromium-thir.patch new file mode 100644 index 0000000..6353c79 --- /dev/null +++ b/third_party/fdlibm/chromium/0001-Import-a-copy-of-V8-s-fdlibm-fork-into-Chromium-thir.patch
@@ -0,0 +1,425 @@ +From 715afeb52a0c6aca1c7fcbe8c7302f20a1a2ed1a Mon Sep 17 00:00:00 2001 +From: Caleb Raitto <caraitto@chromium.org> +Date: Wed, 9 Dec 2020 15:37:30 -0500 +Subject: [PATCH] Import a copy of V8's fdlibm fork into Chromium + //third_party. + +Import a copy of v8/src/base/ieee754.[h/cc] from V8 into +Chromium. + +This will be used to mitigate Web Audio fingerprinting by using the same +math library across OS versions and platforms. + +We use a copy of the V8 math library rather than trying to share this +library. This adds ~8-9kb to the Android apk, according to the Android +binary size trybot on the CL that switches Web Audio to use this fdlibm +fork. + +This avoids complicating the build, and the V8 team also prefers not +sharing these internal details. If further similar logic needs to be +copied in the future, we could consider refactoring that into a common +library that both V8 and Chromium pull in via DEPS. + +The V8 math library also hasn't seen much churn, but we will need to +keep both copies up-to-date. crrev.com/c/2593649 has added a WATCHLISTS +entry in V8 to help with this. + +Due to presubmit requirements, this is *not* a pristine import -- +changes made from upstream to add build support and functionality +necessary for Web Audio are present in the commit patch in the chromium/ +subdirectory. A summary of these changes is also present in +README.chromium. + +Bug:1145192 +--- + third_party/fdlibm/BUILD.gn | 12 +++++ + third_party/fdlibm/DEPS | 6 +++ + third_party/fdlibm/README.chromium | 10 ++++ + third_party/fdlibm/ieee754.cc | 69 +++++++++++++++---------- + third_party/fdlibm/ieee754.h | 73 +++++++++++++++------------ + third_party/fdlibm/overflowing-math.h | 16 +++--- + 6 files changed, 118 insertions(+), 68 deletions(-) + create mode 100644 third_party/fdlibm/BUILD.gn + create mode 100644 third_party/fdlibm/DEPS + +diff --git a/third_party/fdlibm/BUILD.gn b/third_party/fdlibm/BUILD.gn +new file mode 100644 +index 000000000000..9c70cbdb062c +--- /dev/null ++++ b/third_party/fdlibm/BUILD.gn +@@ -0,0 +1,12 @@ ++# Copyright 2020 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. ++ ++source_set("fdlibm") { ++ sources = [ ++ "ieee754.cc", ++ "ieee754.h", ++ "overflowing-math.h", ++ ] ++ deps = [ "//base" ] ++} +diff --git a/third_party/fdlibm/DEPS b/third_party/fdlibm/DEPS +new file mode 100644 +index 000000000000..a94f56d77fbf +--- /dev/null ++++ b/third_party/fdlibm/DEPS +@@ -0,0 +1,6 @@ ++include_rules = [ ++ "+base/bit_cast.h", ++ "+base/compiler_specific.h", ++ "+base/macros.h", ++ "+build/build_config.h", ++] +diff --git a/third_party/fdlibm/README.chromium b/third_party/fdlibm/README.chromium +index eb45e2ab9438..48b3ab4bc6cc 100644 +--- a/third_party/fdlibm/README.chromium ++++ b/third_party/fdlibm/README.chromium +@@ -13,3 +13,13 @@ This library is a copy of that V8 library intended for use in Chromium. + + This library may be useful when mathematical consistency across OS platforms is + desired. ++ ++The initial commit is not a pristine import -- the patch in the chromium/ ++subdirectory documents the changes made to the original sources. ++ ++Changes from V8 upstream: ++- Changed namespace to fdlibm. ++- Alter //v8/src/base usage to use Chromium //base equivalents. ++- Implement 32-bit float functions (sinf(), etc.) by calling the 64-bit ++ versions. ++- Format the code. +diff --git a/third_party/fdlibm/ieee754.cc b/third_party/fdlibm/ieee754.cc +index 1706b56dfd90..4825b22fc6f5 100644 +--- a/third_party/fdlibm/ieee754.cc ++++ b/third_party/fdlibm/ieee754.cc +@@ -1,3 +1,4 @@ ++ + // The following is adapted from fdlibm (http://www.netlib.org/fdlibm). + // + // ==================================================== +@@ -12,30 +13,23 @@ + // The original source code covered by the above license above has been + // modified significantly by Google Inc. + // Copyright 2016 the V8 project authors. All rights reserved. ++// Copyright 2020 The Chromium Authors. All rights reserved. + +-#include "src/base/ieee754.h" ++#include "third_party/fdlibm/ieee754.h" + + #include <cmath> + #include <limits> + +-#include "src/base/build_config.h" +-#include "src/base/macros.h" +-#include "src/base/overflowing-math.h" ++#include "base/bit_cast.h" ++#include "base/compiler_specific.h" ++#include "base/macros.h" ++#include "build/build_config.h" ++#include "third_party/fdlibm/overflowing-math.h" + +-namespace v8 { +-namespace base { +-namespace ieee754 { ++namespace fdlibm { + + namespace { + +-/* Disable "potential divide by 0" warning in Visual Studio compiler. */ +- +-#if V8_CC_MSVC +- +-#pragma warning(disable : 4723) +- +-#endif +- + /* + * The original fdlibm code used statements like: + * n0 = ((*(int*)&one)>>29)^1; * index of high word * +@@ -104,11 +98,11 @@ namespace { + (d) = bit_cast<double>(bits); \ + } while (false) + +-int32_t __ieee754_rem_pio2(double x, double* y) V8_WARN_UNUSED_RESULT; +-double __kernel_cos(double x, double y) V8_WARN_UNUSED_RESULT; ++int32_t __ieee754_rem_pio2(double x, double* y) WARN_UNUSED_RESULT; ++double __kernel_cos(double x, double y) WARN_UNUSED_RESULT; + int __kernel_rem_pio2(double* x, double* y, int e0, int nx, int prec, +- const int32_t* ipio2) V8_WARN_UNUSED_RESULT; +-double __kernel_sin(double x, double y, int iy) V8_WARN_UNUSED_RESULT; ++ const int32_t* ipio2) WARN_UNUSED_RESULT; ++double __kernel_sin(double x, double y, int iy) WARN_UNUSED_RESULT; + + /* __ieee754_rem_pio2(x,y) + * +@@ -302,7 +296,7 @@ int32_t __ieee754_rem_pio2(double x, double *y) { + * magnitude of the latter is at least a quarter of x*x/2, + * thus, reducing the rounding error in the subtraction. + */ +-V8_INLINE double __kernel_cos(double x, double y) { ++ALWAYS_INLINE double __kernel_cos(double x, double y) { + static const double + one = 1.00000000000000000000e+00, /* 0x3FF00000, 0x00000000 */ + C1 = 4.16666666666666019037e-02, /* 0x3FA55555, 0x5555554C */ +@@ -670,7 +664,7 @@ recompute: + * then 3 2 + * sin(x) = x + (S1*x + (x *(r-y/2)+y)) + */ +-V8_INLINE double __kernel_sin(double x, double y, int iy) { ++ALWAYS_INLINE double __kernel_sin(double x, double y, int iy) { + static const double + half = 5.00000000000000000000e-01, /* 0x3FE00000, 0x00000000 */ + S1 = -1.66666666666666324348e-01, /* 0xBFC55555, 0x55555549 */ +@@ -2721,7 +2715,7 @@ double pow(double x, double y) { + } + if (iy == 0x3ff00000) { /* y is +-1 */ + if (hy < 0) { +- return base::Divide(one, x); ++ return Divide(one, x); + } else { + return x; + } +@@ -2739,7 +2733,7 @@ double pow(double x, double y) { + if (lx == 0) { + if (ix == 0x7ff00000 || ix == 0 || ix == 0x3ff00000) { + z = ax; /*x is +-0,+-inf,+-1*/ +- if (hy < 0) z = base::Divide(one, z); /* z = (1/|x|) */ ++ if (hy < 0) z = Divide(one, z); /* z = (1/|x|) */ + if (hx < 0) { + if (((ix - 0x3ff00000) | yisint) == 0) { + /* (-1)**non-int is NaN */ +@@ -2806,7 +2800,7 @@ double pow(double x, double y) { + + /* compute ss = s_h+s_l = (x-1)/(x+1) or (x-1.5)/(x+1.5) */ + u = ax - bp[k]; /* bp[0]=1.0, bp[1]=1.5 */ +- v = base::Divide(one, ax + bp[k]); ++ v = Divide(one, ax + bp[k]); + ss = u * v; + s_h = ss; + SET_LOW_WORD(s_h, 0); +@@ -2883,7 +2877,7 @@ double pow(double x, double y) { + w = v - (z - u); + t = z * z; + t1 = z - t * (P1 + t * (P2 + t * (P3 + t * (P4 + t * P5)))); +- r = base::Divide(z * t1, (t1 - two) - (w + z * w)); ++ r = Divide(z * t1, (t1 - two) - (w + z * w)); + z = one - (r - z); + GET_HIGH_WORD(j, z); + j += static_cast<int>(static_cast<uint32_t>(n) << 20); +@@ -3008,6 +3002,26 @@ double tanh(double x) { + return (jx >= 0) ? z : -z; + } + ++float powf(float x, float y) { ++ return pow(x, y); ++} ++ ++float expf(float x) { ++ return exp(x); ++} ++ ++float log10f(float x) { ++ return log10(x); ++} ++ ++float sinf(double x) { ++ return sin(x); ++} ++ ++float asinf(double x) { ++ return asin(x); ++} ++ + #undef EXTRACT_WORDS + #undef GET_HIGH_WORD + #undef GET_LOW_WORD +@@ -3015,6 +3029,5 @@ double tanh(double x) { + #undef SET_HIGH_WORD + #undef SET_LOW_WORD + +-} // namespace ieee754 +-} // namespace base +-} // namespace v8 ++} // namespace fdlibm ++ +diff --git a/third_party/fdlibm/ieee754.h b/third_party/fdlibm/ieee754.h +index f2b3a3eb5808..27b5013818a2 100644 +--- a/third_party/fdlibm/ieee754.h ++++ b/third_party/fdlibm/ieee754.h +@@ -1,64 +1,61 @@ + // Copyright 2016 the V8 project authors. All rights reserved. ++// Copyright 2020 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 V8_BASE_IEEE754_H_ +-#define V8_BASE_IEEE754_H_ ++#ifndef THIRD_PARTY_FDLIBM_IEEE754_H_ ++#define THIRD_PARTY_FDLIBM_IEEE754_H_ + +-#include "src/base/base-export.h" +- +-namespace v8 { +-namespace base { +-namespace ieee754 { ++namespace fdlibm { + + // Returns the arc cosine of |x|; that is the value whose cosine is |x|. +-V8_BASE_EXPORT double acos(double x); ++double acos(double x); + + // Returns the inverse hyperbolic cosine of |x|; that is the value whose + // hyperbolic cosine is |x|. +-V8_BASE_EXPORT double acosh(double x); ++double acosh(double x); + + // Returns the arc sine of |x|; that is the value whose sine is |x|. +-V8_BASE_EXPORT double asin(double x); ++double asin(double x); + + // Returns the inverse hyperbolic sine of |x|; that is the value whose + // hyperbolic sine is |x|. +-V8_BASE_EXPORT double asinh(double x); ++double asinh(double x); + + // Returns the principal value of the arc tangent of |x|; that is the value + // whose tangent is |x|. +-V8_BASE_EXPORT double atan(double x); ++double atan(double x); + + // Returns the principal value of the arc tangent of |y/x|, using the signs of + // the two arguments to determine the quadrant of the result. +-V8_BASE_EXPORT double atan2(double y, double x); ++double atan2(double y, double x); + + // Returns the cosine of |x|, where |x| is given in radians. +-V8_BASE_EXPORT double cos(double x); ++double cos(double x); + + // Returns the base-e exponential of |x|. +-V8_BASE_EXPORT double exp(double x); ++double exp(double x); + +-V8_BASE_EXPORT double atanh(double x); ++double atanh(double x); + + // Returns the natural logarithm of |x|. +-V8_BASE_EXPORT double log(double x); ++double log(double x); + + // Returns a value equivalent to |log(1+x)|, but computed in a way that is + // accurate even if the value of |x| is near zero. +-V8_BASE_EXPORT double log1p(double x); ++double log1p(double x); + + // Returns the base 2 logarithm of |x|. +-V8_BASE_EXPORT double log2(double x); ++double log2(double x); + + // Returns the base 10 logarithm of |x|. +-V8_BASE_EXPORT double log10(double x); ++double log10(double x); + + // Returns the cube root of |x|. +-V8_BASE_EXPORT double cbrt(double x); ++double cbrt(double x); + + // Returns exp(x)-1, the exponential of |x| minus 1. +-V8_BASE_EXPORT double expm1(double x); ++double expm1(double x); + + // Returns |x| to the power of |y|. + // The result of base ** exponent when base is 1 or -1 and exponent is +@@ -66,25 +63,37 @@ V8_BASE_EXPORT double expm1(double x); + // of ECMAScript specified a result of NaN for this operation, whereas + // later versions of IEEE 754-2008 specified 1. The historical ECMAScript + // behaviour is preserved for compatibility reasons. +-V8_BASE_EXPORT double pow(double x, double y); ++double pow(double x, double y); + + // Returns the sine of |x|, where |x| is given in radians. +-V8_BASE_EXPORT double sin(double x); ++double sin(double x); + + // Returns the tangent of |x|, where |x| is given in radians. +-V8_BASE_EXPORT double tan(double x); ++double tan(double x); + + // Returns the hyperbolic cosine of |x|, where |x| is given radians. +-V8_BASE_EXPORT double cosh(double x); ++double cosh(double x); + + // Returns the hyperbolic sine of |x|, where |x| is given radians. +-V8_BASE_EXPORT double sinh(double x); ++double sinh(double x); + + // Returns the hyperbolic tangent of |x|, where |x| is given radians. +-V8_BASE_EXPORT double tanh(double x); ++double tanh(double x); ++ ++// NOTE(caraitto): These functions are not present in the V8 math library -- ++// they are defined in terms of other functions. ++ ++float powf(float x, float y); ++ ++float expf(float x); ++ ++float log10f(float x); ++ ++float sinf(double x); ++ ++float asinf(double x); ++ ++} // namespace fdlibm + +-} // namespace ieee754 +-} // namespace base +-} // namespace v8 ++#endif // THIRD_PARTY_FDLIBM_IEEE754_H_ + +-#endif // V8_BASE_IEEE754_H_ +diff --git a/third_party/fdlibm/overflowing-math.h b/third_party/fdlibm/overflowing-math.h +index 14dcfb10de1a..815fa624ce11 100644 +--- a/third_party/fdlibm/overflowing-math.h ++++ b/third_party/fdlibm/overflowing-math.h +@@ -1,19 +1,19 @@ + // Copyright 2019 the V8 project authors. All rights reserved. ++// Copyright 2020 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 V8_BASE_OVERFLOWING_MATH_H_ +-#define V8_BASE_OVERFLOWING_MATH_H_ ++#ifndef THIRD_PARTY_FDLIBM_OVERFLOWING_MATH_H_ ++#define THIRD_PARTY_FDLIBM_OVERFLOWING_MATH_H_ + + #include <stdint.h> + + #include <cmath> + #include <type_traits> + +-#include "src/base/macros.h" ++#include "base/macros.h" + +-namespace v8 { +-namespace base { ++namespace fdlibm { + + // Helpers for performing overflowing arithmetic operations without relying + // on C++ undefined behavior. +@@ -90,7 +90,7 @@ inline T RoundingAverageUnsigned(T a, T b) { + return (static_cast<uint64_t>(a) + static_cast<uint64_t>(b) + 1) >> 1; + } + +-} // namespace base +-} // namespace v8 ++} // namespace fdlibm ++ ++#endif // THIRD_PARTY_FDLIBM_OVERFLOWING_MATH_H_ + +-#endif // V8_BASE_OVERFLOWING_MATH_H_ +-- +2.30.0.365.g02bc693789-goog +
diff --git a/third_party/fdlibm/ieee754.cc b/third_party/fdlibm/ieee754.cc new file mode 100644 index 0000000..4825b22 --- /dev/null +++ b/third_party/fdlibm/ieee754.cc
@@ -0,0 +1,3033 @@ + +// The following is adapted from fdlibm (http://www.netlib.org/fdlibm). +// +// ==================================================== +// Copyright (C) 1993 by Sun Microsystems, Inc. All rights reserved. +// +// Developed at SunSoft, a Sun Microsystems, Inc. business. +// Permission to use, copy, modify, and distribute this +// software is freely granted, provided that this notice +// is preserved. +// ==================================================== +// +// The original source code covered by the above license above has been +// modified significantly by Google Inc. +// Copyright 2016 the V8 project authors. All rights reserved. +// Copyright 2020 The Chromium Authors. All rights reserved. + +#include "third_party/fdlibm/ieee754.h" + +#include <cmath> +#include <limits> + +#include "base/bit_cast.h" +#include "base/compiler_specific.h" +#include "base/macros.h" +#include "build/build_config.h" +#include "third_party/fdlibm/overflowing-math.h" + +namespace fdlibm { + +namespace { + +/* + * The original fdlibm code used statements like: + * n0 = ((*(int*)&one)>>29)^1; * index of high word * + * ix0 = *(n0+(int*)&x); * high word of x * + * ix1 = *((1-n0)+(int*)&x); * low word of x * + * to dig two 32 bit words out of the 64 bit IEEE floating point + * value. That is non-ANSI, and, moreover, the gcc instruction + * scheduler gets it wrong. We instead use the following macros. + * Unlike the original code, we determine the endianness at compile + * time, not at run time; I don't see much benefit to selecting + * endianness at run time. + */ + +/* Get two 32 bit ints from a double. */ + +#define EXTRACT_WORDS(ix0, ix1, d) \ + do { \ + uint64_t bits = bit_cast<uint64_t>(d); \ + (ix0) = bits >> 32; \ + (ix1) = bits & 0xFFFFFFFFu; \ + } while (false) + +/* Get the more significant 32 bit int from a double. */ + +#define GET_HIGH_WORD(i, d) \ + do { \ + uint64_t bits = bit_cast<uint64_t>(d); \ + (i) = bits >> 32; \ + } while (false) + +/* Get the less significant 32 bit int from a double. */ + +#define GET_LOW_WORD(i, d) \ + do { \ + uint64_t bits = bit_cast<uint64_t>(d); \ + (i) = bits & 0xFFFFFFFFu; \ + } while (false) + +/* Set a double from two 32 bit ints. */ + +#define INSERT_WORDS(d, ix0, ix1) \ + do { \ + uint64_t bits = 0; \ + bits |= static_cast<uint64_t>(ix0) << 32; \ + bits |= static_cast<uint32_t>(ix1); \ + (d) = bit_cast<double>(bits); \ + } while (false) + +/* Set the more significant 32 bits of a double from an int. */ + +#define SET_HIGH_WORD(d, v) \ + do { \ + uint64_t bits = bit_cast<uint64_t>(d); \ + bits &= 0x0000'0000'FFFF'FFFF; \ + bits |= static_cast<uint64_t>(v) << 32; \ + (d) = bit_cast<double>(bits); \ + } while (false) + +/* Set the less significant 32 bits of a double from an int. */ + +#define SET_LOW_WORD(d, v) \ + do { \ + uint64_t bits = bit_cast<uint64_t>(d); \ + bits &= 0xFFFF'FFFF'0000'0000; \ + bits |= static_cast<uint32_t>(v); \ + (d) = bit_cast<double>(bits); \ + } while (false) + +int32_t __ieee754_rem_pio2(double x, double* y) WARN_UNUSED_RESULT; +double __kernel_cos(double x, double y) WARN_UNUSED_RESULT; +int __kernel_rem_pio2(double* x, double* y, int e0, int nx, int prec, + const int32_t* ipio2) WARN_UNUSED_RESULT; +double __kernel_sin(double x, double y, int iy) WARN_UNUSED_RESULT; + +/* __ieee754_rem_pio2(x,y) + * + * return the remainder of x rem pi/2 in y[0]+y[1] + * use __kernel_rem_pio2() + */ +int32_t __ieee754_rem_pio2(double x, double *y) { + /* + * Table of constants for 2/pi, 396 Hex digits (476 decimal) of 2/pi + */ + static const int32_t two_over_pi[] = { + 0xA2F983, 0x6E4E44, 0x1529FC, 0x2757D1, 0xF534DD, 0xC0DB62, 0x95993C, + 0x439041, 0xFE5163, 0xABDEBB, 0xC561B7, 0x246E3A, 0x424DD2, 0xE00649, + 0x2EEA09, 0xD1921C, 0xFE1DEB, 0x1CB129, 0xA73EE8, 0x8235F5, 0x2EBB44, + 0x84E99C, 0x7026B4, 0x5F7E41, 0x3991D6, 0x398353, 0x39F49C, 0x845F8B, + 0xBDF928, 0x3B1FF8, 0x97FFDE, 0x05980F, 0xEF2F11, 0x8B5A0A, 0x6D1F6D, + 0x367ECF, 0x27CB09, 0xB74F46, 0x3F669E, 0x5FEA2D, 0x7527BA, 0xC7EBE5, + 0xF17B3D, 0x0739F7, 0x8A5292, 0xEA6BFB, 0x5FB11F, 0x8D5D08, 0x560330, + 0x46FC7B, 0x6BABF0, 0xCFBC20, 0x9AF436, 0x1DA9E3, 0x91615E, 0xE61B08, + 0x659985, 0x5F14A0, 0x68408D, 0xFFD880, 0x4D7327, 0x310606, 0x1556CA, + 0x73A8C9, 0x60E27B, 0xC08C6B, + }; + + static const int32_t npio2_hw[] = { + 0x3FF921FB, 0x400921FB, 0x4012D97C, 0x401921FB, 0x401F6A7A, 0x4022D97C, + 0x4025FDBB, 0x402921FB, 0x402C463A, 0x402F6A7A, 0x4031475C, 0x4032D97C, + 0x40346B9C, 0x4035FDBB, 0x40378FDB, 0x403921FB, 0x403AB41B, 0x403C463A, + 0x403DD85A, 0x403F6A7A, 0x40407E4C, 0x4041475C, 0x4042106C, 0x4042D97C, + 0x4043A28C, 0x40446B9C, 0x404534AC, 0x4045FDBB, 0x4046C6CB, 0x40478FDB, + 0x404858EB, 0x404921FB, + }; + + /* + * invpio2: 53 bits of 2/pi + * pio2_1: first 33 bit of pi/2 + * pio2_1t: pi/2 - pio2_1 + * pio2_2: second 33 bit of pi/2 + * pio2_2t: pi/2 - (pio2_1+pio2_2) + * pio2_3: third 33 bit of pi/2 + * pio2_3t: pi/2 - (pio2_1+pio2_2+pio2_3) + */ + + static const double + zero = 0.00000000000000000000e+00, /* 0x00000000, 0x00000000 */ + half = 5.00000000000000000000e-01, /* 0x3FE00000, 0x00000000 */ + two24 = 1.67772160000000000000e+07, /* 0x41700000, 0x00000000 */ + invpio2 = 6.36619772367581382433e-01, /* 0x3FE45F30, 0x6DC9C883 */ + pio2_1 = 1.57079632673412561417e+00, /* 0x3FF921FB, 0x54400000 */ + pio2_1t = 6.07710050650619224932e-11, /* 0x3DD0B461, 0x1A626331 */ + pio2_2 = 6.07710050630396597660e-11, /* 0x3DD0B461, 0x1A600000 */ + pio2_2t = 2.02226624879595063154e-21, /* 0x3BA3198A, 0x2E037073 */ + pio2_3 = 2.02226624871116645580e-21, /* 0x3BA3198A, 0x2E000000 */ + pio2_3t = 8.47842766036889956997e-32; /* 0x397B839A, 0x252049C1 */ + + double z, w, t, r, fn; + double tx[3]; + int32_t e0, i, j, nx, n, ix, hx; + uint32_t low; + + z = 0; + GET_HIGH_WORD(hx, x); /* high word of x */ + ix = hx & 0x7FFFFFFF; + if (ix <= 0x3FE921FB) { /* |x| ~<= pi/4 , no need for reduction */ + y[0] = x; + y[1] = 0; + return 0; + } + if (ix < 0x4002D97C) { /* |x| < 3pi/4, special case with n=+-1 */ + if (hx > 0) { + z = x - pio2_1; + if (ix != 0x3FF921FB) { /* 33+53 bit pi is good enough */ + y[0] = z - pio2_1t; + y[1] = (z - y[0]) - pio2_1t; + } else { /* near pi/2, use 33+33+53 bit pi */ + z -= pio2_2; + y[0] = z - pio2_2t; + y[1] = (z - y[0]) - pio2_2t; + } + return 1; + } else { /* negative x */ + z = x + pio2_1; + if (ix != 0x3FF921FB) { /* 33+53 bit pi is good enough */ + y[0] = z + pio2_1t; + y[1] = (z - y[0]) + pio2_1t; + } else { /* near pi/2, use 33+33+53 bit pi */ + z += pio2_2; + y[0] = z + pio2_2t; + y[1] = (z - y[0]) + pio2_2t; + } + return -1; + } + } + if (ix <= 0x413921FB) { /* |x| ~<= 2^19*(pi/2), medium size */ + t = fabs(x); + n = static_cast<int32_t>(t * invpio2 + half); + fn = static_cast<double>(n); + r = t - fn * pio2_1; + w = fn * pio2_1t; /* 1st round good to 85 bit */ + if (n < 32 && ix != npio2_hw[n - 1]) { + y[0] = r - w; /* quick check no cancellation */ + } else { + uint32_t high; + j = ix >> 20; + y[0] = r - w; + GET_HIGH_WORD(high, y[0]); + i = j - ((high >> 20) & 0x7FF); + if (i > 16) { /* 2nd iteration needed, good to 118 */ + t = r; + w = fn * pio2_2; + r = t - w; + w = fn * pio2_2t - ((t - r) - w); + y[0] = r - w; + GET_HIGH_WORD(high, y[0]); + i = j - ((high >> 20) & 0x7FF); + if (i > 49) { /* 3rd iteration need, 151 bits acc */ + t = r; /* will cover all possible cases */ + w = fn * pio2_3; + r = t - w; + w = fn * pio2_3t - ((t - r) - w); + y[0] = r - w; + } + } + } + y[1] = (r - y[0]) - w; + if (hx < 0) { + y[0] = -y[0]; + y[1] = -y[1]; + return -n; + } else { + return n; + } + } + /* + * all other (large) arguments + */ + if (ix >= 0x7FF00000) { /* x is inf or NaN */ + y[0] = y[1] = x - x; + return 0; + } + /* set z = scalbn(|x|,ilogb(x)-23) */ + GET_LOW_WORD(low, x); + SET_LOW_WORD(z, low); + e0 = (ix >> 20) - 1046; /* e0 = ilogb(z)-23; */ + SET_HIGH_WORD(z, ix - static_cast<int32_t>(static_cast<uint32_t>(e0) << 20)); + for (i = 0; i < 2; i++) { + tx[i] = static_cast<double>(static_cast<int32_t>(z)); + z = (z - tx[i]) * two24; + } + tx[2] = z; + nx = 3; + while (tx[nx - 1] == zero) nx--; /* skip zero term */ + n = __kernel_rem_pio2(tx, y, e0, nx, 2, two_over_pi); + if (hx < 0) { + y[0] = -y[0]; + y[1] = -y[1]; + return -n; + } + return n; +} + +/* __kernel_cos( x, y ) + * kernel cos function on [-pi/4, pi/4], pi/4 ~ 0.785398164 + * Input x is assumed to be bounded by ~pi/4 in magnitude. + * Input y is the tail of x. + * + * Algorithm + * 1. Since cos(-x) = cos(x), we need only to consider positive x. + * 2. if x < 2^-27 (hx<0x3E400000 0), return 1 with inexact if x!=0. + * 3. cos(x) is approximated by a polynomial of degree 14 on + * [0,pi/4] + * 4 14 + * cos(x) ~ 1 - x*x/2 + C1*x + ... + C6*x + * where the remez error is + * + * | 2 4 6 8 10 12 14 | -58 + * |cos(x)-(1-.5*x +C1*x +C2*x +C3*x +C4*x +C5*x +C6*x )| <= 2 + * | | + * + * 4 6 8 10 12 14 + * 4. let r = C1*x +C2*x +C3*x +C4*x +C5*x +C6*x , then + * cos(x) = 1 - x*x/2 + r + * since cos(x+y) ~ cos(x) - sin(x)*y + * ~ cos(x) - x*y, + * a correction term is necessary in cos(x) and hence + * cos(x+y) = 1 - (x*x/2 - (r - x*y)) + * For better accuracy when x > 0.3, let qx = |x|/4 with + * the last 32 bits mask off, and if x > 0.78125, let qx = 0.28125. + * Then + * cos(x+y) = (1-qx) - ((x*x/2-qx) - (r-x*y)). + * Note that 1-qx and (x*x/2-qx) is EXACT here, and the + * magnitude of the latter is at least a quarter of x*x/2, + * thus, reducing the rounding error in the subtraction. + */ +ALWAYS_INLINE double __kernel_cos(double x, double y) { + static const double + one = 1.00000000000000000000e+00, /* 0x3FF00000, 0x00000000 */ + C1 = 4.16666666666666019037e-02, /* 0x3FA55555, 0x5555554C */ + C2 = -1.38888888888741095749e-03, /* 0xBF56C16C, 0x16C15177 */ + C3 = 2.48015872894767294178e-05, /* 0x3EFA01A0, 0x19CB1590 */ + C4 = -2.75573143513906633035e-07, /* 0xBE927E4F, 0x809C52AD */ + C5 = 2.08757232129817482790e-09, /* 0x3E21EE9E, 0xBDB4B1C4 */ + C6 = -1.13596475577881948265e-11; /* 0xBDA8FAE9, 0xBE8838D4 */ + + double a, iz, z, r, qx; + int32_t ix; + GET_HIGH_WORD(ix, x); + ix &= 0x7FFFFFFF; /* ix = |x|'s high word*/ + if (ix < 0x3E400000) { /* if x < 2**27 */ + if (static_cast<int>(x) == 0) return one; /* generate inexact */ + } + z = x * x; + r = z * (C1 + z * (C2 + z * (C3 + z * (C4 + z * (C5 + z * C6))))); + if (ix < 0x3FD33333) { /* if |x| < 0.3 */ + return one - (0.5 * z - (z * r - x * y)); + } else { + if (ix > 0x3FE90000) { /* x > 0.78125 */ + qx = 0.28125; + } else { + INSERT_WORDS(qx, ix - 0x00200000, 0); /* x/4 */ + } + iz = 0.5 * z - qx; + a = one - qx; + return a - (iz - (z * r - x * y)); + } +} + +/* __kernel_rem_pio2(x,y,e0,nx,prec,ipio2) + * double x[],y[]; int e0,nx,prec; int ipio2[]; + * + * __kernel_rem_pio2 return the last three digits of N with + * y = x - N*pi/2 + * so that |y| < pi/2. + * + * The method is to compute the integer (mod 8) and fraction parts of + * (2/pi)*x without doing the full multiplication. In general we + * skip the part of the product that are known to be a huge integer ( + * more accurately, = 0 mod 8 ). Thus the number of operations are + * independent of the exponent of the input. + * + * (2/pi) is represented by an array of 24-bit integers in ipio2[]. + * + * Input parameters: + * x[] The input value (must be positive) is broken into nx + * pieces of 24-bit integers in double precision format. + * x[i] will be the i-th 24 bit of x. The scaled exponent + * of x[0] is given in input parameter e0 (i.e., x[0]*2^e0 + * match x's up to 24 bits. + * + * Example of breaking a double positive z into x[0]+x[1]+x[2]: + * e0 = ilogb(z)-23 + * z = scalbn(z,-e0) + * for i = 0,1,2 + * x[i] = floor(z) + * z = (z-x[i])*2**24 + * + * + * y[] output result in an array of double precision numbers. + * The dimension of y[] is: + * 24-bit precision 1 + * 53-bit precision 2 + * 64-bit precision 2 + * 113-bit precision 3 + * The actual value is the sum of them. Thus for 113-bit + * precison, one may have to do something like: + * + * long double t,w,r_head, r_tail; + * t = (long double)y[2] + (long double)y[1]; + * w = (long double)y[0]; + * r_head = t+w; + * r_tail = w - (r_head - t); + * + * e0 The exponent of x[0] + * + * nx dimension of x[] + * + * prec an integer indicating the precision: + * 0 24 bits (single) + * 1 53 bits (double) + * 2 64 bits (extended) + * 3 113 bits (quad) + * + * ipio2[] + * integer array, contains the (24*i)-th to (24*i+23)-th + * bit of 2/pi after binary point. The corresponding + * floating value is + * + * ipio2[i] * 2^(-24(i+1)). + * + * External function: + * double scalbn(), floor(); + * + * + * Here is the description of some local variables: + * + * jk jk+1 is the initial number of terms of ipio2[] needed + * in the computation. The recommended value is 2,3,4, + * 6 for single, double, extended,and quad. + * + * jz local integer variable indicating the number of + * terms of ipio2[] used. + * + * jx nx - 1 + * + * jv index for pointing to the suitable ipio2[] for the + * computation. In general, we want + * ( 2^e0*x[0] * ipio2[jv-1]*2^(-24jv) )/8 + * is an integer. Thus + * e0-3-24*jv >= 0 or (e0-3)/24 >= jv + * Hence jv = max(0,(e0-3)/24). + * + * jp jp+1 is the number of terms in PIo2[] needed, jp = jk. + * + * q[] double array with integral value, representing the + * 24-bits chunk of the product of x and 2/pi. + * + * q0 the corresponding exponent of q[0]. Note that the + * exponent for q[i] would be q0-24*i. + * + * PIo2[] double precision array, obtained by cutting pi/2 + * into 24 bits chunks. + * + * f[] ipio2[] in floating point + * + * iq[] integer array by breaking up q[] in 24-bits chunk. + * + * fq[] final product of x*(2/pi) in fq[0],..,fq[jk] + * + * ih integer. If >0 it indicates q[] is >= 0.5, hence + * it also indicates the *sign* of the result. + * + */ +int __kernel_rem_pio2(double *x, double *y, int e0, int nx, int prec, + const int32_t *ipio2) { + /* Constants: + * The hexadecimal values are the intended ones for the following + * constants. The decimal values may be used, provided that the + * compiler will convert from decimal to binary accurately enough + * to produce the hexadecimal values shown. + */ + static const int init_jk[] = {2, 3, 4, 6}; /* initial value for jk */ + + static const double PIo2[] = { + 1.57079625129699707031e+00, /* 0x3FF921FB, 0x40000000 */ + 7.54978941586159635335e-08, /* 0x3E74442D, 0x00000000 */ + 5.39030252995776476554e-15, /* 0x3CF84698, 0x80000000 */ + 3.28200341580791294123e-22, /* 0x3B78CC51, 0x60000000 */ + 1.27065575308067607349e-29, /* 0x39F01B83, 0x80000000 */ + 1.22933308981111328932e-36, /* 0x387A2520, 0x40000000 */ + 2.73370053816464559624e-44, /* 0x36E38222, 0x80000000 */ + 2.16741683877804819444e-51, /* 0x3569F31D, 0x00000000 */ + }; + + static const double + zero = 0.0, + one = 1.0, + two24 = 1.67772160000000000000e+07, /* 0x41700000, 0x00000000 */ + twon24 = 5.96046447753906250000e-08; /* 0x3E700000, 0x00000000 */ + + int32_t jz, jx, jv, jp, jk, carry, n, iq[20], i, j, k, m, q0, ih; + double z, fw, f[20], fq[20], q[20]; + + /* initialize jk*/ + jk = init_jk[prec]; + jp = jk; + + /* determine jx,jv,q0, note that 3>q0 */ + jx = nx - 1; + jv = (e0 - 3) / 24; + if (jv < 0) jv = 0; + q0 = e0 - 24 * (jv + 1); + + /* set up f[0] to f[jx+jk] where f[jx+jk] = ipio2[jv+jk] */ + j = jv - jx; + m = jx + jk; + for (i = 0; i <= m; i++, j++) { + f[i] = (j < 0) ? zero : static_cast<double>(ipio2[j]); + } + + /* compute q[0],q[1],...q[jk] */ + for (i = 0; i <= jk; i++) { + for (j = 0, fw = 0.0; j <= jx; j++) fw += x[j] * f[jx + i - j]; + q[i] = fw; + } + + jz = jk; +recompute: + /* distill q[] into iq[] reversingly */ + for (i = 0, j = jz, z = q[jz]; j > 0; i++, j--) { + fw = static_cast<double>(static_cast<int32_t>(twon24 * z)); + iq[i] = static_cast<int32_t>(z - two24 * fw); + z = q[j - 1] + fw; + } + + /* compute n */ + z = scalbn(z, q0); /* actual value of z */ + z -= 8.0 * floor(z * 0.125); /* trim off integer >= 8 */ + n = static_cast<int32_t>(z); + z -= static_cast<double>(n); + ih = 0; + if (q0 > 0) { /* need iq[jz-1] to determine n */ + i = (iq[jz - 1] >> (24 - q0)); + n += i; + iq[jz - 1] -= i << (24 - q0); + ih = iq[jz - 1] >> (23 - q0); + } else if (q0 == 0) { + ih = iq[jz - 1] >> 23; + } else if (z >= 0.5) { + ih = 2; + } + + if (ih > 0) { /* q > 0.5 */ + n += 1; + carry = 0; + for (i = 0; i < jz; i++) { /* compute 1-q */ + j = iq[i]; + if (carry == 0) { + if (j != 0) { + carry = 1; + iq[i] = 0x1000000 - j; + } + } else { + iq[i] = 0xFFFFFF - j; + } + } + if (q0 > 0) { /* rare case: chance is 1 in 12 */ + switch (q0) { + case 1: + iq[jz - 1] &= 0x7FFFFF; + break; + case 2: + iq[jz - 1] &= 0x3FFFFF; + break; + } + } + if (ih == 2) { + z = one - z; + if (carry != 0) z -= scalbn(one, q0); + } + } + + /* check if recomputation is needed */ + if (z == zero) { + j = 0; + for (i = jz - 1; i >= jk; i--) j |= iq[i]; + if (j == 0) { /* need recomputation */ + for (k = 1; jk >= k && iq[jk - k] == 0; k++) { + /* k = no. of terms needed */ + } + + for (i = jz + 1; i <= jz + k; i++) { /* add q[jz+1] to q[jz+k] */ + f[jx + i] = ipio2[jv + i]; + for (j = 0, fw = 0.0; j <= jx; j++) fw += x[j] * f[jx + i - j]; + q[i] = fw; + } + jz += k; + goto recompute; + } + } + + /* chop off zero terms */ + if (z == 0.0) { + jz -= 1; + q0 -= 24; + while (iq[jz] == 0) { + jz--; + q0 -= 24; + } + } else { /* break z into 24-bit if necessary */ + z = scalbn(z, -q0); + if (z >= two24) { + fw = static_cast<double>(static_cast<int32_t>(twon24 * z)); + iq[jz] = z - two24 * fw; + jz += 1; + q0 += 24; + iq[jz] = fw; + } else { + iq[jz] = z; + } + } + + /* convert integer "bit" chunk to floating-point value */ + fw = scalbn(one, q0); + for (i = jz; i >= 0; i--) { + q[i] = fw * iq[i]; + fw *= twon24; + } + + /* compute PIo2[0,...,jp]*q[jz,...,0] */ + for (i = jz; i >= 0; i--) { + for (fw = 0.0, k = 0; k <= jp && k <= jz - i; k++) fw += PIo2[k] * q[i + k]; + fq[jz - i] = fw; + } + + /* compress fq[] into y[] */ + switch (prec) { + case 0: + fw = 0.0; + for (i = jz; i >= 0; i--) fw += fq[i]; + y[0] = (ih == 0) ? fw : -fw; + break; + case 1: + case 2: + fw = 0.0; + for (i = jz; i >= 0; i--) fw += fq[i]; + y[0] = (ih == 0) ? fw : -fw; + fw = fq[0] - fw; + for (i = 1; i <= jz; i++) fw += fq[i]; + y[1] = (ih == 0) ? fw : -fw; + break; + case 3: /* painful */ + for (i = jz; i > 0; i--) { + fw = fq[i - 1] + fq[i]; + fq[i] += fq[i - 1] - fw; + fq[i - 1] = fw; + } + for (i = jz; i > 1; i--) { + fw = fq[i - 1] + fq[i]; + fq[i] += fq[i - 1] - fw; + fq[i - 1] = fw; + } + for (fw = 0.0, i = jz; i >= 2; i--) fw += fq[i]; + if (ih == 0) { + y[0] = fq[0]; + y[1] = fq[1]; + y[2] = fw; + } else { + y[0] = -fq[0]; + y[1] = -fq[1]; + y[2] = -fw; + } + } + return n & 7; +} + +/* __kernel_sin( x, y, iy) + * kernel sin function on [-pi/4, pi/4], pi/4 ~ 0.7854 + * Input x is assumed to be bounded by ~pi/4 in magnitude. + * Input y is the tail of x. + * Input iy indicates whether y is 0. (if iy=0, y assume to be 0). + * + * Algorithm + * 1. Since sin(-x) = -sin(x), we need only to consider positive x. + * 2. if x < 2^-27 (hx<0x3E400000 0), return x with inexact if x!=0. + * 3. sin(x) is approximated by a polynomial of degree 13 on + * [0,pi/4] + * 3 13 + * sin(x) ~ x + S1*x + ... + S6*x + * where + * + * |sin(x) 2 4 6 8 10 12 | -58 + * |----- - (1+S1*x +S2*x +S3*x +S4*x +S5*x +S6*x )| <= 2 + * | x | + * + * 4. sin(x+y) = sin(x) + sin'(x')*y + * ~ sin(x) + (1-x*x/2)*y + * For better accuracy, let + * 3 2 2 2 2 + * r = x *(S2+x *(S3+x *(S4+x *(S5+x *S6)))) + * then 3 2 + * sin(x) = x + (S1*x + (x *(r-y/2)+y)) + */ +ALWAYS_INLINE double __kernel_sin(double x, double y, int iy) { + static const double + half = 5.00000000000000000000e-01, /* 0x3FE00000, 0x00000000 */ + S1 = -1.66666666666666324348e-01, /* 0xBFC55555, 0x55555549 */ + S2 = 8.33333333332248946124e-03, /* 0x3F811111, 0x1110F8A6 */ + S3 = -1.98412698298579493134e-04, /* 0xBF2A01A0, 0x19C161D5 */ + S4 = 2.75573137070700676789e-06, /* 0x3EC71DE3, 0x57B1FE7D */ + S5 = -2.50507602534068634195e-08, /* 0xBE5AE5E6, 0x8A2B9CEB */ + S6 = 1.58969099521155010221e-10; /* 0x3DE5D93A, 0x5ACFD57C */ + + double z, r, v; + int32_t ix; + GET_HIGH_WORD(ix, x); + ix &= 0x7FFFFFFF; /* high word of x */ + if (ix < 0x3E400000) { /* |x| < 2**-27 */ + if (static_cast<int>(x) == 0) return x; + } /* generate inexact */ + z = x * x; + v = z * x; + r = S2 + z * (S3 + z * (S4 + z * (S5 + z * S6))); + if (iy == 0) { + return x + v * (S1 + z * r); + } else { + return x - ((z * (half * y - v * r) - y) - v * S1); + } +} + +/* __kernel_tan( x, y, k ) + * kernel tan function on [-pi/4, pi/4], pi/4 ~ 0.7854 + * Input x is assumed to be bounded by ~pi/4 in magnitude. + * Input y is the tail of x. + * Input k indicates whether tan (if k=1) or + * -1/tan (if k= -1) is returned. + * + * Algorithm + * 1. Since tan(-x) = -tan(x), we need only to consider positive x. + * 2. if x < 2^-28 (hx<0x3E300000 0), return x with inexact if x!=0. + * 3. tan(x) is approximated by a odd polynomial of degree 27 on + * [0,0.67434] + * 3 27 + * tan(x) ~ x + T1*x + ... + T13*x + * where + * + * |tan(x) 2 4 26 | -59.2 + * |----- - (1+T1*x +T2*x +.... +T13*x )| <= 2 + * | x | + * + * Note: tan(x+y) = tan(x) + tan'(x)*y + * ~ tan(x) + (1+x*x)*y + * Therefore, for better accuracy in computing tan(x+y), let + * 3 2 2 2 2 + * r = x *(T2+x *(T3+x *(...+x *(T12+x *T13)))) + * then + * 3 2 + * tan(x+y) = x + (T1*x + (x *(r+y)+y)) + * + * 4. For x in [0.67434,pi/4], let y = pi/4 - x, then + * tan(x) = tan(pi/4-y) = (1-tan(y))/(1+tan(y)) + * = 1 - 2*(tan(y) - (tan(y)^2)/(1+tan(y))) + */ +double __kernel_tan(double x, double y, int iy) { + static const double xxx[] = { + 3.33333333333334091986e-01, /* 3FD55555, 55555563 */ + 1.33333333333201242699e-01, /* 3FC11111, 1110FE7A */ + 5.39682539762260521377e-02, /* 3FABA1BA, 1BB341FE */ + 2.18694882948595424599e-02, /* 3F9664F4, 8406D637 */ + 8.86323982359930005737e-03, /* 3F8226E3, E96E8493 */ + 3.59207910759131235356e-03, /* 3F6D6D22, C9560328 */ + 1.45620945432529025516e-03, /* 3F57DBC8, FEE08315 */ + 5.88041240820264096874e-04, /* 3F4344D8, F2F26501 */ + 2.46463134818469906812e-04, /* 3F3026F7, 1A8D1068 */ + 7.81794442939557092300e-05, /* 3F147E88, A03792A6 */ + 7.14072491382608190305e-05, /* 3F12B80F, 32F0A7E9 */ + -1.85586374855275456654e-05, /* BEF375CB, DB605373 */ + 2.59073051863633712884e-05, /* 3EFB2A70, 74BF7AD4 */ + /* one */ 1.00000000000000000000e+00, /* 3FF00000, 00000000 */ + /* pio4 */ 7.85398163397448278999e-01, /* 3FE921FB, 54442D18 */ + /* pio4lo */ 3.06161699786838301793e-17 /* 3C81A626, 33145C07 */ + }; +#define one xxx[13] +#define pio4 xxx[14] +#define pio4lo xxx[15] +#define T xxx + + double z, r, v, w, s; + int32_t ix, hx; + + GET_HIGH_WORD(hx, x); /* high word of x */ + ix = hx & 0x7FFFFFFF; /* high word of |x| */ + if (ix < 0x3E300000) { /* x < 2**-28 */ + if (static_cast<int>(x) == 0) { /* generate inexact */ + uint32_t low; + GET_LOW_WORD(low, x); + if (((ix | low) | (iy + 1)) == 0) { + return one / fabs(x); + } else { + if (iy == 1) { + return x; + } else { /* compute -1 / (x+y) carefully */ + double a, t; + + z = w = x + y; + SET_LOW_WORD(z, 0); + v = y - (z - x); + t = a = -one / w; + SET_LOW_WORD(t, 0); + s = one + t * z; + return t + a * (s + t * v); + } + } + } + } + if (ix >= 0x3FE59428) { /* |x| >= 0.6744 */ + if (hx < 0) { + x = -x; + y = -y; + } + z = pio4 - x; + w = pio4lo - y; + x = z + w; + y = 0.0; + } + z = x * x; + w = z * z; + /* + * Break x^5*(T[1]+x^2*T[2]+...) into + * x^5(T[1]+x^4*T[3]+...+x^20*T[11]) + + * x^5(x^2*(T[2]+x^4*T[4]+...+x^22*[T12])) + */ + r = T[1] + w * (T[3] + w * (T[5] + w * (T[7] + w * (T[9] + w * T[11])))); + v = z * + (T[2] + w * (T[4] + w * (T[6] + w * (T[8] + w * (T[10] + w * T[12]))))); + s = z * x; + r = y + z * (s * (r + v) + y); + r += T[0] * s; + w = x + r; + if (ix >= 0x3FE59428) { + v = iy; + return (1 - ((hx >> 30) & 2)) * (v - 2.0 * (x - (w * w / (w + v) - r))); + } + if (iy == 1) { + return w; + } else { + /* + * if allow error up to 2 ulp, simply return + * -1.0 / (x+r) here + */ + /* compute -1.0 / (x+r) accurately */ + double a, t; + z = w; + SET_LOW_WORD(z, 0); + v = r - (z - x); /* z+v = r+x */ + t = a = -1.0 / w; /* a = -1.0/w */ + SET_LOW_WORD(t, 0); + s = 1.0 + t * z; + return t + a * (s + t * v); + } + +#undef one +#undef pio4 +#undef pio4lo +#undef T +} + +} // namespace + +/* acos(x) + * Method : + * acos(x) = pi/2 - asin(x) + * acos(-x) = pi/2 + asin(x) + * For |x|<=0.5 + * acos(x) = pi/2 - (x + x*x^2*R(x^2)) (see asin.c) + * For x>0.5 + * acos(x) = pi/2 - (pi/2 - 2asin(sqrt((1-x)/2))) + * = 2asin(sqrt((1-x)/2)) + * = 2s + 2s*z*R(z) ...z=(1-x)/2, s=sqrt(z) + * = 2f + (2c + 2s*z*R(z)) + * where f=hi part of s, and c = (z-f*f)/(s+f) is the correction term + * for f so that f+c ~ sqrt(z). + * For x<-0.5 + * acos(x) = pi - 2asin(sqrt((1-|x|)/2)) + * = pi - 0.5*(s+s*z*R(z)), where z=(1-|x|)/2,s=sqrt(z) + * + * Special cases: + * if x is NaN, return x itself; + * if |x|>1, return NaN with invalid signal. + * + * Function needed: sqrt + */ +double acos(double x) { + static const double + one = 1.00000000000000000000e+00, /* 0x3FF00000, 0x00000000 */ + pi = 3.14159265358979311600e+00, /* 0x400921FB, 0x54442D18 */ + pio2_hi = 1.57079632679489655800e+00, /* 0x3FF921FB, 0x54442D18 */ + pio2_lo = 6.12323399573676603587e-17, /* 0x3C91A626, 0x33145C07 */ + pS0 = 1.66666666666666657415e-01, /* 0x3FC55555, 0x55555555 */ + pS1 = -3.25565818622400915405e-01, /* 0xBFD4D612, 0x03EB6F7D */ + pS2 = 2.01212532134862925881e-01, /* 0x3FC9C155, 0x0E884455 */ + pS3 = -4.00555345006794114027e-02, /* 0xBFA48228, 0xB5688F3B */ + pS4 = 7.91534994289814532176e-04, /* 0x3F49EFE0, 0x7501B288 */ + pS5 = 3.47933107596021167570e-05, /* 0x3F023DE1, 0x0DFDF709 */ + qS1 = -2.40339491173441421878e+00, /* 0xC0033A27, 0x1C8A2D4B */ + qS2 = 2.02094576023350569471e+00, /* 0x40002AE5, 0x9C598AC8 */ + qS3 = -6.88283971605453293030e-01, /* 0xBFE6066C, 0x1B8D0159 */ + qS4 = 7.70381505559019352791e-02; /* 0x3FB3B8C5, 0xB12E9282 */ + + double z, p, q, r, w, s, c, df; + int32_t hx, ix; + GET_HIGH_WORD(hx, x); + ix = hx & 0x7FFFFFFF; + if (ix >= 0x3FF00000) { /* |x| >= 1 */ + uint32_t lx; + GET_LOW_WORD(lx, x); + if (((ix - 0x3FF00000) | lx) == 0) { /* |x|==1 */ + if (hx > 0) + return 0.0; /* acos(1) = 0 */ + else + return pi + 2.0 * pio2_lo; /* acos(-1)= pi */ + } + return std::numeric_limits<double>::signaling_NaN(); // acos(|x|>1) is NaN + } + if (ix < 0x3FE00000) { /* |x| < 0.5 */ + if (ix <= 0x3C600000) return pio2_hi + pio2_lo; /*if|x|<2**-57*/ + z = x * x; + p = z * (pS0 + z * (pS1 + z * (pS2 + z * (pS3 + z * (pS4 + z * pS5))))); + q = one + z * (qS1 + z * (qS2 + z * (qS3 + z * qS4))); + r = p / q; + return pio2_hi - (x - (pio2_lo - x * r)); + } else if (hx < 0) { /* x < -0.5 */ + z = (one + x) * 0.5; + p = z * (pS0 + z * (pS1 + z * (pS2 + z * (pS3 + z * (pS4 + z * pS5))))); + q = one + z * (qS1 + z * (qS2 + z * (qS3 + z * qS4))); + s = sqrt(z); + r = p / q; + w = r * s - pio2_lo; + return pi - 2.0 * (s + w); + } else { /* x > 0.5 */ + z = (one - x) * 0.5; + s = sqrt(z); + df = s; + SET_LOW_WORD(df, 0); + c = (z - df * df) / (s + df); + p = z * (pS0 + z * (pS1 + z * (pS2 + z * (pS3 + z * (pS4 + z * pS5))))); + q = one + z * (qS1 + z * (qS2 + z * (qS3 + z * qS4))); + r = p / q; + w = r * s + c; + return 2.0 * (df + w); + } +} + +/* acosh(x) + * Method : + * Based on + * acosh(x) = log [ x + sqrt(x*x-1) ] + * we have + * acosh(x) := log(x)+ln2, if x is large; else + * acosh(x) := log(2x-1/(sqrt(x*x-1)+x)) if x>2; else + * acosh(x) := log1p(t+sqrt(2.0*t+t*t)); where t=x-1. + * + * Special cases: + * acosh(x) is NaN with signal if x<1. + * acosh(NaN) is NaN without signal. + */ +double acosh(double x) { + static const double + one = 1.0, + ln2 = 6.93147180559945286227e-01; /* 0x3FE62E42, 0xFEFA39EF */ + double t; + int32_t hx; + uint32_t lx; + EXTRACT_WORDS(hx, lx, x); + if (hx < 0x3FF00000) { /* x < 1 */ + return std::numeric_limits<double>::signaling_NaN(); + } else if (hx >= 0x41B00000) { /* x > 2**28 */ + if (hx >= 0x7FF00000) { /* x is inf of NaN */ + return x + x; + } else { + return log(x) + ln2; /* acosh(huge)=log(2x) */ + } + } else if (((hx - 0x3FF00000) | lx) == 0) { + return 0.0; /* acosh(1) = 0 */ + } else if (hx > 0x40000000) { /* 2**28 > x > 2 */ + t = x * x; + return log(2.0 * x - one / (x + sqrt(t - one))); + } else { /* 1<x<2 */ + t = x - one; + return log1p(t + sqrt(2.0 * t + t * t)); + } +} + +/* asin(x) + * Method : + * Since asin(x) = x + x^3/6 + x^5*3/40 + x^7*15/336 + ... + * we approximate asin(x) on [0,0.5] by + * asin(x) = x + x*x^2*R(x^2) + * where + * R(x^2) is a rational approximation of (asin(x)-x)/x^3 + * and its remez error is bounded by + * |(asin(x)-x)/x^3 - R(x^2)| < 2^(-58.75) + * + * For x in [0.5,1] + * asin(x) = pi/2-2*asin(sqrt((1-x)/2)) + * Let y = (1-x), z = y/2, s := sqrt(z), and pio2_hi+pio2_lo=pi/2; + * then for x>0.98 + * asin(x) = pi/2 - 2*(s+s*z*R(z)) + * = pio2_hi - (2*(s+s*z*R(z)) - pio2_lo) + * For x<=0.98, let pio4_hi = pio2_hi/2, then + * f = hi part of s; + * c = sqrt(z) - f = (z-f*f)/(s+f) ...f+c=sqrt(z) + * and + * asin(x) = pi/2 - 2*(s+s*z*R(z)) + * = pio4_hi+(pio4-2s)-(2s*z*R(z)-pio2_lo) + * = pio4_hi+(pio4-2f)-(2s*z*R(z)-(pio2_lo+2c)) + * + * Special cases: + * if x is NaN, return x itself; + * if |x|>1, return NaN with invalid signal. + */ +double asin(double x) { + static const double + one = 1.00000000000000000000e+00, /* 0x3FF00000, 0x00000000 */ + huge = 1.000e+300, + pio2_hi = 1.57079632679489655800e+00, /* 0x3FF921FB, 0x54442D18 */ + pio2_lo = 6.12323399573676603587e-17, /* 0x3C91A626, 0x33145C07 */ + pio4_hi = 7.85398163397448278999e-01, /* 0x3FE921FB, 0x54442D18 */ + /* coefficient for R(x^2) */ + pS0 = 1.66666666666666657415e-01, /* 0x3FC55555, 0x55555555 */ + pS1 = -3.25565818622400915405e-01, /* 0xBFD4D612, 0x03EB6F7D */ + pS2 = 2.01212532134862925881e-01, /* 0x3FC9C155, 0x0E884455 */ + pS3 = -4.00555345006794114027e-02, /* 0xBFA48228, 0xB5688F3B */ + pS4 = 7.91534994289814532176e-04, /* 0x3F49EFE0, 0x7501B288 */ + pS5 = 3.47933107596021167570e-05, /* 0x3F023DE1, 0x0DFDF709 */ + qS1 = -2.40339491173441421878e+00, /* 0xC0033A27, 0x1C8A2D4B */ + qS2 = 2.02094576023350569471e+00, /* 0x40002AE5, 0x9C598AC8 */ + qS3 = -6.88283971605453293030e-01, /* 0xBFE6066C, 0x1B8D0159 */ + qS4 = 7.70381505559019352791e-02; /* 0x3FB3B8C5, 0xB12E9282 */ + + double t, w, p, q, c, r, s; + int32_t hx, ix; + + t = 0; + GET_HIGH_WORD(hx, x); + ix = hx & 0x7FFFFFFF; + if (ix >= 0x3FF00000) { /* |x|>= 1 */ + uint32_t lx; + GET_LOW_WORD(lx, x); + if (((ix - 0x3FF00000) | lx) == 0) { /* asin(1)=+-pi/2 with inexact */ + return x * pio2_hi + x * pio2_lo; + } + return std::numeric_limits<double>::signaling_NaN(); // asin(|x|>1) is NaN + } else if (ix < 0x3FE00000) { /* |x|<0.5 */ + if (ix < 0x3E400000) { /* if |x| < 2**-27 */ + if (huge + x > one) return x; /* return x with inexact if x!=0*/ + } else { + t = x * x; + } + p = t * (pS0 + t * (pS1 + t * (pS2 + t * (pS3 + t * (pS4 + t * pS5))))); + q = one + t * (qS1 + t * (qS2 + t * (qS3 + t * qS4))); + w = p / q; + return x + x * w; + } + /* 1> |x|>= 0.5 */ + w = one - fabs(x); + t = w * 0.5; + p = t * (pS0 + t * (pS1 + t * (pS2 + t * (pS3 + t * (pS4 + t * pS5))))); + q = one + t * (qS1 + t * (qS2 + t * (qS3 + t * qS4))); + s = sqrt(t); + if (ix >= 0x3FEF3333) { /* if |x| > 0.975 */ + w = p / q; + t = pio2_hi - (2.0 * (s + s * w) - pio2_lo); + } else { + w = s; + SET_LOW_WORD(w, 0); + c = (t - w * w) / (s + w); + r = p / q; + p = 2.0 * s * r - (pio2_lo - 2.0 * c); + q = pio4_hi - 2.0 * w; + t = pio4_hi - (p - q); + } + if (hx > 0) + return t; + else + return -t; +} +/* asinh(x) + * Method : + * Based on + * asinh(x) = sign(x) * log [ |x| + sqrt(x*x+1) ] + * we have + * asinh(x) := x if 1+x*x=1, + * := sign(x)*(log(x)+ln2)) for large |x|, else + * := sign(x)*log(2|x|+1/(|x|+sqrt(x*x+1))) if|x|>2, else + * := sign(x)*log1p(|x| + x^2/(1 + sqrt(1+x^2))) + */ +double asinh(double x) { + static const double + one = 1.00000000000000000000e+00, /* 0x3FF00000, 0x00000000 */ + ln2 = 6.93147180559945286227e-01, /* 0x3FE62E42, 0xFEFA39EF */ + huge = 1.00000000000000000000e+300; + + double t, w; + int32_t hx, ix; + GET_HIGH_WORD(hx, x); + ix = hx & 0x7FFFFFFF; + if (ix >= 0x7FF00000) return x + x; /* x is inf or NaN */ + if (ix < 0x3E300000) { /* |x|<2**-28 */ + if (huge + x > one) return x; /* return x inexact except 0 */ + } + if (ix > 0x41B00000) { /* |x| > 2**28 */ + w = log(fabs(x)) + ln2; + } else if (ix > 0x40000000) { /* 2**28 > |x| > 2.0 */ + t = fabs(x); + w = log(2.0 * t + one / (sqrt(x * x + one) + t)); + } else { /* 2.0 > |x| > 2**-28 */ + t = x * x; + w = log1p(fabs(x) + t / (one + sqrt(one + t))); + } + if (hx > 0) { + return w; + } else { + return -w; + } +} + +/* atan(x) + * Method + * 1. Reduce x to positive by atan(x) = -atan(-x). + * 2. According to the integer k=4t+0.25 chopped, t=x, the argument + * is further reduced to one of the following intervals and the + * arctangent of t is evaluated by the corresponding formula: + * + * [0,7/16] atan(x) = t-t^3*(a1+t^2*(a2+...(a10+t^2*a11)...) + * [7/16,11/16] atan(x) = atan(1/2) + atan( (t-0.5)/(1+t/2) ) + * [11/16.19/16] atan(x) = atan( 1 ) + atan( (t-1)/(1+t) ) + * [19/16,39/16] atan(x) = atan(3/2) + atan( (t-1.5)/(1+1.5t) ) + * [39/16,INF] atan(x) = atan(INF) + atan( -1/t ) + * + * Constants: + * The hexadecimal values are the intended ones for the following + * constants. The decimal values may be used, provided that the + * compiler will convert from decimal to binary accurately enough + * to produce the hexadecimal values shown. + */ +double atan(double x) { + static const double atanhi[] = { + 4.63647609000806093515e-01, /* atan(0.5)hi 0x3FDDAC67, 0x0561BB4F */ + 7.85398163397448278999e-01, /* atan(1.0)hi 0x3FE921FB, 0x54442D18 */ + 9.82793723247329054082e-01, /* atan(1.5)hi 0x3FEF730B, 0xD281F69B */ + 1.57079632679489655800e+00, /* atan(inf)hi 0x3FF921FB, 0x54442D18 */ + }; + + static const double atanlo[] = { + 2.26987774529616870924e-17, /* atan(0.5)lo 0x3C7A2B7F, 0x222F65E2 */ + 3.06161699786838301793e-17, /* atan(1.0)lo 0x3C81A626, 0x33145C07 */ + 1.39033110312309984516e-17, /* atan(1.5)lo 0x3C700788, 0x7AF0CBBD */ + 6.12323399573676603587e-17, /* atan(inf)lo 0x3C91A626, 0x33145C07 */ + }; + + static const double aT[] = { + 3.33333333333329318027e-01, /* 0x3FD55555, 0x5555550D */ + -1.99999999998764832476e-01, /* 0xBFC99999, 0x9998EBC4 */ + 1.42857142725034663711e-01, /* 0x3FC24924, 0x920083FF */ + -1.11111104054623557880e-01, /* 0xBFBC71C6, 0xFE231671 */ + 9.09088713343650656196e-02, /* 0x3FB745CD, 0xC54C206E */ + -7.69187620504482999495e-02, /* 0xBFB3B0F2, 0xAF749A6D */ + 6.66107313738753120669e-02, /* 0x3FB10D66, 0xA0D03D51 */ + -5.83357013379057348645e-02, /* 0xBFADDE2D, 0x52DEFD9A */ + 4.97687799461593236017e-02, /* 0x3FA97B4B, 0x24760DEB */ + -3.65315727442169155270e-02, /* 0xBFA2B444, 0x2C6A6C2F */ + 1.62858201153657823623e-02, /* 0x3F90AD3A, 0xE322DA11 */ + }; + + static const double one = 1.0, huge = 1.0e300; + + double w, s1, s2, z; + int32_t ix, hx, id; + + GET_HIGH_WORD(hx, x); + ix = hx & 0x7FFFFFFF; + if (ix >= 0x44100000) { /* if |x| >= 2^66 */ + uint32_t low; + GET_LOW_WORD(low, x); + if (ix > 0x7FF00000 || (ix == 0x7FF00000 && (low != 0))) + return x + x; /* NaN */ + if (hx > 0) + return atanhi[3] + *const_cast<volatile double*>(&atanlo[3]); + else + return -atanhi[3] - *const_cast<volatile double*>(&atanlo[3]); + } + if (ix < 0x3FDC0000) { /* |x| < 0.4375 */ + if (ix < 0x3E400000) { /* |x| < 2^-27 */ + if (huge + x > one) return x; /* raise inexact */ + } + id = -1; + } else { + x = fabs(x); + if (ix < 0x3FF30000) { /* |x| < 1.1875 */ + if (ix < 0x3FE60000) { /* 7/16 <=|x|<11/16 */ + id = 0; + x = (2.0 * x - one) / (2.0 + x); + } else { /* 11/16<=|x|< 19/16 */ + id = 1; + x = (x - one) / (x + one); + } + } else { + if (ix < 0x40038000) { /* |x| < 2.4375 */ + id = 2; + x = (x - 1.5) / (one + 1.5 * x); + } else { /* 2.4375 <= |x| < 2^66 */ + id = 3; + x = -1.0 / x; + } + } + } + /* end of argument reduction */ + z = x * x; + w = z * z; + /* break sum from i=0 to 10 aT[i]z**(i+1) into odd and even poly */ + s1 = z * (aT[0] + + w * (aT[2] + w * (aT[4] + w * (aT[6] + w * (aT[8] + w * aT[10]))))); + s2 = w * (aT[1] + w * (aT[3] + w * (aT[5] + w * (aT[7] + w * aT[9])))); + if (id < 0) { + return x - x * (s1 + s2); + } else { + z = atanhi[id] - ((x * (s1 + s2) - atanlo[id]) - x); + return (hx < 0) ? -z : z; + } +} + +/* atan2(y,x) + * Method : + * 1. Reduce y to positive by atan2(y,x)=-atan2(-y,x). + * 2. Reduce x to positive by (if x and y are unexceptional): + * ARG (x+iy) = arctan(y/x) ... if x > 0, + * ARG (x+iy) = pi - arctan[y/(-x)] ... if x < 0, + * + * Special cases: + * + * ATAN2((anything), NaN ) is NaN; + * ATAN2(NAN , (anything) ) is NaN; + * ATAN2(+-0, +(anything but NaN)) is +-0 ; + * ATAN2(+-0, -(anything but NaN)) is +-pi ; + * ATAN2(+-(anything but 0 and NaN), 0) is +-pi/2; + * ATAN2(+-(anything but INF and NaN), +INF) is +-0 ; + * ATAN2(+-(anything but INF and NaN), -INF) is +-pi; + * ATAN2(+-INF,+INF ) is +-pi/4 ; + * ATAN2(+-INF,-INF ) is +-3pi/4; + * ATAN2(+-INF, (anything but,0,NaN, and INF)) is +-pi/2; + * + * Constants: + * The hexadecimal values are the intended ones for the following + * constants. The decimal values may be used, provided that the + * compiler will convert from decimal to binary accurately enough + * to produce the hexadecimal values shown. + */ +double atan2(double y, double x) { + static volatile double tiny = 1.0e-300; + static const double + zero = 0.0, + pi_o_4 = 7.8539816339744827900E-01, /* 0x3FE921FB, 0x54442D18 */ + pi_o_2 = 1.5707963267948965580E+00, /* 0x3FF921FB, 0x54442D18 */ + pi = 3.1415926535897931160E+00; /* 0x400921FB, 0x54442D18 */ + static volatile double pi_lo = + 1.2246467991473531772E-16; /* 0x3CA1A626, 0x33145C07 */ + + double z; + int32_t k, m, hx, hy, ix, iy; + uint32_t lx, ly; + + EXTRACT_WORDS(hx, lx, x); + ix = hx & 0x7FFFFFFF; + EXTRACT_WORDS(hy, ly, y); + iy = hy & 0x7FFFFFFF; + if (((ix | ((lx | NegateWithWraparound<int32_t>(lx)) >> 31)) > 0x7FF00000) || + ((iy | ((ly | NegateWithWraparound<int32_t>(ly)) >> 31)) > 0x7FF00000)) { + return x + y; /* x or y is NaN */ + } + if ((SubWithWraparound(hx, 0x3FF00000) | lx) == 0) { + return atan(y); /* x=1.0 */ + } + m = ((hy >> 31) & 1) | ((hx >> 30) & 2); /* 2*sign(x)+sign(y) */ + + /* when y = 0 */ + if ((iy | ly) == 0) { + switch (m) { + case 0: + case 1: + return y; /* atan(+-0,+anything)=+-0 */ + case 2: + return pi + tiny; /* atan(+0,-anything) = pi */ + case 3: + return -pi - tiny; /* atan(-0,-anything) =-pi */ + } + } + /* when x = 0 */ + if ((ix | lx) == 0) return (hy < 0) ? -pi_o_2 - tiny : pi_o_2 + tiny; + + /* when x is INF */ + if (ix == 0x7FF00000) { + if (iy == 0x7FF00000) { + switch (m) { + case 0: + return pi_o_4 + tiny; /* atan(+INF,+INF) */ + case 1: + return -pi_o_4 - tiny; /* atan(-INF,+INF) */ + case 2: + return 3.0 * pi_o_4 + tiny; /*atan(+INF,-INF)*/ + case 3: + return -3.0 * pi_o_4 - tiny; /*atan(-INF,-INF)*/ + } + } else { + switch (m) { + case 0: + return zero; /* atan(+...,+INF) */ + case 1: + return -zero; /* atan(-...,+INF) */ + case 2: + return pi + tiny; /* atan(+...,-INF) */ + case 3: + return -pi - tiny; /* atan(-...,-INF) */ + } + } + } + /* when y is INF */ + if (iy == 0x7FF00000) return (hy < 0) ? -pi_o_2 - tiny : pi_o_2 + tiny; + + /* compute y/x */ + k = (iy - ix) >> 20; + if (k > 60) { /* |y/x| > 2**60 */ + z = pi_o_2 + 0.5 * pi_lo; + m &= 1; + } else if (hx < 0 && k < -60) { + z = 0.0; /* 0 > |y|/x > -2**-60 */ + } else { + z = atan(fabs(y / x)); /* safe to do y/x */ + } + switch (m) { + case 0: + return z; /* atan(+,+) */ + case 1: + return -z; /* atan(-,+) */ + case 2: + return pi - (z - pi_lo); /* atan(+,-) */ + default: /* case 3 */ + return (z - pi_lo) - pi; /* atan(-,-) */ + } +} + +/* cos(x) + * Return cosine function of x. + * + * kernel function: + * __kernel_sin ... sine function on [-pi/4,pi/4] + * __kernel_cos ... cosine function on [-pi/4,pi/4] + * __ieee754_rem_pio2 ... argument reduction routine + * + * Method. + * Let S,C and T denote the sin, cos and tan respectively on + * [-PI/4, +PI/4]. Reduce the argument x to y1+y2 = x-k*pi/2 + * in [-pi/4 , +pi/4], and let n = k mod 4. + * We have + * + * n sin(x) cos(x) tan(x) + * ---------------------------------------------------------- + * 0 S C T + * 1 C -S -1/T + * 2 -S -C T + * 3 -C S -1/T + * ---------------------------------------------------------- + * + * Special cases: + * Let trig be any of sin, cos, or tan. + * trig(+-INF) is NaN, with signals; + * trig(NaN) is that NaN; + * + * Accuracy: + * TRIG(x) returns trig(x) nearly rounded + */ +double cos(double x) { + double y[2], z = 0.0; + int32_t n, ix; + + /* High word of x. */ + GET_HIGH_WORD(ix, x); + + /* |x| ~< pi/4 */ + ix &= 0x7FFFFFFF; + if (ix <= 0x3FE921FB) { + return __kernel_cos(x, z); + } else if (ix >= 0x7FF00000) { + /* cos(Inf or NaN) is NaN */ + return x - x; + } else { + /* argument reduction needed */ + n = __ieee754_rem_pio2(x, y); + switch (n & 3) { + case 0: + return __kernel_cos(y[0], y[1]); + case 1: + return -__kernel_sin(y[0], y[1], 1); + case 2: + return -__kernel_cos(y[0], y[1]); + default: + return __kernel_sin(y[0], y[1], 1); + } + } +} + +/* exp(x) + * Returns the exponential of x. + * + * Method + * 1. Argument reduction: + * Reduce x to an r so that |r| <= 0.5*ln2 ~ 0.34658. + * Given x, find r and integer k such that + * + * x = k*ln2 + r, |r| <= 0.5*ln2. + * + * Here r will be represented as r = hi-lo for better + * accuracy. + * + * 2. Approximation of exp(r) by a special rational function on + * the interval [0,0.34658]: + * Write + * R(r**2) = r*(exp(r)+1)/(exp(r)-1) = 2 + r*r/6 - r**4/360 + ... + * We use a special Remes algorithm on [0,0.34658] to generate + * a polynomial of degree 5 to approximate R. The maximum error + * of this polynomial approximation is bounded by 2**-59. In + * other words, + * R(z) ~ 2.0 + P1*z + P2*z**2 + P3*z**3 + P4*z**4 + P5*z**5 + * (where z=r*r, and the values of P1 to P5 are listed below) + * and + * | 5 | -59 + * | 2.0+P1*z+...+P5*z - R(z) | <= 2 + * | | + * The computation of exp(r) thus becomes + * 2*r + * exp(r) = 1 + ------- + * R - r + * r*R1(r) + * = 1 + r + ----------- (for better accuracy) + * 2 - R1(r) + * where + * 2 4 10 + * R1(r) = r - (P1*r + P2*r + ... + P5*r ). + * + * 3. Scale back to obtain exp(x): + * From step 1, we have + * exp(x) = 2^k * exp(r) + * + * Special cases: + * exp(INF) is INF, exp(NaN) is NaN; + * exp(-INF) is 0, and + * for finite argument, only exp(0)=1 is exact. + * + * Accuracy: + * according to an error analysis, the error is always less than + * 1 ulp (unit in the last place). + * + * Misc. info. + * For IEEE double + * if x > 7.09782712893383973096e+02 then exp(x) overflow + * if x < -7.45133219101941108420e+02 then exp(x) underflow + * + * Constants: + * The hexadecimal values are the intended ones for the following + * constants. The decimal values may be used, provided that the + * compiler will convert from decimal to binary accurately enough + * to produce the hexadecimal values shown. + */ +double exp(double x) { + static const double + one = 1.0, + halF[2] = {0.5, -0.5}, + o_threshold = 7.09782712893383973096e+02, /* 0x40862E42, 0xFEFA39EF */ + u_threshold = -7.45133219101941108420e+02, /* 0xC0874910, 0xD52D3051 */ + ln2HI[2] = {6.93147180369123816490e-01, /* 0x3FE62E42, 0xFEE00000 */ + -6.93147180369123816490e-01}, /* 0xBFE62E42, 0xFEE00000 */ + ln2LO[2] = {1.90821492927058770002e-10, /* 0x3DEA39EF, 0x35793C76 */ + -1.90821492927058770002e-10}, /* 0xBDEA39EF, 0x35793C76 */ + invln2 = 1.44269504088896338700e+00, /* 0x3FF71547, 0x652B82FE */ + P1 = 1.66666666666666019037e-01, /* 0x3FC55555, 0x5555553E */ + P2 = -2.77777777770155933842e-03, /* 0xBF66C16C, 0x16BEBD93 */ + P3 = 6.61375632143793436117e-05, /* 0x3F11566A, 0xAF25DE2C */ + P4 = -1.65339022054652515390e-06, /* 0xBEBBBD41, 0xC5D26BF1 */ + P5 = 4.13813679705723846039e-08, /* 0x3E663769, 0x72BEA4D0 */ + E = 2.718281828459045; /* 0x4005BF0A, 0x8B145769 */ + + static volatile double + huge = 1.0e+300, + twom1000 = 9.33263618503218878990e-302, /* 2**-1000=0x01700000,0*/ + two1023 = 8.988465674311579539e307; /* 0x1p1023 */ + + double y, hi = 0.0, lo = 0.0, c, t, twopk; + int32_t k = 0, xsb; + uint32_t hx; + + GET_HIGH_WORD(hx, x); + xsb = (hx >> 31) & 1; /* sign bit of x */ + hx &= 0x7FFFFFFF; /* high word of |x| */ + + /* filter out non-finite argument */ + if (hx >= 0x40862E42) { /* if |x|>=709.78... */ + if (hx >= 0x7FF00000) { + uint32_t lx; + GET_LOW_WORD(lx, x); + if (((hx & 0xFFFFF) | lx) != 0) + return x + x; /* NaN */ + else + return (xsb == 0) ? x : 0.0; /* exp(+-inf)={inf,0} */ + } + if (x > o_threshold) return huge * huge; /* overflow */ + if (x < u_threshold) return twom1000 * twom1000; /* underflow */ + } + + /* argument reduction */ + if (hx > 0x3FD62E42) { /* if |x| > 0.5 ln2 */ + if (hx < 0x3FF0A2B2) { /* and |x| < 1.5 ln2 */ + /* TODO(rtoy): We special case exp(1) here to return the correct + * value of E, as the computation below would get the last bit + * wrong. We should probably fix the algorithm instead. + */ + if (x == 1.0) return E; + hi = x - ln2HI[xsb]; + lo = ln2LO[xsb]; + k = 1 - xsb - xsb; + } else { + k = static_cast<int>(invln2 * x + halF[xsb]); + t = k; + hi = x - t * ln2HI[0]; /* t*ln2HI is exact here */ + lo = t * ln2LO[0]; + } + x = hi - lo; + } else if (hx < 0x3E300000) { /* when |x|<2**-28 */ + if (huge + x > one) return one + x; /* trigger inexact */ + } else { + k = 0; + } + + /* x is now in primary range */ + t = x * x; + if (k >= -1021) { + INSERT_WORDS( + twopk, + 0x3FF00000 + static_cast<int32_t>(static_cast<uint32_t>(k) << 20), 0); + } else { + INSERT_WORDS(twopk, 0x3FF00000 + (static_cast<uint32_t>(k + 1000) << 20), + 0); + } + c = x - t * (P1 + t * (P2 + t * (P3 + t * (P4 + t * P5)))); + if (k == 0) { + return one - ((x * c) / (c - 2.0) - x); + } else { + y = one - ((lo - (x * c) / (2.0 - c)) - hi); + } + if (k >= -1021) { + if (k == 1024) return y * 2.0 * two1023; + return y * twopk; + } else { + return y * twopk * twom1000; + } +} + +/* + * Method : + * 1.Reduced x to positive by atanh(-x) = -atanh(x) + * 2.For x>=0.5 + * 1 2x x + * atanh(x) = --- * log(1 + -------) = 0.5 * log1p(2 * --------) + * 2 1 - x 1 - x + * + * For x<0.5 + * atanh(x) = 0.5*log1p(2x+2x*x/(1-x)) + * + * Special cases: + * atanh(x) is NaN if |x| > 1 with signal; + * atanh(NaN) is that NaN with no signal; + * atanh(+-1) is +-INF with signal. + * + */ +double atanh(double x) { + static const double one = 1.0, huge = 1e300; + static const double zero = 0.0; + + double t; + int32_t hx, ix; + uint32_t lx; + EXTRACT_WORDS(hx, lx, x); + ix = hx & 0x7FFFFFFF; + if ((ix | ((lx | NegateWithWraparound<int32_t>(lx)) >> 31)) > 0x3FF00000) { + /* |x|>1 */ + return std::numeric_limits<double>::signaling_NaN(); + } + if (ix == 0x3FF00000) { + return x > 0 ? std::numeric_limits<double>::infinity() + : -std::numeric_limits<double>::infinity(); + } + if (ix < 0x3E300000 && (huge + x) > zero) return x; /* x<2**-28 */ + SET_HIGH_WORD(x, ix); + if (ix < 0x3FE00000) { /* x < 0.5 */ + t = x + x; + t = 0.5 * log1p(t + t * x / (one - x)); + } else { + t = 0.5 * log1p((x + x) / (one - x)); + } + if (hx >= 0) + return t; + else + return -t; +} + +/* log(x) + * Return the logrithm of x + * + * Method : + * 1. Argument Reduction: find k and f such that + * x = 2^k * (1+f), + * where sqrt(2)/2 < 1+f < sqrt(2) . + * + * 2. Approximation of log(1+f). + * Let s = f/(2+f) ; based on log(1+f) = log(1+s) - log(1-s) + * = 2s + 2/3 s**3 + 2/5 s**5 + ....., + * = 2s + s*R + * We use a special Reme algorithm on [0,0.1716] to generate + * a polynomial of degree 14 to approximate R The maximum error + * of this polynomial approximation is bounded by 2**-58.45. In + * other words, + * 2 4 6 8 10 12 14 + * R(z) ~ Lg1*s +Lg2*s +Lg3*s +Lg4*s +Lg5*s +Lg6*s +Lg7*s + * (the values of Lg1 to Lg7 are listed in the program) + * and + * | 2 14 | -58.45 + * | Lg1*s +...+Lg7*s - R(z) | <= 2 + * | | + * Note that 2s = f - s*f = f - hfsq + s*hfsq, where hfsq = f*f/2. + * In order to guarantee error in log below 1ulp, we compute log + * by + * log(1+f) = f - s*(f - R) (if f is not too large) + * log(1+f) = f - (hfsq - s*(hfsq+R)). (better accuracy) + * + * 3. Finally, log(x) = k*ln2 + log(1+f). + * = k*ln2_hi+(f-(hfsq-(s*(hfsq+R)+k*ln2_lo))) + * Here ln2 is split into two floating point number: + * ln2_hi + ln2_lo, + * where n*ln2_hi is always exact for |n| < 2000. + * + * Special cases: + * log(x) is NaN with signal if x < 0 (including -INF) ; + * log(+INF) is +INF; log(0) is -INF with signal; + * log(NaN) is that NaN with no signal. + * + * Accuracy: + * according to an error analysis, the error is always less than + * 1 ulp (unit in the last place). + * + * Constants: + * The hexadecimal values are the intended ones for the following + * constants. The decimal values may be used, provided that the + * compiler will convert from decimal to binary accurately enough + * to produce the hexadecimal values shown. + */ +double log(double x) { + static const double /* -- */ + ln2_hi = 6.93147180369123816490e-01, /* 3fe62e42 fee00000 */ + ln2_lo = 1.90821492927058770002e-10, /* 3dea39ef 35793c76 */ + two54 = 1.80143985094819840000e+16, /* 43500000 00000000 */ + Lg1 = 6.666666666666735130e-01, /* 3FE55555 55555593 */ + Lg2 = 3.999999999940941908e-01, /* 3FD99999 9997FA04 */ + Lg3 = 2.857142874366239149e-01, /* 3FD24924 94229359 */ + Lg4 = 2.222219843214978396e-01, /* 3FCC71C5 1D8E78AF */ + Lg5 = 1.818357216161805012e-01, /* 3FC74664 96CB03DE */ + Lg6 = 1.531383769920937332e-01, /* 3FC39A09 D078C69F */ + Lg7 = 1.479819860511658591e-01; /* 3FC2F112 DF3E5244 */ + + static const double zero = 0.0; + + double hfsq, f, s, z, R, w, t1, t2, dk; + int32_t k, hx, i, j; + uint32_t lx; + + EXTRACT_WORDS(hx, lx, x); + + k = 0; + if (hx < 0x00100000) { /* x < 2**-1022 */ + if (((hx & 0x7FFFFFFF) | lx) == 0) { + return -std::numeric_limits<double>::infinity(); /* log(+-0)=-inf */ + } + if (hx < 0) { + return std::numeric_limits<double>::signaling_NaN(); /* log(-#) = NaN */ + } + k -= 54; + x *= two54; /* subnormal number, scale up x */ + GET_HIGH_WORD(hx, x); + } + if (hx >= 0x7FF00000) return x + x; + k += (hx >> 20) - 1023; + hx &= 0x000FFFFF; + i = (hx + 0x95F64) & 0x100000; + SET_HIGH_WORD(x, hx | (i ^ 0x3FF00000)); /* normalize x or x/2 */ + k += (i >> 20); + f = x - 1.0; + if ((0x000FFFFF & (2 + hx)) < 3) { /* -2**-20 <= f < 2**-20 */ + if (f == zero) { + if (k == 0) { + return zero; + } else { + dk = static_cast<double>(k); + return dk * ln2_hi + dk * ln2_lo; + } + } + R = f * f * (0.5 - 0.33333333333333333 * f); + if (k == 0) { + return f - R; + } else { + dk = static_cast<double>(k); + return dk * ln2_hi - ((R - dk * ln2_lo) - f); + } + } + s = f / (2.0 + f); + dk = static_cast<double>(k); + z = s * s; + i = hx - 0x6147A; + w = z * z; + j = 0x6B851 - hx; + t1 = w * (Lg2 + w * (Lg4 + w * Lg6)); + t2 = z * (Lg1 + w * (Lg3 + w * (Lg5 + w * Lg7))); + i |= j; + R = t2 + t1; + if (i > 0) { + hfsq = 0.5 * f * f; + if (k == 0) + return f - (hfsq - s * (hfsq + R)); + else + return dk * ln2_hi - ((hfsq - (s * (hfsq + R) + dk * ln2_lo)) - f); + } else { + if (k == 0) + return f - s * (f - R); + else + return dk * ln2_hi - ((s * (f - R) - dk * ln2_lo) - f); + } +} + +/* double log1p(double x) + * + * Method : + * 1. Argument Reduction: find k and f such that + * 1+x = 2^k * (1+f), + * where sqrt(2)/2 < 1+f < sqrt(2) . + * + * Note. If k=0, then f=x is exact. However, if k!=0, then f + * may not be representable exactly. In that case, a correction + * term is need. Let u=1+x rounded. Let c = (1+x)-u, then + * log(1+x) - log(u) ~ c/u. Thus, we proceed to compute log(u), + * and add back the correction term c/u. + * (Note: when x > 2**53, one can simply return log(x)) + * + * 2. Approximation of log1p(f). + * Let s = f/(2+f) ; based on log(1+f) = log(1+s) - log(1-s) + * = 2s + 2/3 s**3 + 2/5 s**5 + ....., + * = 2s + s*R + * We use a special Reme algorithm on [0,0.1716] to generate + * a polynomial of degree 14 to approximate R The maximum error + * of this polynomial approximation is bounded by 2**-58.45. In + * other words, + * 2 4 6 8 10 12 14 + * R(z) ~ Lp1*s +Lp2*s +Lp3*s +Lp4*s +Lp5*s +Lp6*s +Lp7*s + * (the values of Lp1 to Lp7 are listed in the program) + * and + * | 2 14 | -58.45 + * | Lp1*s +...+Lp7*s - R(z) | <= 2 + * | | + * Note that 2s = f - s*f = f - hfsq + s*hfsq, where hfsq = f*f/2. + * In order to guarantee error in log below 1ulp, we compute log + * by + * log1p(f) = f - (hfsq - s*(hfsq+R)). + * + * 3. Finally, log1p(x) = k*ln2 + log1p(f). + * = k*ln2_hi+(f-(hfsq-(s*(hfsq+R)+k*ln2_lo))) + * Here ln2 is split into two floating point number: + * ln2_hi + ln2_lo, + * where n*ln2_hi is always exact for |n| < 2000. + * + * Special cases: + * log1p(x) is NaN with signal if x < -1 (including -INF) ; + * log1p(+INF) is +INF; log1p(-1) is -INF with signal; + * log1p(NaN) is that NaN with no signal. + * + * Accuracy: + * according to an error analysis, the error is always less than + * 1 ulp (unit in the last place). + * + * Constants: + * The hexadecimal values are the intended ones for the following + * constants. The decimal values may be used, provided that the + * compiler will convert from decimal to binary accurately enough + * to produce the hexadecimal values shown. + * + * Note: Assuming log() return accurate answer, the following + * algorithm can be used to compute log1p(x) to within a few ULP: + * + * u = 1+x; + * if(u==1.0) return x ; else + * return log(u)*(x/(u-1.0)); + * + * See HP-15C Advanced Functions Handbook, p.193. + */ +double log1p(double x) { + static const double /* -- */ + ln2_hi = 6.93147180369123816490e-01, /* 3fe62e42 fee00000 */ + ln2_lo = 1.90821492927058770002e-10, /* 3dea39ef 35793c76 */ + two54 = 1.80143985094819840000e+16, /* 43500000 00000000 */ + Lp1 = 6.666666666666735130e-01, /* 3FE55555 55555593 */ + Lp2 = 3.999999999940941908e-01, /* 3FD99999 9997FA04 */ + Lp3 = 2.857142874366239149e-01, /* 3FD24924 94229359 */ + Lp4 = 2.222219843214978396e-01, /* 3FCC71C5 1D8E78AF */ + Lp5 = 1.818357216161805012e-01, /* 3FC74664 96CB03DE */ + Lp6 = 1.531383769920937332e-01, /* 3FC39A09 D078C69F */ + Lp7 = 1.479819860511658591e-01; /* 3FC2F112 DF3E5244 */ + + static const double zero = 0.0; + + double hfsq, f, c, s, z, R, u; + int32_t k, hx, hu, ax; + + GET_HIGH_WORD(hx, x); + ax = hx & 0x7FFFFFFF; + + k = 1; + if (hx < 0x3FDA827A) { /* 1+x < sqrt(2)+ */ + if (ax >= 0x3FF00000) { /* x <= -1.0 */ + if (x == -1.0) + return -std::numeric_limits<double>::infinity(); /* log1p(-1)=+inf */ + else + return std::numeric_limits<double>::signaling_NaN(); // log1p(x<-1)=NaN + } + if (ax < 0x3E200000) { /* |x| < 2**-29 */ + if (two54 + x > zero /* raise inexact */ + && ax < 0x3C900000) /* |x| < 2**-54 */ + return x; + else + return x - x * x * 0.5; + } + if (hx > 0 || hx <= static_cast<int32_t>(0xBFD2BEC4)) { + k = 0; + f = x; + hu = 1; + } /* sqrt(2)/2- <= 1+x < sqrt(2)+ */ + } + if (hx >= 0x7FF00000) return x + x; + if (k != 0) { + if (hx < 0x43400000) { + u = 1.0 + x; + GET_HIGH_WORD(hu, u); + k = (hu >> 20) - 1023; + c = (k > 0) ? 1.0 - (u - x) : x - (u - 1.0); /* correction term */ + c /= u; + } else { + u = x; + GET_HIGH_WORD(hu, u); + k = (hu >> 20) - 1023; + c = 0; + } + hu &= 0x000FFFFF; + /* + * The approximation to sqrt(2) used in thresholds is not + * critical. However, the ones used above must give less + * strict bounds than the one here so that the k==0 case is + * never reached from here, since here we have committed to + * using the correction term but don't use it if k==0. + */ + if (hu < 0x6A09E) { /* u ~< sqrt(2) */ + SET_HIGH_WORD(u, hu | 0x3FF00000); /* normalize u */ + } else { + k += 1; + SET_HIGH_WORD(u, hu | 0x3FE00000); /* normalize u/2 */ + hu = (0x00100000 - hu) >> 2; + } + f = u - 1.0; + } + hfsq = 0.5 * f * f; + if (hu == 0) { /* |f| < 2**-20 */ + if (f == zero) { + if (k == 0) { + return zero; + } else { + c += k * ln2_lo; + return k * ln2_hi + c; + } + } + R = hfsq * (1.0 - 0.66666666666666666 * f); + if (k == 0) + return f - R; + else + return k * ln2_hi - ((R - (k * ln2_lo + c)) - f); + } + s = f / (2.0 + f); + z = s * s; + R = z * (Lp1 + + z * (Lp2 + z * (Lp3 + z * (Lp4 + z * (Lp5 + z * (Lp6 + z * Lp7)))))); + if (k == 0) + return f - (hfsq - s * (hfsq + R)); + else + return k * ln2_hi - ((hfsq - (s * (hfsq + R) + (k * ln2_lo + c))) - f); +} + +/* + * k_log1p(f): + * Return log(1+f) - f for 1+f in ~[sqrt(2)/2, sqrt(2)]. + * + * The following describes the overall strategy for computing + * logarithms in base e. The argument reduction and adding the final + * term of the polynomial are done by the caller for increased accuracy + * when different bases are used. + * + * Method : + * 1. Argument Reduction: find k and f such that + * x = 2^k * (1+f), + * where sqrt(2)/2 < 1+f < sqrt(2) . + * + * 2. Approximation of log(1+f). + * Let s = f/(2+f) ; based on log(1+f) = log(1+s) - log(1-s) + * = 2s + 2/3 s**3 + 2/5 s**5 + ....., + * = 2s + s*R + * We use a special Reme algorithm on [0,0.1716] to generate + * a polynomial of degree 14 to approximate R The maximum error + * of this polynomial approximation is bounded by 2**-58.45. In + * other words, + * 2 4 6 8 10 12 14 + * R(z) ~ Lg1*s +Lg2*s +Lg3*s +Lg4*s +Lg5*s +Lg6*s +Lg7*s + * (the values of Lg1 to Lg7 are listed in the program) + * and + * | 2 14 | -58.45 + * | Lg1*s +...+Lg7*s - R(z) | <= 2 + * | | + * Note that 2s = f - s*f = f - hfsq + s*hfsq, where hfsq = f*f/2. + * In order to guarantee error in log below 1ulp, we compute log + * by + * log(1+f) = f - s*(f - R) (if f is not too large) + * log(1+f) = f - (hfsq - s*(hfsq+R)). (better accuracy) + * + * 3. Finally, log(x) = k*ln2 + log(1+f). + * = k*ln2_hi+(f-(hfsq-(s*(hfsq+R)+k*ln2_lo))) + * Here ln2 is split into two floating point number: + * ln2_hi + ln2_lo, + * where n*ln2_hi is always exact for |n| < 2000. + * + * Special cases: + * log(x) is NaN with signal if x < 0 (including -INF) ; + * log(+INF) is +INF; log(0) is -INF with signal; + * log(NaN) is that NaN with no signal. + * + * Accuracy: + * according to an error analysis, the error is always less than + * 1 ulp (unit in the last place). + * + * Constants: + * The hexadecimal values are the intended ones for the following + * constants. The decimal values may be used, provided that the + * compiler will convert from decimal to binary accurately enough + * to produce the hexadecimal values shown. + */ + +static const double Lg1 = 6.666666666666735130e-01, /* 3FE55555 55555593 */ + Lg2 = 3.999999999940941908e-01, /* 3FD99999 9997FA04 */ + Lg3 = 2.857142874366239149e-01, /* 3FD24924 94229359 */ + Lg4 = 2.222219843214978396e-01, /* 3FCC71C5 1D8E78AF */ + Lg5 = 1.818357216161805012e-01, /* 3FC74664 96CB03DE */ + Lg6 = 1.531383769920937332e-01, /* 3FC39A09 D078C69F */ + Lg7 = 1.479819860511658591e-01; /* 3FC2F112 DF3E5244 */ + +/* + * We always inline k_log1p(), since doing so produces a + * substantial performance improvement (~40% on amd64). + */ +static inline double k_log1p(double f) { + double hfsq, s, z, R, w, t1, t2; + + s = f / (2.0 + f); + z = s * s; + w = z * z; + t1 = w * (Lg2 + w * (Lg4 + w * Lg6)); + t2 = z * (Lg1 + w * (Lg3 + w * (Lg5 + w * Lg7))); + R = t2 + t1; + hfsq = 0.5 * f * f; + return s * (hfsq + R); +} + +/* + * Return the base 2 logarithm of x. See e_log.c and k_log.h for most + * comments. + * + * This reduces x to {k, 1+f} exactly as in e_log.c, then calls the kernel, + * then does the combining and scaling steps + * log2(x) = (f - 0.5*f*f + k_log1p(f)) / ln2 + k + * in not-quite-routine extra precision. + */ +double log2(double x) { + static const double + two54 = 1.80143985094819840000e+16, /* 0x43500000, 0x00000000 */ + ivln2hi = 1.44269504072144627571e+00, /* 0x3FF71547, 0x65200000 */ + ivln2lo = 1.67517131648865118353e-10; /* 0x3DE705FC, 0x2EEFA200 */ + + double f, hfsq, hi, lo, r, val_hi, val_lo, w, y; + int32_t i, k, hx; + uint32_t lx; + + EXTRACT_WORDS(hx, lx, x); + + k = 0; + if (hx < 0x00100000) { /* x < 2**-1022 */ + if (((hx & 0x7FFFFFFF) | lx) == 0) { + return -std::numeric_limits<double>::infinity(); /* log(+-0)=-inf */ + } + if (hx < 0) { + return std::numeric_limits<double>::signaling_NaN(); /* log(-#) = NaN */ + } + k -= 54; + x *= two54; /* subnormal number, scale up x */ + GET_HIGH_WORD(hx, x); + } + if (hx >= 0x7FF00000) return x + x; + if (hx == 0x3FF00000 && lx == 0) return 0.0; /* log(1) = +0 */ + k += (hx >> 20) - 1023; + hx &= 0x000FFFFF; + i = (hx + 0x95F64) & 0x100000; + SET_HIGH_WORD(x, hx | (i ^ 0x3FF00000)); /* normalize x or x/2 */ + k += (i >> 20); + y = static_cast<double>(k); + f = x - 1.0; + hfsq = 0.5 * f * f; + r = k_log1p(f); + + /* + * f-hfsq must (for args near 1) be evaluated in extra precision + * to avoid a large cancellation when x is near sqrt(2) or 1/sqrt(2). + * This is fairly efficient since f-hfsq only depends on f, so can + * be evaluated in parallel with R. Not combining hfsq with R also + * keeps R small (though not as small as a true `lo' term would be), + * so that extra precision is not needed for terms involving R. + * + * Compiler bugs involving extra precision used to break Dekker's + * theorem for spitting f-hfsq as hi+lo, unless double_t was used + * or the multi-precision calculations were avoided when double_t + * has extra precision. These problems are now automatically + * avoided as a side effect of the optimization of combining the + * Dekker splitting step with the clear-low-bits step. + * + * y must (for args near sqrt(2) and 1/sqrt(2)) be added in extra + * precision to avoid a very large cancellation when x is very near + * these values. Unlike the above cancellations, this problem is + * specific to base 2. It is strange that adding +-1 is so much + * harder than adding +-ln2 or +-log10_2. + * + * This uses Dekker's theorem to normalize y+val_hi, so the + * compiler bugs are back in some configurations, sigh. And I + * don't want to used double_t to avoid them, since that gives a + * pessimization and the support for avoiding the pessimization + * is not yet available. + * + * The multi-precision calculations for the multiplications are + * routine. + */ + hi = f - hfsq; + SET_LOW_WORD(hi, 0); + lo = (f - hi) - hfsq + r; + val_hi = hi * ivln2hi; + val_lo = (lo + hi) * ivln2lo + lo * ivln2hi; + + /* spadd(val_hi, val_lo, y), except for not using double_t: */ + w = y + val_hi; + val_lo += (y - w) + val_hi; + val_hi = w; + + return val_lo + val_hi; +} + +/* + * Return the base 10 logarithm of x + * + * Method : + * Let log10_2hi = leading 40 bits of log10(2) and + * log10_2lo = log10(2) - log10_2hi, + * ivln10 = 1/log(10) rounded. + * Then + * n = ilogb(x), + * if(n<0) n = n+1; + * x = scalbn(x,-n); + * log10(x) := n*log10_2hi + (n*log10_2lo + ivln10*log(x)) + * + * Note 1: + * To guarantee log10(10**n)=n, where 10**n is normal, the rounding + * mode must set to Round-to-Nearest. + * Note 2: + * [1/log(10)] rounded to 53 bits has error .198 ulps; + * log10 is monotonic at all binary break points. + * + * Special cases: + * log10(x) is NaN if x < 0; + * log10(+INF) is +INF; log10(0) is -INF; + * log10(NaN) is that NaN; + * log10(10**N) = N for N=0,1,...,22. + */ +double log10(double x) { + static const double + two54 = 1.80143985094819840000e+16, /* 0x43500000, 0x00000000 */ + ivln10 = 4.34294481903251816668e-01, + log10_2hi = 3.01029995663611771306e-01, /* 0x3FD34413, 0x509F6000 */ + log10_2lo = 3.69423907715893078616e-13; /* 0x3D59FEF3, 0x11F12B36 */ + + double y; + int32_t i, k, hx; + uint32_t lx; + + EXTRACT_WORDS(hx, lx, x); + + k = 0; + if (hx < 0x00100000) { /* x < 2**-1022 */ + if (((hx & 0x7FFFFFFF) | lx) == 0) { + return -std::numeric_limits<double>::infinity(); /* log(+-0)=-inf */ + } + if (hx < 0) { + return std::numeric_limits<double>::quiet_NaN(); /* log(-#) = NaN */ + } + k -= 54; + x *= two54; /* subnormal number, scale up x */ + GET_HIGH_WORD(hx, x); + GET_LOW_WORD(lx, x); + } + if (hx >= 0x7FF00000) return x + x; + if (hx == 0x3FF00000 && lx == 0) return 0.0; /* log(1) = +0 */ + k += (hx >> 20) - 1023; + + i = (k & 0x80000000) >> 31; + hx = (hx & 0x000FFFFF) | ((0x3FF - i) << 20); + y = k + i; + SET_HIGH_WORD(x, hx); + SET_LOW_WORD(x, lx); + + double z = y * log10_2lo + ivln10 * log(x); + return z + y * log10_2hi; +} + +/* expm1(x) + * Returns exp(x)-1, the exponential of x minus 1. + * + * Method + * 1. Argument reduction: + * Given x, find r and integer k such that + * + * x = k*ln2 + r, |r| <= 0.5*ln2 ~ 0.34658 + * + * Here a correction term c will be computed to compensate + * the error in r when rounded to a floating-point number. + * + * 2. Approximating expm1(r) by a special rational function on + * the interval [0,0.34658]: + * Since + * r*(exp(r)+1)/(exp(r)-1) = 2+ r^2/6 - r^4/360 + ... + * we define R1(r*r) by + * r*(exp(r)+1)/(exp(r)-1) = 2+ r^2/6 * R1(r*r) + * That is, + * R1(r**2) = 6/r *((exp(r)+1)/(exp(r)-1) - 2/r) + * = 6/r * ( 1 + 2.0*(1/(exp(r)-1) - 1/r)) + * = 1 - r^2/60 + r^4/2520 - r^6/100800 + ... + * We use a special Reme algorithm on [0,0.347] to generate + * a polynomial of degree 5 in r*r to approximate R1. The + * maximum error of this polynomial approximation is bounded + * by 2**-61. In other words, + * R1(z) ~ 1.0 + Q1*z + Q2*z**2 + Q3*z**3 + Q4*z**4 + Q5*z**5 + * where Q1 = -1.6666666666666567384E-2, + * Q2 = 3.9682539681370365873E-4, + * Q3 = -9.9206344733435987357E-6, + * Q4 = 2.5051361420808517002E-7, + * Q5 = -6.2843505682382617102E-9; + * z = r*r, + * with error bounded by + * | 5 | -61 + * | 1.0+Q1*z+...+Q5*z - R1(z) | <= 2 + * | | + * + * expm1(r) = exp(r)-1 is then computed by the following + * specific way which minimize the accumulation rounding error: + * 2 3 + * r r [ 3 - (R1 + R1*r/2) ] + * expm1(r) = r + --- + --- * [--------------------] + * 2 2 [ 6 - r*(3 - R1*r/2) ] + * + * To compensate the error in the argument reduction, we use + * expm1(r+c) = expm1(r) + c + expm1(r)*c + * ~ expm1(r) + c + r*c + * Thus c+r*c will be added in as the correction terms for + * expm1(r+c). Now rearrange the term to avoid optimization + * screw up: + * ( 2 2 ) + * ({ ( r [ R1 - (3 - R1*r/2) ] ) } r ) + * expm1(r+c)~r - ({r*(--- * [--------------------]-c)-c} - --- ) + * ({ ( 2 [ 6 - r*(3 - R1*r/2) ] ) } 2 ) + * ( ) + * + * = r - E + * 3. Scale back to obtain expm1(x): + * From step 1, we have + * expm1(x) = either 2^k*[expm1(r)+1] - 1 + * = or 2^k*[expm1(r) + (1-2^-k)] + * 4. Implementation notes: + * (A). To save one multiplication, we scale the coefficient Qi + * to Qi*2^i, and replace z by (x^2)/2. + * (B). To achieve maximum accuracy, we compute expm1(x) by + * (i) if x < -56*ln2, return -1.0, (raise inexact if x!=inf) + * (ii) if k=0, return r-E + * (iii) if k=-1, return 0.5*(r-E)-0.5 + * (iv) if k=1 if r < -0.25, return 2*((r+0.5)- E) + * else return 1.0+2.0*(r-E); + * (v) if (k<-2||k>56) return 2^k(1-(E-r)) - 1 (or exp(x)-1) + * (vi) if k <= 20, return 2^k((1-2^-k)-(E-r)), else + * (vii) return 2^k(1-((E+2^-k)-r)) + * + * Special cases: + * expm1(INF) is INF, expm1(NaN) is NaN; + * expm1(-INF) is -1, and + * for finite argument, only expm1(0)=0 is exact. + * + * Accuracy: + * according to an error analysis, the error is always less than + * 1 ulp (unit in the last place). + * + * Misc. info. + * For IEEE double + * if x > 7.09782712893383973096e+02 then expm1(x) overflow + * + * Constants: + * The hexadecimal values are the intended ones for the following + * constants. The decimal values may be used, provided that the + * compiler will convert from decimal to binary accurately enough + * to produce the hexadecimal values shown. + */ +double expm1(double x) { + static const double + one = 1.0, + tiny = 1.0e-300, + o_threshold = 7.09782712893383973096e+02, /* 0x40862E42, 0xFEFA39EF */ + ln2_hi = 6.93147180369123816490e-01, /* 0x3FE62E42, 0xFEE00000 */ + ln2_lo = 1.90821492927058770002e-10, /* 0x3DEA39EF, 0x35793C76 */ + invln2 = 1.44269504088896338700e+00, /* 0x3FF71547, 0x652B82FE */ + /* Scaled Q's: Qn_here = 2**n * Qn_above, for R(2*z) where z = hxs = + x*x/2: */ + Q1 = -3.33333333333331316428e-02, /* BFA11111 111110F4 */ + Q2 = 1.58730158725481460165e-03, /* 3F5A01A0 19FE5585 */ + Q3 = -7.93650757867487942473e-05, /* BF14CE19 9EAADBB7 */ + Q4 = 4.00821782732936239552e-06, /* 3ED0CFCA 86E65239 */ + Q5 = -2.01099218183624371326e-07; /* BE8AFDB7 6E09C32D */ + + static volatile double huge = 1.0e+300; + + double y, hi, lo, c, t, e, hxs, hfx, r1, twopk; + int32_t k, xsb; + uint32_t hx; + + GET_HIGH_WORD(hx, x); + xsb = hx & 0x80000000; /* sign bit of x */ + hx &= 0x7FFFFFFF; /* high word of |x| */ + + /* filter out huge and non-finite argument */ + if (hx >= 0x4043687A) { /* if |x|>=56*ln2 */ + if (hx >= 0x40862E42) { /* if |x|>=709.78... */ + if (hx >= 0x7FF00000) { + uint32_t low; + GET_LOW_WORD(low, x); + if (((hx & 0xFFFFF) | low) != 0) + return x + x; /* NaN */ + else + return (xsb == 0) ? x : -1.0; /* exp(+-inf)={inf,-1} */ + } + if (x > o_threshold) return huge * huge; /* overflow */ + } + if (xsb != 0) { /* x < -56*ln2, return -1.0 with inexact */ + if (x + tiny < 0.0) /* raise inexact */ + return tiny - one; /* return -1 */ + } + } + + /* argument reduction */ + if (hx > 0x3FD62E42) { /* if |x| > 0.5 ln2 */ + if (hx < 0x3FF0A2B2) { /* and |x| < 1.5 ln2 */ + if (xsb == 0) { + hi = x - ln2_hi; + lo = ln2_lo; + k = 1; + } else { + hi = x + ln2_hi; + lo = -ln2_lo; + k = -1; + } + } else { + k = invln2 * x + ((xsb == 0) ? 0.5 : -0.5); + t = k; + hi = x - t * ln2_hi; /* t*ln2_hi is exact here */ + lo = t * ln2_lo; + } + x = hi - lo; + c = (hi - x) - lo; + } else if (hx < 0x3C900000) { /* when |x|<2**-54, return x */ + t = huge + x; /* return x with inexact flags when x!=0 */ + return x - (t - (huge + x)); + } else { + k = 0; + } + + /* x is now in primary range */ + hfx = 0.5 * x; + hxs = x * hfx; + r1 = one + hxs * (Q1 + hxs * (Q2 + hxs * (Q3 + hxs * (Q4 + hxs * Q5)))); + t = 3.0 - r1 * hfx; + e = hxs * ((r1 - t) / (6.0 - x * t)); + if (k == 0) { + return x - (x * e - hxs); /* c is 0 */ + } else { + INSERT_WORDS( + twopk, + 0x3FF00000 + static_cast<int32_t>(static_cast<uint32_t>(k) << 20), + 0); /* 2^k */ + e = (x * (e - c) - c); + e -= hxs; + if (k == -1) return 0.5 * (x - e) - 0.5; + if (k == 1) { + if (x < -0.25) + return -2.0 * (e - (x + 0.5)); + else + return one + 2.0 * (x - e); + } + if (k <= -2 || k > 56) { /* suffice to return exp(x)-1 */ + y = one - (e - x); + // TODO(mvstanton): is this replacement for the hex float + // sufficient? + // if (k == 1024) y = y*2.0*0x1p1023; + if (k == 1024) + y = y * 2.0 * 8.98846567431158e+307; + else + y = y * twopk; + return y - one; + } + t = one; + if (k < 20) { + SET_HIGH_WORD(t, 0x3FF00000 - (0x200000 >> k)); /* t=1-2^-k */ + y = t - (e - x); + y = y * twopk; + } else { + SET_HIGH_WORD(t, ((0x3FF - k) << 20)); /* 2^-k */ + y = x - (e + t); + y += one; + y = y * twopk; + } + } + return y; +} + +double cbrt(double x) { + static const uint32_t + B1 = 715094163, /* B1 = (1023-1023/3-0.03306235651)*2**20 */ + B2 = 696219795; /* B2 = (1023-1023/3-54/3-0.03306235651)*2**20 */ + + /* |1/cbrt(x) - p(x)| < 2**-23.5 (~[-7.93e-8, 7.929e-8]). */ + static const double P0 = 1.87595182427177009643, /* 0x3FFE03E6, 0x0F61E692 */ + P1 = -1.88497979543377169875, /* 0xBFFE28E0, 0x92F02420 */ + P2 = 1.621429720105354466140, /* 0x3FF9F160, 0x4A49D6C2 */ + P3 = -0.758397934778766047437, /* 0xBFE844CB, 0xBEE751D9 */ + P4 = 0.145996192886612446982; /* 0x3FC2B000, 0xD4E4EDD7 */ + + int32_t hx; + double r, s, t = 0.0, w; + uint32_t sign; + uint32_t high, low; + + EXTRACT_WORDS(hx, low, x); + sign = hx & 0x80000000; /* sign= sign(x) */ + hx ^= sign; + if (hx >= 0x7FF00000) return (x + x); /* cbrt(NaN,INF) is itself */ + + /* + * Rough cbrt to 5 bits: + * cbrt(2**e*(1+m) ~= 2**(e/3)*(1+(e%3+m)/3) + * where e is integral and >= 0, m is real and in [0, 1), and "/" and + * "%" are integer division and modulus with rounding towards minus + * infinity. The RHS is always >= the LHS and has a maximum relative + * error of about 1 in 16. Adding a bias of -0.03306235651 to the + * (e%3+m)/3 term reduces the error to about 1 in 32. With the IEEE + * floating point representation, for finite positive normal values, + * ordinary integer division of the value in bits magically gives + * almost exactly the RHS of the above provided we first subtract the + * exponent bias (1023 for doubles) and later add it back. We do the + * subtraction virtually to keep e >= 0 so that ordinary integer + * division rounds towards minus infinity; this is also efficient. + */ + if (hx < 0x00100000) { /* zero or subnormal? */ + if ((hx | low) == 0) return (x); /* cbrt(0) is itself */ + SET_HIGH_WORD(t, 0x43500000); /* set t= 2**54 */ + t *= x; + GET_HIGH_WORD(high, t); + INSERT_WORDS(t, sign | ((high & 0x7FFFFFFF) / 3 + B2), 0); + } else { + INSERT_WORDS(t, sign | (hx / 3 + B1), 0); + } + + /* + * New cbrt to 23 bits: + * cbrt(x) = t*cbrt(x/t**3) ~= t*P(t**3/x) + * where P(r) is a polynomial of degree 4 that approximates 1/cbrt(r) + * to within 2**-23.5 when |r - 1| < 1/10. The rough approximation + * has produced t such than |t/cbrt(x) - 1| ~< 1/32, and cubing this + * gives us bounds for r = t**3/x. + * + * Try to optimize for parallel evaluation as in k_tanf.c. + */ + r = (t * t) * (t / x); + t = t * ((P0 + r * (P1 + r * P2)) + ((r * r) * r) * (P3 + r * P4)); + + /* + * Round t away from zero to 23 bits (sloppily except for ensuring that + * the result is larger in magnitude than cbrt(x) but not much more than + * 2 23-bit ulps larger). With rounding towards zero, the error bound + * would be ~5/6 instead of ~4/6. With a maximum error of 2 23-bit ulps + * in the rounded t, the infinite-precision error in the Newton + * approximation barely affects third digit in the final error + * 0.667; the error in the rounded t can be up to about 3 23-bit ulps + * before the final error is larger than 0.667 ulps. + */ + uint64_t bits = bit_cast<uint64_t>(t); + bits = (bits + 0x80000000) & 0xFFFFFFFFC0000000ULL; + t = bit_cast<double>(bits); + + /* one step Newton iteration to 53 bits with error < 0.667 ulps */ + s = t * t; /* t*t is exact */ + r = x / s; /* error <= 0.5 ulps; |r| < |t| */ + w = t + t; /* t+t is exact */ + r = (r - t) / (w + r); /* r-t is exact; w+r ~= 3*t */ + t = t + t * r; /* error <= 0.5 + 0.5/3 + epsilon */ + + return (t); +} + +/* sin(x) + * Return sine function of x. + * + * kernel function: + * __kernel_sin ... sine function on [-pi/4,pi/4] + * __kernel_cos ... cose function on [-pi/4,pi/4] + * __ieee754_rem_pio2 ... argument reduction routine + * + * Method. + * Let S,C and T denote the sin, cos and tan respectively on + * [-PI/4, +PI/4]. Reduce the argument x to y1+y2 = x-k*pi/2 + * in [-pi/4 , +pi/4], and let n = k mod 4. + * We have + * + * n sin(x) cos(x) tan(x) + * ---------------------------------------------------------- + * 0 S C T + * 1 C -S -1/T + * 2 -S -C T + * 3 -C S -1/T + * ---------------------------------------------------------- + * + * Special cases: + * Let trig be any of sin, cos, or tan. + * trig(+-INF) is NaN, with signals; + * trig(NaN) is that NaN; + * + * Accuracy: + * TRIG(x) returns trig(x) nearly rounded + */ +double sin(double x) { + double y[2], z = 0.0; + int32_t n, ix; + + /* High word of x. */ + GET_HIGH_WORD(ix, x); + + /* |x| ~< pi/4 */ + ix &= 0x7FFFFFFF; + if (ix <= 0x3FE921FB) { + return __kernel_sin(x, z, 0); + } else if (ix >= 0x7FF00000) { + /* sin(Inf or NaN) is NaN */ + return x - x; + } else { + /* argument reduction needed */ + n = __ieee754_rem_pio2(x, y); + switch (n & 3) { + case 0: + return __kernel_sin(y[0], y[1], 1); + case 1: + return __kernel_cos(y[0], y[1]); + case 2: + return -__kernel_sin(y[0], y[1], 1); + default: + return -__kernel_cos(y[0], y[1]); + } + } +} + +/* tan(x) + * Return tangent function of x. + * + * kernel function: + * __kernel_tan ... tangent function on [-pi/4,pi/4] + * __ieee754_rem_pio2 ... argument reduction routine + * + * Method. + * Let S,C and T denote the sin, cos and tan respectively on + * [-PI/4, +PI/4]. Reduce the argument x to y1+y2 = x-k*pi/2 + * in [-pi/4 , +pi/4], and let n = k mod 4. + * We have + * + * n sin(x) cos(x) tan(x) + * ---------------------------------------------------------- + * 0 S C T + * 1 C -S -1/T + * 2 -S -C T + * 3 -C S -1/T + * ---------------------------------------------------------- + * + * Special cases: + * Let trig be any of sin, cos, or tan. + * trig(+-INF) is NaN, with signals; + * trig(NaN) is that NaN; + * + * Accuracy: + * TRIG(x) returns trig(x) nearly rounded + */ +double tan(double x) { + double y[2], z = 0.0; + int32_t n, ix; + + /* High word of x. */ + GET_HIGH_WORD(ix, x); + + /* |x| ~< pi/4 */ + ix &= 0x7FFFFFFF; + if (ix <= 0x3FE921FB) { + return __kernel_tan(x, z, 1); + } else if (ix >= 0x7FF00000) { + /* tan(Inf or NaN) is NaN */ + return x - x; /* NaN */ + } else { + /* argument reduction needed */ + n = __ieee754_rem_pio2(x, y); + /* 1 -> n even, -1 -> n odd */ + return __kernel_tan(y[0], y[1], 1 - ((n & 1) << 1)); + } +} + +/* + * ES6 draft 09-27-13, section 20.2.2.12. + * Math.cosh + * Method : + * mathematically cosh(x) if defined to be (exp(x)+exp(-x))/2 + * 1. Replace x by |x| (cosh(x) = cosh(-x)). + * 2. + * [ exp(x) - 1 ]^2 + * 0 <= x <= ln2/2 : cosh(x) := 1 + ------------------- + * 2*exp(x) + * + * exp(x) + 1/exp(x) + * ln2/2 <= x <= 22 : cosh(x) := ------------------- + * 2 + * 22 <= x <= lnovft : cosh(x) := exp(x)/2 + * lnovft <= x <= ln2ovft: cosh(x) := exp(x/2)/2 * exp(x/2) + * ln2ovft < x : cosh(x) := huge*huge (overflow) + * + * Special cases: + * cosh(x) is |x| if x is +INF, -INF, or NaN. + * only cosh(0)=1 is exact for finite x. + */ +double cosh(double x) { + static const double KCOSH_OVERFLOW = 710.4758600739439; + static const double one = 1.0, half = 0.5; + static volatile double huge = 1.0e+300; + + int32_t ix; + + /* High word of |x|. */ + GET_HIGH_WORD(ix, x); + ix &= 0x7FFFFFFF; + + // |x| in [0,0.5*log2], return 1+expm1(|x|)^2/(2*exp(|x|)) + if (ix < 0x3FD62E43) { + double t = expm1(fabs(x)); + double w = one + t; + // For |x| < 2^-55, cosh(x) = 1 + if (ix < 0x3C800000) return w; + return one + (t * t) / (w + w); + } + + // |x| in [0.5*log2, 22], return (exp(|x|)+1/exp(|x|)/2 + if (ix < 0x40360000) { + double t = exp(fabs(x)); + return half * t + half / t; + } + + // |x| in [22, log(maxdouble)], return half*exp(|x|) + if (ix < 0x40862E42) return half * exp(fabs(x)); + + // |x| in [log(maxdouble), overflowthreshold] + if (fabs(x) <= KCOSH_OVERFLOW) { + double w = exp(half * fabs(x)); + double t = half * w; + return t * w; + } + + /* x is INF or NaN */ + if (ix >= 0x7FF00000) return x * x; + + // |x| > overflowthreshold. + return huge * huge; +} + +/* + * ES2019 Draft 2019-01-02 12.6.4 + * Math.pow & Exponentiation Operator + * + * Return X raised to the Yth power + * + * Method: + * Let x = 2 * (1+f) + * 1. Compute and return log2(x) in two pieces: + * log2(x) = w1 + w2, + * where w1 has 53-24 = 29 bit trailing zeros. + * 2. Perform y*log2(x) = n+y' by simulating muti-precision + * arithmetic, where |y'|<=0.5. + * 3. Return x**y = 2**n*exp(y'*log2) + * + * Special cases: + * 1. (anything) ** 0 is 1 + * 2. (anything) ** 1 is itself + * 3. (anything) ** NAN is NAN + * 4. NAN ** (anything except 0) is NAN + * 5. +-(|x| > 1) ** +INF is +INF + * 6. +-(|x| > 1) ** -INF is +0 + * 7. +-(|x| < 1) ** +INF is +0 + * 8. +-(|x| < 1) ** -INF is +INF + * 9. +-1 ** +-INF is NAN + * 10. +0 ** (+anything except 0, NAN) is +0 + * 11. -0 ** (+anything except 0, NAN, odd integer) is +0 + * 12. +0 ** (-anything except 0, NAN) is +INF + * 13. -0 ** (-anything except 0, NAN, odd integer) is +INF + * 14. -0 ** (odd integer) = -( +0 ** (odd integer) ) + * 15. +INF ** (+anything except 0,NAN) is +INF + * 16. +INF ** (-anything except 0,NAN) is +0 + * 17. -INF ** (anything) = -0 ** (-anything) + * 18. (-anything) ** (integer) is (-1)**(integer)*(+anything**integer) + * 19. (-anything except 0 and inf) ** (non-integer) is NAN + * + * Accuracy: + * pow(x,y) returns x**y nearly rounded. In particular, + * pow(integer, integer) always returns the correct integer provided it is + * representable. + * + * Constants: + * The hexadecimal values are the intended ones for the following + * constants. The decimal values may be used, provided that the + * compiler will convert from decimal to binary accurately enough + * to produce the hexadecimal values shown. + */ + +double pow(double x, double y) { + static const double + bp[] = {1.0, 1.5}, + dp_h[] = {0.0, 5.84962487220764160156e-01}, // 0x3FE2B803, 0x40000000 + dp_l[] = {0.0, 1.35003920212974897128e-08}, // 0x3E4CFDEB, 0x43CFD006 + zero = 0.0, one = 1.0, two = 2.0, + two53 = 9007199254740992.0, // 0x43400000, 0x00000000 + huge = 1.0e300, tiny = 1.0e-300, + // poly coefs for (3/2)*(log(x)-2s-2/3*s**3 + L1 = 5.99999999999994648725e-01, // 0x3FE33333, 0x33333303 + L2 = 4.28571428578550184252e-01, // 0x3FDB6DB6, 0xDB6FABFF + L3 = 3.33333329818377432918e-01, // 0x3FD55555, 0x518F264D + L4 = 2.72728123808534006489e-01, // 0x3FD17460, 0xA91D4101 + L5 = 2.30660745775561754067e-01, // 0x3FCD864A, 0x93C9DB65 + L6 = 2.06975017800338417784e-01, // 0x3FCA7E28, 0x4A454EEF + P1 = 1.66666666666666019037e-01, // 0x3FC55555, 0x5555553E + P2 = -2.77777777770155933842e-03, // 0xBF66C16C, 0x16BEBD93 + P3 = 6.61375632143793436117e-05, // 0x3F11566A, 0xAF25DE2C + P4 = -1.65339022054652515390e-06, // 0xBEBBBD41, 0xC5D26BF1 + P5 = 4.13813679705723846039e-08, // 0x3E663769, 0x72BEA4D0 + lg2 = 6.93147180559945286227e-01, // 0x3FE62E42, 0xFEFA39EF + lg2_h = 6.93147182464599609375e-01, // 0x3FE62E43, 0x00000000 + lg2_l = -1.90465429995776804525e-09, // 0xBE205C61, 0x0CA86C39 + ovt = 8.0085662595372944372e-0017, // -(1024-log2(ovfl+.5ulp)) + cp = 9.61796693925975554329e-01, // 0x3FEEC709, 0xDC3A03FD =2/(3ln2) + cp_h = 9.61796700954437255859e-01, // 0x3FEEC709, 0xE0000000 =(float)cp + cp_l = -7.02846165095275826516e-09, // 0xBE3E2FE0, 0x145B01F5 =tail cp_h + ivln2 = 1.44269504088896338700e+00, // 0x3FF71547, 0x652B82FE =1/ln2 + ivln2_h = + 1.44269502162933349609e+00, // 0x3FF71547, 0x60000000 =24b 1/ln2 + ivln2_l = + 1.92596299112661746887e-08; // 0x3E54AE0B, 0xF85DDF44 =1/ln2 tail + + double z, ax, z_h, z_l, p_h, p_l; + double y1, t1, t2, r, s, t, u, v, w; + int i, j, k, yisint, n; + int hx, hy, ix, iy; + unsigned lx, ly; + + EXTRACT_WORDS(hx, lx, x); + EXTRACT_WORDS(hy, ly, y); + ix = hx & 0x7fffffff; + iy = hy & 0x7fffffff; + + /* y==zero: x**0 = 1 */ + if ((iy | ly) == 0) return one; + + /* +-NaN return x+y */ + if (ix > 0x7ff00000 || ((ix == 0x7ff00000) && (lx != 0)) || iy > 0x7ff00000 || + ((iy == 0x7ff00000) && (ly != 0))) { + return x + y; + } + + /* determine if y is an odd int when x < 0 + * yisint = 0 ... y is not an integer + * yisint = 1 ... y is an odd int + * yisint = 2 ... y is an even int + */ + yisint = 0; + if (hx < 0) { + if (iy >= 0x43400000) { + yisint = 2; /* even integer y */ + } else if (iy >= 0x3ff00000) { + k = (iy >> 20) - 0x3ff; /* exponent */ + if (k > 20) { + j = ly >> (52 - k); + if ((j << (52 - k)) == static_cast<int>(ly)) yisint = 2 - (j & 1); + } else if (ly == 0) { + j = iy >> (20 - k); + if ((j << (20 - k)) == iy) yisint = 2 - (j & 1); + } + } + } + + /* special value of y */ + if (ly == 0) { + if (iy == 0x7ff00000) { /* y is +-inf */ + if (((ix - 0x3ff00000) | lx) == 0) { + return y - y; /* inf**+-1 is NaN */ + } else if (ix >= 0x3ff00000) { /* (|x|>1)**+-inf = inf,0 */ + return (hy >= 0) ? y : zero; + } else { /* (|x|<1)**-,+inf = inf,0 */ + return (hy < 0) ? -y : zero; + } + } + if (iy == 0x3ff00000) { /* y is +-1 */ + if (hy < 0) { + return Divide(one, x); + } else { + return x; + } + } + if (hy == 0x40000000) return x * x; /* y is 2 */ + if (hy == 0x3fe00000) { /* y is 0.5 */ + if (hx >= 0) { /* x >= +0 */ + return sqrt(x); + } + } + } + + ax = fabs(x); + /* special value of x */ + if (lx == 0) { + if (ix == 0x7ff00000 || ix == 0 || ix == 0x3ff00000) { + z = ax; /*x is +-0,+-inf,+-1*/ + if (hy < 0) z = Divide(one, z); /* z = (1/|x|) */ + if (hx < 0) { + if (((ix - 0x3ff00000) | yisint) == 0) { + /* (-1)**non-int is NaN */ + z = std::numeric_limits<double>::signaling_NaN(); + } else if (yisint == 1) { + z = -z; /* (x<0)**odd = -(|x|**odd) */ + } + } + return z; + } + } + + n = (hx >> 31) + 1; + + /* (x<0)**(non-int) is NaN */ + if ((n | yisint) == 0) { + return std::numeric_limits<double>::signaling_NaN(); + } + + s = one; /* s (sign of result -ve**odd) = -1 else = 1 */ + if ((n | (yisint - 1)) == 0) s = -one; /* (-ve)**(odd int) */ + + /* |y| is huge */ + if (iy > 0x41e00000) { /* if |y| > 2**31 */ + if (iy > 0x43f00000) { /* if |y| > 2**64, must o/uflow */ + if (ix <= 0x3fefffff) return (hy < 0) ? huge * huge : tiny * tiny; + if (ix >= 0x3ff00000) return (hy > 0) ? huge * huge : tiny * tiny; + } + /* over/underflow if x is not close to one */ + if (ix < 0x3fefffff) return (hy < 0) ? s * huge * huge : s * tiny * tiny; + if (ix > 0x3ff00000) return (hy > 0) ? s * huge * huge : s * tiny * tiny; + /* now |1-x| is tiny <= 2**-20, suffice to compute + log(x) by x-x^2/2+x^3/3-x^4/4 */ + t = ax - one; /* t has 20 trailing zeros */ + w = (t * t) * (0.5 - t * (0.3333333333333333333333 - t * 0.25)); + u = ivln2_h * t; /* ivln2_h has 21 sig. bits */ + v = t * ivln2_l - w * ivln2; + t1 = u + v; + SET_LOW_WORD(t1, 0); + t2 = v - (t1 - u); + } else { + double ss, s2, s_h, s_l, t_h, t_l; + n = 0; + /* take care subnormal number */ + if (ix < 0x00100000) { + ax *= two53; + n -= 53; + GET_HIGH_WORD(ix, ax); + } + n += ((ix) >> 20) - 0x3ff; + j = ix & 0x000fffff; + /* determine interval */ + ix = j | 0x3ff00000; /* normalize ix */ + if (j <= 0x3988E) { + k = 0; /* |x|<sqrt(3/2) */ + } else if (j < 0xBB67A) { + k = 1; /* |x|<sqrt(3) */ + } else { + k = 0; + n += 1; + ix -= 0x00100000; + } + SET_HIGH_WORD(ax, ix); + + /* compute ss = s_h+s_l = (x-1)/(x+1) or (x-1.5)/(x+1.5) */ + u = ax - bp[k]; /* bp[0]=1.0, bp[1]=1.5 */ + v = Divide(one, ax + bp[k]); + ss = u * v; + s_h = ss; + SET_LOW_WORD(s_h, 0); + /* t_h=ax+bp[k] High */ + t_h = zero; + SET_HIGH_WORD(t_h, ((ix >> 1) | 0x20000000) + 0x00080000 + (k << 18)); + t_l = ax - (t_h - bp[k]); + s_l = v * ((u - s_h * t_h) - s_h * t_l); + /* compute log(ax) */ + s2 = ss * ss; + r = s2 * s2 * + (L1 + s2 * (L2 + s2 * (L3 + s2 * (L4 + s2 * (L5 + s2 * L6))))); + r += s_l * (s_h + ss); + s2 = s_h * s_h; + t_h = 3.0 + s2 + r; + SET_LOW_WORD(t_h, 0); + t_l = r - ((t_h - 3.0) - s2); + /* u+v = ss*(1+...) */ + u = s_h * t_h; + v = s_l * t_h + t_l * ss; + /* 2/(3log2)*(ss+...) */ + p_h = u + v; + SET_LOW_WORD(p_h, 0); + p_l = v - (p_h - u); + z_h = cp_h * p_h; /* cp_h+cp_l = 2/(3*log2) */ + z_l = cp_l * p_h + p_l * cp + dp_l[k]; + /* log2(ax) = (ss+..)*2/(3*log2) = n + dp_h + z_h + z_l */ + t = static_cast<double>(n); + t1 = (((z_h + z_l) + dp_h[k]) + t); + SET_LOW_WORD(t1, 0); + t2 = z_l - (((t1 - t) - dp_h[k]) - z_h); + } + + /* split up y into y1+y2 and compute (y1+y2)*(t1+t2) */ + y1 = y; + SET_LOW_WORD(y1, 0); + p_l = (y - y1) * t1 + y * t2; + p_h = y1 * t1; + z = p_l + p_h; + EXTRACT_WORDS(j, i, z); + if (j >= 0x40900000) { /* z >= 1024 */ + if (((j - 0x40900000) | i) != 0) { /* if z > 1024 */ + return s * huge * huge; /* overflow */ + } else { + if (p_l + ovt > z - p_h) return s * huge * huge; /* overflow */ + } + } else if ((j & 0x7fffffff) >= 0x4090cc00) { /* z <= -1075 */ + if (((j - 0xc090cc00) | i) != 0) { /* z < -1075 */ + return s * tiny * tiny; /* underflow */ + } else { + if (p_l <= z - p_h) return s * tiny * tiny; /* underflow */ + } + } + /* + * compute 2**(p_h+p_l) + */ + i = j & 0x7fffffff; + k = (i >> 20) - 0x3ff; + n = 0; + if (i > 0x3fe00000) { /* if |z| > 0.5, set n = [z+0.5] */ + n = j + (0x00100000 >> (k + 1)); + k = ((n & 0x7fffffff) >> 20) - 0x3ff; /* new k for n */ + t = zero; + SET_HIGH_WORD(t, n & ~(0x000fffff >> k)); + n = ((n & 0x000fffff) | 0x00100000) >> (20 - k); + if (j < 0) n = -n; + p_h -= t; + } + t = p_l + p_h; + SET_LOW_WORD(t, 0); + u = t * lg2_h; + v = (p_l - (t - p_h)) * lg2 + t * lg2_l; + z = u + v; + w = v - (z - u); + t = z * z; + t1 = z - t * (P1 + t * (P2 + t * (P3 + t * (P4 + t * P5)))); + r = Divide(z * t1, (t1 - two) - (w + z * w)); + z = one - (r - z); + GET_HIGH_WORD(j, z); + j += static_cast<int>(static_cast<uint32_t>(n) << 20); + if ((j >> 20) <= 0) { + z = scalbn(z, n); /* subnormal output */ + } else { + int tmp; + GET_HIGH_WORD(tmp, z); + SET_HIGH_WORD(z, tmp + static_cast<int>(static_cast<uint32_t>(n) << 20)); + } + return s * z; +} + +/* + * ES6 draft 09-27-13, section 20.2.2.30. + * Math.sinh + * Method : + * mathematically sinh(x) if defined to be (exp(x)-exp(-x))/2 + * 1. Replace x by |x| (sinh(-x) = -sinh(x)). + * 2. + * E + E/(E+1) + * 0 <= x <= 22 : sinh(x) := --------------, E=expm1(x) + * 2 + * + * 22 <= x <= lnovft : sinh(x) := exp(x)/2 + * lnovft <= x <= ln2ovft: sinh(x) := exp(x/2)/2 * exp(x/2) + * ln2ovft < x : sinh(x) := x*shuge (overflow) + * + * Special cases: + * sinh(x) is |x| if x is +Infinity, -Infinity, or NaN. + * only sinh(0)=0 is exact for finite x. + */ +double sinh(double x) { + static const double KSINH_OVERFLOW = 710.4758600739439, + TWO_M28 = + 3.725290298461914e-9, // 2^-28, empty lower half + LOG_MAXD = 709.7822265625; // 0x40862E42 00000000, empty lower half + static const double shuge = 1.0e307; + + double h = (x < 0) ? -0.5 : 0.5; + // |x| in [0, 22]. return sign(x)*0.5*(E+E/(E+1)) + double ax = fabs(x); + if (ax < 22) { + // For |x| < 2^-28, sinh(x) = x + if (ax < TWO_M28) return x; + double t = expm1(ax); + if (ax < 1) { + return h * (2 * t - t * t / (t + 1)); + } + return h * (t + t / (t + 1)); + } + // |x| in [22, log(maxdouble)], return 0.5 * exp(|x|) + if (ax < LOG_MAXD) return h * exp(ax); + // |x| in [log(maxdouble), overflowthreshold] + // overflowthreshold = 710.4758600739426 + if (ax <= KSINH_OVERFLOW) { + double w = exp(0.5 * ax); + double t = h * w; + return t * w; + } + // |x| > overflowthreshold or is NaN. + // Return Infinity of the appropriate sign or NaN. + return x * shuge; +} + +/* Tanh(x) + * Return the Hyperbolic Tangent of x + * + * Method : + * x -x + * e - e + * 0. tanh(x) is defined to be ----------- + * x -x + * e + e + * 1. reduce x to non-negative by tanh(-x) = -tanh(x). + * 2. 0 <= x < 2**-28 : tanh(x) := x with inexact if x != 0 + * -t + * 2**-28 <= x < 1 : tanh(x) := -----; t = expm1(-2x) + * t + 2 + * 2 + * 1 <= x < 22 : tanh(x) := 1 - -----; t = expm1(2x) + * t + 2 + * 22 <= x <= INF : tanh(x) := 1. + * + * Special cases: + * tanh(NaN) is NaN; + * only tanh(0)=0 is exact for finite argument. + */ +double tanh(double x) { + static const volatile double tiny = 1.0e-300; + static const double one = 1.0, two = 2.0, huge = 1.0e300; + double t, z; + int32_t jx, ix; + + GET_HIGH_WORD(jx, x); + ix = jx & 0x7FFFFFFF; + + /* x is INF or NaN */ + if (ix >= 0x7FF00000) { + if (jx >= 0) + return one / x + one; /* tanh(+-inf)=+-1 */ + else + return one / x - one; /* tanh(NaN) = NaN */ + } + + /* |x| < 22 */ + if (ix < 0x40360000) { /* |x|<22 */ + if (ix < 0x3E300000) { /* |x|<2**-28 */ + if (huge + x > one) return x; /* tanh(tiny) = tiny with inexact */ + } + if (ix >= 0x3FF00000) { /* |x|>=1 */ + t = expm1(two * fabs(x)); + z = one - two / (t + two); + } else { + t = expm1(-two * fabs(x)); + z = -t / (t + two); + } + /* |x| >= 22, return +-1 */ + } else { + z = one - tiny; /* raise inexact flag */ + } + return (jx >= 0) ? z : -z; +} + +float powf(float x, float y) { + return pow(x, y); +} + +float expf(float x) { + return exp(x); +} + +float log10f(float x) { + return log10(x); +} + +float sinf(double x) { + return sin(x); +} + +float asinf(double x) { + return asin(x); +} + +#undef EXTRACT_WORDS +#undef GET_HIGH_WORD +#undef GET_LOW_WORD +#undef INSERT_WORDS +#undef SET_HIGH_WORD +#undef SET_LOW_WORD + +} // namespace fdlibm +
diff --git a/third_party/fdlibm/ieee754.h b/third_party/fdlibm/ieee754.h new file mode 100644 index 0000000..27b50138 --- /dev/null +++ b/third_party/fdlibm/ieee754.h
@@ -0,0 +1,99 @@ +// Copyright 2016 the V8 project authors. All rights reserved. +// Copyright 2020 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 THIRD_PARTY_FDLIBM_IEEE754_H_ +#define THIRD_PARTY_FDLIBM_IEEE754_H_ + +namespace fdlibm { + +// Returns the arc cosine of |x|; that is the value whose cosine is |x|. +double acos(double x); + +// Returns the inverse hyperbolic cosine of |x|; that is the value whose +// hyperbolic cosine is |x|. +double acosh(double x); + +// Returns the arc sine of |x|; that is the value whose sine is |x|. +double asin(double x); + +// Returns the inverse hyperbolic sine of |x|; that is the value whose +// hyperbolic sine is |x|. +double asinh(double x); + +// Returns the principal value of the arc tangent of |x|; that is the value +// whose tangent is |x|. +double atan(double x); + +// Returns the principal value of the arc tangent of |y/x|, using the signs of +// the two arguments to determine the quadrant of the result. +double atan2(double y, double x); + +// Returns the cosine of |x|, where |x| is given in radians. +double cos(double x); + +// Returns the base-e exponential of |x|. +double exp(double x); + +double atanh(double x); + +// Returns the natural logarithm of |x|. +double log(double x); + +// Returns a value equivalent to |log(1+x)|, but computed in a way that is +// accurate even if the value of |x| is near zero. +double log1p(double x); + +// Returns the base 2 logarithm of |x|. +double log2(double x); + +// Returns the base 10 logarithm of |x|. +double log10(double x); + +// Returns the cube root of |x|. +double cbrt(double x); + +// Returns exp(x)-1, the exponential of |x| minus 1. +double expm1(double x); + +// Returns |x| to the power of |y|. +// The result of base ** exponent when base is 1 or -1 and exponent is +// +Infinity or -Infinity differs from IEEE 754-2008. The first edition +// of ECMAScript specified a result of NaN for this operation, whereas +// later versions of IEEE 754-2008 specified 1. The historical ECMAScript +// behaviour is preserved for compatibility reasons. +double pow(double x, double y); + +// Returns the sine of |x|, where |x| is given in radians. +double sin(double x); + +// Returns the tangent of |x|, where |x| is given in radians. +double tan(double x); + +// Returns the hyperbolic cosine of |x|, where |x| is given radians. +double cosh(double x); + +// Returns the hyperbolic sine of |x|, where |x| is given radians. +double sinh(double x); + +// Returns the hyperbolic tangent of |x|, where |x| is given radians. +double tanh(double x); + +// NOTE(caraitto): These functions are not present in the V8 math library -- +// they are defined in terms of other functions. + +float powf(float x, float y); + +float expf(float x); + +float log10f(float x); + +float sinf(double x); + +float asinf(double x); + +} // namespace fdlibm + +#endif // THIRD_PARTY_FDLIBM_IEEE754_H_ +
diff --git a/third_party/fdlibm/overflowing-math.h b/third_party/fdlibm/overflowing-math.h new file mode 100644 index 0000000..815fa62 --- /dev/null +++ b/third_party/fdlibm/overflowing-math.h
@@ -0,0 +1,96 @@ +// Copyright 2019 the V8 project authors. All rights reserved. +// Copyright 2020 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 THIRD_PARTY_FDLIBM_OVERFLOWING_MATH_H_ +#define THIRD_PARTY_FDLIBM_OVERFLOWING_MATH_H_ + +#include <stdint.h> + +#include <cmath> +#include <type_traits> + +#include "base/macros.h" + +namespace fdlibm { + +// Helpers for performing overflowing arithmetic operations without relying +// on C++ undefined behavior. +#define ASSERT_SIGNED_INTEGER_TYPE(Type) \ + static_assert(std::is_integral<Type>::value && std::is_signed<Type>::value, \ + "use this for signed integer types"); +#define OP_WITH_WRAPAROUND(Name, OP) \ + template <typename signed_type> \ + inline signed_type Name##WithWraparound(signed_type a, signed_type b) { \ + ASSERT_SIGNED_INTEGER_TYPE(signed_type); \ + using unsigned_type = typename std::make_unsigned<signed_type>::type; \ + unsigned_type a_unsigned = static_cast<unsigned_type>(a); \ + unsigned_type b_unsigned = static_cast<unsigned_type>(b); \ + unsigned_type result = a_unsigned OP b_unsigned; \ + return static_cast<signed_type>(result); \ + } + +OP_WITH_WRAPAROUND(Add, +) +OP_WITH_WRAPAROUND(Sub, -) +OP_WITH_WRAPAROUND(Mul, *) + +// 16-bit integers are special due to C++'s implicit conversion rules. +// See https://bugs.llvm.org/show_bug.cgi?id=25580. +template <> +inline int16_t MulWithWraparound(int16_t a, int16_t b) { + uint32_t a_unsigned = static_cast<uint32_t>(a); + uint32_t b_unsigned = static_cast<uint32_t>(b); + uint32_t result = a_unsigned * b_unsigned; + return static_cast<int16_t>(static_cast<uint16_t>(result)); +} + +#undef OP_WITH_WRAPAROUND + +template <typename signed_type> +inline signed_type NegateWithWraparound(signed_type a) { + ASSERT_SIGNED_INTEGER_TYPE(signed_type); + if (a == std::numeric_limits<signed_type>::min()) return a; + return -a; +} + +template <typename signed_type> +inline signed_type ShlWithWraparound(signed_type a, signed_type b) { + ASSERT_SIGNED_INTEGER_TYPE(signed_type); + using unsigned_type = typename std::make_unsigned<signed_type>::type; + const unsigned_type kMask = (sizeof(a) * 8) - 1; + return static_cast<signed_type>(static_cast<unsigned_type>(a) << (b & kMask)); +} + +#undef ASSERT_SIGNED_INTEGER_TYPE + +// Returns the quotient x/y, avoiding C++ undefined behavior if y == 0. +template <typename T> +inline T Divide(T x, T y) { + if (y != 0) return x / y; + if (x == 0 || x != x) return std::numeric_limits<T>::quiet_NaN(); + if ((x >= 0) == (std::signbit(y) == 0)) { + return std::numeric_limits<T>::infinity(); + } + return -std::numeric_limits<T>::infinity(); +} + +inline float Recip(float a) { return Divide(1.0f, a); } + +inline float RecipSqrt(float a) { + if (a != 0) return 1.0f / std::sqrt(a); + if (std::signbit(a) == 0) return std::numeric_limits<float>::infinity(); + return -std::numeric_limits<float>::infinity(); +} + +template <typename T> +inline T RoundingAverageUnsigned(T a, T b) { + static_assert(std::is_unsigned<T>::value, "Only for unsiged types"); + static_assert(sizeof(T) < sizeof(uint64_t), "Must be smaller than uint64_t"); + return (static_cast<uint64_t>(a) + static_cast<uint64_t>(b) + 1) >> 1; +} + +} // namespace fdlibm + +#endif // THIRD_PARTY_FDLIBM_OVERFLOWING_MATH_H_ +
diff --git a/tools/android/avd/proto/generic_playstore_android27.textpb b/tools/android/avd/proto/generic_playstore_android27.textpb new file mode 100644 index 0000000..8835f6d --- /dev/null +++ b/tools/android/avd/proto/generic_playstore_android27.textpb
@@ -0,0 +1,25 @@ +# Copyright 2021 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. + +# Configuration for a generic x86 android-27 AVD with the Playstore. + +emulator_package { + package_name: "chromium/third_party/android_sdk/public/emulator" + version: "Qv6vr_G7toc3CjPOoR8n_v--fIhm3zOKHSwz349eRIQC" + dest_path: ".emulator_sdk" +} + +system_image_package { + package_name: "chromium/third_party/android_sdk/public/system-images/android-27/google_apis_playstore/x86" + version: "2wUFGQFS3VXHYNlK7HIWwY50VO_wfeFgc4aTD8vTr7cC" + dest_path: ".emulator_sdk" +} +system_image_name: "system-images;android-27;google_apis_playstore;x86" + +avd_package { + package_name: "chromium/third_party/android_sdk/public/avds/android-27/google_apis_playstore/x86" + version: "j-6lAyD3V59ge4P8bQtJeR7B0uF8ZZJav8oInUoP3psC" + dest_path: ".android" +} +avd_name: "android_27_google_apis_playstore_x86"
diff --git a/tools/android/pagecontroller/search_strings.py b/tools/android/pagecontroller/search_strings.py index 8739ee9d..5370ea85 100755 --- a/tools/android/pagecontroller/search_strings.py +++ b/tools/android/pagecontroller/search_strings.py
@@ -15,7 +15,7 @@ os.path.dirname(__file__), '..', '..', '..')) _DEFAULT_GRD = os.path.join(_SRC_DIR, - 'chrome/android/java/strings/android_chrome_strings.grd') + 'chrome/browser/ui/android/strings/android_chrome_strings.grd') _MATCH_MSG = u' R.string.{}:\n Text = "{}"\n Desc = "{}"' class GrdSearch(object):
diff --git a/tools/binary_size/libsupersize/archive.py b/tools/binary_size/libsupersize/archive.py index b8488f6..01e1775 100644 --- a/tools/binary_size/libsupersize/archive.py +++ b/tools/binary_size/libsupersize/archive.py
@@ -844,9 +844,8 @@ metadata[models.METADATA_APK_FILENAME] = shorten_path( args.minimal_apks_file) if args.split_name and args.split_name != 'base': - metadata[models.METADATA_APK_SIZE] = os.path.getsize(args.apk_file) metadata[models.METADATA_APK_SPLIT_NAME] = args.split_name - metadata[models.METADATA_APK_SPLIT_ON_DEMAND] = _IsOnDemand(args.apk_file) + metadata[models.METADATA_APK_SIZE] = os.path.getsize(args.apk_file) else: sizes_by_module = _CollectModuleSizes(args.minimal_apks_file) for name, size in sizes_by_module.items(): @@ -2211,6 +2210,8 @@ with zip_util.UnzipToTemp( sub_args.minimal_apks_file, 'splits/{}-master.apk'.format(module_name)) as temp: + if _IsOnDemand(temp): + continue module_sub_args = copy.copy(sub_args) module_sub_args.apk_file = temp module_sub_args.split_name = module_name
diff --git a/tools/binary_size/libsupersize/integration_test.py b/tools/binary_size/libsupersize/integration_test.py index 90596b4..a24fe5f 100755 --- a/tools/binary_size/libsupersize/integration_test.py +++ b/tools/binary_size/libsupersize/integration_test.py
@@ -48,9 +48,7 @@ # The following files are dynamically created. _TEST_ELF_PATH = os.path.join(_TEST_OUTPUT_DIR, 'elf') _TEST_APK_PATH = os.path.join(_TEST_OUTPUT_DIR, 'test.apk') -_TEST_NOT_ON_DEMAND_SPLIT_APK_PATH = os.path.join(_TEST_OUTPUT_DIR, - 'not_on_demand.apk') -_TEST_ON_DEMAND_SPLIT_APK_PATH = os.path.join(_TEST_OUTPUT_DIR, 'on_demand.apk') +_TEST_OTHER_SPLIT_APK_PATH = os.path.join(_TEST_OUTPUT_DIR, 'other.apk') _TEST_MINIMAL_APKS_PATH = os.path.join(_TEST_OUTPUT_DIR, 'Bundle.minimal.apks') _TEST_SSARGS_PATH = os.path.join(_TEST_OUTPUT_DIR, 'test.ssargs') @@ -154,29 +152,29 @@ apk_file.writestr( _TEST_APK_DEX_PATH, IntegrationTest._CreateBlankData(23)) - with zipfile.ZipFile(_TEST_NOT_ON_DEMAND_SPLIT_APK_PATH, 'w') as z: - z.write(_TEST_ALWAYS_INSTALLED_MANIFEST_PATH, 'AndroidManifest.xml') - with zipfile.ZipFile(_TEST_ON_DEMAND_SPLIT_APK_PATH, 'w') as z: - z.write(_TEST_ON_DEMAND_MANIFEST_PATH, 'AndroidManifest.xml') + with zipfile.ZipFile(_TEST_OTHER_SPLIT_APK_PATH, 'w') as other_apk_zip: + other_apk_zip.write(_TEST_ALWAYS_INSTALLED_MANIFEST_PATH, + 'AndroidManifest.xml') with zipfile.ZipFile(_TEST_MINIMAL_APKS_PATH, 'w') as apk_file: - apk_file.writestr('toc.pb', 'x' * 80) apk_file.write(_TEST_APK_PATH, 'splits/base-master.apk') apk_file.writestr('splits/base-en.apk', 'x' * 10) - apk_file.write(_TEST_NOT_ON_DEMAND_SPLIT_APK_PATH, - 'splits/not_on_demand-master.apk') - apk_file.write(_TEST_ON_DEMAND_SPLIT_APK_PATH, - 'splits/on_demand-master.apk') + + with tempfile.NamedTemporaryFile(suffix='.apk') as vr_apk_file: + with zipfile.ZipFile(vr_apk_file.name, 'w') as vr_apk_zip: + vr_apk_zip.write(_TEST_ON_DEMAND_MANIFEST_PATH, 'AndroidManifest.xml') + apk_file.write(vr_apk_file.name, 'splits/vr-master.apk') apk_file.writestr('splits/vr-en.apk', 'x' * 40) + apk_file.write(_TEST_OTHER_SPLIT_APK_PATH, 'splits/other-master.apk') + apk_file.writestr('toc.pb', 'x' * 80) @classmethod def tearDownClass(cls): IntegrationTest._SafeRemoveFiles([ _TEST_ELF_PATH, _TEST_APK_PATH, - _TEST_NOT_ON_DEMAND_SPLIT_APK_PATH, - _TEST_ON_DEMAND_SPLIT_APK_PATH, + _TEST_OTHER_SPLIT_APK_PATH, _TEST_MINIMAL_APKS_PATH, ]) @@ -264,35 +262,20 @@ raw_symbols_list.append(raw_symbols) if use_minimal_apks: opts.analyze_native = False - args.split_name = 'not_on_demand' - args.apk_file = _TEST_NOT_ON_DEMAND_SPLIT_APK_PATH + args.split_name = 'other' + args.apk_file = _TEST_OTHER_SPLIT_APK_PATH args.elf_file = None args.map_file = None metadata = archive.CreateMetadata(args, None, build_config) container, raw_symbols = archive.CreateContainerAndSymbols( knobs=knobs, opts=opts, - container_name='{}/not_on_demand.apk'.format(container_name), + container_name='{}/other.apk'.format(container_name), metadata=metadata, tool_prefix=args.tool_prefix, output_directory=args.output_directory, source_directory=args.source_directory, - apk_path=_TEST_NOT_ON_DEMAND_SPLIT_APK_PATH, - size_info_prefix=size_info_prefix) - container_list.append(container) - raw_symbols_list.append(raw_symbols) - args.split_name = 'on_demand' - args.apk_file = _TEST_ON_DEMAND_SPLIT_APK_PATH - metadata = archive.CreateMetadata(args, None, build_config) - container, raw_symbols = archive.CreateContainerAndSymbols( - knobs=knobs, - opts=opts, - container_name='{}/on_demand.apk'.format(container_name), - metadata=metadata, - tool_prefix=args.tool_prefix, - output_directory=args.output_directory, - source_directory=args.source_directory, - apk_path=_TEST_ON_DEMAND_SPLIT_APK_PATH, + apk_path=_TEST_OTHER_SPLIT_APK_PATH, size_info_prefix=size_info_prefix) container_list.append(container) raw_symbols_list.append(raw_symbols)
diff --git a/tools/binary_size/libsupersize/models.py b/tools/binary_size/libsupersize/models.py index b74218cf..c5674994 100644 --- a/tools/binary_size/libsupersize/models.py +++ b/tools/binary_size/libsupersize/models.py
@@ -55,7 +55,6 @@ METADATA_APK_FILENAME = 'apk_file_name' # Path relative to output_directory. METADATA_APK_SIZE = 'apk_size' # File size of apk in bytes. METADATA_APK_SPLIT_NAME = 'apk_split_name' # Name of the split if applicable. -METADATA_APK_SPLIT_ON_DEMAND = 'apk_split_on_demand' # Split is onDemand. METADATA_ZIPALIGN_OVERHEAD = 'zipalign_padding' # Overhead from zipalign. METADATA_SIGNING_BLOCK_SIZE = 'apk_signature_block_size' # Size in bytes. METADATA_MAP_FILENAME = 'map_file_name' # Path relative to output_directory. @@ -998,13 +997,6 @@ def WherePssBiggerThan(self, min_pss): return self.Filter(lambda s: s.pss >= min_pss) - def WhereIsOnDemand(self, value=True): - ret = self.Filter(lambda s: not s.container or s.container.metadata.get( - METADATA_APK_SPLIT_ON_DEMAND)) - if not value: - ret = ret.Inverted() - return ret - def WhereInSection(self, section, container=None): """|section| can be section_name ('.bss'), or section chars ('bdr').""" if section.startswith('.'):
diff --git a/tools/binary_size/libsupersize/testdata/Archive_MinimalApks.golden b/tools/binary_size/libsupersize/testdata/Archive_MinimalApks.golden index 292596c..def1dba1d 100644 --- a/tools/binary_size/libsupersize/testdata/Archive_MinimalApks.golden +++ b/tools/binary_size/libsupersize/testdata/Archive_MinimalApks.golden
@@ -4,8 +4,8 @@ tool_prefix=tools/binary_size/libsupersize/testdata/mock_toolchain/ apk_file_name=Bundle.minimal.apks apk_signature_block_size=0 -apk_size-not_on_demand=696 -apk_size-on_demand=695 +apk_size-other=696 +apk_size-vr=695 apk_size=147858911 elf_arch=arm elf_build_id=WhatAnAmazingBuildId @@ -17,14 +17,7 @@ apk_file_name=Bundle.minimal.apks apk_signature_block_size=0 apk_size=696 -apk_split_name=not_on_demand -apk_split_on_demand=False -zipalign_padding=0 -apk_file_name=Bundle.minimal.apks -apk_signature_block_size=0 -apk_size=695 -apk_split_name=on_demand -apk_split_on_demand=True +apk_split_name=other zipalign_padding=0 Container <Bundle.minimal.apks/base.apk> Section .text: has 100.0% of 35982248 bytes accounted for from 22 symbols. 0 bytes are unaccounted for. @@ -99,7 +92,7 @@ * 0 symbols have shared ownership. * 1 symbols are from generated sources. Accounts for 4194304 bytes (4.4%). -Container <Bundle.minimal.apks/not_on_demand.apk> +Container <Bundle.minimal.apks/other.apk> Section .text: 0 bytes from 0 symbols. * Padding accounts for 0 bytes (0.0%) * 0 have source paths. Accounts for 0 bytes (0.0%). @@ -152,60 +145,6 @@ * 0 have a component assigned. Accounts for 0 bytes (0.0%). * 0 symbols have shared ownership. * 1 symbols are from generated sources. Accounts for 560 bytes (80.5%). - -Container <Bundle.minimal.apks/on_demand.apk> -Section .text: 0 bytes from 0 symbols. -* Padding accounts for 0 bytes (0.0%) -* 0 have source paths. Accounts for 0 bytes (0.0%). -* 0 have a component assigned. Accounts for 0 bytes (0.0%). -* 0 symbols have shared ownership. -Section .rodata: 0 bytes from 0 symbols. -* Padding accounts for 0 bytes (0.0%) -* 0 have source paths. Accounts for 0 bytes (0.0%). -* 0 have a component assigned. Accounts for 0 bytes (0.0%). -* 0 string literals exist. Accounts for 0 bytes (0.0%) padding is 0 bytes. -* 0 symbols have shared ownership. -Section .data.rel.ro: 0 bytes from 0 symbols. -* Padding accounts for 0 bytes (0.0%) -* 0 have source paths. Accounts for 0 bytes (0.0%). -* 0 have a component assigned. Accounts for 0 bytes (0.0%). -* 0 symbols have shared ownership. -Section .data: 0 bytes from 0 symbols. -* Padding accounts for 0 bytes (0.0%) -* 0 have source paths. Accounts for 0 bytes (0.0%). -* 0 have a component assigned. Accounts for 0 bytes (0.0%). -* 0 symbols have shared ownership. -Section .bss: 0 bytes from 0 symbols. -* Padding accounts for 0 bytes (0.0%) -* 0 have source paths. Accounts for 0 bytes (0.0%). -* 0 have a component assigned. Accounts for 0 bytes (0.0%). -* 0 symbols have shared ownership. -Section .dex: has 0.0% of 0 bytes accounted for from 0 symbols. 0 bytes are unaccounted for. -* Padding accounts for 0 bytes (0.0%) -* 0 have source paths. Accounts for 0 bytes (0.0%). -* 0 have a component assigned. Accounts for 0 bytes (0.0%). -* 0 symbols have shared ownership. -Section .dex.method: has 0.0% of 0 bytes accounted for from 0 symbols. 0 bytes are unaccounted for. -* Padding accounts for 0 bytes (0.0%) -* 0 have source paths. Accounts for 0 bytes (0.0%). -* 0 have a component assigned. Accounts for 0 bytes (0.0%). -* 0 symbols have shared ownership. -Section .pak.translations: 0 bytes from 0 symbols. -* Padding accounts for 0 bytes (0.0%) -* 0 have source paths. Accounts for 0 bytes (0.0%). -* 0 have a component assigned. Accounts for 0 bytes (0.0%). -* 0 symbols have shared ownership. -Section .pak.nontranslated: 0 bytes from 0 symbols. -* Padding accounts for 0 bytes (0.0%) -* 0 have source paths. Accounts for 0 bytes (0.0%). -* 0 have a component assigned. Accounts for 0 bytes (0.0%). -* 0 symbols have shared ownership. -Section .other: has 100.0% of 695 bytes accounted for from 2 symbols. 0 bytes are unaccounted for. -* Padding accounts for 136 bytes (19.6%) -* 1 have source paths. Accounts for 559 bytes (80.4%). -* 0 have a component assigned. Accounts for 0 bytes (0.0%). -* 0 symbols have shared ownership. -* 1 symbols are from generated sources. Accounts for 559 bytes (80.4%). <Bundle.minimal.apks/base.apk>.text@28d900(size_without_padding=16,padding=0,full_name=_GLOBAL__sub_I_page_allocator.cc,object_path=base/base/page_allocator.o,source_path=base/page_allocator.cc,flags={startup},num_aliases=1,component=Blink>Internal) <Bundle.minimal.apks/base.apk>.text@28d910(size_without_padding=56,padding=0,full_name=_GLOBAL__sub_I_bbr_sender.cc,object_path=base/base/page_allocator.o,source_path=base/page_allocator.cc,flags={startup},num_aliases=1,component=Blink>Internal) <Bundle.minimal.apks/base.apk>.text@28d948(size_without_padding=28,padding=0,full_name=_GLOBAL__sub_I_pacing_sender.cc,object_path=base/base/page_allocator.o,source_path=base/page_allocator.cc,flags={startup},num_aliases=1,component=Blink>Internal) @@ -702,7 +641,5 @@ <Bundle.minimal.apks/base.apk>.other@0(size_without_padding=17166112,padding=0,full_name=** ELF Section: .symtab,object_path=,source_path=,flags={},num_aliases=1,component=) <Bundle.minimal.apks/base.apk>.other@0(size_without_padding=0,padding=764,full_name=Overhead: APK file,object_path=,source_path=,flags={},num_aliases=1,component=) <Bundle.minimal.apks/base.apk>.other@0(size_without_padding=0,padding=33902635,full_name=Overhead: ELF file,object_path=,source_path=,flags={},num_aliases=1,component=) -<Bundle.minimal.apks/not_on_demand.apk>.other@0(size_without_padding=560,padding=0,full_name=AndroidManifest.xml,object_path=,source_path=$APK/AndroidManifest.xml,flags={gen},num_aliases=1,component=) -<Bundle.minimal.apks/not_on_demand.apk>.other@0(size_without_padding=0,padding=136,full_name=Overhead: APK file,object_path=,source_path=,flags={},num_aliases=1,component=) -<Bundle.minimal.apks/on_demand.apk>.other@0(size_without_padding=559,padding=0,full_name=AndroidManifest.xml,object_path=,source_path=$APK/AndroidManifest.xml,flags={gen},num_aliases=1,component=) -<Bundle.minimal.apks/on_demand.apk>.other@0(size_without_padding=0,padding=136,full_name=Overhead: APK file,object_path=,source_path=,flags={},num_aliases=1,component=) +<Bundle.minimal.apks/other.apk>.other@0(size_without_padding=560,padding=0,full_name=AndroidManifest.xml,object_path=,source_path=$APK/AndroidManifest.xml,flags={gen},num_aliases=1,component=) +<Bundle.minimal.apks/other.apk>.other@0(size_without_padding=0,padding=136,full_name=Overhead: APK file,object_path=,source_path=,flags={},num_aliases=1,component=)
diff --git a/tools/binary_size/libsupersize/testdata/Console.golden b/tools/binary_size/libsupersize/testdata/Console.golden index 03a9f2b..26f3e06 100644 --- a/tools/binary_size/libsupersize/testdata/Console.golden +++ b/tools/binary_size/libsupersize/testdata/Console.golden
@@ -4,7 +4,7 @@ SizeInfo: ContainerForName, all_section_sizes, build_config, containers, metadata, metadata_legacy, native_symbols, pak_symbols, raw_symbols, size_path, symbols Symbol: FlagsString, IsBss, IsDelta, IsDex, IsGeneratedByToolchain, IsGroup, IsNameUnique, IsNative, IsOther, IsOverhead, IsPak, IsStringLiteral, IterLeafSymbols, SetName, address, aliases, component, container, container_name, container_short_name, end_address, flags, full_name, generated_source, is_anonymous, name, num_aliases, object_path, padding, padding_pss, pss, pss_without_padding, section, section_name, size, size_without_padding, source_path, template_name -SymbolGroup (extends Symbol): CountUniqueSymbols, Filter, GroupedBy, GroupedByAliases, GroupedByComponent, GroupedByContainer, GroupedByContainerAndSectionName, GroupedByFullName, GroupedByName, GroupedByPath, GroupedBySectionName, Inverted, IterUniqueSymbols, Sorted, SortedByAddress, SortedByCount, SortedByName, WhereAddressInRange, WhereComponentMatches, WhereFullNameMatches, WhereGeneratedByToolchain, WhereHasAnyAttribution, WhereHasComponent, WhereHasFlag, WhereHasPath, WhereInSection, WhereIsDex, WhereIsGroup, WhereIsNative, WhereIsOnDemand, WhereIsPak, WhereIsTemplate, WhereMatches, WhereNameMatches, WhereObjectPathMatches, WherePathMatches, WherePssBiggerThan, WhereSizeBiggerThan, WhereSourceIsGenerated, WhereSourcePathMatches, WhereTemplateNameMatches, index, is_default_sorted +SymbolGroup (extends Symbol): CountUniqueSymbols, Filter, GroupedBy, GroupedByAliases, GroupedByComponent, GroupedByContainer, GroupedByContainerAndSectionName, GroupedByFullName, GroupedByName, GroupedByPath, GroupedBySectionName, Inverted, IterUniqueSymbols, Sorted, SortedByAddress, SortedByCount, SortedByName, WhereAddressInRange, WhereComponentMatches, WhereFullNameMatches, WhereGeneratedByToolchain, WhereHasAnyAttribution, WhereHasComponent, WhereHasFlag, WhereHasPath, WhereInSection, WhereIsDex, WhereIsGroup, WhereIsNative, WhereIsPak, WhereIsTemplate, WhereMatches, WhereNameMatches, WhereObjectPathMatches, WherePathMatches, WherePssBiggerThan, WhereSizeBiggerThan, WhereSourceIsGenerated, WhereSourcePathMatches, WhereTemplateNameMatches, index, is_default_sorted DeltaSizeInfo: ContainerForName, after, all_section_sizes, before, build_config, containers, metadata, native_symbols, pak_symbols, raw_symbols, symbols DeltaSymbol (extends Symbol): after_symbol, before_symbol, diff_status
diff --git a/tools/binary_size/trybot_commit_size_checker.py b/tools/binary_size/trybot_commit_size_checker.py index abd7839..f47f19c 100755 --- a/tools/binary_size/trybot_commit_size_checker.py +++ b/tools/binary_size/trybot_commit_size_checker.py
@@ -102,7 +102,6 @@ def _CreateMethodCountDelta(symbols): - symbols = symbols.WhereIsOnDemand(False) method_symbols = symbols.WhereInSection(models.SECTION_DEX_METHOD) method_lines, net_method_added = _SymbolDiffHelper('Methods', method_symbols) class_symbols = symbols.WhereInSection(
diff --git a/tools/code_coverage/coverage.py b/tools/code_coverage/coverage.py index f840456..f574812 100755 --- a/tools/code_coverage/coverage.py +++ b/tools/code_coverage/coverage.py
@@ -187,6 +187,11 @@ return build_args['target_os'] if 'target_os' in build_args else '' +def _IsAndroid(): + """Returns true if the target_os specified in args.gn file is android""" + return _GetTargetOS() == 'android' + + def _IsIOS(): """Returns true if the target_os specified in args.gn file is ios""" return _GetTargetOS() == 'ios' @@ -351,6 +356,12 @@ profraw_file_paths = [] if _IsIOS(): profraw_file_paths = [_GetProfrawDataFileByParsingOutput(output)] + elif _IsAndroid(): + android_coverage_dir = os.path.join(BUILD_DIR, 'coverage') + for r, _, files in os.walk(android_coverage_dir): + for f in files: + if f.endswith(PROFRAW_FILE_EXTENSION): + profraw_file_paths.append(os.path.join(r, f)) else: for file_or_dir in os.listdir(report_root_dir): if file_or_dir.endswith(PROFRAW_FILE_EXTENSION): @@ -571,7 +582,6 @@ LLVM_PROFDATA_PATH, 'merge', '-o', profdata_file_path, '-sparse=true' ] subprocess_cmd.extend(profraw_file_paths) - output = subprocess.check_output(subprocess_cmd) logging.debug('Merge output: %s', output) except subprocess.CalledProcessError as error: @@ -706,9 +716,10 @@ else: current_platform = coverage_utils.GetHostPlatform() - assert current_platform in [ - 'linux', 'mac', 'chromeos', 'ios', 'win' - ], ('Coverage is only supported on linux, mac, chromeos, ios and win.') + supported_platforms = ['android', 'chromeos', 'ios', 'linux', 'mac', 'win'] + assert current_platform in supported_platforms, ('Coverage is only' + 'supported on %s' % + supported_platforms) def _GetBuildArgs(): @@ -763,8 +774,8 @@ def _GetBinaryPathsFromTargets(targets, build_dir): """Return binary paths from target names.""" - # FIXME: Derive output binary from target build definitions rather than - # assuming that it is always the same name. + # TODO(crbug.com/899974): Derive output binary from target build definitions + # rather than assuming that it is always the same name. binary_paths = [] for target in targets: binary_path = os.path.join(build_dir, target) @@ -798,6 +809,20 @@ return ' '.join(command_list) +def _GetBinaryPathsForAndroid(targets): + """Return binary paths used when running android tests.""" + # TODO(crbug.com/899974): Implement approach that doesn't assume .so file is + # based on the target's name. + android_binaries = set() + for target in targets: + so_library_path = os.path.join(BUILD_DIR, 'lib.unstripped', + 'lib%s__library.so' % target) + if os.path.exists(so_library_path): + android_binaries.add(so_library_path) + + return list(android_binaries) + + def _GetBinaryPathForWebTests(): """Return binary path used to run blink web tests.""" host_platform = coverage_utils.GetHostPlatform() @@ -1035,7 +1060,10 @@ 'otool') if os.path.exists(hermetic_otool_path): otool_path = hermetic_otool_path - if sys.platform.startswith('linux') or sys.platform.startswith('darwin'): + + if _IsAndroid(): + binary_paths = _GetBinaryPathsForAndroid(args.targets) + elif sys.platform.startswith('linux') or sys.platform.startswith('darwin'): binary_paths.extend( coverage_utils.GetSharedLibraries(binary_paths, BUILD_DIR, otool_path))
diff --git a/tools/metrics/histograms/enums.xml b/tools/metrics/histograms/enums.xml index fac433b..bea5f96 100644 --- a/tools/metrics/histograms/enums.xml +++ b/tools/metrics/histograms/enums.xml
@@ -41557,6 +41557,8 @@ label="Main Chrome Launcher Icon Shortcuts (New Tab shortcuts)"/> <int value="8" label="Home screen widget (eg. Search or Bookmarks)"/> <int value="9" label="Open In Browser CCT Menu"/> + <int value="10" + label="External Search Intent (eg. Third Party Voice Search results)"/> </enum> <enum name="LauncherRankingItemType"> @@ -56579,6 +56581,7 @@ <int value="502" label="Ambient Mode Photos (Deprecated)"/> <int value="503" label="Ambient Mode Google Photos Album"/> <int value="504" label="Ambient Mode Art Gallery Album"/> + <int value="505" label="Wallpaper"/> <int value="600" label="Assistant"/> <int value="700" label="App Management"/> <int value="701" label="App Details"/>
diff --git a/tools/metrics/histograms/histograms_xml/ash/histograms.xml b/tools/metrics/histograms/histograms_xml/ash/histograms.xml index 29fa9b2..b37f6bbe 100644 --- a/tools/metrics/histograms/histograms_xml/ash/histograms.xml +++ b/tools/metrics/histograms/histograms_xml/ash/histograms.xml
@@ -1213,6 +1213,36 @@ </summary> </histogram> +<histogram name="Ash.LoginAnimation.Duration" units="ms" + expires_after="2021-12-10"> + <owner>oshima@chromium.org</owner> + <owner>chromeos-wmp@google.com</owner> + <summary> + The duration of how long it took to finish all animations applied during the + login process, from the time the first animation is added, to the time the + last animation is finished. + </summary> +</histogram> + +<histogram name="Ash.LoginAnimation.Jank" units="%" expires_after="2021-12-10"> + <owner>oshima@chromium.org</owner> + <owner>chromeos-wmp@google.com</owner> + <summary> + Jank metrics of all animations applied during the login process. This + represents how often the frame update rate changed during animation. + </summary> +</histogram> + +<histogram name="Ash.LoginAnimation.Smoothness" units="%" + expires_after="2021-12-10"> + <owner>oshima@chromium.org</owner> + <owner>chromeos-wmp@google.com</owner> + <summary> + Relative smoothness of all animations applied during the login process. 100% + represents the ideal smoothness for 60 frames per second. + </summary> +</histogram> + <histogram name="Ash.Media.CameraPrivacySwitch.Event" enum="CameraPrivacySwitchEvent" expires_after="2021-12-31"> <owner>tbarzic@chromium.org</owner> @@ -2169,6 +2199,25 @@ </summary> </histogram> +<histogram name="Ash.UnlockAnimation.Jank" units="%" expires_after="2021-12-10"> + <owner>oshima@chromium.org</owner> + <owner>chromeos-wmp@google.com</owner> + <summary> + Jank metrics of all animations applied during the unlock process. This + represents how often the frame update rate changed during animation. + </summary> +</histogram> + +<histogram name="Ash.UnlockAnimation.Smoothness" units="%" + expires_after="2021-12-10"> + <owner>oshima@chromium.org</owner> + <owner>chromeos-wmp@google.com</owner> + <summary> + Relative smoothness of all animations applied during the unlock process. + 100% represents the ideal smoothness for 60 frames per second. + </summary> +</histogram> + <histogram name="Ash.Wallpaper.ColorExtractionResult2" enum="WallpaperColorExtractionResult" expires_after="M92"> <owner>newcomer@chromium.org</owner>
diff --git a/tools/metrics/histograms/histograms_xml/histogram_suffixes_list.xml b/tools/metrics/histograms/histograms_xml/histogram_suffixes_list.xml index cc285ecf..3556d6f 100644 --- a/tools/metrics/histograms/histograms_xml/histogram_suffixes_list.xml +++ b/tools/metrics/histograms/histograms_xml/histogram_suffixes_list.xml
@@ -16575,7 +16575,11 @@ side detection."/> <suffix name="from_data_saver" label="Interstitial for a resource classified as unsafe by the Data - Saver service."/> + Saver service."> + <obsolete> + Deprecated as of 2021-1. Data saver has been completely turned down. + </obsolete> + </suffix> <suffix name="from_device" label="Interstitial for a resource classified as unsafe by the Safe Browsing database via either
diff --git a/tools/metrics/histograms/histograms_xml/net/histograms.xml b/tools/metrics/histograms/histograms_xml/net/histograms.xml index 0a12bfb..bc6dfef 100644 --- a/tools/metrics/histograms/histograms_xml/net/histograms.xml +++ b/tools/metrics/histograms/histograms_xml/net/histograms.xml
@@ -612,7 +612,7 @@ </histogram> <histogram base="true" name="Net.DNS.DnsTransaction.Insecure.FailureTime" - units="ms" expires_after="2021-02-28"> + units="ms" expires_after="2021-07-28"> <!-- Name completed by histogram_suffixes name="DohProviderId" --> @@ -624,7 +624,7 @@ </histogram> <histogram base="true" name="Net.DNS.DnsTransaction.Insecure.SuccessTime" - units="ms" expires_after="2021-02-28"> + units="ms" expires_after="2021-07-28"> <!-- Name completed by histogram_suffixes name="DohProviderId" --> @@ -682,7 +682,7 @@ <histogram base="true" name="Net.DNS.DnsTransaction.SecureValidated.FailureError" - enum="NetErrorCodes" expires_after="2021-02-28"> + enum="NetErrorCodes" expires_after="2021-07-28"> <!-- Name completed by histogram_suffixes name="DohProviderId" --> @@ -698,7 +698,7 @@ <histogram base="true" name="Net.DNS.DnsTransaction.SecureValidated.FailureTime" units="ms" - expires_after="2021-02-28"> + expires_after="2021-07-28"> <!-- Name completed by histogram_suffixes name="DohProviderId" --> @@ -713,7 +713,7 @@ <histogram base="true" name="Net.DNS.DnsTransaction.SecureValidated.SuccessTime" units="ms" - expires_after="2021-02-28"> + expires_after="2021-07-28"> <!-- Name completed by histogram_suffixes name="DohProviderId" --> @@ -1237,6 +1237,9 @@ <histogram name="Net.DNS.SecureDnsTaskFailure.FallbackDnsTask.Error" enum="NetErrorCodes" expires_after="2021-01-31"> + <obsolete> + Removed from code 2021-01. + </obsolete> <owner>ericorth@chromium.org</owner> <owner>doh-core@google.com</owner> <summary> @@ -1247,6 +1250,9 @@ <histogram name="Net.DNS.SecureDnsTaskFailure.FallbackProcTask.Error" enum="NetErrorCodes" expires_after="2021-01-31"> + <obsolete> + Removed from code 2021-01. + </obsolete> <owner>ericorth@chromium.org</owner> <owner>doh-core@google.com</owner> <summary> @@ -2622,8 +2628,8 @@ <owner>dschinazi@chromium.org</owner> <owner>src/net/quic/OWNERS</owner> <summary> - The QUIC error code which resulted in the Google QUIC connection being - closed by the client. + The QUIC error code which resulted in the QUIC connection being closed by + the client. </summary> </histogram> @@ -2632,8 +2638,8 @@ <owner>dschinazi@chromium.org</owner> <owner>src/net/quic/OWNERS</owner> <summary> - The QUIC error code which resulted in the Google QUIC connection being - closed by the client to a server ending in .google.com. + The QUIC error code which resulted in the QUIC connection being closed by + the client to a Google server. </summary> </histogram> @@ -2642,8 +2648,8 @@ <owner>dschinazi@chromium.org</owner> <owner>src/net/quic/OWNERS</owner> <summary> - The QUIC error code which resulted in the Google QUIC connection being - closed by the server. + The QUIC error code which resulted in the QUIC connection being closed by + the server. </summary> </histogram> @@ -2652,8 +2658,8 @@ <owner>dschinazi@chromium.org</owner> <owner>src/net/quic/OWNERS</owner> <summary> - The QUIC error code which resulted in the Google QUIC connection being - closed by the server with a name ending in .google.com. + The QUIC error code which resulted in the QUIC connection being closed by + the a Google server. </summary> </histogram> @@ -2674,7 +2680,7 @@ <owner>src/net/quic/OWNERS</owner> <summary> The QUIC application transport error code in a CONNECTION_CLOSE frame - received from the server with a name ending in .google.com. + received from a Google server. </summary> </histogram> @@ -2696,8 +2702,7 @@ <owner>src/net/quic/OWNERS</owner> <summary> The QUIC application transport error code in a CONNECTION_CLOSE frame - received from the server with a name ending in .google.com, when the GQUIC - error was missing. + received from a Google server, when the GQUIC error was missing. </summary> </histogram> @@ -2718,7 +2723,7 @@ <owner>src/net/quic/OWNERS</owner> <summary> The QUIC application transport error code in a CONNECTION_CLOSE frame - received from the server with a name ending in .google.com. + received from a Google server. </summary> </histogram> @@ -2740,8 +2745,7 @@ <owner>src/net/quic/OWNERS</owner> <summary> The QUIC application transport error code in a CONNECTION_CLOSE frame - received from the server with a name ending in .google.com, when the GQUIC - error was missing. + received from a Google server, when the GQUIC error was missing. </summary> </histogram> @@ -4458,9 +4462,7 @@ expires_after="2021-07-11"> <owner>dschinazi@chromium.org</owner> <owner>src/net/OWNERS</owner> - <summary> - Net error codes when SpdySession was closed, doesn't inlcuding net::OK. - </summary> + <summary>Net error codes when SpdySession was closed.</summary> </histogram> <histogram name="Net.SpdySession.CreateStreamWithSocketConnected"
diff --git a/tools/perf/core/perfetto_binary_roller/binary_deps.json b/tools/perf/core/perfetto_binary_roller/binary_deps.json index 94e63be..376d30a 100644 --- a/tools/perf/core/perfetto_binary_roller/binary_deps.json +++ b/tools/perf/core/perfetto_binary_roller/binary_deps.json
@@ -1,16 +1,16 @@ { "trace_processor_shell": { "win": { - "hash": "1fe46aed4c4b14293076b2673658de4b83861964", - "remote_path": "perfetto_binaries/trace_processor_shell/win/ba64aafa504a8efc8f08b7ae2bf2b497618798cf/trace_processor_shell.exe" + "hash": "7b9fd9471b5f49e935317fbfdf8a627692b08698", + "remote_path": "perfetto_binaries/trace_processor_shell/win/2c34e7b1bd19a22f5c8d41925069d7e1a7851e3b/trace_processor_shell.exe" }, "mac": { - "hash": "a7bc2f0ad851a73b55c15169a58bbfc10b543baa", - "remote_path": "perfetto_binaries/trace_processor_shell/mac/efde4cb992de62381f9a411279d5511bfe46c86f/trace_processor_shell" + "hash": "8b91ec656a7cae87c90b5a33f96321eac11e9027", + "remote_path": "perfetto_binaries/trace_processor_shell/mac/2c34e7b1bd19a22f5c8d41925069d7e1a7851e3b/trace_processor_shell" }, "linux": { - "hash": "320a6d2d541614e34e8c80333c7fcb4bd877d694", - "remote_path": "perfetto_binaries/trace_processor_shell/linux/2c34e7b1bd19a22f5c8d41925069d7e1a7851e3b/trace_processor_shell" + "hash": "6c866fbf5a4ac5898831591720953aa3bcc008b7", + "remote_path": "perfetto_binaries/trace_processor_shell/linux/83d683fdbb2c1f5e4a903c7cadd436b3b97ead20/trace_processor_shell" } }, "power_profile.sql": {
diff --git a/tools/perf/page_sets/desktop_ui/multitab_story.py b/tools/perf/page_sets/desktop_ui/multitab_story.py index f2bcaf4..b91c1c6 100644 --- a/tools/perf/page_sets/desktop_ui/multitab_story.py +++ b/tools/perf/page_sets/desktop_ui/multitab_story.py
@@ -46,4 +46,4 @@ chrome_trace_config.category_filter.AddIncludedCategory('blink.user_timing') def GetExtraTracingMetrics(self): - return ['webuiMetric'] + return []
diff --git a/ui/accessibility/platform/BUILD.gn b/ui/accessibility/platform/BUILD.gn index 7b8196b..ce6e22e 100644 --- a/ui/accessibility/platform/BUILD.gn +++ b/ui/accessibility/platform/BUILD.gn
@@ -59,6 +59,8 @@ "ax_platform_node_test_helper.h", # Used by DumpAccTree testsuite and a11y tools + "inspect/ax_event_recorder.cc", + "inspect/ax_event_recorder.h", "inspect/ax_inspect.cc", "inspect/ax_inspect.h", "inspect/ax_property_node.cc",
diff --git a/ui/accessibility/platform/inspect/ax_event_recorder.cc b/ui/accessibility/platform/inspect/ax_event_recorder.cc new file mode 100644 index 0000000..779652b --- /dev/null +++ b/ui/accessibility/platform/inspect/ax_event_recorder.cc
@@ -0,0 +1,24 @@ +// Copyright 2021 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 "ui/accessibility/platform/inspect/ax_event_recorder.h" + +#include "base/callback_helpers.h" + +namespace ui { + +AXEventRecorder::AXEventRecorder() = default; +AXEventRecorder::~AXEventRecorder() = default; + +void AXEventRecorder::StopListeningToEvents() { + callback_ = base::NullCallback(); +} + +void AXEventRecorder::OnEvent(const std::string& event) { + event_logs_.push_back(event); + if (callback_) + callback_.Run(event); +} + +} // namespace ui
diff --git a/ui/accessibility/platform/inspect/ax_event_recorder.h b/ui/accessibility/platform/inspect/ax_event_recorder.h new file mode 100644 index 0000000..a398cf8 --- /dev/null +++ b/ui/accessibility/platform/inspect/ax_event_recorder.h
@@ -0,0 +1,73 @@ +// Copyright 2021 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 UI_ACCESSIBILITY_PLATFORM_INSPECT_AX_EVENT_RECORDER_H_ +#define UI_ACCESSIBILITY_PLATFORM_INSPECT_AX_EVENT_RECORDER_H_ + +#include <string> +#include <vector> + +#include "base/callback.h" +#include "ui/accessibility/ax_export.h" + +namespace ui { + +using AXEventCallback = base::RepeatingCallback<void(const std::string&)>; + +// Listens for native accessibility events fired by a given +// BrowserAccessibilityManager and saves human-readable log strings for +// each event fired to a vector. Construct an instance of this class to +// begin listening, call GetEventLogs() to get all of the logs so far, and +// destroy it to stop listening. +// +// A log string should be of the form "<event> on <node>" where <event> is +// the name of the event fired (platform-specific) and <node> is information +// about the accessibility node on which the event was fired, for example its +// role and name. +// +// The implementation is highly platform-specific; a subclass is needed for +// each platform does most of the work. +// +// As currently designed, there should only be one instance of this class. +class AX_EXPORT AXEventRecorder { + public: + AXEventRecorder(); + virtual ~AXEventRecorder(); + + // Scopes/unscopes events to a web area. + void SetOnlyWebEvents(bool only_web_events) { + only_web_events_ = only_web_events; + } + + // Sets a callback which will be called on every event fired. + void ListenToEvents(AXEventCallback callback) { + callback_ = std::move(callback); + } + + // Stop listenting to events. + void StopListeningToEvents(); + + // Called to ensure the event recorder has finished recording async events. + virtual void FlushAsyncEvents() {} + + // Access the vector of human-readable event logs, one string per event. + const std::vector<std::string>& EventLogs() { return event_logs_; } + + protected: + // Called by a derived class which implements platform event handling on + // every fired event. + void OnEvent(const std::string& event); + + bool only_web_events_ = false; + + private: + std::vector<std::string> event_logs_; + AXEventCallback callback_; + + DISALLOW_COPY_AND_ASSIGN(AXEventRecorder); +}; + +} // namespace ui + +#endif // UI_ACCESSIBILITY_PLATFORM_INSPECT_AX_EVENT_RECORDER_H_
diff --git a/ui/ozone/platform/drm/gpu/drm_overlay_validator.cc b/ui/ozone/platform/drm/gpu/drm_overlay_validator.cc index 4c49654..348cba7 100644 --- a/ui/ozone/platform/drm/gpu/drm_overlay_validator.cc +++ b/ui/ozone/platform/drm/gpu/drm_overlay_validator.cc
@@ -46,7 +46,7 @@ // flip commits. std::vector<uint64_t> modifiers = is_0th_plane - ? drm_window->GetController()->GetFormatModifiers(fourcc_format) + ? drm_window->GetController()->GetSupportedModifiers(fourcc_format) : std::vector<uint64_t>(); // Check if we can re-use existing buffers.
diff --git a/ui/ozone/platform/drm/gpu/drm_thread.cc b/ui/ozone/platform/drm/gpu/drm_thread.cc index 1de5138..115231c 100644 --- a/ui/ozone/platform/drm/gpu/drm_thread.cc +++ b/ui/ozone/platform/drm/gpu/drm_thread.cc
@@ -142,7 +142,7 @@ std::vector<uint64_t> modifiers; if (window && window->GetController() && !(flags & GBM_BO_USE_LINEAR) && !(client_flags & GbmPixmap::kFlagNoModifiers)) { - modifiers = window->GetController()->GetFormatModifiers(fourcc_format); + modifiers = window->GetController()->GetSupportedModifiers(fourcc_format); } CreateBufferWithGbmFlags(drm, fourcc_format, size, framebuffer_size, flags,
diff --git a/ui/ozone/platform/drm/gpu/hardware_display_controller.cc b/ui/ozone/platform/drm/gpu/hardware_display_controller.cc index 08418f7..73eae42 100644 --- a/ui/ozone/platform/drm/gpu/hardware_display_controller.cc +++ b/ui/ozone/platform/drm/gpu/hardware_display_controller.cc
@@ -19,6 +19,7 @@ #include "ui/gfx/geometry/point.h" #include "ui/gfx/geometry/size.h" #include "ui/gfx/gpu_fence.h" +#include "ui/gfx/linux/drm_util_linux.h" #include "ui/gfx/native_pixmap.h" #include "ui/gfx/presentation_feedback.h" #include "ui/gfx/swap_result.h" @@ -218,17 +219,16 @@ } std::vector<uint64_t> HardwareDisplayController::GetFormatModifiers( - uint32_t format) const { - std::vector<uint64_t> modifiers; - + uint32_t fourcc_format) const { if (crtc_controllers_.empty()) - return modifiers; + return std::vector<uint64_t>(); - modifiers = crtc_controllers_[0]->GetFormatModifiers(format); + std::vector<uint64_t> modifiers = + crtc_controllers_[0]->GetFormatModifiers(fourcc_format); for (size_t i = 1; i < crtc_controllers_.size(); ++i) { std::vector<uint64_t> other = - crtc_controllers_[i]->GetFormatModifiers(format); + crtc_controllers_[i]->GetFormatModifiers(fourcc_format); std::vector<uint64_t> intersection; std::set_intersection(modifiers.begin(), modifiers.end(), other.begin(), @@ -239,11 +239,26 @@ return modifiers; } -std::vector<uint64_t> -HardwareDisplayController::GetFormatModifiersForModesetting( +std::vector<uint64_t> HardwareDisplayController::GetSupportedModifiers( uint32_t fourcc_format) const { - const auto& modifiers = GetFormatModifiers(fourcc_format); + if (preferred_format_modifier_.empty()) + return std::vector<uint64_t>(); + + auto it = preferred_format_modifier_.find(fourcc_format); + if (it != preferred_format_modifier_.end()) + return std::vector<uint64_t>{it->second}; + + return GetFormatModifiers(fourcc_format); +} + +std::vector<uint64_t> +HardwareDisplayController::GetFormatModifiersForTestModeset( + uint32_t fourcc_format) { + // If we're about to test, clear the current preferred modifier. + preferred_format_modifier_.clear(); + std::vector<uint64_t> filtered_modifiers; + const auto& modifiers = GetFormatModifiers(fourcc_format); for (auto modifier : modifiers) { // AFBC for modeset buffers doesn't work correctly, as we can't fill it with // a valid AFBC buffer. For now, don't use AFBC for modeset buffers. @@ -256,6 +271,18 @@ return filtered_modifiers; } +void HardwareDisplayController::UpdatePreferredModiferForFormat( + gfx::BufferFormat buffer_format, + uint64_t modifier) { + uint32_t fourcc_format = GetFourCCFormatFromBufferFormat(buffer_format); + base::InsertOrAssign(preferred_format_modifier_, fourcc_format, modifier); + + uint32_t opaque_fourcc_format = + GetFourCCFormatForOpaqueFramebuffer(buffer_format); + base::InsertOrAssign(preferred_format_modifier_, opaque_fourcc_format, + modifier); +} + void HardwareDisplayController::MoveCursor(const gfx::Point& location) { cursor_location_ = location; UpdateCursorLocation();
diff --git a/ui/ozone/platform/drm/gpu/hardware_display_controller.h b/ui/ozone/platform/drm/gpu/hardware_display_controller.h index 17a9171..8bffa824 100644 --- a/ui/ozone/platform/drm/gpu/hardware_display_controller.h +++ b/ui/ozone/platform/drm/gpu/hardware_display_controller.h
@@ -14,9 +14,11 @@ #include <vector> #include "base/callback.h" +#include "base/containers/flat_map.h" #include "base/macros.h" #include "base/time/time.h" #include "third_party/skia/include/core/SkBitmap.h" +#include "ui/gfx/buffer_types.h" #include "ui/gfx/swap_result.h" #include "ui/ozone/platform/drm/gpu/drm_overlay_plane.h" #include "ui/ozone/platform/drm/gpu/hardware_display_plane_manager.h" @@ -128,17 +130,19 @@ // doesn't change any state. bool TestPageFlip(const DrmOverlayPlaneList& plane_list); - // Return the supported modifiers for |fourcc_format| for this - // controller. - std::vector<uint64_t> GetFormatModifiers(uint32_t fourcc_format) const; + // Return the supported modifiers for |fourcc_format| for this controller. + std::vector<uint64_t> GetSupportedModifiers(uint32_t fourcc_format) const; // Return the supported modifiers for |fourcc_format| for this // controller to be used for modeset buffers. Currently, this only exists // because we can't provide valid AFBC buffers during modeset. // See https://crbug.com/852675 // TODO: Remove this. - std::vector<uint64_t> GetFormatModifiersForModesetting( - uint32_t fourcc_format) const; + std::vector<uint64_t> GetFormatModifiersForTestModeset( + uint32_t fourcc_format); + + void UpdatePreferredModiferForFormat(gfx::BufferFormat buffer_format, + uint64_t modifier); // Moves the hardware cursor to |location|. void MoveCursor(const gfx::Point& location); @@ -189,6 +193,8 @@ void ResetCursor(); void DisableCursor(); + std::vector<uint64_t> GetFormatModifiers(uint32_t fourcc_format) const; + HardwareDisplayPlaneList owned_hardware_planes_; // Stores the CRTC configuration. This is used to identify monitors and @@ -207,6 +213,11 @@ int cursor_frontbuffer_ = 0; DrmDumbBuffer* current_cursor_ = nullptr; + // Maps each fourcc_format to its preferred modifier which was generated + // through modeset-test and updated in UpdatePreferredModifierForFormat(). + base::flat_map<uint32_t /*fourcc_format*/, uint64_t /*preferred_modifier*/> + preferred_format_modifier_; + base::WeakPtrFactory<HardwareDisplayController> weak_ptr_factory_{this}; DISALLOW_COPY_AND_ASSIGN(HardwareDisplayController);
diff --git a/ui/ozone/platform/drm/gpu/screen_manager.cc b/ui/ozone/platform/drm/gpu/screen_manager.cc index 4b1dcf99..559cc799 100644 --- a/ui/ozone/platform/drm/gpu/screen_manager.cc +++ b/ui/ozone/platform/drm/gpu/screen_manager.cc
@@ -37,7 +37,7 @@ bool FillModesetBuffer(const scoped_refptr<DrmDevice>& drm, HardwareDisplayController* controller, SkSurface* surface, - uint32_t fourcc_format) { + const std::vector<uint64_t>& modifiers) { DCHECK(!controller->crtc_controllers().empty()); CrtcController* first_crtc = controller->crtc_controllers()[0].get(); ScopedDrmCrtcPtr saved_crtc(drm->GetCrtc(first_crtc->crtc())); @@ -46,7 +46,6 @@ return false; } - const auto& modifiers = controller->GetFormatModifiers(fourcc_format); for (const uint64_t modifier : modifiers) { // A value of 0 means DRM_FORMAT_MOD_NONE. If the CRTC has any other // modifier (tiling, compression, etc.) we can't read the fb and assume it's @@ -94,13 +93,6 @@ return nullptr; } -std::vector<uint64_t> GetModifiersForPrimaryFormat( - HardwareDisplayController* controller) { - gfx::BufferFormat format = display::DisplaySnapshot::PrimaryFormat(); - uint32_t fourcc_format = ui::GetFourCCFormatForOpaqueFramebuffer(format); - return controller->GetFormatModifiersForModesetting(fourcc_format); -} - } // namespace ScreenManager::ScreenManager() = default; @@ -254,9 +246,16 @@ bool ScreenManager::TestModeset( const ControllerConfigsList& controllers_params) { - TRACE_EVENT1("drm", "ScreenManager::TestModeset", "display_count", - controllers_params.size()); + return TestAndSetPreferredModifiers(controllers_params) || + TestAndSetLinearModifier(controllers_params); +} +bool ScreenManager::TestAndSetPreferredModifiers( + const ControllerConfigsList& controllers_params) { + TRACE_EVENT1("drm", "ScreenManager::TestAndSetPreferredModifiers", + "display_count", controllers_params.size()); + + CrtcPreferredModifierMap crtcs_preferred_modifier; CommitRequest commit_request; auto drm = controllers_params[0].drm; @@ -266,9 +265,69 @@ HardwareDisplayController* controller = it->get(); if (params.mode) { + uint32_t fourcc_format = ui::GetFourCCFormatForOpaqueFramebuffer( + display::DisplaySnapshot::PrimaryFormat()); + std::vector<uint64_t> modifiers = + controller->GetFormatModifiersForTestModeset(fourcc_format); + DrmOverlayPlane primary_plane = GetModesetBuffer( controller, gfx::Rect(params.origin, ModeSize(*params.mode)), - GetModifiersForPrimaryFormat(controller), /*is_testing=*/true); + modifiers, /*is_testing=*/true); + if (!primary_plane.buffer) { + return false; + } + + crtcs_preferred_modifier[params.crtc] = std::make_pair( + modifiers.empty(), primary_plane.buffer->format_modifier()); + + GetModesetControllerProps(&commit_request, controller, params.origin, + *params.mode, primary_plane); + } else { + controller->GetDisableProps(&commit_request); + } + } + + if (!drm->plane_manager()->Commit( + std::move(commit_request), + DRM_MODE_ATOMIC_TEST_ONLY | DRM_MODE_ATOMIC_ALLOW_MODESET)) { + return false; + } + + SetPreferredModifiers(controllers_params, crtcs_preferred_modifier); + return true; +} + +bool ScreenManager::TestAndSetLinearModifier( + const ControllerConfigsList& controllers_params) { + TRACE_EVENT1("drm", "ScreenManager::TestAndSetLinearModifier", + "display_count", controllers_params.size()); + + CrtcPreferredModifierMap crtcs_preferred_modifier; + CommitRequest commit_request; + auto drm = controllers_params[0].drm; + + for (const auto& params : controllers_params) { + auto it = FindDisplayController(params.drm, params.crtc); + DCHECK(controllers_.end() != it); + HardwareDisplayController* controller = it->get(); + + uint32_t fourcc_format = ui::GetFourCCFormatForOpaqueFramebuffer( + display::DisplaySnapshot::PrimaryFormat()); + std::vector<uint64_t> modifiers = + controller->GetFormatModifiersForTestModeset(fourcc_format); + // Test with an empty list if no preferred modifiers are advertised. + // Platforms might not support gbm_bo_create_with_modifiers(). If the + // platform doesn't expose modifiers, do not attempt to explicitly request + // LINEAR otherwise we might CHECK() when trying to allocate buffers. + if (!modifiers.empty()) + modifiers = std::vector<uint64_t>{DRM_FORMAT_MOD_LINEAR}; + crtcs_preferred_modifier[params.crtc] = + std::make_pair(modifiers.empty(), DRM_FORMAT_MOD_LINEAR); + + if (params.mode) { + DrmOverlayPlane primary_plane = GetModesetBuffer( + controller, gfx::Rect(params.origin, ModeSize(*params.mode)), + modifiers, /*is_testing=*/true); if (!primary_plane.buffer) return false; @@ -279,9 +338,36 @@ } } - return drm->plane_manager()->Commit( - std::move(commit_request), - DRM_MODE_ATOMIC_TEST_ONLY | DRM_MODE_ATOMIC_ALLOW_MODESET); + if (!drm->plane_manager()->Commit( + std::move(commit_request), + DRM_MODE_ATOMIC_TEST_ONLY | DRM_MODE_ATOMIC_ALLOW_MODESET)) { + return false; + } + + SetPreferredModifiers(controllers_params, crtcs_preferred_modifier); + return true; +} + +void ScreenManager::SetPreferredModifiers( + const ControllerConfigsList& controllers_params, + const CrtcPreferredModifierMap& crtcs_preferred_modifier) { + for (const auto& params : controllers_params) { + if (params.mode) { + bool was_modifiers_list_empty = + crtcs_preferred_modifier.at(params.crtc).first; + // No preferred modifiers should be saved as some platforms might not have + // bo_create_with_modifiers implemented, this will send the preferred + // modifiers list as an empty list. + if (!was_modifiers_list_empty) { + uint64_t picked_modifier = + crtcs_preferred_modifier.at(params.crtc).second; + auto it = FindDisplayController(params.drm, params.crtc); + DCHECK(*it); + it->get()->UpdatePreferredModiferForFormat( + display::DisplaySnapshot::PrimaryFormat(), picked_modifier); + } + } + } } bool ScreenManager::Modeset(const ControllerConfigsList& controllers_params) { @@ -297,9 +383,13 @@ DCHECK(controllers_.end() != it); HardwareDisplayController* controller = it->get(); + uint32_t fourcc_format = GetFourCCFormatForOpaqueFramebuffer( + display::DisplaySnapshot::PrimaryFormat()); + std::vector<uint64_t> modifiers = + controller->GetSupportedModifiers(fourcc_format); DrmOverlayPlane primary_plane = GetModesetBuffer( controller, gfx::Rect(params.origin, ModeSize(*params.mode)), - GetModifiersForPrimaryFormat(controller), /*is_testing=*/false); + modifiers, /*is_testing=*/false); if (!primary_plane.buffer) return false; @@ -532,10 +622,14 @@ // otherwise the controller may be waiting for a page flip while the window // tries to schedule another buffer. if (should_enable) { + uint32_t fourcc_format = ui::GetFourCCFormatForOpaqueFramebuffer( + display::DisplaySnapshot::PrimaryFormat()); + std::vector<uint64_t> modifiers = + controller->GetSupportedModifiers(fourcc_format); DrmOverlayPlane primary_plane = GetModesetBuffer( controller, - gfx::Rect(controller->origin(), controller->GetModeSize()), - GetModifiersForPrimaryFormat(controller), /*is_testing=*/false); + gfx::Rect(controller->origin(), controller->GetModeSize()), modifiers, + /*is_testing=*/false); DCHECK(primary_plane.buffer); CommitRequest commit_request; @@ -588,8 +682,7 @@ sk_sp<SkSurface> surface = buffer->GetSurface(); if (!surface) { VLOG(2) << "Can't get a SkSurface from the modeset gbm buffer."; - } else if (!FillModesetBuffer(drm, controller, surface.get(), - buffer->GetFormat())) { + } else if (!FillModesetBuffer(drm, controller, surface.get(), modifiers)) { // If we fail to fill the modeset buffer, clear it black to avoid // displaying an uninitialized framebuffer. surface->getCanvas()->clear(SK_ColorBLACK);
diff --git a/ui/ozone/platform/drm/gpu/screen_manager.h b/ui/ozone/platform/drm/gpu/screen_manager.h index 0071937..d000d3b 100644 --- a/ui/ozone/platform/drm/gpu/screen_manager.h +++ b/ui/ozone/platform/drm/gpu/screen_manager.h
@@ -98,6 +98,9 @@ std::vector<std::unique_ptr<HardwareDisplayController>>; using WidgetToWindowMap = std::unordered_map<gfx::AcceleratedWidget, std::unique_ptr<DrmWindow>>; + using CrtcPreferredModifierMap = base::flat_map< + uint32_t /*crtc_is*/, + std::pair<bool /*modifiers_list.empty()*/, uint64_t /*picked_modifier*/>>; // Returns an iterator into |controllers_| for the controller identified by // (|crtc|, |connector|). @@ -106,6 +109,16 @@ uint32_t crtc); bool TestModeset(const ControllerConfigsList& controllers_params); + bool TestAndSetPreferredModifiers( + const ControllerConfigsList& controllers_params); + bool TestAndSetLinearModifier( + const ControllerConfigsList& controllers_params); + // Setting the Preferred modifiers that passed from one of the Modeset Test + // functions. The preferred modifiers are used in Modeset. + void SetPreferredModifiers( + const ControllerConfigsList& controllers_params, + const CrtcPreferredModifierMap& crtcs_preferred_modifier); + bool Modeset(const ControllerConfigsList& controllers_params); // Configures a display controller to be enabled. The display controller is
diff --git a/ui/views/window/frame_caption_button.cc b/ui/views/window/frame_caption_button.cc index 236a5e0..98fd03c 100644 --- a/ui/views/window/frame_caption_button.cc +++ b/ui/views/window/frame_caption_button.cc
@@ -22,7 +22,6 @@ #include "ui/views/animation/ink_drop_ripple.h" #include "ui/views/controls/focus_ring.h" #include "ui/views/controls/highlight_path_generator.h" -#include "ui/views/metadata/metadata_impl_macros.h" #include "ui/views/window/caption_button_layout_constants.h" #include "ui/views/window/hit_test_utils.h" @@ -58,13 +57,16 @@ gfx::Rect bounds = gfx::ToRoundedRect(rect); bounds.Inset(frame_caption_button_->GetInkdropInsets(bounds.size())); return gfx::RRectF(gfx::RectF(bounds), - frame_caption_button_->GetInkDropCornerRadius()); + frame_caption_button_->ink_drop_corner_radius()); } private: FrameCaptionButton* const frame_caption_button_; }; +// static +const char FrameCaptionButton::kViewClassName[] = "FrameCaptionButton"; + FrameCaptionButton::FrameCaptionButton(PressedCallback callback, CaptionButtonIcon icon, int hit_test_type) @@ -164,6 +166,10 @@ } } +const char* FrameCaptionButton::GetClassName() const { + return kViewClassName; +} + void FrameCaptionButton::OnGestureEvent(ui::GestureEvent* event) { // Button does not become pressed when the user drags off and then back // onto the button. Make FrameCaptionButton pressed in this case because this @@ -218,30 +224,6 @@ UpdateInkDropBaseColor(); } -SkColor FrameCaptionButton::GetBackgroundColor() const { - return background_color_; -} - -void FrameCaptionButton::SetPaintAsActive(bool paint_as_active) { - paint_as_active_ = paint_as_active; - OnPropertyChanged(&paint_as_active, kPropertyEffectsPaint); -} - -bool FrameCaptionButton::GetPaintAsActive() const { - return paint_as_active_; -} - -void FrameCaptionButton::SetInkDropCornerRadius(int ink_drop_corner_radius) { - ink_drop_corner_radius_ = ink_drop_corner_radius; - // Changes to |ink_drop_corner_radius| will affect the ink drop. Therefore - // this effect is handled by the ink drop. - OnPropertyChanged(&ink_drop_corner_radius_, kPropertyEffectsNone); -} - -int FrameCaptionButton::GetInkDropCornerRadius() const { - return ink_drop_corner_radius_; -} - void FrameCaptionButton::PaintButtonContents(gfx::Canvas* canvas) { constexpr SkAlpha kHighlightVisibleOpacity = 0x14; SkAlpha highlight_alpha = SK_AlphaTRANSPARENT; @@ -339,34 +321,4 @@ GetColorWithMaxContrast(GetColorWithMaxContrast(button_color))); } -DEFINE_ENUM_CONVERTERS( - views::CaptionButtonIcon, - {{views::CaptionButtonIcon::CAPTION_BUTTON_ICON_MINIMIZE, - base::ASCIIToUTF16("CAPTION_BUTTON_ICON_MINIMIZE")}, - {views::CaptionButtonIcon::CAPTION_BUTTON_ICON_MAXIMIZE_RESTORE, - base::ASCIIToUTF16("CAPTION_BUTTON_ICON_MAXIMIZE_RESTORE")}, - {views::CaptionButtonIcon::CAPTION_BUTTON_ICON_CLOSE, - base::ASCIIToUTF16("CAPTION_BUTTON_ICON_CLOSE")}, - {views::CaptionButtonIcon::CAPTION_BUTTON_ICON_LEFT_SNAPPED, - base::ASCIIToUTF16("CAPTION_BUTTON_ICON_LEFT_SNAPPED")}, - {views::CaptionButtonIcon::CAPTION_BUTTON_ICON_RIGHT_SNAPPED, - base::ASCIIToUTF16("CAPTION_BUTTON_ICON_RIGHT_SNAPPED")}, - {views::CaptionButtonIcon::CAPTION_BUTTON_ICON_BACK, - base::ASCIIToUTF16("CAPTION_BUTTON_ICON_BACK")}, - {views::CaptionButtonIcon::CAPTION_BUTTON_ICON_LOCATION, - base::ASCIIToUTF16("CAPTION_BUTTON_ICON_LOCATION")}, - {views::CaptionButtonIcon::CAPTION_BUTTON_ICON_MENU, - base::ASCIIToUTF16("CAPTION_BUTTON_ICON_MENU")}, - {views::CaptionButtonIcon::CAPTION_BUTTON_ICON_ZOOM, - base::ASCIIToUTF16("CAPTION_BUTTON_ICON_ZOOM")}, - {views::CaptionButtonIcon::CAPTION_BUTTON_ICON_COUNT, - base::ASCIIToUTF16("CAPTION_BUTTON_ICON_COUNT")}}) - -BEGIN_METADATA(FrameCaptionButton, Button) -ADD_PROPERTY_METADATA(SkColor, BackgroundColor) -ADD_PROPERTY_METADATA(bool, PaintAsActive) -ADD_PROPERTY_METADATA(int, InkDropCornerRadius) -ADD_READONLY_PROPERTY_METADATA(CaptionButtonIcon, Icon) -END_METADATA - } // namespace views
diff --git a/ui/views/window/frame_caption_button.h b/ui/views/window/frame_caption_button.h index e929d41..dd3733c 100644 --- a/ui/views/window/frame_caption_button.h +++ b/ui/views/window/frame_caption_button.h
@@ -11,7 +11,6 @@ #include "ui/gfx/image/image_skia.h" #include "ui/views/controls/button/button.h" #include "ui/views/controls/focus_ring.h" -#include "ui/views/metadata/metadata_header_macros.h" #include "ui/views/views_export.h" #include "ui/views/window/caption_button_types.h" @@ -26,14 +25,13 @@ // close). class VIEWS_EXPORT FrameCaptionButton : public views::Button { public: - METADATA_HEADER(FrameCaptionButton); enum Animate { ANIMATE_YES, ANIMATE_NO }; + static const char kViewClassName[]; + FrameCaptionButton(PressedCallback callback, CaptionButtonIcon icon, int hit_test_type); - FrameCaptionButton(const FrameCaptionButton&) = delete; - FrameCaptionButton& operator=(const FrameCaptionButton&) = delete; ~FrameCaptionButton() override; // Gets the color to use for a frame caption button. @@ -58,21 +56,26 @@ void SetAlpha(int alpha); // views::Button: + const char* GetClassName() const override; void OnGestureEvent(ui::GestureEvent* event) override; views::PaintInfo::ScaleType GetPaintScaleType() const override; std::unique_ptr<views::InkDrop> CreateInkDrop() override; std::unique_ptr<views::InkDropRipple> CreateInkDropRipple() const override; void SetBackgroundColor(SkColor background_color); - SkColor GetBackgroundColor() const; - void SetPaintAsActive(bool paint_as_active); - bool GetPaintAsActive() const; + void set_paint_as_active(bool paint_as_active) { + paint_as_active_ = paint_as_active; + } - void SetInkDropCornerRadius(int ink_drop_corner_radius); - int GetInkDropCornerRadius() const; + bool paint_as_active() const { return paint_as_active_; } - CaptionButtonIcon GetIcon() const { return icon_; } + void set_ink_drop_corner_radius(int ink_drop_corner_radius) { + ink_drop_corner_radius_ = ink_drop_corner_radius; + } + int ink_drop_corner_radius() const { return ink_drop_corner_radius_; } + + CaptionButtonIcon icon() const { return icon_; } const gfx::ImageSkia& icon_image() const { return icon_image_; } @@ -124,6 +127,8 @@ // Crossfade animation started when the button's images are changed by // SetImage(). std::unique_ptr<gfx::SlideAnimation> swap_images_animation_; + + DISALLOW_COPY_AND_ASSIGN(FrameCaptionButton); }; } // namespace views
diff --git a/ui/views/window/frame_caption_button_unittest.cc b/ui/views/window/frame_caption_button_unittest.cc index 85f5109..2c698f9 100644 --- a/ui/views/window/frame_caption_button_unittest.cc +++ b/ui/views/window/frame_caption_button_unittest.cc
@@ -8,7 +8,6 @@ #include "third_party/skia/include/core/SkColor.h" #include "ui/base/hit_test.h" #include "ui/gfx/color_utils.h" -#include "ui/views/test/view_metadata_test_utils.h" #include "ui/views/view.h" #include "ui/views/window/caption_button_types.h" @@ -39,10 +38,4 @@ EXPECT_EQ(View::FocusBehavior::ACCESSIBLE_ONLY, button.GetFocusBehavior()); } -TEST(FrameCaptionButtonTest, MetadataTest) { - FrameCaptionButton button(Button::PressedCallback(), - CAPTION_BUTTON_ICON_MINIMIZE, HTMINBUTTON); - test::TestViewMetadata(&button); -} - } // namespace views
diff --git a/ui/webui/resources/cr_components/chromeos/cellular_setup/esim_flow_ui.js b/ui/webui/resources/cr_components/chromeos/cellular_setup/esim_flow_ui.js index 03fa8c2..263f1bb 100644 --- a/ui/webui/resources/cr_components/chromeos/cellular_setup/esim_flow_ui.js +++ b/ui/webui/resources/cr_components/chromeos/cellular_setup/esim_flow_ui.js
@@ -295,6 +295,12 @@ /** @private */ onActivationCodeUpdated_(event) { + // initializePageState_() may cause this observer to fire and update the + // buttonState when we're not on the activation code page. Check we're on + // the activation code page before proceeding. + if (this.state_ !== ESimUiState.ACTIVATION_CODE_ENTRY) { + return; + } this.set( 'buttonState.forward', event.detail.activationCode ? cellularSetup.ButtonState.ENABLED : @@ -310,6 +316,12 @@ /** @private */ onConfirmationCodeUpdated_() { + // initializePageState_() may cause this observer to fire and update the + // buttonState when we're not on the confirmation code page. Check we're + // on the confirmation code page before proceeding. + if (this.state_ !== ESimUiState.CONFIRMATION_CODE_ENTRY) { + return; + } this.set( 'buttonState.forward', this.confirmationCode_ ? cellularSetup.ButtonState.ENABLED : @@ -351,6 +363,9 @@ .then(this.handleProfileInstallResponse_.bind(this)); } break; + case ESimUiState.SETUP_FINISH: + this.fire('exit-cellular-setup'); + break; default: assertNotReached(); break;
diff --git a/ui/webui/resources/cr_components/chromeos/cellular_setup/psim_flow_ui.js b/ui/webui/resources/cr_components/chromeos/cellular_setup/psim_flow_ui.js index 8d3cce36..5403593 100644 --- a/ui/webui/resources/cr_components/chromeos/cellular_setup/psim_flow_ui.js +++ b/ui/webui/resources/cr_components/chromeos/cellular_setup/psim_flow_ui.js
@@ -186,10 +186,21 @@ }, navigateForward() { - // Navigate forward is only called by clicking forward button - // from the provisioning page. - assert(this.selectedPSimPageName_ === PSimPageName.PROVISIONING); - this.state_ = PSimUIState.WAITING_FOR_ACTIVATION_TO_FINISH; + switch (this.state_) { + case PSimUIState.WAITING_FOR_PORTAL_TO_LOAD: + case PSimUIState.TIMEOUT_PORTAL_LOAD: + case PSimUIState.WAITING_FOR_USER_PAYMENT: + case PSimUIState.ACTIVATION_SUCCESS: + this.state_ = PSimUIState.WAITING_FOR_ACTIVATION_TO_FINISH; + break; + case PSimUIState.WAITING_FOR_ACTIVATION_TO_FINISH: + case PSimUIState.TIMEOUT_FINISH_ACTIVATION: + this.fire('exit-cellular-setup'); + break; + default: + assertNotReached(); + break; + } }, /**
diff --git a/weblayer/browser/java/org/chromium/weblayer_private/ChildProcessServiceImpl.java b/weblayer/browser/java/org/chromium/weblayer_private/ChildProcessServiceImpl.java index 21bd5a21..723c65e 100644 --- a/weblayer/browser/java/org/chromium/weblayer_private/ChildProcessServiceImpl.java +++ b/weblayer/browser/java/org/chromium/weblayer_private/ChildProcessServiceImpl.java
@@ -7,7 +7,6 @@ import android.app.Service; import android.content.Context; import android.content.Intent; -import android.content.pm.ApplicationInfo; import android.os.Build; import android.os.IBinder; import android.webkit.WebViewFactory; @@ -68,12 +67,12 @@ mService = ChildProcessServiceFactory.create(service, context); } - private static void setLibraryPreloader(String packageName, ClassLoader classLoader) { + public static void setLibraryPreloader(String webLayerPackageName, ClassLoader classLoader) { if (!LibraryLoader.getInstance().isLoadedByZygote()) { LibraryLoader.getInstance().setNativeLibraryPreloader(new NativeLibraryPreloader() { @Override - public int loadLibrary(ApplicationInfo info) { - return loadNativeLibrary(packageName, classLoader); + public int loadLibrary(String packageName) { + return loadNativeLibrary(webLayerPackageName, classLoader); } }); }
diff --git a/weblayer/shell/android/shell_apk/DEPS b/weblayer/shell/android/shell_apk/DEPS index 0257866..941c524 100644 --- a/weblayer/shell/android/shell_apk/DEPS +++ b/weblayer/shell/android/shell_apk/DEPS
@@ -1,6 +1,10 @@ noparent = True include_rules = [ - "+base/android/java", - "+components/strictmode/android/java", "+weblayer/public/java", + + # We want to depend on as little of //base and other internal code as + # possible, as it can be confusing since the ClassLoader of the client will be + # different from the implementation. Only simple utility classes are allowed. + "+base/android/java/src/org/chromium/base/IntentUtils.java", + "+base/android/java/src/org/chromium/base/compat/ApiHelperForR.java", ]
diff --git a/weblayer/shell/android/shell_apk/res/menu/app_menu.xml b/weblayer/shell/android/shell_apk/res/menu/app_menu.xml index 57a913a..daa9872 100644 --- a/weblayer/shell/android/shell_apk/res/menu/app_menu.xml +++ b/weblayer/shell/android/shell_apk/res/menu/app_menu.xml
@@ -18,6 +18,10 @@ android:title="Translate" /> <item android:id="@+id/clear_browsing_data_menu_id" android:title="Clear all browsing data" /> + <item android:id="@+id/enable_incognito_menu_id" + android:title="Restart with Incognito" /> + <item android:id="@+id/disable_incognito_menu_id" + android:title="Restart without Incognito" /> <item android:id="@+id/set_translate_target_lang_menu_id" android:title="Set translate target language to German" /> <item android:id="@+id/clear_translate_target_lang_menu_id"
diff --git a/weblayer/shell/android/shell_apk/src/org/chromium/weblayer/shell/WebLayerShellActivity.java b/weblayer/shell/android/shell_apk/src/org/chromium/weblayer/shell/WebLayerShellActivity.java index 93de487c..84265de3 100644 --- a/weblayer/shell/android/shell_apk/src/org/chromium/weblayer/shell/WebLayerShellActivity.java +++ b/weblayer/shell/android/shell_apk/src/org/chromium/weblayer/shell/WebLayerShellActivity.java
@@ -47,7 +47,6 @@ import androidx.fragment.app.FragmentManager; import androidx.fragment.app.FragmentTransaction; -import org.chromium.base.CommandLine; import org.chromium.base.IntentUtils; import org.chromium.base.compat.ApiHelperForR; import org.chromium.weblayer.Browser; @@ -92,6 +91,7 @@ } private static final String NON_INCOGNITO_PROFILE_NAME = "DefaultProfile"; + private static final String EXTRA_START_IN_INCOGNITO = "EXTRA_START_IN_INCOGNITO"; private static class ContextMenuCreator implements View.OnCreateContextMenuListener, MenuItem.OnMenuItemClickListener { @@ -263,6 +263,8 @@ super.onCreate(savedInstanceState); mSetDarkMode = AppCompatDelegate.getDefaultNightMode() == AppCompatDelegate.MODE_NIGHT_YES; + mInIncognitoMode = getIntent().getBooleanExtra(EXTRA_START_IN_INCOGNITO, false); + setContentView(R.layout.main); TextView versionText = (TextView) findViewById(R.id.version_text); versionText.setText(getString( @@ -307,6 +309,8 @@ popup.getMenu() .findItem(R.id.translate_menu_id) .setVisible(mBrowser.getActiveTab().canTranslate()); + popup.getMenu().findItem(R.id.enable_incognito_menu_id).setVisible(!mInIncognitoMode); + popup.getMenu().findItem(R.id.disable_incognito_menu_id).setVisible(mInIncognitoMode); boolean isDesktopUserAgent = mBrowser.getActiveTab().isDesktopUserAgentEnabled(); popup.getMenu().findItem(R.id.desktop_site_menu_id).setVisible(!isDesktopUserAgent); popup.getMenu().findItem(R.id.no_desktop_site_menu_id).setVisible(isDesktopUserAgent); @@ -357,6 +361,14 @@ }); } + if (item.getItemId() == R.id.enable_incognito_menu_id) { + restartShell(true); + } + + if (item.getItemId() == R.id.disable_incognito_menu_id) { + restartShell(false); + } + if (item.getItemId() == R.id.desktop_site_menu_id) { mBrowser.getActiveTab().setDesktopUserAgentEnabled(true); } @@ -719,11 +731,6 @@ } } - if (CommandLine.isInitialized() - && CommandLine.getInstance().hasSwitch("start-in-incognito")) { - mInIncognitoMode = true; - } - String profileName = mInIncognitoMode ? null : NON_INCOGNITO_PROFILE_NAME; Fragment fragment = WebLayer.createBrowserFragment(profileName); @@ -805,6 +812,18 @@ super.onBackPressed(); } + @SuppressWarnings("checkstyle:SystemExitCheck") // Allowed since this shouldn't be a crash. + private void restartShell(boolean enableIncognito) { + finish(); + + Intent intent = new Intent(); + intent.setClassName(getPackageName(), getClass().getName()); + intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); + intent.putExtra(EXTRA_START_IN_INCOGNITO, enableIncognito); + startActivity(intent); + System.exit(0); + } + private void updateFavicon(@NonNull Tab tab) { if (tab == mBrowser.getActiveTab()) { assert mTabToPerTabState.containsKey(tab);