diff --git a/.vpython b/.vpython index 890229f7..617cbc5b 100644 --- a/.vpython +++ b/.vpython
@@ -124,3 +124,19 @@ name: "infra/python/wheels/simplejson/${vpython_platform}" version: "version:3.13.2" > + +# Used by: +# content/test/gpu/gpu_tests/color_profile_manager_mac.py +wheel: < + name: "infra/python/wheels/pyobjc/${vpython_platform}" + version: "version:4.1" + match_tag: < platform: "macosx_10_10_intel" > +> +# TODO(crbug.com/804174): roll out support in vpython for +# "not_match_tag", then uncomment this. +# wheel: < +# name: "infra/python/wheels/pyobjc/${vpython_platform}" +# version: "version:2.5.1" +# match_tag: < platform: "macosx_10_6_intel" > +# not_match_tag: < platform: "macosx_10_10_intel" > +# >
diff --git a/DEPS b/DEPS index 365d45e..e283f5a 100644 --- a/DEPS +++ b/DEPS
@@ -49,10 +49,6 @@ # custom_vars. 'checkout_src_internal': False, - # By default, do not check out Google's internal dependencies. This can be - # overridden e.g. with custom_vars. - 'checkout_google_internal': False, - # Fetch the additional packages and files needed to run all of the # telemetry tests. This is false by default as some stuff is only # privately accessible. @@ -83,11 +79,11 @@ # 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': '2f5b8d81c231ef4acb4b5671c0956a249f0ef4cf', + 'skia_revision': '70204ab029b5d973ce8c2ae0f5b6ac4b69747335', # Three lines of non-changing comments so that # the commit queue can handle CLs rolling V8 # and whatever else without interference from each other. - 'v8_revision': 'bf50906e3ea90d3597ce792971c15bf717383ee0', + 'v8_revision': '70bfb9391d99af92b41db6ba25b0ae04e74ee258', # Three lines of non-changing comments so that # the commit queue can handle CLs rolling swarming_client # and whatever else without interference from each other. @@ -95,7 +91,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': '5dd4ad896bcb69b7e3747c1a17e6b07da63753e8', + 'angle_revision': '199f42941ab5a7afd4f6e548c1d6e6c3cb4ea71a', # Three lines of non-changing comments so that # the commit queue can handle CLs rolling build tools # and whatever else without interference from each other. @@ -107,7 +103,7 @@ # Three lines of non-changing comments so that # the commit queue can handle CLs rolling PDFium # and whatever else without interference from each other. - 'pdfium_revision': '95b232f791231a0db0de780b568a0825a2e6e989', + 'pdfium_revision': '2334660053e044ca79a1831a6c73f69891f039e0', # Three lines of non-changing comments so that # the commit queue can handle CLs rolling openmax_dl # and whatever else without interference from each other. @@ -131,7 +127,7 @@ # Three lines of non-changing comments so that # the commit queue can handle CLs rolling NaCl # and whatever else without interference from each other. - 'nacl_revision': '7f07816e463da403255f0ab4f6d88004450dd09d', + 'nacl_revision': '476698afdd0b114d72e6b4bde36691e5cc8b0bd6', # Three lines of non-changing comments so that # the commit queue can handle CLs rolling freetype # and whatever else without interference from each other. @@ -139,7 +135,7 @@ # Three lines of non-changing comments so that # the commit queue can handle CLs rolling catapult # and whatever else without interference from each other. - 'catapult_revision': '52dc3feb012cce1d690b12d0b137c6c9bd5a4ff1', + 'catapult_revision': '7c98d04db58b6d6b2f6116d27bb00250509dcaa0', # Three lines of non-changing comments so that # the commit queue can handle CLs rolling libFuzzer # and whatever else without interference from each other. @@ -251,11 +247,6 @@ 'condition': 'checkout_ios', }, - 'src/ios_internal': { - 'url': 'https://chrome-internal.googlesource.com/chrome/ios_internal.git' + '@' + '3fd2cebe6fc1ccd43675a23d492c323aa42e3b81', - 'condition': 'checkout_ios and checkout_google_internal', - }, - 'src/media/cdm/api': Var('chromium_git') + '/chromium/cdm.git' + '@' + 'ca7130aa8fe6dd6c0664b52768d1957af31ae91b', @@ -496,7 +487,7 @@ Var('chromium_git') + '/webm/libwebm.git' + '@' + 'b03c65468b06d097f27235d93d76bfc45f490ede', 'src/third_party/libyuv': - Var('chromium_git') + '/libyuv/libyuv.git' + '@' + '92e22cf5b66173d5d5056751ca62bc2254e4ff86', # from r1691 + Var('chromium_git') + '/libyuv/libyuv.git' + '@' + 'ffec313dbe58c6b97d4943387bda618dccbe4591', # from r1694 'src/third_party/lighttpd': { 'url': Var('chromium_git') + '/chromium/deps/lighttpd.git' + '@' + Var('lighttpd_revision'), @@ -658,7 +649,7 @@ Var('chromium_git') + '/external/khronosgroup/webgl.git' + '@' + 'd458ada06171a85af00367251a4ed55db7fe2018', 'src/third_party/webrtc': - Var('webrtc_git') + '/src.git' + '@' + 'f61b3ba65e3d868267ea141c88b59127163e4766', # commit position 21742 + Var('webrtc_git') + '/src.git' + '@' + '70294c8eab2f7bcc4678c3b597beda5ee504b47c', # commit position 21742 'src/third_party/xdg-utils': { 'url': Var('chromium_git') + '/chromium/deps/xdg-utils.git' + '@' + 'd80274d5869b17b8c9067a1022e4416ee7ed5e0d', @@ -1354,7 +1345,6 @@ 'action': [ 'python', 'src/build/fuchsia/update_sdk.py', - '893404234442cf13abbc4e22ed996839ff5b1338', ], }, @@ -1378,8 +1368,4 @@ ("src/third_party/angle", "DEPS.chromium"), # src-internal has its own DEPS file to pull additional internal repos 'src-internal', - # src/ios_internal has its own DEPS file (named DEPS.chromium until the - # transition to gclient conditions is complete, see http://crbug.com/803846 - # for progress). - ('src/ios_internal', 'DEPS.chromium'), ]
diff --git a/PRESUBMIT.py b/PRESUBMIT.py index f94cd5b..7b5d6d81 100644 --- a/PRESUBMIT.py +++ b/PRESUBMIT.py
@@ -532,8 +532,8 @@ # Bypass the AUTHORS check for these accounts. _KNOWN_ROBOTS = set( '%s-chromium-autoroll@skia-buildbots.google.com.iam.gserviceaccount.com' % s - for s in ('angle', 'depot-tools', 'nacl', 'pdfium', 'skia', 'src-internal', - 'webrtc')) + for s in ('angle', 'catapult', 'depot-tools', 'nacl', 'pdfium', 'skia', + 'src-internal', 'webrtc')) def _CheckNoProductionCodeUsingTestOnlyFunctions(input_api, output_api):
diff --git a/android_webview/BUILD.gn b/android_webview/BUILD.gn index 54f07e4c..d42b7a6 100644 --- a/android_webview/BUILD.gn +++ b/android_webview/BUILD.gn
@@ -688,6 +688,7 @@ "//components/cdm/renderer", "//components/crash/content/app", "//components/crash/content/browser", + "//components/download/public/common:public", "//components/google/core/browser", "//components/keyed_service/content", "//components/metrics",
diff --git a/android_webview/browser/DEPS b/android_webview/browser/DEPS index 1cce4b6a..b107137 100644 --- a/android_webview/browser/DEPS +++ b/android_webview/browser/DEPS
@@ -16,6 +16,7 @@ "+components/cdm/browser", "+components/crash/content/browser", "+components/crash/core", + "+components/download/public/common", "+components/navigation_interception", "+components/policy/core/browser", "+components/policy/core/common",
diff --git a/android_webview/browser/aw_browser_policy_connector.cc b/android_webview/browser/aw_browser_policy_connector.cc index df0be7ea..523da4a 100644 --- a/android_webview/browser/aw_browser_policy_connector.cc +++ b/android_webview/browser/aw_browser_policy_connector.cc
@@ -62,14 +62,17 @@ } // namespace AwBrowserPolicyConnector::AwBrowserPolicyConnector() - : BrowserPolicyConnectorBase(base::Bind(&BuildHandlerList)) { + : BrowserPolicyConnectorBase(base::Bind(&BuildHandlerList)) {} + +AwBrowserPolicyConnector::~AwBrowserPolicyConnector() = default; + +std::vector<std::unique_ptr<policy::ConfigurationPolicyProvider>> +AwBrowserPolicyConnector::CreatePolicyProviders() { std::vector<std::unique_ptr<policy::ConfigurationPolicyProvider>> providers; providers.push_back( std::make_unique<policy::android::AndroidCombinedPolicyProvider>( GetSchemaRegistry())); - SetPolicyProviders(std::move(providers)); + return providers; } -AwBrowserPolicyConnector::~AwBrowserPolicyConnector() {} - } // namespace android_webview
diff --git a/android_webview/browser/aw_browser_policy_connector.h b/android_webview/browser/aw_browser_policy_connector.h index 4530657c..65b2cce5 100644 --- a/android_webview/browser/aw_browser_policy_connector.h +++ b/android_webview/browser/aw_browser_policy_connector.h
@@ -13,12 +13,17 @@ // Sets up and keeps the browser-global policy objects such as the PolicyService // and the platform-specific PolicyProvider. class AwBrowserPolicyConnector : public policy::BrowserPolicyConnectorBase { -public: - AwBrowserPolicyConnector(); - ~AwBrowserPolicyConnector() override; + public: + AwBrowserPolicyConnector(); + ~AwBrowserPolicyConnector() override; -private: - DISALLOW_COPY_AND_ASSIGN(AwBrowserPolicyConnector); + protected: + // policy::BrowserPolicyConnectorBase: + std::vector<std::unique_ptr<policy::ConfigurationPolicyProvider>> + CreatePolicyProviders() override; + + private: + DISALLOW_COPY_AND_ASSIGN(AwBrowserPolicyConnector); }; } // namespace android_webview
diff --git a/android_webview/browser/aw_download_manager_delegate.cc b/android_webview/browser/aw_download_manager_delegate.cc index b455bcaf..cf3718b4 100644 --- a/android_webview/browser/aw_download_manager_delegate.cc +++ b/android_webview/browser/aw_download_manager_delegate.cc
@@ -5,7 +5,7 @@ #include "android_webview/browser/aw_download_manager_delegate.h" #include "base/files/file_path.h" -#include "content/public/browser/download_danger_type.h" +#include "components/download/public/common/download_danger_type.h" #include "content/public/browser/download_item.h" namespace android_webview { @@ -20,7 +20,7 @@ // could have already finished by the time DownloadStarting is called. callback.Run(base::FilePath() /* Empty file path for cancel */, content::DownloadItem::TARGET_DISPOSITION_OVERWRITE, - content::DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS, base::FilePath(), + download::DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS, base::FilePath(), content::DOWNLOAD_INTERRUPT_REASON_USER_CANCELED); return true; }
diff --git a/android_webview/javatests/src/org/chromium/android_webview/test/AndroidScrollIntegrationTest.java b/android_webview/javatests/src/org/chromium/android_webview/test/AndroidScrollIntegrationTest.java index 2619b57..3fda1a2 100644 --- a/android_webview/javatests/src/org/chromium/android_webview/test/AndroidScrollIntegrationTest.java +++ b/android_webview/javatests/src/org/chromium/android_webview/test/AndroidScrollIntegrationTest.java
@@ -324,6 +324,13 @@ final int targetScrollYPix = (int) Math.ceil(targetScrollYCss * deviceDIPScale); final JavascriptEventObserver onscrollObserver = new JavascriptEventObserver(); + double expectedScrollXCss = targetScrollXCss; + double expectedScrollYCss = targetScrollYCss; + if (UseZoomForDSFPolicy.isUseZoomForDSFEnabled()) { + expectedScrollXCss = (double) targetScrollXPix / deviceDIPScale; + expectedScrollYCss = (double) targetScrollYPix / deviceDIPScale; + } + InstrumentationRegistry.getInstrumentation().runOnMainSync(() -> onscrollObserver.register(testContainerView.getWebContents(), "onscrollObserver")); @@ -332,8 +339,8 @@ scrollToOnMainSync(testContainerView, targetScrollXPix, targetScrollYPix); onscrollObserver.waitForEvent(WAIT_TIMEOUT_MS); - assertScrollInJs(testContainerView.getAwContents(), contentsClient, - targetScrollXCss, targetScrollYCss); + assertScrollInJs(testContainerView.getAwContents(), contentsClient, expectedScrollXCss, + expectedScrollYCss); } @Test
diff --git a/android_webview/test/BUILD.gn b/android_webview/test/BUILD.gn index 10ff6a15..e360a62 100644 --- a/android_webview/test/BUILD.gn +++ b/android_webview/test/BUILD.gn
@@ -39,7 +39,6 @@ "shell/src/org/chromium/android_webview/shell/AwShellResourceProvider.java", "shell/src/org/chromium/android_webview/shell/AwShellSwitches.java", "shell/src/org/chromium/android_webview/shell/DrawGL.java", - "shell/src/org/chromium/android_webview/test/AwInstrumentationTestRunner.java", "shell/src/org/chromium/android_webview/test/AwTestContainerView.java", "shell/src/org/chromium/android_webview/test/AwTestRunnerActivity.java", "shell/src/org/chromium/android_webview/test/AwJUnit4ClassRunner.java",
diff --git a/android_webview/test/shell/src/org/chromium/android_webview/test/AwInstrumentationTestRunner.java b/android_webview/test/shell/src/org/chromium/android_webview/test/AwInstrumentationTestRunner.java deleted file mode 100644 index 74272a54..0000000 --- a/android_webview/test/shell/src/org/chromium/android_webview/test/AwInstrumentationTestRunner.java +++ /dev/null
@@ -1,22 +0,0 @@ -// Copyright 2015 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 org.chromium.android_webview.test; - -import org.chromium.base.test.BaseChromiumInstrumentationTestRunner; -import org.chromium.base.test.BaseTestResult; -import org.chromium.policy.test.annotations.Policies; - -/** - * Instrumentation test runner that allows integrating features defined above base layer - * for webview testing. - */ -public class AwInstrumentationTestRunner extends BaseChromiumInstrumentationTestRunner { - @Override - protected void addTestHooks(BaseTestResult result) { - super.addTestHooks(result); - - result.addPreTestHook(Policies.getRegistrationHook()); - } -}
diff --git a/ash/BUILD.gn b/ash/BUILD.gn index 8556e01..87c3a9d 100644 --- a/ash/BUILD.gn +++ b/ash/BUILD.gn
@@ -1125,11 +1125,6 @@ "//ash/touch_hud/mus:touch_hud", ] - # TODO(jamescook): Move to ash_unittests? - data = [ - "display/test_data/", - ] - # Usage of content should be in ash_content_unittests. assert_no_deps = [ "//content/public/browser", @@ -1642,6 +1637,11 @@ "//testing/buildbot/filters:ash_unittests_filters", ] + data = [ + # See DisplayColorManagerTest. + "display/test_data/", + ] + # Usage of content should be in ash_with_content. assert_no_deps = [ "//content/public/browser", @@ -1814,10 +1814,6 @@ "test/ash_test_suite.h", "test/ash_test_views_delegate.cc", "test/ash_test_views_delegate.h", - - # TODO(jamescook): Rename to TestChildModalWindow and move to //ash/wm - "test/child_modal_window.cc", - "test/child_modal_window.h", "test/ui_controls_factory_ash.cc", "test/ui_controls_factory_ash.h", "test_media_client.cc", @@ -1836,6 +1832,8 @@ "wm/lock_state_controller_test_api.h", "wm/test_activation_delegate.cc", "wm/test_activation_delegate.h", + "wm/test_child_modal_parent.cc", + "wm/test_child_modal_parent.h", "wm/test_overlay_delegate.cc", "wm/test_overlay_delegate.h", "wm/test_session_state_animator.cc",
diff --git a/ash/ash_strings.grd b/ash/ash_strings.grd index 45acfba..f6c4fc3 100644 --- a/ash/ash_strings.grd +++ b/ash/ash_strings.grd
@@ -432,11 +432,11 @@ <message name="IDS_ASH_USER_IS_SUPERVISED_BY_NOTICE" desc="Text for notifications showing that this user is supervised"> Usage and history of this user can be reviewed by the manager (<ph name="MANAGER_EMAIL">$1<ex>user@example.com</ex></ph>) on chrome.com. </message> - <message name="IDS_ASH_CHILD_USER_IS_MANAGED_BY_ONE_PARENT_NOTICE" desc="Text for notifications showing that this child user is managed by parent's account."> - This is an account for kids managed by <ph name="MANAGER_EMAIL">$1<ex>user@example.com</ex></ph> + <message name="IDS_ASH_CHILD_USER_IS_MANAGED_BY_ONE_PARENT_NOTICE" desc="Text for notifications showing that this user is managed by parent's account."> + Account managed by <ph name="MANAGER_EMAIL">$1<ex>user@example.com</ex></ph> </message> - <message name="IDS_ASH_CHILD_USER_IS_MANAGED_BY_TWO_PARENTS_NOTICE" desc="Text for notifications showing that this child user is managed by two parents' accounts."> - This is an account for kids managed by <ph name="FIRST_PARENT_EMAIL">$1<ex>first@example.com</ex></ph> and <ph name="SECOND_PARENT_EMAIL">$2<ex>second@example.com</ex></ph> + <message name="IDS_ASH_CHILD_USER_IS_MANAGED_BY_TWO_PARENTS_NOTICE" desc="Text for notifications showing that this user is managed by two parents' accounts."> + Account managed by <ph name="FIRST_PARENT_EMAIL">$1<ex>first@example.com</ex></ph> and <ph name="SECOND_PARENT_EMAIL">$2<ex>second@example.com</ex></ph> </message> <message name="IDS_ASH_STATUS_TRAY_PREVIOUS_MENU" desc="The accessible text for header entries for detailed versions of status tray items.">
diff --git a/ash/dip_unittest.cc b/ash/dip_unittest.cc index 9b100bf..29bec09e 100644 --- a/ash/dip_unittest.cc +++ b/ash/dip_unittest.cc
@@ -20,10 +20,6 @@ #include "ui/display/screen.h" #include "ui/gfx/geometry/insets.h" #include "ui/views/widget/widget.h" -#include "ui/wm/core/shadow.h" -#include "ui/wm/core/shadow_controller.h" -#include "ui/wm/core/shadow_types.h" -#include "ui/wm/public/activation_client.h" namespace ash {
diff --git a/ash/display/mirror_window_controller.cc b/ash/display/mirror_window_controller.cc index 69836a7..41fe194c 100644 --- a/ash/display/mirror_window_controller.cc +++ b/ash/display/mirror_window_controller.cc
@@ -305,15 +305,15 @@ } void MirrorWindowController::Close(bool delay_host_deletion) { - for (auto& info : mirroring_host_info_map_) - CloseAndDeleteHost(info.second, delay_host_deletion); - - mirroring_host_info_map_.clear(); if (reflector_) { aura::Env::GetInstance()->context_factory_private()->RemoveReflector( reflector_.get()); reflector_.reset(); } + + for (auto& info : mirroring_host_info_map_) + CloseAndDeleteHost(info.second, delay_host_deletion); + mirroring_host_info_map_.clear(); } void MirrorWindowController::OnHostResized(aura::WindowTreeHost* host) {
diff --git a/ash/frame/caption_buttons/frame_caption_button_container_view.cc b/ash/frame/caption_buttons/frame_caption_button_container_view.cc index 7f21aaf3..269e4fc 100644 --- a/ash/frame/caption_buttons/frame_caption_button_container_view.cc +++ b/ash/frame/caption_buttons/frame_caption_button_container_view.cc
@@ -31,20 +31,21 @@ namespace { -// Duration of the animation of the position of |minimize_button_|. +// Duration of the animation of the position of buttons to the left of +// |size_button_|. const int kPositionAnimationDurationMs = 500; // Duration of the animation of the alpha of |size_button_|. const int kAlphaAnimationDurationMs = 250; // Delay during |tablet_mode_animation_| hide to wait before beginning to -// animate the position of |minimize_button_|. +// animate the position of buttons to the left of |size_button_|. const int kHidePositionDelayMs = 100; // Duration of |tablet_mode_animation_| hiding. // Hiding size button 250 // |------------------------| -// Delay 100 Slide minimize button 500 +// Delay 100 Slide other buttons 500 // |---------|-------------------------------------------------| const int kHideAnimationDurationMs = kHidePositionDelayMs + kPositionAnimationDurationMs; @@ -54,7 +55,7 @@ const int kShowAnimationAlphaDelayMs = 100; // Duration of |tablet_mode_animation_| showing. -// Slide minimize button 500 +// Slide other buttons 500 // |-------------------------------------------------| // Delay 100 Show size button 250 // |---------|-----------------------| @@ -82,7 +83,7 @@ } // Value of |tablet_mode_animation_| hiding to begin animating the position of -// |minimize_button_|. +// buttons to the left of |size_button_|. float HidePositionStartValue() { return 1.0f - static_cast<float>(kHidePositionDelayMs) / kHideAnimationDurationMs; @@ -221,7 +222,7 @@ views::View::Layout(); // This ensures that the first frame of the animation to show the size button - // pushes the minimize button into the center. + // pushes the buttons to the left of the size button into the center. if (tablet_mode_animation_->is_animating()) AnimationProgressed(tablet_mode_animation_.get()); } @@ -250,19 +251,19 @@ const gfx::Animation* animation) { double current_value = animation->GetCurrentValue(); int size_alpha = 0; - int minimize_x = 0; + int x_slide = 0; if (tablet_mode_animation_->IsShowing()) { - double scaled_value = + double scaled_value_alpha = CapAnimationValue((current_value - SizeButtonShowStartValue()) / SizeButtonShowDuration()); double tweened_value_alpha = - gfx::Tween::CalculateValue(gfx::Tween::EASE_OUT, scaled_value); + gfx::Tween::CalculateValue(gfx::Tween::EASE_OUT, scaled_value_alpha); size_alpha = gfx::Tween::LinearIntValueBetween(tweened_value_alpha, 0, 255); double tweened_value_slide = gfx::Tween::CalculateValue(gfx::Tween::EASE_OUT, current_value); - minimize_x = gfx::Tween::LinearIntValueBetween(tweened_value_slide, - size_button_->x(), 0); + x_slide = gfx::Tween::LinearIntValueBetween(tweened_value_slide, + size_button_->width(), 0); } else { double scaled_value_alpha = CapAnimationValue((1.0f - current_value) / SizeButtonHideDuration()); @@ -272,13 +273,21 @@ double scaled_value_position = CapAnimationValue( (HidePositionStartValue() - current_value) / HidePositionStartValue()); - double tweened_value_position = + double tweened_value_slide = gfx::Tween::CalculateValue(gfx::Tween::EASE_OUT, scaled_value_position); - minimize_x = gfx::Tween::LinearIntValueBetween(tweened_value_position, 0, - size_button_->x()); + x_slide = gfx::Tween::LinearIntValueBetween(tweened_value_slide, 0, + size_button_->width()); } size_button_->SetAlpha(size_alpha); - minimize_button_->SetX(minimize_x); + + // Slide all buttons to the left of the size button. Usually this is just the + // minimize button but it can also include a PWA menu button. + int previous_x = 0; + for (int i = 0; i < child_count() && child_at(i) != size_button_; ++i) { + views::View* button = child_at(i); + button->SetX(previous_x + x_slide); + previous_x += button->width(); + } } void FrameCaptionButtonContainerView::SetButtonIcon(FrameCaptionButton* button,
diff --git a/ash/frame/caption_buttons/frame_caption_button_container_view.h b/ash/frame/caption_buttons/frame_caption_button_container_view.h index 86e184f9..f531e1b5 100644 --- a/ash/frame/caption_buttons/frame_caption_button_container_view.h +++ b/ash/frame/caption_buttons/frame_caption_button_container_view.h
@@ -146,8 +146,9 @@ // CaptionButtonIcon. std::map<CaptionButtonIcon, const gfx::VectorIcon*> button_icon_map_; - // Animation that affects the position of |minimize_button_| and the - // visibility of |size_button_|. + // Animation that affects the visibility of |size_button_| and the position of + // buttons to the left of it. Usually this is just the minimize button but it + // can also include a PWA menu button. std::unique_ptr<gfx::SlideAnimation> tablet_mode_animation_; DISALLOW_COPY_AND_ASSIGN(FrameCaptionButtonContainerView);
diff --git a/ash/frame/caption_buttons/frame_caption_button_container_view_unittest.cc b/ash/frame/caption_buttons/frame_caption_button_container_view_unittest.cc index fc3878ac..0d9c594 100644 --- a/ash/frame/caption_buttons/frame_caption_button_container_view_unittest.cc +++ b/ash/frame/caption_buttons/frame_caption_button_container_view_unittest.cc
@@ -148,15 +148,26 @@ TestUpdateSizeButtonVisibilityAnimation) { FrameCaptionButtonContainerView container( CreateTestWidget(MAXIMIZE_ALLOWED, MINIMIZE_ALLOWED)); + + // Add an extra button to the left of the size button to verify that it is + // repositioned similarly to the minimize button. This simulates the PWA menu + // button being added to the left of the minimize button. + FrameCaptionButton* extra_button = + new FrameCaptionButton(&container, CAPTION_BUTTON_ICON_BACK); + container.AddChildViewAt(extra_button, 0); + InitContainer(&container); container.Layout(); FrameCaptionButtonContainerView::TestApi test(&container); + gfx::Rect initial_extra_button_bounds = extra_button->bounds(); gfx::Rect initial_minimize_button_bounds = test.minimize_button()->bounds(); gfx::Rect initial_size_button_bounds = test.size_button()->bounds(); gfx::Rect initial_close_button_bounds = test.close_button()->bounds(); gfx::Rect initial_container_bounds = container.bounds(); + ASSERT_EQ(initial_minimize_button_bounds.x(), + initial_extra_button_bounds.right()); ASSERT_EQ(initial_size_button_bounds.x(), initial_minimize_button_bounds.right()); ASSERT_EQ(initial_close_button_bounds.x(), @@ -173,8 +184,10 @@ EXPECT_TRUE(test.minimize_button()->visible()); EXPECT_FALSE(test.size_button()->visible()); EXPECT_TRUE(test.close_button()->visible()); + gfx::Rect extra_button_bounds = extra_button->bounds(); gfx::Rect minimize_button_bounds = test.minimize_button()->bounds(); gfx::Rect close_button_bounds = test.close_button()->bounds(); + EXPECT_EQ(minimize_button_bounds.x(), extra_button_bounds.right()); EXPECT_EQ(close_button_bounds.x(), minimize_button_bounds.right()); EXPECT_EQ(initial_size_button_bounds, test.size_button()->bounds()); EXPECT_EQ(initial_close_button_bounds.size(), close_button_bounds.size()); @@ -191,6 +204,7 @@ EXPECT_TRUE(test.minimize_button()->visible()); EXPECT_TRUE(test.size_button()->visible()); EXPECT_TRUE(test.close_button()->visible()); + EXPECT_EQ(initial_extra_button_bounds, extra_button->bounds()); EXPECT_EQ(initial_minimize_button_bounds, test.minimize_button()->bounds()); EXPECT_EQ(initial_size_button_bounds, test.size_button()->bounds()); EXPECT_EQ(initial_close_button_bounds, test.close_button()->bounds());
diff --git a/ash/frame/custom_frame_view_ash.cc b/ash/frame/custom_frame_view_ash.cc index dd09771..2b3de8ff 100644 --- a/ash/frame/custom_frame_view_ash.cc +++ b/ash/frame/custom_frame_view_ash.cc
@@ -89,7 +89,8 @@ if (window_state_->IsFullscreen()) return; - if (Shell::Get()->tablet_mode_controller()->ShouldAutoHideTitlebars()) { + if (Shell::Get()->tablet_mode_controller()->ShouldAutoHideTitlebars( + nullptr)) { immersive_fullscreen_controller_->SetEnabled( ImmersiveFullscreenController::WINDOW_TYPE_OTHER, true); } @@ -131,7 +132,8 @@ void OnPostWindowStateTypeChange(wm::WindowState* window_state, mojom::WindowStateType old_type) override { if (Shell::Get()->tablet_mode_controller() && - Shell::Get()->tablet_mode_controller()->ShouldAutoHideTitlebars()) { + Shell::Get()->tablet_mode_controller()->ShouldAutoHideTitlebars( + nullptr)) { DCHECK(immersive_fullscreen_controller_); if (window_state->IsMinimized() && immersive_fullscreen_controller_->IsEnabled()) { @@ -549,8 +551,7 @@ const bool should_hide_titlebar_in_tablet_mode = Shell::Get()->tablet_mode_controller() && - Shell::Get()->tablet_mode_controller()->ShouldAutoHideTitlebars() && - frame_->IsMaximized(); + Shell::Get()->tablet_mode_controller()->ShouldAutoHideTitlebars(frame_); if (should_hide_titlebar_in_tablet_mode) return 0;
diff --git a/ash/frame/custom_frame_view_ash_unittest.cc b/ash/frame/custom_frame_view_ash_unittest.cc index c6e6db28..20c7aba 100644 --- a/ash/frame/custom_frame_view_ash_unittest.cc +++ b/ash/frame/custom_frame_view_ash_unittest.cc
@@ -364,12 +364,15 @@ auto* delegate2 = new CustomFrameTestWidgetDelegate(); auto widget2 = create_widget(delegate2); + Shell::Get()->tablet_mode_controller()->EnableTabletModeWindowManager(true); + // Verify that when one window is snapped, the header is drawn for the snapped // window, but not drawn for the window still in overview. Shell::Get()->window_selector_controller()->ToggleOverview(); Shell::Get()->split_view_controller()->SnapWindow(widget1->GetNativeWindow(), SplitViewController::LEFT); EXPECT_TRUE(delegate1->header_view()->should_paint()); + EXPECT_EQ(0, delegate1->GetCustomFrameViewTopBorderHeight()); EXPECT_FALSE(delegate2->header_view()->should_paint()); // Verify that when both windows are snapped, the header is drawn for both. @@ -377,6 +380,8 @@ SplitViewController::RIGHT); EXPECT_TRUE(delegate1->header_view()->should_paint()); EXPECT_TRUE(delegate2->header_view()->should_paint()); + EXPECT_EQ(0, delegate1->GetCustomFrameViewTopBorderHeight()); + EXPECT_EQ(0, delegate2->GetCustomFrameViewTopBorderHeight()); // Toggle overview mode so we return back to left snapped mode. Verify that // the header is again drawn for the snapped window, but not for the unsnapped @@ -385,6 +390,7 @@ ASSERT_EQ(SplitViewController::LEFT_SNAPPED, Shell::Get()->split_view_controller()->state()); EXPECT_TRUE(delegate1->header_view()->should_paint()); + EXPECT_EQ(0, delegate1->GetCustomFrameViewTopBorderHeight()); EXPECT_FALSE(delegate2->header_view()->should_paint()); Shell::Get()->split_view_controller()->EndSplitView();
diff --git a/ash/frame/header_view.cc b/ash/frame/header_view.cc index 4746309f..c12340f 100644 --- a/ash/frame/header_view.cc +++ b/ash/frame/header_view.cc
@@ -52,8 +52,8 @@ int HeaderView::GetPreferredOnScreenHeight() { const bool should_hide_titlebar_in_tablet_mode = Shell::Get()->tablet_mode_controller() && - Shell::Get()->tablet_mode_controller()->ShouldAutoHideTitlebars() && - target_widget_->IsMaximized(); + Shell::Get()->tablet_mode_controller()->ShouldAutoHideTitlebars( + target_widget_); if (is_immersive_delegate_ && (target_widget_->IsFullscreen() || should_hide_titlebar_in_tablet_mode)) { @@ -162,8 +162,10 @@ void HeaderView::OnTabletModeStarted() { caption_button_container_->UpdateSizeButtonVisibility(); parent()->Layout(); - if (Shell::Get()->tablet_mode_controller()->ShouldAutoHideTitlebars()) + if (Shell::Get()->tablet_mode_controller()->ShouldAutoHideTitlebars( + nullptr)) { target_widget_->non_client_view()->Layout(); + } } void HeaderView::OnTabletModeEnded() {
diff --git a/ash/login/ui/lock_debug_view.cc b/ash/login/ui/lock_debug_view.cc index 4d692f7..bfa2bbf 100644 --- a/ash/login/ui/lock_debug_view.cc +++ b/ash/login/ui/lock_debug_view.cc
@@ -288,7 +288,11 @@ RebuildDebugUserColumn(); } -LockDebugView::~LockDebugView() = default; +LockDebugView::~LockDebugView() { + // Make sure debug_data_dispatcher_ lives longer than LockContentsView so + // pointer debug_dispatcher_ is always valid for LockContentsView. + RemoveChildView(lock_); +} void LockDebugView::Layout() { views::View::Layout();
diff --git a/ash/login/ui/login_button.h b/ash/login/ui/login_button.h index cc6b8cd..1db18b4d 100644 --- a/ash/login/ui/login_button.h +++ b/ash/login/ui/login_button.h
@@ -24,9 +24,10 @@ std::unique_ptr<views::InkDropHighlight> CreateInkDropHighlight() const override; - private: - int GetInkDropRadius() const; + protected: + virtual int GetInkDropRadius() const; + private: DISALLOW_COPY_AND_ASSIGN(LoginButton); };
diff --git a/ash/login/ui/login_pin_view.cc b/ash/login/ui/login_pin_view.cc index 3e776b1..f490cfd 100644 --- a/ash/login/ui/login_pin_view.cc +++ b/ash/login/ui/login_pin_view.cc
@@ -44,9 +44,12 @@ // How long does the user have to long-press the backspace button before it // auto-submits? -const int kInitialBackspaceDelayMs = 500; +constexpr int kInitialBackspaceDelayMs = 500; // After the first auto-submit, how long until the next backspace event fires? -const int kRepeatingBackspaceDelayMs = 150; +constexpr int kRepeatingBackspaceDelayMs = 150; + +// Size of the md-ripple when a PIN button is tapped. +constexpr int kRippleSizeDp = 54; base::string16 GetButtonLabelForNumber(int value) { DCHECK(value >= 0 && value < int{arraysize(kPinLabels)}); @@ -87,6 +90,9 @@ ~BasePinButton() override = default; + // LoginButton: + int GetInkDropRadius() const override { return kRippleSizeDp / 2; } + // views::ButtonListener: void ButtonPressed(Button* sender, const ui::Event& event) override { DCHECK(sender == this); @@ -142,9 +148,7 @@ } // namespace // static -const int LoginPinView::kButtonSeparatorSizeDp = 30; -// static -const int LoginPinView::kButtonSizeDp = 48; +const int LoginPinView::kButtonSizeDp = 78; // A PIN button that displays backspace icon. class LoginPinView::BackspacePinButton : public BasePinButton { @@ -255,14 +259,14 @@ // Builds and returns a new view which contains a row of the PIN keyboard. auto build_and_add_row = [this]() { auto* row = new NonAccessibleView(); - row->SetLayoutManager(std::make_unique<views::BoxLayout>( - views::BoxLayout::kHorizontal, gfx::Insets(), kButtonSeparatorSizeDp)); + row->SetLayoutManager( + std::make_unique<views::BoxLayout>(views::BoxLayout::kHorizontal)); AddChildView(row); return row; }; - SetLayoutManager(std::make_unique<views::BoxLayout>( - views::BoxLayout::kVertical, gfx::Insets(), kButtonSeparatorSizeDp)); + SetLayoutManager( + std::make_unique<views::BoxLayout>(views::BoxLayout::kVertical)); // 1-2-3 auto* row = build_and_add_row();
diff --git a/ash/login/ui/login_pin_view.h b/ash/login/ui/login_pin_view.h index 6e6719b5..d6ca552 100644 --- a/ash/login/ui/login_pin_view.h +++ b/ash/login/ui/login_pin_view.h
@@ -45,8 +45,6 @@ // class ASH_EXPORT LoginPinView : public NonAccessibleView { public: - // Spacing between each pin button. - static const int kButtonSeparatorSizeDp; // Size of each button. static const int kButtonSizeDp;
diff --git a/ash/login/ui/login_pin_view_unittest.cc b/ash/login/ui/login_pin_view_unittest.cc index 2b0f03d..a20eaca 100644 --- a/ash/login/ui/login_pin_view_unittest.cc +++ b/ash/login/ui/login_pin_view_unittest.cc
@@ -107,18 +107,12 @@ // Validate each x or y coordinate has the correct distance between it and the // next one. This is correct because we have already validated button size. EXPECT_EQ(3u, sorted_x.size()); - for (size_t i = 0; i < sorted_x.size() - 1; ++i) { - EXPECT_EQ(sorted_x[i] + LoginPinView::kButtonSizeDp + - LoginPinView::kButtonSeparatorSizeDp, - sorted_x[i + 1]); - } + for (size_t i = 0; i < sorted_x.size() - 1; ++i) + EXPECT_EQ(sorted_x[i] + LoginPinView::kButtonSizeDp, sorted_x[i + 1]); EXPECT_EQ(4u, sorted_y.size()); - for (size_t i = 0; i < sorted_y.size() - 1; ++i) { - EXPECT_EQ(sorted_y[i] + LoginPinView::kButtonSizeDp + - LoginPinView::kButtonSeparatorSizeDp, - sorted_y[i + 1]); - } + for (size_t i = 0; i < sorted_y.size() - 1; ++i) + EXPECT_EQ(sorted_y[i] + LoginPinView::kButtonSizeDp, sorted_y[i + 1]); } // Verifies that holding the backspace button automatically triggers and begins
diff --git a/ash/resources/vector_icons/system_menu_child_user.1x.icon b/ash/resources/vector_icons/system_menu_child_user.1x.icon index c440104..45746de 100644 --- a/ash/resources/vector_icons/system_menu_child_user.1x.icon +++ b/ash/resources/vector_icons/system_menu_child_user.1x.icon
@@ -1,37 +1,25 @@ -// 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. - CANVAS_DIMENSIONS, 20, -MOVE_TO, 11.62f, 9.98f, -ARC_TO, 1.82f, 1.82f, 0, 0, 0, 10, 9.01f, -R_CUBIC_TO, -0.7f, 0, -1.31f, 0.39f, -1.62f, 0.97f, -R_CUBIC_TO, -0.15f, 0.26f, -0.23f, 0.56f, -0.23f, 0.87f, -R_CUBIC_TO, 0, 0.99f, 0.83f, 1.81f, 1.85f, 1.81f, -R_CUBIC_TO, 1.01f, 0, 1.85f, -0.81f, 1.85f, -1.81f, -R_CUBIC_TO, 0, -0.31f, -0.08f, -0.61f, -0.23f, -0.87f, -CLOSE, -MOVE_TO, 10, 1, -R_CUBIC_TO, 1.5f, 0, 2.73f, 1.2f, 2.73f, 2.67f, -R_CUBIC_TO, 0, 1.47f, -1.23f, 2.67f, -2.73f, 2.67f, -R_CUBIC_TO, -1.5f, 0, -2.73f, -1.2f, -2.73f, -2.67f, -CUBIC_TO, 7.27f, 2.2f, 8.5f, 1, 10, 1, -CLOSE, -R_MOVE_TO, -6, 9.49f, -R_V_LINE_TO, 5.22f, -R_CUBIC_TO, 0, 1.05f, 1.01f, 1.95f, 2.4f, 2.55f, -R_ARC_TO, 9.53f, 9.53f, 0, 0, 0, 3.6f, 0.72f, -R_CUBIC_TO, 0.31f, 0, 0.79f, 0.04f, 1.09f, 0, -R_V_LINE_TO, -2.67f, -R_CUBIC_TO, -0.27f, 0.32f, -0.78f, 0.32f, -1.09f, 0.32f, -R_ARC_TO, 9.62f, 9.62f, 0, 0, 1, -3.54f, -0.7f, -R_CUBIC_TO, 0.31f, -0.96f, 2, -1.65f, 3.55f, -1.65f, -R_CUBIC_TO, 0.4f, 0, 0.8f, 0.05f, 1.2f, 0.14f, -R_CUBIC_TO, 1.28f, 0.28f, 2.4f, 0.98f, 2.4f, 1.83f, -R_V_LINE_TO, 2.02f, -R_CUBIC_TO, 1.39f, -0.59f, 2.4f, -1.5f, 2.4f, -2.55f, -R_V_LINE_TO, -5.22f, -R_CUBIC_TO, 0, -1.85f, -3.16f, -3.26f, -6, -3.26f, -R_CUBIC_TO, -2.84f, 0, -6, 1.41f, -6, 3.26f, +MOVE_TO, 10.32f, 2, +LINE_TO, 4.63f, 8, +R_LINE_TO, 4.92f, 7.5f, +R_LINE_TO, -0.4f, 0.6f, +R_CUBIC_TO, -0.04f, 0.07f, -0.09f, 0.12f, -0.14f, 0.18f, +R_CUBIC_TO, -0.24f, 0.25f, -0.56f, 0.39f, -0.9f, 0.39f, +R_CUBIC_TO, -0.34f, 0, -0.65f, -0.13f, -0.9f, -0.39f, +R_ARC_TO, 1.35f, 1.35f, 0, 0, 1, -0.37f, -0.94f, +R_ARC_TO, 2.72f, 2.72f, 0, 0, 0, -0.74f, -1.88f, +R_ARC_TO, 2.44f, 2.44f, 0, 0, 0, -1.78f, -0.78f, +H_LINE_TO, 4, +R_V_LINE_TO, 1.34f, +R_H_LINE_TO, 0.33f, +R_CUBIC_TO, 0.34f, 0, 0.65f, 0.14f, 0.9f, 0.39f, +R_CUBIC_TO, 0.24f, 0.26f, 0.37f, 0.59f, 0.37f, 0.95f, +R_CUBIC_TO, 0, 0.71f, 0.26f, 1.38f, 0.74f, 1.88f, +R_CUBIC_TO, 0.48f, 0.5f, 1.11f, 0.78f, 1.78f, 0.78f, +R_CUBIC_TO, 0.67f, 0, 1.31f, -0.28f, 1.78f, -0.78f, +R_CUBIC_TO, 0.11f, -0.11f, 0.2f, -0.23f, 0.28f, -0.35f, +R_LINE_TO, 1.27f, -1.94f, +LINE_TO, 16, 8, +LINE_TO, 10.32f, 2, CLOSE, END
diff --git a/ash/resources/vector_icons/system_menu_child_user.icon b/ash/resources/vector_icons/system_menu_child_user.icon index aa2bc199..e3dacc5c 100644 --- a/ash/resources/vector_icons/system_menu_child_user.icon +++ b/ash/resources/vector_icons/system_menu_child_user.icon
@@ -1,37 +1,25 @@ -// 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. - CANVAS_DIMENSIONS, 40, -MOVE_TO, 22.96f, 19.96f, -ARC_TO, 3.33f, 3.33f, 0, 0, 0, 20, 18.14f, -R_ARC_TO, 3.33f, 3.33f, 0, 0, 0, -2.96f, 1.82f, -R_ARC_TO, 3.41f, 3.41f, 0, 0, 0, -0.42f, 1.64f, -R_CUBIC_TO, 0, 1.88f, 1.52f, 3.42f, 3.38f, 3.42f, -R_CUBIC_TO, 1.86f, 0, 3.39f, -1.54f, 3.39f, -3.41f, -R_ARC_TO, 3.41f, 3.41f, 0, 0, 0, -0.42f, -1.64f, -CLOSE, -MOVE_TO, 20, 3, -R_CUBIC_TO, 2.75f, 0, 5, 2.27f, 5, 5.05f, -R_CUBIC_TO, 0, 2.78f, -2.25f, 5.05f, -5, 5.05f, -R_CUBIC_TO, -2.75f, 0, -5, -2.27f, -5, -5.04f, -CUBIC_TO, 15, 5.29f, 17.25f, 3, 20, 3, -CLOSE, -MOVE_TO, 9, 20.94f, -R_V_LINE_TO, 9.85f, -R_CUBIC_TO, 0, 1.98f, 1.85f, 3.69f, 4.4f, 4.82f, -ARC_TO, 17.03f, 17.03f, 0, 0, 0, 20, 36.97f, -R_CUBIC_TO, 0.56f, 0, 1.44f, 0.07f, 2, 0, -R_V_LINE_TO, -5.04f, -R_CUBIC_TO, -0.5f, 0.61f, -1.44f, 0.61f, -2, 0.61f, -R_CUBIC_TO, -2.23f, 0, -4.55f, -0.49f, -6.5f, -1.31f, -R_CUBIC_TO, 0.56f, -1.81f, 3.67f, -3.12f, 6.5f, -3.12f, -R_CUBIC_TO, 0.73f, 0, 1.47f, 0.09f, 2.2f, 0.26f, -R_CUBIC_TO, 2.35f, 0.53f, 4.4f, 1.84f, 4.4f, 3.45f, -R_V_LINE_TO, 3.81f, -R_CUBIC_TO, 2.56f, -1.11f, 4.4f, -2.83f, 4.4f, -4.82f, -R_V_LINE_TO, -9.85f, -R_CUBIC_TO, 0, -3.5f, -5.79f, -6.16f, -11, -6.16f, -CUBIC_TO, 14.79f, 14.8f, 9, 17.43f, 9, 20.94f, +MOVE_TO, 20.64f, 4, +LINE_TO, 9.27f, 16, +R_LINE_TO, 9.84f, 14.99f, +R_LINE_TO, -0.8f, 1.2f, +R_CUBIC_TO, -0.08f, 0.14f, -0.18f, 0.24f, -0.28f, 0.36f, +R_CUBIC_TO, -0.48f, 0.5f, -1.11f, 0.78f, -1.79f, 0.78f, +R_CUBIC_TO, -0.68f, 0, -1.31f, -0.27f, -1.79f, -0.78f, +R_ARC_TO, 2.71f, 2.71f, 0, 0, 1, -0.74f, -1.89f, +R_ARC_TO, 5.44f, 5.44f, 0, 0, 0, -1.48f, -3.76f, +R_CUBIC_TO, -0.95f, -1.01f, -2.22f, -1.56f, -3.57f, -1.56f, +H_LINE_TO, 8, +R_V_LINE_TO, 2.67f, +R_H_LINE_TO, 0.65f, +R_CUBIC_TO, 0.68f, 0, 1.31f, 0.27f, 1.79f, 0.78f, +R_CUBIC_TO, 0.48f, 0.51f, 0.74f, 1.17f, 0.74f, 1.89f, +R_ARC_TO, 5.44f, 5.44f, 0, 0, 0, 1.48f, 3.77f, +R_CUBIC_TO, 0.95f, 1, 2.22f, 1.56f, 3.57f, 1.56f, +R_CUBIC_TO, 1.35f, 0, 2.62f, -0.56f, 3.57f, -1.56f, +R_CUBIC_TO, 0.21f, -0.22f, 0.4f, -0.46f, 0.57f, -0.7f, +R_LINE_TO, 2.55f, -3.89f, +LINE_TO, 32, 16, +LINE_TO, 20.64f, 4, CLOSE, END
diff --git a/ash/shell/window_type_launcher.cc b/ash/shell/window_type_launcher.cc index 542f8e37..3c07afb 100644 --- a/ash/shell/window_type_launcher.cc +++ b/ash/shell/window_type_launcher.cc
@@ -15,7 +15,7 @@ #include "ash/shell/toplevel_window.h" #include "ash/system/status_area_widget.h" #include "ash/system/web_notification/web_notification_tray.h" -#include "ash/test/child_modal_window.h" +#include "ash/wm/test_child_modal_parent.h" #include "base/strings/utf_string_conversions.h" #include "ui/aura/window.h" #include "ui/aura/window_event_dispatcher.h" @@ -283,7 +283,7 @@ ModalWindow::OpenModalWindow(GetWidget()->GetNativeView(), ui::MODAL_TYPE_WINDOW); } else if (sender == child_modal_button_) { - test::CreateChildModalParent(GetWidget()->GetNativeView()->GetRootWindow()); + TestChildModalParent::Create(GetWidget()->GetNativeView()->GetRootWindow()); } else if (sender == transient_button_) { NonModalTransient::OpenNonModalTransient(GetWidget()->GetNativeView()); } else if (sender == show_hide_window_button_) {
diff --git a/ash/system/user/tray_user.cc b/ash/system/user/tray_user.cc index 2452585..75c3975 100644 --- a/ash/system/user/tray_user.cc +++ b/ash/system/user/tray_user.cc
@@ -4,6 +4,7 @@ #include "ash/system/user/tray_user.h" +#include "ash/resources/vector_icons/vector_icons.h" #include "ash/session/session_controller.h" #include "ash/shelf/shelf.h" #include "ash/shell.h" @@ -21,7 +22,9 @@ #include "ui/base/l10n/l10n_util.h" #include "ui/gfx/geometry/insets.h" #include "ui/gfx/image/image.h" +#include "ui/gfx/paint_vector_icon.h" #include "ui/views/border.h" +#include "ui/views/controls/image_view.h" #include "ui/views/controls/label.h" #include "ui/views/layout/box_layout.h" #include "ui/views/view.h" @@ -31,6 +34,14 @@ const int kUserLabelToIconPadding = 5; +views::ImageView* CreateIcon() { + gfx::ImageSkia icon_image = + gfx::CreateVectorIcon(ash::kSystemMenuChildUserIcon, ash::kTrayIconColor); + auto* image = new views::ImageView; + image->SetImage(icon_image); + return image; +} + } // namespace namespace ash { @@ -85,11 +96,10 @@ } void TrayUser::UpdateAfterLoginStatusChange(LoginStatus status) { - bool need_label = false; - bool need_avatar = false; SessionController* session = Shell::Get()->session_controller(); - if (session->IsUserSupervised()) - need_label = true; + bool need_label = session->IsUserSupervised(); + bool need_avatar = false; + bool need_icon = false; switch (status) { case LoginStatus::LOCKED: case LoginStatus::USER: @@ -99,7 +109,12 @@ break; case LoginStatus::SUPERVISED: need_avatar = true; - need_label = true; + if (session->IsUserChild()) { + need_label = false; + need_icon = true; + } else { + need_label = true; + } break; case LoginStatus::GUEST: need_label = true; @@ -111,28 +126,33 @@ } if ((need_avatar != (avatar_ != nullptr)) || - (need_label != (label_ != nullptr))) { + (need_label != (label_ != nullptr)) || + (need_icon != (icon_ != nullptr))) { delete label_; delete avatar_; + delete icon_; + label_ = nullptr; + avatar_ = nullptr; + icon_ = nullptr; + if (need_icon) { + icon_ = CreateIcon(); + layout_view_->AddChildView(icon_); + } if (need_label) { label_ = new views::Label; SetupLabelForTray(label_); layout_view_->AddChildView(label_); - } else { - label_ = nullptr; } if (need_avatar) { avatar_ = new tray::RoundedImageView(kTrayRoundedBorderRadius); avatar_->SetPaintToLayer(); avatar_->layer()->SetFillsBoundsOpaquely(false); layout_view_->AddChildView(avatar_); - } else { - avatar_ = nullptr; } } - if (session->IsUserSupervised()) { + if (label_ && session->IsUserSupervised()) { label_->SetText( l10n_util::GetStringUTF16(IDS_ASH_STATUS_TRAY_SUPERVISED_LABEL)); } else if (status == LoginStatus::GUEST) { @@ -141,7 +161,8 @@ UpdateAvatarImage(status); - // Update layout after setting label_ and avatar_ with new login status. + // Update layout after setting label_, icon_ and avatar_ with new login + // status. UpdateLayoutOfItem(); }
diff --git a/ash/system/user/tray_user.h b/ash/system/user/tray_user.h index cf43714..0708cf2 100644 --- a/ash/system/user/tray_user.h +++ b/ash/system/user/tray_user.h
@@ -18,6 +18,7 @@ namespace views { class Label; +class ImageView; } namespace ash { @@ -85,6 +86,7 @@ views::View* layout_view_ = nullptr; tray::RoundedImageView* avatar_ = nullptr; views::Label* label_ = nullptr; + views::ImageView* icon_ = nullptr; DISALLOW_COPY_AND_ASSIGN(TrayUser); };
diff --git a/ash/wm/overview/window_selector_item.cc b/ash/wm/overview/window_selector_item.cc index 4e0cabb..5bdc721 100644 --- a/ash/wm/overview/window_selector_item.cc +++ b/ash/wm/overview/window_selector_item.cc
@@ -50,8 +50,6 @@ #include "ui/views/layout/box_layout.h" #include "ui/views/window/non_client_view.h" #include "ui/wm/core/coordinate_conversion.h" -#include "ui/wm/core/shadow.h" -#include "ui/wm/core/window_util.h" namespace ash {
diff --git a/ash/wm/tablet_mode/tablet_mode_controller.cc b/ash/wm/tablet_mode/tablet_mode_controller.cc index 58b080fc6..456736e 100644 --- a/ash/wm/tablet_mode/tablet_mode_controller.cc +++ b/ash/wm/tablet_mode/tablet_mode_controller.cc
@@ -27,6 +27,7 @@ #include "ui/events/event.h" #include "ui/events/keycodes/keyboard_codes.h" #include "ui/gfx/geometry/vector3d_f.h" +#include "ui/views/widget/widget.h" namespace ash { @@ -214,8 +215,14 @@ tablet_mode_observers_.RemoveObserver(observer); } -bool TabletModeController::ShouldAutoHideTitlebars() const { - return auto_hide_title_bars_ && IsTabletModeWindowManagerEnabled(); +bool TabletModeController::ShouldAutoHideTitlebars(views::Widget* widget) { + const bool allowed = + auto_hide_title_bars_ && IsTabletModeWindowManagerEnabled(); + if (!allowed || !widget) + return allowed; + + return widget->IsMaximized() || + wm::GetWindowState(widget->GetNativeWindow())->IsSnapped(); } void TabletModeController::OnAccelerometerUpdated(
diff --git a/ash/wm/tablet_mode/tablet_mode_controller.h b/ash/wm/tablet_mode/tablet_mode_controller.h index 80f2668..d256c95 100644 --- a/ash/wm/tablet_mode/tablet_mode_controller.h +++ b/ash/wm/tablet_mode/tablet_mode_controller.h
@@ -37,6 +37,10 @@ class Vector3dF; } +namespace views { +class Widget; +} + namespace ash { class ScopedDisableInternalMouseAndKeyboard; @@ -96,8 +100,10 @@ void RemoveObserver(TabletModeObserver* observer); // Checks if we should auto hide title bars in tablet mode. Returns true if - // the feature is enabled and we are in tablet mode. - bool ShouldAutoHideTitlebars() const; + // the feature is enabled and we are in tablet mode. If |widget| is not null + // this also checks if the window associated with |widget| is in an auto hide + // state. + bool ShouldAutoHideTitlebars(views::Widget* widget); bool auto_hide_title_bars() const { return auto_hide_title_bars_; }
diff --git a/ash/test/child_modal_window.cc b/ash/wm/test_child_modal_parent.cc similarity index 83% rename from ash/test/child_modal_window.cc rename to ash/wm/test_child_modal_parent.cc index 1378d557..dd1334b 100644 --- a/ash/test/child_modal_window.cc +++ b/ash/wm/test_child_modal_parent.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 "ash/test/child_modal_window.h" +#include "ash/wm/test_child_modal_parent.h" #include <memory> @@ -20,7 +20,6 @@ using views::Widget; namespace ash { -namespace test { namespace { @@ -49,13 +48,6 @@ } // namespace -void CreateChildModalParent(aura::Window* context) { - Widget::CreateWindowWithContextAndBounds( - new ChildModalParent(context), context, - gfx::Rect(kWindowLeft, kWindowTop, kWindowWidth, kWindowHeight)) - ->Show(); -} - class ChildModalWindow : public views::WidgetDelegateView { public: ChildModalWindow(); @@ -103,7 +95,15 @@ return ui::MODAL_TYPE_CHILD; } -ChildModalParent::ChildModalParent(aura::Window* context) +// static +void TestChildModalParent::Create(aura::Window* context) { + Widget::CreateWindowWithContextAndBounds( + new TestChildModalParent(context), context, + gfx::Rect(kWindowLeft, kWindowTop, kWindowWidth, kWindowHeight)) + ->Show(); +} + +TestChildModalParent::TestChildModalParent(aura::Window* context) : widget_(std::make_unique<Widget>()), button_(new views::LabelButton( this, @@ -123,25 +123,25 @@ AddChildView(host_); } -ChildModalParent::~ChildModalParent() = default; +TestChildModalParent::~TestChildModalParent() = default; -void ChildModalParent::ShowChild() { +void TestChildModalParent::ShowChild() { if (!child_) child_ = CreateChild(); child_->Show(); } -aura::Window* ChildModalParent::GetModalParent() const { +aura::Window* TestChildModalParent::GetModalParent() const { return widget_->GetNativeView(); } -aura::Window* ChildModalParent::GetChild() const { +aura::Window* TestChildModalParent::GetChild() const { if (child_) return child_->GetNativeView(); return nullptr; } -Widget* ChildModalParent::CreateChild() { +Widget* TestChildModalParent::CreateChild() { Widget* child = Widget::CreateWindowWithParent(new ChildModalWindow, GetWidget()->GetNativeView()); wm::SetModalParent(child->GetNativeView(), GetModalParent()); @@ -150,15 +150,15 @@ return child; } -base::string16 ChildModalParent::GetWindowTitle() const { +base::string16 TestChildModalParent::GetWindowTitle() const { return base::ASCIIToUTF16("Examples: Child Modal Parent"); } -bool ChildModalParent::CanResize() const { +bool TestChildModalParent::CanResize() const { return false; } -void ChildModalParent::DeleteDelegate() { +void TestChildModalParent::DeleteDelegate() { if (child_) { child_->RemoveObserver(this); child_->Close(); @@ -168,7 +168,7 @@ delete this; } -void ChildModalParent::Layout() { +void TestChildModalParent::Layout() { int running_y = y(); button_->SetBounds(x(), running_y, width(), kButtonHeight); running_y += kButtonHeight; @@ -177,7 +177,7 @@ host_->SetBounds(x(), running_y, width(), height() - running_y); } -void ChildModalParent::ViewHierarchyChanged( +void TestChildModalParent::ViewHierarchyChanged( const ViewHierarchyChangedDetails& details) { if (details.is_add && details.child == this) { host_->Attach(widget_->GetNativeWindow()); @@ -185,8 +185,8 @@ } } -void ChildModalParent::ButtonPressed(views::Button* sender, - const ui::Event& event) { +void TestChildModalParent::ButtonPressed(views::Button* sender, + const ui::Event& event) { if (sender == button_) { if (!child_) child_ = CreateChild(); @@ -197,12 +197,11 @@ } } -void ChildModalParent::OnWidgetDestroying(Widget* widget) { +void TestChildModalParent::OnWidgetDestroying(Widget* widget) { if (child_) { DCHECK_EQ(child_, widget); child_ = NULL; } } -} // namespace test } // namespace ash
diff --git a/ash/test/child_modal_window.h b/ash/wm/test_child_modal_parent.h similarity index 72% rename from ash/test/child_modal_window.h rename to ash/wm/test_child_modal_parent.h index 73f846ad..d6f3d55 100644 --- a/ash/test/child_modal_window.h +++ b/ash/wm/test_child_modal_parent.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 ASH_TEST_CHILD_MODAL_WINDOW_H_ -#define ASH_TEST_CHILD_MODAL_WINDOW_H_ +#ifndef ASH_WM_TEST_CHILD_MODAL_PARENT_H_ +#define ASH_WM_TEST_CHILD_MODAL_PARENT_H_ #include <memory> @@ -18,21 +18,20 @@ class Textfield; class View; class Widget; -} +} // namespace views namespace ash { -namespace test { -void CreateChildModalParent(aura::Window* context); - -// TODO(jamescook): Rename to TestChildModalParent, remove the test namespcae, -// and move to //ash/wm. -class ChildModalParent : public views::WidgetDelegateView, - public views::ButtonListener, - public views::WidgetObserver { +// Test window that can act as a parent for modal child windows. +class TestChildModalParent : public views::WidgetDelegateView, + public views::ButtonListener, + public views::WidgetObserver { public: - ChildModalParent(aura::Window* context); - ~ChildModalParent() override; + // Creates the test window. + static void Create(aura::Window* context); + + explicit TestChildModalParent(aura::Window* context); + ~TestChildModalParent() override; void ShowChild(); aura::Window* GetModalParent() const; @@ -74,10 +73,9 @@ // The child window. views::Widget* child_; - DISALLOW_COPY_AND_ASSIGN(ChildModalParent); + DISALLOW_COPY_AND_ASSIGN(TestChildModalParent); }; -} // namespace test } // namespace ash -#endif // ASH_TEST_CHILD_MODAL_WINDOW_H_ +#endif // ASH_WM_TEST_CHILD_MODAL_PARENT_H_
diff --git a/ash/wm/window_modality_controller_unittest.cc b/ash/wm/window_modality_controller_unittest.cc index ecacbac..baeb0ec 100644 --- a/ash/wm/window_modality_controller_unittest.cc +++ b/ash/wm/window_modality_controller_unittest.cc
@@ -6,7 +6,7 @@ #include "ash/shell.h" #include "ash/test/ash_test_base.h" -#include "ash/test/child_modal_window.h" +#include "ash/wm/test_child_modal_parent.h" #include "ash/wm/window_util.h" #include "services/ui/public/interfaces/window_manager.mojom.h" #include "ui/aura/client/aura_constants.h" @@ -463,8 +463,7 @@ // |child| window. // - Focus should follow the active window. TEST_F(WindowModalityControllerTest, ChildModal) { - test::ChildModalParent* delegate = - new test::ChildModalParent(CurrentContext()); + TestChildModalParent* delegate = new TestChildModalParent(CurrentContext()); views::Widget* widget = views::Widget::CreateWindowWithContextAndBounds( delegate, CurrentContext(), gfx::Rect(0, 0, 400, 400)); widget->Show(); @@ -523,8 +522,7 @@ // Same as |ChildModal| test, but using |EventGenerator| rather than bypassing // it by calling |ActivateWindow|. TEST_F(WindowModalityControllerTest, ChildModalEventGenerator) { - test::ChildModalParent* delegate = - new test::ChildModalParent(CurrentContext()); + TestChildModalParent* delegate = new TestChildModalParent(CurrentContext()); views::Widget* widget = views::Widget::CreateWindowWithContextAndBounds( delegate, CurrentContext(), gfx::Rect(0, 0, 400, 400)); widget->Show();
diff --git a/base/BUILD.gn b/base/BUILD.gn index fa5a6eae..52f7f99 100644 --- a/base/BUILD.gn +++ b/base/BUILD.gn
@@ -2578,6 +2578,7 @@ "memory/weak_ptr_unittest.nc", "metrics/field_trial_params_unittest.nc", "metrics/histogram_unittest.nc", + "optional_unittest.nc", "strings/string16_unittest.nc", "task_scheduler/task_traits_unittest.nc", ] @@ -2788,8 +2789,6 @@ "//third_party/ub-uiautomator:ub_uiautomator_java", ] java_files = [ - "test/android/javatests/src/org/chromium/base/test/BaseChromiumInstrumentationTestRunner.java", - "test/android/javatests/src/org/chromium/base/test/BaseInstrumentationTestRunner.java", "test/android/javatests/src/org/chromium/base/test/BaseJUnit4ClassRunner.java", "test/android/javatests/src/org/chromium/base/test/BaseChromiumAndroidJUnitRunner.java", "test/android/javatests/src/org/chromium/base/test/BaseChromiumRunnerCommon.java",
diff --git a/base/allocator/BUILD.gn b/base/allocator/BUILD.gn index 3aa14cd..7f3b23f 100644 --- a/base/allocator/BUILD.gn +++ b/base/allocator/BUILD.gn
@@ -175,6 +175,14 @@ #"win_allocator.cc", ] + # Not included on mips64el. + if (current_cpu == "mips64el") { + sources -= [ + "$tcmalloc_dir/src/base/linuxthreads.cc", + "$tcmalloc_dir/src/base/linuxthreads.h", + ] + } + # Disable the heap checker in tcmalloc. defines = [ "NO_HEAP_CHECK" ]
diff --git a/base/allocator/partition_allocator/page_allocator.cc b/base/allocator/partition_allocator/page_allocator.cc index 152ea3b..31dfb57d 100644 --- a/base/allocator/partition_allocator/page_allocator.cc +++ b/base/allocator/partition_allocator/page_allocator.cc
@@ -47,6 +47,8 @@ return PROT_READ | PROT_WRITE; case PageReadExecute: return PROT_READ | PROT_EXEC; + case PageReadWriteExecute: + return PROT_READ | PROT_WRITE | PROT_EXEC; default: NOTREACHED(); FALLTHROUGH; @@ -73,6 +75,8 @@ return PAGE_READWRITE; case PageReadExecute: return PAGE_EXECUTE_READ; + case PageReadWriteExecute: + return PAGE_EXECUTE_READWRITE; default: NOTREACHED(); // Fall through.
diff --git a/base/allocator/partition_allocator/page_allocator.h b/base/allocator/partition_allocator/page_allocator.h index a39b4e30..6d160e98 100644 --- a/base/allocator/partition_allocator/page_allocator.h +++ b/base/allocator/partition_allocator/page_allocator.h
@@ -43,6 +43,9 @@ PageInaccessible, PageReadWrite, PageReadExecute, + // This flag is deprecated and will go away soon. + // TODO(bbudge) Remove this as soon as V8 doesn't need RWX pages. + PageReadWriteExecute, }; // Allocate one or more pages.
diff --git a/base/i18n/rtl.cc b/base/i18n/rtl.cc index 29ed648..a0991cd 100644 --- a/base/i18n/rtl.cc +++ b/base/i18n/rtl.cc
@@ -25,6 +25,7 @@ #include "third_party/icu/source/i18n/unicode/coll.h" #if defined(OS_IOS) +#include "base/debug/crash_logging.h" #include "base/ios/ios_util.h" #endif @@ -154,6 +155,12 @@ } void SetICUDefaultLocale(const std::string& locale_string) { +#if defined(OS_IOS) + static base::debug::CrashKeyString* crash_key_locale = + base::debug::AllocateCrashKeyString("icu_locale_input", + base::debug::CrashKeySize::Size256); + base::debug::SetCrashKeyString(crash_key_locale, locale_string); +#endif icu::Locale locale(ICULocaleName(locale_string).c_str()); UErrorCode error_code = U_ZERO_ERROR; const char* lang = locale.getLanguage();
diff --git a/base/metrics/bucket_ranges.cc b/base/metrics/bucket_ranges.cc index 0404393..39b37932 100644 --- a/base/metrics/bucket_ranges.cc +++ b/base/metrics/bucket_ranges.cc
@@ -75,30 +75,13 @@ // a nice hash, that tends to depend on all the bits of the sample, with very // little chance of changes in one place impacting changes in another place. static uint32_t Crc32(uint32_t sum, HistogramBase::Sample value) { - // TODO(jar): Switch to false and watch stats. - const bool kUseRealCrc = true; - - if (kUseRealCrc) { - union { - HistogramBase::Sample range; - unsigned char bytes[sizeof(HistogramBase::Sample)]; - } converter; - converter.range = value; - for (size_t i = 0; i < sizeof(converter); ++i) - sum = kCrcTable[(sum & 0xff) ^ converter.bytes[i]] ^ (sum >> 8); - } else { - // Use hash techniques provided in ReallyFastHash, except we don't care - // about "avalanching" (which would worsten the hash, and add collisions), - // and we don't care about edge cases since we have an even number of bytes. - union { - HistogramBase::Sample range; - uint16_t ints[sizeof(HistogramBase::Sample) / 2]; - } converter; - DCHECK_EQ(sizeof(HistogramBase::Sample), sizeof(converter)); - converter.range = value; - sum += converter.ints[0]; - sum = (sum << 16) ^ sum ^ (static_cast<uint32_t>(converter.ints[1]) << 11); - sum += sum >> 11; + union { + HistogramBase::Sample range; + unsigned char bytes[sizeof(HistogramBase::Sample)]; + } converter; + converter.range = value; + for (size_t i = 0; i < sizeof(converter); ++i) { + sum = kCrcTable[(sum & 0xff) ^ converter.bytes[i]] ^ (sum >> 8); } return sum; }
diff --git a/base/metrics/histogram_snapshot_manager.cc b/base/metrics/histogram_snapshot_manager.cc index 7b3cff8..5d21e431 100644 --- a/base/metrics/histogram_snapshot_manager.cc +++ b/base/metrics/histogram_snapshot_manager.cc
@@ -43,6 +43,17 @@ HistogramSnapshotManager::~HistogramSnapshotManager() = default; +void HistogramSnapshotManager::PrepareDeltas( + const std::vector<HistogramBase*>& histograms, + HistogramBase::Flags flags_to_set, + HistogramBase::Flags required_flags) { + for (HistogramBase* const histogram : histograms) { + histogram->SetFlags(flags_to_set); + if ((histogram->flags() & required_flags) == required_flags) + PrepareDelta(histogram); + } +} + void HistogramSnapshotManager::PrepareDelta(HistogramBase* histogram) { if (!histogram->ValidateHistogramContents(true, 0)) return;
diff --git a/base/metrics/histogram_snapshot_manager.h b/base/metrics/histogram_snapshot_manager.h index e2a404f..cf7c149 100644 --- a/base/metrics/histogram_snapshot_manager.h +++ b/base/metrics/histogram_snapshot_manager.h
@@ -41,13 +41,7 @@ // |Histogram::kNoFlags|. void PrepareDeltas(const std::vector<HistogramBase*>& histograms, HistogramBase::Flags flags_to_set, - HistogramBase::Flags required_flags) { - for (HistogramBase* const histogram : histograms) { - histogram->SetFlags(flags_to_set); - if ((histogram->flags() & required_flags) == required_flags) - PrepareDelta(histogram); - } - } + HistogramBase::Flags required_flags); // When the collection is not so simple as can be done using a single // iterator, the steps can be performed separately. Call PerpareDelta()
diff --git a/base/optional.h b/base/optional.h index dc77539..8e56ca6 100644 --- a/base/optional.h +++ b/base/optional.h
@@ -30,6 +30,10 @@ // http://en.cppreference.com/w/cpp/utility/optional/nullopt constexpr nullopt_t nullopt(0); +// Forward declaration, which is refered by following helpers. +template <typename T> +class Optional; + namespace internal { template <typename T, bool = std::is_trivially_destructible<T>::value> @@ -219,6 +223,19 @@ constexpr explicit OptionalBase(in_place_t, Args&&... args) : storage_(in_place, std::forward<Args>(args)...) {} + // Implementation of converting constructors. + template <typename U> + explicit OptionalBase(const OptionalBase<U>& other) { + if (other.storage_.is_populated_) + storage_.Init(other.storage_.value_); + } + + template <typename U> + explicit OptionalBase(OptionalBase<U>&& other) { + if (other.storage_.is_populated_) + storage_.Init(std::move(other.storage_.value_)); + } + ~OptionalBase() = default; OptionalBase& operator=(const OptionalBase& other) { @@ -262,6 +279,11 @@ storage_.is_populated_ = false; } + // For implementing conversion, allow access to other typed OptionalBase + // class. + template <typename U> + friend class OptionalBase; + OptionalStorage<T> storage_; }; @@ -317,6 +339,20 @@ MoveAssignable& operator=(MoveAssignable&&) = delete; }; +// Helper to conditionally enable converting constructors. +template <typename T, typename U> +struct IsConvertibleFromOptional + : std::integral_constant< + bool, + std::is_constructible<T, Optional<U>&>::value || + std::is_constructible<T, const Optional<U>&>::value || + std::is_constructible<T, Optional<U>&&>::value || + std::is_constructible<T, const Optional<U>&&>::value || + std::is_convertible<Optional<U>&, T>::value || + std::is_convertible<const Optional<U>&, T>::value || + std::is_convertible<Optional<U>&&, T>::value || + std::is_convertible<const Optional<U>&&, T>::value> {}; + } // namespace internal // base::Optional is a Chromium version of the C++17 optional class: @@ -347,7 +383,47 @@ constexpr Optional(const Optional& other) = default; constexpr Optional(Optional&& other) = default; - constexpr Optional(nullopt_t) {} + constexpr Optional(nullopt_t) {} // NOLINT(runtime/explicit) + + // Converting copy constructor. "explicit" only if + // std::is_convertible<const U&, T>::value is false. It is implemented by + // declaring two almost same constructors, but that condition in enable_if_t + // is different, so that either one is chosen, thanks to SFINAE. + template < + typename U, + std::enable_if_t<std::is_constructible<T, const U&>::value && + !internal::IsConvertibleFromOptional<T, U>::value && + std::is_convertible<const U&, T>::value, + bool> = false> + Optional(const Optional<U>& other) : internal::OptionalBase<T>(other) {} + + template < + typename U, + std::enable_if_t<std::is_constructible<T, const U&>::value && + !internal::IsConvertibleFromOptional<T, U>::value && + !std::is_convertible<const U&, T>::value, + bool> = false> + explicit Optional(const Optional<U>& other) + : internal::OptionalBase<T>(other) {} + + // Converting move constructor. Similar to converting copy constructor, + // declaring two (explicit and non-explicit) constructors. + template < + typename U, + std::enable_if_t<std::is_constructible<T, U&&>::value && + !internal::IsConvertibleFromOptional<T, U>::value && + std::is_convertible<U&&, T>::value, + bool> = false> + Optional(Optional<U>&& other) : internal::OptionalBase<T>(std::move(other)) {} + + template < + typename U, + std::enable_if_t<std::is_constructible<T, U&&>::value && + !internal::IsConvertibleFromOptional<T, U>::value && + !std::is_convertible<U&&, T>::value, + bool> = false> + explicit Optional(Optional<U>&& other) + : internal::OptionalBase<T>(std::move(other)) {} constexpr Optional(const T& value) : internal::OptionalBase<T>(in_place, value) {}
diff --git a/base/optional_unittest.cc b/base/optional_unittest.cc index 09f3106..da3ac2d 100644 --- a/base/optional_unittest.cc +++ b/base/optional_unittest.cc
@@ -364,6 +364,65 @@ } } +TEST(OptionalTest, ConvertingCopyConstructor) { + { + Optional<int> first(1); + Optional<double> second(first); + EXPECT_TRUE(second.has_value()); + EXPECT_EQ(1.0, second.value()); + } + + // Make sure explicit is not marked for convertible case. + { + Optional<int> o(1); + ignore_result<Optional<double>>(o); + } +} + +TEST(OptionalTest, ConvertingMoveConstructor) { + { + Optional<int> first(1); + Optional<double> second(std::move(first)); + EXPECT_TRUE(second.has_value()); + EXPECT_EQ(1.0, second.value()); + } + + // Make sure explicit is not marked for convertible case. + { + Optional<int> o(1); + ignore_result<Optional<double>>(std::move(o)); + } + + { + class Test1 { + public: + explicit Test1(int foo) : foo_(foo) {} + + int foo() const { return foo_; } + + private: + int foo_; + }; + + // Not copyable but convertible from Test1. + class Test2 { + public: + Test2(const Test2&) = delete; + explicit Test2(Test1&& other) : bar_(other.foo()) {} + + double bar() const { return bar_; } + + private: + double bar_; + }; + + Optional<Test1> first(in_place, 42); + Optional<Test2> second(std::move(first)); + EXPECT_TRUE(second.has_value()); + EXPECT_EQ(42.0, second->bar()); + } +} + TEST(OptionalTest, ConstructorForwardArguments) { { constexpr Optional<float> a(base::in_place, 0.1f);
diff --git a/base/optional_unittest.nc b/base/optional_unittest.nc new file mode 100644 index 0000000..eca324a --- /dev/null +++ b/base/optional_unittest.nc
@@ -0,0 +1,49 @@ +// 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. + +// This is a "No Compile Test" suite. +// http://dev.chromium.org/developers/testing/no-compile-tests + +#include <type_traits> + +#include "base/optional.h" + +namespace base { + +#if defined(NCTEST_EXPLICIT_CONVERTING_COPY_CONSTRUCTOR) // [r"fatal error: no matching function for call to object of type"] + +// Optional<T>(const Optional<U>& arg) constructor is marked explicit if +// T is not convertible from "const U&". +void WontCompile() { + struct Test { + // Declares as explicit so that Test is still constructible from int, + // but not convertible. + explicit Test(int a) {} + }; + + static_assert(!std::is_convertible<const int&, Test>::value, + "const int& to Test is convertible"); + const Optional<int> arg(in_place, 1); + ([](Optional<Test> param) {})(arg); +} + +#elif defined(NCTEST_EXPLICIT_CONVERTING_MOVE_CONSTRUCTOR) // [r"fatal error: no matching function for call to object of type"] + +// Optional<T>(Optional<U>&& arg) constructor is marked explicit if +// T is not convertible from "U&&". +void WontCompile() { + struct Test { + // Declares as explicit so that Test is still constructible from int, + // but not convertible. + explicit Test(int a) {} + }; + + static_assert(!std::is_convertible<int&&, Test>::value, + "int&& to Test is convertible"); + ([](Optional<Test> param) {})(Optional<int>(in_place, 1)); +} + +#endif + +} // namespace base
diff --git a/base/test/android/javatests/src/org/chromium/base/test/BaseChromiumInstrumentationTestRunner.java b/base/test/android/javatests/src/org/chromium/base/test/BaseChromiumInstrumentationTestRunner.java deleted file mode 100644 index 693bb62..0000000 --- a/base/test/android/javatests/src/org/chromium/base/test/BaseChromiumInstrumentationTestRunner.java +++ /dev/null
@@ -1,40 +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 org.chromium.base.test; - -import android.app.Application; -import android.content.Context; - -import org.chromium.base.multidex.ChromiumMultiDexInstaller; -import org.chromium.base.test.util.CommandLineFlags; - -// TODO(jbudorick): Add support for on-device handling of timeouts. -/** - * An Instrumentation test runner for applications that are based on - * {@code org.chromium.base.BaseChromiumApplication} - */ -public class BaseChromiumInstrumentationTestRunner extends BaseInstrumentationTestRunner { - @Override - public Application newApplication(ClassLoader cl, String className, Context context) - throws ClassNotFoundException, IllegalAccessException, InstantiationException { - ChromiumMultiDexInstaller.install(new BaseChromiumRunnerCommon.MultiDexContextWrapper( - getContext(), getTargetContext())); - BaseChromiumRunnerCommon.reorderDexPathElements(cl, getContext(), getTargetContext()); - return super.newApplication(cl, className, context); - } - - /** - * Override this method to register hooks and checks to be run for each test. Make sure to call - * the base implementation if you do so. - * - * @see BaseTestResult#addSkipCheck(BaseTestResult.SkipCheck) - * @see BaseTestResult#addPreTestHook(BaseTestResult.PreTestHook) - */ - @Override - protected void addTestHooks(BaseTestResult result) { - super.addTestHooks(result); - result.addPreTestHook(CommandLineFlags.getRegistrationHook()); - } -}
diff --git a/base/test/android/javatests/src/org/chromium/base/test/BaseInstrumentationTestRunner.java b/base/test/android/javatests/src/org/chromium/base/test/BaseInstrumentationTestRunner.java deleted file mode 100644 index 67e1c70..0000000 --- a/base/test/android/javatests/src/org/chromium/base/test/BaseInstrumentationTestRunner.java +++ /dev/null
@@ -1,69 +0,0 @@ -// Copyright 2014 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 org.chromium.base.test; - -import android.app.ActivityOptions; -import android.content.Context; -import android.content.ContextWrapper; -import android.content.Intent; -import android.test.AndroidTestRunner; -import android.test.InstrumentationTestRunner; - -import junit.framework.TestResult; - -import org.chromium.base.test.util.DisableIfSkipCheck; -import org.chromium.base.test.util.MinAndroidSdkLevelSkipCheck; -import org.chromium.base.test.util.RestrictionSkipCheck; -import org.chromium.test.reporter.TestStatusListener; - -// TODO(jbudorick): Add support for on-device handling of timeouts. -/** - * An Instrumentation test runner that checks SDK level for tests with specific requirements. - * - * If the package application for which the instrumetation targets is based on - * {@code org.chromium.base.BaseChromiumApplication}, one should use - * {@code BaseChromiumInstrumentationTestRunner} - */ -public class BaseInstrumentationTestRunner extends InstrumentationTestRunner { - @Override - protected AndroidTestRunner getAndroidTestRunner() { - AndroidTestRunner runner = new AndroidTestRunner() { - @Override - protected TestResult createTestResult() { - BaseTestResult r = new BaseTestResult(BaseInstrumentationTestRunner.this); - addTestHooks(r); - return r; - } - }; - runner.addTestListener(new TestStatusListener(getContext())); - return runner; - } - - /** - * Override this method to register hooks and checks to be run for each test. Make sure to call - * the base implementation if you do so. - * - * @see BaseTestResult#addSkipCheck(BaseTestResult.SkipCheck) - * @see BaseTestResult#addPreTestHook(BaseTestResult.PreTestHook) - */ - protected void addTestHooks(BaseTestResult result) { - result.addSkipCheck(new MinAndroidSdkLevelSkipCheck()); - result.addSkipCheck(new RestrictionSkipCheck(getTargetContext())); - result.addSkipCheck(new DisableIfSkipCheck()); - } - - @Override - public Context getTargetContext() { - return new ContextWrapper(super.getTargetContext()) { - @Override - public void startActivity(Intent intent) { - Context context = getApplicationContext(); - ActivityOptions activityOptions = - ActivityOptions.makeCustomAnimation(context, 0, 0); - startActivity(intent, activityOptions.toBundle()); - } - }; - } -}
diff --git a/base/test/android/javatests/src/org/chromium/base/test/BaseJUnit4ClassRunner.java b/base/test/android/javatests/src/org/chromium/base/test/BaseJUnit4ClassRunner.java index 0cdc167..38f3fa6b 100644 --- a/base/test/android/javatests/src/org/chromium/base/test/BaseJUnit4ClassRunner.java +++ b/base/test/android/javatests/src/org/chromium/base/test/BaseJUnit4ClassRunner.java
@@ -19,6 +19,7 @@ import org.chromium.base.CollectionUtil; import org.chromium.base.CommandLine; +import org.chromium.base.Log; import org.chromium.base.test.BaseTestResult.PreTestHook; import org.chromium.base.test.util.DisableIfSkipCheck; import org.chromium.base.test.util.MinAndroidSdkLevelSkipCheck; @@ -39,6 +40,7 @@ * and {@link #isIgnored} to add SkipChecks and PreTesthook. */ public class BaseJUnit4ClassRunner extends AndroidJUnit4ClassRunner { + private static final String TAG = "BaseJUnit4ClassRunnr"; private final List<SkipCheck> mSkipChecks; private final List<PreTestHook> mPreTestHooks; @@ -127,6 +129,16 @@ return l; } + @Override + protected void collectInitializationErrors(List<Throwable> errors) { + super.collectInitializationErrors(errors); + // Log any initialization errors to help debugging, as the host-side test runner can get + // confused by the thrown exception. + if (!errors.isEmpty()) { + Log.e(TAG, "Initialization errors in %s: %s", getTestClass().getName(), errors); + } + } + /** * Change this static function to add or take out default {@code SkipCheck}s. */
diff --git a/base/test/histogram_tester.h b/base/test/histogram_tester.h index 89e0b5a..8375ad6 100644 --- a/base/test/histogram_tester.h +++ b/base/test/histogram_tester.h
@@ -25,6 +25,10 @@ // HistogramTester provides a simple interface for examining histograms, UMA // or otherwise. Tests can use this interface to verify that histogram data is // getting logged as intended. +// +// Note: When using this class from a browser test, one might have to call +// SubprocessMetricsProvider::MergeHistogramDeltasForTesting() to sync the +// histogram data between the renderer and browser processes. class HistogramTester { public: using CountsMap = std::map<std::string, HistogramBase::Count>;
diff --git a/base/threading/thread_restrictions.h b/base/threading/thread_restrictions.h index baa36c8..828acc2c 100644 --- a/base/threading/thread_restrictions.h +++ b/base/threading/thread_restrictions.h
@@ -123,6 +123,10 @@ class ServerGpuMemoryBufferManager; } +namespace webrtc { +class DesktopConfigurationMonitor; +} + namespace base { namespace android { @@ -276,6 +280,7 @@ friend class net::MultiThreadedCertVerifierScopedAllowBaseSyncPrimitives; friend class rlz_lib::FinancialPing; friend class shell_integration::LaunchXdgUtilityScopedAllowBaseSyncPrimitives; + friend class webrtc::DesktopConfigurationMonitor; ScopedAllowBaseSyncPrimitives() EMPTY_BODY_IF_DCHECK_IS_OFF; ~ScopedAllowBaseSyncPrimitives() EMPTY_BODY_IF_DCHECK_IS_OFF;
diff --git a/base/time/time.h b/base/time/time.h index 15e20904..8d017e7e 100644 --- a/base/time/time.h +++ b/base/time/time.h
@@ -132,7 +132,9 @@ // may be unclear from the perspective of a caller. // // DEPRECATED - Do not use in new code. http://crbug.com/634507 - static TimeDelta FromInternalValue(int64_t delta) { return TimeDelta(delta); } + static constexpr TimeDelta FromInternalValue(int64_t delta) { + return TimeDelta(delta); + } // Returns the maximum time delta, which should be greater than any reasonable // time delta we might compare it to. Adding or subtracting the maximum time @@ -150,10 +152,10 @@ // For serializing, use FromInternalValue to reconstitute. // // DEPRECATED - Do not use in new code. http://crbug.com/634507 - int64_t ToInternalValue() const { return delta_; } + constexpr int64_t ToInternalValue() const { return delta_; } // Returns the magnitude (absolute value) of this TimeDelta. - TimeDelta magnitude() const { + constexpr TimeDelta magnitude() const { // Some toolchains provide an incomplete C++11 implementation and lack an // int64_t overload for std::abs(). The following is a simple branchless // implementation: @@ -162,13 +164,15 @@ } // Returns true if the time delta is zero. - bool is_zero() const { - return delta_ == 0; - } + constexpr bool is_zero() const { return delta_ == 0; } // Returns true if the time delta is the maximum/minimum time delta. - bool is_max() const { return delta_ == std::numeric_limits<int64_t>::max(); } - bool is_min() const { return delta_ == std::numeric_limits<int64_t>::min(); } + constexpr bool is_max() const { + return delta_ == std::numeric_limits<int64_t>::max(); + } + constexpr bool is_min() const { + return delta_ == std::numeric_limits<int64_t>::min(); + } #if defined(OS_POSIX) struct timespec ToTimeSpec() const; @@ -190,12 +194,15 @@ int64_t InMicroseconds() const; int64_t InNanoseconds() const; - TimeDelta& operator=(TimeDelta other) { + constexpr TimeDelta& operator=(TimeDelta other) { delta_ = other.delta_; return *this; } - // Computations with other deltas. + // Computations with other deltas. Can easily be made constexpr with C++17 but + // hard to do until then per limitations around + // __builtin_(add|sub)_overflow in safe_math_clang_gcc_impl.h : + // https://chromium-review.googlesource.com/c/chromium/src/+/873352#message-59594ab70827795a67e0780404adf37b4b6c2f14 TimeDelta operator+(TimeDelta other) const { return TimeDelta(time_internal::SaturatedAdd(*this, other.delta_)); } @@ -209,12 +216,12 @@ TimeDelta& operator-=(TimeDelta other) { return *this = (*this - other); } - TimeDelta operator-() const { - return TimeDelta(-delta_); - } + constexpr TimeDelta operator-() const { return TimeDelta(-delta_); } - // Computations with numeric types. - template<typename T> + // Computations with numeric types. operator*() isn't constexpr because of a + // limitation around __builtin_mul_overflow (but operator/(1.0/a) works for + // |a|'s of "reasonable" size -- i.e. that don't risk overflow). + template <typename T> TimeDelta operator*(T a) const { CheckedNumeric<int64_t> rv(delta_); rv *= a; @@ -225,8 +232,8 @@ return TimeDelta(std::numeric_limits<int64_t>::min()); return TimeDelta(std::numeric_limits<int64_t>::max()); } - template<typename T> - TimeDelta operator/(T a) const { + template <typename T> + constexpr TimeDelta operator/(T a) const { CheckedNumeric<int64_t> rv(delta_); rv /= a; if (rv.IsValid()) @@ -237,17 +244,17 @@ return TimeDelta(std::numeric_limits<int64_t>::min()); return TimeDelta(std::numeric_limits<int64_t>::max()); } - template<typename T> + template <typename T> TimeDelta& operator*=(T a) { return *this = (*this * a); } - template<typename T> - TimeDelta& operator/=(T a) { + template <typename T> + constexpr TimeDelta& operator/=(T a) { return *this = (*this / a); } - int64_t operator/(TimeDelta a) const { return delta_ / a.delta_; } - TimeDelta operator%(TimeDelta a) const { + constexpr int64_t operator/(TimeDelta a) const { return delta_ / a.delta_; } + constexpr TimeDelta operator%(TimeDelta a) const { return TimeDelta(delta_ % a.delta_); } @@ -296,8 +303,8 @@ int64_t delta_; }; -template<typename T> -inline TimeDelta operator*(T a, TimeDelta td) { +template <typename T> +TimeDelta operator*(T a, TimeDelta td) { return td * a; }
diff --git a/base/time/time_unittest.cc b/base/time/time_unittest.cc index d5f85f27..bc2cf8b8 100644 --- a/base/time/time_unittest.cc +++ b/base/time/time_unittest.cc
@@ -1112,19 +1112,19 @@ static_assert( TimeDelta::FromMillisecondsD(2.5) == TimeDelta::FromMicroseconds(2500), ""); - EXPECT_EQ(13, TimeDelta::FromDays(13).InDays()); - EXPECT_EQ(13, TimeDelta::FromHours(13).InHours()); - EXPECT_EQ(13, TimeDelta::FromMinutes(13).InMinutes()); - EXPECT_EQ(13, TimeDelta::FromSeconds(13).InSeconds()); - EXPECT_EQ(13.0, TimeDelta::FromSeconds(13).InSecondsF()); - EXPECT_EQ(13, TimeDelta::FromMilliseconds(13).InMilliseconds()); - EXPECT_EQ(13.0, TimeDelta::FromMilliseconds(13).InMillisecondsF()); - EXPECT_EQ(13, TimeDelta::FromSecondsD(13.1).InSeconds()); - EXPECT_EQ(13.1, TimeDelta::FromSecondsD(13.1).InSecondsF()); - EXPECT_EQ(13, TimeDelta::FromMillisecondsD(13.3).InMilliseconds()); - EXPECT_EQ(13.3, TimeDelta::FromMillisecondsD(13.3).InMillisecondsF()); - EXPECT_EQ(13, TimeDelta::FromMicroseconds(13).InMicroseconds()); - EXPECT_EQ(3.456, TimeDelta::FromMillisecondsD(3.45678).InMillisecondsF()); + EXPECT_EQ(TimeDelta::FromDays(13).InDays(), 13); + EXPECT_EQ(TimeDelta::FromHours(13).InHours(), 13); + EXPECT_EQ(TimeDelta::FromMinutes(13).InMinutes(), 13); + EXPECT_EQ(TimeDelta::FromSeconds(13).InSeconds(), 13); + EXPECT_EQ(TimeDelta::FromSeconds(13).InSecondsF(), 13.0); + EXPECT_EQ(TimeDelta::FromMilliseconds(13).InMilliseconds(), 13); + EXPECT_EQ(TimeDelta::FromMilliseconds(13).InMillisecondsF(), 13.0); + EXPECT_EQ(TimeDelta::FromSecondsD(13.1).InSeconds(), 13); + EXPECT_EQ(TimeDelta::FromSecondsD(13.1).InSecondsF(), 13.1); + EXPECT_EQ(TimeDelta::FromMillisecondsD(13.3).InMilliseconds(), 13); + EXPECT_EQ(TimeDelta::FromMillisecondsD(13.3).InMillisecondsF(), 13.3); + EXPECT_EQ(TimeDelta::FromMicroseconds(13).InMicroseconds(), 13); + EXPECT_EQ(TimeDelta::FromMillisecondsD(3.45678).InMillisecondsF(), 3.456); } #if defined(OS_POSIX) @@ -1187,196 +1187,257 @@ } TEST(TimeDelta, Magnitude) { - const int64_t zero = 0; - EXPECT_EQ(TimeDelta::FromMicroseconds(zero), - TimeDelta::FromMicroseconds(zero).magnitude()); + constexpr int64_t zero = 0; + static_assert(TimeDelta::FromMicroseconds(zero) == + TimeDelta::FromMicroseconds(zero).magnitude(), + ""); - const int64_t one = 1; - const int64_t negative_one = -1; - EXPECT_EQ(TimeDelta::FromMicroseconds(one), - TimeDelta::FromMicroseconds(one).magnitude()); - EXPECT_EQ(TimeDelta::FromMicroseconds(one), - TimeDelta::FromMicroseconds(negative_one).magnitude()); + constexpr int64_t one = 1; + constexpr int64_t negative_one = -1; + static_assert(TimeDelta::FromMicroseconds(one) == + TimeDelta::FromMicroseconds(one).magnitude(), + ""); + static_assert(TimeDelta::FromMicroseconds(one) == + TimeDelta::FromMicroseconds(negative_one).magnitude(), + ""); - const int64_t max_int64_minus_one = std::numeric_limits<int64_t>::max() - 1; - const int64_t min_int64_plus_two = std::numeric_limits<int64_t>::min() + 2; - EXPECT_EQ(TimeDelta::FromMicroseconds(max_int64_minus_one), - TimeDelta::FromMicroseconds(max_int64_minus_one).magnitude()); - EXPECT_EQ(TimeDelta::FromMicroseconds(max_int64_minus_one), - TimeDelta::FromMicroseconds(min_int64_plus_two).magnitude()); + constexpr int64_t max_int64_minus_one = + std::numeric_limits<int64_t>::max() - 1; + constexpr int64_t min_int64_plus_two = + std::numeric_limits<int64_t>::min() + 2; + static_assert( + TimeDelta::FromMicroseconds(max_int64_minus_one) == + TimeDelta::FromMicroseconds(max_int64_minus_one).magnitude(), + ""); + static_assert(TimeDelta::FromMicroseconds(max_int64_minus_one) == + TimeDelta::FromMicroseconds(min_int64_plus_two).magnitude(), + ""); } -TEST(TimeDelta, Max) { - TimeDelta max = TimeDelta::Max(); - EXPECT_TRUE(max.is_max()); - EXPECT_EQ(max, TimeDelta::Max()); - EXPECT_GT(max, TimeDelta::FromDays(100 * 365)); - EXPECT_GT(max, TimeDelta()); +TEST(TimeDelta, ZeroMinMax) { + constexpr TimeDelta kZero; + static_assert(kZero.is_zero(), ""); + + constexpr TimeDelta kMax = TimeDelta::Max(); + static_assert(kMax.is_max(), ""); + static_assert(kMax == TimeDelta::Max(), ""); + static_assert(kMax > TimeDelta::FromDays(100 * 365), ""); + static_assert(kMax > kZero, ""); + + constexpr TimeDelta kMin = TimeDelta::Min(); + static_assert(kMin.is_min(), ""); + static_assert(kMin == TimeDelta::Min(), ""); + static_assert(kMin < TimeDelta::FromDays(-100 * 365), ""); + static_assert(kMin < kZero, ""); } -bool IsMin(TimeDelta delta) { +constexpr bool IsMin(TimeDelta delta) { return delta.is_min(); } TEST(TimeDelta, MaxConversions) { - TimeDelta t = TimeDelta::Max(); - EXPECT_EQ(std::numeric_limits<int64_t>::max(), t.ToInternalValue()); + // static_assert also confirms constexpr works as intended. + constexpr TimeDelta kMax = TimeDelta::Max(); + static_assert(kMax.ToInternalValue() == std::numeric_limits<int64_t>::max(), + ""); + EXPECT_EQ(kMax.InDays(), std::numeric_limits<int>::max()); + EXPECT_EQ(kMax.InHours(), std::numeric_limits<int>::max()); + EXPECT_EQ(kMax.InMinutes(), std::numeric_limits<int>::max()); + EXPECT_EQ(kMax.InSecondsF(), std::numeric_limits<double>::infinity()); + EXPECT_EQ(kMax.InSeconds(), std::numeric_limits<int64_t>::max()); + EXPECT_EQ(kMax.InMillisecondsF(), std::numeric_limits<double>::infinity()); + EXPECT_EQ(kMax.InMilliseconds(), std::numeric_limits<int64_t>::max()); + EXPECT_EQ(kMax.InMillisecondsRoundedUp(), std::numeric_limits<int64_t>::max()); - EXPECT_EQ(std::numeric_limits<int>::max(), t.InDays()); - EXPECT_EQ(std::numeric_limits<int>::max(), t.InHours()); - EXPECT_EQ(std::numeric_limits<int>::max(), t.InMinutes()); - EXPECT_EQ(std::numeric_limits<double>::infinity(), t.InSecondsF()); - EXPECT_EQ(std::numeric_limits<int64_t>::max(), t.InSeconds()); - EXPECT_EQ(std::numeric_limits<double>::infinity(), t.InMillisecondsF()); - EXPECT_EQ(std::numeric_limits<int64_t>::max(), t.InMilliseconds()); - EXPECT_EQ(std::numeric_limits<int64_t>::max(), t.InMillisecondsRoundedUp()); + static_assert(TimeDelta::FromDays(std::numeric_limits<int>::max()).is_max(), + ""); - t = TimeDelta::FromDays(std::numeric_limits<int>::max()); - EXPECT_TRUE(t.is_max()); + static_assert(TimeDelta::FromHours(std::numeric_limits<int>::max()).is_max(), + ""); - t = TimeDelta::FromHours(std::numeric_limits<int>::max()); - EXPECT_TRUE(t.is_max()); + static_assert( + TimeDelta::FromMinutes(std::numeric_limits<int>::max()).is_max(), ""); - t = TimeDelta::FromMinutes(std::numeric_limits<int>::max()); - EXPECT_TRUE(t.is_max()); + constexpr int64_t max_int = std::numeric_limits<int64_t>::max(); + constexpr int64_t min_int = std::numeric_limits<int64_t>::min(); - int64_t max_int = std::numeric_limits<int64_t>::max(); - int64_t min_int = std::numeric_limits<int64_t>::min(); + static_assert( + TimeDelta::FromSeconds(max_int / Time::kMicrosecondsPerSecond + 1) + .is_max(), + ""); - t = TimeDelta::FromSeconds(max_int / Time::kMicrosecondsPerSecond + 1); - EXPECT_TRUE(t.is_max()); + static_assert( + TimeDelta::FromMilliseconds(max_int / Time::kMillisecondsPerSecond + 1) + .is_max(), + ""); - t = TimeDelta::FromMilliseconds(max_int / Time::kMillisecondsPerSecond + 1); - EXPECT_TRUE(t.is_max()); + static_assert(TimeDelta::FromMicroseconds(max_int).is_max(), ""); - t = TimeDelta::FromMicroseconds(max_int); - EXPECT_TRUE(t.is_max()); + static_assert( + IsMin(TimeDelta::FromSeconds(min_int / Time::kMicrosecondsPerSecond - 1)), + ""); - t = TimeDelta::FromSeconds(min_int / Time::kMicrosecondsPerSecond - 1); - EXPECT_TRUE(IsMin(t)); + static_assert(IsMin(TimeDelta::FromMilliseconds( + min_int / Time::kMillisecondsPerSecond - 1)), + ""); - t = TimeDelta::FromMilliseconds(min_int / Time::kMillisecondsPerSecond - 1); - EXPECT_TRUE(IsMin(t)); + static_assert(IsMin(TimeDelta::FromMicroseconds(min_int)), ""); - t = TimeDelta::FromMicroseconds(min_int); - EXPECT_TRUE(IsMin(t)); + static_assert( + IsMin(TimeDelta::FromMicroseconds(std::numeric_limits<int64_t>::min())), + ""); - t = TimeDelta::FromMicroseconds(std::numeric_limits<int64_t>::min()); - EXPECT_TRUE(IsMin(t)); + // Floating point arithmetic resulting in infinity isn't constexpr in C++14. + EXPECT_TRUE(TimeDelta::FromSecondsD(std::numeric_limits<double>::infinity()) + .is_max()); - t = TimeDelta::FromSecondsD(std::numeric_limits<double>::infinity()); - EXPECT_TRUE(t.is_max()); + constexpr double max_d = max_int; + constexpr double min_d = min_int; - double max_d = max_int; - double min_d = min_int; + static_assert( + TimeDelta::FromSecondsD(max_d / Time::kMicrosecondsPerSecond + 1) + .is_max(), + ""); - t = TimeDelta::FromSecondsD(max_d / Time::kMicrosecondsPerSecond + 1); - EXPECT_TRUE(t.is_max()); + // Floating point arithmetic resulting in infinity isn't constexpr in C++14. + EXPECT_TRUE( + TimeDelta::FromMillisecondsD(std::numeric_limits<double>::infinity()) + .is_max()); - t = TimeDelta::FromMillisecondsD(std::numeric_limits<double>::infinity()); - EXPECT_TRUE(t.is_max()); + static_assert( + TimeDelta::FromMillisecondsD(max_d / Time::kMillisecondsPerSecond * 2) + .is_max(), + ""); - t = TimeDelta::FromMillisecondsD(max_d / Time::kMillisecondsPerSecond * 2); - EXPECT_TRUE(t.is_max()); + static_assert( + IsMin(TimeDelta::FromSecondsD(min_d / Time::kMicrosecondsPerSecond - 1)), + ""); - t = TimeDelta::FromSecondsD(min_d / Time::kMicrosecondsPerSecond - 1); - EXPECT_TRUE(IsMin(t)); - - t = TimeDelta::FromMillisecondsD(min_d / Time::kMillisecondsPerSecond * 2); - EXPECT_TRUE(IsMin(t)); + static_assert(IsMin(TimeDelta::FromMillisecondsD( + min_d / Time::kMillisecondsPerSecond * 2)), + ""); } TEST(TimeDelta, NumericOperators) { - double d = 0.5; + constexpr double d = 0.5; EXPECT_EQ(TimeDelta::FromMilliseconds(500), - TimeDelta::FromMilliseconds(1000) * d); - EXPECT_EQ(TimeDelta::FromMilliseconds(2000), - TimeDelta::FromMilliseconds(1000) / d); + (TimeDelta::FromMilliseconds(1000) * d)); + static_assert(TimeDelta::FromMilliseconds(2000) == + (TimeDelta::FromMilliseconds(1000) / d), + ""); EXPECT_EQ(TimeDelta::FromMilliseconds(500), - TimeDelta::FromMilliseconds(1000) *= d); - EXPECT_EQ(TimeDelta::FromMilliseconds(2000), - TimeDelta::FromMilliseconds(1000) /= d); + (TimeDelta::FromMilliseconds(1000) *= d)); + static_assert(TimeDelta::FromMilliseconds(2000) == + (TimeDelta::FromMilliseconds(1000) /= d), + ""); EXPECT_EQ(TimeDelta::FromMilliseconds(500), - d * TimeDelta::FromMilliseconds(1000)); + (d * TimeDelta::FromMilliseconds(1000))); - float f = 0.5; + constexpr float f = 0.5; EXPECT_EQ(TimeDelta::FromMilliseconds(500), - TimeDelta::FromMilliseconds(1000) * f); - EXPECT_EQ(TimeDelta::FromMilliseconds(2000), - TimeDelta::FromMilliseconds(1000) / f); + (TimeDelta::FromMilliseconds(1000) * f)); + static_assert(TimeDelta::FromMilliseconds(2000) == + (TimeDelta::FromMilliseconds(1000) / f), + ""); EXPECT_EQ(TimeDelta::FromMilliseconds(500), - TimeDelta::FromMilliseconds(1000) *= f); - EXPECT_EQ(TimeDelta::FromMilliseconds(2000), - TimeDelta::FromMilliseconds(1000) /= f); + (TimeDelta::FromMilliseconds(1000) *= f)); + static_assert(TimeDelta::FromMilliseconds(2000) == + (TimeDelta::FromMilliseconds(1000) /= f), + ""); EXPECT_EQ(TimeDelta::FromMilliseconds(500), - f * TimeDelta::FromMilliseconds(1000)); + (f * TimeDelta::FromMilliseconds(1000))); - int i = 2; + constexpr int i = 2; EXPECT_EQ(TimeDelta::FromMilliseconds(2000), - TimeDelta::FromMilliseconds(1000) * i); - EXPECT_EQ(TimeDelta::FromMilliseconds(500), - TimeDelta::FromMilliseconds(1000) / i); + (TimeDelta::FromMilliseconds(1000) * i)); + static_assert(TimeDelta::FromMilliseconds(500) == + (TimeDelta::FromMilliseconds(1000) / i), + ""); EXPECT_EQ(TimeDelta::FromMilliseconds(2000), - TimeDelta::FromMilliseconds(1000) *= i); - EXPECT_EQ(TimeDelta::FromMilliseconds(500), - TimeDelta::FromMilliseconds(1000) /= i); + (TimeDelta::FromMilliseconds(1000) *= i)); + static_assert(TimeDelta::FromMilliseconds(500) == + (TimeDelta::FromMilliseconds(1000) /= i), + ""); EXPECT_EQ(TimeDelta::FromMilliseconds(2000), - i * TimeDelta::FromMilliseconds(1000)); + (i * TimeDelta::FromMilliseconds(1000))); - int64_t i64 = 2; + constexpr int64_t i64 = 2; EXPECT_EQ(TimeDelta::FromMilliseconds(2000), - TimeDelta::FromMilliseconds(1000) * i64); - EXPECT_EQ(TimeDelta::FromMilliseconds(500), - TimeDelta::FromMilliseconds(1000) / i64); + (TimeDelta::FromMilliseconds(1000) * i64)); + static_assert(TimeDelta::FromMilliseconds(500) == + (TimeDelta::FromMilliseconds(1000) / i64), + ""); EXPECT_EQ(TimeDelta::FromMilliseconds(2000), - TimeDelta::FromMilliseconds(1000) *= i64); - EXPECT_EQ(TimeDelta::FromMilliseconds(500), - TimeDelta::FromMilliseconds(1000) /= i64); + (TimeDelta::FromMilliseconds(1000) *= i64)); + static_assert(TimeDelta::FromMilliseconds(500) == + (TimeDelta::FromMilliseconds(1000) /= i64), + ""); EXPECT_EQ(TimeDelta::FromMilliseconds(2000), - i64 * TimeDelta::FromMilliseconds(1000)); + (i64 * TimeDelta::FromMilliseconds(1000))); EXPECT_EQ(TimeDelta::FromMilliseconds(500), - TimeDelta::FromMilliseconds(1000) * 0.5); - EXPECT_EQ(TimeDelta::FromMilliseconds(2000), - TimeDelta::FromMilliseconds(1000) / 0.5); + (TimeDelta::FromMilliseconds(1000) * 0.5)); + static_assert(TimeDelta::FromMilliseconds(2000) == + (TimeDelta::FromMilliseconds(1000) / 0.5), + ""); EXPECT_EQ(TimeDelta::FromMilliseconds(500), - TimeDelta::FromMilliseconds(1000) *= 0.5); - EXPECT_EQ(TimeDelta::FromMilliseconds(2000), - TimeDelta::FromMilliseconds(1000) /= 0.5); + (TimeDelta::FromMilliseconds(1000) *= 0.5)); + static_assert(TimeDelta::FromMilliseconds(2000) == + (TimeDelta::FromMilliseconds(1000) /= 0.5), + ""); EXPECT_EQ(TimeDelta::FromMilliseconds(500), - 0.5 * TimeDelta::FromMilliseconds(1000)); + (0.5 * TimeDelta::FromMilliseconds(1000))); EXPECT_EQ(TimeDelta::FromMilliseconds(2000), - TimeDelta::FromMilliseconds(1000) * 2); - EXPECT_EQ(TimeDelta::FromMilliseconds(500), - TimeDelta::FromMilliseconds(1000) / 2); + (TimeDelta::FromMilliseconds(1000) * 2)); + static_assert(TimeDelta::FromMilliseconds(500) == + (TimeDelta::FromMilliseconds(1000) / 2), + ""); EXPECT_EQ(TimeDelta::FromMilliseconds(2000), - TimeDelta::FromMilliseconds(1000) *= 2); - EXPECT_EQ(TimeDelta::FromMilliseconds(500), - TimeDelta::FromMilliseconds(1000) /= 2); + (TimeDelta::FromMilliseconds(1000) *= 2)); + static_assert(TimeDelta::FromMilliseconds(500) == + (TimeDelta::FromMilliseconds(1000) /= 2), + ""); EXPECT_EQ(TimeDelta::FromMilliseconds(2000), - 2 * TimeDelta::FromMilliseconds(1000)); + (2 * TimeDelta::FromMilliseconds(1000))); +} + +// Basic test of operators between TimeDeltas (without overflow -- next test +// handles overflow). +TEST(TimeDelta, TimeDeltaOperators) { + constexpr TimeDelta kElevenSeconds = TimeDelta::FromSeconds(11); + constexpr TimeDelta kThreeSeconds = TimeDelta::FromSeconds(3); + + EXPECT_EQ(TimeDelta::FromSeconds(14), kElevenSeconds + kThreeSeconds); + EXPECT_EQ(TimeDelta::FromSeconds(14), kThreeSeconds + kElevenSeconds); + EXPECT_EQ(TimeDelta::FromSeconds(8), kElevenSeconds - kThreeSeconds); + EXPECT_EQ(TimeDelta::FromSeconds(-8), kThreeSeconds - kElevenSeconds); + static_assert(3 == kElevenSeconds / kThreeSeconds, ""); + static_assert(0 == kThreeSeconds / kElevenSeconds, ""); + static_assert(TimeDelta::FromSeconds(2) == kElevenSeconds % kThreeSeconds, + ""); } TEST(TimeDelta, Overflows) { - // Some sanity checks. - EXPECT_TRUE(TimeDelta::Max().is_max()); - EXPECT_LT(-TimeDelta::Max(), TimeDelta()); - EXPECT_GT(-TimeDelta::Max(), TimeDelta::Min()); - EXPECT_GT(TimeDelta(), -TimeDelta::Max()); + // Some sanity checks. static_assert's used were possible to verify constexpr + // evaluation at the same time. + static_assert(TimeDelta::Max().is_max(), ""); + static_assert(-TimeDelta::Max() < TimeDelta(), ""); + static_assert(-TimeDelta::Max() > TimeDelta::Min(), ""); + static_assert(TimeDelta() > -TimeDelta::Max(), ""); TimeDelta large_delta = TimeDelta::Max() - TimeDelta::FromMilliseconds(1); TimeDelta large_negative = -large_delta; EXPECT_GT(TimeDelta(), large_negative); EXPECT_FALSE(large_delta.is_max()); EXPECT_FALSE(IsMin(-large_negative)); - TimeDelta one_second = TimeDelta::FromSeconds(1); + constexpr TimeDelta kOneSecond = TimeDelta::FromSeconds(1); // Test +, -, * and / operators. - EXPECT_TRUE((large_delta + one_second).is_max()); - EXPECT_TRUE(IsMin(large_negative + (-one_second))); - EXPECT_TRUE(IsMin(large_negative - one_second)); - EXPECT_TRUE((large_delta - (-one_second)).is_max()); + EXPECT_TRUE((large_delta + kOneSecond).is_max()); + EXPECT_TRUE(IsMin(large_negative + (-kOneSecond))); + EXPECT_TRUE(IsMin(large_negative - kOneSecond)); + EXPECT_TRUE((large_delta - (-kOneSecond)).is_max()); EXPECT_TRUE((large_delta * 2).is_max()); EXPECT_TRUE(IsMin(large_delta * -2)); EXPECT_TRUE((large_delta / 0.5).is_max()); @@ -1384,17 +1445,17 @@ // Test +=, -=, *= and /= operators. TimeDelta delta = large_delta; - delta += one_second; + delta += kOneSecond; EXPECT_TRUE(delta.is_max()); delta = large_negative; - delta += -one_second; + delta += -kOneSecond; EXPECT_TRUE(IsMin(delta)); delta = large_negative; - delta -= one_second; + delta -= kOneSecond; EXPECT_TRUE(IsMin(delta)); delta = large_delta; - delta -= -one_second; + delta -= -kOneSecond; EXPECT_TRUE(delta.is_max()); delta = large_delta; @@ -1418,12 +1479,12 @@ EXPECT_TRUE((TimeTicks::Now() + large_delta).is_max()); Time time_now = Time::Now(); - EXPECT_EQ(one_second, (time_now + one_second) - time_now); - EXPECT_EQ(-one_second, (time_now - one_second) - time_now); + EXPECT_EQ(kOneSecond, (time_now + kOneSecond) - time_now); + EXPECT_EQ(-kOneSecond, (time_now - kOneSecond) - time_now); TimeTicks ticks_now = TimeTicks::Now(); - EXPECT_EQ(-one_second, (ticks_now - one_second) - ticks_now); - EXPECT_EQ(one_second, (ticks_now + one_second) - ticks_now); + EXPECT_EQ(-kOneSecond, (ticks_now - kOneSecond) - ticks_now); + EXPECT_EQ(kOneSecond, (ticks_now + kOneSecond) - ticks_now); } TEST(TimeDeltaLogging, DCheckEqCompiles) { @@ -1431,18 +1492,18 @@ } TEST(TimeDeltaLogging, EmptyIsZero) { - TimeDelta zero; - EXPECT_EQ("0 s", AnyToString(zero)); + constexpr TimeDelta kZero; + EXPECT_EQ("0 s", AnyToString(kZero)); } TEST(TimeDeltaLogging, FiveHundredMs) { - TimeDelta five_hundred_ms = TimeDelta::FromMilliseconds(500); - EXPECT_EQ("0.5 s", AnyToString(five_hundred_ms)); + constexpr TimeDelta kFiveHundredMs = TimeDelta::FromMilliseconds(500); + EXPECT_EQ("0.5 s", AnyToString(kFiveHundredMs)); } TEST(TimeDeltaLogging, MinusTenSeconds) { - TimeDelta minus_ten_seconds = TimeDelta::FromSeconds(-10); - EXPECT_EQ("-10 s", AnyToString(minus_ten_seconds)); + constexpr TimeDelta kMinusTenSeconds = TimeDelta::FromSeconds(-10); + EXPECT_EQ("-10 s", AnyToString(kMinusTenSeconds)); } TEST(TimeDeltaLogging, DoesNotMessUpFormattingFlags) {
diff --git a/build/android/gyp/javac.py b/build/android/gyp/javac.py index 4dfd8255..dde7bc04 100755 --- a/build/android/gyp/javac.py +++ b/build/android/gyp/javac.py
@@ -326,10 +326,7 @@ # Pass classpath and source paths as response files to avoid extremely # long command lines that are tedius to debug. if classpath: - classpath_rsp_path = os.path.join(temp_dir, 'classpath.txt') - with open(classpath_rsp_path, 'w') as f: - f.write(':'.join(classpath)) - cmd += ['-classpath', '@' + classpath_rsp_path] + cmd += ['-classpath', ':'.join(classpath)] java_files_rsp_path = os.path.join(temp_dir, 'files_list.txt') with open(java_files_rsp_path, 'w') as f:
diff --git a/build/config/compiler/BUILD.gn b/build/config/compiler/BUILD.gn index 632591a1..c1fb098 100644 --- a/build/config/compiler/BUILD.gn +++ b/build/config/compiler/BUILD.gn
@@ -2020,7 +2020,7 @@ # TODO(thakis): Remove this again once dump_syms is fixed. cflags += [ "-gdwarf-3" ] } - if (is_linux && !using_sanitizer) { + if (!using_sanitizer) { # minimal_symbols needs to only produce valid stack traces, and -g0 does # that, even though you might think it'd produce no symbols at all. # Not using -g1 allows us to speed up link time and save disk space.
diff --git a/build/config/fuchsia/package.gni b/build/config/fuchsia/package.gni index b4351f25..e97bf522 100644 --- a/build/config/fuchsia/package.gni +++ b/build/config/fuchsia/package.gni
@@ -16,11 +16,10 @@ } assert(defined(pkg.binary)) - _pkg_out_dir = "$root_build_dir/package" - _runtime_deps_file = "$root_out_dir/gen.runtime/${pkg.package_name}/" + - "${pkg.package_name}.runtime_deps" - _manifest_file = "$root_out_dir/gen.runtime/${pkg.package_name}/" + - "${pkg.package_name}.archive_manifest" + _pkg_out_dir = "$root_out_dir/gen/" + + get_label_info(pkg.package_name, "dir") + _runtime_deps_file = "$_pkg_out_dir/${pkg.package_name}.runtime_deps" + _manifest_file = "$_pkg_out_dir/${pkg.package_name}.archive_manifest" _archive_file = "$_pkg_out_dir/${pkg.package_name}.far" _write_archive_target = "${pkg.package_name}__write_archive" _write_manifest_target = "${pkg.package_name}__write_manifest"
diff --git a/build/config/fuchsia/rules.gni b/build/config/fuchsia/rules.gni index b9e1ca12..af587ee 100644 --- a/build/config/fuchsia/rules.gni +++ b/build/config/fuchsia/rules.gni
@@ -14,6 +14,12 @@ "$root_out_dir/gen.runtime/" + get_label_info(invoker.root_target_name, "dir") + "/" + get_label_info(invoker.root_target_name, "name") + ".runtime_deps" + _pkg_dir = "$root_out_dir/gen/" + get_label_info(invoker.package_name, "dir") + _manifest_path = "$_pkg_dir/${invoker.package_name}.archive_manifest" + _package_path = "$_pkg_dir/${invoker.package_name}.far" + _runner_target = "${target_name}_runner" + _legacy_runner_target = "${target_name}_legacy_runner" + _target_name = target_name group(_runtime_deps_target) { forward_variables_from(invoker, @@ -25,7 +31,17 @@ write_runtime_deps = _runtime_deps_file } - action(target_name) { + # Build both types of runner scripts until the legacy scripts can be removed. + # TODO(crbug.com/805057): delete legacy runner scripts. + group(target_name) { + forward_variables_from(invoker, [ "testonly" ]) + data_deps = [ + ":${_legacy_runner_target}", + ] + data_deps += [ ":${_runner_target}" ] + } + + action(_legacy_runner_target) { forward_variables_from(invoker, [ "deps", @@ -77,6 +93,59 @@ rebase_path(_runtime_deps_file, root_build_dir), ] } + + action(_runner_target) { + forward_variables_from(invoker, + [ + "runner_script", + "target", + "testonly", + ]) + + deps = [ + "//testing/buildbot/filters:fuchsia_filters", + ] + + _generated_script = "${invoker.generated_script}_v2" + + script = "//build/fuchsia/runner_v2/create_runner_script.py" + depfile = "$target_gen_dir/$_target_name.d" + + outputs = [ + _generated_script, + ] + + data = [ + _generated_script, + "//build/fuchsia/runner_v2/", + "//build/util/lib/", + "//third_party/fuchsia-sdk/", + ] + + # Arguments used at build time by the runner script generator. + args = [ + "--script-output-path", + rebase_path(_generated_script, root_build_dir, root_out_dir), + "--package", + rebase_path(_package_path, root_out_dir, root_build_dir), + "--package-manifest", + rebase_path(_manifest_path, root_out_dir, root_build_dir), + ] + + if (defined(invoker.use_test_server) && invoker.use_test_server) { + args += [ "--enable-test-server" ] + } + + # Arguments used at runtime by the test runner. + args += [ + "--runner-script", + runner_script, + "--output-directory", + rebase_path(root_build_dir, root_build_dir), + "--target-cpu", + target_cpu, + ] + } } # This template is used to generate a runner script for test binaries into the @@ -134,6 +203,7 @@ ] exe_path = _exe_path root_target_name = invoker.target_name + package_name = _exe_name } group(target_name) { @@ -145,6 +215,8 @@ ] } + # This target is superceded by the packaging system. + # TODO(kmarshall): remove this target and remove dependencies from bots. generate_runner_script(_archive_target) { forward_variables_from(invoker, [ "testonly" ]) runner_script = "archive_builder.py" @@ -155,5 +227,6 @@ ] exe_path = _exe_path root_target_name = invoker.target_name + package_name = _exe_name } }
diff --git a/build/config/sanitizers/BUILD.gn b/build/config/sanitizers/BUILD.gn index 6e651a6..0b13684 100644 --- a/build/config/sanitizers/BUILD.gn +++ b/build/config/sanitizers/BUILD.gn
@@ -255,16 +255,18 @@ assert(is_clang, "sanitizers only supported with clang") assert(!is_official_build, "sanitizers not supported in official builds") - if (!sanitizer_keep_symbols) { - cflags += [ "-gline-tables-only" ] - } + if (!sanitizer_no_symbols) { + if (!sanitizer_keep_symbols) { + cflags += [ "-gline-tables-only" ] + } - cflags += [ - # Column info in debug data confuses Visual Studio's debugger, so don't - # use this by default. However, clusterfuzz needs it for good attribution - # of reports to CLs, so turn it on there. - "-gcolumn-info", - ] + cflags += [ + # Column info in debug data confuses Visual Studio's debugger, so don't + # use this by default. However, clusterfuzz needs it for good + # attribution of reports to CLs, so turn it on there. + "-gcolumn-info", + ] + } # Frame pointers are controlled in //build/config/compiler:default_stack_frames }
diff --git a/build/config/sanitizers/sanitizers.gni b/build/config/sanitizers/sanitizers.gni index efea1d48..73441af 100644 --- a/build/config/sanitizers/sanitizers.gni +++ b/build/config/sanitizers/sanitizers.gni
@@ -107,6 +107,10 @@ # necessary, overriding any other symbol level arguments that may be set. # Setting this to true prevents this. sanitizer_keep_symbols = false + + # Builds fuzzer/sanitizers without symbols. Use with symbol_level=0. + # Useful for reducing binary size when building with use_clang_coverage=true. + sanitizer_no_symbols = false } # Disable sanitizers for non-default toolchains.
diff --git a/content/test/data/content-sniffer-test4.html b/build/fuchsia/runner_v2/__init__.py similarity index 100% copy from content/test/data/content-sniffer-test4.html copy to build/fuchsia/runner_v2/__init__.py
diff --git a/build/fuchsia/runner_v2/boot_image.py b/build/fuchsia/runner_v2/boot_data.py similarity index 67% rename from build/fuchsia/runner_v2/boot_image.py rename to build/fuchsia/runner_v2/boot_data.py index 6cab62bd..aff7aba3 100644 --- a/build/fuchsia/runner_v2/boot_image.py +++ b/build/fuchsia/runner_v2/boot_data.py
@@ -5,9 +5,12 @@ """Functions used to provision Fuchsia boot images.""" import common +import logging import os import subprocess import tempfile +import time +import uuid _SSH_CONFIG_TEMPLATE = """ Host * @@ -24,10 +27,6 @@ ServerAliveCountMax 1""" -def _GetKernelPath(target_arch): - return os.path.join(_TargetCpuToSdkBinPath(target_arch), 'zircon.bin') - - def _TargetCpuToSdkBinPath(target_arch): """Returns the path to the kernel & bootfs .bin files for |target_cpu|.""" return os.path.join(common.SDK_ROOT, 'target', target_arch) @@ -47,8 +46,9 @@ id_key_path = output_dir + '/id_ed25519' id_pubkey_path = id_key_path + '.pub' known_hosts_path = output_dir + '/known_hosts' - ssh_config_path = output_dir + '/ssh_config' + ssh_config_path = GetSSHConfigPath(output_dir) + logging.debug('Generating SSH credentials.') if not os.path.isfile(host_key_path): subprocess.check_call(['ssh-keygen', '-t', 'ed25519', '-h', '-f', host_key_path, '-P', '', '-N', ''], @@ -70,27 +70,57 @@ ) -def CreateBootFS(output_dir, target_arch): - """Creates a bootfs image provisoned with the credentials necessary - for SSH remote access. +def GetKernelPath(target_arch): + return os.path.join(_TargetCpuToSdkBinPath(target_arch), 'zircon.bin') - Returns a tuple with the path to SSH config and the path to the boot - image.""" - boot_image = os.path.join( +def GetSSHConfigPath(output_dir): + return output_dir + '/ssh_config' + + +def CreateBootdata(output_dir, target_arch): + """Creates a bootdata image ready for SSH remote access. + + Returns a path to the bootdata.bin file.""" + + base_boot_data = os.path.join( _TargetCpuToSdkBinPath(target_arch), 'bootdata.bin') - ssh_manifest = tempfile.NamedTemporaryFile(delete=False) ssh_config, ssh_data = _ProvisionSSH(output_dir) + ssh_manifest = tempfile.NamedTemporaryFile(delete=False) for key, val in ssh_data: ssh_manifest.write("%s=%s\n" % (key, val)) ssh_manifest.close() mkbootfs_path = os.path.join(common.SDK_ROOT, 'tools', 'mkbootfs') - bootfs_name = output_dir + '/image.bootfs' - args = [mkbootfs_path, '-o', bootfs_name, - '--target=boot', boot_image, + bootfs_path = output_dir + '/image.bootfs' + args = [mkbootfs_path, '-o', bootfs_path, + '--target=boot', base_boot_data, '--target=system', ssh_manifest.name] + logging.debug(' '.join(args)) subprocess.check_call(args) os.remove(ssh_manifest.name) - return ssh_config, bootfs_name + return bootfs_path + + +def GetNodeName(output_dir): + """Returns the cached Zircon node name, or generates one if it doesn't + already exist. The node name is used by Discover to find the prior + deployment on the LAN.""" + + nodename_file = os.path.join(output_dir, 'nodename') + if not os.path.exists(nodename_file): + nodename = uuid.uuid4() + f = open(nodename_file, 'w') + f.write(str(nodename)) + f.flush() + f.close() + return str(nodename) + else: + f = open(nodename_file, 'r') + return f.readline() + + +def GetKernelArgs(output_dir): + return ['devmgr.epoch=%d' % time.time(), + 'zircon.nodename=' + GetNodeName(output_dir)]
diff --git a/build/fuchsia/runner_v2/common_args.py b/build/fuchsia/runner_v2/common_args.py new file mode 100644 index 0000000..e2445e14 --- /dev/null +++ b/build/fuchsia/runner_v2/common_args.py
@@ -0,0 +1,57 @@ +# 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. + +import logging +import os + +from device_target import DeviceTarget +from qemu_target import QemuTarget + + +def AddCommonArgs(arg_parser): + """Adds command line arguments to |arg_parser| for options which are shared + across test and executable target types.""" + + common_args = arg_parser.add_argument_group('common', 'Common arguments') + common_args.add_argument('--package', + type=os.path.realpath, required=True, + help='Path to the package to execute.') + common_args.add_argument('--package-manifest', + type=os.path.realpath, required=True, + help='Path to the Fuchsia package manifest file.') + common_args.add_argument('--output-directory', + type=os.path.realpath, required=True, + help=('Path to the directory in which build files are' + ' located (must include build type).')) + common_args.add_argument('--target-cpu', required=True, + help='GN target_cpu setting for the build.') + common_args.add_argument('--device', '-d', action='store_true', default=False, + help='Run on hardware device instead of QEMU.') + common_args.add_argument('--host', help='The IP of the target device. ' + + 'Optional.') + common_args.add_argument('--port', '-p', type=int, default=22, + help='The port of the SSH service running on the ' + + 'device. Optional.') + common_args.add_argument('--ssh_config', '-F', + help='The path to the SSH configuration used for ' + 'connecting to the target device.') + common_args.add_argument('--verbose', '-v', default=False, action='store_true', + help='Show more logging information.') + + +def ConfigureLogging(args): + """Configures the logging level based on command line |args|.""" + + logging.basicConfig(level=(logging.DEBUG if args.verbose else logging.INFO)) + + +def GetDeploymentTargetForArgs(args): + """Constructs a deployment target object using parameters taken from + command line arguments.""" + + if not args.device: + return QemuTarget(args.output_directory, args.target_cpu) + else: + return DeviceTarget(args.output_directory, args.target_cpu, + args.host, args.port, args.ssh_config)
diff --git a/build/fuchsia/runner_v2/create_runner_script.py b/build/fuchsia/runner_v2/create_runner_script.py new file mode 100755 index 0000000..80fd16d --- /dev/null +++ b/build/fuchsia/runner_v2/create_runner_script.py
@@ -0,0 +1,89 @@ +#!/usr/bin/env python +# +# 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. + +"""Creates a script to run a Fushsia executable by delegating to +build/fuchsia/(exe|test)_runner.py. +""" + +import argparse +import os +import re +import sys + + +SCRIPT_TEMPLATE = """\ +#!/usr/bin/env python +# +# This file was generated by build/fuchsia/runner_v2/create_runner_script.py + +import os +import sys + +def main(): + script_directory = os.path.dirname(__file__) + + def ResolvePath(path): + \"\"\"Returns an absolute filepath given a path relative to this script. + \"\"\" + return os.path.abspath(os.path.join(script_directory, path)) + + runner_path = ResolvePath('{runner_path}') + runner_args = {runner_args} + runner_path_args = {runner_path_args} + for arg, path in runner_path_args: + runner_args.extend([arg, ResolvePath(path)]) + + os.execv(runner_path, + [runner_path] + runner_args + sys.argv[1:]) + +if __name__ == '__main__': + sys.exit(main()) +""" + + +def main(args): + parser = argparse.ArgumentParser() + parser.add_argument('--runner-script', + help='Name of the runner script to use.') + parser.add_argument('--script-output-path', + help='Output path for executable script.') + parser.add_argument('--test-runner-path', + help='Path to test_runner.py (optional).') + group = parser.add_argument_group('Test runner path arguments.') + group.add_argument('--output-directory') + group.add_argument('--package') + group.add_argument('--package-manifest') + args, runner_args = parser.parse_known_args(args) + + def RelativizePathToScript(path): + """Returns the path relative to the output script directory.""" + return os.path.relpath(path, os.path.dirname(args.script_output_path)) + + runner_path = args.test_runner_path or os.path.join( + os.path.dirname(__file__), args.runner_script) + runner_path = RelativizePathToScript(runner_path) + + runner_path_args = [] + runner_path_args.append( + ('--output-directory', RelativizePathToScript(args.output_directory))) + runner_path_args.append( + ('--package', RelativizePathToScript(args.package))) + runner_path_args.append( + ('--package-manifest', RelativizePathToScript(args.package_manifest))) + + with open(args.script_output_path, 'w') as script: + script.write(SCRIPT_TEMPLATE.format( + runner_path=str(runner_path), + runner_args=repr(runner_args), + runner_path_args=repr(runner_path_args))) + + # Sets the mode of the generated script so that it is executable by the + # current user. + os.chmod(args.script_output_path, 0750) + + +if __name__ == '__main__': + sys.exit(main(sys.argv[1:]))
diff --git a/build/fuchsia/runner_v2/device_target.py b/build/fuchsia/runner_v2/device_target.py new file mode 100644 index 0000000..f6eb42f4 --- /dev/null +++ b/build/fuchsia/runner_v2/device_target.py
@@ -0,0 +1,96 @@ +# 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. + +"""Implements commands for running and interacting with Fuchsia on devices.""" + +import boot_data +import common +import logging +import os +import subprocess +import target +import time +import uuid + +CONNECT_RETRY_COUNT = 20 +CONNECT_RETRY_WAIT_SECS = 1 + +class DeviceTarget(target.Target): + def __init__(self, output_dir, target_cpu, host=None, port=None, + ssh_config=None): + """output_dir: The directory which will contain the files that are + generated to support the deployment. + target_cpu: The CPU architecture of the deployment target. Can be + "x64" or "arm64". + host: The address of the deployment target device. + port: The port of the SSH service on the deployment target device. + ssh_config: The path to SSH configuration data.""" + + super(DeviceTarget, self).__init__(output_dir, target_cpu) + + self._port = 22 + self._auto = not host or not ssh_config + + if self._auto: + self._ssh_config_path = boot_data.GetSSHConfigPath(output_dir) + else: + self._ssh_config_path = os.path.expanduser(ssh_config) + self._host = host + if port: + self._port = port + + def __Discover(self, node_name): + """Returns the IP address and port of a Fuchsia instance discovered on + the local area network.""" + + netaddr_path = os.path.join(common.SDK_ROOT, 'tools', 'netaddr') + command = [netaddr_path, '--fuchsia', '--nowait', node_name] + logging.debug(' '.join(command)) + proc = subprocess.Popen(command, + stdout=subprocess.PIPE, + stderr=open(os.devnull, 'w')) + proc.wait() + if proc.returncode == 0: + return proc.stdout.readlines()[0].strip() + return None + + def Start(self): + if self._auto: + logging.debug('Starting automatic device deployment.') + node_name = boot_data.GetNodeName(self._output_dir) + self._host = self.__Discover(node_name) + if self._host and self._WaitUntilReady(retries=0): + logging.info('Connected to an already booted device.') + return + + logging.info('Netbooting Fuchsia. ' + + 'Please ensure that your device is in bootloader mode.') + boot_data_path = boot_data.CreateBootdata( + self._output_dir, self._GetTargetSdkArch()) + bootserver_path = os.path.join(common.SDK_ROOT, 'tools', 'bootserver') + bootserver_command = [bootserver_path, '-1', + boot_data.GetKernelPath(self._GetTargetSdkArch()), + boot_data_path, '--'] + \ + boot_data.GetKernelArgs(self._output_dir) + logging.debug(' '.join(bootserver_command)) + subprocess.check_call(bootserver_command) + + logging.debug('Waiting for device to join network.') + for _ in xrange(CONNECT_RETRY_COUNT): + self._host = self.__Discover(node_name) + if self._host: + break + time.sleep(CONNECT_RETRY_WAIT_SECS) + if not self._host: + raise Exception('Couldn\'t connect to device.') + + logging.debug('host=%s, port=%d' % (self._host, self._port)) + + self._WaitUntilReady(); + + def _GetEndpoint(self): + return (self._host, self._port) + + def _GetSshConfigPath(self): + return self._ssh_config_path
diff --git a/build/fuchsia/runner_v2/qemu_target.py b/build/fuchsia/runner_v2/qemu_target.py index d5ffb44..38a65ec 100644 --- a/build/fuchsia/runner_v2/qemu_target.py +++ b/build/fuchsia/runner_v2/qemu_target.py
@@ -4,8 +4,9 @@ """Implements commands for running and interacting with Fuchsia on QEMU.""" -import boot_image +import boot_data import common +import logging import target import os import platform @@ -31,13 +32,14 @@ class QemuTarget(target.Target): - def __init__(self, output_dir, target_cpu, verbose=True): + def __init__(self, output_dir, target_cpu, ram_size_mb=2048): """output_dir: The directory which will contain the files that are generated to support the QEMU deployment. - target_cpu: The emulated target CPU architecture. Can be 'x64' or 'arm64'. - verbose: If true, emits extra non-error logging data for diagnostics.""" - super(QemuTarget, self).__init__(output_dir, target_cpu, verbose) + target_cpu: The emulated target CPU architecture. + Can be 'x64' or 'arm64'.""" + super(QemuTarget, self).__init__(output_dir, target_cpu) self._qemu_process = None + self._ram_size_mb = ram_size_mb def __enter__(self): return self @@ -49,18 +51,18 @@ self.Shutdown() def Start(self): - self._ssh_config_path, boot_image_path = boot_image.CreateBootFS( + boot_data_path = boot_data.CreateBootdata( self._output_dir, self._GetTargetSdkArch()) qemu_path = os.path.join( common.SDK_ROOT, 'qemu', 'bin', 'qemu-system-' + self._GetTargetSdkArch()) - kernel_args = ['devmgr.epoch=%d' % time.time()] + kernel_args = boot_data.GetKernelArgs(self._output_dir) qemu_command = [qemu_path, - '-m', '2048', + '-m', str(self._ram_size_mb), '-nographic', - '-kernel', boot_image._GetKernelPath(self._GetTargetSdkArch()), - '-initrd', boot_image_path, + '-kernel', boot_data.GetKernelPath(self._GetTargetSdkArch()), + '-initrd', boot_data_path, '-smp', '4', # Use stdio for the guest OS only; don't attach the QEMU interactive @@ -110,18 +112,23 @@ # Python script panicking and aborting. # The precise root cause is still nebulous, but this fix works. # See crbug.com/741194. + logging.debug('Launching QEMU.') + logging.debug(' '.join(qemu_command)) self._qemu_process = subprocess.Popen( - qemu_command, stdout=subprocess.PIPE, stdin=open(os.devnull)) + qemu_command, stdout=open(os.devnull), stdin=open(os.devnull), + stderr=open(os.devnull)) - self._Attach(); + self._WaitUntilReady(); def Shutdown(self): + logging.info('Shutting down QEMU.') self._qemu_process.kill() + def GetQemuStdout(self): + return self._qemu_process.stdout + def _GetEndpoint(self): - return ('127.0.0.1', self._host_ssh_port) + return ('localhost', self._host_ssh_port) def _GetSshConfigPath(self): - return self._ssh_config_path - - + return boot_data.GetSSHConfigPath(self._output_dir)
diff --git a/build/fuchsia/runner_v2/qemu_target_test.py b/build/fuchsia/runner_v2/qemu_target_test.py index ab287684..cefd8f1c 100755 --- a/build/fuchsia/runner_v2/qemu_target_test.py +++ b/build/fuchsia/runner_v2/qemu_target_test.py
@@ -5,6 +5,7 @@ import qemu_target import shutil +import subprocess import tempfile import time import unittest @@ -31,10 +32,10 @@ tmp_path = tmpdir + "/payload" with open(tmp_path, "w") as tmpfile: tmpfile.write(TEST_PAYLOAD) - target.CopyTo(tmp_path, '/tmp/payload') + target.PutFile(tmp_path, '/tmp/payload') tmp_path_roundtrip = tmp_path + ".roundtrip" - target.CopyFrom('/tmp/payload', tmp_path_roundtrip) + target.GetFile('/tmp/payload', tmp_path_roundtrip) with open(tmp_path_roundtrip) as roundtrip: self.assertEqual(TEST_PAYLOAD, roundtrip.read()) @@ -45,7 +46,9 @@ self.assertEqual(1, target.RunCommand(['false'])) def testRunCommandPiped(self): - proc = target.RunCommandPiped(['cat']) + proc = target.RunCommandPiped(['cat'], + stdin=subprocess.PIPE, + stdout=subprocess.PIPE) proc.stdin.write(TEST_PAYLOAD) proc.stdin.flush() proc.stdin.close()
diff --git a/build/fuchsia/runner_v2/remote_cmd.py b/build/fuchsia/runner_v2/remote_cmd.py index 8d7ad3a..88b01d0 100644 --- a/build/fuchsia/runner_v2/remote_cmd.py +++ b/build/fuchsia/runner_v2/remote_cmd.py
@@ -5,8 +5,10 @@ """Helper functions for remotely executing and copying files over a SSH connection.""" +import logging import os import subprocess +import sys _SSH = ['ssh'] _SCP = ['scp'] @@ -15,6 +17,10 @@ COPY_FROM_TARGET = 1 +def _IsLinkLocalIPv6(hostname): + return hostname.startswith('fe80::') + + def RunSsh(config_path, host, port, command, silent): """Executes an SSH command on the remote host and blocks until completion. @@ -29,6 +35,7 @@ ssh_command = _SSH + ['-F', config_path, host, '-p', str(port)] + command + logging.debug('ssh exec: ' + ' '.join(ssh_command)) if silent: devnull = open(os.devnull, 'w') return subprocess.call(ssh_command, stderr=devnull, stdout=devnull) @@ -36,7 +43,7 @@ return subprocess.call(ssh_command) -def RunPipedSsh(config_path, host, port, command): +def RunPipedSsh(config_path, host, port, command, **kwargs): """Executes an SSH command on the remote host and returns a process object with access to the command's stdio streams. Does not block. @@ -44,17 +51,16 @@ host: The hostname or IP address of the remote host. port: The port to connect to. command: A list of strings containing the command and its arguments. - silent: If true, suppresses all output from 'ssh'. + kwargs: A dictionary of parameters to be passed to subprocess.Popen(). + The parameters can be used to override stdin and stdout, for example. Returns a Popen object for the command.""" ssh_command = _SSH + ['-F', config_path, host, '-p', str(port)] + command - return subprocess.Popen(ssh_command, - stdout=subprocess.PIPE, - stderr=subprocess.PIPE, - stdin=subprocess.PIPE) + logging.debug(' '.join(ssh_command)) + return subprocess.Popen(ssh_command, **kwargs) def RunScp(config_path, host, port, source, dest, direction): @@ -72,14 +78,18 @@ Function will raise an assertion if a failure occurred.""" + scp_command = _SCP[:] + if ':' in host: + scp_command.append('-6') + host = '[' + host + ']' + if logging.getLogger().getEffectiveLevel() == logging.DEBUG: + scp_command.append('-v') + if direction == COPY_TO_TARGET: dest = "%s:%s" % (host, dest) else: source = "%s:%s" % (host, source) + scp_command += ['-F', config_path, '-P', str(port), source, dest] - scp_command = _SCP + ['-F', config_path, - '-P', str(port), - source, - dest] - devnull = open('/dev/null', 'w') - subprocess.check_call(scp_command, stdout=devnull) + logging.debug(' '.join(scp_command)) + subprocess.check_call(scp_command, stdout=open(os.devnull, 'w'))
diff --git a/build/fuchsia/runner_v2/run_package.py b/build/fuchsia/runner_v2/run_package.py new file mode 100644 index 0000000..588a2d18 --- /dev/null +++ b/build/fuchsia/runner_v2/run_package.py
@@ -0,0 +1,63 @@ +# 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. + +"""Contains a helper function for deploying and executing a packaged +executable on a Target.""" + +import logging +import os +import subprocess +import uuid + +from symbolizer import FilterStream + +def RunPackage(output_dir, target, package_path, run_args, symbolizer_config=None): + """Copies the Fuchsia package at |package_path| to the target, + executes it with |run_args|, and symbolizes its output. + + output_dir: The path containing the build output files. + target: The deployment Target object that will run the package. + package_path: The path to the .far package file. + run_args: The command-linearguments which will be passed to the Fuchsia process. + symbolizer_config: A newline delimited list of source files contained in the + package. Omitting this parameter will disable symbolization. + + Returns the exit code of the remote package process.""" + + if symbolizer_config: + if logging.getLogger().getEffectiveLevel() == logging.DEBUG: + logging.debug('Contents of package "%s":' % os.path.basename(package_path)) + for next_line in open(symbolizer_config, 'r'): + logging.debug(' ' + next_line.strip().split('=')[0]) + logging.debug('') + + # Copy the package. + deployed_package_path = '/tmp/package-%s.far' % uuid.uuid1() + target.PutFile(package_path, deployed_package_path) + + try: + command = ['run', deployed_package_path] + run_args + process = target.RunCommandPiped(command, + stdin=open(os.devnull, 'r'), + stdout=subprocess.PIPE) + if symbolizer_config: + # Decorate the process output stream with the symbolizer. + output = FilterStream(process.stdout, symbolizer_config, output_dir) + else: + output = process.stdout + + for next_line in output: + print next_line + + process.wait() + if process.returncode != 0: + # The test runner returns an error status code if *any* tests fail, + # so we should proceed anyway. + logging.warning('Command exited with non-zero status code %d.' % + process.returncode) + finally: + logging.debug('Cleaning up package file.') + target.RunCommand(['rm', deployed_package_path]) + + return process.returncode
diff --git a/build/fuchsia/runner_v2/symbolizer.py b/build/fuchsia/runner_v2/symbolizer.py new file mode 100644 index 0000000..f5d71ef --- /dev/null +++ b/build/fuchsia/runner_v2/symbolizer.py
@@ -0,0 +1,199 @@ +# 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. + +import logging +import os +import re +import subprocess + +# Matches the coarse syntax of a backtrace entry. +_BACKTRACE_PREFIX_RE = re.compile(r'bt#(?P<frame_id>\d+): ') + +# Matches the specific fields of a backtrace entry. +# Back-trace line matcher/parser assumes that 'pc' is always present, and +# expects that 'sp' and ('binary','pc_offset') may also be provided. +_BACKTRACE_ENTRY_RE = re.compile( + r'pc 0(?:x[0-9a-f]+)?' + + r'(?: sp 0x[0-9a-f]+)?' + + r'(?: \((?P<binary>\S+),(?P<pc_offset>0x[0-9a-f]+)\))?$') + + +def FilterStream(stream, manifest_path, output_dir): + """Looks for backtrace lines from an iterable |stream| and symbolizes them. + Yields a stream of strings with symbolized entries replaced.""" + + return _SymbolizerFilter(manifest_path, output_dir).SymbolizeStream(stream) + +class _SymbolizerFilter(object): + """Adds backtrace symbolization capabilities to a process output stream.""" + + def __init__(self, manifest_path, output_dir): + self._symbols_mapping = {} + self._output_dir = output_dir + + # Compute remote/local path mappings using the manifest data. + for next_line in open(manifest_path): + split = next_line.strip().split('=') + target = split[0] + source = os.path.join(output_dir, split[1]) + + with open(source, 'rb') as f: + file_tag = f.read(4) + if file_tag != '\x7fELF': + continue + + self._symbols_mapping[os.path.basename(target)] = source + self._symbols_mapping[target] = source + logging.debug('Symbols: %s -> %s' % (source, target)) + + def _SymbolizeEntries(self, entries): + """Symbolizes the parsed backtrace |entries| by calling addr2line. + + Returns a set of (frame_id, result) pairs.""" + + filename_re = re.compile(r'at ([-._a-zA-Z0-9/+]+):(\d+)') + + # Use addr2line to symbolize all the |pc_offset|s in |entries| in one go. + # Entries with no |debug_binary| are also processed here, so that we get + # consistent output in that case, with the cannot-symbolize case. + addr2line_output = None + if entries[0].has_key('debug_binary'): + addr2line_args = (['addr2line', '-Cipf', '-p', + '--exe=' + entries[0]['debug_binary']] + + map(lambda entry: entry['pc_offset'], entries)) + addr2line_output = subprocess.check_output(addr2line_args).splitlines() + assert addr2line_output + + results = {} + for entry in entries: + raw, frame_id = entry['raw'], entry['frame_id'] + prefix = '#%s: ' % frame_id + + if not addr2line_output: + # Either there was no addr2line output, or too little of it. + filtered_line = raw + else: + output_line = addr2line_output.pop(0) + + # Relativize path to the current working (output) directory if we see + # a filename. + def RelativizePath(m): + relpath = os.path.relpath(os.path.normpath(m.group(1))) + return 'at ' + relpath + ':' + m.group(2) + filtered_line = filename_re.sub(RelativizePath, output_line) + + if '??' in filtered_line.split(): + # If symbolization fails just output the raw backtrace. + filtered_line = raw + else: + # Release builds may inline things, resulting in "(inlined by)" lines. + inlined_by_prefix = " (inlined by)" + while (addr2line_output and + addr2line_output[0].startswith(inlined_by_prefix)): + inlined_by_line = \ + '\n' + (' ' * len(prefix)) + addr2line_output.pop(0) + filtered_line += filename_re.sub(RelativizePath, inlined_by_line) + + results[entry['frame_id']] = prefix + filtered_line + + return results + + def _LookupDebugBinary(self, entry): + """Looks up the binary listed in |entry| in the |_symbols_mapping|. + Returns the corresponding host-side binary's filename, or None.""" + + binary = entry['binary'] + if not binary: + return None + + app_prefix = 'app:' + if binary.startswith(app_prefix): + binary = binary[len(app_prefix):] + + # We change directory into /system/ before running the target executable, so + # all paths are relative to "/system/", and will typically start with "./". + # Some crashes still uses the full filesystem path, so cope with that, too. + pkg_prefix = '/pkg/' + cwd_prefix = './' + if binary.startswith(cwd_prefix): + binary = binary[len(cwd_prefix):] + elif binary.startswith(pkg_prefix): + binary = binary[len(pkg_prefix):] + # Allow other paths to pass-through; sometimes neither prefix is present. + + if binary in self._symbols_mapping: + return self._symbols_mapping[binary] + + # |binary| may be truncated by the crashlogger, so if there is a unique + # match for the truncated name in |symbols_mapping|, use that instead. + matches = filter(lambda x: x.startswith(binary), + self._symbols_mapping.keys()) + if len(matches) == 1: + return self._symbols_mapping[matches[0]] + + return None + + def _SymbolizeBacktrace(self, backtrace): + """Group |backtrace| entries according to the associated binary, and locate + the path to the debug symbols for that binary, if any.""" + + batches = {} + + for entry in backtrace: + debug_binary = self._LookupDebugBinary(entry) + if debug_binary: + entry['debug_binary'] = debug_binary + batches.setdefault(debug_binary, []).append(entry) + + # Run _SymbolizeEntries on each batch and collate the results. + symbolized = {} + for batch in batches.itervalues(): + symbolized.update(self._SymbolizeEntries(batch)) + + # Map each entry to its symbolized form, by frame-id, and return the list. + return map(lambda entry: symbolized[entry['frame_id']], backtrace) + + def SymbolizeStream(self, stream): + """Creates a symbolized logging stream object using the output from + |stream|.""" + + # A buffer of backtrace entries awaiting symbolization, stored as dicts: + # raw: The original back-trace line that followed the prefix. + # frame_id: backtrace frame number (starting at 0). + # binary: path to executable code corresponding to the current frame. + # pc_offset: memory offset within the executable. + backtrace_entries = [] + + # Read from the stream until we hit EOF. + for line in stream: + line = line.rstrip() + + # Look for the back-trace prefix, otherwise just emit the line. + matched = _BACKTRACE_PREFIX_RE.match(line) + if not matched: + yield line + continue + backtrace_line = line[matched.end():] + + # If this was the end of a back-trace then symbolize and emit it. + frame_id = matched.group('frame_id') + if backtrace_line == 'end': + if backtrace_entries: + for processed in self._SymbolizeBacktrace(backtrace_entries): + yield processed + backtrace_entries = [] + continue + + # Parse the program-counter offset, etc into |backtrace_entries|. + matched = _BACKTRACE_ENTRY_RE.match(backtrace_line) + if matched: + # |binary| and |pc_offset| will be None if not present. + backtrace_entries.append( + {'raw': backtrace_line, 'frame_id': frame_id, + 'binary': matched.group('binary'), + 'pc_offset': matched.group('pc_offset')}) + else: + backtrace_entries.append( + {'raw': backtrace_line, 'frame_id': frame_id, + 'binary': None, 'pc_offset': None})
diff --git a/build/fuchsia/runner_v2/target.py b/build/fuchsia/runner_v2/target.py index 05ee996..2be8a5db 100644 --- a/build/fuchsia/runner_v2/target.py +++ b/build/fuchsia/runner_v2/target.py
@@ -2,6 +2,7 @@ # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. +import logging import os import remote_cmd import subprocess @@ -14,15 +15,25 @@ _ATTACH_RETRY_INTERVAL = 1 -class Target(object): - """Abstract base class representing a Fuchsia deployment target.""" +class FuchsiaTargetException(Exception): + def __init__(self, message): + super(FuchsiaTargetException, self).__init__(message) - def __init__(self, output_dir, target_cpu, verbose): - self._target_cpu = target_cpu + +class Target(object): + """Base class representing a Fuchsia deployment target.""" + + def __init__(self, output_dir, target_cpu): self._output_dir = output_dir self._started = False self._dry_run = False - self._vlogger = sys.stdout if verbose else open(os.devnull, 'w') + self._target_cpu = target_cpu + + # Functions used by the Python context manager for teardown. + def __enter__(self): + return self + def __exit__(self, exc_type, exc_val, exc_tb): + return self def Start(self): """Handles the instantiation and connection process for the Fuchsia @@ -34,56 +45,59 @@ commands.""" return self._started - def RunCommandPiped(self, command): + def RunCommandPiped(self, command, **kwargs): """Starts a remote command and immediately returns a Popen object for the command. The caller may interact with the streams, inspect the status code, wait on command termination, etc. command: A list of strings representing the command and arguments. + kwargs: A dictionary of parameters to be passed to subprocess.Popen(). + The parameters can be used to override stdin and stdout, for example. Returns: a Popen object. Note: method does not block.""" - self._AssertStarted() + self._AssertIsStarted() + logging.debug('running (non-blocking) \'%s\'.' % ' '.join(command)) host, port = self._GetEndpoint() - return remote_cmd.RunPipedSsh(self._GetSshConfigPath(), host, port, command) + return remote_cmd.RunPipedSsh(self._GetSshConfigPath(), host, port, command, + **kwargs) def RunCommand(self, command, silent=False): """Executes a remote command and waits for it to finish executing. Returns the exit code of the command.""" - self._AssertStarted() + self._AssertIsStarted() + logging.debug('running \'%s\'.' % ' '.join(command)) host, port = self._GetEndpoint() return remote_cmd.RunSsh(self._GetSshConfigPath(), host, port, command, silent) - def CopyTo(self, source, dest): + def PutFile(self, source, dest): """Copies a file from the local filesystem to the target filesystem. source: The path of the file being copied. dest: The path on the remote filesystem which will be copied to.""" - self._AssertStarted() + self._AssertIsStarted() host, port = self._GetEndpoint() + logging.debug('copy local:%s => remote:%s' % (source, dest)) command = remote_cmd.RunScp(self._GetSshConfigPath(), host, port, source, dest, remote_cmd.COPY_TO_TARGET) - def CopyFrom(self, source, dest): + def GetFile(self, source, dest): """Copies a file from the target filesystem to the local filesystem. source: The path of the file being copied. dest: The path on the local filesystem which will be copied to.""" - self._AssertStarted() + self._AssertIsStarted() host, port = self._GetEndpoint() + logging.debug('copy remote:%s => local:%s' % (source, dest)) return remote_cmd.RunScp(self._GetSshConfigPath(), host, port, source, dest, remote_cmd.COPY_FROM_TARGET) - def Shutdown(self): - self.RunCommand(_SHUTDOWN_CMD) - self._started = False - def _GetEndpoint(self): """Returns a (host, port) tuple for the SSH connection to the target.""" raise NotImplementedError @@ -94,28 +108,31 @@ return 'aarch64' elif self._target_cpu == 'x64': return 'x86_64' - raise Exception('Unknown target_cpu:' + self._target_cpu) + raise FuchsiaTargetException('Unknown target_cpu:' + self._target_cpu) - def _AssertStarted(self): + def _AssertIsStarted(self): assert self.IsStarted() - def _Attach(self): - self._vlogger.write('Trying to connect over SSH...') - self._vlogger.flush() - for _ in xrange(_ATTACH_MAX_RETRIES): + def _WaitUntilReady(self, retries=_ATTACH_MAX_RETRIES): + logging.debug('Connecting to Fuchsia using SSH.') + for _ in xrange(retries+1): host, port = self._GetEndpoint() - if remote_cmd.RunSsh(self._ssh_config_path, host, port, ['echo'], + if remote_cmd.RunSsh(self._GetSshConfigPath(), host, port, ['true'], True) == 0: - self._vlogger.write(' connected!\n') - self._vlogger.flush() + logging.debug('Connected!') self._started = True - return - self._vlogger.write('.') - self._vlogger.flush() + return True time.sleep(_ATTACH_RETRY_INTERVAL) sys.stderr.write(' timeout limit reached.\n') - raise Exception('Couldn\'t connect to QEMU using SSH.') + raise FuchsiaTargetException('Couldn\'t connect to QEMU using SSH.') def _GetSshConfigPath(self, path): raise NotImplementedError + def _GetTargetSdkArch(self): + """Returns the Fuchsia SDK architecture name for the target CPU.""" + if self._target_cpu == 'arm64': + return 'aarch64' + elif self._target_cpu == 'x64': + return 'x86_64' + raise Exception('Unknown target_cpu %s:' % self._target_cpu)
diff --git a/build/fuchsia/runner_v2/test_runner.py b/build/fuchsia/runner_v2/test_runner.py new file mode 100755 index 0000000..92f2f196 --- /dev/null +++ b/build/fuchsia/runner_v2/test_runner.py
@@ -0,0 +1,103 @@ +#!/usr/bin/env python +# +# 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. + +"""Packages a user.bootfs for a Fuchsia boot image, pulling in the runtime +dependencies of a test binary, and then uses either QEMU from the Fuchsia SDK +to run, or starts the bootserver to allow running on a hardware device.""" + +import argparse +import json +import logging +import os +import socket +import subprocess +import sys +import tempfile +import time + +from common_args import AddCommonArgs, ConfigureLogging, GetDeploymentTargetForArgs +from run_package import RunPackage + +DEFAULT_TEST_CONCURRENCY = 4 +TEST_RESULT_PATH = '/data/test_summary.json' +TEST_FILTER_PATH = '/data/test_filter.txt' + +def main(): + parser = argparse.ArgumentParser() + AddCommonArgs(parser) + parser.add_argument('--gtest_filter', + help='GTest filter to use in place of any default.') + parser.add_argument('--gtest_repeat', + help='GTest repeat value to use. This also disables the ' + 'test launcher timeout.') + parser.add_argument('--gtest_break_on_failure', action='store_true', + default=False, + help='Should GTest break on failure; useful with ' + '--gtest_repeat.') + parser.add_argument('--single-process-tests', action='store_true', + default=False, + help='Runs the tests and the launcher in the same ' + 'process. Useful for debugging.') + parser.add_argument('--test-launcher-batch-limit', + type=int, + help='Sets the limit of test batch to run in a single ' + 'process.') + # --test-launcher-filter-file is specified relative to --output-directory, + # so specifying type=os.path.* will break it. + parser.add_argument('--test-launcher-filter-file', + default=None, + help='Override default filter file passed to target test ' + 'process. Set an empty path to disable filtering.') + parser.add_argument('--test-launcher-jobs', + type=int, + help='Sets the number of parallel test jobs.') + parser.add_argument('--test-launcher-summary-output', + help='Where the test launcher will output its json.') + parser.add_argument('child_args', nargs='*', + help='Arguments for the test process.') + args = parser.parse_args() + ConfigureLogging(args) + + child_args = ['--test-launcher-retry-limit=0'] + if args.single_process_tests: + child_args.append('--single-process-tests') + if args.test_launcher_batch_limit: + child_args.append('--test-launcher-batch-limit=%d' % + args.test_launcher_batch_limit) + + test_concurrency = args.test_launcher_jobs \ + if args.test_launcher_jobs else DEFAULT_TEST_CONCURRENCY + child_args.append('--test-launcher-jobs=%d' % test_concurrency) + + if args.gtest_filter: + child_args.append('--gtest_filter=' + args.gtest_filter) + if args.gtest_repeat: + child_args.append('--gtest_repeat=' + args.gtest_repeat) + child_args.append('--test-launcher-timeout=-1') + if args.gtest_break_on_failure: + child_args.append('--gtest_break_on_failure') + if args.child_args: + child_args.extend(args.child_args) + + if args.test_launcher_summary_output: + child_args.append('--test-launcher-summary-output=' + TEST_RESULT_PATH) + + with GetDeploymentTargetForArgs(args) as target: + target.Start() + + if args.test_launcher_filter_file: + target.PutFile(args.test_launcher_filter_file, TEST_FILTER_PATH) + child_args.append('--test-launcher-filter-file=' + TEST_FILTER_PATH) + + RunPackage(args.output_directory, target, args.package, + child_args, args.package_manifest) + + if args.test_launcher_summary_output: + target.GetFile(TEST_RESULT_PATH, args.test_launcher_summary_output) + + +if __name__ == '__main__': + sys.exit(main())
diff --git a/build/fuchsia/update_sdk.py b/build/fuchsia/update_sdk.py index 8d707997..0351ebe0 100755 --- a/build/fuchsia/update_sdk.py +++ b/build/fuchsia/update_sdk.py
@@ -13,6 +13,8 @@ import tarfile import tempfile +SDK_HASH = '893404234442cf13abbc4e22ed996839ff5b1338' + REPOSITORY_ROOT = os.path.abspath(os.path.join( os.path.dirname(__file__), '..', '..')) sys.path.append(os.path.join(REPOSITORY_ROOT, 'build')) @@ -27,21 +29,20 @@ def main(): - if len(sys.argv) != 2: - print >>sys.stderr, 'usage: %s <sdk_hash>' % sys.argv[0] + if len(sys.argv) != 1: + print >>sys.stderr, 'usage: %s' % sys.argv[0] return 1 - sdk_hash = sys.argv[1] output_dir = os.path.join(REPOSITORY_ROOT, 'third_party', 'fuchsia-sdk') hash_filename = os.path.join(output_dir, '.hash') if os.path.exists(hash_filename): with open(hash_filename, 'r') as f: - if f.read().strip() == sdk_hash: + if f.read().strip() == SDK_HASH: # Nothing to do. return 0 - print 'Downloading SDK %s...' % sdk_hash + print 'Downloading SDK %s...' % SDK_HASH if os.path.isdir(output_dir): shutil.rmtree(output_dir) @@ -52,7 +53,7 @@ try: bucket = 'gs://fuchsia/sdk/linux-amd64/' cmd = [os.path.join(find_depot_tools.DEPOT_TOOLS_PATH, 'gsutil.py'), - 'cp', bucket + sdk_hash, tmp] + 'cp', bucket + SDK_HASH, tmp] subprocess.check_call(cmd) with open(tmp, 'rb') as f: EnsureDirExists(output_dir) @@ -61,7 +62,7 @@ os.remove(tmp) with open(hash_filename, 'w') as f: - f.write(sdk_hash) + f.write(SDK_HASH) return 0
diff --git a/build/toolchain/concurrent_links.gni b/build/toolchain/concurrent_links.gni index 6962c46..624fc38 100644 --- a/build/toolchain/concurrent_links.gni +++ b/build/toolchain/concurrent_links.gni
@@ -35,6 +35,8 @@ _args = [ "--mem_per_link_gb=4" ] } else if (is_android && !is_component_build && symbol_level == 2) { _args = [ "--mem_per_link_gb=25" ] + } else if (is_linux && !is_chromeos && symbol_level == 1) { + _args = [ "--mem_per_link_gb=3" ] } else { _args = [] }
diff --git a/build/toolchain/win/tool_wrapper.py b/build/toolchain/win/tool_wrapper.py index c64e84c..797dfd1 100644 --- a/build/toolchain/win/tool_wrapper.py +++ b/build/toolchain/win/tool_wrapper.py
@@ -16,6 +16,16 @@ import string import sys +# tool_wrapper.py doesn't get invoked through python.bat so the Python bin +# directory doesn't get added to the path. The Python module search logic +# handles this fine and finds win32file.pyd. However the Windows module +# search logic then looks for pywintypes27.dll and other DLLs in the path and +# if it finds versions with a different bitness first then win32file.pyd will +# fail to load with a cryptic error: +# ImportError: DLL load failed: %1 is not a valid Win32 application. +os.environ['path'] = os.path.dirname(sys.executable) + ';' + os.environ['path'] +import win32file # pylint: disable=import-error + BASE_DIR = os.path.dirname(os.path.abspath(__file__)) # A regex matching an argument corresponding to the output filename passed to @@ -141,10 +151,14 @@ # For that reason, since going through the shell doesn't seem necessary on # non-Windows don't do that there. pdb_name = None + pe_name = None for arg in args: m = _LINK_PDB_OUT_ARG.match(arg) if m: pdb_name = m.group('out') + m = _LINK_EXE_OUT_ARG.match(arg) + if m: + pe_name = m.group('out') for retry_count in range(_LINKER_RETRIES): retry = False link = subprocess.Popen(args, shell=sys.platform == 'win32', env=env, @@ -167,6 +181,13 @@ result = link.wait() if not retry: break + if result == 0: + # Flush the file buffers to try to work around a Windows 10 kernel bug, + # https://crbug.com/644525 + output_handle = win32file.CreateFile(pe_name, win32file.GENERIC_WRITE, + 0, None, win32file.OPEN_EXISTING, 0, 0) + win32file.FlushFileBuffers(output_handle) + output_handle.Close() return result def ExecAsmWrapper(self, arch, *args):
diff --git a/build/util/lib/common/chrome_test_server_spawner.py b/build/util/lib/common/chrome_test_server_spawner.py index 3cbcde17..363ca6e 100644 --- a/build/util/lib/common/chrome_test_server_spawner.py +++ b/build/util/lib/common/chrome_test_server_spawner.py
@@ -257,7 +257,7 @@ if self.is_ready: port_map = [(0, self.host_port)] if self.host_ocsp_port: - port_map.append([(0, self.host_ocsp_port)]) + port_map.extend([(0, self.host_ocsp_port)]) self.port_forwarder.Map(port_map) self.forwarder_device_port = \
diff --git a/cc/animation/BUILD.gn b/cc/animation/BUILD.gn index 30517439..4772346 100644 --- a/cc/animation/BUILD.gn +++ b/cc/animation/BUILD.gn
@@ -38,6 +38,8 @@ "scroll_offset_animations_impl.h", "scroll_timeline.cc", "scroll_timeline.h", + "single_ticker_animation_player.cc", + "single_ticker_animation_player.h", "timing_function.cc", "timing_function.h", "transform_operation.cc",
diff --git a/cc/animation/animation_host.cc b/cc/animation/animation_host.cc index 38a592f8a..ca94c03 100644 --- a/cc/animation/animation_host.cc +++ b/cc/animation/animation_host.cc
@@ -15,6 +15,7 @@ #include "cc/animation/animation_events.h" #include "cc/animation/animation_id_provider.h" #include "cc/animation/animation_player.h" +#include "cc/animation/animation_ticker.h" #include "cc/animation/animation_timeline.h" #include "cc/animation/element_animations.h" #include "cc/animation/scroll_offset_animation_curve.h" @@ -123,10 +124,10 @@ element_animations->ElementUnregistered(element_id, list_type); } -void AnimationHost::RegisterPlayerForElement(ElementId element_id, - AnimationPlayer* player) { +void AnimationHost::RegisterTickerForElement(ElementId element_id, + AnimationTicker* ticker) { DCHECK(element_id); - DCHECK(player); + DCHECK(ticker); scoped_refptr<ElementAnimations> element_animations = GetElementAnimationsForElementId(element_id); @@ -142,26 +143,24 @@ element_animations->InitAffectedElementTypes(); } - element_animations->AddTicker(player->animation_ticker()); + element_animations->AddTicker(ticker); } -void AnimationHost::UnregisterPlayerForElement(ElementId element_id, - AnimationPlayer* player) { +void AnimationHost::UnregisterTickerForElement(ElementId element_id, + AnimationTicker* ticker) { DCHECK(element_id); - DCHECK(player); + DCHECK(ticker); scoped_refptr<ElementAnimations> element_animations = GetElementAnimationsForElementId(element_id); DCHECK(element_animations); - element_animations->RemoveTicker(player->animation_ticker()); + element_animations->RemoveTicker(ticker); if (element_animations->IsEmpty()) { element_animations->ClearAffectedElementTypes(); element_to_animations_map_.erase(element_animations->element_id()); element_animations->SetAnimationHost(nullptr); } - - RemoveFromTicking(player); } void AnimationHost::SetMutatorHostClient(MutatorHostClient* client) {
diff --git a/cc/animation/animation_host.h b/cc/animation/animation_host.h index cfd8416..7516b6d0 100644 --- a/cc/animation/animation_host.h +++ b/cc/animation/animation_host.h
@@ -27,6 +27,7 @@ namespace cc { class AnimationPlayer; +class AnimationTicker; class AnimationTimeline; class ElementAnimations; class LayerTreeHost; @@ -61,9 +62,9 @@ void RemoveAnimationTimeline(scoped_refptr<AnimationTimeline> timeline); AnimationTimeline* GetTimelineById(int timeline_id) const; - void RegisterPlayerForElement(ElementId element_id, AnimationPlayer* player); - void UnregisterPlayerForElement(ElementId element_id, - AnimationPlayer* player); + void RegisterTickerForElement(ElementId element_id, AnimationTicker* ticker); + void UnregisterTickerForElement(ElementId element_id, + AnimationTicker* ticker); scoped_refptr<ElementAnimations> GetElementAnimationsForElementId( ElementId element_id) const;
diff --git a/cc/animation/animation_host_perftest.cc b/cc/animation/animation_host_perftest.cc index 4da56d0..b5d9d06 100644 --- a/cc/animation/animation_host_perftest.cc +++ b/cc/animation/animation_host_perftest.cc
@@ -6,8 +6,9 @@ #include "base/threading/thread_task_runner_handle.h" #include "cc/animation/animation_id_provider.h" -#include "cc/animation/animation_player.h" +#include "cc/animation/animation_ticker.h" #include "cc/animation/animation_timeline.h" +#include "cc/animation/single_ticker_animation_player.h" #include "cc/base/lap_timer.h" #include "cc/test/fake_impl_task_runner_provider.h" #include "cc/test/fake_layer_tree_host.h" @@ -69,13 +70,13 @@ root_layer_->AddChild(layer); layer->SetElementId(LayerIdToElementIdForTesting(layer->id())); - scoped_refptr<AnimationPlayer> player = - AnimationPlayer::Create(last_player_id_); + scoped_refptr<SingleTickerAnimationPlayer> player = + SingleTickerAnimationPlayer::Create(last_player_id_); last_player_id_ = AnimationIdProvider::NextPlayerId(); all_players_timeline_->AttachPlayer(player); player->AttachElement(layer->element_id()); - EXPECT_TRUE(player->element_animations()); + EXPECT_TRUE(player->element_animations(player->animation_ticker()->id())); } // Create impl players.
diff --git a/cc/animation/animation_player.cc b/cc/animation/animation_player.cc index 8271005..68d6ec3 100644 --- a/cc/animation/animation_player.cc +++ b/cc/animation/animation_player.cc
@@ -12,7 +12,6 @@ #include "cc/animation/animation_delegate.h" #include "cc/animation/animation_events.h" #include "cc/animation/animation_host.h" -#include "cc/animation/animation_ticker.h" #include "cc/animation/animation_timeline.h" #include "cc/animation/scroll_offset_animation_curve.h" #include "cc/animation/transform_operations.h" @@ -29,7 +28,7 @@ animation_timeline_(), animation_delegate_(), id_(id), - animation_ticker_(new AnimationTicker(this)) { + ticking_tickers_count(0) { DCHECK(id_); } @@ -42,8 +41,13 @@ return player; } -ElementId AnimationPlayer::element_id() const { - return animation_ticker_->element_id(); +ElementId AnimationPlayer::element_id_of_ticker(TickerId ticker_id) const { + DCHECK(GetTickerById(ticker_id)); + return GetTickerById(ticker_id)->element_id(); +} + +bool AnimationPlayer::IsElementAttached(ElementId id) const { + return !!element_to_ticker_id_map_.count(id); } void AnimationPlayer::SetAnimationHost(AnimationHost* animation_host) { @@ -54,107 +58,201 @@ if (animation_timeline_ == timeline) return; - // We need to unregister player to manage ElementAnimations and observers + // We need to unregister ticker to manage ElementAnimations and observers // properly. - if (animation_ticker_->has_attached_element() && - animation_ticker_->has_bound_element_animations()) - UnregisterPlayer(); + if (!element_to_ticker_id_map_.empty() && animation_host_) { + // Destroy ElementAnimations or release it if it's still needed. + UnregisterTickers(); + } animation_timeline_ = timeline; + // Register player only if layer AND host attached. Unlike the + // SingleAnimationPlayer case, all tickers have been attached to their + // corresponding elements. + if (!element_to_ticker_id_map_.empty() && animation_host_) { + RegisterTickers(); + } +} + +bool AnimationPlayer::has_element_animations() const { + return !element_to_ticker_id_map_.empty(); +} + +scoped_refptr<ElementAnimations> AnimationPlayer::element_animations( + TickerId ticker_id) const { + return GetTickerById(ticker_id)->element_animations(); +} + +void AnimationPlayer::AttachElementForTicker(ElementId element_id, + TickerId ticker_id) { + DCHECK(GetTickerById(ticker_id)); + GetTickerById(ticker_id)->AttachElement(element_id); + element_to_ticker_id_map_[element_id].emplace(ticker_id); // Register player only if layer AND host attached. - if (animation_ticker_->has_attached_element() && animation_host_) - RegisterPlayer(); + if (animation_host_) { + // Create ElementAnimations or re-use existing. + RegisterTicker(element_id, ticker_id); + } } -bool AnimationPlayer::has_any_animation() const { - return animation_ticker_->has_any_animation(); -} +void AnimationPlayer::DetachElementForTicker(ElementId element_id, + TickerId ticker_id) { + DCHECK(GetTickerById(ticker_id)); + DCHECK_EQ(GetTickerById(ticker_id)->element_id(), element_id); -scoped_refptr<ElementAnimations> AnimationPlayer::element_animations() const { - return animation_ticker_->element_animations(); -} - -void AnimationPlayer::AttachElement(ElementId element_id) { - animation_ticker_->AttachElement(element_id); - - // Register player only if layer AND host attached. - if (animation_host_) - RegisterPlayer(); + UnregisterTicker(element_id, ticker_id); + GetTickerById(ticker_id)->DetachElement(); + element_to_ticker_id_map_[element_id].erase(ticker_id); } void AnimationPlayer::DetachElement() { - DCHECK(animation_ticker_->has_attached_element()); + if (animation_host_) { + // Destroy ElementAnimations or release it if it's still needed. + UnregisterTickers(); + } - if (animation_host_) - UnregisterPlayer(); - - animation_ticker_->DetachElement(); + for (auto pair = element_to_ticker_id_map_.begin(); + pair != element_to_ticker_id_map_.end();) { + for (auto ticker = pair->second.begin(); ticker != pair->second.end();) { + GetTickerById(*ticker)->DetachElement(); + ticker = pair->second.erase(ticker); + } + pair = element_to_ticker_id_map_.erase(pair); + } + DCHECK_EQ(element_to_ticker_id_map_.size(), 0u); } -void AnimationPlayer::RegisterPlayer() { +void AnimationPlayer::RegisterTicker(ElementId element_id, TickerId ticker_id) { DCHECK(animation_host_); - DCHECK(animation_ticker_->has_attached_element()); - DCHECK(!animation_ticker_->has_bound_element_animations()); + AnimationTicker* ticker = GetTickerById(ticker_id); + DCHECK(!ticker->has_bound_element_animations()); - // Create ElementAnimations or re-use existing. - animation_host_->RegisterPlayerForElement(animation_ticker_->element_id(), - this); + if (!ticker->has_attached_element()) + return; + animation_host_->RegisterTickerForElement(element_id, ticker); } -void AnimationPlayer::UnregisterPlayer() { +void AnimationPlayer::UnregisterTicker(ElementId element_id, + TickerId ticker_id) { DCHECK(animation_host_); - DCHECK(animation_ticker_->has_attached_element()); - DCHECK(animation_ticker_->has_bound_element_animations()); - - // Destroy ElementAnimations or release it if it's still needed. - animation_host_->UnregisterPlayerForElement(animation_ticker_->element_id(), - this); + AnimationTicker* ticker = GetTickerById(ticker_id); + DCHECK(ticker); + if (ticker->has_attached_element() && + ticker->has_bound_element_animations()) { + animation_host_->UnregisterTickerForElement(element_id, ticker); + } +} +void AnimationPlayer::RegisterTickers() { + for (auto& element_id_ticker_id : element_to_ticker_id_map_) { + const ElementId element_id = element_id_ticker_id.first; + const std::unordered_set<TickerId>& ticker_ids = + element_id_ticker_id.second; + for (auto& ticker_id : ticker_ids) + RegisterTicker(element_id, ticker_id); + } } -void AnimationPlayer::AddAnimation(std::unique_ptr<Animation> animation) { - animation_ticker_->AddAnimation(std::move(animation)); +void AnimationPlayer::UnregisterTickers() { + for (auto& element_id_ticker_id : element_to_ticker_id_map_) { + const ElementId element_id = element_id_ticker_id.first; + const std::unordered_set<TickerId>& ticker_ids = + element_id_ticker_id.second; + for (auto& ticker_id : ticker_ids) + UnregisterTicker(element_id, ticker_id); + } + animation_host_->RemoveFromTicking(this); } -void AnimationPlayer::PauseAnimation(int animation_id, double time_offset) { - animation_ticker_->PauseAnimation(animation_id, time_offset); +void AnimationPlayer::PushAttachedTickersToImplThread( + AnimationPlayer* player_impl) const { + for (auto& ticker : tickers_) { + AnimationTicker* ticker_impl = player_impl->GetTickerById(ticker->id()); + if (ticker_impl) + continue; + + std::unique_ptr<AnimationTicker> to_add = ticker->CreateImplInstance(); + player_impl->AddTicker(std::move(to_add)); + } } -void AnimationPlayer::RemoveAnimation(int animation_id) { - animation_ticker_->RemoveAnimation(animation_id); +void AnimationPlayer::PushPropertiesToImplThread(AnimationPlayer* player_impl) { + for (auto& ticker : tickers_) { + if (AnimationTicker* ticker_impl = + player_impl->GetTickerById(ticker->id())) { + ticker->PushPropertiesTo(ticker_impl); + } + } } -void AnimationPlayer::AbortAnimation(int animation_id) { - animation_ticker_->AbortAnimation(animation_id); +void AnimationPlayer::AddAnimationForTicker( + std::unique_ptr<Animation> animation, + TickerId ticker_id) { + DCHECK(GetTickerById(ticker_id)); + GetTickerById(ticker_id)->AddAnimation(std::move(animation)); +} + +void AnimationPlayer::PauseAnimationForTicker(int animation_id, + double time_offset, + TickerId ticker_id) { + DCHECK(GetTickerById(ticker_id)); + GetTickerById(ticker_id)->PauseAnimation(animation_id, time_offset); +} + +void AnimationPlayer::RemoveAnimationForTicker(int animation_id, + TickerId ticker_id) { + DCHECK(GetTickerById(ticker_id)); + GetTickerById(ticker_id)->RemoveAnimation(animation_id); +} + +void AnimationPlayer::AbortAnimationForTicker(int animation_id, + TickerId ticker_id) { + DCHECK(GetTickerById(ticker_id)); + GetTickerById(ticker_id)->AbortAnimation(animation_id); } void AnimationPlayer::AbortAnimations(TargetProperty::Type target_property, bool needs_completion) { - animation_ticker_->AbortAnimations(target_property, needs_completion); + for (auto& ticker : tickers_) + ticker->AbortAnimations(target_property, needs_completion); } void AnimationPlayer::PushPropertiesTo(AnimationPlayer* player_impl) { - animation_ticker_->PushPropertiesTo(player_impl->animation_ticker_.get()); + PushAttachedTickersToImplThread(player_impl); + PushPropertiesToImplThread(player_impl); } void AnimationPlayer::Tick(base::TimeTicks monotonic_time) { DCHECK(!monotonic_time.is_null()); - animation_ticker_->Tick(monotonic_time, nullptr); + for (auto& ticker : tickers_) + ticker->Tick(monotonic_time, nullptr); } void AnimationPlayer::UpdateState(bool start_ready_animations, AnimationEvents* events) { - animation_ticker_->UpdateState(start_ready_animations, events); - animation_ticker_->UpdateTickingState(UpdateTickingType::NORMAL); + for (auto& ticker : tickers_) { + ticker->UpdateState(start_ready_animations, events); + ticker->UpdateTickingState(UpdateTickingType::NORMAL); + } } void AnimationPlayer::AddToTicking() { + ++ticking_tickers_count; + if (ticking_tickers_count > 1) + return; DCHECK(animation_host_); animation_host_->AddToTicking(this); } void AnimationPlayer::AnimationRemovedFromTicking() { + DCHECK_GE(ticking_tickers_count, 0); + if (!ticking_tickers_count) + return; + --ticking_tickers_count; DCHECK(animation_host_); + DCHECK_GE(ticking_tickers_count, 0); + if (ticking_tickers_count) + return; animation_host_->RemoveFromTicking(this); } @@ -191,17 +289,11 @@ } } -bool AnimationPlayer::NotifyAnimationFinishedForTesting( - TargetProperty::Type target_property, - int group_id) { - AnimationEvent event(AnimationEvent::FINISHED, - animation_ticker_->element_id(), group_id, - target_property, base::TimeTicks()); - return animation_ticker_->NotifyAnimationFinished(event); -} - size_t AnimationPlayer::TickingAnimationsCount() const { - return animation_ticker_->TickingAnimationsCount(); + size_t count = 0; + for (auto& ticker : tickers_) + count += ticker->TickingAnimationsCount(); + return count; } void AnimationPlayer::SetNeedsCommit() { @@ -210,29 +302,49 @@ } void AnimationPlayer::SetNeedsPushProperties() { - DCHECK(animation_timeline_); + if (!animation_timeline_) + return; animation_timeline_->SetNeedsPushProperties(); } void AnimationPlayer::ActivateAnimations() { - animation_ticker_->ActivateAnimations(); - animation_ticker_->UpdateTickingState(UpdateTickingType::NORMAL); + for (auto& ticker : tickers_) { + ticker->ActivateAnimations(); + ticker->UpdateTickingState(UpdateTickingType::NORMAL); + } } -Animation* AnimationPlayer::GetAnimation( - TargetProperty::Type target_property) const { - return animation_ticker_->GetAnimation(target_property); +Animation* AnimationPlayer::GetAnimationForTicker( + TargetProperty::Type target_property, + TickerId ticker_id) const { + DCHECK(GetTickerById(ticker_id)); + return GetTickerById(ticker_id)->GetAnimation(target_property); } std::string AnimationPlayer::ToString() const { - return base::StringPrintf( - "AnimationPlayer{id=%d, element_id=%s, animations=[%s]}", id_, - animation_ticker_->element_id().ToString().c_str(), - animation_ticker_->AnimationsToString().c_str()); + std::string output = base::StringPrintf("AnimationPlayer{id=%d", id_); + for (const auto& ticker : tickers_) { + output += base::StringPrintf(", element_id=%s, animations=[%s]", + ticker->element_id().ToString().c_str(), + ticker->AnimationsToString().c_str()); + } + return output + "}"; } bool AnimationPlayer::IsWorkletAnimationPlayer() const { return false; } +void AnimationPlayer::AddTicker(std::unique_ptr<AnimationTicker> ticker) { + ticker->SetAnimationPlayer(this); + tickers_.push_back(std::move(ticker)); + + SetNeedsPushProperties(); +} + +AnimationTicker* AnimationPlayer::GetTickerById(TickerId ticker_id) const { + // May return nullptr when syncing tickers_ to impl. + return tickers_.size() > ticker_id ? tickers_[ticker_id].get() : nullptr; +} + } // namespace cc
diff --git a/cc/animation/animation_player.h b/cc/animation/animation_player.h index 2089daf9..cd5b331 100644 --- a/cc/animation/animation_player.h +++ b/cc/animation/animation_player.h
@@ -14,6 +14,7 @@ #include "cc/animation/animation.h" #include "cc/animation/animation_curve.h" #include "cc/animation/animation_export.h" +#include "cc/animation/animation_ticker.h" #include "cc/animation/element_animations.h" #include "cc/trees/element_id.h" @@ -23,7 +24,6 @@ class AnimationEvents; class AnimationHost; class AnimationTimeline; -class AnimationTicker; struct AnimationEvent; // An AnimationPlayer manages grouped sets of animations (each set of which are @@ -37,9 +37,7 @@ // Each cc AnimationPlayer has a copy on the impl thread, and will take care of // synchronizing properties to/from the impl thread when requested. // -// NOTE(smcgruer): As of 2017/09/06 there is a 1:1 relationship between -// AnimationPlayer and the AnimationTicker. This is intended to become a 1:N -// relationship to allow for grouped animations. +// There is a 1:n relationship between AnimationPlayer and AnimationTicker. class CC_ANIMATION_EXPORT AnimationPlayer : public base::RefCounted<AnimationPlayer> { public: @@ -47,7 +45,12 @@ virtual scoped_refptr<AnimationPlayer> CreateImplInstance() const; int id() const { return id_; } - ElementId element_id() const; + // An AnimationPlayer is capable of handling group effects in which case each + // of the effects is owned by an AnimationTicker. The tickers are stored in + // tickers_ and indexed by TickerId. + typedef size_t TickerId; + ElementId element_id_of_ticker(TickerId ticker_id) const; + bool IsElementAttached(ElementId id) const; // Parent AnimationHost. AnimationPlayer can be detached from // AnimationTimeline. @@ -61,26 +64,26 @@ const AnimationTimeline* animation_timeline() const { return animation_timeline_; } - void SetAnimationTimeline(AnimationTimeline* timeline); + virtual void SetAnimationTimeline(AnimationTimeline* timeline); - AnimationTicker* animation_ticker() const { return animation_ticker_.get(); } - - // TODO(smcgruer): Only used by a ui/ unittest: remove. - bool has_any_animation() const; - - scoped_refptr<ElementAnimations> element_animations() const; + bool has_element_animations() const; + scoped_refptr<ElementAnimations> element_animations(TickerId ticker_id) const; void set_animation_delegate(AnimationDelegate* delegate) { animation_delegate_ = delegate; } - void AttachElement(ElementId element_id); - void DetachElement(); + void AttachElementForTicker(ElementId element_id, TickerId ticker_id); + void DetachElementForTicker(ElementId element_id, TickerId ticker_id); + virtual void DetachElement(); - void AddAnimation(std::unique_ptr<Animation> animation); - void PauseAnimation(int animation_id, double time_offset); - void RemoveAnimation(int animation_id); - void AbortAnimation(int animation_id); + void AddAnimationForTicker(std::unique_ptr<Animation> animation, + TickerId ticker_id); + void PauseAnimationForTicker(int animation_id, + double time_offset, + TickerId ticker_id); + void RemoveAnimationForTicker(int animation_id, TickerId ticker_id); + void AbortAnimationForTicker(int animation_id, TickerId ticker_id); void AbortAnimations(TargetProperty::Type target_property, bool needs_completion); @@ -97,8 +100,6 @@ void NotifyAnimationFinished(const AnimationEvent& event); void NotifyAnimationAborted(const AnimationEvent& event); void NotifyAnimationTakeover(const AnimationEvent& event); - bool NotifyAnimationFinishedForTesting(TargetProperty::Type target_property, - int group_id); size_t TickingAnimationsCount() const; void SetNeedsPushProperties(); @@ -110,19 +111,33 @@ // Returns the animation animating the given property that is either // running, or is next to run, if such an animation exists. - Animation* GetAnimation(TargetProperty::Type target_property) const; + Animation* GetAnimationForTicker(TargetProperty::Type target_property, + TickerId ticker_id) const; std::string ToString() const; void SetNeedsCommit(); virtual bool IsWorkletAnimationPlayer() const; + void AddTicker(std::unique_ptr<AnimationTicker>); + + AnimationTicker* GetTickerById(TickerId ticker_id) const; + TickerId NextTickerId() { return tickers_.size(); } private: friend class base::RefCounted<AnimationPlayer>; - void RegisterPlayer(); - void UnregisterPlayer(); + void RegisterTicker(ElementId element_id, TickerId ticker_id); + void UnregisterTicker(ElementId element_id, TickerId ticker_id); + void RegisterTickers(); + void UnregisterTickers(); + + void PushAttachedTickersToImplThread(AnimationPlayer* player) const; + void PushPropertiesToImplThread(AnimationPlayer* player); + + protected: + explicit AnimationPlayer(int id); + virtual ~AnimationPlayer(); AnimationHost* animation_host_; AnimationTimeline* animation_timeline_; @@ -130,11 +145,16 @@ int id_; - protected: - explicit AnimationPlayer(int id); - virtual ~AnimationPlayer(); + using ElementToTickerIdMap = std:: + unordered_map<ElementId, std::unordered_set<TickerId>, ElementIdHash>; + using Tickers = std::vector<std::unique_ptr<AnimationTicker>>; - std::unique_ptr<AnimationTicker> animation_ticker_; + // It is possible for a ticker to be in tickers_ but not in + // element_to_ticker_id_map_ but the reverse is not possible. + ElementToTickerIdMap element_to_ticker_id_map_; + Tickers tickers_; + + int ticking_tickers_count; DISALLOW_COPY_AND_ASSIGN(AnimationPlayer); };
diff --git a/cc/animation/animation_player_unittest.cc b/cc/animation/animation_player_unittest.cc index 95956a9..83071b4 100644 --- a/cc/animation/animation_player_unittest.cc +++ b/cc/animation/animation_player_unittest.cc
@@ -7,10 +7,10 @@ #include "base/strings/stringprintf.h" #include "cc/animation/animation_delegate.h" #include "cc/animation/animation_host.h" -#include "cc/animation/animation_id_provider.h" #include "cc/animation/animation_ticker.h" #include "cc/animation/animation_timeline.h" #include "cc/animation/element_animations.h" +#include "cc/animation/keyframed_animation_curve.h" #include "cc/test/animation_test_common.h" #include "cc/test/animation_timelines_test_common.h" @@ -19,102 +19,235 @@ class AnimationPlayerTest : public AnimationTimelinesTest { public: - AnimationPlayerTest() = default; + AnimationPlayerTest() + : player_(AnimationPlayer::Create(player_id_)), + group_id_(100), + animation_id_(100) { + ticker_id_ = player_->NextTickerId(); + } ~AnimationPlayerTest() override = default; -}; + int NextGroupId() { return ++group_id_; } + + int NextAnimationId() { return ++animation_id_; } + + int AddOpacityTransition(AnimationPlayer* target, + double duration, + float start_opacity, + float end_opacity, + bool use_timing_function, + TickerId ticker_id) { + std::unique_ptr<KeyframedFloatAnimationCurve> curve( + KeyframedFloatAnimationCurve::Create()); + + std::unique_ptr<TimingFunction> func; + if (!use_timing_function) + func = CubicBezierTimingFunction::CreatePreset( + CubicBezierTimingFunction::EaseType::EASE); + if (duration > 0.0) + curve->AddKeyframe(FloatKeyframe::Create(base::TimeDelta(), start_opacity, + std::move(func))); + curve->AddKeyframe(FloatKeyframe::Create( + base::TimeDelta::FromSecondsD(duration), end_opacity, nullptr)); + + int id = NextAnimationId(); + + std::unique_ptr<Animation> animation(Animation::Create( + std::move(curve), id, NextGroupId(), TargetProperty::OPACITY)); + animation->set_needs_synchronized_start_time(true); + + target->AddAnimationForTicker(std::move(animation), ticker_id); + return id; + } + + int AddAnimatedTransform(AnimationPlayer* target, + double duration, + TransformOperations start_operations, + TransformOperations operations, + TickerId ticker_id) { + std::unique_ptr<KeyframedTransformAnimationCurve> curve( + KeyframedTransformAnimationCurve::Create()); + + if (duration > 0.0) { + curve->AddKeyframe(TransformKeyframe::Create(base::TimeDelta(), + start_operations, nullptr)); + } + + curve->AddKeyframe(TransformKeyframe::Create( + base::TimeDelta::FromSecondsD(duration), operations, nullptr)); + + int id = NextAnimationId(); + + std::unique_ptr<Animation> animation(Animation::Create( + std::move(curve), id, NextGroupId(), TargetProperty::TRANSFORM)); + animation->set_needs_synchronized_start_time(true); + + target->AddAnimationForTicker(std::move(animation), ticker_id); + return id; + } + + int AddAnimatedTransform(AnimationPlayer* target, + double duration, + int delta_x, + int delta_y, + TickerId ticker_id) { + TransformOperations start_operations; + if (duration > 0.0) { + start_operations.AppendTranslate(0, 0, 0.0); + } + + TransformOperations operations; + operations.AppendTranslate(delta_x, delta_y, 0.0); + return AddAnimatedTransform(target, duration, start_operations, operations, + ticker_id); + } + + int AddAnimatedFilter(AnimationPlayer* target, + double duration, + float start_brightness, + float end_brightness, + TickerId ticker_id) { + std::unique_ptr<KeyframedFilterAnimationCurve> curve( + KeyframedFilterAnimationCurve::Create()); + + if (duration > 0.0) { + FilterOperations start_filters; + start_filters.Append( + FilterOperation::CreateBrightnessFilter(start_brightness)); + curve->AddKeyframe( + FilterKeyframe::Create(base::TimeDelta(), start_filters, nullptr)); + } + + FilterOperations filters; + filters.Append(FilterOperation::CreateBrightnessFilter(end_brightness)); + curve->AddKeyframe(FilterKeyframe::Create( + base::TimeDelta::FromSecondsD(duration), filters, nullptr)); + + int id = NextAnimationId(); + + std::unique_ptr<Animation> animation(Animation::Create( + std::move(curve), id, NextGroupId(), TargetProperty::FILTER)); + animation->set_needs_synchronized_start_time(true); + + target->AddAnimationForTicker(std::move(animation), ticker_id); + return id; + } + + void CheckTickerAndTimelineNeedsPushProperties(bool needs_push_properties, + TickerId ticker_id) const { + AnimationTicker* ticker = player_->GetTickerById(ticker_id); + EXPECT_EQ(ticker->needs_push_properties(), needs_push_properties); + EXPECT_EQ(timeline_->needs_push_properties(), needs_push_properties); + } + + protected: + scoped_refptr<AnimationPlayer> player_; + scoped_refptr<AnimationPlayer> player_impl_; + int group_id_; + TickerId ticker_id_; + int animation_id_; +}; // See element_animations_unittest.cc for active/pending observers tests. TEST_F(AnimationPlayerTest, AttachDetachLayerIfTimelineAttached) { - EXPECT_TRUE(CheckTickerTimelineNeedsPushProperties(false)); + player_->AddTicker(base::MakeUnique<AnimationTicker>(ticker_id_)); + ASSERT_TRUE(player_->GetTickerById(ticker_id_)); + EXPECT_FALSE(player_->GetTickerById(ticker_id_)->needs_push_properties()); + CheckTickerAndTimelineNeedsPushProperties(false, ticker_id_); + host_->AddAnimationTimeline(timeline_); EXPECT_TRUE(timeline_->needs_push_properties()); - EXPECT_FALSE(player_->animation_ticker()->needs_push_properties()); timeline_->AttachPlayer(player_); - EXPECT_FALSE(player_->element_animations()); - EXPECT_FALSE(player_->element_id()); - + EXPECT_FALSE(player_->element_animations(ticker_id_)); + EXPECT_FALSE(player_->element_id_of_ticker(ticker_id_)); EXPECT_TRUE(timeline_->needs_push_properties()); - EXPECT_FALSE(player_->animation_ticker()->needs_push_properties()); + EXPECT_FALSE(player_->GetTickerById(ticker_id_)->needs_push_properties()); host_->PushPropertiesTo(host_impl_); EXPECT_FALSE(GetImplTickerForLayerId(element_id_)); - GetImplTimelineAndPlayerByID(); + timeline_impl_ = host_impl_->GetTimelineById(timeline_id_); + EXPECT_TRUE(timeline_impl_); + player_impl_ = timeline_impl_->GetPlayerById(player_id_); + EXPECT_TRUE(player_impl_); - EXPECT_FALSE(player_impl_->element_animations()); - EXPECT_FALSE(player_impl_->element_id()); - EXPECT_FALSE(player_->animation_ticker()->needs_push_properties()); + EXPECT_FALSE(player_impl_->element_animations(ticker_id_)); + EXPECT_FALSE(player_impl_->element_id_of_ticker(ticker_id_)); + EXPECT_FALSE(player_->GetTickerById(ticker_id_)->needs_push_properties()); EXPECT_FALSE(timeline_->needs_push_properties()); - player_->AttachElement(element_id_); - EXPECT_EQ(player_->animation_ticker(), GetTickerForElementId(element_id_)); - EXPECT_TRUE(player_->element_animations()); - EXPECT_EQ(player_->element_id(), element_id_); - EXPECT_TRUE(CheckTickerTimelineNeedsPushProperties(true)); + player_->AttachElementForTicker(element_id_, ticker_id_); + EXPECT_EQ(player_->GetTickerById(ticker_id_), + GetTickerForElementId(element_id_)); + EXPECT_TRUE(player_->element_animations(ticker_id_)); + EXPECT_EQ(player_->element_id_of_ticker(ticker_id_), element_id_); + CheckTickerAndTimelineNeedsPushProperties(true, ticker_id_); host_->PushPropertiesTo(host_impl_); - EXPECT_EQ(player_impl_->animation_ticker(), + EXPECT_EQ(player_impl_->GetTickerById(ticker_id_), GetImplTickerForLayerId(element_id_)); - EXPECT_TRUE(player_impl_->element_animations()); - EXPECT_EQ(player_impl_->element_id(), element_id_); - EXPECT_TRUE(CheckTickerTimelineNeedsPushProperties(false)); + EXPECT_TRUE(player_impl_->element_animations(ticker_id_)); + EXPECT_EQ(player_impl_->element_id_of_ticker(ticker_id_), element_id_); + CheckTickerAndTimelineNeedsPushProperties(false, ticker_id_); player_->DetachElement(); EXPECT_FALSE(GetTickerForElementId(element_id_)); - EXPECT_FALSE(player_->element_animations()); - EXPECT_FALSE(player_->element_id()); - EXPECT_TRUE(CheckTickerTimelineNeedsPushProperties(true)); + EXPECT_FALSE(player_->element_animations(ticker_id_)); + EXPECT_FALSE(player_->element_id_of_ticker(ticker_id_)); + CheckTickerAndTimelineNeedsPushProperties(true, ticker_id_); host_->PushPropertiesTo(host_impl_); EXPECT_FALSE(GetImplTickerForLayerId(element_id_)); - EXPECT_FALSE(player_impl_->element_animations()); - EXPECT_FALSE(player_impl_->element_id()); - EXPECT_TRUE(CheckTickerTimelineNeedsPushProperties(false)); + EXPECT_FALSE(player_impl_->element_animations(ticker_id_)); + EXPECT_FALSE(player_impl_->element_id_of_ticker(ticker_id_)); + CheckTickerAndTimelineNeedsPushProperties(false, ticker_id_); timeline_->DetachPlayer(player_); EXPECT_FALSE(player_->animation_timeline()); - EXPECT_FALSE(player_->element_animations()); - EXPECT_FALSE(player_->element_id()); + EXPECT_FALSE(player_->element_animations(ticker_id_)); + EXPECT_FALSE(player_->element_id_of_ticker(ticker_id_)); EXPECT_TRUE(timeline_->needs_push_properties()); - EXPECT_FALSE(player_->animation_ticker()->needs_push_properties()); - + EXPECT_FALSE(player_->GetTickerById(ticker_id_)->needs_push_properties()); host_->PushPropertiesTo(host_impl_); - EXPECT_TRUE(CheckTickerTimelineNeedsPushProperties(false)); + CheckTickerAndTimelineNeedsPushProperties(false, ticker_id_); } TEST_F(AnimationPlayerTest, AttachDetachTimelineIfLayerAttached) { host_->AddAnimationTimeline(timeline_); - EXPECT_FALSE(player_->element_animations()); - EXPECT_FALSE(player_->element_id()); - EXPECT_FALSE(player_->animation_ticker()->needs_push_properties()); + player_->AddTicker(base::MakeUnique<AnimationTicker>(ticker_id_)); + ASSERT_TRUE(player_->GetTickerById(ticker_id_)); - player_->AttachElement(element_id_); + EXPECT_FALSE(player_->GetTickerById(ticker_id_)->element_animations()); + EXPECT_FALSE(player_->GetTickerById(ticker_id_)->element_id()); + EXPECT_FALSE(player_->GetTickerById(ticker_id_)->needs_push_properties()); + + player_->AttachElementForTicker(element_id_, ticker_id_); EXPECT_FALSE(player_->animation_timeline()); EXPECT_FALSE(GetTickerForElementId(element_id_)); - EXPECT_FALSE(player_->element_animations()); - EXPECT_EQ(player_->element_id(), element_id_); - EXPECT_FALSE(player_->animation_ticker()->needs_push_properties()); + EXPECT_FALSE(player_->GetTickerById(ticker_id_)->element_animations()); + EXPECT_EQ(player_->GetTickerById(ticker_id_)->element_id(), element_id_); + EXPECT_FALSE(player_->GetTickerById(ticker_id_)->needs_push_properties()); timeline_->AttachPlayer(player_); EXPECT_EQ(timeline_, player_->animation_timeline()); - EXPECT_EQ(player_->animation_ticker(), GetTickerForElementId(element_id_)); - EXPECT_TRUE(player_->element_animations()); - EXPECT_EQ(player_->element_id(), element_id_); - EXPECT_TRUE(player_->animation_ticker()->needs_push_properties()); + EXPECT_EQ(player_->GetTickerById(ticker_id_), + GetTickerForElementId(element_id_)); + EXPECT_TRUE(player_->GetTickerById(ticker_id_)->element_animations()); + EXPECT_EQ(player_->GetTickerById(ticker_id_)->element_id(), element_id_); + EXPECT_TRUE(player_->GetTickerById(ticker_id_)->needs_push_properties()); // Removing player from timeline detaches layer. timeline_->DetachPlayer(player_); EXPECT_FALSE(player_->animation_timeline()); EXPECT_FALSE(GetTickerForElementId(element_id_)); - EXPECT_FALSE(player_->element_animations()); - EXPECT_FALSE(player_->element_id()); - EXPECT_TRUE(player_->animation_ticker()->needs_push_properties()); + EXPECT_FALSE(player_->GetTickerById(ticker_id_)->element_animations()); + EXPECT_FALSE(player_->GetTickerById(ticker_id_)->element_id()); + EXPECT_TRUE(player_->GetTickerById(ticker_id_)->needs_push_properties()); } TEST_F(AnimationPlayerTest, PropertiesMutate) { @@ -123,12 +256,16 @@ client_impl_.RegisterElement(element_id_, ElementListType::ACTIVE); host_->AddAnimationTimeline(timeline_); + + player_->AddTicker(base::MakeUnique<AnimationTicker>(ticker_id_)); + ASSERT_TRUE(player_->GetTickerById(ticker_id_)); + timeline_->AttachPlayer(player_); - player_->AttachElement(element_id_); - EXPECT_TRUE(CheckTickerTimelineNeedsPushProperties(true)); + player_->AttachElementForTicker(element_id_, ticker_id_); + CheckTickerAndTimelineNeedsPushProperties(true, ticker_id_); host_->PushPropertiesTo(host_impl_); - EXPECT_TRUE(CheckTickerTimelineNeedsPushProperties(false)); + CheckTickerAndTimelineNeedsPushProperties(false, ticker_id_); const float start_opacity = .7f; const float end_opacity = .3f; @@ -141,16 +278,17 @@ const double duration = 1.; - AddOpacityTransitionToPlayer(player_.get(), duration, start_opacity, - end_opacity, false); - AddAnimatedTransformToPlayer(player_.get(), duration, transform_x, - transform_y); - AddAnimatedFilterToPlayer(player_.get(), duration, start_brightness, - end_brightness); - EXPECT_TRUE(CheckTickerTimelineNeedsPushProperties(true)); + AddOpacityTransition(player_.get(), duration, start_opacity, end_opacity, + false, ticker_id_); + + AddAnimatedTransform(player_.get(), duration, transform_x, transform_y, + ticker_id_); + AddAnimatedFilter(player_.get(), duration, start_brightness, end_brightness, + ticker_id_); + CheckTickerAndTimelineNeedsPushProperties(true, ticker_id_); host_->PushPropertiesTo(host_impl_); - EXPECT_TRUE(CheckTickerTimelineNeedsPushProperties(false)); + CheckTickerAndTimelineNeedsPushProperties(false, ticker_id_); EXPECT_FALSE(client_.IsPropertyMutated(element_id_, ElementListType::ACTIVE, TargetProperty::OPACITY)); @@ -171,11 +309,11 @@ base::TimeTicks time; time += base::TimeDelta::FromSecondsD(0.1); TickAnimationsTransferEvents(time, 3u); - EXPECT_TRUE(CheckTickerTimelineNeedsPushProperties(false)); + CheckTickerAndTimelineNeedsPushProperties(false, ticker_id_); time += base::TimeDelta::FromSecondsD(duration); TickAnimationsTransferEvents(time, 3u); - EXPECT_TRUE(CheckTickerTimelineNeedsPushProperties(true)); + CheckTickerAndTimelineNeedsPushProperties(true, ticker_id_); client_.ExpectOpacityPropertyMutated(element_id_, ElementListType::ACTIVE, end_opacity); @@ -207,10 +345,15 @@ client_impl_.RegisterElement(element_id_, ElementListType::PENDING); client_impl_.RegisterElement(element_id_, ElementListType::ACTIVE); - scoped_refptr<AnimationPlayer> player1 = - AnimationPlayer::Create(AnimationIdProvider::NextPlayerId()); - scoped_refptr<AnimationPlayer> player2 = - AnimationPlayer::Create(AnimationIdProvider::NextPlayerId()); + scoped_refptr<AnimationPlayer> player1 = AnimationPlayer::Create(100); + scoped_refptr<AnimationPlayer> player2 = AnimationPlayer::Create(200); + + TickerId ticker_id1 = player1->NextTickerId(); + player1->AddTicker(base::MakeUnique<AnimationTicker>(ticker_id1)); + ASSERT_TRUE(player1->GetTickerById(ticker_id1)); + TickerId ticker_id2 = player2->NextTickerId(); + player2->AddTicker(base::MakeUnique<AnimationTicker>(ticker_id2)); + ASSERT_TRUE(player2->GetTickerById(ticker_id2)); host_->AddAnimationTimeline(timeline_); @@ -224,8 +367,8 @@ player2->set_animation_delegate(&delegate2); // Attach players to the same layer. - player1->AttachElement(element_id_); - player2->AttachElement(element_id_); + player1->AttachElementForTicker(element_id_, ticker_id1); + player2->AttachElementForTicker(element_id_, ticker_id2); const float start_opacity = .7f; const float end_opacity = .3f; @@ -235,10 +378,10 @@ const double duration = 1.; - AddOpacityTransitionToPlayer(player1.get(), duration, start_opacity, - end_opacity, false); - AddAnimatedTransformToPlayer(player2.get(), duration, transform_x, - transform_y); + AddOpacityTransition(player1.get(), duration, start_opacity, end_opacity, + false, ticker_id1); + AddAnimatedTransform(player2.get(), duration, transform_x, transform_y, + ticker_id2); host_->PushPropertiesTo(host_impl_); host_impl_->ActivateAnimations(); @@ -259,8 +402,8 @@ EXPECT_TRUE(delegate2.started()); EXPECT_FALSE(delegate2.finished()); - EXPECT_FALSE(player1->animation_ticker()->needs_push_properties()); - EXPECT_FALSE(player2->animation_ticker()->needs_push_properties()); + EXPECT_FALSE(player1->GetTickerById(ticker_id1)->needs_push_properties()); + EXPECT_FALSE(player2->GetTickerById(ticker_id2)->needs_push_properties()); time += base::TimeDelta::FromSecondsD(duration); TickAnimationsTransferEvents(time, 2u); @@ -268,8 +411,8 @@ EXPECT_TRUE(delegate1.finished()); EXPECT_TRUE(delegate2.finished()); - EXPECT_TRUE(player1->animation_ticker()->needs_push_properties()); - EXPECT_TRUE(player2->animation_ticker()->needs_push_properties()); + EXPECT_TRUE(player1->GetTickerById(ticker_id1)->needs_push_properties()); + EXPECT_TRUE(player2->GetTickerById(ticker_id2)->needs_push_properties()); client_.ExpectOpacityPropertyMutated(element_id_, ElementListType::ACTIVE, end_opacity); @@ -292,33 +435,38 @@ client_impl_.RegisterElement(element_id_, ElementListType::PENDING); client_impl_.RegisterElement(element_id_, ElementListType::ACTIVE); + player_->AddTicker(base::MakeUnique<AnimationTicker>(ticker_id_)); + ASSERT_TRUE(player_->GetTickerById(ticker_id_)); + const double duration = 1.; const float start_opacity = .7f; const float end_opacity = .3f; const int filter_id = - AddAnimatedFilterToPlayer(player_.get(), duration, 0.1f, 0.9f); - AddOpacityTransitionToPlayer(player_.get(), duration, start_opacity, - end_opacity, false); + AddAnimatedFilter(player_.get(), duration, 0.1f, 0.9f, ticker_id_); + AddOpacityTransition(player_.get(), duration, start_opacity, end_opacity, + false, ticker_id_); - EXPECT_FALSE(player_->animation_ticker()->needs_push_properties()); + EXPECT_FALSE(player_->GetTickerById(ticker_id_)->needs_push_properties()); host_->AddAnimationTimeline(timeline_); timeline_->AttachPlayer(player_); - EXPECT_FALSE(player_->animation_ticker()->needs_push_properties()); - EXPECT_FALSE(player_->element_animations()); - player_->RemoveAnimation(filter_id); - EXPECT_FALSE(player_->animation_ticker()->needs_push_properties()); + EXPECT_FALSE(player_->GetTickerById(ticker_id_)->needs_push_properties()); + EXPECT_FALSE(player_->GetTickerById(ticker_id_)->element_animations()); + player_->RemoveAnimationForTicker(filter_id, ticker_id_); + EXPECT_FALSE(player_->GetTickerById(ticker_id_)->needs_push_properties()); - player_->AttachElement(element_id_); + player_->AttachElementForTicker(element_id_, ticker_id_); - EXPECT_TRUE(player_->element_animations()); - EXPECT_FALSE(player_->element_animations()->HasAnyAnimationTargetingProperty( - TargetProperty::FILTER)); - EXPECT_TRUE(player_->element_animations()->HasAnyAnimationTargetingProperty( - TargetProperty::OPACITY)); - EXPECT_TRUE(player_->animation_ticker()->needs_push_properties()); + EXPECT_TRUE(player_->GetTickerById(ticker_id_)->element_animations()); + EXPECT_FALSE(player_->GetTickerById(ticker_id_) + ->element_animations() + ->HasAnyAnimationTargetingProperty(TargetProperty::FILTER)); + EXPECT_TRUE(player_->GetTickerById(ticker_id_) + ->element_animations() + ->HasAnyAnimationTargetingProperty(TargetProperty::OPACITY)); + EXPECT_TRUE(player_->GetTickerById(ticker_id_)->needs_push_properties()); host_->PushPropertiesTo(host_impl_); @@ -357,22 +505,25 @@ TEST_F(AnimationPlayerTest, AddRemoveAnimationCausesSetNeedsCommit) { client_.RegisterElement(element_id_, ElementListType::ACTIVE); host_->AddAnimationTimeline(timeline_); + player_->AddTicker(base::MakeUnique<AnimationTicker>(ticker_id_)); + ASSERT_TRUE(player_->GetTickerById(ticker_id_)); + timeline_->AttachPlayer(player_); - player_->AttachElement(element_id_); + player_->AttachElementForTicker(element_id_, ticker_id_); EXPECT_FALSE(client_.mutators_need_commit()); const int animation_id = - AddOpacityTransitionToPlayer(player_.get(), 1., .7f, .3f, false); + AddOpacityTransition(player_.get(), 1., .7f, .3f, false, ticker_id_); EXPECT_TRUE(client_.mutators_need_commit()); client_.set_mutators_need_commit(false); - player_->PauseAnimation(animation_id, 1.); + player_->PauseAnimationForTicker(animation_id, 1., ticker_id_); EXPECT_TRUE(client_.mutators_need_commit()); client_.set_mutators_need_commit(false); - player_->RemoveAnimation(animation_id); + player_->RemoveAnimationForTicker(animation_id, ticker_id_); EXPECT_TRUE(client_.mutators_need_commit()); client_.set_mutators_need_commit(false); } @@ -381,50 +532,63 @@ // impl-thread player must be switched as well. TEST_F(AnimationPlayerTest, SwitchToLayer) { host_->AddAnimationTimeline(timeline_); + player_->AddTicker(base::MakeUnique<AnimationTicker>(ticker_id_)); timeline_->AttachPlayer(player_); - player_->AttachElement(element_id_); + player_->AttachElementForTicker(element_id_, ticker_id_); host_->PushPropertiesTo(host_impl_); - GetImplTimelineAndPlayerByID(); + timeline_impl_ = host_impl_->GetTimelineById(timeline_id_); + EXPECT_TRUE(timeline_impl_); + player_impl_ = timeline_impl_->GetPlayerById(player_id_); + EXPECT_TRUE(player_impl_); - EXPECT_EQ(player_->animation_ticker(), GetTickerForElementId(element_id_)); - EXPECT_TRUE(player_->element_animations()); - EXPECT_EQ(player_->element_id(), element_id_); + EXPECT_EQ(player_->GetTickerById(ticker_id_), + GetTickerForElementId(element_id_)); + EXPECT_TRUE(player_->GetTickerById(ticker_id_)->element_animations()); + EXPECT_EQ(player_->GetTickerById(ticker_id_)->element_id(), element_id_); - EXPECT_EQ(player_impl_->animation_ticker(), + timeline_impl_ = host_impl_->GetTimelineById(timeline_id_); + EXPECT_TRUE(timeline_impl_); + player_impl_ = timeline_impl_->GetPlayerById(player_id_); + EXPECT_TRUE(player_impl_); + EXPECT_EQ(player_impl_->GetTickerById(ticker_id_), GetImplTickerForLayerId(element_id_)); - EXPECT_TRUE(player_impl_->element_animations()); - EXPECT_EQ(player_impl_->element_id(), element_id_); - EXPECT_TRUE(CheckTickerTimelineNeedsPushProperties(false)); + EXPECT_TRUE(player_impl_->GetTickerById(ticker_id_)->element_animations()); + EXPECT_EQ(player_impl_->GetTickerById(ticker_id_)->element_id(), element_id_); + CheckTickerAndTimelineNeedsPushProperties(false, ticker_id_); const ElementId new_element_id(NextTestLayerId()); player_->DetachElement(); - player_->AttachElement(new_element_id); + player_->AttachElementForTicker(new_element_id, ticker_id_); - EXPECT_EQ(player_->animation_ticker(), GetTickerForElementId(new_element_id)); - EXPECT_TRUE(player_->element_animations()); - EXPECT_EQ(player_->element_id(), new_element_id); - EXPECT_TRUE(CheckTickerTimelineNeedsPushProperties(true)); + EXPECT_EQ(player_->GetTickerById(ticker_id_), + GetTickerForElementId(new_element_id)); + EXPECT_TRUE(player_->GetTickerById(ticker_id_)->element_animations()); + EXPECT_EQ(player_->GetTickerById(ticker_id_)->element_id(), new_element_id); + CheckTickerAndTimelineNeedsPushProperties(true, ticker_id_); host_->PushPropertiesTo(host_impl_); - EXPECT_EQ(player_impl_->animation_ticker(), + EXPECT_EQ(player_impl_->GetTickerById(ticker_id_), GetImplTickerForLayerId(new_element_id)); - EXPECT_TRUE(player_impl_->element_animations()); - EXPECT_EQ(player_impl_->element_id(), new_element_id); + EXPECT_TRUE(player_impl_->GetTickerById(ticker_id_)->element_animations()); + EXPECT_EQ(player_impl_->GetTickerById(ticker_id_)->element_id(), + new_element_id); } TEST_F(AnimationPlayerTest, ToString) { - player_->AttachElement(element_id_); + player_->AddTicker(base::MakeUnique<AnimationTicker>(ticker_id_)); + player_->AttachElementForTicker(element_id_, ticker_id_); EXPECT_EQ( base::StringPrintf("AnimationPlayer{id=%d, element_id=%s, animations=[]}", player_->id(), element_id_.ToString().c_str()), player_->ToString()); - player_->AddAnimation( + player_->AddAnimationForTicker( Animation::Create(std::make_unique<FakeFloatAnimationCurve>(15), 42, 73, - TargetProperty::OPACITY)); + TargetProperty::OPACITY), + ticker_id_); EXPECT_EQ(base::StringPrintf("AnimationPlayer{id=%d, element_id=%s, " "animations=[Animation{id=42, " "group=73, target_property_id=1, " @@ -432,9 +596,10 @@ player_->id(), element_id_.ToString().c_str()), player_->ToString()); - player_->AddAnimation( + player_->AddAnimationForTicker( Animation::Create(std::make_unique<FakeFloatAnimationCurve>(18), 45, 76, - TargetProperty::BOUNDS)); + TargetProperty::BOUNDS), + ticker_id_); EXPECT_EQ( base::StringPrintf( "AnimationPlayer{id=%d, element_id=%s, " @@ -445,6 +610,323 @@ "target_property_id=5, run_state=WAITING_FOR_TARGET_AVAILABILITY}]}", player_->id(), element_id_.ToString().c_str()), player_->ToString()); + + TickerId second_ticker_id = player_->NextTickerId(); + ElementId second_element_id(NextTestLayerId()); + player_->AddTicker(base::MakeUnique<AnimationTicker>(second_ticker_id)); + player_->AttachElementForTicker(second_element_id, second_ticker_id); + player_->AddAnimationForTicker( + Animation::Create(std::make_unique<FakeFloatAnimationCurve>(20), 48, 78, + TargetProperty::OPACITY), + second_ticker_id); + EXPECT_EQ( + base::StringPrintf( + "AnimationPlayer{id=%d, element_id=%s, " + "animations=[Animation{id=42, " + "group=73, target_property_id=1, " + "run_state=WAITING_FOR_TARGET_AVAILABILITY}, Animation{id=45, " + "group=76, " + "target_property_id=5, run_state=WAITING_FOR_TARGET_AVAILABILITY}]" + ", element_id=%s, " + "animations=[Animation{id=48, " + "group=78, target_property_id=1, " + "run_state=WAITING_FOR_TARGET_AVAILABILITY}]}", + player_->id(), element_id_.ToString().c_str(), + second_element_id.ToString().c_str()), + player_->ToString()); +} + +TEST_F(AnimationPlayerTest, AddTwoTickersFromTheSameElementToOnePlayerTest) { + host_->AddAnimationTimeline(timeline_); + EXPECT_TRUE(timeline_->needs_push_properties()); + + TickerId ticker_id1 = player_->NextTickerId(); + + player_->AddTicker(base::MakeUnique<AnimationTicker>(ticker_id1)); + ASSERT_TRUE(player_->GetTickerById(ticker_id1)); + EXPECT_FALSE(player_->GetTickerById(ticker_id1)->needs_push_properties()); + + TickerId ticker_id2 = player_->NextTickerId(); + player_->AddTicker(base::MakeUnique<AnimationTicker>(ticker_id2)); + ASSERT_TRUE(player_->GetTickerById(ticker_id2)); + EXPECT_FALSE(player_->GetTickerById(ticker_id2)->needs_push_properties()); + + timeline_->AttachPlayer(player_); + EXPECT_FALSE(player_->element_animations(ticker_id1)); + EXPECT_FALSE(player_->element_animations(ticker_id2)); + EXPECT_FALSE(player_->element_id_of_ticker(ticker_id1)); + EXPECT_FALSE(player_->element_id_of_ticker(ticker_id2)); + EXPECT_TRUE(timeline_->needs_push_properties()); + EXPECT_FALSE(player_->GetTickerById(ticker_id1)->needs_push_properties()); + EXPECT_FALSE(player_->GetTickerById(ticker_id2)->needs_push_properties()); + + host_->PushPropertiesTo(host_impl_); + + timeline_impl_ = host_impl_->GetTimelineById(timeline_id_); + EXPECT_TRUE(timeline_impl_); + player_impl_ = timeline_impl_->GetPlayerById(player_id_); + EXPECT_TRUE(player_impl_); + + player_->AttachElementForTicker(element_id_, ticker_id1); + EXPECT_TRUE(player_->element_animations(ticker_id1)); + EXPECT_EQ(player_->element_id_of_ticker(ticker_id1), element_id_); + EXPECT_TRUE(player_->GetTickerById(ticker_id1)->needs_push_properties()); + + EXPECT_FALSE(player_->element_animations(ticker_id2)); + EXPECT_NE(player_->element_id_of_ticker(ticker_id2), element_id_); + EXPECT_FALSE(player_->GetTickerById(ticker_id2)->needs_push_properties()); + + const scoped_refptr<ElementAnimations> element_animations = + host_->GetElementAnimationsForElementId(element_id_); + EXPECT_TRUE(element_animations->tickers_list().HasObserver( + player_->GetTickerById(ticker_id1))); + EXPECT_FALSE(element_animations->tickers_list().HasObserver( + player_->GetTickerById(ticker_id2))); + + player_->AttachElementForTicker(element_id_, ticker_id2); + EXPECT_TRUE(player_->element_animations(ticker_id2)); + EXPECT_EQ(player_->element_id_of_ticker(ticker_id2), element_id_); + EXPECT_TRUE(player_->GetTickerById(ticker_id2)->needs_push_properties()); + + EXPECT_TRUE(element_animations->tickers_list().HasObserver( + player_->GetTickerById(ticker_id2))); + + host_->PushPropertiesTo(host_impl_); + + const scoped_refptr<ElementAnimations> element_animations_impl = + host_impl_->GetElementAnimationsForElementId(element_id_); + EXPECT_TRUE(element_animations_impl->tickers_list().HasObserver( + player_impl_->GetTickerById(ticker_id1))); + EXPECT_TRUE(element_animations_impl->tickers_list().HasObserver( + player_impl_->GetTickerById(ticker_id2))); + + EXPECT_TRUE(player_impl_->element_animations(ticker_id1)); + EXPECT_EQ(player_impl_->element_id_of_ticker(ticker_id1), element_id_); + EXPECT_TRUE(player_impl_->element_animations(ticker_id2)); + EXPECT_EQ(player_impl_->element_id_of_ticker(ticker_id2), element_id_); + + player_->DetachElement(); + EXPECT_FALSE(player_->element_animations(ticker_id1)); + EXPECT_FALSE(player_->element_id_of_ticker(ticker_id1)); + EXPECT_FALSE(element_animations->tickers_list().HasObserver( + player_->GetTickerById(ticker_id1))); + + EXPECT_FALSE(player_->element_animations(ticker_id2)); + EXPECT_FALSE(player_->element_id_of_ticker(ticker_id2)); + EXPECT_FALSE(element_animations->tickers_list().HasObserver( + player_->GetTickerById(ticker_id2))); + + EXPECT_TRUE(element_animations_impl->tickers_list().HasObserver( + player_impl_->GetTickerById(ticker_id1))); + EXPECT_TRUE(element_animations_impl->tickers_list().HasObserver( + player_impl_->GetTickerById(ticker_id2))); + + host_->PushPropertiesTo(host_impl_); + + EXPECT_FALSE(player_impl_->element_animations(ticker_id1)); + EXPECT_FALSE(player_impl_->element_id_of_ticker(ticker_id1)); + EXPECT_FALSE(element_animations_impl->tickers_list().HasObserver( + player_impl_->GetTickerById(ticker_id1))); + EXPECT_FALSE(player_impl_->element_animations(ticker_id2)); + EXPECT_FALSE(player_impl_->element_id_of_ticker(ticker_id2)); + EXPECT_FALSE(element_animations_impl->tickers_list().HasObserver( + player_impl_->GetTickerById(ticker_id2))); + + timeline_->DetachPlayer(player_); + EXPECT_FALSE(player_->animation_timeline()); + + EXPECT_FALSE(player_->element_animations(ticker_id1)); + EXPECT_FALSE(player_->element_id_of_ticker(ticker_id1)); + EXPECT_FALSE(player_->element_animations(ticker_id2)); + EXPECT_FALSE(player_->element_id_of_ticker(ticker_id2)); + + EXPECT_TRUE(timeline_->needs_push_properties()); + EXPECT_FALSE(player_->GetTickerById(ticker_id1)->needs_push_properties()); + EXPECT_FALSE(player_->GetTickerById(ticker_id2)->needs_push_properties()); +} + +TEST_F(AnimationPlayerTest, AddTwoTickersFromDifferentElementsToOnePlayerTest) { + host_->AddAnimationTimeline(timeline_); + + TickerId ticker_id1 = player_->NextTickerId(); + + player_->AddTicker(base::MakeUnique<AnimationTicker>(ticker_id1)); + ASSERT_TRUE(player_->GetTickerById(ticker_id1)); + EXPECT_FALSE(player_->GetTickerById(ticker_id1)->needs_push_properties()); + + TickerId ticker_id2 = player_->NextTickerId(); + player_->AddTicker(base::MakeUnique<AnimationTicker>(ticker_id2)); + ASSERT_TRUE(player_->GetTickerById(ticker_id2)); + EXPECT_FALSE(player_->GetTickerById(ticker_id2)->needs_push_properties()); + + EXPECT_FALSE(player_->element_animations(ticker_id1)); + EXPECT_FALSE(player_->element_animations(ticker_id2)); + EXPECT_FALSE(player_->element_id_of_ticker(ticker_id1)); + EXPECT_FALSE(player_->element_id_of_ticker(ticker_id2)); + EXPECT_TRUE(timeline_->needs_push_properties()); + EXPECT_FALSE(player_->GetTickerById(ticker_id1)->needs_push_properties()); + EXPECT_FALSE(player_->GetTickerById(ticker_id2)->needs_push_properties()); + + ElementId element1(NextTestLayerId()); + ElementId element2(NextTestLayerId()); + + player_->AttachElementForTicker(element1, ticker_id1); + player_->AttachElementForTicker(element2, ticker_id2); + + EXPECT_FALSE(player_->animation_timeline()); + + scoped_refptr<ElementAnimations> element_animations = + host_->GetElementAnimationsForElementId(element1); + EXPECT_FALSE(element_animations); + EXPECT_FALSE(player_->GetTickerById(ticker_id1)->element_animations()); + EXPECT_EQ(player_->GetTickerById(ticker_id1)->element_id(), element1); + EXPECT_FALSE(player_->GetTickerById(ticker_id1)->needs_push_properties()); + + timeline_->AttachPlayer(player_); + EXPECT_EQ(timeline_, player_->animation_timeline()); + EXPECT_TRUE(player_->GetTickerById(ticker_id1)->element_animations()); + EXPECT_EQ(player_->GetTickerById(ticker_id1)->element_id(), element1); + EXPECT_TRUE(player_->GetTickerById(ticker_id1)->needs_push_properties()); + + element_animations = host_->GetElementAnimationsForElementId(element1); + EXPECT_TRUE(element_animations->tickers_list().HasObserver( + player_->GetTickerById(ticker_id1))); + EXPECT_FALSE(element_animations->tickers_list().HasObserver( + player_->GetTickerById(ticker_id2))); + + element_animations = host_->GetElementAnimationsForElementId(element2); + EXPECT_TRUE(element_animations->tickers_list().HasObserver( + player_->GetTickerById(ticker_id2))); + + player_->DetachElement(); + EXPECT_TRUE(player_->animation_timeline()); + EXPECT_FALSE(element_animations->tickers_list().HasObserver( + player_->GetTickerById(ticker_id2))); + EXPECT_FALSE(player_->GetTickerById(ticker_id1)->element_animations()); + EXPECT_FALSE(player_->GetTickerById(ticker_id1)->element_id()); + EXPECT_TRUE(player_->GetTickerById(ticker_id1)->needs_push_properties()); + EXPECT_FALSE(player_->GetTickerById(ticker_id2)->element_animations()); + EXPECT_FALSE(player_->GetTickerById(ticker_id2)->element_id()); + EXPECT_TRUE(player_->GetTickerById(ticker_id2)->needs_push_properties()); + + // Removing player from timeline detaches layer. + timeline_->DetachPlayer(player_); + EXPECT_FALSE(player_->animation_timeline()); + EXPECT_FALSE(player_->GetTickerById(ticker_id1)->element_animations()); + EXPECT_FALSE(player_->GetTickerById(ticker_id1)->element_id()); + EXPECT_TRUE(player_->GetTickerById(ticker_id1)->needs_push_properties()); + EXPECT_FALSE(player_->GetTickerById(ticker_id2)->element_animations()); + EXPECT_FALSE(player_->GetTickerById(ticker_id2)->element_id()); + EXPECT_TRUE(player_->GetTickerById(ticker_id2)->needs_push_properties()); +} + +TEST_F(AnimationPlayerTest, TickingAnimationsFromTwoTickers) { + TestAnimationDelegate delegate1; + + client_.RegisterElement(element_id_, ElementListType::ACTIVE); + client_impl_.RegisterElement(element_id_, ElementListType::PENDING); + client_impl_.RegisterElement(element_id_, ElementListType::ACTIVE); + + TickerId ticker_id1 = player_->NextTickerId(); + + player_->AddTicker(base::MakeUnique<AnimationTicker>(ticker_id1)); + ASSERT_TRUE(player_->GetTickerById(ticker_id1)); + EXPECT_FALSE(player_->GetTickerById(ticker_id1)->needs_push_properties()); + + TickerId ticker_id2 = player_->NextTickerId(); + player_->AddTicker(base::MakeUnique<AnimationTicker>(ticker_id2)); + ASSERT_TRUE(player_->GetTickerById(ticker_id2)); + EXPECT_FALSE(player_->GetTickerById(ticker_id2)->needs_push_properties()); + + host_->AddAnimationTimeline(timeline_); + + timeline_->AttachPlayer(player_); + EXPECT_TRUE(timeline_->needs_push_properties()); + + player_->set_animation_delegate(&delegate1); + + player_->AttachElementForTicker(element_id_, ticker_id1); + player_->AttachElementForTicker(element_id_, ticker_id2); + + const float start_opacity = .7f; + const float end_opacity = .3f; + + const int transform_x = 10; + const int transform_y = 20; + + const double duration = 1.; + + AddOpacityTransition(player_.get(), duration, start_opacity, end_opacity, + false, ticker_id1); + AddAnimatedTransform(player_.get(), duration, transform_x, transform_y, + ticker_id2); + host_->PushPropertiesTo(host_impl_); + host_impl_->ActivateAnimations(); + + EXPECT_FALSE(delegate1.started()); + EXPECT_FALSE(delegate1.finished()); + + base::TimeTicks time; + time += base::TimeDelta::FromSecondsD(0.1); + TickAnimationsTransferEvents(time, 2u); + + EXPECT_TRUE(delegate1.started()); + EXPECT_FALSE(delegate1.finished()); + + EXPECT_FALSE(player_->GetTickerById(ticker_id1)->needs_push_properties()); + EXPECT_FALSE(player_->GetTickerById(ticker_id2)->needs_push_properties()); + + time += base::TimeDelta::FromSecondsD(duration); + TickAnimationsTransferEvents(time, 2u); + + EXPECT_TRUE(delegate1.finished()); + + EXPECT_TRUE(player_->GetTickerById(ticker_id1)->needs_push_properties()); + EXPECT_TRUE(player_->GetTickerById(ticker_id2)->needs_push_properties()); + + client_.ExpectOpacityPropertyMutated(element_id_, ElementListType::ACTIVE, + end_opacity); + client_.ExpectTransformPropertyMutated(element_id_, ElementListType::ACTIVE, + transform_x, transform_y); + + client_impl_.ExpectOpacityPropertyMutated( + element_id_, ElementListType::ACTIVE, end_opacity); + client_impl_.ExpectTransformPropertyMutated( + element_id_, ElementListType::ACTIVE, transform_x, transform_y); + + client_impl_.ExpectOpacityPropertyMutated( + element_id_, ElementListType::PENDING, end_opacity); + client_impl_.ExpectTransformPropertyMutated( + element_id_, ElementListType::PENDING, transform_x, transform_y); +} + +TEST_F(AnimationPlayerTest, TickerSyncToImplTest) { + host_->AddAnimationTimeline(timeline_); + EXPECT_TRUE(timeline_->needs_push_properties()); + timeline_->AttachPlayer(player_); + + TickerId ticker_id1 = player_->NextTickerId(); + player_->AddTicker(base::MakeUnique<AnimationTicker>(ticker_id1)); + EXPECT_TRUE(player_->GetTickerById(ticker_id1)); + EXPECT_FALSE(player_->GetTickerById(ticker_id1)->needs_push_properties()); + + host_->PushPropertiesTo(host_impl_); + + timeline_impl_ = host_impl_->GetTimelineById(timeline_id_); + EXPECT_TRUE(timeline_impl_); + player_impl_ = timeline_impl_->GetPlayerById(player_id_); + EXPECT_TRUE(player_impl_); + EXPECT_TRUE(player_impl_->GetTickerById(ticker_id1)); + + EXPECT_FALSE(timeline_->needs_push_properties()); + + TickerId ticker_id2 = player_->NextTickerId(); + player_->AddTicker(base::MakeUnique<AnimationTicker>(ticker_id2)); + EXPECT_TRUE(timeline_->needs_push_properties()); + + host_->PushPropertiesTo(host_impl_); + + EXPECT_TRUE(player_impl_->GetTickerById(ticker_id2)); } } // namespace
diff --git a/cc/animation/animation_ticker.cc b/cc/animation/animation_ticker.cc index e868fb5..9b2cdb9 100644 --- a/cc/animation/animation_ticker.cc +++ b/cc/animation/animation_ticker.cc
@@ -16,20 +16,27 @@ namespace cc { -AnimationTicker::AnimationTicker(AnimationPlayer* animation_player) - : animation_player_(animation_player), +AnimationTicker::AnimationTicker(TickerId id) + : animation_player_(), + id_(id), element_animations_(), needs_to_start_animations_(false), scroll_offset_animation_was_interrupted_(false), is_ticking_(false), - needs_push_properties_(false) { - DCHECK(animation_player_); -} + needs_push_properties_(false) {} AnimationTicker::~AnimationTicker() { DCHECK(!has_bound_element_animations()); } +std::unique_ptr<AnimationTicker> AnimationTicker::Create(TickerId id) { + return base::MakeUnique<AnimationTicker>(id); +} + +std::unique_ptr<AnimationTicker> AnimationTicker::CreateImplInstance() const { + return AnimationTicker::Create(id()); +} + void AnimationTicker::SetNeedsPushProperties() { needs_push_properties_ = true; @@ -702,14 +709,18 @@ return; needs_push_properties_ = false; - // Synchronize the animation target between main and impl size. + // Synchronize the animation target between main and impl side. if (element_id_ != animation_ticker_impl->element_id_) { // We have to detach/attach via the AnimationPlayer as it may need to inform // the host as well. - if (animation_ticker_impl->has_attached_element()) - animation_ticker_impl->animation_player_->DetachElement(); - if (element_id_) - animation_ticker_impl->animation_player_->AttachElement(element_id_); + if (animation_ticker_impl->has_attached_element()) { + animation_ticker_impl->animation_player_->DetachElementForTicker( + animation_ticker_impl->element_id_, animation_ticker_impl->id_); + } + if (element_id_) { + animation_ticker_impl->animation_player_->AttachElementForTicker( + element_id_, id_); + } } // If neither main nor impl have any animations, there is nothing further to @@ -743,6 +754,10 @@ animation_ticker_impl->UpdateTickingState(UpdateTickingType::NORMAL); } +void AnimationTicker::SetAnimationPlayer(AnimationPlayer* animation_player) { + animation_player_ = animation_player; +} + std::string AnimationTicker::AnimationsToString() const { std::string str; for (size_t i = 0; i < animations_.size(); i++) {
diff --git a/cc/animation/animation_ticker.h b/cc/animation/animation_ticker.h index b55d612..7270d99 100644 --- a/cc/animation/animation_ticker.h +++ b/cc/animation/animation_ticker.h
@@ -26,6 +26,8 @@ class AnimationPlayer; struct PropertyAnimationState; +typedef size_t TickerId; + // An AnimationTicker owns a group of Animations for a single target (identified // by a ElementId). It is responsible for managing the animations' running // states (starting, running, paused, etc), as well as ticking the animations @@ -42,9 +44,12 @@ virtual base::TimeTicks GetTimeForAnimation(const Animation&) const = 0; }; - explicit AnimationTicker(AnimationPlayer* animation_player); + explicit AnimationTicker(TickerId id); ~AnimationTicker(); + static std::unique_ptr<AnimationTicker> Create(TickerId id); + std::unique_ptr<AnimationTicker> CreateImplInstance() const; + // ElementAnimations object where this controller is listed. scoped_refptr<ElementAnimations> element_animations() const { return element_animations_; @@ -85,6 +90,7 @@ Animation* animation, AnimationTarget* target); void RemoveFromTicking(); + bool is_ticking() const { return is_ticking_; } void UpdateState(bool start_ready_animations, AnimationEvents* events); void UpdateTickingState(UpdateTickingType type); @@ -155,7 +161,10 @@ AnimationTicker* element_ticker_impl) const; void PushPropertiesTo(AnimationTicker* animation_ticker_impl); + void SetAnimationPlayer(AnimationPlayer* animation_player); + std::string AnimationsToString() const; + TickerId id() const { return id_; } private: void StartAnimations(base::TimeTicks monotonic_time); @@ -169,6 +178,8 @@ std::vector<std::unique_ptr<Animation>> animations_; AnimationPlayer* animation_player_; + + TickerId id_; ElementId element_id_; // element_animations_ is non-null if controller is attached to an element.
diff --git a/cc/animation/animation_timeline.cc b/cc/animation/animation_timeline.cc index 8b380e85..0c7147e 100644 --- a/cc/animation/animation_timeline.cc +++ b/cc/animation/animation_timeline.cc
@@ -116,7 +116,7 @@ } void AnimationTimeline::ErasePlayer(scoped_refptr<AnimationPlayer> player) { - if (player->element_animations()) + if (player->has_element_animations()) player->DetachElement(); player->SetAnimationTimeline(nullptr); player->SetAnimationHost(nullptr);
diff --git a/cc/animation/animation_timeline_unittest.cc b/cc/animation/animation_timeline_unittest.cc index cb9a896b..30788882 100644 --- a/cc/animation/animation_timeline_unittest.cc +++ b/cc/animation/animation_timeline_unittest.cc
@@ -6,7 +6,7 @@ #include "cc/animation/animation_host.h" #include "cc/animation/animation_id_provider.h" -#include "cc/animation/animation_player.h" +#include "cc/animation/single_ticker_animation_player.h" #include "cc/test/animation_test_common.h" #include "testing/gmock/include/gmock/gmock.h" #include "testing/gtest/include/gtest/gtest.h" @@ -34,7 +34,8 @@ host_impl->AddAnimationTimeline(timeline_impl.get()); EXPECT_TRUE(timeline_impl->animation_host()); - scoped_refptr<AnimationPlayer> player(AnimationPlayer::Create(player_id)); + scoped_refptr<SingleTickerAnimationPlayer> player( + SingleTickerAnimationPlayer::Create(player_id)); timeline->AttachPlayer(player.get()); EXPECT_TRUE(player->animation_timeline()); @@ -78,9 +79,11 @@ host->AddAnimationTimeline(timeline.get()); host_impl->AddAnimationTimeline(timeline_impl.get()); - scoped_refptr<AnimationPlayer> player1(AnimationPlayer::Create(player_id1)); + scoped_refptr<SingleTickerAnimationPlayer> player1( + SingleTickerAnimationPlayer::Create(player_id1)); timeline->AttachPlayer(player1.get()); - scoped_refptr<AnimationPlayer> player2(AnimationPlayer::Create(player_id2)); + scoped_refptr<SingleTickerAnimationPlayer> player2( + SingleTickerAnimationPlayer::Create(player_id2)); timeline->AttachPlayer(player2.get()); timeline->PushPropertiesTo(timeline_impl.get());
diff --git a/cc/animation/element_animations_unittest.cc b/cc/animation/element_animations_unittest.cc index 1467554..f9daeeb 100644 --- a/cc/animation/element_animations_unittest.cc +++ b/cc/animation/element_animations_unittest.cc
@@ -9,11 +9,11 @@ #include "cc/animation/animation_events.h" #include "cc/animation/animation_host.h" #include "cc/animation/animation_id_provider.h" -#include "cc/animation/animation_player.h" #include "cc/animation/animation_ticker.h" #include "cc/animation/animation_timeline.h" #include "cc/animation/keyframed_animation_curve.h" #include "cc/animation/scroll_offset_animation_curve.h" +#include "cc/animation/single_ticker_animation_player.h" #include "cc/animation/transform_operations.h" #include "cc/test/animation_test_common.h" #include "cc/test/animation_timelines_test_common.h" @@ -41,12 +41,11 @@ void SetUp() override { AnimationTimelinesTest::SetUp(); - ticker_ = player_->animation_ticker(); + player_ = SingleTickerAnimationPlayer::Create(player_id_); } void CreateImplTimelineAndPlayer() override { AnimationTimelinesTest::CreateImplTimelineAndPlayer(); - ticker_impl_ = player_impl_->animation_ticker(); } std::unique_ptr<AnimationEvents> CreateEventsForTesting() { @@ -54,10 +53,6 @@ return base::WrapUnique( static_cast<AnimationEvents*>(mutator_events.release())); } - - protected: - AnimationTicker* ticker_; - AnimationTicker* ticker_impl_; }; // See animation_player_unittest.cc for integration with AnimationPlayer. @@ -95,36 +90,41 @@ // kill layer on main thread. client_.UnregisterElement(element_id_, ElementListType::ACTIVE); - EXPECT_EQ(element_animations_, player_->element_animations()); + EXPECT_EQ(element_animations_, + player_->animation_ticker()->element_animations()); EXPECT_FALSE(element_animations_->has_element_in_active_list()); EXPECT_FALSE(element_animations_->has_element_in_pending_list()); // Sync doesn't detach LayerImpl. PushProperties(); - EXPECT_EQ(element_animations_impl_, player_impl_->element_animations()); + EXPECT_EQ(element_animations_impl_, + player_impl_->animation_ticker()->element_animations()); EXPECT_TRUE(element_animations_impl_->has_element_in_active_list()); EXPECT_TRUE(element_animations_impl_->has_element_in_pending_list()); // Kill layer on impl thread in pending tree. client_impl_.UnregisterElement(element_id_, ElementListType::PENDING); - EXPECT_EQ(element_animations_impl_, player_impl_->element_animations()); + EXPECT_EQ(element_animations_impl_, + player_impl_->animation_ticker()->element_animations()); EXPECT_TRUE(element_animations_impl_->has_element_in_active_list()); EXPECT_FALSE(element_animations_impl_->has_element_in_pending_list()); // Kill layer on impl thread in active tree. client_impl_.UnregisterElement(element_id_, ElementListType::ACTIVE); - EXPECT_EQ(element_animations_impl_, player_impl_->element_animations()); + EXPECT_EQ(element_animations_impl_, + player_impl_->animation_ticker()->element_animations()); EXPECT_FALSE(element_animations_impl_->has_element_in_active_list()); EXPECT_FALSE(element_animations_impl_->has_element_in_pending_list()); // Sync doesn't change anything. PushProperties(); - EXPECT_EQ(element_animations_impl_, player_impl_->element_animations()); + EXPECT_EQ(element_animations_impl_, + player_impl_->animation_ticker()->element_animations()); EXPECT_FALSE(element_animations_impl_->has_element_in_active_list()); EXPECT_FALSE(element_animations_impl_->has_element_in_pending_list()); player_->DetachElement(); - EXPECT_FALSE(player_->element_animations()); + EXPECT_FALSE(player_->animation_ticker()->element_animations()); // Release ptrs now to test the order of destruction. ReleaseRefPtrs(); @@ -139,13 +139,14 @@ // Perform attachment separately. player_->AttachElement(element_id_); - element_animations_ = player_->element_animations(); + element_animations_ = player_->animation_ticker()->element_animations(); EXPECT_FALSE(element_animations_->has_element_in_active_list()); EXPECT_FALSE(element_animations_->has_element_in_pending_list()); PushProperties(); - element_animations_impl_ = player_impl_->element_animations(); + element_animations_impl_ = + player_impl_->animation_ticker()->element_animations(); EXPECT_FALSE(element_animations_impl_->has_element_in_active_list()); EXPECT_FALSE(element_animations_impl_->has_element_in_pending_list()); @@ -170,13 +171,13 @@ player_->AttachElement(element_id_); scoped_refptr<ElementAnimations> element_animations = - player_->element_animations(); + player_->animation_ticker()->element_animations(); EXPECT_TRUE(element_animations); - scoped_refptr<AnimationPlayer> player1 = - AnimationPlayer::Create(AnimationIdProvider::NextPlayerId()); - scoped_refptr<AnimationPlayer> player2 = - AnimationPlayer::Create(AnimationIdProvider::NextPlayerId()); + scoped_refptr<SingleTickerAnimationPlayer> player1 = + SingleTickerAnimationPlayer::Create(AnimationIdProvider::NextPlayerId()); + scoped_refptr<SingleTickerAnimationPlayer> player2 = + SingleTickerAnimationPlayer::Create(AnimationIdProvider::NextPlayerId()); timeline_->AttachPlayer(player1); timeline_->AttachPlayer(player2); @@ -185,14 +186,16 @@ player1->AttachElement(element_id_); player2->AttachElement(element_id_); - EXPECT_EQ(element_animations, player1->element_animations()); - EXPECT_EQ(element_animations, player2->element_animations()); + EXPECT_EQ(element_animations, + player1->animation_ticker()->element_animations()); + EXPECT_EQ(element_animations, + player2->animation_ticker()->element_animations()); PushProperties(); GetImplTimelineAndPlayerByID(); scoped_refptr<ElementAnimations> element_animations_impl = - player_impl_->element_animations(); + player_impl_->animation_ticker()->element_animations(); EXPECT_TRUE(element_animations_impl); const ElementAnimations::TickersList& tickers = @@ -203,12 +206,15 @@ EXPECT_EQ(3, list_size_before); player2->DetachElement(); - EXPECT_FALSE(player2->element_animations()); - EXPECT_EQ(element_animations, player_->element_animations()); - EXPECT_EQ(element_animations, player1->element_animations()); + EXPECT_FALSE(player2->animation_ticker()->element_animations()); + EXPECT_EQ(element_animations, + player_->animation_ticker()->element_animations()); + EXPECT_EQ(element_animations, + player1->animation_ticker()->element_animations()); PushProperties(); - EXPECT_EQ(element_animations_impl, player_impl_->element_animations()); + EXPECT_EQ(element_animations_impl, + player_impl_->animation_ticker()->element_animations()); int list_size_after = 0; for (auto it = tickers.begin(); it != tickers.end(); ++it) @@ -226,17 +232,21 @@ int animation_id = AddOpacityTransitionToPlayer(player_.get(), 1, 0, 1, false); - EXPECT_TRUE(ticker_->GetAnimationById(animation_id)); - EXPECT_EQ(Animation::WAITING_FOR_TARGET_AVAILABILITY, - ticker_->GetAnimationById(animation_id)->run_state()); - EXPECT_FALSE(ticker_impl_->GetAnimationById(animation_id)); + EXPECT_TRUE(player_->animation_ticker()->GetAnimationById(animation_id)); + EXPECT_EQ( + Animation::WAITING_FOR_TARGET_AVAILABILITY, + player_->animation_ticker()->GetAnimationById(animation_id)->run_state()); + EXPECT_FALSE( + player_impl_->animation_ticker()->GetAnimationById(animation_id)); PushProperties(); player_impl_->ActivateAnimations(); - EXPECT_TRUE(ticker_impl_->GetAnimationById(animation_id)); + EXPECT_TRUE(player_impl_->animation_ticker()->GetAnimationById(animation_id)); EXPECT_EQ(Animation::WAITING_FOR_TARGET_AVAILABILITY, - ticker_impl_->GetAnimationById(animation_id)->run_state()); + player_impl_->animation_ticker() + ->GetAnimationById(animation_id) + ->run_state()); } TEST_F(ElementAnimationsTest, @@ -265,11 +275,11 @@ std::move(curve_fixed), animation1_id, 0, TargetProperty::SCROLL_OFFSET)); player_->AddAnimation(std::move(animation_fixed)); PushProperties(); - EXPECT_VECTOR2DF_EQ(initial_value, - ticker_impl_->GetAnimationById(animation1_id) - ->curve() - ->ToScrollOffsetAnimationCurve() - ->GetValue(base::TimeDelta())); + EXPECT_VECTOR2DF_EQ(initial_value, player_impl_->animation_ticker() + ->GetAnimationById(animation1_id) + ->curve() + ->ToScrollOffsetAnimationCurve() + ->GetValue(base::TimeDelta())); // Animation without initial value set. std::unique_ptr<ScrollOffsetAnimationCurve> curve( @@ -282,7 +292,8 @@ player_->AddAnimation(std::move(animation)); PushProperties(); EXPECT_VECTOR2DF_EQ(provider_initial_value, - ticker_impl_->GetAnimationById(animation2_id) + player_impl_->animation_ticker() + ->GetAnimationById(animation2_id) ->curve() ->ToScrollOffsetAnimationCurve() ->GetValue(base::TimeDelta())); @@ -303,14 +314,14 @@ }; void setTimelineAndPlayer(scoped_refptr<AnimationTimeline> timeline, - scoped_refptr<AnimationPlayer> player) { + scoped_refptr<SingleTickerAnimationPlayer> player) { timeline_ = timeline; player_ = player; } private: scoped_refptr<AnimationTimeline> timeline_; - scoped_refptr<AnimationPlayer> player_; + scoped_refptr<SingleTickerAnimationPlayer> player_; }; // Test that we don't crash if a player is deleted while ElementAnimations is @@ -324,7 +335,8 @@ TestAnimationDelegateThatDestroysPlayer delegate; const int player2_id = AnimationIdProvider::NextPlayerId(); - scoped_refptr<AnimationPlayer> player2 = AnimationPlayer::Create(player2_id); + scoped_refptr<SingleTickerAnimationPlayer> player2 = + SingleTickerAnimationPlayer::Create(player2_id); delegate.setTimelineAndPlayer(timeline_, player2); timeline_->AttachPlayer(player2); @@ -336,8 +348,8 @@ PushProperties(); - scoped_refptr<AnimationPlayer> player2_impl = - timeline_impl_->GetPlayerById(player2_id); + scoped_refptr<SingleTickerAnimationPlayer> player2_impl = + (SingleTickerAnimationPlayer*)timeline_impl_->GetPlayerById(player2_id); DCHECK(player2_impl); player2_impl->ActivateAnimations(); @@ -370,9 +382,11 @@ PushProperties(); player_impl_->ActivateAnimations(); - EXPECT_TRUE(ticker_impl_->GetAnimationById(animation_id)); + EXPECT_TRUE(player_impl_->animation_ticker()->GetAnimationById(animation_id)); EXPECT_EQ(Animation::WAITING_FOR_TARGET_AVAILABILITY, - ticker_impl_->GetAnimationById(animation_id)->run_state()); + player_impl_->animation_ticker() + ->GetAnimationById(animation_id) + ->run_state()); auto events = CreateEventsForTesting(); player_impl_->Tick(kInitialTickTime); @@ -380,15 +394,21 @@ // Synchronize the start times. EXPECT_EQ(1u, events->events_.size()); - ticker_->NotifyAnimationStarted(events->events_[0]); - EXPECT_EQ(ticker_->GetAnimationById(animation_id)->start_time(), - ticker_impl_->GetAnimationById(animation_id)->start_time()); + player_->animation_ticker()->NotifyAnimationStarted(events->events_[0]); + EXPECT_EQ( + player_->animation_ticker()->GetAnimationById(animation_id)->start_time(), + player_impl_->animation_ticker() + ->GetAnimationById(animation_id) + ->start_time()); // Start the animation on the main thread. Should not affect the start time. player_impl_->Tick(kInitialTickTime + TimeDelta::FromMilliseconds(500)); player_impl_->UpdateState(true, nullptr); - EXPECT_EQ(ticker_->GetAnimationById(animation_id)->start_time(), - ticker_impl_->GetAnimationById(animation_id)->start_time()); + EXPECT_EQ( + player_->animation_ticker()->GetAnimationById(animation_id)->start_time(), + player_impl_->animation_ticker() + ->GetAnimationById(animation_id) + ->start_time()); } TEST_F(ElementAnimationsTest, UseSpecifiedStartTimes) { @@ -405,9 +425,11 @@ PushProperties(); player_impl_->ActivateAnimations(); - EXPECT_TRUE(ticker_impl_->GetAnimationById(animation_id)); + EXPECT_TRUE(player_impl_->animation_ticker()->GetAnimationById(animation_id)); EXPECT_EQ(Animation::WAITING_FOR_TARGET_AVAILABILITY, - ticker_impl_->GetAnimationById(animation_id)->run_state()); + player_impl_->animation_ticker() + ->GetAnimationById(animation_id) + ->run_state()); auto events = CreateEventsForTesting(); player_impl_->Tick(kInitialTickTime); @@ -415,18 +437,28 @@ // Synchronize the start times. EXPECT_EQ(1u, events->events_.size()); - ticker_->NotifyAnimationStarted(events->events_[0]); + player_->animation_ticker()->NotifyAnimationStarted(events->events_[0]); - EXPECT_EQ(start_time, ticker_->GetAnimationById(animation_id)->start_time()); - EXPECT_EQ(ticker_->GetAnimationById(animation_id)->start_time(), - ticker_impl_->GetAnimationById(animation_id)->start_time()); + EXPECT_EQ(start_time, player_->animation_ticker() + ->GetAnimationById(animation_id) + ->start_time()); + EXPECT_EQ( + player_->animation_ticker()->GetAnimationById(animation_id)->start_time(), + player_impl_->animation_ticker() + ->GetAnimationById(animation_id) + ->start_time()); // Start the animation on the main thread. Should not affect the start time. player_->Tick(kInitialTickTime + TimeDelta::FromMilliseconds(500)); player_->UpdateState(true, nullptr); - EXPECT_EQ(start_time, ticker_->GetAnimationById(animation_id)->start_time()); - EXPECT_EQ(ticker_->GetAnimationById(animation_id)->start_time(), - ticker_impl_->GetAnimationById(animation_id)->start_time()); + EXPECT_EQ(start_time, player_->animation_ticker() + ->GetAnimationById(animation_id) + ->start_time()); + EXPECT_EQ( + player_->animation_ticker()->GetAnimationById(animation_id)->start_time(), + player_impl_->animation_ticker() + ->GetAnimationById(animation_id) + ->start_time()); } // Tests that animationss activate and deactivate as expected. @@ -460,7 +492,7 @@ player_impl_->Tick(kInitialTickTime); player_impl_->UpdateState(true, events.get()); EXPECT_EQ(1u, events->events_.size()); - ticker_->NotifyAnimationStarted(events->events_[0]); + player_->animation_ticker()->NotifyAnimationStarted(events->events_[0]); EXPECT_EQ(1u, host->ticking_players_for_testing().size()); EXPECT_EQ(1u, host_impl->ticking_players_for_testing().size()); @@ -486,7 +518,7 @@ EXPECT_EQ(0u, host_impl->ticking_players_for_testing().size()); EXPECT_EQ(1u, events->events_.size()); - ticker_->NotifyAnimationFinished(events->events_[0]); + player_->animation_ticker()->NotifyAnimationFinished(events->events_[0]); player_->Tick(kInitialTickTime + TimeDelta::FromMilliseconds(1500)); player_->UpdateState(true, nullptr); @@ -497,8 +529,8 @@ PushProperties(); player_impl_->ActivateAnimations(); - EXPECT_FALSE(ticker_->has_any_animation()); - EXPECT_FALSE(ticker_impl_->has_any_animation()); + EXPECT_FALSE(player_->animation_ticker()->has_any_animation()); + EXPECT_FALSE(player_impl_->animation_ticker()->has_any_animation()); EXPECT_EQ(0u, host->ticking_players_for_testing().size()); EXPECT_EQ(0u, host_impl->ticking_players_for_testing().size()); } @@ -516,15 +548,18 @@ AddOpacityStepsToPlayer(player_.get(), duration, 0.2f, 0.4f, 2); // Set start offset to be at the beginning of the second range. - ticker_->GetAnimationById(animation_id) + player_->animation_ticker() + ->GetAnimationById(animation_id) ->set_time_offset(TimeDelta::FromSecondsD(1.01)); PushProperties(); player_impl_->ActivateAnimations(); - EXPECT_TRUE(ticker_impl_->GetAnimationById(animation_id)); + EXPECT_TRUE(player_impl_->animation_ticker()->GetAnimationById(animation_id)); EXPECT_EQ(Animation::WAITING_FOR_TARGET_AVAILABILITY, - ticker_impl_->GetAnimationById(animation_id)->run_state()); + player_impl_->animation_ticker() + ->GetAnimationById(animation_id) + ->run_state()); TimeTicks time = kInitialTickTime; @@ -536,27 +571,32 @@ player_->Tick(time); player_->UpdateState(true, nullptr); - ticker_->NotifyAnimationStarted(events->events_[0]); + player_->animation_ticker()->NotifyAnimationStarted(events->events_[0]); - EXPECT_EQ(Animation::RUNNING, - ticker_impl_->GetAnimationById(animation_id)->run_state()); - EXPECT_EQ(Animation::RUNNING, - ticker_->GetAnimationById(animation_id)->run_state()); + EXPECT_EQ(Animation::RUNNING, player_impl_->animation_ticker() + ->GetAnimationById(animation_id) + ->run_state()); + EXPECT_EQ( + Animation::RUNNING, + player_->animation_ticker()->GetAnimationById(animation_id)->run_state()); EXPECT_EQ(0.3f, client_.GetOpacity(element_id_, ElementListType::ACTIVE)); EXPECT_EQ(0.3f, client_impl_.GetOpacity(element_id_, ElementListType::ACTIVE)); - EXPECT_EQ(kInitialTickTime, - ticker_->GetAnimationById(animation_id)->start_time()); - EXPECT_EQ(kInitialTickTime, - ticker_impl_->GetAnimationById(animation_id)->start_time()); + EXPECT_EQ(kInitialTickTime, player_->animation_ticker() + ->GetAnimationById(animation_id) + ->start_time()); + EXPECT_EQ(kInitialTickTime, player_impl_->animation_ticker() + ->GetAnimationById(animation_id) + ->start_time()); // Pause the animation at the middle of the second range so the offset // delays animation until the middle of the third range. player_->PauseAnimation(animation_id, 1.5); - EXPECT_EQ(Animation::PAUSED, - ticker_->GetAnimationById(animation_id)->run_state()); + EXPECT_EQ( + Animation::PAUSED, + player_->animation_ticker()->GetAnimationById(animation_id)->run_state()); // The pause run state change should make it to the impl thread animations. PushProperties(); @@ -567,8 +607,9 @@ player_->Tick(time); player_impl_->Tick(time); - EXPECT_EQ(Animation::PAUSED, - ticker_impl_->GetAnimationById(animation_id)->run_state()); + EXPECT_EQ(Animation::PAUSED, player_impl_->animation_ticker() + ->GetAnimationById(animation_id) + ->run_state()); // Opacity value doesn't depend on time if paused at specified time offset. EXPECT_EQ(0.4f, client_.GetOpacity(element_id_, ElementListType::ACTIVE)); @@ -591,9 +632,11 @@ PushProperties(); player_impl_->ActivateAnimations(); - EXPECT_TRUE(ticker_impl_->GetAnimationById(animation_id)); + EXPECT_TRUE(player_impl_->animation_ticker()->GetAnimationById(animation_id)); EXPECT_EQ(Animation::WAITING_FOR_TARGET_AVAILABILITY, - ticker_impl_->GetAnimationById(animation_id)->run_state()); + player_impl_->animation_ticker() + ->GetAnimationById(animation_id) + ->run_state()); events = CreateEventsForTesting(); player_impl_->Tick(kInitialTickTime); @@ -602,7 +645,7 @@ EXPECT_EQ(AnimationEvent::STARTED, events->events_[0].type); // Notify main thread animations that the animation has started. - ticker_->NotifyAnimationStarted(events->events_[0]); + player_->animation_ticker()->NotifyAnimationStarted(events->events_[0]); // Complete animation on impl thread. events = CreateEventsForTesting(); @@ -611,15 +654,16 @@ EXPECT_EQ(1u, events->events_.size()); EXPECT_EQ(AnimationEvent::FINISHED, events->events_[0].type); - ticker_->NotifyAnimationFinished(events->events_[0]); + player_->animation_ticker()->NotifyAnimationFinished(events->events_[0]); player_->Tick(kInitialTickTime + TimeDelta::FromSeconds(2)); player_->UpdateState(true, nullptr); PushProperties(); player_impl_->ActivateAnimations(); - EXPECT_FALSE(ticker_->GetAnimationById(animation_id)); - EXPECT_FALSE(ticker_impl_->GetAnimationById(animation_id)); + EXPECT_FALSE(player_->animation_ticker()->GetAnimationById(animation_id)); + EXPECT_FALSE( + player_impl_->animation_ticker()->GetAnimationById(animation_id)); } // Ensure that a finished animation is eventually deleted by both the @@ -634,10 +678,10 @@ AddOpacityTransitionToPlayer(player_.get(), 1.0, 0.0f, 1.0f, false); player_->Tick(kInitialTickTime); player_->UpdateState(true, nullptr); - EXPECT_TRUE(ticker_->needs_push_properties()); + EXPECT_TRUE(player_->animation_ticker()->needs_push_properties()); PushProperties(); - EXPECT_FALSE(ticker_->needs_push_properties()); + EXPECT_FALSE(player_->animation_ticker()->needs_push_properties()); EXPECT_FALSE(host_->needs_push_properties()); EXPECT_FALSE(host_impl_->needs_push_properties()); @@ -650,7 +694,7 @@ // There should be a STARTED event for the animation. EXPECT_EQ(1u, events->events_.size()); EXPECT_EQ(AnimationEvent::STARTED, events->events_[0].type); - ticker_->NotifyAnimationStarted(events->events_[0]); + player_->animation_ticker()->NotifyAnimationStarted(events->events_[0]); player_->Tick(kInitialTickTime + TimeDelta::FromMilliseconds(1000)); player_->UpdateState(true, nullptr); @@ -672,7 +716,7 @@ EXPECT_TRUE(player_->GetAnimation(TargetProperty::OPACITY)); EXPECT_TRUE(player_impl_->GetAnimation(TargetProperty::OPACITY)); - ticker_->NotifyAnimationFinished(events->events_[0]); + player_->animation_ticker()->NotifyAnimationFinished(events->events_[0]); player_->Tick(kInitialTickTime + TimeDelta::FromMilliseconds(3000)); player_->UpdateState(true, nullptr); @@ -684,8 +728,8 @@ // should have deleted the animation even though activation has not occurred, // since the animation was already waiting for deletion when // PushPropertiesTo was called. - EXPECT_FALSE(ticker_->has_any_animation()); - EXPECT_FALSE(ticker_impl_->has_any_animation()); + EXPECT_FALSE(player_->animation_ticker()->has_any_animation()); + EXPECT_FALSE(player_impl_->animation_ticker()->has_any_animation()); } // Tests that transitioning opacity from 0 to 1 works as expected. @@ -708,22 +752,24 @@ 1, TargetProperty::OPACITY)); int animation_id = to_add->id(); - EXPECT_FALSE(ticker_->GetAnimationById(animation_id)); + EXPECT_FALSE(player_->animation_ticker()->GetAnimationById(animation_id)); player_->AddAnimation(std::move(to_add)); - EXPECT_TRUE(ticker_->GetAnimationById(animation_id)); - EXPECT_EQ(Animation::WAITING_FOR_TARGET_AVAILABILITY, - ticker_->GetAnimationById(animation_id)->run_state()); + EXPECT_TRUE(player_->animation_ticker()->GetAnimationById(animation_id)); + EXPECT_EQ( + Animation::WAITING_FOR_TARGET_AVAILABILITY, + player_->animation_ticker()->GetAnimationById(animation_id)->run_state()); player_->Tick(kInitialTickTime); - EXPECT_EQ(Animation::STARTING, - ticker_->GetAnimationById(animation_id)->run_state()); + EXPECT_EQ( + Animation::STARTING, + player_->animation_ticker()->GetAnimationById(animation_id)->run_state()); player_->UpdateState(true, events.get()); - EXPECT_TRUE(ticker_->HasTickingAnimation()); + EXPECT_TRUE(player_->animation_ticker()->HasTickingAnimation()); EXPECT_EQ(0.f, client_.GetOpacity(element_id_, ElementListType::ACTIVE)); player_->Tick(kInitialTickTime + TimeDelta::FromMilliseconds(1000)); player_->UpdateState(true, events.get()); EXPECT_EQ(1.f, client_.GetOpacity(element_id_, ElementListType::ACTIVE)); - EXPECT_FALSE(ticker_->HasTickingAnimation()); + EXPECT_FALSE(player_->animation_ticker()->HasTickingAnimation()); } TEST_F(ElementAnimationsTest, FilterTransition) { @@ -750,7 +796,7 @@ player_->Tick(kInitialTickTime); player_->UpdateState(true, events.get()); - EXPECT_TRUE(ticker_->HasTickingAnimation()); + EXPECT_TRUE(player_->animation_ticker()->HasTickingAnimation()); EXPECT_EQ(start_filters, client_.GetFilters(element_id_, ElementListType::ACTIVE)); @@ -765,7 +811,7 @@ player_->UpdateState(true, events.get()); EXPECT_EQ(end_filters, client_.GetFilters(element_id_, ElementListType::ACTIVE)); - EXPECT_FALSE(ticker_->HasTickingAnimation()); + EXPECT_FALSE(player_->animation_ticker()->HasTickingAnimation()); } TEST_F(ElementAnimationsTest, ScrollOffsetTransition) { @@ -800,20 +846,20 @@ player_->Tick(kInitialTickTime); player_->UpdateState(true, nullptr); - EXPECT_TRUE(ticker_->HasTickingAnimation()); + EXPECT_TRUE(player_->animation_ticker()->HasTickingAnimation()); EXPECT_EQ(initial_value, client_.GetScrollOffset(element_id_, ElementListType::ACTIVE)); player_impl_->Tick(kInitialTickTime); player_impl_->UpdateState(true, events.get()); - EXPECT_TRUE(ticker_impl_->HasTickingAnimation()); + EXPECT_TRUE(player_impl_->animation_ticker()->HasTickingAnimation()); EXPECT_EQ(initial_value, client_impl_.GetScrollOffset(element_id_, ElementListType::ACTIVE)); - ticker_->NotifyAnimationStarted(events->events_[0]); + player_->animation_ticker()->NotifyAnimationStarted(events->events_[0]); player_->Tick(kInitialTickTime + duration / 2); player_->UpdateState(true, nullptr); - EXPECT_TRUE(ticker_->HasTickingAnimation()); + EXPECT_TRUE(player_->animation_ticker()->HasTickingAnimation()); EXPECT_VECTOR2DF_EQ( gfx::Vector2dF(200.f, 250.f), client_.GetScrollOffset(element_id_, ElementListType::ACTIVE)); @@ -828,13 +874,13 @@ player_impl_->UpdateState(true, events.get()); EXPECT_VECTOR2DF_EQ(target_value, client_impl_.GetScrollOffset( element_id_, ElementListType::ACTIVE)); - EXPECT_FALSE(ticker_impl_->HasTickingAnimation()); + EXPECT_FALSE(player_impl_->animation_ticker()->HasTickingAnimation()); player_->Tick(kInitialTickTime + duration); player_->UpdateState(true, nullptr); EXPECT_VECTOR2DF_EQ(target_value, client_.GetScrollOffset( element_id_, ElementListType::ACTIVE)); - EXPECT_FALSE(ticker_->HasTickingAnimation()); + EXPECT_FALSE(player_->animation_ticker()->HasTickingAnimation()); } TEST_F(ElementAnimationsTest, ScrollOffsetTransitionOnImplOnly) { @@ -860,7 +906,7 @@ player_impl_->Tick(kInitialTickTime); player_impl_->UpdateState(true, events.get()); - EXPECT_TRUE(ticker_impl_->HasTickingAnimation()); + EXPECT_TRUE(player_impl_->animation_ticker()->HasTickingAnimation()); EXPECT_EQ(initial_value, client_impl_.GetScrollOffset(element_id_, ElementListType::ACTIVE)); @@ -877,7 +923,7 @@ player_impl_->UpdateState(true, events.get()); EXPECT_VECTOR2DF_EQ(target_value, client_impl_.GetScrollOffset( element_id_, ElementListType::ACTIVE)); - EXPECT_FALSE(ticker_impl_->HasTickingAnimation()); + EXPECT_FALSE(player_impl_->animation_ticker()->HasTickingAnimation()); } // This test verifies that if an animation is added after a layer is animated, @@ -971,7 +1017,7 @@ player_->Tick(kInitialTickTime); player_->UpdateState(true, nullptr); - EXPECT_TRUE(ticker_->HasTickingAnimation()); + EXPECT_TRUE(player_->animation_ticker()->HasTickingAnimation()); EXPECT_EQ(initial_value, client_.GetScrollOffset(element_id_, ElementListType::ACTIVE)); EXPECT_EQ(gfx::ScrollOffset(), client_impl_.GetScrollOffset( @@ -979,7 +1025,7 @@ player_impl_->Tick(kInitialTickTime); - EXPECT_TRUE(ticker_impl_->HasTickingAnimation()); + EXPECT_TRUE(player_impl_->animation_ticker()->HasTickingAnimation()); EXPECT_EQ(initial_value, client_impl_.GetScrollOffset( element_id_, ElementListType::PENDING)); @@ -988,10 +1034,10 @@ player_impl_->UpdateState(true, events.get()); DCHECK_EQ(1UL, events->events_.size()); - ticker_->NotifyAnimationStarted(events->events_[0]); + player_->animation_ticker()->NotifyAnimationStarted(events->events_[0]); player_->Tick(kInitialTickTime + duration / 2); player_->UpdateState(true, nullptr); - EXPECT_TRUE(ticker_->HasTickingAnimation()); + EXPECT_TRUE(player_->animation_ticker()->HasTickingAnimation()); EXPECT_VECTOR2DF_EQ( gfx::Vector2dF(400.f, 150.f), client_.GetScrollOffset(element_id_, ElementListType::ACTIVE)); @@ -1006,13 +1052,13 @@ player_impl_->UpdateState(true, events.get()); EXPECT_VECTOR2DF_EQ(target_value, client_impl_.GetScrollOffset( element_id_, ElementListType::PENDING)); - EXPECT_FALSE(ticker_impl_->HasTickingAnimation()); + EXPECT_FALSE(player_impl_->animation_ticker()->HasTickingAnimation()); player_->Tick(kInitialTickTime + duration); player_->UpdateState(true, nullptr); EXPECT_VECTOR2DF_EQ(target_value, client_.GetScrollOffset( element_id_, ElementListType::ACTIVE)); - EXPECT_FALSE(ticker_->HasTickingAnimation()); + EXPECT_FALSE(player_->animation_ticker()->HasTickingAnimation()); } TEST_F(ElementAnimationsTest, ScrollOffsetRemovalClearsScrollDelta) { @@ -1036,18 +1082,24 @@ player_->AddAnimation(std::move(animation)); PushProperties(); player_impl_->ActivateAnimations(); - EXPECT_FALSE(ticker_->scroll_offset_animation_was_interrupted()); - EXPECT_FALSE(ticker_impl_->scroll_offset_animation_was_interrupted()); + EXPECT_FALSE( + player_->animation_ticker()->scroll_offset_animation_was_interrupted()); + EXPECT_FALSE(player_impl_->animation_ticker() + ->scroll_offset_animation_was_interrupted()); player_->RemoveAnimation(animation_id); - EXPECT_TRUE(ticker_->scroll_offset_animation_was_interrupted()); + EXPECT_TRUE( + player_->animation_ticker()->scroll_offset_animation_was_interrupted()); PushProperties(); - EXPECT_TRUE(ticker_impl_->scroll_offset_animation_was_interrupted()); - EXPECT_FALSE(ticker_->scroll_offset_animation_was_interrupted()); + EXPECT_TRUE(player_impl_->animation_ticker() + ->scroll_offset_animation_was_interrupted()); + EXPECT_FALSE( + player_->animation_ticker()->scroll_offset_animation_was_interrupted()); player_impl_->ActivateAnimations(); - EXPECT_FALSE(ticker_impl_->scroll_offset_animation_was_interrupted()); + EXPECT_FALSE(player_impl_->animation_ticker() + ->scroll_offset_animation_was_interrupted()); // Now, test the 2-argument version of RemoveAnimation. curve = ScrollOffsetAnimationCurve::Create( @@ -1059,52 +1111,70 @@ player_->AddAnimation(std::move(animation)); PushProperties(); player_impl_->ActivateAnimations(); - EXPECT_FALSE(ticker_->scroll_offset_animation_was_interrupted()); - EXPECT_FALSE(ticker_impl_->scroll_offset_animation_was_interrupted()); + EXPECT_FALSE( + player_->animation_ticker()->scroll_offset_animation_was_interrupted()); + EXPECT_FALSE(player_impl_->animation_ticker() + ->scroll_offset_animation_was_interrupted()); player_->RemoveAnimation(animation_id); - EXPECT_TRUE(ticker_->scroll_offset_animation_was_interrupted()); + EXPECT_TRUE( + player_->animation_ticker()->scroll_offset_animation_was_interrupted()); PushProperties(); - EXPECT_TRUE(ticker_impl_->scroll_offset_animation_was_interrupted()); - EXPECT_FALSE(ticker_->scroll_offset_animation_was_interrupted()); + EXPECT_TRUE(player_impl_->animation_ticker() + ->scroll_offset_animation_was_interrupted()); + EXPECT_FALSE( + player_->animation_ticker()->scroll_offset_animation_was_interrupted()); player_impl_->ActivateAnimations(); - EXPECT_FALSE(ticker_impl_->scroll_offset_animation_was_interrupted()); + EXPECT_FALSE(player_impl_->animation_ticker() + ->scroll_offset_animation_was_interrupted()); // Check that removing non-scroll-offset animations does not cause // scroll_offset_animation_was_interrupted() to get set. animation_id = AddAnimatedTransformToPlayer(player_.get(), 1.0, 1, 2); PushProperties(); player_impl_->ActivateAnimations(); - EXPECT_FALSE(ticker_->scroll_offset_animation_was_interrupted()); - EXPECT_FALSE(ticker_impl_->scroll_offset_animation_was_interrupted()); + EXPECT_FALSE( + player_->animation_ticker()->scroll_offset_animation_was_interrupted()); + EXPECT_FALSE(player_impl_->animation_ticker() + ->scroll_offset_animation_was_interrupted()); player_->RemoveAnimation(animation_id); - EXPECT_FALSE(ticker_->scroll_offset_animation_was_interrupted()); + EXPECT_FALSE( + player_->animation_ticker()->scroll_offset_animation_was_interrupted()); PushProperties(); - EXPECT_FALSE(ticker_impl_->scroll_offset_animation_was_interrupted()); - EXPECT_FALSE(ticker_->scroll_offset_animation_was_interrupted()); + EXPECT_FALSE(player_impl_->animation_ticker() + ->scroll_offset_animation_was_interrupted()); + EXPECT_FALSE( + player_->animation_ticker()->scroll_offset_animation_was_interrupted()); player_impl_->ActivateAnimations(); - EXPECT_FALSE(ticker_impl_->scroll_offset_animation_was_interrupted()); + EXPECT_FALSE(player_impl_->animation_ticker() + ->scroll_offset_animation_was_interrupted()); animation_id = AddAnimatedFilterToPlayer(player_.get(), 1.0, 0.1f, 0.2f); PushProperties(); player_impl_->ActivateAnimations(); - EXPECT_FALSE(ticker_->scroll_offset_animation_was_interrupted()); - EXPECT_FALSE(ticker_impl_->scroll_offset_animation_was_interrupted()); + EXPECT_FALSE( + player_->animation_ticker()->scroll_offset_animation_was_interrupted()); + EXPECT_FALSE(player_impl_->animation_ticker() + ->scroll_offset_animation_was_interrupted()); player_->RemoveAnimation(animation_id); - EXPECT_FALSE(ticker_->scroll_offset_animation_was_interrupted()); + EXPECT_FALSE( + player_->animation_ticker()->scroll_offset_animation_was_interrupted()); PushProperties(); - EXPECT_FALSE(ticker_impl_->scroll_offset_animation_was_interrupted()); - EXPECT_FALSE(ticker_->scroll_offset_animation_was_interrupted()); + EXPECT_FALSE(player_impl_->animation_ticker() + ->scroll_offset_animation_was_interrupted()); + EXPECT_FALSE( + player_->animation_ticker()->scroll_offset_animation_was_interrupted()); player_impl_->ActivateAnimations(); - EXPECT_FALSE(ticker_impl_->scroll_offset_animation_was_interrupted()); + EXPECT_FALSE(player_impl_->animation_ticker() + ->scroll_offset_animation_was_interrupted()); } // Tests that impl-only animations lead to start and finished notifications @@ -1171,9 +1241,11 @@ PushProperties(); player_impl_->ActivateAnimations(); - EXPECT_TRUE(ticker_impl_->GetAnimationById(animation_id)); + EXPECT_TRUE(player_impl_->animation_ticker()->GetAnimationById(animation_id)); EXPECT_EQ(Animation::WAITING_FOR_TARGET_AVAILABILITY, - ticker_impl_->GetAnimationById(animation_id)->run_state()); + player_impl_->animation_ticker() + ->GetAnimationById(animation_id) + ->run_state()); auto events = CreateEventsForTesting(); player_impl_->Tick(kInitialTickTime); @@ -1181,7 +1253,7 @@ // Synchronize the start times. EXPECT_EQ(1u, events->events_.size()); - ticker_->NotifyAnimationStarted(events->events_[0]); + player_->animation_ticker()->NotifyAnimationStarted(events->events_[0]); // Validate start time on the main thread delegate. EXPECT_EQ(start_time, delegate.start_time()); @@ -1206,25 +1278,25 @@ player_->AddAnimation(std::move(to_add)); player_->Tick(kInitialTickTime); player_->UpdateState(true, events.get()); - EXPECT_TRUE(ticker_->HasTickingAnimation()); + EXPECT_TRUE(player_->animation_ticker()->HasTickingAnimation()); EXPECT_EQ(0.f, client_.GetOpacity(element_id_, ElementListType::ACTIVE)); player_->Tick(kInitialTickTime + TimeDelta::FromMilliseconds(1000)); player_->UpdateState(true, events.get()); - EXPECT_TRUE(ticker_->HasTickingAnimation()); + EXPECT_TRUE(player_->animation_ticker()->HasTickingAnimation()); EXPECT_EQ(0.f, client_.GetOpacity(element_id_, ElementListType::ACTIVE)); player_->Tick(kInitialTickTime + TimeDelta::FromMilliseconds(2000)); player_->UpdateState(true, events.get()); - EXPECT_TRUE(ticker_->HasTickingAnimation()); + EXPECT_TRUE(player_->animation_ticker()->HasTickingAnimation()); EXPECT_EQ(0.f, client_.GetOpacity(element_id_, ElementListType::ACTIVE)); // Send the synchronized start time. - ticker_->NotifyAnimationStarted(AnimationEvent( + player_->animation_ticker()->NotifyAnimationStarted(AnimationEvent( AnimationEvent::STARTED, ElementId(), 1, TargetProperty::OPACITY, kInitialTickTime + TimeDelta::FromMilliseconds(2000))); player_->Tick(kInitialTickTime + TimeDelta::FromMilliseconds(5000)); player_->UpdateState(true, events.get()); EXPECT_EQ(1.f, client_.GetOpacity(element_id_, ElementListType::ACTIVE)); - EXPECT_FALSE(ticker_->HasTickingAnimation()); + EXPECT_FALSE(player_->animation_ticker()->HasTickingAnimation()); } // Tests that two queued animations affecting the same property run in sequence. @@ -1246,36 +1318,41 @@ player_->Tick(kInitialTickTime); // The first animation should have been started. - EXPECT_TRUE(ticker_->GetAnimationById(animation1_id)); - EXPECT_EQ(Animation::STARTING, - ticker_->GetAnimationById(animation1_id)->run_state()); + EXPECT_TRUE(player_->animation_ticker()->GetAnimationById(animation1_id)); + EXPECT_EQ(Animation::STARTING, player_->animation_ticker() + ->GetAnimationById(animation1_id) + ->run_state()); // The second animation still needs to be started. - EXPECT_TRUE(ticker_->GetAnimationById(animation2_id)); + EXPECT_TRUE(player_->animation_ticker()->GetAnimationById(animation2_id)); EXPECT_EQ(Animation::WAITING_FOR_TARGET_AVAILABILITY, - ticker_->GetAnimationById(animation2_id)->run_state()); + player_->animation_ticker() + ->GetAnimationById(animation2_id) + ->run_state()); player_->UpdateState(true, events.get()); - EXPECT_TRUE(ticker_->HasTickingAnimation()); + EXPECT_TRUE(player_->animation_ticker()->HasTickingAnimation()); EXPECT_EQ(0.f, client_.GetOpacity(element_id_, ElementListType::ACTIVE)); player_->Tick(kInitialTickTime + TimeDelta::FromMilliseconds(1000)); player_->UpdateState(true, events.get()); // Now the first should be finished, and the second started. - EXPECT_TRUE(ticker_->GetAnimationById(animation1_id)); - EXPECT_EQ(Animation::FINISHED, - ticker_->GetAnimationById(animation1_id)->run_state()); - EXPECT_TRUE(ticker_->GetAnimationById(animation2_id)); - EXPECT_EQ(Animation::RUNNING, - ticker_->GetAnimationById(animation2_id)->run_state()); + EXPECT_TRUE(player_->animation_ticker()->GetAnimationById(animation1_id)); + EXPECT_EQ(Animation::FINISHED, player_->animation_ticker() + ->GetAnimationById(animation1_id) + ->run_state()); + EXPECT_TRUE(player_->animation_ticker()->GetAnimationById(animation2_id)); + EXPECT_EQ(Animation::RUNNING, player_->animation_ticker() + ->GetAnimationById(animation2_id) + ->run_state()); - EXPECT_TRUE(ticker_->HasTickingAnimation()); + EXPECT_TRUE(player_->animation_ticker()->HasTickingAnimation()); EXPECT_EQ(1.f, client_.GetOpacity(element_id_, ElementListType::ACTIVE)); player_->Tick(kInitialTickTime + TimeDelta::FromMilliseconds(2000)); player_->UpdateState(true, events.get()); EXPECT_EQ(0.5f, client_.GetOpacity(element_id_, ElementListType::ACTIVE)); - EXPECT_FALSE(ticker_->HasTickingAnimation()); + EXPECT_FALSE(player_->animation_ticker()->HasTickingAnimation()); } // Tests interrupting a transition with another transition. @@ -1290,7 +1367,7 @@ 1, TargetProperty::OPACITY)); player_->Tick(kInitialTickTime); player_->UpdateState(true, events.get()); - EXPECT_TRUE(ticker_->HasTickingAnimation()); + EXPECT_TRUE(player_->animation_ticker()->HasTickingAnimation()); EXPECT_EQ(0.f, client_.GetOpacity(element_id_, ElementListType::ACTIVE)); std::unique_ptr<Animation> to_add(CreateAnimation( @@ -1303,12 +1380,12 @@ // right in this call to animate. player_->Tick(kInitialTickTime + TimeDelta::FromMilliseconds(500)); player_->UpdateState(true, events.get()); - EXPECT_TRUE(ticker_->HasTickingAnimation()); + EXPECT_TRUE(player_->animation_ticker()->HasTickingAnimation()); EXPECT_EQ(1.f, client_.GetOpacity(element_id_, ElementListType::ACTIVE)); player_->Tick(kInitialTickTime + TimeDelta::FromMilliseconds(1500)); player_->UpdateState(true, events.get()); EXPECT_EQ(0.5f, client_.GetOpacity(element_id_, ElementListType::ACTIVE)); - EXPECT_FALSE(ticker_->HasTickingAnimation()); + EXPECT_FALSE(player_->animation_ticker()->HasTickingAnimation()); } // Tests scheduling two animations to run together when only one property is @@ -1332,17 +1409,17 @@ player_->Tick(kInitialTickTime); player_->UpdateState(true, events.get()); EXPECT_EQ(0.f, client_.GetOpacity(element_id_, ElementListType::ACTIVE)); - EXPECT_TRUE(ticker_->HasTickingAnimation()); + EXPECT_TRUE(player_->animation_ticker()->HasTickingAnimation()); player_->Tick(kInitialTickTime + TimeDelta::FromMilliseconds(1000)); player_->UpdateState(true, events.get()); // Should not have started the float transition yet. - EXPECT_TRUE(ticker_->HasTickingAnimation()); + EXPECT_TRUE(player_->animation_ticker()->HasTickingAnimation()); EXPECT_EQ(0.f, client_.GetOpacity(element_id_, ElementListType::ACTIVE)); // The float animation should have started at time 1 and should be done. player_->Tick(kInitialTickTime + TimeDelta::FromMilliseconds(2000)); player_->UpdateState(true, events.get()); EXPECT_EQ(1.f, client_.GetOpacity(element_id_, ElementListType::ACTIVE)); - EXPECT_FALSE(ticker_->HasTickingAnimation()); + EXPECT_FALSE(player_->animation_ticker()->HasTickingAnimation()); } // Tests scheduling two animations to run together with different lengths and @@ -1367,7 +1444,7 @@ // Animations with id 1 should both start now. player_->Tick(kInitialTickTime); player_->UpdateState(true, events.get()); - EXPECT_TRUE(ticker_->HasTickingAnimation()); + EXPECT_TRUE(player_->animation_ticker()->HasTickingAnimation()); EXPECT_EQ(0.f, client_.GetOpacity(element_id_, ElementListType::ACTIVE)); // The opacity animation should have finished at time 1, but the group // of animations with id 1 don't finish until time 2 because of the length @@ -1375,7 +1452,7 @@ player_->Tick(kInitialTickTime + TimeDelta::FromMilliseconds(2000)); player_->UpdateState(true, events.get()); // Should not have started the float transition yet. - EXPECT_TRUE(ticker_->HasTickingAnimation()); + EXPECT_TRUE(player_->animation_ticker()->HasTickingAnimation()); EXPECT_EQ(1.f, client_.GetOpacity(element_id_, ElementListType::ACTIVE)); // The second opacity animation should start at time 2 and should be done by @@ -1383,7 +1460,7 @@ player_->Tick(kInitialTickTime + TimeDelta::FromMilliseconds(3000)); player_->UpdateState(true, events.get()); EXPECT_EQ(0.5f, client_.GetOpacity(element_id_, ElementListType::ACTIVE)); - EXPECT_FALSE(ticker_->HasTickingAnimation()); + EXPECT_FALSE(player_->animation_ticker()->HasTickingAnimation()); } // Test that a looping animation loops and for the correct number of iterations. @@ -1401,27 +1478,27 @@ player_->Tick(kInitialTickTime); player_->UpdateState(true, events.get()); - EXPECT_TRUE(ticker_->HasTickingAnimation()); + EXPECT_TRUE(player_->animation_ticker()->HasTickingAnimation()); EXPECT_EQ(0.f, client_.GetOpacity(element_id_, ElementListType::ACTIVE)); player_->Tick(kInitialTickTime + TimeDelta::FromMilliseconds(1250)); player_->UpdateState(true, events.get()); - EXPECT_TRUE(ticker_->HasTickingAnimation()); + EXPECT_TRUE(player_->animation_ticker()->HasTickingAnimation()); EXPECT_EQ(0.25f, client_.GetOpacity(element_id_, ElementListType::ACTIVE)); player_->Tick(kInitialTickTime + TimeDelta::FromMilliseconds(1750)); player_->UpdateState(true, events.get()); - EXPECT_TRUE(ticker_->HasTickingAnimation()); + EXPECT_TRUE(player_->animation_ticker()->HasTickingAnimation()); EXPECT_EQ(0.75f, client_.GetOpacity(element_id_, ElementListType::ACTIVE)); player_->Tick(kInitialTickTime + TimeDelta::FromMilliseconds(2250)); player_->UpdateState(true, events.get()); - EXPECT_TRUE(ticker_->HasTickingAnimation()); + EXPECT_TRUE(player_->animation_ticker()->HasTickingAnimation()); EXPECT_EQ(0.25f, client_.GetOpacity(element_id_, ElementListType::ACTIVE)); player_->Tick(kInitialTickTime + TimeDelta::FromMilliseconds(2750)); player_->UpdateState(true, events.get()); - EXPECT_TRUE(ticker_->HasTickingAnimation()); + EXPECT_TRUE(player_->animation_ticker()->HasTickingAnimation()); EXPECT_EQ(0.75f, client_.GetOpacity(element_id_, ElementListType::ACTIVE)); player_->Tick(kInitialTickTime + TimeDelta::FromMilliseconds(3000)); player_->UpdateState(true, events.get()); - EXPECT_FALSE(ticker_->HasTickingAnimation()); + EXPECT_FALSE(player_->animation_ticker()->HasTickingAnimation()); EXPECT_EQ(1.f, client_.GetOpacity(element_id_, ElementListType::ACTIVE)); // Just be extra sure. @@ -1445,31 +1522,31 @@ player_->Tick(kInitialTickTime); player_->UpdateState(true, events.get()); - EXPECT_TRUE(ticker_->HasTickingAnimation()); + EXPECT_TRUE(player_->animation_ticker()->HasTickingAnimation()); EXPECT_EQ(0.f, client_.GetOpacity(element_id_, ElementListType::ACTIVE)); player_->Tick(kInitialTickTime + TimeDelta::FromMilliseconds(1250)); player_->UpdateState(true, events.get()); - EXPECT_TRUE(ticker_->HasTickingAnimation()); + EXPECT_TRUE(player_->animation_ticker()->HasTickingAnimation()); EXPECT_EQ(0.25f, client_.GetOpacity(element_id_, ElementListType::ACTIVE)); player_->Tick(kInitialTickTime + TimeDelta::FromMilliseconds(1750)); player_->UpdateState(true, events.get()); - EXPECT_TRUE(ticker_->HasTickingAnimation()); + EXPECT_TRUE(player_->animation_ticker()->HasTickingAnimation()); EXPECT_EQ(0.75f, client_.GetOpacity(element_id_, ElementListType::ACTIVE)); player_->Tick(kInitialTickTime + TimeDelta::FromMilliseconds(1073741824250)); player_->UpdateState(true, events.get()); - EXPECT_TRUE(ticker_->HasTickingAnimation()); + EXPECT_TRUE(player_->animation_ticker()->HasTickingAnimation()); EXPECT_EQ(0.25f, client_.GetOpacity(element_id_, ElementListType::ACTIVE)); player_->Tick(kInitialTickTime + TimeDelta::FromMilliseconds(1073741824750)); player_->UpdateState(true, events.get()); - EXPECT_TRUE(ticker_->HasTickingAnimation()); + EXPECT_TRUE(player_->animation_ticker()->HasTickingAnimation()); EXPECT_EQ(0.75f, client_.GetOpacity(element_id_, ElementListType::ACTIVE)); EXPECT_TRUE(player_->GetAnimation(TargetProperty::OPACITY)); player_->GetAnimation(TargetProperty::OPACITY) ->SetRunState(Animation::ABORTED, kInitialTickTime + TimeDelta::FromMilliseconds(750)); - EXPECT_FALSE(ticker_->HasTickingAnimation()); + EXPECT_FALSE(player_->animation_ticker()->HasTickingAnimation()); EXPECT_EQ(0.75f, client_.GetOpacity(element_id_, ElementListType::ACTIVE)); } @@ -1486,11 +1563,11 @@ player_->Tick(kInitialTickTime); player_->UpdateState(true, events.get()); - EXPECT_TRUE(ticker_->HasTickingAnimation()); + EXPECT_TRUE(player_->animation_ticker()->HasTickingAnimation()); EXPECT_EQ(0.f, client_.GetOpacity(element_id_, ElementListType::ACTIVE)); player_->Tick(kInitialTickTime + TimeDelta::FromMilliseconds(500)); player_->UpdateState(true, events.get()); - EXPECT_TRUE(ticker_->HasTickingAnimation()); + EXPECT_TRUE(player_->animation_ticker()->HasTickingAnimation()); EXPECT_EQ(0.5f, client_.GetOpacity(element_id_, ElementListType::ACTIVE)); EXPECT_TRUE(player_->GetAnimation(TargetProperty::OPACITY)); @@ -1500,7 +1577,7 @@ player_->Tick(kInitialTickTime + TimeDelta::FromMilliseconds(1024000)); player_->UpdateState(true, events.get()); - EXPECT_TRUE(ticker_->HasTickingAnimation()); + EXPECT_TRUE(player_->animation_ticker()->HasTickingAnimation()); EXPECT_EQ(0.5f, client_.GetOpacity(element_id_, ElementListType::ACTIVE)); EXPECT_TRUE(player_->GetAnimation(TargetProperty::OPACITY)); @@ -1509,12 +1586,12 @@ kInitialTickTime + TimeDelta::FromMilliseconds(1024000)); player_->Tick(kInitialTickTime + TimeDelta::FromMilliseconds(1024250)); player_->UpdateState(true, events.get()); - EXPECT_TRUE(ticker_->HasTickingAnimation()); + EXPECT_TRUE(player_->animation_ticker()->HasTickingAnimation()); EXPECT_EQ(0.75f, client_.GetOpacity(element_id_, ElementListType::ACTIVE)); player_->Tick(kInitialTickTime + TimeDelta::FromMilliseconds(1024500)); player_->UpdateState(true, events.get()); - EXPECT_FALSE(ticker_->HasTickingAnimation()); + EXPECT_FALSE(player_->animation_ticker()->HasTickingAnimation()); EXPECT_EQ(1.f, client_.GetOpacity(element_id_, ElementListType::ACTIVE)); } @@ -1537,24 +1614,25 @@ player_->Tick(kInitialTickTime); player_->UpdateState(true, events.get()); - EXPECT_TRUE(ticker_->HasTickingAnimation()); + EXPECT_TRUE(player_->animation_ticker()->HasTickingAnimation()); EXPECT_EQ(0.f, client_.GetOpacity(element_id_, ElementListType::ACTIVE)); player_->Tick(kInitialTickTime + TimeDelta::FromMilliseconds(1000)); player_->UpdateState(true, events.get()); - EXPECT_TRUE(ticker_->HasTickingAnimation()); + EXPECT_TRUE(player_->animation_ticker()->HasTickingAnimation()); EXPECT_EQ(0.5f, client_.GetOpacity(element_id_, ElementListType::ACTIVE)); - EXPECT_TRUE(ticker_->GetAnimationById(animation_id)); - ticker_->GetAnimationById(animation_id) + EXPECT_TRUE(player_->animation_ticker()->GetAnimationById(animation_id)); + player_->animation_ticker() + ->GetAnimationById(animation_id) ->SetRunState(Animation::ABORTED, kInitialTickTime + TimeDelta::FromMilliseconds(1000)); player_->Tick(kInitialTickTime + TimeDelta::FromMilliseconds(1000)); player_->UpdateState(true, events.get()); - EXPECT_TRUE(ticker_->HasTickingAnimation()); + EXPECT_TRUE(player_->animation_ticker()->HasTickingAnimation()); EXPECT_EQ(1.f, client_.GetOpacity(element_id_, ElementListType::ACTIVE)); player_->Tick(kInitialTickTime + TimeDelta::FromMilliseconds(2000)); player_->UpdateState(true, events.get()); - EXPECT_TRUE(!ticker_->HasTickingAnimation()); + EXPECT_TRUE(!player_->animation_ticker()->HasTickingAnimation()); EXPECT_EQ(0.75f, client_.GetOpacity(element_id_, ElementListType::ACTIVE)); } @@ -1573,12 +1651,12 @@ player_->Tick(kInitialTickTime); player_->UpdateState(true, events.get()); - EXPECT_TRUE(ticker_->HasTickingAnimation()); + EXPECT_TRUE(player_->animation_ticker()->HasTickingAnimation()); Animation* active_animation = player_->GetAnimation(TargetProperty::OPACITY); EXPECT_TRUE(active_animation); EXPECT_TRUE(active_animation->needs_synchronized_start_time()); - EXPECT_TRUE(ticker_->needs_push_properties()); + EXPECT_TRUE(player_->animation_ticker()->needs_push_properties()); PushProperties(); player_impl_->ActivateAnimations(); @@ -1622,7 +1700,7 @@ EXPECT_NE(events->events_[0].type, events->events_[1].type); // The float transition should still be at its starting point. - EXPECT_TRUE(ticker_->HasTickingAnimation()); + EXPECT_TRUE(player_->animation_ticker()->HasTickingAnimation()); EXPECT_EQ(0.f, client_.GetOpacity(element_id_, ElementListType::ACTIVE)); player_->Tick(kInitialTickTime + TimeDelta::FromMilliseconds(3000)); @@ -1630,7 +1708,7 @@ // The float tranisition should now be done. EXPECT_EQ(1.f, client_.GetOpacity(element_id_, ElementListType::ACTIVE)); - EXPECT_FALSE(ticker_->HasTickingAnimation()); + EXPECT_FALSE(player_->animation_ticker()->HasTickingAnimation()); } // Tests that an animation animations with only a pending observer gets ticked @@ -1699,8 +1777,8 @@ client_impl_.GetOpacity(element_id_, ElementListType::ACTIVE)); } -// Tests that AbortAnimations aborts all animations targeting the specified -// property. +// Tests that AbortAnimations aborts all animations targeting the +// specified property. TEST_F(ElementAnimationsTest, AbortAnimations) { CreateTestLayer(false, false); AttachTimelinePlayerLayer(); @@ -1728,21 +1806,30 @@ player_->Tick(kInitialTickTime + TimeDelta::FromMilliseconds(1000)); player_->UpdateState(true, nullptr); - EXPECT_EQ(Animation::FINISHED, ticker_->GetAnimationById(1)->run_state()); - EXPECT_EQ(Animation::FINISHED, ticker_->GetAnimationById(2)->run_state()); - EXPECT_EQ(Animation::RUNNING, ticker_->GetAnimationById(3)->run_state()); + EXPECT_EQ(Animation::FINISHED, + player_->animation_ticker()->GetAnimationById(1)->run_state()); + EXPECT_EQ(Animation::FINISHED, + player_->animation_ticker()->GetAnimationById(2)->run_state()); + EXPECT_EQ(Animation::RUNNING, + player_->animation_ticker()->GetAnimationById(3)->run_state()); EXPECT_EQ(Animation::WAITING_FOR_TARGET_AVAILABILITY, - ticker_->GetAnimationById(4)->run_state()); - EXPECT_EQ(Animation::RUNNING, ticker_->GetAnimationById(5)->run_state()); + player_->animation_ticker()->GetAnimationById(4)->run_state()); + EXPECT_EQ(Animation::RUNNING, + player_->animation_ticker()->GetAnimationById(5)->run_state()); player_->AbortAnimations(TargetProperty::TRANSFORM, false); // Only un-finished TRANSFORM animations should have been aborted. - EXPECT_EQ(Animation::FINISHED, ticker_->GetAnimationById(1)->run_state()); - EXPECT_EQ(Animation::FINISHED, ticker_->GetAnimationById(2)->run_state()); - EXPECT_EQ(Animation::ABORTED, ticker_->GetAnimationById(3)->run_state()); - EXPECT_EQ(Animation::ABORTED, ticker_->GetAnimationById(4)->run_state()); - EXPECT_EQ(Animation::RUNNING, ticker_->GetAnimationById(5)->run_state()); + EXPECT_EQ(Animation::FINISHED, + player_->animation_ticker()->GetAnimationById(1)->run_state()); + EXPECT_EQ(Animation::FINISHED, + player_->animation_ticker()->GetAnimationById(2)->run_state()); + EXPECT_EQ(Animation::ABORTED, + player_->animation_ticker()->GetAnimationById(3)->run_state()); + EXPECT_EQ(Animation::ABORTED, + player_->animation_ticker()->GetAnimationById(4)->run_state()); + EXPECT_EQ(Animation::RUNNING, + player_->animation_ticker()->GetAnimationById(5)->run_state()); } // An animation aborted on the main thread should get deleted on both threads. @@ -1759,7 +1846,7 @@ player_impl_->ActivateAnimations(); - EXPECT_TRUE(ticker_impl_->GetAnimationById(animation_id)); + EXPECT_TRUE(player_impl_->animation_ticker()->GetAnimationById(animation_id)); EXPECT_FALSE(host_->needs_push_properties()); player_->AbortAnimations(TargetProperty::OPACITY, false); @@ -1772,15 +1859,16 @@ EXPECT_EQ(Animation::ABORTED, player_->GetAnimation(TargetProperty::OPACITY)->run_state()); - EXPECT_TRUE(ticker_->needs_push_properties()); + EXPECT_TRUE(player_->animation_ticker()->needs_push_properties()); EXPECT_TRUE(host_->needs_push_properties()); PushProperties(); - EXPECT_FALSE(ticker_->needs_push_properties()); + EXPECT_FALSE(player_->animation_ticker()->needs_push_properties()); EXPECT_FALSE(host_->needs_push_properties()); - EXPECT_FALSE(ticker_->GetAnimationById(animation_id)); - EXPECT_FALSE(ticker_impl_->GetAnimationById(animation_id)); + EXPECT_FALSE(player_->animation_ticker()->GetAnimationById(animation_id)); + EXPECT_FALSE( + player_impl_->animation_ticker()->GetAnimationById(animation_id)); } // An animation aborted on the impl thread should get deleted on both threads. @@ -1799,13 +1887,13 @@ EXPECT_FALSE(host_->needs_push_properties()); player_impl_->ActivateAnimations(); - EXPECT_TRUE(ticker_impl_->GetAnimationById(animation_id)); + EXPECT_TRUE(player_impl_->animation_ticker()->GetAnimationById(animation_id)); player_impl_->AbortAnimations(TargetProperty::OPACITY, false); EXPECT_EQ(Animation::ABORTED, player_impl_->GetAnimation(TargetProperty::OPACITY)->run_state()); EXPECT_TRUE(host_impl_->needs_push_properties()); - EXPECT_TRUE(ticker_impl_->needs_push_properties()); + EXPECT_TRUE(player_impl_->animation_ticker()->needs_push_properties()); auto events = CreateEventsForTesting(); player_impl_->Tick(kInitialTickTime); @@ -1816,7 +1904,7 @@ EXPECT_EQ(Animation::WAITING_FOR_DELETION, player_impl_->GetAnimation(TargetProperty::OPACITY)->run_state()); - ticker_->NotifyAnimationAborted(events->events_[0]); + player_->animation_ticker()->NotifyAnimationAborted(events->events_[0]); EXPECT_EQ(Animation::ABORTED, player_->GetAnimation(TargetProperty::OPACITY)->run_state()); EXPECT_TRUE(delegate.aborted()); @@ -1830,8 +1918,9 @@ PushProperties(); player_impl_->ActivateAnimations(); - EXPECT_FALSE(ticker_->GetAnimationById(animation_id)); - EXPECT_FALSE(ticker_impl_->GetAnimationById(animation_id)); + EXPECT_FALSE(player_->animation_ticker()->GetAnimationById(animation_id)); + EXPECT_FALSE( + player_impl_->animation_ticker()->GetAnimationById(animation_id)); } // Test that an impl-only scroll offset animation that needs to be completed on @@ -1865,7 +1954,7 @@ EXPECT_FALSE(host_->needs_push_properties()); player_impl_->ActivateAnimations(); - EXPECT_TRUE(ticker_impl_->GetAnimationById(animation_id)); + EXPECT_TRUE(player_impl_->animation_ticker()->GetAnimationById(animation_id)); player_impl_->AbortAnimations(TargetProperty::SCROLL_OFFSET, true); EXPECT_TRUE(host_impl_->needs_push_properties()); @@ -1887,20 +1976,21 @@ EXPECT_EQ(nullptr, player_impl_->GetAnimation(TargetProperty::SCROLL_OFFSET)); // MT receives the event to take over. - ticker_->NotifyAnimationTakeover(events->events_[0]); + player_->animation_ticker()->NotifyAnimationTakeover(events->events_[0]); EXPECT_TRUE(delegate.takeover()); - // AnimationPlayer::NotifyAnimationTakeover requests SetNeedsPushProperties - // to purge CT animations marked for deletion. - EXPECT_TRUE(ticker_->needs_push_properties()); + // SingleTickerAnimationPlayer::NotifyAnimationTakeover requests + // SetNeedsPushProperties to purge CT animations marked for deletion. + EXPECT_TRUE(player_->animation_ticker()->needs_push_properties()); // ElementAnimations::PurgeAnimationsMarkedForDeletion call happens only in // ElementAnimations::PushPropertiesTo. PushProperties(); player_impl_->ActivateAnimations(); - EXPECT_FALSE(ticker_->GetAnimationById(animation_id)); - EXPECT_FALSE(ticker_impl_->GetAnimationById(animation_id)); + EXPECT_FALSE(player_->animation_ticker()->GetAnimationById(animation_id)); + EXPECT_FALSE( + player_impl_->animation_ticker()->GetAnimationById(animation_id)); } // Ensure that we only generate FINISHED events for animations in a group @@ -1943,8 +2033,9 @@ // a FINISHED event yet. EXPECT_EQ(0u, events->events_.size()); EXPECT_EQ(Animation::FINISHED, - ticker_impl_->GetAnimationById(2)->run_state()); - EXPECT_EQ(Animation::RUNNING, ticker_impl_->GetAnimationById(1)->run_state()); + player_impl_->animation_ticker()->GetAnimationById(2)->run_state()); + EXPECT_EQ(Animation::RUNNING, + player_impl_->animation_ticker()->GetAnimationById(1)->run_state()); player_impl_->Tick(kInitialTickTime + TimeDelta::FromMilliseconds(2000)); player_impl_->UpdateState(true, events.get()); @@ -2006,20 +2097,20 @@ AttachTimelinePlayerLayer(); CreateImplTimelineAndPlayer(); - EXPECT_TRUE( - ticker_impl_->HasOnlyTranslationTransforms(ElementListType::ACTIVE)); - EXPECT_TRUE( - ticker_impl_->HasOnlyTranslationTransforms(ElementListType::PENDING)); + EXPECT_TRUE(player_impl_->animation_ticker()->HasOnlyTranslationTransforms( + ElementListType::ACTIVE)); + EXPECT_TRUE(player_impl_->animation_ticker()->HasOnlyTranslationTransforms( + ElementListType::PENDING)); - ticker_impl_->AddAnimation(CreateAnimation( + player_impl_->AddAnimation(CreateAnimation( std::unique_ptr<AnimationCurve>(new FakeFloatTransition(1.0, 0.f, 1.f)), 1, TargetProperty::OPACITY)); // Opacity animations aren't non-translation transforms. - EXPECT_TRUE( - ticker_impl_->HasOnlyTranslationTransforms(ElementListType::ACTIVE)); - EXPECT_TRUE( - ticker_impl_->HasOnlyTranslationTransforms(ElementListType::PENDING)); + EXPECT_TRUE(player_impl_->animation_ticker()->HasOnlyTranslationTransforms( + ElementListType::ACTIVE)); + EXPECT_TRUE(player_impl_->animation_ticker()->HasOnlyTranslationTransforms( + ElementListType::PENDING)); std::unique_ptr<KeyframedTransformAnimationCurve> curve1( KeyframedTransformAnimationCurve::Create()); @@ -2033,13 +2124,13 @@ std::unique_ptr<Animation> animation( Animation::Create(std::move(curve1), 2, 2, TargetProperty::TRANSFORM)); - ticker_impl_->AddAnimation(std::move(animation)); + player_impl_->AddAnimation(std::move(animation)); // The only transform animation we've added is a translation. - EXPECT_TRUE( - ticker_impl_->HasOnlyTranslationTransforms(ElementListType::ACTIVE)); - EXPECT_TRUE( - ticker_impl_->HasOnlyTranslationTransforms(ElementListType::PENDING)); + EXPECT_TRUE(player_impl_->animation_ticker()->HasOnlyTranslationTransforms( + ElementListType::ACTIVE)); + EXPECT_TRUE(player_impl_->animation_ticker()->HasOnlyTranslationTransforms( + ElementListType::PENDING)); std::unique_ptr<KeyframedTransformAnimationCurve> curve2( KeyframedTransformAnimationCurve::Create()); @@ -2054,35 +2145,37 @@ animation = Animation::Create(std::move(curve2), 3, 3, TargetProperty::TRANSFORM); animation->set_affects_active_elements(false); - ticker_impl_->AddAnimation(std::move(animation)); + player_impl_->AddAnimation(std::move(animation)); // A scale animation is not a translation. - EXPECT_FALSE( - ticker_impl_->HasOnlyTranslationTransforms(ElementListType::PENDING)); - EXPECT_TRUE( - ticker_impl_->HasOnlyTranslationTransforms(ElementListType::ACTIVE)); + EXPECT_FALSE(player_impl_->animation_ticker()->HasOnlyTranslationTransforms( + ElementListType::PENDING)); + EXPECT_TRUE(player_impl_->animation_ticker()->HasOnlyTranslationTransforms( + ElementListType::ACTIVE)); - ticker_impl_->ActivateAnimations(); - EXPECT_FALSE( - ticker_impl_->HasOnlyTranslationTransforms(ElementListType::PENDING)); - EXPECT_FALSE( - ticker_impl_->HasOnlyTranslationTransforms(ElementListType::ACTIVE)); + player_impl_->ActivateAnimations(); + EXPECT_FALSE(player_impl_->animation_ticker()->HasOnlyTranslationTransforms( + ElementListType::PENDING)); + EXPECT_FALSE(player_impl_->animation_ticker()->HasOnlyTranslationTransforms( + ElementListType::ACTIVE)); - ticker_impl_->GetAnimationById(3)->set_affects_pending_elements(false); - EXPECT_TRUE( - ticker_impl_->HasOnlyTranslationTransforms(ElementListType::PENDING)); - EXPECT_FALSE( - ticker_impl_->HasOnlyTranslationTransforms(ElementListType::ACTIVE)); + player_impl_->animation_ticker() + ->GetAnimationById(3) + ->set_affects_pending_elements(false); + EXPECT_TRUE(player_impl_->animation_ticker()->HasOnlyTranslationTransforms( + ElementListType::PENDING)); + EXPECT_FALSE(player_impl_->animation_ticker()->HasOnlyTranslationTransforms( + ElementListType::ACTIVE)); - ticker_impl_->GetAnimationById(3)->SetRunState(Animation::FINISHED, - TicksFromSecondsF(0.0)); + player_impl_->animation_ticker()->GetAnimationById(3)->SetRunState( + Animation::FINISHED, TicksFromSecondsF(0.0)); // Only unfinished animations should be considered by // HasOnlyTranslationTransforms. - EXPECT_TRUE( - ticker_impl_->HasOnlyTranslationTransforms(ElementListType::PENDING)); - EXPECT_TRUE( - ticker_impl_->HasOnlyTranslationTransforms(ElementListType::ACTIVE)); + EXPECT_TRUE(player_impl_->animation_ticker()->HasOnlyTranslationTransforms( + ElementListType::PENDING)); + EXPECT_TRUE(player_impl_->animation_ticker()->HasOnlyTranslationTransforms( + ElementListType::ACTIVE)); } TEST_F(ElementAnimationsTest, AnimationStartScale) { @@ -2106,19 +2199,19 @@ player_impl_->AddAnimation(std::move(animation)); float start_scale = 0.f; - EXPECT_TRUE(ticker_impl_->AnimationStartScale(ElementListType::PENDING, - &start_scale)); + EXPECT_TRUE(player_impl_->animation_ticker()->AnimationStartScale( + ElementListType::PENDING, &start_scale)); EXPECT_EQ(4.f, start_scale); - EXPECT_TRUE( - ticker_impl_->AnimationStartScale(ElementListType::ACTIVE, &start_scale)); + EXPECT_TRUE(player_impl_->animation_ticker()->AnimationStartScale( + ElementListType::ACTIVE, &start_scale)); EXPECT_EQ(0.f, start_scale); player_impl_->ActivateAnimations(); - EXPECT_TRUE(ticker_impl_->AnimationStartScale(ElementListType::PENDING, - &start_scale)); + EXPECT_TRUE(player_impl_->animation_ticker()->AnimationStartScale( + ElementListType::PENDING, &start_scale)); EXPECT_EQ(4.f, start_scale); - EXPECT_TRUE( - ticker_impl_->AnimationStartScale(ElementListType::ACTIVE, &start_scale)); + EXPECT_TRUE(player_impl_->animation_ticker()->AnimationStartScale( + ElementListType::ACTIVE, &start_scale)); EXPECT_EQ(4.f, start_scale); std::unique_ptr<KeyframedTransformAnimationCurve> curve2( @@ -2156,31 +2249,31 @@ animation->set_affects_active_elements(false); player_impl_->AddAnimation(std::move(animation)); - EXPECT_TRUE(ticker_impl_->AnimationStartScale(ElementListType::PENDING, - &start_scale)); + EXPECT_TRUE(player_impl_->animation_ticker()->AnimationStartScale( + ElementListType::PENDING, &start_scale)); EXPECT_EQ(6.f, start_scale); - EXPECT_TRUE( - ticker_impl_->AnimationStartScale(ElementListType::ACTIVE, &start_scale)); + EXPECT_TRUE(player_impl_->animation_ticker()->AnimationStartScale( + ElementListType::ACTIVE, &start_scale)); EXPECT_EQ(0.f, start_scale); player_impl_->ActivateAnimations(); - EXPECT_TRUE(ticker_impl_->AnimationStartScale(ElementListType::PENDING, - &start_scale)); + EXPECT_TRUE(player_impl_->animation_ticker()->AnimationStartScale( + ElementListType::PENDING, &start_scale)); EXPECT_EQ(6.f, start_scale); - EXPECT_TRUE( - ticker_impl_->AnimationStartScale(ElementListType::ACTIVE, &start_scale)); + EXPECT_TRUE(player_impl_->animation_ticker()->AnimationStartScale( + ElementListType::ACTIVE, &start_scale)); EXPECT_EQ(6.f, start_scale); - ticker_impl_->GetAnimationById(2)->SetRunState(Animation::FINISHED, - TicksFromSecondsF(0.0)); + player_impl_->animation_ticker()->GetAnimationById(2)->SetRunState( + Animation::FINISHED, TicksFromSecondsF(0.0)); // Only unfinished animations should be considered by // AnimationStartScale. - EXPECT_TRUE(ticker_impl_->AnimationStartScale(ElementListType::PENDING, - &start_scale)); + EXPECT_TRUE(player_impl_->animation_ticker()->AnimationStartScale( + ElementListType::PENDING, &start_scale)); EXPECT_EQ(5.f, start_scale); - EXPECT_TRUE( - ticker_impl_->AnimationStartScale(ElementListType::ACTIVE, &start_scale)); + EXPECT_TRUE(player_impl_->animation_ticker()->AnimationStartScale( + ElementListType::ACTIVE, &start_scale)); EXPECT_EQ(5.f, start_scale); } @@ -2190,11 +2283,11 @@ CreateImplTimelineAndPlayer(); float max_scale = 0.f; - EXPECT_TRUE( - ticker_impl_->MaximumTargetScale(ElementListType::PENDING, &max_scale)); + EXPECT_TRUE(player_impl_->animation_ticker()->MaximumTargetScale( + ElementListType::PENDING, &max_scale)); EXPECT_EQ(0.f, max_scale); - EXPECT_TRUE( - ticker_impl_->MaximumTargetScale(ElementListType::ACTIVE, &max_scale)); + EXPECT_TRUE(player_impl_->animation_ticker()->MaximumTargetScale( + ElementListType::ACTIVE, &max_scale)); EXPECT_EQ(0.f, max_scale); std::unique_ptr<KeyframedTransformAnimationCurve> curve1( @@ -2212,19 +2305,19 @@ animation->set_affects_active_elements(false); player_impl_->AddAnimation(std::move(animation)); - EXPECT_TRUE( - ticker_impl_->MaximumTargetScale(ElementListType::PENDING, &max_scale)); + EXPECT_TRUE(player_impl_->animation_ticker()->MaximumTargetScale( + ElementListType::PENDING, &max_scale)); EXPECT_EQ(4.f, max_scale); - EXPECT_TRUE( - ticker_impl_->MaximumTargetScale(ElementListType::ACTIVE, &max_scale)); + EXPECT_TRUE(player_impl_->animation_ticker()->MaximumTargetScale( + ElementListType::ACTIVE, &max_scale)); EXPECT_EQ(0.f, max_scale); player_impl_->ActivateAnimations(); - EXPECT_TRUE( - ticker_impl_->MaximumTargetScale(ElementListType::PENDING, &max_scale)); + EXPECT_TRUE(player_impl_->animation_ticker()->MaximumTargetScale( + ElementListType::PENDING, &max_scale)); EXPECT_EQ(4.f, max_scale); - EXPECT_TRUE( - ticker_impl_->MaximumTargetScale(ElementListType::ACTIVE, &max_scale)); + EXPECT_TRUE(player_impl_->animation_ticker()->MaximumTargetScale( + ElementListType::ACTIVE, &max_scale)); EXPECT_EQ(4.f, max_scale); std::unique_ptr<KeyframedTransformAnimationCurve> curve2( @@ -2242,19 +2335,19 @@ animation->set_affects_active_elements(false); player_impl_->AddAnimation(std::move(animation)); - EXPECT_TRUE( - ticker_impl_->MaximumTargetScale(ElementListType::PENDING, &max_scale)); + EXPECT_TRUE(player_impl_->animation_ticker()->MaximumTargetScale( + ElementListType::PENDING, &max_scale)); EXPECT_EQ(6.f, max_scale); - EXPECT_TRUE( - ticker_impl_->MaximumTargetScale(ElementListType::ACTIVE, &max_scale)); + EXPECT_TRUE(player_impl_->animation_ticker()->MaximumTargetScale( + ElementListType::ACTIVE, &max_scale)); EXPECT_EQ(4.f, max_scale); player_impl_->ActivateAnimations(); - EXPECT_TRUE( - ticker_impl_->MaximumTargetScale(ElementListType::PENDING, &max_scale)); + EXPECT_TRUE(player_impl_->animation_ticker()->MaximumTargetScale( + ElementListType::PENDING, &max_scale)); EXPECT_EQ(6.f, max_scale); - EXPECT_TRUE( - ticker_impl_->MaximumTargetScale(ElementListType::ACTIVE, &max_scale)); + EXPECT_TRUE(player_impl_->animation_ticker()->MaximumTargetScale( + ElementListType::ACTIVE, &max_scale)); EXPECT_EQ(6.f, max_scale); std::unique_ptr<KeyframedTransformAnimationCurve> curve3( @@ -2272,30 +2365,30 @@ animation->set_affects_active_elements(false); player_impl_->AddAnimation(std::move(animation)); - EXPECT_FALSE( - ticker_impl_->MaximumTargetScale(ElementListType::PENDING, &max_scale)); - EXPECT_TRUE( - ticker_impl_->MaximumTargetScale(ElementListType::ACTIVE, &max_scale)); + EXPECT_FALSE(player_impl_->animation_ticker()->MaximumTargetScale( + ElementListType::PENDING, &max_scale)); + EXPECT_TRUE(player_impl_->animation_ticker()->MaximumTargetScale( + ElementListType::ACTIVE, &max_scale)); EXPECT_EQ(6.f, max_scale); player_impl_->ActivateAnimations(); - EXPECT_FALSE( - ticker_impl_->MaximumTargetScale(ElementListType::PENDING, &max_scale)); - EXPECT_FALSE( - ticker_impl_->MaximumTargetScale(ElementListType::ACTIVE, &max_scale)); + EXPECT_FALSE(player_impl_->animation_ticker()->MaximumTargetScale( + ElementListType::PENDING, &max_scale)); + EXPECT_FALSE(player_impl_->animation_ticker()->MaximumTargetScale( + ElementListType::ACTIVE, &max_scale)); - ticker_impl_->GetAnimationById(3)->SetRunState(Animation::FINISHED, - TicksFromSecondsF(0.0)); - ticker_impl_->GetAnimationById(2)->SetRunState(Animation::FINISHED, - TicksFromSecondsF(0.0)); + player_impl_->animation_ticker()->GetAnimationById(3)->SetRunState( + Animation::FINISHED, TicksFromSecondsF(0.0)); + player_impl_->animation_ticker()->GetAnimationById(2)->SetRunState( + Animation::FINISHED, TicksFromSecondsF(0.0)); // Only unfinished animations should be considered by // MaximumTargetScale. - EXPECT_TRUE( - ticker_impl_->MaximumTargetScale(ElementListType::PENDING, &max_scale)); + EXPECT_TRUE(player_impl_->animation_ticker()->MaximumTargetScale( + ElementListType::PENDING, &max_scale)); EXPECT_EQ(4.f, max_scale); - EXPECT_TRUE( - ticker_impl_->MaximumTargetScale(ElementListType::ACTIVE, &max_scale)); + EXPECT_TRUE(player_impl_->animation_ticker()->MaximumTargetScale( + ElementListType::ACTIVE, &max_scale)); EXPECT_EQ(4.f, max_scale); } @@ -2326,76 +2419,76 @@ // NORMAL direction with positive playback rate. animation->set_direction(Animation::Direction::NORMAL); - EXPECT_TRUE( - ticker_impl_->MaximumTargetScale(ElementListType::PENDING, &max_scale)); + EXPECT_TRUE(player_impl_->animation_ticker()->MaximumTargetScale( + ElementListType::PENDING, &max_scale)); EXPECT_EQ(6.f, max_scale); - EXPECT_TRUE( - ticker_impl_->MaximumTargetScale(ElementListType::ACTIVE, &max_scale)); + EXPECT_TRUE(player_impl_->animation_ticker()->MaximumTargetScale( + ElementListType::ACTIVE, &max_scale)); EXPECT_EQ(6.f, max_scale); // ALTERNATE direction with positive playback rate. animation->set_direction(Animation::Direction::ALTERNATE_NORMAL); - EXPECT_TRUE( - ticker_impl_->MaximumTargetScale(ElementListType::PENDING, &max_scale)); + EXPECT_TRUE(player_impl_->animation_ticker()->MaximumTargetScale( + ElementListType::PENDING, &max_scale)); EXPECT_EQ(6.f, max_scale); - EXPECT_TRUE( - ticker_impl_->MaximumTargetScale(ElementListType::ACTIVE, &max_scale)); + EXPECT_TRUE(player_impl_->animation_ticker()->MaximumTargetScale( + ElementListType::ACTIVE, &max_scale)); EXPECT_EQ(6.f, max_scale); // REVERSE direction with positive playback rate. animation->set_direction(Animation::Direction::REVERSE); - EXPECT_TRUE( - ticker_impl_->MaximumTargetScale(ElementListType::PENDING, &max_scale)); + EXPECT_TRUE(player_impl_->animation_ticker()->MaximumTargetScale( + ElementListType::PENDING, &max_scale)); EXPECT_EQ(3.f, max_scale); - EXPECT_TRUE( - ticker_impl_->MaximumTargetScale(ElementListType::ACTIVE, &max_scale)); + EXPECT_TRUE(player_impl_->animation_ticker()->MaximumTargetScale( + ElementListType::ACTIVE, &max_scale)); EXPECT_EQ(3.f, max_scale); // ALTERNATE reverse direction. animation->set_direction(Animation::Direction::REVERSE); - EXPECT_TRUE( - ticker_impl_->MaximumTargetScale(ElementListType::PENDING, &max_scale)); + EXPECT_TRUE(player_impl_->animation_ticker()->MaximumTargetScale( + ElementListType::PENDING, &max_scale)); EXPECT_EQ(3.f, max_scale); - EXPECT_TRUE( - ticker_impl_->MaximumTargetScale(ElementListType::ACTIVE, &max_scale)); + EXPECT_TRUE(player_impl_->animation_ticker()->MaximumTargetScale( + ElementListType::ACTIVE, &max_scale)); EXPECT_EQ(3.f, max_scale); animation->set_playback_rate(-1.0); // NORMAL direction with negative playback rate. animation->set_direction(Animation::Direction::NORMAL); - EXPECT_TRUE( - ticker_impl_->MaximumTargetScale(ElementListType::PENDING, &max_scale)); + EXPECT_TRUE(player_impl_->animation_ticker()->MaximumTargetScale( + ElementListType::PENDING, &max_scale)); EXPECT_EQ(3.f, max_scale); - EXPECT_TRUE( - ticker_impl_->MaximumTargetScale(ElementListType::ACTIVE, &max_scale)); + EXPECT_TRUE(player_impl_->animation_ticker()->MaximumTargetScale( + ElementListType::ACTIVE, &max_scale)); EXPECT_EQ(3.f, max_scale); // ALTERNATE direction with negative playback rate. animation->set_direction(Animation::Direction::ALTERNATE_NORMAL); - EXPECT_TRUE( - ticker_impl_->MaximumTargetScale(ElementListType::PENDING, &max_scale)); + EXPECT_TRUE(player_impl_->animation_ticker()->MaximumTargetScale( + ElementListType::PENDING, &max_scale)); EXPECT_EQ(3.f, max_scale); - EXPECT_TRUE( - ticker_impl_->MaximumTargetScale(ElementListType::ACTIVE, &max_scale)); + EXPECT_TRUE(player_impl_->animation_ticker()->MaximumTargetScale( + ElementListType::ACTIVE, &max_scale)); EXPECT_EQ(3.f, max_scale); // REVERSE direction with negative playback rate. animation->set_direction(Animation::Direction::REVERSE); - EXPECT_TRUE( - ticker_impl_->MaximumTargetScale(ElementListType::PENDING, &max_scale)); + EXPECT_TRUE(player_impl_->animation_ticker()->MaximumTargetScale( + ElementListType::PENDING, &max_scale)); EXPECT_EQ(6.f, max_scale); - EXPECT_TRUE( - ticker_impl_->MaximumTargetScale(ElementListType::ACTIVE, &max_scale)); + EXPECT_TRUE(player_impl_->animation_ticker()->MaximumTargetScale( + ElementListType::ACTIVE, &max_scale)); EXPECT_EQ(6.f, max_scale); // ALTERNATE reverse direction with negative playback rate. animation->set_direction(Animation::Direction::REVERSE); - EXPECT_TRUE( - ticker_impl_->MaximumTargetScale(ElementListType::PENDING, &max_scale)); + EXPECT_TRUE(player_impl_->animation_ticker()->MaximumTargetScale( + ElementListType::PENDING, &max_scale)); EXPECT_EQ(6.f, max_scale); - EXPECT_TRUE( - ticker_impl_->MaximumTargetScale(ElementListType::ACTIVE, &max_scale)); + EXPECT_TRUE(player_impl_->animation_ticker()->MaximumTargetScale( + ElementListType::ACTIVE, &max_scale)); EXPECT_EQ(6.f, max_scale); } @@ -2408,28 +2501,35 @@ int animation_id = AddOpacityTransitionToPlayer(player_.get(), 1, 0.5f, 1.f, false); - EXPECT_TRUE(ticker_->GetAnimationById(animation_id)); - EXPECT_FALSE(ticker_impl_->GetAnimationById(animation_id)); + EXPECT_TRUE(player_->animation_ticker()->GetAnimationById(animation_id)); + EXPECT_FALSE( + player_impl_->animation_ticker()->GetAnimationById(animation_id)); PushProperties(); - EXPECT_TRUE(ticker_impl_->GetAnimationById(animation_id)); + EXPECT_TRUE(player_impl_->animation_ticker()->GetAnimationById(animation_id)); EXPECT_EQ(Animation::WAITING_FOR_TARGET_AVAILABILITY, - ticker_impl_->GetAnimationById(animation_id)->run_state()); - EXPECT_TRUE( - ticker_impl_->GetAnimationById(animation_id)->affects_pending_elements()); - EXPECT_FALSE( - ticker_impl_->GetAnimationById(animation_id)->affects_active_elements()); + player_impl_->animation_ticker() + ->GetAnimationById(animation_id) + ->run_state()); + EXPECT_TRUE(player_impl_->animation_ticker() + ->GetAnimationById(animation_id) + ->affects_pending_elements()); + EXPECT_FALSE(player_impl_->animation_ticker() + ->GetAnimationById(animation_id) + ->affects_active_elements()); player_impl_->Tick(kInitialTickTime); - EXPECT_EQ(Animation::STARTING, - ticker_impl_->GetAnimationById(animation_id)->run_state()); + EXPECT_EQ(Animation::STARTING, player_impl_->animation_ticker() + ->GetAnimationById(animation_id) + ->run_state()); player_impl_->UpdateState(true, events.get()); // Since the animation hasn't been activated, it should still be STARTING // rather than RUNNING. - EXPECT_EQ(Animation::STARTING, - ticker_impl_->GetAnimationById(animation_id)->run_state()); + EXPECT_EQ(Animation::STARTING, player_impl_->animation_ticker() + ->GetAnimationById(animation_id) + ->run_state()); // Since the animation hasn't been activated, only the pending observer // should have been ticked. @@ -2438,18 +2538,21 @@ EXPECT_EQ(0.f, client_impl_.GetOpacity(element_id_, ElementListType::ACTIVE)); player_impl_->ActivateAnimations(); - EXPECT_TRUE( - ticker_impl_->GetAnimationById(animation_id)->affects_pending_elements()); - EXPECT_TRUE( - ticker_impl_->GetAnimationById(animation_id)->affects_active_elements()); + EXPECT_TRUE(player_impl_->animation_ticker() + ->GetAnimationById(animation_id) + ->affects_pending_elements()); + EXPECT_TRUE(player_impl_->animation_ticker() + ->GetAnimationById(animation_id) + ->affects_active_elements()); player_impl_->Tick(kInitialTickTime + TimeDelta::FromMilliseconds(1000)); player_impl_->UpdateState(true, events.get()); // Since the animation has been activated, it should have reached the // RUNNING state and the active observer should start to get ticked. - EXPECT_EQ(Animation::RUNNING, - ticker_impl_->GetAnimationById(animation_id)->run_state()); + EXPECT_EQ(Animation::RUNNING, player_impl_->animation_ticker() + ->GetAnimationById(animation_id) + ->run_state()); EXPECT_EQ(0.5f, client_impl_.GetOpacity(element_id_, ElementListType::PENDING)); EXPECT_EQ(0.5f, @@ -2468,13 +2571,17 @@ PushProperties(); - EXPECT_TRUE(ticker_impl_->GetAnimationById(animation_id)); + EXPECT_TRUE(player_impl_->animation_ticker()->GetAnimationById(animation_id)); EXPECT_EQ(Animation::WAITING_FOR_TARGET_AVAILABILITY, - ticker_impl_->GetAnimationById(animation_id)->run_state()); - EXPECT_TRUE( - ticker_impl_->GetAnimationById(animation_id)->affects_pending_elements()); - EXPECT_FALSE( - ticker_impl_->GetAnimationById(animation_id)->affects_active_elements()); + player_impl_->animation_ticker() + ->GetAnimationById(animation_id) + ->run_state()); + EXPECT_TRUE(player_impl_->animation_ticker() + ->GetAnimationById(animation_id) + ->affects_pending_elements()); + EXPECT_FALSE(player_impl_->animation_ticker() + ->GetAnimationById(animation_id) + ->affects_active_elements()); player_impl_->Tick(kInitialTickTime); @@ -2485,17 +2592,20 @@ EXPECT_EQ(0.f, client_impl_.GetOpacity(element_id_, ElementListType::ACTIVE)); player_impl_->ActivateAnimations(); - EXPECT_TRUE( - ticker_impl_->GetAnimationById(animation_id)->affects_pending_elements()); - EXPECT_TRUE( - ticker_impl_->GetAnimationById(animation_id)->affects_active_elements()); + EXPECT_TRUE(player_impl_->animation_ticker() + ->GetAnimationById(animation_id) + ->affects_pending_elements()); + EXPECT_TRUE(player_impl_->animation_ticker() + ->GetAnimationById(animation_id) + ->affects_active_elements()); player_impl_->UpdateState(true, events.get()); // Since the animation has been activated, it should have reached the // RUNNING state. - EXPECT_EQ(Animation::RUNNING, - ticker_impl_->GetAnimationById(animation_id)->run_state()); + EXPECT_EQ(Animation::RUNNING, player_impl_->animation_ticker() + ->GetAnimationById(animation_id) + ->run_state()); player_impl_->Tick(kInitialTickTime + TimeDelta::FromMilliseconds(500)); @@ -2556,7 +2666,7 @@ player_impl_->Tick(kInitialTickTime); player_impl_->UpdateState(true, events.get()); - ticker_->NotifyAnimationStarted(events->events_[0]); + player_->animation_ticker()->NotifyAnimationStarted(events->events_[0]); events->events_.clear(); // Finish the animation. @@ -2594,9 +2704,11 @@ // Case 2: An animation that's removed before it finishes. int animation_id = AddAnimatedTransformToPlayer(player_.get(), 10.0, 2, 2); int animation2_id = AddAnimatedTransformToPlayer(player_.get(), 10.0, 2, 1); - ticker_->GetAnimationById(animation2_id) + player_->animation_ticker() + ->GetAnimationById(animation2_id) ->set_time_offset(base::TimeDelta::FromMilliseconds(-10000)); - ticker_->GetAnimationById(animation2_id) + player_->animation_ticker() + ->GetAnimationById(animation2_id) ->set_fill_mode(Animation::FillMode::NONE); EXPECT_TRUE(client_.GetHasPotentialTransformAnimation( element_id_, ElementListType::ACTIVE)); @@ -2625,7 +2737,7 @@ player_impl_->Tick(kInitialTickTime + TimeDelta::FromMilliseconds(2000)); player_impl_->UpdateState(true, events.get()); - ticker_->NotifyAnimationStarted(events->events_[0]); + player_->animation_ticker()->NotifyAnimationStarted(events->events_[0]); events->events_.clear(); player_->RemoveAnimation(animation_id); @@ -2677,7 +2789,7 @@ player_impl_->Tick(kInitialTickTime + TimeDelta::FromMilliseconds(2000)); player_impl_->UpdateState(true, events.get()); - ticker_->NotifyAnimationStarted(events->events_[0]); + player_->animation_ticker()->NotifyAnimationStarted(events->events_[0]); events->events_.clear(); player_impl_->AbortAnimations(TargetProperty::TRANSFORM, false); @@ -2701,9 +2813,11 @@ // Case 4 : An animation that's not in effect. animation_id = AddAnimatedTransformToPlayer(player_.get(), 1.0, 1, 6); - ticker_->GetAnimationById(animation_id) + player_->animation_ticker() + ->GetAnimationById(animation_id) ->set_time_offset(base::TimeDelta::FromMilliseconds(-10000)); - ticker_->GetAnimationById(animation_id) + player_->animation_ticker() + ->GetAnimationById(animation_id) ->set_fill_mode(Animation::FillMode::NONE); PushProperties(); @@ -2774,7 +2888,7 @@ player_impl_->Tick(kInitialTickTime); player_impl_->UpdateState(true, events.get()); - ticker_->NotifyAnimationStarted(events->events_[0]); + player_->animation_ticker()->NotifyAnimationStarted(events->events_[0]); events->events_.clear(); // Finish the animation. @@ -2836,7 +2950,7 @@ player_impl_->Tick(kInitialTickTime + TimeDelta::FromMilliseconds(2000)); player_impl_->UpdateState(true, events.get()); - ticker_->NotifyAnimationStarted(events->events_[0]); + player_->animation_ticker()->NotifyAnimationStarted(events->events_[0]); events->events_.clear(); player_->RemoveAnimation(animation_id); @@ -2888,7 +3002,7 @@ player_impl_->Tick(kInitialTickTime + TimeDelta::FromMilliseconds(2000)); player_impl_->UpdateState(true, events.get()); - ticker_->NotifyAnimationStarted(events->events_[0]); + player_->animation_ticker()->NotifyAnimationStarted(events->events_[0]); events->events_.clear(); player_impl_->AbortAnimations(TargetProperty::OPACITY, false); @@ -2913,9 +3027,11 @@ // Case 4 : An animation that's not in effect. animation_id = AddOpacityTransitionToPlayer(player_.get(), 1.0, 0.f, 0.5f, false /*use_timing_function*/); - ticker_->GetAnimationById(animation_id) + player_->animation_ticker() + ->GetAnimationById(animation_id) ->set_time_offset(base::TimeDelta::FromMilliseconds(-10000)); - ticker_->GetAnimationById(animation_id) + player_->animation_ticker() + ->GetAnimationById(animation_id) ->set_fill_mode(Animation::FillMode::NONE); PushProperties(); @@ -2985,7 +3101,7 @@ player_impl_->Tick(kInitialTickTime); player_impl_->UpdateState(true, events.get()); - ticker_->NotifyAnimationStarted(events->events_[0]); + player_->animation_ticker()->NotifyAnimationStarted(events->events_[0]); events->events_.clear(); // Finish the animation. @@ -3046,7 +3162,7 @@ player_impl_->Tick(kInitialTickTime + TimeDelta::FromMilliseconds(2000)); player_impl_->UpdateState(true, events.get()); - ticker_->NotifyAnimationStarted(events->events_[0]); + player_->animation_ticker()->NotifyAnimationStarted(events->events_[0]); events->events_.clear(); player_->RemoveAnimation(animation_id); @@ -3097,7 +3213,7 @@ player_impl_->Tick(kInitialTickTime + TimeDelta::FromMilliseconds(2000)); player_impl_->UpdateState(true, events.get()); - ticker_->NotifyAnimationStarted(events->events_[0]); + player_->animation_ticker()->NotifyAnimationStarted(events->events_[0]); events->events_.clear(); player_impl_->AbortAnimations(TargetProperty::FILTER, false); @@ -3121,9 +3237,11 @@ // Case 4 : An animation that's not in effect. animation_id = AddAnimatedFilterToPlayer(player_.get(), 1.0, 0.f, 0.5f); - ticker_->GetAnimationById(animation_id) + player_->animation_ticker() + ->GetAnimationById(animation_id) ->set_time_offset(base::TimeDelta::FromMilliseconds(-10000)); - ticker_->GetAnimationById(animation_id) + player_->animation_ticker() + ->GetAnimationById(animation_id) ->set_fill_mode(Animation::FillMode::NONE); PushProperties(); @@ -3184,17 +3302,20 @@ player_impl_->ActivateAnimations(); player_impl_->Tick(kInitialTickTime); player_impl_->UpdateState(true, events.get()); - EXPECT_EQ(Animation::RUNNING, - ticker_impl_->GetAnimationById(animation_id)->run_state()); + EXPECT_EQ(Animation::RUNNING, player_impl_->animation_ticker() + ->GetAnimationById(animation_id) + ->run_state()); EXPECT_EQ(0.5f, client_impl_.GetOpacity(element_id_, ElementListType::PENDING)); EXPECT_EQ(0.5f, client_impl_.GetOpacity(element_id_, ElementListType::ACTIVE)); - EXPECT_TRUE( - ticker_impl_->GetAnimationById(animation_id)->affects_pending_elements()); - EXPECT_TRUE( - ticker_impl_->GetAnimationById(animation_id)->affects_active_elements()); + EXPECT_TRUE(player_impl_->animation_ticker() + ->GetAnimationById(animation_id) + ->affects_pending_elements()); + EXPECT_TRUE(player_impl_->animation_ticker() + ->GetAnimationById(animation_id) + ->affects_active_elements()); // Delete the animation on the main-thread animations. player_->RemoveAnimation( @@ -3202,10 +3323,12 @@ PushProperties(); // The animation should no longer affect pending elements. - EXPECT_FALSE( - ticker_impl_->GetAnimationById(animation_id)->affects_pending_elements()); - EXPECT_TRUE( - ticker_impl_->GetAnimationById(animation_id)->affects_active_elements()); + EXPECT_FALSE(player_impl_->animation_ticker() + ->GetAnimationById(animation_id) + ->affects_pending_elements()); + EXPECT_TRUE(player_impl_->animation_ticker() + ->GetAnimationById(animation_id) + ->affects_active_elements()); player_impl_->Tick(kInitialTickTime + TimeDelta::FromMilliseconds(500)); player_impl_->UpdateState(true, events.get()); @@ -3224,14 +3347,16 @@ // thread. UpdateState for this animation would put the animation to wait for // deletion state. EXPECT_EQ(Animation::WAITING_FOR_DELETION, - ticker_impl_->GetAnimationById(animation_id)->run_state()); + player_impl_->animation_ticker() + ->GetAnimationById(animation_id) + ->run_state()); EXPECT_EQ(1u, events->events_.size()); // The animation is finished on impl thread, and main thread will delete it // during commit. player_->animation_host()->SetAnimationEvents(std::move(events)); PushProperties(); - EXPECT_FALSE(ticker_impl_->has_any_animation()); + EXPECT_FALSE(player_impl_->animation_ticker()->has_any_animation()); } // Tests that an animation that affects only active elements won't block @@ -3261,13 +3386,17 @@ // The original animation should only affect active elements, and the new // animation should only affect pending elements. - EXPECT_FALSE(ticker_impl_->GetAnimationById(first_animation_id) + EXPECT_FALSE(player_impl_->animation_ticker() + ->GetAnimationById(first_animation_id) ->affects_pending_elements()); - EXPECT_TRUE(ticker_impl_->GetAnimationById(first_animation_id) + EXPECT_TRUE(player_impl_->animation_ticker() + ->GetAnimationById(first_animation_id) ->affects_active_elements()); - EXPECT_TRUE(ticker_impl_->GetAnimationById(second_animation_id) + EXPECT_TRUE(player_impl_->animation_ticker() + ->GetAnimationById(second_animation_id) ->affects_pending_elements()); - EXPECT_FALSE(ticker_impl_->GetAnimationById(second_animation_id) + EXPECT_FALSE(player_impl_->animation_ticker() + ->GetAnimationById(second_animation_id) ->affects_active_elements()); player_impl_->Tick(kInitialTickTime + TimeDelta::FromMilliseconds(500)); @@ -3275,10 +3404,12 @@ // The original animation should still be running, and the new animation // should be starting. - EXPECT_EQ(Animation::RUNNING, - ticker_impl_->GetAnimationById(first_animation_id)->run_state()); - EXPECT_EQ(Animation::STARTING, - ticker_impl_->GetAnimationById(second_animation_id)->run_state()); + EXPECT_EQ(Animation::RUNNING, player_impl_->animation_ticker() + ->GetAnimationById(first_animation_id) + ->run_state()); + EXPECT_EQ(Animation::STARTING, player_impl_->animation_ticker() + ->GetAnimationById(second_animation_id) + ->run_state()); // The active observer should have been ticked by the original animation, // and the pending observer should have been ticked by the new animation. @@ -3291,13 +3422,17 @@ // The original animation no longer affect either elements, and the new // animation should now affect both elements. - EXPECT_FALSE(ticker_impl_->GetAnimationById(first_animation_id) + EXPECT_FALSE(player_impl_->animation_ticker() + ->GetAnimationById(first_animation_id) ->affects_pending_elements()); - EXPECT_FALSE(ticker_impl_->GetAnimationById(first_animation_id) + EXPECT_FALSE(player_impl_->animation_ticker() + ->GetAnimationById(first_animation_id) ->affects_active_elements()); - EXPECT_TRUE(ticker_impl_->GetAnimationById(second_animation_id) + EXPECT_TRUE(player_impl_->animation_ticker() + ->GetAnimationById(second_animation_id) ->affects_pending_elements()); - EXPECT_TRUE(ticker_impl_->GetAnimationById(second_animation_id) + EXPECT_TRUE(player_impl_->animation_ticker() + ->GetAnimationById(second_animation_id) ->affects_active_elements()); player_impl_->Tick(kInitialTickTime + TimeDelta::FromMilliseconds(1000)); @@ -3305,12 +3440,15 @@ // The original animation should be marked for waiting for deletion. EXPECT_EQ(Animation::WAITING_FOR_DELETION, - ticker_impl_->GetAnimationById(first_animation_id)->run_state()); + player_impl_->animation_ticker() + ->GetAnimationById(first_animation_id) + ->run_state()); // The new animation should be running, and the active observer should have // been ticked at the new animation's starting point. - EXPECT_EQ(Animation::RUNNING, - ticker_impl_->GetAnimationById(second_animation_id)->run_state()); + EXPECT_EQ(Animation::RUNNING, player_impl_->animation_ticker() + ->GetAnimationById(second_animation_id) + ->run_state()); EXPECT_EQ(1.f, client_impl_.GetOpacity(element_id_, ElementListType::PENDING)); EXPECT_EQ(1.f, client_impl_.GetOpacity(element_id_, ElementListType::ACTIVE)); @@ -3328,44 +3466,44 @@ player_->AddAnimation(std::move(animation)); player_->Tick(kInitialTickTime); - EXPECT_TRUE(ticker_->IsCurrentlyAnimatingProperty(TargetProperty::OPACITY, - ElementListType::PENDING)); - EXPECT_FALSE(ticker_->IsCurrentlyAnimatingProperty(TargetProperty::OPACITY, - ElementListType::ACTIVE)); + EXPECT_TRUE(player_->animation_ticker()->IsCurrentlyAnimatingProperty( + TargetProperty::OPACITY, ElementListType::PENDING)); + EXPECT_FALSE(player_->animation_ticker()->IsCurrentlyAnimatingProperty( + TargetProperty::OPACITY, ElementListType::ACTIVE)); player_->UpdateState(true, nullptr); - EXPECT_TRUE(ticker_->HasTickingAnimation()); + EXPECT_TRUE(player_->animation_ticker()->HasTickingAnimation()); - EXPECT_TRUE(ticker_->IsCurrentlyAnimatingProperty(TargetProperty::OPACITY, - ElementListType::PENDING)); - EXPECT_FALSE(ticker_->IsCurrentlyAnimatingProperty(TargetProperty::OPACITY, - ElementListType::ACTIVE)); - EXPECT_FALSE(ticker_->IsCurrentlyAnimatingProperty(TargetProperty::FILTER, - ElementListType::PENDING)); - EXPECT_FALSE(ticker_->IsCurrentlyAnimatingProperty(TargetProperty::FILTER, - ElementListType::ACTIVE)); + EXPECT_TRUE(player_->animation_ticker()->IsCurrentlyAnimatingProperty( + TargetProperty::OPACITY, ElementListType::PENDING)); + EXPECT_FALSE(player_->animation_ticker()->IsCurrentlyAnimatingProperty( + TargetProperty::OPACITY, ElementListType::ACTIVE)); + EXPECT_FALSE(player_->animation_ticker()->IsCurrentlyAnimatingProperty( + TargetProperty::FILTER, ElementListType::PENDING)); + EXPECT_FALSE(player_->animation_ticker()->IsCurrentlyAnimatingProperty( + TargetProperty::FILTER, ElementListType::ACTIVE)); player_->ActivateAnimations(); - EXPECT_TRUE(ticker_->IsCurrentlyAnimatingProperty(TargetProperty::OPACITY, - ElementListType::PENDING)); - EXPECT_TRUE(ticker_->IsCurrentlyAnimatingProperty(TargetProperty::OPACITY, - ElementListType::ACTIVE)); - EXPECT_FALSE(ticker_->IsCurrentlyAnimatingProperty(TargetProperty::FILTER, - ElementListType::PENDING)); - EXPECT_FALSE(ticker_->IsCurrentlyAnimatingProperty(TargetProperty::FILTER, - ElementListType::ACTIVE)); + EXPECT_TRUE(player_->animation_ticker()->IsCurrentlyAnimatingProperty( + TargetProperty::OPACITY, ElementListType::PENDING)); + EXPECT_TRUE(player_->animation_ticker()->IsCurrentlyAnimatingProperty( + TargetProperty::OPACITY, ElementListType::ACTIVE)); + EXPECT_FALSE(player_->animation_ticker()->IsCurrentlyAnimatingProperty( + TargetProperty::FILTER, ElementListType::PENDING)); + EXPECT_FALSE(player_->animation_ticker()->IsCurrentlyAnimatingProperty( + TargetProperty::FILTER, ElementListType::ACTIVE)); player_->Tick(kInitialTickTime + TimeDelta::FromMilliseconds(10)); player_->UpdateState(true, nullptr); - EXPECT_TRUE(ticker_->IsCurrentlyAnimatingProperty(TargetProperty::OPACITY, - ElementListType::PENDING)); - EXPECT_TRUE(ticker_->IsCurrentlyAnimatingProperty(TargetProperty::OPACITY, - ElementListType::ACTIVE)); - EXPECT_FALSE(ticker_->IsCurrentlyAnimatingProperty(TargetProperty::FILTER, - ElementListType::PENDING)); - EXPECT_FALSE(ticker_->IsCurrentlyAnimatingProperty(TargetProperty::FILTER, - ElementListType::ACTIVE)); + EXPECT_TRUE(player_->animation_ticker()->IsCurrentlyAnimatingProperty( + TargetProperty::OPACITY, ElementListType::PENDING)); + EXPECT_TRUE(player_->animation_ticker()->IsCurrentlyAnimatingProperty( + TargetProperty::OPACITY, ElementListType::ACTIVE)); + EXPECT_FALSE(player_->animation_ticker()->IsCurrentlyAnimatingProperty( + TargetProperty::FILTER, ElementListType::PENDING)); + EXPECT_FALSE(player_->animation_ticker()->IsCurrentlyAnimatingProperty( + TargetProperty::FILTER, ElementListType::ACTIVE)); EXPECT_EQ(0.f, client_.GetOpacity(element_id_, ElementListType::ACTIVE)); @@ -3373,14 +3511,14 @@ player_->Tick(kInitialTickTime + TimeDelta::FromMilliseconds(1100)); player_->UpdateState(true, nullptr); - EXPECT_FALSE(ticker_->IsCurrentlyAnimatingProperty(TargetProperty::OPACITY, - ElementListType::PENDING)); - EXPECT_FALSE(ticker_->IsCurrentlyAnimatingProperty(TargetProperty::OPACITY, - ElementListType::ACTIVE)); - EXPECT_FALSE(ticker_->IsCurrentlyAnimatingProperty(TargetProperty::FILTER, - ElementListType::PENDING)); - EXPECT_FALSE(ticker_->IsCurrentlyAnimatingProperty(TargetProperty::FILTER, - ElementListType::ACTIVE)); + EXPECT_FALSE(player_->animation_ticker()->IsCurrentlyAnimatingProperty( + TargetProperty::OPACITY, ElementListType::PENDING)); + EXPECT_FALSE(player_->animation_ticker()->IsCurrentlyAnimatingProperty( + TargetProperty::OPACITY, ElementListType::ACTIVE)); + EXPECT_FALSE(player_->animation_ticker()->IsCurrentlyAnimatingProperty( + TargetProperty::FILTER, ElementListType::PENDING)); + EXPECT_FALSE(player_->animation_ticker()->IsCurrentlyAnimatingProperty( + TargetProperty::FILTER, ElementListType::ACTIVE)); EXPECT_EQ(1.f, client_.GetOpacity(element_id_, ElementListType::ACTIVE)); } @@ -3405,34 +3543,34 @@ // Since the animation has a start delay, the elements it affects have a // potentially running transform animation but aren't currently animating // transform. - EXPECT_TRUE(ticker_->IsPotentiallyAnimatingProperty( + EXPECT_TRUE(player_->animation_ticker()->IsPotentiallyAnimatingProperty( TargetProperty::OPACITY, ElementListType::PENDING)); - EXPECT_FALSE(ticker_->IsPotentiallyAnimatingProperty( + EXPECT_FALSE(player_->animation_ticker()->IsPotentiallyAnimatingProperty( TargetProperty::OPACITY, ElementListType::ACTIVE)); - EXPECT_FALSE(ticker_->IsCurrentlyAnimatingProperty(TargetProperty::OPACITY, - ElementListType::PENDING)); - EXPECT_FALSE(ticker_->IsCurrentlyAnimatingProperty(TargetProperty::OPACITY, - ElementListType::ACTIVE)); - EXPECT_TRUE(ticker_->HasTickingAnimation()); - EXPECT_FALSE(ticker_->IsPotentiallyAnimatingProperty( + EXPECT_FALSE(player_->animation_ticker()->IsCurrentlyAnimatingProperty( + TargetProperty::OPACITY, ElementListType::PENDING)); + EXPECT_FALSE(player_->animation_ticker()->IsCurrentlyAnimatingProperty( + TargetProperty::OPACITY, ElementListType::ACTIVE)); + EXPECT_TRUE(player_->animation_ticker()->HasTickingAnimation()); + EXPECT_FALSE(player_->animation_ticker()->IsPotentiallyAnimatingProperty( TargetProperty::FILTER, ElementListType::PENDING)); - EXPECT_FALSE(ticker_->IsPotentiallyAnimatingProperty( + EXPECT_FALSE(player_->animation_ticker()->IsPotentiallyAnimatingProperty( TargetProperty::FILTER, ElementListType::ACTIVE)); player_->ActivateAnimations(); - EXPECT_TRUE(ticker_->IsPotentiallyAnimatingProperty( + EXPECT_TRUE(player_->animation_ticker()->IsPotentiallyAnimatingProperty( TargetProperty::OPACITY, ElementListType::PENDING)); - EXPECT_TRUE(ticker_->IsPotentiallyAnimatingProperty(TargetProperty::OPACITY, - ElementListType::ACTIVE)); - EXPECT_FALSE(ticker_->IsCurrentlyAnimatingProperty(TargetProperty::OPACITY, - ElementListType::PENDING)); - EXPECT_FALSE(ticker_->IsCurrentlyAnimatingProperty(TargetProperty::OPACITY, - ElementListType::ACTIVE)); - EXPECT_TRUE(ticker_->HasTickingAnimation()); - EXPECT_FALSE(ticker_->IsPotentiallyAnimatingProperty( + EXPECT_TRUE(player_->animation_ticker()->IsPotentiallyAnimatingProperty( + TargetProperty::OPACITY, ElementListType::ACTIVE)); + EXPECT_FALSE(player_->animation_ticker()->IsCurrentlyAnimatingProperty( + TargetProperty::OPACITY, ElementListType::PENDING)); + EXPECT_FALSE(player_->animation_ticker()->IsCurrentlyAnimatingProperty( + TargetProperty::OPACITY, ElementListType::ACTIVE)); + EXPECT_TRUE(player_->animation_ticker()->HasTickingAnimation()); + EXPECT_FALSE(player_->animation_ticker()->IsPotentiallyAnimatingProperty( TargetProperty::FILTER, ElementListType::PENDING)); - EXPECT_FALSE(ticker_->IsPotentiallyAnimatingProperty( + EXPECT_FALSE(player_->animation_ticker()->IsPotentiallyAnimatingProperty( TargetProperty::FILTER, ElementListType::ACTIVE)); player_->UpdateState(true, nullptr); @@ -3440,28 +3578,28 @@ // Tick past the start delay. player_->Tick(kInitialTickTime + TimeDelta::FromMilliseconds(2000)); player_->UpdateState(true, nullptr); - EXPECT_TRUE(ticker_->IsPotentiallyAnimatingProperty( + EXPECT_TRUE(player_->animation_ticker()->IsPotentiallyAnimatingProperty( TargetProperty::OPACITY, ElementListType::PENDING)); - EXPECT_TRUE(ticker_->IsPotentiallyAnimatingProperty(TargetProperty::OPACITY, - ElementListType::ACTIVE)); - EXPECT_TRUE(ticker_->IsCurrentlyAnimatingProperty(TargetProperty::OPACITY, - ElementListType::PENDING)); - EXPECT_TRUE(ticker_->IsCurrentlyAnimatingProperty(TargetProperty::OPACITY, - ElementListType::ACTIVE)); + EXPECT_TRUE(player_->animation_ticker()->IsPotentiallyAnimatingProperty( + TargetProperty::OPACITY, ElementListType::ACTIVE)); + EXPECT_TRUE(player_->animation_ticker()->IsCurrentlyAnimatingProperty( + TargetProperty::OPACITY, ElementListType::PENDING)); + EXPECT_TRUE(player_->animation_ticker()->IsCurrentlyAnimatingProperty( + TargetProperty::OPACITY, ElementListType::ACTIVE)); // After the animaton finishes, the elements it affects have neither a // potentially running transform animation nor a currently running transform // animation. player_->Tick(kInitialTickTime + TimeDelta::FromMilliseconds(4000)); player_->UpdateState(true, nullptr); - EXPECT_FALSE(ticker_->IsPotentiallyAnimatingProperty( + EXPECT_FALSE(player_->animation_ticker()->IsPotentiallyAnimatingProperty( TargetProperty::OPACITY, ElementListType::PENDING)); - EXPECT_FALSE(ticker_->IsPotentiallyAnimatingProperty( + EXPECT_FALSE(player_->animation_ticker()->IsPotentiallyAnimatingProperty( TargetProperty::OPACITY, ElementListType::ACTIVE)); - EXPECT_FALSE(ticker_->IsCurrentlyAnimatingProperty(TargetProperty::OPACITY, - ElementListType::PENDING)); - EXPECT_FALSE(ticker_->IsCurrentlyAnimatingProperty(TargetProperty::OPACITY, - ElementListType::ACTIVE)); + EXPECT_FALSE(player_->animation_ticker()->IsCurrentlyAnimatingProperty( + TargetProperty::OPACITY, ElementListType::PENDING)); + EXPECT_FALSE(player_->animation_ticker()->IsCurrentlyAnimatingProperty( + TargetProperty::OPACITY, ElementListType::ACTIVE)); } TEST_F(ElementAnimationsTest, DestroyTestMainLayerBeforePushProperties) { @@ -3493,7 +3631,7 @@ std::unique_ptr<AnimationCurve>(new FakeFloatTransition(1.0, 1.f, 0.5f)), 2, TargetProperty::OPACITY)); ASSERT_EQ(1u, host_->ticking_players_for_testing().size()); - ticker_->RemoveFromTicking(); + player_->animation_ticker()->RemoveFromTicking(); ASSERT_EQ(0u, host_->ticking_players_for_testing().size()); // Ensure that adding a new animation will correctly update the ticking @@ -3519,7 +3657,7 @@ TargetProperty::TRANSFORM)); EXPECT_EQ(2u, player_->TickingAnimationsCount()); EXPECT_EQ(2u, host_->CompositedAnimationsCount()); - ticker_->RemoveFromTicking(); + player_->animation_ticker()->RemoveFromTicking(); EXPECT_EQ(0u, host_->CompositedAnimationsCount()); }
diff --git a/cc/animation/scroll_offset_animations_impl.cc b/cc/animation/scroll_offset_animations_impl.cc index a41c1ee..14c7839 100644 --- a/cc/animation/scroll_offset_animations_impl.cc +++ b/cc/animation/scroll_offset_animations_impl.cc
@@ -6,9 +6,9 @@ #include "cc/animation/animation_host.h" #include "cc/animation/animation_id_provider.h" -#include "cc/animation/animation_player.h" #include "cc/animation/animation_timeline.h" #include "cc/animation/element_animations.h" +#include "cc/animation/single_ticker_animation_player.h" #include "cc/animation/timing_function.h" namespace cc { @@ -18,8 +18,8 @@ : animation_host_(animation_host), scroll_offset_timeline_( AnimationTimeline::Create(AnimationIdProvider::NextTimelineId())), - scroll_offset_animation_player_( - AnimationPlayer::Create(AnimationIdProvider::NextPlayerId())) { + scroll_offset_animation_player_(SingleTickerAnimationPlayer::Create( + AnimationIdProvider::NextPlayerId())) { scroll_offset_timeline_->set_is_impl_only(true); scroll_offset_animation_player_->set_animation_delegate(this); @@ -66,7 +66,7 @@ base::TimeTicks frame_monotonic_time, base::TimeDelta delayed_by) { DCHECK(scroll_offset_animation_player_); - if (!scroll_offset_animation_player_->element_animations()) + if (!scroll_offset_animation_player_->has_element_animations()) return false; DCHECK_EQ(element_id, scroll_offset_animation_player_->element_id()); @@ -112,7 +112,7 @@ if (element_id != scroll_offset_animation_player_->element_id()) return; - if (!scroll_offset_animation_player_->element_animations()) + if (!scroll_offset_animation_player_->has_element_animations()) return; Animation* animation = scroll_offset_animation_player_->GetAnimation(
diff --git a/cc/animation/scroll_offset_animations_impl.h b/cc/animation/scroll_offset_animations_impl.h index e7c95d35..325da37 100644 --- a/cc/animation/scroll_offset_animations_impl.h +++ b/cc/animation/scroll_offset_animations_impl.h
@@ -15,9 +15,9 @@ namespace cc { -class AnimationPlayer; class AnimationHost; class AnimationTimeline; +class SingleTickerAnimationPlayer; // Contains an AnimationTimeline and its AnimationPlayer that owns the impl // only scroll offset animations running on a particular CC Layer. @@ -78,7 +78,7 @@ // We have just one player for impl-only scroll offset animations. // I.e. only one element can have an impl-only scroll offset animation at // any given time. - scoped_refptr<AnimationPlayer> scroll_offset_animation_player_; + scoped_refptr<SingleTickerAnimationPlayer> scroll_offset_animation_player_; DISALLOW_COPY_AND_ASSIGN(ScrollOffsetAnimationsImpl); };
diff --git a/cc/animation/single_ticker_animation_player.cc b/cc/animation/single_ticker_animation_player.cc new file mode 100644 index 0000000..eed9b218 --- /dev/null +++ b/cc/animation/single_ticker_animation_player.cc
@@ -0,0 +1,99 @@ +// 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 "cc/animation/single_ticker_animation_player.h" + +#include <inttypes.h> +#include <algorithm> + +#include "base/stl_util.h" +#include "base/strings/stringprintf.h" +#include "cc/animation/animation_delegate.h" +#include "cc/animation/animation_events.h" +#include "cc/animation/animation_host.h" +#include "cc/animation/animation_ticker.h" +#include "cc/animation/animation_timeline.h" +#include "cc/animation/scroll_offset_animation_curve.h" +#include "cc/animation/transform_operations.h" +#include "cc/trees/property_animation_state.h" + +namespace cc { + +scoped_refptr<SingleTickerAnimationPlayer> SingleTickerAnimationPlayer::Create( + int id) { + return base::WrapRefCounted(new SingleTickerAnimationPlayer(id)); +} + +SingleTickerAnimationPlayer::SingleTickerAnimationPlayer(int id) + : AnimationPlayer(id) { + DCHECK(id_); + AddTicker(base::MakeUnique<AnimationTicker>(NextTickerId())); +} + +SingleTickerAnimationPlayer::SingleTickerAnimationPlayer(int id, + size_t ticker_id) + : AnimationPlayer(id) { + DCHECK(id_); + AddTicker(base::MakeUnique<AnimationTicker>(ticker_id)); +} + +SingleTickerAnimationPlayer::~SingleTickerAnimationPlayer() {} + +AnimationTicker* SingleTickerAnimationPlayer::GetTicker() const { + DCHECK_EQ(tickers_.size(), 1u); + return tickers_[0].get(); +} + +scoped_refptr<AnimationPlayer> SingleTickerAnimationPlayer::CreateImplInstance() + const { + DCHECK(GetTicker()); + scoped_refptr<SingleTickerAnimationPlayer> player = base::WrapRefCounted( + new SingleTickerAnimationPlayer(id(), GetTicker()->id())); + return player; +} + +ElementId SingleTickerAnimationPlayer::element_id() const { + return element_id_of_ticker(GetTicker()->id()); +} + +void SingleTickerAnimationPlayer::AttachElement(ElementId element_id) { + AttachElementForTicker(element_id, GetTicker()->id()); +} + +AnimationTicker* SingleTickerAnimationPlayer::animation_ticker() const { + return GetTicker(); +} + +void SingleTickerAnimationPlayer::AddAnimation( + std::unique_ptr<Animation> animation) { + AddAnimationForTicker(std::move(animation), GetTicker()->id()); +} + +void SingleTickerAnimationPlayer::PauseAnimation(int animation_id, + double time_offset) { + PauseAnimationForTicker(animation_id, time_offset, GetTicker()->id()); +} + +void SingleTickerAnimationPlayer::RemoveAnimation(int animation_id) { + RemoveAnimationForTicker(animation_id, GetTicker()->id()); +} + +void SingleTickerAnimationPlayer::AbortAnimation(int animation_id) { + AbortAnimationForTicker(animation_id, GetTicker()->id()); +} + +bool SingleTickerAnimationPlayer::NotifyAnimationFinishedForTesting( + TargetProperty::Type target_property, + int group_id) { + AnimationEvent event(AnimationEvent::FINISHED, GetTicker()->element_id(), + group_id, target_property, base::TimeTicks()); + return GetTicker()->NotifyAnimationFinished(event); +} + +Animation* SingleTickerAnimationPlayer::GetAnimation( + TargetProperty::Type target_property) const { + return GetAnimationForTicker(target_property, GetTicker()->id()); +} + +} // namespace cc
diff --git a/cc/animation/single_ticker_animation_player.h b/cc/animation/single_ticker_animation_player.h new file mode 100644 index 0000000..924ccf3 --- /dev/null +++ b/cc/animation/single_ticker_animation_player.h
@@ -0,0 +1,69 @@ +// 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. + +#ifndef CC_ANIMATION_SINGLE_TICKER_ANIMATION_PLAYER_H_ +#define CC_ANIMATION_SINGLE_TICKER_ANIMATION_PLAYER_H_ + +#include <vector> + +#include <memory> +#include "base/macros.h" +#include "base/memory/ref_counted.h" +#include "base/time/time.h" +#include "cc/animation/animation.h" +#include "cc/animation/animation_curve.h" +#include "cc/animation/animation_export.h" +#include "cc/animation/animation_player.h" +#include "cc/animation/element_animations.h" +#include "cc/trees/element_id.h" + +namespace cc { + +class AnimationTicker; + +// SingleTickerAnimationPlayer is a sub-class of AnimationPlayer. It serves as a +// bridge between the cc animation clients and cc because we previously only +// supported single effect(ticker) per player. +// +// There is a 1:1 relationship between SingleTickerAnimationPlayer and the +// AnimationTicker. In general, the base class AnimationPlayer is a 1:N +// relationship to allow for grouped animations. +// +// TODO(yigu): Deprecate SingleTickerAnimationPlayer once grouped animations are +// fully supported by all clients. +class CC_ANIMATION_EXPORT SingleTickerAnimationPlayer : public AnimationPlayer { + public: + static scoped_refptr<SingleTickerAnimationPlayer> Create(int id); + scoped_refptr<AnimationPlayer> CreateImplInstance() const override; + + ElementId element_id() const; + + void AttachElement(ElementId element_id); + + AnimationTicker* animation_ticker() const; + void AddAnimation(std::unique_ptr<Animation> animation); + void PauseAnimation(int animation_id, double time_offset); + void RemoveAnimation(int animation_id); + void AbortAnimation(int animation_id); + + bool NotifyAnimationFinishedForTesting(TargetProperty::Type target_property, + int group_id); + Animation* GetAnimation(TargetProperty::Type target_property) const; + + private: + friend class base::RefCounted<SingleTickerAnimationPlayer>; + + AnimationTicker* GetTicker() const; + + protected: + explicit SingleTickerAnimationPlayer(int id); + explicit SingleTickerAnimationPlayer(int id, size_t ticker_id); + ~SingleTickerAnimationPlayer() override; + + DISALLOW_COPY_AND_ASSIGN(SingleTickerAnimationPlayer); +}; + +} // namespace cc + +#endif // CC_ANIMATION_SINGLE_TICKER_ANIMATION_PLAYER_H_
diff --git a/cc/animation/worklet_animation_player.cc b/cc/animation/worklet_animation_player.cc index 0afbeff..e985f1f 100644 --- a/cc/animation/worklet_animation_player.cc +++ b/cc/animation/worklet_animation_player.cc
@@ -13,7 +13,7 @@ int id, const std::string& name, std::unique_ptr<ScrollTimeline> scroll_timeline) - : AnimationPlayer(id), + : SingleTickerAnimationPlayer(id), name_(name), scroll_timeline_(std::move(scroll_timeline)) {} @@ -43,7 +43,7 @@ } void WorkletAnimationPlayer::Tick(base::TimeTicks monotonic_time) { - animation_ticker_->Tick(monotonic_time, this); + animation_ticker()->Tick(monotonic_time, this); } // TODO(crbug.com/780151): The current time returned should be an offset against @@ -68,7 +68,7 @@ void WorkletAnimationPlayer::PushPropertiesTo( AnimationPlayer* animation_player_impl) { - AnimationPlayer::PushPropertiesTo(animation_player_impl); + SingleTickerAnimationPlayer::PushPropertiesTo(animation_player_impl); static_cast<WorkletAnimationPlayer*>(animation_player_impl) ->SetLocalTime(local_time_); }
diff --git a/cc/animation/worklet_animation_player.h b/cc/animation/worklet_animation_player.h index 6859e1f5..0044a9b6 100644 --- a/cc/animation/worklet_animation_player.h +++ b/cc/animation/worklet_animation_player.h
@@ -7,8 +7,8 @@ #include "base/time/time.h" #include "cc/animation/animation_export.h" -#include "cc/animation/animation_player.h" #include "cc/animation/animation_ticker.h" +#include "cc/animation/single_ticker_animation_player.h" namespace cc { @@ -18,7 +18,7 @@ // timing to be controlled by an animator instance that is running in a // AnimationWorkletGlobalScope. class CC_ANIMATION_EXPORT WorkletAnimationPlayer final - : public AnimationPlayer, + : public SingleTickerAnimationPlayer, AnimationTicker::AnimationTimeProvider { public: WorkletAnimationPlayer(int id,
diff --git a/cc/test/animation_test_common.cc b/cc/test/animation_test_common.cc index fbb07e7..2c68e44 100644 --- a/cc/test/animation_test_common.cc +++ b/cc/test/animation_test_common.cc
@@ -7,11 +7,11 @@ #include "base/memory/ptr_util.h" #include "cc/animation/animation_host.h" #include "cc/animation/animation_id_provider.h" -#include "cc/animation/animation_player.h" #include "cc/animation/animation_ticker.h" #include "cc/animation/element_animations.h" #include "cc/animation/keyframed_animation_curve.h" #include "cc/animation/scroll_offset_animation_curve.h" +#include "cc/animation/single_ticker_animation_player.h" #include "cc/animation/timing_function.h" #include "cc/animation/transform_operations.h" #include "cc/base/time_util.h" @@ -28,7 +28,7 @@ namespace cc { -int AddOpacityTransition(AnimationPlayer* target, +int AddOpacityTransition(SingleTickerAnimationPlayer* target, double duration, float start_opacity, float end_opacity, @@ -53,11 +53,12 @@ TargetProperty::OPACITY)); animation->set_needs_synchronized_start_time(true); - target->AddAnimation(std::move(animation)); + target->AddAnimationForTicker(std::move(animation), + target->animation_ticker()->id()); return id; } -int AddAnimatedTransform(AnimationPlayer* target, +int AddAnimatedTransform(SingleTickerAnimationPlayer* target, double duration, TransformOperations start_operations, TransformOperations operations) { @@ -79,11 +80,12 @@ TargetProperty::TRANSFORM)); animation->set_needs_synchronized_start_time(true); - target->AddAnimation(std::move(animation)); + target->AddAnimationForTicker(std::move(animation), + target->animation_ticker()->id()); return id; } -int AddAnimatedTransform(AnimationPlayer* target, +int AddAnimatedTransform(SingleTickerAnimationPlayer* target, double duration, int delta_x, int delta_y) { @@ -97,7 +99,7 @@ return AddAnimatedTransform(target, duration, start_operations, operations); } -int AddAnimatedFilter(AnimationPlayer* target, +int AddAnimatedFilter(SingleTickerAnimationPlayer* target, double duration, float start_brightness, float end_brightness) { @@ -124,7 +126,8 @@ TargetProperty::FILTER)); animation->set_needs_synchronized_start_time(true); - target->AddAnimation(std::move(animation)); + target->AddAnimationForTicker(std::move(animation), + target->animation_ticker()->id()); return id; } @@ -213,7 +216,7 @@ return base::WrapUnique(new FakeFloatTransition(*this)); } -int AddScrollOffsetAnimationToPlayer(AnimationPlayer* player, +int AddScrollOffsetAnimationToPlayer(SingleTickerAnimationPlayer* player, gfx::ScrollOffset initial_value, gfx::ScrollOffset target_value, bool impl_only) { @@ -230,26 +233,27 @@ TargetProperty::SCROLL_OFFSET)); animation->set_is_impl_only(impl_only); - player->AddAnimation(std::move(animation)); + player->AddAnimationForTicker(std::move(animation), + player->animation_ticker()->id()); return id; } -int AddAnimatedTransformToPlayer(AnimationPlayer* player, +int AddAnimatedTransformToPlayer(SingleTickerAnimationPlayer* player, double duration, int delta_x, int delta_y) { return AddAnimatedTransform(player, duration, delta_x, delta_y); } -int AddAnimatedTransformToPlayer(AnimationPlayer* player, +int AddAnimatedTransformToPlayer(SingleTickerAnimationPlayer* player, double duration, TransformOperations start_operations, TransformOperations operations) { return AddAnimatedTransform(player, duration, start_operations, operations); } -int AddOpacityTransitionToPlayer(AnimationPlayer* player, +int AddOpacityTransitionToPlayer(SingleTickerAnimationPlayer* player, double duration, float start_opacity, float end_opacity, @@ -258,14 +262,14 @@ use_timing_function); } -int AddAnimatedFilterToPlayer(AnimationPlayer* player, +int AddAnimatedFilterToPlayer(SingleTickerAnimationPlayer* player, double duration, float start_brightness, float end_brightness) { return AddAnimatedFilter(player, duration, start_brightness, end_brightness); } -int AddOpacityStepsToPlayer(AnimationPlayer* player, +int AddOpacityStepsToPlayer(SingleTickerAnimationPlayer* player, double duration, float start_opacity, float end_opacity, @@ -288,18 +292,19 @@ TargetProperty::OPACITY)); animation->set_needs_synchronized_start_time(true); - player->AddAnimation(std::move(animation)); + player->AddAnimationForTicker(std::move(animation), + player->animation_ticker()->id()); return id; } void AddAnimationToElementWithPlayer(ElementId element_id, scoped_refptr<AnimationTimeline> timeline, std::unique_ptr<Animation> animation) { - scoped_refptr<AnimationPlayer> player = - AnimationPlayer::Create(AnimationIdProvider::NextPlayerId()); + scoped_refptr<SingleTickerAnimationPlayer> player = + SingleTickerAnimationPlayer::Create(AnimationIdProvider::NextPlayerId()); timeline->AttachPlayer(player); player->AttachElement(element_id); - DCHECK(player->element_animations()); + DCHECK(player->animation_ticker()->element_animations()); player->AddAnimation(std::move(animation)); } @@ -348,11 +353,11 @@ double duration, float start_brightness, float end_brightness) { - scoped_refptr<AnimationPlayer> player = - AnimationPlayer::Create(AnimationIdProvider::NextPlayerId()); + scoped_refptr<SingleTickerAnimationPlayer> player = + SingleTickerAnimationPlayer::Create(AnimationIdProvider::NextPlayerId()); timeline->AttachPlayer(player); player->AttachElement(element_id); - DCHECK(player->element_animations()); + DCHECK(player->animation_ticker()->element_animations()); return AddAnimatedFilterToPlayer(player.get(), duration, start_brightness, end_brightness); } @@ -363,11 +368,11 @@ double duration, int delta_x, int delta_y) { - scoped_refptr<AnimationPlayer> player = - AnimationPlayer::Create(AnimationIdProvider::NextPlayerId()); + scoped_refptr<SingleTickerAnimationPlayer> player = + SingleTickerAnimationPlayer::Create(AnimationIdProvider::NextPlayerId()); timeline->AttachPlayer(player); player->AttachElement(element_id); - DCHECK(player->element_animations()); + DCHECK(player->animation_ticker()->element_animations()); return AddAnimatedTransformToPlayer(player.get(), duration, delta_x, delta_y); } @@ -377,11 +382,11 @@ double duration, TransformOperations start_operations, TransformOperations operations) { - scoped_refptr<AnimationPlayer> player = - AnimationPlayer::Create(AnimationIdProvider::NextPlayerId()); + scoped_refptr<SingleTickerAnimationPlayer> player = + SingleTickerAnimationPlayer::Create(AnimationIdProvider::NextPlayerId()); timeline->AttachPlayer(player); player->AttachElement(element_id); - DCHECK(player->element_animations()); + DCHECK(player->animation_ticker()->element_animations()); return AddAnimatedTransformToPlayer(player.get(), duration, start_operations, operations); } @@ -393,11 +398,11 @@ float start_opacity, float end_opacity, bool use_timing_function) { - scoped_refptr<AnimationPlayer> player = - AnimationPlayer::Create(AnimationIdProvider::NextPlayerId()); + scoped_refptr<SingleTickerAnimationPlayer> player = + SingleTickerAnimationPlayer::Create(AnimationIdProvider::NextPlayerId()); timeline->AttachPlayer(player); player->AttachElement(element_id); - DCHECK(player->element_animations()); + DCHECK(player->animation_ticker()->element_animations()); return AddOpacityTransitionToPlayer(player.get(), duration, start_opacity, end_opacity, use_timing_function); }
diff --git a/cc/test/animation_test_common.h b/cc/test/animation_test_common.h index 0d52c35..c5bd9f1 100644 --- a/cc/test/animation_test_common.h +++ b/cc/test/animation_test_common.h
@@ -13,16 +13,14 @@ #include "cc/test/geometry_test_utils.h" #include "cc/trees/element_id.h" -namespace cc { -class AnimationPlayer; -} - namespace gfx { class ScrollOffset; } namespace cc { +class SingleTickerAnimationPlayer; + class FakeFloatAnimationCurve : public FloatAnimationCurve { public: FakeFloatAnimationCurve(); @@ -75,33 +73,33 @@ float to_; }; -int AddScrollOffsetAnimationToPlayer(AnimationPlayer* player, +int AddScrollOffsetAnimationToPlayer(SingleTickerAnimationPlayer* player, gfx::ScrollOffset initial_value, gfx::ScrollOffset target_value, bool impl_only); -int AddAnimatedTransformToPlayer(AnimationPlayer* player, +int AddAnimatedTransformToPlayer(SingleTickerAnimationPlayer* player, double duration, int delta_x, int delta_y); -int AddAnimatedTransformToPlayer(AnimationPlayer* player, +int AddAnimatedTransformToPlayer(SingleTickerAnimationPlayer* player, double duration, TransformOperations start_operations, TransformOperations operations); -int AddOpacityTransitionToPlayer(AnimationPlayer* player, +int AddOpacityTransitionToPlayer(SingleTickerAnimationPlayer* player, double duration, float start_opacity, float end_opacity, bool use_timing_function); -int AddAnimatedFilterToPlayer(AnimationPlayer* player, +int AddAnimatedFilterToPlayer(SingleTickerAnimationPlayer* player, double duration, float start_brightness, float end_brightness); -int AddOpacityStepsToPlayer(AnimationPlayer* player, +int AddOpacityStepsToPlayer(SingleTickerAnimationPlayer* player, double duration, float start_opacity, float end_opacity,
diff --git a/cc/test/animation_timelines_test_common.cc b/cc/test/animation_timelines_test_common.cc index 313ac73..2524644 100644 --- a/cc/test/animation_timelines_test_common.cc +++ b/cc/test/animation_timelines_test_common.cc
@@ -7,10 +7,10 @@ #include "base/memory/ptr_util.h" #include "cc/animation/animation_events.h" #include "cc/animation/animation_id_provider.h" -#include "cc/animation/animation_player.h" #include "cc/animation/animation_ticker.h" #include "cc/animation/animation_timeline.h" #include "cc/animation/element_animations.h" +#include "cc/animation/single_ticker_animation_player.h" #include "cc/paint/filter_operation.h" #include "cc/paint/filter_operations.h" #include "cc/trees/property_tree.h" @@ -364,7 +364,6 @@ void AnimationTimelinesTest::SetUp() { timeline_ = AnimationTimeline::Create(timeline_id_); - player_ = AnimationPlayer::Create(player_id_); } void AnimationTimelinesTest::TearDown() { @@ -401,7 +400,7 @@ timeline_->AttachPlayer(player_); player_->AttachElement(element_id_); - element_animations_ = player_->element_animations(); + element_animations_ = player_->animation_ticker()->element_animations(); } void AnimationTimelinesTest::CreateImplTimelineAndPlayer() { @@ -412,10 +411,12 @@ void AnimationTimelinesTest::GetImplTimelineAndPlayerByID() { timeline_impl_ = host_impl_->GetTimelineById(timeline_id_); EXPECT_TRUE(timeline_impl_); - player_impl_ = timeline_impl_->GetPlayerById(player_id_); + player_impl_ = static_cast<SingleTickerAnimationPlayer*>( + timeline_impl_->GetPlayerById(player_id_)); EXPECT_TRUE(player_impl_); - element_animations_impl_ = player_impl_->element_animations(); + element_animations_impl_ = + player_impl_->animation_ticker()->element_animations(); } void AnimationTimelinesTest::ReleaseRefPtrs() {
diff --git a/cc/test/animation_timelines_test_common.h b/cc/test/animation_timelines_test_common.h index a7ef85a3..6422b348 100644 --- a/cc/test/animation_timelines_test_common.h +++ b/cc/test/animation_timelines_test_common.h
@@ -18,8 +18,8 @@ namespace cc { -class AnimationPlayer; class AnimationTicker; +class SingleTickerAnimationPlayer; class TestLayer { public: @@ -274,11 +274,11 @@ int next_test_layer_id_; scoped_refptr<AnimationTimeline> timeline_; - scoped_refptr<AnimationPlayer> player_; + scoped_refptr<SingleTickerAnimationPlayer> player_; scoped_refptr<ElementAnimations> element_animations_; scoped_refptr<AnimationTimeline> timeline_impl_; - scoped_refptr<AnimationPlayer> player_impl_; + scoped_refptr<SingleTickerAnimationPlayer> player_impl_; scoped_refptr<ElementAnimations> element_animations_impl_; };
diff --git a/cc/test/layer_tree_test.cc b/cc/test/layer_tree_test.cc index 758126c..3d65ca1 100644 --- a/cc/test/layer_tree_test.cc +++ b/cc/test/layer_tree_test.cc
@@ -12,8 +12,8 @@ #include "base/threading/thread_task_runner_handle.h" #include "cc/animation/animation.h" #include "cc/animation/animation_host.h" -#include "cc/animation/animation_player.h" #include "cc/animation/animation_ticker.h" +#include "cc/animation/single_ticker_animation_player.h" #include "cc/animation/timing_function.h" #include "cc/base/switches.h" #include "cc/input/input_handler.h" @@ -346,7 +346,7 @@ LayerTreeHostImpl::UpdateAnimationState(start_ready_animations); bool has_unfinished_animation = false; for (const auto& it : animation_host()->ticking_players_for_testing()) { - if (it->animation_ticker()->HasTickingAnimation()) { + if (it.get()->TickingAnimationsCount()) { has_unfinished_animation = true; break; } @@ -646,7 +646,7 @@ } void LayerTreeTest::PostAddAnimationToMainThreadPlayer( - AnimationPlayer* player_to_receive_animation) { + SingleTickerAnimationPlayer* player_to_receive_animation) { main_task_runner_->PostTask( FROM_HERE, base::BindOnce(&LayerTreeTest::DispatchAddAnimationToPlayer, @@ -655,7 +655,7 @@ } void LayerTreeTest::PostAddInstantAnimationToMainThreadPlayer( - AnimationPlayer* player_to_receive_animation) { + SingleTickerAnimationPlayer* player_to_receive_animation) { main_task_runner_->PostTask( FROM_HERE, base::BindOnce(&LayerTreeTest::DispatchAddAnimationToPlayer, @@ -664,7 +664,7 @@ } void LayerTreeTest::PostAddLongAnimationToMainThreadPlayer( - AnimationPlayer* player_to_receive_animation) { + SingleTickerAnimationPlayer* player_to_receive_animation) { main_task_runner_->PostTask( FROM_HERE, base::BindOnce(&LayerTreeTest::DispatchAddAnimationToPlayer, @@ -839,7 +839,7 @@ } void LayerTreeTest::DispatchAddAnimationToPlayer( - AnimationPlayer* player_to_receive_animation, + SingleTickerAnimationPlayer* player_to_receive_animation, double animation_duration) { DCHECK(main_task_runner_->BelongsToCurrentThread());
diff --git a/cc/test/layer_tree_test.h b/cc/test/layer_tree_test.h index 1686b664..8f3e8f2e 100644 --- a/cc/test/layer_tree_test.h +++ b/cc/test/layer_tree_test.h
@@ -24,12 +24,12 @@ namespace cc { class AnimationHost; -class AnimationPlayer; class LayerImpl; class LayerTreeHost; class LayerTreeHostForTesting; class LayerTreeTestLayerTreeFrameSinkClient; class Proxy; +class SingleTickerAnimationPlayer; class TestContextProvider; class TestTaskGraphRunner; @@ -73,11 +73,11 @@ void EndTestAfterDelayMs(int delay_milliseconds); void PostAddAnimationToMainThreadPlayer( - AnimationPlayer* player_to_receive_animation); + SingleTickerAnimationPlayer* player_to_receive_animation); void PostAddInstantAnimationToMainThreadPlayer( - AnimationPlayer* player_to_receive_animation); + SingleTickerAnimationPlayer* player_to_receive_animation); void PostAddLongAnimationToMainThreadPlayer( - AnimationPlayer* player_to_receive_animation); + SingleTickerAnimationPlayer* player_to_receive_animation); void PostSetLocalSurfaceIdToMainThread( const viz::LocalSurfaceId& local_surface_id); void PostSetDeferCommitsToMainThread(bool defer_commits); @@ -167,7 +167,7 @@ private: virtual void DispatchAddAnimationToPlayer( - AnimationPlayer* player_to_receive_animation, + SingleTickerAnimationPlayer* player_to_receive_animation, double animation_duration); void DispatchSetLocalSurfaceId(const viz::LocalSurfaceId& local_surface_id); void DispatchSetDeferCommits(bool defer_commits);
diff --git a/cc/trees/layer_tree_host_common_unittest.cc b/cc/trees/layer_tree_host_common_unittest.cc index 774fe2d..b283fb8c 100644 --- a/cc/trees/layer_tree_host_common_unittest.cc +++ b/cc/trees/layer_tree_host_common_unittest.cc
@@ -14,8 +14,8 @@ #include "base/memory/ptr_util.h" #include "cc/animation/animation_host.h" #include "cc/animation/animation_id_provider.h" -#include "cc/animation/animation_player.h" #include "cc/animation/keyframed_animation_curve.h" +#include "cc/animation/single_ticker_animation_player.h" #include "cc/animation/transform_operations.h" #include "cc/base/math_util.h" #include "cc/input/main_thread_scrolling_reason.h" @@ -7328,23 +7328,23 @@ host_impl.active_tree()->SetElementIdsForTesting(); - scoped_refptr<AnimationPlayer> grand_parent_player = - AnimationPlayer::Create(AnimationIdProvider::NextPlayerId()); + scoped_refptr<SingleTickerAnimationPlayer> grand_parent_player = + SingleTickerAnimationPlayer::Create(AnimationIdProvider::NextPlayerId()); timeline->AttachPlayer(grand_parent_player); grand_parent_player->AttachElement(grand_parent_raw->element_id()); - scoped_refptr<AnimationPlayer> parent_player = - AnimationPlayer::Create(AnimationIdProvider::NextPlayerId()); + scoped_refptr<SingleTickerAnimationPlayer> parent_player = + SingleTickerAnimationPlayer::Create(AnimationIdProvider::NextPlayerId()); timeline->AttachPlayer(parent_player); parent_player->AttachElement(parent_raw->element_id()); - scoped_refptr<AnimationPlayer> child_player = - AnimationPlayer::Create(AnimationIdProvider::NextPlayerId()); + scoped_refptr<SingleTickerAnimationPlayer> child_player = + SingleTickerAnimationPlayer::Create(AnimationIdProvider::NextPlayerId()); timeline->AttachPlayer(child_player); child_player->AttachElement(child_raw->element_id()); - scoped_refptr<AnimationPlayer> grand_child_player = - AnimationPlayer::Create(AnimationIdProvider::NextPlayerId()); + scoped_refptr<SingleTickerAnimationPlayer> grand_child_player = + SingleTickerAnimationPlayer::Create(AnimationIdProvider::NextPlayerId()); timeline->AttachPlayer(grand_child_player); grand_child_player->AttachElement(grand_child_raw->element_id()); @@ -8813,12 +8813,13 @@ base::TimeDelta::FromSecondsD(1.0), operation, nullptr)); std::unique_ptr<Animation> transform_animation( Animation::Create(std::move(curve), 3, 3, TargetProperty::TRANSFORM)); - scoped_refptr<AnimationPlayer> player(AnimationPlayer::Create(1)); + scoped_refptr<SingleTickerAnimationPlayer> player( + SingleTickerAnimationPlayer::Create(1)); timeline()->AttachPlayer(player); // TODO(smcgruer): Should attach a timeline and element rather than call this // directly. See http://crbug.com/771316 - host_impl.animation_host()->RegisterPlayerForElement(root_ptr->element_id(), - player.get()); + host_impl.animation_host()->RegisterTickerForElement( + root_ptr->element_id(), player->animation_ticker()); player->AddAnimation(std::move(transform_animation)); grandchild_ptr->set_visible_layer_rect(gfx::Rect()); root_ptr->test_properties()->transform = singular; @@ -8827,8 +8828,9 @@ ExecuteCalculateDrawPropertiesAndSaveUpdateLayerList(root_ptr); EXPECT_EQ(gfx::Rect(0, 0), grandchild_ptr->visible_layer_rect()); - host_impl.animation_host()->UnregisterPlayerForElement(root_ptr->element_id(), - player.get()); + host_impl.animation_host()->UnregisterTickerForElement( + root_ptr->element_id(), player->animation_ticker()); + host_impl.animation_host()->RemoveFromTicking(player.get()); timeline()->DetachPlayer(player); } @@ -8864,20 +8866,22 @@ base::TimeDelta::FromSecondsD(1.0), operation, nullptr)); std::unique_ptr<Animation> transform_animation( Animation::Create(std::move(curve), 3, 3, TargetProperty::TRANSFORM)); - scoped_refptr<AnimationPlayer> player(AnimationPlayer::Create(1)); + scoped_refptr<SingleTickerAnimationPlayer> player( + SingleTickerAnimationPlayer::Create(1)); timeline()->AttachPlayer(player); // TODO(smcgruer): Should attach a timeline and element rather than call this // directly. See http://crbug.com/771316 - host_impl()->animation_host()->RegisterPlayerForElement( - grand_child->element_id(), player.get()); + host_impl()->animation_host()->RegisterTickerForElement( + grand_child->element_id(), player->animation_ticker()); player->AddAnimation(std::move(transform_animation)); ExecuteCalculateDrawProperties(root); EXPECT_EQ(gfx::Rect(0, 0), grand_child->visible_layer_rect()); EXPECT_EQ(gfx::Rect(0, 0), child->visible_layer_rect()); - host_impl()->animation_host()->UnregisterPlayerForElement( - grand_child->element_id(), player.get()); + host_impl()->animation_host()->UnregisterTickerForElement( + grand_child->element_id(), player->animation_ticker()); + host_impl()->animation_host()->RemoveFromTicking(player.get()); timeline()->DetachPlayer(player); } @@ -8928,12 +8932,13 @@ FloatKeyframe::Create(base::TimeDelta::FromSecondsD(1.0), 0.3f, nullptr)); std::unique_ptr<Animation> animation( Animation::Create(std::move(curve), 3, 3, TargetProperty::OPACITY)); - scoped_refptr<AnimationPlayer> player(AnimationPlayer::Create(1)); + scoped_refptr<SingleTickerAnimationPlayer> player( + SingleTickerAnimationPlayer::Create(1)); timeline()->AttachPlayer(player); // TODO(smcgruer): Should attach a timeline and element rather than call this // directly. See http://crbug.com/771316 - host_impl.animation_host()->RegisterPlayerForElement(root_ptr->element_id(), - player.get()); + host_impl.animation_host()->RegisterTickerForElement( + root_ptr->element_id(), player->animation_ticker()); player->AddAnimation(std::move(animation)); root_ptr->test_properties()->opacity = 0.f; grandchild_ptr->set_visible_layer_rect(gfx::Rect()); @@ -8941,8 +8946,9 @@ ExecuteCalculateDrawPropertiesAndSaveUpdateLayerList(root_ptr); EXPECT_EQ(gfx::Rect(10, 10), grandchild_ptr->visible_layer_rect()); - host_impl.animation_host()->UnregisterPlayerForElement(root_ptr->element_id(), - player.get()); + host_impl.animation_host()->UnregisterTickerForElement( + root_ptr->element_id(), player->animation_ticker()); + host_impl.animation_host()->RemoveFromTicking(player.get()); timeline()->DetachPlayer(player); } @@ -9760,8 +9766,8 @@ animated->SetBounds(gfx::Size(20, 20)); animated->SetOpacity(0.f); - scoped_refptr<AnimationPlayer> player = - AnimationPlayer::Create(AnimationIdProvider::NextPlayerId()); + scoped_refptr<SingleTickerAnimationPlayer> player = + SingleTickerAnimationPlayer::Create(AnimationIdProvider::NextPlayerId()); timeline()->AttachPlayer(player); player->AttachElement(animated->element_id()); @@ -9807,8 +9813,8 @@ root->SetForceRenderSurfaceForTesting(true); animated->SetBounds(gfx::Size(20, 20)); - scoped_refptr<AnimationPlayer> player = - AnimationPlayer::Create(AnimationIdProvider::NextPlayerId()); + scoped_refptr<SingleTickerAnimationPlayer> player = + SingleTickerAnimationPlayer::Create(AnimationIdProvider::NextPlayerId()); timeline()->AttachPlayer(player); player->AttachElement(animated->element_id());
diff --git a/cc/trees/layer_tree_host_unittest_animation.cc b/cc/trees/layer_tree_host_unittest_animation.cc index 8f695e36..3b246713 100644 --- a/cc/trees/layer_tree_host_unittest_animation.cc +++ b/cc/trees/layer_tree_host_unittest_animation.cc
@@ -11,12 +11,12 @@ #include "cc/animation/animation_curve.h" #include "cc/animation/animation_host.h" #include "cc/animation/animation_id_provider.h" -#include "cc/animation/animation_player.h" #include "cc/animation/animation_ticker.h" #include "cc/animation/animation_timeline.h" #include "cc/animation/element_animations.h" #include "cc/animation/scroll_offset_animation_curve.h" #include "cc/animation/scroll_offset_animations.h" +#include "cc/animation/single_ticker_animation_player.h" #include "cc/animation/timing_function.h" #include "cc/animation/transform_operations.h" #include "cc/base/completion_event.h" @@ -39,8 +39,8 @@ player_id_(AnimationIdProvider::NextPlayerId()), player_child_id_(AnimationIdProvider::NextPlayerId()) { timeline_ = AnimationTimeline::Create(timeline_id_); - player_ = AnimationPlayer::Create(player_id_); - player_child_ = AnimationPlayer::Create(player_child_id_); + player_ = SingleTickerAnimationPlayer::Create(player_id_); + player_child_ = SingleTickerAnimationPlayer::Create(player_child_id_); player_->set_animation_delegate(this); } @@ -56,9 +56,11 @@ AnimationHost* animation_host_impl = GetImplAnimationHost(&host_impl); timeline_impl_ = animation_host_impl->GetTimelineById(timeline_id_); EXPECT_TRUE(timeline_impl_); - player_impl_ = timeline_impl_->GetPlayerById(player_id_); + player_impl_ = static_cast<SingleTickerAnimationPlayer*>( + timeline_impl_->GetPlayerById(player_id_)); EXPECT_TRUE(player_impl_); - player_child_impl_ = timeline_impl_->GetPlayerById(player_child_id_); + player_child_impl_ = static_cast<SingleTickerAnimationPlayer*>( + timeline_impl_->GetPlayerById(player_child_id_)); EXPECT_TRUE(player_child_impl_); } @@ -69,12 +71,12 @@ protected: scoped_refptr<AnimationTimeline> timeline_; - scoped_refptr<AnimationPlayer> player_; - scoped_refptr<AnimationPlayer> player_child_; + scoped_refptr<SingleTickerAnimationPlayer> player_; + scoped_refptr<SingleTickerAnimationPlayer> player_child_; scoped_refptr<AnimationTimeline> timeline_impl_; - scoped_refptr<AnimationPlayer> player_impl_; - scoped_refptr<AnimationPlayer> player_child_impl_; + scoped_refptr<SingleTickerAnimationPlayer> player_impl_; + scoped_refptr<SingleTickerAnimationPlayer> player_child_impl_; const int timeline_id_; const int player_id_; @@ -311,8 +313,9 @@ scoped_refptr<AnimationTimeline> timeline_impl = GetImplAnimationHost(host_impl)->GetTimelineById(timeline_id_); - scoped_refptr<AnimationPlayer> player_child_impl = - timeline_impl->GetPlayerById(player_child_id_); + scoped_refptr<SingleTickerAnimationPlayer> player_child_impl = + static_cast<SingleTickerAnimationPlayer*>( + timeline_impl->GetPlayerById(player_child_id_)); Animation* animation = player_child_impl->GetAnimation(TargetProperty::OPACITY); @@ -376,8 +379,9 @@ bool has_unfinished_animation) override { scoped_refptr<AnimationTimeline> timeline_impl = GetImplAnimationHost(impl_host)->GetTimelineById(timeline_id_); - scoped_refptr<AnimationPlayer> player_child_impl = - timeline_impl->GetPlayerById(player_child_id_); + scoped_refptr<SingleTickerAnimationPlayer> player_child_impl = + static_cast<SingleTickerAnimationPlayer*>( + timeline_impl->GetPlayerById(player_child_id_)); Animation* animation = player_child_impl->GetAnimation(TargetProperty::OPACITY); @@ -453,8 +457,9 @@ void DidActivateTreeOnThread(LayerTreeHostImpl* host_impl) override { scoped_refptr<AnimationTimeline> timeline_impl = GetImplAnimationHost(host_impl)->GetTimelineById(timeline_id_); - scoped_refptr<AnimationPlayer> player_impl = - timeline_impl->GetPlayerById(player_id_); + scoped_refptr<SingleTickerAnimationPlayer> player_impl = + static_cast<SingleTickerAnimationPlayer*>( + timeline_impl->GetPlayerById(player_id_)); Animation* animation_impl = player_impl->GetAnimation(TargetProperty::OPACITY); @@ -1039,8 +1044,9 @@ scoped_refptr<AnimationTimeline> timeline_impl = GetImplAnimationHost(host_impl)->GetTimelineById(timeline_id_); - scoped_refptr<AnimationPlayer> player_impl = - timeline_impl->GetPlayerById(player_child_id_); + scoped_refptr<SingleTickerAnimationPlayer> player_impl = + static_cast<SingleTickerAnimationPlayer*>( + timeline_impl->GetPlayerById(player_child_id_)); LayerImpl* scroll_layer_impl = host_impl->active_tree()->LayerById(scroll_layer_->id()); @@ -1129,13 +1135,15 @@ bool has_unfinished_animation) override { scoped_refptr<AnimationTimeline> timeline_impl = GetImplAnimationHost(host_impl)->GetTimelineById(timeline_id_); - scoped_refptr<AnimationPlayer> player_impl = - timeline_impl->GetPlayerById(player_id_); - scoped_refptr<AnimationPlayer> player_child_impl = - timeline_impl->GetPlayerById(player_child_id_); + scoped_refptr<SingleTickerAnimationPlayer> player_impl = + static_cast<SingleTickerAnimationPlayer*>( + timeline_impl->GetPlayerById(player_id_)); + scoped_refptr<SingleTickerAnimationPlayer> player_child_impl = + static_cast<SingleTickerAnimationPlayer*>( + timeline_impl->GetPlayerById(player_child_id_)); // wait for tree activation. - if (!player_impl->element_animations()) + if (!player_impl->animation_ticker()->element_animations()) return; Animation* root_animation = @@ -1208,8 +1216,9 @@ scoped_refptr<AnimationTimeline> timeline_impl = GetImplAnimationHost(host_impl)->GetTimelineById(timeline_id_); - scoped_refptr<AnimationPlayer> player_impl = - timeline_impl->GetPlayerById(player_id_); + scoped_refptr<SingleTickerAnimationPlayer> player_impl = + static_cast<SingleTickerAnimationPlayer*>( + timeline_impl->GetPlayerById(player_id_)); LayerImpl* child = sync_tree->LayerById(layer_->id()); Animation* animation = player_impl->GetAnimation(TargetProperty::TRANSFORM); @@ -1254,7 +1263,7 @@ animation_host()->AddAnimationTimeline(timeline_.get()); timeline_->AttachPlayer(player_.get()); player_->AttachElement(layer_->element_id()); - DCHECK(player_->element_animations()); + DCHECK(player_->animation_ticker()->element_animations()); AddOpacityTransitionToPlayer(player_.get(), 10000.0, 0.1f, 0.9f, true); } @@ -1264,26 +1273,32 @@ void DidCommit() override { switch (layer_tree_host()->SourceFrameNumber()) { case 0: - EXPECT_TRUE( - player_->element_animations()->has_element_in_active_list()); - EXPECT_FALSE( - player_->element_animations()->has_element_in_pending_list()); + EXPECT_TRUE(player_->animation_ticker() + ->element_animations() + ->has_element_in_active_list()); + EXPECT_FALSE(player_->animation_ticker() + ->element_animations() + ->has_element_in_pending_list()); EXPECT_TRUE(animation_host()->NeedsTickAnimations()); break; case 1: layer_->RemoveFromParent(); - EXPECT_FALSE( - player_->element_animations()->has_element_in_active_list()); - EXPECT_FALSE( - player_->element_animations()->has_element_in_pending_list()); + EXPECT_FALSE(player_->animation_ticker() + ->element_animations() + ->has_element_in_active_list()); + EXPECT_FALSE(player_->animation_ticker() + ->element_animations() + ->has_element_in_pending_list()); EXPECT_FALSE(animation_host()->NeedsTickAnimations()); break; case 2: layer_tree_host()->root_layer()->AddChild(layer_); - EXPECT_TRUE( - player_->element_animations()->has_element_in_active_list()); - EXPECT_FALSE( - player_->element_animations()->has_element_in_pending_list()); + EXPECT_TRUE(player_->animation_ticker() + ->element_animations() + ->has_element_in_active_list()); + EXPECT_FALSE(player_->animation_ticker() + ->element_animations() + ->has_element_in_pending_list()); EXPECT_TRUE(animation_host()->NeedsTickAnimations()); break; } @@ -1292,23 +1307,27 @@ void DidActivateTreeOnThread(LayerTreeHostImpl* host_impl) override { scoped_refptr<AnimationTimeline> timeline_impl = GetImplAnimationHost(host_impl)->GetTimelineById(timeline_id_); - scoped_refptr<AnimationPlayer> player_impl = - timeline_impl->GetPlayerById(player_id_); + scoped_refptr<SingleTickerAnimationPlayer> player_impl = + static_cast<SingleTickerAnimationPlayer*>( + timeline_impl->GetPlayerById(player_id_)); switch (host_impl->active_tree()->source_frame_number()) { case 0: - EXPECT_TRUE( - player_impl->element_animations()->has_element_in_active_list()); + EXPECT_TRUE(player_impl->animation_ticker() + ->element_animations() + ->has_element_in_active_list()); EXPECT_TRUE(GetImplAnimationHost(host_impl)->NeedsTickAnimations()); break; case 1: - EXPECT_FALSE( - player_impl->element_animations()->has_element_in_active_list()); + EXPECT_FALSE(player_impl->animation_ticker() + ->element_animations() + ->has_element_in_active_list()); EXPECT_FALSE(GetImplAnimationHost(host_impl)->NeedsTickAnimations()); break; case 2: - EXPECT_TRUE( - player_impl->element_animations()->has_element_in_active_list()); + EXPECT_TRUE(player_impl->animation_ticker() + ->element_animations() + ->has_element_in_active_list()); EXPECT_TRUE(GetImplAnimationHost(host_impl)->NeedsTickAnimations()); EndTest(); break; @@ -1789,7 +1808,7 @@ // Check that transform sync happens correctly at commit when we remove and add // a different animation player to an element. -class LayerTreeHostAnimationTestChangeAnimationPlayer +class LayerTreeHostAnimationTestChangeSingleTickerAnimationPlayer : public LayerTreeHostAnimationTest { public: void SetupTree() override { @@ -1847,7 +1866,8 @@ void AfterTest() override {} }; -SINGLE_AND_MULTI_THREAD_TEST_F(LayerTreeHostAnimationTestChangeAnimationPlayer); +SINGLE_AND_MULTI_THREAD_TEST_F( + LayerTreeHostAnimationTestChangeSingleTickerAnimationPlayer); // Check that SetTransformIsPotentiallyAnimatingChanged is called // if we destroy ElementAnimations. @@ -1932,7 +1952,8 @@ MULTI_THREAD_TEST_F( LayerTreeHostAnimationTestSetPotentiallyAnimatingOnLacDestruction); -// Check that we invalidate property trees on AnimationPlayer::SetNeedsCommit. +// Check that we invalidate property trees on +// SingleTickerAnimationPlayer::SetNeedsCommit. class LayerTreeHostAnimationTestRebuildPropertyTreesOnAnimationSetNeedsCommit : public LayerTreeHostAnimationTest { public:
diff --git a/chrome/VERSION b/chrome/VERSION index e82460d2..1ad6650 100644 --- a/chrome/VERSION +++ b/chrome/VERSION
@@ -1,4 +1,4 @@ MAJOR=66 MINOR=0 -BUILD=3335 +BUILD=3336 PATCH=0
diff --git a/chrome/android/java/res/values-v17/styles.xml b/chrome/android/java/res/values-v17/styles.xml index f8d86d8..0873bff 100644 --- a/chrome/android/java/res/values-v17/styles.xml +++ b/chrome/android/java/res/values-v17/styles.xml
@@ -98,7 +98,9 @@ </style> <!-- Web app themes --> - <style name="WebappTheme" parent="MainTheme"> + <!-- Extend MainThemeBase rather than MainTheme to avoid values-v27 navigation bar colors from + being applied --> + <style name="WebappTheme" parent="MainThemeBase"> <item name="android:windowBackground">@null</item> <item name="android:windowDisablePreview">true</item> </style>
diff --git a/chrome/android/java/res/values/dimens.xml b/chrome/android/java/res/values/dimens.xml index 50a1e78..1c22f8d 100644 --- a/chrome/android/java/res/values/dimens.xml +++ b/chrome/android/java/res/values/dimens.xml
@@ -521,7 +521,7 @@ <!-- Miscellaneous dimensions --> <dimen name="action_bar_shadow_height">10dp</dimen> <dimen name="card_corner_radius">2dp</dimen> - <dimen name="clear_text_button_end_padding">8dp</dimen> + <dimen name="clear_text_button_end_padding">4dp</dimen> <dimen name="sync_promo_view_padding">16dp</dimen> <dimen name="sad_tab_bullet_gap">12dp</dimen> <dimen name="sad_tab_bullet_leading_offset">1dp</dimen>
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/compositor/scene_layer/TabListSceneLayer.java b/chrome/android/java/src/org/chromium/chrome/browser/compositor/scene_layer/TabListSceneLayer.java index 861effe0..52f4471 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/compositor/scene_layer/TabListSceneLayer.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/compositor/scene_layer/TabListSceneLayer.java
@@ -81,11 +81,13 @@ toolbarBackgroundColor = defaultThemeColor; textBoxBackgroundColor = ColorUtils.getTextBoxColorForToolbarBackground( res, false, toolbarBackgroundColor, useModernDesign); - // In the modern design, the text box is always drawn in the Java layer rather - // than the compositor layer. - textBoxAlpha = useModernDesign ? 0.f : t.isIncognito() ? textBoxAlpha : 1f; + textBoxAlpha = t.isIncognito() ? textBoxAlpha : 1f; } + // In the modern design, the text box is always drawn in the Java layer rather + // than the compositor layer. + if (useModernDesign) textBoxAlpha = 0.f; + int closeButtonColor = ColorUtils.getThemedAssetColor(toolbarBackgroundColor, t.isIncognito());
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/download/ui/DownloadManagerUi.java b/chrome/android/java/src/org/chromium/chrome/browser/download/ui/DownloadManagerUi.java index cca9d25..7aa679f1 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/download/ui/DownloadManagerUi.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/download/ui/DownloadManagerUi.java
@@ -22,6 +22,7 @@ import org.chromium.base.DiscardableReferencePool; import org.chromium.base.FileUtils; import org.chromium.base.ObserverList; +import org.chromium.base.TraceEvent; import org.chromium.base.VisibleForTesting; import org.chromium.base.metrics.RecordHistogram; import org.chromium.base.metrics.RecordUserAction; @@ -212,6 +213,7 @@ public DownloadManagerUi(Activity activity, boolean isOffTheRecord, ComponentName parentComponent, boolean isSeparateActivity, SnackbarManager snackbarManager) { + TraceEvent.startAsync("DownloadManagerUi shown", hashCode()); mActivity = activity; ChromeApplication application = (ChromeApplication) activity.getApplication(); mBackendProvider = sProviderForTests == null @@ -302,6 +304,7 @@ mBackendProvider.destroy(); mSelectableListLayout.onDestroyed(); + TraceEvent.finishAsync("DownloadManagerUi shown", hashCode()); } /**
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/omnibox/LocationBarLayout.java b/chrome/android/java/src/org/chromium/chrome/browser/omnibox/LocationBarLayout.java index 8c04fd9b..f3d2c05 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/omnibox/LocationBarLayout.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/omnibox/LocationBarLayout.java
@@ -93,7 +93,9 @@ import org.chromium.chrome.browser.widget.bottomsheet.BottomSheetPaddingUtils; import org.chromium.components.security_state.ConnectionSecurityLevel; import org.chromium.content_public.browser.LoadUrlParams; +import org.chromium.content_public.browser.RenderFrameHost; import org.chromium.content_public.browser.WebContents; +import org.chromium.content_public.browser.WebContentsObserver; import org.chromium.content_public.common.ContentUrlConstants; import org.chromium.ui.UiUtils; import org.chromium.ui.base.DeviceFormFactor; @@ -237,6 +239,8 @@ private DeferredOnSelectionRunnable mDeferredOnSelection; + private WebContentsObserver mVoiceSearchWebContentsObserver; + private static abstract class DeferredOnSelectionRunnable implements Runnable { protected final OmniboxSuggestion mSuggestion; protected final int mPosition; @@ -264,6 +268,45 @@ } /** + * Instantiated when a voice search is performed to monitor the web contents for a navigation + * to be started so we can notify the render frame that a user gesture has been performed. This + * allows autoplay of the voice response for search results. + */ + private final class VoiceSearchWebContentsObserver extends WebContentsObserver { + public VoiceSearchWebContentsObserver(WebContents webContents) { + super(webContents); + } + + /** + * Forces the user gesture flag to be set on a render frame if the URL being navigated to + * is a SRP. + * + * @param url The URL for the navigation that started, so we can ensure that what we're + * navigating to is actually a SRP. + */ + private void setReceivedUserGesture(String url) { + WebContents webContents = mWebContents.get(); + if (webContents == null) return; + + RenderFrameHost renderFrameHost = webContents.getMainFrame(); + if (renderFrameHost == null) return; + if (TemplateUrlService.getInstance().isSearchResultsPageFromDefaultSearchProvider( + url)) { + renderFrameHost.setHasReceivedUserGesture(); + } + } + + @Override + public void didFinishNavigation(String url, boolean isInMainFrame, boolean isErrorPage, + boolean hasCommitted, boolean isSameDocument, boolean isFragmentNavigation, + @Nullable Integer pageTransition, int errorCode, String errorDescription, + int httpStatusCode) { + if (hasCommitted && isInMainFrame && !isErrorPage) setReceivedUserGesture(url); + destroy(); + } + } + + /** * Class to handle input from a hardware keyboard when the focus is on the URL bar. In * particular, handle navigating the suggestions list from the keyboard. */ @@ -450,7 +493,7 @@ mSuggestionDefinitionHeight = context.getResources().getDimensionPixelOffset( R.dimen.omnibox_suggestion_definition_height); - int paddingTop = mBottomSheet != null + int paddingTop = useModernDesign() ? 0 : context.getResources().getDimensionPixelOffset( R.dimen.omnibox_suggestion_list_padding_top); @@ -1899,6 +1942,7 @@ } startZeroSuggest(); + RecordUserAction.record("MobileOmniboxDeleteUrl"); return; } else if (!mUrlHasFocus && shouldShowPageInfoForView(v)) { if (mToolbarDataProvider.hasTab() && getCurrentTab().getWebContents() != null @@ -2599,6 +2643,18 @@ url = TemplateUrlService.getInstance().getUrlForVoiceSearchQuery( topResultQuery); } + // Since voice was used, we need to let the frame know that there was a user gesture. + Tab currentTab = getCurrentTab(); + if (currentTab != null) { + if (mVoiceSearchWebContentsObserver != null) { + mVoiceSearchWebContentsObserver.destroy(); + mVoiceSearchWebContentsObserver = null; + } + if (currentTab.getWebContents() != null) { + mVoiceSearchWebContentsObserver = + new VoiceSearchWebContentsObserver(currentTab.getWebContents()); + } + } loadUrl(url, PageTransition.TYPED); }
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/omnibox/LocationBarTablet.java b/chrome/android/java/src/org/chromium/chrome/browser/omnibox/LocationBarTablet.java index 59f4564..0149aee 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/omnibox/LocationBarTablet.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/omnibox/LocationBarTablet.java
@@ -326,6 +326,11 @@ } } + @Override + public boolean useModernDesign() { + return false; + } + /** * @param button The {@link View} of the button to show. * @return An animator to run for the given view when showing buttons in the unfocused location
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/photo_picker/PickerBitmapView.java b/chrome/android/java/src/org/chromium/chrome/browser/photo_picker/PickerBitmapView.java index 8031f4a..b2c4055 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/photo_picker/PickerBitmapView.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/photo_picker/PickerBitmapView.java
@@ -144,6 +144,13 @@ @Override public void onSelectionStateChange(List<PickerBitmap> selectedItems) { + // If the user cancels the dialog before this object has initialized, + // the SelectionDelegate will try to notify us that all selections have + // been cleared. However, we don't need to process that message and, in + // fact, we can't do so because isPictureTile relies on mBitmapDetails + // being initialized. + if (mBitmapDetails == null) return; + updateSelectionState(); if (!isPictureTile()) return; @@ -327,14 +334,6 @@ * Updates the selection controls for this view. */ private void updateSelectionState() { - // If the user cancels the dialog before this object has initialized, - // the SelectionDelegate will try to notify us that all selections have - // been cleared. However, we don't need to process that message and, in - // fact, we can't do so because isPictureTile relies on mBitmapDetails - // being initialized. - if (mBitmapDetails == null) - return; - boolean special = !isPictureTile(); boolean checked = super.isChecked(); boolean anySelection =
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/preferences/password/SavePasswordsPreferences.java b/chrome/android/java/src/org/chromium/chrome/browser/preferences/password/SavePasswordsPreferences.java index e7e5ecb..fc02762 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/preferences/password/SavePasswordsPreferences.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/preferences/password/SavePasswordsPreferences.java
@@ -70,6 +70,9 @@ // Used to pass the password id into a new activity. public static final String PASSWORD_LIST_ID = "id"; + // The key for saving |mSearchQuery| to instance bundle. + private static final String SAVED_STATE_SEARCH_QUERY = "saved-state-search-query"; + // The key for saving |mExportRequested| to instance bundle. private static final String SAVED_STATE_EXPORT_REQUESTED = "saved-state-export-requested"; @@ -145,6 +148,9 @@ mExportFileUri = Uri.parse(uriString); } } + if (savedInstanceState.containsKey(SAVED_STATE_SEARCH_QUERY)) { + mSearchQuery = savedInstanceState.getString(SAVED_STATE_SEARCH_QUERY); + } } @Override @@ -170,6 +176,10 @@ SearchView searchView = (SearchView) searchItem.getActionView(); searchView.setImeOptions(EditorInfo.IME_FLAG_NO_FULLSCREEN); searchItem.setIcon(convertToPlainWhite(searchItem.getIcon())); + if (mSearchQuery != null) { // If a query was recovered, restore the search view. + searchItem.expandActionView(); + searchView.setQuery(mSearchQuery, false); + } searchItem.setOnActionExpandListener(new MenuItem.OnActionExpandListener() { @Override public boolean onMenuItemActionExpand(MenuItem menuItem) { @@ -490,8 +500,8 @@ } mNoPasswords = profileCategory.getPreferenceCount() == 0; if (mNoPasswords) { - displayManageAccountLink(); // Maybe the password is just not on the device. - displayEmptyScreenMessage(); + if (count == 0) displayEmptyScreenMessage(); // Show if the list was already empty. + getPreferenceScreen().removePreference(profileCategory); } } @@ -568,6 +578,9 @@ if (mExportFileUri != null) { outState.putString(SAVED_STATE_EXPORT_FILE_URI, mExportFileUri.toString()); } + if (mSearchQuery != null) { + outState.putString(SAVED_STATE_SEARCH_QUERY, mSearchQuery); + } } @Override
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/tabmodel/TabModelUtils.java b/chrome/android/java/src/org/chromium/chrome/browser/tabmodel/TabModelUtils.java index 55a18d89..3c2f0e3 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/tabmodel/TabModelUtils.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/tabmodel/TabModelUtils.java
@@ -8,6 +8,9 @@ import org.chromium.chrome.browser.tabmodel.TabModel.TabSelectionType; import org.chromium.content.browser.ContentViewCore; +import java.util.ArrayList; +import java.util.List; + /** * A set of convenience methods used for interacting with {@link TabList}s and {@link TabModel}s. */ @@ -151,4 +154,22 @@ model.setIndex(index, TabSelectionType.FROM_USER); } -} \ No newline at end of file + /** + * Returns all the Tabs in the specified TabList that were opened from the Tab with the + * specified ID. The returned Tabs are in the same order as in the TabList. + * @param model The {@link TabModel} to act on. + * @param tabId The ID of the Tab whose children should be returned. + */ + public static List<Tab> getChildTabs(TabList model, int tabId) { + Tab tab = model.getTabAt(tabId); + + ArrayList<Tab> childTabs = new ArrayList<Tab>(); + for (int i = 0; i < model.getCount(); i++) { + if (model.getTabAt(i).getParentId() == tabId) { + childTabs.add(model.getTabAt(i)); + } + } + + return childTabs; + } +}
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/toolbar/ToolbarPhone.java b/chrome/android/java/src/org/chromium/chrome/browser/toolbar/ToolbarPhone.java index 64acdd2..295fe47e 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/toolbar/ToolbarPhone.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/toolbar/ToolbarPhone.java
@@ -485,6 +485,7 @@ // native is loaded. if (mLocationBar.useModernDesign()) { mNewTabButton.setIsModern(); + if (mToolbarShadow != null) mToolbarShadow.setImageDrawable(getToolbarShadowDrawable()); initLocationBarBackground(); } @@ -1114,7 +1115,10 @@ mToolbarButtonsContainer.setTranslationY(0); if (mHomeButton != null) mHomeButton.setTranslationY(0); } - if (!mToolbarShadowPermanentlyHidden) mToolbarShadow.setAlpha(1f); + if (!mToolbarShadowPermanentlyHidden) { + mToolbarShadow.setAlpha( + mLocationBar.useModernDesign() && mUrlBar.hasFocus() ? 0.f : 1.f); + } mLocationBar.setAlpha(1); mForceDrawLocationBarBackground = false; mLocationBarBackgroundAlpha = 255; @@ -1482,11 +1486,19 @@ // This is a workaround for http://crbug.com/574928. Since Jelly Bean is the lowest version // we support now and the next deprecation target, we decided to simply workaround. if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.JELLY_BEAN) { - mToolbarShadow.setImageDrawable( - ApiCompatibilityUtils.getDrawable(getResources(), R.drawable.toolbar_shadow)); + mToolbarShadow.setImageDrawable(getToolbarShadowDrawable()); } } + /** + * @return The {@link Drawable} to use for the toolbar shadow. + */ + private Drawable getToolbarShadowDrawable() { + return ApiCompatibilityUtils.getDrawable(getResources(), + mLocationBar.useModernDesign() ? R.drawable.modern_toolbar_shadow + : R.drawable.toolbar_shadow); + } + @Override public void draw(Canvas canvas) { // If capturing a texture of the toolbar, ensure the alpha is set prior to draw(...) being @@ -1941,6 +1953,13 @@ animator.setInterpolator(BakedBezierInterpolator.FADE_OUT_CURVE); animators.add(animator); } + + if (mLocationBar.useModernDesign()) { + animator = ObjectAnimator.ofFloat(mToolbarShadow, ALPHA, 0); + animator.setDuration(URL_FOCUS_CHANGE_ANIMATION_DURATION_MS); + animator.setInterpolator(BakedBezierInterpolator.TRANSFORM_CURVE); + animators.add(animator); + } } private void populateUrlClearFocusingAnimatorSet(List<Animator> animators) { @@ -2012,6 +2031,13 @@ animators.add(animator); } } + + if (mLocationBar.useModernDesign() && !isLocationBarShownInNTP()) { + animator = ObjectAnimator.ofFloat(mToolbarShadow, ALPHA, 1); + animator.setDuration(URL_FOCUS_CHANGE_ANIMATION_DURATION_MS); + animator.setInterpolator(BakedBezierInterpolator.TRANSFORM_CURVE); + animators.add(animator); + } } @Override @@ -2020,15 +2046,9 @@ triggerUrlFocusAnimation(hasFocus); - if (mToolbarShadowPermanentlyHidden) return; + if (hasFocus) dismissTabSwitcherCallout(); - TransitionDrawable shadowDrawable = (TransitionDrawable) mToolbarShadow.getDrawable(); - if (hasFocus) { - dismissTabSwitcherCallout(); - shadowDrawable.startTransition(URL_FOCUS_CHANGE_ANIMATION_DURATION_MS); - } else { - shadowDrawable.reverseTransition(URL_FOCUS_CHANGE_ANIMATION_DURATION_MS); - } + transitionShadowDrawable(hasFocus); } protected void triggerUrlFocusAnimation(final boolean hasFocus) { @@ -2253,10 +2273,24 @@ protected void handleFindToolbarStateChange(boolean showing) { setVisibility(showing ? View.GONE : View.VISIBLE); + transitionShadowDrawable(showing); + } + + /** + * Transition the shadow drawable, if a transition drawable is being used. + * @param startTransition Whether the transition, showing the second layer on top of the first, + * should begin. See {@link TransitionDrawable#startTransition(int)}. + * If false, the transition will be reversed. + * See {@link TransitionDrawable#reverseTransition(int)}. + */ + private void transitionShadowDrawable(boolean startTransition) { if (mToolbarShadowPermanentlyHidden) return; + // Modern does not use a transition drawable for the shadow. + if (mLocationBar.useModernDesign()) return; + TransitionDrawable shadowDrawable = (TransitionDrawable) mToolbarShadow.getDrawable(); - if (showing) { + if (startTransition) { shadowDrawable.startTransition(URL_FOCUS_CHANGE_ANIMATION_DURATION_MS); } else { shadowDrawable.reverseTransition(URL_FOCUS_CHANGE_ANIMATION_DURATION_MS);
diff --git a/chrome/android/javatests/AndroidManifest.xml b/chrome/android/javatests/AndroidManifest.xml index 2d8c57b..f84772e 100644 --- a/chrome/android/javatests/AndroidManifest.xml +++ b/chrome/android/javatests/AndroidManifest.xml
@@ -58,7 +58,4 @@ android:targetPackage="{{manifest_package}}" android:label="Tests for {{manifest_package}}" chromium-junit4="true"/> - <instrumentation android:name="org.chromium.chrome.test.ChromeInstrumentationTestRunner" - android:targetPackage="{{manifest_package}}" - android:label="Tests for {{manifest_package}}"/> </manifest>
diff --git a/chrome/android/javatests/src/org/chromium/chrome/browser/download/DownloadNotificationServiceTest.java b/chrome/android/javatests/src/org/chromium/chrome/browser/download/DownloadNotificationServiceTest.java index 0eb95b7..2ef756a 100644 --- a/chrome/android/javatests/src/org/chromium/chrome/browser/download/DownloadNotificationServiceTest.java +++ b/chrome/android/javatests/src/org/chromium/chrome/browser/download/DownloadNotificationServiceTest.java
@@ -10,11 +10,14 @@ import android.os.Handler; import android.os.HandlerThread; import android.os.IBinder; +import android.support.test.InstrumentationRegistry; import android.support.test.filters.SmallTest; import android.support.test.runner.AndroidJUnit4; import android.test.ServiceTestCase; +import org.junit.After; import org.junit.Assert; +import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; @@ -112,17 +115,20 @@ }); } + @Before @Override - protected void setUp() throws Exception { + public void setUp() throws Exception { super.setUp(); + setContext(InstrumentationRegistry.getTargetContext()); SharedPreferences sharedPrefs = ContextUtils.getAppSharedPreferences(); // TODO(yolandyan): added for debugging reasons, remove if tests no longer flakes Assert.assertNull(sharedPrefs.getStringSet( DownloadSharedPreferenceHelper.KEY_PENDING_DOWNLOAD_NOTIFICATIONS, null)); } + @After @Override - protected void tearDown() throws Exception { + public void tearDown() throws Exception { SharedPreferences sharedPrefs = ContextUtils.getAppSharedPreferences(); SharedPreferences.Editor editor = sharedPrefs.edit(); editor.remove(DownloadSharedPreferenceHelper.KEY_PENDING_DOWNLOAD_NOTIFICATIONS); @@ -261,7 +267,7 @@ @DisabledTest(message = "crbug.com/773346") public void testPausingWithOngoingDownloads() { setupService(); - Context mockContext = new AdvancedMockContext(getSystemContext()); + Context mockContext = new AdvancedMockContext(InstrumentationRegistry.getTargetContext()); getService().setContext(mockContext); Set<String> notifications = new HashSet<>(); notifications.add(buildEntryString(1, "test1", true, true)); @@ -295,7 +301,7 @@ @DisabledTest(message = "crbug.com/773346") public void testAddingAndCancelingNotifications() { setupService(); - Context mockContext = new AdvancedMockContext(getSystemContext()); + Context mockContext = new AdvancedMockContext(InstrumentationRegistry.getTargetContext()); getService().setContext(mockContext); Set<String> notifications = new HashSet<>(); String guid1 = UUID.randomUUID().toString(); @@ -382,7 +388,7 @@ @DisabledTest(message = "crbug.com/773346") public void testResumeAllPendingDownloads() throws Exception { setupService(); - Context mockContext = new AdvancedMockContext(getSystemContext()); + Context mockContext = new AdvancedMockContext(InstrumentationRegistry.getTargetContext()); getService().setContext(mockContext); Set<String> notifications = new HashSet<>(); String guid1 = UUID.randomUUID().toString(); @@ -402,8 +408,8 @@ DownloadNotificationService service = bindNotificationService(); DownloadManagerService.disableNetworkListenerForTest(); - final MockDownloadManagerService manager = - new MockDownloadManagerService(getSystemContext().getApplicationContext()); + final MockDownloadManagerService manager = new MockDownloadManagerService( + InstrumentationRegistry.getTargetContext().getApplicationContext()); ThreadUtils.runOnUiThreadBlocking(new Runnable() { @Override public void run() { @@ -431,7 +437,7 @@ @DisabledTest(message = "crbug.com/773346") public void testIncognitoDownloadCanceledOnServiceShutdown() throws Exception { setupService(); - Context mockContext = new AdvancedMockContext(getSystemContext()); + Context mockContext = new AdvancedMockContext(InstrumentationRegistry.getTargetContext()); getService().setContext(mockContext); Set<String> notifications = new HashSet<>(); String uuid = UUID.randomUUID().toString();
diff --git a/chrome/android/javatests/src/org/chromium/chrome/browser/preferences/password/SavePasswordsPreferencesTest.java b/chrome/android/javatests/src/org/chromium/chrome/browser/preferences/password/SavePasswordsPreferencesTest.java index 149086e..a76376b 100644 --- a/chrome/android/javatests/src/org/chromium/chrome/browser/preferences/password/SavePasswordsPreferencesTest.java +++ b/chrome/android/javatests/src/org/chromium/chrome/browser/preferences/password/SavePasswordsPreferencesTest.java
@@ -836,16 +836,16 @@ @SmallTest @Feature({"Preferences"}) @EnableFeatures(ChromeFeatureList.PASSWORD_SEARCH) - public void testSearchDisplaysAccountLinkIfSearchTurnsUpEmpty() throws Exception { + public void testSearchDisplaysBlankPageIfSearchTurnsUpEmpty() throws Exception { setPasswordSourceWithMultipleEntries(GREEK_GODS); PreferencesTest.startPreferences(InstrumentationRegistry.getInstrumentation(), SavePasswordsPreferences.class.getName()); + Espresso.onView(withText(startsWith("View and manage"))).check(matches(isDisplayed())); // Open the search which should hide the Account link. Espresso.onView(withSearchMenuIdOrText()).perform(click()); - Espresso.onView(withText(startsWith("View and manage"))).check(doesNotExist()); - // Search for a string that matches nothing which should bring the Account link back. + // Search for a string that matches nothing which should leave the results entirely blank. Espresso.onView(withId(R.id.search_src_text)) .perform(click(), typeText("Mars"), closeSoftKeyboard()); @@ -853,7 +853,9 @@ Espresso.onView(allOf(withText(god.getUserName()), withText(god.getUrl()))) .check(doesNotExist()); } - Espresso.onView(withText(startsWith("View and manage"))).check(matches(isDisplayed())); + Espresso.onView(withText(startsWith("View and manage"))).check(doesNotExist()); + Espresso.onView(withText(R.string.saved_passwords_none_text)).check(doesNotExist()); + Espresso.onView(withText(R.string.section_saved_passwords)).check(doesNotExist()); } /** @@ -1006,5 +1008,10 @@ Espresso.onView(withText(ZEUS_ON_EARTH.getUserName())).check(matches(isDisplayed())); Espresso.onView(withText(PHOBOS_AT_OLYMP.getUserName())).check(doesNotExist()); Espresso.onView(withText(HADES_AT_UNDERWORLD.getUrl())).check(doesNotExist()); + InstrumentationRegistry.getInstrumentation().waitForIdleSync(); + + // The search bar should still be open and still display the search query. + Espresso.onView(withId(R.id.search_src_text)).check(matches(isDisplayed())); + Espresso.onView(withId(R.id.search_src_text)).check(matches(withText("Zeu"))); } }
diff --git a/chrome/android/javatests/src/org/chromium/chrome/browser/share/ShareMenuActionHandlerTest.java b/chrome/android/javatests/src/org/chromium/chrome/browser/share/ShareMenuActionHandlerTest.java index a2ac40f..2fa24b3c 100644 --- a/chrome/android/javatests/src/org/chromium/chrome/browser/share/ShareMenuActionHandlerTest.java +++ b/chrome/android/javatests/src/org/chromium/chrome/browser/share/ShareMenuActionHandlerTest.java
@@ -413,5 +413,8 @@ public InterfaceProvider getRemoteInterfaces() { return null; } + + @Override + public void setHasReceivedUserGesture() {} } }
diff --git a/chrome/android/javatests/src/org/chromium/chrome/browser/vr_shell/VrShellControllerInputTest.java b/chrome/android/javatests/src/org/chromium/chrome/browser/vr_shell/VrShellControllerInputTest.java index c02a956e..181a156 100644 --- a/chrome/android/javatests/src/org/chromium/chrome/browser/vr_shell/VrShellControllerInputTest.java +++ b/chrome/android/javatests/src/org/chromium/chrome/browser/vr_shell/VrShellControllerInputTest.java
@@ -20,7 +20,6 @@ import org.junit.runner.RunWith; import org.chromium.base.test.util.CommandLineFlags; -import org.chromium.base.test.util.DisabledTest; import org.chromium.base.test.util.Restriction; import org.chromium.base.test.util.RetryOnFailure; import org.chromium.chrome.browser.ChromeSwitches; @@ -145,7 +144,6 @@ * fullscreen */ @Test - @DisabledTest(message = "crbug.com/804808") @MediumTest @RetryOnFailure(message = "Very rarely, button press not registered (race condition?)") public void testAppButtonExitsFullscreen() throws InterruptedException, TimeoutException { @@ -154,7 +152,8 @@ VrTransitionUtils.forceEnterVr(); VrTransitionUtils.waitForVrEntry(POLL_TIMEOUT_LONG_MS); // Enter fullscreen - DOMUtils.clickNode(mVrTestFramework.getFirstTabCvc(), "fullscreen"); + DOMUtils.clickNode(mVrTestFramework.getFirstTabCvc(), "fullscreen", + false /* goThroughRootAndroidView */); VrTestFramework.waitOnJavaScriptStep(mVrTestFramework.getFirstTabWebContents()); Assert.assertTrue(DOMUtils.isFullscreen(mVrTestFramework.getFirstTabWebContents()));
diff --git a/chrome/android/javatests/src/org/chromium/chrome/browser/vr_shell/VrShellNavigationTest.java b/chrome/android/javatests/src/org/chromium/chrome/browser/vr_shell/VrShellNavigationTest.java index 83349162..bdf272c6 100644 --- a/chrome/android/javatests/src/org/chromium/chrome/browser/vr_shell/VrShellNavigationTest.java +++ b/chrome/android/javatests/src/org/chromium/chrome/browser/vr_shell/VrShellNavigationTest.java
@@ -22,7 +22,6 @@ import org.chromium.base.ThreadUtils; import org.chromium.base.test.util.CommandLineFlags; -import org.chromium.base.test.util.DisabledTest; import org.chromium.base.test.util.Restriction; import org.chromium.chrome.browser.ChromeSwitches; import org.chromium.chrome.browser.UrlConstants; @@ -105,7 +104,7 @@ private void enterFullscreenOrFail(ContentViewCore cvc) throws InterruptedException, TimeoutException { - DOMUtils.clickNode(cvc, "fullscreen"); + DOMUtils.clickNode(cvc, "fullscreen", false /* goThroughRootAndroidView */); VrTestFramework.waitOnJavaScriptStep(cvc.getWebContents()); Assert.assertTrue(DOMUtils.isFullscreen(cvc.getWebContents())); } @@ -179,7 +178,6 @@ * Tests navigation from a fullscreened 2D to a WebVR page. */ @Test - @DisabledTest(message = "crbug.com/804808") @MediumTest public void test2dFullscreenToWebVr() throws IllegalArgumentException, InterruptedException, TimeoutException { @@ -228,7 +226,6 @@ * Tests navigation from a presenting WebVR to a 2D page. */ @Test - @DisabledTest(message = "crbug.com/804808") @MediumTest @Restriction(RESTRICTION_TYPE_VIEWER_DAYDREAM) public void testWebVrPresentingTo2d() @@ -246,7 +243,6 @@ * Tests navigation from a presenting WebVR to a WebVR page. */ @Test - @DisabledTest(message = "crbug.com/804808") @MediumTest @Restriction(RESTRICTION_TYPE_VIEWER_DAYDREAM) public void testWebVrPresentingToWebVr() @@ -264,7 +260,6 @@ * Tests navigation from a fullscreened WebVR to a 2D page. */ @Test - @DisabledTest(message = "crbug.com/804808") @MediumTest @Restriction(RESTRICTION_TYPE_VIEWER_DAYDREAM) public void testWebVrFullscreenTo2d() @@ -282,7 +277,6 @@ * Tests navigation from a fullscreened WebVR to a WebVR page. */ @Test - @DisabledTest(message = "crbug.com/804808") @MediumTest @Restriction(RESTRICTION_TYPE_VIEWER_DAYDREAM) public void testWebVrFullscreenToWebVr()
diff --git a/chrome/android/javatests/src/org/chromium/chrome/browser/vr_shell/VrShellTransitionTest.java b/chrome/android/javatests/src/org/chromium/chrome/browser/vr_shell/VrShellTransitionTest.java index 51b0bff..9b561a9 100644 --- a/chrome/android/javatests/src/org/chromium/chrome/browser/vr_shell/VrShellTransitionTest.java +++ b/chrome/android/javatests/src/org/chromium/chrome/browser/vr_shell/VrShellTransitionTest.java
@@ -24,7 +24,6 @@ import org.chromium.base.ApplicationStatus; import org.chromium.base.test.util.CommandLineFlags; -import org.chromium.base.test.util.DisabledTest; import org.chromium.base.test.util.Restriction; import org.chromium.base.test.util.RetryOnFailure; import org.chromium.chrome.browser.ChromeSwitches; @@ -194,7 +193,6 @@ */ @Test @Restriction(RESTRICTION_TYPE_VIEWER_DAYDREAM) - @DisabledTest(message = "crbug.com/804808") @MediumTest public void testExitFullscreenAfterExitingVrFromCinemaMode() throws InterruptedException, TimeoutException { @@ -202,7 +200,8 @@ VrTransitionUtils.waitForVrEntry(POLL_TIMEOUT_LONG_MS); mVrTestFramework.loadUrlAndAwaitInitialization( VrTestFramework.getHtmlTestFile("test_navigation_2d_page"), PAGE_LOAD_TIMEOUT_S); - DOMUtils.clickNode(mVrTestFramework.getFirstTabCvc(), "fullscreen"); + DOMUtils.clickNode(mVrTestFramework.getFirstTabCvc(), "fullscreen", + false /* goThroughRootAndroidView */); VrTestFramework.waitOnJavaScriptStep(mVrTestFramework.getFirstTabWebContents()); Assert.assertTrue(DOMUtils.isFullscreen(mVrTestFramework.getFirstTabWebContents())); @@ -226,7 +225,6 @@ * from WebVR presentation to the VR browser. */ @Test - @DisabledTest(message = "crbug.com/804808") @CommandLineFlags.Add("enable-webvr") @Restriction(RESTRICTION_TYPE_VIEWER_DAYDREAM) @MediumTest @@ -263,7 +261,6 @@ @Test @CommandLineFlags.Add("enable-webvr") @Restriction(RESTRICTION_TYPE_VIEWER_DAYDREAM) - @DisabledTest(message = "crbug.com/804808") @MediumTest public void testWebVrReEntryFromVrBrowser() throws InterruptedException, TimeoutException { VrTransitionUtils.forceEnterVr();
diff --git a/chrome/android/javatests/src/org/chromium/chrome/browser/vr_shell/util/TransitionUtils.java b/chrome/android/javatests/src/org/chromium/chrome/browser/vr_shell/util/TransitionUtils.java index 79d2d2c..5ccf1051 100644 --- a/chrome/android/javatests/src/org/chromium/chrome/browser/vr_shell/util/TransitionUtils.java +++ b/chrome/android/javatests/src/org/chromium/chrome/browser/vr_shell/util/TransitionUtils.java
@@ -96,7 +96,7 @@ */ public static void enterPresentation(ContentViewCore cvc) { try { - DOMUtils.clickNode(cvc, "webgl-canvas"); + DOMUtils.clickNode(cvc, "webgl-canvas", false /* goThroughRootAndroidView */); } catch (InterruptedException | TimeoutException e) { Assert.fail("Failed to click canvas to enter presentation: " + e.toString()); }
diff --git a/chrome/app/settings_strings.grdp b/chrome/app/settings_strings.grdp index 49e775c3..56f6664a 100644 --- a/chrome/app/settings_strings.grdp +++ b/chrome/app/settings_strings.grdp
@@ -1625,25 +1625,28 @@ Unable to detect your phone </message> <message name="IDS_SETTINGS_INTERNET_GMSCORE_NOTIFICATIONS_TITLE" desc="Title of the section which explains how to enable Google Play Services notifications on an Android phone in order to use Instant Tethering."> - Google Play Services notifications are required for Instant Tethering + To use Instant Tethering, turn on notifications for Google Play Services. </message> <message name="IDS_SETTINGS_INTERNET_GMSCORE_NOTIFICATIONS_ONE_DEVICE_SUBTITLE" desc="Subtitle of the section which explains how to enable Google Play Services notifications. This subtitle is used when only one phone needs to have its notifications enabled."> - On your '<ph name="PHONE_NAME">$1<ex>Google Pixel</ex></ph>', enable notifications by following these steps: + On your '<ph name="PHONE_NAME">$1<ex>Google Pixel</ex></ph>': </message> <message name="IDS_SETTINGS_INTERNET_GMSCORE_NOTIFICATIONS_TWO_DEVICES_SUBTITLE" desc="Subtitle of the section which explains how to enable Google Play Services notifications. This subtitle is used when two phones need to have their notifications enabled."> - On your '<ph name="PHONE_NAME_1">$1<ex>Google Pixel</ex></ph>' and '<ph name="PHONE_NAME_2">$2<ex>Google Pixel 2</ex></ph>', enable notifications by following these steps: + On your '<ph name="PHONE_NAME_1">$1<ex>Google Pixel</ex></ph>' and '<ph name="PHONE_NAME_2">$2<ex>Google Pixel 2</ex></ph>': </message> <message name="IDS_SETTINGS_INTERNET_GMSCORE_NOTIFICATIONS_MANY_DEVICES_SUBTITLE" desc="Subtitle of the section which explains how to enable Google Play Services notifications. This subtitle is used when three or more phones need to have their notifications enabled."> - On your devices, enable notifications by following these steps: + On your devices: </message> - <message name="IDS_SETTINGS_INTERNET_GMSCORE_NOTIFICATIONS_FIRST_STEP" desc="First instruction for how to enable Google Play Services notifications on an Android phone. This step teaches the user how to look at Google Play Services settings."> - Go to Settings > Apps & notifications > All apps > Google Play Services. + <message name="IDS_SETTINGS_INTERNET_GMSCORE_NOTIFICATIONS_FIRST_STEP" desc="First instruction for how to enable Google Play Services notifications on an Android phone. This step teaches the user how to look at notification settings."> + Go to Settings > Apps & notifications > Notifications. </message> - <message name="IDS_SETTINGS_INTERNET_GMSCORE_NOTIFICATIONS_SECOND_STEP" desc="Second instruction for how to enable Google Play Services notifications on an Android phone. This step teaches the user how to look at notification settings when already viewing Google Play Services settings."> - Tap on App notifications. + <message name="IDS_SETTINGS_INTERNET_GMSCORE_NOTIFICATIONS_SECOND_STEP" desc="Second instruction for how to enable Google Play Services notifications on an Android phone. This step teaches the user how to look at notification settings for the Google Play Services app."> + Tap App notifications > Google Play services. </message> <message name="IDS_SETTINGS_INTERNET_GMSCORE_NOTIFICATIONS_THIRD_STEP" desc="Third instruction for how to enable Google Play Services notifications on an Android phone. This step teaches the user how to enable notifications when already viewing noticiations settings for Google Play Services."> - Check that app notifications are "On". If not, toggle to enable. + Turn on Google Play services. + </message> + <message name="IDS_SETTINGS_INTERNET_GMSCORE_NOTIFICATIONS_FOURTH_STEP" desc="Fourth instruction for how to enable Google Play Services notifications on an Android phone. This step teaches the user how to enable the Instant Tethering notification channel for Google Play Services."> + Scroll to the bottom of the screen and turn on Instant Tethering, if it appears. If it doesn't, you're all set. </message> <message name="IDS_SETTINGS_INTERNET_NO_NETWORKS_MOBILE_DATA" desc="Text shown when viewing the Mobile data page when there are no cellular or tether networks available."> No mobile connection found. Turn on Instant Tethering on your other devices and try again. <a target="_blank" href="<ph name="URL">$1<ex>https://google.com/</ex></ph>">Learn more</a>
diff --git a/chrome/browser/BUILD.gn b/chrome/browser/BUILD.gn index ee6a9f6d..9e7c310 100644 --- a/chrome/browser/BUILD.gn +++ b/chrome/browser/BUILD.gn
@@ -664,6 +664,7 @@ "media/webrtc/desktop_media_list.h", "media/webrtc/desktop_media_list_base.cc", "media/webrtc/desktop_media_list_base.h", + "media/webrtc/desktop_media_picker.cc", "media/webrtc/desktop_media_picker.h", "media/webrtc/desktop_streams_registry.cc", "media/webrtc/desktop_streams_registry.h", @@ -2158,8 +2159,6 @@ "android/url_utilities.cc", "android/usb/web_usb_chooser_service_android.cc", "android/usb/web_usb_chooser_service_android.h", - "android/voice_search_tab_helper.cc", - "android/voice_search_tab_helper.h", "android/warmup_manager.cc", "android/web_contents_factory.cc", "android/webapk/chrome_webapk_host.cc",
diff --git a/chrome/browser/about_flags.cc b/chrome/browser/about_flags.cc index 70191d6..3ed23e1 100644 --- a/chrome/browser/about_flags.cc +++ b/chrome/browser/about_flags.cc
@@ -3484,6 +3484,11 @@ flag_descriptions::kImprovedLanguageSettingsDescription, kOsAll, FEATURE_VALUE_TYPE(translate::kImprovedLanguageSettings)}, + {"enable-regional-locales-as-display-ui", + flag_descriptions::kRegionalLocalesAsDisplayUIName, + flag_descriptions::kRegionalLocalesAsDisplayUIDescription, kOsAll, + FEATURE_VALUE_TYPE(translate::kRegionalLocalesAsDisplayUI)}, + {"enable-module-scripts-dynamic-import", flag_descriptions::kModuleScriptsDynamicImportName, flag_descriptions::kModuleScriptsDynamicImportDescription, kOsAll, @@ -3685,6 +3690,11 @@ flag_descriptions::kEnableDisplayZoomSettingName, flag_descriptions::kEnableDisplayZoomSettingDescription, kOsCrOS, SINGLE_VALUE_TYPE(chromeos::switches::kEnableDisplayZoomSetting)}, + + {"ash-enable-new-overview-ui", + flag_descriptions::kAshEnableNewOverviewUiName, + flag_descriptions::kAshEnableNewOverviewUiDescription, kOsCrOS, + SINGLE_VALUE_TYPE(ash::switches::kAshEnableNewOverviewUi)}, #endif // defined(OS_CHROMEOS) // NOTE: Adding a new flag requires adding a corresponding entry to enum
diff --git a/chrome/browser/android/download/download_controller.cc b/chrome/browser/android/download/download_controller.cc index df6988e..cf9fdc3e3 100644 --- a/chrome/browser/android/download/download_controller.cc +++ b/chrome/browser/android/download/download_controller.cc
@@ -112,7 +112,7 @@ offline_pages::android::OfflinePageBridge::GetEncodedOriginApp( web_contents)); RecordDownloadSource(DOWNLOAD_INITIATED_BY_CONTEXT_MENU); - dl_params->set_download_source(content::DownloadSource::CONTEXT_MENU); + dl_params->set_download_source(download::DownloadSource::CONTEXT_MENU); dlm->DownloadUrl(std::move(dl_params)); }
diff --git a/chrome/browser/android/voice_search_tab_helper.cc b/chrome/browser/android/voice_search_tab_helper.cc deleted file mode 100644 index 2ee429e..0000000 --- a/chrome/browser/android/voice_search_tab_helper.cc +++ /dev/null
@@ -1,56 +0,0 @@ -// Copyright 2014 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/android/voice_search_tab_helper.h" - -#include "base/command_line.h" -#include "components/google/core/browser/google_util.h" -#include "content/public/browser/render_view_host.h" -#include "content/public/browser/web_contents.h" -#include "content/public/common/web_preferences.h" -#include "media/base/media_switches.h" - -DEFINE_WEB_CONTENTS_USER_DATA_KEY(VoiceSearchTabHelper); - -// TODO(715588): this class shouldn't be playing with the user gesture -// requirements like this. -VoiceSearchTabHelper::VoiceSearchTabHelper(content::WebContents* contents) - : content::WebContentsObserver(contents) { - const base::CommandLine* command_line = - base::CommandLine::ForCurrentProcess(); - gesture_requirement_for_playback_disabled_ = - media::GetEffectiveAutoplayPolicy(*command_line) == - switches::autoplay::kNoUserGestureRequiredPolicy; -} - -VoiceSearchTabHelper::~VoiceSearchTabHelper() { -} - -void VoiceSearchTabHelper::NavigationEntryCommitted( - const content::LoadCommittedDetails& load_details) { - // In the case where media autoplay has been disabled by default (e.g. in - // performance media tests) do not update it based on navigation changes. - if (gesture_requirement_for_playback_disabled_) - return; - - content::RenderViewHost* host = web_contents()->GetRenderViewHost(); - content::WebPreferences prefs = host->GetWebkitPreferences(); - - bool gesture_required = - !google_util::IsGoogleSearchUrl(web_contents()->GetLastCommittedURL()); - bool gesture_required_by_prefs = - prefs.autoplay_policy == content::AutoplayPolicy::kUserGestureRequired; - - if (gesture_required != gesture_required_by_prefs) { - // TODO(chrishtr): this is wrong. user_gesture_required_for_media_playback - // will be reset the next time a preference changes. - // TODO(mlamouri): this is even more wrong because it makes assumptions with - // regards to the default autoplay policy. - prefs.autoplay_policy = - gesture_required - ? content::AutoplayPolicy::kDocumentUserActivationRequired - : content::AutoplayPolicy::kNoUserGestureRequired; - host->UpdateWebkitPreferences(prefs); - } -}
diff --git a/chrome/browser/android/voice_search_tab_helper.h b/chrome/browser/android/voice_search_tab_helper.h deleted file mode 100644 index c0e6292..0000000 --- a/chrome/browser/android/voice_search_tab_helper.h +++ /dev/null
@@ -1,32 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef CHROME_BROWSER_ANDROID_VOICE_SEARCH_TAB_HELPER_H_ -#define CHROME_BROWSER_ANDROID_VOICE_SEARCH_TAB_HELPER_H_ - -#include "base/macros.h" -#include "content/public/browser/web_contents_observer.h" -#include "content/public/browser/web_contents_user_data.h" - -// Tab helper to toggle media autoplay for voice URL searches. -class VoiceSearchTabHelper - : public content::WebContentsObserver, - public content::WebContentsUserData<VoiceSearchTabHelper> { - public: - ~VoiceSearchTabHelper() override; - - // content::WebContentsObserver overrides. - void NavigationEntryCommitted( - const content::LoadCommittedDetails& load_details) override; - - private: - explicit VoiceSearchTabHelper(content::WebContents* contents); - friend class content::WebContentsUserData<VoiceSearchTabHelper>; - - bool gesture_requirement_for_playback_disabled_; - - DISALLOW_COPY_AND_ASSIGN(VoiceSearchTabHelper); -}; - -#endif // CHROME_BROWSER_ANDROID_VOICE_SEARCH_TAB_HELPER_H_
diff --git a/chrome/browser/android/vr_shell/vr_shell.cc b/chrome/browser/android/vr_shell/vr_shell.cc index d0b0fce68..7c1c76ca 100644 --- a/chrome/browser/android/vr_shell/vr_shell.cc +++ b/chrome/browser/android/vr_shell/vr_shell.cc
@@ -71,6 +71,7 @@ #include "url/gurl.h" using base::android::JavaParamRef; +using base::android::ScopedJavaLocalRef; namespace vr_shell { @@ -457,9 +458,8 @@ void VrShell::ProcessTabArray(JNIEnv* env, jobjectArray tabs, bool incognito) { size_t len = env->GetArrayLength(tabs); for (size_t i = 0; i < len; ++i) { - jobject jtab = env->GetObjectArrayElement(tabs, i); - TabAndroid* tab = - TabAndroid::GetNativeTab(env, JavaParamRef<jobject>(env, jtab)); + ScopedJavaLocalRef<jobject> j_tab(env, env->GetObjectArrayElement(tabs, i)); + TabAndroid* tab = TabAndroid::GetNativeTab(env, j_tab); ui_->AppendToTabList(incognito, tab->GetAndroidId(), tab->GetTitle()); } }
diff --git a/chrome/browser/app_mode/app_mode_utils.cc b/chrome/browser/app_mode/app_mode_utils.cc index 1fe2e17..738cb0c 100644 --- a/chrome/browser/app_mode/app_mode_utils.cc +++ b/chrome/browser/app_mode/app_mode_utils.cc
@@ -9,11 +9,28 @@ #include "base/command_line.h" #include "base/logging.h" #include "base/macros.h" +#include "base/optional.h" #include "chrome/app/chrome_command_ids.h" #include "chrome/common/chrome_switches.h" namespace chrome { +namespace { + +// If the device is running in forced app mode, returns the ID of the app for +// which the device is forced in app mode. Otherwise, returns nullopt. +base::Optional<std::string> GetForcedAppModeApp() { + base::CommandLine* command_line = base::CommandLine::ForCurrentProcess(); + if (!command_line->HasSwitch(switches::kForceAppMode) || + !command_line->HasSwitch(switches::kAppId)) { + return base::nullopt; + } + + return command_line->GetSwitchValueASCII(switches::kAppId); +} + +} // namespace + bool IsCommandAllowedInAppMode(int command_id) { DCHECK(IsRunningInForcedAppMode()); @@ -47,10 +64,19 @@ } bool IsRunningInForcedAppMode() { - base::CommandLine* command_line = base::CommandLine::ForCurrentProcess(); - return (command_line->HasSwitch(switches::kForceAppMode) && - command_line->HasSwitch(switches::kAppId)) || - command_line->HasSwitch(switches::kForceAndroidAppMode); + return GetForcedAppModeApp().has_value() || + base::CommandLine::ForCurrentProcess()->HasSwitch( + switches::kForceAndroidAppMode); +} + +bool IsRunningInForcedAppModeForApp(const std::string& app_id) { + DCHECK(!app_id.empty()); + + base::Optional<std::string> forced_app_mode_app = GetForcedAppModeApp(); + if (!forced_app_mode_app.has_value()) + return false; + + return app_id == forced_app_mode_app.value(); } } // namespace chrome
diff --git a/chrome/browser/app_mode/app_mode_utils.h b/chrome/browser/app_mode/app_mode_utils.h index a591814..5f7a0e8 100644 --- a/chrome/browser/app_mode/app_mode_utils.h +++ b/chrome/browser/app_mode/app_mode_utils.h
@@ -5,6 +5,8 @@ #ifndef CHROME_BROWSER_APP_MODE_APP_MODE_UTILS_H_ #define CHROME_BROWSER_APP_MODE_APP_MODE_UTILS_H_ +#include <string> + namespace chrome { // Returns true if the given browser command is allowed in app mode. @@ -16,6 +18,10 @@ // Return true if browser process is run in forced app mode. bool IsRunningInForcedAppMode(); +// Returns true if browser process is run in forced app mode for Chrome app +// with the provided id. +bool IsRunningInForcedAppModeForApp(const std::string& app_id); + } // namespace chrome #endif // CHROME_BROWSER_APP_MODE_APP_MODE_UTILS_H_
diff --git a/chrome/browser/apps/guest_view/web_view_interactive_browsertest.cc b/chrome/browser/apps/guest_view/web_view_interactive_browsertest.cc index 6dfcada..ef28eb3 100644 --- a/chrome/browser/apps/guest_view/web_view_interactive_browsertest.cc +++ b/chrome/browser/apps/guest_view/web_view_interactive_browsertest.cc
@@ -1316,7 +1316,8 @@ } // Flaky on ChromeOS and Linux: http://crbug.com/526886 -#if defined(OS_CHROMEOS) || defined(OS_LINUX) +// TODO(crbug.com/807446): Flaky on Mac. +#if defined(OS_CHROMEOS) || defined(OS_LINUX) || defined(OS_MACOSX) #define MAYBE_PopupPositioningMoved DISABLED_PopupPositioningMoved #else #define MAYBE_PopupPositioningMoved PopupPositioningMoved
diff --git a/chrome/browser/browser_process_impl.cc b/chrome/browser/browser_process_impl.cc index 52e1b5ea..bf4b6ef1 100644 --- a/chrome/browser/browser_process_impl.cc +++ b/chrome/browser/browser_process_impl.cc
@@ -653,7 +653,6 @@ DCHECK(!browser_policy_connector_); browser_policy_connector_ = platform_part_->CreateBrowserPolicyConnector(); created_browser_policy_connector_ = true; - browser_policy_connector_->InitPolicyProviders(); } return browser_policy_connector_.get(); }
diff --git a/chrome/browser/browsing_data/chrome_browsing_data_remover_delegate.cc b/chrome/browser/browsing_data/chrome_browsing_data_remover_delegate.cc index 2d5d340..57d1783 100644 --- a/chrome/browser/browsing_data/chrome_browsing_data_remover_delegate.cc +++ b/chrome/browser/browsing_data/chrome_browsing_data_remover_delegate.cc
@@ -785,6 +785,12 @@ PermissionDecisionAutoBlocker::GetForProfile(profile_)->RemoveCountsByUrl( filter); + +#if BUILDFLAG(ENABLE_PLUGINS) + host_content_settings_map_->ClearSettingsForOneTypeWithPredicate( + CONTENT_SETTINGS_TYPE_PLUGINS_DATA, base::Time(), + base::Bind(&WebsiteSettingsFilterAdapter, filter)); +#endif } //////////////////////////////////////////////////////////////////////////////
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 1fd75f5e..805ab525 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
@@ -108,6 +108,8 @@ #if BUILDFLAG(ENABLE_PLUGINS) #include "chrome/browser/browsing_data/mock_browsing_data_flash_lso_helper.h" +#include "chrome/browser/plugins/chrome_plugin_service_filter.h" +#include "chrome/browser/plugins/plugin_utils.h" #endif // BUILDFLAG(ENABLE_PLUGINS) #if BUILDFLAG(ENABLE_REPORTING) @@ -740,6 +742,36 @@ DISALLOW_COPY_AND_ASSIGN(RemovePluginDataTester); }; + +// Waits until a change is observed in content settings. +class FlashContentSettingsChangeWaiter : public content_settings::Observer { + public: + explicit FlashContentSettingsChangeWaiter(Profile* profile) + : profile_(profile) { + HostContentSettingsMapFactory::GetForProfile(profile)->AddObserver(this); + } + ~FlashContentSettingsChangeWaiter() override { + HostContentSettingsMapFactory::GetForProfile(profile_)->RemoveObserver( + this); + } + + // content_settings::Observer: + void OnContentSettingChanged(const ContentSettingsPattern& primary_pattern, + const ContentSettingsPattern& secondary_pattern, + ContentSettingsType content_type, + std::string resource_identifier) override { + if (content_type == CONTENT_SETTINGS_TYPE_PLUGINS) + run_loop_.Quit(); + } + + void Wait() { run_loop_.Run(); } + + private: + Profile* profile_; + base::RunLoop run_loop_; + + DISALLOW_COPY_AND_ASSIGN(FlashContentSettingsChangeWaiter); +}; #endif // Custom matcher to test the equivalence of two URL filters. Since those are @@ -2391,6 +2423,54 @@ } #if BUILDFLAG(ENABLE_PLUGINS) +// Check the |CONTENT_SETTINGS_TYPE_PLUGINS_DATA| content setting is cleared +// with browsing data. +TEST_F(ChromeBrowsingDataRemoverDelegateTest, ClearFlashPreviouslyChanged) { + ChromePluginServiceFilter::GetInstance()->RegisterResourceContext( + GetProfile(), GetProfile()->GetResourceContext()); + + HostContentSettingsMap* host_content_settings_map = + HostContentSettingsMapFactory::GetForProfile(GetProfile()); + + // PLUGINS_DATA gets cleared with history OR site usage data. + for (ChromeBrowsingDataRemoverDelegate::DataType data_type : + {ChromeBrowsingDataRemoverDelegate::DATA_TYPE_SITE_USAGE_DATA, + ChromeBrowsingDataRemoverDelegate::DATA_TYPE_HISTORY}) { + FlashContentSettingsChangeWaiter waiter(GetProfile()); + host_content_settings_map->SetContentSettingDefaultScope( + kOrigin1, kOrigin1, CONTENT_SETTINGS_TYPE_PLUGINS, std::string(), + CONTENT_SETTING_ALLOW); + host_content_settings_map->SetContentSettingDefaultScope( + kOrigin2, kOrigin2, CONTENT_SETTINGS_TYPE_PLUGINS, std::string(), + CONTENT_SETTING_BLOCK); + waiter.Wait(); + + // Check that as a result, the PLUGINS_DATA prefs were populated. + EXPECT_NE(nullptr, + host_content_settings_map->GetWebsiteSetting( + kOrigin1, kOrigin1, CONTENT_SETTINGS_TYPE_PLUGINS_DATA, + std::string(), nullptr)); + EXPECT_NE(nullptr, + host_content_settings_map->GetWebsiteSetting( + kOrigin2, kOrigin2, CONTENT_SETTINGS_TYPE_PLUGINS_DATA, + std::string(), nullptr)); + + std::unique_ptr<BrowsingDataFilterBuilder> filter( + BrowsingDataFilterBuilder::Create( + BrowsingDataFilterBuilder::BLACKLIST)); + BlockUntilOriginDataRemoved(AnHourAgo(), base::Time::Max(), data_type, + std::move(filter)); + EXPECT_EQ(nullptr, + host_content_settings_map->GetWebsiteSetting( + kOrigin1, kOrigin1, CONTENT_SETTINGS_TYPE_PLUGINS_DATA, + std::string(), nullptr)); + EXPECT_EQ(nullptr, + host_content_settings_map->GetWebsiteSetting( + kOrigin2, kOrigin2, CONTENT_SETTINGS_TYPE_PLUGINS_DATA, + std::string(), nullptr)); + } +} + TEST_F(ChromeBrowsingDataRemoverDelegateTest, RemovePluginData) { RemovePluginDataTester tester(GetProfile());
diff --git a/chrome/browser/browsing_data/counters/downloads_counter_browsertest.cc b/chrome/browser/browsing_data/counters/downloads_counter_browsertest.cc index 252868621..4c51b57 100644 --- a/chrome/browser/browsing_data/counters/downloads_counter_browsertest.cc +++ b/chrome/browser/browsing_data/counters/downloads_counter_browsertest.cc
@@ -59,11 +59,8 @@ std::string AddDownload() { std::string guid = AddDownloadInternal( content::DownloadItem::COMPLETE, - content::DownloadDangerType::DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS, - content::DOWNLOAD_INTERRUPT_REASON_NONE, - GURL(), - std::string(), - false); + download::DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS, + content::DOWNLOAD_INTERRUPT_REASON_NONE, GURL(), std::string(), false); guids_to_add_.insert(guid); return guid; } @@ -71,44 +68,36 @@ std::string AddIncognitoDownload() { // Incognito downloads are not expected to be persisted. We don't need to // wait for a callback from them, so we don't add them to |guids_to_add_|. - return AddDownloadInternal( - content::DownloadItem::COMPLETE, - content::DownloadDangerType::DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS, - content::DOWNLOAD_INTERRUPT_REASON_NONE, - GURL(), - std::string(), - true); + return AddDownloadInternal(content::DownloadItem::COMPLETE, + download::DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS, + content::DOWNLOAD_INTERRUPT_REASON_NONE, GURL(), + std::string(), true); } #if BUILDFLAG(ENABLE_EXTENSIONS) std::string AddExtensionDownload() { // Extension downloads are not expected to be persisted. We don't need to // wait for a callback from them, so we don't add them to |guids_to_add_|. - return AddDownloadInternal( - content::DownloadItem::COMPLETE, - content::DownloadDangerType::DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS, - content::DOWNLOAD_INTERRUPT_REASON_NONE, - GURL(), - extensions::Extension::kMimeType, - false); + return AddDownloadInternal(content::DownloadItem::COMPLETE, + download::DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS, + content::DOWNLOAD_INTERRUPT_REASON_NONE, GURL(), + extensions::Extension::kMimeType, false); } std::string AddUserScriptDownload() { // User script downloads are not expected to be persisted. We don't need to // wait for a callback from them, so we don't add them to |guids_to_add_|. - return AddDownloadInternal( - content::DownloadItem::COMPLETE, - content::DownloadDangerType::DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS, - content::DOWNLOAD_INTERRUPT_REASON_NONE, - GURL("file:///download.user.js"), - "text/javascript", - false); + return AddDownloadInternal(content::DownloadItem::COMPLETE, + download::DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS, + content::DOWNLOAD_INTERRUPT_REASON_NONE, + GURL("file:///download.user.js"), + "text/javascript", false); } #endif std::string AddDownloadWithProperties( content::DownloadItem::DownloadState state, - content::DownloadDangerType danger, + download::DownloadDangerType danger, content::DownloadInterruptReason reason) { std::string guid = AddDownloadInternal( state, danger, reason, GURL(), std::string(), false); @@ -116,13 +105,12 @@ return guid; } - std::string AddDownloadInternal( - content::DownloadItem::DownloadState state, - content::DownloadDangerType danger, - content::DownloadInterruptReason reason, - const GURL& url, - std::string mime_type, - bool incognito) { + std::string AddDownloadInternal(content::DownloadItem::DownloadState state, + download::DownloadDangerType danger, + content::DownloadInterruptReason reason, + const GURL& url, + std::string mime_type, + bool incognito) { std::string guid = base::GenerateGUID(); std::vector<GURL> url_chain; @@ -284,26 +272,21 @@ base::Unretained(this))); AddDownload(); - AddDownloadWithProperties( - content::DownloadItem::COMPLETE, - content::DOWNLOAD_DANGER_TYPE_DANGEROUS_FILE, - content::DOWNLOAD_INTERRUPT_REASON_NONE); - AddDownloadWithProperties( - content::DownloadItem::COMPLETE, - content::DOWNLOAD_DANGER_TYPE_USER_VALIDATED, - content::DOWNLOAD_INTERRUPT_REASON_NONE); - AddDownloadWithProperties( - content::DownloadItem::CANCELLED, - content::DOWNLOAD_DANGER_TYPE_DANGEROUS_URL, - content::DOWNLOAD_INTERRUPT_REASON_NONE); - AddDownloadWithProperties( - content::DownloadItem::INTERRUPTED, - content::DOWNLOAD_DANGER_TYPE_DANGEROUS_URL, - content::DOWNLOAD_INTERRUPT_REASON_FILE_FAILED); - AddDownloadWithProperties( - content::DownloadItem::INTERRUPTED, - content::DOWNLOAD_DANGER_TYPE_UNCOMMON_CONTENT, - content::DOWNLOAD_INTERRUPT_REASON_USER_CANCELED); + AddDownloadWithProperties(content::DownloadItem::COMPLETE, + download::DOWNLOAD_DANGER_TYPE_DANGEROUS_FILE, + content::DOWNLOAD_INTERRUPT_REASON_NONE); + AddDownloadWithProperties(content::DownloadItem::COMPLETE, + download::DOWNLOAD_DANGER_TYPE_USER_VALIDATED, + content::DOWNLOAD_INTERRUPT_REASON_NONE); + AddDownloadWithProperties(content::DownloadItem::CANCELLED, + download::DOWNLOAD_DANGER_TYPE_DANGEROUS_URL, + content::DOWNLOAD_INTERRUPT_REASON_NONE); + AddDownloadWithProperties(content::DownloadItem::INTERRUPTED, + download::DOWNLOAD_DANGER_TYPE_DANGEROUS_URL, + content::DOWNLOAD_INTERRUPT_REASON_FILE_FAILED); + AddDownloadWithProperties(content::DownloadItem::INTERRUPTED, + download::DOWNLOAD_DANGER_TYPE_UNCOMMON_CONTENT, + content::DOWNLOAD_INTERRUPT_REASON_USER_CANCELED); WaitForDownloadHistory(); counter.Restart();
diff --git a/chrome/browser/chromeos/BUILD.gn b/chrome/browser/chromeos/BUILD.gn index e23082c..cc3eb02 100644 --- a/chrome/browser/chromeos/BUILD.gn +++ b/chrome/browser/chromeos/BUILD.gn
@@ -93,6 +93,7 @@ "//components/keep_alive_registry", "//components/keyed_service/content", "//components/keyed_service/core", + "//components/language/core/common", "//components/login", "//components/metrics:serialization", "//components/metrics/leak_detector", @@ -426,6 +427,8 @@ "arc/process/arc_process_service.h", "arc/screen_capture/arc_screen_capture_bridge.cc", "arc/screen_capture/arc_screen_capture_bridge.h", + "arc/screen_capture/arc_screen_capture_session.cc", + "arc/screen_capture/arc_screen_capture_session.h", "arc/tracing/arc_tracing_bridge.cc", "arc/tracing/arc_tracing_bridge.h", "arc/tts/arc_tts_service.cc",
diff --git a/chrome/browser/chromeos/arc/enterprise/arc_cert_store_bridge_browsertest.cc b/chrome/browser/chromeos/arc/enterprise/arc_cert_store_bridge_browsertest.cc index 2507212..905c6db 100644 --- a/chrome/browser/chromeos/arc/enterprise/arc_cert_store_bridge_browsertest.cc +++ b/chrome/browser/chromeos/arc/enterprise/arc_cert_store_bridge_browsertest.cc
@@ -113,6 +113,18 @@ kFakeUserName); command_line->AppendSwitchASCII(chromeos::switches::kLoginProfile, TestingProfile::kTestUserProfileDir); + // Don't require policy for our sessions - this is required because + // this test creates a secondary profile synchronously, so we need to + // let the policy code know not to expect cached policy. + command_line->AppendSwitchASCII(chromeos::switches::kProfileRequiresPolicy, + "false"); + + // Tell the policy subsystem to wait for an initial policy load, even + // though we are using a synchronously loaded profile. + // TODO(edmanp): Update this test to properly use an asynchronously loaded + // user profile and remove the use of this flag (crbug.com/795737). + command_line->AppendSwitchASCII( + chromeos::switches::kWaitForInitialPolicyFetchForTest, "true"); } void SetUpOnMainThread() override {
diff --git a/chrome/browser/chromeos/arc/screen_capture/arc_screen_capture_bridge.cc b/chrome/browser/chromeos/arc/screen_capture/arc_screen_capture_bridge.cc index 12478bd9..90a32b7 100644 --- a/chrome/browser/chromeos/arc/screen_capture/arc_screen_capture_bridge.cc +++ b/chrome/browser/chromeos/arc/screen_capture/arc_screen_capture_bridge.cc
@@ -4,9 +4,15 @@ #include "chrome/browser/chromeos/arc/screen_capture/arc_screen_capture_bridge.h" +#include "ash/shell.h" +#include "base/bind.h" #include "base/memory/singleton.h" +#include "base/strings/utf_string_conversions.h" +#include "chrome/browser/chromeos/arc/screen_capture/arc_screen_capture_session.h" +#include "chrome/browser/media/webrtc/desktop_media_list_ash.h" #include "components/arc/arc_bridge_service.h" #include "components/arc/arc_browser_context_keyed_service_factory_base.h" +#include "content/public/browser/browser_thread.h" namespace arc { namespace { @@ -52,7 +58,41 @@ const std::string& display_name, const std::string& package_name, RequestPermissionCallback callback) { - NOTREACHED(); + DCHECK_CURRENTLY_ON(content::BrowserThread::UI); + std::unique_ptr<DesktopMediaPicker> picker = DesktopMediaPicker::Create(); + std::vector<std::unique_ptr<DesktopMediaList>> source_lists; + source_lists.emplace_back(std::make_unique<DesktopMediaListAsh>( + content::DesktopMediaID::TYPE_SCREEN)); + const base::string16 display_name16 = base::UTF8ToUTF16(display_name); + DesktopMediaPicker::Params picker_params; + picker_params.context = ash::Shell::GetRootWindowForDisplayId( + display::Screen::GetScreen()->GetPrimaryDisplay().id()); + picker_params.modality = ui::ModalType::MODAL_TYPE_SYSTEM; + picker_params.app_name = display_name16; + picker_params.target_name = display_name16; + picker->Show( + picker_params, std::move(source_lists), + base::BindRepeating(&ArcScreenCaptureBridge::PermissionPromptCallback, + base::Unretained(this), base::Passed(&picker), + display_name, package_name, base::Passed(&callback))); +} + +void ArcScreenCaptureBridge::PermissionPromptCallback( + std::unique_ptr<DesktopMediaPicker> picker, + const std::string& display_name, + const std::string& package_name, + RequestPermissionCallback callback, + content::DesktopMediaID desktop_id) { + DCHECK_CURRENTLY_ON(content::BrowserThread::UI); + if (desktop_id.is_null()) { + std::move(callback).Run(false); + return; + } + // This may overwrite an existing entry which is OK since these persist + // forever and this may be requested again with a different desktop. + permissions_map_[package_name] = + std::make_unique<GrantedCaptureParams>(display_name, desktop_id); + std::move(callback).Run(true); } void ArcScreenCaptureBridge::OpenSession( @@ -60,7 +100,19 @@ const std::string& package_name, const gfx::Size& size, OpenSessionCallback callback) { - NOTREACHED(); + DCHECK_CURRENTLY_ON(content::BrowserThread::UI); + auto found = permissions_map_.find(package_name); + if (found == permissions_map_.end()) { + LOG(ERROR) << "Attempt to open screen capture session without granted " + "permissions for package " + << package_name; + std::move(callback).Run(nullptr); + return; + } + DCHECK(found->second) << package_name; + std::move(callback).Run(ArcScreenCaptureSession::Create( + std::move(notifier), found->second->display_name, + found->second->desktop_id, size)); } } // namespace arc
diff --git a/chrome/browser/chromeos/arc/screen_capture/arc_screen_capture_bridge.h b/chrome/browser/chromeos/arc/screen_capture/arc_screen_capture_bridge.h index 617467b8..18ce8c7 100644 --- a/chrome/browser/chromeos/arc/screen_capture/arc_screen_capture_bridge.h +++ b/chrome/browser/chromeos/arc/screen_capture/arc_screen_capture_bridge.h
@@ -5,9 +5,14 @@ #ifndef CHROME_BROWSER_CHROMEOS_ARC_SCREEN_CAPTURE_ARC_SCREEN_CAPTURE_BRIDGE_H_ #define CHROME_BROWSER_CHROMEOS_ARC_SCREEN_CAPTURE_ARC_SCREEN_CAPTURE_BRIDGE_H_ +#include <memory> +#include <unordered_map> + #include "base/macros.h" +#include "chrome/browser/media/webrtc/desktop_media_picker.h" #include "components/arc/common/screen_capture.mojom.h" #include "components/keyed_service/core/keyed_service.h" +#include "content/public/browser/desktop_media_id.h" namespace content { class BrowserContext; @@ -39,8 +44,28 @@ RequestPermissionCallback callback) override; private: + struct GrantedCaptureParams { + GrantedCaptureParams(const std::string display_name, + content::DesktopMediaID desktop_id) + : display_name(display_name), desktop_id(desktop_id) {} + std::string display_name; + content::DesktopMediaID desktop_id; + }; + + void PermissionPromptCallback(std::unique_ptr<DesktopMediaPicker> picker, + const std::string& display_name, + const std::string& package_name, + RequestPermissionCallback callback, + content::DesktopMediaID desktop_id); + ArcBridgeService* const arc_bridge_service_; // Owned by ArcServiceManager. + // The string in this map corresponds to the passed in package_name when + // RequestPermission is called. That same string should then be passed into + // OpenSession as a token that correlates the two calls. This map is used to + // validate that. + std::unordered_map<std::string, std::unique_ptr<GrantedCaptureParams>> + permissions_map_; // WeakPtrFactory to use for callbacks. base::WeakPtrFactory<ArcScreenCaptureBridge> weak_factory_;
diff --git a/chrome/browser/chromeos/arc/screen_capture/arc_screen_capture_session.cc b/chrome/browser/chromeos/arc/screen_capture/arc_screen_capture_session.cc new file mode 100644 index 0000000..5b0e35d --- /dev/null +++ b/chrome/browser/chromeos/arc/screen_capture/arc_screen_capture_session.cc
@@ -0,0 +1,359 @@ +// 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/chromeos/arc/screen_capture/arc_screen_capture_session.h" + +#include <utility> + +#include "base/bind.h" +#include "base/strings/utf_string_conversions.h" +#include "chrome/browser/chromeos/ui/screen_capture_notification_ui_chromeos.h" +#include "chrome/browser/media/webrtc/desktop_capture_access_handler.h" +#include "chrome/grit/generated_resources.h" +#include "components/viz/common/frame_sinks/copy_output_request.h" +#include "components/viz/common/frame_sinks/copy_output_result.h" +#include "components/viz/common/gpu/context_provider.h" +#include "content/public/browser/browser_thread.h" +#include "content/public/browser/desktop_media_id.h" +#include "content/public/common/media_stream_request.h" +#include "gpu/GLES2/gl2extchromium.h" +#include "gpu/command_buffer/client/context_support.h" +#include "gpu/command_buffer/client/gles2_interface.h" +#include "gpu/ipc/client/gpu_memory_buffer_impl.h" +#include "gpu/ipc/client/gpu_memory_buffer_impl_native_pixmap.h" +#include "mojo/public/cpp/bindings/interface_request.h" +#include "mojo/public/cpp/system/platform_handle.h" +#include "ui/aura/env.h" +#include "ui/aura/window.h" +#include "ui/aura/window_tree_host.h" +#include "ui/base/l10n/l10n_util.h" +#include "ui/compositor/dip_util.h" +#include "ui/gfx/gpu_memory_buffer.h" + +namespace { +// Callback into Android to force screen updates if the queue gets this big. +constexpr size_t kQueueSizeToForceUpdate = 4; +// Drop frames if the queue gets this big. +constexpr size_t kQueueSizeToDropFrames = 8; +// Bytes per pixel, Android returns stride in pixel units, Chrome uses it in +// bytes. +constexpr size_t kBytesPerPixel = 4; +} // namespace + +namespace arc { + +struct ArcScreenCaptureSession::PendingBuffer { + PendingBuffer(std::unique_ptr<gfx::GpuMemoryBuffer> gpu_buffer, + SetOutputBufferCallback callback, + GLuint texture, + GLuint image_id) + : gpu_buffer_(std::move(gpu_buffer)), + callback_(std::move(callback)), + texture_(texture), + image_id_(image_id) {} + std::unique_ptr<gfx::GpuMemoryBuffer> gpu_buffer_; + SetOutputBufferCallback callback_; + const GLuint texture_; + const GLuint image_id_; +}; + +struct ArcScreenCaptureSession::DesktopTexture { + DesktopTexture(GLuint texture, + gfx::Size size, + std::unique_ptr<viz::SingleReleaseCallback> release_callback) + : texture_(texture), + size_(size), + release_callback_(std::move(release_callback)) {} + const GLuint texture_; + gfx::Size size_; + std::unique_ptr<viz::SingleReleaseCallback> release_callback_; +}; + +// static +mojom::ScreenCaptureSessionPtr ArcScreenCaptureSession::Create( + mojom::ScreenCaptureSessionNotifierPtr notifier, + const std::string& display_name, + content::DesktopMediaID desktop_id, + const gfx::Size& size) { + // This will get cleaned up when the connection error handler is called. + ArcScreenCaptureSession* session = + new ArcScreenCaptureSession(std::move(notifier), size); + mojo::InterfacePtr<mojom::ScreenCaptureSession> result = + session->Initialize(desktop_id, display_name); + if (!result) + delete session; + return result; +} + +ArcScreenCaptureSession::ArcScreenCaptureSession( + mojom::ScreenCaptureSessionNotifierPtr notifier, + const gfx::Size& size) + : binding_(this), + notifier_(std::move(notifier)), + size_(size), + desktop_window_(nullptr), + weak_ptr_factory_(this) {} + +mojom::ScreenCaptureSessionPtr ArcScreenCaptureSession::Initialize( + content::DesktopMediaID desktop_id, + const std::string& display_name) { + DCHECK_CURRENTLY_ON(content::BrowserThread::UI); + desktop_window_ = content::DesktopMediaID::GetAuraWindowById(desktop_id); + if (!desktop_window_) { + LOG(ERROR) << "Unable to find Aura desktop window"; + return nullptr; + } + + ui::Layer* layer = desktop_window_->layer(); + if (!layer) { + LOG(ERROR) << "Unable to find layer for the desktop window"; + return nullptr; + } + auto context_provider = aura::Env::GetInstance() + ->context_factory() + ->SharedMainThreadContextProvider(); + gl_helper_ = std::make_unique<viz::GLHelper>( + context_provider->ContextGL(), context_provider->ContextSupport()); + gfx::Size desktop_size = + ui::ConvertSizeToPixel(layer, layer->bounds().size()); + scaler_ = gl_helper_->CreateScaler( + viz::GLHelper::ScalerQuality::SCALER_QUALITY_GOOD, + gfx::Vector2d(desktop_size.width(), desktop_size.height()), + gfx::Vector2d(size_.width(), size_.height()), false, true, false); + + desktop_window_->GetHost()->compositor()->AddAnimationObserver(this); + + // Show the tray notification icon now. + base::string16 notification_text = + l10n_util::GetStringFUTF16(IDS_MEDIA_SCREEN_CAPTURE_NOTIFICATION_TEXT, + base::UTF8ToUTF16(display_name)); + notification_ui_ = ScreenCaptureNotificationUI::Create(notification_text); + notification_ui_->OnStarted( + base::BindRepeating(&ArcScreenCaptureSession::NotificationStop, + weak_ptr_factory_.GetWeakPtr())); + + mojom::ScreenCaptureSessionPtr interface_ptr; + binding_.Bind(mojo::MakeRequest(&interface_ptr)); + binding_.set_connection_error_handler( + base::BindOnce(&ArcScreenCaptureSession::Close, base::Unretained(this))); + return interface_ptr; +} + +void ArcScreenCaptureSession::Close() { + DCHECK_CURRENTLY_ON(content::BrowserThread::UI); + delete this; +} + +ArcScreenCaptureSession::~ArcScreenCaptureSession() { + desktop_window_->GetHost()->compositor()->RemoveAnimationObserver(this); +} + +void ArcScreenCaptureSession::NotificationStop() { + DCHECK_CURRENTLY_ON(content::BrowserThread::UI); + Close(); +} + +void ArcScreenCaptureSession::SetOutputBuffer( + mojo::ScopedHandle graphics_buffer, + uint32_t stride, + SetOutputBufferCallback callback) { + DCHECK_CURRENTLY_ON(content::BrowserThread::UI); + if (!graphics_buffer.is_valid()) { + LOG(ERROR) << "Invalid handle passed into SetOutputBuffer"; + std::move(callback).Run(); + return; + } + gpu::gles2::GLES2Interface* gl = aura::Env::GetInstance() + ->context_factory() + ->SharedMainThreadContextProvider() + ->ContextGL(); + if (!gl) { + LOG(ERROR) << "Unable to get the GL context"; + std::move(callback).Run(); + return; + } + + gfx::GpuMemoryBufferHandle handle; + handle.type = gfx::NATIVE_PIXMAP; + base::PlatformFile platform_file; + MojoResult mojo_result = + mojo::UnwrapPlatformFile(std::move(graphics_buffer), &platform_file); + if (mojo_result != MOJO_RESULT_OK) { + LOG(ERROR) << "Failed unwrapping Mojo handle " << mojo_result; + std::move(callback).Run(); + return; + } + base::ScopedFD scoped_fd(platform_file); + handle.native_pixmap_handle.fds.emplace_back(std::move(scoped_fd)); + handle.native_pixmap_handle.planes.emplace_back( + stride * kBytesPerPixel, 0, stride * kBytesPerPixel * size_.height(), 0); + std::unique_ptr<gfx::GpuMemoryBuffer> gpu_memory_buffer = + gpu::GpuMemoryBufferImplNativePixmap::CreateFromHandle( + handle, size_, gfx::BufferFormat::RGBX_8888, + gfx::BufferUsage::SCANOUT, + gpu::GpuMemoryBufferImpl::DestructionCallback()); + if (!gpu_memory_buffer) { + LOG(ERROR) << "Failed creating GpuMemoryBuffer"; + std::move(callback).Run(); + return; + } + + GLuint texture; + gl->GenTextures(1, &texture); + GLuint id = gl->CreateImageCHROMIUM(gpu_memory_buffer->AsClientBuffer(), + size_.width(), size_.height(), GL_RGB); + if (!id) { + LOG(ERROR) << "Failed to allocate backing surface from GpuMemoryBuffer"; + gl->DeleteTextures(1, &texture); + std::move(callback).Run(); + return; + } + gl->BindTexture(GL_TEXTURE_2D, texture); + gl->BindTexImage2DCHROMIUM(GL_TEXTURE_2D, id); + + std::unique_ptr<PendingBuffer> pending_buffer = + std::make_unique<PendingBuffer>(std::move(gpu_memory_buffer), + std::move(callback), texture, id); + if (texture_queue_.empty()) { + // Put our GPU buffer into a queue so it can be used on the next callback + // where we get a desktop texture. + buffer_queue_.push(std::move(pending_buffer)); + } else { + // We already have a texture from the animation callbacks, use that for + // rendering. + CopyDesktopTextureToGpuBuffer(std::move(texture_queue_.front()), + std::move(pending_buffer)); + texture_queue_.pop(); + } +} + +void ArcScreenCaptureSession::QueryCompleted( + std::unique_ptr<gfx::GpuMemoryBuffer> gpu_memory_buffer, + GLuint query_id, + GLuint texture, + GLuint id, + SetOutputBufferCallback callback) { + DCHECK_CURRENTLY_ON(content::BrowserThread::UI); + std::move(callback).Run(); + gpu::gles2::GLES2Interface* gl = aura::Env::GetInstance() + ->context_factory() + ->SharedMainThreadContextProvider() + ->ContextGL(); + if (!gl) { + LOG(ERROR) << "Unable to get the GL context"; + return; + } + gl->BindTexture(GL_TEXTURE_2D, texture); + gl->ReleaseTexImage2DCHROMIUM(GL_TEXTURE_2D, id); + gl->DeleteTextures(1, &texture); + gl->DestroyImageCHROMIUM(id); + gl->DeleteQueriesEXT(1, &query_id); +} + +void ArcScreenCaptureSession::OnDesktopCaptured( + std::unique_ptr<viz::CopyOutputResult> result) { + DCHECK_CURRENTLY_ON(content::BrowserThread::UI); + gpu::gles2::GLES2Interface* gl = aura::Env::GetInstance() + ->context_factory() + ->SharedMainThreadContextProvider() + ->ContextGL(); + if (!gl) { + LOG(ERROR) << "Unable to get the GL context"; + return; + } + if (result->IsEmpty()) + return; + + // Get the source texture + GLuint src_texture = gl_helper_->ConsumeMailboxToTexture( + result->GetTextureResult()->mailbox, + result->GetTextureResult()->sync_token); + std::unique_ptr<viz::SingleReleaseCallback> release_callback = + result->TakeTextureOwnership(); + + std::unique_ptr<DesktopTexture> desktop_texture = + std::make_unique<DesktopTexture>(src_texture, result->size(), + std::move(release_callback)); + if (buffer_queue_.empty()) { + // We don't have a GPU buffer to render to, so put this in a queue to use + // when we have one. + texture_queue_.emplace(std::move(desktop_texture)); + } else { + // Take the first GPU buffer from the queue and render to that. + CopyDesktopTextureToGpuBuffer(std::move(desktop_texture), + std::move(buffer_queue_.front())); + buffer_queue_.pop(); + } +} + +void ArcScreenCaptureSession::CopyDesktopTextureToGpuBuffer( + std::unique_ptr<DesktopTexture> desktop_texture, + std::unique_ptr<PendingBuffer> pending_buffer) { + gpu::gles2::GLES2Interface* gl = aura::Env::GetInstance() + ->context_factory() + ->SharedMainThreadContextProvider() + ->ContextGL(); + if (!gl) { + LOG(ERROR) << "Unable to get the GL context"; + return; + } + GLuint query_id; + gl->GenQueriesEXT(1, &query_id); + gl->BeginQueryEXT(GL_COMMANDS_COMPLETED_CHROMIUM, query_id); + scaler_->Scale(desktop_texture->texture_, desktop_texture->size_, + gfx::Vector2dF(), pending_buffer->texture_, + gfx::Rect(0, 0, size_.width(), size_.height())); + gl->EndQueryEXT(GL_COMMANDS_COMPLETED_CHROMIUM); + gl->DeleteTextures(1, &desktop_texture->texture_); + if (desktop_texture->release_callback_) { + desktop_texture->release_callback_->Run(gpu::SyncToken(), false); + } + aura::Env::GetInstance() + ->context_factory() + ->SharedMainThreadContextProvider() + ->ContextSupport() + ->SignalQuery( + query_id, + base::BindOnce(&ArcScreenCaptureSession::QueryCompleted, + weak_ptr_factory_.GetWeakPtr(), + base::Passed(&pending_buffer->gpu_buffer_), query_id, + pending_buffer->texture_, pending_buffer->image_id_, + base::Passed(&pending_buffer->callback_))); +} + +void ArcScreenCaptureSession::OnAnimationStep(base::TimeTicks timestamp) { + DCHECK_CURRENTLY_ON(content::BrowserThread::UI); + if (texture_queue_.size() >= kQueueSizeToForceUpdate) { + DVLOG(3) << "AnimationStep callback forcing update due to texture queue " + "size " + << texture_queue_.size(); + notifier_->ForceUpdate(); + } + if (texture_queue_.size() >= kQueueSizeToDropFrames) { + DVLOG(3) << "AnimationStep callback dropping frame due to texture queue " + "size " + << texture_queue_.size(); + return; + } + + ui::Layer* layer = desktop_window_->layer(); + if (!layer) { + LOG(ERROR) << "Unable to find layer for the desktop window"; + return; + } + std::unique_ptr<viz::CopyOutputRequest> request = + std::make_unique<viz::CopyOutputRequest>( + viz::CopyOutputRequest::ResultFormat::RGBA_TEXTURE, + base::BindOnce(&ArcScreenCaptureSession::OnDesktopCaptured, + weak_ptr_factory_.GetWeakPtr())); + layer->RequestCopyOfOutput(std::move(request)); +} + +void ArcScreenCaptureSession::OnCompositingShuttingDown( + ui::Compositor* compositor) { + DCHECK_CURRENTLY_ON(content::BrowserThread::UI); + compositor->RemoveAnimationObserver(this); +} + +} // namespace arc
diff --git a/chrome/browser/chromeos/arc/screen_capture/arc_screen_capture_session.h b/chrome/browser/chromeos/arc/screen_capture/arc_screen_capture_session.h new file mode 100644 index 0000000..a6cf83c --- /dev/null +++ b/chrome/browser/chromeos/arc/screen_capture/arc_screen_capture_session.h
@@ -0,0 +1,113 @@ +// 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. + +#ifndef CHROME_BROWSER_CHROMEOS_ARC_SCREEN_CAPTURE_ARC_SCREEN_CAPTURE_SESSION_H_ +#define CHROME_BROWSER_CHROMEOS_ARC_SCREEN_CAPTURE_ARC_SCREEN_CAPTURE_SESSION_H_ + +#include <memory> +#include <queue> +#include <string> + +#include "base/macros.h" +#include "components/arc/common/screen_capture.mojom.h" +#include "components/viz/common/gl_helper.h" +#include "mojo/public/cpp/bindings/binding.h" +#include "ui/compositor/compositor_animation_observer.h" + +namespace aura { +class Window; +} // namespace aura + +namespace content { +struct DesktopMediaID; +class MediaStreamUI; +} // namespace content + +namespace gfx { +class GpuMemoryBuffer; +class Size; +} // namespace gfx + +namespace viz { +class CopyOutputResult; +} // namespace viz + +namespace arc { + +class ArcScreenCaptureSession : public mojom::ScreenCaptureSession, + public ui::CompositorAnimationObserver { + public: + // Creates a new ScreenCaptureSession and returns the interface pointer for + // passing back across a Mojo pipe. This object will be automatically + // destructed when the Mojo connection is closed. + static mojom::ScreenCaptureSessionPtr Create( + mojom::ScreenCaptureSessionNotifierPtr notifier, + const std::string& display_name, + content::DesktopMediaID desktop_id, + const gfx::Size& size); + + // Implements mojo::ScreenCaptureSession interface. + void SetOutputBuffer(mojo::ScopedHandle graphics_buffer, + uint32_t stride, + SetOutputBufferCallback callback) override; + + // Implements ui::CompositorAnimationObserver. + void OnAnimationStep(base::TimeTicks timestamp) override; + void OnCompositingShuttingDown(ui::Compositor* compositor) override; + + private: + struct DesktopTexture; + struct PendingBuffer; + + ArcScreenCaptureSession(mojom::ScreenCaptureSessionNotifierPtr notifier, + const gfx::Size& size); + ~ArcScreenCaptureSession() override; + + // Does additional checks and upon success returns a valid InterfacePtr, null + // otherwise. + mojom::ScreenCaptureSessionPtr Initialize(content::DesktopMediaID desktop_id, + const std::string& display_name); + // Copies the GL texture from a desktop capture to the corresponding GL + // texture for a GPU buffer. + void CopyDesktopTextureToGpuBuffer( + std::unique_ptr<DesktopTexture> desktop_texture, + std::unique_ptr<PendingBuffer> pending_buffer); + // Closes the Mojo connection by destroying this object. + void Close(); + // Callback for when we perform CopyOutputRequests. + void OnDesktopCaptured(std::unique_ptr<viz::CopyOutputResult> result); + // Callback for completion of GL commands. + void QueryCompleted(std::unique_ptr<gfx::GpuMemoryBuffer> gpu_memory_buffer, + GLuint query_id, + GLuint texture, + GLuint id, + SetOutputBufferCallback callback); + // Callback for a user clicking Stop on the notification for screen capture. + void NotificationStop(); + + mojo::Binding<mojom::ScreenCaptureSession> binding_; + mojom::ScreenCaptureSessionNotifierPtr notifier_; + gfx::Size size_; + aura::Window* desktop_window_; + + // We have 2 separate queues for handling incoming GPU buffers from Android + // and also textures for the desktop we have captured already. Due to the + // parallel nature of the operations, we can end up with starvation in a queue + // if we only implemented a queue for one end of this. This technique allows + // us to maximize throughput and never have overhead with frame duplication as + // well as never skip any output buffers. + std::queue<std::unique_ptr<PendingBuffer>> buffer_queue_; + std::queue<std::unique_ptr<DesktopTexture>> texture_queue_; + std::unique_ptr<viz::GLHelper> gl_helper_; + std::unique_ptr<viz::GLHelper::ScalerInterface> scaler_; + std::unique_ptr<content::MediaStreamUI> notification_ui_; + + base::WeakPtrFactory<ArcScreenCaptureSession> weak_ptr_factory_; + + DISALLOW_COPY_AND_ASSIGN(ArcScreenCaptureSession); +}; + +} // namespace arc + +#endif // CHROME_BROWSER_CHROMEOS_ARC_SCREEN_CAPTURE_ARC_SCREEN_CAPTURE_SESSION_H_
diff --git a/chrome/browser/chromeos/attestation/attestation_ca_client.cc b/chrome/browser/chromeos/attestation/attestation_ca_client.cc index 66db47f..88a2ef6 100644 --- a/chrome/browser/chromeos/attestation/attestation_ca_client.cc +++ b/chrome/browser/chromeos/attestation/attestation_ca_client.cc
@@ -112,9 +112,38 @@ void AttestationCAClient::FetchURL(const std::string& url, const std::string& request, const DataCallback& on_response) { + const net::NetworkTrafficAnnotationTag traffic_annotation = + net::DefineNetworkTrafficAnnotation("attestation_ca_client", R"( + semantics { + sender: "Attestation CA client" + description: + "Sends requests to the Attestation CA as part of the remote " + "attestation feature, such as enrolling for remote attestation or " + "to obtain an attestation certificate." + trigger: + "Device enrollment, content protection or get an attestation " + "certificate for a hardware-protected key." + data: + "The data from AttestationCertificateRequest or from " + "AttestationEnrollmentRequest message from " + "cryptohome/attestation.proto. Some of the important data being " + "encrypted endorsement certificate, attestation identity public " + "key, PCR0 and PCR1 TPM values." + destination: GOOGLE_OWNED_SERVICE + } + policy { + cookies_allowed: NO + setting: + "The device setting DeviceAttestationEnabled can disable the " + "attestation requests and AttestationForContentProtectionEnabled " + "can disable the attestation for content protection. But they " + "cannot be controlled by a policy or through settings." + policy_exception_justification: "Not implemented." + })"); // The first argument allows the use of TestURLFetcherFactory in tests. net::URLFetcher* fetcher = - net::URLFetcher::Create(0, GURL(url), net::URLFetcher::POST, this) + net::URLFetcher::Create(0, GURL(url), net::URLFetcher::POST, this, + traffic_annotation) .release(); fetcher->SetRequestContext(g_browser_process->system_request_context()); fetcher->SetLoadFlags(net::LOAD_DO_NOT_SEND_COOKIES |
diff --git a/chrome/browser/chromeos/extensions/quick_unlock_private/quick_unlock_private_api.cc b/chrome/browser/chromeos/extensions/quick_unlock_private/quick_unlock_private_api.cc index 1ddef79..2b7f9c794 100644 --- a/chrome/browser/chromeos/extensions/quick_unlock_private/quick_unlock_private_api.cc +++ b/chrome/browser/chromeos/extensions/quick_unlock_private/quick_unlock_private_api.cc
@@ -4,7 +4,9 @@ #include "chrome/browser/chromeos/extensions/quick_unlock_private/quick_unlock_private_api.h" -#include <memory> +#include <algorithm> +#include <string> +#include <utility> #include "base/stl_util.h" #include "chrome/browser/chromeos/login/quick_unlock/quick_unlock_factory.h" @@ -42,14 +44,16 @@ "|modes| and |credentials| must have the same number of elements"; const char kMultipleModesNotSupported[] = "At most one quick unlock mode can be active."; + // PINs greater in length than |kMinLengthForWeakPin| will be checked for // weakness. -const int kMinLengthForNonWeakPin = 2; +constexpr size_t kMinLengthForNonWeakPin = 2U; + // A list of the most commmonly used PINs, whose digits are not all the same, // increasing or decreasing. This list is taken from // www.datagenetics.com/blog/september32012/. -const char* kMostCommonPins[] = {"1212", "1004", "2000", "6969", - "1122", "1313", "2001", "1010"}; +constexpr const char* kMostCommonPins[] = {"1212", "1004", "2000", "6969", + "1122", "1313", "2001", "1010"}; // Returns the active set of quick unlock modes. QuickUnlockModeList ComputeActiveModes(Profile* profile) { @@ -83,52 +87,42 @@ return std::all_of(pin.begin(), pin.end(), ::isdigit); } -void GetSanitizedPolicyPinMinMaxLength(PrefService* pref_service, - int* out_min_length, - int* out_max_length) { - DCHECK(out_min_length && out_max_length); - - int min_length = pref_service->GetInteger(prefs::kPinUnlockMinimumLength); +// Reads and sanitizes the pin length policy. +// Returns the minimum and maximum required pin lengths. +// - minimum must be at least 1. +// - maximum must be at least |min_length|, or 0. +std::pair<int, int> GetSanitizedPolicyPinMinMaxLength( + PrefService* pref_service) { + int min_length = + std::max(pref_service->GetInteger(prefs::kPinUnlockMinimumLength), 1); int max_length = pref_service->GetInteger(prefs::kPinUnlockMaximumLength); + max_length = max_length > 0 ? std::max(max_length, min_length) : 0; - // Sanitize the policy input. - if (min_length < 1) - min_length = 1; - if (max_length < 0) - max_length = 0; - - if (max_length != 0 && max_length < min_length) - max_length = min_length; - - *out_min_length = min_length; - *out_max_length = max_length; + DCHECK_GE(min_length, 1); + DCHECK_GE(max_length, 0); + return std::make_pair(min_length, max_length); } -// Checks whether a given |pin| is valid given the PIN min/max policies in -// |pref_service|. If |length_problem| is a valid pointer return the type of -// problem. -bool IsPinLengthValid(const std::string& pin, - PrefService* pref_service, - CredentialProblem* length_problem) { - int min_length, max_length; - GetSanitizedPolicyPinMinMaxLength(pref_service, &min_length, &max_length); +// Checks whether a given |pin| has any problems given the PIN min/max policies +// in |pref_service|. Returns CREDENTIAL_PROBLEM_NONE if |pin| has no problems, +// or another CREDENTIAL_PROBLEM_ enum value to indicate the detected problem. +CredentialProblem GetCredentialProblemForPin(const std::string& pin, + PrefService* pref_service) { + int min_length; + int max_length; + std::tie(min_length, max_length) = + GetSanitizedPolicyPinMinMaxLength(pref_service); // Check if the PIN is shorter than the minimum specified length. - if (static_cast<int>(pin.size()) < min_length) { - if (length_problem) - *length_problem = CredentialProblem::CREDENTIAL_PROBLEM_TOO_SHORT; - return false; - } + if (pin.size() < static_cast<size_t>(min_length)) + return CredentialProblem::CREDENTIAL_PROBLEM_TOO_SHORT; // If the maximum specified length is zero, there is no maximum length. // Otherwise check if the PIN is longer than the maximum specified length. - if (max_length != 0 && static_cast<int>(pin.size()) > max_length) { - if (length_problem) - *length_problem = CredentialProblem::CREDENTIAL_PROBLEM_TOO_LONG; - return false; - } + if (max_length != 0 && pin.size() > static_cast<size_t>(max_length)) + return CredentialProblem::CREDENTIAL_PROBLEM_TOO_LONG; - return true; + return CredentialProblem::CREDENTIAL_PROBLEM_NONE; } // Checks if a given |pin| is weak or not. A PIN is considered weak if it: @@ -141,21 +135,19 @@ bool IsPinDifficultEnough(const std::string& pin) { // If the pin length is |kMinLengthForNonWeakPin| or less, there is no need to // check for same character and increasing pin. - if (static_cast<int>(pin.size()) <= kMinLengthForNonWeakPin) + if (pin.size() <= kMinLengthForNonWeakPin) return true; // Check if it is on the list of most common PINs. - if (std::find(kMostCommonPins, std::end(kMostCommonPins), pin) != - std::end(kMostCommonPins)) { + if (base::ContainsValue(kMostCommonPins, pin)) return false; - } // Check for same digits, increasing and decreasing PIN simultaneously. bool is_same = true; // TODO(sammiequon): Should longer PINs (5+) be still subjected to this? bool is_increasing = true; bool is_decreasing = true; - for (int i = 1; i < static_cast<int>(pin.length()); ++i) { + for (size_t i = 1; i < pin.length(); ++i) { const char previous = pin[i - 1]; const char current = pin[i]; @@ -235,25 +227,19 @@ bool allow_weak = pref_service->GetBoolean(prefs::kPinUnlockWeakPinsAllowed); // Check and return the problems. - if (!IsPinNumeric(credential)) { - result->errors.push_back( - CredentialProblem::CREDENTIAL_PROBLEM_CONTAINS_NONDIGIT); - } + std::vector<CredentialProblem>& warnings = result->warnings; + std::vector<CredentialProblem>& errors = result->errors; + if (!IsPinNumeric(credential)) + errors.push_back(CredentialProblem::CREDENTIAL_PROBLEM_CONTAINS_NONDIGIT); - CredentialProblem length_problem = CredentialProblem::CREDENTIAL_PROBLEM_NONE; - // Note: This function call writes values |length_problem|. - if (!IsPinLengthValid(credential, pref_service, &length_problem)) { - DCHECK_NE(length_problem, CredentialProblem::CREDENTIAL_PROBLEM_NONE); - result->errors.push_back(length_problem); - } + CredentialProblem length_problem = + GetCredentialProblemForPin(credential, pref_service); + if (length_problem != CredentialProblem::CREDENTIAL_PROBLEM_NONE) + errors.push_back(length_problem); if (!IsPinDifficultEnough(credential)) { - if (allow_weak) { - result->warnings.push_back( - CredentialProblem::CREDENTIAL_PROBLEM_TOO_WEAK); - } else { - result->errors.push_back(CredentialProblem::CREDENTIAL_PROBLEM_TOO_WEAK); - } + auto& log = allow_weak ? warnings : errors; + log.push_back(CredentialProblem::CREDENTIAL_PROBLEM_TOO_WEAK); } return RespondNow(ArgumentList(CheckCredential::Results::Create(*result))); @@ -272,10 +258,9 @@ EXTENSION_FUNCTION_VALIDATE(params_); auto result = std::make_unique<CredentialRequirements>(); - - GetSanitizedPolicyPinMinMaxLength( - Profile::FromBrowserContext(browser_context())->GetPrefs(), - &result->min_length, &result->max_length); + std::tie(result->min_length, result->max_length) = + GetSanitizedPolicyPinMinMaxLength( + Profile::FromBrowserContext(browser_context())->GetPrefs()); return RespondNow( ArgumentList(GetCredentialRequirements::Results::Create(*result))); @@ -317,20 +302,22 @@ Profile::FromBrowserContext(browser_context())->GetPrefs(); bool allow_weak = pref_service->GetBoolean(prefs::kPinUnlockWeakPinsAllowed); - for (size_t j = 0; j < params_->modes.size(); ++j) { - if (params_->credentials[j].empty()) + for (size_t i = 0; i < params_->modes.size(); ++i) { + if (params_->credentials[i].empty()) continue; - if (params_->modes[j] != QuickUnlockMode::QUICK_UNLOCK_MODE_PIN) + if (params_->modes[i] != QuickUnlockMode::QUICK_UNLOCK_MODE_PIN) continue; - if (!IsPinNumeric(params_->credentials[j])) + if (!IsPinNumeric(params_->credentials[i])) return RespondNow(ArgumentList(SetModes::Results::Create(false))); - if (!IsPinLengthValid(params_->credentials[j], pref_service, nullptr)) + CredentialProblem problem = + GetCredentialProblemForPin(params_->credentials[i], pref_service); + if (problem != CredentialProblem::CREDENTIAL_PROBLEM_NONE) return RespondNow(ArgumentList(SetModes::Results::Create(false))); - if (!allow_weak && !IsPinDifficultEnough(params_->credentials[j])) { + if (!allow_weak && !IsPinDifficultEnough(params_->credentials[i])) { return RespondNow(ArgumentList(SetModes::Results::Create(false))); } } @@ -352,10 +339,10 @@ // Lazily allocate the authenticator. We do this here, instead of in the ctor, // so that tests can install a fake. DCHECK(!extended_authenticator_); - if (authenticator_allocator_.is_null()) - extended_authenticator_ = chromeos::ExtendedAuthenticator::Create(this); - else + if (authenticator_allocator_) extended_authenticator_ = authenticator_allocator_.Run(this); + else + extended_authenticator_ = chromeos::ExtendedAuthenticator::Create(this); // The extension function needs to stay alive while the authenticator is // running the password check. Add a ref before the authenticator starts, and @@ -410,6 +397,7 @@ std::string pin_credential; // Compute needed changes. + DCHECK_EQ(params_->credentials.size(), params_->modes.size()); for (size_t i = 0; i < params_->modes.size(); ++i) { const QuickUnlockMode mode = params_->modes[i]; const std::string& credential = params_->credentials[i]; @@ -439,15 +427,15 @@ void QuickUnlockPrivateSetModesFunction::FireEvent( const QuickUnlockModeList& modes) { // Allow unit tests to override how events are raised/handled. - if (!modes_changed_handler_.is_null()) { + if (modes_changed_handler_) { modes_changed_handler_.Run(modes); return; } std::unique_ptr<base::ListValue> args = OnActiveModesChanged::Create(modes); - std::unique_ptr<Event> event( - new Event(events::QUICK_UNLOCK_PRIVATE_ON_ACTIVE_MODES_CHANGED, - OnActiveModesChanged::kEventName, std::move(args))); + auto event = std::make_unique<Event>( + events::QUICK_UNLOCK_PRIVATE_ON_ACTIVE_MODES_CHANGED, + OnActiveModesChanged::kEventName, std::move(args)); EventRouter::Get(browser_context())->BroadcastEvent(std::move(event)); }
diff --git a/chrome/browser/chromeos/extensions/quick_unlock_private/quick_unlock_private_api.h b/chrome/browser/chromeos/extensions/quick_unlock_private/quick_unlock_private_api.h index 34aac6a1..6c48051 100644 --- a/chrome/browser/chromeos/extensions/quick_unlock_private/quick_unlock_private_api.h +++ b/chrome/browser/chromeos/extensions/quick_unlock_private/quick_unlock_private_api.h
@@ -5,6 +5,9 @@ #ifndef CHROME_BROWSER_CHROMEOS_EXTENSIONS_QUICK_UNLOCK_PRIVATE_QUICK_UNLOCK_PRIVATE_API_H_ #define CHROME_BROWSER_CHROMEOS_EXTENSIONS_QUICK_UNLOCK_PRIVATE_QUICK_UNLOCK_PRIVATE_API_H_ +#include <memory> +#include <vector> + #include "base/callback.h" #include "base/memory/ref_counted.h" #include "chrome/browser/extensions/chrome_extension_function_details.h"
diff --git a/chrome/browser/chromeos/file_manager/external_filesystem_apitest.cc b/chrome/browser/chromeos/file_manager/external_filesystem_apitest.cc index e013b0b..d323af4 100644 --- a/chrome/browser/chromeos/file_manager/external_filesystem_apitest.cc +++ b/chrome/browser/chromeos/file_manager/external_filesystem_apitest.cc
@@ -21,6 +21,7 @@ #include "chrome/browser/ui/browser.h" #include "chrome/common/chrome_constants.h" #include "chrome/common/chrome_paths.h" +#include "chromeos/chromeos_switches.h" #include "components/drive/service/fake_drive_service.h" #include "components/session_manager/core/session_manager.h" #include "content/public/browser/browser_context.h" @@ -331,8 +332,10 @@ BackgroundObserver page_complete; const Extension* file_handler = LoadExtension(test_data_dir_.AppendASCII(filehandler_path)); - if (!file_handler) + if (!file_handler) { + message_ = "Error loading file handler extension"; return false; + } if (flags & FLAGS_LAZY_FILE_HANDLER) { page_complete.WaitUntilClosed(); @@ -346,8 +349,10 @@ const Extension* file_browser = LoadExtensionAsComponentWithManifest( test_data_dir_.AppendASCII(filebrowser_path), filebrowser_manifest); - if (!file_browser) + if (!file_browser) { + message_ = "Could not create file browser"; return false; + } if (!catcher.GetNextResult()) { message_ = catcher.message(); @@ -500,6 +505,15 @@ public: MultiProfileDriveFileSystemExtensionApiTest() {} + void SetUpCommandLine(base::CommandLine* command_line) override { + FileSystemExtensionApiTestBase::SetUpCommandLine(command_line); + // Don't require policy for our sessions - this is required because + // this test creates a secondary profile synchronously, so we need to + // let the policy code know not to expect cached policy. + command_line->AppendSwitchASCII(chromeos::switches::kProfileRequiresPolicy, + "false"); + } + void SetUpOnMainThread() override { base::FilePath user_data_directory; PathService::Get(chrome::DIR_USER_DATA, &user_data_directory);
diff --git a/chrome/browser/chromeos/file_manager/file_manager_browsertest.cc b/chrome/browser/chromeos/file_manager/file_manager_browsertest.cc index 7e3bce5..752a51d 100644 --- a/chrome/browser/chromeos/file_manager/file_manager_browsertest.cc +++ b/chrome/browser/chromeos/file_manager/file_manager_browsertest.cc
@@ -596,6 +596,11 @@ kTestAccounts[DUMMY_ACCOUNT_INDEX].email); command_line->AppendSwitchASCII(chromeos::switches::kLoginProfile, kTestAccounts[DUMMY_ACCOUNT_INDEX].hash); + // Don't require policy for our sessions - this is required because + // this test creates a secondary profile synchronously, so we need to + // let the policy code know not to expect cached policy. + command_line->AppendSwitchASCII(chromeos::switches::kProfileRequiresPolicy, + "false"); } // Logs in to the primary profile of this test.
diff --git a/chrome/browser/chromeos/hats/hats_dialog.cc b/chrome/browser/chromeos/hats/hats_dialog.cc index d29dbbc26..c999ac7 100644 --- a/chrome/browser/chromeos/hats/hats_dialog.cc +++ b/chrome/browser/chromeos/hats/hats_dialog.cc
@@ -13,6 +13,7 @@ #include "chrome/grit/browser_resources.h" #include "chrome/grit/generated_resources.h" #include "chromeos/system/version_loader.h" +#include "components/language/core/common/locale_util.h" #include "components/prefs/pref_service.h" #include "components/version_info/version_info.h" #include "ui/base/l10n/l10n_util.h" @@ -119,6 +120,7 @@ Profile* profile = ProfileManager::GetActiveUserProfile(); std::string user_locale = profile->GetPrefs()->GetString(prefs::kApplicationLocale); + language::ConvertToActualUILocale(&user_locale); if (!user_locale.length()) user_locale = kDefaultProfileLocale;
diff --git a/chrome/browser/chromeos/locale_change_guard.cc b/chrome/browser/chromeos/locale_change_guard.cc index 6454e0f..5bbdf38 100644 --- a/chrome/browser/chromeos/locale_change_guard.cc +++ b/chrome/browser/chromeos/locale_change_guard.cc
@@ -19,6 +19,7 @@ #include "chrome/browser/ui/browser.h" #include "chrome/browser/ui/browser_commands.h" #include "chrome/common/pref_names.h" +#include "components/language/core/common/locale_util.h" #include "components/prefs/pref_service.h" #include "content/public/browser/notification_service.h" #include "content/public/browser/notification_source.h" @@ -141,6 +142,7 @@ PrefService* prefs = profile_->GetPrefs(); DCHECK(prefs); std::string owner_locale = prefs->GetString(prefs::kApplicationLocale); + language::ConvertToActualUILocale(&owner_locale); if (!owner_locale.empty()) local_state->SetString(prefs::kOwnerLocale, owner_locale); } @@ -159,6 +161,7 @@ } std::string to_locale = prefs->GetString(prefs::kApplicationLocale); + language::ConvertToActualUILocale(&to_locale); if (to_locale != cur_locale) { // This conditional branch can occur in cases like: // (1) kApplicationLocale preference was modified by synchronization;
diff --git a/chrome/browser/chromeos/login/auto_launched_kiosk_browsertest.cc b/chrome/browser/chromeos/login/auto_launched_kiosk_browsertest.cc index 4c41f62..b67baee 100644 --- a/chrome/browser/chromeos/login/auto_launched_kiosk_browsertest.cc +++ b/chrome/browser/chromeos/login/auto_launched_kiosk_browsertest.cc
@@ -23,6 +23,7 @@ #include "chrome/browser/chromeos/ownership/owner_settings_service_chromeos_factory.h" #include "chrome/browser/chromeos/policy/device_local_account.h" #include "chrome/browser/chromeos/policy/device_policy_builder.h" +#include "chrome/browser/chromeos/policy/device_policy_cros_browser_test.h" #include "chrome/browser/chromeos/settings/stub_install_attributes.h" #include "chrome/browser/extensions/browsertest_util.h" #include "chrome/browser/extensions/extension_apitest.h" @@ -34,7 +35,6 @@ #include "chromeos/dbus/dbus_thread_manager.h" #include "chromeos/dbus/fake_session_manager_client.h" #include "chromeos/dbus/shill_manager_client.h" -#include "components/ownership/mock_owner_key_util.h" #include "content/public/browser/notification_observer.h" #include "content/public/browser/notification_registrar.h" #include "content/public/browser/notification_service.h" @@ -44,6 +44,7 @@ #include "extensions/browser/app_window/native_app_window.h" #include "extensions/common/value_builder.h" #include "extensions/test/extension_test_message_listener.h" +#include "extensions/test/result_catcher.h" #include "net/dns/mock_host_resolver.h" #include "third_party/cros_system_api/switches/chrome_switches.h" @@ -57,26 +58,50 @@ // it again. Webstore data json is in // chrome/test/data/chromeos/app_mode/webstore/inlineinstall/ // detail/ggbflgnkafappblpkiflbgpmkfdpnhhe -const char kTestKioskApp[] = "ggbflgnkafappblpkiflbgpmkfdpnhhe"; +constexpr char kTestKioskApp[] = "ggbflgnkafappblpkiflbgpmkfdpnhhe"; // This is a simple test that only sends an extension message when app launch is // requested. Webstore data json is in // chrome/test/data/chromeos/app_mode/webstore/inlineinstall/ // detail/mogpelihofihkjnkkfkcchbkchggmcld -const char kTestNonKioskEnabledApp[] = "mogpelihofihkjnkkfkcchbkchggmcld"; +constexpr char kTestNonKioskEnabledApp[] = "mogpelihofihkjnkkfkcchbkchggmcld"; -const char kTestAccountId[] = "enterprise-kiosk-app@localhost"; +// Primary kiosk app that runs tests for chrome.management API. +// The tests are run on the kiosk app launch event. +// It has a secondary test kiosk app, which is loaded alongside the app. The +// secondary app will send a message to run chrome.management API tests in +// in its context as well. +// The app's CRX is located under: +// chrome/test/data/chromeos/app_mode/webstore/downloads/ +// faiboenfkkoaedoehhkjmenkhidadgje.crx +// Source from which the CRX is generated is under path: +// chrome/test/data/chromeos/app_mode/management_api/primary_app/ +constexpr char kTestManagementApiKioskApp[] = + "faiboenfkkoaedoehhkjmenkhidadgje"; -const char kSessionManagerStateCache[] = "test_session_manager_state.json"; +// Secondary kiosk app that runs tests for chrome.management API. +// The app is loaded alongside |kTestManagementApiKioskApp|. The tests are run +// in the response to a message sent from |kTestManagementApiKioskApp|. +// The app's CRX is located under: +// chrome/test/data/chromeos/app_mode/webstore/downloads/ +// lfaidgolgikbpapkmdhoppddflhaocnf.crx +// Source from which the CRX is generated is under path: +// chrome/test/data/chromeos/app_mode/management_api/secondary_app/ +constexpr char kTestManagementApiSecondaryApp[] = + "lfaidgolgikbpapkmdhoppddflhaocnf"; + +constexpr char kTestAccountId[] = "enterprise-kiosk-app@localhost"; + +constexpr char kSessionManagerStateCache[] = "test_session_manager_state.json"; // Keys for values in dictionary used to preserve session manager state. -const char kLoginArgsKey[] = "login_args"; -const char kExtraArgsKey[] = "extra_args"; -const char kArgNameKey[] = "name"; -const char kArgValueKey[] = "value"; +constexpr char kLoginArgsKey[] = "login_args"; +constexpr char kExtraArgsKey[] = "extra_args"; +constexpr char kArgNameKey[] = "name"; +constexpr char kArgValueKey[] = "value"; // Default set policy switches. -const struct { +constexpr struct { const char* name; const char* value; } kDefaultPolicySwitches[] = {{"test_switch_1", ""}, @@ -264,7 +289,6 @@ chromeos::ScopedStubInstallAttributes::CreateCloudManaged( "domain.com", "device_id")), - owner_key_util_(new ownership::MockOwnerKeyUtil()), fake_session_manager_(new PersistentSessionManagerClient()), fake_cws_(new FakeCWS) { set_chromeos_user_ = false; @@ -273,6 +297,9 @@ ~AutoLaunchedKioskTest() override = default; virtual std::string GetTestAppId() const { return kTestKioskApp; } + virtual std::vector<std::string> GetTestSecondaryAppIds() const { + return std::vector<std::string>(); + } void SetUp() override { ASSERT_TRUE(embedded_test_server()->InitializeAndListen()); @@ -284,6 +311,9 @@ void SetUpCommandLine(base::CommandLine* command_line) override { fake_cws_->Init(embedded_test_server()); fake_cws_->SetUpdateCrx(GetTestAppId(), GetTestAppId() + ".crx", "1.0.0"); + std::vector<std::string> secondary_apps = GetTestSecondaryAppIds(); + for (const auto& secondary_app : secondary_apps) + fake_cws_->SetUpdateCrx(secondary_app, secondary_app + ".crx", "1.0.0"); ExtensionApiTest::SetUpCommandLine(command_line); } @@ -312,12 +342,13 @@ void SetUpInProcessBrowserTestFixture() override { host_resolver()->AddRule("*", "127.0.0.1"); - OwnerSettingsServiceChromeOSFactory::GetInstance() - ->SetOwnerKeyUtilForTesting(owner_key_util_); - owner_key_util_->SetPublicKeyFromPrivateKey( - *device_policy_.GetSigningKey()); + fake_session_manager_->set_device_policy( + device_policy_helper_.device_policy()->GetBlob()); + fake_session_manager_->set_device_local_account_policy( + kTestAccountId, device_local_account_policy_.GetBlob()); - fake_session_manager_->set_device_policy(device_policy_.GetBlob()); + // Arbitrary non-empty state keys. + fake_session_manager_->set_server_backed_state_keys({"1"}); DBusThreadManager::GetSetterForTesting()->SetSessionManagerClient( std::move(fake_session_manager_)); @@ -344,9 +375,14 @@ } void InitDevicePolicy() { + device_policy_helper_.InstallOwnerKey(); + device_policy_helper_.MarkAsEnterpriseOwned(); + // Create device policy, and cache it to local state. em::DeviceLocalAccountsProto* const device_local_accounts = - device_policy_.payload().mutable_device_local_accounts(); + device_policy_helper_.device_policy() + ->payload() + .mutable_device_local_accounts(); em::DeviceLocalAccountInfoProto* const account = device_local_accounts->add_account(); @@ -356,12 +392,19 @@ device_local_accounts->set_auto_login_id(kTestAccountId); - device_policy_.Build(); + device_policy_helper_.device_policy()->Build(); + + device_local_account_policy_.policy_data().set_username(kTestAccountId); + device_local_account_policy_.policy_data().set_policy_type( + policy::dm_protocol::kChromePublicAccountPolicyType); + device_local_account_policy_.policy_data().set_settings_entity_id( + kTestAccountId); + device_local_account_policy_.Build(); } bool CacheDevicePolicyToLocalState(const base::FilePath& user_data_path) { em::PolicyData policy_data; - if (!device_policy_.payload().SerializeToString( + if (!device_policy_helper_.device_policy()->payload().SerializeToString( policy_data.mutable_policy_value())) { ADD_FAILURE() << "Failed to serialize device policy."; return false; @@ -440,8 +483,8 @@ private: chromeos::ScopedStubInstallAttributes install_attributes_; - policy::DevicePolicyBuilder device_policy_; - scoped_refptr<ownership::MockOwnerKeyUtil> owner_key_util_; + policy::UserPolicyBuilder device_local_account_policy_; + policy::DevicePolicyCrosTestHelper device_policy_helper_; std::unique_ptr<PersistentSessionManagerClient> fake_session_manager_; std::unique_ptr<FakeCWS> fake_cws_; @@ -525,4 +568,37 @@ EXPECT_EQ(KioskAppLaunchError::NOT_KIOSK_ENABLED, KioskAppLaunchError::Get()); } +// Used to test management API availability in kiosk sessions. +class ManagementApiKioskTest : public AutoLaunchedKioskTest { + public: + ManagementApiKioskTest() {} + ~ManagementApiKioskTest() override = default; + + // AutoLaunchedKioskTest: + std::string GetTestAppId() const override { + return kTestManagementApiKioskApp; + } + std::vector<std::string> GetTestSecondaryAppIds() const override { + return {kTestManagementApiSecondaryApp}; + } + + private: + DISALLOW_COPY_AND_ASSIGN(ManagementApiKioskTest); +}; + +IN_PROC_BROWSER_TEST_F(ManagementApiKioskTest, ManagementApi) { + // Set up default network connections, so tests think the device is online. + DBusThreadManager::Get() + ->GetShillManagerClient() + ->GetTestInterface() + ->SetupDefaultEnvironment(); + + // The tests expects to recieve two test result messages: + // * result for tests run by the secondary kiosk app. + // * result for tests run by the primary kiosk app. + extensions::ResultCatcher catcher; + EXPECT_TRUE(catcher.GetNextResult()) << catcher.message(); + EXPECT_TRUE(catcher.GetNextResult()) << catcher.message(); +} + } // namespace chromeos
diff --git a/chrome/browser/chromeos/login/ui/login_display_host_webui.cc b/chrome/browser/chromeos/login/ui/login_display_host_webui.cc index deddcb56..7604e10 100644 --- a/chrome/browser/chromeos/login/ui/login_display_host_webui.cc +++ b/chrome/browser/chromeos/login/ui/login_display_host_webui.cc
@@ -74,6 +74,7 @@ #include "chromeos/timezone/timezone_resolver.h" #include "components/keep_alive_registry/keep_alive_types.h" #include "components/keep_alive_registry/scoped_keep_alive.h" +#include "components/language/core/common/locale_util.h" #include "components/prefs/pref_service.h" #include "components/session_manager/core/session_manager.h" #include "components/signin/core/account_id/account_id.h" @@ -1287,8 +1288,8 @@ } PrefService* prefs = g_browser_process->local_state(); - const std::string& current_locale = - prefs->GetString(prefs::kApplicationLocale); + std::string current_locale = prefs->GetString(prefs::kApplicationLocale); + language::ConvertToActualUILocale(¤t_locale); VLOG(1) << "Current locale: " << current_locale; if (ShouldShowSigninScreen(first_screen)) {
diff --git a/chrome/browser/chromeos/login/users/user_manager_unittest.cc b/chrome/browser/chromeos/login/users/user_manager_unittest.cc index c05e31f..848eee8 100644 --- a/chrome/browser/chromeos/login/users/user_manager_unittest.cc +++ b/chrome/browser/chromeos/login/users/user_manager_unittest.cc
@@ -304,4 +304,14 @@ EXPECT_TRUE((*users)[0]->profile_ever_initialized()); } +TEST_F(UserManagerTest, ProfileRequiresPolicyUnknown) { + user_manager::UserManager::Get()->UserLoggedIn( + owner_account_id_at_invalid_domain_, + owner_account_id_at_invalid_domain_.GetUserEmail(), false, false); + EXPECT_EQ(user_manager::known_user::ProfileRequiresPolicy::kUnknown, + user_manager::known_user::GetProfileRequiresPolicy( + owner_account_id_at_invalid_domain_)); + ResetUserManager(); +} + } // namespace chromeos
diff --git a/chrome/browser/chromeos/net/shill_error.cc b/chrome/browser/chromeos/net/shill_error.cc index 088f6368..1d8b3b9 100644 --- a/chrome/browser/chromeos/net/shill_error.cc +++ b/chrome/browser/chromeos/net/shill_error.cc
@@ -110,6 +110,15 @@ base::UTF8ToUTF16(error)); } +bool IsConfigurationError(const std::string& error) { + if (error.empty()) + return false; + return error == shill::kErrorPinMissing || + error == shill::kErrorBadPassphrase || + error == shill::kErrorResultInvalidPassphrase || + error == shill::kErrorBadWEPKey; +} + } // namespace shill_error } // namespace chromeos
diff --git a/chrome/browser/chromeos/net/shill_error.h b/chrome/browser/chromeos/net/shill_error.h index 068feb9..77837722 100644 --- a/chrome/browser/chromeos/net/shill_error.h +++ b/chrome/browser/chromeos/net/shill_error.h
@@ -15,6 +15,9 @@ base::string16 GetShillErrorString(const std::string& error, const std::string& network_id); +// Returns true if |error| is known to be a configuration error. +bool IsConfigurationError(const std::string& error); + } // namespace shill_error } // namespace chromeos
diff --git a/chrome/browser/chromeos/policy/blocking_login_browsertest.cc b/chrome/browser/chromeos/policy/blocking_login_browsertest.cc index 3c3771e..5b29962 100644 --- a/chrome/browser/chromeos/policy/blocking_login_browsertest.cc +++ b/chrome/browser/chromeos/policy/blocking_login_browsertest.cc
@@ -26,6 +26,7 @@ #include "components/policy/core/common/cloud/device_management_service.h" #include "components/policy/core/common/policy_switches.h" #include "components/policy/proto/device_management_backend.pb.h" +#include "components/user_manager/known_user.h" #include "components/user_manager/user_manager.h" #include "content/public/browser/notification_observer.h" #include "content/public/browser/notification_registrar.h" @@ -82,7 +83,7 @@ const bool enroll_device; }; -// TODO(atwilson): This test is completely broken - it originally was built +// TODO(poromov): This test is completely broken - it originally was built // when we made an entirely different set of network calls on startup. As a // result it generates random failures in startup network requests, then waits // to see if the profile finishes loading which is not at all what it is @@ -101,9 +102,6 @@ command_line->AppendSwitchASCII( policy::switches::kDeviceManagementUrl, embedded_test_server()->GetURL("/device_management").spec()); - - command_line->AppendSwitch( - chromeos::switches::kAllowFailedPolicyFetchForTest); } void SetUpOnMainThread() override { @@ -338,7 +336,9 @@ {5, kUsernameOtherDomain, true}, }; -INSTANTIATE_TEST_CASE_P(BlockingLoginTestInstance, +// TODO(poromov): Disabled because it has become flaky due to incorrect mock +// network requests - re-enable this when https://crbug.com/580537 is fixed. +INSTANTIATE_TEST_CASE_P(DISABLED_BlockingLoginTestInstance, BlockingLoginTest, testing::ValuesIn(kBlockinLoginTestCases));
diff --git a/chrome/browser/chromeos/policy/browser_policy_connector_chromeos.cc b/chrome/browser/chromeos/policy/browser_policy_connector_chromeos.cc index 809baa40..15e9a38 100644 --- a/chrome/browser/chromeos/policy/browser_policy_connector_chromeos.cc +++ b/chrome/browser/chromeos/policy/browser_policy_connector_chromeos.cc
@@ -355,11 +355,13 @@ RestartDeviceCloudPolicyInitializer(); } -void BrowserPolicyConnectorChromeOS::BuildPolicyProviders( - std::vector<std::unique_ptr<ConfigurationPolicyProvider>>* providers) { +std::vector<std::unique_ptr<policy::ConfigurationPolicyProvider>> +BrowserPolicyConnectorChromeOS::CreatePolicyProviders() { + auto providers = ChromeBrowserPolicyConnector::CreatePolicyProviders(); for (auto& provider_ptr : providers_for_init_) - providers->push_back(std::move(provider_ptr)); + providers.push_back(std::move(provider_ptr)); providers_for_init_.clear(); + return providers; } void BrowserPolicyConnectorChromeOS::SetTimezoneIfPolicyAvailable() {
diff --git a/chrome/browser/chromeos/policy/browser_policy_connector_chromeos.h b/chrome/browser/chromeos/policy/browser_policy_connector_chromeos.h index d79f700..c72c00c 100644 --- a/chrome/browser/chromeos/policy/browser_policy_connector_chromeos.h +++ b/chrome/browser/chromeos/policy/browser_policy_connector_chromeos.h
@@ -180,9 +180,8 @@ protected: // ChromeBrowserPolicyConnector: - void BuildPolicyProviders( - std::vector<std::unique_ptr<ConfigurationPolicyProvider>>* providers) - override; + std::vector<std::unique_ptr<policy::ConfigurationPolicyProvider>> + CreatePolicyProviders() override; private: // Set the timezone as soon as the policies are available.
diff --git a/chrome/browser/chromeos/policy/cloud_external_data_policy_observer_unittest.cc b/chrome/browser/chromeos/policy/cloud_external_data_policy_observer_unittest.cc index 70da940..40465dc20 100644 --- a/chrome/browser/chromeos/policy/cloud_external_data_policy_observer_unittest.cc +++ b/chrome/browser/chromeos/policy/cloud_external_data_policy_observer_unittest.cc
@@ -334,8 +334,7 @@ providers.push_back(device_local_account_policy_provider_.get()); TestingProfile::Builder builder; std::unique_ptr<PolicyServiceImpl> policy_service = - std::make_unique<PolicyServiceImpl>(); - policy_service->SetProviders(providers); + std::make_unique<PolicyServiceImpl>(std::move(providers)); builder.SetPolicyService(std::move(policy_service)); builder.SetPath(chromeos::ProfileHelper::Get()->GetProfilePathByUserIdHash( chromeos::ProfileHelper::GetUserIdHashByUserIdForTesting( @@ -370,8 +369,7 @@ providers.push_back(&user_policy_provider_); TestingProfile::Builder builder; std::unique_ptr<PolicyServiceImpl> policy_service = - std::make_unique<PolicyServiceImpl>(); - policy_service->SetProviders(providers); + std::make_unique<PolicyServiceImpl>(std::move(providers)); builder.SetPolicyService(std::move(policy_service)); builder.SetPath(chromeos::ProfileHelper::Get()->GetProfilePathByUserIdHash( chromeos::ProfileHelper::GetUserIdHashByUserIdForTesting(
diff --git a/chrome/browser/chromeos/policy/network_configuration_updater_unittest.cc b/chrome/browser/chromeos/policy/network_configuration_updater_unittest.cc index 6dfce50..a184fd89 100644 --- a/chrome/browser/chromeos/policy/network_configuration_updater_unittest.cc +++ b/chrome/browser/chromeos/policy/network_configuration_updater_unittest.cc
@@ -220,8 +220,7 @@ provider_.Init(); PolicyServiceImpl::Providers providers; providers.push_back(&provider_); - policy_service_ = std::make_unique<PolicyServiceImpl>(); - policy_service_->SetProviders(providers); + policy_service_ = std::make_unique<PolicyServiceImpl>(std::move(providers)); std::unique_ptr<base::DictionaryValue> fake_toplevel_onc = chromeos::onc::ReadDictionaryFromJson(kFakeONC);
diff --git a/chrome/browser/chromeos/policy/policy_oauth2_token_fetcher.cc b/chrome/browser/chromeos/policy/policy_oauth2_token_fetcher.cc index 3787e97..a2230a8f 100644 --- a/chrome/browser/chromeos/policy/policy_oauth2_token_fetcher.cc +++ b/chrome/browser/chromeos/policy/policy_oauth2_token_fetcher.cc
@@ -248,7 +248,8 @@ base::TimeDelta::FromMilliseconds(kRequestRestartDelay)); return; } - LOG(ERROR) << "Unrecoverable error or retry count max reached."; + LOG(ERROR) << "Unrecoverable error or retry count max reached: " + << error.state(); failed_ = true; // Invoking the |callback_| signals to the owner of this object that it has // completed, and the owner may delete this object on the callback method.
diff --git a/chrome/browser/chromeos/policy/remote_commands/screenshot_delegate.cc b/chrome/browser/chromeos/policy/remote_commands/screenshot_delegate.cc index 06e1e4e..8768838 100644 --- a/chrome/browser/chromeos/policy/remote_commands/screenshot_delegate.cc +++ b/chrome/browser/chromeos/policy/remote_commands/screenshot_delegate.cc
@@ -59,11 +59,30 @@ device_oauth2_token_service->GetRobotAccountId(); SYSLOG(INFO) << "Creating upload job for screenshot"; + net::NetworkTrafficAnnotationTag traffic_annotation = + net::DefineNetworkTrafficAnnotation("remote_command_screenshot", R"( + semantics { + sender: "Chrome OS Remote Commands" + description: "Admins of kiosks are able to request screenshots " + "of the current screen shown on the kiosk, which is uploaded to " + "the device management server." + trigger: "Admin requests remote screenshot on the Admin Console." + data: "Screenshot of the current screen shown on the kiosk." + destination: GOOGLE_OWNED_SERVICE + } + policy { + cookies_allowed: NO + setting: "This feature cannot be disabled in settings, however this " + "request will only happen on explicit admin request and when no " + "user interaction or media capture happened since last reboot." + policy_exception_justification: "Requires explicit admin action." + } + )"); return std::unique_ptr<UploadJob>(new UploadJobImpl( upload_url, robot_account_id, device_oauth2_token_service, system_request_context, delegate, base::WrapUnique(new UploadJobImpl::RandomMimeBoundaryGenerator), - base::ThreadTaskRunnerHandle::Get())); + traffic_annotation, base::ThreadTaskRunnerHandle::Get())); } void ScreenshotDelegate::StoreScreenshot(
diff --git a/chrome/browser/chromeos/policy/system_log_uploader.cc b/chrome/browser/chromeos/policy/system_log_uploader.cc index 955b31e1..5d1136ef 100644 --- a/chrome/browser/chromeos/policy/system_log_uploader.cc +++ b/chrome/browser/chromeos/policy/system_log_uploader.cc
@@ -149,11 +149,32 @@ device_oauth2_token_service->GetRobotAccountId(); SYSLOG(INFO) << "Creating upload job for system log"; + net::NetworkTrafficAnnotationTag traffic_annotation = + net::DefineNetworkTrafficAnnotation("policy_system_logs", R"( + semantics { + sender: "Chrome OS system log uploader" + description: + "Admins can ask that their devices regularly upload their system " + "logs." + trigger: "After reboot and every 12 hours." + data: "Non-user specific, anonymized system logs from /var/log/." + destination: GOOGLE_OWNED_SERVICE + } + policy { + cookies_allowed: NO + setting: "This feature cannot be disabled in settings." + chrome_policy { + LogUploadEnabled { + LogUploadEnabled: false + } + } + } + )"); return std::make_unique<UploadJobImpl>( upload_url, robot_account_id, device_oauth2_token_service, system_request_context, delegate, std::make_unique<UploadJobImpl::RandomMimeBoundaryGenerator>(), - task_runner_); + traffic_annotation, task_runner_); } // Returns the system log upload frequency.
diff --git a/chrome/browser/chromeos/policy/upload_job_impl.cc b/chrome/browser/chromeos/policy/upload_job_impl.cc index ec54f93cd..9fd89b2 100644 --- a/chrome/browser/chromeos/policy/upload_job_impl.cc +++ b/chrome/browser/chromeos/policy/upload_job_impl.cc
@@ -18,6 +18,7 @@ #include "google_apis/gaia/google_service_auth_error.h" #include "net/base/mime_util.h" #include "net/http/http_status_code.h" +#include "net/traffic_annotation/network_traffic_annotation.h" #include "net/url_request/url_request_status.h" namespace policy { @@ -153,6 +154,7 @@ scoped_refptr<net::URLRequestContextGetter> url_context_getter, Delegate* delegate, std::unique_ptr<MimeBoundaryGenerator> boundary_generator, + net::NetworkTrafficAnnotationTag traffic_annotation, scoped_refptr<base::SequencedTaskRunner> task_runner) : OAuth2TokenService::Consumer("cros_upload_job"), upload_url_(upload_url), @@ -161,6 +163,7 @@ url_context_getter_(url_context_getter), delegate_(delegate), boundary_generator_(std::move(boundary_generator)), + traffic_annotation_(traffic_annotation), state_(IDLE), retry_(0), task_runner_(task_runner), @@ -305,8 +308,8 @@ content_type.append("; boundary="); content_type.append(*mime_boundary_.get()); - upload_fetcher_ = - net::URLFetcher::Create(upload_url_, net::URLFetcher::POST, this); + upload_fetcher_ = net::URLFetcher::Create(upload_url_, net::URLFetcher::POST, + this, traffic_annotation_); upload_fetcher_->SetRequestContext(url_context_getter_.get()); upload_fetcher_->SetUploadData(content_type, *post_data_); upload_fetcher_->AddExtraRequestHeader(
diff --git a/chrome/browser/chromeos/policy/upload_job_impl.h b/chrome/browser/chromeos/policy/upload_job_impl.h index 1b2d1cd..4c639519 100644 --- a/chrome/browser/chromeos/policy/upload_job_impl.h +++ b/chrome/browser/chromeos/policy/upload_job_impl.h
@@ -62,7 +62,8 @@ scoped_refptr<net::URLRequestContextGetter> url_context_getter, Delegate* delegate, std::unique_ptr<MimeBoundaryGenerator> boundary_generator, - const scoped_refptr<base::SequencedTaskRunner> task_runner); + net::NetworkTrafficAnnotationTag traffic_annotation, + scoped_refptr<base::SequencedTaskRunner> task_runner); ~UploadJobImpl() override; // UploadJob: @@ -145,6 +146,10 @@ // SetUpMultipart(). std::unique_ptr<MimeBoundaryGenerator> boundary_generator_; + // Network traffic annotation set by the delegate describing what kind of data + // is uploaded. + net::NetworkTrafficAnnotationTag traffic_annotation_; + // Current state the uploader is in. State state_;
diff --git a/chrome/browser/chromeos/policy/upload_job_unittest.cc b/chrome/browser/chromeos/policy/upload_job_unittest.cc index 2073f96..ab2bec3 100644 --- a/chrome/browser/chromeos/policy/upload_job_unittest.cc +++ b/chrome/browser/chromeos/policy/upload_job_unittest.cc
@@ -26,6 +26,7 @@ #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" +#include "net/traffic_annotation/network_traffic_annotation_test_helper.h" #include "net/url_request/url_request_test_util.h" #include "testing/gtest/include/gtest/gtest.h" @@ -200,7 +201,7 @@ std::unique_ptr<UploadJob> upload_job(new UploadJobImpl( GetServerURL(), kRobotAccountId, &oauth2_service_, request_context_getter_.get(), this, std::move(mime_boundary_generator), - base::ThreadTaskRunnerHandle::Get())); + TRAFFIC_ANNOTATION_FOR_TESTS, base::ThreadTaskRunnerHandle::Get())); std::map<std::string, std::string> header_entries; header_entries.insert(std::make_pair(kCustomField1, "CUSTOM1"));
diff --git a/chrome/browser/chromeos/policy/user_cloud_policy_manager_chromeos.cc b/chrome/browser/chromeos/policy/user_cloud_policy_manager_chromeos.cc index f1206f7..81dac49 100644 --- a/chrome/browser/chromeos/policy/user_cloud_policy_manager_chromeos.cc +++ b/chrome/browser/chromeos/policy/user_cloud_policy_manager_chromeos.cc
@@ -26,6 +26,8 @@ #include "chrome/browser/lifetime/application_lifetime.h" #include "chrome/common/chrome_content_client.h" #include "chromeos/chromeos_switches.h" +#include "chromeos/cryptohome/cryptohome_parameters.h" +#include "chromeos/dbus/dbus_thread_manager.h" #include "components/crash/core/common/crash_key.h" #include "components/policy/core/common/cloud/cloud_external_data_manager.h" #include "components/policy/core/common/cloud/cloud_policy_refresh_scheduler.h" @@ -34,6 +36,7 @@ #include "components/policy/core/common/policy_pref_names.h" #include "components/policy/core/common/policy_types.h" #include "components/policy/policy_constants.h" +#include "components/user_manager/known_user.h" #include "components/user_manager/user.h" #include "components/user_manager/user_manager.h" #include "net/url_request/url_request_context_getter.h" @@ -63,29 +66,16 @@ const char kUMAInitialFetchOAuth2NetworkError[] = "Enterprise.UserPolicyChromeOS.InitialFetch.OAuth2NetworkError"; -void OnWildcardCheckCompleted(const std::string& username, - WildcardLoginChecker::Result result) { - if (result == WildcardLoginChecker::RESULT_BLOCKED) { - LOG(ERROR) << "Online wildcard login check failed, terminating session."; - - // TODO(mnissler): This only removes the user pod from the login screen, but - // the cryptohome remains. This is because deleting the cryptohome for a - // logged-in session is not possible. Fix this either by delaying the - // cryptohome deletion operation or by getting rid of the in-session - // wildcard check. - user_manager::UserManager::Get()->RemoveUserFromList( - AccountId::FromUserEmail(username)); - chrome::AttemptUserExit(); - } -} - } // namespace UserCloudPolicyManagerChromeOS::UserCloudPolicyManagerChromeOS( std::unique_ptr<CloudPolicyStore> store, std::unique_ptr<CloudExternalDataManager> external_data_manager, const base::FilePath& component_policy_cache_path, - base::TimeDelta initial_policy_fetch_timeout, + PolicyEnforcement enforcement_type, + base::TimeDelta policy_refresh_timeout, + base::OnceClosure fatal_error_callback, + const AccountId& account_id, const scoped_refptr<base::SequencedTaskRunner>& task_runner, const scoped_refptr<base::SequencedTaskRunner>& io_task_runner) : CloudPolicyManager(dm_protocol::kChromeUserPolicyType, @@ -96,30 +86,40 @@ store_(std::move(store)), external_data_manager_(std::move(external_data_manager)), component_policy_cache_path_(component_policy_cache_path), - waiting_for_initial_policy_fetch_( - !initial_policy_fetch_timeout.is_zero()) { + waiting_for_policy_fetch_(enforcement_type == + PolicyEnforcement::kServerCheckRequired || + !policy_refresh_timeout.is_zero()), + enforcement_type_(enforcement_type), + account_id_(account_id), + fatal_error_callback_(std::move(fatal_error_callback)) { time_init_started_ = base::Time::Now(); - initial_policy_fetch_may_fail_ = - base::CommandLine::ForCurrentProcess()->HasSwitch( - chromeos::switches::kAllowFailedPolicyFetchForTest) || - !initial_policy_fetch_timeout.is_max(); - // No need to set the timer when the timeout is infinite. - if (waiting_for_initial_policy_fetch_ && initial_policy_fetch_may_fail_) { - policy_fetch_timeout_.Start( - FROM_HERE, - initial_policy_fetch_timeout, - base::Bind(&UserCloudPolicyManagerChromeOS::OnBlockingFetchTimeout, - base::Unretained(this))); + // Some tests don't want to complete policy initialization until they have + // manually injected policy even though the profile itself is synchronously + // initialized. + if (base::CommandLine::ForCurrentProcess()->HasSwitch( + chromeos::switches::kWaitForInitialPolicyFetchForTest)) { + waiting_for_policy_fetch_ = true; + } + + // If a refresh timeout was specified, set a timer to call us back. + if (!policy_refresh_timeout.is_zero()) { + // Shouldn't pass a timeout unless we're refreshing existing policy. + DCHECK_EQ(enforcement_type_, PolicyEnforcement::kPolicyRequired); + policy_refresh_timeout_.Start( + FROM_HERE, policy_refresh_timeout, + base::BindRepeating( + &UserCloudPolicyManagerChromeOS::OnPolicyRefreshTimeout, + base::Unretained(this))); } } void UserCloudPolicyManagerChromeOS::ForceTimeoutForTest() { - DCHECK(policy_fetch_timeout_.IsRunning()); + DCHECK(policy_refresh_timeout_.IsRunning()); // Stop the timer to mimic what happens when a real timer fires, then invoke // the timer callback directly. - policy_fetch_timeout_.Stop(); - OnBlockingFetchTimeout(); + policy_refresh_timeout_.Stop(); + OnPolicyRefreshTimeout(); } UserCloudPolicyManagerChromeOS::~UserCloudPolicyManagerChromeOS() {} @@ -163,21 +163,33 @@ // Determine the next step after the CloudPolicyService initializes. if (service()->IsInitializationComplete()) { - OnInitializationCompleted(service()); + // The CloudPolicyStore is already initialized here, which means we must + // have done a synchronous load of policy - this only happens after a crash + // and restart. If we crashed and restarted, it's not possible to block + // waiting for a policy fetch (profile is loading synchronously and async + // operations can't be handled). - // The cloud policy client may be already registered by this point if the - // store has already been loaded and contains a valid policy - the - // registration setup in this case is performed by the CloudPolicyService - // that is instantiated inside the CloudPolicyCore::Connect() method call. - // If that's the case and |waiting_for_initial_policy_fetch_| is true, then - // the policy fetch needs to be issued (it happens otherwise after the - // client registration is finished, in OnRegistrationStateChanged()). - if (client()->is_registered() && waiting_for_initial_policy_fetch_) { - service()->RefreshPolicy( - base::Bind(&UserCloudPolicyManagerChromeOS::CancelWaitForPolicyFetch, - base::Unretained(this))); + // If we are doing a synchronous load, then wait_for_policy_fetch_ should + // never be set (because we can't wait). + CHECK(!waiting_for_policy_fetch_ || + base::CommandLine::ForCurrentProcess()->HasSwitch( + chromeos::switches::kWaitForInitialPolicyFetchForTest)); + if (!client()->is_registered() && + enforcement_type_ != PolicyEnforcement::kPolicyOptional) { + // We expected to load policy, but we don't have policy, so exit the + // session. + LOG(ERROR) << "Failed to load policy during synchronous restart " + << "- terminating session"; + if (fatal_error_callback_) + std::move(fatal_error_callback_).Run(); + return; } + + // Initialization has completed before our observer was registered + // so invoke our callback directly. + OnInitializationCompleted(service()); } else { + // Wait for the CloudPolicyStore to finish initializing. service()->AddObserver(this); } } @@ -188,9 +200,14 @@ if (!wildcard_username_.empty()) { wildcard_login_checker_.reset(new WildcardLoginChecker()); + // Safe to set a callback with an unretained pointer because the + // WildcardLoginChecker is owned by this object and won't invoke the + // callback after we destroy it. wildcard_login_checker_->StartWithAccessToken( access_token, - base::Bind(&OnWildcardCheckCompleted, wildcard_username_)); + base::BindOnce( + &UserCloudPolicyManagerChromeOS::OnWildcardCheckCompleted, + base::Unretained(this), wildcard_username_)); } if (service() && service()->IsInitializationComplete() && @@ -200,6 +217,24 @@ } } +void UserCloudPolicyManagerChromeOS::OnWildcardCheckCompleted( + const std::string& username, + WildcardLoginChecker::Result result) { + if (result == WildcardLoginChecker::RESULT_BLOCKED) { + LOG(ERROR) << "Online wildcard login check failed, terminating session."; + + // TODO(mnissler): This only removes the user pod from the login screen, but + // the cryptohome remains. This is because deleting the cryptohome for a + // logged-in session is not possible. Fix this either by delaying the + // cryptohome deletion operation or by getting rid of the in-session + // wildcard check. + user_manager::UserManager::Get()->RemoveUserFromList( + AccountId::FromUserEmail(username)); + if (fatal_error_callback_) + std::move(fatal_error_callback_).Run(); + } +} + bool UserCloudPolicyManagerChromeOS::IsClientRegistered() const { return client() && client()->is_registered(); } @@ -225,7 +260,7 @@ if (!CloudPolicyManager::IsInitializationComplete(domain)) return false; if (domain == POLICY_DOMAIN_CHROME) - return !waiting_for_initial_policy_fetch_; + return !waiting_for_policy_fetch_; return true; } @@ -239,29 +274,31 @@ time_init_completed_ - time_init_started_); // If the CloudPolicyClient isn't registered at this stage then it needs an - // OAuth token for the initial registration. + // OAuth token for the initial registration (there's no cached policy). // - // If |waiting_for_initial_policy_fetch_| is true then Profile initialization + // If |waiting_for_policy_fetch_| is true then Profile initialization // is blocking on the initial policy fetch, so the token must be fetched // immediately. In that case, the signin Profile is used to authenticate a // Gaia request to fetch a refresh token, and then the policy token is // fetched. // - // If |waiting_for_initial_policy_fetch_| is false then the - // UserCloudPolicyTokenForwarder service will eventually call + // If |waiting_for_policy_fetch_| is false (meaning this is a + // pre-existing session that doesn't have policy and we're just doing a + // background check to see if the user has become managed since last signin) + // then the UserCloudPolicyTokenForwarder service will eventually call // OnAccessTokenAvailable() once an access token is available. That call may // have already happened while waiting for initialization of the // CloudPolicyService, so in that case check if an access token is already // available. if (!client()->is_registered()) { - if (waiting_for_initial_policy_fetch_) { + if (waiting_for_policy_fetch_) { FetchPolicyOAuthToken(); } else if (!access_token_.empty()) { OnAccessTokenAvailable(access_token_); } } - if (!waiting_for_initial_policy_fetch_) { + if (!waiting_for_policy_fetch_) { // If this isn't blocking on a policy fetch then // CloudPolicyManager::OnStoreLoaded() already published the cached policy. // Start the refresh scheduler now, which will eventually refresh the @@ -274,15 +311,14 @@ void UserCloudPolicyManagerChromeOS::OnPolicyFetched( CloudPolicyClient* client) { // No action required. If we're blocked on a policy fetch, we'll learn about - // completion of it through OnInitialPolicyFetchComplete(), or through the - // CancelWaitForPolicyFetch() callback. + // completion of it through OnInitialPolicyFetchComplete(). } void UserCloudPolicyManagerChromeOS::OnRegistrationStateChanged( CloudPolicyClient* cloud_policy_client) { DCHECK_EQ(client(), cloud_policy_client); - if (waiting_for_initial_policy_fetch_) { + if (waiting_for_policy_fetch_) { time_client_registered_ = base::Time::Now(); if (!time_token_available_.is_null()) { UMA_HISTOGRAM_MEDIUM_TIMES( @@ -307,15 +343,19 @@ void UserCloudPolicyManagerChromeOS::OnClientError( CloudPolicyClient* cloud_policy_client) { DCHECK_EQ(client(), cloud_policy_client); - if (waiting_for_initial_policy_fetch_) { + if (waiting_for_policy_fetch_) { base::UmaHistogramSparse(kUMAInitialFetchClientError, cloud_policy_client->status()); } switch (client()->status()) { - case DM_STATUS_SUCCESS: case DM_STATUS_SERVICE_MANAGEMENT_NOT_SUPPORTED: // If management is not supported for this user, then a registration - // error is to be expected. + // error is to be expected - treat as a policy fetch success. Also + // mark this profile as not requiring policy. + SetPolicyRequired(false); + CancelWaitForPolicyFetch(true); + break; + case DM_STATUS_SUCCESS: CancelWaitForPolicyFetch(true); break; default: @@ -337,6 +377,14 @@ em::PolicyData const* const policy_data = cloud_policy_store->policy(); if (policy_data) { + // We have cached policy in the store, so update the various flags to + // reflect that we have policy. + SetPolicyRequired(true); + + // Policy was successfully loaded from disk, so it's OK if a subsequent + // server fetch fails. + enforcement_type_ = PolicyEnforcement::kPolicyOptional; + DCHECK(policy_data->has_username()); chromeos::AffiliationIDSet set_of_user_affiliation_ids( policy_data->user_affiliation_ids().begin(), @@ -347,6 +395,33 @@ } } +void UserCloudPolicyManagerChromeOS::SetPolicyRequired(bool policy_required) { + chromeos::ChromeUserManager* user_manager = + chromeos::ChromeUserManager::Get(); + user_manager::known_user::SetProfileRequiresPolicy( + account_id_, + policy_required + ? user_manager::known_user::ProfileRequiresPolicy::kPolicyRequired + : user_manager::known_user::ProfileRequiresPolicy::kNoPolicyRequired); + if (user_manager->IsCurrentUserNonCryptohomeDataEphemeral()) { + // For ephemeral users, we need to set a flag via session manager - this + // handles the case where the session restarts due to a crash (the restarted + // instance will know whether policy is required via this flag). This + // overwrites flags set by about://flags, but that's OK since we can't have + // any of those flags set at startup anyway for ephemeral sessions. + base::CommandLine command_line = + base::CommandLine(base::CommandLine::NO_PROGRAM); + command_line.AppendSwitchASCII(chromeos::switches::kProfileRequiresPolicy, + policy_required ? "true" : "false"); + base::CommandLine::StringVector flags; + flags.assign(command_line.argv().begin() + 1, command_line.argv().end()); + DCHECK_EQ(1u, flags.size()); + chromeos::DBusThreadManager::Get() + ->GetSessionManagerClient() + ->SetFlagsForUser(cryptohome::Identification(account_id_), flags); + } +} + void UserCloudPolicyManagerChromeOS::GetChromePolicy(PolicyMap* policy_map) { CloudPolicyManager::GetChromePolicy(policy_map); @@ -401,7 +476,7 @@ const GoogleServiceAuthError& error) { DCHECK(!client()->is_registered()); time_token_available_ = base::Time::Now(); - if (waiting_for_initial_policy_fetch_) { + if (waiting_for_policy_fetch_) { UMA_HISTOGRAM_MEDIUM_TIMES(kUMAInitialFetchDelayOAuth2Token, time_token_available_ - time_init_completed_); } @@ -441,36 +516,35 @@ CancelWaitForPolicyFetch(success); } -void UserCloudPolicyManagerChromeOS::OnBlockingFetchTimeout() { - DCHECK(waiting_for_initial_policy_fetch_); - LOG(WARNING) << "Timed out while waiting for the policy fetch. " +void UserCloudPolicyManagerChromeOS::OnPolicyRefreshTimeout() { + DCHECK(waiting_for_policy_fetch_); + LOG(WARNING) << "Timed out while waiting for the policy refresh. " << "The session will start with the cached policy."; CancelWaitForPolicyFetch(false); } void UserCloudPolicyManagerChromeOS::CancelWaitForPolicyFetch(bool success) { - if (!waiting_for_initial_policy_fetch_) + if (!waiting_for_policy_fetch_) return; - policy_fetch_timeout_.Stop(); + policy_refresh_timeout_.Stop(); // If there was an error, and we don't want to allow profile initialization - // to go forward after a failed policy fetch, then just return (profile - // initialization will not complete). - // TODO(atwilson): Add code to retry policy fetching. - if (!success && !initial_policy_fetch_may_fail_) { + // to go forward after a failed policy fetch, then trigger a fatal error. + if (!success && enforcement_type_ != PolicyEnforcement::kPolicyOptional) { LOG(ERROR) << "Policy fetch failed for the user. " "Aborting profile initialization"; // Need to exit the current user, because we've already started this user's // session. - chrome::AttemptUserExit(); + if (fatal_error_callback_) + std::move(fatal_error_callback_).Run(); return; } - waiting_for_initial_policy_fetch_ = false; + waiting_for_policy_fetch_ = false; CheckAndPublishPolicy(); - // Now that |waiting_for_initial_policy_fetch_| is guaranteed to be false, the + // Now that |waiting_for_policy_fetch_| is guaranteed to be false, the // scheduler can be started. StartRefreshSchedulerIfReady(); } @@ -479,7 +553,7 @@ if (core()->refresh_scheduler()) return; // Already started. - if (waiting_for_initial_policy_fetch_) + if (waiting_for_policy_fetch_) return; // Still waiting for the initial, blocking fetch. if (!service() || !local_state_)
diff --git a/chrome/browser/chromeos/policy/user_cloud_policy_manager_chromeos.h b/chrome/browser/chromeos/policy/user_cloud_policy_manager_chromeos.h index 8215244..9d32356 100644 --- a/chrome/browser/chromeos/policy/user_cloud_policy_manager_chromeos.h +++ b/chrome/browser/chromeos/policy/user_cloud_policy_manager_chromeos.h
@@ -8,6 +8,7 @@ #include <memory> #include <string> +#include "base/bind.h" #include "base/compiler_specific.h" #include "base/debug/stack_trace.h" #include "base/files/file_path.h" @@ -15,11 +16,13 @@ #include "base/memory/ref_counted.h" #include "base/time/time.h" #include "base/timer/timer.h" +#include "chrome/browser/chromeos/policy/wildcard_login_checker.h" #include "components/keyed_service/core/keyed_service.h" #include "components/policy/core/common/cloud/cloud_policy_client.h" #include "components/policy/core/common/cloud/cloud_policy_constants.h" #include "components/policy/core/common/cloud/cloud_policy_manager.h" #include "components/policy/core/common/cloud/cloud_policy_service.h" +#include "components/signin/core/account_id/account_id.h" class GoogleServiceAuthError; class PrefService; @@ -37,7 +40,6 @@ class CloudExternalDataManager; class DeviceManagementService; class PolicyOAuth2TokenFetcher; -class WildcardLoginChecker; // Implements logic for initializing user policy on Chrome OS. class UserCloudPolicyManagerChromeOS : public CloudPolicyManager, @@ -45,10 +47,44 @@ public CloudPolicyService::Observer, public KeyedService { public: - // If |initial_policy_fetch_timeout| is non-zero, IsInitializationComplete() - // is forced to false until either there has been a successful policy fetch - // from the server or |initial_policy_fetch_timeout| has expired. (The timeout - // may be set to TimeDelta::Max() to block permanently.) + // Enum describing what behavior we want to enforce here. + enum class PolicyEnforcement { + // No policy enforcement - it's OK to start the session even without a + // policy check because it has previously been established that this + // session is unmanaged. + kPolicyOptional, + + // This is a managed session so require a successful policy load before + // completing profile initialization. + kPolicyRequired, + + // It is unknown whether this session should be managed, so require a check + // with the policy server before initializing the profile. + kServerCheckRequired + }; + + // |enforcement_type| specifies what kind of policy state will be + // enforced by this object: + // + // * kPolicyOptional: The class will kick off a background policy fetch to + // detect whether the user has become managed since the last signin, but + // there's no enforcement (it's OK for the server request to fail, and the + // profile initialization is allowed to proceed immediately). + // + // * kServerCheckRequired: Profile initialization will be blocked + // (IsInitializationComplete() will return false) until we have made a + // successful call to DMServer to check for policy or loaded policy from + // cache. If this call is unsuccessful due to network/server errors, then + // |fatal_error_callback| is invoked to close the session. + // + // * kPolicyRequired: A background policy refresh will be initiated. If a + // non-zero |policy_refresh_timeout| is passed, then profile initialization + // will be blocked (IsInitializationComplete() will return false) until + // either the fetch completes or the timeout fires. |fatal_error_callback| + // will be invoked if the system could not load policy from either cache or + // the server. + // + // |account_id| is the AccountId associated with the user's session. // |task_runner| is the runner for policy refresh tasks. // |io_task_runner| is used for network IO. Currently this must be the IO // BrowserThread. @@ -56,7 +92,10 @@ std::unique_ptr<CloudPolicyStore> store, std::unique_ptr<CloudExternalDataManager> external_data_manager, const base::FilePath& component_policy_cache_path, - base::TimeDelta initial_policy_fetch_timeout, + PolicyEnforcement enforcement_type, + base::TimeDelta policy_refresh_timeout, + base::OnceClosure fatal_error_callback, + const AccountId& account_id, const scoped_refptr<base::SequencedTaskRunner>& task_runner, const scoped_refptr<base::SequencedTaskRunner>& io_task_runner); ~UserCloudPolicyManagerChromeOS() override; @@ -112,6 +151,12 @@ void GetChromePolicy(PolicyMap* policy_map) override; private: + // Sets the appropriate persistent flags to mark whether the current session + // requires policy. If |policy_required| is true, this ensures that future + // instances of this session will not start up unless a valid policy blob can + // be loaded. + void SetPolicyRequired(bool policy_required); + // Fetches a policy token using the refresh token if available, or the // authentication context of the signin context, and calls back // OnOAuth2PolicyTokenFetched when done. @@ -123,15 +168,20 @@ const GoogleServiceAuthError& error); // Completion handler for the explicit policy fetch triggered on startup in - // case |waiting_for_initial_policy_fetch_| is true. |success| is true if the + // case |waiting_for_policy_fetch_| is true. |success| is true if the // fetch was successful. void OnInitialPolicyFetchComplete(bool success); - // Called when |policy_fetch_timeout_| times out, to cancel the blocking wait - // for the initial policy fetch. - void OnBlockingFetchTimeout(); + // Called when |policy_refresh_timeout_| times out, to cancel the blocking + // wait for the policy refresh. + void OnPolicyRefreshTimeout(); - // Cancels waiting for the initial policy fetch and flags the + // Called when a wildcard check has completed, to allow us to exit the session + // if required. + void OnWildcardCheckCompleted(const std::string& username, + WildcardLoginChecker::Result result); + + // Cancels waiting for the initial policy fetch/refresh and flags the // ConfigurationPolicyProvider ready (assuming all other initialization tasks // have completed). Pass |true| if policy fetch was successful (either because // policy was successfully fetched, or if DMServer has notified us that the @@ -154,16 +204,15 @@ // Whether we're waiting for a policy fetch to complete before reporting // IsInitializationComplete(). - bool waiting_for_initial_policy_fetch_; + bool waiting_for_policy_fetch_; - // Whether the user session is continued in case of failure of initial policy - // fetch. - bool initial_policy_fetch_may_fail_; + // What kind of enforcement we need to implement. + PolicyEnforcement enforcement_type_; - // A timer that puts a hard limit on the maximum time to wait for the initial - // policy fetch. - base::Timer policy_fetch_timeout_{false /* retain_user_task */, - false /* is_repeating */}; + // A timer that puts a hard limit on the maximum time to wait for a policy + // refresh. + base::Timer policy_refresh_timeout_{false /* retain_user_task */, + false /* is_repeating */}; // The pref service to pass to the refresh scheduler on initialization. PrefService* local_state_; @@ -190,6 +239,13 @@ // are fixed. base::debug::StackTrace connect_callstack_; + // The AccountId associated with the user whose policy is being loaded. + AccountId account_id_; + + // The callback to invoke if the user session should be shutdown. This is + // injected in the constructor to make it easier to write tests. + base::OnceClosure fatal_error_callback_; + DISALLOW_COPY_AND_ASSIGN(UserCloudPolicyManagerChromeOS); };
diff --git a/chrome/browser/chromeos/policy/user_cloud_policy_manager_chromeos_browsertest.cc b/chrome/browser/chromeos/policy/user_cloud_policy_manager_chromeos_browsertest.cc index 13d156f5..6f1b9eb 100644 --- a/chrome/browser/chromeos/policy/user_cloud_policy_manager_chromeos_browsertest.cc +++ b/chrome/browser/chromeos/policy/user_cloud_policy_manager_chromeos_browsertest.cc
@@ -11,6 +11,7 @@ #include "base/values.h" #include "chrome/browser/chrome_notification_types.h" #include "chrome/browser/chromeos/login/ui/login_display_webui.h" +#include "chrome/browser/chromeos/login/users/chrome_user_manager.h" #include "chrome/browser/chromeos/policy/login_policy_test_base.h" #include "chrome/browser/chromeos/policy/user_policy_test_helper.h" #include "chrome/browser/prefs/session_startup_pref.h" @@ -18,6 +19,7 @@ #include "chrome/browser/ui/browser_list.h" #include "chrome/browser/ui/tabs/tab_strip_model.h" #include "components/policy/policy_constants.h" +#include "components/user_manager/known_user.h" #include "components/user_manager/user.h" #include "components/user_manager/user_manager.h" #include "content/public/browser/notification_observer.h" @@ -26,6 +28,10 @@ #include "testing/gtest/include/gtest/gtest.h" namespace { +// The Gaia ID supplied by FakeGaia for our mocked-out signin. +const char kTestGaiaId[] = "12345"; +const char kConsumerAccount[] = "test_user@gmail.com"; + // Helper class that counts the number of notifications of the specified // type that have been received. class CountNotificationObserver : public content::NotificationObserver { @@ -77,6 +83,11 @@ IN_PROC_BROWSER_TEST_F(UserCloudPolicyManagerTest, StartSession) { const char* const kStartupURLs[] = {"chrome://policy", "chrome://about"}; + // User hasn't signed in yet, so shouldn't know if the user requires policy. + AccountId account_id = + AccountId::FromUserEmailGaiaId(kAccountId, kTestGaiaId); + EXPECT_EQ(user_manager::known_user::ProfileRequiresPolicy::kUnknown, + user_manager::known_user::GetProfileRequiresPolicy(account_id)); SkipToLoginScreen(); LogIn(kAccountId, kAccountPassword); @@ -101,11 +112,14 @@ EXPECT_EQ(GURL(kStartupURLs[i]), tabs->GetWebContentsAt(i)->GetVisibleURL()); } + EXPECT_TRUE(user_manager->GetActiveUser()->profile_ever_initialized()); + + // User should be marked as requiring policy. + EXPECT_EQ(user_manager::known_user::ProfileRequiresPolicy::kPolicyRequired, + user_manager::known_user::GetProfileRequiresPolicy(account_id)); } -// Test disabled. See crbug.com/600617. -IN_PROC_BROWSER_TEST_F(UserCloudPolicyManagerTest, - DISABLED_ErrorLoadingPolicy) { +IN_PROC_BROWSER_TEST_F(UserCloudPolicyManagerTest, ErrorLoadingPolicy) { // Delete the policy file - this will cause a 500 error on policy requests. user_policy_helper()->DeletePolicyFile(); SkipToLoginScreen(); @@ -117,12 +131,106 @@ // Should not receive a SESSION_STARTED notification. ASSERT_EQ(0, observer.notification_count()); - // User should not be marked as having a valid OAuth token. That way, if we - // try to load the user in the future, we will attempt to load policy again. + // User should not be marked as having completed profile initialization. const user_manager::UserManager* user_manager = user_manager::UserManager::Get(); - EXPECT_NE(user_manager::User::OAUTH2_TOKEN_STATUS_VALID, + EXPECT_FALSE(user_manager->GetActiveUser()->profile_ever_initialized()); + // User should be marked as not knowing if policy is required yet. + AccountId account_id = + AccountId::FromUserEmailGaiaId(kAccountId, kTestGaiaId); + EXPECT_EQ(user_manager::known_user::ProfileRequiresPolicy::kUnknown, + user_manager::known_user::GetProfileRequiresPolicy(account_id)); +} + +IN_PROC_BROWSER_TEST_F(UserCloudPolicyManagerTest, + ErrorLoadingPolicyForUnmanagedUser) { + // Mark user as not needing policy - errors loading policy should be + // ignored (unlike previous ErrorLoadingPolicy test). + AccountId account_id = + AccountId::FromUserEmailGaiaId(kAccountId, kTestGaiaId); + user_manager::known_user::SetProfileRequiresPolicy( + account_id, + user_manager::known_user::ProfileRequiresPolicy::kNoPolicyRequired); + + // Delete the policy file - this will cause a 500 error on policy requests. + user_policy_helper()->DeletePolicyFile(); + SkipToLoginScreen(); + LogIn(kAccountId, kAccountPassword); + + // User should be marked as having a valid OAuth token. + const user_manager::UserManager* const user_manager = + user_manager::UserManager::Get(); + EXPECT_EQ(user_manager::User::OAUTH2_TOKEN_STATUS_VALID, user_manager->GetActiveUser()->oauth_token_status()); + + // User should be marked as having completed profile initialization. + EXPECT_TRUE(user_manager->GetActiveUser()->profile_ever_initialized()); + + // User should still be marked as not needing policy + EXPECT_EQ(user_manager::known_user::ProfileRequiresPolicy::kNoPolicyRequired, + user_manager::known_user::GetProfileRequiresPolicy(account_id)); +} + +IN_PROC_BROWSER_TEST_F(UserCloudPolicyManagerTest, MigrateForExistingUser) { + // Mark user as already having initialized the profile - this should allow + // the policy code to ignore errors (because we presume we already have a + // valid cache). We can remove this test when we fix crbug.com/731726 and + // remove the associated migration code from UserPolicyManagerFactoryChromeOS. + AccountId account_id = + AccountId::FromUserEmailGaiaId(kAccountId, kTestGaiaId); + chromeos::ChromeUserManager* user_manager = + chromeos::ChromeUserManager::Get(); + user_manager::User* user = + user_manager::User::CreateRegularUserForTesting(account_id); + user->set_profile_ever_initialized(true); + user_manager->AddUserRecordForTesting(user); + + EXPECT_EQ(user_manager::known_user::ProfileRequiresPolicy::kUnknown, + user_manager::known_user::GetProfileRequiresPolicy(account_id)); + + user_manager::known_user::SetProfileEverInitialized(account_id, true); + EXPECT_TRUE(user_manager::known_user::WasProfileEverInitialized(account_id)); + + // Delete the policy file - this will cause a 500 error on policy requests. + user_policy_helper()->DeletePolicyFile(); + SkipToLoginScreen(); + LogIn(kAccountId, kAccountPassword); + + // User should be marked as having a valid OAuth token. + EXPECT_EQ(user_manager::User::OAUTH2_TOKEN_STATUS_VALID, + user_manager->GetActiveUser()->oauth_token_status()); + + // User should still be marked as having completed profile initialization. + EXPECT_TRUE(user_manager->GetActiveUser()->profile_ever_initialized()); + + // Policy status should still be unknown since we haven't managed to load + // policy from disk nor have we been able to talk to the server. + EXPECT_EQ(user_manager::known_user::ProfileRequiresPolicy::kUnknown, + user_manager::known_user::GetProfileRequiresPolicy(account_id)); +} + +IN_PROC_BROWSER_TEST_F(UserCloudPolicyManagerTest, NoPolicyForConsumer) { + // If a user signs in with a known non-enterprise account there should be no + // policy. + AccountId account_id = + AccountId::FromUserEmailGaiaId(kConsumerAccount, kTestGaiaId); + EXPECT_EQ(user_manager::known_user::ProfileRequiresPolicy::kUnknown, + user_manager::known_user::GetProfileRequiresPolicy(account_id)); + + SkipToLoginScreen(); + LogIn(kConsumerAccount, kAccountPassword); + + // User should be marked as having a valid OAuth token. + const user_manager::UserManager* const user_manager = + user_manager::UserManager::Get(); + EXPECT_EQ(user_manager::User::OAUTH2_TOKEN_STATUS_VALID, + user_manager->GetActiveUser()->oauth_token_status()); + + EXPECT_TRUE(user_manager->GetActiveUser()->profile_ever_initialized()); + + // User should be marked as not requiring policy. + EXPECT_EQ(user_manager::known_user::ProfileRequiresPolicy::kNoPolicyRequired, + user_manager::known_user::GetProfileRequiresPolicy(account_id)); } } // namespace policy
diff --git a/chrome/browser/chromeos/policy/user_cloud_policy_manager_chromeos_unittest.cc b/chrome/browser/chromeos/policy/user_cloud_policy_manager_chromeos_unittest.cc index f92930d..86d4f69f 100644 --- a/chrome/browser/chromeos/policy/user_cloud_policy_manager_chromeos_unittest.cc +++ b/chrome/browser/chromeos/policy/user_cloud_policy_manager_chromeos_unittest.cc
@@ -67,8 +67,19 @@ using testing::Mock; using testing::_; +namespace { + +enum PolicyRequired { POLICY_NOT_REQUIRED, POLICY_REQUIRED }; + +} // namespace + namespace policy { +using PolicyEnforcement = UserCloudPolicyManagerChromeOS::PolicyEnforcement; + +const char kAccountId[] = "user@example.com"; +const char kTestGaiaId[] = "12345"; + const char kOAuthCodeCookie[] = "oauth_code=1234; Secure; HttpOnly"; const char kOAuth2TokenPairData[] = @@ -88,17 +99,16 @@ public: // Note: This method has to be public, so that a pointer to it may be obtained // in the test. - void MakeManagerWithPreloadedStore(int fetch_timeout_seconds) { + void MakeManagerWithPreloadedStore(const base::TimeDelta& fetch_timeout) { std::unique_ptr<MockCloudPolicyStore> store = std::make_unique<MockCloudPolicyStore>(); store->policy_.reset(new em::PolicyData(policy_data_)); store->policy_map_.CopyFrom(policy_map_); store->NotifyStoreLoaded(); - CreateManager(std::move(store), fetch_timeout_seconds); - // The manager gets already initialized by this point if the store is - // initialized and there is no blocking for policy fetch. - EXPECT_NE(fetch_timeout_seconds != 0, - manager_->IsInitializationComplete(POLICY_DOMAIN_CHROME)); + CreateManager(std::move(store), fetch_timeout, + PolicyEnforcement::kPolicyRequired); + // The manager should already be initialized by this point. + EXPECT_TRUE(manager_->IsInitializationComplete(POLICY_DOMAIN_CHROME)); InitAndConnectManager(); EXPECT_TRUE(manager_->core()->service()->IsInitializationComplete()); } @@ -164,9 +174,15 @@ EXPECT_CALL(device_management_service_, StartJob(_, _, _, _, _, _)) .Times(AnyNumber()); + AccountId account_id = + AccountId::FromUserEmailGaiaId(kAccountId, kTestGaiaId); + user_manager_->AddUser(account_id); + user_manager_->SwitchActiveUser(account_id); + ASSERT_TRUE(user_manager_->GetActiveUser()); } void TearDown() override { + EXPECT_EQ(fatal_error_expected_, fatal_error_encountered_); if (token_forwarder_) token_forwarder_->Shutdown(); if (manager_) { @@ -178,11 +194,12 @@ profile_manager_->DeleteTestingProfile(chrome::kInitialProfile); } - void MakeManagerWithEmptyStore(int fetch_timeout) { + void MakeManagerWithEmptyStore(const base::TimeDelta& fetch_timeout, + PolicyEnforcement enforcement_type) { std::unique_ptr<MockCloudPolicyStore> store = std::make_unique<MockCloudPolicyStore>(); EXPECT_CALL(*store, Load()); - CreateManager(std::move(store), fetch_timeout); + CreateManager(std::move(store), fetch_timeout, enforcement_type); EXPECT_FALSE(manager_->IsInitializationComplete(POLICY_DOMAIN_CHROME)); InitAndConnectManager(); Mock::VerifyAndClearExpectations(store_); @@ -277,12 +294,12 @@ // Expects a policy fetch request to be issued after invoking |trigger_fetch|. // This method replies to that fetch request and verifies that the manager // handled the response. - void FetchPolicy(const base::Closure& trigger_fetch) { + void FetchPolicy(base::OnceClosure trigger_fetch, bool timeout) { MockDeviceManagementJob* policy_request = NULL; EXPECT_CALL(device_management_service_, CreateJob(DeviceManagementRequestJob::TYPE_POLICY_FETCH, _)) .WillOnce(device_management_service_.CreateAsyncJob(&policy_request)); - trigger_fetch.Run(); + std::move(trigger_fetch).Run(); ASSERT_TRUE(policy_request); EXPECT_TRUE(manager_->core()->service()->IsInitializationComplete()); EXPECT_TRUE(manager_->core()->client()->is_registered()); @@ -291,16 +308,19 @@ EXPECT_CALL(device_management_service_, StartJob(_, _, _, _, _, _)) .Times(AnyNumber()); - // Send the initial policy back. This completes the initialization flow. - EXPECT_CALL(*store_, Store(_)); - policy_request->SendResponse(DM_STATUS_SUCCESS, policy_blob_); - Mock::VerifyAndClearExpectations(store_); - - // Notifying that the store is has cached the fetched policy completes the - // process, and initializes the manager. - EXPECT_CALL(observer_, OnUpdatePolicy(manager_.get())); - store_->policy_map_.CopyFrom(policy_map_); - store_->NotifyStoreLoaded(); + if (timeout) { + manager_->ForceTimeoutForTest(); + } else { + // Send the initial policy back. This completes the initialization flow. + EXPECT_CALL(*store_, Store(_)); + policy_request->SendResponse(DM_STATUS_SUCCESS, policy_blob_); + Mock::VerifyAndClearExpectations(store_); + // Notifying that the store has cached the fetched policy completes the + // process, and initializes the manager. + EXPECT_CALL(observer_, OnUpdatePolicy(manager_.get())); + store_->policy_map_.CopyFrom(policy_map_); + store_->NotifyStoreLoaded(); + } EXPECT_TRUE(manager_->IsInitializationComplete(POLICY_DOMAIN_CHROME)); Mock::VerifyAndClearExpectations(&observer_); EXPECT_TRUE(manager_->policies().Equals(expected_bundle_)); @@ -336,20 +356,27 @@ chromeos::FakeChromeUserManager* user_manager_; user_manager::ScopedUserManager user_manager_enabler_; + // This is automatically checked in TearDown() to ensure that we get a + // fatal error iff |fatal_error_expected_| is true. + bool fatal_error_expected_ = false; - private: void CreateManager(std::unique_ptr<MockCloudPolicyStore> store, - int fetch_timeout_seconds) { + const base::TimeDelta& fetch_timeout, + PolicyEnforcement enforcement_type) { store_ = store.get(); external_data_manager_ = new MockCloudExternalDataManager; external_data_manager_->SetPolicyStore(store_); manager_.reset(new UserCloudPolicyManagerChromeOS( std::move(store), base::WrapUnique<MockCloudExternalDataManager>(external_data_manager_), - base::FilePath(), base::TimeDelta::FromSeconds(fetch_timeout_seconds), - task_runner_, task_runner_)); + base::FilePath(), enforcement_type, fetch_timeout, + base::BindOnce( + &UserCloudPolicyManagerChromeOSTest::OnFatalErrorEncountered, + base::Unretained(this)), + user_manager_->GetActiveUser()->GetAccountId(), task_runner_, + task_runner_)); manager_->AddObserver(&observer_); - should_create_token_forwarder_ = (fetch_timeout_seconds == 0); + should_create_token_forwarder_ = fetch_timeout.is_zero(); } void InitAndConnectManager() { @@ -371,7 +398,12 @@ } } + private: + // Invoked when a fatal error is encountered. + void OnFatalErrorEncountered() { fatal_error_encountered_ = true; } + bool should_create_token_forwarder_ = false; + bool fatal_error_encountered_ = false; DISALLOW_COPY_AND_ASSIGN(UserCloudPolicyManagerChromeOSTest); }; @@ -379,7 +411,8 @@ TEST_F(UserCloudPolicyManagerChromeOSTest, BlockingFirstFetch) { // Tests the initialization of a manager whose Profile is waiting for the // initial fetch, when the policy cache is empty. - ASSERT_NO_FATAL_FAILURE(MakeManagerWithEmptyStore(1000)); + ASSERT_NO_FATAL_FAILURE(MakeManagerWithEmptyStore( + base::TimeDelta(), PolicyEnforcement::kServerCheckRequired)); // Initialize the CloudPolicyService without any stored data. EXPECT_FALSE(manager_->core()->service()->IsInitializationComplete()); @@ -394,42 +427,46 @@ // Reply with a valid registration response. This triggers the initial policy // fetch. - FetchPolicy(base::Bind(&MockDeviceManagementJob::SendResponse, - base::Unretained(register_request), - DM_STATUS_SUCCESS, register_blob_)); + FetchPolicy(base::BindOnce(&MockDeviceManagementJob::SendResponse, + base::Unretained(register_request), + DM_STATUS_SUCCESS, register_blob_), + false); } TEST_F(UserCloudPolicyManagerChromeOSTest, BlockingRefreshFetch) { // Tests the initialization of a manager whose Profile is waiting for the - // initial fetch, when a previously cached policy and DMToken already exist. - ASSERT_NO_FATAL_FAILURE(MakeManagerWithEmptyStore(1000)); + // refresh fetch, when a previously cached policy and DMToken already exist. + ASSERT_NO_FATAL_FAILURE(MakeManagerWithEmptyStore( + base::TimeDelta::FromSeconds(1000), PolicyEnforcement::kPolicyRequired)); // Set the initially cached data and initialize the CloudPolicyService. // The initial policy fetch is issued using the cached DMToken. store_->policy_.reset(new em::PolicyData(policy_data_)); - FetchPolicy(base::Bind(&MockCloudPolicyStore::NotifyStoreLoaded, - base::Unretained(store_))); + FetchPolicy(base::BindOnce(&MockCloudPolicyStore::NotifyStoreLoaded, + base::Unretained(store_)), + false); } -TEST_F(UserCloudPolicyManagerChromeOSTest, - BlockingRefreshFetchWithPreloadedStore) { - // Tests the initialization of a manager whose Profile is waiting for the - // initial fetch, when a previously cached policy and DMToken are already - // loaded before the manager is constructed. The manager is still - // uninitialized after the Init() call, despite that the store is already - // initialized. The manager becomes initialized only after the policy is - // fetched, and this is triggered from Connect() with the client registration - // performed by cloud policy service (as opposed to the registration normally - // performed by the manager). - FetchPolicy(base::Bind( - &UserCloudPolicyManagerChromeOSTest::MakeManagerWithPreloadedStore, - base::Unretained(this), 1000)); +TEST_F(UserCloudPolicyManagerChromeOSTest, SynchronousLoadWithEmptyStore) { + // Tests the initialization of a manager who requires policy, but who + // has no policy stored on disk. The manager should abort and exit the + // session. + fatal_error_expected_ = true; + std::unique_ptr<MockCloudPolicyStore> store = + base::MakeUnique<MockCloudPolicyStore>(); + // Tell the store it couldn't load data. + store->NotifyStoreError(); + CreateManager(std::move(store), base::TimeDelta(), + PolicyEnforcement::kPolicyRequired); + InitAndConnectManager(); + EXPECT_TRUE(manager_->core()->service()->IsInitializationComplete()); } TEST_F(UserCloudPolicyManagerChromeOSTest, BlockingFetchStoreError) { // Tests the initialization of a manager whose Profile is waiting for the // initial fetch, when the initial store load fails. - ASSERT_NO_FATAL_FAILURE(MakeManagerWithEmptyStore(1000)); + ASSERT_NO_FATAL_FAILURE(MakeManagerWithEmptyStore( + base::TimeDelta(), PolicyEnforcement::kServerCheckRequired)); // Initialize the CloudPolicyService without any stored data. EXPECT_FALSE(manager_->core()->service()->IsInitializationComplete()); @@ -444,15 +481,19 @@ // Reply with a valid registration response. This triggers the initial policy // fetch. - FetchPolicy(base::Bind(&MockDeviceManagementJob::SendResponse, - base::Unretained(register_request), - DM_STATUS_SUCCESS, register_blob_)); + FetchPolicy(base::BindOnce(&MockDeviceManagementJob::SendResponse, + base::Unretained(register_request), + DM_STATUS_SUCCESS, register_blob_), + false); } TEST_F(UserCloudPolicyManagerChromeOSTest, BlockingFetchOAuthError) { // Tests the initialization of a manager whose Profile is waiting for the - // initial fetch, when the OAuth2 token fetch fails. - ASSERT_NO_FATAL_FAILURE(MakeManagerWithEmptyStore(1000)); + // initial fetch, when the OAuth2 token fetch fails. This should result in a + // fatal error. + fatal_error_expected_ = true; + ASSERT_NO_FATAL_FAILURE(MakeManagerWithEmptyStore( + base::TimeDelta(), PolicyEnforcement::kServerCheckRequired)); // Initialize the CloudPolicyService without any stored data. EXPECT_FALSE(manager_->core()->service()->IsInitializationComplete()); @@ -460,10 +501,6 @@ EXPECT_TRUE(manager_->core()->service()->IsInitializationComplete()); EXPECT_FALSE(manager_->core()->client()->is_registered()); - // This starts the OAuth2 policy token fetcher using the signin Profile. - // The manager will initialize with no policy after the token fetcher fails. - EXPECT_CALL(observer_, OnUpdatePolicy(manager_.get())); - // The PolicyOAuth2TokenFetcher posts delayed retries on some errors. This // data will make it fail immediately. net::TestURLFetcher* fetcher = PrepareOAuthFetcher( @@ -473,7 +510,8 @@ fetcher->SetResponseString("Error=BadAuthentication"); EXPECT_FALSE(manager_->IsInitializationComplete(POLICY_DOMAIN_CHROME)); fetcher->delegate()->OnURLFetchComplete(fetcher); - EXPECT_TRUE(manager_->IsInitializationComplete(POLICY_DOMAIN_CHROME)); + // Server check failed, so profile should not be initialized. + EXPECT_FALSE(manager_->IsInitializationComplete(POLICY_DOMAIN_CHROME)); EXPECT_TRUE(PolicyBundle().Equals(manager_->policies())); Mock::VerifyAndClearExpectations(&observer_); } @@ -481,7 +519,9 @@ TEST_F(UserCloudPolicyManagerChromeOSTest, BlockingFetchRegisterError) { // Tests the initialization of a manager whose Profile is waiting for the // initial fetch, when the device management registration fails. - ASSERT_NO_FATAL_FAILURE(MakeManagerWithEmptyStore(1000)); + fatal_error_expected_ = true; + ASSERT_NO_FATAL_FAILURE(MakeManagerWithEmptyStore( + base::TimeDelta(), PolicyEnforcement::kServerCheckRequired)); // Initialize the CloudPolicyService without any stored data. EXPECT_FALSE(manager_->core()->service()->IsInitializationComplete()); @@ -496,10 +536,10 @@ // Now make it fail. EXPECT_FALSE(manager_->IsInitializationComplete(POLICY_DOMAIN_CHROME)); - EXPECT_CALL(observer_, OnUpdatePolicy(manager_.get())); + EXPECT_CALL(observer_, OnUpdatePolicy(manager_.get())).Times(0); register_request->SendResponse(DM_STATUS_TEMPORARY_UNAVAILABLE, em::DeviceManagementResponse()); - EXPECT_TRUE(manager_->IsInitializationComplete(POLICY_DOMAIN_CHROME)); + EXPECT_FALSE(manager_->IsInitializationComplete(POLICY_DOMAIN_CHROME)); EXPECT_TRUE(PolicyBundle().Equals(manager_->policies())); Mock::VerifyAndClearExpectations(&observer_); } @@ -507,7 +547,9 @@ TEST_F(UserCloudPolicyManagerChromeOSTest, BlockingFetchPolicyFetchError) { // Tests the initialization of a manager whose Profile is waiting for the // initial fetch, when the policy fetch request fails. - ASSERT_NO_FATAL_FAILURE(MakeManagerWithEmptyStore(1000)); + fatal_error_expected_ = true; + ASSERT_NO_FATAL_FAILURE(MakeManagerWithEmptyStore( + base::TimeDelta(), PolicyEnforcement::kServerCheckRequired)); // Initialize the CloudPolicyService without any stored data. EXPECT_FALSE(manager_->core()->service()->IsInitializationComplete()); @@ -536,17 +578,24 @@ // RefreshPolicies callback, and another from the OnClientError callback. // A single notification suffices for this edge case, but this behavior is // also correct and makes the implementation simpler. - EXPECT_CALL(observer_, OnUpdatePolicy(manager_.get())).Times(AtLeast(1)); + EXPECT_CALL(observer_, OnUpdatePolicy(manager_.get())).Times(0); EXPECT_FALSE(manager_->IsInitializationComplete(POLICY_DOMAIN_CHROME)); policy_request->SendResponse(DM_STATUS_TEMPORARY_UNAVAILABLE, em::DeviceManagementResponse()); Mock::VerifyAndClearExpectations(&observer_); - EXPECT_TRUE(manager_->IsInitializationComplete(POLICY_DOMAIN_CHROME)); + EXPECT_FALSE(manager_->IsInitializationComplete(POLICY_DOMAIN_CHROME)); EXPECT_TRUE(PolicyBundle().Equals(manager_->policies())); } -TEST_F(UserCloudPolicyManagerChromeOSTest, BlockingFetchTimeout) { - ASSERT_NO_FATAL_FAILURE(MakeManagerWithEmptyStore(1000)); +TEST_F(UserCloudPolicyManagerChromeOSTest, + NoCacheButPolicyExpectedRegistrationError) { + // Tests the case where we have no local policy and the policy fetch + // request fails, but we think we should have policy - this covers the + // situation where local policy cache is lost due to disk corruption and + // we can't access the server. + fatal_error_expected_ = true; + ASSERT_NO_FATAL_FAILURE(MakeManagerWithEmptyStore( + base::TimeDelta::Max(), PolicyEnforcement::kPolicyRequired)); // Initialize the CloudPolicyService without any stored data. EXPECT_FALSE(manager_->core()->service()->IsInitializationComplete()); @@ -554,22 +603,71 @@ EXPECT_TRUE(manager_->core()->service()->IsInitializationComplete()); EXPECT_FALSE(manager_->core()->client()->is_registered()); - // Triggering the timeout should invoke our callback. - EXPECT_CALL(observer_, OnUpdatePolicy(manager_.get())).Times(AtLeast(1)); + // This starts the OAuth2 policy token fetcher using the signin Profile. + // The manager will then issue the registration request. + MockDeviceManagementJob* register_request = IssueOAuthToken(false); + ASSERT_TRUE(register_request); + + // Make the registration attempt fail. + register_request->SendResponse(DM_STATUS_TEMPORARY_UNAVAILABLE, + register_blob_); + Mock::VerifyAndClearExpectations(&device_management_service_); + EXPECT_TRUE(manager_->core()->service()->IsInitializationComplete()); + EXPECT_FALSE(manager_->core()->client()->is_registered()); +} + +TEST_F(UserCloudPolicyManagerChromeOSTest, NoCacheButPolicyExpectedFetchError) { + // Tests the case where we have no local policy and the policy fetch + // request fails, but we think we should have policy - this covers the + // situation where local policy cache is lost due to disk corruption and + // we can't access the server. + fatal_error_expected_ = true; + ASSERT_NO_FATAL_FAILURE(MakeManagerWithEmptyStore( + base::TimeDelta::Max(), PolicyEnforcement::kPolicyRequired)); + + // Initialize the CloudPolicyService without any stored data. + EXPECT_FALSE(manager_->core()->service()->IsInitializationComplete()); + store_->NotifyStoreLoaded(); + EXPECT_TRUE(manager_->core()->service()->IsInitializationComplete()); + EXPECT_FALSE(manager_->core()->client()->is_registered()); + + // This starts the OAuth2 policy token fetcher using the signin Profile. + // The manager will then issue the registration request. + MockDeviceManagementJob* register_request = IssueOAuthToken(false); + ASSERT_TRUE(register_request); + + // Reply with a valid registration response. This triggers the initial policy + // fetch. + MockDeviceManagementJob* policy_request = NULL; + EXPECT_CALL(device_management_service_, + CreateJob(DeviceManagementRequestJob::TYPE_POLICY_FETCH, _)) + .WillOnce(device_management_service_.CreateAsyncJob(&policy_request)); + register_request->SendResponse(DM_STATUS_SUCCESS, register_blob_); + Mock::VerifyAndClearExpectations(&device_management_service_); + ASSERT_TRUE(policy_request); + EXPECT_TRUE(manager_->core()->service()->IsInitializationComplete()); + EXPECT_TRUE(manager_->core()->client()->is_registered()); + + // Make the policy fetch fail. The observer gets 2 notifications: one from the + // RefreshPolicies callback, and another from the OnClientError callback. + // A single notification suffices for this edge case, but this behavior is + // also correct and makes the implementation simpler. EXPECT_FALSE(manager_->IsInitializationComplete(POLICY_DOMAIN_CHROME)); - manager_->ForceTimeoutForTest(); + policy_request->SendResponse(DM_STATUS_TEMPORARY_UNAVAILABLE, + em::DeviceManagementResponse()); Mock::VerifyAndClearExpectations(&observer_); - EXPECT_TRUE(manager_->IsInitializationComplete(POLICY_DOMAIN_CHROME)); + EXPECT_FALSE(manager_->IsInitializationComplete(POLICY_DOMAIN_CHROME)); EXPECT_TRUE(PolicyBundle().Equals(manager_->policies())); } TEST_F(UserCloudPolicyManagerChromeOSTest, NonBlockingFirstFetch) { // Tests the first policy fetch request by a Profile that isn't managed. - ASSERT_NO_FATAL_FAILURE(MakeManagerWithEmptyStore(0)); + ASSERT_NO_FATAL_FAILURE(MakeManagerWithEmptyStore( + base::TimeDelta(), PolicyEnforcement::kPolicyOptional)); // Initialize the CloudPolicyService without any stored data. Since the // manager is not waiting for the initial fetch, it will become initialized - // once the store is ready. + // once the store is loaded. EXPECT_FALSE(manager_->core()->service()->IsInitializationComplete()); EXPECT_FALSE(manager_->IsInitializationComplete(POLICY_DOMAIN_CHROME)); EXPECT_CALL(observer_, OnUpdatePolicy(manager_.get())); @@ -605,13 +703,16 @@ // The refresh scheduler takes care of the initial fetch for unmanaged users. // Running the task runner issues the initial fetch. FetchPolicy( - base::Bind(&base::TestSimpleTaskRunner::RunUntilIdle, task_runner_)); + base::BindOnce(&base::TestSimpleTaskRunner::RunUntilIdle, task_runner_), + false); } -TEST_F(UserCloudPolicyManagerChromeOSTest, NonBlockingRefreshFetch) { - // Tests a non-blocking initial policy fetch for a Profile that already has - // a cached DMToken. - ASSERT_NO_FATAL_FAILURE(MakeManagerWithEmptyStore(0)); +TEST_F(UserCloudPolicyManagerChromeOSTest, BlockingRefreshFetchWithTimeout) { + // Tests the case where a profile has policy, but the refresh policy fetch + // fails (times out) - ensures that we don't mark the profile as initialized + // until after the timeout. + ASSERT_NO_FATAL_FAILURE(MakeManagerWithEmptyStore( + base::TimeDelta::FromSeconds(1000), PolicyEnforcement::kPolicyRequired)); // Set the initially cached data and initialize the CloudPolicyService. // The initial policy fetch is issued using the cached DMToken. @@ -619,25 +720,22 @@ EXPECT_FALSE(manager_->IsInitializationComplete(POLICY_DOMAIN_CHROME)); EXPECT_CALL(observer_, OnUpdatePolicy(manager_.get())); store_->policy_.reset(new em::PolicyData(policy_data_)); - store_->NotifyStoreLoaded(); - Mock::VerifyAndClearExpectations(&observer_); - EXPECT_TRUE(manager_->core()->service()->IsInitializationComplete()); - EXPECT_TRUE(manager_->IsInitializationComplete(POLICY_DOMAIN_CHROME)); - EXPECT_TRUE(manager_->core()->client()->is_registered()); + store_->policy_map_.CopyFrom(policy_map_); - // The refresh scheduler takes care of the initial fetch for unmanaged users. - // Running the task runner issues the initial fetch. - FetchPolicy( - base::Bind(&base::TestSimpleTaskRunner::RunUntilIdle, task_runner_)); + // Mock out the initial policy fetch and have it trigger a timeout. + FetchPolicy(base::BindOnce(&MockCloudPolicyStore::NotifyStoreLoaded, + base::Unretained(store_)), + true); + Mock::VerifyAndClearExpectations(&observer_); } -TEST_F(UserCloudPolicyManagerChromeOSTest, - NonBlockingRefreshFetchWithPreloadedStore) { +TEST_F(UserCloudPolicyManagerChromeOSTest, SynchronousLoadWithPreloadedStore) { // Tests the initialization of a manager with non-blocking initial policy // fetch, when a previously cached policy and DMToken are already loaded - // before the manager is constructed. The manager gets initialized straight - // away after the construction. - MakeManagerWithPreloadedStore(0); + // before the manager is constructed (this simulates synchronously + // initializing a profile during a crash restart). The manager gets + // initialized straight away after the construction. + MakeManagerWithPreloadedStore(base::TimeDelta()); EXPECT_TRUE(manager_->policies().Equals(expected_bundle_)); }
diff --git a/chrome/browser/chromeos/policy/user_policy_manager_factory_chromeos.cc b/chrome/browser/chromeos/policy/user_policy_manager_factory_chromeos.cc index 8bdd116c..1375a74 100644 --- a/chrome/browser/chromeos/policy/user_policy_manager_factory_chromeos.cc +++ b/chrome/browser/chromeos/policy/user_policy_manager_factory_chromeos.cc
@@ -11,6 +11,7 @@ #include "base/files/file_path.h" #include "base/logging.h" #include "base/memory/ref_counted.h" +#include "base/metrics/histogram_macros.h" #include "base/path_service.h" #include "base/sequenced_task_runner.h" #include "base/task_scheduler/post_task.h" @@ -29,6 +30,7 @@ #include "chrome/browser/policy/schema_registry_service.h" #include "chrome/browser/policy/schema_registry_service_factory.h" #include "chrome/browser/profiles/profile.h" +#include "chrome/common/pref_names.h" #include "chromeos/chromeos_paths.h" #include "chromeos/chromeos_switches.h" #include "chromeos/dbus/dbus_thread_manager.h" @@ -38,13 +40,17 @@ #include "components/policy/core/common/cloud/device_management_service.h" #include "components/policy/core/common/configuration_policy_provider.h" #include "components/policy/policy_constants.h" +#include "components/prefs/pref_service.h" +#include "components/user_manager/known_user.h" #include "components/user_manager/user.h" #include "components/user_manager/user_manager.h" #include "content/public/browser/browser_thread.h" #include "net/url_request/url_request_context_getter.h" +using user_manager::known_user::ProfileRequiresPolicy; namespace policy { +using PolicyEnforcement = UserCloudPolicyManagerChromeOS::PolicyEnforcement; namespace { // Directory under the profile directory where policy-related resources are @@ -61,9 +67,12 @@ const base::FilePath::CharType kPolicyExternalDataDir[] = FILE_PATH_LITERAL("External Data"); -// Timeout in seconds after which to abandon the initial policy fetch and start -// the session regardless. -const int kInitialPolicyFetchTimeoutSeconds = 10; +// How long we'll block session initialization to try to refresh policy. +constexpr base::TimeDelta kPolicyRefreshTimeout = + base::TimeDelta::FromSeconds(10); + +const char kUMAHasPolicyPrefNotMigrated[] = + "Enterprise.UserPolicyChromeOS.HasPolicyPrefNotMigrated"; } // namespace @@ -144,9 +153,7 @@ DCHECK(active_directory_managers_.find(profile) == active_directory_managers_.end()); - const base::CommandLine* command_line = - base::CommandLine::ForCurrentProcess(); - // Don't initialize cloud policy for the signin and the lock screen app + // Don't initialize cloud policy for the signin and the lock screen app // profile. if (chromeos::ProfileHelper::IsSigninProfile(profile) || chromeos::ProfileHelper::IsLockScreenAppProfile(profile)) { @@ -170,8 +177,14 @@ // |DeviceLocalAccountPolicyService|. // All other user types do not have user policy. const AccountId& account_id = user->GetAccountId(); + const bool is_stub_user = + user_manager::UserManager::Get()->IsStubAccountId(account_id); if (user->IsSupervised() || BrowserPolicyConnector::IsNonEnterpriseUser(account_id.GetUserEmail())) { + DLOG(WARNING) << "No policy loaded for known non-enterprise user"; + // Mark this profile as not requiring policy. + user_manager::known_user::SetProfileRequiresPolicy( + account_id, ProfileRequiresPolicy::kNoPolicyRequired); return {}; } @@ -184,6 +197,7 @@ // TODO(tnagel): Return nullptr for unknown accounts once AccountId // migration is finished. (KioskAppManager still needs to be migrated.) if (!user->HasGaiaAccount()) { + DLOG(WARNING) << "No policy for users without Gaia accounts"; return {}; } is_active_directory = false; @@ -196,34 +210,116 @@ break; } - const bool is_browser_restart = - command_line->HasSwitch(chromeos::switches::kLoginUser); - const user_manager::UserManager* const user_manager = - user_manager::UserManager::Get(); + const ProfileRequiresPolicy requires_policy_user_property = + user_manager::known_user::GetProfileRequiresPolicy(account_id); + const base::CommandLine* command_line = + base::CommandLine::ForCurrentProcess(); - // We want to block for policy if the session has never been initialized - // (generally true if the user is new, or if there was a crash before the - // profile finished initializing). There is code in UserSelectionScreen to - // force an online signin for uninitialized sessions to help ensure we are - // able to load policy. - const bool block_forever_for_policy = - !user_manager->IsLoggedInAsStub() && - !user_manager->GetActiveUser()->profile_ever_initialized(); + // If true, we don't know if we've ever checked for policy for this user - + // this typically means that we need to do a policy check during + // initialization (see comment below). If this is true, then |policy_required| + // must be false. + const bool cannot_tell_if_policy_required = + (requires_policy_user_property == ProfileRequiresPolicy::kUnknown) && + !is_stub_user && + !command_line->HasSwitch(chromeos::switches::kProfileRequiresPolicy) && + !command_line->HasSwitch( + chromeos::switches::kAllowFailedPolicyFetchForTest); - const bool wait_for_policy_fetch = - block_forever_for_policy || !is_browser_restart; + // |force_immediate_load| is true during Chrome restart, or during + // initialization of stub user profiles when running tests. If we ever get + // a Chrome restart before a real user session has been initialized, we should + // exit the user session entirely - it means that there was a crash during + // profile initialization, and we can't rely on the cached policy being valid + // (so can't force immediate load of policy). + if (cannot_tell_if_policy_required && force_immediate_load) { + LOG(ERROR) << "Exiting non-stub session because browser restarted before" + << " profile was initialized."; + chrome::AttemptUserExit(); + return {}; + } - base::TimeDelta initial_policy_fetch_timeout; - if (block_forever_for_policy) { - initial_policy_fetch_timeout = base::TimeDelta::Max(); - } else if (wait_for_policy_fetch) { - initial_policy_fetch_timeout = - base::TimeDelta::FromSeconds(kInitialPolicyFetchTimeoutSeconds); + // If true, we must load policy for this user - we will abort profile + // initialization if we are unable to load policy (say, due to disk errors). + // We either read this flag from the known_user database, or from a + // command-line flag (required for ephemeral users who are not persisted + // in the known_user database). + const bool policy_required = + !command_line->HasSwitch( + chromeos::switches::kAllowFailedPolicyFetchForTest) && + ((requires_policy_user_property == + ProfileRequiresPolicy::kPolicyRequired) || + (command_line->GetSwitchValueASCII( + chromeos::switches::kProfileRequiresPolicy) == "true")); + + DCHECK(!(cannot_tell_if_policy_required && policy_required)); + + // If true, we must either load policy from disk, or else check the server + // for policy. This differs from |policy_required| in that it's OK if the + // server says we don't have policy. + bool policy_check_required = false; + + if (cannot_tell_if_policy_required) { + // There is no preference telling us that the profile has policy. In + // general, this means that this is a new session, or else there was a crash + // before this preference could be set. However, there is also a chance that + // this user existed before we started tracking the ProfileRequiresPolicy + // flag, so we rely on profile_ever_initialized() instead in that case -- + // otherwise, this would break offline login for pre-existing users. + // We track this case via UMA - once people stop hitting this migration + // path, we can remove the migration code here and in + // known_user::WasProfileEverInitialized(). + // TODO(atwilson): Remove this when UMA stats show migration is complete + // (https://crbug.com/731726). + if (user->profile_ever_initialized()) { + LOG(WARNING) << "Migrating user with no policy status"; + UMA_HISTOGRAM_BOOLEAN(kUMAHasPolicyPrefNotMigrated, true); + } else { + // Profile was truly never initialized - we have to block until we've + // checked for policy. + policy_check_required = true; + } + } + + // We should never have |policy_required| and |policy_check_required| both + // set, since the |policy_required| implies that we already know that + // the user requires policy. + CHECK(!(policy_required && policy_check_required)); + + // Determine whether we need to enforce policy load or not. + PolicyEnforcement enforcement_type = PolicyEnforcement::kPolicyOptional; + if (policy_required) { + enforcement_type = PolicyEnforcement::kPolicyRequired; + } else if (policy_check_required) { + enforcement_type = PolicyEnforcement::kServerCheckRequired; + } + + // If there's a chance the user might be managed (enforcement_type != + // kPolicyOptional) then we can't let the profile complete initialization + // until we complete a policy check. + // + // The only exception is if |force_immediate_load| is true, then we can't + // block at all (loading from network is not allowed - only from cache). In + // this case, logic in UserCloudPolicyManagerChromeOS will exit the session + // if we fail to load policy from our cache. + const bool block_profile_init_on_policy_refresh = + (enforcement_type != PolicyEnforcement::kPolicyOptional) && + !force_immediate_load && !is_stub_user; + + base::TimeDelta policy_refresh_timeout; + if (block_profile_init_on_policy_refresh && + enforcement_type == PolicyEnforcement::kPolicyRequired) { + // We already have policy, so block signin for a short period to check + // for a policy update, so we can pick up any important policy changes + // that can't easily change on the fly (like changes to the startup tabs). + // We can fallback to the cached policy if we can't access the policy + // server. + policy_refresh_timeout = kPolicyRefreshTimeout; } DeviceManagementService* device_management_service = connector->device_management_service(); - if (wait_for_policy_fetch) + if (block_profile_init_on_policy_refresh) device_management_service->ScheduleInitialization(0); base::FilePath profile_dir = profile->GetPath(); @@ -258,7 +354,7 @@ if (is_active_directory) { std::unique_ptr<ActiveDirectoryPolicyManager> manager = ActiveDirectoryPolicyManager::CreateForUserPolicy( - account_id, initial_policy_fetch_timeout, + account_id, policy_refresh_timeout, base::BindOnce(&chrome::AttemptUserExit), std::move(store)); manager->Init( SchemaRegistryServiceFactory::GetForContext(profile)->registry()); @@ -269,8 +365,10 @@ std::unique_ptr<UserCloudPolicyManagerChromeOS> manager = std::make_unique<UserCloudPolicyManagerChromeOS>( std::move(store), std::move(external_data_manager), - component_policy_cache_dir, initial_policy_fetch_timeout, - base::ThreadTaskRunnerHandle::Get(), io_task_runner); + component_policy_cache_dir, enforcement_type, + policy_refresh_timeout, + base::BindOnce(&chrome::AttemptUserExit) /* fatal_error_callback */, + account_id, base::ThreadTaskRunnerHandle::Get(), io_task_runner); // TODO(tnagel): Enable whitelist for Active Directory. bool wildcard_match = false;
diff --git a/chrome/browser/chromeos/policy/user_policy_test_helper.cc b/chrome/browser/chromeos/policy/user_policy_test_helper.cc index b4006d4..32ff0cf0 100644 --- a/chrome/browser/chromeos/policy/user_policy_test_helper.cc +++ b/chrome/browser/chromeos/policy/user_policy_test_helper.cc
@@ -94,6 +94,7 @@ UserCloudPolicyManagerChromeOS* const policy_manager = UserPolicyManagerFactoryChromeOS::GetCloudPolicyManagerForProfile( profile); + DCHECK(!policy_manager->IsInitializationComplete(POLICY_DOMAIN_CHROME)); // Give a bogus OAuth token to the |policy_manager|. This should make its // CloudPolicyClient fetch the DMToken.
diff --git a/chrome/browser/chromeos/policy/wildcard_login_checker.cc b/chrome/browser/chromeos/policy/wildcard_login_checker.cc index 7f04721..b0192d8 100644 --- a/chrome/browser/chromeos/policy/wildcard_login_checker.cc +++ b/chrome/browser/chromeos/policy/wildcard_login_checker.cc
@@ -36,12 +36,12 @@ void WildcardLoginChecker::StartWithSigninContext( scoped_refptr<net::URLRequestContextGetter> signin_context, - const StatusCallback& callback) { + StatusCallback callback) { CHECK(!token_fetcher_); CHECK(!user_info_fetcher_); start_timestamp_ = base::Time::Now(); - callback_ = callback; + callback_ = std::move(callback); token_fetcher_.reset(PolicyOAuth2TokenFetcher::CreateInstance()); token_fetcher_->StartWithSigninContext( @@ -52,12 +52,12 @@ void WildcardLoginChecker::StartWithRefreshToken( const std::string& refresh_token, - const StatusCallback& callback) { + StatusCallback callback) { CHECK(!token_fetcher_); CHECK(!user_info_fetcher_); start_timestamp_ = base::Time::Now(); - callback_ = callback; + callback_ = std::move(callback); token_fetcher_.reset(PolicyOAuth2TokenFetcher::CreateInstance()); token_fetcher_->StartWithRefreshToken( @@ -66,14 +66,13 @@ base::Unretained(this))); } -void WildcardLoginChecker::StartWithAccessToken( - const std::string& access_token, - const StatusCallback& callback) { +void WildcardLoginChecker::StartWithAccessToken(const std::string& access_token, + StatusCallback callback) { CHECK(!token_fetcher_); CHECK(!user_info_fetcher_); start_timestamp_ = base::Time::Now(); - callback_ = callback; + callback_ = std::move(callback); StartUserInfoFetcher(access_token); } @@ -126,7 +125,7 @@ void WildcardLoginChecker::OnCheckCompleted(Result result) { if (!callback_.is_null()) - callback_.Run(result); + std::move(callback_).Run(result); } } // namespace policy
diff --git a/chrome/browser/chromeos/policy/wildcard_login_checker.h b/chrome/browser/chromeos/policy/wildcard_login_checker.h index 2044181a..3fac2fb 100644 --- a/chrome/browser/chromeos/policy/wildcard_login_checker.h +++ b/chrome/browser/chromeos/policy/wildcard_login_checker.h
@@ -33,7 +33,7 @@ RESULT_FAILED, // Failure due to network errors etc. }; - typedef base::Callback<void(Result)> StatusCallback; + using StatusCallback = base::OnceCallback<void(Result)>; WildcardLoginChecker(); virtual ~WildcardLoginChecker(); @@ -41,15 +41,15 @@ // Starts checking. The result will be reported via |callback_|. void StartWithSigninContext( scoped_refptr<net::URLRequestContextGetter> signin_context, - const StatusCallback& callback); + StatusCallback callback); // Starts checking with a provided refresh token. void StartWithRefreshToken(const std::string& refresh_token, - const StatusCallback& callback); + StatusCallback callback); // Starts checking with a provided access token. void StartWithAccessToken(const std::string& access_token, - const StatusCallback& callback); + StatusCallback callback); // UserInfoFetcher::Delegate: void OnGetUserInfoSuccess(const base::DictionaryValue* response) override;
diff --git a/chrome/browser/chromeos/smb_client/smb_file_system.cc b/chrome/browser/chromeos/smb_client/smb_file_system.cc index e9779f9..ec4b630 100644 --- a/chrome/browser/chromeos/smb_client/smb_file_system.cc +++ b/chrome/browser/chromeos/smb_client/smb_file_system.cc
@@ -320,7 +320,10 @@ const base::FilePath& file_path, int64_t length, const storage::AsyncFileUtil::StatusCallback& callback) { - NOTIMPLEMENTED(); + GetSmbProviderClient()->Truncate( + GetMountId(), file_path, length, + base::BindOnce(&SmbFileSystem::HandleRequestTruncateCallback, + weak_ptr_factory_.GetWeakPtr(), callback)); return CreateAbortCallback(); } @@ -493,6 +496,12 @@ callback.Run(total_read, false /* has_more */, base::File::FILE_OK); } +void SmbFileSystem::HandleRequestTruncateCallback( + const storage::AsyncFileUtil::StatusCallback& callback, + smbprovider::ErrorType error) const { + callback.Run(TranslateError(error)); +} + base::WeakPtr<file_system_provider::ProvidedFileSystemInterface> SmbFileSystem::GetWeakPtr() { return weak_ptr_factory_.GetWeakPtr();
diff --git a/chrome/browser/chromeos/smb_client/smb_file_system.h b/chrome/browser/chromeos/smb_client/smb_file_system.h index 6ad45c0..35fd03b2 100644 --- a/chrome/browser/chromeos/smb_client/smb_file_system.h +++ b/chrome/browser/chromeos/smb_client/smb_file_system.h
@@ -209,6 +209,10 @@ const storage::AsyncFileUtil::StatusCallback& callback, smbprovider::ErrorType error) const; + void HandleRequestTruncateCallback( + const storage::AsyncFileUtil::StatusCallback& callback, + smbprovider::ErrorType error) const; + base::File::Error RunUnmountCallback( const ProviderId& provider_id, const std::string& file_system_id,
diff --git a/chrome/browser/content_settings/host_content_settings_map_unittest.cc b/chrome/browser/content_settings/host_content_settings_map_unittest.cc index 10fae9c..4a4782b 100644 --- a/chrome/browser/content_settings/host_content_settings_map_unittest.cc +++ b/chrome/browser/content_settings/host_content_settings_map_unittest.cc
@@ -1737,3 +1737,68 @@ invalid_url, invalid_url, CONTENT_SETTINGS_TYPE_POPUPS)); } + +#if BUILDFLAG(ENABLE_PLUGINS) +// Test that existing Flash preferences should get copied into the +// |CONTENT_SETTINGS_TYPE_PLUGINS_DATA| setting on the creation of a new +// |HostContentSettingsMap|. +TEST_F(HostContentSettingsMapTest, PluginDataMigration) { + TestingProfile profile; + // Set a website-specific Flash preference and a pattern exception. + std::unique_ptr<base::Value> value = base::JSONReader::Read( + "{\"https://urlwithflashchanged.com:443,*\":{\"setting\":1}, " + "\"[*.]patternurl.com:443,*\":{\"setting\":1}}"); + profile.GetPrefs()->Set(GetPrefName(CONTENT_SETTINGS_TYPE_PLUGINS), *value); + + HostContentSettingsMap* map = + HostContentSettingsMapFactory::GetForProfile(&profile); + + // Check it was copied successfully. + const GURL url1("https://urlwithflashchanged.com"); + EXPECT_NE(nullptr, map->GetWebsiteSetting(url1, url1, + CONTENT_SETTINGS_TYPE_PLUGINS_DATA, + std::string(), nullptr)); + // Check other urls were not affected. + const GURL url2("https://urlwithflashdefault.com"); + EXPECT_EQ(nullptr, map->GetWebsiteSetting(url2, url2, + CONTENT_SETTINGS_TYPE_PLUGINS_DATA, + std::string(), nullptr)); + // Check patterns are also unaffected. + const GURL pattern("[*.]patternurl.com"); + EXPECT_EQ(nullptr, map->GetWebsiteSetting(pattern, pattern, + CONTENT_SETTINGS_TYPE_PLUGINS_DATA, + std::string(), nullptr)); +} + +// If there are existing |CONTENT_SETTINGS_TYPE_PLUGINS_DATA| preferences +// stored, check we skip the migration. +TEST_F(HostContentSettingsMapTest, PluginDataMigrated) { + TestingProfile profile; + // Set a website-specific Flash preference and another preference indicating + // that the Flash setting has changed for a different website. + std::unique_ptr<base::Value> value = base::JSONReader::Read( + "{\"https://unmigratedurl.com:443,*\":{\"setting\":1}}"); + profile.GetPrefs()->Set(GetPrefName(CONTENT_SETTINGS_TYPE_PLUGINS), *value); + value = base::JSONReader::Read( + "{\"https://" + "example.com:443,*\":{\"setting\":{\"flashPreviouslyChanged\":true}}}"); + profile.GetPrefs()->Set(GetPrefName(CONTENT_SETTINGS_TYPE_PLUGINS_DATA), + *value); + + HostContentSettingsMap* map = + HostContentSettingsMapFactory::GetForProfile(&profile); + + // Check it was copied successfully. + const GURL flash_data_url("https://example.com"); + EXPECT_NE(nullptr, map->GetWebsiteSetting(flash_data_url, flash_data_url, + CONTENT_SETTINGS_TYPE_PLUGINS_DATA, + std::string(), nullptr)); + // Check the migration code was not run (i.e. the other Flash preference set + // above was not migrated). Theoretically this should never happen, but this + // scenario is useful for testing. + const GURL unmigrated_url("https://unmigratedurl.com"); + EXPECT_EQ(nullptr, map->GetWebsiteSetting(unmigrated_url, unmigrated_url, + CONTENT_SETTINGS_TYPE_PLUGINS_DATA, + std::string(), nullptr)); +} +#endif
diff --git a/chrome/browser/content_settings/sound_content_setting_observer.cc b/chrome/browser/content_settings/sound_content_setting_observer.cc index f882634..46db4019 100644 --- a/chrome/browser/content_settings/sound_content_setting_observer.cc +++ b/chrome/browser/content_settings/sound_content_setting_observer.cc
@@ -69,6 +69,10 @@ if (!mute && reason == TabMutedReason::MEDIA_CAPTURE) return; + // Do not unmute if we're muted due to audio indicator. + if (!mute && reason == TabMutedReason::AUDIO_INDICATOR) + return; + // Do not override the decisions of an extension. if (reason == TabMutedReason::EXTENSION) return;
diff --git a/chrome/browser/content_settings/sound_content_setting_observer_unittest.cc b/chrome/browser/content_settings/sound_content_setting_observer_unittest.cc index 55739ab..c2bf4a9 100644 --- a/chrome/browser/content_settings/sound_content_setting_observer_unittest.cc +++ b/chrome/browser/content_settings/sound_content_setting_observer_unittest.cc
@@ -7,6 +7,7 @@ #include "build/build_config.h" #include "chrome/browser/content_settings/host_content_settings_map_factory.h" #include "chrome/browser/profiles/profile.h" +#include "chrome/common/chrome_switches.h" #include "chrome/test/base/chrome_render_view_host_test_harness.h" #include "components/content_settings/core/browser/host_content_settings_map.h" #include "components/ukm/content/source_url_recorder.h" @@ -189,6 +190,19 @@ EXPECT_TRUE(web_contents()->IsAudioMuted()); } +TEST_F(SoundContentSettingObserverTest, DontUnmuteWhenMutedByAudioIndicator) { + base::CommandLine::ForCurrentProcess()->AppendSwitch( + switches::kEnableTabAudioMuting); + EXPECT_FALSE(web_contents()->IsAudioMuted()); + + SetMuteStateForReason(true, TabMutedReason::AUDIO_INDICATOR); + EXPECT_TRUE(web_contents()->IsAudioMuted()); + + // Navigating to a new URL should not unmute the tab muted by audio indicator. + NavigateAndCommit(GURL(kURL2)); + EXPECT_TRUE(web_contents()->IsAudioMuted()); +} + TEST_F(SoundContentSettingObserverTest, DontUnmuteChromeTabWhenMuted) { NavigateAndCommit(GURL(kChromeURL)); EXPECT_FALSE(web_contents()->IsAudioMuted());
diff --git a/chrome/browser/download/chrome_download_manager_delegate.cc b/chrome/browser/download/chrome_download_manager_delegate.cc index 176a688..6ac2338 100644 --- a/chrome/browser/download/chrome_download_manager_delegate.cc +++ b/chrome/browser/download/chrome_download_manager_delegate.cc
@@ -164,20 +164,20 @@ const DownloadTargetDeterminerDelegate::CheckDownloadUrlCallback& callback, bool is_content_check_supported, safe_browsing::DownloadCheckResult result) { - content::DownloadDangerType danger_type; + download::DownloadDangerType danger_type; if (result == safe_browsing::DownloadCheckResult::SAFE || result == safe_browsing::DownloadCheckResult::UNKNOWN) { // If this type of files is handled by the enhanced SafeBrowsing download // protection, mark it as potentially dangerous content until we are done // with scanning it. if (is_content_check_supported) - danger_type = content::DOWNLOAD_DANGER_TYPE_MAYBE_DANGEROUS_CONTENT; + danger_type = download::DOWNLOAD_DANGER_TYPE_MAYBE_DANGEROUS_CONTENT; else - danger_type = content::DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS; + danger_type = download::DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS; } else { // If the URL is malicious, we'll use that as the danger type. The results // of the content check, if one is performed, will be ignored. - danger_type = content::DOWNLOAD_DANGER_TYPE_DANGEROUS_URL; + danger_type = download::DOWNLOAD_DANGER_TYPE_DANGEROUS_URL; } callback.Run(danger_type); } @@ -432,23 +432,23 @@ // In case the service was disabled between the download starting and now, // we need to restore the danger state. - content::DownloadDangerType danger_type = item->GetDangerType(); + download::DownloadDangerType danger_type = item->GetDangerType(); if (DownloadItemModel(item).GetDangerLevel() != DownloadFileType::NOT_DANGEROUS && - (danger_type == content::DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS || + (danger_type == download::DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS || danger_type == - content::DOWNLOAD_DANGER_TYPE_MAYBE_DANGEROUS_CONTENT)) { + download::DOWNLOAD_DANGER_TYPE_MAYBE_DANGEROUS_CONTENT)) { DVLOG(2) << __func__ << "() SB service disabled. Marking download as DANGEROUS FILE"; - if (ShouldBlockFile(content::DOWNLOAD_DANGER_TYPE_DANGEROUS_FILE)) { + if (ShouldBlockFile(download::DOWNLOAD_DANGER_TYPE_DANGEROUS_FILE)) { item->OnContentCheckCompleted( // Specifying a dangerous type here would take precendence over the // blocking of the file. - content::DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS, + download::DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS, content::DOWNLOAD_INTERRUPT_REASON_FILE_BLOCKED); } else { item->OnContentCheckCompleted( - content::DOWNLOAD_DANGER_TYPE_DANGEROUS_FILE, + download::DOWNLOAD_DANGER_TYPE_DANGEROUS_FILE, content::DOWNLOAD_INTERRUPT_REASON_NONE); } UMA_HISTOGRAM_ENUMERATION("Download.DangerousFile.Reason", @@ -863,7 +863,7 @@ return; } #endif - callback.Run(content::DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS); + callback.Run(download::DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS); } void ChromeDownloadManagerDelegate::GetFileMimeType( @@ -886,17 +886,17 @@ << " verdict = " << static_cast<int>(result); // We only mark the content as being dangerous if the download's safety state // has not been set to DANGEROUS yet. We don't want to show two warnings. - if (item->GetDangerType() == content::DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS || + if (item->GetDangerType() == download::DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS || item->GetDangerType() == - content::DOWNLOAD_DANGER_TYPE_MAYBE_DANGEROUS_CONTENT) { - content::DownloadDangerType danger_type = - content::DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS; + download::DOWNLOAD_DANGER_TYPE_MAYBE_DANGEROUS_CONTENT) { + download::DownloadDangerType danger_type = + download::DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS; switch (result) { case safe_browsing::DownloadCheckResult::UNKNOWN: // The check failed or was inconclusive. if (DownloadItemModel(item).GetDangerLevel() != DownloadFileType::NOT_DANGEROUS) { - danger_type = content::DOWNLOAD_DANGER_TYPE_DANGEROUS_FILE; + danger_type = download::DOWNLOAD_DANGER_TYPE_DANGEROUS_FILE; UMA_HISTOGRAM_ENUMERATION("Download.DangerousFile.Reason", SB_RETURNS_UNKOWN, DANGEROUS_FILE_REASON_MAX); @@ -908,33 +908,33 @@ // whether the download is intended or not. if (DownloadItemModel(item).GetDangerLevel() == DownloadFileType::DANGEROUS) { - danger_type = content::DOWNLOAD_DANGER_TYPE_DANGEROUS_FILE; + danger_type = download::DOWNLOAD_DANGER_TYPE_DANGEROUS_FILE; UMA_HISTOGRAM_ENUMERATION("Download.DangerousFile.Reason", SB_RETURNS_SAFE, DANGEROUS_FILE_REASON_MAX); } break; case safe_browsing::DownloadCheckResult::DANGEROUS: - danger_type = content::DOWNLOAD_DANGER_TYPE_DANGEROUS_CONTENT; + danger_type = download::DOWNLOAD_DANGER_TYPE_DANGEROUS_CONTENT; break; case safe_browsing::DownloadCheckResult::UNCOMMON: - danger_type = content::DOWNLOAD_DANGER_TYPE_UNCOMMON_CONTENT; + danger_type = download::DOWNLOAD_DANGER_TYPE_UNCOMMON_CONTENT; break; case safe_browsing::DownloadCheckResult::DANGEROUS_HOST: - danger_type = content::DOWNLOAD_DANGER_TYPE_DANGEROUS_HOST; + danger_type = download::DOWNLOAD_DANGER_TYPE_DANGEROUS_HOST; break; case safe_browsing::DownloadCheckResult::POTENTIALLY_UNWANTED: - danger_type = content::DOWNLOAD_DANGER_TYPE_POTENTIALLY_UNWANTED; + danger_type = download::DOWNLOAD_DANGER_TYPE_POTENTIALLY_UNWANTED; break; } DCHECK_NE(danger_type, - content::DOWNLOAD_DANGER_TYPE_MAYBE_DANGEROUS_CONTENT); + download::DOWNLOAD_DANGER_TYPE_MAYBE_DANGEROUS_CONTENT); - if (danger_type != content::DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS) { + if (danger_type != download::DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS) { if (ShouldBlockFile(danger_type)) { item->OnContentCheckCompleted( // Specifying a dangerous type here would take precendence over the // blocking of the file. - content::DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS, + download::DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS, content::DOWNLOAD_INTERRUPT_REASON_FILE_BLOCKED); } else { item->OnContentCheckCompleted(danger_type, @@ -990,7 +990,7 @@ if (ShouldBlockFile(target_info->danger_type)) { target_info->result = content::DOWNLOAD_INTERRUPT_REASON_FILE_BLOCKED; // A dangerous type would take precendence over the blocking of the file. - target_info->danger_type = content::DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS; + target_info->danger_type = download::DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS; } callback.Run(target_info->target_path, target_info->target_disposition, @@ -1029,7 +1029,7 @@ } bool ChromeDownloadManagerDelegate::ShouldBlockFile( - content::DownloadDangerType danger_type) const { + download::DownloadDangerType danger_type) const { DownloadPrefs::DownloadRestriction download_restriction = download_prefs_->download_restriction(); @@ -1038,12 +1038,12 @@ return false; case (DownloadPrefs::DownloadRestriction::POTENTIALLY_DANGEROUS_FILES): - return danger_type != content::DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS; + return danger_type != download::DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS; case (DownloadPrefs::DownloadRestriction::DANGEROUS_FILES): { - return (danger_type == content::DOWNLOAD_DANGER_TYPE_DANGEROUS_CONTENT || - danger_type == content::DOWNLOAD_DANGER_TYPE_DANGEROUS_FILE || - danger_type == content::DOWNLOAD_DANGER_TYPE_DANGEROUS_URL); + return (danger_type == download::DOWNLOAD_DANGER_TYPE_DANGEROUS_CONTENT || + danger_type == download::DOWNLOAD_DANGER_TYPE_DANGEROUS_FILE || + danger_type == download::DOWNLOAD_DANGER_TYPE_DANGEROUS_URL); } case (DownloadPrefs::DownloadRestriction::ALL_FILES):
diff --git a/chrome/browser/download/chrome_download_manager_delegate.h b/chrome/browser/download/chrome_download_manager_delegate.h index dc035f8d..c408ca5 100644 --- a/chrome/browser/download/chrome_download_manager_delegate.h +++ b/chrome/browser/download/chrome_download_manager_delegate.h
@@ -23,7 +23,7 @@ #include "chrome/browser/download/download_target_info.h" #include "chrome/browser/safe_browsing/download_protection/download_protection_service.h" #include "chrome/browser/safe_browsing/download_protection/download_protection_util.h" -#include "content/public/browser/download_danger_type.h" +#include "components/download/public/common/download_danger_type.h" #include "content/public/browser/download_item.h" #include "content/public/browser/download_manager_delegate.h" #include "content/public/browser/notification_observer.h" @@ -183,7 +183,7 @@ // Return true if the downloaded file should be blocked based on the current // download restriction pref and |danger_type|. - bool ShouldBlockFile(content::DownloadDangerType danger_type) const; + bool ShouldBlockFile(download::DownloadDangerType danger_type) const; void MaybeSendDangerousDownloadOpenedReport(content::DownloadItem* download, bool show_download_in_folder);
diff --git a/chrome/browser/download/chrome_download_manager_delegate_unittest.cc b/chrome/browser/download/chrome_download_manager_delegate_unittest.cc index 237f349..7701b6e 100644 --- a/chrome/browser/download/chrome_download_manager_delegate_unittest.cc +++ b/chrome/browser/download/chrome_download_manager_delegate_unittest.cc
@@ -102,14 +102,14 @@ base::FilePath target_path; content::DownloadItem::TargetDisposition disposition; - content::DownloadDangerType danger_type; + download::DownloadDangerType danger_type; base::FilePath intermediate_path; content::DownloadInterruptReason interrupt_reason; }; DetermineDownloadTargetResult::DetermineDownloadTargetResult() : disposition(content::DownloadItem::TARGET_DISPOSITION_OVERWRITE), - danger_type(content::DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS), + danger_type(download::DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS), interrupt_reason(content::DOWNLOAD_INTERRUPT_REASON_NONE) {} // Subclass of the ChromeDownloadManagerDelegate that replaces a few interaction @@ -119,7 +119,7 @@ explicit TestChromeDownloadManagerDelegate(Profile* profile) : ChromeDownloadManagerDelegate(profile) { ON_CALL(*this, MockCheckDownloadUrl(_, _)) - .WillByDefault(Return(content::DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS)); + .WillByDefault(Return(download::DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS)); ON_CALL(*this, GetDownloadProtectionService()) .WillByDefault(Return(nullptr)); ON_CALL(*this, MockReserveVirtualPath(_, _, _, _, _)) @@ -177,8 +177,8 @@ } MOCK_METHOD2(MockCheckDownloadUrl, - content::DownloadDangerType(DownloadItem*, - const base::FilePath&)); + download::DownloadDangerType(DownloadItem*, + const base::FilePath&)); MOCK_METHOD0(GetDownloadProtectionService, safe_browsing::DownloadProtectionService*()); @@ -292,7 +292,7 @@ ON_CALL(*item, GetBrowserContext()) .WillByDefault(Return(profile())); ON_CALL(*item, GetDangerType()) - .WillByDefault(Return(content::DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS)); + .WillByDefault(Return(download::DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS)); ON_CALL(*item, GetForcedFilePath()) .WillByDefault(ReturnRefOfCopy(base::FilePath())); ON_CALL(*item, GetFullPath()) @@ -342,7 +342,7 @@ DetermineDownloadTargetResult* result, const base::FilePath& target_path, DownloadItem::TargetDisposition target_disposition, - content::DownloadDangerType danger_type, + download::DownloadDangerType danger_type, const base::FilePath& intermediate_path, content::DownloadInterruptReason interrupt_reason) { result->target_path = target_path; @@ -523,7 +523,7 @@ .WillRepeatedly(Return(DownloadItem::TARGET_DISPOSITION_OVERWRITE)); EXPECT_CALL(*delegate(), MockCheckDownloadUrl(_, _)) .WillRepeatedly( - Return(content::DOWNLOAD_DANGER_TYPE_MAYBE_DANGEROUS_CONTENT)); + Return(download::DOWNLOAD_DANGER_TYPE_MAYBE_DANGEROUS_CONTENT)); { const std::string kDangerousContentDisposition( @@ -535,7 +535,7 @@ EXPECT_EQ(DownloadFileType::DANGEROUS, DownloadItemModel(download_item.get()).GetDangerLevel()); - EXPECT_EQ(content::DOWNLOAD_DANGER_TYPE_MAYBE_DANGEROUS_CONTENT, + EXPECT_EQ(download::DOWNLOAD_DANGER_TYPE_MAYBE_DANGEROUS_CONTENT, result.danger_type); } @@ -548,7 +548,7 @@ DetermineDownloadTarget(download_item.get(), &result); EXPECT_EQ(DownloadFileType::NOT_DANGEROUS, DownloadItemModel(download_item.get()).GetDangerLevel()); - EXPECT_EQ(content::DOWNLOAD_DANGER_TYPE_MAYBE_DANGEROUS_CONTENT, + EXPECT_EQ(download::DOWNLOAD_DANGER_TYPE_MAYBE_DANGEROUS_CONTENT, result.danger_type); } @@ -561,7 +561,7 @@ DetermineDownloadTarget(download_item.get(), &result); EXPECT_EQ(DownloadFileType::ALLOW_ON_USER_GESTURE, DownloadItemModel(download_item.get()).GetDangerLevel()); - EXPECT_EQ(content::DOWNLOAD_DANGER_TYPE_MAYBE_DANGEROUS_CONTENT, + EXPECT_EQ(download::DOWNLOAD_DANGER_TYPE_MAYBE_DANGEROUS_CONTENT, result.danger_type); } } @@ -648,12 +648,12 @@ namespace { struct SafeBrowsingTestParameters { - content::DownloadDangerType initial_danger_type; + download::DownloadDangerType initial_danger_type; DownloadFileType::DangerLevel initial_danger_level; safe_browsing::DownloadCheckResult verdict; DownloadPrefs::DownloadRestriction download_restriction; - content::DownloadDangerType expected_danger_type; + download::DownloadDangerType expected_danger_type; bool blocked; }; @@ -700,162 +700,162 @@ const SafeBrowsingTestParameters kSafeBrowsingTestCases[] = { // SAFE verdict for a safe file. - {content::DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS, + {download::DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS, DownloadFileType::NOT_DANGEROUS, safe_browsing::DownloadCheckResult::SAFE, DownloadPrefs::DownloadRestriction::NONE, - content::DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS, + download::DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS, /*blocked=*/false}, // UNKNOWN verdict for a safe file. - {content::DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS, + {download::DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS, DownloadFileType::NOT_DANGEROUS, safe_browsing::DownloadCheckResult::UNKNOWN, DownloadPrefs::DownloadRestriction::NONE, - content::DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS, + download::DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS, /*blocked=*/false}, // DANGEROUS verdict for a safe file. - {content::DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS, + {download::DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS, DownloadFileType::NOT_DANGEROUS, safe_browsing::DownloadCheckResult::DANGEROUS, DownloadPrefs::DownloadRestriction::NONE, - content::DOWNLOAD_DANGER_TYPE_DANGEROUS_CONTENT, + download::DOWNLOAD_DANGER_TYPE_DANGEROUS_CONTENT, /*blocked=*/false}, // UNCOMMON verdict for a safe file. - {content::DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS, + {download::DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS, DownloadFileType::NOT_DANGEROUS, safe_browsing::DownloadCheckResult::UNCOMMON, DownloadPrefs::DownloadRestriction::NONE, - content::DOWNLOAD_DANGER_TYPE_UNCOMMON_CONTENT, + download::DOWNLOAD_DANGER_TYPE_UNCOMMON_CONTENT, /*blocked=*/false}, // POTENTIALLY_UNWANTED verdict for a safe file. - {content::DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS, + {download::DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS, DownloadFileType::NOT_DANGEROUS, safe_browsing::DownloadCheckResult::POTENTIALLY_UNWANTED, DownloadPrefs::DownloadRestriction::NONE, - content::DOWNLOAD_DANGER_TYPE_POTENTIALLY_UNWANTED, + download::DOWNLOAD_DANGER_TYPE_POTENTIALLY_UNWANTED, /*blocked=*/false}, // SAFE verdict for a potentially dangerous file. - {content::DOWNLOAD_DANGER_TYPE_MAYBE_DANGEROUS_CONTENT, + {download::DOWNLOAD_DANGER_TYPE_MAYBE_DANGEROUS_CONTENT, DownloadFileType::ALLOW_ON_USER_GESTURE, safe_browsing::DownloadCheckResult::SAFE, DownloadPrefs::DownloadRestriction::NONE, - content::DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS, + download::DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS, /*blocked=*/false}, // UNKNOWN verdict for a potentially dangerous file. - {content::DOWNLOAD_DANGER_TYPE_MAYBE_DANGEROUS_CONTENT, + {download::DOWNLOAD_DANGER_TYPE_MAYBE_DANGEROUS_CONTENT, DownloadFileType::ALLOW_ON_USER_GESTURE, safe_browsing::DownloadCheckResult::UNKNOWN, DownloadPrefs::DownloadRestriction::NONE, - content::DOWNLOAD_DANGER_TYPE_DANGEROUS_FILE, + download::DOWNLOAD_DANGER_TYPE_DANGEROUS_FILE, /*blocked=*/false}, // UNKNOWN verdict for a potentially dangerous file blocked by policy. - {content::DOWNLOAD_DANGER_TYPE_MAYBE_DANGEROUS_CONTENT, + {download::DOWNLOAD_DANGER_TYPE_MAYBE_DANGEROUS_CONTENT, DownloadFileType::ALLOW_ON_USER_GESTURE, safe_browsing::DownloadCheckResult::UNKNOWN, DownloadPrefs::DownloadRestriction::DANGEROUS_FILES, - content::DOWNLOAD_DANGER_TYPE_DANGEROUS_FILE, + download::DOWNLOAD_DANGER_TYPE_DANGEROUS_FILE, /*blocked=*/true}, // DANGEROUS verdict for a potentially dangerous file. - {content::DOWNLOAD_DANGER_TYPE_MAYBE_DANGEROUS_CONTENT, + {download::DOWNLOAD_DANGER_TYPE_MAYBE_DANGEROUS_CONTENT, DownloadFileType::ALLOW_ON_USER_GESTURE, safe_browsing::DownloadCheckResult::DANGEROUS, DownloadPrefs::DownloadRestriction::NONE, - content::DOWNLOAD_DANGER_TYPE_DANGEROUS_CONTENT, + download::DOWNLOAD_DANGER_TYPE_DANGEROUS_CONTENT, /*blocked=*/false}, // UNCOMMON verdict for a potentially dangerous file. - {content::DOWNLOAD_DANGER_TYPE_MAYBE_DANGEROUS_CONTENT, + {download::DOWNLOAD_DANGER_TYPE_MAYBE_DANGEROUS_CONTENT, DownloadFileType::ALLOW_ON_USER_GESTURE, safe_browsing::DownloadCheckResult::UNCOMMON, DownloadPrefs::DownloadRestriction::NONE, - content::DOWNLOAD_DANGER_TYPE_UNCOMMON_CONTENT, + download::DOWNLOAD_DANGER_TYPE_UNCOMMON_CONTENT, /*blocked=*/false}, // POTENTIALLY_UNWANTED verdict for a potentially dangerous file. - {content::DOWNLOAD_DANGER_TYPE_MAYBE_DANGEROUS_CONTENT, + {download::DOWNLOAD_DANGER_TYPE_MAYBE_DANGEROUS_CONTENT, DownloadFileType::ALLOW_ON_USER_GESTURE, safe_browsing::DownloadCheckResult::POTENTIALLY_UNWANTED, DownloadPrefs::DownloadRestriction::NONE, - content::DOWNLOAD_DANGER_TYPE_POTENTIALLY_UNWANTED, + download::DOWNLOAD_DANGER_TYPE_POTENTIALLY_UNWANTED, /*blocked=*/false}, // POTENTIALLY_UNWANTED verdict for a potentially dangerous file, blocked by // policy. - {content::DOWNLOAD_DANGER_TYPE_MAYBE_DANGEROUS_CONTENT, + {download::DOWNLOAD_DANGER_TYPE_MAYBE_DANGEROUS_CONTENT, DownloadFileType::ALLOW_ON_USER_GESTURE, safe_browsing::DownloadCheckResult::POTENTIALLY_UNWANTED, DownloadPrefs::DownloadRestriction::POTENTIALLY_DANGEROUS_FILES, - content::DOWNLOAD_DANGER_TYPE_POTENTIALLY_UNWANTED, + download::DOWNLOAD_DANGER_TYPE_POTENTIALLY_UNWANTED, /*blocked=*/true}, // POTENTIALLY_UNWANTED verdict for a potentially dangerous file, not // blocked by policy. - {content::DOWNLOAD_DANGER_TYPE_MAYBE_DANGEROUS_CONTENT, + {download::DOWNLOAD_DANGER_TYPE_MAYBE_DANGEROUS_CONTENT, DownloadFileType::ALLOW_ON_USER_GESTURE, safe_browsing::DownloadCheckResult::POTENTIALLY_UNWANTED, DownloadPrefs::DownloadRestriction::DANGEROUS_FILES, - content::DOWNLOAD_DANGER_TYPE_POTENTIALLY_UNWANTED, + download::DOWNLOAD_DANGER_TYPE_POTENTIALLY_UNWANTED, /*blocked=*/false}, // SAFE verdict for a dangerous file. - {content::DOWNLOAD_DANGER_TYPE_MAYBE_DANGEROUS_CONTENT, + {download::DOWNLOAD_DANGER_TYPE_MAYBE_DANGEROUS_CONTENT, DownloadFileType::DANGEROUS, safe_browsing::DownloadCheckResult::SAFE, DownloadPrefs::DownloadRestriction::NONE, - content::DOWNLOAD_DANGER_TYPE_DANGEROUS_FILE, + download::DOWNLOAD_DANGER_TYPE_DANGEROUS_FILE, /*blocked=*/false}, // UNKNOWN verdict for a dangerous file. - {content::DOWNLOAD_DANGER_TYPE_MAYBE_DANGEROUS_CONTENT, + {download::DOWNLOAD_DANGER_TYPE_MAYBE_DANGEROUS_CONTENT, DownloadFileType::DANGEROUS, safe_browsing::DownloadCheckResult::UNKNOWN, DownloadPrefs::DownloadRestriction::NONE, - content::DOWNLOAD_DANGER_TYPE_DANGEROUS_FILE, + download::DOWNLOAD_DANGER_TYPE_DANGEROUS_FILE, /*blocked=*/false}, // DANGEROUS verdict for a dangerous file. - {content::DOWNLOAD_DANGER_TYPE_MAYBE_DANGEROUS_CONTENT, + {download::DOWNLOAD_DANGER_TYPE_MAYBE_DANGEROUS_CONTENT, DownloadFileType::DANGEROUS, safe_browsing::DownloadCheckResult::DANGEROUS, DownloadPrefs::DownloadRestriction::NONE, - content::DOWNLOAD_DANGER_TYPE_DANGEROUS_CONTENT, + download::DOWNLOAD_DANGER_TYPE_DANGEROUS_CONTENT, /*blocked=*/false}, // UNCOMMON verdict for a dangerous file. - {content::DOWNLOAD_DANGER_TYPE_MAYBE_DANGEROUS_CONTENT, + {download::DOWNLOAD_DANGER_TYPE_MAYBE_DANGEROUS_CONTENT, DownloadFileType::DANGEROUS, safe_browsing::DownloadCheckResult::UNCOMMON, DownloadPrefs::DownloadRestriction::NONE, - content::DOWNLOAD_DANGER_TYPE_UNCOMMON_CONTENT, + download::DOWNLOAD_DANGER_TYPE_UNCOMMON_CONTENT, /*blocked=*/false}, // POTENTIALLY_UNWANTED verdict for a dangerous file. - {content::DOWNLOAD_DANGER_TYPE_MAYBE_DANGEROUS_CONTENT, + {download::DOWNLOAD_DANGER_TYPE_MAYBE_DANGEROUS_CONTENT, DownloadFileType::DANGEROUS, safe_browsing::DownloadCheckResult::POTENTIALLY_UNWANTED, DownloadPrefs::DownloadRestriction::NONE, - content::DOWNLOAD_DANGER_TYPE_POTENTIALLY_UNWANTED, + download::DOWNLOAD_DANGER_TYPE_POTENTIALLY_UNWANTED, /*blocked=*/false}, }; @@ -882,13 +882,13 @@ } if (kParameters.expected_danger_type != - content::DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS) { + download::DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS) { if (kParameters.blocked) { EXPECT_CALL(*download_item, OnContentCheckCompleted( // Specifying a dangerous type here would take precendence // over the blocking of the file. - content::DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS, + download::DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS, content::DOWNLOAD_INTERRUPT_REASON_FILE_BLOCKED)); } else { EXPECT_CALL(*download_item, OnContentCheckCompleted( @@ -922,7 +922,7 @@ EXPECT_CALL(*download_protection_service(), MockCheckClientDownload()) .WillOnce(Return(safe_browsing::DownloadCheckResult::SAFE)); EXPECT_CALL(*download_item, GetDangerType()) - .WillRepeatedly(Return(content::DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS)); + .WillRepeatedly(Return(download::DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS)); base::RunLoop run_loop; ASSERT_FALSE(delegate()->ShouldCompleteDownload(download_item.get(),
diff --git a/chrome/browser/download/download_browsertest.cc b/chrome/browser/download/download_browsertest.cc index 6d0b180..2806f4a6 100644 --- a/chrome/browser/download/download_browsertest.cc +++ b/chrome/browser/download/download_browsertest.cc
@@ -76,6 +76,7 @@ #include "chrome/grit/generated_resources.h" #include "chrome/test/base/in_process_browser_test.h" #include "chrome/test/base/ui_test_utils.h" +#include "components/download/public/common/download_danger_type.h" #include "components/history/content/browser/download_conversions.h" #include "components/history/core/browser/download_constants.h" #include "components/history/core/browser/download_row.h" @@ -85,11 +86,9 @@ #include "components/prefs/pref_service.h" #include "components/safe_browsing/common/safe_browsing_prefs.h" #include "components/safe_browsing/proto/csd.pb.h" -#include "content/public/browser/download_danger_type.h" #include "content/public/browser/download_interrupt_reasons.h" #include "content/public/browser/download_item.h" #include "content/public/browser/download_manager.h" -#include "content/public/browser/download_save_info.h" #include "content/public/browser/download_url_parameters.h" #include "content/public/browser/notification_source.h" #include "content/public/browser/render_frame_host.h" @@ -3481,7 +3480,7 @@ final_state_seen_ = true; browser_->profile()->GetPrefs()->SetBoolean(prefs::kSafeBrowsingEnabled, false); - EXPECT_EQ(content::DOWNLOAD_DANGER_TYPE_MAYBE_DANGEROUS_CONTENT, + EXPECT_EQ(download::DOWNLOAD_DANGER_TYPE_MAYBE_DANGEROUS_CONTENT, download->GetDangerType()); EXPECT_FALSE(download->IsDangerous()); EXPECT_NE(safe_browsing::DownloadFileType::NOT_DANGEROUS, @@ -3533,7 +3532,7 @@ dangerous_observer->WaitForFinished(); EXPECT_TRUE(download->IsDangerous()); - EXPECT_EQ(content::DOWNLOAD_DANGER_TYPE_DANGEROUS_FILE, + EXPECT_EQ(download::DOWNLOAD_DANGER_TYPE_DANGEROUS_FILE, download->GetDangerType()); download->Cancel(true); } @@ -3561,7 +3560,7 @@ DownloadItem* download = downloads[0]; EXPECT_TRUE(download->IsDangerous()); - EXPECT_EQ(content::DOWNLOAD_DANGER_TYPE_DANGEROUS_FILE, + EXPECT_EQ(download::DOWNLOAD_DANGER_TYPE_DANGEROUS_FILE, download->GetDangerType()); download->Cancel(true); @@ -3581,7 +3580,7 @@ DownloadItem* download = downloads[0]; EXPECT_FALSE(download->IsDangerous()); - EXPECT_EQ(content::DOWNLOAD_DANGER_TYPE_MAYBE_DANGEROUS_CONTENT, + EXPECT_EQ(download::DOWNLOAD_DANGER_TYPE_MAYBE_DANGEROUS_CONTENT, download->GetDangerType()); download->Cancel(true);
diff --git a/chrome/browser/download/download_commands.cc b/chrome/browser/download/download_commands.cc index 2f77b9f..577da9e 100644 --- a/chrome/browser/download/download_commands.cc +++ b/chrome/browser/download/download_commands.cc
@@ -322,7 +322,7 @@ // 4. User is not in incognito mode. #if defined(FULL_SAFE_BROWSING) if (download_item_->GetDangerType() == - content::DOWNLOAD_DANGER_TYPE_UNCOMMON_CONTENT && + download::DOWNLOAD_DANGER_TYPE_UNCOMMON_CONTENT && !download_item_->GetURL().is_empty() && !download_item_->GetBrowserContext()->IsOffTheRecord()) { safe_browsing::SafeBrowsingService* sb_service =
diff --git a/chrome/browser/download/download_danger_prompt.cc b/chrome/browser/download/download_danger_prompt.cc index 6639adc..9f1ade57 100644 --- a/chrome/browser/download/download_danger_prompt.cc +++ b/chrome/browser/download/download_danger_prompt.cc
@@ -11,7 +11,7 @@ #include "chrome/browser/safe_browsing/download_protection/download_protection_service.h" #include "chrome/browser/safe_browsing/safe_browsing_service.h" #include "chrome/common/safe_browsing/file_type_policies.h" -#include "content/public/browser/download_danger_type.h" +#include "components/download/public/common/download_danger_type.h" #include "content/public/browser/download_item.h" using safe_browsing::ClientDownloadResponse; @@ -23,24 +23,24 @@ // Converts DownloadDangerType into their corresponding string. const char* GetDangerTypeString( - const content::DownloadDangerType& danger_type) { + const download::DownloadDangerType& danger_type) { switch (danger_type) { - case content::DOWNLOAD_DANGER_TYPE_DANGEROUS_FILE: + case download::DOWNLOAD_DANGER_TYPE_DANGEROUS_FILE: return "DangerousFile"; - case content::DOWNLOAD_DANGER_TYPE_DANGEROUS_URL: + case download::DOWNLOAD_DANGER_TYPE_DANGEROUS_URL: return "DangerousURL"; - case content::DOWNLOAD_DANGER_TYPE_DANGEROUS_CONTENT: + case download::DOWNLOAD_DANGER_TYPE_DANGEROUS_CONTENT: return "DangerousContent"; - case content::DOWNLOAD_DANGER_TYPE_DANGEROUS_HOST: + case download::DOWNLOAD_DANGER_TYPE_DANGEROUS_HOST: return "DangerousHost"; - case content::DOWNLOAD_DANGER_TYPE_UNCOMMON_CONTENT: + case download::DOWNLOAD_DANGER_TYPE_UNCOMMON_CONTENT: return "UncommonContent"; - case content::DOWNLOAD_DANGER_TYPE_POTENTIALLY_UNWANTED: + case download::DOWNLOAD_DANGER_TYPE_POTENTIALLY_UNWANTED: return "PotentiallyUnwanted"; - case content::DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS: - case content::DOWNLOAD_DANGER_TYPE_MAYBE_DANGEROUS_CONTENT: - case content::DOWNLOAD_DANGER_TYPE_USER_VALIDATED: - case content::DOWNLOAD_DANGER_TYPE_MAX: + case download::DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS: + case download::DOWNLOAD_DANGER_TYPE_MAYBE_DANGEROUS_CONTENT: + case download::DOWNLOAD_DANGER_TYPE_USER_VALIDATED: + case download::DOWNLOAD_DANGER_TYPE_MAX: break; } NOTREACHED(); @@ -58,17 +58,17 @@ ClientSafeBrowsingReportRequest report; report.set_type(report_type); switch (download.GetDangerType()) { - case content::DOWNLOAD_DANGER_TYPE_DANGEROUS_URL: - case content::DOWNLOAD_DANGER_TYPE_DANGEROUS_CONTENT: + case download::DOWNLOAD_DANGER_TYPE_DANGEROUS_URL: + case download::DOWNLOAD_DANGER_TYPE_DANGEROUS_CONTENT: report.set_download_verdict(ClientDownloadResponse::DANGEROUS); break; - case content::DOWNLOAD_DANGER_TYPE_UNCOMMON_CONTENT: + case download::DOWNLOAD_DANGER_TYPE_UNCOMMON_CONTENT: report.set_download_verdict(ClientDownloadResponse::UNCOMMON); break; - case content::DOWNLOAD_DANGER_TYPE_POTENTIALLY_UNWANTED: + case download::DOWNLOAD_DANGER_TYPE_POTENTIALLY_UNWANTED: report.set_download_verdict(ClientDownloadResponse::POTENTIALLY_UNWANTED); break; - case content::DOWNLOAD_DANGER_TYPE_DANGEROUS_HOST: + case download::DOWNLOAD_DANGER_TYPE_DANGEROUS_HOST: report.set_download_verdict(ClientDownloadResponse::DANGEROUS_HOST); break; default: // Don't send report for any other danger types. @@ -94,7 +94,7 @@ int64_t file_type_uma_value = safe_browsing::FileTypePolicies::GetInstance()->UmaValueForFile( download.GetTargetFilePath()); - content::DownloadDangerType danger_type = download.GetDangerType(); + download::DownloadDangerType danger_type = download.GetDangerType(); base::UmaHistogramSparse( base::StringPrintf("%s.%s.Shown", kDownloadDangerPromptPrefix,
diff --git a/chrome/browser/download/download_danger_prompt_browsertest.cc b/chrome/browser/download/download_danger_prompt_browsertest.cc index 44a6f98..cfa9bf9c 100644 --- a/chrome/browser/download/download_danger_prompt_browsertest.cc +++ b/chrome/browser/download/download_danger_prompt_browsertest.cc
@@ -107,7 +107,7 @@ void SetUpExpectations( const DownloadDangerPrompt::Action& expected_action, - const content::DownloadDangerType& danger_type, + const download::DownloadDangerType& danger_type, const ClientDownloadResponse::Verdict& download_verdict, const std::string& token, bool from_download_api) { @@ -153,7 +153,7 @@ private: void SetUpDownloadItemExpectations( - const content::DownloadDangerType& danger_type, + const download::DownloadDangerType& danger_type, const std::string& token) { EXPECT_CALL(download_, GetFileNameToReportUser()).WillRepeatedly(Return( base::FilePath(FILE_PATH_LITERAL("evil.exe")))); @@ -234,9 +234,8 @@ // Clicking the Accept button should invoke the ACCEPT action. SetUpExpectations(DownloadDangerPrompt::ACCEPT, - content::DOWNLOAD_DANGER_TYPE_DANGEROUS_URL, - ClientDownloadResponse::DANGEROUS, - kDownloadResponseToken, + download::DOWNLOAD_DANGER_TYPE_DANGEROUS_URL, + ClientDownloadResponse::DANGEROUS, kDownloadResponseToken, false); EXPECT_CALL(download(), IsDangerous()).WillRepeatedly(Return(true)); SimulatePromptAction(DownloadDangerPrompt::ACCEPT); @@ -244,10 +243,8 @@ // Clicking the Cancel button should invoke the CANCEL action. SetUpExpectations(DownloadDangerPrompt::CANCEL, - content::DOWNLOAD_DANGER_TYPE_UNCOMMON_CONTENT, - ClientDownloadResponse::UNCOMMON, - std::string(), - false); + download::DOWNLOAD_DANGER_TYPE_UNCOMMON_CONTENT, + ClientDownloadResponse::UNCOMMON, std::string(), false); EXPECT_CALL(download(), IsDangerous()).WillRepeatedly(Return(true)); SimulatePromptAction(DownloadDangerPrompt::CANCEL); VerifyExpectations(true); @@ -255,10 +252,9 @@ // If the download is no longer dangerous (because it was accepted), the // dialog should DISMISS itself. SetUpExpectations(DownloadDangerPrompt::DISMISS, - content::DOWNLOAD_DANGER_TYPE_POTENTIALLY_UNWANTED, + download::DOWNLOAD_DANGER_TYPE_POTENTIALLY_UNWANTED, ClientDownloadResponse::POTENTIALLY_UNWANTED, - kDownloadResponseToken, - false); + kDownloadResponseToken, false); EXPECT_CALL(download(), IsDangerous()).WillRepeatedly(Return(false)); download().NotifyObserversDownloadUpdated(); VerifyExpectations(false); @@ -266,10 +262,9 @@ // If the download is in a terminal state then the dialog should DISMISS // itself. SetUpExpectations(DownloadDangerPrompt::DISMISS, - content::DOWNLOAD_DANGER_TYPE_DANGEROUS_HOST, + download::DOWNLOAD_DANGER_TYPE_DANGEROUS_HOST, ClientDownloadResponse::DANGEROUS_HOST, - kDownloadResponseToken, - false); + kDownloadResponseToken, false); EXPECT_CALL(download(), IsDangerous()).WillRepeatedly(Return(true)); EXPECT_CALL(download(), IsDone()).WillRepeatedly(Return(true)); download().NotifyObserversDownloadUpdated(); @@ -278,9 +273,8 @@ // If the download is dangerous and is not in a terminal state, don't dismiss // the dialog. SetUpExpectations(DownloadDangerPrompt::ACCEPT, - content::DOWNLOAD_DANGER_TYPE_DANGEROUS_CONTENT, - ClientDownloadResponse::DANGEROUS, - kDownloadResponseToken, + download::DOWNLOAD_DANGER_TYPE_DANGEROUS_CONTENT, + ClientDownloadResponse::DANGEROUS, kDownloadResponseToken, false); EXPECT_CALL(download(), IsDangerous()).WillRepeatedly(Return(true)); EXPECT_CALL(download(), IsDone()).WillRepeatedly(Return(false)); @@ -291,9 +285,8 @@ // If the download is not dangerous, no report will be sent. SetUpExpectations(DownloadDangerPrompt::ACCEPT, - content::DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS, - ClientDownloadResponse::SAFE, - kDownloadResponseToken, + download::DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS, + ClientDownloadResponse::SAFE, kDownloadResponseToken, false); SimulatePromptAction(DownloadDangerPrompt::ACCEPT); VerifyExpectations(false); @@ -301,9 +294,8 @@ // If the containing tab is closed, the dialog should DISMISS itself. OpenNewTab(); SetUpExpectations(DownloadDangerPrompt::DISMISS, - content::DOWNLOAD_DANGER_TYPE_DANGEROUS_URL, - ClientDownloadResponse::DANGEROUS, - kDownloadResponseToken, + download::DOWNLOAD_DANGER_TYPE_DANGEROUS_URL, + ClientDownloadResponse::DANGEROUS, kDownloadResponseToken, false); chrome::CloseTab(browser()); VerifyExpectations(false); @@ -313,9 +305,8 @@ // invoke the ACCEPT action, a report will be sent with type // DANGEROUS_DOWNLOAD_BY_API. SetUpExpectations(DownloadDangerPrompt::ACCEPT, - content::DOWNLOAD_DANGER_TYPE_DANGEROUS_URL, - ClientDownloadResponse::DANGEROUS, - kDownloadResponseToken, + download::DOWNLOAD_DANGER_TYPE_DANGEROUS_URL, + ClientDownloadResponse::DANGEROUS, kDownloadResponseToken, true); EXPECT_CALL(download(), IsDangerous()).WillRepeatedly(Return(true)); SimulatePromptAction(DownloadDangerPrompt::ACCEPT); @@ -326,10 +317,8 @@ // invoke the CANCEL action, a report will be sent with type // DANGEROUS_DOWNLOAD_BY_API. SetUpExpectations(DownloadDangerPrompt::CANCEL, - content::DOWNLOAD_DANGER_TYPE_UNCOMMON_CONTENT, - ClientDownloadResponse::UNCOMMON, - std::string(), - true); + download::DOWNLOAD_DANGER_TYPE_UNCOMMON_CONTENT, + ClientDownloadResponse::UNCOMMON, std::string(), true); EXPECT_CALL(download(), IsDangerous()).WillRepeatedly(Return(true)); SimulatePromptAction(DownloadDangerPrompt::CANCEL); VerifyExpectations(true); @@ -349,7 +338,7 @@ enum InvocationType { USER_INITIATED, FROM_DOWNLOAD_API }; DownloadDangerPromptBrowserTest() : download_url_(kTestDownloadUrl) {} - void RunTest(content::DownloadDangerType danger_type, + void RunTest(download::DownloadDangerType danger_type, InvocationType invocation_type) { danger_type_ = danger_type; invocation_type_ = invocation_type; @@ -381,7 +370,7 @@ const GURL download_url_; const base::FilePath empty_file_path_; - content::DownloadDangerType danger_type_; + download::DownloadDangerType danger_type_; InvocationType invocation_type_; content::MockDownloadItem download_; @@ -390,37 +379,37 @@ IN_PROC_BROWSER_TEST_F(DownloadDangerPromptBrowserTest, InvokeUi_DangerousFile) { - RunTest(content::DOWNLOAD_DANGER_TYPE_DANGEROUS_FILE, USER_INITIATED); + RunTest(download::DOWNLOAD_DANGER_TYPE_DANGEROUS_FILE, USER_INITIATED); } IN_PROC_BROWSER_TEST_F(DownloadDangerPromptBrowserTest, InvokeUi_DangerousFileFromApi) { - RunTest(content::DOWNLOAD_DANGER_TYPE_DANGEROUS_FILE, FROM_DOWNLOAD_API); + RunTest(download::DOWNLOAD_DANGER_TYPE_DANGEROUS_FILE, FROM_DOWNLOAD_API); } IN_PROC_BROWSER_TEST_F(DownloadDangerPromptBrowserTest, InvokeUi_DangerousUrl) { - RunTest(content::DOWNLOAD_DANGER_TYPE_DANGEROUS_URL, USER_INITIATED); + RunTest(download::DOWNLOAD_DANGER_TYPE_DANGEROUS_URL, USER_INITIATED); } IN_PROC_BROWSER_TEST_F(DownloadDangerPromptBrowserTest, InvokeUi_DangerousUrlFromApi) { - RunTest(content::DOWNLOAD_DANGER_TYPE_DANGEROUS_URL, FROM_DOWNLOAD_API); + RunTest(download::DOWNLOAD_DANGER_TYPE_DANGEROUS_URL, FROM_DOWNLOAD_API); } IN_PROC_BROWSER_TEST_F(DownloadDangerPromptBrowserTest, InvokeUi_UncommonContent) { - RunTest(content::DOWNLOAD_DANGER_TYPE_UNCOMMON_CONTENT, USER_INITIATED); + RunTest(download::DOWNLOAD_DANGER_TYPE_UNCOMMON_CONTENT, USER_INITIATED); } IN_PROC_BROWSER_TEST_F(DownloadDangerPromptBrowserTest, InvokeUi_UncommonContentFromApi) { - RunTest(content::DOWNLOAD_DANGER_TYPE_UNCOMMON_CONTENT, FROM_DOWNLOAD_API); + RunTest(download::DOWNLOAD_DANGER_TYPE_UNCOMMON_CONTENT, FROM_DOWNLOAD_API); } IN_PROC_BROWSER_TEST_F(DownloadDangerPromptBrowserTest, InvokeUi_PotentiallyUnwanted) { - RunTest(content::DOWNLOAD_DANGER_TYPE_POTENTIALLY_UNWANTED, USER_INITIATED); + RunTest(download::DOWNLOAD_DANGER_TYPE_POTENTIALLY_UNWANTED, USER_INITIATED); } IN_PROC_BROWSER_TEST_F(DownloadDangerPromptBrowserTest, InvokeUi_PotentiallyUnwantedFromApi) { - RunTest(content::DOWNLOAD_DANGER_TYPE_POTENTIALLY_UNWANTED, + RunTest(download::DOWNLOAD_DANGER_TYPE_POTENTIALLY_UNWANTED, FROM_DOWNLOAD_API); }
diff --git a/chrome/browser/download/download_history_unittest.cc b/chrome/browser/download/download_history_unittest.cc index 9946571..4d1b5b6 100644 --- a/chrome/browser/download/download_history_unittest.cc +++ b/chrome/browser/download/download_history_unittest.cc
@@ -347,7 +347,7 @@ info->total_bytes = 100; info->state = history::ToHistoryDownloadState(state); info->danger_type = history::ToHistoryDownloadDangerType( - content::DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS); + download::DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS); info->interrupt_reason = history::ToHistoryDownloadInterruptReason( content::DOWNLOAD_INTERRUPT_REASON_NONE); info->id = @@ -398,7 +398,7 @@ .WillRepeatedly(Return(info->total_bytes)); EXPECT_CALL(item(index), GetState()).WillRepeatedly(Return(state)); EXPECT_CALL(item(index), GetDangerType()) - .WillRepeatedly(Return(content::DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS)); + .WillRepeatedly(Return(download::DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS)); EXPECT_CALL(item(index), GetLastReason()) .WillRepeatedly(Return(content::DOWNLOAD_INTERRUPT_REASON_NONE)); EXPECT_CALL(item(index), GetOpened()).WillRepeatedly(Return(info->opened)); @@ -705,7 +705,7 @@ // danger_type EXPECT_CALL(item(0), GetDangerType()) - .WillRepeatedly(Return(content::DOWNLOAD_DANGER_TYPE_DANGEROUS_CONTENT)); + .WillRepeatedly(Return(download::DOWNLOAD_DANGER_TYPE_DANGEROUS_CONTENT)); info.danger_type = history::DownloadDangerType::DANGEROUS_CONTENT; item(0).NotifyObserversDownloadUpdated(); ExpectDownloadUpdated(info, false);
diff --git a/chrome/browser/download/download_item_model.cc b/chrome/browser/download/download_item_model.cc index 0cc6f54..03a611ce 100644 --- a/chrome/browser/download/download_item_model.cc +++ b/chrome/browser/download/download_item_model.cc
@@ -24,7 +24,7 @@ #include "chrome/common/safe_browsing/download_file_types.pb.h" #include "chrome/grit/chromium_strings.h" #include "chrome/grit/generated_resources.h" -#include "content/public/browser/download_danger_type.h" +#include "components/download/public/common/download_danger_type.h" #include "content/public/browser/download_interrupt_reasons.h" #include "content/public/browser/download_item.h" #include "net/base/mime_util.h" @@ -412,10 +412,10 @@ gfx::ElideFilename(download_->GetFileNameToReportUser(), font_list, base_width, gfx::Typesetter::BROWSER); switch (download_->GetDangerType()) { - case content::DOWNLOAD_DANGER_TYPE_DANGEROUS_URL: { + case download::DOWNLOAD_DANGER_TYPE_DANGEROUS_URL: { return l10n_util::GetStringUTF16(IDS_PROMPT_MALICIOUS_DOWNLOAD_URL); } - case content::DOWNLOAD_DANGER_TYPE_DANGEROUS_FILE: { + case download::DOWNLOAD_DANGER_TYPE_DANGEROUS_FILE: { if (download_crx_util::IsExtensionDownload(*download_)) { return l10n_util::GetStringUTF16( IDS_PROMPT_DANGEROUS_DOWNLOAD_EXTENSION); @@ -424,23 +424,23 @@ elided_filename); } } - case content::DOWNLOAD_DANGER_TYPE_DANGEROUS_CONTENT: - case content::DOWNLOAD_DANGER_TYPE_DANGEROUS_HOST: { + case download::DOWNLOAD_DANGER_TYPE_DANGEROUS_CONTENT: + case download::DOWNLOAD_DANGER_TYPE_DANGEROUS_HOST: { return l10n_util::GetStringFUTF16(IDS_PROMPT_MALICIOUS_DOWNLOAD_CONTENT, elided_filename); } - case content::DOWNLOAD_DANGER_TYPE_UNCOMMON_CONTENT: { + case download::DOWNLOAD_DANGER_TYPE_UNCOMMON_CONTENT: { return l10n_util::GetStringFUTF16(IDS_PROMPT_UNCOMMON_DOWNLOAD_CONTENT, elided_filename); } - case content::DOWNLOAD_DANGER_TYPE_POTENTIALLY_UNWANTED: { + case download::DOWNLOAD_DANGER_TYPE_POTENTIALLY_UNWANTED: { return l10n_util::GetStringFUTF16( IDS_PROMPT_DOWNLOAD_CHANGES_SETTINGS, elided_filename); } - case content::DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS: - case content::DOWNLOAD_DANGER_TYPE_MAYBE_DANGEROUS_CONTENT: - case content::DOWNLOAD_DANGER_TYPE_USER_VALIDATED: - case content::DOWNLOAD_DANGER_TYPE_MAX: { + case download::DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS: + case download::DOWNLOAD_DANGER_TYPE_MAYBE_DANGEROUS_CONTENT: + case download::DOWNLOAD_DANGER_TYPE_USER_VALIDATED: + case download::DOWNLOAD_DANGER_TYPE_MAX: { break; } } @@ -452,7 +452,7 @@ // Should only be called if IsDangerous() DCHECK(IsDangerous()); if (download_->GetDangerType() == - content::DOWNLOAD_DANGER_TYPE_DANGEROUS_FILE && + download::DOWNLOAD_DANGER_TYPE_DANGEROUS_FILE && download_crx_util::IsExtensionDownload(*download_)) { return l10n_util::GetStringUTF16(IDS_CONTINUE_EXTENSION_DOWNLOAD); } else { @@ -484,21 +484,21 @@ if (!IsDangerous()) return false; switch (download_->GetDangerType()) { - case content::DOWNLOAD_DANGER_TYPE_DANGEROUS_URL: - case content::DOWNLOAD_DANGER_TYPE_DANGEROUS_CONTENT: - case content::DOWNLOAD_DANGER_TYPE_UNCOMMON_CONTENT: - case content::DOWNLOAD_DANGER_TYPE_DANGEROUS_HOST: - case content::DOWNLOAD_DANGER_TYPE_POTENTIALLY_UNWANTED: + case download::DOWNLOAD_DANGER_TYPE_DANGEROUS_URL: + case download::DOWNLOAD_DANGER_TYPE_DANGEROUS_CONTENT: + case download::DOWNLOAD_DANGER_TYPE_UNCOMMON_CONTENT: + case download::DOWNLOAD_DANGER_TYPE_DANGEROUS_HOST: + case download::DOWNLOAD_DANGER_TYPE_POTENTIALLY_UNWANTED: return true; - case content::DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS: - case content::DOWNLOAD_DANGER_TYPE_MAYBE_DANGEROUS_CONTENT: - case content::DOWNLOAD_DANGER_TYPE_USER_VALIDATED: - case content::DOWNLOAD_DANGER_TYPE_MAX: + case download::DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS: + case download::DOWNLOAD_DANGER_TYPE_MAYBE_DANGEROUS_CONTENT: + case download::DOWNLOAD_DANGER_TYPE_USER_VALIDATED: + case download::DOWNLOAD_DANGER_TYPE_MAX: // We shouldn't get any of these due to the IsDangerous() test above. NOTREACHED(); FALLTHROUGH; - case content::DOWNLOAD_DANGER_TYPE_DANGEROUS_FILE: + case download::DOWNLOAD_DANGER_TYPE_DANGEROUS_FILE: return false; } NOTREACHED(); @@ -511,21 +511,21 @@ if (!MightBeMalicious()) return false; switch (download_->GetDangerType()) { - case content::DOWNLOAD_DANGER_TYPE_DANGEROUS_URL: - case content::DOWNLOAD_DANGER_TYPE_DANGEROUS_CONTENT: - case content::DOWNLOAD_DANGER_TYPE_DANGEROUS_HOST: - case content::DOWNLOAD_DANGER_TYPE_POTENTIALLY_UNWANTED: + case download::DOWNLOAD_DANGER_TYPE_DANGEROUS_URL: + case download::DOWNLOAD_DANGER_TYPE_DANGEROUS_CONTENT: + case download::DOWNLOAD_DANGER_TYPE_DANGEROUS_HOST: + case download::DOWNLOAD_DANGER_TYPE_POTENTIALLY_UNWANTED: return true; - case content::DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS: - case content::DOWNLOAD_DANGER_TYPE_MAYBE_DANGEROUS_CONTENT: - case content::DOWNLOAD_DANGER_TYPE_USER_VALIDATED: - case content::DOWNLOAD_DANGER_TYPE_MAX: - case content::DOWNLOAD_DANGER_TYPE_DANGEROUS_FILE: + case download::DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS: + case download::DOWNLOAD_DANGER_TYPE_MAYBE_DANGEROUS_CONTENT: + case download::DOWNLOAD_DANGER_TYPE_USER_VALIDATED: + case download::DOWNLOAD_DANGER_TYPE_MAX: + case download::DOWNLOAD_DANGER_TYPE_DANGEROUS_FILE: // We shouldn't get any of these due to the MightBeMalicious() test above. NOTREACHED(); FALLTHROUGH; - case content::DOWNLOAD_DANGER_TYPE_UNCOMMON_CONTENT: + case download::DOWNLOAD_DANGER_TYPE_UNCOMMON_CONTENT: return false; } NOTREACHED();
diff --git a/chrome/browser/download/download_query.cc b/chrome/browser/download/download_query.cc index 372baa9..559997a 100644 --- a/chrome/browser/download/download_query.cc +++ b/chrome/browser/download/download_query.cc
@@ -30,7 +30,7 @@ #include "third_party/re2/src/re2/re2.h" #include "url/gurl.h" -using content::DownloadDangerType; +using download::DownloadDangerType; using content::DownloadItem; namespace { @@ -96,7 +96,7 @@ bool GetDangerAccepted(const DownloadItem& item) { return (item.GetDangerType() == - content::DOWNLOAD_DANGER_TYPE_USER_VALIDATED); + download::DOWNLOAD_DANGER_TYPE_USER_VALIDATED); } bool GetExists(const DownloadItem& item) {
diff --git a/chrome/browser/download/download_query.h b/chrome/browser/download/download_query.h index 9d9327c..f965c89 100644 --- a/chrome/browser/download/download_query.h +++ b/chrome/browser/download/download_query.h
@@ -113,7 +113,7 @@ // filter out all items. bool AddFilter(const FilterCallback& filter); bool AddFilter(FilterType type, const base::Value& value); - void AddFilter(content::DownloadDangerType danger); + void AddFilter(download::DownloadDangerType danger); void AddFilter(content::DownloadItem::DownloadState state); // Adds a new sorter of type |type| with direction |direction|. After
diff --git a/chrome/browser/download/download_query_unittest.cc b/chrome/browser/download/download_query_unittest.cc index 9c0a1821..9560e79 100644 --- a/chrome/browser/download/download_query_unittest.cc +++ b/chrome/browser/download/download_query_unittest.cc
@@ -462,20 +462,20 @@ TEST_F(DownloadQueryTest, DownloadQueryTest_FilterDangerAccepted) { CreateMocks(2); - EXPECT_CALL(mock(0), GetDangerType()).WillRepeatedly(Return( - content::DOWNLOAD_DANGER_TYPE_USER_VALIDATED)); - EXPECT_CALL(mock(1), GetDangerType()).WillRepeatedly(Return( - content::DOWNLOAD_DANGER_TYPE_DANGEROUS_FILE)); + EXPECT_CALL(mock(0), GetDangerType()) + .WillRepeatedly(Return(download::DOWNLOAD_DANGER_TYPE_USER_VALIDATED)); + EXPECT_CALL(mock(1), GetDangerType()) + .WillRepeatedly(Return(download::DOWNLOAD_DANGER_TYPE_DANGEROUS_FILE)); AddFilter(DownloadQuery::FILTER_DANGER_ACCEPTED, true); ExpectStandardFilterResults(); } TEST_F(DownloadQueryTest, DownloadQueryTest_SortDangerAccepted) { CreateMocks(2); - EXPECT_CALL(mock(0), GetDangerType()).WillRepeatedly(Return( - content::DOWNLOAD_DANGER_TYPE_USER_VALIDATED)); - EXPECT_CALL(mock(1), GetDangerType()).WillRepeatedly(Return( - content::DOWNLOAD_DANGER_TYPE_DANGEROUS_FILE)); + EXPECT_CALL(mock(0), GetDangerType()) + .WillRepeatedly(Return(download::DOWNLOAD_DANGER_TYPE_USER_VALIDATED)); + EXPECT_CALL(mock(1), GetDangerType()) + .WillRepeatedly(Return(download::DOWNLOAD_DANGER_TYPE_DANGEROUS_FILE)); query()->AddSorter(DownloadQuery::SORT_DANGER_ACCEPTED, DownloadQuery::ASCENDING); ExpectSortInverted(); @@ -739,20 +739,20 @@ TEST_F(DownloadQueryTest, DownloadQueryTest_FilterDanger) { CreateMocks(2); - EXPECT_CALL(mock(0), GetDangerType()).WillRepeatedly(Return( - content::DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS)); - EXPECT_CALL(mock(1), GetDangerType()).WillRepeatedly(Return( - content::DOWNLOAD_DANGER_TYPE_DANGEROUS_FILE)); - query()->AddFilter(content::DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS); + EXPECT_CALL(mock(0), GetDangerType()) + .WillRepeatedly(Return(download::DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS)); + EXPECT_CALL(mock(1), GetDangerType()) + .WillRepeatedly(Return(download::DOWNLOAD_DANGER_TYPE_DANGEROUS_FILE)); + query()->AddFilter(download::DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS); ExpectStandardFilterResults(); } TEST_F(DownloadQueryTest, DownloadQueryTest_SortDanger) { CreateMocks(2); - EXPECT_CALL(mock(0), GetDangerType()).WillRepeatedly(Return( - content::DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS)); - EXPECT_CALL(mock(1), GetDangerType()).WillRepeatedly(Return( - content::DOWNLOAD_DANGER_TYPE_DANGEROUS_FILE)); + EXPECT_CALL(mock(0), GetDangerType()) + .WillRepeatedly(Return(download::DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS)); + EXPECT_CALL(mock(1), GetDangerType()) + .WillRepeatedly(Return(download::DOWNLOAD_DANGER_TYPE_DANGEROUS_FILE)); query()->AddSorter(DownloadQuery::SORT_DANGER, DownloadQuery::DESCENDING); ExpectSortInverted(); }
diff --git a/chrome/browser/download/download_stats.cc b/chrome/browser/download/download_stats.cc index 7dc513ec..5c9a15b 100644 --- a/chrome/browser/download/download_stats.cc +++ b/chrome/browser/download/download_stats.cc
@@ -32,17 +32,15 @@ } void RecordDangerousDownloadWarningShown( - content::DownloadDangerType danger_type) { - UMA_HISTOGRAM_ENUMERATION("Download.DownloadWarningShown", - danger_type, - content::DOWNLOAD_DANGER_TYPE_MAX); + download::DownloadDangerType danger_type) { + UMA_HISTOGRAM_ENUMERATION("Download.DownloadWarningShown", danger_type, + download::DOWNLOAD_DANGER_TYPE_MAX); } void RecordOpenedDangerousConfirmDialog( - content::DownloadDangerType danger_type) { + download::DownloadDangerType danger_type) { UMA_HISTOGRAM_ENUMERATION("Download.ShowDangerousDownloadConfirmationPrompt", - danger_type, - content::DOWNLOAD_DANGER_TYPE_MAX); + danger_type, download::DOWNLOAD_DANGER_TYPE_MAX); } void RecordDownloadOpenMethod(ChromeDownloadOpenMethod open_method) {
diff --git a/chrome/browser/download/download_stats.h b/chrome/browser/download/download_stats.h index e8bb996..1c422ebe 100644 --- a/chrome/browser/download/download_stats.h +++ b/chrome/browser/download/download_stats.h
@@ -6,7 +6,7 @@ #define CHROME_BROWSER_DOWNLOAD_DOWNLOAD_STATS_H_ #include "chrome/browser/download/download_path_reservation_tracker.h" -#include "content/public/browser/download_danger_type.h" +#include "components/download/public/common/download_danger_type.h" // Record the total number of items and the number of in-progress items showing // in the shelf when it closes. Set |autoclose| to true when the shelf is @@ -100,11 +100,11 @@ // Record that a download warning was shown. void RecordDangerousDownloadWarningShown( - content::DownloadDangerType danger_type); + download::DownloadDangerType danger_type); // Record that the user opened the confirmation dialog for a dangerous download. void RecordOpenedDangerousConfirmDialog( - content::DownloadDangerType danger_type); + download::DownloadDangerType danger_type); // Record how a download was opened. void RecordDownloadOpenMethod(ChromeDownloadOpenMethod open_method);
diff --git a/chrome/browser/download/download_target_determiner.cc b/chrome/browser/download/download_target_determiner.cc index 4f4dadd..e464771 100644 --- a/chrome/browser/download/download_target_determiner.cc +++ b/chrome/browser/download/download_target_determiner.cc
@@ -653,7 +653,7 @@ next_state_ = STATE_CHECK_VISITED_REFERRER_BEFORE; // If user has validated a dangerous download, don't check. - if (danger_type_ == content::DOWNLOAD_DANGER_TYPE_USER_VALIDATED) + if (danger_type_ == download::DOWNLOAD_DANGER_TYPE_USER_VALIDATED) return CONTINUE; delegate_->CheckDownloadUrl( @@ -665,7 +665,7 @@ } void DownloadTargetDeterminer::CheckDownloadUrlDone( - content::DownloadDangerType danger_type) { + download::DownloadDangerType danger_type) { DCHECK_CURRENTLY_ON(BrowserThread::UI); DVLOG(20) << "URL Check Result:" << danger_type; DCHECK_EQ(STATE_CHECK_VISITED_REFERRER_BEFORE, next_state_); @@ -680,8 +680,8 @@ // Checking if there are prior visits to the referrer is only necessary if the // danger level of the download depends on the file type. - if (danger_type_ != content::DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS && - danger_type_ != content::DOWNLOAD_DANGER_TYPE_MAYBE_DANGEROUS_CONTENT) + if (danger_type_ != download::DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS && + danger_type_ != download::DOWNLOAD_DANGER_TYPE_MAYBE_DANGEROUS_CONTENT) return CONTINUE; // First determine the danger level assuming that the user doesn't have any @@ -718,8 +718,8 @@ // If the danger level doesn't depend on having visited the refererrer URL or // if original profile doesn't have a HistoryService or the referrer url is // invalid, then assume the referrer has not been visited before. - if (danger_type_ == content::DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS) - danger_type_ = content::DOWNLOAD_DANGER_TYPE_DANGEROUS_FILE; + if (danger_type_ == download::DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS) + danger_type_ = download::DOWNLOAD_DANGER_TYPE_DANGEROUS_FILE; return CONTINUE; } @@ -730,8 +730,8 @@ danger_level_ = GetDangerLevel( visited_referrer_before ? VISITED_REFERRER : NO_VISITS_TO_REFERRER); if (danger_level_ != DownloadFileType::NOT_DANGEROUS && - danger_type_ == content::DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS) - danger_type_ = content::DOWNLOAD_DANGER_TYPE_DANGEROUS_FILE; + danger_type_ == download::DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS) + danger_type_ = download::DOWNLOAD_DANGER_TYPE_DANGEROUS_FILE; DoLoop(); } @@ -763,7 +763,7 @@ // target path. In practice the temporary download file that was created prior // to download filename determination is already named // download_->GetForcedFilePath(). - if (danger_type_ == content::DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS && + if (danger_type_ == download::DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS && !download_->GetForcedFilePath().empty()) { DCHECK_EQ(download_->GetForcedFilePath().value(), local_path_.value()); intermediate_path_ = local_path_; @@ -771,14 +771,14 @@ } // Transient downloads don't need to be renamed to intermediate file. - if (danger_type_ == content::DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS && + if (danger_type_ == download::DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS && download_->IsTransient()) { intermediate_path_ = local_path_; return COMPLETE; } // Other safe downloads get a .crdownload suffix for their intermediate name. - if (danger_type_ == content::DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS) { + if (danger_type_ == download::DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS) { intermediate_path_ = GetCrDownloadPath(local_path_); return COMPLETE; } @@ -789,7 +789,7 @@ // intermediate file should already be in the correct form. if (is_resumption_ && !download_->GetFullPath().empty() && local_path_.DirName() == download_->GetFullPath().DirName()) { - DCHECK_NE(content::DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS, + DCHECK_NE(download::DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS, download_->GetDangerType()); DCHECK_EQ(kCrdownloadSuffix, download_->GetFullPath().Extension()); intermediate_path_ = download_->GetFullPath();
diff --git a/chrome/browser/download/download_target_determiner.h b/chrome/browser/download/download_target_determiner.h index dbc42ac..2032ee0 100644 --- a/chrome/browser/download/download_target_determiner.h +++ b/chrome/browser/download/download_target_determiner.h
@@ -18,7 +18,7 @@ #include "chrome/browser/download/download_target_determiner_delegate.h" #include "chrome/browser/download/download_target_info.h" #include "chrome/common/safe_browsing/download_file_types.pb.h" -#include "content/public/browser/download_danger_type.h" +#include "components/download/public/common/download_danger_type.h" #include "content/public/browser/download_item.h" #include "content/public/browser/download_manager_delegate.h" #include "ppapi/features/features.h" @@ -249,7 +249,7 @@ // Callback invoked after the delegate has checked the download URL. Sets the // danger type of the download to |danger_type|. - void CheckDownloadUrlDone(content::DownloadDangerType danger_type); + void CheckDownloadUrlDone(download::DownloadDangerType danger_type); // Checks if the user has visited the referrer URL of the download prior to // today. The actual check is only performed if it would be needed to @@ -317,7 +317,7 @@ bool should_notify_extensions_; bool create_target_directory_; DownloadPathReservationTracker::FilenameConflictAction conflict_action_; - content::DownloadDangerType danger_type_; + download::DownloadDangerType danger_type_; safe_browsing::DownloadFileType::DangerLevel danger_level_; base::FilePath virtual_path_; base::FilePath local_path_;
diff --git a/chrome/browser/download/download_target_determiner_delegate.h b/chrome/browser/download/download_target_determiner_delegate.h index a7ae1207..bfab53c1 100644 --- a/chrome/browser/download/download_target_determiner_delegate.h +++ b/chrome/browser/download/download_target_determiner_delegate.h
@@ -11,7 +11,7 @@ #include "chrome/browser/download/download_confirmation_reason.h" #include "chrome/browser/download/download_confirmation_result.h" #include "chrome/browser/download/download_path_reservation_tracker.h" -#include "content/public/browser/download_danger_type.h" +#include "components/download/public/common/download_danger_type.h" namespace base { class FilePath; @@ -58,8 +58,8 @@ // Callback to be invoked after CheckDownloadUrl() completes. The parameter to // the callback should indicate the danger type of the download based on the // results of the URL check. - typedef base::Callback<void(content::DownloadDangerType danger_type)> - CheckDownloadUrlCallback; + typedef base::Callback<void(download::DownloadDangerType danger_type)> + CheckDownloadUrlCallback; // Callback to be invoked after GetFileMimeType() completes. The parameter // should be the MIME type of the requested file. If no MIME type can be
diff --git a/chrome/browser/download/download_target_determiner_unittest.cc b/chrome/browser/download/download_target_determiner_unittest.cc index 4d1592d..edbc847 100644 --- a/chrome/browser/download/download_target_determiner_unittest.cc +++ b/chrome/browser/download/download_target_determiner_unittest.cc
@@ -145,7 +145,7 @@ TestCaseType test_type; // Expected danger type. Verified at the end of target determination. - content::DownloadDangerType expected_danger_type; + download::DownloadDangerType expected_danger_type; // Expected danger level. Verified at the end of target determination. DownloadFileType::DangerLevel expected_danger_level; @@ -199,7 +199,7 @@ void SetupDefaults() { ON_CALL(*this, CheckDownloadUrl(_, _, _)) .WillByDefault(WithArg<2>( - ScheduleCallback(content::DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS))); + ScheduleCallback(download::DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS))); ON_CALL(*this, NotifyExtensions(_, _, _)) .WillByDefault(WithArg<2>( ScheduleCallback2(base::FilePath(), @@ -348,7 +348,7 @@ ON_CALL(*item, GetBrowserContext()) .WillByDefault(Return(profile())); ON_CALL(*item, GetDangerType()) - .WillByDefault(Return(content::DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS)); + .WillByDefault(Return(download::DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS)); ON_CALL(*item, GetForcedFilePath()) .WillByDefault(ReturnRefOfCopy(forced_file_path)); ON_CALL(*item, GetFullPath()) @@ -580,7 +580,7 @@ TEST_F(DownloadTargetDeterminerTest, Basic) { const DownloadTestCase kBasicTestCases[] = { {// Automatic Safe - AUTOMATIC, content::DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS, + AUTOMATIC, download::DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS, DownloadFileType::NOT_DANGEROUS, "http://example.com/foo.txt", "text/plain", FILE_PATH_LITERAL(""), @@ -589,7 +589,7 @@ EXPECT_CRDOWNLOAD}, {// Save_As Safe - SAVE_AS, content::DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS, + SAVE_AS, download::DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS, DownloadFileType::NOT_DANGEROUS, "http://example.com/foo.txt", "text/plain", FILE_PATH_LITERAL(""), @@ -598,7 +598,7 @@ EXPECT_CRDOWNLOAD}, {// Automatic Dangerous - AUTOMATIC, content::DOWNLOAD_DANGER_TYPE_DANGEROUS_FILE, + AUTOMATIC, download::DOWNLOAD_DANGER_TYPE_DANGEROUS_FILE, DownloadFileType::ALLOW_ON_USER_GESTURE, "http://example.com/foo.kindabad", "", FILE_PATH_LITERAL(""), @@ -608,7 +608,7 @@ EXPECT_UNCONFIRMED}, {// Forced Safe - FORCED, content::DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS, + FORCED, download::DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS, DownloadFileType::NOT_DANGEROUS, "http://example.com/foo.txt", "", FILE_PATH_LITERAL("forced-foo.txt"), @@ -629,7 +629,7 @@ TEST_F(DownloadTargetDeterminerTest, CancelSaveAs) { const DownloadTestCase kCancelSaveAsTestCases[] = { {// 0: Save_As Safe, Cancelled. - SAVE_AS, content::DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS, + SAVE_AS, download::DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS, DownloadFileType::NOT_DANGEROUS, "http://example.com/foo.txt", "text/plain", FILE_PATH_LITERAL(""), @@ -648,7 +648,7 @@ TEST_F(DownloadTargetDeterminerTest, DangerousUrl) { const DownloadTestCase kSafeBrowsingTestCases[] = { {// 0: Automatic Dangerous URL - AUTOMATIC, content::DOWNLOAD_DANGER_TYPE_DANGEROUS_URL, + AUTOMATIC, download::DOWNLOAD_DANGER_TYPE_DANGEROUS_URL, DownloadFileType::NOT_DANGEROUS, "http://phishing.example.com/foo.txt", "", FILE_PATH_LITERAL(""), @@ -657,7 +657,7 @@ EXPECT_UNCONFIRMED}, {// 1: Save As Dangerous URL - SAVE_AS, content::DOWNLOAD_DANGER_TYPE_DANGEROUS_URL, + SAVE_AS, download::DOWNLOAD_DANGER_TYPE_DANGEROUS_URL, DownloadFileType::NOT_DANGEROUS, "http://phishing.example.com/foo.txt", "", FILE_PATH_LITERAL(""), @@ -666,7 +666,7 @@ EXPECT_UNCONFIRMED}, {// 2: Forced Dangerous URL - FORCED, content::DOWNLOAD_DANGER_TYPE_DANGEROUS_URL, + FORCED, download::DOWNLOAD_DANGER_TYPE_DANGEROUS_URL, DownloadFileType::NOT_DANGEROUS, "http://phishing.example.com/foo.txt", "", FILE_PATH_LITERAL("forced-foo.txt"), @@ -677,7 +677,7 @@ {// 3: Automatic Dangerous URL + Dangerous file. Dangerous URL takes // precedence. - AUTOMATIC, content::DOWNLOAD_DANGER_TYPE_DANGEROUS_URL, + AUTOMATIC, download::DOWNLOAD_DANGER_TYPE_DANGEROUS_URL, DownloadFileType::NOT_DANGEROUS, "http://phishing.example.com/foo.html", "", FILE_PATH_LITERAL(""), @@ -687,7 +687,7 @@ EXPECT_UNCONFIRMED}, {// 4: Save As Dangerous URL + Dangerous file - SAVE_AS, content::DOWNLOAD_DANGER_TYPE_DANGEROUS_URL, + SAVE_AS, download::DOWNLOAD_DANGER_TYPE_DANGEROUS_URL, DownloadFileType::NOT_DANGEROUS, "http://phishing.example.com/foo.html", "", FILE_PATH_LITERAL(""), @@ -696,7 +696,7 @@ EXPECT_UNCONFIRMED}, {// 5: Forced Dangerous URL + Dangerous file - FORCED, content::DOWNLOAD_DANGER_TYPE_DANGEROUS_URL, + FORCED, download::DOWNLOAD_DANGER_TYPE_DANGEROUS_URL, DownloadFileType::NOT_DANGEROUS, "http://phishing.example.com/foo.html", "", FILE_PATH_LITERAL("forced-foo.html"), @@ -707,8 +707,8 @@ }; ON_CALL(*delegate(), CheckDownloadUrl(_, _, _)) - .WillByDefault(WithArg<2>(ScheduleCallback( - content::DOWNLOAD_DANGER_TYPE_DANGEROUS_URL))); + .WillByDefault(WithArg<2>( + ScheduleCallback(download::DOWNLOAD_DANGER_TYPE_DANGEROUS_URL))); RunTestCasesWithActiveItem(kSafeBrowsingTestCases, arraysize(kSafeBrowsingTestCases)); } @@ -718,7 +718,7 @@ TEST_F(DownloadTargetDeterminerTest, MaybeDangerousContent) { const DownloadTestCase kSafeBrowsingTestCases[] = { {// 0: Automatic Maybe dangerous content - AUTOMATIC, content::DOWNLOAD_DANGER_TYPE_MAYBE_DANGEROUS_CONTENT, + AUTOMATIC, download::DOWNLOAD_DANGER_TYPE_MAYBE_DANGEROUS_CONTENT, DownloadFileType::ALLOW_ON_USER_GESTURE, "http://phishing.example.com/foo.kindabad", "", FILE_PATH_LITERAL(""), @@ -726,7 +726,7 @@ DownloadItem::TARGET_DISPOSITION_OVERWRITE, EXPECT_UNCONFIRMED}, {// 1: Automatic Maybe dangerous content with DANGEROUS type. - AUTOMATIC, content::DOWNLOAD_DANGER_TYPE_MAYBE_DANGEROUS_CONTENT, + AUTOMATIC, download::DOWNLOAD_DANGER_TYPE_MAYBE_DANGEROUS_CONTENT, DownloadFileType::DANGEROUS, "http://phishing.example.com/foo.bad", "", FILE_PATH_LITERAL(""), @@ -734,7 +734,7 @@ EXPECT_UNCONFIRMED}, {// 2: Save As Maybe dangerous content - SAVE_AS, content::DOWNLOAD_DANGER_TYPE_MAYBE_DANGEROUS_CONTENT, + SAVE_AS, download::DOWNLOAD_DANGER_TYPE_MAYBE_DANGEROUS_CONTENT, DownloadFileType::NOT_DANGEROUS, "http://phishing.example.com/foo.kindabad", "", FILE_PATH_LITERAL(""), @@ -744,7 +744,7 @@ EXPECT_UNCONFIRMED}, {// 3: Forced Maybe dangerous content - FORCED, content::DOWNLOAD_DANGER_TYPE_MAYBE_DANGEROUS_CONTENT, + FORCED, download::DOWNLOAD_DANGER_TYPE_MAYBE_DANGEROUS_CONTENT, DownloadFileType::NOT_DANGEROUS, "http://phishing.example.com/foo.kindabad", "", FILE_PATH_LITERAL("forced-foo.kindabad"), @@ -764,7 +764,7 @@ ON_CALL(*delegate(), CheckDownloadUrl(_, _, _)) .WillByDefault(WithArg<2>(ScheduleCallback( - content::DOWNLOAD_DANGER_TYPE_MAYBE_DANGEROUS_CONTENT))); + download::DOWNLOAD_DANGER_TYPE_MAYBE_DANGEROUS_CONTENT))); RunTestCasesWithActiveItem(kSafeBrowsingTestCases, arraysize(kSafeBrowsingTestCases)); } @@ -774,7 +774,7 @@ const DownloadTestCase kLastSavePathTestCasesPre[] = { {// 0: If the last save path is empty, then the default download directory // should be used. - SAVE_AS, content::DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS, + SAVE_AS, download::DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS, DownloadFileType::NOT_DANGEROUS, "http://example.com/foo.txt", "text/plain", FILE_PATH_LITERAL(""), @@ -787,7 +787,7 @@ const DownloadTestCase kLastSavePathTestCasesPost[] = { {// 0: This test case is run with the last download directory set to // '<test_download_dir()>/foo'. - SAVE_AS, content::DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS, + SAVE_AS, download::DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS, DownloadFileType::NOT_DANGEROUS, "http://example.com/foo.txt", "text/plain", FILE_PATH_LITERAL(""), @@ -798,7 +798,7 @@ {// 1: Start an automatic download. This should be saved to the user's // default download directory and not the last used Save As directory. - AUTOMATIC, content::DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS, + AUTOMATIC, download::DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS, DownloadFileType::NOT_DANGEROUS, "http://example.com/foo.txt", "text/plain", FILE_PATH_LITERAL(""), @@ -810,7 +810,7 @@ // This test case is run with the last save path set to a non-empty virtual // directory. const DownloadTestCase kLastSavePathTestCasesVirtual[] = { - {SAVE_AS, content::DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS, + {SAVE_AS, download::DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS, DownloadFileType::NOT_DANGEROUS, "http://example.com/foo.txt", "text/plain", FILE_PATH_LITERAL(""), @@ -873,7 +873,7 @@ SCOPED_TRACE(testing::Message() << "Automatic Safe Download"); const DownloadTestCase kAutomaticDownloadToVirtualDir = { AUTOMATIC, - content::DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS, + download::DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS, DownloadFileType::NOT_DANGEROUS, "http://example.com/foo.txt", "text/plain", @@ -893,7 +893,7 @@ SCOPED_TRACE(testing::Message() << "Save As to virtual directory"); const DownloadTestCase kSaveAsToVirtualDir = { SAVE_AS, - content::DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS, + download::DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS, DownloadFileType::NOT_DANGEROUS, "http://example.com/bar.txt", "text/plain", @@ -920,7 +920,7 @@ SCOPED_TRACE(testing::Message() << "Save As to local directory"); const DownloadTestCase kSaveAsToLocalDir = { SAVE_AS, - content::DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS, + download::DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS, DownloadFileType::NOT_DANGEROUS, "http://example.com/bar.txt", "text/plain", @@ -943,7 +943,7 @@ SCOPED_TRACE(testing::Message() << "Forced safe download"); const DownloadTestCase kForcedSafe = { FORCED, - content::DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS, + download::DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS, DownloadFileType::NOT_DANGEROUS, "http://example.com/foo.txt", "", @@ -962,7 +962,7 @@ TEST_F(DownloadTargetDeterminerTest, InactiveDownload) { const DownloadTestCase kBaseTestCase = { AUTOMATIC, - content::DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS, + download::DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS, DownloadFileType::NOT_DANGEROUS, "http://example.com/foo.txt", "text/plain", @@ -1004,7 +1004,7 @@ // 0: Automatic download. Since the reservation fails, the disposition of // the target is to prompt, but the returned path is used. AUTOMATIC, - content::DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS, + download::DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS, DownloadFileType::NOT_DANGEROUS, "http://example.com/foo.txt", "text/plain", @@ -1058,7 +1058,7 @@ TEST_F(DownloadTargetDeterminerTest, LocalPathFailed) { const DownloadTestCase kLocalPathFailedCases[] = { {// 0: Automatic download. - AUTOMATIC, content::DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS, + AUTOMATIC, download::DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS, DownloadFileType::NOT_DANGEROUS, "http://example.com/foo.txt", "text/plain", FILE_PATH_LITERAL(""), @@ -1085,7 +1085,7 @@ // http://visited.example.com/ is added to the history as a visit that // happened prior to today. {// 0: Safe download due to visiting referrer before. - AUTOMATIC, content::DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS, + AUTOMATIC, download::DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS, DownloadFileType::NOT_DANGEROUS, "http://visited.example.com/foo.kindabad", "application/xml", FILE_PATH_LITERAL(""), @@ -1096,7 +1096,7 @@ EXPECT_CRDOWNLOAD}, {// 1: Dangerous due to not having visited referrer before. - AUTOMATIC, content::DOWNLOAD_DANGER_TYPE_DANGEROUS_FILE, + AUTOMATIC, download::DOWNLOAD_DANGER_TYPE_DANGEROUS_FILE, DownloadFileType::ALLOW_ON_USER_GESTURE, "http://not-visited.example.com/foo.kindabad", "application/xml", FILE_PATH_LITERAL(""), @@ -1107,7 +1107,7 @@ EXPECT_UNCONFIRMED}, {// 2: Safe because the user is being prompted. - SAVE_AS, content::DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS, + SAVE_AS, download::DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS, DownloadFileType::NOT_DANGEROUS, "http://not-visited.example.com/foo.kindabad", "application/xml", FILE_PATH_LITERAL(""), @@ -1118,7 +1118,7 @@ EXPECT_CRDOWNLOAD}, {// 3: Safe because of forced path. - FORCED, content::DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS, + FORCED, download::DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS, DownloadFileType::NOT_DANGEROUS, "http://not-visited.example.com/foo.kindabad", "application/xml", FILE_PATH_LITERAL("foo.kindabad"), @@ -1156,7 +1156,7 @@ TEST_F(DownloadTargetDeterminerTest, TransitionType) { const DownloadTestCase kSafeFile = { AUTOMATIC, - content::DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS, + download::DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS, DownloadFileType::NOT_DANGEROUS, "http://example.com/foo.txt", "text/plain", @@ -1169,7 +1169,7 @@ const DownloadTestCase kAllowOnUserGesture = { AUTOMATIC, - content::DOWNLOAD_DANGER_TYPE_DANGEROUS_FILE, + download::DOWNLOAD_DANGER_TYPE_DANGEROUS_FILE, DownloadFileType::ALLOW_ON_USER_GESTURE, "http://example.com/foo.kindabad", "application/octet-stream", @@ -1182,7 +1182,7 @@ const DownloadTestCase kDangerousFile = { AUTOMATIC, - content::DOWNLOAD_DANGER_TYPE_DANGEROUS_FILE, + download::DOWNLOAD_DANGER_TYPE_DANGEROUS_FILE, DownloadFileType::DANGEROUS, "http://example.com/foo.bad", "application/octet-stream", @@ -1195,17 +1195,17 @@ const struct { ui::PageTransition page_transition; - content::DownloadDangerType expected_danger_type; + download::DownloadDangerType expected_danger_type; const DownloadTestCase& template_download_test_case; } kTestCases[] = { {// Benign file type. Results in a danger type of NOT_DANGEROUS. Page // transition type is irrelevant. - ui::PAGE_TRANSITION_LINK, content::DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS, + ui::PAGE_TRANSITION_LINK, download::DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS, kSafeFile}, {// File type is ALLOW_ON_USER_GESTURE. PAGE_TRANSITION_LINK doesn't // cause file to be marked as safe. - ui::PAGE_TRANSITION_LINK, content::DOWNLOAD_DANGER_TYPE_DANGEROUS_FILE, + ui::PAGE_TRANSITION_LINK, download::DOWNLOAD_DANGER_TYPE_DANGEROUS_FILE, kAllowOnUserGesture}, {// File type is ALLOW_ON_USER_GESTURE. PAGE_TRANSITION_TYPED doesn't @@ -1213,30 +1213,30 @@ // types of explicit page transitions that aren't necessarily // initiated by a user. Hence a resulting download may not be // intentional. - ui::PAGE_TRANSITION_TYPED, content::DOWNLOAD_DANGER_TYPE_DANGEROUS_FILE, + ui::PAGE_TRANSITION_TYPED, download::DOWNLOAD_DANGER_TYPE_DANGEROUS_FILE, kAllowOnUserGesture}, {// File type is ALLOW_ON_USER_GESTURE. // PAGE_TRANSITION_FROM_ADDRESS_BAR causes file to be marked as safe. static_cast<ui::PageTransition>(ui::PAGE_TRANSITION_TYPED | ui::PAGE_TRANSITION_FROM_ADDRESS_BAR), - content::DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS, kAllowOnUserGesture}, + download::DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS, kAllowOnUserGesture}, {// File type is ALLOW_ON_USER_GESTURE. // PAGE_TRANSITION_FROM_ADDRESS_BAR causes file to be marked as safe. static_cast<ui::PageTransition>(ui::PAGE_TRANSITION_GENERATED | ui::PAGE_TRANSITION_FROM_ADDRESS_BAR), - content::DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS, kAllowOnUserGesture}, + download::DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS, kAllowOnUserGesture}, {// File type is ALLOW_ON_USER_GESTURE. // PAGE_TRANSITION_FROM_ADDRESS_BAR causes file to be marked as safe. ui::PAGE_TRANSITION_FROM_ADDRESS_BAR, - content::DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS, kAllowOnUserGesture}, + download::DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS, kAllowOnUserGesture}, {// File type is DANGEROUS. PageTransition is irrelevant. static_cast<ui::PageTransition>(ui::PAGE_TRANSITION_TYPED | ui::PAGE_TRANSITION_FROM_ADDRESS_BAR), - content::DOWNLOAD_DANGER_TYPE_DANGEROUS_FILE, kDangerousFile}, + download::DOWNLOAD_DANGER_TYPE_DANGEROUS_FILE, kDangerousFile}, }; // Test assumptions: @@ -1258,7 +1258,7 @@ DownloadTestCase download_test_case = test_case.template_download_test_case; download_test_case.expected_danger_type = test_case.expected_danger_type; if (test_case.expected_danger_type == - content::DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS) { + download::DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS) { download_test_case.expected_danger_level = DownloadFileType::NOT_DANGEROUS; download_test_case.expected_intermediate = EXPECT_CRDOWNLOAD; @@ -1279,7 +1279,7 @@ // 0: Safe Automatic - Should prompt because of "Prompt for download" // preference setting. AUTOMATIC, - content::DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS, + download::DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS, DownloadFileType::NOT_DANGEROUS, "http://example.com/automatic.txt", "text/plain", @@ -1302,7 +1302,7 @@ const DownloadTestCase kSafeSaveAs = { // 1: Safe Save As - Should prompt because of "Save as" invocation. SAVE_AS, - content::DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS, + download::DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS, DownloadFileType::NOT_DANGEROUS, "http://example.com/save-as.txt", "text/plain", @@ -1325,7 +1325,7 @@ const DownloadTestCase kSafeForced = { // 2: Safe Forced - Shouldn't prompt. FORCED, - content::DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS, + download::DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS, DownloadFileType::NOT_DANGEROUS, "http://example.com/foo.txt", "text/plain", @@ -1345,7 +1345,7 @@ // 3: Automatic - The filename extension is marked as one that we will // open automatically. Shouldn't prompt. AUTOMATIC, - content::DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS, + download::DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS, DownloadFileType::NOT_DANGEROUS, "http://example.com/foo.dummy", "", @@ -1366,7 +1366,7 @@ TEST_F(DownloadTargetDeterminerTest, ContinueWithoutConfirmation_SaveAs) { const DownloadTestCase kTestCase = { SAVE_AS, - content::DOWNLOAD_DANGER_TYPE_DANGEROUS_FILE, + download::DOWNLOAD_DANGER_TYPE_DANGEROUS_FILE, DownloadFileType::ALLOW_ON_USER_GESTURE, "http://example.com/save-as.kindabad", "text/plain", @@ -1394,7 +1394,7 @@ TEST_F(DownloadTargetDeterminerTest, ContinueWithConfirmation_SaveAs) { const DownloadTestCase kTestCase = { SAVE_AS, - content::DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS, + download::DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS, DownloadFileType::NOT_DANGEROUS, "http://example.com/save-as.kindabad", "text/plain", @@ -1425,7 +1425,7 @@ {// 0: Automatic Browser Extension download. - Shouldn't prompt for // browser extension downloads even if "Prompt for download" // preference is set. - AUTOMATIC, content::DOWNLOAD_DANGER_TYPE_DANGEROUS_FILE, + AUTOMATIC, download::DOWNLOAD_DANGER_TYPE_DANGEROUS_FILE, DownloadFileType::ALLOW_ON_USER_GESTURE, "http://example.com/foo.kindabad", extensions::Extension::kMimeType, FILE_PATH_LITERAL(""), @@ -1437,7 +1437,7 @@ {// 1: Automatic User Script - Shouldn't prompt for user script downloads // even if "Prompt for download" preference is set. - AUTOMATIC, content::DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS, + AUTOMATIC, download::DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS, DownloadFileType::NOT_DANGEROUS, "http://example.com/foo.user.js", "", FILE_PATH_LITERAL(""), @@ -1458,7 +1458,7 @@ TEST_F(DownloadTargetDeterminerTest, ManagedPath) { const DownloadTestCase kManagedPathTestCases[] = { {// 0: Automatic Safe - AUTOMATIC, content::DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS, + AUTOMATIC, download::DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS, DownloadFileType::NOT_DANGEROUS, "http://example.com/foo.txt", "text/plain", FILE_PATH_LITERAL(""), @@ -1467,7 +1467,7 @@ EXPECT_CRDOWNLOAD}, {// 1: Save_As Safe - SAVE_AS, content::DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS, + SAVE_AS, download::DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS, DownloadFileType::NOT_DANGEROUS, "http://example.com/foo.txt", "text/plain", FILE_PATH_LITERAL(""), @@ -1487,7 +1487,7 @@ TEST_F(DownloadTargetDeterminerTest, NotifyExtensionsSafe) { const DownloadTestCase kNotifyExtensionsTestCases[] = { {// 0: Automatic Safe - AUTOMATIC, content::DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS, + AUTOMATIC, download::DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS, DownloadFileType::NOT_DANGEROUS, "http://example.com/foo.txt", "text/plain", FILE_PATH_LITERAL(""), @@ -1497,7 +1497,7 @@ EXPECT_CRDOWNLOAD}, {// 1: Save_As Safe - SAVE_AS, content::DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS, + SAVE_AS, download::DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS, DownloadFileType::NOT_DANGEROUS, "http://example.com/foo.txt", "text/plain", FILE_PATH_LITERAL(""), @@ -1507,7 +1507,7 @@ EXPECT_CRDOWNLOAD}, {// 2: Automatic Dangerous - AUTOMATIC, content::DOWNLOAD_DANGER_TYPE_DANGEROUS_FILE, + AUTOMATIC, download::DOWNLOAD_DANGER_TYPE_DANGEROUS_FILE, DownloadFileType::ALLOW_ON_USER_GESTURE, "http://example.com/foo.kindabad", "", FILE_PATH_LITERAL(""), @@ -1517,7 +1517,7 @@ EXPECT_UNCONFIRMED}, {// 3: Forced Safe - FORCED, content::DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS, + FORCED, download::DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS, DownloadFileType::NOT_DANGEROUS, "http://example.com/foo.txt", "", FILE_PATH_LITERAL("forced-foo.txt"), @@ -1538,7 +1538,7 @@ TEST_F(DownloadTargetDeterminerTest, NotifyExtensionsUnsafe) { const DownloadTestCase kNotHandledBySafeBrowsing = { AUTOMATIC, - content::DOWNLOAD_DANGER_TYPE_DANGEROUS_FILE, + download::DOWNLOAD_DANGER_TYPE_DANGEROUS_FILE, DownloadFileType::ALLOW_ON_USER_GESTURE, "http://example.com/foo.kindabad.remove", "text/plain", @@ -1551,7 +1551,7 @@ const DownloadTestCase kHandledBySafeBrowsing = { AUTOMATIC, - content::DOWNLOAD_DANGER_TYPE_MAYBE_DANGEROUS_CONTENT, + download::DOWNLOAD_DANGER_TYPE_MAYBE_DANGEROUS_CONTENT, DownloadFileType::ALLOW_ON_USER_GESTURE, "http://example.com/foo.kindabad.remove", "text/plain", @@ -1568,7 +1568,7 @@ ON_CALL(*delegate(), CheckDownloadUrl(_, _, _)) .WillByDefault(WithArg<2>(ScheduleCallback( - content::DOWNLOAD_DANGER_TYPE_MAYBE_DANGEROUS_CONTENT))); + download::DOWNLOAD_DANGER_TYPE_MAYBE_DANGEROUS_CONTENT))); RunTestCasesWithActiveItem(&kHandledBySafeBrowsing, 1); } @@ -1577,7 +1577,7 @@ TEST_F(DownloadTargetDeterminerTest, NotifyExtensionsConflict) { const DownloadTestCase kNotifyExtensionsTestCase = { AUTOMATIC, - content::DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS, + download::DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS, DownloadFileType::NOT_DANGEROUS, "http://example.com/foo.txt", "text/plain", @@ -1626,7 +1626,7 @@ TEST_F(DownloadTargetDeterminerTest, NotifyExtensionsDefaultPath) { const DownloadTestCase kNotifyExtensionsTestCase = { AUTOMATIC, - content::DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS, + download::DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS, DownloadFileType::NOT_DANGEROUS, "http://example.com/foo.txt", "text/plain", @@ -1663,7 +1663,7 @@ // but the initial path is unsafe. However, the download is not considered // dangerous since the user has been prompted. SAVE_AS, - content::DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS, + download::DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS, DownloadFileType::NOT_DANGEROUS, "http://example.com/foo.txt", "text/plain", @@ -1699,7 +1699,7 @@ const DownloadTestCase kResumedTestCases[] = { {// 0: Automatic Safe: Initial path is ignored since the user has not been // prompted before. - AUTOMATIC, content::DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS, + AUTOMATIC, download::DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS, DownloadFileType::NOT_DANGEROUS, "http://example.com/foo.txt", "text/plain", FILE_PATH_LITERAL(""), @@ -1708,7 +1708,7 @@ EXPECT_CRDOWNLOAD}, {// 1: Save_As Safe: Initial path used. - SAVE_AS, content::DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS, + SAVE_AS, download::DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS, DownloadFileType::NOT_DANGEROUS, "http://example.com/foo.txt", "text/plain", FILE_PATH_LITERAL(""), @@ -1718,7 +1718,7 @@ {// 2: Automatic Dangerous: Initial path is ignored since the user hasn't // been prompted before. - AUTOMATIC, content::DOWNLOAD_DANGER_TYPE_DANGEROUS_FILE, + AUTOMATIC, download::DOWNLOAD_DANGER_TYPE_DANGEROUS_FILE, DownloadFileType::ALLOW_ON_USER_GESTURE, "http://example.com/foo.kindabad", "", FILE_PATH_LITERAL(""), @@ -1728,7 +1728,7 @@ EXPECT_UNCONFIRMED}, {// 3: Forced Safe: Initial path is ignored due to the forced path. - FORCED, content::DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS, + FORCED, download::DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS, DownloadFileType::NOT_DANGEROUS, "http://example.com/foo.txt", "", FILE_PATH_LITERAL("forced-foo.txt"), @@ -1775,7 +1775,7 @@ const DownloadTestCase kResumedForcedDownload = { // 3: Forced Safe FORCED, - content::DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS, + download::DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS, DownloadFileType::NOT_DANGEROUS, "http://example.com/foo.txt", "", @@ -1815,7 +1815,7 @@ const DownloadTestCase kResumedTestCases[] = { {// 0: Automatic Safe - AUTOMATIC, content::DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS, + AUTOMATIC, download::DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS, DownloadFileType::NOT_DANGEROUS, "http://example.com/foo.txt", "text/plain", FILE_PATH_LITERAL(""), @@ -1823,7 +1823,7 @@ EXPECT_CRDOWNLOAD}, {// 1: Save_As Safe - SAVE_AS, content::DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS, + SAVE_AS, download::DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS, DownloadFileType::NOT_DANGEROUS, "http://example.com/foo.txt", "text/plain", FILE_PATH_LITERAL(""), @@ -1833,7 +1833,7 @@ { // 2: Automatic Dangerous - AUTOMATIC, content::DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS, + AUTOMATIC, download::DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS, DownloadFileType::NOT_DANGEROUS, "http://example.com/foo.kindabad", "", FILE_PATH_LITERAL(""), @@ -1843,7 +1843,7 @@ { // 3: Automatic Dangerous - AUTOMATIC, content::DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS, + AUTOMATIC, download::DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS, DownloadFileType::NOT_DANGEROUS, "http://example.com/foo.bad", "", FILE_PATH_LITERAL(""), @@ -1896,7 +1896,7 @@ const base::FilePath::CharType* expected_intermediate_path; } kIntermediateNameTestCases[] = { {{// 0: Automatic Safe - AUTOMATIC, content::DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS, + AUTOMATIC, download::DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS, DownloadFileType::NOT_DANGEROUS, "http://example.com/foo.txt", "text/plain", FILE_PATH_LITERAL(""), @@ -1908,7 +1908,7 @@ FILE_PATH_LITERAL("foo.txt.crdownload")}, {{// 1: Save_As Safe - SAVE_AS, content::DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS, + SAVE_AS, download::DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS, DownloadFileType::NOT_DANGEROUS, "http://example.com/foo.txt", "text/plain", FILE_PATH_LITERAL(""), @@ -1919,7 +1919,7 @@ FILE_PATH_LITERAL("some_path/bar.txt.crdownload")}, {{// 2: Automatic Dangerous - AUTOMATIC, content::DOWNLOAD_DANGER_TYPE_DANGEROUS_FILE, + AUTOMATIC, download::DOWNLOAD_DANGER_TYPE_DANGEROUS_FILE, DownloadFileType::ALLOW_ON_USER_GESTURE, "http://example.com/foo.kindabad", "", FILE_PATH_LITERAL(""), @@ -1931,7 +1931,7 @@ FILE_PATH_LITERAL("Unconfirmed abcd.crdownload")}, {{// 3: Automatic Dangerous - AUTOMATIC, content::DOWNLOAD_DANGER_TYPE_DANGEROUS_FILE, + AUTOMATIC, download::DOWNLOAD_DANGER_TYPE_DANGEROUS_FILE, DownloadFileType::ALLOW_ON_USER_GESTURE, "http://example.com/foo.kindabad", "", FILE_PATH_LITERAL(""), @@ -1947,7 +1947,7 @@ FILE_PATH_LITERAL("")}, {{// 3: Forced Safe: Initial path is ignored due to the forced path. - FORCED, content::DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS, + FORCED, download::DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS, DownloadFileType::NOT_DANGEROUS, "http://example.com/foo.txt", "", FILE_PATH_LITERAL("forced-foo.txt"), @@ -2006,7 +2006,7 @@ const char* expected_mime_type; } kMIMETypeTestCases[] = { {{// 0: - AUTOMATIC, content::DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS, + AUTOMATIC, download::DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS, DownloadFileType::NOT_DANGEROUS, "http://example.com/foo.png", "image/png", FILE_PATH_LITERAL(""), @@ -2016,7 +2016,7 @@ EXPECT_CRDOWNLOAD}, "image/png"}, {{// 1: Empty MIME type in response. - AUTOMATIC, content::DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS, + AUTOMATIC, download::DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS, DownloadFileType::NOT_DANGEROUS, "http://example.com/foo.png", "", FILE_PATH_LITERAL(""), @@ -2026,7 +2026,7 @@ EXPECT_CRDOWNLOAD}, "image/png"}, {{// 2: Forced path. - FORCED, content::DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS, + FORCED, download::DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS, DownloadFileType::NOT_DANGEROUS, "http://example.com/foo.abc", "", FILE_PATH_LITERAL("foo.png"), @@ -2036,7 +2036,7 @@ EXPECT_CRDOWNLOAD}, "image/png"}, {{// 3: Unknown file type. - AUTOMATIC, content::DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS, + AUTOMATIC, download::DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS, DownloadFileType::NOT_DANGEROUS, "http://example.com/foo.notarealext", "", FILE_PATH_LITERAL(""), @@ -2046,7 +2046,7 @@ EXPECT_CRDOWNLOAD}, ""}, {{// 4: Unknown file type. - AUTOMATIC, content::DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS, + AUTOMATIC, download::DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS, DownloadFileType::NOT_DANGEROUS, "http://example.com/foo.notarealext", "image/png", FILE_PATH_LITERAL(""), @@ -2056,7 +2056,7 @@ EXPECT_CRDOWNLOAD}, ""}, {{// 5: x-x509-user-cert mime-type. - AUTOMATIC, content::DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS, + AUTOMATIC, download::DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS, DownloadFileType::NOT_DANGEROUS, "http://example.com/foo.notarealext", "application/x-x509-user-cert", FILE_PATH_LITERAL(""), @@ -2093,7 +2093,7 @@ const DownloadTestCase kUserValidatedTestCase = { AUTOMATIC, - content::DOWNLOAD_DANGER_TYPE_USER_VALIDATED, + download::DOWNLOAD_DANGER_TYPE_USER_VALIDATED, DownloadFileType::NOT_DANGEROUS, "http://example.com/foo.crx", "", @@ -2108,7 +2108,7 @@ base::FilePath expected_path = GetPathInDownloadDir(test_case.expected_local_path); ON_CALL(*item.get(), GetDangerType()) - .WillByDefault(Return(content::DOWNLOAD_DANGER_TYPE_USER_VALIDATED)); + .WillByDefault(Return(download::DOWNLOAD_DANGER_TYPE_USER_VALIDATED)); ON_CALL(*item.get(), GetFullPath()) .WillByDefault(ReturnRefOfCopy(GetPathInDownloadDir(kIntermediatePath))); ON_CALL(*item.get(), GetLastReason()) @@ -2128,7 +2128,7 @@ DownloadTestCase transient_test_case = { TRANSIENT, - content::DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS, + download::DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS, DownloadFileType::NOT_DANGEROUS, "http://example.com/foo", "", @@ -2175,7 +2175,7 @@ DownloadTestCase transient_test_case = { TRANSIENT, - content::DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS, + download::DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS, DownloadFileType::NOT_DANGEROUS, "http://example.com/foo", "", @@ -2339,7 +2339,7 @@ DownloadTestCase kSecureHandlingTestCase = { AUTOMATIC, - content::DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS, + download::DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS, DownloadFileType::NOT_DANGEROUS, "http://example.com/foo.fakeext", "", @@ -2408,7 +2408,7 @@ DownloadTestCase kSecureHandlingTestCase = { AUTOMATIC, - content::DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS, + download::DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS, DownloadFileType::NOT_DANGEROUS, "http://example.com/foo.fakeext", "",
diff --git a/chrome/browser/download/download_target_info.cc b/chrome/browser/download/download_target_info.cc index b1bb713..2e16a36 100644 --- a/chrome/browser/download/download_target_info.cc +++ b/chrome/browser/download/download_target_info.cc
@@ -8,7 +8,7 @@ DownloadTargetInfo::DownloadTargetInfo() : target_disposition(content::DownloadItem::TARGET_DISPOSITION_OVERWRITE), - danger_type(content::DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS), + danger_type(download::DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS), danger_level(safe_browsing::DownloadFileType::NOT_DANGEROUS), is_filetype_handled_safely(false), result(content::DOWNLOAD_INTERRUPT_REASON_NONE) {}
diff --git a/chrome/browser/download/download_target_info.h b/chrome/browser/download/download_target_info.h index 6e3a492..84a98923 100644 --- a/chrome/browser/download/download_target_info.h +++ b/chrome/browser/download/download_target_info.h
@@ -9,7 +9,7 @@ #include "base/files/file_path.h" #include "chrome/common/safe_browsing/download_file_types.pb.h" -#include "content/public/browser/download_danger_type.h" +#include "components/download/public/common/download_danger_type.h" #include "content/public/browser/download_interrupt_reasons.h" #include "content/public/browser/download_item.h" @@ -30,7 +30,7 @@ content::DownloadItem::TargetDisposition target_disposition; // Danger type of the download. - content::DownloadDangerType danger_type; + download::DownloadDangerType danger_type; // The danger type of the download could be set to MAYBE_DANGEROUS_CONTENT if // the file type is handled by SafeBrowsing. However, if the SafeBrowsing
diff --git a/chrome/browser/download/download_ui_controller_unittest.cc b/chrome/browser/download/download_ui_controller_unittest.cc index 490fc49..f1d75977 100644 --- a/chrome/browser/download/download_ui_controller_unittest.cc +++ b/chrome/browser/download/download_ui_controller_unittest.cc
@@ -232,7 +232,7 @@ EXPECT_CALL(*item, GetLastModifiedTime()) .WillRepeatedly(ReturnRefOfCopy(std::string())); EXPECT_CALL(*item, GetDangerType()) - .WillRepeatedly(Return(content::DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS)); + .WillRepeatedly(Return(download::DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS)); EXPECT_CALL(*item, GetLastReason()) .WillRepeatedly(Return(content::DOWNLOAD_INTERRUPT_REASON_NONE)); EXPECT_CALL(*item, GetReceivedBytes()).WillRepeatedly(Return(0));
diff --git a/chrome/browser/download/notification/download_item_notification.cc b/chrome/browser/download/notification/download_item_notification.cc index 87942d1..968cb5e 100644 --- a/chrome/browser/download/notification/download_item_notification.cc +++ b/chrome/browser/download/notification/download_item_notification.cc
@@ -669,10 +669,10 @@ base::string16 elided_filename = item_->GetFileNameToReportUser().LossyDisplayName(); switch (item_->GetDangerType()) { - case content::DOWNLOAD_DANGER_TYPE_DANGEROUS_URL: { + case download::DOWNLOAD_DANGER_TYPE_DANGEROUS_URL: { return l10n_util::GetStringUTF16(IDS_PROMPT_MALICIOUS_DOWNLOAD_URL); } - case content::DOWNLOAD_DANGER_TYPE_DANGEROUS_FILE: { + case download::DOWNLOAD_DANGER_TYPE_DANGEROUS_FILE: { if (download_crx_util::IsExtensionDownload(*item_)) { return l10n_util::GetStringUTF16( IDS_PROMPT_DANGEROUS_DOWNLOAD_EXTENSION); @@ -681,23 +681,23 @@ elided_filename); } } - case content::DOWNLOAD_DANGER_TYPE_DANGEROUS_CONTENT: - case content::DOWNLOAD_DANGER_TYPE_DANGEROUS_HOST: { + case download::DOWNLOAD_DANGER_TYPE_DANGEROUS_CONTENT: + case download::DOWNLOAD_DANGER_TYPE_DANGEROUS_HOST: { return l10n_util::GetStringFUTF16(IDS_PROMPT_MALICIOUS_DOWNLOAD_CONTENT, elided_filename); } - case content::DOWNLOAD_DANGER_TYPE_UNCOMMON_CONTENT: { + case download::DOWNLOAD_DANGER_TYPE_UNCOMMON_CONTENT: { return l10n_util::GetStringFUTF16(IDS_PROMPT_UNCOMMON_DOWNLOAD_CONTENT, elided_filename); } - case content::DOWNLOAD_DANGER_TYPE_POTENTIALLY_UNWANTED: { + case download::DOWNLOAD_DANGER_TYPE_POTENTIALLY_UNWANTED: { return l10n_util::GetStringFUTF16(IDS_PROMPT_DOWNLOAD_CHANGES_SETTINGS, elided_filename); } - case content::DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS: - case content::DOWNLOAD_DANGER_TYPE_MAYBE_DANGEROUS_CONTENT: - case content::DOWNLOAD_DANGER_TYPE_USER_VALIDATED: - case content::DOWNLOAD_DANGER_TYPE_MAX: { + case download::DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS: + case download::DOWNLOAD_DANGER_TYPE_MAYBE_DANGEROUS_CONTENT: + case download::DOWNLOAD_DANGER_TYPE_USER_VALIDATED: + case download::DOWNLOAD_DANGER_TYPE_MAX: { break; } }
diff --git a/chrome/browser/download/notification/download_item_notification_unittest.cc b/chrome/browser/download/notification/download_item_notification_unittest.cc index 2d8d4a7..9b0095b 100644 --- a/chrome/browser/download/notification/download_item_notification_unittest.cc +++ b/chrome/browser/download/notification/download_item_notification_unittest.cc
@@ -73,7 +73,7 @@ ON_CALL(*download_item_, GetTargetFilePath()) .WillByDefault(ReturnRefOfCopy(download_item_target_path)); ON_CALL(*download_item_, GetDangerType()) - .WillByDefault(Return(content::DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS)); + .WillByDefault(Return(download::DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS)); ON_CALL(*download_item_, IsDone()).WillByDefault(Return(false)); ON_CALL(*download_item_, GetURL()).WillByDefault(ReturnRefOfCopy( GURL("http://www.example.com/download.bin")));
diff --git a/chrome/browser/download/notification/download_notification_browsertest.cc b/chrome/browser/download/notification/download_notification_browsertest.cc index 9bb2671..27362f5 100644 --- a/chrome/browser/download/notification/download_notification_browsertest.cc +++ b/chrome/browser/download/notification/download_notification_browsertest.cc
@@ -478,7 +478,7 @@ base::FilePath filename = download_item()->GetFileNameToReportUser(); // Checks the download status. - EXPECT_EQ(content::DOWNLOAD_DANGER_TYPE_DANGEROUS_FILE, + EXPECT_EQ(download::DOWNLOAD_DANGER_TYPE_DANGEROUS_FILE, download_item()->GetDangerType()); EXPECT_TRUE(download_item()->IsDangerous()); @@ -500,7 +500,7 @@ EXPECT_EQ(1u, GetMessageCenter()->GetVisibleNotifications().size()); // Checks the download status. - EXPECT_EQ(content::DOWNLOAD_DANGER_TYPE_USER_VALIDATED, + EXPECT_EQ(download::DOWNLOAD_DANGER_TYPE_USER_VALIDATED, download_item()->GetDangerType()); EXPECT_FALSE(download_item()->IsDangerous()); @@ -529,7 +529,7 @@ base::FilePath filename = download_item()->GetFileNameToReportUser(); // Checks the download status. - EXPECT_EQ(content::DOWNLOAD_DANGER_TYPE_DANGEROUS_FILE, + EXPECT_EQ(download::DOWNLOAD_DANGER_TYPE_DANGEROUS_FILE, download_item()->GetDangerType()); EXPECT_TRUE(download_item()->IsDangerous()); @@ -1160,6 +1160,11 @@ kTestAccounts[DUMMY_ACCOUNT_INDEX].email); command_line->AppendSwitchASCII(chromeos::switches::kLoginProfile, kTestAccounts[DUMMY_ACCOUNT_INDEX].hash); + // Don't require policy for our sessions - this is required because + // this test creates a secondary profile synchronously, so we need to + // let the policy code know not to expect cached policy. + command_line->AppendSwitchASCII(chromeos::switches::kProfileRequiresPolicy, + "false"); } // Logs in to the primary profile.
diff --git a/chrome/browser/extensions/BUILD.gn b/chrome/browser/extensions/BUILD.gn index b0bddfd0..61b9cf6 100644 --- a/chrome/browser/extensions/BUILD.gn +++ b/chrome/browser/extensions/BUILD.gn
@@ -833,7 +833,8 @@ "//components/history/core/browser", "//components/infobars/core", "//components/keyed_service/content", - "//components/language/core/browser:browser", + "//components/language/core/browser", + "//components/language/core/common", "//components/nacl/common:features", "//components/navigation_interception", "//components/net_log", @@ -849,6 +850,8 @@ "//components/proxy_config", "//components/rappor", "//components/resources", + "//components/safe_browsing:csd_proto", + "//components/safe_browsing:features", "//components/safe_browsing/common:safe_browsing_prefs", "//components/safe_browsing/db:database_manager", "//components/search_engines",
diff --git a/chrome/browser/extensions/api/desktop_capture/desktop_capture_apitest.cc b/chrome/browser/extensions/api/desktop_capture/desktop_capture_apitest.cc index 11ecad1..c6c75b4 100644 --- a/chrome/browser/extensions/api/desktop_capture/desktop_capture_apitest.cc +++ b/chrome/browser/extensions/api/desktop_capture/desktop_capture_apitest.cc
@@ -66,13 +66,8 @@ ~FakeDesktopMediaPicker() override { expectation_->picker_deleted = true; } // DesktopMediaPicker interface. - void Show(content::WebContents* web_contents, - gfx::NativeWindow context, - gfx::NativeWindow parent, - const base::string16& app_name, - const base::string16& target_name, + void Show(const DesktopMediaPicker::Params& params, std::vector<std::unique_ptr<DesktopMediaList>> source_lists, - bool request_audio, const DoneCallback& done_callback) override { bool show_screens = false; bool show_windows = false; @@ -96,7 +91,8 @@ EXPECT_EQ(expectation_->expect_screens, show_screens); EXPECT_EQ(expectation_->expect_windows, show_windows); EXPECT_EQ(expectation_->expect_tabs, show_tabs); - EXPECT_EQ(expectation_->expect_audio, request_audio); + EXPECT_EQ(expectation_->expect_audio, params.request_audio); + EXPECT_EQ(params.modality, ui::ModalType::MODAL_TYPE_CHILD); if (!expectation_->cancelled) { // Post a task to call the callback asynchronously.
diff --git a/chrome/browser/extensions/api/desktop_capture/desktop_capture_base.cc b/chrome/browser/extensions/api/desktop_capture/desktop_capture_base.cc index b2b7336d..4e8b6cc 100644 --- a/chrome/browser/extensions/api/desktop_capture/desktop_capture_base.cc +++ b/chrome/browser/extensions/api/desktop_capture/desktop_capture_base.cc
@@ -204,10 +204,14 @@ DesktopMediaPicker::DoneCallback callback = base::Bind( &DesktopCaptureChooseDesktopMediaFunctionBase::OnPickerDialogResults, this); - - picker_->Show(web_contents, parent_window, parent_window, - base::UTF8ToUTF16(GetCallerDisplayName()), target_name, - std::move(source_lists), request_audio, callback); + DesktopMediaPicker::Params picker_params; + picker_params.web_contents = web_contents; + picker_params.context = parent_window; + picker_params.parent = parent_window; + picker_params.app_name = base::UTF8ToUTF16(GetCallerDisplayName()); + picker_params.target_name = target_name; + picker_params.request_audio = request_audio; + picker_->Show(picker_params, std::move(source_lists), callback); origin_ = origin; return true; }
diff --git a/chrome/browser/extensions/api/downloads/downloads_api.cc b/chrome/browser/extensions/api/downloads/downloads_api.cc index e4fd3fb3..81274ea 100644 --- a/chrome/browser/extensions/api/downloads/downloads_api.cc +++ b/chrome/browser/extensions/api/downloads/downloads_api.cc
@@ -59,7 +59,6 @@ #include "components/web_modal/web_contents_modal_dialog_manager.h" #include "content/public/browser/download_interrupt_reasons.h" #include "content/public/browser/download_item.h" -#include "content/public/browser/download_save_info.h" #include "content/public/browser/download_url_parameters.h" #include "content/public/browser/notification_details.h" #include "content/public/browser/notification_service.h" @@ -193,7 +192,7 @@ kDangerHost, kDangerUnwanted }; -static_assert(arraysize(kDangerStrings) == content::DOWNLOAD_DANGER_TYPE_MAX, +static_assert(arraysize(kDangerStrings) == download::DOWNLOAD_DANGER_TYPE_MAX, "kDangerStrings should have DOWNLOAD_DANGER_TYPE_MAX elements"); // Note: Any change to the state strings, should be accompanied by a @@ -207,22 +206,22 @@ static_assert(arraysize(kStateStrings) == DownloadItem::MAX_DOWNLOAD_STATE, "kStateStrings should have MAX_DOWNLOAD_STATE elements"); -const char* DangerString(content::DownloadDangerType danger) { +const char* DangerString(download::DownloadDangerType danger) { DCHECK(danger >= 0); - DCHECK(danger < static_cast<content::DownloadDangerType>( - arraysize(kDangerStrings))); - if (danger < 0 || danger >= static_cast<content::DownloadDangerType>( - arraysize(kDangerStrings))) + DCHECK(danger < + static_cast<download::DownloadDangerType>(arraysize(kDangerStrings))); + if (danger < 0 || danger >= static_cast<download::DownloadDangerType>( + arraysize(kDangerStrings))) return ""; return kDangerStrings[danger]; } -content::DownloadDangerType DangerEnumFromString(const std::string& danger) { +download::DownloadDangerType DangerEnumFromString(const std::string& danger) { for (size_t i = 0; i < arraysize(kDangerStrings); ++i) { if (danger == kDangerStrings[i]) - return static_cast<content::DownloadDangerType>(i); + return static_cast<download::DownloadDangerType>(i); } - return content::DOWNLOAD_DANGER_TYPE_MAX; + return download::DOWNLOAD_DANGER_TYPE_MAX; } const char* StateString(DownloadItem::DownloadState state) { @@ -563,9 +562,9 @@ std::string danger_string = downloads::ToString(query_in.danger); if (!danger_string.empty()) { - content::DownloadDangerType danger_type = DangerEnumFromString( - danger_string); - if (danger_type == content::DOWNLOAD_DANGER_TYPE_MAX) { + download::DownloadDangerType danger_type = + DangerEnumFromString(danger_string); + if (danger_type == download::DOWNLOAD_DANGER_TYPE_MAX) { *error = errors::kInvalidDangerType; return; } @@ -1089,7 +1088,7 @@ creator_suggested_filename, options.conflict_action)); // Prevent login prompts for 401/407 responses. download_params->set_do_not_prompt_for_login(true); - download_params->set_download_source(content::DownloadSource::EXTENSION_API); + download_params->set_download_source(download::DownloadSource::EXTENSION_API); DownloadManager* manager = BrowserContext::GetDownloadManager( current_profile);
diff --git a/chrome/browser/extensions/api/downloads/downloads_api_browsertest.cc b/chrome/browser/extensions/api/downloads/downloads_api_browsertest.cc index ee60798..d40e320a 100644 --- a/chrome/browser/extensions/api/downloads/downloads_api_browsertest.cc +++ b/chrome/browser/extensions/api/downloads/downloads_api_browsertest.cc
@@ -47,7 +47,6 @@ #include "content/public/browser/storage_partition.h" #include "content/public/browser/web_contents.h" #include "content/public/common/content_features.h" -#include "content/public/test/controllable_http_response.h" #include "content/public/test/download_test_observer.h" #include "content/public/test/test_download_http_response.h" #include "content/public/test/test_utils.h" @@ -55,6 +54,7 @@ #include "extensions/browser/notification_types.h" #include "net/base/data_url.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/url_request/url_request_slow_download_job.h" #include "net/url_request/url_request.h" @@ -270,7 +270,7 @@ // Danger type for the download. Only use DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS // and DOWNLOAD_DANGER_TYPE_DANGEROUS_CONTENT. - content::DownloadDangerType danger_type; + download::DownloadDangerType danger_type; }; void LoadExtension(const char* name) { @@ -329,10 +329,12 @@ DownloadTestFileActivityObserver observer(current_browser()->profile()); observer.EnableFileChooser(false); - first_download_ = std::make_unique<content::ControllableHttpResponse>( - embedded_test_server(), kFirstDownloadUrl); - second_download_ = std::make_unique<content::ControllableHttpResponse>( - embedded_test_server(), kSecondDownloadUrl); + first_download_ = + std::make_unique<net::test_server::ControllableHttpResponse>( + embedded_test_server(), kFirstDownloadUrl); + second_download_ = + std::make_unique<net::test_server::ControllableHttpResponse>( + embedded_test_server(), kSecondDownloadUrl); host_resolver()->AddRule("*", "127.0.0.1"); } @@ -477,7 +479,7 @@ } DownloadItem* CreateSlowTestDownload( - content::ControllableHttpResponse* response, + net::test_server::ControllableHttpResponse* response, const std::string& path) { if (!embedded_test_server()->Started()) StartEmbeddedTestServer(); @@ -515,7 +517,8 @@ FinishSlowDownloads(second_download_.get()); } - void FinishSlowDownloads(content::ControllableHttpResponse* response) { + void FinishSlowDownloads( + net::test_server::ControllableHttpResponse* response) { std::unique_ptr<content::DownloadTestObserver> observer( CreateDownloadObserver(1)); response->Done(); @@ -619,8 +622,8 @@ Browser* current_browser_; std::unique_ptr<DownloadsEventsListener> events_listener_; - std::unique_ptr<content::ControllableHttpResponse> first_download_; - std::unique_ptr<content::ControllableHttpResponse> second_download_; + std::unique_ptr<net::test_server::ControllableHttpResponse> first_download_; + std::unique_ptr<net::test_server::ControllableHttpResponse> second_download_; DISALLOW_COPY_AND_ASSIGN(DownloadExtensionTest); }; @@ -1063,13 +1066,10 @@ IN_PROC_BROWSER_TEST_F(DownloadExtensionTest, DownloadExtensionTest_FileIcon_History) { const HistoryDownloadInfo kHistoryInfo[] = { - { FILE_PATH_LITERAL("real.txt"), - DownloadItem::COMPLETE, - content::DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS }, - { FILE_PATH_LITERAL("fake.txt"), - DownloadItem::COMPLETE, - content::DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS } - }; + {FILE_PATH_LITERAL("real.txt"), DownloadItem::COMPLETE, + download::DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS}, + {FILE_PATH_LITERAL("fake.txt"), DownloadItem::COMPLETE, + download::DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS}}; DownloadManager::DownloadVector all_downloads; ASSERT_TRUE(CreateHistoryDownloads(kHistoryInfo, arraysize(kHistoryInfo), &all_downloads)); @@ -1144,13 +1144,10 @@ IN_PROC_BROWSER_TEST_F(DownloadExtensionTest, DownloadExtensionTest_SearchFilenameRegex) { const HistoryDownloadInfo kHistoryInfo[] = { - { FILE_PATH_LITERAL("foobar"), - DownloadItem::COMPLETE, - content::DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS }, - { FILE_PATH_LITERAL("baz"), - DownloadItem::COMPLETE, - content::DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS } - }; + {FILE_PATH_LITERAL("foobar"), DownloadItem::COMPLETE, + download::DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS}, + {FILE_PATH_LITERAL("baz"), DownloadItem::COMPLETE, + download::DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS}}; DownloadManager::DownloadVector all_downloads; ASSERT_TRUE(CreateHistoryDownloads(kHistoryInfo, arraysize(kHistoryInfo), &all_downloads)); @@ -1223,13 +1220,10 @@ IN_PROC_BROWSER_TEST_F(DownloadExtensionTest, DownloadExtensionTest_SearchOrderBy) { const HistoryDownloadInfo kHistoryInfo[] = { - { FILE_PATH_LITERAL("zzz"), - DownloadItem::COMPLETE, - content::DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS }, - { FILE_PATH_LITERAL("baz"), - DownloadItem::COMPLETE, - content::DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS } - }; + {FILE_PATH_LITERAL("zzz"), DownloadItem::COMPLETE, + download::DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS}, + {FILE_PATH_LITERAL("baz"), DownloadItem::COMPLETE, + download::DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS}}; DownloadManager::DownloadVector items; ASSERT_TRUE(CreateHistoryDownloads(kHistoryInfo, arraysize(kHistoryInfo), &items)); @@ -1256,13 +1250,10 @@ IN_PROC_BROWSER_TEST_F(DownloadExtensionTest, DownloadExtensionTest_SearchOrderByEmpty) { const HistoryDownloadInfo kHistoryInfo[] = { - { FILE_PATH_LITERAL("zzz"), - DownloadItem::COMPLETE, - content::DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS }, - { FILE_PATH_LITERAL("baz"), - DownloadItem::COMPLETE, - content::DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS } - }; + {FILE_PATH_LITERAL("zzz"), DownloadItem::COMPLETE, + download::DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS}, + {FILE_PATH_LITERAL("baz"), DownloadItem::COMPLETE, + download::DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS}}; DownloadManager::DownloadVector items; ASSERT_TRUE(CreateHistoryDownloads(kHistoryInfo, arraysize(kHistoryInfo), &items)); @@ -1293,13 +1284,10 @@ IN_PROC_BROWSER_TEST_F(DownloadExtensionTest, DownloadExtensionTest_SearchDanger) { const HistoryDownloadInfo kHistoryInfo[] = { - { FILE_PATH_LITERAL("zzz"), - DownloadItem::COMPLETE, - content::DOWNLOAD_DANGER_TYPE_DANGEROUS_CONTENT }, - { FILE_PATH_LITERAL("baz"), - DownloadItem::COMPLETE, - content::DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS } - }; + {FILE_PATH_LITERAL("zzz"), DownloadItem::COMPLETE, + download::DOWNLOAD_DANGER_TYPE_DANGEROUS_CONTENT}, + {FILE_PATH_LITERAL("baz"), DownloadItem::COMPLETE, + download::DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS}}; DownloadManager::DownloadVector items; ASSERT_TRUE(CreateHistoryDownloads(kHistoryInfo, arraysize(kHistoryInfo), &items)); @@ -1379,15 +1367,12 @@ IN_PROC_BROWSER_TEST_F(DownloadExtensionTest, DownloadExtensionTest_SearchPlural) { const HistoryDownloadInfo kHistoryInfo[] = { - { FILE_PATH_LITERAL("aaa"), - DownloadItem::CANCELLED, - content::DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS }, - { FILE_PATH_LITERAL("zzz"), - DownloadItem::COMPLETE, - content::DOWNLOAD_DANGER_TYPE_DANGEROUS_CONTENT }, - { FILE_PATH_LITERAL("baz"), - DownloadItem::COMPLETE, - content::DOWNLOAD_DANGER_TYPE_DANGEROUS_CONTENT }, + {FILE_PATH_LITERAL("aaa"), DownloadItem::CANCELLED, + download::DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS}, + {FILE_PATH_LITERAL("zzz"), DownloadItem::COMPLETE, + download::DOWNLOAD_DANGER_TYPE_DANGEROUS_CONTENT}, + {FILE_PATH_LITERAL("baz"), DownloadItem::COMPLETE, + download::DOWNLOAD_DANGER_TYPE_DANGEROUS_CONTENT}, }; DownloadManager::DownloadVector items; ASSERT_TRUE(CreateHistoryDownloads(kHistoryInfo, arraysize(kHistoryInfo),
diff --git a/chrome/browser/extensions/api/language_settings_private/language_settings_private_api.cc b/chrome/browser/extensions/api/language_settings_private/language_settings_private_api.cc index e42d686..59177c3 100644 --- a/chrome/browser/extensions/api/language_settings_private/language_settings_private_api.cc +++ b/chrome/browser/extensions/api/language_settings_private/language_settings_private_api.cc
@@ -12,6 +12,7 @@ #include <utility> #include <vector> +#include "base/containers/flat_set.h" #include "base/feature_list.h" #include "base/stl_util.h" #include "base/strings/string16.h" @@ -32,6 +33,7 @@ #include "chrome/common/extensions/api/language_settings_private.h" #include "chrome/common/pref_names.h" #include "components/language/core/browser/language_model.h" +#include "components/language/core/common/locale_util.h" #include "components/spellcheck/common/spellcheck_common.h" #include "components/translate/core/browser/translate_download_manager.h" #include "components/translate/core/browser/translate_prefs.h" @@ -178,15 +180,14 @@ app_locale, translate_prefs->IsTranslateAllowedByPolicy(), &languages); // Get the list of available locales (display languages) and convert to a set. - const std::vector<std::string>& locales = l10n_util::GetAvailableLocales(); - const std::unordered_set<std::string> locale_set(locales.begin(), - locales.end()); + const base::flat_set<std::string> locale_set( + l10n_util::GetAvailableLocales()); // Get the list of spell check languages and convert to a set. std::vector<std::string> spellcheck_languages = spellcheck::SpellCheckLanguages(); - const std::unordered_set<std::string> spellcheck_language_set( - spellcheck_languages.begin(), spellcheck_languages.end()); + const base::flat_set<std::string> spellcheck_language_set( + std::move(spellcheck_languages)); // Build the language list. std::unique_ptr<base::ListValue> language_list(new base::ListValue); @@ -198,15 +199,20 @@ language.native_display_name = entry.native_display_name; // Set optional fields only if they differ from the default. - if (locale_set.count(entry.code) > 0) { - language.supports_ui.reset(new bool(true)); - } - if (spellcheck_language_set.count(entry.code) > 0) { + if (base::ContainsKey(spellcheck_language_set, entry.code)) { language.supports_spellcheck.reset(new bool(true)); } if (entry.supports_translate) { language.supports_translate.reset(new bool(true)); } + if (base::FeatureList::IsEnabled(translate::kRegionalLocalesAsDisplayUI)) { + std::string temp_locale = entry.code; + if (language::ConvertToActualUILocale(&temp_locale)) { + language.supports_ui.reset(new bool(true)); + } + } else if (base::ContainsKey(locale_set, entry.code)) { + language.supports_ui.reset(new bool(true)); + } language_list->Append(language.ToValue()); }
diff --git a/chrome/browser/extensions/api/networking_private/networking_private_chromeos_apitest.cc b/chrome/browser/extensions/api/networking_private/networking_private_chromeos_apitest.cc index 742eda58..4abe0b89 100644 --- a/chrome/browser/extensions/api/networking_private/networking_private_chromeos_apitest.cc +++ b/chrome/browser/extensions/api/networking_private/networking_private_chromeos_apitest.cc
@@ -155,10 +155,6 @@ void ShowAccountDetails(const std::string& guid) const override { ++s_show_account_details_called_; } - bool HandleConnectFailed(const std::string& guid, - const std::string error) const override { - return false; - } }; // static
diff --git a/chrome/browser/extensions/api/networking_private/networking_private_ui_delegate_chromeos.cc b/chrome/browser/extensions/api/networking_private/networking_private_ui_delegate_chromeos.cc index fbdbf5d..ea3f616 100644 --- a/chrome/browser/extensions/api/networking_private/networking_private_ui_delegate_chromeos.cc +++ b/chrome/browser/extensions/api/networking_private/networking_private_ui_delegate_chromeos.cc
@@ -20,11 +20,5 @@ chromeos::NetworkConnect::Get()->ShowMobileSetup(guid); } -bool NetworkingPrivateUIDelegateChromeOS::HandleConnectFailed( - const std::string& guid, - const std::string error) const { - return chromeos::NetworkConnect::Get()->MaybeShowConfigureUI(guid, error); -} - } // namespace extensions } // namespace chromeos
diff --git a/chrome/browser/extensions/api/networking_private/networking_private_ui_delegate_chromeos.h b/chrome/browser/extensions/api/networking_private/networking_private_ui_delegate_chromeos.h index 43732c0a..941fd24 100644 --- a/chrome/browser/extensions/api/networking_private/networking_private_ui_delegate_chromeos.h +++ b/chrome/browser/extensions/api/networking_private/networking_private_ui_delegate_chromeos.h
@@ -20,8 +20,6 @@ // NetworkingPrivateDelegate::UIDelegate void ShowAccountDetails(const std::string& guid) const override; - bool HandleConnectFailed(const std::string& guid, - const std::string error) const override; private: DISALLOW_COPY_AND_ASSIGN(NetworkingPrivateUIDelegateChromeOS);
diff --git a/chrome/browser/extensions/chrome_extensions_browser_client.cc b/chrome/browser/extensions/chrome_extensions_browser_client.cc index 4c02711..adee7d44 100644 --- a/chrome/browser/extensions/chrome_extensions_browser_client.cc +++ b/chrome/browser/extensions/chrome_extensions_browser_client.cc
@@ -266,6 +266,11 @@ return chrome::IsRunningInForcedAppMode(); } +bool ChromeExtensionsBrowserClient::IsAppModeForcedForApp( + const ExtensionId& extension_id) { + return chrome::IsRunningInForcedAppModeForApp(extension_id); +} + bool ChromeExtensionsBrowserClient::IsLoggedInAsPublicAccount() { #if defined(OS_CHROMEOS) return user_manager::UserManager::Get()->IsLoggedInAsPublicAccount();
diff --git a/chrome/browser/extensions/chrome_extensions_browser_client.h b/chrome/browser/extensions/chrome_extensions_browser_client.h index 1ae7a2f..9bf9655 100644 --- a/chrome/browser/extensions/chrome_extensions_browser_client.h +++ b/chrome/browser/extensions/chrome_extensions_browser_client.h
@@ -89,6 +89,7 @@ bool DidVersionUpdate(content::BrowserContext* context) override; void PermitExternalProtocolHandler() override; bool IsRunningInForcedAppMode() override; + bool IsAppModeForcedForApp(const ExtensionId& extension_id) override; bool IsLoggedInAsPublicAccount() override; ExtensionSystemProvider* GetExtensionSystemFactory() override; void RegisterExtensionFunctions(
diff --git a/chrome/browser/extensions/content_verifier_browsertest.cc b/chrome/browser/extensions/content_verifier_browsertest.cc index 1377c43..1f18564 100644 --- a/chrome/browser/extensions/content_verifier_browsertest.cc +++ b/chrome/browser/extensions/content_verifier_browsertest.cc
@@ -22,7 +22,6 @@ #include "chrome/browser/extensions/extension_service.h" #include "chrome/browser/extensions/policy_extension_reinstaller.h" #include "chrome/common/chrome_switches.h" -#include "chrome/test/base/ui_test_utils.h" #include "components/policy/core/browser/browser_policy_connector.h" #include "components/policy/core/common/mock_configuration_policy_provider.h" #include "content/public/common/browser_side_navigation_policy.h" @@ -116,56 +115,6 @@ DISALLOW_COPY_AND_ASSIGN(RegistryObserver); }; -// Helper for forcing ContentVerifyJob's to return an error. -class JobDelegate : public ContentVerifyJob::TestDelegate { - public: - JobDelegate() - : fail_next_read_(false), - fail_next_done_(false), - bytes_read_failed_(0), - done_reading_failed_(0) {} - - ~JobDelegate() override {} - - void set_id(const ExtensionId& id) { id_ = id; } - void fail_next_read() { fail_next_read_ = true; } - void fail_next_done() { fail_next_done_ = true; } - - // Return the number of BytesRead/DoneReading calls we actually failed, - // respectively. - int bytes_read_failed() { return bytes_read_failed_; } - int done_reading_failed() { return done_reading_failed_; } - - ContentVerifyJob::FailureReason BytesRead(const ExtensionId& id, - int count, - const char* data) override { - if (id == id_ && fail_next_read_) { - fail_next_read_ = false; - bytes_read_failed_++; - return ContentVerifyJob::HASH_MISMATCH; - } - return ContentVerifyJob::NONE; - } - - ContentVerifyJob::FailureReason DoneReading(const ExtensionId& id) override { - if (id == id_ && fail_next_done_) { - fail_next_done_ = false; - done_reading_failed_++; - return ContentVerifyJob::HASH_MISMATCH; - } - return ContentVerifyJob::NONE; - } - - private: - ExtensionId id_; - bool fail_next_read_; - bool fail_next_done_; - int bytes_read_failed_; - int done_reading_failed_; - - DISALLOW_COPY_AND_ASSIGN(JobDelegate); -}; - class JobObserver : public ContentVerifyJob::TestObserver { public: JobObserver(); @@ -449,19 +398,6 @@ DISALLOW_COPY_AND_ASSIGN(ForceInstallProvider); }; -class ScopedContentVerifyJobDelegateOverride { - public: - explicit ScopedContentVerifyJobDelegateOverride(JobDelegate* delegate) { - ContentVerifyJob::SetDelegateForTests(delegate); - } - ~ScopedContentVerifyJobDelegateOverride() { - ContentVerifyJob::SetDelegateForTests(nullptr); - } - - private: - DISALLOW_COPY_AND_ASSIGN(ScopedContentVerifyJobDelegateOverride); -}; - } // namespace class ContentVerifierTest : public ExtensionBrowserTest { @@ -478,32 +414,6 @@ bool ShouldEnableContentVerification() override { return true; } - virtual void OpenPageAndWaitForUnload() { - ScopedContentVerifyJobDelegateOverride scoped_delegate(&delegate_); - std::string id = "npnbmohejbjohgpjnmjagbafnjhkmgko"; - delegate_.set_id(id); - - // |unload_observer| needs to destroy before the ExtensionRegistry gets - // deleted, which happens before TearDownOnMainThread is called. - RegistryObserver unload_observer(ExtensionRegistry::Get(profile())); - const Extension* extension = InstallExtensionFromWebstore( - test_data_dir_.AppendASCII("content_verifier/v1.crx"), 1); - ASSERT_TRUE(extension); - ASSERT_EQ(id, extension->id()); - page_url_ = extension->GetResourceURL("page.html"); - // Wait for 0 navigations to complete because with PlzNavigate it's racy - // when the didstop IPC arrives relative to the tab being closed. The - // wait call below is what the tests care about. - ui_test_utils::NavigateToURLWithDispositionBlockUntilNavigationsComplete( - browser(), page_url_, 0, WindowOpenDisposition::NEW_FOREGROUND_TAB, - ui_test_utils::BROWSER_TEST_NONE); - - EXPECT_TRUE(unload_observer.WaitForUnload(id)); - ExtensionPrefs* prefs = ExtensionPrefs::Get(profile()); - int reasons = prefs->GetDisableReasons(id); - EXPECT_TRUE(reasons & disable_reason::DISABLE_CORRUPTED); - } - void TestContentScriptExtension(const std::string& crx_relpath, const std::string& id, const std::string& script_relpath) { @@ -553,24 +463,9 @@ } protected: - JobDelegate delegate_; GURL page_url_; }; -IN_PROC_BROWSER_TEST_F(ContentVerifierTest, FailOnRead) { - EXPECT_EQ(0, delegate_.bytes_read_failed()); - delegate_.fail_next_read(); - OpenPageAndWaitForUnload(); - EXPECT_EQ(1, delegate_.bytes_read_failed()); -} - -IN_PROC_BROWSER_TEST_F(ContentVerifierTest, FailOnDone) { - EXPECT_EQ(0, delegate_.done_reading_failed()); - delegate_.fail_next_done(); - OpenPageAndWaitForUnload(); - EXPECT_EQ(1, delegate_.done_reading_failed()); -} - IN_PROC_BROWSER_TEST_F(ContentVerifierTest, DotSlashPaths) { JobObserver job_observer; std::string id = "hoipipabpcoomfapcecilckodldhmpgl";
diff --git a/chrome/browser/extensions/extension_functional_browsertest.cc b/chrome/browser/extensions/extension_functional_browsertest.cc index f77b100..18ccc0c 100644 --- a/chrome/browser/extensions/extension_functional_browsertest.cc +++ b/chrome/browser/extensions/extension_functional_browsertest.cc
@@ -4,11 +4,13 @@ #include <stddef.h> +#include "base/test/histogram_tester.h" #include "build/build_config.h" #include "chrome/browser/extensions/crx_installer.h" #include "chrome/browser/extensions/extension_browsertest.h" #include "chrome/browser/extensions/extension_service.h" #include "chrome/browser/extensions/extension_util.h" +#include "chrome/browser/metrics/subprocess_metrics_provider.h" #include "chrome/browser/profiles/profile.h" #include "chrome/browser/ui/browser.h" #include "chrome/browser/ui/browser_commands.h" @@ -23,6 +25,8 @@ #include "extensions/browser/extension_util.h" #include "extensions/browser/notification_types.h" #include "extensions/browser/test_extension_registry_observer.h" +#include "testing/gmock/include/gmock/gmock.h" +#include "testing/gtest/include/gtest/gtest.h" namespace extensions { @@ -165,6 +169,7 @@ // behavior. We want to change the old behavior - this would expectedly make // the assestion below fail and in this case we would need to tweak the test // to look-up another window (most likely a background page). + base::HistogramTester histogram_tester; std::string location_of_opened_window; EXPECT_TRUE(ExecuteScriptAndExtractString( tab1_popup, @@ -172,6 +177,24 @@ "window.domAutomationController.send(w.location.href);", &location_of_opened_window)); EXPECT_EQ(tab2->GetLastCommittedURL(), location_of_opened_window); + + // Verify UMA got recorded as expected. + SubprocessMetricsProvider::MergeHistogramDeltasForTesting(); + EXPECT_THAT(histogram_tester.GetAllSamples( + "Extensions.BrowsingInstanceViolation.ExtensionType"), + testing::ElementsAre(base::Bucket(Manifest::TYPE_EXTENSION, 1))); + EXPECT_THAT( + histogram_tester.GetAllSamples( + "Extensions.BrowsingInstanceViolation.SourceExtensionViewType"), + testing::ElementsAre(base::Bucket(VIEW_TYPE_TAB_CONTENTS, 1))); + EXPECT_THAT( + histogram_tester.GetAllSamples( + "Extensions.BrowsingInstanceViolation.TargetExtensionViewType"), + testing::ElementsAre(base::Bucket(VIEW_TYPE_TAB_CONTENTS, 1))); + EXPECT_THAT( + histogram_tester.GetAllSamples( + "Extensions.BrowsingInstanceViolation.IsBackgroundSourceOrTarget"), + testing::ElementsAre(base::Bucket(false, 1))); } } // namespace extensions
diff --git a/chrome/browser/extensions/extension_protocols_unittest.cc b/chrome/browser/extensions/extension_protocols_unittest.cc index b247cad..f171bc42 100644 --- a/chrome/browser/extensions/extension_protocols_unittest.cc +++ b/chrome/browser/extensions/extension_protocols_unittest.cc
@@ -29,11 +29,13 @@ #include "content/public/test/test_browser_thread_bundle.h" #include "content/public/test/test_utils.h" #include "extensions/browser/content_verifier.h" +#include "extensions/browser/content_verifier/test_utils.h" #include "extensions/browser/extension_protocols.h" #include "extensions/browser/info_map.h" #include "extensions/common/constants.h" #include "extensions/common/extension.h" #include "extensions/common/extension_builder.h" +#include "extensions/common/extension_paths.h" #include "extensions/common/file_util.h" #include "extensions/test/test_extension_dir.h" #include "net/base/request_priority.h" @@ -55,14 +57,11 @@ return path.AppendASCII("extensions").AppendASCII(name); } -// Helper function that creates a file at |relative_path| within |directory| -// and fills it with |content|. -bool AddFileToDirectory(const base::FilePath& directory, - const base::FilePath& relative_path, - const std::string& content) { - base::FilePath full_path = directory.Append(relative_path); - int result = base::WriteFile(full_path, content.data(), content.size()); - return static_cast<size_t>(result) == content.size(); +base::FilePath GetContentVerifierTestPath() { + base::FilePath path; + EXPECT_TRUE(PathService::Get(extensions::DIR_TEST_DATA, &path)); + return path.AppendASCII("content_hash_fetcher") + .AppendASCII("different_sized_files"); } scoped_refptr<Extension> CreateTestExtension(const std::string& name, @@ -120,60 +119,6 @@ return extension; } -// A ContentVerifyJob::TestDelegate that observes DoneReading(). -class JobDelegate : public ContentVerifyJob::TestDelegate { - public: - explicit JobDelegate(const std::string& expected_contents) - : expected_contents_(expected_contents), run_loop_(new base::RunLoop()) { - ContentVerifyJob::SetDelegateForTests(this); - } - ~JobDelegate() override { ContentVerifyJob::SetDelegateForTests(nullptr); } - - ContentVerifyJob::FailureReason BytesRead(const ExtensionId& id, - int count, - const char* data) override { - read_contents_.append(data, count); - return ContentVerifyJob::NONE; - } - - ContentVerifyJob::FailureReason DoneReading(const ExtensionId& id) override { - seen_done_reading_extension_ids_.insert(id); - if (waiting_for_extension_id_ == id) - run_loop_->Quit(); - - if (!base::StartsWith(expected_contents_, read_contents_, - base::CompareCase::SENSITIVE)) { - ADD_FAILURE() << "Unexpected read, expected: " << expected_contents_ - << ", but found: " << read_contents_; - } - return ContentVerifyJob::NONE; - } - - void WaitForDoneReading(const ExtensionId& id) { - ASSERT_FALSE(waiting_for_extension_id_); - if (seen_done_reading_extension_ids_.count(id)) - return; - waiting_for_extension_id_ = id; - run_loop_->Run(); - } - - void Reset() { - read_contents_.clear(); - waiting_for_extension_id_.reset(); - seen_done_reading_extension_ids_.clear(); - run_loop_ = std::make_unique<base::RunLoop>(); - } - - private: - std::string expected_contents_; - std::string read_contents_; - std::set<ExtensionId> seen_done_reading_extension_ids_; - base::Optional<ExtensionId> waiting_for_extension_id_; - std::unique_ptr<base::RunLoop> run_loop_; - - DISALLOW_COPY_AND_ASSIGN(JobDelegate); -}; - } // namespace // This test lives in src/chrome instead of src/extensions because it tests @@ -516,101 +461,121 @@ // Tests that unreadable files and deleted files correctly go through // ContentVerifyJob. TEST_F(ExtensionProtocolsTest, VerificationSeenForFileAccessErrors) { - const char kFooJsContents[] = "hello world."; - JobDelegate test_job_delegate(kFooJsContents); SetProtocolHandler(false); - const std::string kFooJs("foo.js"); - // Create a temporary directory that a fake extension will live in and fill - // it with some test files. + // Unzip extension containing verification hashes to a temporary directory. base::ScopedTempDir temp_dir; ASSERT_TRUE(temp_dir.CreateUniqueTempDir()); - base::FilePath foo_js(FILE_PATH_LITERAL("foo.js")); - ASSERT_TRUE(AddFileToDirectory(temp_dir.GetPath(), foo_js, kFooJsContents)) - << "Failed to write " << temp_dir.GetPath().value() << "/" - << foo_js.value(); - - ExtensionBuilder builder; - builder - .SetManifest(DictionaryBuilder() - .Set("name", "Foo") - .Set("version", "1.0") - .Set("manifest_version", 2) - .Set("update_url", - "https://clients2.google.com/service/update2/crx") - .Build()) - .SetID(crx_file::id_util::GenerateId("whatever")) - .SetPath(temp_dir.GetPath()) - .SetLocation(Manifest::INTERNAL); - scoped_refptr<Extension> extension(builder.Build()); - + base::FilePath unzipped_path = temp_dir.GetPath(); + scoped_refptr<Extension> extension = + content_verifier_test_utils::UnzipToDirAndLoadExtension( + GetContentVerifierTestPath().AppendASCII("source.zip"), + unzipped_path); ASSERT_TRUE(extension.get()); - content_verifier_->OnExtensionLoaded(testing_profile_.get(), extension.get()); - // Wait for PostTask to ContentVerifierIOData::AddData() to finish. - content::RunAllPendingInMessageLoop(); + ExtensionId extension_id = extension->id(); - // Valid and readable foo.js. - EXPECT_EQ(net::OK, DoRequest(*extension, kFooJs)); - test_job_delegate.WaitForDoneReading(extension->id()); + const std::string kJs("1024.js"); + base::FilePath kRelativePath(FILE_PATH_LITERAL("1024.js")); - // chmod -r foo.js. - base::FilePath foo_path = temp_dir.GetPath().AppendASCII(kFooJs); - ASSERT_TRUE(base::MakeFileUnreadable(foo_path)); - test_job_delegate.Reset(); - EXPECT_EQ(net::ERR_ACCESS_DENIED, DoRequest(*extension, kFooJs)); - test_job_delegate.WaitForDoneReading(extension->id()); + // Valid and readable 1024.js. + { + TestContentVerifyJobObserver observer(extension_id, kRelativePath); - // Delete foo.js. - ASSERT_TRUE(base::DieFileDie(foo_path, false)); - test_job_delegate.Reset(); - EXPECT_EQ(net::ERR_FILE_NOT_FOUND, DoRequest(*extension, kFooJs)); - test_job_delegate.WaitForDoneReading(extension->id()); + content_verifier_->OnExtensionLoaded(testing_profile_.get(), + extension.get()); + // Wait for PostTask to ContentVerifierIOData::AddData() to finish. + content::RunAllPendingInMessageLoop(); + + EXPECT_EQ(net::OK, DoRequest(*extension, kJs)); + EXPECT_EQ(ContentVerifyJob::NONE, observer.WaitAndGetFailureReason()); + } + + // chmod -r 1024.js. + { + TestContentVerifyJobObserver observer(extension->id(), kRelativePath); + base::FilePath file_path = unzipped_path.AppendASCII(kJs); + ASSERT_TRUE(base::MakeFileUnreadable(file_path)); + EXPECT_EQ(net::ERR_ACCESS_DENIED, DoRequest(*extension, kJs)); + EXPECT_EQ(ContentVerifyJob::HASH_MISMATCH, + observer.WaitAndGetFailureReason()); + // NOTE: In production, hash mismatch would have disabled |extension|, but + // since UnzipToDirAndLoadExtension() doesn't add the extension to + // ExtensionRegistry, ChromeContentVerifierDelegate won't disable it. + // TODO(lazyboy): We may want to update this to more closely reflect the + // real flow. + } + + // Delete 1024.js. + { + TestContentVerifyJobObserver observer(extension_id, kRelativePath); + base::FilePath file_path = unzipped_path.AppendASCII(kJs); + ASSERT_TRUE(base::DieFileDie(file_path, false)); + EXPECT_EQ(net::ERR_FILE_NOT_FOUND, DoRequest(*extension, kJs)); + EXPECT_EQ(ContentVerifyJob::HASH_MISMATCH, + observer.WaitAndGetFailureReason()); + } } // Tests that zero byte files correctly go through ContentVerifyJob. TEST_F(ExtensionProtocolsTest, VerificationSeenForZeroByteFile) { - const char kFooJsContents[] = ""; // Empty. - JobDelegate test_job_delegate(kFooJsContents); SetProtocolHandler(false); - const std::string kFooJs("foo.js"); - // Create a temporary directory that a fake extension will live in and fill - // it with some test files. + const std::string kEmptyJs("empty.js"); base::ScopedTempDir temp_dir; ASSERT_TRUE(temp_dir.CreateUniqueTempDir()); - base::FilePath foo_js(FILE_PATH_LITERAL("foo.js")); - ASSERT_TRUE(AddFileToDirectory(temp_dir.GetPath(), foo_js, kFooJsContents)) - << "Failed to write " << temp_dir.GetPath().value() << "/" - << foo_js.value(); + base::FilePath unzipped_path = temp_dir.GetPath(); - // Sanity check foo.js. - base::FilePath foo_path = temp_dir.GetPath().AppendASCII(kFooJs); + scoped_refptr<Extension> extension = + content_verifier_test_utils::UnzipToDirAndLoadExtension( + GetContentVerifierTestPath().AppendASCII("source.zip"), + unzipped_path); + ASSERT_TRUE(extension.get()); + + base::FilePath kRelativePath(FILE_PATH_LITERAL("empty.js")); + ExtensionId extension_id = extension->id(); + + // Sanity check empty.js. + base::FilePath file_path = unzipped_path.AppendASCII(kEmptyJs); int64_t foo_file_size = -1; - ASSERT_TRUE(base::GetFileSize(foo_path, &foo_file_size)); + ASSERT_TRUE(base::GetFileSize(file_path, &foo_file_size)); ASSERT_EQ(0, foo_file_size); - ExtensionBuilder builder; - builder - .SetManifest(DictionaryBuilder() - .Set("name", "Foo") - .Set("version", "1.0") - .Set("manifest_version", 2) - .Set("update_url", - "https://clients2.google.com/service/update2/crx") - .Build()) - .SetID(crx_file::id_util::GenerateId("whatever")) - .SetPath(temp_dir.GetPath()) - .SetLocation(Manifest::INTERNAL); - scoped_refptr<Extension> extension(builder.Build()); + // Request empty.js. + { + TestContentVerifyJobObserver observer(extension_id, kRelativePath); - ASSERT_TRUE(extension.get()); - content_verifier_->OnExtensionLoaded(testing_profile_.get(), extension.get()); - // Wait for PostTask to ContentVerifierIOData::AddData() to finish. - content::RunAllPendingInMessageLoop(); + content_verifier_->OnExtensionLoaded(testing_profile_.get(), + extension.get()); + // Wait for PostTask to ContentVerifierIOData::AddData() to finish. + content::RunAllPendingInMessageLoop(); - // Request foo.js. - EXPECT_EQ(net::OK, DoRequest(*extension, kFooJs)); - test_job_delegate.WaitForDoneReading(extension->id()); + EXPECT_EQ(net::OK, DoRequest(*extension, kEmptyJs)); + EXPECT_EQ(ContentVerifyJob::NONE, observer.WaitAndGetFailureReason()); + } + + // chmod -r empty.js. + // Unreadable empty file doesn't generate hash mismatch. Note that this is the + // current behavior of ContentVerifyJob. + // TODO(lazyboy): The behavior is probably incorrect. + { + TestContentVerifyJobObserver observer(extension->id(), kRelativePath); + base::FilePath file_path = unzipped_path.AppendASCII(kEmptyJs); + ASSERT_TRUE(base::MakeFileUnreadable(file_path)); + EXPECT_EQ(net::ERR_ACCESS_DENIED, DoRequest(*extension, kEmptyJs)); + EXPECT_EQ(ContentVerifyJob::NONE, observer.WaitAndGetFailureReason()); + } + + // rm empty.js. + // Deleted empty file doesn't generate hash mismatch. Note that this is the + // current behavior of ContentVerifyJob. + // TODO(lazyboy): The behavior is probably incorrect. + { + TestContentVerifyJobObserver observer(extension_id, kRelativePath); + base::FilePath file_path = unzipped_path.AppendASCII(kEmptyJs); + ASSERT_TRUE(base::DieFileDie(file_path, false)); + EXPECT_EQ(net::ERR_FILE_NOT_FOUND, DoRequest(*extension, kEmptyJs)); + EXPECT_EQ(ContentVerifyJob::NONE, observer.WaitAndGetFailureReason()); + } } // Tests that mime types are properly set for returned extension resources.
diff --git a/chrome/browser/extensions/webstore_data_fetcher.cc b/chrome/browser/extensions/webstore_data_fetcher.cc index ccb17fd..3dbc403 100644 --- a/chrome/browser/extensions/webstore_data_fetcher.cc +++ b/chrome/browser/extensions/webstore_data_fetcher.cc
@@ -7,8 +7,10 @@ #include <utility> #include "base/bind.h" +#include "base/metrics/field_trial_params.h" #include "base/values.h" #include "chrome/browser/extensions/webstore_data_fetcher_delegate.h" +#include "components/safe_browsing/features.h" #include "content/public/common/service_manager_connection.h" #include "extensions/common/extension_urls.h" #include "net/base/load_flags.h" @@ -35,18 +37,22 @@ referrer_url_(referrer_url), id_(webstore_item_id), max_auto_retries_(0) { + upload_content_type_ = + base::FeatureList::IsEnabled(safe_browsing::kAppendRecentNavigationEvents) + ? "application/octet-stream" + : "application/json"; } WebstoreDataFetcher::~WebstoreDataFetcher() {} -void WebstoreDataFetcher::SetJsonPostData(const std::string& json) { - json_post_data_ = json; +void WebstoreDataFetcher::SetPostData(const std::string& data) { + post_data_ = data; } void WebstoreDataFetcher::Start() { GURL webstore_data_url(extension_urls::GetWebstoreItemJsonDataURL(id_)); net::URLFetcher::RequestType request_type = - json_post_data_.empty() ? net::URLFetcher::GET : net::URLFetcher::POST; + post_data_.empty() ? net::URLFetcher::GET : net::URLFetcher::POST; net::NetworkTrafficAnnotationTag traffic_annotation = net::DefineNetworkTrafficAnnotation("webstore_data_fetcher", R"( semantics { @@ -84,10 +90,8 @@ webstore_data_url_fetcher_->SetLoadFlags(net::LOAD_DO_NOT_SAVE_COOKIES | net::LOAD_DISABLE_CACHE); - if (!json_post_data_.empty()) { - webstore_data_url_fetcher_->SetUploadData("application/json", - json_post_data_); - } + if (!post_data_.empty()) + webstore_data_url_fetcher_->SetUploadData(upload_content_type_, post_data_); if (max_auto_retries_ > 0) { webstore_data_url_fetcher_->SetMaxRetriesOn5xx(max_auto_retries_);
diff --git a/chrome/browser/extensions/webstore_data_fetcher.h b/chrome/browser/extensions/webstore_data_fetcher.h index 7179fb7c..dd2a2bb7 100644 --- a/chrome/browser/extensions/webstore_data_fetcher.h +++ b/chrome/browser/extensions/webstore_data_fetcher.h
@@ -37,9 +37,9 @@ const std::string webstore_item_id); ~WebstoreDataFetcher() override; - // Makes this request use a POST instead of GET, and sends |json| in the - // body of the request. If |json| is empty, this is a no-op. - void SetJsonPostData(const std::string& json); + // Makes this request use a POST instead of GET, and sends |data| in the + // body of the request. If |data| is empty, this is a no-op. + void SetPostData(const std::string& data); void Start(); @@ -47,6 +47,8 @@ max_auto_retries_ = max_retries; } + std::string upload_content_type() const { return upload_content_type_; } + private: void OnJsonParseSuccess(std::unique_ptr<base::Value> parsed_json); void OnJsonParseFailure(const std::string& error); @@ -58,7 +60,8 @@ net::URLRequestContextGetter* request_context_; GURL referrer_url_; std::string id_; - std::string json_post_data_; + std::string post_data_; + std::string upload_content_type_; // For fetching webstore JSON data. std::unique_ptr<net::URLFetcher> webstore_data_url_fetcher_;
diff --git a/chrome/browser/extensions/webstore_inline_installer.cc b/chrome/browser/extensions/webstore_inline_installer.cc index ee4e890a8..da5b2ea 100644 --- a/chrome/browser/extensions/webstore_inline_installer.cc +++ b/chrome/browser/extensions/webstore_inline_installer.cc
@@ -18,6 +18,7 @@ #include "chrome/browser/ui/exclusive_access/fullscreen_controller.h" #include "chrome/common/pref_names.h" #include "components/prefs/pref_service.h" +#include "components/safe_browsing/proto/csd.pb.h" #include "content/public/browser/navigation_entry.h" #include "content/public/browser/navigation_handle.h" #include "content/public/browser/web_contents.h" @@ -118,7 +119,10 @@ return SafeBrowsingNavigationObserverManager::IsEnabledAndReady(profile()); } -std::string WebstoreInlineInstaller::GetJsonPostData() { +std::string WebstoreInlineInstaller::GetPostData( + const std::string& upload_content_type) { + DCHECK(upload_content_type == "application/octet-stream" || + upload_content_type == "application/json"); // web_contents() might return null during tab destruction. This object would // also be destroyed shortly thereafter but check to be on the safe side. if (!web_contents()) @@ -129,72 +133,10 @@ if (!profile()->GetPrefs()->GetBoolean(prefs::kSafeBrowsingEnabled)) return std::string(); - auto redirect_chain = std::make_unique<base::ListValue>(); - - if (SafeBrowsingNavigationEventsEnabled()) { - // If we have it, use the new referrer checker. - safe_browsing::SafeBrowsingService* safe_browsing_service = - g_browser_process->safe_browsing_service(); - // May be null in some tests. - if (!safe_browsing_service) - return std::string(); - - scoped_refptr<SafeBrowsingNavigationObserverManager> - navigation_observer_manager = - safe_browsing_service->navigation_observer_manager(); - // This may be null if the navigation observer manager feature is - // disabled by experiment. - if (!navigation_observer_manager) - return std::string(); - - ReferrerChain referrer_chain; - SafeBrowsingNavigationObserverManager::AttributionResult result = - navigation_observer_manager->IdentifyReferrerChainByWebContents( - web_contents(), kExtensionReferrerUserGestureLimit, - &referrer_chain); - if (result != - SafeBrowsingNavigationObserverManager::NAVIGATION_EVENT_NOT_FOUND) { - // For now the CWS post data is JSON encoded. Consider moving it to a - // proto. - for (const auto& referrer_chain_entry : referrer_chain) { - // Referrer chain entries are a list of URLs in reverse chronological - // order, so the final URL is the last thing in the list and the initial - // landing page is the first thing in the list. - // Furthermore each entry may contain a series of server redirects - // stored in the same order. - redirect_chain->AppendString(referrer_chain_entry.url()); - for (const auto& server_side_redirect : - referrer_chain_entry.server_redirect_chain()) { - redirect_chain->AppendString(server_side_redirect.url()); - } - } - } - } else { - content::NavigationController& navigation_controller = - web_contents()->GetController(); - content::NavigationEntry* navigation_entry = - navigation_controller.GetLastCommittedEntry(); - if (navigation_entry) { - const std::vector<GURL>& redirect_urls = - navigation_entry->GetRedirectChain(); - for (const GURL& url : redirect_urls) { - redirect_chain->AppendString(url.spec()); - } - } - } - - if (!redirect_chain->empty()) { - base::DictionaryValue dictionary; - dictionary.SetString("id", id()); - dictionary.SetString("referrer", requestor_url_.spec()); - dictionary.Set("redirect_chain", std::move(redirect_chain)); - - std::string json; - base::JSONWriter::Write(dictionary, &json); - return json; - } - - return std::string(); + if (upload_content_type == "application/json") + return GetJsonPostData(); + else + return GetProtoPostData(); } bool WebstoreInlineInstaller::CheckRequestorAlive() const { @@ -305,6 +247,91 @@ AbortInstall(); } +std::string WebstoreInlineInstaller::GetJsonPostData() { + auto redirect_chain = base::MakeUnique<base::ListValue>(); + + if (SafeBrowsingNavigationEventsEnabled()) { + scoped_refptr<SafeBrowsingNavigationObserverManager> + navigation_observer_manager = g_browser_process->safe_browsing_service() + ->navigation_observer_manager(); + + ReferrerChain referrer_chain; + SafeBrowsingNavigationObserverManager::AttributionResult result = + navigation_observer_manager->IdentifyReferrerChainByWebContents( + web_contents(), kExtensionReferrerUserGestureLimit, + &referrer_chain); + if (result != + SafeBrowsingNavigationObserverManager::NAVIGATION_EVENT_NOT_FOUND) { + for (const auto& referrer_chain_entry : referrer_chain) { + // Referrer chain entries are a list of URLs in reverse chronological + // order, so the final URL is the last thing in the list and the initial + // landing page is the first thing in the list. + // Furthermore each entry may contain a series of server redirects + // stored in the same order. + redirect_chain->AppendString(referrer_chain_entry.url()); + for (const auto& server_side_redirect : + referrer_chain_entry.server_redirect_chain()) { + redirect_chain->AppendString(server_side_redirect.url()); + } + } + } + } else { + content::NavigationController& navigation_controller = + web_contents()->GetController(); + content::NavigationEntry* navigation_entry = + navigation_controller.GetLastCommittedEntry(); + if (navigation_entry) { + const std::vector<GURL>& redirect_urls = + navigation_entry->GetRedirectChain(); + for (const GURL& url : redirect_urls) { + redirect_chain->AppendString(url.spec()); + } + } + } + + if (!redirect_chain->empty()) { + base::DictionaryValue dictionary; + dictionary.SetString("id", id()); + dictionary.SetString("referrer", requestor_url_.spec()); + dictionary.Set("redirect_chain", std::move(redirect_chain)); + + std::string json; + base::JSONWriter::Write(dictionary, &json); + return json; + } + + return std::string(); +} + +std::string WebstoreInlineInstaller::GetProtoPostData() { + if (!SafeBrowsingNavigationEventsEnabled()) + return std::string(); + + scoped_refptr<SafeBrowsingNavigationObserverManager> + navigation_observer_manager = g_browser_process->safe_browsing_service() + ->navigation_observer_manager(); + + ReferrerChain referrer_chain; + SafeBrowsingNavigationObserverManager::AttributionResult result = + navigation_observer_manager->IdentifyReferrerChainByWebContents( + web_contents(), kExtensionReferrerUserGestureLimit, &referrer_chain); + + // If the referrer chain is incomplete we'll append most recent navigations + // to referrer chain for diagnose purpose. This only happens if user is not + // in incognito mode and has opted into extended reporting to Scout reporting. + int recent_navigations_to_collect = + SafeBrowsingNavigationObserverManager::CountOfRecentNavigationsToAppend( + *profile(), result); + navigation_observer_manager->AppendRecentNavigations( + recent_navigations_to_collect, &referrer_chain); + safe_browsing::ExtensionWebStoreInstallRequest request; + request.mutable_referrer_chain()->Swap(&referrer_chain); + request.mutable_referrer_chain_options()->set_recent_navigations_to_collect( + recent_navigations_to_collect); + + return request.SerializeAsString(); +} + // static bool WebstoreInlineInstaller::IsRequestorURLInVerifiedSite( const GURL& requestor_url,
diff --git a/chrome/browser/extensions/webstore_inline_installer.h b/chrome/browser/extensions/webstore_inline_installer.h index 3e3760e..646f9fbe 100644 --- a/chrome/browser/extensions/webstore_inline_installer.h +++ b/chrome/browser/extensions/webstore_inline_installer.h
@@ -53,7 +53,7 @@ virtual bool SafeBrowsingNavigationEventsEnabled() const; // Implementations WebstoreStandaloneInstaller Template Method's hooks. - std::string GetJsonPostData() override; + std::string GetPostData(const std::string& upload_content_type) override; bool CheckRequestorAlive() const override; const GURL& GetRequestorURL() const override; bool ShouldShowPostInstallUI() const override; @@ -72,6 +72,11 @@ content::NavigationHandle* navigation_handle) override; void WebContentsDestroyed() override; + // Get Json string that contains extension install referrer chain info. + std::string GetJsonPostData(); + // Get serialized ExtensionWebStoreInstallRequest protobuf. + std::string GetProtoPostData(); + // Checks whether the install is initiated by a page in a verified site // (which is at least a domain, but can also have a port or a path). static bool IsRequestorURLInVerifiedSite(const GURL& requestor_url,
diff --git a/chrome/browser/extensions/webstore_inline_installer_browsertest.cc b/chrome/browser/extensions/webstore_inline_installer_browsertest.cc index 8ca86623..a90590a 100644 --- a/chrome/browser/extensions/webstore_inline_installer_browsertest.cc +++ b/chrome/browser/extensions/webstore_inline_installer_browsertest.cc
@@ -25,6 +25,8 @@ #include "chrome/test/base/ui_test_utils.h" #include "components/content_settings/core/browser/host_content_settings_map.h" #include "components/prefs/pref_service.h" +#include "components/safe_browsing/features.h" +#include "components/safe_browsing/proto/csd.pb.h" #include "content/public/browser/web_contents.h" #include "content/public/test/browser_test_utils.h" #include "extensions/browser/extension_registry.h" @@ -408,22 +410,35 @@ void ProcessServerRequest( const net::test_server::HttpRequest& request) override { cws_request_received_ = true; + if (request.content.empty()) + return; + if (request.content.find("redirect_chain") != std::string::npos) { std::unique_ptr<base::Value> contents = base::JSONReader::Read(request.content); ASSERT_EQ(base::Value::Type::DICTIONARY, contents->type()); cws_request_json_data_ = base::DictionaryValue::From(std::move(contents)); + } else { + cws_request_proto_ = + base::MakeUnique<safe_browsing::ExtensionWebStoreInstallRequest>(); + if (!cws_request_proto_->ParseFromString(request.content)) + cws_request_proto_.reset(); } } bool cws_request_received_; std::unique_ptr<base::DictionaryValue> cws_request_json_data_; + std::unique_ptr<safe_browsing::ExtensionWebStoreInstallRequest> + cws_request_proto_; }; // Test that an install from a page arrived at via redirects includes the // redirect information in the webstore request. IN_PROC_BROWSER_TEST_P(WebstoreInlineInstallerRedirectTest, - IncludesRedirectData) { + IncludesRedirectJsonData) { + base::test::ScopedFeatureList scoped_feature_list; + scoped_feature_list.InitAndDisableFeature( + safe_browsing::kAppendRecentNavigationEvents); const bool using_safe_browsing_tracker = GetParam(); WebContents* web_contents = browser()->tab_strip_model()->GetActiveWebContents(); @@ -456,6 +471,7 @@ EXPECT_TRUE(cws_request_received_); ASSERT_NE(nullptr, cws_request_json_data_); + ASSERT_EQ(nullptr, cws_request_proto_); base::ListValue* redirect_list = nullptr; cws_request_json_data_->GetList("redirect_chain", &redirect_list); @@ -480,6 +496,68 @@ } } +// Test that an install from a page arrived at via redirects includes the +// redirect information in the webstore request. +IN_PROC_BROWSER_TEST_P(WebstoreInlineInstallerRedirectTest, + IncludesRedirectProtoData) { + base::test::ScopedFeatureList scoped_feature_list; + scoped_feature_list.InitAndEnableFeatureWithParameters( + safe_browsing::kAppendRecentNavigationEvents, + {{"recent_navigation_count", "3"}}); + const bool using_safe_browsing_tracker = GetParam(); + WebContents* web_contents = + browser()->tab_strip_model()->GetActiveWebContents(); + TabHelper* tab_helper = TabHelper::FromWebContents(web_contents); + WebstoreInlineInstallerForTestFactory* factory = + new WebstoreInlineInstallerForTestFactory(using_safe_browsing_tracker); + tab_helper->SetWebstoreInlineInstallerFactoryForTests(factory); + + net::HostPortPair host_port = embedded_test_server()->host_port_pair(); + + std::string final_url = + GenerateTestServerUrl(kAppDomain, "install.html").spec(); + std::string redirect_url = + base::StringPrintf("http://%s:%d/server-redirect?%s", kRedirect2Domain, + host_port.port(), final_url.c_str()); + std::string install_url = + base::StringPrintf("http://%s:%d/server-redirect?%s", kRedirect1Domain, + host_port.port(), redirect_url.c_str()); + AutoAcceptInstall(); + ui_test_utils::NavigateToURL(browser(), GURL(install_url)); + + RunTestAsync("runTest"); + while (!ProgrammableInstallPrompt::Ready()) + base::RunLoop().RunUntilIdle(); + web_contents->Close(); + + EXPECT_TRUE(cws_request_received_); + ASSERT_EQ(nullptr, cws_request_json_data_); + if (!using_safe_browsing_tracker) { + ASSERT_EQ(nullptr, cws_request_proto_); + return; + } + + ASSERT_NE(nullptr, cws_request_proto_); + ASSERT_EQ(1, cws_request_proto_->referrer_chain_size()); + + safe_browsing::ReferrerChainEntry referrer_entry = + cws_request_proto_->referrer_chain(0); + + // Check that the expected domains are in the redirect list. + const std::set<std::string> expected_redirect_domains = { + kRedirect1Domain, kRedirect2Domain, kAppDomain}; + + EXPECT_EQ(final_url, referrer_entry.url()); + EXPECT_EQ(safe_browsing::ReferrerChainEntry::CLIENT_REDIRECT, + referrer_entry.type()); + EXPECT_EQ(3, referrer_entry.server_redirect_chain_size()); + EXPECT_EQ(install_url, referrer_entry.server_redirect_chain(0).url()); + EXPECT_EQ(redirect_url, referrer_entry.server_redirect_chain(1).url()); + EXPECT_EQ(final_url, referrer_entry.server_redirect_chain(2).url()); + EXPECT_TRUE(cws_request_proto_->referrer_chain_options() + .has_recent_navigations_to_collect()); +} + // Test that an install from a page arrived at via redirects does not include // redirect information when SafeBrowsing is disabled. IN_PROC_BROWSER_TEST_F(WebstoreInlineInstallerRedirectTest, @@ -510,6 +588,7 @@ EXPECT_TRUE(cws_request_received_); ASSERT_EQ(nullptr, cws_request_json_data_); + ASSERT_EQ(nullptr, cws_request_proto_); } INSTANTIATE_TEST_CASE_P(NetRedirectTracking,
diff --git a/chrome/browser/extensions/webstore_installer.cc b/chrome/browser/extensions/webstore_installer.cc index 705c0d8..d9917e6 100644 --- a/chrome/browser/extensions/webstore_installer.cc +++ b/chrome/browser/extensions/webstore_installer.cc
@@ -45,7 +45,6 @@ #include "components/update_client/update_query_params.h" #include "content/public/browser/browser_thread.h" #include "content/public/browser/download_manager.h" -#include "content/public/browser/download_save_info.h" #include "content/public/browser/download_url_parameters.h" #include "content/public/browser/navigation_controller.h" #include "content/public/browser/navigation_entry.h" @@ -706,7 +705,7 @@ params->set_callback(base::Bind(&WebstoreInstaller::OnDownloadStarted, this, extension_id)); - params->set_download_source(content::DownloadSource::EXTENSION_INSTALLER); + params->set_download_source(download::DownloadSource::EXTENSION_INSTALLER); download_manager->DownloadUrl(std::move(params)); }
diff --git a/chrome/browser/extensions/webstore_standalone_installer.cc b/chrome/browser/extensions/webstore_standalone_installer.cc index d7e83ec2..644d66c 100644 --- a/chrome/browser/extensions/webstore_standalone_installer.cc +++ b/chrome/browser/extensions/webstore_standalone_installer.cc
@@ -69,9 +69,8 @@ GetRequestorURL(), id_)); - std::string json_post_data = GetJsonPostData(); - if (!json_post_data.empty()) - webstore_data_fetcher_->SetJsonPostData(json_post_data); + webstore_data_fetcher_->SetPostData( + GetPostData(webstore_data_fetcher_->upload_content_type())); webstore_data_fetcher_->Start(); } @@ -157,7 +156,8 @@ return localized_extension_for_display_.get(); } -std::string WebstoreStandaloneInstaller::GetJsonPostData() { +std::string WebstoreStandaloneInstaller::GetPostData( + const std::string& upload_content_type_unused) { return std::string(); }
diff --git a/chrome/browser/extensions/webstore_standalone_installer.h b/chrome/browser/extensions/webstore_standalone_installer.h index d471b1c..c4a6cbb 100644 --- a/chrome/browser/extensions/webstore_standalone_installer.h +++ b/chrome/browser/extensions/webstore_standalone_installer.h
@@ -88,9 +88,10 @@ // Template Method's hooks to be implemented by subclasses. // Gives subclasses an opportunity to provide extra post data in the form of - // serialized JSON to the webstore data request before sending. The default - // implementation returns an empty string. - virtual std::string GetJsonPostData(); + // serialized JSON or proto based on |upload_content_type| to the webstore + // data request before sending. The default implementation returns an empty + // string. + virtual std::string GetPostData(const std::string& upload_content_type); // Called at certain check points of the workflow to decide whether it makes // sense to proceed with installation. A requestor can be a website that
diff --git a/chrome/browser/flag_descriptions.cc b/chrome/browser/flag_descriptions.cc index b759718..1b6be22 100644 --- a/chrome/browser/flag_descriptions.cc +++ b/chrome/browser/flag_descriptions.cc
@@ -1180,6 +1180,13 @@ "reduce the amount of information in the 'referer' header for cross-origin " "requests."; +extern const char kRegionalLocalesAsDisplayUIName[] = + "Allow regional locales as display UI"; +extern const char kRegionalLocalesAsDisplayUIDescription[] = + "This flag allows regional locales to be selected as display UI by the " + "user in Language Settings. The actual locale of the system is derived " + "from the user selection based on some simple fallback logic."; + const char kRemoveUsageOfDeprecatedGaiaSigninEndpointName[] = "Remove usage of the deprecated GAIA sign-in endpoint"; const char kRemoveUsageOfDeprecatedGaiaSigninEndpointDescription[] = @@ -2933,6 +2940,10 @@ "Enable the mirrored screen mode. This mode flips the screen image " "horizontally."; +const char kAshEnableNewOverviewUiName[] = "Enable new overview UI."; +const char kAshEnableNewOverviewUiDescription[] = + "Enables the new overview mode UI."; + const char kAshEnablePersistentWindowBoundsName[] = "Enable persistent window bounds in multi-displays scenario."; const char kAshEnablePersistentWindowBoundsDescription[] =
diff --git a/chrome/browser/flag_descriptions.h b/chrome/browser/flag_descriptions.h index 8e77c20..7921990 100644 --- a/chrome/browser/flag_descriptions.h +++ b/chrome/browser/flag_descriptions.h
@@ -734,6 +734,9 @@ extern const char kReducedReferrerGranularityName[]; extern const char kReducedReferrerGranularityDescription[]; +extern const char kRegionalLocalesAsDisplayUIName[]; +extern const char kRegionalLocalesAsDisplayUIDescription[]; + extern const char kRemoveUsageOfDeprecatedGaiaSigninEndpointName[]; extern const char kRemoveUsageOfDeprecatedGaiaSigninEndpointDescription[]; @@ -1809,6 +1812,9 @@ extern const char kAshEnableMirroredScreenName[]; extern const char kAshEnableMirroredScreenDescription[]; +extern const char kAshEnableNewOverviewUiName[]; +extern const char kAshEnableNewOverviewUiDescription[]; + extern const char kAshEnablePersistentWindowBoundsName[]; extern const char kAshEnablePersistentWindowBoundsDescription[];
diff --git a/chrome/browser/lifetime/application_lifetime.cc b/chrome/browser/lifetime/application_lifetime.cc index 44b609b9..14b7a277 100644 --- a/chrome/browser/lifetime/application_lifetime.cc +++ b/chrome/browser/lifetime/application_lifetime.cc
@@ -32,6 +32,7 @@ #include "chrome/common/features.h" #include "chrome/common/pref_names.h" #include "components/keep_alive_registry/keep_alive_registry.h" +#include "components/language/core/common/locale_util.h" #include "components/metrics/metrics_service.h" #include "components/prefs/pref_service.h" #include "content/public/browser/browser_thread.h" @@ -104,8 +105,9 @@ // Login screen should show up in owner's locale. std::string owner_locale = local_state->GetString(prefs::kOwnerLocale); - if (!owner_locale.empty() && - local_state->GetString(prefs::kApplicationLocale) != owner_locale && + std::string pref_locale = local_state->GetString(prefs::kApplicationLocale); + language::ConvertToActualUILocale(&pref_locale); + if (!owner_locale.empty() && pref_locale != owner_locale && !local_state->IsManagedPreference(prefs::kApplicationLocale)) { local_state->SetString(prefs::kApplicationLocale, owner_locale); return true;
diff --git a/chrome/browser/lifetime/browser_close_manager_browsertest.cc b/chrome/browser/lifetime/browser_close_manager_browsertest.cc index 7a53077..6ca3c12b 100644 --- a/chrome/browser/lifetime/browser_close_manager_browsertest.cc +++ b/chrome/browser/lifetime/browser_close_manager_browsertest.cc
@@ -215,10 +215,11 @@ static void SetDangerous(const content::DownloadTargetCallback& callback, const base::FilePath& target_path, content::DownloadItem::TargetDisposition disp, - content::DownloadDangerType danger_type, + download::DownloadDangerType danger_type, const base::FilePath& intermediate_path, content::DownloadInterruptReason reason) { - callback.Run(target_path, disp, content::DOWNLOAD_DANGER_TYPE_DANGEROUS_URL, + callback.Run(target_path, disp, + download::DOWNLOAD_DANGER_TYPE_DANGEROUS_URL, intermediate_path, reason); } };
diff --git a/chrome/browser/mac/exception_processor_unittest.mm b/chrome/browser/mac/exception_processor_unittest.mm index 445a2b8..8ef87aca 100644 --- a/chrome/browser/mac/exception_processor_unittest.mm +++ b/chrome/browser/mac/exception_processor_unittest.mm
@@ -9,16 +9,10 @@ #include <sys/wait.h> #include "base/mac/os_crash_dumps.h" -#include "base/metrics/histogram_macros.h" -#include "base/metrics/histogram_samples.h" -#include "base/metrics/statistics_recorder.h" +#include "base/test/histogram_tester.h" #include "testing/gmock/include/gmock/gmock.h" #include "testing/gtest/include/gtest/gtest.h" -using base::HistogramBase; -using base::HistogramSamples; -using base::StatisticsRecorder; - namespace chrome { // Generate an NSException with the given name. @@ -48,9 +42,7 @@ } TEST(ExceptionProcessorTest, RecordException) { - EXPECT_THAT(StatisticsRecorder::WithName(StatisticsRecorder::GetHistograms(), - "OSX.NSException"), - testing::IsEmpty()); + base::HistogramTester tester; // Record some known exceptions. RecordExceptionWithUma(ExceptionNamed(NSGenericException)); @@ -71,23 +63,14 @@ RecordExceptionWithUma(nil); // We should have exactly the right number of exceptions. - const StatisticsRecorder::Histograms histograms = - StatisticsRecorder::WithName(StatisticsRecorder::GetHistograms(), - "OSX.NSException"); - ASSERT_THAT(histograms, testing::SizeIs(1)); - EXPECT_EQ(HistogramBase::kUmaTargetedHistogramFlag, histograms[0]->flags()); - - std::unique_ptr<HistogramSamples> samples(histograms[0]->SnapshotSamples()); - EXPECT_EQ(4, samples->GetCount(0)); - EXPECT_EQ(1, samples->GetCount(1)); - EXPECT_EQ(3, samples->GetCount(2)); - EXPECT_EQ(2, samples->GetCount(3)); + const char kHistogramName[] = "OSX.NSException"; + tester.ExpectBucketCount(kHistogramName, 0, 4); + tester.ExpectBucketCount(kHistogramName, 1, 1); + tester.ExpectBucketCount(kHistogramName, 2, 3); + tester.ExpectBucketCount(kHistogramName, 3, 2); // The unknown exceptions should end up in the overflow bucket. - EXPECT_TRUE(histograms[0]->HasConstructionArguments(1, - kUnknownNSException, - kUnknownNSException + 1)); - EXPECT_EQ(4, samples->GetCount(kUnknownNSException)); + tester.ExpectBucketCount(kHistogramName, kUnknownNSException, 4); } void RaiseExceptionInRunLoop() {
diff --git a/chrome/browser/media/media_engagement_contents_observer_unittest.cc b/chrome/browser/media/media_engagement_contents_observer_unittest.cc index 29d923c4..1b5e0911 100644 --- a/chrome/browser/media/media_engagement_contents_observer_unittest.cc +++ b/chrome/browser/media/media_engagement_contents_observer_unittest.cc
@@ -674,7 +674,7 @@ Navigate(url); SimulateAudible(); SimulateSignificantPlaybackTimeForPage(); - ExpectScores(url, 0.0, 2, 1, 0, 0); + ExpectScores(url, 0.05, 2, 1, 0, 0); } TEST_F(MediaEngagementContentsObserverTest, @@ -734,7 +734,7 @@ Navigate(url3); SimulateAudioVideoPlaybackStarted(0); tester.ExpectBucketCount( - MediaEngagementContentsObserver::kHistogramScoreAtPlaybackName, 0, 1); + MediaEngagementContentsObserver::kHistogramScoreAtPlaybackName, 20, 1); tester.ExpectTotalCount( MediaEngagementContentsObserver::kHistogramScoreAtPlaybackName, 4); @@ -915,11 +915,11 @@ SimulateSignificantPlaybackTimeForPlayer(0); SimulateSignificantPlaybackTimeForPlayer(1); SimulateSignificantPlaybackTimeForPlayer(2); - ExpectScores(url, 0, 1, 1, 0, 0); + ExpectScores(url, 0.05, 1, 1, 0, 0); // Test that when we destroy the audible players the scores are recorded. SimulateDestroy(); - ExpectScores(url, 0, 1, 1, 3, 3); + ExpectScores(url, 0.05, 1, 1, 3, 3); } TEST_F(MediaEngagementContentsObserverTest, RecordAudiblePlayers_OnNavigate) { @@ -947,18 +947,18 @@ SimulateSignificantPlaybackTimeForPlayer(0); SimulateSignificantPlaybackTimeForPlayer(1); SimulateSignificantPlaybackTimeForPlayer(2); - ExpectScores(url, 0, 1, 1, 0, 0); + ExpectScores(url, 0.05, 1, 1, 0, 0); // Navigate to a sub page and continue watching. Navigate(GURL("https://www.google.com/test")); SimulateSignificantAudioPlayer(1); SimulateLongMediaPlayback(1); - ExpectScores(url, 0, 1, 1, 0, 0); + ExpectScores(url, 0.05, 1, 1, 0, 0); // Test that when we navigate to a new origin the audible players the scores // are recorded. Navigate(GURL("https://www.google.co.uk")); - ExpectScores(url, 0, 1, 1, 4, 3); + ExpectScores(url, 0.05, 1, 1, 4, 3); } TEST_F(MediaEngagementContentsObserverTest, TimerSpecificToPlayer) {
diff --git a/chrome/browser/media/media_engagement_score.cc b/chrome/browser/media/media_engagement_score.cc index 7ffa50b..ba49283 100644 --- a/chrome/browser/media/media_engagement_score.cc +++ b/chrome/browser/media/media_engagement_score.cc
@@ -201,12 +201,10 @@ } void MediaEngagementScore::Recalculate() { - // Update the engagement score. - actual_score_ = 0; - if (visits() >= GetScoreMinVisits()) { - actual_score_ = - static_cast<double>(media_playbacks()) / static_cast<double>(visits()); - } + // Use the minimum visits to compute the score to allow websites that would + // surely have a high MEI to pass the bar early. + double effective_visits = std::max(visits(), GetScoreMinVisits()); + actual_score_ = static_cast<double>(media_playbacks()) / effective_visits; // Recalculate whether the engagement score is considered high. if (is_high_) {
diff --git a/chrome/browser/media/media_engagement_score_unittest.cc b/chrome/browser/media/media_engagement_score_unittest.cc index 0f9fc0d..b6d8ea7 100644 --- a/chrome/browser/media/media_engagement_score_unittest.cc +++ b/chrome/browser/media/media_engagement_score_unittest.cc
@@ -343,10 +343,9 @@ EXPECT_EQ(0, score_->actual_score()); UpdateScore(score_); - // Check that the score is zero even with 1 visit. - EXPECT_EQ(0.0, score_->actual_score()); + // Check that the score increases when there is one visit. + EXPECT_EQ(0.05, score_->actual_score()); - EXPECT_EQ(0, score_->actual_score()); SetScore(20, 8); EXPECT_EQ(0.4, score_->actual_score()); @@ -429,9 +428,9 @@ EXPECT_FALSE(score_->high_score()); EXPECT_EQ(0.85, MediaEngagementScore::GetHighScoreLowerThreshold()); - // Raise the minimum visits, the score will now be zero as it does not meet - // the threshold requirements. + // Raise the minimum visits, the score will now be relative to this new + // visits requirements. OverrideFieldTrial(25, 0.85, 0.9); - EXPECT_EQ(0.0, score_->actual_score()); + EXPECT_EQ(0.64, score_->actual_score()); EXPECT_EQ(25, MediaEngagementScore::GetScoreMinVisits()); }
diff --git a/chrome/browser/media/media_engagement_service.cc b/chrome/browser/media/media_engagement_service.cc index 1ee9130..e925906 100644 --- a/chrome/browser/media/media_engagement_service.cc +++ b/chrome/browser/media/media_engagement_service.cc
@@ -290,6 +290,11 @@ content_settings::ResourceIdentifier(), &content_settings); + // `GetSettingsForOneType` mixes incognito and non-incognito results in + // incognito profiles creating duplicates. The incognito results are first so + // we should discard the results following. + std::map<GURL, const ContentSettingPatternSource*> filtered_results; + for (const auto& site : content_settings) { GURL origin(site.primary_pattern.ToString()); if (!origin.is_valid()) { @@ -297,8 +302,21 @@ continue; } + const auto& result = filtered_results.find(origin); + if (result != filtered_results.end()) { + DCHECK(result->second->incognito && !site.incognito); + continue; + } + + filtered_results[origin] = &site; + } + + for (const auto& it : filtered_results) { + const auto& origin = it.first; + auto* const site = it.second; + std::unique_ptr<base::Value> clone = - std::make_unique<base::Value>(site.setting_value->Clone()); + std::make_unique<base::Value>(site->setting_value->Clone()); data.push_back(MediaEngagementScore( clock_, origin, base::DictionaryValue::From(std::move(clone)),
diff --git a/chrome/browser/media/media_engagement_service_unittest.cc b/chrome/browser/media/media_engagement_service_unittest.cc index ff47b29b..d6d1fd3 100644 --- a/chrome/browser/media/media_engagement_service_unittest.cc +++ b/chrome/browser/media/media_engagement_service_unittest.cc
@@ -209,6 +209,15 @@ void SetSchemaVersion(int version) { service_->SetSchemaVersion(version); } + std::vector<MediaEngagementScore> GetAllStoredScores( + const MediaEngagementService* service) const { + return service->GetAllStoredScores(); + } + + std::vector<MediaEngagementScore> GetAllStoredScores() const { + return GetAllStoredScores(service_.get()); + } + private: base::SimpleTestClock test_clock_; @@ -250,19 +259,19 @@ GURL url1("https://www.google.com"); ExpectScores(url1, 0.0, 0, 0, TimeNotSet()); RecordVisitAndPlaybackAndAdvanceClock(url1); - ExpectScores(url1, 0.0, 1, 1, Now()); + ExpectScores(url1, 0.05, 1, 1, Now()); RecordVisit(url1); - ExpectScores(url1, 0.0, 2, 1, Now()); + ExpectScores(url1, 0.05, 2, 1, Now()); RecordPlayback(url1); - ExpectScores(url1, 0.0, 2, 2, Now()); + ExpectScores(url1, 0.1, 2, 2, Now()); base::Time url1_time = Now(); GURL url2("https://www.google.co.uk"); RecordVisitAndPlaybackAndAdvanceClock(url2); - ExpectScores(url2, 0.0, 1, 1, Now()); - ExpectScores(url1, 0.0, 2, 2, url1_time); + ExpectScores(url2, 0.05, 1, 1, Now()); + ExpectScores(url1, 0.1, 2, 2, url1_time); } TEST_F(MediaEngagementServiceTest, IncognitoEngagementService) { @@ -277,8 +286,8 @@ MediaEngagementService* incognito_service = MediaEngagementService::Get(profile()->GetOffTheRecordProfile()); - ExpectScores(incognito_service, url1, 0.0, 1, 1, url1_time); - ExpectScores(incognito_service, url2, 0.0, 1, 1, Now()); + ExpectScores(incognito_service, url1, 0.05, 1, 1, url1_time); + ExpectScores(incognito_service, url2, 0.05, 1, 1, Now()); ExpectScores(incognito_service, url3, 0.0, 0, 0, TimeNotSet()); incognito_service->RecordVisit(url3); @@ -286,17 +295,90 @@ ExpectScores(url3, 0.0, 0, 0, TimeNotSet()); incognito_service->RecordVisit(url2); - ExpectScores(incognito_service, url2, 0.0, 2, 1, Now()); - ExpectScores(url2, 0.0, 1, 1, Now()); + ExpectScores(incognito_service, url2, 0.05, 2, 1, Now()); + ExpectScores(url2, 0.05, 1, 1, Now()); RecordVisitAndPlaybackAndAdvanceClock(url3); ExpectScores(incognito_service, url3, 0.0, 1, 0, TimeNotSet()); - ExpectScores(url3, 0.0, 1, 1, Now()); + ExpectScores(url3, 0.05, 1, 1, Now()); ExpectScores(incognito_service, url4, 0.0, 0, 0, TimeNotSet()); RecordVisitAndPlaybackAndAdvanceClock(url4); - ExpectScores(incognito_service, url4, 0.0, 1, 1, Now()); - ExpectScores(url4, 0.0, 1, 1, Now()); + ExpectScores(incognito_service, url4, 0.05, 1, 1, Now()); + ExpectScores(url4, 0.05, 1, 1, Now()); +} + +TEST_F(MediaEngagementServiceTest, IncognitoOverrideRegularProfile) { + const GURL kUrl1("https://example.org"); + const GURL kUrl2("https://example.com"); + + SetScores(kUrl1, MediaEngagementScore::GetScoreMinVisits(), 1); + SetScores(kUrl2, 1, 0); + + ExpectScores(kUrl1, 0.05, MediaEngagementScore::GetScoreMinVisits(), 1, + TimeNotSet()); + ExpectScores(kUrl2, 0.0, 1, 0, TimeNotSet()); + + MediaEngagementService* incognito_service = + MediaEngagementService::Get(profile()->GetOffTheRecordProfile()); + ExpectScores(incognito_service, kUrl1, 0.05, + MediaEngagementScore::GetScoreMinVisits(), 1, TimeNotSet()); + ExpectScores(incognito_service, kUrl2, 0.0, 1, 0, TimeNotSet()); + + // Scores should be the same in incognito and regular profile. + { + std::vector<std::pair<GURL, double>> kExpectedResults = { + {kUrl2, 0.0}, {kUrl1, 0.05}, + }; + + const auto& scores = GetAllStoredScores(); + const auto& incognito_scores = GetAllStoredScores(incognito_service); + + EXPECT_EQ(kExpectedResults.size(), scores.size()); + EXPECT_EQ(kExpectedResults.size(), incognito_scores.size()); + + for (size_t i = 0; i < scores.size(); ++i) { + EXPECT_EQ(kExpectedResults[i].first, scores[i].origin()); + EXPECT_EQ(kExpectedResults[i].second, scores[i].actual_score()); + + EXPECT_EQ(kExpectedResults[i].first, incognito_scores[i].origin()); + EXPECT_EQ(kExpectedResults[i].second, incognito_scores[i].actual_score()); + } + } + + incognito_service->RecordVisit(kUrl1); + incognito_service->RecordPlayback(kUrl2); + + // Score shouldn't have changed in regular profile. + { + std::vector<std::pair<GURL, double>> kExpectedResults = { + {kUrl2, 0.0}, {kUrl1, 0.05}, + }; + + const auto& scores = GetAllStoredScores(); + EXPECT_EQ(kExpectedResults.size(), scores.size()); + + for (size_t i = 0; i < scores.size(); ++i) { + EXPECT_EQ(kExpectedResults[i].first, scores[i].origin()); + EXPECT_EQ(kExpectedResults[i].second, scores[i].actual_score()); + } + } + + // Incognito scores should have the same number of entries but have new + // values. + { + std::vector<std::pair<GURL, double>> kExpectedResults = { + {kUrl2, 0.05}, {kUrl1, 1.0 / 21.0}, + }; + + const auto& scores = GetAllStoredScores(incognito_service); + EXPECT_EQ(kExpectedResults.size(), scores.size()); + + for (size_t i = 0; i < scores.size(); ++i) { + EXPECT_EQ(kExpectedResults[i].first, scores[i].origin()); + EXPECT_EQ(kExpectedResults[i].second, scores[i].actual_score()); + } + } } TEST_F(MediaEngagementServiceTest, CleanupOriginsOnHistoryDeletion) { @@ -338,14 +420,14 @@ // Check that the scores are valid at the beginning. ExpectScores(origin1, 7.0 / 11.0, MediaEngagementScore::GetScoreMinVisits() + 2, 14, TimeNotSet()); - EXPECT_TRUE(GetActualScore(origin1)); - ExpectScores(origin2, 0.0, 2, 1, TimeNotSet()); - EXPECT_FALSE(GetActualScore(origin2)); - ExpectScores(origin3, 0.0, 2, 1, TimeNotSet()); - EXPECT_FALSE(GetActualScore(origin3)); + EXPECT_EQ(14.0 / 22.0, GetActualScore(origin1)); + ExpectScores(origin2, 0.05, 2, 1, TimeNotSet()); + EXPECT_EQ(1 / 20.0, GetActualScore(origin2)); + ExpectScores(origin3, 0.05, 2, 1, TimeNotSet()); + EXPECT_EQ(1 / 20.0, GetActualScore(origin3)); ExpectScores(origin4, 0.5, MediaEngagementScore::GetScoreMinVisits(), 10, TimeNotSet()); - EXPECT_TRUE(GetActualScore(origin4)); + EXPECT_EQ(0.5, GetActualScore(origin4)); { base::HistogramTester histogram_tester; @@ -364,9 +446,9 @@ // visits. origin4 should have the old score. ExpectScores(origin1, 0.6, MediaEngagementScore::GetScoreMinVisits(), 12, TimeNotSet()); - EXPECT_TRUE(GetActualScore(origin1)); + EXPECT_EQ(12.0 / 20.0, GetActualScore(origin1)); ExpectScores(origin2, 0.0, 1, 0, TimeNotSet()); - EXPECT_FALSE(GetActualScore(origin2)); + EXPECT_EQ(0, GetActualScore(origin2)); ExpectScores(origin3, 0.0, 1, 0, TimeNotSet()); ExpectScores(origin4, 0.5, MediaEngagementScore::GetScoreMinVisits(), 10, TimeNotSet()); @@ -374,7 +456,7 @@ histogram_tester.ExpectTotalCount( MediaEngagementService::kHistogramURLsDeletedScoreReductionName, 3); histogram_tester.ExpectBucketCount( - MediaEngagementService::kHistogramURLsDeletedScoreReductionName, 0, 2); + MediaEngagementService::kHistogramURLsDeletedScoreReductionName, 5, 2); histogram_tester.ExpectBucketCount( MediaEngagementService::kHistogramURLsDeletedScoreReductionName, 4, 1); } @@ -396,7 +478,7 @@ waiter.Wait(); // origin1's score should have changed but the rest should remain the same. - ExpectScores(origin1, 0.0, MediaEngagementScore::GetScoreMinVisits() - 1, + ExpectScores(origin1, 0.55, MediaEngagementScore::GetScoreMinVisits() - 1, 11, TimeNotSet()); ExpectScores(origin2, 0.0, 1, 0, TimeNotSet()); ExpectScores(origin3, 0.0, 1, 0, TimeNotSet()); @@ -406,7 +488,7 @@ histogram_tester.ExpectTotalCount( MediaEngagementService::kHistogramURLsDeletedScoreReductionName, 1); histogram_tester.ExpectBucketCount( - MediaEngagementService::kHistogramURLsDeletedScoreReductionName, 60, 1); + MediaEngagementService::kHistogramURLsDeletedScoreReductionName, 5, 1); } { @@ -428,7 +510,7 @@ // origin3's score should be removed but the rest should remain the same. std::map<GURL, double> scores = GetScoreMapForTesting(); EXPECT_TRUE(scores.find(origin3) == scores.end()); - ExpectScores(origin1, 0.0, MediaEngagementScore::GetScoreMinVisits() - 1, + ExpectScores(origin1, 0.55, MediaEngagementScore::GetScoreMinVisits() - 1, 11, TimeNotSet()); ExpectScores(origin2, 0.0, 1, 0, TimeNotSet()); ExpectScores(origin3, 0.0, 0, 0, TimeNotSet()); @@ -454,7 +536,7 @@ ClearDataBetweenTime(today - base::TimeDelta::FromDays(2), today - base::TimeDelta::FromDays(1)); - ExpectScores(origin, 0.0, 1, 1, today); + ExpectScores(origin, 0.05, 1, 1, today); } TEST_F(MediaEngagementServiceTest, @@ -473,8 +555,8 @@ SetLastMediaPlaybackTime(origin2, two_days_ago); ClearDataBetweenTime(two_days_ago, yesterday); - ExpectScores(origin1, 0.0, 0, 0, TimeNotSet()); - ExpectScores(origin2, 0.0, 0, 0, TimeNotSet()); + ExpectScores(origin1, 0, 0, 0, TimeNotSet()); + ExpectScores(origin2, 0, 0, 0, TimeNotSet()); } TEST_F(MediaEngagementServiceTest, CleanupDataOnSiteDataCleanup_NoTimeSet) { @@ -501,7 +583,7 @@ ExpectScores(url1, 5.0 / 6.0, 24, 20, TimeNotSet()); ExpectScores(url2, 0.5, 24, 12, TimeNotSet()); - ExpectScores(url3, 0.0, 1, 1, Now()); + ExpectScores(url3, 0.05, 1, 1, Now()); base::HistogramTester histogram_tester; std::unique_ptr<MediaEngagementService> new_service = @@ -512,7 +594,7 @@ histogram_tester.ExpectTotalCount( MediaEngagementService::kHistogramScoreAtStartupName, 3); histogram_tester.ExpectBucketCount( - MediaEngagementService::kHistogramScoreAtStartupName, 0, 1); + MediaEngagementService::kHistogramScoreAtStartupName, 5, 1); histogram_tester.ExpectBucketCount( MediaEngagementService::kHistogramScoreAtStartupName, 50, 1); histogram_tester.ExpectBucketCount( @@ -553,6 +635,6 @@ base::WrapUnique<MediaEngagementService>( StartNewMediaEngagementService()); - ExpectScores(new_service.get(), url, 0.0, 1, 2, TimeNotSet()); + ExpectScores(new_service.get(), url, 0.1, 1, 2, TimeNotSet()); new_service->Shutdown(); }
diff --git a/chrome/browser/media/media_engagement_session_unittest.cc b/chrome/browser/media/media_engagement_session_unittest.cc index 253456aa..b484fc2 100644 --- a/chrome/browser/media/media_engagement_session_unittest.cc +++ b/chrome/browser/media/media_engagement_session_unittest.cc
@@ -548,7 +548,7 @@ ukm_entry, Entry::kPlaybacks_TotalName)); EXPECT_EQ(1, *test_ukm_recorder().GetEntryMetric(ukm_entry, Entry::kVisits_TotalName)); - EXPECT_EQ(0, *test_ukm_recorder().GetEntryMetric( + EXPECT_EQ(5, *test_ukm_recorder().GetEntryMetric( ukm_entry, Entry::kEngagement_ScoreName)); EXPECT_EQ(1, *test_ukm_recorder().GetEntryMetric( ukm_entry, Entry::kPlaybacks_DeltaName)); @@ -581,8 +581,8 @@ ukm_entry, Entry::kPlaybacks_TotalName)); EXPECT_EQ(1, *test_ukm_recorder().GetEntryMetric(ukm_entry, Entry::kVisits_TotalName)); - EXPECT_EQ(0, *test_ukm_recorder().GetEntryMetric( - ukm_entry, Entry::kEngagement_ScoreName)); + EXPECT_EQ(10, *test_ukm_recorder().GetEntryMetric( + ukm_entry, Entry::kEngagement_ScoreName)); EXPECT_EQ(1, *test_ukm_recorder().GetEntryMetric( ukm_entry, Entry::kPlaybacks_DeltaName)); EXPECT_EQ(0, *test_ukm_recorder().GetEntryMetric(
diff --git a/chrome/browser/media/unified_autoplay_browsertest.cc b/chrome/browser/media/unified_autoplay_browsertest.cc index 83aedaa..149a6dfa 100644 --- a/chrome/browser/media/unified_autoplay_browsertest.cc +++ b/chrome/browser/media/unified_autoplay_browsertest.cc
@@ -38,13 +38,21 @@ } content::WebContents* OpenNewTab(const GURL& url, bool from_context_menu) { - return OpenInternal(url, from_context_menu, - WindowOpenDisposition::NEW_FOREGROUND_TAB); + return OpenInternal( + url, from_context_menu, WindowOpenDisposition::NEW_FOREGROUND_TAB, + false /* is_renderer_initiated */, true /* user_gesture */); } content::WebContents* OpenNewWindow(const GURL& url, bool from_context_menu) { - return OpenInternal(url, from_context_menu, - WindowOpenDisposition::NEW_WINDOW); + return OpenInternal( + url, from_context_menu, WindowOpenDisposition::NEW_WINDOW, + false /* is_renderer_initiated */, true /* user_gesture */); + } + + content::WebContents* OpenFromRenderer(const GURL& url, bool user_gesture) { + return OpenInternal(url, false /* from_context_menu */, + WindowOpenDisposition::NEW_FOREGROUND_TAB, + true /* is_renderer_initiated */, user_gesture); } bool AttemptPlay(content::WebContents* web_contents) { @@ -57,7 +65,9 @@ private: content::WebContents* OpenInternal(const GURL& url, bool from_context_menu, - WindowOpenDisposition disposition) { + WindowOpenDisposition disposition, + bool is_renderer_initiated, + bool user_gesture) { content::WebContents* active_contents = browser()->tab_strip_model()->GetActiveWebContents(); @@ -65,14 +75,15 @@ active_contents->GetLastCommittedURL(), blink::WebReferrerPolicy::kWebReferrerPolicyAlways); - content::OpenURLParams open_url_params(url, referrer, disposition, - ui::PAGE_TRANSITION_LINK, false, - from_context_menu); + content::OpenURLParams open_url_params( + url, referrer, disposition, ui::PAGE_TRANSITION_LINK, + is_renderer_initiated, from_context_menu); open_url_params.source_render_process_id = active_contents->GetMainFrame()->GetProcess()->GetID(); open_url_params.source_render_frame_id = active_contents->GetMainFrame()->GetRoutingID(); + open_url_params.user_gesture = user_gesture; return active_contents->OpenURL(open_url_params); } @@ -146,3 +157,23 @@ EXPECT_FALSE(AttemptPlay(new_contents)); } + +IN_PROC_BROWSER_TEST_F(UnifiedAutoplayBrowserTest, OpenFromRendererGesture) { + const GURL kTestPageUrl = embedded_test_server()->GetURL(kTestPagePath); + + ui_test_utils::NavigateToURL(browser(), kTestPageUrl); + + content::WebContents* new_contents = OpenFromRenderer(kTestPageUrl, true); + content::WaitForLoadStop(new_contents); + + EXPECT_TRUE(AttemptPlay(new_contents)); +} + +IN_PROC_BROWSER_TEST_F(UnifiedAutoplayBrowserTest, OpenFromRendererNoGesture) { + const GURL kTestPageUrl = embedded_test_server()->GetURL(kTestPagePath); + + ui_test_utils::NavigateToURL(browser(), kTestPageUrl); + + content::WebContents* new_contents = OpenFromRenderer(kTestPageUrl, false); + EXPECT_EQ(nullptr, new_contents); +}
diff --git a/chrome/browser/media/webrtc/desktop_media_picker.cc b/chrome/browser/media/webrtc/desktop_media_picker.cc new file mode 100644 index 0000000..39d33cc --- /dev/null +++ b/chrome/browser/media/webrtc/desktop_media_picker.cc
@@ -0,0 +1,8 @@ +// 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 "desktop_media_picker.h" + +DesktopMediaPicker::Params::Params() = default; +DesktopMediaPicker::Params::~Params() = default;
diff --git a/chrome/browser/media/webrtc/desktop_media_picker.h b/chrome/browser/media/webrtc/desktop_media_picker.h index 6cb1b8e..9aed4c7 100644 --- a/chrome/browser/media/webrtc/desktop_media_picker.h +++ b/chrome/browser/media/webrtc/desktop_media_picker.h
@@ -11,6 +11,7 @@ #include "base/macros.h" #include "base/strings/string16.h" #include "content/public/browser/desktop_media_id.h" +#include "ui/base/ui_base_types.h" #include "ui/gfx/native_widget_types.h" class DesktopMediaList; @@ -20,10 +21,33 @@ } // Abstract interface for desktop media picker UI. It's used by Desktop Media -// API to let user choose a desktop media source. +// API and by ARC to let user choose a desktop media source. class DesktopMediaPicker { public: typedef base::Callback<void(content::DesktopMediaID)> DoneCallback; + struct Params { + Params(); + ~Params(); + + // WebContents this picker is relative to, can be null. + content::WebContents* web_contents = nullptr; + // The context whose root window is used for dialog placement, cannot be + // null for Aura. + gfx::NativeWindow context = nullptr; + // Parent window the dialog is relative to, only used on Mac. + gfx::NativeWindow parent = nullptr; + // The modality used for showing the dialog. + ui::ModalType modality = ui::ModalType::MODAL_TYPE_CHILD; + // The name used in the dialog for what is requesting the picker to be + // shown. + base::string16 app_name; + // Can be the same as target_name. If it is not then this is used in the + // dialog for what is specific target within the app_name is requesting the + // picker. + base::string16 target_name; + // Whether audio capture should be shown as an option in the picker. + bool request_audio = false; + }; // Creates default implementation of DesktopMediaPicker for the current // platform. @@ -33,16 +57,11 @@ virtual ~DesktopMediaPicker() {} // Shows dialog with list of desktop media sources (screens, windows, tabs) - // provided by |screen_list|, |window_list| and |tab_list|. + // provided by |sources_lists|. // Dialog window will call |done_callback| when user chooses one of the // sources or closes the dialog. - virtual void Show(content::WebContents* web_contents, - gfx::NativeWindow context, - gfx::NativeWindow parent, - const base::string16& app_name, - const base::string16& target_name, + virtual void Show(const Params& params, std::vector<std::unique_ptr<DesktopMediaList>> source_lists, - bool request_audio, const DoneCallback& done_callback) = 0; private:
diff --git a/chrome/browser/metrics/tab_stats_data_store.cc b/chrome/browser/metrics/tab_stats_data_store.cc index 44e74b0..8225317 100644 --- a/chrome/browser/metrics/tab_stats_data_store.cc +++ b/chrome/browser/metrics/tab_stats_data_store.cc
@@ -25,11 +25,11 @@ : pref_service_(pref_service) { DCHECK(pref_service != nullptr); tab_stats_.total_tab_count_max = - pref_service->GetInteger(prefs::kTabStatsTotalTabCountMax); + pref_service->GetInteger(::prefs::kTabStatsTotalTabCountMax); tab_stats_.max_tab_per_window = - pref_service->GetInteger(prefs::kTabStatsMaxTabsPerWindow); + pref_service->GetInteger(::prefs::kTabStatsMaxTabsPerWindow); tab_stats_.window_count_max = - pref_service->GetInteger(prefs::kTabStatsWindowCountMax); + pref_service->GetInteger(::prefs::kTabStatsWindowCountMax); } void TabStatsDataStore::OnWindowAdded() { @@ -61,7 +61,7 @@ if (value <= tab_stats_.max_tab_per_window) return; tab_stats_.max_tab_per_window = value; - pref_service_->SetInteger(prefs::kTabStatsMaxTabsPerWindow, value); + pref_service_->SetInteger(::prefs::kTabStatsMaxTabsPerWindow, value); } void TabStatsDataStore::ResetMaximumsToCurrentState() { @@ -88,7 +88,7 @@ if (tab_stats_.total_tab_count <= tab_stats_.total_tab_count_max) return; tab_stats_.total_tab_count_max = tab_stats_.total_tab_count; - pref_service_->SetInteger(prefs::kTabStatsTotalTabCountMax, + pref_service_->SetInteger(::prefs::kTabStatsTotalTabCountMax, tab_stats_.total_tab_count_max); } @@ -97,7 +97,7 @@ if (tab_stats_.window_count <= tab_stats_.window_count_max) return; tab_stats_.window_count_max = tab_stats_.window_count; - pref_service_->SetInteger(prefs::kTabStatsWindowCountMax, + pref_service_->SetInteger(::prefs::kTabStatsWindowCountMax, tab_stats_.window_count_max); }
diff --git a/chrome/browser/metrics/tab_stats_tracker.cc b/chrome/browser/metrics/tab_stats_tracker.cc index 9563453..642c51d 100644 --- a/chrome/browser/metrics/tab_stats_tracker.cc +++ b/chrome/browser/metrics/tab_stats_tracker.cc
@@ -58,7 +58,7 @@ tab_stats_data_store_(base::MakeUnique<TabStatsDataStore>(pref_service)), daily_event_( base::MakeUnique<DailyEvent>(pref_service, - prefs::kTabStatsDailySample, + ::prefs::kTabStatsDailySample, kTabStatsDailyEventHistogramName)) { DCHECK(pref_service != nullptr); // Get the list of existing windows/tabs. There shouldn't be any if this is @@ -111,10 +111,10 @@ } void TabStatsTracker::RegisterPrefs(PrefRegistrySimple* registry) { - registry->RegisterIntegerPref(prefs::kTabStatsTotalTabCountMax, 0); - registry->RegisterIntegerPref(prefs::kTabStatsMaxTabsPerWindow, 0); - registry->RegisterIntegerPref(prefs::kTabStatsWindowCountMax, 0); - DailyEvent::RegisterPref(registry, prefs::kTabStatsDailySample); + registry->RegisterIntegerPref(::prefs::kTabStatsTotalTabCountMax, 0); + registry->RegisterIntegerPref(::prefs::kTabStatsMaxTabsPerWindow, 0); + registry->RegisterIntegerPref(::prefs::kTabStatsWindowCountMax, 0); + DailyEvent::RegisterPref(registry, ::prefs::kTabStatsDailySample); } void TabStatsTracker::TabStatsDailyObserver::OnDailyEvent(
diff --git a/chrome/browser/net/OWNERS b/chrome/browser/net/OWNERS index 6e9ab05a..7123cf4 100644 --- a/chrome/browser/net/OWNERS +++ b/chrome/browser/net/OWNERS
@@ -1,5 +1,6 @@ file://net/OWNERS +per-file *predictor*=alexilin@chromium.org per-file disk_cache_dir_policy_handler*=atwilson@chromium.org # COMPONENT: Internals>Network
diff --git a/chrome/browser/net/predictor_browsertest.cc b/chrome/browser/net/predictor_browsertest.cc index f2d4710..d2f195fa 100644 --- a/chrome/browser/net/predictor_browsertest.cc +++ b/chrome/browser/net/predictor_browsertest.cc
@@ -23,12 +23,14 @@ #include "base/single_thread_task_runner.h" #include "base/stl_util.h" #include "base/synchronization/lock.h" +#include "base/test/scoped_feature_list.h" #include "base/threading/thread_task_runner_handle.h" #include "build/build_config.h" #include "chrome/browser/browser_process.h" #include "chrome/browser/browsing_data/browsing_data_helper.h" #include "chrome/browser/browsing_data/chrome_browsing_data_remover_delegate.h" #include "chrome/browser/net/predictor.h" +#include "chrome/browser/predictors/loading_predictor_config.h" #include "chrome/browser/profiles/profile.h" #include "chrome/browser/ui/browser.h" #include "chrome/browser/ui/tabs/tab_strip_model.h" @@ -514,6 +516,8 @@ Predictor::kMaxSpeculativeResolveQueueDelayMs + 300); rule_based_resolver_proc_->AddRuleWithLatency("delay.google.com", "127.0.0.1", 1000 * 60); + scoped_feature_list_.InitAndDisableFeature( + predictors::kSpeculativePreconnectFeature); } ~PredictorBrowserTest() override {} @@ -804,6 +808,8 @@ EXPECT_TRUE(result); } + base::test::ScopedFeatureList scoped_feature_list_; + const GURL startup_url_; const GURL referring_url_; const GURL target_url_;
diff --git a/chrome/browser/notifications/notification_platform_bridge_linux.cc b/chrome/browser/notifications/notification_platform_bridge_linux.cc index 7390936..0f332ed 100644 --- a/chrome/browser/notifications/notification_platform_bridge_linux.cc +++ b/chrome/browser/notifications/notification_platform_bridge_linux.cc
@@ -18,6 +18,7 @@ #include "base/files/file_util.h" #include "base/i18n/number_formatting.h" #include "base/metrics/histogram_macros.h" +#include "base/numerics/ranges.h" #include "base/strings/nullable_string16.h" #include "base/strings/string_number_conversions.h" #include "base/strings/string_split.h" @@ -109,10 +110,6 @@ NUM_ITEMS }; -int ClampInt(int value, int low, int hi) { - return std::max(std::min(value, hi), low); -} - base::string16 CreateNotificationTitle( const message_center::Notification& notification) { base::string16 title; @@ -164,8 +161,8 @@ const SkBitmap* image_bitmap = image.ToSkBitmap(); double scale = std::min(static_cast<double>(kMaxImageWidth) / width, static_cast<double>(kMaxImageHeight) / height); - width = ClampInt(scale * width, 1, kMaxImageWidth); - height = ClampInt(scale * height, 1, kMaxImageHeight); + width = base::ClampToRange<int>(scale * width, 1, kMaxImageWidth); + height = base::ClampToRange<int>(scale * height, 1, kMaxImageHeight); return gfx::Image( gfx::ImageSkia::CreateFrom1xBitmap(skia::ImageOperations::Resize( *image_bitmap, skia::ImageOperations::RESIZE_LANCZOS3, width,
diff --git a/chrome/browser/ntp_snippets/content_suggestions_service_factory.cc b/chrome/browser/ntp_snippets/content_suggestions_service_factory.cc index 4002ea6..3fee001 100644 --- a/chrome/browser/ntp_snippets/content_suggestions_service_factory.cc +++ b/chrome/browser/ntp_snippets/content_suggestions_service_factory.cc
@@ -25,6 +25,7 @@ #include "chrome/browser/ntp_snippets/dependent_features.h" #include "chrome/browser/profiles/profile.h" #include "chrome/browser/search/suggestions/image_decoder_impl.h" +#include "chrome/browser/signin/identity_manager_factory.h" #include "chrome/browser/signin/profile_oauth2_token_service_factory.h" #include "chrome/browser/signin/signin_manager_factory.h" #include "chrome/browser/sync/profile_sync_service_factory.h" @@ -338,8 +339,8 @@ } PrefService* pref_service = profile->GetPrefs(); - OAuth2TokenService* token_service = - ProfileOAuth2TokenServiceFactory::GetForProfile(profile); + identity::IdentityManager* identity_manager = + IdentityManagerFactory::GetForProfile(profile); UrlLanguageHistogram* language_histogram = UrlLanguageHistogramFactory::GetForBrowserContext(profile); @@ -375,8 +376,7 @@ } #endif // BUILDFLAG(ENABLE_OFFLINE_PAGES) auto suggestions_fetcher = base::MakeUnique<RemoteSuggestionsFetcherImpl>( - signin_manager, token_service, request_context, pref_service, - language_histogram, + identity_manager, request_context, pref_service, language_histogram, base::Bind( &data_decoder::SafeJsonParser::Parse, content::ServiceManagerConnection::GetForProcess()->GetConnector()), @@ -454,6 +454,7 @@ BrowserContextDependencyManager::GetInstance()) { DependsOn(BookmarkModelFactory::GetInstance()); DependsOn(HistoryServiceFactory::GetInstance()); + DependsOn(IdentityManagerFactory::GetInstance()); DependsOn(LargeIconServiceFactory::GetInstance()); #if BUILDFLAG(ENABLE_OFFLINE_PAGES) DependsOn(OfflinePageModelFactory::GetInstance());
diff --git a/chrome/browser/offline_pages/android/downloads/offline_page_download_bridge.cc b/chrome/browser/offline_pages/android/downloads/offline_page_download_bridge.cc index d4c4a87c..077be715 100644 --- a/chrome/browser/offline_pages/android/downloads/offline_page_download_bridge.cc +++ b/chrome/browser/offline_pages/android/downloads/offline_page_download_bridge.cc
@@ -255,7 +255,7 @@ dl_params->set_prefer_cache(true); dl_params->set_prompt(false); - dl_params->set_download_source(content::DownloadSource::OFFLINE_PAGE); + dl_params->set_download_source(download::DownloadSource::OFFLINE_PAGE); dlm->DownloadUrl(std::move(dl_params)); }
diff --git a/chrome/browser/page_load_metrics/observers/service_worker_page_load_metrics_observer.cc b/chrome/browser/page_load_metrics/observers/service_worker_page_load_metrics_observer.cc index 5c99d33..6bb84b80 100644 --- a/chrome/browser/page_load_metrics/observers/service_worker_page_load_metrics_observer.cc +++ b/chrome/browser/page_load_metrics/observers/service_worker_page_load_metrics_observer.cc
@@ -13,6 +13,9 @@ namespace internal { +const char kHistogramServiceWorkerPageTransition[] = + "PageLoad.Clients.ServiceWorker.PageTransition"; + const char kHistogramServiceWorkerParseStart[] = "PageLoad.Clients.ServiceWorker.ParseTiming.NavigationToParseStart"; const char kHistogramServiceWorkerParseStartForwardBack[] = @@ -322,6 +325,17 @@ const page_load_metrics::PageLoadExtraInfo& info) { if (!IsServiceWorkerControlled(info)) return; + + // TODO(falken): It may be cleaner to record page transition in OnCommit() but + // at that point we don't yet know if the page is controlled by a service + // worker. It should be possible to plumb the information there since the + // browser process already sends the controller service worker in the + // navigation commit IPC. + UMA_HISTOGRAM_ENUMERATION( + internal::kHistogramServiceWorkerPageTransition, + static_cast<int>(ui::PageTransitionStripQualifier(transition_)), + static_cast<int>(ui::PAGE_TRANSITION_LAST_CORE) + 1); + if (WasStartedInForegroundOptionalEventInForeground( timing.parse_timing->parse_start, info)) { PAGE_LOAD_HISTOGRAM(internal::kHistogramServiceWorkerParseStart,
diff --git a/chrome/browser/plugins/chrome_plugin_service_filter.cc b/chrome/browser/plugins/chrome_plugin_service_filter.cc index 5b07f3a..b0ef289b 100644 --- a/chrome/browser/plugins/chrome_plugin_service_filter.cc +++ b/chrome/browser/plugins/chrome_plugin_service_filter.cc
@@ -43,10 +43,19 @@ const ContentSettingsPattern& secondary_pattern, ContentSettingsType content_type, std::string resource_identifier) override { - if (content_type == CONTENT_SETTINGS_TYPE_PLUGINS && - PluginUtils::ShouldPreferHtmlOverPlugins( - HostContentSettingsMapFactory::GetForProfile(profile_))) { + if (content_type != CONTENT_SETTINGS_TYPE_PLUGINS) + return; + + HostContentSettingsMap* map = + HostContentSettingsMapFactory::GetForProfile(profile_); + if (PluginUtils::ShouldPreferHtmlOverPlugins(map)) PluginService::GetInstance()->PurgePluginListCache(profile_, false); + + const GURL primary(primary_pattern.ToString()); + if (primary.is_valid()) { + DCHECK_EQ(ContentSettingsPattern::Relation::IDENTITY, + ContentSettingsPattern::Wildcard().Compare(secondary_pattern)); + PluginUtils::RememberFlashChangedForSite(map, primary); } }
diff --git a/chrome/browser/plugins/plugin_utils.cc b/chrome/browser/plugins/plugin_utils.cc index 09fbfc7..b603667 100644 --- a/chrome/browser/plugins/plugin_utils.cc +++ b/chrome/browser/plugins/plugin_utils.cc
@@ -121,6 +121,20 @@ } // static +void PluginUtils::RememberFlashChangedForSite( + HostContentSettingsMap* host_content_settings_map, + const GURL& top_level_url) { + // A |base::DictionaryValue| is set here but for now, clients only check this + // is a non-nullptr value. + auto dict = std::make_unique<base::DictionaryValue>(); + constexpr char kFlagKey[] = "flashPreviouslyChanged"; + dict->SetKey(kFlagKey, base::Value(true)); + host_content_settings_map->SetWebsiteSettingDefaultScope( + top_level_url, top_level_url, CONTENT_SETTINGS_TYPE_PLUGINS_DATA, + std::string(), std::move(dict)); +} + +// static bool PluginUtils::ShouldPreferHtmlOverPlugins( const HostContentSettingsMap* host_content_settings_map) { return base::FeatureList::IsEnabled(features::kPreferHtmlOverPlugins);
diff --git a/chrome/browser/plugins/plugin_utils.h b/chrome/browser/plugins/plugin_utils.h index 6c8d6fe..97f16630 100644 --- a/chrome/browser/plugins/plugin_utils.h +++ b/chrome/browser/plugins/plugin_utils.h
@@ -41,6 +41,12 @@ const GURL& plugin_url, bool* is_managed); + // Remember that the user has changed the Flash permission for + // |top_level_url|. + static void RememberFlashChangedForSite( + HostContentSettingsMap* host_content_settings_map, + const GURL& top_level_url); + // Returns true if HTML content should be prefered, by hiding Flash from the // plugin list. Use this instead of // base::FeatureList::IsEnabled(features::kPreferHtmlOverPlugins).
diff --git a/chrome/browser/policy/chrome_browser_policy_connector.cc b/chrome/browser/policy/chrome_browser_policy_connector.cc index 4facd0f..683e9ad3 100644 --- a/chrome/browser/policy/chrome_browser_policy_connector.cc +++ b/chrome/browser/policy/chrome_browser_policy_connector.cc
@@ -71,18 +71,6 @@ BrowserPolicyConnectorBase::OnResourceBundleCreated(); } -void ChromeBrowserPolicyConnector::InitPolicyProviders() { - std::vector<std::unique_ptr<ConfigurationPolicyProvider>> providers; - std::unique_ptr<ConfigurationPolicyProvider> platform_provider = - CreatePlatformProvider(); - if (platform_provider) { - platform_provider_ = platform_provider.get(); - providers.push_back(std::move(platform_provider)); - } - BuildPolicyProviders(&providers); - SetPolicyProviders(std::move(providers)); -} - void ChromeBrowserPolicyConnector::Init( PrefService* local_state, scoped_refptr<net::URLRequestContextGetter> request_context) { @@ -104,6 +92,19 @@ return provider ? provider : platform_provider_; } +std::vector<std::unique_ptr<policy::ConfigurationPolicyProvider>> +ChromeBrowserPolicyConnector::CreatePolicyProviders() { + auto providers = BrowserPolicyConnector::CreatePolicyProviders(); + std::unique_ptr<ConfigurationPolicyProvider> platform_provider = + CreatePlatformProvider(); + if (platform_provider) { + platform_provider_ = platform_provider.get(); + // PlatformProvider should be before all other providers (highest priority). + providers.insert(providers.begin(), std::move(platform_provider)); + } + return providers; +} + std::unique_ptr<ConfigurationPolicyProvider> ChromeBrowserPolicyConnector::CreatePlatformProvider() { #if defined(OS_WIN) @@ -140,7 +141,4 @@ #endif } -void ChromeBrowserPolicyConnector::BuildPolicyProviders( - std::vector<std::unique_ptr<ConfigurationPolicyProvider>>* providers) {} - } // namespace policy
diff --git a/chrome/browser/policy/chrome_browser_policy_connector.h b/chrome/browser/policy/chrome_browser_policy_connector.h index 14f1ddf..5b21e20 100644 --- a/chrome/browser/policy/chrome_browser_policy_connector.h +++ b/chrome/browser/policy/chrome_browser_policy_connector.h
@@ -42,9 +42,6 @@ // class to notify observers. void OnResourceBundleCreated(); - // TODO(sky): remove. Temporary until resolve ordering. - void InitPolicyProviders(); - void Init( PrefService* local_state, scoped_refptr<net::URLRequestContextGetter> request_context) override; @@ -52,12 +49,9 @@ ConfigurationPolicyProvider* GetPlatformProvider(); protected: - // Called from Init() to build the list of ConfigurationPolicyProviders that - // is supplied to SetPolicyProviders(). This implementation does nothing - // and is provided for subclasses. NOTE: |providers| may already contain - // some providers, generally subclasses should append. - virtual void BuildPolicyProviders( - std::vector<std::unique_ptr<ConfigurationPolicyProvider>>* providers); + // BrowserPolicyConnector: + std::vector<std::unique_ptr<policy::ConfigurationPolicyProvider>> + CreatePolicyProviders() override; private: std::unique_ptr<ConfigurationPolicyProvider> CreatePlatformProvider();
diff --git a/chrome/browser/policy/cloud/component_cloud_policy_browsertest.cc b/chrome/browser/policy/cloud/component_cloud_policy_browsertest.cc index 5fb94ebf..c1f5e072 100644 --- a/chrome/browser/policy/cloud/component_cloud_policy_browsertest.cc +++ b/chrome/browser/policy/cloud/component_cloud_policy_browsertest.cc
@@ -38,7 +38,6 @@ #include "net/url_request/url_request_context_getter.h" #include "testing/gmock/include/gmock/gmock.h" #include "testing/gtest/include/gtest/gtest.h" - #if defined(OS_CHROMEOS) #include "chrome/browser/chromeos/policy/user_cloud_policy_manager_chromeos.h" #include "chrome/browser/chromeos/policy/user_policy_manager_factory_chromeos.h" @@ -106,6 +105,10 @@ // testserver. command_line->AppendSwitchASCII(::chromeos::switches::kLoginUser, PolicyBuilder::kFakeUsername); + // Let policy code know that policy is not required to be cached at startup + // (it can be loaded asynchronously). + command_line->AppendSwitchASCII( + ::chromeos::switches::kProfileRequiresPolicy, "false"); #endif }
diff --git a/chrome/browser/policy/policy_initialization_browsertest.cc b/chrome/browser/policy/policy_initialization_browsertest.cc new file mode 100644 index 0000000..260b000 --- /dev/null +++ b/chrome/browser/policy/policy_initialization_browsertest.cc
@@ -0,0 +1,98 @@ +// 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 <string> + +#include "base/macros.h" +#include "base/strings/string16.h" +#include "base/strings/utf_string_conversions.h" +#include "build/build_config.h" +#include "chrome/browser/browser_process.h" +#include "chrome/browser/chrome_browser_main.h" +#include "chrome/browser/chrome_browser_main_extra_parts.h" +#include "chrome/common/pref_names.h" +#include "chrome/test/base/in_process_browser_test.h" +#include "components/policy/policy_constants.h" +#include "components/prefs/pref_service.h" + +#if defined(OS_WIN) +#include <windows.h> +#include "base/test/test_reg_util_win.h" +#include "base/win/registry.h" +#endif + +namespace { + +#if defined(OS_WIN) +const char kMockPolicyName[] = "AllowFileSelectionDialogs"; +#endif + +void VerifyLocalState() { + const PrefService* prefs = g_browser_process->local_state(); + ASSERT_NE(nullptr, prefs); + const PrefService::Preference* pref = + prefs->FindPreference(prefs::kAllowFileSelectionDialogs); + ASSERT_NE(nullptr, pref); + EXPECT_FALSE(pref->IsDefaultValue()); +} + +class ChromeBrowserMainExtraPartsPolicyValueChecker + : public ChromeBrowserMainExtraParts { + public: + ChromeBrowserMainExtraPartsPolicyValueChecker() {} + + // ChromeBrowserMainExtraParts + void PreCreateThreads() override { VerifyLocalState(); } + void PreBrowserStart() override { VerifyLocalState(); } + void PreMainMessageLoopRun() override { VerifyLocalState(); } + + private: + DISALLOW_COPY_AND_ASSIGN(ChromeBrowserMainExtraPartsPolicyValueChecker); +}; + +} // namespace + +// Test if the policy value can be read from the pref properly on Windows. +class PolicyInitializationBrowserTest : public InProcessBrowserTest { + protected: + PolicyInitializationBrowserTest() {} + + // content::BrowserTestBase: + void SetUpInProcessBrowserTestFixture() override { + SetUpPlatformPolicyValue(); + } + void CreatedBrowserMainParts(content::BrowserMainParts* parts) override { + static_cast<ChromeBrowserMainParts*>(parts)->AddParts( + new ChromeBrowserMainExtraPartsPolicyValueChecker()); + } + + private: +#if defined(OS_WIN) + // Set up policy value for windows platform + void SetUpPlatformPolicyValue() { + HKEY root = HKEY_CURRENT_USER; + ASSERT_NO_FATAL_FAILURE(registry_override_manager_.OverrideRegistry(root)); + + base::win::RegKey key; + + ASSERT_EQ(ERROR_SUCCESS, key.Create(root, policy::kRegistryChromePolicyKey, + KEY_SET_VALUE | KEY_WOW64_32KEY)); + ASSERT_EQ(ERROR_SUCCESS, + key.WriteValue(base::ASCIIToUTF16(kMockPolicyName).c_str(), 1)); + } + + registry_util::RegistryOverrideManager registry_override_manager_; +#else + // This test hasn't supported other platform yet. + void SetUpPlatformPolicyValue() {} +#endif + + DISALLOW_COPY_AND_ASSIGN(PolicyInitializationBrowserTest); +}; + +#if defined(OS_WIN) +IN_PROC_BROWSER_TEST_F(PolicyInitializationBrowserTest, VerifyLocalState) { + VerifyLocalState(); +} +#endif
diff --git a/chrome/browser/policy/profile_policy_connector.cc b/chrome/browser/policy/profile_policy_connector.cc index 1ca34ba..de4286d 100644 --- a/chrome/browser/policy/profile_policy_connector.cc +++ b/chrome/browser/policy/profile_policy_connector.cc
@@ -104,10 +104,7 @@ } #endif - std::unique_ptr<PolicyServiceImpl> policy_service = - std::make_unique<PolicyServiceImpl>(); - policy_service->SetProviders(policy_providers_); - policy_service_ = std::move(policy_service); + policy_service_ = std::make_unique<PolicyServiceImpl>(policy_providers_); #if defined(OS_CHROMEOS) if (is_primary_user_) {
diff --git a/chrome/browser/policy/profile_policy_connector_factory.cc b/chrome/browser/policy/profile_policy_connector_factory.cc index e96938c..e8a5f081 100644 --- a/chrome/browser/policy/profile_policy_connector_factory.cc +++ b/chrome/browser/policy/profile_policy_connector_factory.cc
@@ -154,8 +154,7 @@ providers.push_back(test_providers_.front()); test_providers_.pop_front(); std::unique_ptr<PolicyServiceImpl> service = - std::make_unique<PolicyServiceImpl>(); - service->SetProviders(providers); + std::make_unique<PolicyServiceImpl>(std::move(providers)); connector->InitForTesting(std::move(service)); }
diff --git a/chrome/browser/prefs/proxy_policy_unittest.cc b/chrome/browser/prefs/proxy_policy_unittest.cc index 4ed5293..f387aa4 100644 --- a/chrome/browser/prefs/proxy_policy_unittest.cc +++ b/chrome/browser/prefs/proxy_policy_unittest.cc
@@ -98,8 +98,7 @@ PolicyServiceImpl::Providers providers; providers.push_back(&provider_); - policy_service_ = std::make_unique<PolicyServiceImpl>(); - policy_service_->SetProviders(providers); + policy_service_ = std::make_unique<PolicyServiceImpl>(std::move(providers)); provider_.Init(); }
diff --git a/chrome/browser/prefs/tracked/pref_hash_browsertest.cc b/chrome/browser/prefs/tracked/pref_hash_browsertest.cc index 0a9172f..cf50a55 100644 --- a/chrome/browser/prefs/tracked/pref_hash_browsertest.cc +++ b/chrome/browser/prefs/tracked/pref_hash_browsertest.cc
@@ -688,18 +688,16 @@ // the previous one. switch (protection_level_) { case PROTECTION_ENABLED_ALL: - // Falls through. case PROTECTION_ENABLED_EXTENSIONS: ++num_protected_prefs; - // Falls through. + FALLTHROUGH; case PROTECTION_ENABLED_DSE: ++num_protected_prefs; - // Falls through. + FALLTHROUGH; case PROTECTION_ENABLED_BASIC: num_protected_prefs += num_tracked_prefs() - num_null_values - 2; - // Falls through. + FALLTHROUGH; case PROTECTION_DISABLED_FOR_GROUP: - // No protection. Falls through. case PROTECTION_DISABLED_ON_PLATFORM: // No protection. break;
diff --git a/chrome/browser/profiles/profile_downloader_unittest.cc b/chrome/browser/profiles/profile_downloader_unittest.cc index 1b340c1..b2591d0a 100644 --- a/chrome/browser/profiles/profile_downloader_unittest.cc +++ b/chrome/browser/profiles/profile_downloader_unittest.cc
@@ -9,7 +9,6 @@ #include "chrome/browser/profiles/profile_downloader_delegate.h" #include "chrome/browser/signin/account_fetcher_service_factory.h" #include "chrome/browser/signin/account_tracker_service_factory.h" -#include "chrome/browser/signin/chrome_signin_client_factory.h" #include "chrome/browser/signin/fake_account_fetcher_service_builder.h" #include "chrome/browser/signin/fake_profile_oauth2_token_service_builder.h" #include "chrome/browser/signin/profile_oauth2_token_service_factory.h" @@ -47,17 +46,11 @@ &BuildAutoIssuingFakeProfileOAuth2TokenService); builder.AddTestingFactory(AccountFetcherServiceFactory::GetInstance(), FakeAccountFetcherServiceBuilder::BuildForTests); - builder.AddTestingFactory(ChromeSigninClientFactory::GetInstance(), - signin::BuildTestSigninClient); - profile_ = builder.Build(); account_tracker_service_ = AccountTrackerServiceFactory::GetForProfile(profile_.get()); account_fetcher_service_ = static_cast<FakeAccountFetcherService*>( AccountFetcherServiceFactory::GetForProfile(profile_.get())); - signin_client_ = static_cast<TestSigninClient*>( - ChromeSigninClientFactory::GetForProfile(profile_.get())); - signin_client_->SetURLRequestContext(profile_->GetRequestContext()); profile_downloader_.reset(new ProfileDownloader(this)); } @@ -88,7 +81,6 @@ AccountTrackerService* account_tracker_service_; FakeAccountFetcherService* account_fetcher_service_; content::TestBrowserThreadBundle thread_bundle_; - TestSigninClient* signin_client_; std::unique_ptr<Profile> profile_; std::unique_ptr<ProfileDownloader> profile_downloader_; };
diff --git a/chrome/browser/profiles/profile_impl.cc b/chrome/browser/profiles/profile_impl.cc index 46d813b..7b76c53 100644 --- a/chrome/browser/profiles/profile_impl.cc +++ b/chrome/browser/profiles/profile_impl.cc
@@ -103,6 +103,7 @@ #include "components/domain_reliability/service.h" #include "components/gcm_driver/gcm_profile_service.h" #include "components/keyed_service/content/browser_context_dependency_manager.h" +#include "components/language/core/common/locale_util.h" #include "components/metrics/metrics_service.h" #include "components/omnibox/browser/autocomplete_classifier.h" #include "components/pref_registry/pref_registry_syncable.h" @@ -1149,6 +1150,7 @@ if (local_state->IsManagedPreference(prefs::kApplicationLocale)) return; std::string pref_locale = GetPrefs()->GetString(prefs::kApplicationLocale); + language::ConvertToActualUILocale(&pref_locale); bool do_update_pref = true; switch (via) { case APP_LOCALE_CHANGED_VIA_SETTINGS:
diff --git a/chrome/browser/renderer_context_menu/render_view_context_menu.cc b/chrome/browser/renderer_context_menu/render_view_context_menu.cc index 45bc532b..96a11b7 100644 --- a/chrome/browser/renderer_context_menu/render_view_context_menu.cc +++ b/chrome/browser/renderer_context_menu/render_view_context_menu.cc
@@ -100,7 +100,6 @@ #include "components/web_modal/web_contents_modal_dialog_manager.h" #include "content/public/browser/child_process_security_policy.h" #include "content/public/browser/download_manager.h" -#include "content/public/browser/download_save_info.h" #include "content/public/browser/download_url_parameters.h" #include "content/public/browser/guest_mode.h" #include "content/public/browser/navigation_details.h" @@ -2384,7 +2383,7 @@ dl_params->set_referrer_encoding(params_.frame_charset); dl_params->set_suggested_name(params_.suggested_filename); dl_params->set_prompt(true); - dl_params->set_download_source(content::DownloadSource::CONTEXT_MENU); + dl_params->set_download_source(download::DownloadSource::CONTEXT_MENU); BrowserContext::GetDownloadManager(browser_context_) ->DownloadUrl(std::move(dl_params));
diff --git a/chrome/browser/resources/chromeos/chromevox/cvox2/background/background_test.extjs b/chrome/browser/resources/chromeos/chromevox/cvox2/background/background_test.extjs index 509a6d6..430ceed 100644 --- a/chrome/browser/resources/chromeos/chromevox/cvox2/background/background_test.extjs +++ b/chrome/browser/resources/chromeos/chromevox/cvox2/background/background_test.extjs
@@ -1394,3 +1394,43 @@ .replay(); }); }); + +TEST_F('BackgroundTest', 'TableColumnHeaders', function() { + var mockFeedback = this.createMockFeedback(); + this.runWithLoadedTree(function(root) {/*! + <div role="grid"> + <div role="rowgroup"> + <div role="row"> + <div role="columnheader">city</div> + <div role="columnheader">state</div> + <div role="columnheader">zip</div> + </div> + </div> + <div role="rowgroup"> + <div role="row"> + <div role="gridcell">Mountain View</div> + <div role="gridcell">CA</div> + <div role="gridcell">94043</div> + </div> + <div role="row"> + <div role="gridcell">San Jose</div> + <div role="gridcell">CA</div> + <div role="gridcell">95128</div> + </div> + </div> + </div> + */}, function(root) { + mockFeedback.call(doCmd('nextRow')) + .expectSpeech('Mountain View', 'row 2 column 1') + .call(doCmd('nextRow')) + .expectNextSpeechUtteranceIsNot('city') + .expectSpeech('San Jose', 'row 3 column 1') + .call(doCmd('nextCol')) + .expectSpeech('CA', 'row 3 column 2', 'state') + .call(doCmd('previousRow')) + .expectSpeech('CA', 'row 2 column 2') + .call(doCmd('previousRow')) + .expectSpeech('state', 'row 1 column 2') + .replay(); + }); +});
diff --git a/chrome/browser/resources/chromeos/chromevox/cvox2/background/output.js b/chrome/browser/resources/chromeos/chromevox/cvox2/background/output.js index 2426c78..9fa98571 100644 --- a/chrome/browser/resources/chromeos/chromevox/cvox2/background/output.js +++ b/chrome/browser/resources/chromeos/chromevox/cvox2/background/output.js
@@ -1211,10 +1211,41 @@ buff); } } else if (token == 'node') { - if (!tree.firstChild || !node[tree.firstChild.value]) + if (!tree.firstChild) return; - var related = node[tree.firstChild.value]; - this.node_(related, related, Output.EventType.NAVIGATE, buff); + + var relationName = tree.firstChild.value; + if (node[relationName]) { + var related = node[relationName]; + this.node_(related, related, Output.EventType.NAVIGATE, buff); + } else if ( + relationName == 'tableColumnHeader' && + node.role == RoleType.CELL) { + // Because table columns do not contain cells as descendants, we + // must search for the correct column. + var columnIndex = node.tableCellColumnIndex; + if (opt_prevNode) { + // Skip output when previous position falls on the same column. + while (opt_prevNode && + !AutomationPredicate.cellLike(opt_prevNode)) { + opt_prevNode = opt_prevNode.parent; + } + + if (opt_prevNode && + opt_prevNode.tableCellColumnIndex == columnIndex) + return; + } + var tableLike = node.parent && node.parent.parent; + if (!tableLike || !AutomationPredicate.table(tableLike)) + return; + var column = tableLike.children.find(function(candidate) { + return columnIndex === candidate.tableColumnIndex; + }); + if (column && column.tableColumnHeader && + column.tableColumnHeader.name) { + this.append_(buff, column.tableColumnHeader.name, options); + } + } } else if (token == 'nameOrTextContent') { if (node.name) { this.format_(node, '$name', buff);
diff --git a/chrome/browser/resources/chromeos/login/oobe_welcome.js b/chrome/browser/resources/chromeos/login/oobe_welcome.js index 8263678..bdd1a79 100644 --- a/chrome/browser/resources/chromeos/login/oobe_welcome.js +++ b/chrome/browser/resources/chromeos/login/oobe_welcome.js
@@ -368,22 +368,37 @@ var self = this; var networkStateCopy = Object.assign({}, state); - // TODO(stevenjb): Do this when state.Connectable == false once network - // configuration is integrated into the Settings UI / details dialog. + // Cellular should normally auto connect. If it is selected, show the + // details UI since there is no configuration UI for Cellular. if (state.Type == chrome.networkingPrivate.NetworkType.CELLULAR) { chrome.send('showNetworkDetails', [state.GUID]); return; } - chrome.networkingPrivate.startConnect(state.GUID, function() { - var lastError = chrome.runtime.lastError; + // Allow proxy to be set for connected networks. + if (state.ConnectionState == CrOnc.ConnectionState.CONNECTED) { + chrome.send('showNetworkDetails', [state.GUID]); + return; + } + + if (state.Connectable === false || state.ErrorState) { + chrome.send('showNetworkConfig', [state.GUID]); + return; + } + + chrome.networkingPrivate.startConnect(state.GUID, () => { + const lastError = chrome.runtime.lastError; if (!lastError) return; - - if (lastError.message == 'connected' || lastError.message == 'connecting') + const message = lastError.message; + if (message == 'connecting' || message == 'connect-canceled' || + message == 'connected' || message == 'Error.InvalidNetworkGuid') { return; - - console.error('networkingPrivate.startConnect error: ' + lastError); + } + console.error( + 'networkingPrivate.startConnect error: ' + message + + ' For: ' + state.GUID); + chrome.send('showNetworkConfig', [state.GUID]); }); },
diff --git a/chrome/browser/resources/md_bookmarks/app.html b/chrome/browser/resources/md_bookmarks/app.html index 64393cd..82c01245 100644 --- a/chrome/browser/resources/md_bookmarks/app.html +++ b/chrome/browser/resources/md_bookmarks/app.html
@@ -30,6 +30,7 @@ display: flex; flex-direction: row; flex-grow: 1; + overflow: hidden; } #splitter {
diff --git a/chrome/browser/resources/media/media_engagement.html b/chrome/browser/resources/media/media_engagement.html index fd374ce5..59b265a 100644 --- a/chrome/browser/resources/media/media_engagement.html +++ b/chrome/browser/resources/media/media_engagement.html
@@ -18,6 +18,10 @@ font-size: 14px; } + button { + margin-bottom: 20px; + } + table { border-collapse: collapse; margin-bottom: 20px; @@ -50,7 +54,6 @@ .origin-cell { background-color: rgba(230, 230, 230, 0.5); - min-width: 500px; } .visits-count-cell, @@ -60,6 +63,7 @@ .significant-playbacks-count-cell { background-color: rgba(230, 230, 230, 0.5); text-align: right; + white-space: nowrap; } .base-score-input { @@ -96,6 +100,7 @@ </head> <body> <h1>Media Engagement</h1> + <button id="copy-all-to-clipboard">Copy all to clipboard</button> <table> <thead> <tr id="config-table-header"> @@ -117,10 +122,10 @@ Origin </th> <th sort-key="visits" sort-reverse> - Visits + Sessions </th> <th sort-key="mediaPlaybacks" sort-reverse> - Playbacks + Playbacks per session </th> <th sort-key="audiblePlaybacks" sort-reverse> Audible Playbacks*
diff --git a/chrome/browser/resources/media/media_engagement.js b/chrome/browser/resources/media/media_engagement.js index 0ca0a3c..b1aebf8d 100644 --- a/chrome/browser/resources/media/media_engagement.js +++ b/chrome/browser/resources/media/media_engagement.js
@@ -108,7 +108,7 @@ configTableBody.innerHTML = ''; configTableBody.appendChild( - createConfigRow('Min Visits', config.scoreMinVisits)); + createConfigRow('Min Sessions', config.scoreMinVisits)); configTableBody.appendChild( createConfigRow('Lower Threshold', config.highScoreLowerThreshold)); configTableBody.appendChild( @@ -173,5 +173,18 @@ renderTable(); }); } + + // Add handler to 'copy all to clipboard' button + var copyAllToClipboardButton = $('copy-all-to-clipboard'); + copyAllToClipboardButton.addEventListener('click', (e) => { + // Make sure nothing is selected + window.getSelection().removeAllRanges(); + + document.execCommand('selectAll'); + document.execCommand('copy'); + + // And deselect everything at the end. + window.getSelection().removeAllRanges(); + }); }); })();
diff --git a/chrome/browser/resources/print_preview/images/2x/printer.png b/chrome/browser/resources/print_preview/images/2x/printer.png index b704e02..76d6a6a 100644 --- a/chrome/browser/resources/print_preview/images/2x/printer.png +++ b/chrome/browser/resources/print_preview/images/2x/printer.png Binary files differ
diff --git a/chrome/browser/resources/print_preview/images/2x/printer_shared.png b/chrome/browser/resources/print_preview/images/2x/printer_shared.png index bbddfd0..464343e 100644 --- a/chrome/browser/resources/print_preview/images/2x/printer_shared.png +++ b/chrome/browser/resources/print_preview/images/2x/printer_shared.png Binary files differ
diff --git a/chrome/browser/resources/print_preview/new/app.html b/chrome/browser/resources/print_preview/new/app.html index 661f3c0..b9eb5538 100644 --- a/chrome/browser/resources/print_preview/new/app.html +++ b/chrome/browser/resources/print_preview/new/app.html
@@ -65,7 +65,9 @@ settings="[[settings]]"></print-preview-header> <div id="settings-sections"> <print-preview-destination-settings destination="[[destination_]]" - destination-store="[[destinationStore_]]" user-info="[[userInfo_]]"> + destination-store="[[destinationStore_]]" + recent-destinations="[[recentDestinations_]]" + user-info="[[userInfo_]]"> </print-preview-destination-settings> <print-preview-pages-settings settings="{{settings}}" document-info="[[documentInfo_]]"
diff --git a/chrome/browser/resources/print_preview/new/compiled_resources2.gyp b/chrome/browser/resources/print_preview/new/compiled_resources2.gyp index de2b144..65b2149 100644 --- a/chrome/browser/resources/print_preview/new/compiled_resources2.gyp +++ b/chrome/browser/resources/print_preview/new/compiled_resources2.gyp
@@ -193,6 +193,14 @@ '<(DEPTH)/ui/webui/resources/js/compiled_resources2.gyp:i18n_behavior', '../compiled_resources2.gyp:native_layer', '../data/compiled_resources2.gyp:destination', + 'print_preview_search_box', + ], + 'includes': ['../../../../../third_party/closure_compiler/compile_js2.gypi'], + }, + { + 'target_name': 'print_preview_search_box', + 'dependencies': [ + '<(DEPTH)/ui/webui/resources/cr_elements/cr_search_field/compiled_resources2.gyp:cr_search_field_behavior', ], 'includes': ['../../../../../third_party/closure_compiler/compile_js2.gypi'], },
diff --git a/chrome/browser/resources/print_preview/new/destination_dialog.html b/chrome/browser/resources/print_preview/new/destination_dialog.html index 92099a2..e441605 100644 --- a/chrome/browser/resources/print_preview/new/destination_dialog.html +++ b/chrome/browser/resources/print_preview/new/destination_dialog.html
@@ -8,6 +8,7 @@ <link rel="import" href="../data/destination_store.html"> <link rel="import" href="button_css.html"> <link rel="import" href="destination_list.html"> +<link rel="import" href="print_preview_search_box.html"> <link rel="import" href="print_preview_shared_css.html"> <dom-module id="print-preview-destination-dialog"> @@ -32,6 +33,7 @@ box-shadow: 0 4px 23px 5px rgba(0, 0, 0, 0.2), 0 2px 6px rgba(0, 0, 0, 0.15); + max-height: calc(100% - 40px); width: 640px; } @@ -57,14 +59,26 @@ width: 24px; } </style> - <dialog is="cr-dialog" id="dialog"> + <dialog is="cr-dialog" id="dialog" on-cancel="onCloseOrCancel_" + on-close="onCloseOrCancel_"> <div slot="title"> <span>$i18n{destinationSearchTitle}</span> </div> <div slot="body" scrollable> + <print-preview-search-box id="searchBox" + label="$i18n{searchBoxPlaceholder}" search-query="{{searchQuery_}}"> + </print-preview-search-box> + <print-preview-destination-list + destinations="[[recentDestinationList_]]" + search-query="[[searchQuery_]]" + title="$i18n{recentDestinationsTitle}" + on-destination-selected="onDestinationSelected_"> + </print-preview-destination-list> <print-preview-destination-list destinations="[[destinations_]]" - has-action-link=true loading-destinations="[[loadingDestinations_]]" - title="$i18n{printDestinationsTitle}"> + has-action-link loading-destinations="[[loadingDestinations_]]" + search-query="[[searchQuery_]]" + title="$i18n{printDestinationsTitle}" + on-destination-selected="onDestinationSelected_"> </print-preview-destination-list> </div> <div slot="button-container">
diff --git a/chrome/browser/resources/print_preview/new/destination_dialog.js b/chrome/browser/resources/print_preview/new/destination_dialog.js index 6b1e7e4..eb9d3e8 100644 --- a/chrome/browser/resources/print_preview/new/destination_dialog.js +++ b/chrome/browser/resources/print_preview/new/destination_dialog.js
@@ -15,7 +15,7 @@ /** @type {!print_preview.UserInfo} */ userInfo: Object, - /** @private {Array<!print_preview.Destination>} */ + /** @private {!Array<!print_preview.Destination>} */ destinations_: { type: Array, notify: true, @@ -27,6 +27,24 @@ type: Boolean, value: false, }, + + /** @type {!Array<!print_preview.RecentDestination>} */ + recentDestinations: Array, + + /** @private {!Array<!print_preview.Destination>} */ + recentDestinationList_: { + type: Array, + notify: true, + computed: 'computeRecentDestinationList_(' + + 'destinationStore, recentDestinations, recentDestinations.*, ' + + 'userInfo, destinations_.*)', + }, + + /** @private {?RegExp} */ + searchQuery_: { + type: Object, + value: null, + }, }, /** @private {!EventTracker} */ @@ -56,6 +74,25 @@ }, /** + * @return {!Array<!print_preview.Destination>} + * @private + */ + computeRecentDestinationList_: function() { + let recentDestinations = []; + const filterAccount = this.userInfo.activeUser; + this.recentDestinations.forEach((recentDestination) => { + const destination = this.destinationStore.getDestination( + recentDestination.origin, recentDestination.id, + recentDestination.account || ''); + if (destination && + (!destination.account || destination.account == filterAccount)) { + recentDestinations.push(destination); + } + }); + return recentDestinations; + }, + + /** * @return {string} The cloud print promotion HTML. * @private */ @@ -65,10 +102,28 @@ }, /** @private */ + onCloseOrCancel_: function() { + if (this.searchQuery_) + this.$.searchBox.setValue(''); + this.shadowRoot.querySelectorAll('print-preview-destination-list') + .forEach(list => list.reset()); + }, + + /** @private */ onCancelButtonTap_: function() { this.$.dialog.cancel(); }, + /** + * @param {!CustomEvent} e Event containing the selected destination. + * @private + */ + onDestinationSelected_: function(e) { + this.destinationStore.selectDestination( + /** @type {!print_preview.Destination} */ (e.detail)); + this.$.dialog.close(); + }, + show: function() { this.loadingDestinations_ = this.destinationStore.isPrintDestinationSearchInProgress;
diff --git a/chrome/browser/resources/print_preview/new/destination_list.html b/chrome/browser/resources/print_preview/new/destination_list.html index fe26591a..b541772 100644 --- a/chrome/browser/resources/print_preview/new/destination_list.html +++ b/chrome/browser/resources/print_preview/new/destination_list.html
@@ -11,6 +11,11 @@ <dom-module id="print-preview-destination-list"> <template> <style include="print-preview-shared action-link cr-hidden-style throbber"> + :host { + padding: 0 14px 18px; + user-select: none; + } + :host > header { -webkit-padding-end: 19px; -webkit-padding-start: 0; @@ -64,7 +69,7 @@ padding: 0; } - :host .destination-list-item { + :host .list-item { -webkit-padding-end: 2px; -webkit-padding-start: 18px; cursor: default; @@ -73,22 +78,22 @@ padding-top: 3px; } - :not(.moving).destination-list-item { + :not(.moving).list-item { transition: background-color 150ms; } - .destination-list-item:hover, - .destination-list-item:focus { + .list-item:hover, + .list-item:focus { background-color: rgb(228, 236, 247); } - .destination-list-item:focus { + .list-item:focus { outline: none; } - .destination-list-item.stale :-webkit-any(.destination-list-item-icon, - .destination-list-item-name, - .connection-status) { + .list-item.stale :-webkit-any(.destination-list-item-icon, + .destination-list-item-name, + .connection-status) { opacity: 0.4; } @@ -102,7 +107,8 @@ width: 24px; } - .destination-list-item-name { + .destination-list-item-name, + .search-hint { flex: 0 1 auto; line-height: 24px; overflow: hidden; @@ -111,8 +117,14 @@ white-space: nowrap; } - .destination-list-item .connection-status, - .destination-list-item .learn-more-link { + .list-item .search-hint { + -webkit-margin-start: 1em; + color: #999; + font-size: 75%; + } + + .list-item .connection-status, + .list-item .learn-more-link { -webkit-margin-start: 1em; flex: 0 0 auto; font-size: 75%; @@ -120,7 +132,7 @@ vertical-align: middle; } - .destination-list-item .learn-more-link { + .list-item .learn-more-link { color: rgb(51, 103, 214); } @@ -179,15 +191,15 @@ </div> </header> <ul> - <template is="dom-repeat" items="[[destinations]]"> - <li class$="destination-list-item - [[getStaleCssClass_(item.isOfflineOrInvalid)]]" - hidden$="[[isDestinationHidden_(index, showAll_)]]"> - <img class="destination-list-item-icon" alt="" + <template is="dom-repeat" items="[[displayedDestinations_]]"> + <li class$="list-item [[getStaleCssClass_(item.isOfflineOrInvalid)]]" + title="[[item.displayName]]" + hidden$="[[isDestinationHidden_(index, showAll_)]]" + on-tap="onDestinationSelected_"> + <img class="destination-list-item-icon" src="[[item.iconUrl]]" srcset="[[item.srcSet]]"> - <span class="destination-list-item-name"> - [[item.displayName]] - </span> + <span class="destination-list-item-name">[[item.displayName]]</span> + <span class="search-hint">[[getSearchHint_(item, searchQuery)]]</span> <span class="connection-status" hidden$="[[!item.isOfflineOrInvalid]]"> [[item.connectionStatusText]] @@ -227,7 +239,9 @@ <button class="show-all-button" on-tap="onShowAllTap_"> $i18n{showAllButtonText} </button> - <span class="total">[[totalDestinations_(destinations)]]</span> + <span class="total"> + [[i18n('destinationCount', displayedDestinations_.length)]] + </span> </footer> </template> <script src="destination_list.js"></script>
diff --git a/chrome/browser/resources/print_preview/new/destination_list.js b/chrome/browser/resources/print_preview/new/destination_list.js index 811cac6..29bbaa4e 100644 --- a/chrome/browser/resources/print_preview/new/destination_list.js +++ b/chrome/browser/resources/print_preview/new/destination_list.js
@@ -18,10 +18,19 @@ destinations: Array, /** @type {boolean} */ - hasActionLink: Boolean, + hasActionLink: { + type: Boolean, + value: false, + }, /** @type {boolean} */ - loadingDestinations: Boolean, + loadingDestinations: { + type: Boolean, + value: false, + }, + + /** @type {?RegExp} */ + searchQuery: Object, /** @type {boolean} */ title: String, @@ -32,25 +41,60 @@ value: false, }, + /** @private {!Array<!print_preview.Destination>} */ + displayedDestinations_: { + type: Array, + computed: 'computeDisplayedDestinations_(destinations, searchQuery)', + }, + /** @type {boolean} */ footerHidden_: { type: Boolean, - computed: 'computeFooterHidden_(destinations, showAll_)', + computed: 'computeFooterHidden_(displayedDestinations_, showAll_)', }, /** @private {boolean} */ hasDestinations_: { type: Boolean, - computed: 'computeHasDestinations_(destinations)', + computed: 'computeHasDestinations_(displayedDestinations_)', }, }, /** + * @return {!Array<!print_preview.Destination>} + * @private + */ + computeDisplayedDestinations_: function() { + if (!this.searchQuery) + return assert(this.destinations); + return this.destinations.filter(destination => { + return destination.matches(assert(this.searchQuery)); + }); + }, + + /** + * @param {!print_preview.Destination} destination The destination to get the + * search hint for. + * @return {string} The property or properties matching the search query. + * @private + */ + getSearchHint_: function(destination) { + if (!this.searchQuery) + return ''; + let hint = ''; + destination.extraPropertiesToMatch.some(property => { + if (property.match(this.searchQuery)) + hint += property; + }); + return hint; + }, + + /** * @return {boolean} * @private */ computeFooterHidden_: function() { - return this.destinations.length < SHORT_DESTINATION_LIST_SIZE || + return this.displayedDestinations_.length < SHORT_DESTINATION_LIST_SIZE || this.showAll_; }, @@ -59,7 +103,7 @@ * @private */ computeHasDestinations_: function() { - return this.destinations.length != 0; + return this.displayedDestinations_.length > 0; }, /** @@ -81,11 +125,6 @@ return offlineOrInvalid ? 'stale' : ''; }, - /** @private string */ - totalDestinations_: function() { - return this.i18n('destinationCount', this.destinations.length.toString()); - }, - /** @private */ onActionLinkTap_: function() { print_preview.NativeLayer.getInstance().managePrinters(); @@ -95,5 +134,18 @@ onShowAllTap_: function() { this.showAll_ = true; }, + + /** + * @param {!Event} e Event containing the destination that was selected. + * @private + */ + onDestinationSelected_: function(e) { + this.fire( + 'destination-selected', /** @type {!{model: Object}} */ (e).model.item); + }, + + reset: function() { + this.showAll_ = false; + }, }); })();
diff --git a/chrome/browser/resources/print_preview/new/destination_settings.html b/chrome/browser/resources/print_preview/new/destination_settings.html index 1b50ff5e..02809a2 100644 --- a/chrome/browser/resources/print_preview/new/destination_settings.html +++ b/chrome/browser/resources/print_preview/new/destination_settings.html
@@ -88,7 +88,9 @@ </print-preview-settings-section> <template is="cr-lazy-render" id="destinationDialog"> <print-preview-destination-dialog - destination-store="[[destinationStore]]" user-info="[[userInfo]]"> + destination-store="[[destinationStore]]" + recent-destinations="[[recentDestinations]]" + user-info="[[userInfo]]"> </print-preview-destination-dialog> </template> </template>
diff --git a/chrome/browser/resources/print_preview/new/destination_settings.js b/chrome/browser/resources/print_preview/new/destination_settings.js index ea8da4e..1c8d325c 100644 --- a/chrome/browser/resources/print_preview/new/destination_settings.js +++ b/chrome/browser/resources/print_preview/new/destination_settings.js
@@ -12,6 +12,9 @@ /** @type {?print_preview.DestinationStore} */ destinationStore: Object, + /** @type {!Array<!print_preview.RecentDestination>} */ + recentDestinations: Array, + /** @type {!print_preview.UserInfo} */ userInfo: Object,
diff --git a/chrome/browser/resources/print_preview/new/model.js b/chrome/browser/resources/print_preview/new/model.js index bf4fe07..a11c5b2 100644 --- a/chrome/browser/resources/print_preview/new/model.js +++ b/chrome/browser/resources/print_preview/new/model.js
@@ -371,8 +371,7 @@ this.recentDestinations.splice(indexFound, 1); // Add the most recent destination - this.recentDestinations.splice(0, 0, newDestination); - this.notifyPath('recentDestinations'); + this.splice('recentDestinations', 0, 0, newDestination); // Persist sticky settings. this.stickySettingsChanged_();
diff --git a/chrome/browser/resources/print_preview/new/print_preview_search_box.html b/chrome/browser/resources/print_preview/new/print_preview_search_box.html new file mode 100644 index 0000000..50e421b --- /dev/null +++ b/chrome/browser/resources/print_preview/new/print_preview_search_box.html
@@ -0,0 +1,41 @@ +<link rel="import" href="chrome://resources/html/polymer.html"> + +<link rel="import" href="chrome://resources/cr_elements/cr_search_field/cr_search_field_behavior.html"> +<link rel="import" href="print_preview_shared_css.html"> + +<dom-module id="print-preview-search-box"> + <template> + <style include="print-preview-shared"> + :host { + display: flex; + position: relative; + user-select: none; + } + + .search-box-icon { + display: inline-block; + height: 1em; + left: 8px; + position: absolute; + right: 8px; + top: 6px; + user-select: none; + width: 1em; + } + + .search-box-input { + text-indent: 2em; + width: 100%; + } + + .search-box-input::-webkit-search-cancel-button { + -webkit-appearance: none; + } + </style> + <img src="../images/search.png" class="search-box-icon" alt=""> + <input type="search" id="searchInput" class="search-box-input" + on-search="onSearchTermSearch" on-input="onSearchTermInput" + incremental aria-label$="[[label]]" placeholder="[[label]]"> + </template> + <script src="print_preview_search_box.js"></script> +</dom-module>
diff --git a/chrome/browser/resources/print_preview/new/print_preview_search_box.js b/chrome/browser/resources/print_preview/new/print_preview_search_box.js new file mode 100644 index 0000000..f1928a1 --- /dev/null +++ b/chrome/browser/resources/print_preview/new/print_preview_search_box.js
@@ -0,0 +1,42 @@ +// 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. + +(function() { +'use strict'; + +/** @type {!RegExp} */ +const SANITIZE_REGEX = /[-[\]{}()*+?.,\\^$|#\s]/g; + +Polymer({ + is: 'print-preview-search-box', + + behaviors: [CrSearchFieldBehavior], + + properties: { + /** @type {?RegExp} */ + searchQuery: { + type: Object, + notify: true, + }, + }, + + listeners: { + 'search-changed': 'onSearchChanged_', + }, + + /** @return {!HTMLInputElement} */ + getSearchInput: function() { + return this.$.searchInput; + }, + + /** + * @param {!CustomEvent} e Event containing the new search. + */ + onSearchChanged_: function(e) { + const safeQuery = e.detail.trim().replace(SANITIZE_REGEX, '\\$&'); + this.searchQuery = + safeQuery.length > 0 ? new RegExp(`(${safeQuery})`, 'ig') : null; + }, +}); +})();
diff --git a/chrome/browser/resources/print_preview/print_preview_resources.grd b/chrome/browser/resources/print_preview/print_preview_resources.grd index 45218df6..2feb6bd 100644 --- a/chrome/browser/resources/print_preview/print_preview_resources.grd +++ b/chrome/browser/resources/print_preview/print_preview_resources.grd
@@ -220,9 +220,7 @@ type="chrome_html" /> <structure name="IDR_PRINT_PREVIEW_NEW_DESTINATION_DIALOG_HTML" file="new/destination_dialog.html" - type="chrome_html" - flattenhtml="true" - allowexternalscript="true" /> + type="chrome_html" /> <structure name="IDR_PRINT_PREVIEW_NEW_DESTINATION_DIALOG_JS" file="new/destination_dialog.js" type="chrome_html" /> @@ -233,6 +231,14 @@ <structure name="IDR_PRINT_PREVIEW_NEW_DESTINATION_LIST_JS" file="new/destination_list.js" type="chrome_html" /> + <structure name="IDR_PRINT_PREVIEW_NEW_PRINT_PREVIEW_SEARCH_BOX_HTML" + file="new/print_preview_search_box.html" + type="chrome_html" + flattenhtml="true" + allowexternalscript="true" /> + <structure name="IDR_PRINT_PREVIEW_NEW_PRINT_PREVIEW_SEARCH_BOX_JS" + file="new/print_preview_search_box.js" + type="chrome_html" /> <structure name="IDR_PRINT_PREVIEW_NEW_PRINT_PREVIEW_SHARED_CSS_HTML" file="new/print_preview_shared_css.html" type="chrome_html"
diff --git a/chrome/browser/resources/settings/about_page/about_page.js b/chrome/browser/resources/settings/about_page/about_page.js index ac46a56..beecac1 100644 --- a/chrome/browser/resources/settings/about_page/about_page.js +++ b/chrome/browser/resources/settings/about_page/about_page.js
@@ -417,7 +417,7 @@ /** @private */ onRelaunchAndPowerwashTap_: function() { - this.lifetimeBrowserProxy_.factoryReset(); + this.lifetimeBrowserProxy_.factoryReset(false); }, /**
diff --git a/chrome/browser/resources/settings/internet_page/internet_page.js b/chrome/browser/resources/settings/internet_page/internet_page.js index ec8f7cf4..b834ac3 100644 --- a/chrome/browser/resources/settings/internet_page/internet_page.js +++ b/chrome/browser/resources/settings/internet_page/internet_page.js
@@ -586,19 +586,25 @@ */ onNetworkConnect_: function(event) { const properties = event.detail.networkProperties; + const name = CrOnc.getNetworkName(properties); if (!event.detail.bypassConnectionDialog && CrOnc.shouldShowTetherDialogBeforeConnection(properties)) { const params = new URLSearchParams; params.append('guid', properties.GUID); params.append('type', properties.Type); - params.append('name', CrOnc.getNetworkName(properties)); + params.append('name', name); params.append('showConfigure', true.toString()); settings.navigateTo(settings.routes.NETWORK_DETAIL, params); return; } - this.networkingPrivate.startConnect(properties.GUID, function() { + if (properties.Connectable === false || properties.ErrorState) { + this.showConfig_(properties.Type, properties.GUID, name); + return; + } + + this.networkingPrivate.startConnect(properties.GUID, () => { if (chrome.runtime.lastError) { const message = chrome.runtime.lastError.message; if (message == 'connecting' || message == 'connect-canceled' || @@ -606,8 +612,9 @@ return; } console.error( - 'Unexpected networkingPrivate.startConnect error: ' + message + + 'networkingPrivate.startConnect error: ' + message + ' For: ' + properties.GUID); + this.showConfig_(properties.Type, properties.GUID, name); } }); },
diff --git a/chrome/browser/resources/settings/internet_page/internet_subpage.html b/chrome/browser/resources/settings/internet_page/internet_subpage.html index 3119ac4ec..976a5d2 100644 --- a/chrome/browser/resources/settings/internet_page/internet_subpage.html +++ b/chrome/browser/resources/settings/internet_page/internet_subpage.html
@@ -143,6 +143,7 @@ <li>$i18n{gmscoreNotificationsFirstStep}</li> <li>$i18n{gmscoreNotificationsSecondStep}</li> <li>$i18n{gmscoreNotificationsThirdStep}</li> + <li>$i18n{gmscoreNotificationsFourthStep}</li> </ol> </div> </template>
diff --git a/chrome/browser/resources/settings/lifetime_browser_proxy.js b/chrome/browser/resources/settings/lifetime_browser_proxy.js index 19bc02a..3965397 100644 --- a/chrome/browser/resources/settings/lifetime_browser_proxy.js +++ b/chrome/browser/resources/settings/lifetime_browser_proxy.js
@@ -19,7 +19,7 @@ * Triggers a factory reset. The parameter indicates whether to install a * TPM firmware update (if available) after the reset. * - * @param {boolean=} requestTpmFirmwareUpdate + * @param {boolean} requestTpmFirmwareUpdate */ factoryReset(requestTpmFirmwareUpdate) {} // </if>
diff --git a/chrome/browser/resources/settings/reset_page/compiled_resources2.gyp b/chrome/browser/resources/settings/reset_page/compiled_resources2.gyp index 39f600e..831d1e4 100644 --- a/chrome/browser/resources/settings/reset_page/compiled_resources2.gyp +++ b/chrome/browser/resources/settings/reset_page/compiled_resources2.gyp
@@ -4,6 +4,14 @@ { 'targets': [ { + 'target_name': 'powerwash_dialog', + 'dependencies': [ + '../compiled_resources2.gyp:lifetime_browser_proxy', + 'reset_browser_proxy', + ], + 'includes': ['../../../../../third_party/closure_compiler/compile_js2.gypi'], + }, + { 'target_name': 'reset_page', 'dependencies': [ '../compiled_resources2.gyp:route',
diff --git a/chrome/browser/resources/settings/reset_page/powerwash_dialog.js b/chrome/browser/resources/settings/reset_page/powerwash_dialog.js index 2ff5c06e..3778634 100644 --- a/chrome/browser/resources/settings/reset_page/powerwash_dialog.js +++ b/chrome/browser/resources/settings/reset_page/powerwash_dialog.js
@@ -12,7 +12,10 @@ properties: { /** @public */ - requestTpmFirmwareUpdate: Boolean, + requestTpmFirmwareUpdate: { + type: Boolean, + value: false, + } }, /** @override */
diff --git a/chrome/browser/resources/settings/site_settings/site_details.js b/chrome/browser/resources/settings/site_settings/site_details.js index 45b3afb0..73bd087 100644 --- a/chrome/browser/resources/settings/site_settings/site_details.js +++ b/chrome/browser/resources/settings/site_settings/site_details.js
@@ -245,6 +245,8 @@ onClearAndReset_: function() { this.browserProxy.setOriginPermissions( this.origin, this.getCategoryList_(), settings.ContentSetting.DEFAULT); + if (this.getCategoryList_().includes(settings.ContentSettingsTypes.PLUGINS)) + this.browserProxy.clearFlashPref(this.origin); if (this.storedData_ != '') this.onClearStorage_();
diff --git a/chrome/browser/resources/settings/site_settings/site_settings_prefs_browser_proxy.js b/chrome/browser/resources/settings/site_settings/site_settings_prefs_browser_proxy.js index 81a019e..0bfcff8 100644 --- a/chrome/browser/resources/settings/site_settings/site_settings_prefs_browser_proxy.js +++ b/chrome/browser/resources/settings/site_settings/site_settings_prefs_browser_proxy.js
@@ -137,6 +137,13 @@ setOriginPermissions(origin, contentTypes, blanketSetting) {} /** + * Clears the flag that's set when the user has changed the Flash permission + * for this particular origin. + * @param {string} origin The origin to clear the Flash preference for. + */ + clearFlashPref(origin) {} + + /** * Resets the category permission for a given origin (expressed as primary * and secondary patterns). Only use this if intending to remove an * exception - use setOriginPermissions() for origin-scoped settings. @@ -307,6 +314,11 @@ } /** @override */ + clearFlashPref(origin) { + chrome.send('clearFlashPref', [origin]); + } + + /** @override */ resetCategoryPermissionForPattern( primaryPattern, secondaryPattern, contentType, incognito) { chrome.send(
diff --git a/chrome/browser/safe_browsing/BUILD.gn b/chrome/browser/safe_browsing/BUILD.gn index d870ac22..5818058 100644 --- a/chrome/browser/safe_browsing/BUILD.gn +++ b/chrome/browser/safe_browsing/BUILD.gn
@@ -233,6 +233,7 @@ deps += [ "//chrome/services/file_util/public/cpp", "//components/content_settings/core/browser:browser", + "//components/language/core/common:common", "//components/prefs:prefs", "//components/safe_browsing/common:safe_browsing_prefs", "//components/safe_browsing/db:db",
diff --git a/chrome/browser/safe_browsing/download_protection/check_client_download_request.cc b/chrome/browser/safe_browsing/download_protection/check_client_download_request.cc index 1c5ba8d..9d79a14 100644 --- a/chrome/browser/safe_browsing/download_protection/check_client_download_request.cc +++ b/chrome/browser/safe_browsing/download_protection/check_client_download_request.cc
@@ -1031,6 +1031,7 @@ // so we may be deleted now. } else { callback_.Run(DownloadCheckResult::UNKNOWN); + item_ = NULL; } }
diff --git a/chrome/browser/safe_browsing/download_protection/download_feedback_service.cc b/chrome/browser/safe_browsing/download_protection/download_feedback_service.cc index d2f73911..90a3f7b1 100644 --- a/chrome/browser/safe_browsing/download_protection/download_feedback_service.cc +++ b/chrome/browser/safe_browsing/download_protection/download_feedback_service.cc
@@ -13,7 +13,6 @@ #include "base/supports_user_data.h" #include "base/task_runner.h" #include "chrome/browser/safe_browsing/download_protection/download_feedback.h" -#include "content/public/browser/download_danger_type.h" #include "content/public/browser/download_item.h" namespace safe_browsing { @@ -126,9 +125,9 @@ // static void DownloadFeedbackService::RecordEligibleDownloadShown( - content::DownloadDangerType danger_type) { + download::DownloadDangerType danger_type) { UMA_HISTOGRAM_ENUMERATION("SBDownloadFeedback.Eligible", danger_type, - content::DOWNLOAD_DANGER_TYPE_MAX); + download::DOWNLOAD_DANGER_TYPE_MAX); } void DownloadFeedbackService::BeginFeedbackForDownload( @@ -137,7 +136,7 @@ DCHECK_CURRENTLY_ON(content::BrowserThread::UI); UMA_HISTOGRAM_ENUMERATION("SBDownloadFeedback.Activations", download->GetDangerType(), - content::DOWNLOAD_DANGER_TYPE_MAX); + download::DOWNLOAD_DANGER_TYPE_MAX); DownloadFeedbackPings* pings = DownloadFeedbackPings::FromDownload(*download); DCHECK(pings);
diff --git a/chrome/browser/safe_browsing/download_protection/download_feedback_service.h b/chrome/browser/safe_browsing/download_protection/download_feedback_service.h index 8183ef5b..d3a97424 100644 --- a/chrome/browser/safe_browsing/download_protection/download_feedback_service.h +++ b/chrome/browser/safe_browsing/download_protection/download_feedback_service.h
@@ -14,7 +14,7 @@ #include "chrome/browser/download/download_commands.h" #include "chrome/browser/safe_browsing/download_protection/download_protection_service.h" #include "chrome/browser/safe_browsing/download_protection/download_protection_util.h" -#include "content/public/browser/download_danger_type.h" +#include "components/download/public/common/download_danger_type.h" namespace base { class TaskRunner; @@ -65,7 +65,7 @@ // Records histogram for download feedback option shown to user. static void RecordEligibleDownloadShown( - content::DownloadDangerType danger_type); + download::DownloadDangerType danger_type); // Begin download feedback for |download|. Then delete download file if // |download_command| is DISCARD, or run the KEEP command otherwise.This must
diff --git a/chrome/browser/safe_browsing/download_protection/download_feedback_service_unittest.cc b/chrome/browser/safe_browsing/download_protection/download_feedback_service_unittest.cc index cfd78346..f0b5c63 100644 --- a/chrome/browser/safe_browsing/download_protection/download_feedback_service_unittest.cc +++ b/chrome/browser/safe_browsing/download_protection/download_feedback_service_unittest.cc
@@ -213,7 +213,7 @@ content::MockDownloadItem item; EXPECT_CALL(item, GetDangerType()) - .WillRepeatedly(Return(content::DOWNLOAD_DANGER_TYPE_UNCOMMON_CONTENT)); + .WillRepeatedly(Return(download::DOWNLOAD_DANGER_TYPE_UNCOMMON_CONTENT)); EXPECT_CALL(item, GetReceivedBytes()).WillRepeatedly(Return(1000)); EXPECT_CALL(item, StealDangerousDownload(true /*delete_file_after_feedback*/, _)) @@ -252,7 +252,7 @@ content::MockDownloadItem item; EXPECT_CALL(item, GetDangerType()) - .WillRepeatedly(Return(content::DOWNLOAD_DANGER_TYPE_UNCOMMON_CONTENT)); + .WillRepeatedly(Return(download::DOWNLOAD_DANGER_TYPE_UNCOMMON_CONTENT)); EXPECT_CALL(item, GetReceivedBytes()).WillRepeatedly(Return(1000)); EXPECT_CALL(item, StealDangerousDownload(false /*delete_file_after_feedback*/, _)) @@ -298,7 +298,8 @@ for (size_t i = 0; i < kNumDownloads; ++i) { file_path[i] = CreateTestFile(i); EXPECT_CALL(item[i], GetDangerType()) - .WillRepeatedly(Return(content::DOWNLOAD_DANGER_TYPE_UNCOMMON_CONTENT)); + .WillRepeatedly( + Return(download::DOWNLOAD_DANGER_TYPE_UNCOMMON_CONTENT)); EXPECT_CALL(item[i], GetReceivedBytes()).WillRepeatedly(Return(1000)); EXPECT_CALL(item[i], StealDangerousDownload(true, _)) .WillOnce(SaveArg<1>(&download_discarded_callback[i])); @@ -367,7 +368,8 @@ for (size_t i = 0; i < kNumDownloads; ++i) { file_path[i] = CreateTestFile(i); EXPECT_CALL(item[i], GetDangerType()) - .WillRepeatedly(Return(content::DOWNLOAD_DANGER_TYPE_UNCOMMON_CONTENT)); + .WillRepeatedly( + Return(download::DOWNLOAD_DANGER_TYPE_UNCOMMON_CONTENT)); EXPECT_CALL(item[i], GetReceivedBytes()).WillRepeatedly(Return(1000)); EXPECT_CALL(item[i], StealDangerousDownload(true, _)) .WillOnce(SaveArg<1>(&download_discarded_callback[i]));
diff --git a/chrome/browser/safe_browsing/download_protection/download_protection_service_unittest.cc b/chrome/browser/safe_browsing/download_protection/download_protection_service_unittest.cc index 1f75e087..e064c450 100644 --- a/chrome/browser/safe_browsing/download_protection/download_protection_service_unittest.cc +++ b/chrome/browser/safe_browsing/download_protection/download_protection_service_unittest.cc
@@ -40,6 +40,7 @@ #include "chrome/common/safe_browsing/binary_feature_extractor.h" #include "chrome/common/safe_browsing/file_type_policies_test_util.h" #include "chrome/test/base/testing_profile.h" +#include "components/download/public/common/download_danger_type.h" #include "components/history/core/browser/history_service.h" #include "components/prefs/pref_service.h" #include "components/safe_browsing/common/safe_browsing_prefs.h" @@ -48,7 +49,6 @@ #include "components/safe_browsing/db/test_database_manager.h" #include "components/safe_browsing/db/v4_protocol_manager_util.h" #include "components/safe_browsing/proto/csd.pb.h" -#include "content/public/browser/download_danger_type.h" #include "content/public/browser/page_navigator.h" #include "content/public/test/mock_download_item.h" #include "content/public/test/test_browser_thread_bundle.h" @@ -2188,7 +2188,7 @@ StrictMock<content::MockDownloadItem> mock_download_item; EXPECT_CALL(mock_download_item, GetDangerType()) - .WillOnce(Return(content::DOWNLOAD_DANGER_TYPE_DANGEROUS_HOST)); + .WillOnce(Return(download::DOWNLOAD_DANGER_TYPE_DANGEROUS_HOST)); EXPECT_CALL(mock_page_navigator, OpenURL(OpenURLParamsWithContextValue("7"))); download_service_->ShowDetailsForDownload(mock_download_item,
diff --git a/chrome/browser/safe_browsing/incident_reporting/last_download_finder.cc b/chrome/browser/safe_browsing/incident_reporting/last_download_finder.cc index 5d36b8b..2f5af2d 100644 --- a/chrome/browser/safe_browsing/incident_reporting/last_download_finder.cc +++ b/chrome/browser/safe_browsing/incident_reporting/last_download_finder.cc
@@ -27,6 +27,7 @@ #include "chrome/common/safe_browsing/file_type_policies.h" #include "components/history/core/browser/download_constants.h" #include "components/history/core/browser/history_service.h" +#include "components/language/core/common/locale_util.h" #include "components/prefs/pref_service.h" #include "components/safe_browsing/proto/csd.pb.h" #include "content/public/browser/notification_details.h" @@ -205,8 +206,10 @@ download.target_path.BaseName().AsUTF8Unsafe()); download_request->set_download_type( download_protection_util::GetDownloadType(download.target_path)); - download_request->set_locale( - g_browser_process->local_state()->GetString(prefs::kApplicationLocale)); + std::string pref_locale = + g_browser_process->local_state()->GetString(prefs::kApplicationLocale); + language::ConvertToActualUILocale(&pref_locale); + download_request->set_locale(pref_locale); details->set_download_time_msec(download.end_time.ToJavaTime()); // Opened time is unknown for now, so use the download time if the file was
diff --git a/chrome/browser/search/one_google_bar/one_google_bar_fetcher_impl.cc b/chrome/browser/search/one_google_bar/one_google_bar_fetcher_impl.cc index f7d5c84..ff2d30b 100644 --- a/chrome/browser/search/one_google_bar/one_google_bar_fetcher_impl.cc +++ b/chrome/browser/search/one_google_bar/one_google_bar_fetcher_impl.cc
@@ -205,7 +205,9 @@ variations::SignedIn::kNo, &headers); #if defined(OS_CHROMEOS) signin::ChromeConnectedHeaderHelper chrome_connected_header_helper( - account_consistency_mirror_required_); + account_consistency_mirror_required_ + ? signin::AccountConsistencyMethod::kMirror + : signin::AccountConsistencyMethod::kDisabled); int profile_mode = signin::PROFILE_MODE_DEFAULT; if (account_consistency_mirror_required_) { // For the child account case (where currently
diff --git a/chrome/browser/signin/about_signin_internals_factory.cc b/chrome/browser/signin/about_signin_internals_factory.cc index 0a89f5d..8cf4aaff 100644 --- a/chrome/browser/signin/about_signin_internals_factory.cc +++ b/chrome/browser/signin/about_signin_internals_factory.cc
@@ -5,6 +5,7 @@ #include "chrome/browser/signin/about_signin_internals_factory.h" #include "chrome/browser/profiles/profile.h" +#include "chrome/browser/signin/account_consistency_mode_manager.h" #include "chrome/browser/signin/account_tracker_service_factory.h" #include "chrome/browser/signin/chrome_signin_client_factory.h" #include "chrome/browser/signin/gaia_cookie_manager_service_factory.h" @@ -54,7 +55,8 @@ AccountTrackerServiceFactory::GetForProfile(profile), SigninManagerFactory::GetForProfile(profile), SigninErrorControllerFactory::GetForProfile(profile), - GaiaCookieManagerServiceFactory::GetForProfile(profile)); + GaiaCookieManagerServiceFactory::GetForProfile(profile), + AccountConsistencyModeManager::GetMethodForProfile(profile)); service->Initialize(ChromeSigninClientFactory::GetForProfile(profile)); return service; }
diff --git a/chrome/browser/signin/account_consistency_mode_manager.cc b/chrome/browser/signin/account_consistency_mode_manager.cc index 3702c70b..569175b7 100644 --- a/chrome/browser/signin/account_consistency_mode_manager.cc +++ b/chrome/browser/signin/account_consistency_mode_manager.cc
@@ -5,10 +5,14 @@ #include "chrome/browser/signin/account_consistency_mode_manager.h" #include "base/logging.h" +#include "base/memory/singleton.h" #include "base/metrics/histogram_macros.h" #include "chrome/browser/profiles/profile.h" +#include "components/keyed_service/content/browser_context_dependency_manager.h" +#include "components/keyed_service/content/browser_context_keyed_service_factory.h" #include "components/pref_registry/pref_registry_syncable.h" #include "components/prefs/pref_service.h" +#include "content/public/browser/browser_context.h" #include "content/public/browser/browser_thread.h" namespace { @@ -33,11 +37,61 @@ }; #endif +class AccountConsistencyModeManagerFactory + : public BrowserContextKeyedServiceFactory { + public: + // Returns an instance of the factory singleton. + static AccountConsistencyModeManagerFactory* GetInstance() { + return base::Singleton<AccountConsistencyModeManagerFactory>::get(); + } + + static AccountConsistencyModeManager* GetForProfile(Profile* profile) { + DCHECK(profile); + return static_cast<AccountConsistencyModeManager*>( + GetInstance()->GetServiceForBrowserContext(profile, true)); + } + + private: + friend struct base::DefaultSingletonTraits< + AccountConsistencyModeManagerFactory>; + + AccountConsistencyModeManagerFactory() + : BrowserContextKeyedServiceFactory( + "AccountConsistencyModeManager", + BrowserContextDependencyManager::GetInstance()) {} + + ~AccountConsistencyModeManagerFactory() override = default; + + // BrowserContextKeyedServiceFactory: + KeyedService* BuildServiceInstanceFor( + content::BrowserContext* context) const override { + DCHECK(!context->IsOffTheRecord()); + Profile* profile = static_cast<Profile*>(context); + return new AccountConsistencyModeManager(profile); + } +}; + +// Returns the default account consistency for guest profiles. +signin::AccountConsistencyMethod GetMethodForNonRegularProfile() { +#if BUILDFLAG(ENABLE_DICE_SUPPORT) + return signin::AccountConsistencyMethod::kDiceFixAuthErrors; +#else + return signin::AccountConsistencyMethod::kDisabled; +#endif +} + } // namespace +// static +AccountConsistencyModeManager* AccountConsistencyModeManager::GetForProfile( + Profile* profile) { + return AccountConsistencyModeManagerFactory::GetForProfile(profile); +} + AccountConsistencyModeManager::AccountConsistencyModeManager(Profile* profile) : profile_(profile) { DCHECK(profile_); + DCHECK(!profile_->IsOffTheRecord()); #if BUILDFLAG(ENABLE_DICE_SUPPORT) bool is_ready_for_dice = IsReadyForDiceMigration(); PrefService* user_prefs = profile->GetPrefs(); @@ -69,19 +123,36 @@ #endif } +// static +signin::AccountConsistencyMethod +AccountConsistencyModeManager::GetMethodForProfile(Profile* profile) { + if (profile->IsOffTheRecord()) + return GetMethodForNonRegularProfile(); + + return AccountConsistencyModeManager::GetForProfile(profile) + ->GetAccountConsistencyMethod(); +} + +// static +signin::AccountConsistencyMethod +AccountConsistencyModeManager::GetMethodForPrefMember( + BooleanPrefMember* dice_pref_member) { + if (signin::IsDiceEnabled(dice_pref_member)) + return signin::AccountConsistencyMethod::kDice; + + return signin::GetAccountConsistencyMethod(); +} + #if BUILDFLAG(ENABLE_DICE_SUPPORT) void AccountConsistencyModeManager::SetReadyForDiceMigration(bool is_ready) { + DCHECK_EQ(Profile::ProfileType::REGULAR_PROFILE, profile_->GetProfileType()); SetDiceMigrationOnStartup(profile_->GetPrefs(), is_ready); } // static -bool AccountConsistencyModeManager::IsDiceEnabledForProfile( - const Profile* profile) { - DCHECK_CURRENTLY_ON(content::BrowserThread::UI); - DCHECK(profile); - - return profile->GetProfileType() == Profile::ProfileType::REGULAR_PROFILE && - signin::IsDiceEnabledForProfile(profile->GetPrefs()); +bool AccountConsistencyModeManager::IsDiceEnabledForProfile(Profile* profile) { + return GetMethodForProfile(profile) == + signin::AccountConsistencyMethod::kDice; } // static @@ -93,20 +164,38 @@ } bool AccountConsistencyModeManager::IsReadyForDiceMigration() { - return profile_->IsNewProfile() || - profile_->GetPrefs()->GetBoolean(kDiceMigrationOnStartupPref); + return (profile_->GetProfileType() == + Profile::ProfileType::REGULAR_PROFILE) && + (profile_->IsNewProfile() || + profile_->GetPrefs()->GetBoolean(kDiceMigrationOnStartupPref)); } #endif // BUILDFLAG(ENABLE_DICE_SUPPORT) // static bool AccountConsistencyModeManager::IsMirrorEnabledForProfile( - const Profile* profile) { - DCHECK_CURRENTLY_ON(content::BrowserThread::UI); - DCHECK(profile); + Profile* profile) { + return GetMethodForProfile(profile) == + signin::AccountConsistencyMethod::kMirror; +} + +signin::AccountConsistencyMethod +AccountConsistencyModeManager::GetAccountConsistencyMethod() { + if (profile_->GetProfileType() != Profile::ProfileType::REGULAR_PROFILE) { + DCHECK_EQ(Profile::ProfileType::GUEST_PROFILE, profile_->GetProfileType()); + return GetMethodForNonRegularProfile(); + } + +#if BUILDFLAG(ENABLE_MIRROR) + return signin::AccountConsistencyMethod::kMirror; +#endif #if defined(OS_CHROMEOS) - return profile->IsChild(); -#else - return signin::IsAccountConsistencyMirrorEnabled(); + if (profile_->IsChild()) + return signin::AccountConsistencyMethod::kMirror; #endif + + if (signin::IsDiceEnabledForProfile(profile_->GetPrefs())) + return signin::AccountConsistencyMethod::kDice; + + return signin::GetAccountConsistencyMethod(); }
diff --git a/chrome/browser/signin/account_consistency_mode_manager.h b/chrome/browser/signin/account_consistency_mode_manager.h index 182361a..07c39ab4 100644 --- a/chrome/browser/signin/account_consistency_mode_manager.h +++ b/chrome/browser/signin/account_consistency_mode_manager.h
@@ -8,6 +8,8 @@ #include "base/gtest_prod_util.h" #include "base/macros.h" #include "build/buildflag.h" +#include "components/keyed_service/core/keyed_service.h" +#include "components/prefs/pref_member.h" #include "components/signin/core/browser/profile_management_switches.h" #include "components/signin/core/browser/signin_features.h" @@ -18,13 +20,26 @@ class Profile; // Manages the account consistency mode for each profile. -class AccountConsistencyModeManager { +class AccountConsistencyModeManager : public KeyedService { public: + // Returns the AccountConsistencyModeManager associated with this profile. + // May return nullptr if there is none (e.g. in incognito). + static AccountConsistencyModeManager* GetForProfile(Profile* profile); + explicit AccountConsistencyModeManager(Profile* profile); - ~AccountConsistencyModeManager(); + ~AccountConsistencyModeManager() override; static void RegisterProfilePrefs(user_prefs::PrefRegistrySyncable* registry); + // Helper method, shorthand for calling GetAccountConsistencyMethod(). + static signin::AccountConsistencyMethod GetMethodForProfile(Profile* profile); + + // Returns the account consistency method for the current profile. Can be + // called from any thread, with a PrefMember created with + // signin::CreateDicePrefMember(). + static signin::AccountConsistencyMethod GetMethodForPrefMember( + BooleanPrefMember* dice_pref_member); + #if BUILDFLAG(ENABLE_DICE_SUPPORT) // Schedules migration to happen at next startup. void SetReadyForDiceMigration(bool is_ready); @@ -35,13 +50,13 @@ // Returns false if |profile| is in Guest or Incognito mode. // A given |profile| will have only one of Mirror or Dice consistency // behaviour enabled. - static bool IsDiceEnabledForProfile(const Profile* profile); + static bool IsDiceEnabledForProfile(Profile* profile); // Returns |true| if Mirror account consistency is enabled for |profile|. // Can only be used on the UI thread. // A given |profile| will have only one of Mirror or Dice consistency // behaviour enabled. - static bool IsMirrorEnabledForProfile(const Profile* profile); + static bool IsMirrorEnabledForProfile(Profile* profile); private: FRIEND_TEST_ALL_PREFIXES(AccountConsistencyModeManagerTest, @@ -56,6 +71,9 @@ bool IsReadyForDiceMigration(); #endif + // Returns the account consistency method for the current profile. + signin::AccountConsistencyMethod GetAccountConsistencyMethod(); + Profile* profile_; DISALLOW_COPY_AND_ASSIGN(AccountConsistencyModeManager);
diff --git a/chrome/browser/signin/account_consistency_mode_manager_unittest.cc b/chrome/browser/signin/account_consistency_mode_manager_unittest.cc index 137c424c..b4777ec 100644 --- a/chrome/browser/signin/account_consistency_mode_manager_unittest.cc +++ b/chrome/browser/signin/account_consistency_mode_manager_unittest.cc
@@ -92,6 +92,43 @@ ASSERT_TRUE(profile->IsNewProfile()); EXPECT_TRUE(signin::IsDiceEnabledForProfile(profile->GetPrefs())); } + +TEST(AccountConsistencyModeManagerTest, DiceOnlyForRegularProfile) { + signin::ScopedAccountConsistencyDice scoped_dice; + content::TestBrowserThreadBundle test_thread_bundle; + + { + // Regular profile. + TestingProfile profile; + EXPECT_TRUE( + AccountConsistencyModeManager::IsDiceEnabledForProfile(&profile)); + EXPECT_EQ(signin::AccountConsistencyMethod::kDice, + AccountConsistencyModeManager::GetMethodForProfile(&profile)); + + // Incognito profile. + Profile* incognito_profile = profile.GetOffTheRecordProfile(); + EXPECT_FALSE(AccountConsistencyModeManager::IsDiceEnabledForProfile( + incognito_profile)); + EXPECT_FALSE( + AccountConsistencyModeManager::GetForProfile(incognito_profile)); + EXPECT_EQ( + signin::AccountConsistencyMethod::kDiceFixAuthErrors, + AccountConsistencyModeManager::GetMethodForProfile(incognito_profile)); + } + + { + // Guest profile. + TestingProfile::Builder profile_builder; + profile_builder.SetGuestSession(); + std::unique_ptr<Profile> profile = profile_builder.Build(); + ASSERT_TRUE(profile->IsGuestSession()); + EXPECT_FALSE( + AccountConsistencyModeManager::IsDiceEnabledForProfile(profile.get())); + EXPECT_EQ( + signin::AccountConsistencyMethod::kDiceFixAuthErrors, + AccountConsistencyModeManager::GetMethodForProfile(profile.get())); + } +} #endif // BUILDFLAG(ENABLE_DICE_SUPPORT) #if defined(OS_CHROMEOS) @@ -102,6 +139,8 @@ TestingProfile profile; EXPECT_FALSE( AccountConsistencyModeManager::IsMirrorEnabledForProfile(&profile)); + EXPECT_EQ(signin::AccountConsistencyMethod::kDisabled, + AccountConsistencyModeManager::GetMethodForProfile(&profile)); } TEST(AccountConsistencyModeManagerTest, MirrorEnabledForUnicorn) { @@ -112,6 +151,8 @@ profile.SetSupervisedUserId(supervised_users::kChildAccountSUID); EXPECT_TRUE( AccountConsistencyModeManager::IsMirrorEnabledForProfile(&profile)); + EXPECT_EQ(signin::AccountConsistencyMethod::kMirror, + AccountConsistencyModeManager::GetMethodForProfile(&profile)); } #endif @@ -124,10 +165,14 @@ TestingProfile profile; EXPECT_TRUE( AccountConsistencyModeManager::IsMirrorEnabledForProfile(&profile)); + EXPECT_EQ(signin::AccountConsistencyMethod::kMirror, + AccountConsistencyModeManager::GetMethodForProfile(&profile)); // Test that Mirror is enabled for child accounts. profile.SetSupervisedUserId(supervised_users::kChildAccountSUID); EXPECT_TRUE( AccountConsistencyModeManager::IsMirrorEnabledForProfile(&profile)); + EXPECT_EQ(signin::AccountConsistencyMethod::kMirror, + AccountConsistencyModeManager::GetMethodForProfile(&profile)); } #endif
diff --git a/chrome/browser/signin/account_reconcilor_factory.cc b/chrome/browser/signin/account_reconcilor_factory.cc index 4d5541c0..b0d640c 100644 --- a/chrome/browser/signin/account_reconcilor_factory.cc +++ b/chrome/browser/signin/account_reconcilor_factory.cc
@@ -131,7 +131,8 @@ case signin::AccountConsistencyMethod::kDice: #if BUILDFLAG(ENABLE_DICE_SUPPORT) return std::make_unique<signin::DiceAccountReconcilorDelegate>( - ChromeSigninClientFactory::GetForProfile(profile)); + ChromeSigninClientFactory::GetForProfile(profile), + AccountConsistencyModeManager::GetMethodForProfile(profile)); #else NOTREACHED(); return nullptr;
diff --git a/chrome/browser/signin/chrome_signin_client.cc b/chrome/browser/signin/chrome_signin_client.cc index 4dbeef50..4dac09d 100644 --- a/chrome/browser/signin/chrome_signin_client.cc +++ b/chrome/browser/signin/chrome_signin_client.cc
@@ -24,6 +24,7 @@ #include "chrome/browser/profiles/profile_manager.h" #include "chrome/browser/profiles/profile_metrics.h" #include "chrome/browser/profiles/profile_window.h" +#include "chrome/browser/signin/account_consistency_mode_manager.h" #include "chrome/browser/signin/force_signin_verifier.h" #include "chrome/browser/signin/local_auth.h" #include "chrome/browser/signin/profile_oauth2_token_service_factory.h" @@ -71,7 +72,6 @@ : OAuth2TokenService::Consumer("chrome_signin_client"), profile_(profile), signin_error_controller_(signin_error_controller), - account_consistency_mode_manager_(profile), weak_ptr_factory_(this) { signin_error_controller_->AddObserver(this); #if !defined(OS_CHROMEOS) @@ -468,7 +468,8 @@ void ChromeSigninClient::SetReadyForDiceMigration(bool is_ready) { #if BUILDFLAG(ENABLE_DICE_SUPPORT) - account_consistency_mode_manager_.SetReadyForDiceMigration(is_ready); + AccountConsistencyModeManager::GetForProfile(profile_) + ->SetReadyForDiceMigration(is_ready); #else NOTREACHED(); #endif
diff --git a/chrome/browser/signin/chrome_signin_client.h b/chrome/browser/signin/chrome_signin_client.h index 3557ac4..3405435 100644 --- a/chrome/browser/signin/chrome_signin_client.h +++ b/chrome/browser/signin/chrome_signin_client.h
@@ -9,7 +9,6 @@ #include "base/macros.h" #include "base/memory/weak_ptr.h" #include "build/build_config.h" -#include "chrome/browser/signin/account_consistency_mode_manager.h" #include "components/signin/core/browser/signin_client.h" #include "components/signin/core/browser/signin_error_controller.h" #include "google_apis/gaia/gaia_oauth_client.h" @@ -37,6 +36,7 @@ explicit ChromeSigninClient( Profile* profile, SigninErrorController* signin_error_controller); ~ChromeSigninClient() override; + void DoFinalInit() override; // Utility method. @@ -134,7 +134,6 @@ std::unique_ptr<gaia::GaiaOAuthClient> oauth_client_; std::unique_ptr<OAuth2TokenService::Request> oauth_request_; - AccountConsistencyModeManager account_consistency_mode_manager_; base::WeakPtrFactory<ChromeSigninClient> weak_ptr_factory_;
diff --git a/chrome/browser/signin/chrome_signin_client_unittest.cc b/chrome/browser/signin/chrome_signin_client_unittest.cc index 0af583fb..98f5727 100644 --- a/chrome/browser/signin/chrome_signin_client_unittest.cc +++ b/chrome/browser/signin/chrome_signin_client_unittest.cc
@@ -20,6 +20,7 @@ #include "chrome/test/base/browser_with_test_window_test.h" #include "chrome/test/base/testing_browser_process.h" #include "chrome/test/base/testing_profile.h" +#include "components/signin/core/browser/profile_management_switches.h" #include "content/public/common/network_connection_tracker.h" #include "content/public/test/test_browser_thread_bundle.h" #include "testing/gmock/include/gmock/gmock.h" @@ -181,7 +182,8 @@ nullptr, &fake_service_, nullptr, - signin_error_controller) { + signin_error_controller, + signin::AccountConsistencyMethod::kDisabled) { DCHECK(signin_error_controller); }
diff --git a/chrome/browser/signin/chrome_signin_helper.cc b/chrome/browser/signin/chrome_signin_helper.cc index 3fa2dcc2..c070eb7e 100644 --- a/chrome/browser/signin/chrome_signin_helper.cc +++ b/chrome/browser/signin/chrome_signin_helper.cc
@@ -18,6 +18,7 @@ #include "build/build_config.h" #include "chrome/browser/prefs/incognito_mode_prefs.h" #include "chrome/browser/profiles/profile_io_data.h" +#include "chrome/browser/signin/account_consistency_mode_manager.h" #include "chrome/browser/signin/account_reconcilor_factory.h" #include "chrome/browser/signin/chrome_signin_client.h" #include "chrome/browser/signin/chrome_signin_client_factory.h" @@ -441,9 +442,14 @@ profile_mode_mask |= PROFILE_MODE_INCOGNITO_DISABLED; } + AccountConsistencyMethod account_consistency = + AccountConsistencyModeManager::GetMethodForPrefMember( + io_data->dice_enabled()); + #if defined(OS_CHROMEOS) // Mirror account consistency required by profile. if (io_data->account_consistency_mirror_required()->GetValue()) { + account_consistency = AccountConsistencyMethod::kMirror; // Can't add new accounts. profile_mode_mask |= PROFILE_MODE_ADD_ACCOUNT_DISABLED; } @@ -456,7 +462,7 @@ // Dice header: bool dice_header_added = AppendOrRemoveDiceRequestHeader( request, redirect_url, account_id, io_data->IsSyncEnabled(), - io_data->SyncHasAuthError(), io_data->dice_enabled(), + io_data->SyncHasAuthError(), account_consistency, io_data->GetCookieSettings()); // Block the AccountReconcilor while the Dice requests are in flight. This @@ -465,18 +471,10 @@ if (dice_header_added) DiceURLRequestUserData::AttachToRequest(request); -#if defined(OS_CHROMEOS) - bool mirror_enabled = - io_data->account_consistency_mirror_required()->GetValue() || - IsAccountConsistencyMirrorEnabled(); -#else - bool mirror_enabled = IsAccountConsistencyMirrorEnabled(); -#endif - // Mirror header: - AppendOrRemoveMirrorRequestHeader(request, redirect_url, account_id, - io_data->GetCookieSettings(), - mirror_enabled, profile_mode_mask); + AppendOrRemoveMirrorRequestHeader( + request, redirect_url, account_id, account_consistency, + io_data->GetCookieSettings(), profile_mode_mask); } void ProcessAccountConsistencyResponseHeaders(net::URLRequest* request,
diff --git a/chrome/browser/signin/dice_response_handler_unittest.cc b/chrome/browser/signin/dice_response_handler_unittest.cc index 5db318d1..03dd73a 100644 --- a/chrome/browser/signin/dice_response_handler_unittest.cc +++ b/chrome/browser/signin/dice_response_handler_unittest.cc
@@ -134,7 +134,8 @@ &account_tracker_service_, &signin_manager_, &signin_error_controller_, - &cookie_service_), + &cookie_service_, + signin::AccountConsistencyMethod::kDice), reconcilor_blocked_count_(0), reconcilor_unblocked_count_(0) { loop_.SetTaskRunner(task_runner_); @@ -147,7 +148,7 @@ signin::SetGaiaOriginIsolatedCallback(base::Bind([] { return true; })); auto account_reconcilor_delegate = std::make_unique<signin::DiceAccountReconcilorDelegate>( - &signin_client_); + &signin_client_, signin::AccountConsistencyMethod::kDisabled); account_reconcilor_ = std::make_unique<AccountReconcilor>( &token_service_, &signin_manager_, &signin_client_, nullptr, std::move(account_reconcilor_delegate));
diff --git a/chrome/browser/signin/signin_manager_factory.cc b/chrome/browser/signin/signin_manager_factory.cc index 8d077812d..c149bae 100644 --- a/chrome/browser/signin/signin_manager_factory.cc +++ b/chrome/browser/signin/signin_manager_factory.cc
@@ -7,6 +7,7 @@ #include "build/build_config.h" #include "chrome/browser/browser_process.h" #include "chrome/browser/profiles/profile.h" +#include "chrome/browser/signin/account_consistency_mode_manager.h" #include "chrome/browser/signin/account_fetcher_service_factory.h" #include "chrome/browser/signin/account_tracker_service_factory.h" #include "chrome/browser/signin/chrome_signin_client_factory.h" @@ -121,7 +122,8 @@ client, ProfileOAuth2TokenServiceFactory::GetForProfile(profile), AccountTrackerServiceFactory::GetForProfile(profile), GaiaCookieManagerServiceFactory::GetForProfile(profile), - SigninErrorControllerFactory::GetForProfile(profile)); + SigninErrorControllerFactory::GetForProfile(profile), + AccountConsistencyModeManager::GetMethodForProfile(profile)); AccountFetcherServiceFactory::GetForProfile(profile); #endif service->Initialize(g_browser_process->local_state());
diff --git a/chrome/browser/supervised_user/supervised_user_navigation_throttle.cc b/chrome/browser/supervised_user/supervised_user_navigation_throttle.cc index e9f434c..ab2d549 100644 --- a/chrome/browser/supervised_user/supervised_user_navigation_throttle.cc +++ b/chrome/browser/supervised_user/supervised_user_navigation_throttle.cc
@@ -79,6 +79,7 @@ // Should never happen, only used for requests from Webview NOTREACHED(); } + FALLTHROUGH; case SupervisedUserURLFilter::INVALID: NOTREACHED(); }
diff --git a/chrome/browser/task_manager/providers/child_process_task.cc b/chrome/browser/task_manager/providers/child_process_task.cc index ec8eee4..66cd00d 100644 --- a/chrome/browser/task_manager/providers/child_process_task.cc +++ b/chrome/browser/task_manager/providers/child_process_task.cc
@@ -94,6 +94,7 @@ return l10n_util::GetStringFUTF16(IDS_TASK_MANAGER_RENDERER_PREFIX, result_title); } + FALLTHROUGH; } // These types don't need display names or get them from elsewhere. case content::PROCESS_TYPE_BROWSER:
diff --git a/chrome/browser/task_manager/task_manager_browsertest.cc b/chrome/browser/task_manager/task_manager_browsertest.cc index 276665f..9f237c33 100644 --- a/chrome/browser/task_manager/task_manager_browsertest.cc +++ b/chrome/browser/task_manager/task_manager_browsertest.cc
@@ -698,12 +698,8 @@ ->GetActiveWebContents() ->GetMainFrame() ->ExecuteJavaScriptForTests(base::UTF8ToUTF16(test_js)); - // TODO(cburn): The assertion below currently assumes that the rate - // contribution of the entire 16MB upload arrives in a single refresh cycle. - // That's true now because it's only reported when the transaction completes, - // but if that changes in the future, this assertion may need to change. ASSERT_NO_FATAL_FAILURE(WaitForTaskManagerStatToExceed( - MatchTab("network use"), ColumnSpecifier::NETWORK_USE, 16000000)); + MatchTab("network use"), ColumnSpecifier::TOTAL_NETWORK_USE, 16000000)); } IN_PROC_BROWSER_TEST_F(TaskManagerBrowserTest, TotalSentDataObserved) {
diff --git a/chrome/browser/task_manager/task_manager_tester.cc b/chrome/browser/task_manager/task_manager_tester.cc index 3a9b327..bdb2c9a8 100644 --- a/chrome/browser/task_manager/task_manager_tester.cc +++ b/chrome/browser/task_manager/task_manager_tester.cc
@@ -168,6 +168,7 @@ case ColumnSpecifier::NETWORK_USE: value = task_manager()->GetNetworkUsage(task_id); success = true; + break; case ColumnSpecifier::TOTAL_NETWORK_USE: value = task_manager()->GetCumulativeNetworkUsage(task_id); success = true;
diff --git a/chrome/browser/thumbnails/thumbnail_browsertest.cc b/chrome/browser/thumbnails/thumbnail_browsertest.cc index 3abca46..bd170dc 100644 --- a/chrome/browser/thumbnails/thumbnail_browsertest.cc +++ b/chrome/browser/thumbnails/thumbnail_browsertest.cc
@@ -26,7 +26,7 @@ #include "content/public/browser/navigation_handle.h" #include "content/public/browser/web_contents_observer.h" #include "content/public/common/content_switches.h" -#include "content/public/test/controllable_http_response.h" +#include "net/test/embedded_test_server/controllable_http_response.h" #include "net/test/embedded_test_server/embedded_test_server.h" #include "testing/gmock/include/gmock/gmock.h" #include "testing/gtest/include/gtest/gtest.h" @@ -203,12 +203,12 @@ IN_PROC_BROWSER_TEST_F(ThumbnailTest, ShouldCaptureOnNavigatingAwayExplicitWait) { - content::ControllableHttpResponse response_red(embedded_test_server(), - "/red.html"); - content::ControllableHttpResponse response_yellow(embedded_test_server(), - "/yellow.html"); - content::ControllableHttpResponse response_green(embedded_test_server(), - "/green.html"); + net::test_server::ControllableHttpResponse response_red( + embedded_test_server(), "/red.html"); + net::test_server::ControllableHttpResponse response_yellow( + embedded_test_server(), "/yellow.html"); + net::test_server::ControllableHttpResponse response_green( + embedded_test_server(), "/green.html"); ASSERT_TRUE(embedded_test_server()->Start()); const GURL about_blank_url("about:blank");
diff --git a/chrome/browser/ui/BUILD.gn b/chrome/browser/ui/BUILD.gn index de6e1d77..307fc1a2 100644 --- a/chrome/browser/ui/BUILD.gn +++ b/chrome/browser/ui/BUILD.gn
@@ -987,6 +987,7 @@ "//components/invalidation/impl", "//components/keyed_service/content", "//components/keyed_service/core", + "//components/language/core/common", "//components/navigation_metrics", "//components/net_log", "//components/ntp_snippets",
diff --git a/chrome/browser/ui/ash/auto_connect_notifier_unittest.cc b/chrome/browser/ui/ash/auto_connect_notifier_unittest.cc index fa27cd6..4dd12bb 100644 --- a/chrome/browser/ui/ash/auto_connect_notifier_unittest.cc +++ b/chrome/browser/ui/ash/auto_connect_notifier_unittest.cc
@@ -117,7 +117,6 @@ } void TearDown() override { - display_service_.reset(); auto_connect_notifier_.reset(); ShutdownNetworkState();
diff --git a/chrome/browser/ui/ash/chrome_new_window_client_browsertest.cc b/chrome/browser/ui/ash/chrome_new_window_client_browsertest.cc index 89d8c68..ea939f1e 100644 --- a/chrome/browser/ui/ash/chrome_new_window_client_browsertest.cc +++ b/chrome/browser/ui/ash/chrome_new_window_client_browsertest.cc
@@ -12,6 +12,8 @@ #include "chrome/test/base/in_process_browser_test.h" #include "components/session_manager/core/session_manager.h" #include "components/signin/core/account_id/account_id.h" +#include "components/user_manager/known_user.h" +#include "components/user_manager/user_manager.h" #include "testing/gtest/include/gtest/gtest.h" #include "ui/aura/window.h" @@ -26,6 +28,9 @@ using chromeos::ProfileHelper; using session_manager::SessionManager; + user_manager::known_user::SetProfileRequiresPolicy( + account_id, + user_manager::known_user::ProfileRequiresPolicy::kNoPolicyRequired); const std::string user_id_hash = ProfileHelper::GetUserIdHashByUserIdForTesting(account_id.GetUserEmail()); SessionManager::Get()->CreateSession(account_id, user_id_hash, false);
diff --git a/chrome/browser/ui/ash/network/data_promo_notification_unittest.cc b/chrome/browser/ui/ash/network/data_promo_notification_unittest.cc index 2785e7d7..268eea3 100644 --- a/chrome/browser/ui/ash/network/data_promo_notification_unittest.cc +++ b/chrome/browser/ui/ash/network/data_promo_notification_unittest.cc
@@ -77,7 +77,6 @@ chromeos::NetworkConnect::Shutdown(); network_connect_delegate_.reset(); LoginState::Shutdown(); - display_service_.reset(); profile_manager_.reset(); user_manager_enabler_.reset(); data_promo_notification_.reset();
diff --git a/chrome/browser/ui/ash/network/network_state_notifier.cc b/chrome/browser/ui/ash/network/network_state_notifier.cc index 4f3e0ff..6e884378 100644 --- a/chrome/browser/ui/ash/network/network_state_notifier.cc +++ b/chrome/browser/ui/ash/network/network_state_notifier.cc
@@ -478,7 +478,21 @@ void NetworkStateNotifier::ShowNetworkSettings(const std::string& network_id) { if (!SystemTrayClient::Get()) return; - SystemTrayClient::Get()->ShowNetworkSettings(network_id); + const NetworkState* network = GetNetworkStateForGuid(network_id); + if (!network) + return; + std::string error = network->GetErrorState(); + if (!error.empty()) { + NET_LOG(ERROR) << "Notify ShowNetworkSettings: " << network_id + << ": Error: " << error; + } + if (!NetworkTypePattern::Primitive(network->type()) + .MatchesPattern(NetworkTypePattern::Mobile()) && + shill_error::IsConfigurationError(error)) { + SystemTrayClient::Get()->ShowNetworkConfigure(network_id); + } else { + SystemTrayClient::Get()->ShowNetworkSettings(network_id); + } } } // namespace chromeos
diff --git a/chrome/browser/ui/ash/network/tether_notification_presenter_unittest.cc b/chrome/browser/ui/ash/network/tether_notification_presenter_unittest.cc index 6110867f..c7ec24a 100644 --- a/chrome/browser/ui/ash/network/tether_notification_presenter_unittest.cc +++ b/chrome/browser/ui/ash/network/tether_notification_presenter_unittest.cc
@@ -45,10 +45,6 @@ // NetworkConnect: void DisconnectFromNetworkId(const std::string& network_id) override {} - bool MaybeShowConfigureUI(const std::string& network_id, - const std::string& connect_error) override { - return false; - } void SetTechnologyEnabled(const chromeos::NetworkTypePattern& technology, bool enabled_state) override {} void ShowMobileSetup(const std::string& network_id) override {} @@ -109,11 +105,6 @@ base::WrapUnique(test_settings_ui_delegate_)); } - void TearDown() override { - display_service_.reset(); - BrowserWithTestWindowTest::TearDown(); - } - std::string GetActiveHostNotificationId() { return std::string(TetherNotificationPresenter::kActiveHostNotificationId); }
diff --git a/chrome/browser/ui/ash/system_tray_client.cc b/chrome/browser/ui/ash/system_tray_client.cc index f112f00..bb4072a 100644 --- a/chrome/browser/ui/ash/system_tray_client.cc +++ b/chrome/browser/ui/ash/system_tray_client.cc
@@ -342,7 +342,7 @@ } if (chromeos::switches::IsNetworkSettingsConfigEnabled()) - chromeos::InternetConfigDialog::ShowDialogForNetworkState(network_state); + chromeos::InternetConfigDialog::ShowDialogForNetworkId(network_id); else chromeos::NetworkConfigView::ShowForNetworkId(network_id); }
diff --git a/chrome/browser/ui/browser_navigator.cc b/chrome/browser/ui/browser_navigator.cc index bde0039..96c79a5d 100644 --- a/chrome/browser/ui/browser_navigator.cc +++ b/chrome/browser/ui/browser_navigator.cc
@@ -307,6 +307,7 @@ load_url_params.is_renderer_initiated = params->is_renderer_initiated; load_url_params.started_from_context_menu = params->started_from_context_menu; load_url_params.suggested_filename = params->suggested_filename; + load_url_params.has_user_gesture = params->user_gesture; if (params->uses_post) { load_url_params.load_type = NavigationController::LOAD_TYPE_HTTP_POST;
diff --git a/chrome/browser/ui/cocoa/bubble_anchor_helper.mm b/chrome/browser/ui/cocoa/bubble_anchor_helper.mm index 0c46a603..481c01d6 100644 --- a/chrome/browser/ui/cocoa/bubble_anchor_helper.mm +++ b/chrome/browser/ui/cocoa/bubble_anchor_helper.mm
@@ -12,6 +12,7 @@ #include "chrome/browser/ui/bubble_anchor_util.h" #import "chrome/browser/ui/cocoa/browser_window_controller.h" #import "chrome/browser/ui/cocoa/fullscreen/fullscreen_toolbar_controller.h" +#import "chrome/browser/ui/cocoa/l10n_util.h" #import "chrome/browser/ui/cocoa/location_bar/location_bar_view_mac.h" #import "ui/base/cocoa/cocoa_base_utils.h" @@ -47,9 +48,13 @@ // Position the bubble on the left of the screen if there is no page info // button to point at. NSRect contentFrame = [[parentWindow contentView] frame]; - anchor = NSMakePoint( - NSMinX(contentFrame) + bubble_anchor_util::kNoToolbarLeftOffset, - NSMaxY(contentFrame)); + CGFloat x_offset = + NSMinX(contentFrame) + bubble_anchor_util::kNoToolbarLeftOffset; + if (cocoa_l10n_util::ShouldDoExperimentalRTLLayout()) { + x_offset = + NSMaxX(contentFrame) - bubble_anchor_util::kNoToolbarLeftOffset; + } + anchor = NSMakePoint(x_offset, NSMaxY(contentFrame)); } return ui::ConvertPointFromWindowToScreen(parentWindow, anchor);
diff --git a/chrome/browser/ui/cocoa/download/download_danger_prompt_impl.cc b/chrome/browser/ui/cocoa/download/download_danger_prompt_impl.cc index 8f10bb5..f036aff 100644 --- a/chrome/browser/ui/cocoa/download/download_danger_prompt_impl.cc +++ b/chrome/browser/ui/cocoa/download/download_danger_prompt_impl.cc
@@ -14,9 +14,9 @@ #include "chrome/browser/ui/tab_modal_confirm_dialog_delegate.h" #include "chrome/grit/chromium_strings.h" #include "chrome/grit/generated_resources.h" +#include "components/download/public/common/download_danger_type.h" #include "components/strings/grit/components_strings.h" #include "content/public/browser/browser_context.h" -#include "content/public/browser/download_danger_type.h" #include "content/public/browser/download_item.h" #include "ui/base/l10n/l10n_util.h" #include "url/gurl.h" @@ -126,12 +126,12 @@ if (show_context_) return l10n_util::GetStringUTF16(IDS_CONFIRM_KEEP_DANGEROUS_DOWNLOAD_TITLE); switch (download_->GetDangerType()) { - case content::DOWNLOAD_DANGER_TYPE_DANGEROUS_URL: - case content::DOWNLOAD_DANGER_TYPE_DANGEROUS_CONTENT: - case content::DOWNLOAD_DANGER_TYPE_DANGEROUS_HOST: - case content::DOWNLOAD_DANGER_TYPE_POTENTIALLY_UNWANTED: + case download::DOWNLOAD_DANGER_TYPE_DANGEROUS_URL: + case download::DOWNLOAD_DANGER_TYPE_DANGEROUS_CONTENT: + case download::DOWNLOAD_DANGER_TYPE_DANGEROUS_HOST: + case download::DOWNLOAD_DANGER_TYPE_POTENTIALLY_UNWANTED: return l10n_util::GetStringUTF16(IDS_KEEP_DANGEROUS_DOWNLOAD_TITLE); - case content::DOWNLOAD_DANGER_TYPE_UNCOMMON_CONTENT: + case download::DOWNLOAD_DANGER_TYPE_UNCOMMON_CONTENT: return l10n_util::GetStringUTF16(IDS_KEEP_UNCOMMON_DOWNLOAD_TITLE); default: { return l10n_util::GetStringUTF16( @@ -143,42 +143,42 @@ base::string16 DownloadDangerPromptImpl::GetDialogMessage() { if (show_context_) { switch (download_->GetDangerType()) { - case content::DOWNLOAD_DANGER_TYPE_DANGEROUS_FILE: { + case download::DOWNLOAD_DANGER_TYPE_DANGEROUS_FILE: { return l10n_util::GetStringFUTF16( IDS_PROMPT_DANGEROUS_DOWNLOAD, download_->GetFileNameToReportUser().LossyDisplayName()); } - case content::DOWNLOAD_DANGER_TYPE_DANGEROUS_URL: // Fall through - case content::DOWNLOAD_DANGER_TYPE_DANGEROUS_CONTENT: - case content::DOWNLOAD_DANGER_TYPE_DANGEROUS_HOST: { + case download::DOWNLOAD_DANGER_TYPE_DANGEROUS_URL: // Fall through + case download::DOWNLOAD_DANGER_TYPE_DANGEROUS_CONTENT: + case download::DOWNLOAD_DANGER_TYPE_DANGEROUS_HOST: { return l10n_util::GetStringFUTF16( IDS_PROMPT_MALICIOUS_DOWNLOAD_CONTENT, download_->GetFileNameToReportUser().LossyDisplayName()); } - case content::DOWNLOAD_DANGER_TYPE_UNCOMMON_CONTENT: { + case download::DOWNLOAD_DANGER_TYPE_UNCOMMON_CONTENT: { return l10n_util::GetStringFUTF16( IDS_PROMPT_UNCOMMON_DOWNLOAD_CONTENT, download_->GetFileNameToReportUser().LossyDisplayName()); } - case content::DOWNLOAD_DANGER_TYPE_POTENTIALLY_UNWANTED: { + case download::DOWNLOAD_DANGER_TYPE_POTENTIALLY_UNWANTED: { return l10n_util::GetStringFUTF16( IDS_PROMPT_DOWNLOAD_CHANGES_SETTINGS, download_->GetFileNameToReportUser().LossyDisplayName()); } - case content::DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS: - case content::DOWNLOAD_DANGER_TYPE_MAYBE_DANGEROUS_CONTENT: - case content::DOWNLOAD_DANGER_TYPE_USER_VALIDATED: - case content::DOWNLOAD_DANGER_TYPE_MAX: { + case download::DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS: + case download::DOWNLOAD_DANGER_TYPE_MAYBE_DANGEROUS_CONTENT: + case download::DOWNLOAD_DANGER_TYPE_USER_VALIDATED: + case download::DOWNLOAD_DANGER_TYPE_MAX: { break; } } } else { switch (download_->GetDangerType()) { - case content::DOWNLOAD_DANGER_TYPE_DANGEROUS_URL: - case content::DOWNLOAD_DANGER_TYPE_DANGEROUS_CONTENT: - case content::DOWNLOAD_DANGER_TYPE_DANGEROUS_HOST: - case content::DOWNLOAD_DANGER_TYPE_POTENTIALLY_UNWANTED: - case content::DOWNLOAD_DANGER_TYPE_UNCOMMON_CONTENT: { + case download::DOWNLOAD_DANGER_TYPE_DANGEROUS_URL: + case download::DOWNLOAD_DANGER_TYPE_DANGEROUS_CONTENT: + case download::DOWNLOAD_DANGER_TYPE_DANGEROUS_HOST: + case download::DOWNLOAD_DANGER_TYPE_POTENTIALLY_UNWANTED: + case download::DOWNLOAD_DANGER_TYPE_UNCOMMON_CONTENT: { return l10n_util::GetStringUTF16( IDS_PROMPT_CONFIRM_KEEP_MALICIOUS_DOWNLOAD_BODY); }
diff --git a/chrome/browser/ui/cocoa/download/download_item_controller_unittest.mm b/chrome/browser/ui/cocoa/download/download_item_controller_unittest.mm index 7e4de44..c287db8 100644 --- a/chrome/browser/ui/cocoa/download/download_item_controller_unittest.mm +++ b/chrome/browser/ui/cocoa/download/download_item_controller_unittest.mm
@@ -50,7 +50,7 @@ ON_CALL(*download_item_, GetFileNameToReportUser()) .WillByDefault(Return(base::FilePath())); ON_CALL(*download_item_, GetDangerType()) - .WillByDefault(Return(content::DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS)); + .WillByDefault(Return(download::DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS)); ON_CALL(*download_item_, GetTargetFilePath()) .WillByDefault(ReturnRefOfCopy(base::FilePath())); ON_CALL(*download_item_, GetLastReason()) @@ -101,7 +101,7 @@ TEST_F(DownloadItemControllerTest, DangerousDownload) { ON_CALL(*download_item_, GetDangerType()) - .WillByDefault(Return(content::DOWNLOAD_DANGER_TYPE_DANGEROUS_FILE)); + .WillByDefault(Return(download::DOWNLOAD_DANGER_TYPE_DANGEROUS_FILE)); ON_CALL(*download_item_, IsDangerous()).WillByDefault(Return(true)); [[(id)shelf_controller_ expect] layoutItems]; download_item_->NotifyObserversDownloadUpdated(); @@ -117,7 +117,7 @@ // The download is now marked as dangerous. [[(id)shelf_controller_ expect] layoutItems]; ON_CALL(*download_item_, GetDangerType()) - .WillByDefault(Return(content::DOWNLOAD_DANGER_TYPE_DANGEROUS_FILE)); + .WillByDefault(Return(download::DOWNLOAD_DANGER_TYPE_DANGEROUS_FILE)); ON_CALL(*download_item_, IsDangerous()).WillByDefault(Return(true)); download_item_->NotifyObserversDownloadUpdated(); @@ -128,7 +128,7 @@ // And then marked as safe again. [[(id)shelf_controller_ expect] layoutItems]; ON_CALL(*download_item_, GetDangerType()) - .WillByDefault(Return(content::DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS)); + .WillByDefault(Return(download::DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS)); ON_CALL(*download_item_, IsDangerous()).WillByDefault(Return(false)); download_item_->NotifyObserversDownloadUpdated();
diff --git a/chrome/browser/ui/cocoa/download/md_download_item_view_unittest.mm b/chrome/browser/ui/cocoa/download/md_download_item_view_unittest.mm index ddb32743..28412ee 100644 --- a/chrome/browser/ui/cocoa/download/md_download_item_view_unittest.mm +++ b/chrome/browser/ui/cocoa/download/md_download_item_view_unittest.mm
@@ -50,7 +50,7 @@ ON_CALL(item_, GetDangerType()) .WillByDefault( - testing::Return(content::DOWNLOAD_DANGER_TYPE_DANGEROUS_URL)); + testing::Return(download::DOWNLOAD_DANGER_TYPE_DANGEROUS_URL)); ON_CALL(item_, IsDangerous()).WillByDefault(testing::Return(true)); set_state_and_display();
diff --git a/chrome/browser/ui/cocoa/extensions/browser_actions_controller.h b/chrome/browser/ui/cocoa/extensions/browser_actions_controller.h index 319de81..bd880d8 100644 --- a/chrome/browser/ui/cocoa/extensions/browser_actions_controller.h +++ b/chrome/browser/ui/cocoa/extensions/browser_actions_controller.h
@@ -62,6 +62,9 @@ // Bridge for showing the toolkit-views bubble on a Cocoa browser. std::unique_ptr<ToolbarActionsBarBubbleViewsPresenter> viewsBubblePresenter_; + + // True if a toolbar action button is being dragged. + BOOL isDraggingSession_; } @property(nonatomic) CGFloat maxWidth;
diff --git a/chrome/browser/ui/cocoa/extensions/browser_actions_controller.mm b/chrome/browser/ui/cocoa/extensions/browser_actions_controller.mm index 203bf81..f479d50 100644 --- a/chrome/browser/ui/cocoa/extensions/browser_actions_controller.mm +++ b/chrome/browser/ui/cocoa/extensions/browser_actions_controller.mm
@@ -679,6 +679,15 @@ // Determine what index the dragged button should lie in, alter the model and // reposition the buttons. BrowserActionButton* draggedButton = [notification object]; + + if (!isDraggingSession_) { + for (BrowserActionButton* button : buttons_.get()) { + if (button != draggedButton) + [[button cell] setIsHoverDisabled:YES]; + } + isDraggingSession_ = YES; + } + NSRect draggedButtonFrame = [draggedButton frame]; // Find the mid-point. We flip the y-coordinates so that y = 0 is at the // top of the container to make row calculation more logical. @@ -712,6 +721,13 @@ } - (void)actionButtonDragFinished:(NSNotification*)notification { + BrowserActionButton* draggedButton = [notification object]; + for (BrowserActionButton* button : buttons_.get()) { + if (button != draggedButton) + [[button cell] setIsHoverDisabled:NO]; + } + + isDraggingSession_ = NO; [self redraw]; }
diff --git a/chrome/browser/ui/cocoa/image_button_cell.h b/chrome/browser/ui/cocoa/image_button_cell.h index d6c7cf8..9fc9b03 100644 --- a/chrome/browser/ui/cocoa/image_button_cell.h +++ b/chrome/browser/ui/cocoa/image_button_cell.h
@@ -46,6 +46,9 @@ base::scoped_nsobject<NSImage> image; } image_[image_button_cell::kButtonStateCount]; BOOL isMouseInside_; + + // Disables the hover effect if set to true. + BOOL isHoverDisabled_; } @property(assign, nonatomic) BOOL isMouseInside; @@ -75,6 +78,10 @@ // Draws the cell's image within |cellFrame|. - (void)drawImageWithFrame:(NSRect)cellFrame inView:(NSView*)controlView; +// Setter for |isHoverDisabled|. If |disable| is true, set |isMouseInside_| to +// false. +- (void)setIsHoverDisabled:(BOOL)disable; + @end #endif // CHROME_BROWSER_UI_COCOA_IMAGE_BUTTON_CELL_H_
diff --git a/chrome/browser/ui/cocoa/image_button_cell.mm b/chrome/browser/ui/cocoa/image_button_cell.mm index 81639be6..f864db1 100644 --- a/chrome/browser/ui/cocoa/image_button_cell.mm +++ b/chrome/browser/ui/cocoa/image_button_cell.mm
@@ -167,6 +167,13 @@ hints:nil]; } +- (void)setIsHoverDisabled:(BOOL)disable { + if (disable) + [self setIsMouseInside:NO]; + + isHoverDisabled_ = disable; +} + - (void)drawWithFrame:(NSRect)cellFrame inView:(NSView*)controlView { [self drawImageWithFrame:cellFrame inView:controlView]; } @@ -235,6 +242,9 @@ } - (void)setIsMouseInside:(BOOL)isMouseInside { + if (isHoverDisabled_) + return; + if (isMouseInside_ != isMouseInside) { oldState_ = [self currentButtonState]; isMouseInside_ = isMouseInside;
diff --git a/chrome/browser/ui/cocoa/media_picker/desktop_media_picker_cocoa.h b/chrome/browser/ui/cocoa/media_picker/desktop_media_picker_cocoa.h index d68638ee..36da5ea5 100644 --- a/chrome/browser/ui/cocoa/media_picker/desktop_media_picker_cocoa.h +++ b/chrome/browser/ui/cocoa/media_picker/desktop_media_picker_cocoa.h
@@ -19,13 +19,8 @@ ~DesktopMediaPickerCocoa() override; // Overridden from DesktopMediaPicker: - void Show(content::WebContents* web_contents, - gfx::NativeWindow context, - gfx::NativeWindow parent, - const base::string16& app_name, - const base::string16& target_name, + void Show(const DesktopMediaPicker::Params& params, std::vector<std::unique_ptr<DesktopMediaList>> source_lists, - bool request_audio, const DoneCallback& done_callback) override; private:
diff --git a/chrome/browser/ui/cocoa/media_picker/desktop_media_picker_cocoa.mm b/chrome/browser/ui/cocoa/media_picker/desktop_media_picker_cocoa.mm index bce6a90..1036938 100644 --- a/chrome/browser/ui/cocoa/media_picker/desktop_media_picker_cocoa.mm +++ b/chrome/browser/ui/cocoa/media_picker/desktop_media_picker_cocoa.mm
@@ -15,21 +15,16 @@ } void DesktopMediaPickerCocoa::Show( - content::WebContents* web_contents, - gfx::NativeWindow context, - gfx::NativeWindow parent, - const base::string16& app_name, - const base::string16& target_name, + const DesktopMediaPicker::Params& params, std::vector<std::unique_ptr<DesktopMediaList>> source_lists, - bool request_audio, const DoneCallback& done_callback) { controller_.reset([[DesktopMediaPickerController alloc] initWithSourceLists:std::move(source_lists) - parent:parent + parent:params.parent callback:done_callback - appName:app_name - targetName:target_name - requestAudio:request_audio]); + appName:params.app_name + targetName:params.target_name + requestAudio:params.request_audio]); [controller_ showWindow:nil]; }
diff --git a/chrome/browser/ui/extensions/hosted_app_browsertest.cc b/chrome/browser/ui/extensions/hosted_app_browsertest.cc index b51d71d..793c8cf 100644 --- a/chrome/browser/ui/extensions/hosted_app_browsertest.cc +++ b/chrome/browser/ui/extensions/hosted_app_browsertest.cc
@@ -1002,7 +1002,13 @@ // Tests that hosted app URLs loaded in iframes of non-app pages won't cause an // OOPIF unless there is another reason to create it, but popups from outside // the app will swap into the app. -IN_PROC_BROWSER_TEST_P(HostedAppProcessModelTest, FromOutsideHostedApp) { +// TODO(crbug.com/807471): Flaky on Windows 7. +#if defined(OS_WIN) +#define MAYBE_FromOutsideHostedApp DISABLED_FromOutsideHostedApp +#else +#define MAYBE_FromOutsideHostedApp FromOutsideHostedApp +#endif +IN_PROC_BROWSER_TEST_P(HostedAppProcessModelTest, MAYBE_FromOutsideHostedApp) { // Set up and launch the hosted app. GURL app_url = embedded_test_server()->GetURL("app.site.com", "/frame_tree/simple.htm");
diff --git a/chrome/browser/ui/page_info/page_info.cc b/chrome/browser/ui/page_info/page_info.cc index d39a79f4..27f2cfa 100644 --- a/chrome/browser/ui/page_info/page_info.cc +++ b/chrome/browser/ui/page_info/page_info.cc
@@ -181,9 +181,13 @@ if (info.type == CONTENT_SETTINGS_TYPE_GEOLOCATION) return true; #else - // Flash will always be shown. See https://crbug.com/791142. - if (info.type == CONTENT_SETTINGS_TYPE_PLUGINS) + // Flash is shown if the user has ever changed its setting for |site_url|. + if (info.type == CONTENT_SETTINGS_TYPE_PLUGINS && + content_settings->GetWebsiteSetting(site_url, site_url, + CONTENT_SETTINGS_TYPE_PLUGINS_DATA, + std::string(), nullptr) != nullptr) { return true; + } #endif #if !defined(OS_ANDROID)
diff --git a/chrome/browser/ui/page_info/page_info_unittest.cc b/chrome/browser/ui/page_info/page_info_unittest.cc index c943ef6..b2029ef 100644 --- a/chrome/browser/ui/page_info/page_info_unittest.cc +++ b/chrome/browser/ui/page_info/page_info_unittest.cc
@@ -221,18 +221,9 @@ // check for DSE settings (so expect 1 item), but isn't actually shown later // on because this test isn't testing with a default search engine origin. expected_visible_permissions.insert(CONTENT_SETTINGS_TYPE_GEOLOCATION); - EXPECT_EQ(expected_visible_permissions.size(), - last_permission_info_list().size()); - EXPECT_EQ(CONTENT_SETTINGS_TYPE_GEOLOCATION, - last_permission_info_list().back().type); -#else - expected_visible_permissions.insert(CONTENT_SETTINGS_TYPE_PLUGINS); - // Flash is always visible on desktop - see https://crbug.com/791142. - EXPECT_EQ(expected_visible_permissions.size(), - last_permission_info_list().size()); - EXPECT_EQ(CONTENT_SETTINGS_TYPE_PLUGINS, - last_permission_info_list().back().type); #endif + EXPECT_EQ(expected_visible_permissions.size(), + last_permission_info_list().size()); // Change some default-ask settings away from the default. page_info()->OnSitePermissionChanged(CONTENT_SETTINGS_TYPE_GEOLOCATION,
diff --git a/chrome/browser/ui/passwords/manage_passwords_ui_controller.cc b/chrome/browser/ui/passwords/manage_passwords_ui_controller.cc index d5f308d..e287abb 100644 --- a/chrome/browser/ui/passwords/manage_passwords_ui_controller.cc +++ b/chrome/browser/ui/passwords/manage_passwords_ui_controller.cc
@@ -145,6 +145,7 @@ save_fallback_timer_.Stop(); + ClearPopUpFlagForBubble(); if (passwords_data_.GetCurrentForms().empty()) passwords_data_.OnInactive(); else @@ -218,6 +219,7 @@ // for the user that the current state. if (passwords_data_.state() == password_manager::ui::INACTIVE_STATE || passwords_data_.state() == password_manager::ui::MANAGE_STATE) { + ClearPopUpFlagForBubble(); passwords_data_.OnPasswordAutofilled(password_form_map, origin, federated_matches); // Don't close the existing bubble. Update the icon later. @@ -232,8 +234,10 @@ const password_manager::PasswordStoreChangeList& changes) { password_manager::ui::State current_state = GetState(); passwords_data_.ProcessLoginsChanged(changes); - if (current_state != GetState()) + if (current_state != GetState()) { + ClearPopUpFlagForBubble(); UpdateBubbleAndIconVisibility(); + } } void ManagePasswordsUIController::UpdateIconAndBubbleState( @@ -247,8 +251,7 @@ icon->SetState(GetState()); ShowBubbleWithoutUserInteraction(); // If the bubble appeared then the status is updated in OnBubbleShown(). - if (ShouldBubblePopUp()) - bubble_status_ = NOT_SHOWN; + ClearPopUpFlagForBubble(); } else { password_manager::ui::State state = GetState(); // The dialog should hide the icon. @@ -439,6 +442,7 @@ save_fallback_timer_.Stop(); UpdatePasswordInternal(password_form); + ClearPopUpFlagForBubble(); passwords_data_.TransitionToState(password_manager::ui::MANAGE_STATE); UpdateBubbleAndIconVisibility(); } @@ -454,6 +458,7 @@ autofill::PasswordForm copy_form = form; dialog_controller_.reset(); passwords_data_.ChooseCredential(©_form); + ClearPopUpFlagForBubble(); passwords_data_.TransitionToState(password_manager::ui::MANAGE_STATE); UpdateBubbleAndIconVisibility(); } @@ -491,6 +496,7 @@ void ManagePasswordsUIController::OnDialogHidden() { dialog_controller_.reset(); if (GetState() == password_manager::ui::CREDENTIAL_REQUEST_STATE) { + ClearPopUpFlagForBubble(); passwords_data_.TransitionToState(password_manager::ui::MANAGE_STATE); UpdateBubbleAndIconVisibility(); } @@ -545,12 +551,14 @@ // display either the bubble or the icon. if (!ChromePasswordManagerClient::CanShowBubbleOnURL( web_contents()->GetLastCommittedURL())) { + ClearPopUpFlagForBubble(); passwords_data_.OnInactive(); } Browser* browser = chrome::FindBrowserWithWebContents(web_contents()); if (!browser) return; + LocationBar* location_bar = browser->window()->GetLocationBar(); DCHECK(location_bar); location_bar->UpdateManagePasswordsIconAndBubble(); @@ -588,6 +596,7 @@ // Otherwise, reset the password manager. DestroyAccountChooser(); + ClearPopUpFlagForBubble(); passwords_data_.OnInactive(); UpdateBubbleAndIconVisibility(); } @@ -605,12 +614,18 @@ void ManagePasswordsUIController::ShowBubbleWithoutUserInteraction() { DCHECK(ShouldBubblePopUp()); Browser* browser = chrome::FindBrowserWithWebContents(web_contents()); - if (!browser || browser->toolbar_model()->input_in_progress()) + // Can be zero in the tests. + if (!browser) return; chrome::ExecuteCommand(browser, IDC_MANAGE_PASSWORDS_FOR_PAGE); } +void ManagePasswordsUIController::ClearPopUpFlagForBubble() { + if (ShouldBubblePopUp()) + bubble_status_ = NOT_SHOWN; +} + void ManagePasswordsUIController::DestroyAccountChooser() { if (dialog_controller_ && dialog_controller_->IsShowingAccountChooser()) { dialog_controller_.reset();
diff --git a/chrome/browser/ui/passwords/manage_passwords_ui_controller.h b/chrome/browser/ui/passwords/manage_passwords_ui_controller.h index e15b41bc..6b5161e 100644 --- a/chrome/browser/ui/passwords/manage_passwords_ui_controller.h +++ b/chrome/browser/ui/passwords/manage_passwords_ui_controller.h
@@ -132,6 +132,13 @@ bool AuthenticateUser() override; bool ArePasswordsRevealedWhenBubbleIsOpened() const override; +#if defined(UNIT_TEST) + // Overwrites the client for |passwords_data_|. + void set_client(password_manager::PasswordManagerClient* client) { + passwords_data_.set_client(client); + } +#endif // defined(UNIT_TEST) + protected: explicit ManagePasswordsUIController( content::WebContents* web_contents); @@ -165,11 +172,6 @@ bubble_status_ == SHOULD_POP_UP_AFTER_REAUTH; } - // Overwrites the client for |passwords_data_|. - void set_client(password_manager::PasswordManagerClient* client) { - passwords_data_.set_client(client); - } - // content::WebContentsObserver: void DidFinishNavigation( content::NavigationHandle* navigation_handle) override; @@ -196,6 +198,10 @@ // Shows the password bubble without user interaction. void ShowBubbleWithoutUserInteraction(); + // Resets |bubble_status_| signalling that if the bubble was due to pop up, + // it shouldn't anymore. + void ClearPopUpFlagForBubble(); + // Closes the account chooser gracefully so the callback is called. Then sets // the state to MANAGE_STATE. void DestroyAccountChooser();
diff --git a/chrome/browser/ui/passwords/manage_passwords_ui_controller_unittest.cc b/chrome/browser/ui/passwords/manage_passwords_ui_controller_unittest.cc index 7c56432c..3dfb11b2 100644 --- a/chrome/browser/ui/passwords/manage_passwords_ui_controller_unittest.cc +++ b/chrome/browser/ui/passwords/manage_passwords_ui_controller_unittest.cc
@@ -181,6 +181,7 @@ void SetUp() override; + password_manager::StubPasswordManagerClient& client() { return client_; } password_manager::FakeFormFetcher& fetcher() { return fetcher_; } autofill::PasswordForm& test_local_form() { return test_local_form_; } autofill::PasswordForm& test_federated_form() { return test_federated_form_; } @@ -429,6 +430,33 @@ variations::testing::ClearAllVariationParams(); } +TEST_F(ManagePasswordsUIControllerTest, PasswordSubmittedBubbleCancelled) { + // Test on the real controller. + std::unique_ptr<content::WebContents> web_content(CreateTestWebContents()); + content::WebContentsTester::For(web_content.get()) + ->NavigateAndCommit(GURL("http://example.com")); + ManagePasswordsUIController::CreateForWebContents(web_content.get()); + ManagePasswordsUIController* controller = + ManagePasswordsUIController::FromWebContents(web_content.get()); + controller->set_client(&client()); + + std::unique_ptr<password_manager::PasswordFormManager> test_form_manager( + CreateFormManager()); + test_form_manager->ProvisionallySave( + test_local_form(), + password_manager::PasswordFormManager::IGNORE_OTHER_POSSIBLE_USERNAMES); + // The bubble is ready to open but the tab is inactive. Therefore, we don't + // call UpdateIconAndBubbleState here. + controller->OnPasswordSubmitted(std::move(test_form_manager)); + EXPECT_TRUE(controller->IsAutomaticallyOpeningBubble()); + + // The tab navigated in background. Because the controller's state has changed + // the bubble shouldn't pop up anymore. + content::WebContentsTester::For(web_content.get()) + ->NavigateAndCommit(GURL("http://google.com")); + EXPECT_FALSE(controller->IsAutomaticallyOpeningBubble()); +} + TEST_F(ManagePasswordsUIControllerTest, PasswordSaved) { std::unique_ptr<password_manager::PasswordFormManager> test_form_manager( CreateFormManager());
diff --git a/chrome/browser/ui/tab_helpers.cc b/chrome/browser/ui/tab_helpers.cc index dba09fd..c9c8c2a3 100644 --- a/chrome/browser/ui/tab_helpers.cc +++ b/chrome/browser/ui/tab_helpers.cc
@@ -94,7 +94,6 @@ #include "chrome/browser/android/data_usage/data_use_tab_helper.h" #include "chrome/browser/android/oom_intervention/oom_intervention_tab_helper.h" #include "chrome/browser/android/search_permissions/search_geolocation_disclosure_tab_helper.h" -#include "chrome/browser/android/voice_search_tab_helper.h" #include "chrome/browser/android/webapps/single_tab_mode_tab_helper.h" #include "chrome/browser/banners/app_banner_manager_android.h" #include "chrome/browser/ui/android/context_menu_helper.h" @@ -277,7 +276,6 @@ SearchGeolocationDisclosureTabHelper::CreateForWebContents(web_contents); SingleTabModeTabHelper::CreateForWebContents(web_contents); ViewAndroidHelper::CreateForWebContents(web_contents); - VoiceSearchTabHelper::CreateForWebContents(web_contents); #else BookmarkTabHelper::CreateForWebContents(web_contents); extensions::ChromeExtensionWebContentsObserver::CreateForWebContents(
diff --git a/chrome/browser/ui/views/apps/chrome_native_app_window_views_aura_ash.cc b/chrome/browser/ui/views/apps/chrome_native_app_window_views_aura_ash.cc index 55b4a15..5d5cab80 100644 --- a/chrome/browser/ui/views/apps/chrome_native_app_window_views_aura_ash.cc +++ b/chrome/browser/ui/views/apps/chrome_native_app_window_views_aura_ash.cc
@@ -340,7 +340,7 @@ // Enter immersive mode if the app is opened in tablet mode with the hide // titlebars feature enabled. - if (CanAutohideTitlebarsInTabletMode()) { + if (ShouldUseImmersiveMode()) { immersive_fullscreen_controller_->SetEnabled( ash::ImmersiveFullscreenController::WINDOW_TYPE_PACKAGED_APP, true); } @@ -361,7 +361,7 @@ if (immersive_fullscreen_controller_.get()) { // Immersive mode should not change if we set fullscreen on a maximizable // app in tablet mode when the hide titlebars feature is enabled. - bool autohide_titlebars_enabled = CanAutohideTitlebarsInTabletMode(); + bool autohide_titlebars_enabled = ShouldUseImmersiveMode(); if (!autohide_titlebars_enabled) { // |immersive_fullscreen_controller_| should only be set if immersive @@ -438,15 +438,14 @@ return; if (enabled) { - // Enter immersive mode if the widget can maximize and the hide titlebars - // in tablet mode feature is enabled. - if (CanAutohideTitlebarsInTabletMode()) { + if (ShouldUseImmersiveMode()) { immersive_fullscreen_controller_->SetEnabled( ash::ImmersiveFullscreenController::WINDOW_TYPE_PACKAGED_APP, true); } } else { - // Exit immersive mode if the widget is not in fullscreen and can maximize. - if (!widget()->IsFullscreen() && CanMaximize()) { + // Apps which are resizeable have immersive mode enabled upon entry or + // creation in tablet mode. Disable immersive mode upon exiting tablet mode. + if (!widget()->IsFullscreen()) { immersive_fullscreen_controller_->SetEnabled( ash::ImmersiveFullscreenController::WINDOW_TYPE_PACKAGED_APP, false); } @@ -572,14 +571,38 @@ return true; } +void ChromeNativeAppWindowViewsAuraAsh::OnWidgetActivationChanged( + views::Widget* widget, + bool active) { + ChromeNativeAppWindowViewsAura::OnWidgetActivationChanged(widget, active); + // In splitview, minimized windows go back into the overview grid. If we + // minimize by using the minimize button on the immersive header, the + // overview window will calculate the title bar offset and the window will be + // missing its top portion. Prevent this by disabling immersive mode upon + // minimize. + // TODO(crbug.com/801619): This adds a little extra animation when minimizing + // or unminimizing window. + if (immersive_fullscreen_controller_) { + immersive_fullscreen_controller_->SetEnabled( + ash::ImmersiveFullscreenController::WINDOW_TYPE_PACKAGED_APP, + ShouldUseImmersiveMode()); + } +} + void ChromeNativeAppWindowViewsAuraAsh::OnMenuClosed() { menu_runner_.reset(); menu_model_.reset(); } -bool ChromeNativeAppWindowViewsAuraAsh::CanAutohideTitlebarsInTabletMode() - const { +bool ChromeNativeAppWindowViewsAuraAsh::ShouldUseImmersiveMode() const { TabletModeClient* client = TabletModeClient::Get(); - return CanMaximize() && client && client->tablet_mode_enabled() && - client->auto_hide_title_bars(); + // Windows in tablet mode which are resizable have their title bars hidden in + // ash for more size, so enable immersive mode so users have access to + // window controls. Non resizable windows do not gain size by hidding the + // title bar, so it is not hidden and thus there is no need for immersive + // mode. + // TODO(sammiequon): Investigate whether we should check resizability using + // WindowState instead of CanResize. + return client && client->tablet_mode_enabled() && + client->auto_hide_title_bars() && CanResize() && !IsMinimized(); }
diff --git a/chrome/browser/ui/views/apps/chrome_native_app_window_views_aura_ash.h b/chrome/browser/ui/views/apps/chrome_native_app_window_views_aura_ash.h index 18af222c..9eb54e9f 100644 --- a/chrome/browser/ui/views/apps/chrome_native_app_window_views_aura_ash.h +++ b/chrome/browser/ui/views/apps/chrome_native_app_window_views_aura_ash.h
@@ -113,6 +113,9 @@ void DestroyAnyExclusiveAccessBubble() override; bool CanTriggerOnMouse() const override; + // WidgetObserver: + void OnWidgetActivationChanged(views::Widget* widget, bool active) override; + private: FRIEND_TEST_ALL_PREFIXES(ChromeNativeAppWindowViewsAuraAshBrowserTest, ImmersiveWorkFlow); @@ -133,8 +136,8 @@ void OnMenuClosed(); // Helper function which returns true if in tablet mode, the auto hide - // titlebars feature is turned on, and the widget is maximizable. - bool CanAutohideTitlebarsInTabletMode() const; + // titlebars feature is turned on, and the widget is resizable. + bool ShouldUseImmersiveMode() const; // Used to put non-frameless windows into immersive fullscreen on ChromeOS. In // immersive fullscreen, the window header (title bar and window controls)
diff --git a/chrome/browser/ui/views/apps/chrome_native_app_window_views_aura_ash_browsertest.cc b/chrome/browser/ui/views/apps/chrome_native_app_window_views_aura_ash_browsertest.cc index 9358fb9c..5cc0611 100644 --- a/chrome/browser/ui/views/apps/chrome_native_app_window_views_aura_ash_browsertest.cc +++ b/chrome/browser/ui/views/apps/chrome_native_app_window_views_aura_ash_browsertest.cc
@@ -60,6 +60,21 @@ tablet_mode_controller->EnableTabletModeWindowManager(false); tablet_mode_controller->FlushForTesting(); EXPECT_TRUE(window->immersive_fullscreen_controller_->IsEnabled()); + window->SetFullscreen(extensions::AppWindow::FULLSCREEN_TYPE_NONE); + + // Verify that minimized windows do not have immersive mode enabled. + window->Minimize(); + EXPECT_FALSE(window->immersive_fullscreen_controller_->IsEnabled()); + tablet_mode_controller->EnableTabletModeWindowManager(true); + tablet_mode_controller->FlushForTesting(); + EXPECT_FALSE(window->immersive_fullscreen_controller_->IsEnabled()); + window->Show(); + EXPECT_TRUE(window->immersive_fullscreen_controller_->IsEnabled()); + window->Minimize(); + EXPECT_FALSE(window->immersive_fullscreen_controller_->IsEnabled()); + tablet_mode_controller->EnableTabletModeWindowManager(false); + tablet_mode_controller->FlushForTesting(); + EXPECT_FALSE(window->immersive_fullscreen_controller_->IsEnabled()); CloseAppWindow(app_window); }
diff --git a/chrome/browser/ui/views/desktop_capture/desktop_media_picker_views.cc b/chrome/browser/ui/views/desktop_capture/desktop_media_picker_views.cc index 766418b9..b30ebb23 100644 --- a/chrome/browser/ui/views/desktop_capture/desktop_media_picker_views.cc +++ b/chrome/browser/ui/views/desktop_capture/desktop_media_picker_views.cc
@@ -51,14 +51,11 @@ } // namespace DesktopMediaPickerDialogView::DesktopMediaPickerDialogView( - content::WebContents* parent_web_contents, - gfx::NativeWindow context, + const DesktopMediaPicker::Params& params, DesktopMediaPickerViews* parent, - const base::string16& app_name, - const base::string16& target_name, - std::vector<std::unique_ptr<DesktopMediaList>> source_lists, - bool request_audio) + std::vector<std::unique_ptr<DesktopMediaList>> source_lists) : parent_(parent), + modality_(params.modality), description_label_(new views::Label()), audio_share_checkbox_(nullptr), pane_(new views::TabbedPane()) { @@ -182,19 +179,20 @@ } } - if (app_name == target_name) { - description_label_->SetText( - l10n_util::GetStringFUTF16(IDS_DESKTOP_MEDIA_PICKER_TEXT, app_name)); - } else { + if (params.app_name == params.target_name) { description_label_->SetText(l10n_util::GetStringFUTF16( - IDS_DESKTOP_MEDIA_PICKER_TEXT_DELEGATED, app_name, target_name)); + IDS_DESKTOP_MEDIA_PICKER_TEXT, params.app_name)); + } else { + description_label_->SetText( + l10n_util::GetStringFUTF16(IDS_DESKTOP_MEDIA_PICKER_TEXT_DELEGATED, + params.app_name, params.target_name)); } DCHECK(!source_types_.empty()); pane_->SetFocusBehavior(views::View::FocusBehavior::NEVER); AddChildView(pane_); - if (request_audio) { + if (params.request_audio) { audio_share_checkbox_ = new views::Checkbox( l10n_util::GetStringUTF16(IDS_DESKTOP_MEDIA_PICKER_AUDIO_SHARE)); audio_share_checkbox_->SetChecked(true); @@ -203,18 +201,18 @@ // Focus on the first non-null media_list. OnSourceTypeSwitched(0); - // If |parent_web_contents| is set and it's not a background page then the + // If |params.web_contents| is set and it's not a background page then the // picker will be shown modal to the web contents. Otherwise the picker is // shown in a separate window. views::Widget* widget = nullptr; bool modal_dialog = - parent_web_contents && - !parent_web_contents->GetDelegate()->IsNeverVisible(parent_web_contents); + params.web_contents && + !params.web_contents->GetDelegate()->IsNeverVisible(params.web_contents); if (modal_dialog) { widget = - constrained_window::ShowWebModalDialogViews(this, parent_web_contents); + constrained_window::ShowWebModalDialogViews(this, params.web_contents); } else { - widget = DialogDelegate::CreateDialogWidget(this, context, nullptr); + widget = DialogDelegate::CreateDialogWidget(this, params.context, nullptr); widget->Show(); } chrome::RecordDialogCreation(chrome::DialogIdentifier::DESKTOP_MEDIA_PICKER); @@ -281,7 +279,7 @@ } ui::ModalType DesktopMediaPickerDialogView::GetModalType() const { - return ui::MODAL_TYPE_CHILD; + return modality_; } base::string16 DesktopMediaPickerDialogView::GetWindowTitle() const { @@ -426,18 +424,12 @@ } void DesktopMediaPickerViews::Show( - content::WebContents* web_contents, - gfx::NativeWindow context, - gfx::NativeWindow parent, - const base::string16& app_name, - const base::string16& target_name, + const DesktopMediaPicker::Params& params, std::vector<std::unique_ptr<DesktopMediaList>> source_lists, - bool request_audio, const DoneCallback& done_callback) { callback_ = done_callback; - dialog_ = new DesktopMediaPickerDialogView( - web_contents, context, this, app_name, target_name, - std::move(source_lists), request_audio); + dialog_ = + new DesktopMediaPickerDialogView(params, this, std::move(source_lists)); } void DesktopMediaPickerViews::NotifyDialogResult(DesktopMediaID source) {
diff --git a/chrome/browser/ui/views/desktop_capture/desktop_media_picker_views.h b/chrome/browser/ui/views/desktop_capture/desktop_media_picker_views.h index 6e82b45..78e87ca 100644 --- a/chrome/browser/ui/views/desktop_capture/desktop_media_picker_views.h +++ b/chrome/browser/ui/views/desktop_capture/desktop_media_picker_views.h
@@ -25,13 +25,9 @@ public views::TabbedPaneListener { public: DesktopMediaPickerDialogView( - content::WebContents* parent_web_contents, - gfx::NativeWindow context, + const DesktopMediaPicker::Params& params, DesktopMediaPickerViews* parent, - const base::string16& app_name, - const base::string16& target_name, - std::vector<std::unique_ptr<DesktopMediaList>> source_lists, - bool request_audio); + std::vector<std::unique_ptr<DesktopMediaList>> source_lists); ~DesktopMediaPickerDialogView() override; // Called by parent (DesktopMediaPickerViews) when it's destroyed. @@ -71,6 +67,7 @@ void OnSourceTypeSwitched(int index); DesktopMediaPickerViews* parent_; + ui::ModalType modality_; views::Label* description_label_; @@ -92,13 +89,8 @@ void NotifyDialogResult(content::DesktopMediaID source); // DesktopMediaPicker overrides. - void Show(content::WebContents* web_contents, - gfx::NativeWindow context, - gfx::NativeWindow parent, - const base::string16& app_name, - const base::string16& target_name, + void Show(const DesktopMediaPicker::Params& params, std::vector<std::unique_ptr<DesktopMediaList>> source_lists, - bool request_audio, const DoneCallback& done_callback) override; DesktopMediaPickerDialogView* GetDialogViewForTesting() const {
diff --git a/chrome/browser/ui/views/desktop_capture/desktop_media_picker_views_browsertest.cc b/chrome/browser/ui/views/desktop_capture/desktop_media_picker_views_browsertest.cc index f15561b..445f2ae 100644 --- a/chrome/browser/ui/views/desktop_capture/desktop_media_picker_views_browsertest.cc +++ b/chrome/browser/ui/views/desktop_capture/desktop_media_picker_views_browsertest.cc
@@ -33,10 +33,14 @@ source_lists.push_back(std::make_unique<FakeDesktopMediaList>(type)); } - picker_->Show(web_contents, native_window, nullptr, - base::ASCIIToUTF16("app_name"), - base::ASCIIToUTF16("target_name"), std::move(source_lists), - true, DesktopMediaPicker::DoneCallback()); + DesktopMediaPicker::Params picker_params; + picker_params.web_contents = web_contents; + picker_params.context = native_window; + picker_params.app_name = base::ASCIIToUTF16("app_name"); + picker_params.target_name = base::ASCIIToUTF16("target_name"); + picker_params.request_audio = true; + picker_->Show(picker_params, std::move(source_lists), + DesktopMediaPicker::DoneCallback()); } private:
diff --git a/chrome/browser/ui/views/desktop_capture/desktop_media_picker_views_unittest.cc b/chrome/browser/ui/views/desktop_capture/desktop_media_picker_views_unittest.cc index a152700..2279002 100644 --- a/chrome/browser/ui/views/desktop_capture/desktop_media_picker_views_unittest.cc +++ b/chrome/browser/ui/views/desktop_capture/desktop_media_picker_views_unittest.cc
@@ -55,8 +55,12 @@ base::string16 app_name = base::ASCIIToUTF16("foo"); picker_views_.reset(new DesktopMediaPickerViews()); - picker_views_->Show(nullptr, test_helper_.GetContext(), nullptr, app_name, - app_name, std::move(source_lists), true, + DesktopMediaPicker::Params picker_params; + picker_params.context = test_helper_.GetContext(); + picker_params.app_name = app_name; + picker_params.target_name = app_name; + picker_params.request_audio = true; + picker_views_->Show(picker_params, std::move(source_lists), base::Bind(&DesktopMediaPickerViewsTest::OnPickerDone, base::Unretained(this))); }
diff --git a/chrome/browser/ui/views/download/download_danger_prompt_views.cc b/chrome/browser/ui/views/download/download_danger_prompt_views.cc index 23b28c7..e42f922 100644 --- a/chrome/browser/ui/views/download/download_danger_prompt_views.cc +++ b/chrome/browser/ui/views/download/download_danger_prompt_views.cc
@@ -12,10 +12,10 @@ #include "chrome/grit/chromium_strings.h" #include "chrome/grit/generated_resources.h" #include "components/constrained_window/constrained_window_views.h" +#include "components/download/public/common/download_danger_type.h" #include "components/strings/grit/components_strings.h" #include "content/public/browser/browser_context.h" #include "content/public/browser/browser_thread.h" -#include "content/public/browser/download_danger_type.h" #include "content/public/browser/download_item.h" #include "ui/base/l10n/l10n_util.h" #include "ui/base/resource/resource_bundle.h" @@ -172,12 +172,12 @@ if (show_context_) return l10n_util::GetStringUTF16(IDS_CONFIRM_KEEP_DANGEROUS_DOWNLOAD_TITLE); switch (download_->GetDangerType()) { - case content::DOWNLOAD_DANGER_TYPE_DANGEROUS_URL: - case content::DOWNLOAD_DANGER_TYPE_DANGEROUS_CONTENT: - case content::DOWNLOAD_DANGER_TYPE_DANGEROUS_HOST: - case content::DOWNLOAD_DANGER_TYPE_POTENTIALLY_UNWANTED: + case download::DOWNLOAD_DANGER_TYPE_DANGEROUS_URL: + case download::DOWNLOAD_DANGER_TYPE_DANGEROUS_CONTENT: + case download::DOWNLOAD_DANGER_TYPE_DANGEROUS_HOST: + case download::DOWNLOAD_DANGER_TYPE_POTENTIALLY_UNWANTED: return l10n_util::GetStringUTF16(IDS_KEEP_DANGEROUS_DOWNLOAD_TITLE); - case content::DOWNLOAD_DANGER_TYPE_UNCOMMON_CONTENT: + case download::DOWNLOAD_DANGER_TYPE_UNCOMMON_CONTENT: return l10n_util::GetStringUTF16(IDS_KEEP_UNCOMMON_DOWNLOAD_TITLE); default: { return l10n_util::GetStringUTF16( @@ -259,42 +259,42 @@ base::string16 DownloadDangerPromptViews::GetMessageBody() const { if (show_context_) { switch (download_->GetDangerType()) { - case content::DOWNLOAD_DANGER_TYPE_DANGEROUS_FILE: { + case download::DOWNLOAD_DANGER_TYPE_DANGEROUS_FILE: { return l10n_util::GetStringFUTF16( IDS_PROMPT_DANGEROUS_DOWNLOAD, download_->GetFileNameToReportUser().LossyDisplayName()); } - case content::DOWNLOAD_DANGER_TYPE_DANGEROUS_URL: // Fall through - case content::DOWNLOAD_DANGER_TYPE_DANGEROUS_CONTENT: - case content::DOWNLOAD_DANGER_TYPE_DANGEROUS_HOST: { + case download::DOWNLOAD_DANGER_TYPE_DANGEROUS_URL: // Fall through + case download::DOWNLOAD_DANGER_TYPE_DANGEROUS_CONTENT: + case download::DOWNLOAD_DANGER_TYPE_DANGEROUS_HOST: { return l10n_util::GetStringFUTF16( IDS_PROMPT_MALICIOUS_DOWNLOAD_CONTENT, download_->GetFileNameToReportUser().LossyDisplayName()); } - case content::DOWNLOAD_DANGER_TYPE_UNCOMMON_CONTENT: { + case download::DOWNLOAD_DANGER_TYPE_UNCOMMON_CONTENT: { return l10n_util::GetStringFUTF16( IDS_PROMPT_UNCOMMON_DOWNLOAD_CONTENT, download_->GetFileNameToReportUser().LossyDisplayName()); } - case content::DOWNLOAD_DANGER_TYPE_POTENTIALLY_UNWANTED: { + case download::DOWNLOAD_DANGER_TYPE_POTENTIALLY_UNWANTED: { return l10n_util::GetStringFUTF16( IDS_PROMPT_DOWNLOAD_CHANGES_SETTINGS, download_->GetFileNameToReportUser().LossyDisplayName()); } - case content::DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS: - case content::DOWNLOAD_DANGER_TYPE_MAYBE_DANGEROUS_CONTENT: - case content::DOWNLOAD_DANGER_TYPE_USER_VALIDATED: - case content::DOWNLOAD_DANGER_TYPE_MAX: { + case download::DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS: + case download::DOWNLOAD_DANGER_TYPE_MAYBE_DANGEROUS_CONTENT: + case download::DOWNLOAD_DANGER_TYPE_USER_VALIDATED: + case download::DOWNLOAD_DANGER_TYPE_MAX: { break; } } } else { switch (download_->GetDangerType()) { - case content::DOWNLOAD_DANGER_TYPE_DANGEROUS_URL: - case content::DOWNLOAD_DANGER_TYPE_DANGEROUS_CONTENT: - case content::DOWNLOAD_DANGER_TYPE_DANGEROUS_HOST: - case content::DOWNLOAD_DANGER_TYPE_POTENTIALLY_UNWANTED: - case content::DOWNLOAD_DANGER_TYPE_UNCOMMON_CONTENT: { + case download::DOWNLOAD_DANGER_TYPE_DANGEROUS_URL: + case download::DOWNLOAD_DANGER_TYPE_DANGEROUS_CONTENT: + case download::DOWNLOAD_DANGER_TYPE_DANGEROUS_HOST: + case download::DOWNLOAD_DANGER_TYPE_POTENTIALLY_UNWANTED: + case download::DOWNLOAD_DANGER_TYPE_UNCOMMON_CONTENT: { return l10n_util::GetStringUTF16( IDS_PROMPT_CONFIRM_KEEP_MALICIOUS_DOWNLOAD_BODY); }
diff --git a/chrome/browser/ui/views/download/download_item_view.cc b/chrome/browser/ui/views/download/download_item_view.cc index f12fe378..0ab0912 100644 --- a/chrome/browser/ui/views/download/download_item_view.cc +++ b/chrome/browser/ui/views/download/download_item_view.cc
@@ -39,10 +39,10 @@ #include "chrome/browser/ui/views/frame/browser_view.h" #include "chrome/common/pref_names.h" #include "chrome/grit/generated_resources.h" +#include "components/download/public/common/download_danger_type.h" #include "components/prefs/pref_service.h" #include "components/safe_browsing/common/safe_browsing_prefs.h" #include "components/vector_icons/vector_icons.h" -#include "content/public/browser/download_danger_type.h" #include "third_party/icu/source/common/unicode/uchar.h" #include "ui/accessibility/ax_node_data.h" #include "ui/base/l10n/l10n_util.h" @@ -928,7 +928,7 @@ void DownloadItemView::ClearWarningDialog() { DCHECK(download()->GetDangerType() == - content::DOWNLOAD_DANGER_TYPE_USER_VALIDATED); + download::DOWNLOAD_DANGER_TYPE_USER_VALIDATED); DCHECK(IsShowingWarningDialog()); SetMode(NORMAL_MODE); @@ -957,7 +957,7 @@ void DownloadItemView::ShowWarningDialog() { DCHECK(!IsShowingWarningDialog()); time_download_warning_shown_ = base::Time::Now(); - content::DownloadDangerType danger_type = download()->GetDangerType(); + download::DownloadDangerType danger_type = download()->GetDangerType(); RecordDangerousDownloadWarningShown(danger_type); #if defined(FULL_SAFE_BROWSING) if (model_.ShouldAllowDownloadFeedback()) { @@ -1000,19 +1000,19 @@ gfx::ImageSkia DownloadItemView::GetWarningIcon() { switch (download()->GetDangerType()) { - case content::DOWNLOAD_DANGER_TYPE_DANGEROUS_URL: - case content::DOWNLOAD_DANGER_TYPE_DANGEROUS_CONTENT: - case content::DOWNLOAD_DANGER_TYPE_UNCOMMON_CONTENT: - case content::DOWNLOAD_DANGER_TYPE_DANGEROUS_HOST: - case content::DOWNLOAD_DANGER_TYPE_POTENTIALLY_UNWANTED: - case content::DOWNLOAD_DANGER_TYPE_DANGEROUS_FILE: + case download::DOWNLOAD_DANGER_TYPE_DANGEROUS_URL: + case download::DOWNLOAD_DANGER_TYPE_DANGEROUS_CONTENT: + case download::DOWNLOAD_DANGER_TYPE_UNCOMMON_CONTENT: + case download::DOWNLOAD_DANGER_TYPE_DANGEROUS_HOST: + case download::DOWNLOAD_DANGER_TYPE_POTENTIALLY_UNWANTED: + case download::DOWNLOAD_DANGER_TYPE_DANGEROUS_FILE: return gfx::CreateVectorIcon(vector_icons::kWarningIcon, kWarningIconSize, gfx::kGoogleRed700); - case content::DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS: - case content::DOWNLOAD_DANGER_TYPE_MAYBE_DANGEROUS_CONTENT: - case content::DOWNLOAD_DANGER_TYPE_USER_VALIDATED: - case content::DOWNLOAD_DANGER_TYPE_MAX: + case download::DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS: + case download::DOWNLOAD_DANGER_TYPE_MAYBE_DANGEROUS_CONTENT: + case download::DOWNLOAD_DANGER_TYPE_USER_VALIDATED: + case download::DOWNLOAD_DANGER_TYPE_MAX: NOTREACHED(); break; }
diff --git a/chrome/browser/ui/views/dropdown_bar_host.cc b/chrome/browser/ui/views/dropdown_bar_host.cc index 487b3e58..56918af 100644 --- a/chrome/browser/ui/views/dropdown_bar_host.cc +++ b/chrome/browser/ui/views/dropdown_bar_host.cc
@@ -86,6 +86,12 @@ SetDialogPosition(GetDialogPosition(gfx::Rect())); + // If we're in the middle of a close animation, stop it and skip to the end. + // This ensures that the state is consistent and prepared to show the drop- + // down bar. + if (animation_->IsClosing()) + StopAnimation(); + host_->Show(); bool was_visible = is_visible_;
diff --git a/chrome/browser/ui/views/location_bar/location_bar_view.cc b/chrome/browser/ui/views/location_bar/location_bar_view.cc index 7689bce..29587b5 100644 --- a/chrome/browser/ui/views/location_bar/location_bar_view.cc +++ b/chrome/browser/ui/views/location_bar/location_bar_view.cc
@@ -8,7 +8,6 @@ #include <map> #include <memory> -#include "base/feature_list.h" #include "base/i18n/rtl.h" #include "base/strings/utf_string_conversions.h" #include "build/build_config.h" @@ -57,7 +56,6 @@ #include "chrome/grit/generated_resources.h" #include "components/bookmarks/common/bookmark_pref_names.h" #include "components/favicon/content/content_favicon_driver.h" -#include "components/omnibox/browser/omnibox_field_trial.h" #include "components/omnibox/browser/omnibox_popup_model.h" #include "components/omnibox/browser/omnibox_popup_view.h" #include "components/prefs/pref_service.h" @@ -375,33 +373,6 @@ return location_icon_view()->GetImageView(); } -void LocationBarView::GetOmniboxPopupPositioningInfo( - gfx::Point* top_left_screen_coord, - int* popup_width, - int* left_margin, - int* right_margin, - int top_edge_overlap) { - // The popup contents are always sized matching the location bar size. - const int popup_contents_left = x(); - const int popup_contents_right = bounds().right(); - - // The popup itself may either be the same width as the contents, or as wide - // as the toolbar. - bool narrow_popup = - base::FeatureList::IsEnabled(omnibox::kUIExperimentNarrowDropdown); - const int popup_left = narrow_popup ? popup_contents_left : 0; - const int popup_right = - narrow_popup ? popup_contents_right : parent()->width(); - - *top_left_screen_coord = - gfx::Point(popup_left, parent()->height() - top_edge_overlap); - views::View::ConvertPointToScreen(parent(), top_left_screen_coord); - - *popup_width = popup_right - popup_left; - *left_margin = popup_contents_left - popup_left; - *right_margin = popup_right - popup_contents_right; -} - //////////////////////////////////////////////////////////////////////////////// // LocationBarView, public LocationBar implementation:
diff --git a/chrome/browser/ui/views/location_bar/location_bar_view.h b/chrome/browser/ui/views/location_bar/location_bar_view.h index ceaa68e..2bc40ab 100644 --- a/chrome/browser/ui/views/location_bar/location_bar_view.h +++ b/chrome/browser/ui/views/location_bar/location_bar_view.h
@@ -206,17 +206,6 @@ OmniboxViewViews* omnibox_view() { return omnibox_view_; } const OmniboxViewViews* omnibox_view() const { return omnibox_view_; } - // Returns the position and width that the popup should be, and also the left - // edge that the results should align themselves to (which will leave some - // border on the left of the popup). |top_edge_overlap| specifies the number - // of pixels the top edge of the popup should overlap the bottom edge of - // the toolbar. - void GetOmniboxPopupPositioningInfo(gfx::Point* top_left_screen_coord, - int* popup_width, - int* left_margin, - int* right_margin, - int top_edge_overlap); - // Updates the controller, and, if |contents| is non-null, restores saved // state that the tab holds. void Update(const content::WebContents* contents);
diff --git a/chrome/browser/ui/views/omnibox/omnibox_popup_contents_view.cc b/chrome/browser/ui/views/omnibox/omnibox_popup_contents_view.cc index 5e29e4a..303d1cc4 100644 --- a/chrome/browser/ui/views/omnibox/omnibox_popup_contents_view.cc +++ b/chrome/browser/ui/views/omnibox/omnibox_popup_contents_view.cc
@@ -43,7 +43,7 @@ base::LazyInstance<gfx::ImageSkia>::DestructorAtExit g_bottom_shadow = LAZY_INSTANCE_INITIALIZER; -const int kPopupVerticalPadding = 4; +constexpr int kPopupVerticalPadding = 4; } // namespace @@ -77,7 +77,7 @@ // The contents is owned by the LocationBarView. set_owned_by_client(); - bool narrow_popup = + const bool narrow_popup = base::FeatureList::IsEnabled(omnibox::kUIExperimentNarrowDropdown); if (g_top_shadow.Get().isNull() && !narrow_popup) { @@ -218,26 +218,8 @@ for (size_t i = result_size; i < AutocompleteResult::GetMaxMatches(); ++i) child_at(i)->SetVisible(false); - int top_edge_overlap = 0; - bool narrow_popup = - base::FeatureList::IsEnabled(omnibox::kUIExperimentNarrowDropdown); - if (!narrow_popup) { - // We want the popup to appear to overlay the bottom of the toolbar. So we - // shift the popup to completely cover the client edge, and then draw an - // additional semitransparent shadow above that. - top_edge_overlap = g_top_shadow.Get().height() + - views::NonClientFrameView::kClientEdgeThickness; - } - - gfx::Point top_left_screen_coord; - int width; - location_bar_view_->GetOmniboxPopupPositioningInfo( - &top_left_screen_coord, &width, &start_margin_, - &end_margin_, top_edge_overlap); - gfx::Rect new_target_bounds(top_left_screen_coord, - gfx::Size(width, CalculatePopupHeight())); - - if (narrow_popup) { + gfx::Rect new_target_bounds = UpdateMarginsAndGetTargetBounds(); + if (base::FeatureList::IsEnabled(omnibox::kUIExperimentNarrowDropdown)) { SkColor background_color = GetNativeTheme()->GetSystemColor( ui::NativeTheme::kColorId_ResultsTableNormalBackground); auto border = std::make_unique<views::BubbleBorder>( @@ -399,6 +381,40 @@ //////////////////////////////////////////////////////////////////////////////// // OmniboxPopupContentsView, private: +gfx::Rect OmniboxPopupContentsView::UpdateMarginsAndGetTargetBounds() { + int top_edge_overlap = 0; + // The popup itself may either be the same width as the contents, or as wide + // as the toolbar. + const bool narrow_popup = + base::FeatureList::IsEnabled(omnibox::kUIExperimentNarrowDropdown); + if (!narrow_popup) { + // We want the popup to appear to overlay the bottom of the toolbar. So we + // shift the popup to completely cover the client edge, and then draw an + // additional semitransparent shadow above that. + top_edge_overlap = g_top_shadow.Get().height() + + views::NonClientFrameView::kClientEdgeThickness; + } + + views::View* toolbar = location_bar_view_->parent(); + + // The popup contents are always sized matching the location bar size. + const int popup_contents_left = location_bar_view_->x(); + const int popup_contents_right = location_bar_view_->bounds().right(); + const int popup_left = narrow_popup ? popup_contents_left : 0; + const int popup_right = + narrow_popup ? popup_contents_right : toolbar->width(); + const int width = popup_right - popup_left; + + start_margin_ = popup_contents_left - popup_left; + end_margin_ = popup_right - popup_contents_right; + + gfx::Point top_left_screen_coord = + gfx::Point(popup_left, toolbar->height() - top_edge_overlap); + views::View::ConvertPointToScreen(toolbar, &top_left_screen_coord); + return gfx::Rect(top_left_screen_coord, + gfx::Size(width, CalculatePopupHeight())); +} + int OmniboxPopupContentsView::CalculatePopupHeight() { DCHECK_GE(static_cast<size_t>(child_count()), model_->result().size()); int popup_height = 0;
diff --git a/chrome/browser/ui/views/omnibox/omnibox_popup_contents_view.h b/chrome/browser/ui/views/omnibox/omnibox_popup_contents_view.h index 66ff8b2..6e99092 100644 --- a/chrome/browser/ui/views/omnibox/omnibox_popup_contents_view.h +++ b/chrome/browser/ui/views/omnibox/omnibox_popup_contents_view.h
@@ -77,6 +77,11 @@ private: class AutocompletePopupWidget; + // Updates |start_margin_| and |end_margin_| and returns the target popup + // bounds by querying the bounds of |location_bar_view_| and its parent view + // on screen. + gfx::Rect UpdateMarginsAndGetTargetBounds(); + // Calculates the height needed to show all the results in the model. int CalculatePopupHeight();
diff --git a/chrome/browser/ui/views/page_info/page_info_bubble_view_unittest.cc b/chrome/browser/ui/views/page_info/page_info_bubble_view_unittest.cc index d6ce3bf..289dfa1 100644 --- a/chrome/browser/ui/views/page_info/page_info_bubble_view_unittest.cc +++ b/chrome/browser/ui/views/page_info/page_info_bubble_view_unittest.cc
@@ -7,6 +7,7 @@ #include "base/macros.h" #include "base/strings/utf_string_conversions.h" #include "build/build_config.h" +#include "chrome/browser/content_settings/host_content_settings_map_factory.h" #include "chrome/browser/ui/exclusive_access/exclusive_access_manager.h" #include "chrome/browser/ui/views/harmony/chrome_layout_provider.h" #include "chrome/browser/ui/views/hover_button.h" @@ -15,6 +16,7 @@ #include "chrome/browser/usb/usb_chooser_context.h" #include "chrome/browser/usb/usb_chooser_context_factory.h" #include "chrome/test/base/testing_profile.h" +#include "components/content_settings/core/browser/host_content_settings_map.h" #include "components/strings/grit/components_strings.h" #include "content/public/browser/ssl_status.h" #include "content/public/test/test_browser_thread_bundle.h" @@ -22,6 +24,7 @@ #include "device/base/mock_device_client.h" #include "device/usb/mock_usb_device.h" #include "device/usb/mock_usb_service.h" +#include "ppapi/features/features.h" #include "testing/gtest/include/gtest/gtest.h" #include "ui/base/l10n/l10n_util.h" #include "ui/base/material_design/material_design_controller.h" @@ -34,6 +37,10 @@ #include "ui/views/test/scoped_views_test_helper.h" #include "ui/views/test/test_views_delegate.h" +#if BUILDFLAG(ENABLE_PLUGINS) +#include "chrome/browser/plugins/chrome_plugin_service_filter.h" +#endif + const char* kUrl = "http://www.example.com/index.html"; namespace test { @@ -195,6 +202,40 @@ DISALLOW_COPY_AND_ASSIGN(PageInfoBubbleViewTest); }; +#if BUILDFLAG(ENABLE_PLUGINS) +// Waits until a change is observed in content settings. +class FlashContentSettingsChangeWaiter : public content_settings::Observer { + public: + explicit FlashContentSettingsChangeWaiter(Profile* profile) + : profile_(profile) { + HostContentSettingsMapFactory::GetForProfile(profile)->AddObserver(this); + } + ~FlashContentSettingsChangeWaiter() override { + HostContentSettingsMapFactory::GetForProfile(profile_)->RemoveObserver( + this); + } + + // content_settings::Observer: + void OnContentSettingChanged(const ContentSettingsPattern& primary_pattern, + const ContentSettingsPattern& secondary_pattern, + ContentSettingsType content_type, + std::string resource_identifier) override { + if (content_type == CONTENT_SETTINGS_TYPE_PLUGINS) + Proceed(); + } + + void Wait() { run_loop_.Run(); } + + private: + void Proceed() { run_loop_.Quit(); } + + Profile* profile_; + base::RunLoop run_loop_; + + DISALLOW_COPY_AND_ASSIGN(FlashContentSettingsChangeWaiter); +}; +#endif + } // namespace // Each permission selector row is like this: [icon] [label] [selector] @@ -221,9 +262,8 @@ list.back().is_incognito = false; list.back().setting = CONTENT_SETTING_BLOCK; - // Initially, no permissions are shown because they are all set to default, - // except for Flash. - int num_expected_children = 3; + // Initially, no permissions are shown because they are all set to default. + int num_expected_children = 0; EXPECT_EQ(num_expected_children, api_->permissions_view()->child_count()); num_expected_children += kViewsPerPermissionRow * list.size(); @@ -280,8 +320,7 @@ // Test UI construction and reconstruction with USB devices. TEST_F(PageInfoBubbleViewTest, SetPermissionInfoWithUsbDevice) { - // One permission row is always shown here (Flash). https://crbug.com/791142 - const int kExpectedChildren = kViewsPerPermissionRow; + const int kExpectedChildren = 0; EXPECT_EQ(kExpectedChildren, api_->permissions_view()->child_count()); const GURL origin = GURL(kUrl).GetOrigin(); @@ -349,3 +388,49 @@ size_t index = api_->GetCookiesLinkText().find(expected); EXPECT_NE(std::string::npos, index); } + +#if BUILDFLAG(ENABLE_PLUGINS) +TEST_F(PageInfoBubbleViewTest, ChangingFlashSettingForSiteIsRemembered) { + Profile* profile = web_contents_helper_.profile(); + ChromePluginServiceFilter::GetInstance()->RegisterResourceContext( + profile, profile->GetResourceContext()); + FlashContentSettingsChangeWaiter waiter(profile); + + const GURL url(kUrl); + HostContentSettingsMap* map = + HostContentSettingsMapFactory::GetForProfile(profile); + // Make sure the site being tested doesn't already have this marker set. + EXPECT_EQ(nullptr, + map->GetWebsiteSetting(url, url, CONTENT_SETTINGS_TYPE_PLUGINS_DATA, + std::string(), nullptr)); + EXPECT_EQ(0, api_->permissions_view()->child_count()); + + // Change the Flash setting. + map->SetContentSettingDefaultScope(url, url, CONTENT_SETTINGS_TYPE_PLUGINS, + std::string(), CONTENT_SETTING_ALLOW); + waiter.Wait(); + + // Check that this site has now been marked for displaying Flash always. + EXPECT_NE(nullptr, + map->GetWebsiteSetting(url, url, CONTENT_SETTINGS_TYPE_PLUGINS_DATA, + std::string(), nullptr)); + + // Check the Flash permission is now showing since it's non-default. + api_->CreateView(); + const int kPermissionLabelIndex = 1; + views::Label* label = static_cast<views::Label*>( + api_->permissions_view()->child_at(kPermissionLabelIndex)); + EXPECT_EQ(base::ASCIIToUTF16("Flash"), label->text()); + + // Change the Flash setting back to the default. + map->SetContentSettingDefaultScope(url, url, CONTENT_SETTINGS_TYPE_PLUGINS, + std::string(), CONTENT_SETTING_DEFAULT); + EXPECT_EQ(kViewsPerPermissionRow, api_->permissions_view()->child_count()); + + // Check the Flash permission is still showing since the user changed it + // previously. + label = static_cast<views::Label*>( + api_->permissions_view()->child_at(kPermissionLabelIndex)); + EXPECT_EQ(base::ASCIIToUTF16("Flash"), label->text()); +} +#endif
diff --git a/chrome/browser/ui/views/payments/payment_request_dialog_view.cc b/chrome/browser/ui/views/payments/payment_request_dialog_view.cc index ec08dc59..802b5ac 100644 --- a/chrome/browser/ui/views/payments/payment_request_dialog_view.cc +++ b/chrome/browser/ui/views/payments/payment_request_dialog_view.cc
@@ -389,7 +389,8 @@ throbber_overlay_.SetVisible(false); // The throbber overlay has to have a solid white background to hide whatever // would be under it. - throbber_overlay_.SetBackground(views::CreateSolidBackground(SK_ColorWHITE)); + throbber_overlay_.SetBackground(views::CreateThemedSolidBackground( + &throbber_overlay_, ui::NativeTheme::kColorId_WindowBackground)); views::GridLayout* layout = throbber_overlay_.SetLayoutManager( std::make_unique<views::GridLayout>(&throbber_overlay_));
diff --git a/chrome/browser/ui/views/payments/payment_request_sheet_controller.cc b/chrome/browser/ui/views/payments/payment_request_sheet_controller.cc index 1743080..33a9592b 100644 --- a/chrome/browser/ui/views/payments/payment_request_sheet_controller.cc +++ b/chrome/browser/ui/views/payments/payment_request_sheet_controller.cc
@@ -160,7 +160,8 @@ }; BorderedScrollView() : views::ScrollView() { - SetBackgroundColor(SK_ColorWHITE); + SetBackground(views::CreateThemedSolidBackground( + this, ui::NativeTheme::kColorId_WindowBackground)); SetBorder(views::CreateBorderPainter( std::make_unique<BorderedScrollViewBorderPainter>( GetNativeTheme()->GetSystemColor( @@ -212,7 +213,8 @@ if (GetSheetId(&sheet_id)) view->set_id(static_cast<int>(sheet_id)); - view->SetBackground(views::CreateSolidBackground(SK_ColorWHITE)); + view->SetBackground(views::CreateThemedSolidBackground( + view.get(), ui::NativeTheme::kColorId_WindowBackground)); // Paint the sheets to layers, otherwise the MD buttons (which do paint to a // layer) won't do proper clipping. @@ -250,7 +252,8 @@ content_view_ = new views::View; content_view_->SetPaintToLayer(); content_view_->layer()->SetFillsBoundsOpaquely(true); - content_view_->SetBackground(views::CreateSolidBackground(SK_ColorWHITE)); + content_view_->SetBackground(views::CreateThemedSolidBackground( + content_view_, ui::NativeTheme::kColorId_WindowBackground)); content_view_->set_id(static_cast<int>(DialogViewID::CONTENT_VIEW)); pane_layout->AddView(content_view_); pane_->SizeToPreferredSize();
diff --git a/chrome/browser/ui/views/profiles/profile_chooser_view.cc b/chrome/browser/ui/views/profiles/profile_chooser_view.cc index dbd99c5..3572f954 100644 --- a/chrome/browser/ui/views/profiles/profile_chooser_view.cc +++ b/chrome/browser/ui/views/profiles/profile_chooser_view.cc
@@ -174,7 +174,7 @@ return back_button; } -BadgedProfilePhoto::BadgeType GetProfileBadgeType(const Profile* profile) { +BadgedProfilePhoto::BadgeType GetProfileBadgeType(Profile* profile) { if (!profile->IsSupervised()) { return AccountConsistencyModeManager::IsDiceEnabledForProfile(profile) ? BadgedProfilePhoto::BADGE_TYPE_SYNC_COMPLETE
diff --git a/chrome/browser/ui/webui/chromeos/internet_config_dialog.cc b/chrome/browser/ui/webui/chromeos/internet_config_dialog.cc index 858c2e8..2f559bed 100644 --- a/chrome/browser/ui/webui/chromeos/internet_config_dialog.cc +++ b/chrome/browser/ui/webui/chromeos/internet_config_dialog.cc
@@ -50,12 +50,19 @@ } // namespace // static -void InternetConfigDialog::ShowDialogForNetworkState( - const NetworkState* network_state) { +void InternetConfigDialog::ShowDialogForNetworkId( + const std::string& network_id) { + const NetworkState* network_state = + NetworkHandler::Get()->network_state_handler()->GetNetworkStateFromGuid( + network_id); + if (!network_state) { + LOG(ERROR) << "Network not found: " << network_id; + return; + } std::string network_type = chromeos::network_util::TranslateShillTypeToONC(network_state->type()); InternetConfigDialog* dialog = - new InternetConfigDialog(network_type, network_state->guid()); + new InternetConfigDialog(network_type, network_id); dialog->ShowSystemDialog(); }
diff --git a/chrome/browser/ui/webui/chromeos/internet_config_dialog.h b/chrome/browser/ui/webui/chromeos/internet_config_dialog.h index 8c3d0b8..6b793c5 100644 --- a/chrome/browser/ui/webui/chromeos/internet_config_dialog.h +++ b/chrome/browser/ui/webui/chromeos/internet_config_dialog.h
@@ -18,8 +18,9 @@ class InternetConfigDialog : public SystemWebDialogDelegate { public: - // Shows a network configuration dialog for |network_state|. - static void ShowDialogForNetworkState(const NetworkState* network_state); + // Shows a network configuration dialog for |network_id|. Does nothing if + // there is no NetworkState matching |network_id|. + static void ShowDialogForNetworkId(const std::string& network_id); // Shows a network configuration dialog for a new network of |network_type|. static void ShowDialogForNetworkType(const std::string& network_type);
diff --git a/chrome/browser/ui/webui/chromeos/login/network_dropdown_handler.cc b/chrome/browser/ui/webui/chromeos/login/network_dropdown_handler.cc index 3cfd3d75..9b1091e 100644 --- a/chrome/browser/ui/webui/chromeos/login/network_dropdown_handler.cc +++ b/chrome/browser/ui/webui/chromeos/login/network_dropdown_handler.cc
@@ -29,6 +29,7 @@ const char kJsApiNetworkDropdownRefresh[] = "networkDropdownRefresh"; const char kJsApiLaunchInternetDetailDialog[] = "launchInternetDetailDialog"; const char kJsApiLaunchAddWiFiNetworkDialog[] = "launchAddWiFiNetworkDialog"; +const char kJsApiShowNetworkConfig[] = "showNetworkConfig"; const char kJsApiShowNetworkDetails[] = "showNetworkDetails"; } // namespace @@ -39,8 +40,7 @@ set_call_js_prefix(kJsScreenPath); } -NetworkDropdownHandler::~NetworkDropdownHandler() { -} +NetworkDropdownHandler::~NetworkDropdownHandler() {} void NetworkDropdownHandler::AddObserver(Observer* observer) { if (observer && !observers_.HasObserver(observer)) @@ -57,8 +57,7 @@ builder->Add("selectAnotherNetwork", IDS_ANOTHER_NETWORK_SELECTION_SELECT); } -void NetworkDropdownHandler::Initialize() { -} +void NetworkDropdownHandler::Initialize() {} void NetworkDropdownHandler::RegisterMessages() { AddCallback(kJsApiNetworkItemChosen, @@ -77,6 +76,8 @@ &NetworkDropdownHandler::HandleLaunchAddWiFiNetworkDialog); AddRawCallback(kJsApiShowNetworkDetails, &NetworkDropdownHandler::HandleShowNetworkDetails); + AddRawCallback(kJsApiShowNetworkConfig, + &NetworkDropdownHandler::HandleShowNetworkConfig); } void NetworkDropdownHandler::HandleLaunchInternetDetailDialog() { @@ -107,6 +108,16 @@ InternetDetailDialog::ShowDialog(guid); } +void NetworkDropdownHandler::HandleShowNetworkConfig( + const base::ListValue* args) { + std::string guid; + args->GetString(0, &guid); + if (chromeos::switches::IsNetworkSettingsConfigEnabled()) + chromeos::InternetConfigDialog::ShowDialogForNetworkId(guid); + else + NetworkConfigView::ShowForNetworkId(guid); +} + void NetworkDropdownHandler::OnConnectToNetworkRequested() { for (Observer& observer : observers_) observer.OnConnectToNetworkRequested();
diff --git a/chrome/browser/ui/webui/chromeos/login/network_dropdown_handler.h b/chrome/browser/ui/webui/chromeos/login/network_dropdown_handler.h index 2bb1c14..72d8b13 100644 --- a/chrome/browser/ui/webui/chromeos/login/network_dropdown_handler.h +++ b/chrome/browser/ui/webui/chromeos/login/network_dropdown_handler.h
@@ -55,6 +55,7 @@ void HandleLaunchInternetDetailDialog(); void HandleLaunchAddWiFiNetworkDialog(); void HandleShowNetworkDetails(const base::ListValue* args); + void HandleShowNetworkConfig(const base::ListValue* args); std::unique_ptr<NetworkDropdown> dropdown_;
diff --git a/chrome/browser/ui/webui/chromeos/login/terms_of_service_screen_handler.cc b/chrome/browser/ui/webui/chromeos/login/terms_of_service_screen_handler.cc index e927f9b..a1afa85e 100644 --- a/chrome/browser/ui/webui/chromeos/login/terms_of_service_screen_handler.cc +++ b/chrome/browser/ui/webui/chromeos/login/terms_of_service_screen_handler.cc
@@ -21,6 +21,7 @@ #include "chrome/common/pref_names.h" #include "chrome/grit/chromium_strings.h" #include "chrome/grit/generated_resources.h" +#include "components/language/core/common/locale_util.h" #include "components/login/localized_values_builder.h" #include "components/prefs/pref_service.h" #include "components/user_manager/user.h" @@ -81,12 +82,13 @@ return; } - const std::string locale = + std::string locale = ProfileHelper::Get() ->GetProfileByUserUnsafe( user_manager::UserManager::Get()->GetActiveUser()) ->GetPrefs() ->GetString(prefs::kApplicationLocale); + language::ConvertToActualUILocale(&locale); if (locale.empty() || locale == g_browser_process->GetApplicationLocale()) { // If the user has not chosen a UI locale yet or the chosen locale matches
diff --git a/chrome/browser/ui/webui/md_downloads/downloads_list_tracker.cc b/chrome/browser/ui/webui/md_downloads/downloads_list_tracker.cc index 2400a23b..51a84c2 100644 --- a/chrome/browser/ui/webui/md_downloads/downloads_list_tracker.cc +++ b/chrome/browser/ui/webui/md_downloads/downloads_list_tracker.cc
@@ -42,24 +42,24 @@ // CreateDownloadItemValue(). Only return strings for DANGEROUS_FILE, // DANGEROUS_URL, DANGEROUS_CONTENT, and UNCOMMON_CONTENT because the // |danger_type| value is only defined if the value of |state| is |DANGEROUS|. -const char* GetDangerTypeString(content::DownloadDangerType danger_type) { +const char* GetDangerTypeString(download::DownloadDangerType danger_type) { switch (danger_type) { - case content::DOWNLOAD_DANGER_TYPE_DANGEROUS_FILE: + case download::DOWNLOAD_DANGER_TYPE_DANGEROUS_FILE: return "DANGEROUS_FILE"; - case content::DOWNLOAD_DANGER_TYPE_DANGEROUS_URL: + case download::DOWNLOAD_DANGER_TYPE_DANGEROUS_URL: return "DANGEROUS_URL"; - case content::DOWNLOAD_DANGER_TYPE_DANGEROUS_CONTENT: + case download::DOWNLOAD_DANGER_TYPE_DANGEROUS_CONTENT: return "DANGEROUS_CONTENT"; - case content::DOWNLOAD_DANGER_TYPE_UNCOMMON_CONTENT: + case download::DOWNLOAD_DANGER_TYPE_UNCOMMON_CONTENT: return "UNCOMMON_CONTENT"; - case content::DOWNLOAD_DANGER_TYPE_DANGEROUS_HOST: + case download::DOWNLOAD_DANGER_TYPE_DANGEROUS_HOST: return "DANGEROUS_HOST"; - case content::DOWNLOAD_DANGER_TYPE_POTENTIALLY_UNWANTED: + case download::DOWNLOAD_DANGER_TYPE_POTENTIALLY_UNWANTED: return "POTENTIALLY_UNWANTED"; - case content::DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS: - case content::DOWNLOAD_DANGER_TYPE_MAYBE_DANGEROUS_CONTENT: - case content::DOWNLOAD_DANGER_TYPE_USER_VALIDATED: - case content::DOWNLOAD_DANGER_TYPE_MAX: + case download::DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS: + case download::DOWNLOAD_DANGER_TYPE_MAYBE_DANGEROUS_CONTENT: + case download::DOWNLOAD_DANGER_TYPE_USER_VALIDATED: + case download::DOWNLOAD_DANGER_TYPE_MAX: break; } // Don't return a danger type string if it is NOT_DANGEROUS,
diff --git a/chrome/browser/ui/webui/md_downloads/md_downloads_dom_handler.cc b/chrome/browser/ui/webui/md_downloads/md_downloads_dom_handler.cc index 7cb3c72..18e4879d 100644 --- a/chrome/browser/ui/webui/md_downloads/md_downloads_dom_handler.cc +++ b/chrome/browser/ui/webui/md_downloads/md_downloads_dom_handler.cc
@@ -32,10 +32,10 @@ #include "chrome/common/chrome_switches.h" #include "chrome/common/pref_names.h" #include "chrome/common/url_constants.h" +#include "components/download/public/common/download_danger_type.h" #include "components/prefs/pref_service.h" #include "components/safe_browsing/common/safe_browsing_prefs.h" #include "content/public/browser/browser_thread.h" -#include "content/public/browser/download_danger_type.h" #include "content/public/browser/download_item.h" #include "content/public/browser/download_manager.h" #include "content/public/browser/url_data_source.h" @@ -206,7 +206,7 @@ // If danger type is NOT DANGEROUS_FILE, chrome shows users a download danger // prompt. if (download->GetDangerType() != - content::DOWNLOAD_DANGER_TYPE_DANGEROUS_FILE) { + download::DOWNLOAD_DANGER_TYPE_DANGEROUS_FILE) { ShowDangerPrompt(download); } else { // If danger type is DANGEROUS_FILE, chrome proceeds to keep this download
diff --git a/chrome/browser/ui/webui/md_downloads/md_downloads_dom_handler_unittest.cc b/chrome/browser/ui/webui/md_downloads/md_downloads_dom_handler_unittest.cc index 947dfe8..cdd1b35e 100644 --- a/chrome/browser/ui/webui/md_downloads/md_downloads_dom_handler_unittest.cc +++ b/chrome/browser/ui/webui/md_downloads/md_downloads_dom_handler_unittest.cc
@@ -135,7 +135,7 @@ testing::StrictMock<content::MockDownloadItem> dangerous_file_type; EXPECT_CALL(dangerous_file_type, GetDangerType()) .WillRepeatedly( - testing::Return(content::DOWNLOAD_DANGER_TYPE_DANGEROUS_FILE)); + testing::Return(download::DOWNLOAD_DANGER_TYPE_DANGEROUS_FILE)); EXPECT_CALL(dangerous_file_type, GetId()) .WillOnce(testing::Return(uint32_t())); TestMdDownloadsDOMHandler handler(manager(), web_ui()); @@ -148,7 +148,7 @@ testing::StrictMock<content::MockDownloadItem> malicious_download; EXPECT_CALL(malicious_download, GetDangerType()) .WillRepeatedly( - testing::Return(content::DOWNLOAD_DANGER_TYPE_DANGEROUS_URL)); + testing::Return(download::DOWNLOAD_DANGER_TYPE_DANGEROUS_URL)); handler.SaveDownload(&malicious_download); EXPECT_EQ(1, handler.danger_prompt_count()); }
diff --git a/chrome/browser/ui/webui/settings/browser_lifetime_handler.cc b/chrome/browser/ui/webui/settings/browser_lifetime_handler.cc index 3c264c5..d8fce5d4 100644 --- a/chrome/browser/ui/webui/settings/browser_lifetime_handler.cc +++ b/chrome/browser/ui/webui/settings/browser_lifetime_handler.cc
@@ -59,8 +59,10 @@ void BrowserLifetimeHandler::HandleFactoryReset( const base::ListValue* args) { - bool tpm_firmware_update_requested; - args->GetBoolean(0, &tpm_firmware_update_requested); + const base::Value::ListStorage& args_list = args->GetList(); + CHECK_EQ(1U, args_list.size()); + bool tpm_firmware_update_requested = args_list[0].GetBool(); + if (tpm_firmware_update_requested) { chromeos::tpm_firmware_update::ShouldOfferUpdateViaPowerwash( base::BindOnce([](bool offer_update) {
diff --git a/chrome/browser/ui/webui/settings/md_settings_localized_strings_provider.cc b/chrome/browser/ui/webui/settings/md_settings_localized_strings_provider.cc index cff34e16..d83b3b4 100644 --- a/chrome/browser/ui/webui/settings/md_settings_localized_strings_provider.cc +++ b/chrome/browser/ui/webui/settings/md_settings_localized_strings_provider.cc
@@ -1091,6 +1091,8 @@ IDS_SETTINGS_INTERNET_GMSCORE_NOTIFICATIONS_SECOND_STEP}, {"gmscoreNotificationsThirdStep", IDS_SETTINGS_INTERNET_GMSCORE_NOTIFICATIONS_THIRD_STEP}, + {"gmscoreNotificationsFourthStep", + IDS_SETTINGS_INTERNET_GMSCORE_NOTIFICATIONS_FOURTH_STEP}, {"tetherConnectionDialogTitle", IDS_SETTINGS_INTERNET_TETHER_CONNECTION_DIALOG_TITLE}, {"tetherConnectionAvailableDeviceTitle",
diff --git a/chrome/browser/ui/webui/settings/site_settings_handler.cc b/chrome/browser/ui/webui/settings/site_settings_handler.cc index ba3bf56..d02fe762 100644 --- a/chrome/browser/ui/webui/settings/site_settings_handler.cc +++ b/chrome/browser/ui/webui/settings/site_settings_handler.cc
@@ -159,6 +159,9 @@ base::Bind(&SiteSettingsHandler::HandleSetOriginPermissions, base::Unretained(this))); web_ui()->RegisterMessageCallback( + "clearFlashPref", base::Bind(&SiteSettingsHandler::HandleClearFlashPref, + base::Unretained(this))); + web_ui()->RegisterMessageCallback( "resetCategoryPermissionForPattern", base::Bind(&SiteSettingsHandler::HandleResetCategoryPermissionForPattern, base::Unretained(this))); @@ -621,6 +624,19 @@ } } +void SiteSettingsHandler::HandleClearFlashPref(const base::ListValue* args) { + CHECK_EQ(1U, args->GetSize()); + std::string origin_string; + CHECK(args->GetString(0, &origin_string)); + + HostContentSettingsMap* map = + HostContentSettingsMapFactory::GetForProfile(profile_); + const GURL origin(origin_string); + map->SetWebsiteSettingDefaultScope(origin, origin, + CONTENT_SETTINGS_TYPE_PLUGINS_DATA, + std::string(), nullptr); +} + void SiteSettingsHandler::HandleResetCategoryPermissionForPattern( const base::ListValue* args) { CHECK_EQ(4U, args->GetSize());
diff --git a/chrome/browser/ui/webui/settings/site_settings_handler.h b/chrome/browser/ui/webui/settings/site_settings_handler.h index 63fa495c..9761de8 100644 --- a/chrome/browser/ui/webui/settings/site_settings_handler.h +++ b/chrome/browser/ui/webui/settings/site_settings_handler.h
@@ -16,6 +16,7 @@ #include "content/public/browser/host_zoom_map.h" #include "content/public/browser/notification_observer.h" #include "content/public/browser/notification_registrar.h" +#include "ppapi/features/features.h" #include "third_party/WebKit/common/quota/quota_types.mojom.h" class HostContentSettingsMap; @@ -70,6 +71,10 @@ private: friend class SiteSettingsHandlerTest; friend class SiteSettingsHandlerInfobarTest; +#if BUILDFLAG(ENABLE_PLUGINS) + FRIEND_TEST_ALL_PREFIXES(SiteSettingsHandlerTest, + ChangingFlashSettingForSiteIsRemembered); +#endif FRIEND_TEST_ALL_PREFIXES(SiteSettingsHandlerTest, DefaultSettingSource); FRIEND_TEST_ALL_PREFIXES(SiteSettingsHandlerTest, ExceptionHelpers); FRIEND_TEST_ALL_PREFIXES(SiteSettingsHandlerTest, ExtensionDisplayName); @@ -110,6 +115,10 @@ void HandleGetOriginPermissions(const base::ListValue* args); void HandleSetOriginPermissions(const base::ListValue* args); + // Clears the Flash data setting used to remember if the user has changed the + // Flash permission for an origin. + void HandleClearFlashPref(const base::ListValue* args); + // Handles setting and resetting an origin permission. void HandleResetCategoryPermissionForPattern(const base::ListValue* args); void HandleSetCategoryPermissionForPattern(const base::ListValue* args);
diff --git a/chrome/browser/ui/webui/settings/site_settings_handler_unittest.cc b/chrome/browser/ui/webui/settings/site_settings_handler_unittest.cc index 434947c..7e40e5e5 100644 --- a/chrome/browser/ui/webui/settings/site_settings_handler_unittest.cc +++ b/chrome/browser/ui/webui/settings/site_settings_handler_unittest.cc
@@ -31,6 +31,7 @@ #include "content/public/test/test_web_ui.h" #include "extensions/browser/extension_registry.h" #include "extensions/common/extension_builder.h" +#include "ppapi/features/features.h" #include "testing/gtest/include/gtest/gtest.h" #if defined(OS_CHROMEOS) @@ -38,6 +39,10 @@ #include "components/user_manager/scoped_user_manager.h" #endif +#if BUILDFLAG(ENABLE_PLUGINS) +#include "chrome/browser/plugins/chrome_plugin_service_filter.h" +#endif + namespace { constexpr char kCallbackId[] = "test-callback-id"; @@ -45,7 +50,41 @@ constexpr char kSource[] = "source"; constexpr char kExtensionName[] = "Test Extension"; -} +#if BUILDFLAG(ENABLE_PLUGINS) +// Waits until a change is observed in content settings. +class FlashContentSettingsChangeWaiter : public content_settings::Observer { + public: + explicit FlashContentSettingsChangeWaiter(Profile* profile) + : profile_(profile) { + HostContentSettingsMapFactory::GetForProfile(profile)->AddObserver(this); + } + ~FlashContentSettingsChangeWaiter() override { + HostContentSettingsMapFactory::GetForProfile(profile_)->RemoveObserver( + this); + } + + // content_settings::Observer: + void OnContentSettingChanged(const ContentSettingsPattern& primary_pattern, + const ContentSettingsPattern& secondary_pattern, + ContentSettingsType content_type, + std::string resource_identifier) override { + if (content_type == CONTENT_SETTINGS_TYPE_PLUGINS) + Proceed(); + } + + void Wait() { run_loop_.Run(); } + + private: + void Proceed() { run_loop_.Quit(); } + + Profile* profile_; + base::RunLoop run_loop_; + + DISALLOW_COPY_AND_ASSIGN(FlashContentSettingsChangeWaiter); +}; +#endif + +} // namespace namespace settings { @@ -90,6 +129,8 @@ CONTENT_SETTINGS_TYPE_NOTIFICATIONS)), kCookies(site_settings::ContentSettingsTypeToGroupName( CONTENT_SETTINGS_TYPE_COOKIES)), + kFlash(site_settings::ContentSettingsTypeToGroupName( + CONTENT_SETTINGS_TYPE_PLUGINS)), handler_(&profile_) { #if defined(OS_CHROMEOS) user_manager_enabler_ = std::make_unique<user_manager::ScopedUserManager>( @@ -277,6 +318,7 @@ // Content setting group name for the relevant ContentSettingsType. const std::string kNotifications; const std::string kCookies; + const std::string kFlash; private: content::TestBrowserThreadBundle thread_bundle_; @@ -476,6 +518,56 @@ site_settings::SiteSettingSource::kDefault, 4U); } +#if BUILDFLAG(ENABLE_PLUGINS) +TEST_F(SiteSettingsHandlerTest, ChangingFlashSettingForSiteIsRemembered) { + ChromePluginServiceFilter::GetInstance()->RegisterResourceContext( + profile(), profile()->GetResourceContext()); + FlashContentSettingsChangeWaiter waiter(profile()); + + const std::string origin_with_port("https://www.example.com:443"); + // The display name won't show the port if it's default for that scheme. + const std::string origin("https://www.example.com"); + base::ListValue get_args; + get_args.AppendString(kCallbackId); + get_args.AppendString(origin_with_port); + const GURL url(origin_with_port); + + HostContentSettingsMap* map = + HostContentSettingsMapFactory::GetForProfile(profile()); + // Make sure the site being tested doesn't already have this marker set. + EXPECT_EQ(nullptr, + map->GetWebsiteSetting(url, url, CONTENT_SETTINGS_TYPE_PLUGINS_DATA, + std::string(), nullptr)); + + // Change the Flash setting. + base::ListValue set_args; + set_args.AppendString(origin_with_port); + { + auto category_list = std::make_unique<base::ListValue>(); + category_list->AppendString(kFlash); + set_args.Append(std::move(category_list)); + } + set_args.AppendString( + content_settings::ContentSettingToString(CONTENT_SETTING_BLOCK)); + handler()->HandleSetOriginPermissions(&set_args); + EXPECT_EQ(1U, web_ui()->call_data().size()); + waiter.Wait(); + + // Check that this site has now been marked for displaying Flash always, then + // clear it and check this works. + EXPECT_NE(nullptr, + map->GetWebsiteSetting(url, url, CONTENT_SETTINGS_TYPE_PLUGINS_DATA, + std::string(), nullptr)); + base::ListValue clear_args; + clear_args.AppendString(origin_with_port); + handler()->HandleSetOriginPermissions(&set_args); + handler()->HandleClearFlashPref(&clear_args); + EXPECT_EQ(nullptr, + map->GetWebsiteSetting(url, url, CONTENT_SETTINGS_TYPE_PLUGINS_DATA, + std::string(), nullptr)); +} +#endif + TEST_F(SiteSettingsHandlerTest, GetAndSetForInvalidURLs) { const std::string origin("arbitrary string"); EXPECT_FALSE(GURL(origin).is_valid());
diff --git a/chrome/browser/ui/webui/site_settings_helper.cc b/chrome/browser/ui/webui/site_settings_helper.cc index bf59df31..6c210595 100644 --- a/chrome/browser/ui/webui/site_settings_helper.cc +++ b/chrome/browser/ui/webui/site_settings_helper.cc
@@ -99,6 +99,7 @@ {CONTENT_SETTINGS_TYPE_CLIENT_HINTS, nullptr}, {CONTENT_SETTINGS_TYPE_ACCESSIBILITY_EVENTS, nullptr}, {CONTENT_SETTINGS_TYPE_CLIPBOARD_WRITE, nullptr}, + {CONTENT_SETTINGS_TYPE_PLUGINS_DATA, nullptr}, }; static_assert(arraysize(kContentSettingsTypeGroupNames) == // ContentSettingsType starts at -1, so add 1 here.
diff --git a/chrome/browser/ui/webui/theme_source.cc b/chrome/browser/ui/webui/theme_source.cc index 1aa3453d..f368150 100644 --- a/chrome/browser/ui/webui/theme_source.cc +++ b/chrome/browser/ui/webui/theme_source.cc
@@ -117,6 +117,7 @@ case version_info::Channel::BETA: case version_info::Channel::STABLE: NOTREACHED(); + FALLTHROUGH; #endif case version_info::Channel::UNKNOWN: resource_id = IDR_PRODUCT_LOGO_32;
diff --git a/chrome/browser/vr/ui_scene_creator.cc b/chrome/browser/vr/ui_scene_creator.cc index 84f69b7..c115813 100644 --- a/chrome/browser/vr/ui_scene_creator.cc +++ b/chrome/browser/vr/ui_scene_creator.cc
@@ -253,7 +253,8 @@ element_binding->bindings().push_back( VR_BIND(AutocompleteMatch::Type, SuggestionBinding, element_binding, model->model()->type, VectorIcon, p_icon, - view->SetIcon(AutocompleteMatch::TypeToVectorIcon(value)))); + view->SetIcon(AutocompleteMatch::TypeToVectorIcon( + value, /*is_bookmark=*/false)))); element_binding->set_view(background.get()); scene->AddUiElement(kOmniboxSuggestions, std::move(background)); }
diff --git a/chrome/common/extensions/api/_permission_features.json b/chrome/common/extensions/api/_permission_features.json index 2385912..e2c9556 100644 --- a/chrome/common/extensions/api/_permission_features.json +++ b/chrome/common/extensions/api/_permission_features.json
@@ -479,6 +479,11 @@ "whitelist": [ "B44D08FD98F1523ED5837D78D0A606EA9D6206E5" // Web Store ] + }, + { + "channel": "dev", + "extension_types": ["platform_app"], + "session_types": ["kiosk"] } ], "mediaGalleries": {
diff --git a/chrome/common/extensions/api/automation.idl b/chrome/common/extensions/api/automation.idl index e675ef36..d283b59 100644 --- a/chrome/common/extensions/api/automation.idl +++ b/chrome/common/extensions/api/automation.idl
@@ -119,6 +119,10 @@ inlineTextBox, inputTime, labelText, + layoutTable, + layoutTableCell, + layoutTableColumn, + layoutTableRow, legend, lineBreak, link, @@ -611,6 +615,12 @@ // The corresponding row header for this cell. AutomationNode? tableRowHeader; + // The column index of this column node. + long? tableColumnIndex; + + // The row index of this row node. + long? tableRowIndex; + // // Live region attributes. // @@ -676,7 +686,7 @@ DOMString? language; // Input restriction, if any, such as readonly or disabled: - // undefined - enabled control or other object that is not disabled + // undefined - enabled control or other object that is not disabled // Restriction.DISABLED - disallows input in itself + any descendants // Restriction.READONLY - allow focus/selection but not input DOMString? restriction;
diff --git a/chrome/common/pref_names.cc b/chrome/common/pref_names.cc index c0e876a..5aa0d5c 100644 --- a/chrome/common/pref_names.cc +++ b/chrome/common/pref_names.cc
@@ -189,11 +189,7 @@ const char kRlzPingDelaySeconds[] = "rlz_ping_delay"; #endif // BUILDFLAG(ENABLE_RLZ) -// The application locale. -// For OS_CHROMEOS we maintain the kApplicationLocale property in both local -// state and the user's profile. The global property determines the locale of -// the login screen, while the user's profile determines their personal locale -// preference. +// Important: Refer to header file for how to use this. const char kApplicationLocale[] = "intl.app_locale"; #if defined(OS_CHROMEOS) // Locale preference of device' owner. ChromeOS device appears in this locale
diff --git a/chrome/common/pref_names.h b/chrome/common/pref_names.h index 29f4853..972bd80 100644 --- a/chrome/common/pref_names.h +++ b/chrome/common/pref_names.h
@@ -61,11 +61,15 @@ extern const char kRlzPingDelaySeconds[]; #endif // BUILDFLAG(ENABLE_RLZ) +// The application locale. +// DO NOT USE this locale directly: use language::ConverToActualLocale() after +// reading it to get the system locale. +// This pref stores the locale that the user selected, if applicable. +extern const char kApplicationLocale[]; // For OS_CHROMEOS we maintain the kApplicationLocale property in both local // state and the user's profile. The global property determines the locale of // the login screen, while the user's profile determines their personal locale // preference. -extern const char kApplicationLocale[]; #if defined(OS_CHROMEOS) extern const char kApplicationLocaleBackup[]; extern const char kApplicationLocaleAccepted[];
diff --git a/chrome/renderer/autofill/page_passwords_analyser_browsertest.cc b/chrome/renderer/autofill/page_passwords_analyser_browsertest.cc index 5fa5edc..d66e3f20b 100644 --- a/chrome/renderer/autofill/page_passwords_analyser_browsertest.cc +++ b/chrome/renderer/autofill/page_passwords_analyser_browsertest.cc
@@ -99,6 +99,13 @@ " <input type='password' autocomplete='new-password'>" "</form>"; +const char kPasswordFieldsWithAndWithoutAutocomplete[] = + "<form>" + " <input type='password'>" + " <input type='text'>" + " <input type='password' autocomplete='current-password'>" + "</form>"; + const std::string AutocompleteSuggestionString(const std::string& suggestion) { return "Input elements should have autocomplete " "attributes (suggested: \"" + @@ -254,4 +261,14 @@ RunTestCase(); } +TEST_F(PagePasswordsAnalyserTest, PasswordFieldWithAndWithoutAutocomplete) { + LoadTestCase(kPasswordFieldsWithAndWithoutAutocomplete); + Expect( + "Multiple forms should be contained in their own " + "form elements; break up complex forms into ones that represent a " + "single action:", + PageFormAnalyserLogger::kVerbose, {0}); + RunTestCase(); +} + } // namespace autofill
diff --git a/chrome/renderer/chrome_render_frame_observer.cc b/chrome/renderer/chrome_render_frame_observer.cc index e92a694..fff89635 100644 --- a/chrome/renderer/chrome_render_frame_observer.cc +++ b/chrome/renderer/chrome_render_frame_observer.cc
@@ -242,13 +242,12 @@ if (gfx::PNGCodec::EncodeBGRASkBitmap( bitmap, kDiscardTransparencyForContextMenu, &data)) { thumbnail_data.swap(data); - break; } + break; case chrome::mojom::ImageFormat::JPEG: - if (gfx::JPEGCodec::Encode(bitmap, kDefaultQuality, &data)) { + if (gfx::JPEGCodec::Encode(bitmap, kDefaultQuality, &data)) thumbnail_data.swap(data); - break; - } + break; } callback.Run(thumbnail_data, original_size); }
diff --git a/chrome/renderer/extensions/automation_internal_custom_bindings.cc b/chrome/renderer/extensions/automation_internal_custom_bindings.cc index be3a916..904749c 100644 --- a/chrome/renderer/extensions/automation_internal_custom_bindings.cc +++ b/chrome/renderer/extensions/automation_internal_custom_bindings.cc
@@ -517,7 +517,28 @@ RouteNodeIDFunction( "GetRole", [](v8::Isolate* isolate, v8::ReturnValue<v8::Value> result, AutomationAXTreeWrapper* tree_wrapper, ui::AXNode* node) { - std::string role_name = ui::ToString(node->data().role); + auto role = node->data().role; + auto mapped_role = role; + + // These roles are remapped for simplicity in handling them in AT. + switch (role) { + case ax::mojom::Role::kLayoutTable: + mapped_role = ax::mojom::Role::kTable; + break; + case ax::mojom::Role::kLayoutTableCell: + mapped_role = ax::mojom::Role::kCell; + break; + case ax::mojom::Role::kLayoutTableColumn: + mapped_role = ax::mojom::Role::kColumn; + break; + case ax::mojom::Role::kLayoutTableRow: + mapped_role = ax::mojom::Role::kRow; + break; + default: + break; + } + + std::string role_name = ui::ToString(mapped_role); result.Set(v8::String::NewFromUtf8(isolate, role_name.c_str())); }); RouteNodeIDFunction(
diff --git a/chrome/renderer/resources/extensions/media_router_bindings.js b/chrome/renderer/resources/extensions/media_router_bindings.js index 6d5f113..1d49718 100644 --- a/chrome/renderer/resources/extensions/media_router_bindings.js +++ b/chrome/renderer/resources/extensions/media_router_bindings.js
@@ -618,6 +618,34 @@ } /** + * Converts string to Mojo origin. + * @param {string|!url.mojom.Origin} origin + * @return {!url.mojom.Origin} + */ +function stringToMojoOrigin_(origin) { + if (origin instanceof url.mojom.Origin) { + return origin; + } + var originUrl = new URL(origin); + var mojoOrigin = {}; + mojoOrigin.scheme = originUrl.protocol.replace(':', ''); + mojoOrigin.host = originUrl.hostname; + var port = originUrl.port ? Number.parseInt(originUrl.port) : 0; + switch (mojoOrigin.scheme) { + case 'http': + mojoOrigin.port = port || 80; + break; + case 'https': + mojoOrigin.port = port || 443; + break; + default: + throw new Error('Scheme must be http or https'); + } + mojoOrigin.suborigin = ''; + return new url.mojom.Origin(mojoOrigin); +} + +/** * Parses the given route request Error object and converts it to the * corresponding result code. * @param {!Error} error @@ -782,12 +810,16 @@ * updated. * @param {!string} sourceUrn * @param {!Array<!MediaSink>} sinks - * @param {!Array<!url.mojom.Origin>} origins + * @param {!Array<string|!url.mojom.Origin>} origins */ MediaRouter.prototype.onSinksReceived = function(sourceUrn, sinks, origins) { + // |origins| is a string array if the Media Router component extension version + // is 59 or older. Without the stringToMojoOrigin_() conversion, clients using + // those extension versions would see a crash shown in + // https://crbug.com/787427. this.service_.onSinksReceived( mediaRouter.mojom.MediaRouteProvider.Id.EXTENSION, sourceUrn, - sinks.map(sinkToMojo_), origins); + sinks.map(sinkToMojo_), origins.map(stringToMojoOrigin_)); }; /**
diff --git a/chrome/service/DEPS b/chrome/service/DEPS index 4618fc5..893a993f 100644 --- a/chrome/service/DEPS +++ b/chrome/service/DEPS
@@ -2,6 +2,7 @@ "+chrome/grit", "+chrome/services/printing/public", "+components/data_use_measurement/core", + "+components/language/core/common", "+components/network_session_configurator/common", "+components/prefs", "+components/version_info",
diff --git a/chrome/service/service_process.cc b/chrome/service/service_process.cc index aaa41f83..0b2e540 100644 --- a/chrome/service/service_process.cc +++ b/chrome/service/service_process.cc
@@ -43,6 +43,7 @@ #include "chrome/service/cloud_print/cloud_print_proxy.h" #include "chrome/service/net/service_url_request_context_getter.h" #include "chrome/service/service_process_prefs.h" +#include "components/language/core/common/locale_util.h" #include "components/network_session_configurator/common/network_switches.h" #include "components/prefs/json_pref_store.h" #include "mojo/edk/embedder/embedder.h" @@ -220,6 +221,7 @@ // the prefs. locale = service_prefs_->GetString(prefs::kApplicationLocale, std::string()); + language::ConvertToActualUILocale(&locale); // If no locale was specified anywhere, use the default one. if (locale.empty()) locale = kDefaultServiceProcessLocale;
diff --git a/chrome/test/BUILD.gn b/chrome/test/BUILD.gn index b0e8119..8fa3a42 100644 --- a/chrome/test/BUILD.gn +++ b/chrome/test/BUILD.gn
@@ -627,6 +627,7 @@ "../browser/policy/cloud/test_request_interceptor.cc", "../browser/policy/cloud/test_request_interceptor.h", "../browser/policy/policy_browsertest.cc", + "../browser/policy/policy_initialization_browsertest.cc", "../browser/policy/policy_network_browsertest.cc", "../browser/policy/policy_prefs_browsertest.cc", "../browser/policy/policy_startup_browsertest.cc", @@ -934,7 +935,7 @@ "//net", "//net:test_support", "//services/device/public/interfaces", - "//services/network/public/cpp:network_features", + "//services/network/public/cpp", "//services/service_manager/public/cpp", "//skia", "//testing/gmock",
diff --git a/chrome/test/android/BUILD.gn b/chrome/test/android/BUILD.gn index 772e866d..589e453 100644 --- a/chrome/test/android/BUILD.gn +++ b/chrome/test/android/BUILD.gn
@@ -9,7 +9,6 @@ java_files = [ "javatests/src/org/chromium/chrome/test/BottomSheetTestRule.java", "javatests/src/org/chromium/chrome/test/ChromeActivityTestRule.java", - "javatests/src/org/chromium/chrome/test/ChromeInstrumentationTestRunner.java", "javatests/src/org/chromium/chrome/test/ChromeJUnit4ClassRunner.java", "javatests/src/org/chromium/chrome/test/ChromeJUnit4RunnerDelegate.java", "javatests/src/org/chromium/chrome/test/ChromeTabbedActivityTestRule.java",
diff --git a/chrome/test/android/javatests/src/org/chromium/chrome/test/ChromeInstrumentationTestRunner.java b/chrome/test/android/javatests/src/org/chromium/chrome/test/ChromeInstrumentationTestRunner.java deleted file mode 100644 index bb70e72..0000000 --- a/chrome/test/android/javatests/src/org/chromium/chrome/test/ChromeInstrumentationTestRunner.java +++ /dev/null
@@ -1,167 +0,0 @@ -// Copyright 2014 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 org.chromium.chrome.test; - -import android.content.Context; -import android.os.Bundle; -import android.text.TextUtils; - -import com.google.android.gms.common.ConnectionResult; -import com.google.android.gms.common.GoogleApiAvailability; - -import org.chromium.base.CommandLine; -import org.chromium.base.ThreadUtils; -import org.chromium.base.test.BaseChromiumInstrumentationTestRunner; -import org.chromium.base.test.BaseTestResult; -import org.chromium.base.test.util.RestrictionSkipCheck; -import org.chromium.chrome.browser.ChromeVersionInfo; -import org.chromium.chrome.browser.vr_shell.VrClassesWrapper; -import org.chromium.chrome.browser.vr_shell.VrDaydreamApi; -import org.chromium.chrome.test.util.ChromeRestriction; -import org.chromium.content.browser.test.ChildProcessAllocatorSettingsHook; -import org.chromium.policy.test.annotations.Policies; -import org.chromium.ui.test.util.UiDisableIfSkipCheck; -import org.chromium.ui.test.util.UiRestrictionSkipCheck; - -import java.lang.reflect.Constructor; -import java.lang.reflect.InvocationTargetException; -import java.util.concurrent.Callable; -import java.util.concurrent.CancellationException; -import java.util.concurrent.ExecutionException; -import java.util.concurrent.FutureTask; - -/** - * An Instrumentation test runner that optionally spawns a test HTTP server. - * The server's root directory is the device's external storage directory. - */ -public class ChromeInstrumentationTestRunner extends BaseChromiumInstrumentationTestRunner { - @Override - public void onCreate(Bundle arguments) { - super.onCreate(arguments); - } - - @Override - protected void addTestHooks(BaseTestResult result) { - super.addTestHooks(result); - result.addSkipCheck(new ChromeRestrictionSkipCheck(getTargetContext())); - result.addSkipCheck(new UiDisableIfSkipCheck(getTargetContext())); - result.addSkipCheck(new UiRestrictionSkipCheck(getTargetContext())); - - result.addPreTestHook(Policies.getRegistrationHook()); - result.addPreTestHook(new ChildProcessAllocatorSettingsHook()); - } - - static class ChromeRestrictionSkipCheck extends RestrictionSkipCheck { - private VrDaydreamApi mDaydreamApi; - private boolean mAttemptedToGetApi; - - public ChromeRestrictionSkipCheck(Context targetContext) { - super(targetContext); - } - - @SuppressWarnings("unchecked") - private VrDaydreamApi getDaydreamApi() { - if (!mAttemptedToGetApi) { - mAttemptedToGetApi = true; - try { - Class<? extends VrClassesWrapper> vrClassesBuilderClass = - (Class<? extends VrClassesWrapper>) Class.forName( - "org.chromium.chrome.browser.vr_shell.VrClassesWrapperImpl"); - Constructor<?> vrClassesBuilderConstructor = - vrClassesBuilderClass.getConstructor(); - VrClassesWrapper vrClassesBuilder = - (VrClassesWrapper) vrClassesBuilderConstructor.newInstance(); - mDaydreamApi = vrClassesBuilder.createVrDaydreamApi(getTargetContext()); - } catch (ClassNotFoundException | InstantiationException | IllegalAccessException - | IllegalArgumentException | InvocationTargetException - | NoSuchMethodException e) { - return null; - } - } - return mDaydreamApi; - } - - private boolean isDaydreamReady() { - return getDaydreamApi() == null ? false : - getDaydreamApi().isDaydreamReadyDevice(); - } - - private boolean isDaydreamViewPaired() { - if (getDaydreamApi() == null) { - return false; - } - // isDaydreamCurrentViewer() creates a concrete instance of DaydreamApi, - // which can only be done on the main thread - FutureTask<Boolean> checker = new FutureTask<>(new Callable<Boolean>() { - @Override - public Boolean call() { - return getDaydreamApi().isDaydreamCurrentViewer(); - } - }); - ThreadUtils.runOnUiThreadBlocking(checker); - try { - return checker.get().booleanValue(); - } catch (CancellationException | InterruptedException | ExecutionException - | IllegalArgumentException e) { - return false; - } - } - - private boolean isDonEnabled() { - // We can't directly check whether the VR DON flow is enabled since - // we don't have permission to read the VrCore settings file. Instead, - // pass a flag. - return CommandLine.getInstance().hasSwitch("don-enabled"); - } - - @Override - protected boolean restrictionApplies(String restriction) { - if (TextUtils.equals( - restriction, ChromeRestriction.RESTRICTION_TYPE_GOOGLE_PLAY_SERVICES) - && (ConnectionResult.SUCCESS - != GoogleApiAvailability.getInstance().isGooglePlayServicesAvailable( - getTargetContext()))) { - return true; - } - if (TextUtils.equals(restriction, - ChromeRestriction.RESTRICTION_TYPE_OFFICIAL_BUILD) - && (!ChromeVersionInfo.isOfficialBuild())) { - return true; - } - if (TextUtils.equals(restriction, ChromeRestriction.RESTRICTION_TYPE_DEVICE_DAYDREAM) - || TextUtils.equals(restriction, - ChromeRestriction.RESTRICTION_TYPE_DEVICE_NON_DAYDREAM)) { - boolean isDaydream = isDaydreamReady(); - if (TextUtils.equals( - restriction, ChromeRestriction.RESTRICTION_TYPE_DEVICE_DAYDREAM) - && !isDaydream) { - return true; - } else if (TextUtils.equals(restriction, - ChromeRestriction.RESTRICTION_TYPE_DEVICE_NON_DAYDREAM) - && isDaydream) { - return true; - } - } - if (TextUtils.equals(restriction, ChromeRestriction.RESTRICTION_TYPE_VIEWER_DAYDREAM) - || TextUtils.equals(restriction, - ChromeRestriction.RESTRICTION_TYPE_VIEWER_NON_DAYDREAM)) { - boolean daydreamViewPaired = isDaydreamViewPaired(); - if (TextUtils.equals( - restriction, ChromeRestriction.RESTRICTION_TYPE_VIEWER_DAYDREAM) - && !daydreamViewPaired) { - return true; - } else if (TextUtils.equals(restriction, - ChromeRestriction.RESTRICTION_TYPE_VIEWER_NON_DAYDREAM) - && daydreamViewPaired) { - return true; - } - } - if (TextUtils.equals(restriction, ChromeRestriction.RESTRICTION_TYPE_DON_ENABLED)) { - return !isDonEnabled(); - } - return false; - } - } -}
diff --git a/chrome/test/android/javatests/src/org/chromium/chrome/test/ChromeJUnit4ClassRunner.java b/chrome/test/android/javatests/src/org/chromium/chrome/test/ChromeJUnit4ClassRunner.java index e21b055..bc87cb0e 100644 --- a/chrome/test/android/javatests/src/org/chromium/chrome/test/ChromeJUnit4ClassRunner.java +++ b/chrome/test/android/javatests/src/org/chromium/chrome/test/ChromeJUnit4ClassRunner.java
@@ -4,23 +4,40 @@ package org.chromium.chrome.test; +import android.content.Context; import android.support.test.InstrumentationRegistry; +import android.text.TextUtils; + +import com.google.android.gms.common.ConnectionResult; +import com.google.android.gms.common.GoogleApiAvailability; import org.junit.runners.model.InitializationError; import org.chromium.base.CollectionUtil; +import org.chromium.base.CommandLine; import org.chromium.base.CommandLineInitUtil; +import org.chromium.base.ThreadUtils; import org.chromium.base.test.BaseJUnit4ClassRunner; import org.chromium.base.test.BaseTestResult.PreTestHook; import org.chromium.base.test.util.CommandLineFlags; +import org.chromium.base.test.util.RestrictionSkipCheck; import org.chromium.base.test.util.SkipCheck; -import org.chromium.chrome.test.ChromeInstrumentationTestRunner.ChromeRestrictionSkipCheck; +import org.chromium.chrome.browser.ChromeVersionInfo; +import org.chromium.chrome.browser.vr_shell.VrClassesWrapper; +import org.chromium.chrome.browser.vr_shell.VrDaydreamApi; +import org.chromium.chrome.test.util.ChromeRestriction; import org.chromium.content.browser.test.ChildProcessAllocatorSettingsHook; import org.chromium.policy.test.annotations.Policies; import org.chromium.ui.test.util.UiDisableIfSkipCheck; import org.chromium.ui.test.util.UiRestrictionSkipCheck; +import java.lang.reflect.Constructor; +import java.lang.reflect.InvocationTargetException; import java.util.List; +import java.util.concurrent.Callable; +import java.util.concurrent.CancellationException; +import java.util.concurrent.ExecutionException; +import java.util.concurrent.FutureTask; /** * A custom runner for //chrome JUnit4 tests. @@ -52,4 +69,114 @@ CommandLineInitUtil.initCommandLine( InstrumentationRegistry.getTargetContext(), CommandLineFlags.getTestCmdLineFile()); } + + private static class ChromeRestrictionSkipCheck extends RestrictionSkipCheck { + private VrDaydreamApi mDaydreamApi; + private boolean mAttemptedToGetApi; + + public ChromeRestrictionSkipCheck(Context targetContext) { + super(targetContext); + } + + @SuppressWarnings("unchecked") + private VrDaydreamApi getDaydreamApi() { + if (!mAttemptedToGetApi) { + mAttemptedToGetApi = true; + try { + Class<? extends VrClassesWrapper> vrClassesBuilderClass = + (Class<? extends VrClassesWrapper>) Class.forName( + "org.chromium.chrome.browser.vr_shell.VrClassesWrapperImpl"); + Constructor<?> vrClassesBuilderConstructor = + vrClassesBuilderClass.getConstructor(); + VrClassesWrapper vrClassesBuilder = + (VrClassesWrapper) vrClassesBuilderConstructor.newInstance(); + mDaydreamApi = vrClassesBuilder.createVrDaydreamApi(getTargetContext()); + } catch (ClassNotFoundException | InstantiationException | IllegalAccessException + | IllegalArgumentException | InvocationTargetException + | NoSuchMethodException e) { + return null; + } + } + return mDaydreamApi; + } + + private boolean isDaydreamReady() { + return getDaydreamApi() == null ? false : getDaydreamApi().isDaydreamReadyDevice(); + } + + private boolean isDaydreamViewPaired() { + if (getDaydreamApi() == null) { + return false; + } + // isDaydreamCurrentViewer() creates a concrete instance of DaydreamApi, + // which can only be done on the main thread + FutureTask<Boolean> checker = new FutureTask<>(new Callable<Boolean>() { + @Override + public Boolean call() { + return getDaydreamApi().isDaydreamCurrentViewer(); + } + }); + ThreadUtils.runOnUiThreadBlocking(checker); + try { + return checker.get().booleanValue(); + } catch (CancellationException | InterruptedException | ExecutionException + | IllegalArgumentException e) { + return false; + } + } + + private boolean isDonEnabled() { + // We can't directly check whether the VR DON flow is enabled since + // we don't have permission to read the VrCore settings file. Instead, + // pass a flag. + return CommandLine.getInstance().hasSwitch("don-enabled"); + } + + @Override + protected boolean restrictionApplies(String restriction) { + if (TextUtils.equals( + restriction, ChromeRestriction.RESTRICTION_TYPE_GOOGLE_PLAY_SERVICES) + && (ConnectionResult.SUCCESS + != GoogleApiAvailability.getInstance().isGooglePlayServicesAvailable( + getTargetContext()))) { + return true; + } + if (TextUtils.equals(restriction, ChromeRestriction.RESTRICTION_TYPE_OFFICIAL_BUILD) + && (!ChromeVersionInfo.isOfficialBuild())) { + return true; + } + if (TextUtils.equals(restriction, ChromeRestriction.RESTRICTION_TYPE_DEVICE_DAYDREAM) + || TextUtils.equals(restriction, + ChromeRestriction.RESTRICTION_TYPE_DEVICE_NON_DAYDREAM)) { + boolean isDaydream = isDaydreamReady(); + if (TextUtils.equals( + restriction, ChromeRestriction.RESTRICTION_TYPE_DEVICE_DAYDREAM) + && !isDaydream) { + return true; + } else if (TextUtils.equals(restriction, + ChromeRestriction.RESTRICTION_TYPE_DEVICE_NON_DAYDREAM) + && isDaydream) { + return true; + } + } + if (TextUtils.equals(restriction, ChromeRestriction.RESTRICTION_TYPE_VIEWER_DAYDREAM) + || TextUtils.equals(restriction, + ChromeRestriction.RESTRICTION_TYPE_VIEWER_NON_DAYDREAM)) { + boolean daydreamViewPaired = isDaydreamViewPaired(); + if (TextUtils.equals( + restriction, ChromeRestriction.RESTRICTION_TYPE_VIEWER_DAYDREAM) + && !daydreamViewPaired) { + return true; + } else if (TextUtils.equals(restriction, + ChromeRestriction.RESTRICTION_TYPE_VIEWER_NON_DAYDREAM) + && daydreamViewPaired) { + return true; + } + } + if (TextUtils.equals(restriction, ChromeRestriction.RESTRICTION_TYPE_DON_ENABLED)) { + return !isDonEnabled(); + } + return false; + } + } }
diff --git a/chrome/test/base/in_process_browser_test.cc b/chrome/test/base/in_process_browser_test.cc index 14e44e8..5ad361b3 100644 --- a/chrome/test/base/in_process_browser_test.cc +++ b/chrome/test/base/in_process_browser_test.cc
@@ -102,53 +102,15 @@ InProcessBrowserTest::SetUpBrowserFunction* InProcessBrowserTest::global_browser_set_up_function_ = nullptr; -// Library used for testing accessibility. -const base::FilePath::CharType kAXSTesting[] = - FILE_PATH_LITERAL("third_party/accessibility-audit/axs_testing.js"); -// JavaScript snippet to configure and run the accessibility audit. -const char kAccessibilityTestString[] = - "var config = new axs.AuditConfiguration();" - "/* Disable warning about rules that cannot be checked. */" - "config.showUnsupportedRulesWarning = false;" - "config.auditRulesToIgnore = [" - " /*" - " * The 'elements with meaningful background image' accessibility" - " * audit (AX_IMAGE_01) does not apply, since Chrome doesn't" - " * disable background images in high-contrast mode like some" - " * browsers do." - " */" - " 'elementsWithMeaningfulBackgroundImage'," - " /*" - " * Most WebUI pages are inside an IFrame, so the 'web page should" - " * have a title that describes topic or purpose' test (AX_TITLE_01)" - " * generally does not apply." - " */" - " 'pageWithoutTitle'," - " /*" - " * Enable when crbug.com/267035 is fixed." - " * Until then it's just noise." - " */" - " 'lowContrastElements'" - "];" - "var result = axs.Audit.run(config);" - "var error = '';" - "for (var i = 0; i < result.length; ++i) {" - " if (result[i].result == axs.constants.AuditResult.FAIL) {" - " error = axs.Audit.createReport(result);" - " break;" - " }" - "}" - "domAutomationController.send(error);"; - InProcessBrowserTest::InProcessBrowserTest() : browser_(NULL), exit_when_last_browser_closes_(true), - open_about_blank_on_browser_launch_(true), - run_accessibility_checks_for_test_case_(false) + open_about_blank_on_browser_launch_(true) #if defined(OS_MACOSX) - , autorelease_pool_(NULL) + , + autorelease_pool_(NULL) #endif // OS_MACOSX - { +{ #if defined(OS_MACOSX) // TODO(phajdan.jr): Make browser_tests self-contained on Mac, remove this. // Before we run the browser, we have to hack the path to the exe to match @@ -299,57 +261,6 @@ command_line->AppendArg(url::kAboutBlankURL); } -bool InProcessBrowserTest::RunAccessibilityChecks(std::string* error_message) { - base::ScopedAllowBlockingForTesting allow_blocking; - if (!browser()) { - *error_message = "browser is NULL"; - return false; - } - auto* tab_strip = browser()->tab_strip_model(); - if (!tab_strip) { - *error_message = "tab_strip is NULL"; - return false; - } - auto* web_contents = tab_strip->GetActiveWebContents(); - if (!web_contents) { - *error_message = "web_contents is NULL"; - return false; - } - auto* focused_frame = web_contents->GetFocusedFrame(); - if (!focused_frame) { - *error_message = "focused_frame is NULL"; - return false; - } - - // Load accessibility library. - base::FilePath src_dir; - if (!PathService::Get(base::DIR_SOURCE_ROOT, &src_dir)) { - *error_message = "PathService::Get failed"; - return false; - } - base::FilePath script_path = src_dir.Append(kAXSTesting); - std::string script; - if (!base::ReadFileToString(script_path, &script)) { - *error_message = "Could not read accessibility library"; - return false; - } - if (!content::ExecuteScript(web_contents, script)) { - *error_message = "Failed to load accessibility library"; - return false; - } - - // Run accessibility audit. - if (!content::ExecuteScriptAndExtractString(focused_frame, - kAccessibilityTestString, - error_message)) { - *error_message = "Failed to run accessibility audit"; - return false; - } - - // Test result should be empty if there are no errors. - return error_message->empty(); -} - bool InProcessBrowserTest::CreateUserDataDirectory() { base::CommandLine* command_line = base::CommandLine::ForCurrentProcess(); base::FilePath user_data_dir = @@ -563,11 +474,6 @@ // browser. content::RunAllPendingInMessageLoop(); - // run_accessibility_checks_for_test_case_ must be set before calling - // SetUpOnMainThread or RunTestOnMainThread so that one or all tests can - // enable/disable the accessibility audit. - run_accessibility_checks_for_test_case_ = false; - if (browser_ && global_browser_set_up_function_) ASSERT_TRUE(global_browser_set_up_function_(browser_)); @@ -585,16 +491,6 @@ autorelease_pool_->Recycle(); #endif - if (run_accessibility_checks_for_test_case_) { - std::string error_message; - EXPECT_TRUE(RunAccessibilityChecks(&error_message)); - EXPECT_EQ("", error_message); - } - -#if defined(OS_MACOSX) - autorelease_pool_->Recycle(); -#endif - // Sometimes tests leave Quit tasks in the MessageLoop (for shame), so let's // run all pending messages here to avoid preempting the QuitBrowsers tasks. // TODO(jbates) Once crbug.com/134753 is fixed, this can be removed because it
diff --git a/chrome/test/base/in_process_browser_test.h b/chrome/test/base/in_process_browser_test.h index 3199740..2d42ab3a 100644 --- a/chrome/test/base/in_process_browser_test.h +++ b/chrome/test/base/in_process_browser_test.h
@@ -204,13 +204,6 @@ // the navigation to complete, and show the browser's window. void AddBlankTabAndShow(Browser* browser); - // Enables running of accessibility audit for a particular test case. - // - Call in test body to enable/disable for one test case. - // - Call in SetUpOnMainThread() to enable for all test cases. - void EnableAccessibilityChecksForTestCase(bool enabled) { - run_accessibility_checks_for_test_case_ = enabled; - } - #if !defined OS_MACOSX // Return a CommandLine object that is used to relaunch the browser_test // binary as a browser process. This function is deliberately not defined on @@ -236,9 +229,6 @@ open_about_blank_on_browser_launch_ = value; } - // Runs accessibility checks and sets |error_message| if it fails. - bool RunAccessibilityChecks(std::string* error_message); - private: // Creates a user data directory for the test if one is needed. Returns true // if successful. @@ -262,10 +252,6 @@ // True if the about:blank tab should be opened when the browser is launched. bool open_about_blank_on_browser_launch_; - // True if the accessibility test should run for a particular test case. - // This is reset for every test case. - bool run_accessibility_checks_for_test_case_; - // We use hardcoded quota settings to have a consistent testing environment. storage::QuotaSettings quota_settings_;
diff --git a/chrome/test/base/in_process_browser_test_browsertest.cc b/chrome/test/base/in_process_browser_test_browsertest.cc index 22953ce9..61841a8 100644 --- a/chrome/test/base/in_process_browser_test_browsertest.cc +++ b/chrome/test/base/in_process_browser_test_browsertest.cc
@@ -93,61 +93,4 @@ EXPECT_TRUE(AfterStartupTaskUtils::IsBrowserStartupComplete()); } -// Paths are to very simple HTML files. One is accessible, the other is not. -const base::FilePath::CharType kPassHTML[] = - FILE_PATH_LITERAL("chrome/test/data/accessibility_pass.html"); -const base::FilePath::CharType kFailHTML[] = - FILE_PATH_LITERAL("chrome/test/data/accessibility_fail.html"); - -/* - * This class is meant as a test for the accessibility audit in the - * InProcessBrowserTest. These tests do NOT validate the accessibility audit, - * just the ability to run it. - */ -class InProcessAccessibilityBrowserTest : public InProcessBrowserTest { - protected: - // Construct a URL from a file path that can be used to get to a web page. - base::FilePath BuildURLToFile(const base::FilePath::CharType* file_path) { - base::FilePath source_root; - if (!PathService::Get(base::DIR_SOURCE_ROOT, &source_root)) - return base::FilePath(); - return source_root.Append(file_path); - } - - bool NavigateToURL(const base::FilePath::CharType* address) { - GURL url = net::FilePathToFileURL(BuildURLToFile(address)); - - if (!url.is_valid() || url.is_empty() || !browser()) - return false; - - ui_test_utils::NavigateToURLBlockUntilNavigationsComplete( - browser(), url, 1); - return true; - } -}; - -// Test that an accessible page doesn't fail the accessibility audit. -IN_PROC_BROWSER_TEST_F( - InProcessAccessibilityBrowserTest, DISABLED_VerifyAccessibilityPass) { - ASSERT_TRUE(NavigateToURL(kPassHTML)); - - std::string test_result; - EXPECT_TRUE(RunAccessibilityChecks(&test_result)); - - // No error message on success. - EXPECT_EQ("", test_result); -} - -// Test that a page that is not accessible will fail the accessibility audit. -IN_PROC_BROWSER_TEST_F( - InProcessAccessibilityBrowserTest, VerifyAccessibilityFail) { - ASSERT_TRUE(NavigateToURL(kFailHTML)); - - std::string test_result; - EXPECT_FALSE(RunAccessibilityChecks(&test_result)); - - // Error should NOT be empty on failure. - EXPECT_NE("", test_result); -} - } // namespace
diff --git a/chrome/test/base/testing_profile.cc b/chrome/test/base/testing_profile.cc index 19a9b0e..429b1cfa 100644 --- a/chrome/test/base/testing_profile.cc +++ b/chrome/test/base/testing_profile.cc
@@ -800,8 +800,7 @@ if (!policy_service_) { std::vector<policy::ConfigurationPolicyProvider*> providers; std::unique_ptr<policy::PolicyServiceImpl> policy_service = - std::make_unique<policy::PolicyServiceImpl>(); - policy_service->SetProviders(providers); + std::make_unique<policy::PolicyServiceImpl>(std::move(providers)); policy_service_ = std::move(policy_service); } profile_policy_connector_.reset(new policy::ProfilePolicyConnector());
diff --git a/chrome/test/chromedriver/BUILD.gn b/chrome/test/chromedriver/BUILD.gn index 1af0cf3..c571ca3 100644 --- a/chrome/test/chromedriver/BUILD.gn +++ b/chrome/test/chromedriver/BUILD.gn
@@ -347,6 +347,11 @@ data_deps = [ "//chrome/test/chromedriver", ] + + if (is_win) { + # On Windows, the following target produces the final chrome.exe + data_deps += [ "//chrome:reorder_imports" ] + } } test("chromedriver_unittests") {
diff --git a/chrome/test/chromedriver/test/run_py_tests.py b/chrome/test/chromedriver/test/run_py_tests.py index cf8c934..91bc649e 100755 --- a/chrome/test/chromedriver/test/run_py_tests.py +++ b/chrome/test/chromedriver/test/run_py_tests.py
@@ -84,11 +84,12 @@ ] _VERSION_SPECIFIC_FILTER = {} -_VERSION_SPECIFIC_FILTER['HEAD'] = [ - # https://bugs.chromium.org/p/chromium/issues/detail?id=764519 - 'MobileEmulationCapabilityTest.testDeviceName', - 'MobileEmulationCapabilityTest.testNetworkConnectionTypeIsAppliedToAllTabs', - 'MobileEmulationCapabilityTest.testNetworkConnectionTypeIsAppliedToAllTabsImmediately', +_VERSION_SPECIFIC_FILTER['HEAD'] = [] + +_VERSION_SPECIFIC_FILTER['65'] = [ + # https://bugs.chromium.org/p/chromium/issues/detail?id=803678 + 'ChromeDriverTest.testGoBackAndGoForward', + 'ChromeDriverTest.testAlertHandlingOnPageUnload' ] _VERSION_SPECIFIC_FILTER['64'] = [ @@ -2713,9 +2714,16 @@ options, args = parser.parse_args() + if options.chromedriver is None: + parser.error('--chromedriver is required.\n' + + 'Please run "%s --help" for help' % __file__) options.chromedriver = util.GetAbsolutePathOfUserPath(options.chromedriver) - if not options.chromedriver or not os.path.exists(options.chromedriver): - parser.error('chromedriver is required or the given path is invalid.' + + if (not os.path.exists(options.chromedriver) and + util.GetPlatformName() == 'win' and + not options.chromedriver.lower().endswith('.exe')): + options.chromedriver = options.chromedriver + '.exe' + if not os.path.exists(options.chromedriver): + parser.error('Path given by --chromedriver is invalid.\n' + 'Please run "%s --help" for help' % __file__) global _CHROMEDRIVER_BINARY
diff --git a/chrome/test/data/chromeos/app_mode/management_api/primary_app/key.pem b/chrome/test/data/chromeos/app_mode/management_api/primary_app/key.pem new file mode 100644 index 0000000..611da272 --- /dev/null +++ b/chrome/test/data/chromeos/app_mode/management_api/primary_app/key.pem
@@ -0,0 +1,28 @@ +-----BEGIN PRIVATE KEY----- +MIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIBAQC3aFAcHk8yszLB +n+3LtibvlyPBmh2BLKq7t9A03LKx7zbFVCxxX9N+KMfXFvAW+craT/yyAYV3KOsF +V6hyTr4QnSJ4WP8u9HRgLLkrbHgnnlzsd74NKz0IpwREd4AG/AhAtA2znX9wZFdN +3//vLzTp1+QLbqvj5dWGJatgXKXwuaHyL8S2UrtmwZEBMrMH1ju9QpltWatYdAv5 +73x950hBTh6ow6S3qMlOAGuJEtrk++7opMn4FLO3dhYrPv7zDX6RHiaqYMQpAaDe +BQmMgV4gUeiZAYvgbra7T/KI7EgmKwvu0lypcpUIOCy2tIwMVjzvnH4xRk+ljbxA +Yo39jYX7AgMBAAECggEAK2A4vgWvDlsSMHfN6gVI3RYeJz33J2M0d9PnonDltC5S +gkW/gwq6PpaPeL+chZqLDqmnJkQ01/Mt7iQGmw4jZlN7YQIPTAAVe99n5aywGBKc +gHJrWLr2otK5MCYg+cXmf8L1kJq5lo+slCbbZSqBdaKQ9OE2Nt5W6vSCvPX8attd +Y+K7mSFsOqchVGKNj2x6TKNt2W0MNRgNqR3dZlf4qRw/JhRgUrJLQjy+NeUaZFM4 +OZK4tS2Riq8b2ROBi4agio1lGc9nY5wKwl7zsV83bPEmWYL0t0PnL0muBRlVrRG6 +1LnGdeOMGg7XU8JI6xSxHdnBRLsVyC0XqTV0FIUphQKBgQDr6uB8w2p846XWcU6P +KWsN74AjvXyEZCgOtppDYcl6Am8Z5A/zGc+fd/lkxgHrS4V9/ZM15REHSF7B4jaF +qstvHu0crocrn1K3mCW0bKXcDP4tiNVTnGZyIL/jLK6PbDHX7dux631MhcWzjf9H +PeFmFqDTglCevsZZCBv58Ut/nwKBgQDHBSK+f9wsPlO2V4FWndzXyHZVqd66MJHx +AT22Gr9nk6DBOfHuIefDz+ZVIZozgCphi24It3Mduc9dmP4fwuyo6nmm57uMev4p +C5LG2DWtCGASdVtlWCXK1vugwHut5sBtw2VbyifTCpQUDPVPKAhe/mU7I23sgXv3 +iNNYVRNsJQKBgQDWD0tbyVBxO3n5JtxaSAGMJnlFdKRr2BkEqKk2ZJ8UZur6OhZC +xXO/RXPz/To2jlL068XMDCm0SvU3xRMlm8B09kG9WZrqeOjsD1B+8mpYTS3AkTzH +Xc0S1yZlceB94HUlcPx75qnNaj/l2Pz9XmeLYxLQd5jBQWbl19bSph+UDwKBgQCJ +B9w4Vkj+nZt9/RoszVz1piz0JpYYlMCntDcNX7VSV69j28XcNLQjes4Y554Iv8Ju +j1Yf4k/8s6c3xtOSgt/4HhnM9dmIjFbbZACXsN6kWRPtIajgSqUa2JNAx8dgoXT1 +Hoh3fuWUxb/XXmS5L9MztO12nppdMXptoWQDefB5kQKBgEZLaz4xukznI6YpKy5R +pA2iHpLzHEcDW8dmvKq93LGqfrvq+hs5vXW5UXWHFopkjb1sRkQ0apNuaD7QeQ0S +eNdEc5c7lLW2krDP64mpHfGVSKmsuvqBuVHkMONp6h8YAbuOkB2Rw594FBz3Xwuo +FW8WIqaeB/5nmx/emYZD/TsV +-----END PRIVATE KEY-----
diff --git a/chrome/test/data/chromeos/app_mode/management_api/primary_app/src/main.js b/chrome/test/data/chromeos/app_mode/management_api/primary_app/src/main.js new file mode 100644 index 0000000..4cfc6764 --- /dev/null +++ b/chrome/test/data/chromeos/app_mode/management_api/primary_app/src/main.js
@@ -0,0 +1,125 @@ +// 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. + +chrome.app.runtime.onLaunched.addListener(function() { + var kSecondaryAppId = 'lfaidgolgikbpapkmdhoppddflhaocnf'; + var kNotAllowedError = 'Not allowed in kiosk.'; + + chrome.test.runTests([ + function getSelf() { + chrome.management.getSelf(chrome.test.callbackPass(function(info) { + chrome.test.assertEq(chrome.runtime.id, info.id); + })); + }, + + function getAll() { + chrome.management.getAll(chrome.test.callbackPass(function(result) { + chrome.test.assertEq(2, result.length); + var self = result.find(entry => entry.id == chrome.runtime.id); + chrome.test.assertTrue(!!self); + + var secondary = result.find(entry => entry.id == kSecondaryAppId); + chrome.test.assertTrue(!!secondary); + })); + }, + + function getSecondary() { + chrome.management.get( + kSecondaryAppId, chrome.test.callbackPass(function(info) { + chrome.test.assertEq(kSecondaryAppId, info.id); + chrome.test.assertTrue(info.enabled); + })); + }, + + function disableSelf() { + chrome.management.setEnabled( + chrome.runtime.id, false, + chrome.test.callbackFail( + 'Cannot change the primary kiosk app state.')); + }, + + function disableSecondary() { + chrome.test.listenOnce(chrome.management.onDisabled, function(info) { + chrome.test.assertEq(kSecondaryAppId, info.id); + chrome.test.assertFalse(info.enabled); + }); + + chrome.management.setEnabled( + kSecondaryAppId, false, chrome.test.callbackPass(function() { + chrome.management.get( + kSecondaryAppId, chrome.test.callbackPass(function(info) { + chrome.test.assertFalse(info.enabled); + chrome.test.assertTrue(info.mayEnable); + })); + })); + }, + + function enableSecondary() { + chrome.test.listenOnce(chrome.management.onEnabled, function(info) { + chrome.test.assertEq(kSecondaryAppId, info.id); + chrome.test.assertTrue(info.enabled); + }); + + chrome.management.setEnabled( + kSecondaryAppId, true, chrome.test.callbackPass(function() { + chrome.management.get( + kSecondaryAppId, chrome.test.callbackPass(function(info) { + chrome.test.assertTrue(info.enabled); + })); + })); + }, + + function uninstallSelf() { + chrome.management.uninstallSelf( + chrome.test.callbackFail(kNotAllowedError)); + }, + + function uninstallSecondary() { + chrome.management.uninstall( + kSecondaryAppId, chrome.test.callbackFail(kNotAllowedError)); + }, + + function launchSecondary() { + chrome.management.launchApp( + kSecondaryAppId, chrome.test.callbackFail(kNotAllowedError)); + }, + + function createAppShortcut() { + chrome.management.createAppShortcut( + kSecondaryAppId, chrome.test.callbackFail(kNotAllowedError)); + }, + + function setLaunchType() { + chrome.management.setLaunchType( + kSecondaryAppId, 'OPEN_AS_WINDOW', + chrome.test.callbackFail(kNotAllowedError)); + }, + + function generateAppForLink() { + chrome.management.generateAppForLink( + 'https://test.test', 'Test app', + chrome.test.callbackFail(kNotAllowedError)); + }, + + function testSecondaryApp() { + chrome.runtime.sendMessage( + kSecondaryAppId, 'runTests', function(response) { + // If tests in secondary app failed to run, notify test runner of + // failure before continuing tests in primary app - the test runner + // expects two test results. + if (chrome.runtime.lastError) { + chrome.test.notifyFail( + 'Secondary app tests failed to run: ' + + chrome.runtime.lastError.message); + } else if (response != 'ok') { + chrome.test.notifyFail( + 'Secondary app tests failed to run: app responded: ' + + response); + } + + chrome.test.succeed(); + }); + }, + ]); +});
diff --git a/chrome/test/data/chromeos/app_mode/management_api/primary_app/src/manifest.json b/chrome/test/data/chromeos/app_mode/management_api/primary_app/src/manifest.json new file mode 100644 index 0000000..c2099bc --- /dev/null +++ b/chrome/test/data/chromeos/app_mode/management_api/primary_app/src/manifest.json
@@ -0,0 +1,17 @@ +{ + "name": "Kiosk app testing management API", + "manifest_version": 2, + "version": "1.0.0", + "app": { + "background": { + "scripts": ["main.js"] + } + }, + "kiosk_enabled": true, + "permissions": [ + "management" + ], + "kiosk_secondary_apps": [ + {"id": "lfaidgolgikbpapkmdhoppddflhaocnf"} + ] +}
diff --git a/chrome/test/data/chromeos/app_mode/management_api/secondary_app/key.pem b/chrome/test/data/chromeos/app_mode/management_api/secondary_app/key.pem new file mode 100644 index 0000000..58b1ad7 --- /dev/null +++ b/chrome/test/data/chromeos/app_mode/management_api/secondary_app/key.pem
@@ -0,0 +1,28 @@ +-----BEGIN PRIVATE KEY----- +MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQCVdTSbM2/zS/qt +6kwc7FsJjUtbQ1t6FtwCR7wXbw8dcPH+EyzxOj56mNXPPYqPTBcC2n04AO0oCSLq +s8SlBsJedO3kOg9Syc4x51+rXMkBTnIRGHXZbE6myFvJHmZPOaqpfwIuW5ESZMJR +RtpgVZz/x7ydBt0nm05iDwhuuHVmPtEio02sRkCLQkDj1YGxinTdZWWOCLseQoVj +6Q7G8/pojF5PGv6k6TuYj03NIGx1FDhsGjHY/wNzH4KdI9xD8FpdlgSC2Qt/Dzum +WnypxHH6neheKZ8shw3T6O4RF2u4pK0cOnV8D+2deOiHfpKEnAhlqBIHMMKbLhTp +TyHAP/3VAgMBAAECggEAAMY0KQ+pp01/9XGuxkGVMSX5u3XMXgQLTLm5aDerkN/6 +aPIJfBBsrW7oQKQVeSuQPPQLzQP4Nophk2yt+prf2+RoLRP961RfTJPhw33+DpMs +9Ri215L/j06fZxnQtt1aHHmrdbkEtd8uwIQI8pHO9+Y9fGTCNYfQ7qIcTZKIDSkJ +HQ22hEqoYNPKKRFIT3rlweDLMpVOdptMktJmHkZFDEs4/LZ76ijRrRCysih+E50N +TBm2jBt4g39FvK7G8fIFczqIjRrUdlOQ5xuTJFrMtR2eArdHgHcjp1Z23hto7hIl +roxX3g7o32w6HDoaWhZCAiS3iFd2HjS2R0LKo6jMAQKBgQDSyCGSg5IuAQ1H+n7B +cgwaAMgWCWPYEOjLn+egP39hASOuebn+awGgx8fFgJmZQGL//a//lLcO5nRq2+CT +aE9ERS6ezSYOyK9zC/YIvm3ncouaERddSeyzfymlNCS/pGCMMU6txH0Q1oQd1+nC +Y6tFsR/jlXI1NrYf0mHguDuT1QKBgQC1hT3QRNlFEpA4vIQWAwNECE+WHVYNuLLx +2eTSr+GxfFF597W8QORV6D/7xurvx6KVcQvUJVn2FO+I5XJQ/BQoYY8mpHIWm/YL +NJzReYU+0DcouW+YappDWY8/YjSfpt7lM0p6H8z57zkCJKziFSuBLWMZqez08rw1 +9VGeMYnCAQKBgHNChsE0ezH210ld3ARyFdX+SWtrdRKIpJP8e89wCXqFAfr9i0xp +PTmrJT2Fxfg8ciZjleMfcj6OnGh2lcZlirrdTdH+gmohKXeyubYsU7L1OwtjfzA/ +JVU+GwrAibvV6gmfSNPSl0Um2JXtJGFs2RJB+hsb9JjOsyaRh343oDSFAoGBAIkB +VUNyA69vsG0yVFus0HUz9KXv5Hic1GtYs64V1Do7A+AUCBZbwDva/RgS7lYmjt9O +oMfxnTHwYU8pJxxa9vf3kq1u5zGLa6zPfCFbICflzgwt0j3vEBoPaeBERkXOFGRY +TzlX8UUfux6UAezuX5SzZh4DtHa5EzeCvqSw7TIBAoGATmIBZLt/udfYyX3HDvM8 +CyTRldT77T0XhSXQTKhBMWhdvGcrdbWnpv1cqKNbCLNm8SaGCKSPy0/arTEAlwXM +d5Dyw259qs2uXt47HVkYox4oF3yDCdQtIXtTfyEaGzmRh3F9hcPfXKXQdHboI54P +6vNKgnPozOy5+2TkqXXMvQI= +-----END PRIVATE KEY-----
diff --git a/chrome/test/data/chromeos/app_mode/management_api/secondary_app/src/main.js b/chrome/test/data/chromeos/app_mode/management_api/secondary_app/src/main.js new file mode 100644 index 0000000..f86e1fd --- /dev/null +++ b/chrome/test/data/chromeos/app_mode/management_api/secondary_app/src/main.js
@@ -0,0 +1,91 @@ +// 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. + +chrome.runtime.onMessageExternal.addListener(function( + message, sender, callback) { + var kPrimaryAppId = 'faiboenfkkoaedoehhkjmenkhidadgje'; + var kNotAllowedError = 'Not allowed in kiosk.'; + var kChangingPrimaryAppError = 'Cannot change the primary kiosk app state.'; + + if (!sender || sender.id != kPrimaryAppId) + return; + + if (message != 'runTests') { + callback('invalidMessage: ' + message); + return; + } + + callback('ok'); + + chrome.test.runTests([ + function getSelf() { + chrome.management.getSelf(chrome.test.callbackPass(function(info) { + chrome.test.assertEq(chrome.runtime.id, info.id); + })); + }, + + function getAll() { + chrome.management.getAll(chrome.test.callbackPass(function(result) { + chrome.test.assertEq(2, result.length); + var self = result.find(entry => entry.id == chrome.runtime.id); + chrome.test.assertTrue(!!self); + + var secondary = result.find(entry => entry.id == kPrimaryAppId); + chrome.test.assertTrue(!!secondary); + })); + }, + + function getPrimary() { + chrome.management.get( + kPrimaryAppId, chrome.test.callbackPass(function(info) { + chrome.test.assertEq(kPrimaryAppId, info.id); + chrome.test.assertTrue(info.enabled); + })); + }, + + function disablePrimary() { + chrome.management.setEnabled( + kPrimaryAppId, false, + chrome.test.callbackFail(kChangingPrimaryAppError)); + }, + + function enablePrimary() { + chrome.management.setEnabled( + kPrimaryAppId, true, + chrome.test.callbackFail(kChangingPrimaryAppError)); + }, + + function uninstallSelf() { + chrome.management.uninstallSelf( + chrome.test.callbackFail(kNotAllowedError)); + }, + + function uninstallPrimary() { + chrome.management.uninstall( + kPrimaryAppId, chrome.test.callbackFail(kNotAllowedError)); + }, + + function launchPrimary() { + chrome.management.launchApp( + kPrimaryAppId, chrome.test.callbackFail(kNotAllowedError)); + }, + + function createAppShortcut() { + chrome.management.createAppShortcut( + chrome.runtime.id, chrome.test.callbackFail(kNotAllowedError)); + }, + + function setLaunchType() { + chrome.management.setLaunchType( + chrome.runtime.id, 'OPEN_AS_WINDOW', + chrome.test.callbackFail(kNotAllowedError)); + }, + + function generateAppForLink() { + chrome.management.generateAppForLink( + 'https://test.test', 'Test app', + chrome.test.callbackFail(kNotAllowedError)); + } + ]); +});
diff --git a/chrome/test/data/chromeos/app_mode/management_api/secondary_app/src/manifest.json b/chrome/test/data/chromeos/app_mode/management_api/secondary_app/src/manifest.json new file mode 100644 index 0000000..b2c15614f --- /dev/null +++ b/chrome/test/data/chromeos/app_mode/management_api/secondary_app/src/manifest.json
@@ -0,0 +1,10 @@ +{ + "name": "Secondary kiosk app for management API tests.", + "version": "1.0.0", + "manifest_version": 2, + "background": { + "scripts": ["main.js"], + "persistent": false + }, + "permissions": ["management"] +}
diff --git a/chrome/test/data/chromeos/app_mode/webstore/downloads/faiboenfkkoaedoehhkjmenkhidadgje.crx b/chrome/test/data/chromeos/app_mode/webstore/downloads/faiboenfkkoaedoehhkjmenkhidadgje.crx new file mode 100644 index 0000000..dd6ab46 --- /dev/null +++ b/chrome/test/data/chromeos/app_mode/webstore/downloads/faiboenfkkoaedoehhkjmenkhidadgje.crx Binary files differ
diff --git a/chrome/test/data/chromeos/app_mode/webstore/downloads/lfaidgolgikbpapkmdhoppddflhaocnf.crx b/chrome/test/data/chromeos/app_mode/webstore/downloads/lfaidgolgikbpapkmdhoppddflhaocnf.crx new file mode 100644 index 0000000..c5ba8b3 --- /dev/null +++ b/chrome/test/data/chromeos/app_mode/webstore/downloads/lfaidgolgikbpapkmdhoppddflhaocnf.crx Binary files differ
diff --git a/chrome/test/data/extensions/api_test/automation/tests/webview/webview_frame.html b/chrome/test/data/extensions/api_test/automation/tests/webview/webview_frame.html index 4073aa7..6d24293f 100644 --- a/chrome/test/data/extensions/api_test/automation/tests/webview/webview_frame.html +++ b/chrome/test/data/extensions/api_test/automation/tests/webview/webview_frame.html
@@ -1,3 +1,4 @@ +<!DOCTYPE html> <html> <head> <title>Frame with WebView</title>
diff --git a/chrome/test/data/extensions/api_test/debugger/background.js b/chrome/test/data/extensions/api_test/debugger/background.js index 87ec46d..6d76789 100644 --- a/chrome/test/data/extensions/api_test/debugger/background.js +++ b/chrome/test/data/extensions/api_test/debugger/background.js
@@ -7,8 +7,8 @@ var tabId; var debuggee; -var protocolVersion = "1.2"; -var protocolPreviousVersion = "1.1"; +var protocolVersion = "1.3"; +var protocolPreviousVersion = "1.2"; var unsupportedMinorProtocolVersion = "1.5"; var unsupportedMajorProtocolVersion = "100.0";
diff --git a/chrome/test/data/extensions/api_test/debugger_extension/background.js b/chrome/test/data/extensions/api_test/debugger_extension/background.js index 6a22290f6..eddff72 100644 --- a/chrome/test/data/extensions/api_test/debugger_extension/background.js +++ b/chrome/test/data/extensions/api_test/debugger_extension/background.js
@@ -6,7 +6,7 @@ var fail = chrome.test.callbackFail; var debuggee; -var protocolVersion = "1.2"; +var protocolVersion = "1.3"; chrome.test.runTests([
diff --git a/chrome/test/data/extensions/api_test/networking_private/chromeos/test.js b/chrome/test/data/extensions/api_test/networking_private/chromeos/test.js index b6582d4..10d093e 100644 --- a/chrome/test/data/extensions/api_test/networking_private/chromeos/test.js +++ b/chrome/test/data/extensions/api_test/networking_private/chromeos/test.js
@@ -139,35 +139,27 @@ })); }, function startActivate() { - // Must connect to a network before we can activate it. - chrome.networkingPrivate.startConnect( - kCellularGuid, callbackPass(function() { - chrome.networkingPrivate.startActivate( - kCellularGuid, callbackPass(function() { - // For non Sprint networks, startActivate will delegate - // showing the activation UI to the browser host and not - // immediately activate the network. - chrome.networkingPrivate.getState( - kCellularGuid, callbackPass(function(state) { - assertEq(ActivationStateType.NOT_ACTIVATED, - state.Cellular.ActivationState); - })); - })); - })); + chrome.networkingPrivate.startActivate( + kCellularGuid, callbackPass(function() { + // For non Sprint networks, startActivate will delegate + // showing the activation UI to the browser host and not + // immediately activate the network. + chrome.networkingPrivate.getState( + kCellularGuid, callbackPass(function(state) { + assertEq(ActivationStateType.NOT_ACTIVATED, + state.Cellular.ActivationState); + })); + })); }, function startActivateSprint() { - // Must connect to a network before we can activate it. - chrome.networkingPrivate.startConnect( - kCellularGuid, callbackPass(function() { - chrome.networkingPrivate.startActivate( - kCellularGuid, callbackPass(function() { - chrome.networkingPrivate.getState( - kCellularGuid, callbackPass(function(state) { - assertEq(ActivationStateType.ACTIVATED, - state.Cellular.ActivationState); - })); - })); - })); + chrome.networkingPrivate.startActivate( + kCellularGuid, callbackPass(function() { + chrome.networkingPrivate.getState( + kCellularGuid, callbackPass(function(state) { + assertEq(ActivationStateType.ACTIVATED, + state.Cellular.ActivationState); + })); + })); }, function startConnectNonexistent() { chrome.networkingPrivate.startConnect(
diff --git a/chrome/test/data/password/password_fetch_submit.html b/chrome/test/data/password/password_fetch_submit.html index e279b05c..05e8065d 100644 --- a/chrome/test/data/password/password_fetch_submit.html +++ b/chrome/test/data/password/password_fetch_submit.html
@@ -22,11 +22,10 @@ // Pretend like auth succeeded by hiding the login and signup forms. document.getElementById("testform").style.display = "none"; document.getElementById("signup_testform").style.display = "none"; - // Finish loading the body of the response and then give - // PasswordAutofillAgent a chance to run before upload. It will run as - // soon as JS execution ends, so this shouldn't introduce any timing - // dependent flakes. - response.arrayBuffer().then(() => setTimeout(delayedUpload, 0)); + // Delay upload so that handler in PasswordAutofillAgent can be run + // first. This will happen immediately after JS execution ends, so + // this shouldn't introduce any timing dependent flakes. + setTimeout(delayedUpload, 0); } } )
diff --git a/chrome/test/data/webui/settings/about_page_tests.js b/chrome/test/data/webui/settings/about_page_tests.js index 3698a00..ede8dbc6 100644 --- a/chrome/test/data/webui/settings/about_page_tests.js +++ b/chrome/test/data/webui/settings/about_page_tests.js
@@ -491,7 +491,10 @@ assertFalse(page.$.relaunchAndPowerwash.hidden); MockInteractions.tap(page.$.relaunchAndPowerwash); - return lifetimeBrowserProxy.whenCalled('factoryReset'); + return lifetimeBrowserProxy.whenCalled('factoryReset') + .then((requestTpmFirmwareUpdate) => { + assertFalse(requestTpmFirmwareUpdate); + }); }); }); @@ -590,7 +593,7 @@ assertTrue(dialog.$.dialog.open); MockInteractions.tap(dialog.$$('#powerwash')); return lifetimeBrowserProxy.whenCalled('factoryReset') - .then(function(requestTpmFirmwareUpdate) { + .then((requestTpmFirmwareUpdate) => { assertTrue(requestTpmFirmwareUpdate); }); });
diff --git a/chrome/test/data/webui/settings/reset_page_test.js b/chrome/test/data/webui/settings/reset_page_test.js index 92a66e5b..6fec238 100644 --- a/chrome/test/data/webui/settings/reset_page_test.js +++ b/chrome/test/data/webui/settings/reset_page_test.js
@@ -196,7 +196,10 @@ const dialog = resetPage.$$('settings-powerwash-dialog'); assertTrue(!!dialog); MockInteractions.tap(dialog.$.powerwash); - return lifetimeBrowserProxy.whenCalled('factoryReset'); + return lifetimeBrowserProxy.whenCalled('factoryReset') + .then((requestTpmFirmwareUpdate) => { + assertFalse(requestTpmFirmwareUpdate); + }); }); } });
diff --git a/chrome/test/data/webui/settings/site_details_tests.js b/chrome/test/data/webui/settings/site_details_tests.js index 251e21e..0a1ec4e 100644 --- a/chrome/test/data/webui/settings/site_details_tests.js +++ b/chrome/test/data/webui/settings/site_details_tests.js
@@ -413,6 +413,9 @@ return browserProxy.whenCalled('setOriginPermissions'); }) .then(() => { + return browserProxy.whenCalled('clearFlashPref'); + }) + .then(() => { return browserProxy.whenCalled('getOriginPermissions'); }) .then((args) => {
diff --git a/chrome/test/data/webui/settings/test_site_settings_prefs_browser_proxy.js b/chrome/test/data/webui/settings/test_site_settings_prefs_browser_proxy.js index 1a5f28b..23a27b6 100644 --- a/chrome/test/data/webui/settings/test_site_settings_prefs_browser_proxy.js +++ b/chrome/test/data/webui/settings/test_site_settings_prefs_browser_proxy.js
@@ -70,6 +70,7 @@ class TestSiteSettingsPrefsBrowserProxy extends TestBrowserProxy { constructor() { super([ + 'clearFlashPref', 'fetchUsbDevices', 'fetchZoomLevels', 'getDefaultValueForContentType', @@ -231,6 +232,11 @@ } /** @override */ + clearFlashPref(origin) { + this.methodCalled('clearFlashPref', origin); + } + + /** @override */ getDefaultValueForContentType(contentType) { this.methodCalled('getDefaultValueForContentType', contentType);
diff --git a/chrome/test/vr/auto_bisect.py b/chrome/test/vr/auto_bisect.py new file mode 100755 index 0000000..b0bf8bb8 --- /dev/null +++ b/chrome/test/vr/auto_bisect.py
@@ -0,0 +1,343 @@ +#!/usr/bin/python +# 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. + +"""Script to bisect a VR perf regression. + +This is only meant to be used on a developer's workstation, not on bots or any +other sort of automated infrastructure. This is to help reduce the amount of +work necessary to bisect VR perf regressions until the perf dashboard supports +automatic bisects on devices outside of the Telemetry lab. + +As a result, this is a bit crude and makes a number of assumptions. +""" + + +import argparse +import json +import os +import shutil +import subprocess +import sys +import tempfile +import time + + +class TempDir(): + """Context manager for temp dirs since Python 2 doesn't have one.""" + def __enter__(self): + self._dirpath = tempfile.mkdtemp() + return self._dirpath + + def __exit__(self, type, value, traceback): + shutil.rmtree(self._dirpath) + + +def VerifyCwd(): + """Checks that the script is being run from the Chromium root directory. + + Not robust in the slightest, but should catch common issues like running the + script from the directory that it's located in. + """ + if os.path.basename(os.getcwd()) != 'src': + raise RuntimeError('Script must be run from the Chromium root directory') + + +def ParseArgsAndAssertValid(): + """Parses all the provided arguments and ensures everything is valid.""" + parser = argparse.ArgumentParser(); + + # Arguments related to the actual bisection + parser.add_argument_group('bisect arguments') + parser.add_argument('--good-revision', required=True, + help='A known good Git revision') + parser.add_argument('--bad-revision', required=True, + help='A known bad Git revision') + parser.add_argument('--metric', required=True, + help='The perf metric being bisected') + parser.add_argument('--story', required=True, + help='The perf story to check the affected metric in') + parser.add_argument('--good-value', required=True, type=float, + help='The value of the metric at the good revision') + parser.add_argument('--bad-value', required=True, type=float, + help='The value of the metric at the bad revision') + parser.add_argument('--clank-revision', + help='The Clank revision to sync to during the bisect. ' + 'Only necessary if the revision on ToT is not ' + 'compatible with the revision range of the bisect') + parser.add_argument('--reset-before-sync', action='store_true', + default=False, + help='When set, runs "git reset --hard HEAD" before ' + 'syncing. This has the potential to accidentally ' + 'delete any uncommitted changes, but can help avoid ' + 'random bisect failures.') + + parser.add_argument_group('swarming arguments') + parser.add_argument('--swarming-server', required=True, + help='The swarming server to trigger the test on') + parser.add_argument('--isolate-server', required=True, + help='The isolate server to upload the test to') + def dimension(arg): + split_arg = arg.split(',') + if len(split_arg) != 2: + raise argparse.ArgumentError( + 'Expected two comma-separated strings for --dimension, ' + 'received %d' % len(split_arg)) + return {split_arg[0]: split_arg[1]} + parser.add_argument('--dimension', action='append', type=dimension, + default=[], dest='dimensions', + help='A comma-separated swarming dimension key/value ' + 'pair. At least one must be provided.') + parser.add_argument('--isolate-target', + help='The target to isolate. Defaults to the build ' + 'target') + + parser.add_argument_group('compile arguments') + parser.add_argument('-j', '--parallel-jobs', type=int, default=1000, + help='The number of parallel jobs ninja will compile ' + 'with') + parser.add_argument('-l', '--load-limit', type=int, default=70, + help='Don\'t start new ninja jobs if the average CPU ' + 'is above this') + parser.add_argument('--build-output-dir', + default=os.path.join('out', 'Release'), + help='The directory that builds will take place in. ' + 'Assumes that gn args have already been generated ' + 'for the provided directory') + parser.add_argument('--build-target', required=True, + help='The target to build for testing') + + args, unknown_args = parser.parse_known_args() + + # Set defaults + if not args.isolate_target: + args.isolate_target = args.build_target + + # Make sure we have at least one swarming dimension + if len(args.dimensions) == 0: + raise RuntimeError('No swarming dimensions provided') + + return (args, unknown_args) + + +def VerifyInput(args, unknown_args): + """Verifies with the user that the provided args are satisfactory. + + Args: + args: The known args parsed by the argument parser + unknown_args: The unknown args parsed by the argument parser + """ + print '======' + print 'This will start a bisect for a for:' + print 'Metric: %s' % args.metric + print 'Story: %s' % args.story + print 'Changing from %f at %s to %f at %s' % (args.good_value, + args.good_revision, args.bad_value, args.bad_revision) + print '======' + print 'The test target %s will be built to %s' % (args.build_target, + args.build_output_dir) + print '%d parallel jobs will be used with a load limit of %d' % ( + args.parallel_jobs, args.load_limit) + print '======' + print 'The target %s will be isolated and uploaded to %s' % ( + args.isolate_target, args.isolate_server) + print 'The test will be triggered on %s with the following dimensions:' % ( + args.swarming_server) + for pair in args.dimensions: + for key, val in pair.iteritems(): + print '%s = %s' % (key, val) + print '======' + print 'The test will be run with these additional arguments:' + for extra_arg in unknown_args: + print extra_arg + print '======' + if args.reset_before_sync: + print '**WARNING** This will run git reset --hard HEAD' + print 'If you have any uncommitted changes, commit or stash them beforehand' + if raw_input('Are these settings correct? y/N').lower() != 'y': + print 'Aborting' + sys.exit(1) + + +def SetupBisect(args): + """Does all the one-time setup for a bisect. + + This includes creating a new branch and starting a bisect. + + Args + args: The parsed args from argparse + Returns: + The name of the git branch created and the first revision to sync to + """ + # bisect-year-month-day-hour-minute-second + branch_name = 'bisect-' + time.strftime('%Y-%m-%d-%H-%M-%S') + subprocess.check_output(['git', 'checkout', '-b', branch_name]) + subprocess.check_output(['git', 'bisect', 'start']) + subprocess.check_output(['git', 'bisect', 'good', args.good_revision]) + output = subprocess.check_output(['git', 'bisect', 'bad', args.bad_revision]) + print output + # Get the revision, which is between [] + revision = output.split('[', 1)[1].split(']', 1)[0] + return (branch_name, revision) + + +def RunTestOnSwarming(args, unknown_args, output_dir): + """Isolates the test target and runs it on swarming to get perf results. + + Args: + args: The known args parsed by the argument parser + unknown_args: The unknown args parsed by the argument parser + output_dir: The directory to save swarming results to + """ + print "=== Isolating and running target %s ===" % args.isolate_target + print 'Isolating' + subprocess.check_output(['python', os.path.join('tools', 'mb', 'mb.py'), + 'isolate', + '//%s' % args.build_output_dir, args.isolate_target]) + print 'Uploading' + output = subprocess.check_output([ + 'python', os.path.join('tools', 'swarming_client', 'isolate.py'), + 'batcharchive', '--isolate-server', args.isolate_server, + os.path.join(args.build_output_dir, + '%s.isolated.gen.json' % args.isolate_target)]) + isolate_hash = output.split(' ')[0] + + swarming_args = [ + 'python', os.path.join('tools', 'swarming_client', 'swarming.py'), 'run', + '--isolated', isolate_hash, + '--isolate-server', args.isolate_server, + '--swarming', args.swarming_server, + '--task-output-dir', output_dir, + ] + for pair in args.dimensions: + for key, val in pair.iteritems(): + swarming_args.extend(['--dimension', key, val]) + + swarming_args.append('--') + swarming_args.extend(unknown_args) + swarming_args.extend([ + '--isolated-script-test-output', + '${ISOLATED_OUTDIR}/output.json', + '--isolated-script-test-perf-output', + '${ISOLATED_OUTDIR}/perftest-output.json', + '--output-format', 'chartjson']) + print 'Running test' + subprocess.check_output(swarming_args) + + +def CheckSwarmingResult(args, unknown_args, output_dir): + """Checks the perf results and determines whether they're good or bad. + + Triggers another bisect step if the culprit CL has not yet been found. + + Args: + args: The known args parsed from the argument parser + unknown_args: The unknown args parsed from the argument parser + output_dir: The directory where swarming results have been saved to + """ + with open( + os.path.join(output_dir, '0', 'perftest-output.json'), 'r') as infile: + perf_results = json.load(infile) + all_results = perf_results.get(unicode('charts'), {}).get( + unicode(args.metric), {}).get(unicode(args.story), {}).get( + unicode('values'), []) + if len(all_results) == 0: + raise RuntimeError('Got no results for the story/metric combo. ' + 'Is there a typo in one of them?') + result = all_results[0] + print 'Got result %s' % str(result) + + output = "" + # Regression was an increased value + if args.bad_value > args.good_value: + # If we're greater than the provided bad value or between good and bad, but + # closer to bad, we're still bad + if (result > args.bad_value or + abs(args.bad_value - result) < abs(args.good_value - result)): + print '=== Current revision is BAD ===' + output = subprocess.check_output(['git', 'bisect', 'bad']) + else: + print '=== Current revision is GOOD ===' + output = subprocess.check_output(['git', 'bisect', 'good']) + # Regression was a decreased value + else: + # If we're smaller than the provided bad value or between good and bad, but + # closer to bad, we're still bad + if (result < args.bad_value or + abs(args.bad_value - result) < abs(args.good_value - result)): + print '=== Current revision is BAD ===' + output = subprocess.check_output(['git', 'bisect', 'bad']) + else: + print '=== Current revision is GOOD ===' + output = subprocess.check_output(['git', 'bisect', 'good']) + + print output + if output.startswith('Bisecting:'): + RunBisectStep(args, unknown_args, output.split('[', 1)[1].split(']', 1)[0], + output_dir) + + +def RunBisectStep(args, unknown_args, revision, output_dir): + """Runs a bisect step for a revision. + + This will run recursively until the culprit CL is found. + + Args: + args: The known args parsed from the argument parser + unknown_args: The unknown args parsed from the argument parser + revision: The git revision to sync to and test + output_dir: The directory to save swarming results to + """ + print '=== Syncing to revision %s and building ===' % revision + # Sometimes random files show up as unstaged changes (???), so make sure that + # isn't the case before we try to run gclient sync + if args.reset_before_sync: + subprocess.check_output(['git', 'reset', '--hard', 'HEAD']) + print 'Syncing' + output = subprocess.check_output(['gclient', 'sync', '-r', + 'src@%s' % revision]) + if ('error: Your local changes to the following files would be overwritten ' + 'by checkout:' in output): + raise RuntimeError('Could not run gclient sync due to uncommitted changes. ' + 'If these changes are actually yours, please commit or stash them. If ' + 'they are not, remove them and try again. If the issue persists, try ' + 'running with --reset-before-sync') + if args.clank_revision: + os.chdir('clank') + subprocess.check_output(['git', 'checkout', args.clank_revision]) + os.chdir('..') + print 'Building' + subprocess.check_output(['ninja', '-C', args.build_output_dir, + '-j', str(args.parallel_jobs), + '-l', str(args.load_limit), args.build_target]) + RunTestOnSwarming(args, unknown_args, output_dir) + CheckSwarmingResult(args, unknown_args, output_dir) + + +def BisectRegression(args, unknown_args): + """Runs all steps necessary to bisect a perf regression. + + Intermediate steps and the culprit CL will be printed to stdout. + + Args: + args: The known args parsed by the argument parser + unknown_args: The unknown args parsed by the argument parser + """ + + with TempDir() as output_dir: + try: + branch_name, revision = SetupBisect(args) + RunBisectStep(args, unknown_args, revision, output_dir) + finally: + subprocess.check_output(['git', 'bisect', 'reset']) + + +def main(): + VerifyCwd() + args, unknown_args = ParseArgsAndAssertValid() + VerifyInput(args, unknown_args) + BisectRegression(args, unknown_args) + +if __name__ == '__main__': + main()
diff --git a/chrome_elf/BUILD.gn b/chrome_elf/BUILD.gn index e41180c..08dc1dd 100644 --- a/chrome_elf/BUILD.gn +++ b/chrome_elf/BUILD.gn
@@ -58,7 +58,7 @@ ":hook_util", ":nt_registry", ":security", - ":whitelist", + ":third_party_dlls", "//build/config:exe_and_shlib_deps", "//chrome/install_static:install_static_util", "//chrome/install_static:primary_module", @@ -138,14 +138,14 @@ ] } -# This source_set defines whitelist-related structures and APIs used from +# This source_set defines third-party-related structures and APIs used from # outside chrome_elf.dll. The APIs are exported from chrome_elf (add a # data_dep on //chrome_elf:chrome_elf), which will always be loaded before # chrome.dll. -source_set("whitelist_packed_format") { +source_set("third_party_packed_list_format") { sources = [ - "whitelist/whitelist_packed_format.cc", - "whitelist/whitelist_packed_format.h", + "third_party_dlls/packed_list_format.cc", + "third_party_dlls/packed_list_format.h", ] } @@ -237,22 +237,22 @@ libs = [ "kernel32.lib" ] } -static_library("whitelist") { +static_library("third_party_dlls") { visibility = [ ":*" ] # Only targets in this file can depend on this. sources = [ - "whitelist/whitelist.cc", - "whitelist/whitelist.h", - "whitelist/whitelist_file.cc", - "whitelist/whitelist_file.h", - "whitelist/whitelist_ime.cc", - "whitelist/whitelist_ime.h", - "whitelist/whitelist_log.cc", - "whitelist/whitelist_log.h", + "third_party_dlls/imes.cc", + "third_party_dlls/imes.h", + "third_party_dlls/logs.cc", + "third_party_dlls/logs.h", + "third_party_dlls/main.cc", + "third_party_dlls/main.h", + "third_party_dlls/packed_list_file.cc", + "third_party_dlls/packed_list_file.h", ] deps = [ ":nt_registry", ":sha1", - ":whitelist_packed_format", + ":third_party_packed_list_format", "//chrome/install_static:install_static_util", ] } @@ -270,9 +270,9 @@ "nt_registry/nt_registry_unittest.cc", "run_all_unittests.cc", "sha1/sha1_unittest.cc", - "whitelist/whitelist_file_unittest.cc", - "whitelist/whitelist_ime_unittest.cc", - "whitelist/whitelist_log_unittest.cc", + "third_party_dlls/imes_unittest.cc", + "third_party_dlls/logs_unittest.cc", + "third_party_dlls/packed_list_file_unittest.cc", ] include_dirs = [ "$target_gen_dir" ] deps = [ @@ -285,8 +285,8 @@ ":nt_registry", ":security", ":sha1", - ":whitelist", - ":whitelist_packed_format", + ":third_party_dlls", + ":third_party_packed_list_format", "//base", "//base/test:test_support", "//chrome/common:version_header",
diff --git a/chrome_elf/chrome_elf_x64.def b/chrome_elf/chrome_elf_x64.def index 123b0a6..e1ec2a5 100644 --- a/chrome_elf/chrome_elf_x64.def +++ b/chrome_elf/chrome_elf_x64.def
@@ -18,7 +18,7 @@ RegisterNonABICompliantCodeRange_ExportThunk UnregisterNonABICompliantCodeRange_ExportThunk - ; From chrome_elf/crash_helper.cc + ; From chrome_elf/crash/crash_helper.cc SetMetricsClientId ; From chrome_elf/chrome_elf_main.cc @@ -30,11 +30,11 @@ ; From chrome/install_static GetInstallDetailsPayload - ; From chrome_elf/blacklist.cc + ; From chrome_elf/blacklist/blacklist.cc AddDllToBlacklist IsBlacklistInitialized SuccessfullyBlocked - ; From chrome_elf/whitelist_log + ; From chrome_elf/third_party_dlls/logs DrainLog RegisterLogNotification
diff --git a/chrome_elf/chrome_elf_x86.def b/chrome_elf/chrome_elf_x86.def index abf68b6..be256778 100644 --- a/chrome_elf/chrome_elf_x86.def +++ b/chrome_elf/chrome_elf_x86.def
@@ -14,7 +14,7 @@ RequestSingleCrashUpload_ExportThunk SetUploadConsent_ExportThunk - ; From chrome_elf/crash_helper.cc + ; From chrome_elf/crash/crash_helper.cc SetMetricsClientId ; From chrome_elf/chrome_elf_main.cc @@ -26,11 +26,11 @@ ; From chrome/install_static GetInstallDetailsPayload - ; From chrome_elf/blacklist.cc + ; From chrome_elf/blacklist/blacklist.cc AddDllToBlacklist IsBlacklistInitialized SuccessfullyBlocked - ; From chrome_elf/whitelist_log + ; From chrome_elf/third_party_dlls/logs DrainLog RegisterLogNotification
diff --git a/chrome_elf/whitelist/DEPS b/chrome_elf/third_party_dlls/DEPS similarity index 90% rename from chrome_elf/whitelist/DEPS rename to chrome_elf/third_party_dlls/DEPS index c55f348..b76182d 100644 --- a/chrome_elf/whitelist/DEPS +++ b/chrome_elf/third_party_dlls/DEPS
@@ -8,7 +8,7 @@ "-chrome_elf", "+chrome_elf/nt_registry/nt_registry.h", "+chrome_elf/sha1/sha1.h", - "+chrome_elf/whitelist", + "+chrome_elf/third_party_dlls", ] specific_include_rules = { ".*_unittest\.cc": [
diff --git a/chrome_elf/whitelist/whitelist_ime.cc b/chrome_elf/third_party_dlls/imes.cc similarity index 98% rename from chrome_elf/whitelist/whitelist_ime.cc rename to chrome_elf/third_party_dlls/imes.cc index 37f9234..db96e4df 100644 --- a/chrome_elf/whitelist/whitelist_ime.cc +++ b/chrome_elf/third_party_dlls/imes.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_elf/whitelist/whitelist_ime.h" +#include "chrome_elf/third_party_dlls/imes.h" #include <assert.h> #include <string.h> @@ -14,7 +14,7 @@ #include "chrome_elf/nt_registry/nt_registry.h" -namespace whitelist { +namespace third_party_dlls { namespace { // Holds third-party IME information. @@ -287,4 +287,4 @@ GetImeVector()->clear(); } -} // namespace whitelist +} // namespace third_party_dlls
diff --git a/chrome_elf/whitelist/whitelist_ime.h b/chrome_elf/third_party_dlls/imes.h similarity index 83% rename from chrome_elf/whitelist/whitelist_ime.h rename to chrome_elf/third_party_dlls/imes.h index f286760..9fb5967 100644 --- a/chrome_elf/whitelist/whitelist_ime.h +++ b/chrome_elf/third_party_dlls/imes.h
@@ -2,12 +2,12 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#ifndef CHROME_ELF_WHITELIST_WHITELIST_IME_H_ -#define CHROME_ELF_WHITELIST_WHITELIST_IME_H_ +#ifndef CHROME_ELF_THIRD_PARTY_DLLS_IMES_H_ +#define CHROME_ELF_THIRD_PARTY_DLLS_IMES_H_ #include <stdint.h> -namespace whitelist { +namespace third_party_dlls { // "static_cast<int>(IMEStatus::value)" to access underlying value. enum class IMEStatus { @@ -37,6 +37,6 @@ // Removes initialization for use by tests. void DeinitIMEsForTesting(); -} // namespace whitelist +} // namespace third_party_dlls -#endif // CHROME_ELF_WHITELIST_WHITELIST_IME_H_ +#endif // CHROME_ELF_THIRD_PARTY_DLLS_IMES_H_
diff --git a/chrome_elf/whitelist/whitelist_ime_unittest.cc b/chrome_elf/third_party_dlls/imes_unittest.cc similarity index 94% rename from chrome_elf/whitelist/whitelist_ime_unittest.cc rename to chrome_elf/third_party_dlls/imes_unittest.cc index 046da41..9abf4e3 100644 --- a/chrome_elf/whitelist/whitelist_ime_unittest.cc +++ b/chrome_elf/third_party_dlls/imes_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_elf/whitelist/whitelist_ime.h" +#include "chrome_elf/third_party_dlls/imes.h" #include <windows.h> @@ -13,7 +13,7 @@ #include "sandbox/win/src/nt_internals.h" #include "testing/gtest/include/gtest/gtest.h" -namespace whitelist { +namespace third_party_dlls { namespace { constexpr wchar_t kNewGuid[] = L"{12345678-1234-1234-1234-123456789ABC}"; @@ -96,11 +96,11 @@ } //------------------------------------------------------------------------------ -// Whitelist IME tests +// Third-party IME tests //------------------------------------------------------------------------------ // Test initialization with whatever IMEs are on the current machine. -TEST(Whitelist, IMEInitExisting) { +TEST(ThirdParty, IMEInitExisting) { // Init IME! EXPECT_EQ(InitIMEs(), IMEStatus::kSuccess); DeinitIMEsForTesting(); @@ -110,7 +110,7 @@ // non-Microsoft-provided IMEs. // // Note: Uses registry test override to protect machine from registry writes. -TEST(Whitelist, IMEInitNonMs) { +TEST(ThirdParty, IMEInitNonMs) { // 1. Read in any real registry info needed. // 2. Enable reg override for test net. // 3. Write fake registry data. @@ -140,4 +140,4 @@ } } // namespace -} // namespace whitelist +} // namespace third_party_dlls
diff --git a/chrome_elf/whitelist/whitelist_log.cc b/chrome_elf/third_party_dlls/logs.cc similarity index 96% rename from chrome_elf/whitelist/whitelist_log.cc rename to chrome_elf/third_party_dlls/logs.cc index 5897715..16c1ed1 100644 --- a/chrome_elf/whitelist/whitelist_log.cc +++ b/chrome_elf/third_party_dlls/logs.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_elf/whitelist/whitelist_log.h" +#include "chrome_elf/third_party_dlls/logs.h" #include <windows.h> @@ -12,7 +12,7 @@ #include "chrome_elf/sha1/sha1.h" -namespace whitelist { +namespace third_party_dlls { namespace { enum { kMaxLogEntries = 100, kMaxMutexWaitMs = 5000 }; @@ -204,14 +204,14 @@ g_log_mutex = nullptr; } -} // namespace whitelist +} // namespace third_party_dlls //------------------------------------------------------------------------------ // Exports -// - Function definition in whitelist_packed_format.h +// - Function definition in third_party_packed_list_format.h // - Export declared in chrome_elf_[x64|x86].def //------------------------------------------------------------------------------ -using namespace whitelist; +using namespace third_party_dlls; uint32_t DrainLog(uint8_t* buffer, uint32_t buffer_size,
diff --git a/chrome_elf/whitelist/whitelist_log.h b/chrome_elf/third_party_dlls/logs.h similarity index 75% rename from chrome_elf/whitelist/whitelist_log.h rename to chrome_elf/third_party_dlls/logs.h index a55be5a7..a53b13d5 100644 --- a/chrome_elf/whitelist/whitelist_log.h +++ b/chrome_elf/third_party_dlls/logs.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_ELF_WHITELIST_WHITELIST_LOG_H_ -#define CHROME_ELF_WHITELIST_WHITELIST_LOG_H_ +#ifndef CHROME_ELF_THIRD_PARTY_DLLS_LOGS_H_ +#define CHROME_ELF_THIRD_PARTY_DLLS_LOGS_H_ #include <windows.h> @@ -11,14 +11,14 @@ #include <string> -#include "chrome_elf/whitelist/whitelist_packed_format.h" +#include "chrome_elf/third_party_dlls/packed_list_format.h" -namespace whitelist { +namespace third_party_dlls { // "static_cast<int>(LogStatus::value)" to access underlying value. enum class LogStatus { kSuccess = 0, kCreateMutexFailure = 1, COUNT }; -// Adds a load attempt to the internal load log. +// Adds a module load attempt to the internal load log. // - |log_type| indicates the type of logging. // - |basename_hash| and |code_id_hash| must each point to a 20-byte buffer // holding a SHA-1 digest (of the module's basename and code identifier, @@ -36,6 +36,6 @@ // Removes initialization for use by tests. void DeinitLogsForTesting(); -} // namespace whitelist +} // namespace third_party_dlls -#endif // CHROME_ELF_WHITELIST_WHITELIST_LOG_H_ +#endif // CHROME_ELF_THIRD_PARTY_DLLS_LOGS_H_
diff --git a/chrome_elf/whitelist/whitelist_log_unittest.cc b/chrome_elf/third_party_dlls/logs_unittest.cc similarity index 96% rename from chrome_elf/whitelist/whitelist_log_unittest.cc rename to chrome_elf/third_party_dlls/logs_unittest.cc index 025fe349..4f746b9 100644 --- a/chrome_elf/whitelist/whitelist_log_unittest.cc +++ b/chrome_elf/third_party_dlls/logs_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_elf/whitelist/whitelist_log.h" +#include "chrome_elf/third_party_dlls/logs.h" #include <windows.h> @@ -13,10 +13,10 @@ #include "base/synchronization/waitable_event.h" #include "base/time/time.h" #include "chrome_elf/sha1/sha1.h" -#include "chrome_elf/whitelist/whitelist_packed_format.h" +#include "chrome_elf/third_party_dlls/packed_list_format.h" #include "testing/gtest/include/gtest/gtest.h" -namespace whitelist { +namespace third_party_dlls { namespace { enum { kWaitTimeoutMs = 3000 }; @@ -142,11 +142,11 @@ } //------------------------------------------------------------------------------ -// Whitelist log tests +// Third-party log tests //------------------------------------------------------------------------------ // Test successful initialization and module lookup. -TEST(Whitelist, Logs) { +TEST(ThirdParty, Logs) { // Init. ASSERT_EQ(InitLogs(), LogStatus::kSuccess); @@ -176,7 +176,7 @@ } // Test notifications. -TEST(Whitelist, LogNotifications) { +TEST(ThirdParty, LogNotifications) { // Init. ASSERT_EQ(InitLogs(), LogStatus::kSuccess); @@ -215,4 +215,4 @@ } } // namespace -} // namespace whitelist +} // namespace third_party_dlls
diff --git a/chrome_elf/third_party_dlls/main.cc b/chrome_elf/third_party_dlls/main.cc new file mode 100644 index 0000000..14045f9 --- /dev/null +++ b/chrome_elf/third_party_dlls/main.cc
@@ -0,0 +1,46 @@ +// 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. + +#include "chrome_elf/third_party_dlls/main.h" + +#include <assert.h> + +#include "chrome_elf/nt_registry/nt_registry.h" +#include "chrome_elf/third_party_dlls/imes.h" +#include "chrome_elf/third_party_dlls/logs.h" +#include "chrome_elf/third_party_dlls/packed_list_file.h" + +namespace { + +// Record if all the third-party DLL management code was successfully +// initialized, so processes can easily determine if it is enabled for them. +bool g_third_party_initialized = false; + +} // namespace + +namespace third_party_dlls { + +bool IsThirdPartyInitialized() { + return g_third_party_initialized; +} + +bool Init() { + // Debug check: Init should not be called more than once. + assert(!g_third_party_initialized); + + // TODO(pennymac): As work is added, consider multi-threaded init. + // TODO(pennymac): Handle return status codes for UMA. + if (InitIMEs() != IMEStatus::kSuccess || + InitFromFile() != FileStatus::kSuccess || + InitLogs() != LogStatus::kSuccess) { + return false; + } + + // Record initialization. + g_third_party_initialized = true; + + return true; +} + +} // namespace third_party_dlls
diff --git a/chrome_elf/third_party_dlls/main.h b/chrome_elf/third_party_dlls/main.h new file mode 100644 index 0000000..fdbb950 --- /dev/null +++ b/chrome_elf/third_party_dlls/main.h
@@ -0,0 +1,31 @@ +// 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. + +// Developers: +// - All contents of the third_party_dlls project must be compatible +// with chrome_elf (early loading framework) requirements. +// +// - IMPORTANT: all code executed during Init() must be meet the restrictions +// for DllMain on Windows. +// https://msdn.microsoft.com/en-us/library/windows/desktop/dn633971.aspx + +#ifndef CHROME_ELF_THIRD_PARTY_DLLS_MAIN_H_ +#define CHROME_ELF_THIRD_PARTY_DLLS_MAIN_H_ + +namespace third_party_dlls { + +// Third-party DLL control is enabled and initialized in this process. +bool IsThirdPartyInitialized(); + +// Init Third-Party +// ---------------- +// Central initialization for all third-party DLL management. Users only need to +// include this file, and call this one function at startup. +// - This should be called as early as possible, before any undesirable DLLs +// might be loaded. +bool Init(); + +} // namespace third_party_dlls + +#endif // CHROME_ELF_THIRD_PARTY_DLLS_MAIN_H_
diff --git a/chrome_elf/whitelist/whitelist_file.cc b/chrome_elf/third_party_dlls/packed_list_file.cc similarity index 85% rename from chrome_elf/whitelist/whitelist_file.cc rename to chrome_elf/third_party_dlls/packed_list_file.cc index e0f241a0..63945e4 100644 --- a/chrome_elf/whitelist/whitelist_file.cc +++ b/chrome_elf/third_party_dlls/packed_list_file.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_elf/whitelist/whitelist_file.h" +#include "chrome_elf/third_party_dlls/packed_list_file.h" -#include "windows.h" +#include <windows.h> #include <assert.h> #include <stdio.h> @@ -14,17 +14,17 @@ #include "chrome/install_static/user_data_dir.h" #include "chrome_elf/sha1/sha1.h" -#include "chrome_elf/whitelist/whitelist_packed_format.h" +#include "chrome_elf/third_party_dlls/packed_list_format.h" -namespace whitelist { +namespace third_party_dlls { namespace { // No concern about concurrency control in chrome_elf. bool g_initialized = false; // This will hold a packed blacklist module array, read directly from a -// data file during InitComponent(). -PackedWhitelistModule* g_bl_module_array = nullptr; +// data file during InitFromFile(). +PackedListModule* g_bl_module_array = nullptr; size_t g_bl_module_array_size = 0; // NOTE: this "global" is only initialized once during InitComponent(). @@ -40,8 +40,8 @@ // Binary predicate compare function for use with // std::equal_range/std::is_sorted. Must return TRUE if lhs < rhs. -bool HashBinaryPredicate(const PackedWhitelistModule& lhs, - const PackedWhitelistModule& rhs) { +bool HashBinaryPredicate(const PackedListModule& lhs, + const PackedListModule& rhs) { return elf_sha1::CompareHashes(lhs.basename_hash, rhs.basename_hash) < 0; } @@ -50,18 +50,18 @@ // - Returns kSuccess or kArraySizeZero on success. FileStatus ReadInArray(HANDLE file, size_t* array_size, - PackedWhitelistModule** array_ptr) { - PackedWhitelistMetadata metadata; + PackedListModule** array_ptr) { + PackedListMetadata metadata; DWORD bytes_read = 0; - if (!::ReadFile(file, &metadata, sizeof(PackedWhitelistMetadata), &bytes_read, + if (!::ReadFile(file, &metadata, sizeof(PackedListMetadata), &bytes_read, FALSE) || - bytes_read != sizeof(PackedWhitelistMetadata)) { + bytes_read != sizeof(PackedListMetadata)) { return FileStatus::kMetadataReadFail; } // Careful of versioning. For now, only support the latest version. - if (metadata.version != PackedWhitelistVersion::kCurrent) + if (metadata.version != PackedListVersion::kCurrent) return FileStatus::kInvalidFormatVersion; *array_size = metadata.module_count; @@ -71,15 +71,14 @@ // Sanity check the array fits in a DWORD. if (*array_size > - (std::numeric_limits<DWORD>::max() / sizeof(PackedWhitelistModule))) { + (std::numeric_limits<DWORD>::max() / sizeof(PackedListModule))) { assert(false); return FileStatus::kArrayTooBig; } DWORD buffer_size = - static_cast<DWORD>(*array_size * sizeof(PackedWhitelistModule)); - *array_ptr = - reinterpret_cast<PackedWhitelistModule*>(new uint8_t[buffer_size]); + static_cast<DWORD>(*array_size * sizeof(PackedListModule)); + *array_ptr = reinterpret_cast<PackedListModule*>(new uint8_t[buffer_size]); // Read in the array. // NOTE: Ignore the rest of the file - other data could be stored at the end. @@ -178,7 +177,7 @@ std::string code_id(buffer); code_id = elf_sha1::SHA1HashString(code_id); std::string basename_hash = elf_sha1::SHA1HashString(basename); - PackedWhitelistModule target = {}; + PackedListModule target = {}; ::memcpy(target.basename_hash, basename_hash.data(), elf_sha1::kSHA1Length); ::memcpy(target.code_id_hash, code_id.data(), elf_sha1::kSHA1Length); @@ -189,7 +188,7 @@ target, HashBinaryPredicate); // Search for secondary hash. - for (PackedWhitelistModule* i = pair.first; i != pair.second; ++i) { + for (PackedListModule* i = pair.first; i != pair.second; ++i) { if (!elf_sha1::CompareHashes(target.code_id_hash, i->code_id_hash)) return true; } @@ -202,7 +201,7 @@ return GetBlFilePath(); } -// Grab the latest whitelist and blacklist. +// Grab the latest module list(s) from file. FileStatus InitFromFile() { // Debug check: InitFromFile should not be called more than once. assert(!g_initialized); @@ -232,4 +231,4 @@ g_initialized = false; } -} // namespace whitelist +} // namespace third_party_dlls
diff --git a/chrome_elf/whitelist/whitelist_file.h b/chrome_elf/third_party_dlls/packed_list_file.h similarity index 74% rename from chrome_elf/whitelist/whitelist_file.h rename to chrome_elf/third_party_dlls/packed_list_file.h index b16ec744..1dc3bd1 100644 --- a/chrome_elf/whitelist/whitelist_file.h +++ b/chrome_elf/third_party_dlls/packed_list_file.h
@@ -2,14 +2,14 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#ifndef CHROME_ELF_WHITELIST_WHITELIST_FILE_H_ -#define CHROME_ELF_WHITELIST_WHITELIST_FILE_H_ +#ifndef CHROME_ELF_THIRD_PARTY_DLLS_PACKED_LIST_FILE_H_ +#define CHROME_ELF_THIRD_PARTY_DLLS_PACKED_LIST_FILE_H_ -#include "windows.h" +#include <windows.h> #include <string> -namespace whitelist { +namespace third_party_dlls { // "static_cast<int>(FileStatus::value)" to access underlying value. enum class FileStatus { @@ -28,7 +28,7 @@ }; // Look up a binary based on the required data points. -// - Returns true if match found in the blacklist. I.E. Block if true. +// - Returns true if match found in the list. bool IsModuleListed(const std::string& basename, DWORD image_size, DWORD time_date_stamp); @@ -36,7 +36,7 @@ // Get the full path of the blacklist file used. std::wstring GetBlFilePathUsed(); -// Initialize internal whitelist from file. +// Initialize internal module list from file. FileStatus InitFromFile(); // Overrides the blacklist path for use by tests. @@ -45,6 +45,6 @@ // Removes initialization for use by tests. void DeinitFromFileForTesting(); -} // namespace whitelist +} // namespace third_party_dlls -#endif // CHROME_ELF_WHITELIST_WHITELIST_FILE_H_ +#endif // CHROME_ELF_THIRD_PARTY_DLLS_PACKED_LIST_FILE_H_
diff --git a/chrome_elf/whitelist/whitelist_file_unittest.cc b/chrome_elf/third_party_dlls/packed_list_file_unittest.cc similarity index 87% rename from chrome_elf/whitelist/whitelist_file_unittest.cc rename to chrome_elf/third_party_dlls/packed_list_file_unittest.cc index 6aa1e84..68e9eae 100644 --- a/chrome_elf/whitelist/whitelist_file_unittest.cc +++ b/chrome_elf/third_party_dlls/packed_list_file_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_elf/whitelist/whitelist_file.h" +#include "chrome_elf/third_party_dlls/packed_list_file.h" #include <windows.h> @@ -17,10 +17,10 @@ #include "base/win/pe_image.h" #include "chrome/install_static/user_data_dir.h" #include "chrome_elf/sha1/sha1.h" -#include "chrome_elf/whitelist/whitelist_packed_format.h" +#include "chrome_elf/third_party_dlls/packed_list_format.h" #include "testing/gtest/include/gtest/gtest.h" -namespace whitelist { +namespace third_party_dlls { namespace { constexpr wchar_t kTestBlFileName[] = L"blfile"; @@ -33,7 +33,7 @@ }; bool GetTestModules(std::vector<TestModule>* test_modules, - std::vector<PackedWhitelistModule>* packed_modules) { + std::vector<PackedListModule>* packed_modules) { // Test binaries in system32/syswow64. // Define them in hash order so that the resulting array is ordered! // ole32 = 65 6e 16..., gdi32 = 91 7a e5..., crypt32 = ce ab 70... @@ -76,7 +76,7 @@ code_id = elf_sha1::SHA1HashString(code_id); basename_hash = elf_sha1::SHA1HashString(test_module.basename); - PackedWhitelistModule packed_module; + PackedListModule packed_module; ::memcpy(packed_module.code_id_hash, code_id.data(), elf_sha1::kSHA1Length); ::memcpy(packed_module.basename_hash, basename_hash.data(), elf_sha1::kSHA1Length); @@ -87,12 +87,12 @@ } //------------------------------------------------------------------------------ -// WhitelistFileTest class +// ThirdPartyFileTest class //------------------------------------------------------------------------------ -class WhitelistFileTest : public testing::Test { +class ThirdPartyFileTest : public testing::Test { protected: - WhitelistFileTest() = default; + ThirdPartyFileTest() = default; void SetUp() override { ASSERT_TRUE(GetTestModules(&test_array_, &test_packed_array_)); @@ -119,14 +119,14 @@ ASSERT_TRUE(file.IsValid()); // Write content {metadata}{array_of_modules}. - PackedWhitelistMetadata meta = { + PackedListMetadata meta = { kInitialVersion, static_cast<uint32_t>(test_packed_array_.size())}; ASSERT_EQ(file.Write(0, reinterpret_cast<const char*>(&meta), sizeof(meta)), static_cast<int>(sizeof(meta))); - int size = static_cast<int>(test_packed_array_.size() * - sizeof(PackedWhitelistModule)); + int size = + static_cast<int>(test_packed_array_.size() * sizeof(PackedListModule)); ASSERT_EQ( - file.Write(sizeof(PackedWhitelistMetadata), + file.Write(sizeof(PackedListMetadata), reinterpret_cast<const char*>(test_packed_array_.data()), size), size); @@ -146,17 +146,17 @@ base::File bl_file_; base::string16 bl_test_file_path_; std::vector<TestModule> test_array_; - std::vector<PackedWhitelistModule> test_packed_array_; + std::vector<PackedListModule> test_packed_array_; - DISALLOW_COPY_AND_ASSIGN(WhitelistFileTest); + DISALLOW_COPY_AND_ASSIGN(ThirdPartyFileTest); }; //------------------------------------------------------------------------------ -// Whitelist file tests +// Third-party file tests //------------------------------------------------------------------------------ // Test successful initialization and module lookup. -TEST_F(WhitelistFileTest, Success) { +TEST_F(ThirdPartyFileTest, Success) { // Create blacklist data file. CreateTestFile(); @@ -174,19 +174,19 @@ } // Test successful initialization with no packed files. -TEST_F(WhitelistFileTest, NoFiles) { +TEST_F(ThirdPartyFileTest, NoFiles) { ASSERT_EQ(InitFromFile(), FileStatus::kSuccess); EXPECT_FALSE(IsModuleListed("booya.dll", 1337, 0x12345678)); } -TEST_F(WhitelistFileTest, CorruptFile) { +TEST_F(ThirdPartyFileTest, CorruptFile) { CreateTestFile(); base::File* file = GetBlFile(); ASSERT_TRUE(file->IsValid()); // 1) Not enough data for array size - PackedWhitelistMetadata meta = {kCurrent, static_cast<uint32_t>(50)}; + PackedListMetadata meta = {kCurrent, static_cast<uint32_t>(50)}; ASSERT_EQ(file->Write(0, reinterpret_cast<const char*>(&meta), sizeof(meta)), static_cast<int>(sizeof(meta))); EXPECT_EQ(InitFromFile(), FileStatus::kArrayReadFail); @@ -207,4 +207,4 @@ } } // namespace -} // namespace whitelist +} // namespace third_party_dlls
diff --git a/chrome_elf/whitelist/whitelist_packed_format.cc b/chrome_elf/third_party_dlls/packed_list_format.cc similarity index 85% rename from chrome_elf/whitelist/whitelist_packed_format.cc rename to chrome_elf/third_party_dlls/packed_list_format.cc index 9d75a6e1..87090bf 100644 --- a/chrome_elf/whitelist/whitelist_packed_format.cc +++ b/chrome_elf/third_party_dlls/packed_list_format.cc
@@ -2,11 +2,11 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#include "chrome_elf/whitelist/whitelist_packed_format.h" +#include "chrome_elf/third_party_dlls/packed_list_format.h" #include <stddef.h> -namespace whitelist { +namespace third_party_dlls { // Subdir relative to install_static::GetUserDataDirectory(). const wchar_t kFileSubdir[] = @@ -27,4 +27,4 @@ return ((offsetof(LogEntry, path) + path_len + 4) & ~3U); } -} // namespace whitelist +} // namespace third_party_dlls
diff --git a/chrome_elf/whitelist/whitelist_packed_format.h b/chrome_elf/third_party_dlls/packed_list_format.h similarity index 71% rename from chrome_elf/whitelist/whitelist_packed_format.h rename to chrome_elf/third_party_dlls/packed_list_format.h index 210d9c3..00e0ea26 100644 --- a/chrome_elf/whitelist/whitelist_packed_format.h +++ b/chrome_elf/third_party_dlls/packed_list_format.h
@@ -2,28 +2,27 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -// This source set defines shared expectations for the module load -// whitelist/blacklist (WL/BL). -// 1. The BL packed data file format used to pass information from chrome.dll +// This source set defines shared expectations for: +// 1. The packed-data format used to pass information from chrome.dll // to chrome_elf.dll across restarts. // 2. The APIs exported by chrome_elf.dll to share logs of module load attempts. -#ifndef CHROME_ELF_WHITELIST_WHITELIST_PACKED_FORMAT_H_ -#define CHROME_ELF_WHITELIST_WHITELIST_PACKED_FORMAT_H_ +#ifndef CHROME_ELF_THIRD_PARTY_DLLS_PACKED_LIST_FORMAT_H_ +#define CHROME_ELF_THIRD_PARTY_DLLS_PACKED_LIST_FORMAT_H_ #include <windows.h> #include <stdint.h> -namespace whitelist { +namespace third_party_dlls { // ----------------------------------------------------------------------------- -// This defines the expected contents of a packed whitelist file. -// - At offset 0 of the file: {PackedWhitelistMetadata} -// - Immediately following: {Array of PackedWhitelistModule} +// This defines the expected format for a packed list of third-party modules. +// - At offset 0: {PackedListMetadata} +// - Immediately following: {Array of PackedListModule} // - Anything else can be stored in the rest of the file. // -// - It's a requirement that the file be packed little-endian and also that +// - It's a requirement that the list be packed little-endian and also that // 32-bit alignment == 64-bit alignment (so no handling required). // - It's also required that the array be *sorted*. First by basename hash, // second by code_id hash (there can be multiple of the same basename hash). @@ -32,25 +31,25 @@ // Subdir relative to install_static::GetUserDataDirectory(). extern const wchar_t kFileSubdir[]; -// Packed module data cache file. +// Packed module list cache file. extern const wchar_t kBlFileName[]; -enum PackedWhitelistVersion : uint32_t { +enum PackedListVersion : uint32_t { kInitialVersion = 1, kCurrent = kInitialVersion, kUnsupported }; -struct PackedWhitelistMetadata { - // The version of the packed whitelist format. This should always be ordered +struct PackedListMetadata { + // The version of the packed list format. This should always be ordered // first for backward compatibility purposes. - PackedWhitelistVersion version; - // The number of PackedWhitelistModule elements that follows the metadata in - // the packed whitelist file. + PackedListVersion version; + // The number of PackedListModule elements that follows the metadata in + // the packed list. uint32_t module_count; }; -struct PackedWhitelistModule { +struct PackedListModule { // SHA1 of lowercase basename (no path). uint8_t basename_hash[20]; // Code ID. This is equivalent to the string generated by formatting @@ -62,14 +61,14 @@ uint32_t time_date_stamp; }; -// These struct are directly written to a file. Therefore the padding should -// be consistent across compilations. -static_assert(sizeof(PackedWhitelistMetadata) == 8, - "The actual padding of the PackedWhitelistMetadata struct " - "doesn't match the expected padding"); -static_assert(sizeof(PackedWhitelistModule) == 44, - "The actual padding of the PackedWhitelistModule struct doesn't " +// These structs are directly written to a storage type. Therefore the padding +// should be consistent across compilations. +static_assert(sizeof(PackedListMetadata) == 8, + "The actual padding of the PackedListMetadata struct doesn't" "match the expected padding"); +static_assert(sizeof(PackedListModule) == 44, + "The actual padding of the PackedListModule struct doesn't match" + "the expected padding"); //------------------------------------------------------------------------------ // chrome_elf log API @@ -114,7 +113,7 @@ // } uint32_t GetLogEntrySize(uint32_t path_len); -} // namespace whitelist +} // namespace third_party_dlls // Exported API for calling from outside chrome_elf.dll. // Drains the load attempt LogEntries into the provided buffer. @@ -129,12 +128,12 @@ uint32_t* log_remaining); // Exported API for calling from outside chrome_elf.dll. -// Register an event to be notified when whitelist logs are available via -// DrainLog API. +// Register an event to be notified when load-attempt logs are available +// via DrainLog API. // - Pass in a HANDLE to an event created via ::CreateEvent(), or nullptr to // clear. // - This function will duplicate |event_handle|, and call ::SetEvent() when any -// new whitelist log is added. +// new load-attempt log is added. extern "C" bool RegisterLogNotification(HANDLE event_handle); -#endif // CHROME_ELF_WHITELIST_WHITELIST_PACKED_FORMAT_H_ +#endif // CHROME_ELF_THIRD_PARTY_DLLS_PACKED_LIST_FORMAT_H_
diff --git a/chrome_elf/whitelist/whitelist.cc b/chrome_elf/whitelist/whitelist.cc deleted file mode 100644 index 6410552b..0000000 --- a/chrome_elf/whitelist/whitelist.cc +++ /dev/null
@@ -1,46 +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. - -#include "chrome_elf/whitelist/whitelist.h" - -#include <assert.h> - -#include "chrome_elf/nt_registry/nt_registry.h" -#include "chrome_elf/whitelist/whitelist_file.h" -#include "chrome_elf/whitelist/whitelist_ime.h" -#include "chrome_elf/whitelist/whitelist_log.h" - -namespace { - -// Record if the whitelist was successfully initialized so processes can easily -// determine if the whitelist is enabled for them. -bool g_whitelist_initialized = false; - -} // namespace - -namespace whitelist { - -bool IsWhitelistInitialized() { - return g_whitelist_initialized; -} - -bool Init() { - // Debug check: Init should not be called more than once. - assert(!g_whitelist_initialized); - - // TODO(pennymac): As work is added, consider multi-threaded init. - // TODO(pennymac): Handle return status codes for UMA. - if (InitIMEs() != IMEStatus::kSuccess || - InitFromFile() != FileStatus::kSuccess || - InitLogs() != LogStatus::kSuccess) { - return false; - } - - // Record initialization. - g_whitelist_initialized = true; - - return true; -} - -} // namespace whitelist
diff --git a/chrome_elf/whitelist/whitelist.h b/chrome_elf/whitelist/whitelist.h deleted file mode 100644 index db002cf..0000000 --- a/chrome_elf/whitelist/whitelist.h +++ /dev/null
@@ -1,32 +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. - -// Developers: -// - All contents of the whitelist project must be compatible -// with chrome_elf (early loading framework) requirements. -// -// - IMPORTANT: all code executed during Init() must be meet the restrictions -// for DllMain on Windows. -// https://msdn.microsoft.com/en-us/library/windows/desktop/dn633971.aspx - -#ifndef CHROME_ELF_WHITELIST_WHITELIST_H_ -#define CHROME_ELF_WHITELIST_WHITELIST_H_ - -namespace whitelist { - -// Whitelist support is enabled and initialized in this process. -bool IsWhitelistInitialized(); - -// Init Whitelist -// -------------- -// Central initialization for all whitelist sources. Users of the whitelist -// only need to include this file, and call this one function at startup. -// -// Initializes the DLL whitelist in the current process. This should be called -// before any undesirable DLLs might be loaded. -bool Init(); - -} // namespace whitelist - -#endif // CHROME_ELF_WHITELIST_WHITELIST_H_
diff --git a/chromecast/browser/BUILD.gn b/chromecast/browser/BUILD.gn index 7b7d0a5a..56a2fef1 100644 --- a/chromecast/browser/BUILD.gn +++ b/chromecast/browser/BUILD.gn
@@ -102,6 +102,7 @@ "//chromecast/media/service", "//chromecast/net", "//chromecast/service", + "//components/download/public/common:public", "//components/metrics", "//components/metrics:gpu", "//components/metrics:net",
diff --git a/chromecast/browser/DEPS b/chromecast/browser/DEPS index 511a65d..6081648 100644 --- a/chromecast/browser/DEPS +++ b/chromecast/browser/DEPS
@@ -9,6 +9,7 @@ "+chromecast/service", "+components/cdm/browser", "+components/crash", + "+components/download/public/common", "+components/keyed_service", "+components/network_hints/browser", "+components/network_session_configurator/common",
diff --git a/chromecast/browser/android/apk/src/org/chromium/chromecast/shell/CastCrashUploader.java b/chromecast/browser/android/apk/src/org/chromium/chromecast/shell/CastCrashUploader.java index f78f170..01c1a894 100644 --- a/chromecast/browser/android/apk/src/org/chromium/chromecast/shell/CastCrashUploader.java +++ b/chromecast/browser/android/apk/src/org/chromium/chromecast/shell/CastCrashUploader.java
@@ -47,7 +47,7 @@ private final String mCrashReportUploadUrl; private final String mUuid; private final String mApplicationFeedback; - private final Runnable mQueueAllCrashDumpUploadsRunnable = () -> queueAllCrashDumpUploads(); + private final Runnable mQueueAllCrashDumpUploadsRunnable = () -> checkForCrashDumps(); public CastCrashUploader(ScheduledExecutorService executorService, ElidedLogcatProvider logcatProvider, String crashDumpPath, String uuid, @@ -92,16 +92,20 @@ * @param synchronous Whether or not this function should block on queued uploads * @param log Log to include, if any */ - private void queueAllCrashDumpUploads() { + private void checkForCrashDumps() { if (mCrashDumpPath == null) return; Log.i(TAG, "Checking for crash dumps"); - - mLogcatProvider.getElidedLogcat((String logs) -> queueAllCrashDumpUploadsWithLogs(logs)); - } - - private void queueAllCrashDumpUploadsWithLogs(String logs) { File crashDumpDirectory = new File(mCrashDumpPath); + int numCrashDumps = crashDumpDirectory.listFiles().length; + if (numCrashDumps > 0) { + Log.i(TAG, numCrashDumps + " crash dumps found"); + mLogcatProvider.getElidedLogcat( + (String logs) -> queueAllCrashDumpUploadsWithLogs(crashDumpDirectory, logs)); + } + } + + private void queueAllCrashDumpUploadsWithLogs(File crashDumpDirectory, String logs) { for (final File potentialDump : crashDumpDirectory.listFiles()) { String dumpName = potentialDump.getName(); if (dumpName.matches(DUMP_FILE_REGEX)) {
diff --git a/chromecast/browser/android/apk/src/org/chromium/chromecast/shell/CastWebContentsActivity.java b/chromecast/browser/android/apk/src/org/chromium/chromecast/shell/CastWebContentsActivity.java index 234dc2a..545a14b 100644 --- a/chromecast/browser/android/apk/src/org/chromium/chromecast/shell/CastWebContentsActivity.java +++ b/chromecast/browser/android/apk/src/org/chromium/chromecast/shell/CastWebContentsActivity.java
@@ -96,6 +96,10 @@ protected void handleIntent(Intent intent) { final Bundle bundle = intent.getExtras(); + if (bundle == null) { + Log.i(TAG, "Intent without bundle received!"); + return; + } final String uriString = bundle.getString(CastWebContentsComponent.INTENT_EXTRA_URI); if (uriString == null) { Log.i(TAG, "Intent without uri received!");
diff --git a/chromecast/browser/android/apk/src/org/chromium/chromecast/shell/CastWebContentsSurfaceHelper.java b/chromecast/browser/android/apk/src/org/chromium/chromecast/shell/CastWebContentsSurfaceHelper.java index e23d6f10..d7eff8e6 100644 --- a/chromecast/browser/android/apk/src/org/chromium/chromecast/shell/CastWebContentsSurfaceHelper.java +++ b/chromecast/browser/android/apk/src/org/chromium/chromecast/shell/CastWebContentsSurfaceHelper.java
@@ -154,7 +154,7 @@ mHandler.postDelayed(new Runnable() { @Override public void run() { - if (currentInstanceId.equals(mInstanceId)) { + if (currentInstanceId != null && currentInstanceId.equals(mInstanceId)) { Log.d(TAG, "Finishing."); if (mShowInFragment) { Intent in = new Intent();
diff --git a/chromecast/browser/android/apk/src/org/chromium/chromecast/shell/ExternalServiceDeviceLogcatProvider.java b/chromecast/browser/android/apk/src/org/chromium/chromecast/shell/ExternalServiceDeviceLogcatProvider.java index c9ba86f..8117aa9 100644 --- a/chromecast/browser/android/apk/src/org/chromium/chromecast/shell/ExternalServiceDeviceLogcatProvider.java +++ b/chromecast/browser/android/apk/src/org/chromium/chromecast/shell/ExternalServiceDeviceLogcatProvider.java
@@ -8,6 +8,7 @@ import android.content.Context; import android.content.Intent; import android.content.ServiceConnection; +import android.os.AsyncTask; import android.os.IBinder; import android.os.RemoteException; @@ -42,27 +43,41 @@ public void onServiceConnected(ComponentName name, IBinder service) { Log.i(TAG, "onServiceConnected for this"); IDeviceLogsProvider provider = IDeviceLogsProvider.Stub.asInterface(service); - CircularBuffer<String> rawLogcat = new CircularBuffer<>(BuildConfig.LOGCAT_SIZE); - try { - String logsFileName = provider.getLogs(); - Log.i(TAG, "Log Location: " + logsFileName); - try (BufferedReader bReader = - new BufferedReader(new FileReader(logsFileName))) { - String logLn; - while ((logLn = bReader.readLine()) != null) { - rawLogcat.add(logLn); + ServiceConnection conn = this; + new AsyncTask<Void, Void, CircularBuffer<String>>() { + @Override + public CircularBuffer<String> doInBackground(Void... params) { + CircularBuffer<String> rawLogcat = + new CircularBuffer<>(BuildConfig.LOGCAT_SIZE); + try { + // getLogs() currently gives us the filename of the location of the logs + String logsFileName = provider.getLogs(); + Log.i(TAG, "Log Location: " + logsFileName); + + try (BufferedReader bReader = + new BufferedReader(new FileReader(logsFileName))) { + String logLn; + while ((logLn = bReader.readLine()) != null) { + rawLogcat.add(logLn); + } + } catch (IOException e) { + Log.e(TAG, "Can't read logs", e); + } + } catch (RemoteException e) { + Log.e(TAG, "Can't get logs", e); + } finally { + ContextUtils.getApplicationContext().unbindService(conn); + return rawLogcat; } - } catch (IOException e) { - Log.e(TAG, "Can't get logs", e); } - } catch (RemoteException e) { - Log.e(TAG, "Can't get logs", e); - } finally { - ContextUtils.getApplicationContext().unbindService(this); - callback.onLogsDone(rawLogcat); + @Override + public void onPostExecute(CircularBuffer<String> rawLogcat) { + callback.onLogsDone(rawLogcat); + } } + .execute(); } @Override
diff --git a/chromecast/browser/cast_download_manager_delegate.cc b/chromecast/browser/cast_download_manager_delegate.cc index 201eab65..fc2cba5 100644 --- a/chromecast/browser/cast_download_manager_delegate.cc +++ b/chromecast/browser/cast_download_manager_delegate.cc
@@ -8,7 +8,7 @@ #include "base/files/file_path.h" #include "base/logging.h" -#include "content/public/browser/download_danger_type.h" +#include "components/download/public/common/download_danger_type.h" #include "content/public/browser/download_interrupt_reasons.h" #include "content/public/browser/download_item.h" @@ -31,7 +31,7 @@ const content::DownloadTargetCallback& callback) { base::FilePath empty; callback.Run(empty, content::DownloadItem::TARGET_DISPOSITION_OVERWRITE, - content::DOWNLOAD_DANGER_TYPE_MAYBE_DANGEROUS_CONTENT, empty, + download::DOWNLOAD_DANGER_TYPE_MAYBE_DANGEROUS_CONTENT, empty, content::DOWNLOAD_INTERRUPT_REASON_USER_CANCELED); return true; }
diff --git a/chromeos/chromeos_switches.cc b/chromeos/chromeos_switches.cc index dc1ee9aa..451f0de 100644 --- a/chromeos/chromeos_switches.cc +++ b/chromeos/chromeos_switches.cc
@@ -508,6 +508,10 @@ // Interval at which we check for total time on OOBE. const char kOobeTimerInterval[] = "oobe-timer-interval"; +// If set to "true", the profile requires policy during restart (policy load +// must succeed, otherwise session restart should fail). +const char kProfileRequiresPolicy[] = "profile-requires-policy"; + // Overrides network stub behavior. By default, ethernet, wifi and vpn are // enabled, and transitions occur instantaneously. Multiple options can be // comma separated (no spaces). Note: all options are in the format 'foo=x'. @@ -556,6 +560,14 @@ // List of locales supported by voice interaction. const char kVoiceInteractionLocales[] = "voice-interaction-supported-locales"; +// Used to tell the policy infrastructure to not let profile initialization +// complete until policy is manually set by a test. This is used to provide +// backward compatibility with a few tests that incorrectly use the +// synchronously-initialized login profile to run their tests - do not add new +// uses of this flag. +const char kWaitForInitialPolicyFetchForTest[] = + "wait-for-initial-policy-fetch-for-test"; + // Enables wake on wifi packet feature, which wakes the device on the receipt // of network packets from whitelisted sources. const char kWakeOnWifiPacket[] = "wake-on-wifi-packet";
diff --git a/chromeos/chromeos_switches.h b/chromeos/chromeos_switches.h index bde54f2..3c81137c 100644 --- a/chromeos/chromeos_switches.h +++ b/chromeos/chromeos_switches.h
@@ -145,6 +145,7 @@ CHROMEOS_EXPORT extern const char kOobeSkipPostLogin[]; CHROMEOS_EXPORT extern const char kOobeSkipToLogin[]; CHROMEOS_EXPORT extern const char kOobeTimerInterval[]; +CHROMEOS_EXPORT extern const char kProfileRequiresPolicy[]; CHROMEOS_EXPORT extern const char kShillStub[]; CHROMEOS_EXPORT extern const char kShowLoginDevOverlay[]; CHROMEOS_EXPORT extern const char kShowNonMdLogin[]; @@ -154,6 +155,7 @@ CHROMEOS_EXPORT extern const char kTestEncryptionMigrationUI[]; CHROMEOS_EXPORT extern const char kTetherStub[]; CHROMEOS_EXPORT extern const char kVoiceInteractionLocales[]; +CHROMEOS_EXPORT extern const char kWaitForInitialPolicyFetchForTest[]; CHROMEOS_EXPORT extern const char kWakeOnWifiPacket[]; // Returns true if the system should wake in response to wifi traffic.
diff --git a/chromeos/components/tether/host_scanner_operation.cc b/chromeos/components/tether/host_scanner_operation.cc index 4301879..4bd33ec 100644 --- a/chromeos/components/tether/host_scanner_operation.cc +++ b/chromeos/components/tether/host_scanner_operation.cc
@@ -64,8 +64,11 @@ return false; return response->response_code() == - TetherAvailabilityResponse_ResponseCode:: - TetherAvailabilityResponse_ResponseCode_NOTIFICATIONS_DISABLED; + TetherAvailabilityResponse_ResponseCode:: + TetherAvailabilityResponse_ResponseCode_NOTIFICATIONS_DISABLED_LEGACY || + response->response_code() == + TetherAvailabilityResponse_ResponseCode:: + TetherAvailabilityResponse_ResponseCode_NOTIFICATIONS_DISABLED_WITH_NOTIFICATION_CHANNEL; } } // namespace @@ -181,7 +184,7 @@ PA_LOG(INFO) << "Received TetherAvailabilityResponse from device with ID " << remote_device.GetTruncatedDeviceIdForLogs() << " which " << "indicates that Google Play Services notifications are " - << "disabled."; + << "disabled. Response code: " << response->response_code(); gms_core_notifications_disabled_devices_.push_back(remote_device); NotifyObserversOfScannedDeviceList(false /* is_final_scan_result */); } else if (!IsTetheringAvailableWithValidDeviceStatus(response)) {
diff --git a/chromeos/components/tether/host_scanner_operation_unittest.cc b/chromeos/components/tether/host_scanner_operation_unittest.cc index 9a1b7b99..a1b5b37 100644 --- a/chromeos/components/tether/host_scanner_operation_unittest.cc +++ b/chromeos/components/tether/host_scanner_operation_unittest.cc
@@ -325,14 +325,27 @@ } TEST_F(HostScannerOperationTest, - TestOperation_OneDevice_NotificationsDisabled) { + TestOperation_OneDevice_NotificationsDisabled_Legacy) { EXPECT_CALL(*mock_tether_host_response_recorder_, RecordSuccessfulTetherAvailabilityResponse(_)) .Times(0); TestOperationWithOneDevice( TetherAvailabilityResponse_ResponseCode :: - TetherAvailabilityResponse_ResponseCode_NOTIFICATIONS_DISABLED); + TetherAvailabilityResponse_ResponseCode_NOTIFICATIONS_DISABLED_LEGACY); + EXPECT_EQ(std::vector<cryptauth::RemoteDevice>{test_devices_[0]}, + test_observer_->gms_core_notifications_disabled_devices()); +} + +TEST_F(HostScannerOperationTest, + TestOperation_OneDevice_NotificationsDisabled_NotificationChannel) { + EXPECT_CALL(*mock_tether_host_response_recorder_, + RecordSuccessfulTetherAvailabilityResponse(_)) + .Times(0); + + TestOperationWithOneDevice( + TetherAvailabilityResponse_ResponseCode :: + TetherAvailabilityResponse_ResponseCode_NOTIFICATIONS_DISABLED_WITH_NOTIFICATION_CHANNEL); EXPECT_EQ(std::vector<cryptauth::RemoteDevice>{test_devices_[0]}, test_observer_->gms_core_notifications_disabled_devices()); }
diff --git a/chromeos/components/tether/proto/tether.proto b/chromeos/components/tether/proto/tether.proto index f8809db..651fc1e 100644 --- a/chromeos/components/tether/proto/tether.proto +++ b/chromeos/components/tether/proto/tether.proto
@@ -63,7 +63,7 @@ // Next id: 1 message TetherAvailabilityRequest {} -// Next id: 6 +// Next id: 7 message TetherAvailabilityResponse { enum ResponseCode { UNKNOWN_ERROR = 0; @@ -71,7 +71,8 @@ SETUP_NEEDED = 2; NO_RECEPTION = 3; NO_SIM_CARD = 4; - NOTIFICATIONS_DISABLED = 5; + NOTIFICATIONS_DISABLED_LEGACY = 5; + NOTIFICATIONS_DISABLED_WITH_NOTIFICATION_CHANNEL = 6; } optional ResponseCode response_code = 1;
diff --git a/chromeos/components/tether/wifi_hotspot_connector_unittest.cc b/chromeos/components/tether/wifi_hotspot_connector_unittest.cc index bab264f..93bf5380 100644 --- a/chromeos/components/tether/wifi_hotspot_connector_unittest.cc +++ b/chromeos/components/tether/wifi_hotspot_connector_unittest.cc
@@ -96,10 +96,6 @@ } // NetworkConnect: - bool MaybeShowConfigureUI(const std::string& network_id, - const std::string& connect_error) override { - return false; - } void SetTechnologyEnabled(const chromeos::NetworkTypePattern& technology, bool enabled_state) override {} void ShowMobileSetup(const std::string& network_id) override {}
diff --git a/chromeos/dbus/fake_smb_provider_client.cc b/chromeos/dbus/fake_smb_provider_client.cc index 1dace416..15877f3 100644 --- a/chromeos/dbus/fake_smb_provider_client.cc +++ b/chromeos/dbus/fake_smb_provider_client.cc
@@ -88,4 +88,12 @@ FROM_HERE, base::BindOnce(std::move(callback), smbprovider::ERROR_OK)); } +void FakeSmbProviderClient::Truncate(int32_t mount_id, + const base::FilePath& file_path, + int64_t length, + StatusCallback callback) { + base::ThreadTaskRunnerHandle::Get()->PostTask( + FROM_HERE, base::BindOnce(std::move(callback), smbprovider::ERROR_OK)); +} + } // namespace chromeos
diff --git a/chromeos/dbus/fake_smb_provider_client.h b/chromeos/dbus/fake_smb_provider_client.h index 392068f7..487b2c3 100644 --- a/chromeos/dbus/fake_smb_provider_client.h +++ b/chromeos/dbus/fake_smb_provider_client.h
@@ -49,6 +49,11 @@ const base::FilePath& file_path, StatusCallback callback) override; + void Truncate(int32_t mount_id, + const base::FilePath& file_path, + int64_t length, + StatusCallback callback) override; + private: DISALLOW_COPY_AND_ASSIGN(FakeSmbProviderClient); };
diff --git a/chromeos/dbus/proto/media_perception.proto b/chromeos/dbus/proto/media_perception.proto index 265dd38..ec3e88f 100644 --- a/chromeos/dbus/proto/media_perception.proto +++ b/chromeos/dbus/proto/media_perception.proto
@@ -20,6 +20,10 @@ // A single FramePerception message or array of perceptions (if reporting the // results from multiple frames). repeated FramePerception frame_perception = 2; + + // A single AudioPerception message or array of audio perceptions (if + // reporting the results from multiple audio frames). + repeated AudioPerception audio_perception = 3; } // Used to transmit a history of image frames and their associated annotations. @@ -72,8 +76,55 @@ // This is the output of the MediaPerceptionSinkCalculator. message PerceptionSample { optional FramePerception frame_perception = 1; + // The image frame data associated with the frame perception. optional ImageFrame image_frame = 2; + + optional AudioPerception audio_perception = 3; +} + +// Audio perception results for an audio frame. +message AudioPerception { + // A timestamp in microseconds attached when this message was generated. + optional uint64 timestamp_us = 1; + + // Audio localization results for an audio frame. + optional AudioLocalization audio_localization = 2; + + // Human presence detection results for an audio frame. + optional AudioHumanPresenceDetection audio_human_presence_detection = 3; +} + +// An estimate of the direction that the sound is coming from. +message AudioLocalization { + // An angle in radians in the horizontal plane. It roughly points to the peak + // in the probability distribution of azimuth defined below. + optional double azimuth_radians = 1; + + // A probability distribution for the current snapshot in time that shows the + // likelihood of a sound source being at a particular azimuth. For example, + // azimuthScores = [0.1, 0.2, 0.3, 0.4] means that the probability that the + // sound is coming from an azimuth of 0, pi/2, pi, 3*pi/2 is 0.1, 0.2, 0.3 and + // 0.4, respectively. + repeated double azimuth_scores = 2; +} + +// Detection of human presence close to the microphone. +message AudioHumanPresenceDetection { + // Indicates a probability in [0, 1] interval that a human has caused a sound + // close to the microphone. + optional double human_presence_likelihood = 1; + + // Estimate of the noise spectrogram. + optional AudioSpectrogram noise_spectrogram = 2; + + // Spectrogram of an audio frame. + optional AudioSpectrogram frame_spectrogram = 3; +} + +// Spectrogram of an audio frame. +message AudioSpectrogram { + repeated double values = 1; } // This message stores the image frame along with the meta data. @@ -106,6 +157,50 @@ // Latency measurement for a list of packet streams in drishti graph. repeated PacketLatency packet_latency = 6; + + // Human presence detection results for a video frame. + optional VideoHumanPresenceDetection video_human_presence_detection = 7; +} + +// Detection of human presence close to the camera. +message VideoHumanPresenceDetection { + // Indicates a probability in [0, 1] interval that a human is present in the + // video frame. + optional double human_presence_likelihood = 1; + + // Indicates a probability in [0, 1] interval that motion has been detected + // in the video frame. + optional double motion_detected_likelihood = 2; + + // Type of lighting conditions. + enum LightCondition { + UNSPECIFIED = 0; + + // No noticeable change occurred. + NO_CHANGE = 1; + + // Light was switched on in the room. + TURNED_ON = 2; + + // Light was switched off in the room. + TURNED_OFF = 3; + + // Light gradually got dimmer (for example, due to a sunset). + DIMMER = 4; + + // Light gradually got brighter (for example, due to a sunrise). + BRIGHTER = 5; + + // Black frame detected - the current frame contains only noise. + BLACK_FRAME = 6; + } + + // Indicates lighting condition in the video frame. + optional LightCondition light_condition = 3; + + // Indicates a probability in [0, 1] interval that light condition value is + // correct. + optional double light_condition_likelihood = 4; } message Entity {
diff --git a/chromeos/dbus/smb_provider_client.cc b/chromeos/dbus/smb_provider_client.cc index 9de599a..e26086ac 100644 --- a/chromeos/dbus/smb_provider_client.cc +++ b/chromeos/dbus/smb_provider_client.cc
@@ -148,6 +148,18 @@ &SmbProviderClientImpl::HandleCreateFileCallback, &callback); } + void Truncate(int32_t mount_id, + const base::FilePath& file_path, + int64_t length, + StatusCallback callback) override { + smbprovider::TruncateOptionsProto options; + options.set_mount_id(mount_id); + options.set_file_path(file_path.value()); + options.set_length(length); + CallMethod(smbprovider::kTruncateMethod, options, + &SmbProviderClientImpl::HandleTruncateCallback, &callback); + } + protected: // DBusClient override. void Init(dbus::Bus* bus) override { @@ -287,6 +299,17 @@ std::move(callback).Run(GetErrorFromReader(&reader)); } + // Handles D-Bus callback for Truncate. + void HandleTruncateCallback(StatusCallback callback, + dbus::Response* response) { + if (!response) { + DLOG(ERROR) << "Truncate: failed to call smbprovider"; + std::move(callback).Run(smbprovider::ERROR_DBUS_PARSE_FAILED); + } + dbus::MessageReader reader(response); + std::move(callback).Run(GetErrorFromReader(&reader)); + } + // Handles D-Bus responses for methods that return an error and a protobuf // object. template <class T>
diff --git a/chromeos/dbus/smb_provider_client.h b/chromeos/dbus/smb_provider_client.h index e4de2c7..65ac690 100644 --- a/chromeos/dbus/smb_provider_client.h +++ b/chromeos/dbus/smb_provider_client.h
@@ -102,6 +102,13 @@ const base::FilePath& file_path, StatusCallback callback) = 0; + // Calls Truncate. Using the corresponding mount |mount_id|, this truncates + // the file in |file_path| to the desired |length|. + virtual void Truncate(int32_t mount_id, + const base::FilePath& file_path, + int64_t length, + StatusCallback callback) = 0; + protected: // Create() should be used instead. SmbProviderClient();
diff --git a/chromeos/network/network_configuration_handler.cc b/chromeos/network/network_configuration_handler.cc index 0262d73..9e4bd3dc 100644 --- a/chromeos/network/network_configuration_handler.cc +++ b/chromeos/network/network_configuration_handler.cc
@@ -286,6 +286,9 @@ LogConfigProperties("SetProperty", service_path, *properties_to_set); + // Clear error state when setting Shill properties. + network_state_handler_->ClearLastErrorForNetwork(service_path); + std::unique_ptr<base::DictionaryValue> properties_copy( properties_to_set->DeepCopy()); DBusThreadManager::Get()->GetShillServiceClient()->SetProperties(
diff --git a/chromeos/network/network_connect.cc b/chromeos/network/network_connect.cc index 13abf33c..f6bbf34 100644 --- a/chromeos/network/network_connect.cc +++ b/chromeos/network/network_connect.cc
@@ -53,8 +53,6 @@ // NetworkConnect void ConnectToNetworkId(const std::string& network_id) override; void DisconnectFromNetworkId(const std::string& network_id) override; - bool MaybeShowConfigureUI(const std::string& network_id, - const std::string& connect_error) override; void SetTechnologyEnabled(const NetworkTypePattern& technology, bool enabled_state) override; void ShowMobileSetup(const std::string& network_id) override; @@ -73,8 +71,6 @@ void OnConnectFailed(const std::string& network_id, const std::string& error_name, std::unique_ptr<base::DictionaryValue> error_data); - bool MaybeShowConfigureUIImpl(const std::string& network_id, - const std::string& connect_error); bool GetNetworkProfilePath(bool shared, std::string* profile_path); void OnConnectSucceeded(const std::string& network_id); void CallConnectToNetwork(const std::string& network_id, @@ -194,42 +190,22 @@ const std::string& network_id, const std::string& error_name, std::unique_ptr<base::DictionaryValue> error_data) { - MaybeShowConfigureUIImpl(network_id, error_name); -} + NET_LOG(ERROR) << "Connect Failed: " << error_name << " For: " << network_id; -// This handles connect failures that are a direct result of a user initiated -// connect request and result in a new UI being shown. Note: notifications are -// handled by NetworkStateNotifier. -bool NetworkConnectImpl::MaybeShowConfigureUIImpl( - const std::string& network_id, - const std::string& connect_error) { - NET_LOG_ERROR("Connect Failed: " + connect_error, network_id); - - if (connect_error == NetworkConnectionHandler::kErrorBadPassphrase || - connect_error == NetworkConnectionHandler::kErrorPassphraseRequired || - connect_error == NetworkConnectionHandler::kErrorConfigurationRequired || - connect_error == NetworkConnectionHandler::kErrorAuthenticationRequired) { + if (error_name == NetworkConnectionHandler::kErrorConnectFailed || + error_name == NetworkConnectionHandler::kErrorBadPassphrase || + error_name == NetworkConnectionHandler::kErrorPassphraseRequired || + error_name == NetworkConnectionHandler::kErrorConfigurationRequired || + error_name == NetworkConnectionHandler::kErrorAuthenticationRequired) { HandleUnconfiguredNetwork(network_id); - return true; - } - - if (connect_error == NetworkConnectionHandler::kErrorCertificateRequired) { + } else if (error_name == + NetworkConnectionHandler::kErrorCertificateRequired) { + // If ShowEnrollNetwork does fails, treat as an unconfigured network. if (!delegate_->ShowEnrollNetwork(network_id)) HandleUnconfiguredNetwork(network_id); - return true; } - - // Only show a configure dialog if there was a ConnectFailed error. The dialog - // allows the user to request a new connect attempt or cancel. Note: a - // notification may also be displayed by NetworkStateNotifier in this case. - if (connect_error == NetworkConnectionHandler::kErrorConnectFailed) { - HandleUnconfiguredNetwork(network_id); - return true; - } - // Notifications for other connect failures are handled by // NetworkStateNotifier, so no need to do anything else here. - return false; } void NetworkConnectImpl::OnConnectSucceeded(const std::string& network_id) { @@ -413,12 +389,6 @@ base::Bind(&IgnoreDisconnectError)); } -bool NetworkConnectImpl::MaybeShowConfigureUI( - const std::string& network_id, - const std::string& connect_error) { - return MaybeShowConfigureUIImpl(network_id, connect_error); -} - void NetworkConnectImpl::SetTechnologyEnabled( const NetworkTypePattern& technology, bool enabled_state) {
diff --git a/chromeos/network/network_connect.h b/chromeos/network/network_connect.h index c837995..ad09d1b1 100644 --- a/chromeos/network/network_connect.h +++ b/chromeos/network/network_connect.h
@@ -71,11 +71,6 @@ // Requests a network disconnection. Ignores any errors and notifications. virtual void DisconnectFromNetworkId(const std::string& network_id) = 0; - // Maybe show the configuration UI after a connect failure based on the - // network state and error name. Returns true if the UI is shown. - virtual bool MaybeShowConfigureUI(const std::string& network_id, - const std::string& connect_error) = 0; - // Enables or disables a network technology. If |technology| refers to // cellular and the device cannot be enabled due to a SIM lock, this function // will launch the SIM unlock dialog.
diff --git a/chromeos/network/network_connect_unittest.cc b/chromeos/network/network_connect_unittest.cc index be242d7..91c62f9 100644 --- a/chromeos/network/network_connect_unittest.cc +++ b/chromeos/network/network_connect_unittest.cc
@@ -213,62 +213,6 @@ false); } -TEST_F(NetworkConnectTest, ShowConfigureUI) { - EXPECT_CALL(*mock_delegate_, ShowNetworkConfigure(kWiFi1Guid)).Times(5); - - NetworkConnect::Get()->MaybeShowConfigureUI( - kWiFi1Guid, NetworkConnectionHandler::kErrorBadPassphrase); - NetworkConnect::Get()->MaybeShowConfigureUI( - kWiFi1Guid, NetworkConnectionHandler::kErrorPassphraseRequired); - NetworkConnect::Get()->MaybeShowConfigureUI( - kWiFi1Guid, NetworkConnectionHandler::kErrorConfigurationRequired); - NetworkConnect::Get()->MaybeShowConfigureUI( - kWiFi1Guid, NetworkConnectionHandler::kErrorAuthenticationRequired); - NetworkConnect::Get()->MaybeShowConfigureUI( - kWiFi1Guid, NetworkConnectionHandler::kErrorConnectFailed); -} - -TEST_F(NetworkConnectTest, ConfigureUINotShownForTetherAssociatedWifiNetwork) { - // The configure UI should *not* be shown for Wi-Fi networks which serve as - // the underlying Wi-Fi hotspot for a Tether network. - EXPECT_CALL(*mock_delegate_, ShowNetworkConfigure(kWiFi1Guid)).Times(0); - - AddTetherNetwork(false /* has_connected_to_host */); - NetworkHandler::Get() - ->network_state_handler() - ->AssociateTetherNetworkStateWithWifiNetwork(kTetherGuid, kWiFi1Guid); - - NetworkConnect::Get()->MaybeShowConfigureUI( - kWiFi1Guid, NetworkConnectionHandler::kErrorConnectFailed); -} - -TEST_F(NetworkConnectTest, ShowConfigureUI_BadErrorCode) { - EXPECT_CALL(*mock_delegate_, ShowNetworkConfigure(kWiFi1Guid)).Times(0); - - NetworkConnect::Get()->MaybeShowConfigureUI(kWiFi1Guid, - "incorrect error code"); -} - -TEST_F(NetworkConnectTest, ShowConfigureUI_CertRequired_ShowEnrollNetwork) { - EXPECT_CALL(*mock_delegate_, ShowEnrollNetwork(_)).Times(AnyNumber()); - EXPECT_CALL(*mock_delegate_, ShowNetworkConfigure(kWiFi1Guid)).Times(0); - - NetworkConnect::Get()->MaybeShowConfigureUI( - kWiFi1Guid, NetworkConnectionHandler::kErrorCertificateRequired); -} - -TEST_F(NetworkConnectTest, - ShowConfigureUI_CertRequired_DoNotShowEnrollNetwork) { - EXPECT_CALL(*mock_delegate_, ShowEnrollNetwork(_)).Times(AnyNumber()); - EXPECT_CALL(*mock_delegate_, ShowNetworkConfigure(kWiFi1Guid)); - - ON_CALL(*mock_delegate_, ShowEnrollNetwork(kWiFi1Guid)) - .WillByDefault(Return(false)); - - NetworkConnect::Get()->MaybeShowConfigureUI( - kWiFi1Guid, NetworkConnectionHandler::kErrorCertificateRequired); -} - TEST_F(NetworkConnectTest, ConnectThenDisconnectWiFiNetwork) { const NetworkState* network = NetworkHandler::Get()->network_state_handler()->GetNetworkStateFromGuid( @@ -304,26 +248,6 @@ fake_tether_delegate_->last_connected_tether_network_guid().empty()); } -// ShowNetworkSettings only applies to cellular networks. -TEST_F(NetworkConnectTest, ShowNetworkSettings) { - EXPECT_CALL(*mock_delegate_, ShowNetworkSettings(kCellular1Guid)); - - NetworkConnect::Get()->MaybeShowConfigureUI( - kCellular1Guid, NetworkConnectionHandler::kErrorConnectFailed); -} - -TEST_F(NetworkConnectTest, ShowNetworkSettings_CellOutOfCredits) { - EXPECT_CALL(*mock_delegate_, ShowNetworkSettings(kCellular1Guid)).Times(0); - EXPECT_CALL(*mock_delegate_, ShowMobileSetupDialog(kCellular1Guid)); - - service_test_->SetServiceProperty( - kCellular1ServicePath, shill::kOutOfCreditsProperty, base::Value(true)); - base::RunLoop().RunUntilIdle(); - - NetworkConnect::Get()->MaybeShowConfigureUI( - kCellular1Guid, NetworkConnectionHandler::kErrorConnectFailed); -} - TEST_F(NetworkConnectTest, ActivateCellular) { EXPECT_CALL(*mock_delegate_, ShowMobileSetupDialog(kCellular1Guid));
diff --git a/chromeos/network/network_state_handler.cc b/chromeos/network/network_state_handler.cc index 506e964..d97792db 100644 --- a/chromeos/network/network_state_handler.cc +++ b/chromeos/network/network_state_handler.cc
@@ -36,7 +36,7 @@ namespace { -bool ConnectionStateChanged(NetworkState* network, +bool ConnectionStateChanged(const NetworkState* network, const std::string& prev_connection_state, bool prev_is_captive_portal) { if (network->is_captive_portal() != prev_is_captive_portal) @@ -992,11 +992,11 @@ true /* configured_only */, false /* visible_only */, 1 /* limit */, &list); if (list.empty()) { - NET_LOG_ERROR("GetEAPForEthernet", - base::StringPrintf( - "Ethernet service %s connected using EAP, but no " - "EAP service found.", - service_path.c_str())); + NET_LOG_ERROR( + "GetEAPForEthernet", + base::StringPrintf("Ethernet service %s connected using EAP, but no " + "EAP service found.", + service_path.c_str())); return nullptr; } return list.front(); @@ -1152,6 +1152,7 @@ const std::string& service_path, const std::string& key, const base::Value& value) { + DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); SCOPED_NET_LOG_IF_SLOW(); bool changed = false; NetworkState* network = GetModifiableNetworkState(service_path); @@ -1168,15 +1169,22 @@ // gets created. bool request_update = prev_profile_path.empty() && !network->profile_path().empty(); - + bool sort_networks = false; bool notify_default = network->path() == default_network_path_; + bool notify_connection_state = false; if (key == shill::kStateProperty || key == shill::kVisibleProperty) { network_list_sorted_ = false; if (ConnectionStateChanged(network, prev_connection_state, prev_is_captive_portal)) { - if (OnNetworkConnectionStateChanged(network)) - notify_default = false; // already notified + notify_connection_state = true; + if (notify_default) + notify_default = VerifyDefaultNetworkConnectionStateChange(network); + // If the default network connection state changed, sort networks now + // and ensure that a default cellular network exists. + if (notify_default) + sort_networks = true; + // If the connection state changes, other properties such as IPConfig // may have changed, so request a full update. request_update = true; @@ -1202,9 +1210,13 @@ } LogPropertyUpdated(network, key, value); + if (notify_connection_state) + NotifyNetworkConnectionStateChanged(network); if (notify_default) - NotifyDefaultNetworkChanged(network); + NotifyDefaultNetworkChanged(); NotifyNetworkPropertiesUpdated(network); + if (sort_networks) + SortNetworkList(true /* ensure_cellular */); } void NetworkStateHandler::UpdateDeviceProperty(const std::string& device_path, @@ -1253,7 +1265,7 @@ network->IPConfigPropertiesChanged(properties); NotifyNetworkPropertiesUpdated(network); if (network->path() == default_network_path_) - NotifyDefaultNetworkChanged(network); + NotifyDefaultNetworkChanged(); } else if (type == ManagedState::MANAGED_TYPE_DEVICE) { DeviceState* device = GetModifiableDeviceState(path); if (!device) @@ -1265,7 +1277,7 @@ GetNetworkState(default_network_path_); if (default_network && default_network->device_path() == path) { NotifyNetworkPropertiesUpdated(default_network); - NotifyDefaultNetworkChanged(default_network); + NotifyDefaultNetworkChanged(); } } } @@ -1435,7 +1447,7 @@ // connection state changes. return; } - NotifyDefaultNetworkChanged(network); + NotifyDefaultNetworkChanged(); } //------------------------------------------------------------------------------ @@ -1586,31 +1598,42 @@ return nullptr; } -bool NetworkStateHandler::OnNetworkConnectionStateChanged( +void NetworkStateHandler::OnNetworkConnectionStateChanged( NetworkState* network) { - SCOPED_NET_LOG_IF_SLOW(); DCHECK(network); - bool notify_default = false; - if (network->path() == default_network_path_) { - if (network->IsConnectedState()) { - notify_default = true; - } else if (network->IsConnectingState()) { - // Wait until the network is actually connected to notify that the default - // network changed. - NET_LOG(EVENT) << "Default network is not connected: " - << GetLogName(network) - << "State: " << network->connection_state(); - } else { - NET_LOG(ERROR) << "Default network in unexpected state: " - << GetLogName(network) - << "State: " << network->connection_state(); - default_network_path_.clear(); - SortNetworkList(true /* ensure_cellular */); - NotifyDefaultNetworkChanged(nullptr); - } + bool default_changed = false; + if (network->path() == default_network_path_) + default_changed = VerifyDefaultNetworkConnectionStateChange(network); + NotifyNetworkConnectionStateChanged(network); + if (default_changed) + NotifyDefaultNetworkChanged(); +} + +bool NetworkStateHandler::VerifyDefaultNetworkConnectionStateChange( + NetworkState* network) { + DCHECK(network->path() == default_network_path_); + if (network->IsConnectedState()) + return true; + if (network->IsConnectingState()) { + // Wait until the network is actually connected to notify that the default + // network changed. + NET_LOG(EVENT) << "Default network is connecting: " << GetLogName(network) + << "State: " << network->connection_state(); + return false; } + NET_LOG(ERROR) << "Default network in unexpected state: " + << GetLogName(network) + << "State: " << network->connection_state(); + default_network_path_.clear(); + return true; +} + +void NetworkStateHandler::NotifyNetworkConnectionStateChanged( + NetworkState* network) { + DCHECK(network); + SCOPED_NET_LOG_IF_SLOW(); std::string desc = "NetworkConnectionStateChanged"; - if (notify_default) + if (network->path() == default_network_path_) desc = "Default" + desc; NET_LOG(EVENT) << "NOTIFY: " << desc << ": " << GetLogName(network) << ": " << network->connection_state(); @@ -1618,14 +1641,19 @@ for (auto& observer : observers_) observer.NetworkConnectionStateChanged(network); notifying_network_observers_ = false; - if (notify_default) - NotifyDefaultNetworkChanged(network); - return notify_default; } -void NetworkStateHandler::NotifyDefaultNetworkChanged( - const NetworkState* default_network) { +void NetworkStateHandler::NotifyDefaultNetworkChanged() { SCOPED_NET_LOG_IF_SLOW(); + // If the default network is in an invalid state, |default_network_path_| + // will be cleared; call DefaultNetworkChanged(nullptr). + const NetworkState* default_network; + if (default_network_path_.empty()) { + default_network = nullptr; + } else { + default_network = GetModifiableNetworkState(default_network_path_); + DCHECK(default_network) << "No default network: " << default_network_path_; + } NET_LOG_EVENT("NOTIFY:DefaultNetworkChanged", GetLogName(default_network)); notifying_network_observers_ = true; for (auto& observer : observers_)
diff --git a/chromeos/network/network_state_handler.h b/chromeos/network/network_state_handler.h index cfb6e212..f236a4a 100644 --- a/chromeos/network/network_state_handler.h +++ b/chromeos/network/network_state_handler.h
@@ -468,12 +468,20 @@ // Gets the list specified by |type|. ManagedStateList* GetManagedList(ManagedState::ManagedType type); - // Helper function to notify observers. Calls CheckDefaultNetworkChanged(). - // Returns true if NotifyDefaultNetworkChanged() was called. - bool OnNetworkConnectionStateChanged(NetworkState* network); + // Helper function that calls NotifyNetworkConnectionStateChanged and, + // for the default network, OnDefaultNetworkConnectionStateChanged and + // NotifyDefaultNetworkChanged. + void OnNetworkConnectionStateChanged(NetworkState* network); + + // Verifies the connection state of the default network. Returns false + // if the connection state change should be ignored. + bool VerifyDefaultNetworkConnectionStateChange(NetworkState* network); + + // Notifies observers when a network's connection state changes. + void NotifyNetworkConnectionStateChanged(NetworkState* network); // Notifies observers when the default network or its properties change. - void NotifyDefaultNetworkChanged(const NetworkState* default_network); + void NotifyDefaultNetworkChanged(); // Notifies observers about changes to |network|, including IPConfg. void NotifyNetworkPropertiesUpdated(const NetworkState* network);
diff --git a/components/BUILD.gn b/components/BUILD.gn index e27827d1..680fe6d4 100644 --- a/components/BUILD.gn +++ b/components/BUILD.gn
@@ -98,6 +98,7 @@ "//components/json_schema:unit_tests", "//components/keyed_service/core:unit_tests", "//components/language/core/browser:unit_tests", + "//components/language/core/common:unit_tests", "//components/language_usage_metrics:unit_tests", "//components/leveldb_proto:unit_tests", "//components/login:unit_tests", @@ -153,6 +154,7 @@ "//components/url_matcher:unit_tests", "//components/url_pattern_index:unit_tests", "//components/variations:unit_tests", + "//components/variations/field_trial_config:unit_tests", "//components/variations/service:unit_tests", "//components/web_resource:unit_tests", "//components/webdata/common:unit_tests",
diff --git a/components/assist_ranker/OWNERS b/components/assist_ranker/OWNERS index 5f847a5..36ad72d71e 100644 --- a/components/assist_ranker/OWNERS +++ b/components/assist_ranker/OWNERS
@@ -1,2 +1,3 @@ +charleszhao@chromium.org hamelphi@chromium.org -rogerm@chromium.org \ No newline at end of file +rogerm@chromium.org
diff --git a/components/assist_ranker/ranker_model_loader_impl.cc b/components/assist_ranker/ranker_model_loader_impl.cc index b45cb45..e03529f 100644 --- a/components/assist_ranker/ranker_model_loader_impl.cc +++ b/components/assist_ranker/ranker_model_loader_impl.cc
@@ -121,6 +121,7 @@ // There was no configured model path. Switch the state to IDLE and // fall through to consider the URL. state_ = LoaderState::IDLE; + FALLTHROUGH; case LoaderState::IDLE: if (model_url_.is_valid()) { StartLoadFromURL(); @@ -129,6 +130,7 @@ // There was no configured model URL. Switch the state to FINISHED and // fall through. state_ = LoaderState::FINISHED; + FALLTHROUGH; case LoaderState::FINISHED: case LoaderState::LOADING_FROM_FILE: case LoaderState::LOADING_FROM_URL:
diff --git a/components/autofill/content/renderer/form_tracker.cc b/components/autofill/content/renderer/form_tracker.cc index 97d2e2a..dd73f186b 100644 --- a/components/autofill/content/renderer/form_tracker.cc +++ b/components/autofill/content/renderer/form_tracker.cc
@@ -154,8 +154,8 @@ ui::PageTransition type = navigation_state->GetTransitionType(); if (ui::PageTransitionIsWebTriggerable(type) && ui::PageTransitionIsNewNavigation(type) && - !blink::WebUserGestureIndicator::IsProcessingUserGesture( - navigated_frame)) { + !ui::PageTransitionTypeIncludingQualifiersIs(type, + ui::PAGE_TRANSITION_LINK)) { FireProbablyFormSubmitted(); } }
diff --git a/components/autofill/content/renderer/page_passwords_analyser.cc b/components/autofill/content/renderer/page_passwords_analyser.cc index 7a6c1a5c..0f32b13 100644 --- a/components/autofill/content/renderer/page_passwords_analyser.cc +++ b/components/autofill/content/renderer/page_passwords_analyser.cc
@@ -371,8 +371,9 @@ } else { // By default (if the other heuristics fail), the first text field // preceding a password field will be considered the username field. - for (username_field_guess = password_inputs[0] - 1;; + for (username_field_guess = explicit_password_inputs[0] - 1;; --username_field_guess) { + DCHECK(username_field_guess < signature.size()); if (signature[username_field_guess] == kTextFieldSignature) break; }
diff --git a/components/browser_sync/profile_sync_service.cc b/components/browser_sync/profile_sync_service.cc index f76497cf..2beb364 100644 --- a/components/browser_sync/profile_sync_service.cc +++ b/components/browser_sync/profile_sync_service.cc
@@ -605,7 +605,7 @@ UMA_HISTOGRAM_ENUMERATION("Sync.SyncAuthError", AUTH_ERROR_ENCOUNTERED, AUTH_ERROR_LIMIT); } - // Fallthrough. + FALLTHROUGH; } default: { if (error.state() != GoogleServiceAuthError::INVALID_GAIA_CREDENTIALS) {
diff --git a/components/browser_sync/profile_sync_test_util.cc b/components/browser_sync/profile_sync_test_util.cc index 06011dc..6a174e93 100644 --- a/components/browser_sync/profile_sync_test_util.cc +++ b/components/browser_sync/profile_sync_test_util.cc
@@ -13,7 +13,6 @@ #include "components/history/core/browser/history_model_worker.h" #include "components/history/core/browser/history_service.h" #include "components/pref_registry/pref_registry_syncable.h" -#include "components/signin/core/browser/profile_management_switches.h" #include "components/signin/core/browser/signin_manager_base.h" #include "components/sync/base/sync_prefs.h" #include "components/sync/driver/signin_manager_wrapper.h" @@ -176,7 +175,6 @@ AccountTrackerService::RegisterPrefs(registry); SigninManagerBase::RegisterProfilePrefs(registry); SigninManagerBase::RegisterPrefs(registry); - signin::RegisterAccountConsistencyProfilePrefs(registry); } ProfileSyncServiceBundle::SyncClientBuilder::~SyncClientBuilder() = default; @@ -241,7 +239,6 @@ url_request_context_(new net::TestURLRequestContextGetter( base::ThreadTaskRunnerHandle::Get())) { RegisterPrefsForProfileSyncService(pref_service_.registry()); - signin::SetGaiaOriginIsolatedCallback(base::Bind([] { return true; })); auth_service_.set_auto_post_fetch_response_on_message_loop(true); account_tracker_.Initialize(&signin_client_); signin_manager_.Initialize(&pref_service_);
diff --git a/components/browser_watcher/BUILD.gn b/components/browser_watcher/BUILD.gn index 6ec8d23..59683c59 100644 --- a/components/browser_watcher/BUILD.gn +++ b/components/browser_watcher/BUILD.gn
@@ -49,20 +49,18 @@ "postmortem_minidump_writer_win.cc", "postmortem_report_collector.cc", "postmortem_report_collector.h", - "system_session_analyzer_win.cc", - "system_session_analyzer_win.h", ] deps = [ ":stability_client", ":stability_common", ":stability_report_proto", "//base", + "//components/metrics:metrics", "//components/variations", "//third_party/crashpad/crashpad/client", "//third_party/crashpad/crashpad/minidump", "//third_party/crashpad/crashpad/util", ] - libs = [ "wevtapi.lib" ] ldflags = [ "/DELAYLOAD:wevtapi.dll" ] # Only used after unclean shutdowns. } @@ -128,7 +126,6 @@ "stability_debugging_win_unittest.cc", "stability_paths_unittest.cc", "stability_report_extractor_unittest.cc", - "system_session_analyzer_win_unittest.cc", "watcher_client_win_unittest.cc", "watcher_metrics_provider_win_unittest.cc", "window_hang_monitor_win_unittest.cc", @@ -143,6 +140,7 @@ ":stability_report_proto", "//base", "//base/test:test_support", + "//components/metrics:metrics", "//testing/gmock", "//testing/gtest", "//third_party/crashpad/crashpad/client", @@ -171,6 +169,7 @@ deps = [ ":postmortem_stability", "//base", + "//components/metrics:metrics", ] } }
diff --git a/components/browser_watcher/fetch_system_session_events_main_win.cc b/components/browser_watcher/fetch_system_session_events_main_win.cc index 2f17b933..ff54b973 100644 --- a/components/browser_watcher/fetch_system_session_events_main_win.cc +++ b/components/browser_watcher/fetch_system_session_events_main_win.cc
@@ -9,11 +9,11 @@ #include "base/logging.h" #include "base/strings/stringprintf.h" #include "base/time/time.h" -#include "components/browser_watcher/system_session_analyzer_win.h" +#include "components/metrics/system_session_analyzer_win.h" namespace { -using browser_watcher::SystemSessionAnalyzer; +using metrics::SystemSessionAnalyzer; class SystemSessionEventFetcher : public SystemSessionAnalyzer { public:
diff --git a/components/browser_watcher/postmortem_report_collector.cc b/components/browser_watcher/postmortem_report_collector.cc index d59b526c..2eedc2c 100644 --- a/components/browser_watcher/postmortem_report_collector.cc +++ b/components/browser_watcher/postmortem_report_collector.cc
@@ -60,14 +60,14 @@ } // namespace PostmortemReportCollector::PostmortemReportCollector( - SystemSessionAnalyzer* analyzer) + metrics::SystemSessionAnalyzer* analyzer) : report_database_(nullptr), system_session_analyzer_(analyzer) {} PostmortemReportCollector::PostmortemReportCollector( const std::string& product_name, const std::string& version_number, const std::string& channel_name, crashpad::CrashReportDatabase* report_database, - SystemSessionAnalyzer* analyzer) + metrics::SystemSessionAnalyzer* analyzer) : product_name_(product_name), version_number_(version_number), channel_name_(channel_name), @@ -193,19 +193,19 @@ } else if (!system_session_analyzer_) { status = SYSTEM_SESSION_ANALYSIS_NO_ANALYZER; } else { - SystemSessionAnalyzer::Status analyzer_status = + metrics::SystemSessionAnalyzer::Status analyzer_status = system_session_analyzer_->IsSessionUnclean(time); switch (analyzer_status) { - case SystemSessionAnalyzer::FAILED: + case metrics::SystemSessionAnalyzer::FAILED: status = SYSTEM_SESSION_ANALYSIS_FAILED; break; - case SystemSessionAnalyzer::CLEAN: + case metrics::SystemSessionAnalyzer::CLEAN: session_state = SystemState::CLEAN; break; - case SystemSessionAnalyzer::UNCLEAN: + case metrics::SystemSessionAnalyzer::UNCLEAN: session_state = SystemState::UNCLEAN; break; - case SystemSessionAnalyzer::OUTSIDE_RANGE: + case metrics::SystemSessionAnalyzer::OUTSIDE_RANGE: status = SYSTEM_SESSION_ANALYSIS_OUTSIDE_RANGE; break; }
diff --git a/components/browser_watcher/postmortem_report_collector.h b/components/browser_watcher/postmortem_report_collector.h index 09a3284..367250a 100644 --- a/components/browser_watcher/postmortem_report_collector.h +++ b/components/browser_watcher/postmortem_report_collector.h
@@ -23,7 +23,7 @@ #include "base/strings/string16.h" #include "components/browser_watcher/stability_report.pb.h" #include "components/browser_watcher/stability_report_extractor.h" -#include "components/browser_watcher/system_session_analyzer_win.h" +#include "components/metrics/system_session_analyzer_win.h" #include "third_party/crashpad/crashpad/client/crash_report_database.h" namespace browser_watcher { @@ -39,12 +39,12 @@ // crash reports. If |report_database| is set, postmortem crash reports are // generated and registered against it. If |analyzer| is set, it used to // analyze the containing system session. - PostmortemReportCollector(SystemSessionAnalyzer* analyzer); + PostmortemReportCollector(metrics::SystemSessionAnalyzer* analyzer); PostmortemReportCollector(const std::string& product_name, const std::string& version_number, const std::string& channel_name, crashpad::CrashReportDatabase* report_database, - SystemSessionAnalyzer* analyzer); + metrics::SystemSessionAnalyzer* analyzer); ~PostmortemReportCollector(); // Analyzes |stability_files|, logs postmortem user metrics and optionally @@ -104,7 +104,7 @@ std::string channel_name_; crashpad::CrashReportDatabase* report_database_; // Not owned. - SystemSessionAnalyzer* system_session_analyzer_; // Not owned. + metrics::SystemSessionAnalyzer* system_session_analyzer_; // Not owned. DISALLOW_COPY_AND_ASSIGN(PostmortemReportCollector); };
diff --git a/components/browser_watcher/postmortem_report_collector_unittest.cc b/components/browser_watcher/postmortem_report_collector_unittest.cc index 9192551a..8d24e84c 100644 --- a/components/browser_watcher/postmortem_report_collector_unittest.cc +++ b/components/browser_watcher/postmortem_report_collector_unittest.cc
@@ -28,6 +28,7 @@ #include "base/threading/platform_thread.h" #include "components/browser_watcher/stability_data_names.h" #include "components/browser_watcher/stability_report_extractor.h" +#include "components/metrics/system_session_analyzer_win.h" #include "testing/gmock/include/gmock/gmock.h" #include "testing/gtest/include/gtest/gtest.h" #include "third_party/crashpad/crashpad/client/crash_report_database.h" @@ -119,7 +120,7 @@ base::PlatformFile minidump_file)); }; -class MockSystemSessionAnalyzer : public SystemSessionAnalyzer { +class MockSystemSessionAnalyzer : public metrics::SystemSessionAnalyzer { public: MockSystemSessionAnalyzer() : SystemSessionAnalyzer(10U) {} MOCK_METHOD1(IsSessionUnclean, Status(base::Time timestamp)); @@ -361,7 +362,7 @@ EXPECT_CALL(analyzer, IsSessionUnclean(base::Time::FromInternalValue(12345LL))) .Times(1) - .WillOnce(Return(SystemSessionAnalyzer::CLEAN)); + .WillOnce(Return(metrics::SystemSessionAnalyzer::CLEAN)); MockCrashReportDatabase crash_db; PostmortemReportCollector collector(kProductName, kVersionNumber, kChannelName, &crash_db, &analyzer);
diff --git a/components/browser_watcher/watcher_metrics_provider_win.cc b/components/browser_watcher/watcher_metrics_provider_win.cc index 2e842e3..3850f07f 100644 --- a/components/browser_watcher/watcher_metrics_provider_win.cc +++ b/components/browser_watcher/watcher_metrics_provider_win.cc
@@ -29,7 +29,7 @@ #include "components/browser_watcher/features.h" #include "components/browser_watcher/postmortem_report_collector.h" #include "components/browser_watcher/stability_paths.h" -#include "components/browser_watcher/system_session_analyzer_win.h" +#include "components/metrics/system_session_analyzer_win.h" #include "third_party/crashpad/crashpad/client/crash_report_database.h" namespace browser_watcher { @@ -285,7 +285,7 @@ LogCollectionInitStatus(INIT_SUCCESS); const size_t kSystemSessionsToInspect = 5U; - SystemSessionAnalyzer analyzer(kSystemSessionsToInspect); + metrics::SystemSessionAnalyzer analyzer(kSystemSessionsToInspect); if (should_collect) { base::string16 product_name, version_number, channel_name;
diff --git a/components/content_settings/core/browser/host_content_settings_map.cc b/components/content_settings/core/browser/host_content_settings_map.cc index ab44dae..f41087e7 100644 --- a/components/content_settings/core/browser/host_content_settings_map.cc +++ b/components/content_settings/core/browser/host_content_settings_map.cc
@@ -223,6 +223,7 @@ default_provider->AddObserver(this); content_settings_providers_[DEFAULT_PROVIDER] = std::move(default_provider); + InitializePluginsDataSettings(); RecordExceptionMetrics(); } @@ -533,6 +534,10 @@ return weak_ptr_factory_.GetWeakPtr(); } +void HostContentSettingsMap::SetClockForTesting(base::Clock* clock) { + pref_provider_->SetClockForTesting(clock); +} + void HostContentSettingsMap::RecordExceptionMetrics() { for (const content_settings::WebsiteSettingsInfo* info : *content_settings::WebsiteSettingsRegistry::GetInstance()) { @@ -849,6 +854,32 @@ return std::unique_ptr<base::Value>(); } -void HostContentSettingsMap::SetClockForTesting(base::Clock* clock) { - pref_provider_->SetClockForTesting(clock); +void HostContentSettingsMap::InitializePluginsDataSettings() { + if (!content_settings::WebsiteSettingsRegistry::GetInstance()->Get( + CONTENT_SETTINGS_TYPE_PLUGINS_DATA)) { + return; + } + ContentSettingsForOneType host_settings; + GetSettingsForOneType(CONTENT_SETTINGS_TYPE_PLUGINS_DATA, std::string(), + &host_settings); + if (host_settings.empty()) { + GetSettingsForOneType(CONTENT_SETTINGS_TYPE_PLUGINS, std::string(), + &host_settings); + for (ContentSettingPatternSource pattern : host_settings) { + if (pattern.source != "preference") + continue; + const GURL primary(pattern.primary_pattern.ToString()); + if (!primary.is_valid()) + continue; + DCHECK_EQ(ContentSettingsPattern::Relation::IDENTITY, + ContentSettingsPattern::Wildcard().Compare( + pattern.secondary_pattern)); + auto dict = std::make_unique<base::DictionaryValue>(); + constexpr char kFlagKey[] = "flashPreviouslyChanged"; + dict->SetKey(kFlagKey, base::Value(true)); + SetWebsiteSettingDefaultScope(primary, primary, + CONTENT_SETTINGS_TYPE_PLUGINS_DATA, + std::string(), std::move(dict)); + } + } }
diff --git a/components/content_settings/core/browser/host_content_settings_map.h b/components/content_settings/core/browser/host_content_settings_map.h index 890e895..be6ca47 100644 --- a/components/content_settings/core/browser/host_content_settings_map.h +++ b/components/content_settings/core/browser/host_content_settings_map.h
@@ -18,6 +18,7 @@ #include "base/observer_list.h" #include "base/threading/platform_thread.h" #include "base/threading/thread_checker.h" +#include "build/build_config.h" #include "components/content_settings/core/browser/content_settings_observer.h" #include "components/content_settings/core/browser/content_settings_utils.h" #include "components/content_settings/core/browser/user_modifiable_provider.h" @@ -372,6 +373,11 @@ ContentSettingsPattern* primary_pattern, ContentSettingsPattern* secondary_pattern); + // Make sure existing non-default Flash settings set by the user are marked to + // always show the Flash setting for this site in Page Info. + // TODO(patricialor): Remove after m66 (migration code). + void InitializePluginsDataSettings(); + #ifndef NDEBUG // This starts as the thread ID of the thread that constructs this // object, and remains until used by a different thread, at which
diff --git a/components/content_settings/core/browser/website_settings_registry.cc b/components/content_settings/core/browser/website_settings_registry.cc index b33ded9..5c74c36 100644 --- a/components/content_settings/core/browser/website_settings_registry.cc +++ b/components/content_settings/core/browser/website_settings_registry.cc
@@ -181,6 +181,10 @@ WebsiteSettingsInfo::REQUESTING_ORIGIN_ONLY_SCOPE, DESKTOP | PLATFORM_ANDROID, WebsiteSettingsInfo::DONT_INHERIT_IN_INCOGNITO); + Register(CONTENT_SETTINGS_TYPE_PLUGINS_DATA, "flash-data", nullptr, + WebsiteSettingsInfo::UNSYNCABLE, WebsiteSettingsInfo::NOT_LOSSY, + WebsiteSettingsInfo::REQUESTING_ORIGIN_ONLY_SCOPE, DESKTOP, + WebsiteSettingsInfo::INHERIT_IN_INCOGNITO); } } // namespace content_settings
diff --git a/components/content_settings/core/common/content_settings.cc b/components/content_settings/core/common/content_settings.cc index 2d116fc1..08a0cae 100644 --- a/components/content_settings/core/common/content_settings.cc +++ b/components/content_settings/core/common/content_settings.cc
@@ -29,7 +29,7 @@ // content settings type name instead. // // The array size must be explicit for the static_asserts below. -constexpr size_t kNumHistogramValues = 35; +constexpr size_t kNumHistogramValues = 36; constexpr HistogramValue kHistogramValue[kNumHistogramValues] = { {CONTENT_SETTINGS_TYPE_COOKIES, 0}, {CONTENT_SETTINGS_TYPE_IMAGES, 1}, @@ -66,6 +66,7 @@ {CONTENT_SETTINGS_TYPE_ACCESSIBILITY_EVENTS, 39}, {CONTENT_SETTINGS_TYPE_CLIPBOARD_READ, 40}, {CONTENT_SETTINGS_TYPE_CLIPBOARD_WRITE, 41}, + {CONTENT_SETTINGS_TYPE_PLUGINS_DATA, 42}, }; } // namespace
diff --git a/components/content_settings/core/common/content_settings_types.h b/components/content_settings/core/common/content_settings_types.h index ef4c1f0..d6f4d7b 100644 --- a/components/content_settings/core/common/content_settings_types.h +++ b/components/content_settings/core/common/content_settings_types.h
@@ -100,6 +100,10 @@ // such doesn't have associated prefs data. CONTENT_SETTINGS_TYPE_CLIPBOARD_WRITE, + // Used to store whether the user has ever changed the Flash permission for + // a site. + CONTENT_SETTINGS_TYPE_PLUGINS_DATA, + CONTENT_SETTINGS_NUM_TYPES, };
diff --git a/components/cronet/android/BUILD.gn b/components/cronet/android/BUILD.gn index ec9b89f..1ab3481 100644 --- a/components/cronet/android/BUILD.gn +++ b/components/cronet/android/BUILD.gn
@@ -499,7 +499,6 @@ "//base:i18n", "//base/test:test_support", "//components/cronet:cronet_version_header", - "//components/cronet/native:cronet_native_tests", "//components/prefs", "//net", "//net:simple_quic_tools", @@ -843,10 +842,12 @@ deps = [ ":cronet_android_cert_proto", + ":cronet_impl_native_java", ":cronet_static", "//base", "//base/test:test_support", "//components/cronet:cronet_common_unittests", + "//components/cronet/native:cronet_native_tests", "//components/cronet/native:cronet_native_unittests", "//components/metrics", "//components/prefs:test_support",
diff --git a/components/cronet/android/build_instructions.md b/components/cronet/android/build_instructions.md index a0a0a17..e6045dad 100644 --- a/components/cronet/android/build_instructions.md +++ b/components/cronet/android/build_instructions.md
@@ -25,6 +25,9 @@ `out/Cronet`. If `--out_dir` is left out, the output directory defaults to `out/Debug`. +If `--x86` option is specified, then native library is built for Intel x86 +architecture, and the output directory defaults to `out/Debug-x86`. + ### Building Cronet for releases To build Cronet with optimizations and with debug information stripped out: @@ -43,11 +46,9 @@ targeting other architectures modify [cr_cronet.py](../tools/cr_cronet.py)'s `gn_args` variable to include: -* For ARMv6 32-bit: `arm_version=6` * For ARMv8 64-bit: `target_cpu="arm64"` * For x86 32-bit: `target_cpu="x86"` * For x86 64-bit: `target_cpu="x64"` -* For MIPS: `target_cpu="mipsel"` ## Running tests
diff --git a/components/cronet/android/cronet_library_loader.cc b/components/cronet/android/cronet_library_loader.cc index de6553eb..86b259d 100644 --- a/components/cronet/android/cronet_library_loader.cc +++ b/components/cronet/android/cronet_library_loader.cc
@@ -20,6 +20,7 @@ #include "base/logging.h" #include "base/macros.h" #include "base/message_loop/message_loop.h" +#include "base/synchronization/waitable_event.h" #include "base/task_scheduler/task_scheduler.h" #include "components/cronet/android/cronet_jni_registration.h" #include "components/cronet/cronet_global_state.h" @@ -48,14 +49,14 @@ net::NetworkChangeNotifier* g_network_change_notifier = nullptr; -bool NativeInit() { - if (!base::android::OnJNIOnLoadInit()) - return false; +base::WaitableEvent g_init_thread_init_done( + base::WaitableEvent::ResetPolicy::MANUAL, + base::WaitableEvent::InitialState::NOT_SIGNALED); + +void NativeInit() { if (!base::TaskScheduler::GetInstance()) base::TaskScheduler::CreateAndStartWithDefaultParams("Cronet"); - url::Initialize(); - return true; } } // namespace @@ -72,9 +73,9 @@ if (!RegisterMainDexNatives(env) || !RegisterNonMainDexNatives(env)) { return -1; } - if (!NativeInit()) { + if (!base::android::OnJNIOnLoadInit()) return -1; - } + NativeInit(); return JNI_VERSION_1_6; } @@ -105,6 +106,7 @@ new net::NetworkChangeNotifierFactoryAndroid()); } g_network_change_notifier = net::NetworkChangeNotifier::Create(); + g_init_thread_init_done.Signal(); } ScopedJavaLocalRef<jstring> JNI_CronetLibraryLoader_GetCronetVersion( @@ -113,6 +115,32 @@ return base::android::ConvertUTF8ToJavaString(env, CRONET_VERSION); } +void PostTaskToInitThread(const base::Location& posted_from, + base::OnceClosure task) { + g_init_thread_init_done.Wait(); + g_init_message_loop->task_runner()->PostTask(posted_from, std::move(task)); +} + +void EnsureInitialized() { + if (g_init_message_loop) { + // Ensure that init is done on the init thread. + g_init_thread_init_done.Wait(); + return; + } + + // The initialization can only be done once, so static |s_run_once| variable + // is used to do it in the constructor. + static class RunOnce { + public: + RunOnce() { + NativeInit(); + JNIEnv* env = base::android::AttachCurrentThread(); + // Ensure initialized from Java side to properly create Init thread. + cronet::Java_CronetLibraryLoader_ensureInitializedFromNative(env); + } + } s_run_once; +} + std::unique_ptr<net::ProxyConfigService> CreateProxyConfigService( const scoped_refptr<base::SequencedTaskRunner>& io_task_runner) { std::unique_ptr<net::ProxyConfigService> service = @@ -138,4 +166,19 @@ std::move(proxy_config_service), net_log); } +// Creates default User-Agent request value, combining optional +// |partial_user_agent| with system-dependent values. +std::string CreateDefaultUserAgent(const std::string& partial_user_agent) { + // Cronet global state must be initialized to include application info + // into default user agent + cronet::EnsureInitialized(); + + JNIEnv* env = base::android::AttachCurrentThread(); + std::string user_agent = base::android::ConvertJavaStringToUTF8( + cronet::Java_CronetLibraryLoader_getDefaultUserAgent(env)); + if (!partial_user_agent.empty()) + user_agent.insert(user_agent.size() - 1, "; " + partial_user_agent); + return user_agent; +} + } // namespace cronet
diff --git a/components/cronet/android/cronet_url_request_context_adapter.cc b/components/cronet/android/cronet_url_request_context_adapter.cc index 38f6d87..4fba584 100644 --- a/components/cronet/android/cronet_url_request_context_adapter.cc +++ b/components/cronet/android/cronet_url_request_context_adapter.cc
@@ -287,6 +287,7 @@ static_cast<URLRequestContextConfig::HttpCacheType>(jhttp_cache_mode), jhttp_cache_max_size, jdisable_cache, ConvertNullableJavaStringToUTF8(env, jstorage_path), + /* accept_languages */ std::string(), ConvertNullableJavaStringToUTF8(env, juser_agent), ConvertNullableJavaStringToUTF8(env, jexperimental_quic_connection_options),
diff --git a/components/cronet/android/java/src/org/chromium/net/impl/CronetLibraryLoader.java b/components/cronet/android/java/src/org/chromium/net/impl/CronetLibraryLoader.java index c956ac0..536d8ba 100644 --- a/components/cronet/android/java/src/org/chromium/net/impl/CronetLibraryLoader.java +++ b/components/cronet/android/java/src/org/chromium/net/impl/CronetLibraryLoader.java
@@ -13,6 +13,7 @@ import org.chromium.base.ContextUtils; import org.chromium.base.Log; import org.chromium.base.VisibleForTesting; +import org.chromium.base.annotations.CalledByNative; import org.chromium.base.annotations.JNINamespace; import org.chromium.net.NetworkChangeNotifier; @@ -123,6 +124,49 @@ } } + /** + * Called from native library to get default user agent constructed + * using application context. May be called on any thread. + * + * Expects that ContextUtils.initApplicationContext() was called already + * either by some testing framework or an embedder constructing a Java + * CronetEngine via CronetEngine.Builder.build(). + */ + @CalledByNative + private static String getDefaultUserAgent() { + return UserAgent.from(ContextUtils.getApplicationContext()); + } + + /** + * Called from native library to ensure that library is initialized. + * May be called on any thread, but initialization is performed on + * this.sInitThread. + * + * Expects that ContextUtils.initApplicationContext() was called already + * either by some testing framework or an embedder constructing a Java + * CronetEngine via CronetEngine.Builder.build(). + * + * TODO(mef): In the long term this should be changed to some API with + * lower overhead like CronetEngine.Builder.loadNativeCronet(). + */ + @CalledByNative + private static void ensureInitializedFromNative() { + // Called by native, so native library is already loaded. + // It is possible that loaded native library is not regular + // "libcronet.xyz.so" but test library that statically links + // native code like "libcronet_unittests.so". + synchronized (sLoadLock) { + sLibraryLoaded = true; + sWaitForLibLoad.open(); + } + + // The application context must already be initialized + // using ContextUtils.initApplicationContext(). + Context applicationContext = ContextUtils.getApplicationContext(); + assert applicationContext != null; + ensureInitialized(applicationContext, null); + } + // Native methods are implemented in cronet_library_loader.cc. private static native void nativeCronetInitOnInitThread(); private static native String nativeGetCronetVersion();
diff --git a/components/cronet/android/test/native_test_server.cc b/components/cronet/android/test/native_test_server.cc index c9a8d9b..364f73c 100644 --- a/components/cronet/android/test/native_test_server.cc +++ b/components/cronet/android/test/native_test_server.cc
@@ -24,6 +24,7 @@ #include "net/base/host_port_pair.h" #include "net/base/url_util.h" #include "net/http/http_status_code.h" +#include "net/test/embedded_test_server/default_handlers.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" @@ -42,37 +43,9 @@ const char kEchoAllHeadersPath[] = "/echo_all_headers"; const char kEchoMethodPath[] = "/echo_method"; const char kRedirectToEchoBodyPath[] = "/redirect_to_echo_body"; -const char kExabyteResponsePath[] = "/exabyte_response"; net::EmbeddedTestServer* g_test_server = nullptr; -// A HttpResponse that is almost never ending (with an Extabyte content-length). -class ExabyteResponse : public net::test_server::BasicHttpResponse { - public: - ExabyteResponse() {} - - void SendResponse( - const net::test_server::SendBytesCallback& send, - const net::test_server::SendCompleteCallback& done) override { - // Use 10^18 bytes (exabyte) as the content length so that the client will - // be expecting data. - send.Run("HTTP/1.1 200 OK\r\nContent-Length:1000000000000000000\r\n\r\n", - base::Bind(&ExabyteResponse::SendExabyte, send)); - } - - private: - // Keeps sending the word "echo" over and over again. It can go further to - // limit the response to exactly an exabyte, but it shouldn't be necessary - // for the purpose of testing. - static void SendExabyte(const net::test_server::SendBytesCallback& send) { - base::ThreadTaskRunnerHandle::Get()->PostTask( - FROM_HERE, base::Bind(send, "echo", - base::Bind(&ExabyteResponse::SendExabyte, send))); - } - - DISALLOW_COPY_AND_ASSIGN(ExabyteResponse); -}; - std::unique_ptr<net::test_server::HttpResponse> NativeTestServerRequestHandler( const net::test_server::HttpRequest& request) { DCHECK(g_test_server); @@ -121,11 +94,6 @@ return std::unique_ptr<net::test_server::BasicHttpResponse>(); } -std::unique_ptr<net::test_server::HttpResponse> HandleExabyteRequest( - const net::test_server::HttpRequest& request) { - return base::WrapUnique(new ExabyteResponse); -} - } // namespace jboolean JNI_NativeTestServer_StartNativeTestServer( @@ -144,15 +112,15 @@ g_test_server = new net::EmbeddedTestServer(); g_test_server->RegisterRequestHandler( base::Bind(&NativeTestServerRequestHandler)); - g_test_server->RegisterDefaultHandler( - base::Bind(&net::test_server::HandlePrefixedRequest, kExabyteResponsePath, - base::Bind(&HandleExabyteRequest))); base::FilePath test_files_root( base::android::ConvertJavaStringToUTF8(env, jtest_files_root)); // Add a third handler for paths that NativeTestServerRequestHandler does not // handle. g_test_server->ServeFilesFromDirectory(test_files_root); + + RegisterDefaultHandlers(g_test_server); + return g_test_server->Start(); } @@ -230,7 +198,7 @@ JNIEnv* env, const JavaParamRef<jclass>& jcaller) { DCHECK(g_test_server); - GURL url = g_test_server->GetURL(kExabyteResponsePath); + GURL url = g_test_server->GetURL("/exabyte_response"); return base::android::ConvertUTF8ToJavaString(env, url.spec()); }
diff --git a/components/cronet/cronet_global_state.h b/components/cronet/cronet_global_state.h index 7c070f49..b369bf9 100644 --- a/components/cronet/cronet_global_state.h +++ b/components/cronet/cronet_global_state.h
@@ -22,6 +22,16 @@ // Only callable after initialization thread is started. bool OnInitThread(); +// Posts a task to run on initialization thread. Blocks until initialization +// thread is started. +void PostTaskToInitThread(const base::Location& posted_from, + base::OnceClosure task); + +// Ensure that one time initialization of Cronet global state is done. Can be +// called from any thread. The initialization is performed on initialization +// thread. +void EnsureInitialized(); + // Creates a proxy config service appropriate for this platform that fetches the // system proxy settings. std::unique_ptr<net::ProxyConfigService> CreateProxyConfigService( @@ -33,6 +43,10 @@ std::unique_ptr<net::ProxyConfigService> proxy_config_service, net::NetLog* net_log); +// Creates default User-Agent request value, combining optional +// |partial_user_agent| with system-dependent values. +std::string CreateDefaultUserAgent(const std::string& partial_user_agent); + } // namespace cronet #endif // COMPONENTS_CRONET_CRONET_GLOBAL_STATE_H_
diff --git a/components/cronet/cronet_url_request_context.cc b/components/cronet/cronet_url_request_context.cc index 14f8c40..423d807e 100644 --- a/components/cronet/cronet_url_request_context.cc +++ b/components/cronet/cronet_url_request_context.cc
@@ -311,7 +311,6 @@ std::unique_ptr<net::ProxyConfigService> proxy_config_service) { DCHECK_CALLED_ON_VALID_THREAD(network_thread_checker_); DCHECK(!is_context_initialized_); - DCHECK(proxy_config_service); std::unique_ptr<URLRequestContextConfig> config(std::move(context_config_)); network_task_runner_ = network_task_runner;
diff --git a/components/cronet/ios/BUILD.gn b/components/cronet/ios/BUILD.gn index 282a1e97..95866b4 100644 --- a/components/cronet/ios/BUILD.gn +++ b/components/cronet/ios/BUILD.gn
@@ -6,8 +6,6 @@ import("//build/config/ios/rules.gni") import("//build/config/mac/symbols.gni") import("//build/mac/tweak_info_plist.gni") -import("//build/util/process_version.gni") -import("//build/util/version.gni") import("//components/cronet/native/include/headers.gni") import("//components/grpc_support/include/headers.gni") import("//testing/test.gni") @@ -21,18 +19,6 @@ ] } -process_version("cronet_version_header") { - template_file = "//components/cronet/version.h.in" - sources = [ - "//chrome/VERSION", - ] - output = "$target_gen_dir/version.h" - extra_args = [ - "-e", - "VERSION_FULL=\"%s.%s.%s.%s\" % (MAJOR,MINOR,BUILD,PATCH)", - ] -} - config("cronet_include_config") { include_dirs = [ "//components/grpc_support/include" ] } @@ -51,13 +37,12 @@ } _cronet_deps = [ - ":cronet_version_header", ":generate_accept_languages", "//base:base", + "//components/cronet:cronet_common", + "//components/cronet:cronet_version_header", "//components/cronet/native:cronet_native_impl", "//components/grpc_support", - "//components/metrics:metrics", - "//third_party/metrics_proto", "//components/prefs:prefs", "//ios/net:net", "//ios/web/public:user_agent", @@ -67,20 +52,11 @@ ] _cronet_sources = [ - "../cronet_prefs_manager.cc", - "../cronet_prefs_manager.h", - "../histogram_manager.cc", - "../histogram_manager.h", - "../host_cache_persistence_manager.cc", - "../host_cache_persistence_manager.h", - "../stale_host_resolver.cc", - "../stale_host_resolver.h", - "../url_request_context_config.cc", - "../url_request_context_config.h", "Cronet.h", "Cronet.mm", "cronet_environment.h", "cronet_environment.mm", + "cronet_global_state_ios.mm", "cronet_metrics.h", "cronet_metrics.mm", ] @@ -154,17 +130,13 @@ test("cronet_unittests_ios") { testonly = true - sources = [ - "//components/cronet/histogram_manager_unittest.cc", - "//components/cronet/run_all_unittests.cc", - "//components/cronet/stale_host_resolver_unittest.cc", - "//components/cronet/url_request_context_config_unittest.cc", - ] + sources = [] deps = [ ":cronet_sources_with_global_state", "//base", "//base/test:test_support", + "//components/cronet:cronet_common_unittests", "//components/cronet/native:cronet_native_unittests", "//components/metrics", "//net",
diff --git a/components/cronet/ios/Cronet.mm b/components/cronet/ios/Cronet.mm index 27d04cb..88870f0e 100644 --- a/components/cronet/ios/Cronet.mm +++ b/components/cronet/ios/Cronet.mm
@@ -13,6 +13,7 @@ #include "base/mac/scoped_block.h" #include "base/strings/sys_string_conversions.h" #include "base/synchronization/lock.h" +#include "components/cronet/cronet_global_state.h" #include "components/cronet/ios/accept_languages_table.h" #include "components/cronet/ios/cronet_environment.h" #include "components/cronet/ios/cronet_metrics.h" @@ -367,17 +368,7 @@ } + (void)start { - static dispatch_once_t onceToken; - dispatch_once(&onceToken, ^{ - if (![NSThread isMainThread]) { - dispatch_sync(dispatch_get_main_queue(), ^(void) { - cronet::CronetEnvironment::Initialize(); - }); - } else { - cronet::CronetEnvironment::Initialize(); - } - }); - + cronet::EnsureInitialized(); [self startInternal]; }
diff --git a/components/cronet/ios/cronet_environment.h b/components/cronet/ios/cronet_environment.h index fac4d747..44999b36 100644 --- a/components/cronet/ios/cronet_environment.h +++ b/components/cronet/ios/cronet_environment.h
@@ -6,7 +6,9 @@ #define COMPONENTS_CRONET_IOS_CRONET_ENVIRONMENT_H_ #include <list> +#include <memory> #include <string> +#include <utility> #include <vector> #include "base/files/file_path.h" @@ -15,8 +17,8 @@ #include "base/strings/sys_string_conversions.h" #include "base/synchronization/waitable_event.h" #include "base/threading/thread.h" -#include "components/cronet/ios/version.h" #include "components/cronet/url_request_context_config.h" +#include "components/cronet/version.h" #include "net/cert/cert_verifier.h" #include "net/url_request/url_request_context.h" #include "net/url_request/url_request_context_getter.h" @@ -44,10 +46,6 @@ // should not be altered when a thread is created. static const double kKeepDefaultThreadPriority; - // Initialize Cronet environment globals. Must be called only once on the - // main thread. - static void Initialize(); - // |user_agent| will be used to generate the user-agent if // |user_agent_partial| is true, or will be used as the complete user-agent // otherwise.
diff --git a/components/cronet/ios/cronet_environment.mm b/components/cronet/ios/cronet_environment.mm index 922a0bb..fec8e1c 100644 --- a/components/cronet/ios/cronet_environment.mm +++ b/components/cronet/ios/cronet_environment.mm
@@ -23,7 +23,6 @@ #include "base/threading/thread_restrictions.h" #include "components/cronet/cronet_prefs_manager.h" #include "components/cronet/histogram_manager.h" -#include "components/cronet/ios/version.h" #include "components/prefs/pref_filter.h" #include "ios/net/cookies/cookie_store_ios.h" #include "ios/net/cookies/cookie_store_ios_client.h" @@ -147,22 +146,6 @@ return main_context_getter_.get(); } -// static -void CronetEnvironment::Initialize() { - // This method must be called once from the main thread. - DCHECK_EQ([NSThread currentThread], [NSThread mainThread]); - - ios_global_state::CreateParams create_params; - create_params.install_at_exit_manager = true; - ios_global_state::Create(create_params); - ios_global_state::StartTaskScheduler(/*init_params=*/nullptr); - - url::Initialize(); - - ios_global_state::BuildMessageLoop(); - ios_global_state::CreateNetworkChangeNotifier(); -} - bool CronetEnvironment::StartNetLog(base::FilePath::StringType file_name, bool log_bytes) { if (file_name.empty()) @@ -349,6 +332,8 @@ context_config_builder.http_cache = http_cache_; // Set HTTP cache. context_config_builder.storage_path = storage_path.value(); // Storage path for http cache and prefs storage. + context_config_builder.accept_language = + accept_language_; // Accept-Language request header field. context_config_builder.user_agent = user_agent_; // User-Agent request header field. context_config_builder.experimental_options = @@ -362,8 +347,6 @@ net::URLRequestContextBuilder context_builder; - context_builder.set_accept_language(accept_language_); - // Explicitly disable the persister for Cronet to avoid persistence of dynamic // HPKP. This is a safety measure ensuring that nobody enables the // persistence of HPKP by specifying transport_security_persister_path in the
diff --git a/components/cronet/ios/cronet_global_state_ios.mm b/components/cronet/ios/cronet_global_state_ios.mm new file mode 100644 index 0000000..267fe5b --- /dev/null +++ b/components/cronet/ios/cronet_global_state_ios.mm
@@ -0,0 +1,90 @@ +// 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. + +#include "components/cronet/cronet_global_state.h" + +#import <Foundation/Foundation.h> + +#include <utility> + +#include "base/callback.h" +#include "ios/web/public/global_state/ios_global_state.h" +#include "ios/web/public/global_state/ios_global_state_configuration.h" +#include "ios/web/public/user_agent.h" +#include "net/proxy_resolution/proxy_config_service.h" +#include "net/proxy_resolution/proxy_service.h" +#include "url/url_util.h" + +#if !defined(__has_feature) || !__has_feature(objc_arc) +#error "This file requires ARC support." +#endif + +namespace { + +void InitializeOnMainThread() { + // This method must be called once from the main thread. + DCHECK_EQ([NSThread currentThread], [NSThread mainThread]); + + ios_global_state::CreateParams create_params; + create_params.install_at_exit_manager = true; + ios_global_state::Create(create_params); + ios_global_state::StartTaskScheduler(/*init_params=*/nullptr); + + url::Initialize(); + + ios_global_state::BuildMessageLoop(); + ios_global_state::CreateNetworkChangeNotifier(); +} + +} // namespace + +namespace cronet { + +bool OnInitThread() { + return [NSThread isMainThread] == YES; +} + +void PostTaskToInitThread(const base::Location& posted_from, + base::OnceClosure task) { + __block base::OnceClosure block_task(std::move(task)); + if (!OnInitThread()) { + dispatch_async(dispatch_get_main_queue(), ^(void) { + std::move(block_task).Run(); + }); + } else { + std::move(block_task).Run(); + } +} + +void EnsureInitialized() { + static dispatch_once_t onceToken; + dispatch_once(&onceToken, ^{ + if (!OnInitThread()) { + dispatch_sync(dispatch_get_main_queue(), ^(void) { + InitializeOnMainThread(); + }); + } else { + InitializeOnMainThread(); + } + }); +} + +std::unique_ptr<net::ProxyConfigService> CreateProxyConfigService( + const scoped_refptr<base::SequencedTaskRunner>& io_task_runner) { + return nullptr; +} + +std::unique_ptr<net::ProxyResolutionService> CreateProxyService( + std::unique_ptr<net::ProxyConfigService> proxy_config_service, + net::NetLog* net_log) { + return nullptr; +} + +// Creates default User-Agent request value, combining optional +// |partial_user_agent| with system-dependent values. +std::string CreateDefaultUserAgent(const std::string& partial_user_agent) { + return web::BuildUserAgentFromProduct(partial_user_agent); +} + +} // namespace cronet
diff --git a/components/cronet/native/BUILD.gn b/components/cronet/native/BUILD.gn index 10f3959..0b28bca 100644 --- a/components/cronet/native/BUILD.gn +++ b/components/cronet/native/BUILD.gn
@@ -1,3 +1,7 @@ +# 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. + import("//components/cronet/native/include/headers.gni") import("//testing/test.gni") @@ -10,8 +14,20 @@ # Cronet native API implementation. source_set("cronet_native_impl") { + deps = [ + "//base", + "//components/cronet:cronet_common", + "//components/cronet:cronet_version_header", + "//net", + ] + + configs += [ ":cronet_native_include_config" ] + public_configs = [ ":cronet_native_include_config" ] + sources = [ "buffer.cc", + "engine.cc", + "engine.h", "include/cronet_c.h", "runnables.cc", "runnables.h", @@ -23,15 +39,23 @@ "generated/cronet.idl_impl_struct.cc", "generated/cronet.idl_impl_struct.h", ] +} + +source_set("cronet_native_testutil") { + visibility = [ ":*" ] + testonly = true + deps = [ "//base", - "//net", ] - include_dirs = [ - "//components/cronet/native/generated", - "//components/cronet/native/include", - ] + + configs += [ ":cronet_native_include_config" ] public_configs = [ ":cronet_native_include_config" ] + + sources = [ + "test_util.cc", + "test_util.h", + ] } # Unit tests for Cronet native API. Depends on cronet_native_impl to test @@ -41,18 +65,14 @@ deps = [ ":cronet_native_impl", + ":cronet_native_testutil", "//net:test_support", ] - include_dirs = [ - "//components/cronet/native/generated", - "//components/cronet/native/include", - ] + configs += [ ":cronet_native_include_config" ] sources = [ "runnables_unittest.cc", - "test_util.cc", - "test_util.h", # Generated from cronet.idl. "generated/cronet.idl_impl_interface_unittest.cc", @@ -66,19 +86,18 @@ testonly = true deps = [ + ":cronet_native_testutil", "//base", "//base/test:test_support", + "//net:test_support", "//testing/gtest", ] - include_dirs = [ - "//components/cronet/native/generated", - "//components/cronet/native/include", - ] + configs += [ ":cronet_native_include_config" ] + sources = [ "buffer_test.cc", + "engine_test.cc", "executors_test.cc", - "test_util.cc", - "test_util.h", ] }
diff --git a/components/cronet/native/cronet.idl b/components/cronet/native/cronet.idl index c1b7505..908770b 100644 --- a/components/cronet/native/cronet.idl +++ b/components/cronet/native/cronet.idl
@@ -174,6 +174,70 @@ }; /** + * Runtime result code returned by Engine and UrlRequest. Equivalent to + * runtime exceptions in Android Java API. All results except SUCCESS trigger + * native crash (via SIGABRT triggered by CHECK failure) unless + * EngineParams.enableCheckResult is set to false. + */ +enum RESULT { + /** + * Operation completed successfully + */ + SUCCESS = 0, + + /** + * Illegal argument + */ + ILLEGAL_ARGUMENT = -100, + /** + * Storage path must be set to existing directory + */ + ILLEGAL_ARGUMENT_STORAGE_PATH_MUST_EXIST = -101, + /** + * Public key pin is invalid + */ + ILLEGAL_ARGUMENT_INVALID_PIN = -102, + /** + * Host name is invalid + */ + ILLEGAL_ARGUMENT_INVALID_HOSTNAME = -103, + + /** + * Illegal state + */ + ILLEGAL_STATE = -200, + /** + * Storage path is used by another engine + */ + ILLEGAL_STATE_STORAGE_PATH_IN_USE = -201, + /** + * Cannot shutdown engine from network thread + */ + ILLEGAL_STATE_CANNOT_SHUTDOWN_ENGINE_FROM_NETWORK_THREAD = -202, + /** + * The engine has already started + */ + ILLEGAL_STATE_ENGINE_ALREADY_STARTED = -203, + + /** + * Null pointer or empty data + */ + NULL_POINTER = -300, + /** + * The hostname cannot be null + */ + NULL_POINTER_HOSTNAME = -301, + /** + * The set of SHA256 pins cannot be null + */ + NULL_POINTER_SHA256_PINS = -302, + /** + * The pin expiration date cannot be null + */ + NULL_POINTER_EXPIRATION_DATE = -303, +}; + +/** * An engine to process UrlRequests, which uses the best HTTP stack * available on the current platform. An instance of this class can be started * using StartWithParams. @@ -183,13 +247,15 @@ * Starts Engine using given |params|. The engine must be started once * and only once before other methods can be used. */ - StartWithParams(EngineParams params); + [Sync] + StartWithParams(EngineParams params) => (RESULT result); /** * Starts NetLog logging to a file. The NetLog will contain events emitted * by all live Engines. The NetLog is useful for debugging. * The file can be viewed using a Chrome browser navigated to * chrome://net-internals/#import + * Returns |true| if netlog has started successfully, |false| otherwise. * @param fileName the complete file path. It must not be empty. If the file * exists, it is truncated before starting. If actively logging, * this method is ignored. @@ -199,26 +265,41 @@ * only be used with the user's consent and in situations where the log * won't be public. {@code false} to just include basic events. */ - StartNetLogToFile(string fileName, bool logAll); + [Sync] + StartNetLogToFile(string fileName, bool logAll) => (bool started); /** * Stops NetLog logging and flushes file to disk. If a logging session is - * not in progress, this call is ignored. + * not in progress, this call is ignored. This method blocks until the log is + * closed to ensure that log file is complete and available. */ - StopNetLog(); + [Sync] + StopNetLog() => (); + + /** + * Shuts down the Engine if there are no active requests, + * otherwise throws an exception. + * + * Cannot be called on network thread - the thread Cronet calls into + * Executor on (which is different from the thread the Executor invokes + * callbacks on). This method blocks until all the Engine's resources have + * been cleaned up. + */ + [Sync] + Shutdown() => (RESULT result); /** * Returns a human-readable version string of the engine. */ [Sync] - GetVersionString() => (string version_string); + GetVersionString() => (string versionString); /** * Returns default human-readable version string of the engine. Can be used * before StartWithParams() is called. */ [Sync] - GetDefaultUserAgent() => (string default_user_agent); + GetDefaultUserAgent() => (string defaultUserAgent); }; /** @@ -263,18 +344,23 @@ /** * An array of pins. Each pin is the SHA-256 cryptographic - * hash of the DER-encoded ASN.1 representation of the Subject Public - * Key Info (SPKI) of the host's X.509 certificate. + * hash (in the form of "sha256/<base64-hash-value>") of the DER-encoded ASN.1 + * representation of the Subject Public Key Info (SPKI) of the host's X.509 certificate. * Although, the method does not mandate the presence of the backup pin * that can be used if the control of the primary private key has been * lost, it is highly recommended to supply one. */ - array<handle> pinsSha256; + array<string> pinsSha256; /** * Indicates whether the pinning policy should be applied to subdomains of |host|. */ bool includeSubdomains = false; + + /** + * The expiration date for the pins in milliseconds since epoch (as in java.util.Date). + */ + int64 expirationDate; }; /** @@ -284,12 +370,25 @@ */ struct EngineParams { /** + * Override strict result checking for all operations that return RESULT. + * If set to true, then failed result will cause native crash via SIGABORT. + */ + bool enableCheckResult = true; + + /** * Override of the User-Agent header for all requests. An explicitly * set User-Agent header will override a value set using this param. */ string userAgent; /** + * Sets a default value for the Accept-Language header value for UrlRequests + * created by this engine. Explicitly setting the Accept-Language header + * value for individual UrlRequests will override this value. + */ + string acceptLanguage; + + /** * Directory for HTTP Cache and Prefs Storage. The directory must exist. */ string storagePath; @@ -369,6 +468,11 @@ * https://www.chromium.org/Home/chromium-security/security-faq */ bool enablePublicKeyPinningBypassForLocalTrustAnchors = true; + + /** + * JSON formatted experimental options to be used in Cronet Engine. + */ + string experimentalOptions; }; /** @@ -587,7 +691,6 @@ */ [Abstract] interface UrlRequestCallback { - /** * Invoked whenever a redirect is encountered. This will only be invoked * between the call to UrlRequest.start() and @@ -772,7 +875,6 @@ * Note: All methods must be called on the Executor passed to InitWithParams(). */ interface UrlRequest { - /** * Initialized UrlRequest to |url| with |params|. All methods of |callback| for * request will be invoked on |executor|. The |executor| must not run tasks on
diff --git a/components/cronet/native/engine.cc b/components/cronet/native/engine.cc new file mode 100644 index 0000000..54de7a12 --- /dev/null +++ b/components/cronet/native/engine.cc
@@ -0,0 +1,360 @@ +// 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 "components/cronet/native/engine.h" + +#include <unordered_set> +#include <utility> + +#include "base/bind.h" +#include "base/bind_helpers.h" +#include "base/files/file_path.h" +#include "base/files/file_util.h" +#include "base/logging.h" +#include "base/macros.h" +#include "base/no_destructor.h" +#include "components/cronet/cronet_global_state.h" +#include "components/cronet/cronet_url_request_context.h" +#include "components/cronet/native/generated/cronet.idl_impl_struct.h" +#include "components/cronet/native/include/cronet_c.h" +#include "components/cronet/url_request_context_config.h" +#include "components/cronet/version.h" +#include "net/base/hash_value.h" +#include "net/url_request/url_request_context.h" +#include "net/url_request/url_request_context_builder.h" + +namespace { + +class SharedEngineState { + public: + SharedEngineState() + : default_user_agent_(cronet::CreateDefaultUserAgent(CRONET_VERSION)) {} + + // Marks |storage_path| in use, so multiple engines would not use it at the + // same time. Returns |true| if marked successfully, |false| if it is in use + // by another engine. + bool MarkStoragePathInUse(const std::string& storage_path) { + base::AutoLock lock(lock_); + return in_use_storage_paths_.emplace(storage_path).second; + } + + // Unmarks |storage_path| in use, so another engine could use it. + void UnmarkStoragePathInUse(const std::string& storage_path) { + base::AutoLock lock(lock_); + in_use_storage_paths_.erase(storage_path); + } + + // Returns default user agent, based on Cronet version, application info and + // platform-specific additional information. + CharString GetDefaultUserAgent() const { return default_user_agent_.c_str(); } + + static SharedEngineState* GetInstance(); + + private: + const std::string default_user_agent_; + // Protecting shared state. + base::Lock lock_; + std::unordered_set<std::string> in_use_storage_paths_; + + DISALLOW_COPY_AND_ASSIGN(SharedEngineState); +}; + +SharedEngineState* SharedEngineState::GetInstance() { + static base::NoDestructor<SharedEngineState> instance; + return instance.get(); +} + +// Does basic validation of host name for PKP and returns |true| if +// host is valid. +bool IsValidHostnameForPkp(const std::string& host) { + if (host.empty()) + return false; + if (host.size() > 255) + return false; + if (host.find_first_of(":\\/=\'\",") != host.npos) + return false; + return true; +} + +} // namespace + +namespace cronet { + +Cronet_EngineImpl::Cronet_EngineImpl() + : init_completed_(base::WaitableEvent::ResetPolicy::MANUAL, + base::WaitableEvent::InitialState::NOT_SIGNALED), + stop_netlog_completed_(base::WaitableEvent::ResetPolicy::MANUAL, + base::WaitableEvent::InitialState::NOT_SIGNALED) {} + +Cronet_EngineImpl::~Cronet_EngineImpl() { + Shutdown(); +} + +void Cronet_EngineImpl::SetContext(Cronet_EngineContext context) { + engine_context_ = context; +} + +Cronet_EngineContext Cronet_EngineImpl::GetContext() { + return engine_context_; +} + +Cronet_RESULT Cronet_EngineImpl::StartWithParams( + Cronet_EngineParamsPtr params) { + cronet::EnsureInitialized(); + base::AutoLock lock(lock_); + + enable_check_result_ = params->enableCheckResult; + if (context_) { + return CheckResult(Cronet_RESULT_ILLEGAL_STATE_ENGINE_ALREADY_STARTED); + } + + URLRequestContextConfigBuilder context_config_builder; + context_config_builder.enable_quic = params->enableQuic; + context_config_builder.enable_spdy = params->enableHttp2; + context_config_builder.enable_brotli = params->enableBrotli; + switch (params->httpCacheMode) { + case Cronet_EngineParams_HTTP_CACHE_MODE_DISABLED: + context_config_builder.http_cache = URLRequestContextConfig::DISABLED; + break; + case Cronet_EngineParams_HTTP_CACHE_MODE_IN_MEMORY: + context_config_builder.http_cache = URLRequestContextConfig::MEMORY; + break; + case Cronet_EngineParams_HTTP_CACHE_MODE_DISK: + context_config_builder.http_cache = URLRequestContextConfig::DISK; + if (!base::DirectoryExists(base::FilePath(params->storagePath))) { + return CheckResult( + Cronet_RESULT_ILLEGAL_ARGUMENT_STORAGE_PATH_MUST_EXIST); + } + if (!SharedEngineState::GetInstance()->MarkStoragePathInUse( + params->storagePath)) { + LOG(ERROR) << "Disk cache path " << params->storagePath + << " is already used, cache disabled."; + return CheckResult(Cronet_RESULT_ILLEGAL_STATE_STORAGE_PATH_IN_USE); + } + in_use_storage_path_ = params->storagePath; + break; + default: + context_config_builder.http_cache = URLRequestContextConfig::DISABLED; + } + context_config_builder.http_cache_max_size = params->httpCacheMaxSize; + context_config_builder.storage_path = params->storagePath; + context_config_builder.accept_language = params->acceptLanguage; + context_config_builder.user_agent = params->userAgent; + context_config_builder.experimental_options = params->experimentalOptions; + context_config_builder.bypass_public_key_pinning_for_local_trust_anchors = + params->enablePublicKeyPinningBypassForLocalTrustAnchors; + + std::unique_ptr<URLRequestContextConfig> config = + context_config_builder.Build(); + + for (const auto& publicKeyPins : params->publicKeyPins) { + auto pkp = std::make_unique<URLRequestContextConfig::Pkp>( + publicKeyPins->host, publicKeyPins->includeSubdomains, + base::Time::FromJavaTime(publicKeyPins->expirationDate)); + if (pkp->host.empty()) + return CheckResult(Cronet_RESULT_NULL_POINTER_HOSTNAME); + if (!IsValidHostnameForPkp(pkp->host)) + return CheckResult(Cronet_RESULT_ILLEGAL_ARGUMENT_INVALID_HOSTNAME); + if (pkp->expiration_date.is_null()) + return CheckResult(Cronet_RESULT_NULL_POINTER_EXPIRATION_DATE); + if (publicKeyPins->pinsSha256.empty()) + return CheckResult(Cronet_RESULT_NULL_POINTER_SHA256_PINS); + for (const auto& pin_sha256 : publicKeyPins->pinsSha256) { + net::HashValue pin_hash; + if (!pin_hash.FromString(pin_sha256)) + return CheckResult(Cronet_RESULT_ILLEGAL_ARGUMENT_INVALID_PIN); + pkp->pin_hashes.push_back(pin_hash); + } + config->pkp_list.push_back(std::move(pkp)); + } + + for (const auto& quic_hint : params->quicHints) { + config->quic_hints.push_back( + std::make_unique<URLRequestContextConfig::QuicHint>( + quic_hint->host, quic_hint->port, quic_hint->alternatePort)); + } + + context_ = std::make_unique<CronetURLRequestContext>( + std::move(config), std::make_unique<Callback>(this)); + + // TODO(mef): It'd be nice to remove the java code and this code, and get + // rid of CronetURLRequestContextAdapter::InitRequestContextOnInitThread. + // Could also make CronetURLRequestContext::InitRequestContextOnInitThread() + // private and mark CronetLibraryLoader.postToInitThread() as + // @VisibleForTesting (as the only external use will be in a test). + + // Initialize context on the init thread. + cronet::PostTaskToInitThread( + FROM_HERE, + base::BindOnce(&CronetURLRequestContext::InitRequestContextOnInitThread, + base::Unretained(context_.get()))); + return CheckResult(Cronet_RESULT_SUCCESS); +} + +bool Cronet_EngineImpl::StartNetLogToFile(CharString fileName, bool logAll) { + base::AutoLock lock(lock_); + if (is_logging_ || !context_) + return false; + is_logging_ = context_->StartNetLogToFile(fileName, logAll); + return is_logging_; +} + +void Cronet_EngineImpl::StopNetLog() { + { + base::AutoLock lock(lock_); + if (!is_logging_ || !context_) + return; + context_->StopNetLog(); + // Release |lock| so it could be acquired in OnStopNetLog. + } + stop_netlog_completed_.Wait(); + stop_netlog_completed_.Reset(); +} + +CharString Cronet_EngineImpl::GetVersionString() { + return CRONET_VERSION; +} + +CharString Cronet_EngineImpl::GetDefaultUserAgent() { + return SharedEngineState::GetInstance()->GetDefaultUserAgent(); +} + +Cronet_RESULT Cronet_EngineImpl::Shutdown() { + { // Check whether engine is running. + base::AutoLock lock(lock_); + if (!context_) + return CheckResult(Cronet_RESULT_SUCCESS); + } + // Wait for init to complete on init and network thread (without lock, so + // other thread could access it). + init_completed_.Wait(); + // If not logging, this is a no-op. + StopNetLog(); + // Stop the engine. + base::AutoLock lock(lock_); + if (context_->IsOnNetworkThread()) { + return CheckResult( + Cronet_RESULT_ILLEGAL_STATE_CANNOT_SHUTDOWN_ENGINE_FROM_NETWORK_THREAD); + } + + if (!in_use_storage_path_.empty()) { + SharedEngineState::GetInstance()->UnmarkStoragePathInUse( + in_use_storage_path_); + } + + context_.reset(); + return CheckResult(Cronet_RESULT_SUCCESS); +} + +Cronet_RESULT Cronet_EngineImpl::CheckResult(Cronet_RESULT result) { + if (enable_check_result_) + CHECK_EQ(Cronet_RESULT_SUCCESS, result); + return result; +} + +// Callback is owned by CronetURLRequestContext. It is invoked and deleted +// on the network thread. +class Cronet_EngineImpl::Callback : public CronetURLRequestContext::Callback { + public: + explicit Callback(Cronet_EngineImpl* engine); + ~Callback() override; + + // CronetURLRequestContext::Callback implementation: + void OnInitNetworkThread() override; + void OnDestroyNetworkThread() override; + void OnInitCertVerifierData(net::CertVerifier* cert_verifier, + const std::string& cert_verifier_data) override; + void OnSaveCertVerifierData(net::CertVerifier* cert_verifier) override; + void OnEffectiveConnectionTypeChanged( + net::EffectiveConnectionType effective_connection_type) override; + void OnRTTOrThroughputEstimatesComputed( + int32_t http_rtt_ms, + int32_t transport_rtt_ms, + int32_t downstream_throughput_kbps) override; + void OnRTTObservation(int32_t rtt_ms, + int32_t timestamp_ms, + net::NetworkQualityObservationSource source) override; + void OnThroughputObservation( + int32_t throughput_kbps, + int32_t timestamp_ms, + net::NetworkQualityObservationSource source) override; + void OnStopNetLogCompleted() override; + + private: + // The engine which owns context that owns |this| callback. + Cronet_EngineImpl* const engine_; + + // All methods are invoked on the network thread. + THREAD_CHECKER(network_thread_checker_); + DISALLOW_COPY_AND_ASSIGN(Callback); +}; + +Cronet_EngineImpl::Callback::Callback(Cronet_EngineImpl* engine) + : engine_(engine) { + DETACH_FROM_THREAD(network_thread_checker_); +} + +Cronet_EngineImpl::Callback::~Callback() = default; + +void Cronet_EngineImpl::Callback::OnInitNetworkThread() { + DCHECK_CALLED_ON_VALID_THREAD(network_thread_checker_); + // It is possible that engine_->context_ is reset from main thread while + // being intialized on network thread. + base::AutoLock lock(engine_->lock_); + if (engine_->context_) { + engine_->init_completed_.Signal(); + } +} + +void Cronet_EngineImpl::Callback::OnDestroyNetworkThread() { + DCHECK_CALLED_ON_VALID_THREAD(network_thread_checker_); +} + +void Cronet_EngineImpl::Callback::OnInitCertVerifierData( + net::CertVerifier* cert_verifier, + const std::string& cert_verifier_data) {} + +void Cronet_EngineImpl::Callback::OnSaveCertVerifierData( + net::CertVerifier* cert_verifier) {} + +void Cronet_EngineImpl::Callback::OnEffectiveConnectionTypeChanged( + net::EffectiveConnectionType effective_connection_type) { + NOTIMPLEMENTED(); +} + +void Cronet_EngineImpl::Callback::OnRTTOrThroughputEstimatesComputed( + int32_t http_rtt_ms, + int32_t transport_rtt_ms, + int32_t downstream_throughput_kbps) { + NOTIMPLEMENTED(); +} + +void Cronet_EngineImpl::Callback::OnRTTObservation( + int32_t rtt_ms, + int32_t timestamp_ms, + net::NetworkQualityObservationSource source) { + NOTIMPLEMENTED(); +} + +void Cronet_EngineImpl::Callback::OnThroughputObservation( + int32_t throughput_kbps, + int32_t timestamp_ms, + net::NetworkQualityObservationSource source) { + NOTIMPLEMENTED(); +} + +void Cronet_EngineImpl::Callback::OnStopNetLogCompleted() { + DCHECK_CALLED_ON_VALID_THREAD(network_thread_checker_); + CHECK(engine_); + base::AutoLock lock(engine_->lock_); + DCHECK(engine_->is_logging_); + engine_->is_logging_ = false; + engine_->stop_netlog_completed_.Signal(); +} + +}; // namespace cronet + +CRONET_EXPORT Cronet_EnginePtr Cronet_Engine_Create() { + return new cronet::Cronet_EngineImpl(); +}
diff --git a/components/cronet/native/engine.h b/components/cronet/native/engine.h new file mode 100644 index 0000000..67dcc60 --- /dev/null +++ b/components/cronet/native/engine.h
@@ -0,0 +1,69 @@ +// 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. + +#ifndef COMPONENTS_CRONET_NATIVE_ENGINE_H_ +#define COMPONENTS_CRONET_NATIVE_ENGINE_H_ + +#include <memory> +#include <string> + +#include "base/macros.h" +#include "base/synchronization/lock.h" +#include "base/synchronization/waitable_event.h" +#include "components/cronet/native/generated/cronet.idl_impl_interface.h" + +namespace cronet { + +class CronetURLRequestContext; + +// Implementation of Cronet_Engine that uses CronetURLRequestContext. +class Cronet_EngineImpl : public Cronet_Engine { + public: + Cronet_EngineImpl(); + ~Cronet_EngineImpl() override; + + // Cronet_Engine implementation: + void SetContext(Cronet_EngineContext context) override; + Cronet_EngineContext GetContext() override; + Cronet_RESULT StartWithParams(Cronet_EngineParamsPtr params) override; + bool StartNetLogToFile(CharString fileName, bool logAll) override; + void StopNetLog() override; + CharString GetVersionString() override; + CharString GetDefaultUserAgent() override; + Cronet_RESULT Shutdown() override; + + // Check |result| and aborts if result is not SUCCESS and enableCheckResult + // is true. + Cronet_RESULT CheckResult(Cronet_RESULT result); + + private: + class Callback; + + // Enable runtime CHECK of the result. + bool enable_check_result_ = true; + + // Synchronize access to member variables from different threads. + base::Lock lock_; + // Cronet URLRequest context used for all network operations. + std::unique_ptr<CronetURLRequestContext> context_; + // Signaled when |context_| initialization is done. + base::WaitableEvent init_completed_; + + // Flag that indicates whether logging is in progress. + bool is_logging_ = false; + // Signaled when |StopNetLog| is done. + base::WaitableEvent stop_netlog_completed_; + + // Storage path used by this engine. + std::string in_use_storage_path_; + + // Engine context. Not owned, accessed from client thread. + Cronet_EngineContext engine_context_ = nullptr; + + DISALLOW_COPY_AND_ASSIGN(Cronet_EngineImpl); +}; + +}; // namespace cronet + +#endif // COMPONENTS_CRONET_NATIVE_ENGINE_H_
diff --git a/components/cronet/native/engine_test.cc b/components/cronet/native/engine_test.cc new file mode 100644 index 0000000..752c6ee --- /dev/null +++ b/components/cronet/native/engine_test.cc
@@ -0,0 +1,200 @@ +// 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 "cronet_c.h" + +#include "base/files/file_util.h" +#include "base/files/scoped_temp_dir.h" +#include "base/logging.h" +#include "base/macros.h" +#include "base/test/scoped_task_environment.h" +#include "components/cronet/native/test_util.h" +#include "testing/gtest/include/gtest/gtest.h" + +namespace { + +const char* kUserAgent = "EngineTest/1"; + +class EngineTest : public ::testing::Test { + protected: + EngineTest() = default; + ~EngineTest() override {} + + private: + DISALLOW_COPY_AND_ASSIGN(EngineTest); +}; + +TEST_F(EngineTest, StartCronetEngine) { + Cronet_EnginePtr engine = Cronet_Engine_Create(); + Cronet_EngineParamsPtr engine_params = Cronet_EngineParams_Create(); + Cronet_EngineParams_set_userAgent(engine_params, kUserAgent); + EXPECT_EQ(Cronet_RESULT_SUCCESS, + Cronet_Engine_StartWithParams(engine, engine_params)); + Cronet_Engine_Destroy(engine); + Cronet_EngineParams_Destroy(engine_params); +} + +TEST_F(EngineTest, CronetEngineDefaultUserAgent) { + Cronet_EnginePtr engine = Cronet_Engine_Create(); + // Version and DefaultUserAgent don't require engine start. + std::string version = Cronet_Engine_GetVersionString(engine); + std::string default_agent = Cronet_Engine_GetDefaultUserAgent(engine); + EXPECT_NE(default_agent.find(version), std::string::npos); + Cronet_Engine_Destroy(engine); +} + +TEST_F(EngineTest, InitDifferentEngines) { + Cronet_EngineParamsPtr engine_params = Cronet_EngineParams_Create(); + Cronet_EnginePtr first_engine = Cronet_Engine_Create(); + Cronet_Engine_StartWithParams(first_engine, engine_params); + Cronet_EnginePtr second_engine = Cronet_Engine_Create(); + Cronet_Engine_StartWithParams(second_engine, engine_params); + Cronet_EnginePtr third_engine = Cronet_Engine_Create(); + Cronet_Engine_StartWithParams(third_engine, engine_params); + Cronet_EngineParams_Destroy(engine_params); + Cronet_Engine_Destroy(first_engine); + Cronet_Engine_Destroy(second_engine); + Cronet_Engine_Destroy(third_engine); +} + +TEST_F(EngineTest, StartResults) { + Cronet_EngineParamsPtr engine_params = Cronet_EngineParams_Create(); + Cronet_EnginePtr engine = Cronet_Engine_Create(); + // Disable runtime CHECK of the result, so it could be verified. + Cronet_EngineParams_set_enableCheckResult(engine_params, false); + Cronet_EngineParams_set_httpCacheMode( + engine_params, Cronet_EngineParams_HTTP_CACHE_MODE_DISK); + EXPECT_EQ(Cronet_RESULT_ILLEGAL_ARGUMENT_STORAGE_PATH_MUST_EXIST, + Cronet_Engine_StartWithParams(engine, engine_params)); + Cronet_EngineParams_set_storagePath(engine_params, "InvalidPath"); + EXPECT_EQ(Cronet_RESULT_ILLEGAL_ARGUMENT_STORAGE_PATH_MUST_EXIST, + Cronet_Engine_StartWithParams(engine, engine_params)); + base::ScopedTempDir temp_dir; + EXPECT_TRUE(temp_dir.CreateUniqueTempDir()); + base::FilePath temp_path = base::MakeAbsoluteFilePath(temp_dir.GetPath()); + Cronet_EngineParams_set_storagePath(engine_params, temp_path.value().c_str()); + // Now the engine should start successfully. + EXPECT_EQ(Cronet_RESULT_SUCCESS, + Cronet_Engine_StartWithParams(engine, engine_params)); + // The second start should fail. + EXPECT_EQ(Cronet_RESULT_ILLEGAL_STATE_ENGINE_ALREADY_STARTED, + Cronet_Engine_StartWithParams(engine, engine_params)); + // The second engine should fail because storage path is already used. + Cronet_EnginePtr second_engine = Cronet_Engine_Create(); + EXPECT_EQ(Cronet_RESULT_ILLEGAL_STATE_STORAGE_PATH_IN_USE, + Cronet_Engine_StartWithParams(second_engine, engine_params)); + // Shutdown first engine to free storage path. + EXPECT_EQ(Cronet_RESULT_SUCCESS, Cronet_Engine_Shutdown(engine)); + // Now the second engine should start. + EXPECT_EQ(Cronet_RESULT_SUCCESS, + Cronet_Engine_StartWithParams(second_engine, engine_params)); + Cronet_Engine_Destroy(second_engine); + Cronet_Engine_Destroy(engine); + Cronet_EngineParams_Destroy(engine_params); +} + +TEST_F(EngineTest, InvalidPkpParams) { + Cronet_EngineParamsPtr engine_params = Cronet_EngineParams_Create(); + Cronet_EnginePtr engine = Cronet_Engine_Create(); + // Disable runtime CHECK of the result, so it could be verified. + Cronet_EngineParams_set_enableCheckResult(engine_params, false); + // Try adding invalid public key pins. + Cronet_PublicKeyPinsPtr public_key_pins = Cronet_PublicKeyPins_Create(); + Cronet_EngineParams_add_publicKeyPins(engine_params, public_key_pins); + EXPECT_EQ(Cronet_RESULT_NULL_POINTER_HOSTNAME, + Cronet_Engine_StartWithParams(engine, engine_params)); + Cronet_PublicKeyPins_set_host(public_key_pins, std::string(256, 'a').c_str()); + EXPECT_EQ(Cronet_RESULT_ILLEGAL_ARGUMENT_INVALID_HOSTNAME, + Cronet_Engine_StartWithParams(engine, engine_params)); + Cronet_PublicKeyPins_set_host(public_key_pins, "invalid:host/name"); + EXPECT_EQ(Cronet_RESULT_ILLEGAL_ARGUMENT_INVALID_HOSTNAME, + Cronet_Engine_StartWithParams(engine, engine_params)); + Cronet_PublicKeyPins_set_host(public_key_pins, "valid.host.name"); + // Detect missing pins. + EXPECT_EQ(Cronet_RESULT_NULL_POINTER_SHA256_PINS, + Cronet_Engine_StartWithParams(engine, engine_params)); + // Detect invalid pin. + Cronet_PublicKeyPins_add_pinsSha256(public_key_pins, "invalid_sha256"); + EXPECT_EQ(Cronet_RESULT_ILLEGAL_ARGUMENT_INVALID_PIN, + Cronet_Engine_StartWithParams(engine, engine_params)); + // THe engine cannot start with these params, and have to be destroyed. + Cronet_Engine_Destroy(engine); + Cronet_EngineParams_Destroy(engine_params); +} + +TEST_F(EngineTest, ValidPkpParams) { + Cronet_EngineParamsPtr engine_params = Cronet_EngineParams_Create(); + Cronet_EnginePtr engine = Cronet_Engine_Create(); + // Disable runtime CHECK of the result, so it could be verified. + Cronet_EngineParams_set_enableCheckResult(engine_params, false); + // Add valid public key pins. + Cronet_PublicKeyPinsPtr public_key_pins = Cronet_PublicKeyPins_Create(); + Cronet_PublicKeyPins_set_host(public_key_pins, "valid.host.name"); + Cronet_PublicKeyPins_add_pinsSha256( + public_key_pins, "sha256/AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA="); + Cronet_EngineParams_add_publicKeyPins(engine_params, public_key_pins); + // The engine should start successfully. + EXPECT_EQ(Cronet_RESULT_SUCCESS, + Cronet_Engine_StartWithParams(engine, engine_params)); + Cronet_Engine_Destroy(engine); + Cronet_EngineParams_Destroy(engine_params); +} + +TEST_F(EngineTest, StartNetLogToFile) { + base::ScopedTempDir temp_dir; + EXPECT_TRUE(temp_dir.CreateUniqueTempDir()); + base::FilePath temp_path = base::MakeAbsoluteFilePath(temp_dir.GetPath()); + base::FilePath net_log_file = + temp_path.Append(FILE_PATH_LITERAL("netlog.json")); + + Cronet_EnginePtr engine = Cronet_Engine_Create(); + Cronet_EngineParamsPtr engine_params = Cronet_EngineParams_Create(); + Cronet_EngineParams_set_experimentalOptions( + engine_params, + "{ \"QUIC\" : {\"max_server_configs_stored_in_properties\" : 8} }"); + // Test that net log cannot start/stop before engine start. + EXPECT_FALSE(Cronet_Engine_StartNetLogToFile( + engine, net_log_file.value().c_str(), true)); + Cronet_Engine_StopNetLog(engine); + + // Start the engine. + Cronet_Engine_StartWithParams(engine, engine_params); + Cronet_EngineParams_Destroy(engine_params); + + // Test that normal start/stop net log works. + EXPECT_TRUE(Cronet_Engine_StartNetLogToFile( + engine, net_log_file.value().c_str(), true)); + Cronet_Engine_StopNetLog(engine); + + // Test that double start/stop net log works. + EXPECT_TRUE(Cronet_Engine_StartNetLogToFile( + engine, net_log_file.value().c_str(), true)); + // Test that second start fails. + EXPECT_FALSE(Cronet_Engine_StartNetLogToFile( + engine, net_log_file.value().c_str(), true)); + // Test that multiple stops work. + Cronet_Engine_StopNetLog(engine); + Cronet_Engine_StopNetLog(engine); + Cronet_Engine_StopNetLog(engine); + + // Test that net log contains effective experimental options. + std::string net_log; + EXPECT_TRUE(base::ReadFileToString(net_log_file, &net_log)); + EXPECT_TRUE( + net_log.find( + "{\"QUIC\":{\"max_server_configs_stored_in_properties\":8}") != + std::string::npos); + + // Test that bad file name fails. + EXPECT_FALSE(Cronet_Engine_StartNetLogToFile(engine, "bad/file/name", true)); + + Cronet_Engine_Shutdown(engine); + // Test that net log cannot start/stop after engine shutdown. + EXPECT_FALSE(Cronet_Engine_StartNetLogToFile( + engine, net_log_file.value().c_str(), true)); + Cronet_Engine_StopNetLog(engine); + Cronet_Engine_Destroy(engine); +} + +} // namespace
diff --git a/components/cronet/native/generated/cronet.idl_c.h b/components/cronet/native/generated/cronet.idl_c.h index d5169f07..d8e1ff20 100644 --- a/components/cronet/native/generated/cronet.idl_c.h +++ b/components/cronet/native/generated/cronet.idl_c.h
@@ -67,6 +67,22 @@ typedef struct Cronet_UrlRequestParams* Cronet_UrlRequestParamsPtr; // Declare enums +typedef enum Cronet_RESULT { + Cronet_RESULT_SUCCESS = 0, + Cronet_RESULT_ILLEGAL_ARGUMENT = -100, + Cronet_RESULT_ILLEGAL_ARGUMENT_STORAGE_PATH_MUST_EXIST = -101, + Cronet_RESULT_ILLEGAL_ARGUMENT_INVALID_PIN = -102, + Cronet_RESULT_ILLEGAL_ARGUMENT_INVALID_HOSTNAME = -103, + Cronet_RESULT_ILLEGAL_STATE = -200, + Cronet_RESULT_ILLEGAL_STATE_STORAGE_PATH_IN_USE = -201, + Cronet_RESULT_ILLEGAL_STATE_CANNOT_SHUTDOWN_ENGINE_FROM_NETWORK_THREAD = -202, + Cronet_RESULT_ILLEGAL_STATE_ENGINE_ALREADY_STARTED = -203, + Cronet_RESULT_NULL_POINTER = -300, + Cronet_RESULT_NULL_POINTER_HOSTNAME = -301, + Cronet_RESULT_NULL_POINTER_SHA256_PINS = -302, + Cronet_RESULT_NULL_POINTER_EXPIRATION_DATE = -303, +} Cronet_RESULT; + typedef enum Cronet_Exception_ERROR_CODE { Cronet_Exception_ERROR_CODE_ERROR_CALLBACK = 0, Cronet_Exception_ERROR_CODE_ERROR_HOSTNAME_NOT_RESOLVED = 1, @@ -256,27 +272,30 @@ // Concrete methods of Cronet_Engine implemented by Cronet. // The app calls them to manipulate Cronet_Engine. CRONET_EXPORT -void Cronet_Engine_StartWithParams(Cronet_EnginePtr self, - Cronet_EngineParamsPtr params); +Cronet_RESULT Cronet_Engine_StartWithParams(Cronet_EnginePtr self, + Cronet_EngineParamsPtr params); CRONET_EXPORT -void Cronet_Engine_StartNetLogToFile(Cronet_EnginePtr self, +bool Cronet_Engine_StartNetLogToFile(Cronet_EnginePtr self, CharString fileName, bool logAll); CRONET_EXPORT void Cronet_Engine_StopNetLog(Cronet_EnginePtr self); CRONET_EXPORT +Cronet_RESULT Cronet_Engine_Shutdown(Cronet_EnginePtr self); +CRONET_EXPORT CharString Cronet_Engine_GetVersionString(Cronet_EnginePtr self); CRONET_EXPORT CharString Cronet_Engine_GetDefaultUserAgent(Cronet_EnginePtr self); // Concrete interface Cronet_Engine is implemented by Cronet. // The app can implement these for testing / mocking. -typedef void (*Cronet_Engine_StartWithParamsFunc)( +typedef Cronet_RESULT (*Cronet_Engine_StartWithParamsFunc)( Cronet_EnginePtr self, Cronet_EngineParamsPtr params); -typedef void (*Cronet_Engine_StartNetLogToFileFunc)(Cronet_EnginePtr self, +typedef bool (*Cronet_Engine_StartNetLogToFileFunc)(Cronet_EnginePtr self, CharString fileName, bool logAll); typedef void (*Cronet_Engine_StopNetLogFunc)(Cronet_EnginePtr self); +typedef Cronet_RESULT (*Cronet_Engine_ShutdownFunc)(Cronet_EnginePtr self); typedef CharString (*Cronet_Engine_GetVersionStringFunc)(Cronet_EnginePtr self); typedef CharString (*Cronet_Engine_GetDefaultUserAgentFunc)( Cronet_EnginePtr self); @@ -286,6 +305,7 @@ Cronet_Engine_StartWithParamsFunc StartWithParamsFunc, Cronet_Engine_StartNetLogToFileFunc StartNetLogToFileFunc, Cronet_Engine_StopNetLogFunc StopNetLogFunc, + Cronet_Engine_ShutdownFunc ShutdownFunc, Cronet_Engine_GetVersionStringFunc GetVersionStringFunc, Cronet_Engine_GetDefaultUserAgentFunc GetDefaultUserAgentFunc); @@ -626,20 +646,25 @@ CharString host); CRONET_EXPORT void Cronet_PublicKeyPins_add_pinsSha256(Cronet_PublicKeyPinsPtr self, - RawDataPtr pinsSha256); + CharString pinsSha256); CRONET_EXPORT void Cronet_PublicKeyPins_set_includeSubdomains(Cronet_PublicKeyPinsPtr self, bool includeSubdomains); +CRONET_EXPORT +void Cronet_PublicKeyPins_set_expirationDate(Cronet_PublicKeyPinsPtr self, + int64_t expirationDate); // Cronet_PublicKeyPins getters. CRONET_EXPORT CharString Cronet_PublicKeyPins_get_host(Cronet_PublicKeyPinsPtr self); CRONET_EXPORT uint32_t Cronet_PublicKeyPins_get_pinsSha256Size(Cronet_PublicKeyPinsPtr self); -RawDataPtr Cronet_PublicKeyPins_get_pinsSha256AtIndex( +CharString Cronet_PublicKeyPins_get_pinsSha256AtIndex( Cronet_PublicKeyPinsPtr self, uint32_t index); CRONET_EXPORT bool Cronet_PublicKeyPins_get_includeSubdomains(Cronet_PublicKeyPinsPtr self); +CRONET_EXPORT +int64_t Cronet_PublicKeyPins_get_expirationDate(Cronet_PublicKeyPinsPtr self); /////////////////////// // Struct Cronet_EngineParams. @@ -647,9 +672,15 @@ CRONET_EXPORT void Cronet_EngineParams_Destroy(Cronet_EngineParamsPtr self); // Cronet_EngineParams setters. CRONET_EXPORT +void Cronet_EngineParams_set_enableCheckResult(Cronet_EngineParamsPtr self, + bool enableCheckResult); +CRONET_EXPORT void Cronet_EngineParams_set_userAgent(Cronet_EngineParamsPtr self, CharString userAgent); CRONET_EXPORT +void Cronet_EngineParams_set_acceptLanguage(Cronet_EngineParamsPtr self, + CharString acceptLanguage); +CRONET_EXPORT void Cronet_EngineParams_set_storagePath(Cronet_EngineParamsPtr self, CharString storagePath); CRONET_EXPORT @@ -679,10 +710,18 @@ void Cronet_EngineParams_set_enablePublicKeyPinningBypassForLocalTrustAnchors( Cronet_EngineParamsPtr self, bool enablePublicKeyPinningBypassForLocalTrustAnchors); +CRONET_EXPORT +void Cronet_EngineParams_set_experimentalOptions( + Cronet_EngineParamsPtr self, + CharString experimentalOptions); // Cronet_EngineParams getters. CRONET_EXPORT +bool Cronet_EngineParams_get_enableCheckResult(Cronet_EngineParamsPtr self); +CRONET_EXPORT CharString Cronet_EngineParams_get_userAgent(Cronet_EngineParamsPtr self); CRONET_EXPORT +CharString Cronet_EngineParams_get_acceptLanguage(Cronet_EngineParamsPtr self); +CRONET_EXPORT CharString Cronet_EngineParams_get_storagePath(Cronet_EngineParamsPtr self); CRONET_EXPORT bool Cronet_EngineParams_get_enableQuic(Cronet_EngineParamsPtr self); @@ -708,6 +747,9 @@ CRONET_EXPORT bool Cronet_EngineParams_get_enablePublicKeyPinningBypassForLocalTrustAnchors( Cronet_EngineParamsPtr self); +CRONET_EXPORT +CharString Cronet_EngineParams_get_experimentalOptions( + Cronet_EngineParamsPtr self); /////////////////////// // Struct Cronet_HttpHeader.
diff --git a/components/cronet/native/generated/cronet.idl_impl_interface.cc b/components/cronet/native/generated/cronet.idl_impl_interface.cc index 04ac221c..9e89d89 100644 --- a/components/cronet/native/generated/cronet.idl_impl_interface.cc +++ b/components/cronet/native/generated/cronet.idl_impl_interface.cc
@@ -281,17 +281,17 @@ return self->GetContext(); } -void Cronet_Engine_StartWithParams(Cronet_EnginePtr self, - Cronet_EngineParamsPtr params) { +Cronet_RESULT Cronet_Engine_StartWithParams(Cronet_EnginePtr self, + Cronet_EngineParamsPtr params) { DCHECK(self); - self->StartWithParams(params); + return self->StartWithParams(params); } -void Cronet_Engine_StartNetLogToFile(Cronet_EnginePtr self, +bool Cronet_Engine_StartNetLogToFile(Cronet_EnginePtr self, CharString fileName, bool logAll) { DCHECK(self); - self->StartNetLogToFile(fileName, logAll); + return self->StartNetLogToFile(fileName, logAll); } void Cronet_Engine_StopNetLog(Cronet_EnginePtr self) { @@ -299,6 +299,11 @@ self->StopNetLog(); } +Cronet_RESULT Cronet_Engine_Shutdown(Cronet_EnginePtr self) { + DCHECK(self); + return self->Shutdown(); +} + CharString Cronet_Engine_GetVersionString(Cronet_EnginePtr self) { DCHECK(self); return self->GetVersionString(); @@ -317,11 +322,13 @@ Cronet_Engine_StartWithParamsFunc StartWithParamsFunc, Cronet_Engine_StartNetLogToFileFunc StartNetLogToFileFunc, Cronet_Engine_StopNetLogFunc StopNetLogFunc, + Cronet_Engine_ShutdownFunc ShutdownFunc, Cronet_Engine_GetVersionStringFunc GetVersionStringFunc, Cronet_Engine_GetDefaultUserAgentFunc GetDefaultUserAgentFunc) : StartWithParamsFunc_(StartWithParamsFunc), StartNetLogToFileFunc_(StartNetLogToFileFunc), StopNetLogFunc_(StopNetLogFunc), + ShutdownFunc_(ShutdownFunc), GetVersionStringFunc_(GetVersionStringFunc), GetDefaultUserAgentFunc_(GetDefaultUserAgentFunc) {} @@ -332,16 +339,18 @@ Cronet_EngineContext GetContext() override { return context_; } protected: - void StartWithParams(Cronet_EngineParamsPtr params) override { - StartWithParamsFunc_(this, params); + Cronet_RESULT StartWithParams(Cronet_EngineParamsPtr params) override { + return StartWithParamsFunc_(this, params); } - void StartNetLogToFile(CharString fileName, bool logAll) override { - StartNetLogToFileFunc_(this, fileName, logAll); + bool StartNetLogToFile(CharString fileName, bool logAll) override { + return StartNetLogToFileFunc_(this, fileName, logAll); } void StopNetLog() override { StopNetLogFunc_(this); } + Cronet_RESULT Shutdown() override { return ShutdownFunc_(this); } + CharString GetVersionString() override { return GetVersionStringFunc_(this); } CharString GetDefaultUserAgent() override { @@ -353,6 +362,7 @@ const Cronet_Engine_StartWithParamsFunc StartWithParamsFunc_; const Cronet_Engine_StartNetLogToFileFunc StartNetLogToFileFunc_; const Cronet_Engine_StopNetLogFunc StopNetLogFunc_; + const Cronet_Engine_ShutdownFunc ShutdownFunc_; const Cronet_Engine_GetVersionStringFunc GetVersionStringFunc_; const Cronet_Engine_GetDefaultUserAgentFunc GetDefaultUserAgentFunc_; @@ -363,11 +373,12 @@ Cronet_Engine_StartWithParamsFunc StartWithParamsFunc, Cronet_Engine_StartNetLogToFileFunc StartNetLogToFileFunc, Cronet_Engine_StopNetLogFunc StopNetLogFunc, + Cronet_Engine_ShutdownFunc ShutdownFunc, Cronet_Engine_GetVersionStringFunc GetVersionStringFunc, Cronet_Engine_GetDefaultUserAgentFunc GetDefaultUserAgentFunc) { return new Cronet_EngineStub(StartWithParamsFunc, StartNetLogToFileFunc, - StopNetLogFunc, GetVersionStringFunc, - GetDefaultUserAgentFunc); + StopNetLogFunc, ShutdownFunc, + GetVersionStringFunc, GetDefaultUserAgentFunc); } // C functions of Cronet_UrlRequestStatusListener that forward calls to C++
diff --git a/components/cronet/native/generated/cronet.idl_impl_interface.h b/components/cronet/native/generated/cronet.idl_impl_interface.h index 7cf09d9..f0395f7 100644 --- a/components/cronet/native/generated/cronet.idl_impl_interface.h +++ b/components/cronet/native/generated/cronet.idl_impl_interface.h
@@ -77,9 +77,10 @@ virtual void SetContext(Cronet_EngineContext context) = 0; virtual Cronet_EngineContext GetContext() = 0; - virtual void StartWithParams(Cronet_EngineParamsPtr params) = 0; - virtual void StartNetLogToFile(CharString fileName, bool logAll) = 0; + virtual Cronet_RESULT StartWithParams(Cronet_EngineParamsPtr params) = 0; + virtual bool StartNetLogToFile(CharString fileName, bool logAll) = 0; virtual void StopNetLog() = 0; + virtual Cronet_RESULT Shutdown() = 0; virtual CharString GetVersionString() = 0; virtual CharString GetDefaultUserAgent() = 0;
diff --git a/components/cronet/native/generated/cronet.idl_impl_interface_unittest.cc b/components/cronet/native/generated/cronet.idl_impl_interface_unittest.cc index 09c3c95..43f72cb 100644 --- a/components/cronet/native/generated/cronet.idl_impl_interface_unittest.cc +++ b/components/cronet/native/generated/cronet.idl_impl_interface_unittest.cc
@@ -222,6 +222,7 @@ bool StartWithParams_called_ = false; bool StartNetLogToFile_called_ = false; bool StopNetLog_called_ = false; + bool Shutdown_called_ = false; bool GetVersionString_called_ = false; bool GetDefaultUserAgent_called_ = false; @@ -231,15 +232,17 @@ namespace { // Implementation of Cronet_Engine methods for testing. -void TestCronet_Engine_StartWithParams(Cronet_EnginePtr self, - Cronet_EngineParamsPtr params) { +Cronet_RESULT TestCronet_Engine_StartWithParams(Cronet_EnginePtr self, + Cronet_EngineParamsPtr params) { CHECK(self); Cronet_EngineContext context = Cronet_Engine_GetContext(self); Cronet_EngineTest* test = static_cast<Cronet_EngineTest*>(context); CHECK(test); test->StartWithParams_called_ = true; + + return static_cast<Cronet_RESULT>(0); } -void TestCronet_Engine_StartNetLogToFile(Cronet_EnginePtr self, +bool TestCronet_Engine_StartNetLogToFile(Cronet_EnginePtr self, CharString fileName, bool logAll) { CHECK(self); @@ -247,6 +250,8 @@ Cronet_EngineTest* test = static_cast<Cronet_EngineTest*>(context); CHECK(test); test->StartNetLogToFile_called_ = true; + + return static_cast<bool>(0); } void TestCronet_Engine_StopNetLog(Cronet_EnginePtr self) { CHECK(self); @@ -255,6 +260,15 @@ CHECK(test); test->StopNetLog_called_ = true; } +Cronet_RESULT TestCronet_Engine_Shutdown(Cronet_EnginePtr self) { + CHECK(self); + Cronet_EngineContext context = Cronet_Engine_GetContext(self); + Cronet_EngineTest* test = static_cast<Cronet_EngineTest*>(context); + CHECK(test); + test->Shutdown_called_ = true; + + return static_cast<Cronet_RESULT>(0); +} CharString TestCronet_Engine_GetVersionString(Cronet_EnginePtr self) { CHECK(self); Cronet_EngineContext context = Cronet_Engine_GetContext(self); @@ -279,7 +293,8 @@ TEST_F(Cronet_EngineTest, TestCreate) { Cronet_EnginePtr test = Cronet_Engine_CreateStub( TestCronet_Engine_StartWithParams, TestCronet_Engine_StartNetLogToFile, - TestCronet_Engine_StopNetLog, TestCronet_Engine_GetVersionString, + TestCronet_Engine_StopNetLog, TestCronet_Engine_Shutdown, + TestCronet_Engine_GetVersionString, TestCronet_Engine_GetDefaultUserAgent); CHECK(test); Cronet_Engine_SetContext(test, this); @@ -287,6 +302,8 @@ CHECK(!StartNetLogToFile_called_); Cronet_Engine_StopNetLog(test); CHECK(StopNetLog_called_); + Cronet_Engine_Shutdown(test); + CHECK(Shutdown_called_); Cronet_Engine_GetVersionString(test); CHECK(GetVersionString_called_); Cronet_Engine_GetDefaultUserAgent(test);
diff --git a/components/cronet/native/generated/cronet.idl_impl_struct.cc b/components/cronet/native/generated/cronet.idl_impl_struct.cc index 34e3cbe50..a57f0118 100644 --- a/components/cronet/native/generated/cronet.idl_impl_struct.cc +++ b/components/cronet/native/generated/cronet.idl_impl_struct.cc
@@ -139,7 +139,7 @@ } void Cronet_PublicKeyPins_add_pinsSha256(Cronet_PublicKeyPinsPtr self, - RawDataPtr pinsSha256) { + CharString pinsSha256) { DCHECK(self); self->pinsSha256.push_back(pinsSha256); } @@ -150,6 +150,12 @@ self->includeSubdomains = includeSubdomains; } +void Cronet_PublicKeyPins_set_expirationDate(Cronet_PublicKeyPinsPtr self, + int64_t expirationDate) { + DCHECK(self); + self->expirationDate = expirationDate; +} + // Struct Cronet_PublicKeyPins getters. CharString Cronet_PublicKeyPins_get_host(Cronet_PublicKeyPinsPtr self) { DCHECK(self); @@ -160,12 +166,12 @@ DCHECK(self); return self->pinsSha256.size(); } -RawDataPtr Cronet_PublicKeyPins_get_pinsSha256AtIndex( +CharString Cronet_PublicKeyPins_get_pinsSha256AtIndex( Cronet_PublicKeyPinsPtr self, uint32_t index) { DCHECK(self); DCHECK(index < self->pinsSha256.size()); - return self->pinsSha256[index]; + return self->pinsSha256[index].c_str(); } bool Cronet_PublicKeyPins_get_includeSubdomains(Cronet_PublicKeyPinsPtr self) { @@ -173,6 +179,11 @@ return self->includeSubdomains; } +int64_t Cronet_PublicKeyPins_get_expirationDate(Cronet_PublicKeyPinsPtr self) { + DCHECK(self); + return self->expirationDate; +} + // Struct Cronet_EngineParams. Cronet_EngineParams::Cronet_EngineParams() {} @@ -187,12 +198,24 @@ } // Struct Cronet_EngineParams setters. +void Cronet_EngineParams_set_enableCheckResult(Cronet_EngineParamsPtr self, + bool enableCheckResult) { + DCHECK(self); + self->enableCheckResult = enableCheckResult; +} + void Cronet_EngineParams_set_userAgent(Cronet_EngineParamsPtr self, CharString userAgent) { DCHECK(self); self->userAgent = userAgent; } +void Cronet_EngineParams_set_acceptLanguage(Cronet_EngineParamsPtr self, + CharString acceptLanguage) { + DCHECK(self); + self->acceptLanguage = acceptLanguage; +} + void Cronet_EngineParams_set_storagePath(Cronet_EngineParamsPtr self, CharString storagePath) { DCHECK(self); @@ -253,12 +276,29 @@ enablePublicKeyPinningBypassForLocalTrustAnchors; } +void Cronet_EngineParams_set_experimentalOptions( + Cronet_EngineParamsPtr self, + CharString experimentalOptions) { + DCHECK(self); + self->experimentalOptions = experimentalOptions; +} + // Struct Cronet_EngineParams getters. +bool Cronet_EngineParams_get_enableCheckResult(Cronet_EngineParamsPtr self) { + DCHECK(self); + return self->enableCheckResult; +} + CharString Cronet_EngineParams_get_userAgent(Cronet_EngineParamsPtr self) { DCHECK(self); return self->userAgent.c_str(); } +CharString Cronet_EngineParams_get_acceptLanguage(Cronet_EngineParamsPtr self) { + DCHECK(self); + return self->acceptLanguage.c_str(); +} + CharString Cronet_EngineParams_get_storagePath(Cronet_EngineParamsPtr self) { DCHECK(self); return self->storagePath.c_str(); @@ -321,6 +361,12 @@ return self->enablePublicKeyPinningBypassForLocalTrustAnchors; } +CharString Cronet_EngineParams_get_experimentalOptions( + Cronet_EngineParamsPtr self) { + DCHECK(self); + return self->experimentalOptions.c_str(); +} + // Struct Cronet_HttpHeader. Cronet_HttpHeader::Cronet_HttpHeader() {}
diff --git a/components/cronet/native/generated/cronet.idl_impl_struct.h b/components/cronet/native/generated/cronet.idl_impl_struct.h index 6107156d..ab3b7e1 100644 --- a/components/cronet/native/generated/cronet.idl_impl_struct.h +++ b/components/cronet/native/generated/cronet.idl_impl_struct.h
@@ -52,8 +52,9 @@ ~Cronet_PublicKeyPins(); std::string host; - std::vector<RawDataPtr> pinsSha256; + std::vector<std::string> pinsSha256; bool includeSubdomains = false; + int64_t expirationDate; private: DISALLOW_COPY_AND_ASSIGN(Cronet_PublicKeyPins); @@ -65,7 +66,9 @@ Cronet_EngineParams(); ~Cronet_EngineParams(); + bool enableCheckResult = true; std::string userAgent; + std::string acceptLanguage; std::string storagePath; bool enableQuic = false; bool enableHttp2 = true; @@ -76,6 +79,7 @@ std::vector<std::unique_ptr<Cronet_QuicHint>> quicHints; std::vector<std::unique_ptr<Cronet_PublicKeyPins>> publicKeyPins; bool enablePublicKeyPinningBypassForLocalTrustAnchors = true; + std::string experimentalOptions; private: DISALLOW_COPY_AND_ASSIGN(Cronet_EngineParams);
diff --git a/components/cronet/native/generated/cronet.idl_impl_struct_unittest.cc b/components/cronet/native/generated/cronet.idl_impl_struct_unittest.cc index e2027e3..f255245 100644 --- a/components/cronet/native/generated/cronet.idl_impl_struct_unittest.cc +++ b/components/cronet/native/generated/cronet.idl_impl_struct_unittest.cc
@@ -82,6 +82,10 @@ second, Cronet_PublicKeyPins_get_includeSubdomains(first)); EXPECT_EQ(Cronet_PublicKeyPins_get_includeSubdomains(first), Cronet_PublicKeyPins_get_includeSubdomains(second)); + Cronet_PublicKeyPins_set_expirationDate( + second, Cronet_PublicKeyPins_get_expirationDate(first)); + EXPECT_EQ(Cronet_PublicKeyPins_get_expirationDate(first), + Cronet_PublicKeyPins_get_expirationDate(second)); Cronet_PublicKeyPins_Destroy(first); Cronet_PublicKeyPins_Destroy(second); } @@ -92,10 +96,18 @@ Cronet_EngineParamsPtr second = Cronet_EngineParams_Create(); // Copy values from |first| to |second|. + Cronet_EngineParams_set_enableCheckResult( + second, Cronet_EngineParams_get_enableCheckResult(first)); + EXPECT_EQ(Cronet_EngineParams_get_enableCheckResult(first), + Cronet_EngineParams_get_enableCheckResult(second)); Cronet_EngineParams_set_userAgent(second, Cronet_EngineParams_get_userAgent(first)); EXPECT_STREQ(Cronet_EngineParams_get_userAgent(first), Cronet_EngineParams_get_userAgent(second)); + Cronet_EngineParams_set_acceptLanguage( + second, Cronet_EngineParams_get_acceptLanguage(first)); + EXPECT_STREQ(Cronet_EngineParams_get_acceptLanguage(first), + Cronet_EngineParams_get_acceptLanguage(second)); Cronet_EngineParams_set_storagePath( second, Cronet_EngineParams_get_storagePath(first)); EXPECT_STREQ(Cronet_EngineParams_get_storagePath(first), @@ -131,6 +143,10 @@ first), Cronet_EngineParams_get_enablePublicKeyPinningBypassForLocalTrustAnchors( second)); + Cronet_EngineParams_set_experimentalOptions( + second, Cronet_EngineParams_get_experimentalOptions(first)); + EXPECT_STREQ(Cronet_EngineParams_get_experimentalOptions(first), + Cronet_EngineParams_get_experimentalOptions(second)); Cronet_EngineParams_Destroy(first); Cronet_EngineParams_Destroy(second); }
diff --git a/components/cronet/stale_host_resolver_unittest.cc b/components/cronet/stale_host_resolver_unittest.cc index e1c8be4..b35871a 100644 --- a/components/cronet/stale_host_resolver_unittest.cc +++ b/components/cronet/stale_host_resolver_unittest.cc
@@ -501,6 +501,8 @@ false, // Storage path for http cache and cookie storage. "/data/data/org.chromium.net/app_cronet_test/test_storage", + // Accept-Language request header field. + "foreign-language", // User-Agent request header field. "fake agent", // JSON encoded experimental options.
diff --git a/components/cronet/tools/cr_cronet.py b/components/cronet/tools/cr_cronet.py index bb32d410..bb7422e 100755 --- a/components/cronet/tools/cr_cronet.py +++ b/components/cronet/tools/cr_cronet.py
@@ -81,6 +81,8 @@ help='name of the build directory') parser.add_argument('-i', '--iphoneos', action='store_true', help='build for physical iphone') + parser.add_argument('-x', '--x86', action='store_true', + help='build for Intel x86 architecture') parser.add_argument('-r', '--release', action='store_true', help='use release configuration') parser.add_argument('-a', '--asan', action='store_true', @@ -99,25 +101,30 @@ 'use_xcode_clang=true ios_deployment_target="9.0" ' gn_extra = '--ide=xcode' if options.iphoneos: - gn_args += ' target_cpu="arm64" ' + gn_args += 'target_cpu="arm64" ' out_dir_suffix = '-iphoneos' else: - gn_args += ' target_cpu="x64" ' + gn_args += 'target_cpu="x64" ' out_dir_suffix = '-iphonesimulator' if options.asan: - gn_args += ' is_asan=true use_xcode_clang=true ' + gn_args += 'is_asan=true use_xcode_clang=true ' out_dir_suffix += '-asan' else: target_os = 'android' test_target = 'cronet_test_instrumentation_apk' unit_target = 'cronet_unittests' - gn_args = 'use_errorprone_java_compiler=true arm_use_neon=false ' + gn_args = 'use_errorprone_java_compiler=true ' gn_extra = '' out_dir_suffix = '' + if options.x86: + gn_args += 'target_cpu="x86" ' + out_dir_suffix = '-x86' + else: + gn_args += 'arm_use_neon=false ' if options.asan: # ASAN on Android requires one-time setup described here: # https://www.chromium.org/developers/testing/addresssanitizer - gn_args += ' is_asan=true is_clang=true is_debug=false ' + gn_args += 'is_asan=true is_clang=true is_debug=false ' out_dir_suffix += '-asan' gn_args += 'target_os="' + target_os + '" enable_websockets=false '+ \ @@ -127,7 +134,7 @@ 'enable_reporting=false '+ \ 'is_component_build=false ' + \ 'ignore_elf32_limitations=true use_partition_alloc=false ' + \ - 'include_transport_security_state_preload_list=false' + 'include_transport_security_state_preload_list=false ' extra_options = ' '.join(extra_options_list) if options.gn: @@ -135,7 +142,7 @@ if options.release: out_dir = 'out/Release' + out_dir_suffix - gn_args += ' is_debug=false is_official_build=true ' + gn_args += 'is_debug=false is_official_build=true ' else: out_dir = 'out/Debug' + out_dir_suffix
diff --git a/components/cronet/url_request_context_config.cc b/components/cronet/url_request_context_config.cc index ed6e6efd..093e710 100644 --- a/components/cronet/url_request_context_config.cc +++ b/components/cronet/url_request_context_config.cc
@@ -165,6 +165,7 @@ int http_cache_max_size, bool load_disable_cache, const std::string& storage_path, + const std::string& accept_language, const std::string& user_agent, const std::string& experimental_options, std::unique_ptr<net::CertVerifier> mock_cert_verifier, @@ -179,6 +180,7 @@ http_cache_max_size(http_cache_max_size), load_disable_cache(load_disable_cache), storage_path(storage_path), + accept_language(accept_language), user_agent(user_agent), mock_cert_verifier(std::move(mock_cert_verifier)), enable_network_quality_estimator(enable_network_quality_estimator), @@ -553,6 +555,7 @@ } else { context_builder->DisableHttpCache(); } + context_builder->set_accept_language(accept_language); context_builder->set_user_agent(user_agent); net::HttpNetworkSession::Params session_params; session_params.enable_http2 = enable_spdy; @@ -590,8 +593,8 @@ URLRequestContextConfigBuilder::Build() { return std::make_unique<URLRequestContextConfig>( enable_quic, quic_user_agent_id, enable_spdy, enable_brotli, http_cache, - http_cache_max_size, load_disable_cache, storage_path, user_agent, - experimental_options, std::move(mock_cert_verifier), + http_cache_max_size, load_disable_cache, storage_path, accept_language, + user_agent, experimental_options, std::move(mock_cert_verifier), enable_network_quality_estimator, bypass_public_key_pinning_for_local_trust_anchors, cert_verifier_data); }
diff --git a/components/cronet/url_request_context_config.h b/components/cronet/url_request_context_config.h index 507d493..fd27dc4 100644 --- a/components/cronet/url_request_context_config.h +++ b/components/cronet/url_request_context_config.h
@@ -97,6 +97,8 @@ bool load_disable_cache, // Storage path for http cache and cookie storage. const std::string& storage_path, + // Accept-Language request header field. + const std::string& accept_language, // User-Agent request header field. const std::string& user_agent, // JSON encoded experimental options. @@ -133,6 +135,8 @@ const bool load_disable_cache; // Storage path for http cache and cookie storage. const std::string storage_path; + // Accept-Language request header field. + const std::string accept_language; // User-Agent request header field. const std::string user_agent; @@ -220,6 +224,8 @@ bool load_disable_cache = false; // Storage path for http cache and cookie storage. std::string storage_path = ""; + // Accept-Language request header field. + std::string accept_language = ""; // User-Agent request header field. std::string user_agent = ""; // Experimental options encoded as a string in a JSON format containing
diff --git a/components/cronet/url_request_context_config_unittest.cc b/components/cronet/url_request_context_config_unittest.cc index 4af5b31..5174b6f 100644 --- a/components/cronet/url_request_context_config_unittest.cc +++ b/components/cronet/url_request_context_config_unittest.cc
@@ -14,6 +14,7 @@ #include "net/log/net_log_with_source.h" #include "net/proxy_resolution/proxy_config.h" #include "net/proxy_resolution/proxy_config_service_fixed.h" +#include "net/url_request/http_user_agent_settings.h" #include "net/url_request/url_request_context.h" #include "net/url_request/url_request_context_builder.h" #include "testing/gtest/include/gtest/gtest.h" @@ -42,6 +43,8 @@ false, // Storage path for http cache and cookie storage. "/data/data/org.chromium.net/app_cronet_test/test_storage", + // Accept-Language request header field. + "foreign-language", // User-Agent request header field. "fake agent", // JSON encoded experimental options. @@ -145,6 +148,8 @@ false, // Storage path for http cache and cookie storage. "/data/data/org.chromium.net/app_cronet_test/test_storage", + // Accept-Language request header field. + "foreign-language", // User-Agent request header field. "fake agent", // JSON encoded experimental options. @@ -197,6 +202,8 @@ false, // Storage path for http cache and cookie storage. "/data/data/org.chromium.net/app_cronet_test/test_storage", + // Accept-Language request header field. + "foreign-language", // User-Agent request header field. "fake agent", // JSON encoded experimental options. @@ -254,6 +261,8 @@ false, // Storage path for http cache and cookie storage. "/data/data/org.chromium.net/app_cronet_test/test_storage", + // Accept-Language request header field. + "foreign-language", // User-Agent request header field. "fake agent", // JSON encoded experimental options. @@ -306,6 +315,8 @@ false, // Storage path for http cache and cookie storage. "/data/data/org.chromium.net/app_cronet_test/test_storage", + // Accept-Language request header field. + "foreign-language", // User-Agent request header field. "fake agent", // JSON encoded experimental options. @@ -357,6 +368,8 @@ false, // Storage path for http cache and cookie storage. "/data/data/org.chromium.net/app_cronet_test/test_storage", + // Accept-Language request header field. + "foreign-language", // User-Agent request header field. "fake agent", // JSON encoded experimental options. @@ -394,6 +407,56 @@ EXPECT_EQ(client_connection_options, params->quic_client_connection_options); } +TEST(URLURLRequestContextConfigTest, SetAcceptLanguageAndUserAgent) { + base::test::ScopedTaskEnvironment scoped_task_environment_( + base::test::ScopedTaskEnvironment::MainThreadType::IO); + + URLRequestContextConfig config( + // Enable QUIC. + true, + // QUIC User Agent ID. + "Default QUIC User Agent ID", + // Enable SPDY. + true, + // Enable Brotli. + false, + // Type of http cache. + URLRequestContextConfig::HttpCacheType::DISK, + // Max size of http cache in bytes. + 1024000, + // Disable caching for HTTP responses. Other information may be stored in + // the cache. + false, + // Storage path for http cache and cookie storage. + "/data/data/org.chromium.net/app_cronet_test/test_storage", + // Accept-Language request header field. + "foreign-language", + // User-Agent request header field. + "fake agent", + // JSON encoded experimental options. + "{}", + // MockCertVerifier to use for testing purposes. + std::unique_ptr<net::CertVerifier>(), + // Enable network quality estimator. + false, + // Enable Public Key Pinning bypass for local trust anchors. + true, + // Certificate verifier cache data. + ""); + + net::URLRequestContextBuilder builder; + net::NetLog net_log; + config.ConfigureURLRequestContextBuilder(&builder, &net_log); + // Set a ProxyConfigService to avoid DCHECK failure when building. + builder.set_proxy_config_service( + std::make_unique<net::ProxyConfigServiceFixed>( + net::ProxyConfig::CreateDirect())); + std::unique_ptr<net::URLRequestContext> context(builder.Build()); + EXPECT_EQ("foreign-language", + context->http_user_agent_settings()->GetAcceptLanguage()); + EXPECT_EQ("fake agent", context->http_user_agent_settings()->GetUserAgent()); +} + // See stale_host_resolver_unittest.cc for test of StaleDNS options. } // namespace cronet
diff --git a/components/data_reduction_proxy/core/browser/data_reduction_proxy_delegate.cc b/components/data_reduction_proxy/core/browser/data_reduction_proxy_delegate.cc index 5332a1b9..f0cf68e 100644 --- a/components/data_reduction_proxy/core/browser/data_reduction_proxy_delegate.cc +++ b/components/data_reduction_proxy/core/browser/data_reduction_proxy_delegate.cc
@@ -32,52 +32,6 @@ static const char kDataReductionCoreProxy[] = "proxy.googlezip.net"; -// Adds data reduction proxies to |result|, where applicable, if result -// otherwise uses a direct connection for |url|, and the data reduction proxy is -// not bypassed. Also, configures |result| to proceed directly to the origin if -// |result|'s current proxy is the data reduction proxy. -void OnResolveProxyHandler( - const GURL& url, - const std::string& method, - const net::ProxyConfig& proxy_config, - const net::ProxyRetryInfoMap& proxy_retry_info, - const DataReductionProxyConfig& data_reduction_proxy_config, - DataReductionProxyIOData* io_data, - net::ProxyInfo* result) { - DCHECK(result->is_empty() || result->is_direct() || - !data_reduction_proxy_config.IsDataReductionProxy( - result->proxy_server(), nullptr)); - - if (!util::EligibleForDataReductionProxy(*result, url, method)) - return; - - net::ProxyInfo data_reduction_proxy_info; - bool data_saver_proxy_used = util::ApplyProxyConfigToProxyInfo( - proxy_config, proxy_retry_info, url, &data_reduction_proxy_info); - if (data_saver_proxy_used) - result->OverrideProxyList(data_reduction_proxy_info.proxy_list()); - - if (io_data && io_data->resource_type_provider()) { - ResourceTypeProvider::ContentType content_type = - io_data->resource_type_provider()->GetContentType(url); - DCHECK_GT(ResourceTypeProvider::CONTENT_TYPE_MAX, content_type); - UMA_HISTOGRAM_ENUMERATION("DataReductionProxy.ResourceContentType", - content_type, - ResourceTypeProvider::CONTENT_TYPE_MAX); - } - - // The |proxy_config| must be valid otherwise the proxy cannot be used. - DCHECK(proxy_config.is_valid() || !data_saver_proxy_used); - - if (data_reduction_proxy_config.enabled_by_user_and_reachable() && - url.SchemeIs(url::kHttpScheme) && !net::IsLocalhost(url) && - !params::IsIncludedInHoldbackFieldTrial()) { - UMA_HISTOGRAM_BOOLEAN( - "DataReductionProxy.ConfigService.HTTPRequests", - !data_reduction_proxy_config.GetProxiesForHttp().empty()); - } -} - } // namespace DataReductionProxyDelegate::DataReductionProxyDelegate( @@ -121,15 +75,21 @@ const std::string& method, const net::ProxyRetryInfoMap& proxy_retry_info, net::ProxyInfo* result) { - DCHECK(result); DCHECK(thread_checker_.CalledOnValidThread()); + DCHECK(result); + DCHECK(result->is_empty() || result->is_direct() || + !config_->IsDataReductionProxy(result->proxy_server(), nullptr)); + + if (!params::IsIncludedInQuicFieldTrial()) + RecordQuicProxyStatus(QUIC_PROXY_DISABLED_VIA_FIELD_TRIAL); + + if (!util::EligibleForDataReductionProxy(*result, url, method)) + return; ResourceTypeProvider::ContentType content_type = ResourceTypeProvider::CONTENT_TYPE_UNKNOWN; - - if (io_data_ && io_data_->resource_type_provider()) { + if (io_data_ && io_data_->resource_type_provider()) content_type = io_data_->resource_type_provider()->GetContentType(url); - } std::vector<DataReductionProxyServer> proxies_for_http = params::IsIncludedInHoldbackFieldTrial() @@ -175,23 +135,33 @@ net::ProxyConfig proxy_config = configurator_->CreateProxyConfig( is_warmup_url, config_->GetNetworkPropertiesManager(), proxies_for_http); - OnResolveProxyHandler(url, method, proxy_config, proxy_retry_info, *config_, - io_data_, result); + net::ProxyInfo data_reduction_proxy_info; + if (util::ApplyProxyConfigToProxyInfo(proxy_config, proxy_retry_info, url, + &data_reduction_proxy_info)) { + DCHECK(!data_reduction_proxy_info.is_empty() && + !data_reduction_proxy_info.is_direct()); + result->OverrideProxyList(data_reduction_proxy_info.proxy_list()); - if (!result->is_empty()) { - net::ProxyServer alternative_proxy_server; - if (GetAlternativeProxy(url, result->proxy_server(), proxy_retry_info, - &alternative_proxy_server)) { - result->SetAlternativeProxy(alternative_proxy_server); + GetAlternativeProxy(url, proxy_retry_info, result); + + if (!first_data_saver_request_recorded_) { + UMA_HISTOGRAM_MEDIUM_TIMES( + "DataReductionProxy.TimeToFirstDataSaverRequest", + tick_clock_->NowTicks() - last_network_change_time_); + first_data_saver_request_recorded_ = true; } } - if (!first_data_saver_request_recorded_ && !result->is_empty() && - config_->IsDataReductionProxy(result->proxy_server(), nullptr)) { - UMA_HISTOGRAM_MEDIUM_TIMES( - "DataReductionProxy.TimeToFirstDataSaverRequest", - tick_clock_->NowTicks() - last_network_change_time_); - first_data_saver_request_recorded_ = true; + DCHECK_GT(ResourceTypeProvider::CONTENT_TYPE_MAX, content_type); + UMA_HISTOGRAM_ENUMERATION("DataReductionProxy.ResourceContentType", + content_type, + ResourceTypeProvider::CONTENT_TYPE_MAX); + + if (config_->enabled_by_user_and_reachable() && + url.SchemeIs(url::kHttpScheme) && !net::IsLocalhost(url) && + !params::IsIncludedInHoldbackFieldTrial()) { + UMA_HISTOGRAM_BOOLEAN("DataReductionProxy.ConfigService.HTTPRequests", + !config_->GetProxiesForHttp().empty()); } } @@ -216,34 +186,32 @@ last_network_change_time_ = tick_clock_->NowTicks(); } -bool DataReductionProxyDelegate::GetAlternativeProxy( +void DataReductionProxyDelegate::GetAlternativeProxy( const GURL& url, - const net::ProxyServer& resolved_proxy_server, const net::ProxyRetryInfoMap& proxy_retry_info, - net::ProxyServer* alternative_proxy_server) const { + net::ProxyInfo* result) const { DCHECK(thread_checker_.CalledOnValidThread()); + net::ProxyServer resolved_proxy_server = result->proxy_server(); + DCHECK(resolved_proxy_server.is_valid()); + DCHECK(config_->IsDataReductionProxy(resolved_proxy_server, nullptr)); + if (!url.is_valid() || !url.SchemeIsHTTPOrHTTPS() || url.SchemeIsCryptographic()) { - return false; + return; } if (!params::IsIncludedInQuicFieldTrial()) { - RecordQuicProxyStatus(QUIC_PROXY_DISABLED_VIA_FIELD_TRIAL); - return false; + // RecordQuicProxyStatus already called by OnResolveProxy. + return; } - if (!resolved_proxy_server.is_valid() || !resolved_proxy_server.is_https()) - return false; - - if (!config_ || - !config_->IsDataReductionProxy(resolved_proxy_server, nullptr)) { - return false; - } + if (!resolved_proxy_server.is_https()) + return; if (!SupportsQUIC(resolved_proxy_server)) { RecordQuicProxyStatus(QUIC_PROXY_NOT_SUPPORTED); - return false; + return; } net::ProxyInfo alternative_proxy_info; @@ -253,12 +221,11 @@ if (alternative_proxy_info.is_empty()) { RecordQuicProxyStatus(QUIC_PROXY_STATUS_MARKED_AS_BROKEN); - return false; + return; } RecordQuicProxyStatus(QUIC_PROXY_STATUS_AVAILABLE); - *alternative_proxy_server = alternative_proxy_info.proxy_server(); - return true; + result->SetAlternativeProxy(alternative_proxy_info.proxy_server()); } bool DataReductionProxyDelegate::SupportsQUIC(
diff --git a/components/data_reduction_proxy/core/browser/data_reduction_proxy_delegate.h b/components/data_reduction_proxy/core/browser/data_reduction_proxy_delegate.h index a56bc16..f5adf5c6 100644 --- a/components/data_reduction_proxy/core/browser/data_reduction_proxy_delegate.h +++ b/components/data_reduction_proxy/core/browser/data_reduction_proxy_delegate.h
@@ -80,10 +80,11 @@ // NetworkChangeNotifier::IPAddressObserver: void OnIPAddressChanged() override; - bool GetAlternativeProxy(const GURL& url, - const net::ProxyServer& resolved_proxy_server, + // Checks if the first proxy server in |result| supports QUIC and if so + // adds an alternative proxy configuration to |result|. + void GetAlternativeProxy(const GURL& url, const net::ProxyRetryInfoMap& proxy_retry_info, - net::ProxyServer* alternative_proxy_server) const; + net::ProxyInfo* result) const; const DataReductionProxyConfig* config_; const DataReductionProxyConfigurator* configurator_;
diff --git a/components/download/content/internal/download_driver_impl.cc b/components/download/content/internal/download_driver_impl.cc index 5f32c48a..0b19651 100644 --- a/components/download/content/internal/download_driver_impl.cc +++ b/components/download/content/internal/download_driver_impl.cc
@@ -168,7 +168,7 @@ if (request_params.fetch_error_body) download_url_params->set_fetch_error_body(true); download_url_params->set_download_source( - content::DownloadSource::INTERNAL_API); + download::DownloadSource::INTERNAL_API); download_manager_->DownloadUrl(std::move(download_url_params)); }
diff --git a/components/download/downloader/in_progress/BUILD.gn b/components/download/downloader/in_progress/BUILD.gn index 5b7a1b15..e29d519 100644 --- a/components/download/downloader/in_progress/BUILD.gn +++ b/components/download/downloader/in_progress/BUILD.gn
@@ -11,7 +11,6 @@ sources = [ "download_entry.cc", "download_entry.h", - "download_source.h", "in_progress_cache.h", "in_progress_cache_impl.cc", "in_progress_cache_impl.h", @@ -22,6 +21,7 @@ deps = [ "//base", "//components/download/downloader/in_progress/proto", + "//components/download/public/common:public", "//services/metrics/public/cpp:metrics_cpp", ] }
diff --git a/components/download/downloader/in_progress/DEPS b/components/download/downloader/in_progress/DEPS index 18f63456..74bead6e 100644 --- a/components/download/downloader/in_progress/DEPS +++ b/components/download/downloader/in_progress/DEPS
@@ -1,3 +1,4 @@ include_rules = [ + "+components/download/public/common", "+services/metrics/public" ]
diff --git a/components/download/downloader/in_progress/download_entry.h b/components/download/downloader/in_progress/download_entry.h index e267182..449d29ef 100644 --- a/components/download/downloader/in_progress/download_entry.h +++ b/components/download/downloader/in_progress/download_entry.h
@@ -7,7 +7,7 @@ #include <string> -#include "components/download/downloader/in_progress/download_source.h" +#include "components/download/public/common/download_source.h" #include "services/metrics/public/cpp/ukm_source_id.h" namespace download {
diff --git a/components/download/downloader/in_progress/download_source.h b/components/download/downloader/in_progress/download_source.h deleted file mode 100644 index 71a9a06a..0000000 --- a/components/download/downloader/in_progress/download_source.h +++ /dev/null
@@ -1,30 +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. - -#ifndef COMPONENTS_DOWNLOAD_DOWNLOADER_IN_PROGRESS_DOWNLOAD_SOURCE_H_ -#define COMPONENTS_DOWNLOAD_DOWNLOADER_IN_PROGRESS_DOWNLOAD_SOURCE_H_ - -#include <string> - -namespace download { -// The source of download. -// This enum should match content::DownloadSource in -// content/public/browser/download_source.h. -// Any changes here should also apply to download_source.proto. -enum class DownloadSource { - UNKNOWN = 0, - NAVIGATION = 1, - DRAG_AND_DROP = 2, - FROM_RENDERER = 3, - EXTENSION_API = 4, - EXTENSION_INSTALLER = 5, - INTERNAL_API = 6, - WEB_CONTENTS_API = 7, - OFFLINE_PAGE = 8, - CONTEXT_MENU = 9, -}; - -} // namespace download - -#endif // COMPONENTS_DOWNLOAD_DOWNLOADER_IN_PROGRESS_DOWNLOAD_SOURCE_H_
diff --git a/components/download/downloader/in_progress/proto/download_source.proto b/components/download/downloader/in_progress/proto/download_source.proto index 2405b94..375b059 100644 --- a/components/download/downloader/in_progress/proto/download_source.proto +++ b/components/download/downloader/in_progress/proto/download_source.proto
@@ -9,7 +9,7 @@ package metadata_pb; // This should stay in sync with the download::DownloadSource enum in -// components/download/downloader/in_progress/download_source.h. +// components/download/public/core/download_source.h. enum DownloadSource { UNKNOWN = 0; NAVIGATION = 1;
diff --git a/components/download/public/common/BUILD.gn b/components/download/public/common/BUILD.gn new file mode 100644 index 0000000..d7dd03a --- /dev/null +++ b/components/download/public/common/BUILD.gn
@@ -0,0 +1,19 @@ +# 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. + +component("public") { + sources = [ + "download_danger_type.h", + "download_save_info.cc", + "download_save_info.h", + "download_source.h", + ] + + defines = [ "COMPONENTS_DOWNLOAD_IMPLEMENTATION" ] + + public_deps = [ + "//base", + "//crypto", + ] +}
diff --git a/components/download/public/common/DEPS b/components/download/public/common/DEPS new file mode 100644 index 0000000..4ef4138e4 --- /dev/null +++ b/components/download/public/common/DEPS
@@ -0,0 +1,3 @@ +include_rules = [ + "+crypto", +]
diff --git a/content/public/browser/download_danger_type.h b/components/download/public/common/download_danger_type.h similarity index 84% rename from content/public/browser/download_danger_type.h rename to components/download/public/common/download_danger_type.h index ed8c7b1a..c97bd08 100644 --- a/content/public/browser/download_danger_type.h +++ b/components/download/public/common/download_danger_type.h
@@ -1,11 +1,11 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. +// 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. -#ifndef CONTENT_PUBLIC_BROWSER_DOWNLOAD_DANGER_TYPE_H_ -#define CONTENT_PUBLIC_BROWSER_DOWNLOAD_DANGER_TYPE_H_ +#ifndef COMPONENTS_DOWNLOAD_PUBLIC_COMMON_DOWNLOAD_DANGER_TYPE_H_ +#define COMPONENTS_DOWNLOAD_PUBLIC_COMMON_DOWNLOAD_DANGER_TYPE_H_ -namespace content { +namespace download { // This enum is also used by histograms. Do not change the ordering or remove // items. @@ -49,6 +49,6 @@ DOWNLOAD_DANGER_TYPE_MAX }; -} +} // namespace download -#endif // CONTENT_PUBLIC_BROWSER_DOWNLOAD_DANGER_TYPE_H_ +#endif // COMPONENTS_DOWNLOAD_PUBLIC_COMMON_DOWNLOAD_DANGER_TYPE_H_
diff --git a/components/download/public/common/download_export.h b/components/download/public/common/download_export.h new file mode 100644 index 0000000..aa74da80b --- /dev/null +++ b/components/download/public/common/download_export.h
@@ -0,0 +1,29 @@ +// 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. + +#ifndef COMPONENTS_DOWNLOAD_PUBLIC_COMMON_DOWNLOAD_EXPORT_H_ +#define COMPONENTS_DOWNLOAD_PUBLIC_COMMON_DOWNLOAD_EXPORT_H_ + +#if defined(COMPONENT_BUILD) +#if defined(WIN32) + +#if defined(COMPONENTS_DOWNLOAD_IMPLEMENTATION) +#define COMPONENTS_DOWNLOAD_EXPORT __declspec(dllexport) +#else +#define COMPONENTS_DOWNLOAD_EXPORT __declspec(dllimport) +#endif // defined(COMPONENTS_DOWNLOAD_IMPLEMENTATION) + +#else // defined(WIN32) +#if defined(COMPONENTS_DOWNLOAD_IMPLEMENTATION) +#define COMPONENTS_DOWNLOAD_EXPORT __attribute__((visibility("default"))) +#else +#define COMPONENTS_DOWNLOAD_EXPORT +#endif +#endif + +#else // defined(COMPONENT_BUILD) +#define COMPONENTS_DOWNLOAD_EXPORT +#endif + +#endif // COMPONENTS_DOWNLOAD_PUBLIC_COMMON_DOWNLOAD_EXPORT_H_
diff --git a/content/public/browser/download_save_info.cc b/components/download/public/common/download_save_info.cc similarity index 76% rename from content/public/browser/download_save_info.cc rename to components/download/public/common/download_save_info.cc index 8e686f3..075ba24 100644 --- a/content/public/browser/download_save_info.cc +++ b/components/download/public/common/download_save_info.cc
@@ -1,10 +1,10 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. +// 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 "content/public/browser/download_save_info.h" +#include "components/download/public/common/download_save_info.h" -namespace content { +namespace download { // static const int64_t DownloadSaveInfo::kLengthFullContent = 0; @@ -12,8 +12,7 @@ DownloadSaveInfo::DownloadSaveInfo() : offset(0), length(kLengthFullContent), prompt_for_save_location(false) {} -DownloadSaveInfo::~DownloadSaveInfo() { -} +DownloadSaveInfo::~DownloadSaveInfo() {} DownloadSaveInfo::DownloadSaveInfo(DownloadSaveInfo&& that) : file_path(std::move(that.file_path)), @@ -25,4 +24,4 @@ hash_of_partial_file(std::move(that.hash_of_partial_file)), prompt_for_save_location(that.prompt_for_save_location) {} -} // namespace content +} // namespace download
diff --git a/content/public/browser/download_save_info.h b/components/download/public/common/download_save_info.h similarity index 85% rename from content/public/browser/download_save_info.h rename to components/download/public/common/download_save_info.h index c1c97bf5..b43d0f97 100644 --- a/content/public/browser/download_save_info.h +++ b/components/download/public/common/download_save_info.h
@@ -1,9 +1,9 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. +// 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. -#ifndef CONTENT_PUBLIC_BROWSER_DOWNLOAD_SAVE_INFO_H_ -#define CONTENT_PUBLIC_BROWSER_DOWNLOAD_SAVE_INFO_H_ +#ifndef COMPONENTS_DOWNLOAD_PUBLIC_COMMON_DOWNLOAD_SAVE_INFO_H_ +#define COMPONENTS_DOWNLOAD_PUBLIC_COMMON_DOWNLOAD_SAVE_INFO_H_ #include <stdint.h> @@ -12,16 +12,16 @@ #include "base/files/file.h" #include "base/files/file_path.h" #include "base/macros.h" -#include "content/common/content_export.h" +#include "components/download/public/common/download_export.h" #include "crypto/secure_hash.h" -namespace content { +namespace download { // Holds the information about how to save a download file. // In the case of download continuation, |file_path| is set to the current file // name, |offset| is set to the point where we left off, and |hash_state| will // hold the state of the hash algorithm where we left off. -struct CONTENT_EXPORT DownloadSaveInfo { +struct COMPONENTS_DOWNLOAD_EXPORT DownloadSaveInfo { // The default value for |length|. Used when request the rest of the file // starts from |offset|. static const int64_t kLengthFullContent; @@ -73,6 +73,6 @@ DISALLOW_COPY_AND_ASSIGN(DownloadSaveInfo); }; -} // namespace content +} // namespace download -#endif // CONTENT_PUBLIC_BROWSER_DOWNLOAD_SAVE_INFO_H_ +#endif // COMPONENTS_DOWNLOAD_PUBLIC_COMMON_DOWNLOAD_SAVE_INFO_H_
diff --git a/content/public/browser/download_source.h b/components/download/public/common/download_source.h similarity index 76% rename from content/public/browser/download_source.h rename to components/download/public/common/download_source.h index 78eae4c..1a330ebf 100644 --- a/content/public/browser/download_source.h +++ b/components/download/public/common/download_source.h
@@ -1,11 +1,11 @@ -// Copyright 2017 The Chromium Authors. All rights reserved. +// 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. -#ifndef CONTENT_PUBLIC_BROWSER_DOWNLOAD_SOURCE_H_ -#define CONTENT_PUBLIC_BROWSER_DOWNLOAD_SOURCE_H_ +#ifndef COMPONENTS_DOWNLOAD_PUBLIC_COMMON_DOWNLOAD_SOURCE_H_ +#define COMPONENTS_DOWNLOAD_PUBLIC_COMMON_DOWNLOAD_SOURCE_H_ -namespace content { +namespace download { // The source of download. // Used in UMA metrics and persisted to disk. @@ -43,6 +43,6 @@ CONTEXT_MENU = 9, }; -} // namespace content +} // namespace download -#endif // CONTENT_PUBLIC_BROWSER_DOWNLOAD_SOURCE_H_ +#endif // COMPONENTS_DOWNLOAD_PUBLIC_COMMON_DOWNLOAD_SOURCE_H_
diff --git a/components/exo/shell_surface_unittest.cc b/components/exo/shell_surface_unittest.cc index ea3e69d6..9eb38d8 100644 --- a/components/exo/shell_surface_unittest.cc +++ b/components/exo/shell_surface_unittest.cc
@@ -34,9 +34,6 @@ #include "ui/display/manager/display_manager.h" #include "ui/display/screen.h" #include "ui/views/widget/widget.h" -#include "ui/wm/core/shadow.h" -#include "ui/wm/core/shadow_controller.h" -#include "ui/wm/core/shadow_types.h" #include "ui/wm/core/window_util.h" namespace exo {
diff --git a/components/grpc_support/bidirectional_stream.cc b/components/grpc_support/bidirectional_stream.cc index 129b334..9e0ff9d6 100644 --- a/components/grpc_support/bidirectional_stream.cc +++ b/components/grpc_support/bidirectional_stream.cc
@@ -6,6 +6,7 @@ #include <memory> #include <string> +#include <utility> #include <vector> #include "base/bind.h" @@ -100,8 +101,8 @@ request_info->end_stream_on_headers = end_of_stream; write_end_of_stream_ = end_of_stream; PostToNetworkThread(FROM_HERE, - base::Bind(&BidirectionalStream::StartOnNetworkThread, - weak_this_, base::Passed(&request_info))); + base::BindOnce(&BidirectionalStream::StartOnNetworkThread, + weak_this_, base::Passed(&request_info))); return 0; } @@ -111,9 +112,9 @@ scoped_refptr<net::WrappedIOBuffer> read_buffer( new net::WrappedIOBuffer(buffer)); - PostToNetworkThread(FROM_HERE, - base::Bind(&BidirectionalStream::ReadDataOnNetworkThread, - weak_this_, read_buffer, capacity)); + PostToNetworkThread( + FROM_HERE, base::BindOnce(&BidirectionalStream::ReadDataOnNetworkThread, + weak_this_, read_buffer, capacity)); return true; } @@ -127,30 +128,31 @@ new net::WrappedIOBuffer(buffer)); PostToNetworkThread( - FROM_HERE, base::Bind(&BidirectionalStream::WriteDataOnNetworkThread, - weak_this_, write_buffer, count, end_of_stream)); + FROM_HERE, + base::BindOnce(&BidirectionalStream::WriteDataOnNetworkThread, weak_this_, + write_buffer, count, end_of_stream)); return true; } void BidirectionalStream::Flush() { PostToNetworkThread( FROM_HERE, - base::Bind(&BidirectionalStream::FlushOnNetworkThread, weak_this_)); + base::BindOnce(&BidirectionalStream::FlushOnNetworkThread, weak_this_)); } void BidirectionalStream::Cancel() { PostToNetworkThread( FROM_HERE, - base::Bind(&BidirectionalStream::CancelOnNetworkThread, weak_this_)); + base::BindOnce(&BidirectionalStream::CancelOnNetworkThread, weak_this_)); } void BidirectionalStream::Destroy() { // Destroy could be called from any thread, including network thread (if // posting task to executor throws an exception), but is posted, so |this| // is valid until calling task is complete. - PostToNetworkThread(FROM_HERE, - base::Bind(&BidirectionalStream::DestroyOnNetworkThread, - base::Unretained(this))); + PostToNetworkThread( + FROM_HERE, base::BindOnce(&BidirectionalStream::DestroyOnNetworkThread, + base::Unretained(this))); } void BidirectionalStream::OnStreamReady(bool request_headers_sent) { @@ -249,9 +251,9 @@ read_state_ = write_state_ = ERR; weak_factory_.InvalidateWeakPtrs(); // Delete underlying |bidi_stream_| asynchronously as it may still be used. - PostToNetworkThread(FROM_HERE, - base::Bind(&base::DeletePointer<net::BidirectionalStream>, - bidi_stream_.release())); + PostToNetworkThread( + FROM_HERE, base::BindOnce(&base::DeletePointer<net::BidirectionalStream>, + bidi_stream_.release())); delegate_->OnFailed(error); } @@ -381,8 +383,9 @@ weak_factory_.InvalidateWeakPtrs(); // Delete underlying |bidi_stream_| asynchronously as it may still be used. PostToNetworkThread( - FROM_HERE, base::Bind(&base::DeletePointer<net::BidirectionalStream>, - bidi_stream_.release())); + FROM_HERE, + base::BindOnce(&base::DeletePointer<net::BidirectionalStream>, + bidi_stream_.release())); delegate_->OnSucceeded(); } } @@ -393,8 +396,9 @@ } void BidirectionalStream::PostToNetworkThread(const base::Location& from_here, - const base::Closure& task) { - request_context_getter_->GetNetworkTaskRunner()->PostTask(from_here, task); + base::OnceClosure task) { + request_context_getter_->GetNetworkTaskRunner()->PostTask(from_here, + std::move(task)); } -} // namespace cronet +} // namespace grpc_support
diff --git a/components/grpc_support/bidirectional_stream.h b/components/grpc_support/bidirectional_stream.h index e736319..b65be34 100644 --- a/components/grpc_support/bidirectional_stream.h +++ b/components/grpc_support/bidirectional_stream.h
@@ -17,7 +17,7 @@ namespace base { class Location; -} // namespace tracked_objects +} // namespace base namespace net { class HttpRequestHeaders; @@ -193,7 +193,7 @@ bool IsOnNetworkThread(); void PostToNetworkThread(const base::Location& from_here, - const base::Closure& task); + base::OnceClosure task); // Read state is tracking reading flow. Only accessed on network thread. // | <--- READING <--- |
diff --git a/components/grpc_support/bidirectional_stream_c.cc b/components/grpc_support/bidirectional_stream_c.cc index 67fc9c59..aa7902b 100644 --- a/components/grpc_support/bidirectional_stream_c.cc +++ b/components/grpc_support/bidirectional_stream_c.cc
@@ -38,12 +38,12 @@ class HeadersArray : public bidirectional_stream_header_array { public: - HeadersArray(const net::SpdyHeaderBlock& header_block); + explicit HeadersArray(const net::SpdyHeaderBlock& header_block); ~HeadersArray(); private: - DISALLOW_COPY_AND_ASSIGN(HeadersArray); base::StringPairs headers_strings_; + DISALLOW_COPY_AND_ASSIGN(HeadersArray); }; HeadersArray::HeadersArray(const net::SpdyHeaderBlock& header_block) @@ -195,8 +195,9 @@ // is valid until calling task is complete. adapter->bidirectional_stream_->Destroy(); adapter->request_context_getter_->GetNetworkTaskRunner()->PostTask( - FROM_HERE, base::Bind(&BidirectionalStreamAdapter::DestroyOnNetworkThread, - base::Unretained(adapter))); + FROM_HERE, + base::BindOnce(&BidirectionalStreamAdapter::DestroyOnNetworkThread, + base::Unretained(adapter))); } void BidirectionalStreamAdapter::DestroyOnNetworkThread() {
diff --git a/components/grpc_support/bidirectional_stream_unittest.cc b/components/grpc_support/bidirectional_stream_unittest.cc index f2e4d9e..e0bea67 100644 --- a/components/grpc_support/bidirectional_stream_unittest.cc +++ b/components/grpc_support/bidirectional_stream_unittest.cc
@@ -119,13 +119,14 @@ static TestBidirectionalStreamCallback* FromStream( bidirectional_stream* stream) { DCHECK(stream); - return (TestBidirectionalStreamCallback*)stream->annotation; + return reinterpret_cast<TestBidirectionalStreamCallback*>( + stream->annotation); } virtual bool MaybeCancel(bidirectional_stream* stream, ResponseStep step) { DCHECK_EQ(stream, this->stream); response_step = step; - DLOG(WARNING) << "Step: " << step; + DVLOG(3) << "Step: " << step; if (step != cancel_from_step) return false; @@ -538,9 +539,8 @@ : public TestBidirectionalStreamCallback { bool MaybeCancel(bidirectional_stream* stream, ResponseStep step) override { if (step == ResponseStep::ON_READ_COMPLETED) { - // Shut down the server, and the stream should error out. - // The second call to ShutdownQuicTestServer is no-op. - ShutdownQuicTestServer(); + // Shut down the server dispatcher, and the stream should error out. + ShutdownQuicTestServerDispatcher(); } return TestBidirectionalStreamCallback::MaybeCancel(stream, step); } @@ -582,9 +582,8 @@ : public TestBidirectionalStreamCallback { bool MaybeCancel(bidirectional_stream* stream, ResponseStep step) override { if (step == ResponseStep::ON_STREAM_READY) { - // Shut down the server, and the stream should error out. - // The second call to ShutdownQuicTestServer is no-op. - ShutdownQuicTestServer(); + // Shut down the server dispatcher, and the stream should error out. + ShutdownQuicTestServerDispatcher(); } return TestBidirectionalStreamCallback::MaybeCancel(stream, step); } @@ -612,9 +611,8 @@ : public TestBidirectionalStreamCallback { bool MaybeCancel(bidirectional_stream* stream, ResponseStep step) override { if (step == ResponseStep::ON_WRITE_COMPLETED) { - // Shut down the server, and the stream should error out. - // The second call to ShutdownQuicTestServer is no-op. - ShutdownQuicTestServer(); + // Shut down the server dispatcher, and the stream should error out. + ShutdownQuicTestServerDispatcher(); } return TestBidirectionalStreamCallback::MaybeCancel(stream, step); }
diff --git a/components/grpc_support/test/quic_test_server.cc b/components/grpc_support/test/quic_test_server.cc index f47bdd5..2d286fd 100644 --- a/components/grpc_support/test/quic_test_server.cc +++ b/components/grpc_support/test/quic_test_server.cc
@@ -4,6 +4,7 @@ #include "components/grpc_support/test/quic_test_server.h" +#include <memory> #include <utility> #include "base/bind.h" @@ -19,6 +20,7 @@ #include "net/quic/chromium/crypto/proof_source_chromium.h" #include "net/spdy/core/spdy_header_block.h" #include "net/test/test_data_directory.h" +#include "net/tools/quic/quic_dispatcher.h" #include "net/tools/quic/quic_http_response_cache.h" #include "net/tools/quic/quic_simple_server.h" @@ -110,8 +112,15 @@ server_stopped_event->Signal(); } +void ShutdownDispatcherOnServerThread( + base::WaitableEvent* dispatcher_stopped_event) { + DCHECK(g_quic_server_thread->task_runner()->BelongsToCurrentThread()); + g_quic_server->dispatcher()->Shutdown(); + dispatcher_stopped_event->Signal(); +} + bool StartQuicTestServer() { - LOG(INFO) << g_quic_server_thread; + DVLOG(3) << g_quic_server_thread; DCHECK(!g_quic_server_thread); g_quic_server_thread = new base::Thread("quic server thread"); base::Thread::Options thread_options; @@ -124,21 +133,36 @@ base::WaitableEvent::ResetPolicy::MANUAL, base::WaitableEvent::InitialState::NOT_SIGNALED); g_quic_server_thread->task_runner()->PostTask( - FROM_HERE, base::Bind(&StartQuicServerOnServerThread, test_files_root, - &server_started_event)); + FROM_HERE, base::BindOnce(&StartQuicServerOnServerThread, test_files_root, + &server_started_event)); server_started_event.Wait(); return true; } +// Shut down the server dispatcher, and the stream should error out. +void ShutdownQuicTestServerDispatcher() { + if (!g_quic_server) + return; + DCHECK(!g_quic_server_thread->task_runner()->BelongsToCurrentThread()); + base::WaitableEvent dispatcher_stopped_event( + base::WaitableEvent::ResetPolicy::MANUAL, + base::WaitableEvent::InitialState::NOT_SIGNALED); + g_quic_server_thread->task_runner()->PostTask( + FROM_HERE, base::BindOnce(&ShutdownDispatcherOnServerThread, + &dispatcher_stopped_event)); + dispatcher_stopped_event.Wait(); +} + void ShutdownQuicTestServer() { - if (!g_quic_server_thread) + if (!g_quic_server) return; DCHECK(!g_quic_server_thread->task_runner()->BelongsToCurrentThread()); base::WaitableEvent server_stopped_event( base::WaitableEvent::ResetPolicy::MANUAL, base::WaitableEvent::InitialState::NOT_SIGNALED); g_quic_server_thread->task_runner()->PostTask( - FROM_HERE, base::Bind(&ShutdownOnServerThread, &server_stopped_event)); + FROM_HERE, + base::BindOnce(&ShutdownOnServerThread, &server_stopped_event)); server_stopped_event.Wait(); delete g_quic_server_thread; g_quic_server_thread = nullptr;
diff --git a/components/grpc_support/test/quic_test_server.h b/components/grpc_support/test/quic_test_server.h index 81e0306..6bc25da0 100644 --- a/components/grpc_support/test/quic_test_server.h +++ b/components/grpc_support/test/quic_test_server.h
@@ -13,6 +13,10 @@ void ShutdownQuicTestServer(); +// Shuts down the server dispatcher, which results in sending ConnectionClose +// frames to all connected clients. +void ShutdownQuicTestServerDispatcher(); + int GetQuicTestServerPort(); extern const char kTestServerDomain[]; @@ -40,4 +44,4 @@ } // namespace grpc_support -#endif // COMPONENTS_CRONET_IOS_TEST_QUIC_TEST_SERVER_H_ +#endif // COMPONENTS_GRPC_SUPPORT_TEST_QUIC_TEST_SERVER_H_
diff --git a/components/history/content/browser/BUILD.gn b/components/history/content/browser/BUILD.gn index 55bdb00..41f00a5 100644 --- a/components/history/content/browser/BUILD.gn +++ b/components/history/content/browser/BUILD.gn
@@ -18,6 +18,7 @@ deps = [ "//base", + "//components/download/public/common:public", "//components/history/core/browser", "//components/visitedlink/browser", "//content/public/browser",
diff --git a/components/history/content/browser/DEPS b/components/history/content/browser/DEPS index 4ef4ece..e42f693 100644 --- a/components/history/content/browser/DEPS +++ b/components/history/content/browser/DEPS
@@ -1,4 +1,5 @@ include_rules = [ + "+components/download/public/common", "+components/visitedlink/browser", "+content/public/browser", ]
diff --git a/components/history/content/browser/download_conversions.cc b/components/history/content/browser/download_conversions.cc index ea9f112..7e80bb7 100644 --- a/components/history/content/browser/download_conversions.cc +++ b/components/history/content/browser/download_conversions.cc
@@ -48,55 +48,55 @@ return DownloadState::INVALID; } -content::DownloadDangerType ToContentDownloadDangerType( +download::DownloadDangerType ToContentDownloadDangerType( DownloadDangerType danger_type) { switch (danger_type) { case DownloadDangerType::NOT_DANGEROUS: - return content::DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS; + return download::DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS; case DownloadDangerType::DANGEROUS_FILE: - return content::DOWNLOAD_DANGER_TYPE_DANGEROUS_FILE; + return download::DOWNLOAD_DANGER_TYPE_DANGEROUS_FILE; case DownloadDangerType::DANGEROUS_URL: - return content::DOWNLOAD_DANGER_TYPE_DANGEROUS_URL; + return download::DOWNLOAD_DANGER_TYPE_DANGEROUS_URL; case DownloadDangerType::DANGEROUS_CONTENT: - return content::DOWNLOAD_DANGER_TYPE_DANGEROUS_CONTENT; + return download::DOWNLOAD_DANGER_TYPE_DANGEROUS_CONTENT; case DownloadDangerType::MAYBE_DANGEROUS_CONTENT: - return content::DOWNLOAD_DANGER_TYPE_MAYBE_DANGEROUS_CONTENT; + return download::DOWNLOAD_DANGER_TYPE_MAYBE_DANGEROUS_CONTENT; case DownloadDangerType::UNCOMMON_CONTENT: - return content::DOWNLOAD_DANGER_TYPE_UNCOMMON_CONTENT; + return download::DOWNLOAD_DANGER_TYPE_UNCOMMON_CONTENT; case DownloadDangerType::USER_VALIDATED: - return content::DOWNLOAD_DANGER_TYPE_USER_VALIDATED; + return download::DOWNLOAD_DANGER_TYPE_USER_VALIDATED; case DownloadDangerType::DANGEROUS_HOST: - return content::DOWNLOAD_DANGER_TYPE_DANGEROUS_HOST; + return download::DOWNLOAD_DANGER_TYPE_DANGEROUS_HOST; case DownloadDangerType::POTENTIALLY_UNWANTED: - return content::DOWNLOAD_DANGER_TYPE_POTENTIALLY_UNWANTED; + return download::DOWNLOAD_DANGER_TYPE_POTENTIALLY_UNWANTED; case DownloadDangerType::INVALID: NOTREACHED(); - return content::DOWNLOAD_DANGER_TYPE_MAX; + return download::DOWNLOAD_DANGER_TYPE_MAX; } NOTREACHED(); - return content::DOWNLOAD_DANGER_TYPE_MAX; + return download::DOWNLOAD_DANGER_TYPE_MAX; } DownloadDangerType ToHistoryDownloadDangerType( - content::DownloadDangerType danger_type) { + download::DownloadDangerType danger_type) { switch (danger_type) { - case content::DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS: + case download::DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS: return DownloadDangerType::NOT_DANGEROUS; - case content::DOWNLOAD_DANGER_TYPE_DANGEROUS_FILE: + case download::DOWNLOAD_DANGER_TYPE_DANGEROUS_FILE: return DownloadDangerType::DANGEROUS_FILE; - case content::DOWNLOAD_DANGER_TYPE_DANGEROUS_URL: + case download::DOWNLOAD_DANGER_TYPE_DANGEROUS_URL: return DownloadDangerType::DANGEROUS_URL; - case content::DOWNLOAD_DANGER_TYPE_DANGEROUS_CONTENT: + case download::DOWNLOAD_DANGER_TYPE_DANGEROUS_CONTENT: return DownloadDangerType::DANGEROUS_CONTENT; - case content::DOWNLOAD_DANGER_TYPE_MAYBE_DANGEROUS_CONTENT: + case download::DOWNLOAD_DANGER_TYPE_MAYBE_DANGEROUS_CONTENT: return DownloadDangerType::MAYBE_DANGEROUS_CONTENT; - case content::DOWNLOAD_DANGER_TYPE_UNCOMMON_CONTENT: + case download::DOWNLOAD_DANGER_TYPE_UNCOMMON_CONTENT: return DownloadDangerType::UNCOMMON_CONTENT; - case content::DOWNLOAD_DANGER_TYPE_USER_VALIDATED: + case download::DOWNLOAD_DANGER_TYPE_USER_VALIDATED: return DownloadDangerType::USER_VALIDATED; - case content::DOWNLOAD_DANGER_TYPE_DANGEROUS_HOST: + case download::DOWNLOAD_DANGER_TYPE_DANGEROUS_HOST: return DownloadDangerType::DANGEROUS_HOST; - case content::DOWNLOAD_DANGER_TYPE_POTENTIALLY_UNWANTED: + case download::DOWNLOAD_DANGER_TYPE_POTENTIALLY_UNWANTED: return DownloadDangerType::POTENTIALLY_UNWANTED; default: NOTREACHED();
diff --git a/components/history/content/browser/download_conversions.h b/components/history/content/browser/download_conversions.h index e708944a..bf433b55 100644 --- a/components/history/content/browser/download_conversions.h +++ b/components/history/content/browser/download_conversions.h
@@ -9,9 +9,9 @@ #include <string> +#include "components/download/public/common/download_danger_type.h" #include "components/history/core/browser/download_slice_info.h" #include "components/history/core/browser/download_types.h" -#include "content/public/browser/download_danger_type.h" #include "content/public/browser/download_interrupt_reasons.h" #include "content/public/browser/download_item.h" @@ -24,12 +24,12 @@ DownloadState ToHistoryDownloadState( content::DownloadItem::DownloadState state); -// Utility functions to convert between content::DownloadDangerType enumeration +// Utility functions to convert between download::DownloadDangerType enumeration // and history::DownloadDangerType constants. -content::DownloadDangerType ToContentDownloadDangerType( +download::DownloadDangerType ToContentDownloadDangerType( DownloadDangerType danger_type); DownloadDangerType ToHistoryDownloadDangerType( - content::DownloadDangerType danger_type); + download::DownloadDangerType danger_type); // Utility functions to convert between content::DownloadInterruptReason // enumeration and history::DownloadInterruptReason type (value have no
diff --git a/components/history/core/browser/history_backend.cc b/components/history/core/browser/history_backend.cc index 510529f..2500839 100644 --- a/components/history/core/browser/history_backend.cc +++ b/components/history/core/browser/history_backend.cc
@@ -648,7 +648,8 @@ // The frequency of this UMA will indicate how often history // initialization fails. UMA_HISTOGRAM_BOOLEAN("History.AttemptedToFixProfileError", kill_db); - } // Falls through. + FALLTHROUGH; + } case sql::INIT_TOO_NEW: { db_diagnostics_ += sql::GetCorruptFileDiagnosticsInfo(history_name); delegate_->NotifyProfileError(status, db_diagnostics_);
diff --git a/components/history/core/browser/history_backend_unittest.cc b/components/history/core/browser/history_backend_unittest.cc index a6d3758..0401408 100644 --- a/components/history/core/browser/history_backend_unittest.cc +++ b/components/history/core/browser/history_backend_unittest.cc
@@ -1373,6 +1373,7 @@ break; case history::SOURCE_SYNCED: sources |= 0x4; + break; default: break; }
diff --git a/components/invalidation/impl/android/javatests/src/org/chromium/components/invalidation/InvalidationClientServiceTest.java b/components/invalidation/impl/android/javatests/src/org/chromium/components/invalidation/InvalidationClientServiceTest.java index fed1d48..ebf15e0 100644 --- a/components/invalidation/impl/android/javatests/src/org/chromium/components/invalidation/InvalidationClientServiceTest.java +++ b/components/invalidation/impl/android/javatests/src/org/chromium/components/invalidation/InvalidationClientServiceTest.java
@@ -7,6 +7,7 @@ import android.accounts.Account; import android.content.ComponentName; import android.content.Intent; +import android.support.test.InstrumentationRegistry; import android.support.test.filters.SmallTest; import android.test.ServiceTestCase; @@ -71,7 +72,7 @@ public void setUp() throws Exception { super.setUp(); mStartServiceIntents = new ArrayList<>(); - setContext(new AdvancedMockContext(getContext()) { + setContext(new AdvancedMockContext(InstrumentationRegistry.getTargetContext()) { @Override public ComponentName startService(Intent intent) { mStartServiceIntents.add(intent);
diff --git a/components/language/core/common/BUILD.gn b/components/language/core/common/BUILD.gn new file mode 100644 index 0000000..6d8f155 --- /dev/null +++ b/components/language/core/common/BUILD.gn
@@ -0,0 +1,28 @@ +# 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. + +static_library("common") { + sources = [ + "locale_util.cc", + "locale_util.h", + ] + + deps = [ + "//base", + "//ui/base", + ] +} + +source_set("unit_tests") { + testonly = true + sources = [ + "locale_util_unittest.cc", + ] + deps = [ + ":common", + "//base", + "//testing/gmock", + "//testing/gtest", + ] +}
diff --git a/components/language/core/common/DEPS b/components/language/core/common/DEPS new file mode 100644 index 0000000..ebbc9b8 --- /dev/null +++ b/components/language/core/common/DEPS
@@ -0,0 +1,3 @@ +include_rules = [ + "+ui/base/l10n", +]
diff --git a/components/language/core/common/locale_util.cc b/components/language/core/common/locale_util.cc new file mode 100644 index 0000000..7ed93d6 --- /dev/null +++ b/components/language/core/common/locale_util.cc
@@ -0,0 +1,117 @@ +// 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 "components/language/core/common/locale_util.h" + +#include <algorithm> +#include <set> +#include <vector> + +#include "base/command_line.h" +#include "base/macros.h" +#include "base/strings/string_split.h" +#include "ui/base/l10n/l10n_util.h" + +namespace language { + +namespace { + +// Pair of locales, where the first element should fallback to the second one. +struct LocaleUIFallbackPair { + const char* const chosen_locale; + const char* const fallback_locale; +}; + +// This list MUST be sorted by the first element in the pair, because we perform +// binary search on it. +// TODO(claudiomagni): Investigate Norvegian language. There are 2 codes ("nn", +// "no") that fallback to "nb", but the base language should be "nn". +const LocaleUIFallbackPair kLocaleUIFallbackTable[] = { + {"en", "en-US"}, {"en-AU", "en-GB"}, {"en-CA", "en-GB"}, + {"en-IN", "en-GB"}, {"en-NZ", "en-GB"}, {"en-ZA", "en-GB"}, + {"es-AR", "es-419"}, {"es-CL", "es-419"}, {"es-CO", "es-419"}, + {"es-CR", "es-419"}, {"es-HN", "es-419"}, {"es-MX", "es-419"}, + {"es-PE", "es-419"}, {"es-US", "es-419"}, {"es-UY", "es-419"}, + {"es-VE", "es-419"}, {"it-CH", "it"}, {"nn", "nb"}, + {"no", "nb"}, {"pt", "pt-PT"}}; + +bool LocaleCompare(const LocaleUIFallbackPair& p1, const std::string& p2) { + return p1.chosen_locale < p2; +} + +bool GetUIFallbackLocale(const std::string& input, std::string* const output) { + *output = input; + const auto* it = + std::lower_bound(std::begin(kLocaleUIFallbackTable), + std::end(kLocaleUIFallbackTable), input, LocaleCompare); + if (it != std::end(kLocaleUIFallbackTable) && it->chosen_locale == input) { + *output = it->fallback_locale; + return true; + } + return false; +} + +// Given a language code, extract the base language only. +// Example: from "en-US", extract "en". +std::string ExtractBaseLanguage(const std::string& language_code) { + std::string base; + std::string tail; + SplitIntoMainAndTail(language_code, &base, &tail); + return base; +} + +} // namespace + +void SplitIntoMainAndTail(const std::string& locale, + std::string* main_part, + std::string* tail_part) { + DCHECK(main_part); + DCHECK(tail_part); + + std::vector<base::StringPiece> chunks = base::SplitStringPiece( + locale, "-", base::TRIM_WHITESPACE, base::SPLIT_WANT_ALL); + if (chunks.empty()) + return; + + chunks[0].CopyToString(main_part); + *tail_part = locale.substr(main_part->size()); +} + +bool ContainsSameBaseLanguage(const std::vector<std::string>& list, + const std::string& language_code) { + const std::string base_language = ExtractBaseLanguage(language_code); + for (const auto& item : list) { + const std::string compare_base = ExtractBaseLanguage(item); + if (compare_base == base_language) + return true; + } + + return false; +} + +bool ConvertToActualUILocale(std::string* input_locale) { + const std::vector<std::string>& ui_locales = l10n_util::GetAvailableLocales(); + const std::set<std::string> ui_set(ui_locales.begin(), ui_locales.end()); + + // 1) Convert input to a fallback, if available. + std::string fallback; + GetUIFallbackLocale(*input_locale, &fallback); + + // 2) Check if input is part of the UI languages. + if (ui_set.count(fallback) > 0) { + *input_locale = fallback; + return true; + } + + // 3) Check if the base language of the input is part of the UI languages. + const std::string base = ExtractBaseLanguage(*input_locale); + if (base != *input_locale && ui_set.count(base) > 0) { + *input_locale = base; + return true; + } + + return false; +} + +} // namespace language
diff --git a/components/language/core/common/locale_util.h b/components/language/core/common/locale_util.h new file mode 100644 index 0000000..68f5563 --- /dev/null +++ b/components/language/core/common/locale_util.h
@@ -0,0 +1,36 @@ +// 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. + +#ifndef COMPONENTS_LANGUAGE_CORE_COMMON_LOCALE_UTIL_H_ +#define COMPONENTS_LANGUAGE_CORE_COMMON_LOCALE_UTIL_H_ + +#include <string> +#include <vector> + +namespace language { + +// Split the |locale| into two parts. For example, if |locale| is 'en-US', +// this will be split into the main part 'en' and the tail part '-US'. +void SplitIntoMainAndTail(const std::string& locale, + std::string* main_part, + std::string* tail_part); + +// Returns whether or not the given list includes at least one language with +// the same base as the input language. +// For example: "en-US" and "en-UK" share the same base "en". +bool ContainsSameBaseLanguage(const std::vector<std::string>& list, + const std::string& language_code); + +// Converts the input locale into its corresponding actual UI locale that +// Chrome should use for display and returns whether such locale exist. +// This method must be called whenever the display locale preference is +// read, because users can select a set of languages that is larger than +// the set of actual UI locales. +// If |input_locale| cannot be used as display UI, this method returns false +// and the content of |input_locale| is not modified. +bool ConvertToActualUILocale(std::string* input_locale); + +} // namespace language + +#endif // COMPONENTS_LANGUAGE_CORE_COMMON_LOCALE_UTIL_H_
diff --git a/components/language/core/common/locale_util_unittest.cc b/components/language/core/common/locale_util_unittest.cc new file mode 100644 index 0000000..eb06a0b --- /dev/null +++ b/components/language/core/common/locale_util_unittest.cc
@@ -0,0 +1,264 @@ +// 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. + +#include "components/language/core/common/locale_util.h" + +#include "base/command_line.h" +#include "build/build_config.h" +#include "testing/gtest/include/gtest/gtest.h" + +typedef testing::Test LocaleUtilTest; + +TEST_F(LocaleUtilTest, SplitIntoMainAndTail) { + std::string locale; + std::string main; + std::string tail; + + locale = ""; + language::SplitIntoMainAndTail(locale, &main, &tail); + EXPECT_TRUE(main.empty()); + EXPECT_TRUE(tail.empty()); + + locale = "en"; + main.clear(); + tail.clear(); + language::SplitIntoMainAndTail(locale, &main, &tail); + EXPECT_EQ("en", main); + EXPECT_TRUE(tail.empty()); + + locale = "ogard543i"; + main.clear(); + tail.clear(); + language::SplitIntoMainAndTail(locale, &main, &tail); + EXPECT_EQ("ogard543i", main); + EXPECT_TRUE(tail.empty()); + + locale = "en-AU"; + main.clear(); + tail.clear(); + language::SplitIntoMainAndTail(locale, &main, &tail); + EXPECT_EQ("en", main); + EXPECT_EQ("-AU", tail); + + locale = "es-419"; + main.clear(); + tail.clear(); + language::SplitIntoMainAndTail(locale, &main, &tail); + EXPECT_EQ("es", main); + EXPECT_EQ("-419", tail); + + locale = "en-AU-2009"; + main.clear(); + tail.clear(); + language::SplitIntoMainAndTail(locale, &main, &tail); + EXPECT_EQ("en", main); + EXPECT_EQ("-AU-2009", tail); +} + +TEST_F(LocaleUtilTest, ContainsSameBaseLanguage) { + std::vector<std::string> list; + + // Empty input. + EXPECT_EQ(false, language::ContainsSameBaseLanguage(list, "")); + + // Empty list. + EXPECT_EQ(false, language::ContainsSameBaseLanguage(list, "fr-FR")); + + // Empty language. + list = {"en-US"}; + EXPECT_EQ(false, language::ContainsSameBaseLanguage(list, "")); + + // One element, no match. + list = {"en-US"}; + EXPECT_EQ(false, language::ContainsSameBaseLanguage(list, "fr-FR")); + + // One element, with match. + list = {"fr-CA"}; + EXPECT_EQ(true, language::ContainsSameBaseLanguage(list, "fr-FR")); + + // Multiple elements, no match. + list = {"en-US", "es-AR", "en-UK"}; + EXPECT_EQ(false, language::ContainsSameBaseLanguage(list, "fr-FR")); + + // Multiple elements, with match. + list = {"en-US", "fr-CA", "es-AR"}; + EXPECT_EQ(true, language::ContainsSameBaseLanguage(list, "fr-FR")); + + // Multiple elements matching. + list = {"en-US", "fr-CA", "es-AR", "fr-FR"}; + EXPECT_EQ(true, language::ContainsSameBaseLanguage(list, "fr-FR")); + + // List includes base language. + list = {"en-US", "fr", "es-AR", "fr-FR"}; + EXPECT_EQ(true, language::ContainsSameBaseLanguage(list, "fr-FR")); +} + +TEST_F(LocaleUtilTest, ConvertToActualUILocale) { + std::string locale; + + //--------------------------------------------------------------------------- + // Languages that are enabled as display UI. + //--------------------------------------------------------------------------- + locale = "en-US"; + bool is_ui = language::ConvertToActualUILocale(&locale); + EXPECT_TRUE(is_ui); + EXPECT_EQ("en-US", locale); + + locale = "it"; + is_ui = language::ConvertToActualUILocale(&locale); + EXPECT_TRUE(is_ui); + EXPECT_EQ("it", locale); + + locale = "fr-FR"; + is_ui = language::ConvertToActualUILocale(&locale); + EXPECT_TRUE(is_ui); + EXPECT_EQ("fr-FR", locale); + + //--------------------------------------------------------------------------- + // Languages that are converted to their fallback version. + //--------------------------------------------------------------------------- + + // All Latin American Spanish languages fall back to "es-419". + locale = "es-AR"; + is_ui = language::ConvertToActualUILocale(&locale); + EXPECT_TRUE(is_ui); + EXPECT_EQ("es-419", locale); + + locale = "es-CL"; + is_ui = language::ConvertToActualUILocale(&locale); + EXPECT_TRUE(is_ui); + EXPECT_EQ("es-419", locale); + + locale = "es-CO"; + is_ui = language::ConvertToActualUILocale(&locale); + EXPECT_TRUE(is_ui); + EXPECT_EQ("es-419", locale); + + locale = "es-CR"; + is_ui = language::ConvertToActualUILocale(&locale); + EXPECT_TRUE(is_ui); + EXPECT_EQ("es-419", locale); + + locale = "es-HN"; + is_ui = language::ConvertToActualUILocale(&locale); + EXPECT_TRUE(is_ui); + EXPECT_EQ("es-419", locale); + + locale = "es-MX"; + is_ui = language::ConvertToActualUILocale(&locale); + EXPECT_TRUE(is_ui); + EXPECT_EQ("es-419", locale); + + locale = "es-PE"; + is_ui = language::ConvertToActualUILocale(&locale); + EXPECT_TRUE(is_ui); + EXPECT_EQ("es-419", locale); + + locale = "es-US"; + is_ui = language::ConvertToActualUILocale(&locale); + EXPECT_TRUE(is_ui); + EXPECT_EQ("es-419", locale); + + locale = "es-UY"; + is_ui = language::ConvertToActualUILocale(&locale); + EXPECT_TRUE(is_ui); + EXPECT_EQ("es-419", locale); + + locale = "es-VE"; + is_ui = language::ConvertToActualUILocale(&locale); + EXPECT_TRUE(is_ui); + EXPECT_EQ("es-419", locale); + + // English falls back to US. + locale = "en"; + is_ui = language::ConvertToActualUILocale(&locale); + EXPECT_TRUE(is_ui); + EXPECT_EQ("en-US", locale); + + // All other regional English languages fall back to UK. + locale = "en-AU"; + is_ui = language::ConvertToActualUILocale(&locale); + EXPECT_TRUE(is_ui); + EXPECT_EQ("en-GB", locale); + + locale = "en-CA"; + is_ui = language::ConvertToActualUILocale(&locale); + EXPECT_TRUE(is_ui); + EXPECT_EQ("en-GB", locale); + + locale = "en-IN"; + is_ui = language::ConvertToActualUILocale(&locale); + EXPECT_TRUE(is_ui); + EXPECT_EQ("en-GB", locale); + + locale = "en-NZ"; + is_ui = language::ConvertToActualUILocale(&locale); + EXPECT_TRUE(is_ui); + EXPECT_EQ("en-GB", locale); + + locale = "en-ZA"; + is_ui = language::ConvertToActualUILocale(&locale); + EXPECT_TRUE(is_ui); + EXPECT_EQ("en-GB", locale); + + locale = "pt"; + is_ui = language::ConvertToActualUILocale(&locale); + EXPECT_TRUE(is_ui); + EXPECT_EQ("pt-PT", locale); + + locale = "it-CH"; + is_ui = language::ConvertToActualUILocale(&locale); + EXPECT_TRUE(is_ui); + EXPECT_EQ("it", locale); + + locale = "nn"; + is_ui = language::ConvertToActualUILocale(&locale); + EXPECT_TRUE(is_ui); + EXPECT_EQ("nb", locale); + + locale = "no"; + is_ui = language::ConvertToActualUILocale(&locale); + EXPECT_TRUE(is_ui); + EXPECT_EQ("nb", locale); + + //--------------------------------------------------------------------------- + // Languages that have their base language is a UI language. + //--------------------------------------------------------------------------- + locale = "it-IT"; + is_ui = language::ConvertToActualUILocale(&locale); + EXPECT_TRUE(is_ui); + EXPECT_EQ("it", locale); + + locale = "de-DE"; + is_ui = language::ConvertToActualUILocale(&locale); + EXPECT_TRUE(is_ui); + EXPECT_EQ("de", locale); + +//--------------------------------------------------------------------------- +// Languages that cannot be used as display UI. +//--------------------------------------------------------------------------- +// This only matters for ChromeOS and Windows, as they are the only systems +// where users can set the display UI. +#if defined(OS_CHROMEOS) || defined(OS_WIN) + locale = "sd"; // Sindhi + is_ui = language::ConvertToActualUILocale(&locale); + EXPECT_FALSE(is_ui); + + locale = "af"; // Afrikaans + is_ui = language::ConvertToActualUILocale(&locale); + EXPECT_FALSE(is_ui); + + locale = "ga"; // Irish + is_ui = language::ConvertToActualUILocale(&locale); + EXPECT_FALSE(is_ui); + + locale = "ky"; // Kyrgyz + is_ui = language::ConvertToActualUILocale(&locale); + EXPECT_FALSE(is_ui); + + locale = "zu"; // Zulu + is_ui = language::ConvertToActualUILocale(&locale); + EXPECT_FALSE(is_ui); +#endif +}
diff --git a/components/metrics/BUILD.gn b/components/metrics/BUILD.gn index 825b7ea6..125430e 100644 --- a/components/metrics/BUILD.gn +++ b/components/metrics/BUILD.gn
@@ -94,6 +94,8 @@ "system_memory_stats_recorder.h", "system_memory_stats_recorder_linux.cc", "system_memory_stats_recorder_win.cc", + "system_session_analyzer_win.cc", + "system_session_analyzer_win.h", "url_constants.cc", "url_constants.h", "version_utils.cc", @@ -132,6 +134,7 @@ if (is_win) { sources -= [ "machine_id_provider_stub.cc" ] deps += [ "//components/browser_watcher:stability_client" ] + libs = [ "wevtapi.lib" ] } if (is_fuchsia) { @@ -346,6 +349,7 @@ "single_sample_metrics_factory_impl_unittest.cc", "stability_metrics_helper_unittest.cc", "stability_metrics_provider_unittest.cc", + "system_session_analyzer_win_unittest.cc", "ui/screen_info_metrics_provider_unittest.cc", ]
diff --git a/components/metrics/OWNERS b/components/metrics/OWNERS index c929027..68c3f9c 100644 --- a/components/metrics/OWNERS +++ b/components/metrics/OWNERS
@@ -1,3 +1,5 @@ file://base/metrics/OWNERS +per-file *call_stack_profile*=wittman@chromium.org + # COMPONENT: Internals>Metrics
diff --git a/components/metrics/metrics_upload_scheduler.cc b/components/metrics/metrics_upload_scheduler.cc index 22e1f2d..457a725 100644 --- a/components/metrics/metrics_upload_scheduler.cc +++ b/components/metrics/metrics_upload_scheduler.cc
@@ -15,13 +15,6 @@ namespace metrics { -// This feature moves the upload schedule to a seperate schedule from the -// log rotation schedule. This may change upload timing slightly, but -// would allow some compartmentalization of uploader logic to allow more -// code reuse between different metrics services. -const base::Feature kUploadSchedulerFeature{"UMAUploadScheduler", - base::FEATURE_DISABLED_BY_DEFAULT}; - namespace { // When uploading metrics to the server fails, we progressively wait longer and @@ -51,24 +44,16 @@ return interval; } -// Gets a time interval in seconds from a variations parameter. -base::TimeDelta GetTimeParameterSeconds(const std::string& param_name, - int default_seconds) { - int seconds = base::GetFieldTrialParamByFeatureAsInt( - kUploadSchedulerFeature, param_name, default_seconds); - return base::TimeDelta::FromSeconds(seconds); -} - // Time delay after a log is uploaded successfully before attempting another. // On mobile, keeping the radio on is very expensive, so prefer to keep this // short and send in bursts. base::TimeDelta GetUnsentLogsInterval() { - return GetTimeParameterSeconds("UnsentLogsIntervalSeconds", 3); + return base::TimeDelta::FromSeconds(3); } // Inital time delay after a log uploaded fails before retrying it. base::TimeDelta GetInitialBackoffInterval() { - return GetTimeParameterSeconds("InitialBackoffIntervalSeconds", 15); + return base::TimeDelta::FromSeconds(15); } } // namespace
diff --git a/components/metrics/metrics_upload_scheduler.h b/components/metrics/metrics_upload_scheduler.h index b1fa958..a97b7cb 100644 --- a/components/metrics/metrics_upload_scheduler.h +++ b/components/metrics/metrics_upload_scheduler.h
@@ -13,8 +13,6 @@ namespace metrics { -extern const base::Feature kUploadSchedulerFeature; - // Scheduler task to drive a ReportingService object's uploading. class MetricsUploadScheduler : public MetricsScheduler { public:
diff --git a/components/browser_watcher/system_session_analyzer_win.cc b/components/metrics/system_session_analyzer_win.cc similarity index 97% rename from components/browser_watcher/system_session_analyzer_win.cc rename to components/metrics/system_session_analyzer_win.cc index e488219..8e33647e 100644 --- a/components/browser_watcher/system_session_analyzer_win.cc +++ b/components/metrics/system_session_analyzer_win.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 "components/browser_watcher/system_session_analyzer_win.h" +#include "components/metrics/system_session_analyzer_win.h" #include <windows.h> #include <winevt.h> @@ -12,7 +12,7 @@ #include "base/macros.h" #include "base/time/time.h" -namespace browser_watcher { +namespace metrics { namespace { @@ -241,4 +241,4 @@ return true; } -} // namespace browser_watcher +} // namespace metrics
diff --git a/components/browser_watcher/system_session_analyzer_win.h b/components/metrics/system_session_analyzer_win.h similarity index 91% rename from components/browser_watcher/system_session_analyzer_win.h rename to components/metrics/system_session_analyzer_win.h index 33162cd..f5d8288 100644 --- a/components/browser_watcher/system_session_analyzer_win.h +++ b/components/metrics/system_session_analyzer_win.h
@@ -12,7 +12,7 @@ #include "base/gtest_prod_util.h" #include "base/time/time.h" -namespace browser_watcher { +namespace metrics { // Analyzes system session events for unclean sessions. Initialization is // expensive and therefore done lazily, as the analyzer is instantiated before @@ -38,6 +38,9 @@ virtual ~SystemSessionAnalyzer(); // Returns an analysis status for the system session that contains timestamp. + // TODO(siggi): it'd make more sense to do iterative fetching in this + // function. This will require moving the query handle into the class + // declaration. virtual Status IsSessionUnclean(base::Time timestamp); protected: @@ -70,6 +73,6 @@ DISALLOW_COPY_AND_ASSIGN(SystemSessionAnalyzer); }; -} // namespace browser_watcher +} // namespace metrics #endif // COMPONENTS_BROWSER_WATCHER_SYSTEM_SESSION_ANALYZER_WIN_H_
diff --git a/components/browser_watcher/system_session_analyzer_win_unittest.cc b/components/metrics/system_session_analyzer_win_unittest.cc similarity index 96% rename from components/browser_watcher/system_session_analyzer_win_unittest.cc rename to components/metrics/system_session_analyzer_win_unittest.cc index 62c96234..c43156f 100644 --- a/components/browser_watcher/system_session_analyzer_win_unittest.cc +++ b/components/metrics/system_session_analyzer_win_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 "components/browser_watcher/system_session_analyzer_win.h" +#include "components/metrics/system_session_analyzer_win.h" #include <utility> #include <vector> @@ -11,7 +11,7 @@ #include "testing/gmock/include/gmock/gmock.h" #include "testing/gtest/include/gtest/gtest.h" -namespace browser_watcher { +namespace metrics { namespace { @@ -114,4 +114,4 @@ analyzer.IsSessionUnclean(base::Time::Now())); } -} // namespace browser_watcher +} // namespace metrics
diff --git a/components/ntp_snippets/breaking_news/subscription_manager_impl_unittest.cc b/components/ntp_snippets/breaking_news/subscription_manager_impl_unittest.cc index 7d240da..091022eb 100644 --- a/components/ntp_snippets/breaking_news/subscription_manager_impl_unittest.cc +++ b/components/ntp_snippets/breaking_news/subscription_manager_impl_unittest.cc
@@ -13,7 +13,6 @@ #include "components/prefs/testing_pref_service.h" #include "components/signin/core/browser/fake_profile_oauth2_token_service.h" #include "components/signin/core/browser/fake_signin_manager.h" -#include "components/signin/core/browser/profile_management_switches.h" #include "components/signin/core/browser/test_signin_client.h" #include "google_apis/gaia/fake_oauth2_token_service_delegate.h" #include "net/base/net_errors.h" @@ -50,9 +49,6 @@ void SetUp() override { SubscriptionManagerImpl::RegisterProfilePrefs( utils_.pref_service()->registry()); - signin::RegisterAccountConsistencyProfilePrefs( - utils_.pref_service()->registry()); - signin::SetGaiaOriginIsolatedCallback(base::Bind([] { return true; })); utils_.token_service()->AddDiagnosticsObserver(this); }
diff --git a/components/ntp_snippets/remote/remote_suggestions_fetcher_impl.cc b/components/ntp_snippets/remote/remote_suggestions_fetcher_impl.cc index 10ed99a..c9e4990 100644 --- a/components/ntp_snippets/remote/remote_suggestions_fetcher_impl.cc +++ b/components/ntp_snippets/remote/remote_suggestions_fetcher_impl.cc
@@ -15,9 +15,9 @@ #include "components/ntp_snippets/category.h" #include "components/ntp_snippets/ntp_snippets_constants.h" #include "components/ntp_snippets/user_classifier.h" -#include "components/signin/core/browser/signin_manager_base.h" #include "net/url_request/url_fetcher.h" #include "net/url_request/url_request_status.h" +#include "services/identity/public/cpp/identity_manager.h" #include "services/identity/public/cpp/primary_account_access_token_fetcher.h" using language::UrlLanguageHistogram; @@ -124,8 +124,7 @@ } // namespace RemoteSuggestionsFetcherImpl::RemoteSuggestionsFetcherImpl( - SigninManagerBase* signin_manager, - OAuth2TokenService* token_service, + identity::IdentityManager* identity_manager, scoped_refptr<URLRequestContextGetter> url_request_context_getter, PrefService* pref_service, UrlLanguageHistogram* language_histogram, @@ -133,8 +132,7 @@ const GURL& api_endpoint, const std::string& api_key, const UserClassifier* user_classifier) - : signin_manager_(signin_manager), - token_service_(token_service), + : identity_manager_(identity_manager), url_request_context_getter_(std::move(url_request_context_getter)), language_histogram_(language_histogram), parse_json_callback_(parse_json_callback), @@ -184,7 +182,7 @@ .SetUrlRequestContextGetter(url_request_context_getter_) .SetUserClassifier(*user_classifier_); - if (signin_manager_->IsAuthenticated()) { + if (identity_manager_->HasPrimaryAccount()) { // Signed-in: get OAuth token --> fetch suggestions. pending_requests_.emplace(std::move(builder), std::move(callback)); StartTokenRequest(); @@ -217,7 +215,7 @@ SnippetsAvailableCallback callback, const std::string& oauth_access_token) { builder.SetUrl(fetch_url_) - .SetAuthentication(signin_manager_->GetAuthenticatedAccountId(), + .SetAuthentication(identity_manager_->GetPrimaryAccountInfo().account_id, base::StringPrintf(kAuthorizationRequestHeaderFormat, oauth_access_token.c_str())); StartRequest(std::move(builder), std::move(callback), @@ -242,8 +240,8 @@ } OAuth2TokenService::ScopeSet scopes{kContentSuggestionsApiScope}; - token_fetcher_ = std::make_unique<identity::PrimaryAccountAccessTokenFetcher>( - "ntp_snippets", signin_manager_, token_service_, scopes, + token_fetcher_ = identity_manager_->CreateAccessTokenFetcherForPrimaryAccount( + "ntp_snippets", scopes, base::BindOnce(&RemoteSuggestionsFetcherImpl::AccessTokenFetchFinished, base::Unretained(this)), identity::PrimaryAccountAccessTokenFetcher::Mode::kWaitUntilAvailable);
diff --git a/components/ntp_snippets/remote/remote_suggestions_fetcher_impl.h b/components/ntp_snippets/remote/remote_suggestions_fetcher_impl.h index feb79e5..1eb456b 100644 --- a/components/ntp_snippets/remote/remote_suggestions_fetcher_impl.h +++ b/components/ntp_snippets/remote/remote_suggestions_fetcher_impl.h
@@ -20,15 +20,14 @@ #include "components/ntp_snippets/remote/request_params.h" #include "net/url_request/url_request_context_getter.h" -class OAuth2TokenService; class PrefService; -class SigninManagerBase; namespace base { class Value; } // namespace base namespace identity { +class IdentityManager; class PrimaryAccountAccessTokenFetcher; } @@ -43,8 +42,7 @@ class RemoteSuggestionsFetcherImpl : public RemoteSuggestionsFetcher { public: RemoteSuggestionsFetcherImpl( - SigninManagerBase* signin_manager, - OAuth2TokenService* token_service, + identity::IdentityManager* identity_manager, scoped_refptr<net::URLRequestContextGetter> url_request_context_getter, PrefService* pref_service, language::UrlLanguageHistogram* language_histogram, @@ -94,8 +92,7 @@ bool is_authenticated); // Authentication for signed-in users. - SigninManagerBase* signin_manager_; - OAuth2TokenService* token_service_; + identity::IdentityManager* identity_manager_; std::unique_ptr<identity::PrimaryAccountAccessTokenFetcher> token_fetcher_;
diff --git a/components/ntp_snippets/remote/remote_suggestions_fetcher_impl_unittest.cc b/components/ntp_snippets/remote/remote_suggestions_fetcher_impl_unittest.cc index 67d205b..f0779a4 100644 --- a/components/ntp_snippets/remote/remote_suggestions_fetcher_impl_unittest.cc +++ b/components/ntp_snippets/remote/remote_suggestions_fetcher_impl_unittest.cc
@@ -10,6 +10,7 @@ #include "base/containers/circular_deque.h" #include "base/json/json_reader.h" +#include "base/message_loop/message_loop.h" #include "base/optional.h" #include "base/test/histogram_tester.h" #include "base/test/test_mock_time_task_runner.h" @@ -26,14 +27,12 @@ #include "components/ntp_snippets/remote/test_utils.h" #include "components/ntp_snippets/user_classifier.h" #include "components/prefs/testing_pref_service.h" -#include "components/signin/core/browser/fake_profile_oauth2_token_service.h" -#include "components/signin/core/browser/fake_signin_manager.h" #include "components/variations/entropy_provider.h" #include "components/variations/variations_params_manager.h" -#include "google_apis/gaia/fake_oauth2_token_service_delegate.h" #include "net/traffic_annotation/network_traffic_annotation_test_helper.h" #include "net/url_request/test_url_fetcher_factory.h" #include "net/url_request/url_request_test_util.h" +#include "services/identity/public/cpp/identity_test_environment.h" #include "testing/gmock/include/gmock/gmock.h" #include "testing/gtest/include/gtest/gtest.h" @@ -59,7 +58,7 @@ const char kTestChromeContentSuggestionsSignedInUrl[] = "https://chromecontentsuggestions-pa.googleapis.com/v1/suggestions/fetch"; -const char kTestEmail[] = "foo@bar.com"; +const char kTestAccount[] = "foo@bar.com"; // Artificial time delay for JSON parsing. const int64_t kTestJsonParsingLatencyMs = 20; @@ -259,9 +258,7 @@ } // namespace -class RemoteSuggestionsFetcherImplTestBase - : public testing::Test, - public OAuth2TokenService::DiagnosticsObserver { +class RemoteSuggestionsFetcherImplTestBase : public testing::Test { public: explicit RemoteSuggestionsFetcherImplTestBase(const GURL& gurl) : default_variation_params_( @@ -281,8 +278,6 @@ } ~RemoteSuggestionsFetcherImplTestBase() override { - if (fake_token_service_) - fake_token_service_->RemoveDiagnosticsObserver(this); } void ResetFetcher() { ResetFetcherWithAPIKey(kAPIKey); } @@ -291,16 +286,8 @@ scoped_refptr<net::TestURLRequestContextGetter> request_context_getter = new net::TestURLRequestContextGetter(mock_task_runner_.get()); - if (fake_token_service_) - fake_token_service_->RemoveDiagnosticsObserver(this); - fake_token_service_ = std::make_unique<FakeProfileOAuth2TokenService>( - std::make_unique<FakeOAuth2TokenServiceDelegate>( - request_context_getter.get())); - - fake_token_service_->AddDiagnosticsObserver(this); - fetcher_ = std::make_unique<RemoteSuggestionsFetcherImpl>( - utils_.fake_signin_manager(), fake_token_service_.get(), + identity_test_env_.identity_manager(), std::move(request_context_getter), utils_.pref_service(), nullptr, base::BindRepeating(&ParseJsonDelayed), GetFetchEndpoint(version_info::Channel::STABLE), api_key, @@ -311,26 +298,8 @@ } void SignIn() { -#if defined(OS_CHROMEOS) - utils_.fake_signin_manager()->SignIn(kTestEmail); -#else - utils_.fake_signin_manager()->SignIn(kTestEmail, "user", "password"); -#endif - } - - void IssueRefreshToken() { - fake_token_service_->GetDelegate()->UpdateCredentials(kTestEmail, "token"); - } - - void IssueOAuth2Token() { - fake_token_service_->IssueAllTokensForAccount(kTestEmail, "access_token", - base::Time::Max()); - } - - void CancelOAuth2TokenRequests() { - fake_token_service_->IssueErrorForAllPendingRequestsForAccount( - kTestEmail, GoogleServiceAuthError( - GoogleServiceAuthError::State::REQUEST_CANCELED)); + identity_test_env_.MakePrimaryAccountAvailable(kTestAccount, kTestAccount, + "token"); } RemoteSuggestionsFetcher::SnippetsAvailableCallback @@ -380,23 +349,12 @@ fake_url_fetcher_factory_->SetFakeResponse(test_url_, response_data, response_code, status); } - void set_on_access_token_request_callback(base::OnceClosure callback) { - on_access_token_request_callback_ = std::move(callback); - } protected: std::map<std::string, std::string> default_variation_params_; + identity::IdentityTestEnvironment identity_test_env_; private: - // OAuth2TokenService::DiagnosticsObserver: - void OnAccessTokenRequested( - const std::string& account_id, - const std::string& consumer_id, - const OAuth2TokenService::ScopeSet& scopes) override { - if (on_access_token_request_callback_) - std::move(on_access_token_request_callback_).Run(); - } - // TODO(tzik): Remove |clock_| after updating GetMockTickClock to own the // instance. http://crbug.com/789079 std::unique_ptr<base::Clock> clock_; @@ -407,13 +365,11 @@ FailingFakeURLFetcherFactory failing_url_fetcher_factory_; // Initialized lazily in SetFakeResponse(). std::unique_ptr<net::FakeURLFetcherFactory> fake_url_fetcher_factory_; - std::unique_ptr<FakeProfileOAuth2TokenService> fake_token_service_; std::unique_ptr<RemoteSuggestionsFetcherImpl> fetcher_; std::unique_ptr<UserClassifier> user_classifier_; MockSnippetsAvailableCallback mock_callback_; const GURL test_url_; base::HistogramTester histogram_tester_; - base::OnceClosure on_access_token_request_callback_; DISALLOW_COPY_AND_ASSIGN(RemoteSuggestionsFetcherImplTestBase); }; @@ -489,11 +445,7 @@ } TEST_F(RemoteSuggestionsSignedInFetcherTest, ShouldFetchSuccessfully) { - base::RunLoop run_loop; - set_on_access_token_request_callback(run_loop.QuitClosure()); - SignIn(); - IssueRefreshToken(); const std::string kJsonStr = "{\"categories\" : [{" @@ -523,9 +475,9 @@ fetcher().FetchSnippets(test_params(), ToSnippetsAvailableCallback(&mock_callback())); - run_loop.Run(); + identity_test_env_.WaitForAccessTokenRequestAndRespondWithToken( + "access_token", base::Time::Max()); - IssueOAuth2Token(); // Wait for the fake response. FastForwardUntilNoTasksRemain(); @@ -540,11 +492,7 @@ } TEST_F(RemoteSuggestionsSignedInFetcherTest, ShouldRetryWhenOAuthCancelled) { - base::RunLoop run_loop; - set_on_access_token_request_callback(run_loop.QuitClosure()); - SignIn(); - IssueRefreshToken(); const std::string kJsonStr = "{\"categories\" : [{" @@ -574,20 +522,15 @@ fetcher().FetchSnippets(test_params(), ToSnippetsAvailableCallback(&mock_callback())); - // Wait for the first access token request to be made. - run_loop.Run(); + // Cancel the first access token request that's made. + identity_test_env_.WaitForAccessTokenRequestAndRespondWithError( + GoogleServiceAuthError(GoogleServiceAuthError::State::REQUEST_CANCELED)); - // Before cancelling the outstanding access token request, prepare to wait for - // the second access token request to be made in response to the cancellation. - base::RunLoop run_loop2; - set_on_access_token_request_callback(run_loop2.QuitClosure()); + // RemoteSuggestionsFetcher should retry fetching an access token if the first + // attempt is cancelled. Respond with a valid access token on the retry. + identity_test_env_.WaitForAccessTokenRequestAndRespondWithToken( + "access_token", base::Time::Max()); - CancelOAuth2TokenRequests(); - - // Wait for the second access token request to be made. - run_loop2.Run(); - - IssueOAuth2Token(); // Wait for the fake response. FastForwardUntilNoTasksRemain();
diff --git a/components/ntp_snippets/remote/remote_suggestions_provider_impl.cc b/components/ntp_snippets/remote/remote_suggestions_provider_impl.cc index 4b92259..f866e6c 100644 --- a/components/ntp_snippets/remote/remote_suggestions_provider_impl.cc +++ b/components/ntp_snippets/remote/remote_suggestions_provider_impl.cc
@@ -390,7 +390,8 @@ breaking_news_raw_data_provider_( std::move(breaking_news_raw_data_provider)), debug_logger_(debug_logger), - fetch_timeout_timer_(std::move(fetch_timeout_timer)) { + fetch_timeout_timer_(std::move(fetch_timeout_timer)), + request_status_(FetchRequestStatus::NONE) { DCHECK(debug_logger_); DCHECK(fetch_timeout_timer_); RestoreCategoriesFromPrefs(); @@ -572,6 +573,14 @@ } return; } + if (request_status_ == FetchRequestStatus::NONE) { + // We cannot rule out concurrent requests although they are rare as the user + // has to trigger ReloadSuggestions() while the scheduler decides for a + // background fetch. Although preventing concurrent fetches would be + // desireable, it's not worth the effort (also see TODO() in + // OnFetchFinished()). + request_status_ = FetchRequestStatus::IN_PROGRESS; + } // |count_to_fetch| is actually ignored, because the server does not support // this functionality. @@ -724,6 +733,19 @@ // because it is not known which history entries were used for the suggestions // personalization. ClearHistoryDependentState(); + if (request_status_ == FetchRequestStatus::IN_PROGRESS || + request_status_ == FetchRequestStatus::IN_PROGRESS_NEEDS_REFETCH) { + request_status_ = FetchRequestStatus::IN_PROGRESS_CANCELED; + } +} + +void RemoteSuggestionsProviderImpl::ClearCachedSuggestions() { + ClearCachedSuggestionsImpl(); + if (request_status_ == FetchRequestStatus::IN_PROGRESS) { + // Called by external cache-cleared trigger. As this can be caused by + // language change, we need to refetch a potentiall ongoing fetch. + request_status_ = FetchRequestStatus::IN_PROGRESS_NEEDS_REFETCH; + } } void RemoteSuggestionsProviderImpl::OnSignInStateChanged(bool has_signed_in) { @@ -897,12 +919,31 @@ RemoteSuggestionsFetcher::OptionalFetchedCategories fetched_categories) { debug_logger_->Log(FROM_HERE, /*message=*/std::string()); + FetchRequestStatus request_status = request_status_; + // TODO(jkrcal): This is potentially incorrect if there is another concurrent + // request in progress; when it finishes we will treat it as a standard + // request even though it may need to be refetched/disregarded. Even though + // the scheduler never triggers two concurrent requests, the user can trigger + // the second request via the UI. If cache/history gets cleared before neither + // of the two finishes, we can get outdated results afterwards. Low chance & + // low risk, feels safe to ignore. + request_status_ = FetchRequestStatus::NONE; + if (!ready()) { // TODO(tschumann): What happens if this was a user-triggered, interactive // request? Is the UI waiting indefinitely now? return; } + if (request_status == FetchRequestStatus::IN_PROGRESS_NEEDS_REFETCH) { + // Disregard the results and start a fetch again. + FetchSuggestions(interactive_request, std::move(callback)); + return; + } else if (request_status == FetchRequestStatus::IN_PROGRESS_CANCELED) { + // Disregard the results. + return; + } + if (!status.IsSuccess()) { if (callback) { std::move(callback).Run(status); @@ -1333,16 +1374,18 @@ return; } + debug_logger_->Log(FROM_HERE, /*message=*/std::string()); NukeAllSuggestions(); remote_suggestions_scheduler_->OnHistoryCleared(); } -void RemoteSuggestionsProviderImpl::ClearCachedSuggestions() { +void RemoteSuggestionsProviderImpl::ClearCachedSuggestionsImpl() { if (!initialized()) { clear_cached_suggestions_when_initialized_ = true; return; } + debug_logger_->Log(FROM_HERE, /*message=*/std::string()); NukeAllSuggestions(); remote_suggestions_scheduler_->OnSuggestionsCleared(); } @@ -1469,7 +1512,10 @@ DCHECK(state_ == State::READY); // Clear nonpersonalized suggestions (and notify the scheduler there are // no suggestions). - ClearCachedSuggestions(); + ClearCachedSuggestionsImpl(); + if (request_status_ == FetchRequestStatus::IN_PROGRESS) { + request_status_ = FetchRequestStatus::IN_PROGRESS_NEEDS_REFETCH; + } } else { EnterState(State::READY); } @@ -1480,7 +1526,10 @@ DCHECK(state_ == State::READY); // Clear personalized suggestions (and notify the scheduler there are // no suggestions). - ClearCachedSuggestions(); + ClearCachedSuggestionsImpl(); + if (request_status_ == FetchRequestStatus::IN_PROGRESS) { + request_status_ = FetchRequestStatus::IN_PROGRESS_NEEDS_REFETCH; + } } else { EnterState(State::READY); } @@ -1521,7 +1570,7 @@ UpdateAllCategoryStatus(CategoryStatus::AVAILABLE); if (clear_cached_suggestions_when_initialized_) { - ClearCachedSuggestions(); + ClearCachedSuggestionsImpl(); clear_cached_suggestions_when_initialized_ = false; } if (clear_history_dependent_state_when_initialized_) { @@ -1547,7 +1596,7 @@ clear_history_dependent_state_when_initialized_ = false; ClearHistoryDependentState(); } - ClearCachedSuggestions(); + ClearCachedSuggestionsImpl(); clear_cached_suggestions_when_initialized_ = false; if (breaking_news_raw_data_provider_ &&
diff --git a/components/ntp_snippets/remote/remote_suggestions_provider_impl.h b/components/ntp_snippets/remote/remote_suggestions_provider_impl.h index a8e67b8..bd27cda 100644 --- a/components/ntp_snippets/remote/remote_suggestions_provider_impl.h +++ b/components/ntp_snippets/remote/remote_suggestions_provider_impl.h
@@ -161,6 +161,8 @@ CallsSchedulerWhenSignedIn); FRIEND_TEST_ALL_PREFIXES(RemoteSuggestionsProviderImplTest, CallsSchedulerWhenSignedOut); + FRIEND_TEST_ALL_PREFIXES(RemoteSuggestionsProviderImplTest, + RestartsFetchWhenSignedInWhileFetching); FRIEND_TEST_ALL_PREFIXES( RemoteSuggestionsProviderImplTest, ShouldNotSetExclusiveCategoryWhenFetchingSuggestions); @@ -206,6 +208,25 @@ COUNT }; + // Documents the status of the ongoing request and what action should be taken + // on completion. + enum class FetchRequestStatus { + // There is no request in progress for remote suggestions. + NONE, + + // There is a valid request in progress that should be treated normally on + // completion. + IN_PROGRESS, + + // There is a canceled request in progress. The response should be ignored + // when it arrives. + IN_PROGRESS_CANCELED, + + // There is an invalidated request in progress. On completion, we should + // ignore the response and initiate a new fetch (with updated parameters). + IN_PROGRESS_NEEDS_REFETCH + }; + struct CategoryContent { // The current status of the category. CategoryStatus status = CategoryStatus::INITIALIZING; @@ -333,6 +354,9 @@ // Clears suggestions because any history item has been removed. void ClearHistoryDependentState(); + // Clears the cached suggestions + void ClearCachedSuggestionsImpl(); + // Clears all stored suggestions and updates the observer. void NukeAllSuggestions(); @@ -448,6 +472,12 @@ // A Timer for canceling too long fetches. std::unique_ptr<base::OneShotTimer> fetch_timeout_timer_; + // Keeps track of the status of the ongoing request(s) and what action should + // be taken on completion. Requests via Fetch() (fetching more) are _not_ + // tracked by this variable (as they do not need any special actions on + // completion). + FetchRequestStatus request_status_; + DISALLOW_COPY_AND_ASSIGN(RemoteSuggestionsProviderImpl); };
diff --git a/components/ntp_snippets/remote/remote_suggestions_provider_impl_unittest.cc b/components/ntp_snippets/remote/remote_suggestions_provider_impl_unittest.cc index 945923c3..4eb9606 100644 --- a/components/ntp_snippets/remote/remote_suggestions_provider_impl_unittest.cc +++ b/components/ntp_snippets/remote/remote_suggestions_provider_impl_unittest.cc
@@ -569,6 +569,19 @@ } RemoteSuggestionsFetcher::SnippetsAvailableCallback + FetchSuggestionsAndGetResponseCallback( + RemoteSuggestionsProviderImpl* provider, + bool interactive_request) { + RemoteSuggestionsFetcher::SnippetsAvailableCallback snippets_callback; + EXPECT_CALL(*mock_suggestions_fetcher(), FetchSnippets(_, _)) + .WillOnce(MoveSecondArgumentPointeeTo(&snippets_callback)) + .RetiresOnSaturation(); + provider->FetchSuggestions( + interactive_request, RemoteSuggestionsProvider::FetchStatusCallback()); + return snippets_callback; + } + + RemoteSuggestionsFetcher::SnippetsAvailableCallback RefetchWhileDisplayingAndGetResponseCallback( RemoteSuggestionsProviderImpl* provider) { RemoteSuggestionsFetcher::SnippetsAvailableCallback snippets_callback; @@ -2453,6 +2466,65 @@ } TEST_F(RemoteSuggestionsProviderImplTest, + RestartsFetchWhenSignedInWhileFetching) { + auto provider = + MakeSuggestionsProviderWithoutInitializationWithStrictScheduler(); + // Initiate the provider so that it is already READY. + EXPECT_CALL(*scheduler(), OnProviderActivated()); + WaitForSuggestionsProviderInitialization(provider.get()); + + // Initiate the fetch. + RemoteSuggestionsFetcher::SnippetsAvailableCallback snippets_callback; + EXPECT_CALL(*mock_suggestions_fetcher(), FetchSnippets(_, _)) + .WillOnce(MoveSecondArgumentPointeeTo(&snippets_callback)) + .RetiresOnSaturation(); + provider->FetchSuggestions(/*interactive_request=*/false, + RemoteSuggestionsProvider::FetchStatusCallback()); + + // The scheduler should be notified of clearing the suggestions. + EXPECT_CALL(*scheduler(), OnSuggestionsCleared()); + provider->OnStatusChanged(RemoteSuggestionsStatus::ENABLED_AND_SIGNED_OUT, + RemoteSuggestionsStatus::ENABLED_AND_SIGNED_IN); + + // Once we signal the first fetch to be finished (calling snippets_callback + // below), a new fetch should get triggered. + EXPECT_CALL(*mock_suggestions_fetcher(), FetchSnippets(_, _)).Times(1); + std::move(snippets_callback) + .Run(Status::Success(), std::vector<FetchedCategory>()); +} + +TEST_F(RemoteSuggestionsProviderImplTest, + IgnoresResultsWhenHistoryClearedWhileFetching) { + auto provider = + MakeSuggestionsProviderWithoutInitializationWithStrictScheduler(); + // Initiate the provider so that it is already READY. + EXPECT_CALL(*scheduler(), OnProviderActivated()); + WaitForSuggestionsProviderInitialization(provider.get()); + + // Initiate the fetch. + RemoteSuggestionsFetcher::SnippetsAvailableCallback snippets_callback = + FetchSuggestionsAndGetResponseCallback(provider.get(), + /*interactive_request=*/false); + + // The scheduler should be notified of clearing the history. + EXPECT_CALL(*scheduler(), OnHistoryCleared()); + provider->ClearHistory(GetDefaultCreationTime(), GetDefaultExpirationTime(), + base::RepeatingCallback<bool(const GURL& url)>()); + + // Once the fetch finishes, the returned suggestions are ignored. + FetchedCategoryBuilder category_builder; + category_builder.SetCategory(articles_category()); + category_builder.AddSuggestionViaBuilder( + RemoteSuggestionBuilder().AddId(base::StringPrintf("http://abc.com"))); + std::vector<FetchedCategory> fetched_categories; + fetched_categories.push_back(category_builder.Build()); + std::move(snippets_callback) + .Run(Status::Success(), std::move(fetched_categories)); + EXPECT_THAT(observer().SuggestionsForCategory(articles_category()), + SizeIs(0)); +} + +TEST_F(RemoteSuggestionsProviderImplTest, ShouldExcludeKnownSuggestionsWithoutTruncatingWhenFetchingMore) { auto provider = MakeSuggestionsProvider( /*use_mock_prefetched_pages_tracker=*/false,
diff --git a/components/offline_pages/core/downloads/download_ui_adapter.cc b/components/offline_pages/core/downloads/download_ui_adapter.cc index 4334e0c..8bb08e0 100644 --- a/components/offline_pages/core/downloads/download_ui_adapter.cc +++ b/components/offline_pages/core/downloads/download_ui_adapter.cc
@@ -8,6 +8,7 @@ #include "base/guid.h" #include "base/logging.h" #include "base/threading/thread_task_runner_handle.h" +#include "base/trace_event/trace_event.h" #include "components/offline_pages/core/background/request_coordinator.h" #include "components/offline_pages/core/background/save_page_request.h" #include "components/offline_pages/core/client_namespace_constants.h" @@ -386,6 +387,8 @@ } items_.clear(); state_ = State::NOT_LOADED; + TRACE_EVENT_ASYNC_END0("offline_pages", "DownloadUIAdapter: items cached", + this); } void DownloadUIAdapter::OnOfflinePagesLoaded( @@ -437,6 +440,8 @@ request_coordinator_->AddObserver(this); state_ = State::LOADED; + TRACE_EVENT_ASYNC_BEGIN1("offline_pages", "DownloadUIAdapter: items cached", + this, "initial count", items_.size()); for (auto& observer : observers_) observer.OnItemsAvailable(this);
diff --git a/components/offline_pages/core/model/clear_legacy_temporary_pages_task.cc b/components/offline_pages/core/model/clear_legacy_temporary_pages_task.cc index b2802c85..bea3cb6 100644 --- a/components/offline_pages/core/model/clear_legacy_temporary_pages_task.cc +++ b/components/offline_pages/core/model/clear_legacy_temporary_pages_task.cc
@@ -10,6 +10,7 @@ #include "base/bind.h" #include "base/files/file_util.h" +#include "base/trace_event/trace_event.h" #include "components/offline_pages/core/client_policy_controller.h" #include "components/offline_pages/core/offline_page_metadata_store_sql.h" #include "components/offline_pages/core/offline_store_utils.h" @@ -128,6 +129,8 @@ ClearLegacyTemporaryPagesTask::~ClearLegacyTemporaryPagesTask() {} void ClearLegacyTemporaryPagesTask::Run() { + TRACE_EVENT_ASYNC_BEGIN0("offline_pages", + "ClearLegacyTemporaryPagesTask running", this); std::vector<std::string> temp_namespaces = policy_controller_->GetNamespacesRemovedOnCacheReset(); store_->Execute( @@ -145,6 +148,9 @@ // indicating which part failed. DVLOG(1) << "ClearLegacyTemporaryPagesTask returns with result: " << result; TaskComplete(); + TRACE_EVENT_ASYNC_END1("offline_pages", + "ClearLegacyTemporaryPagesTask running", this, + "result", result); } } // namespace offline_pages
diff --git a/components/offline_pages/core/model/clear_storage_task.cc b/components/offline_pages/core/model/clear_storage_task.cc index a494369..bd203f98 100644 --- a/components/offline_pages/core/model/clear_storage_task.cc +++ b/components/offline_pages/core/model/clear_storage_task.cc
@@ -16,6 +16,7 @@ #include "base/time/clock.h" #include "base/time/default_clock.h" #include "base/time/time.h" +#include "base/trace_event/trace_event.h" #include "components/offline_pages/core/client_policy_controller.h" #include "components/offline_pages/core/offline_page_client_policy.h" #include "components/offline_pages/core/offline_page_metadata_store_sql.h" @@ -240,6 +241,7 @@ ClearStorageTask::~ClearStorageTask() {} void ClearStorageTask::Run() { + TRACE_EVENT_ASYNC_BEGIN0("offline_pages", "ClearStorageTask running", this); archive_manager_->GetStorageStats( base::Bind(&ClearStorageTask::OnGetStorageStatsDone, weak_ptr_factory_.GetWeakPtr())); @@ -272,6 +274,9 @@ ClearStorageResult result) { std::move(callback_).Run(pages_cleared, result); TaskComplete(); + TRACE_EVENT_ASYNC_END2("offline_pages", "ClearStorageTask running", this, + "result", static_cast<int>(result), "pages_cleared", + pages_cleared); } } // namespace offline_pages
diff --git a/components/offline_pages/core/model/persistent_pages_consistency_check_task.cc b/components/offline_pages/core/model/persistent_pages_consistency_check_task.cc index 5b7b383b..2d25774 100644 --- a/components/offline_pages/core/model/persistent_pages_consistency_check_task.cc +++ b/components/offline_pages/core/model/persistent_pages_consistency_check_task.cc
@@ -14,6 +14,7 @@ #include "base/files/file_enumerator.h" #include "base/files/file_util.h" #include "base/metrics/histogram_macros.h" +#include "base/trace_event/trace_event.h" #include "components/offline_pages/core/client_policy_controller.h" #include "components/offline_pages/core/offline_page_metadata_store_sql.h" #include "components/offline_pages/core/offline_page_types.h" @@ -172,6 +173,8 @@ PersistentPagesConsistencyCheckTask::~PersistentPagesConsistencyCheckTask() {} void PersistentPagesConsistencyCheckTask::Run() { + TRACE_EVENT_ASYNC_BEGIN0("offline_pages", + "PersistentPagesConsistencyCheckTask running", this); std::vector<std::string> namespaces = policy_controller_->GetAllNamespaces(); std::vector<std::string> persistent_namespace_names; for (const auto& name_space : namespaces) { @@ -191,6 +194,9 @@ UMA_HISTOGRAM_ENUMERATION("OfflinePages.ConsistencyCheck.Persistent.Result", result, SyncOperationResult::RESULT_COUNT); TaskComplete(); + TRACE_EVENT_ASYNC_END1("offline_pages", + "PersistentPagesConsistencyCheckTask running", this, + "result", static_cast<int>(result)); } } // namespace offline_pages
diff --git a/components/offline_pages/core/model/temporary_pages_consistency_check_task.cc b/components/offline_pages/core/model/temporary_pages_consistency_check_task.cc index 7f8e83b..21e04f9 100644 --- a/components/offline_pages/core/model/temporary_pages_consistency_check_task.cc +++ b/components/offline_pages/core/model/temporary_pages_consistency_check_task.cc
@@ -14,6 +14,7 @@ #include "base/files/file_enumerator.h" #include "base/files/file_util.h" #include "base/metrics/histogram_macros.h" +#include "base/trace_event/trace_event.h" #include "components/offline_pages/core/client_policy_controller.h" #include "components/offline_pages/core/offline_page_metadata_store_sql.h" #include "components/offline_pages/core/offline_page_types.h" @@ -171,6 +172,8 @@ TemporaryPagesConsistencyCheckTask::~TemporaryPagesConsistencyCheckTask() {} void TemporaryPagesConsistencyCheckTask::Run() { + TRACE_EVENT_ASYNC_BEGIN0("offline_pages", + "TemporaryPagesConsistencyCheckTask running", this); std::vector<std::string> temp_namespaces = policy_controller_->GetNamespacesRemovedOnCacheReset(); store_->Execute( @@ -185,6 +188,9 @@ UMA_HISTOGRAM_ENUMERATION("OfflinePages.ConsistencyCheck.Temporary.Result", result, SyncOperationResult::RESULT_COUNT); TaskComplete(); + TRACE_EVENT_ASYNC_END1("offline_pages", + "TemporaryPagesConsistencyCheckTask running", this, + "result", static_cast<int>(result)); } } // namespace offline_pages
diff --git a/components/offline_pages/core/offline_page_metadata_store_sql.h b/components/offline_pages/core/offline_page_metadata_store_sql.h index 3b7dadd..4cfc96c 100644 --- a/components/offline_pages/core/offline_page_metadata_store_sql.h +++ b/components/offline_pages/core/offline_page_metadata_store_sql.h
@@ -123,9 +123,9 @@ return; } - TRACE_EVENT_ASYNC_BEGIN1("offline_pages", - "Metadata Store: Command execution", this, - "is store loaded", state_ == StoreState::LOADED); + TRACE_EVENT_ASYNC_BEGIN1("offline_pages", "Metadata Store: task execution", + this, "is store loaded", + state_ == StoreState::LOADED); // This if allows to run commands later, after store was given a chance to // initialize. They would be failing immediately otherwise. if (state_ == StoreState::INITIALIZING) { @@ -133,9 +133,8 @@ base::BindOnce(&OfflinePageMetadataStoreSQL::Execute<T>, weak_ptr_factory_.GetWeakPtr(), std::move(run_callback), std::move(result_callback))); - TRACE_EVENT_ASYNC_END1("offline_pages", - "Metadata Store: Command execution", this, - "postponed", true); + TRACE_EVENT_ASYNC_END1("offline_pages", "Metadata Store: task execution", + this, "postponed", true); return; } @@ -172,10 +171,16 @@ base::BindOnce(&OfflinePageMetadataStoreSQL::CloseInternal, closing_weak_ptr_factory_.GetWeakPtr()), kClosingDelay); - TRACE_EVENT_ASYNC_END0("offline_pages", "Metadata Store: Command execution", - this); + // Note: the time recorded for this trace step will include thread hop wait + // times to the background thread and back. + TRACE_EVENT_ASYNC_STEP_PAST0( + "offline_pages", "Metadata Store: task execution", this, "Task"); std::move(result_callback).Run(std::move(result)); + TRACE_EVENT_ASYNC_STEP_PAST0( + "offline_pages", "Metadata Store: task execution", this, "Callback"); + TRACE_EVENT_ASYNC_END0("offline_pages", "Metadata Store: task execution", + this); } // Internal function initiating the closing.
diff --git a/components/offline_pages/core/prefetch/prefetch_downloader_impl.cc b/components/offline_pages/core/prefetch/prefetch_downloader_impl.cc index fe3fada..2006d54f 100644 --- a/components/offline_pages/core/prefetch/prefetch_downloader_impl.cc +++ b/components/offline_pages/core/prefetch/prefetch_downloader_impl.cc
@@ -9,6 +9,7 @@ #include "base/strings/string_util.h" #include "base/time/default_clock.h" #include "base/time/time.h" +#include "base/trace_event/trace_event.h" #include "components/download/public/background_service/download_params.h" #include "components/download/public/background_service/download_service.h" #include "components/offline_pages/core/offline_event_logger.h" @@ -146,6 +147,15 @@ success_downloads) { DCHECK_EQ(DownloadServiceStatus::INITIALIZING, download_service_status_); download_service_status_ = DownloadServiceStatus::STARTED; + // Given the imposed simultaneous downloads limits, outstanding_download_ids + // will only ever contain a handful of elements and so only a negligible + // performance impact is expected from the trace-only loop below. + for (const std::string& outstanding_download_id : outstanding_download_ids) { + TRACE_EVENT_ASYNC_BEGIN2( + "offline_pages", "PrefetchDownloaderImpl: downloading article", + std::hash<std::string>{}(outstanding_download_id), "download_id", + outstanding_download_id, "resumed after restart", "true"); + } prefetch_service_->GetLogger()->RecordActivity("Downloader: Service ready."); @@ -177,6 +187,9 @@ const std::string& download_id, const base::FilePath& file_path, int64_t file_size) { + TRACE_EVENT_ASYNC_END1( + "offline_pages", "PrefetchDownloaderImpl: downloading article", + std::hash<std::string>{}(download_id), "succeeded", "true"); prefetch_service_->GetLogger()->RecordActivity( "Downloader: Download succeeded, download_id=" + download_id); NotifyDispatcher(prefetch_service_, @@ -184,6 +197,9 @@ } void PrefetchDownloaderImpl::OnDownloadFailed(const std::string& download_id) { + TRACE_EVENT_ASYNC_END1( + "offline_pages", "PrefetchDownloaderImpl: downloading article", + std::hash<std::string>{}(download_id), "succeeded", "false"); PrefetchDownloadResult result; result.download_id = download_id; prefetch_service_->GetLogger()->RecordActivity( @@ -206,8 +222,13 @@ // to simplify the control flow since this situation should rarely happen. The // Download.Service.Request.StartResult.OfflinePage histogram tracks these // cases and would signal the need to revisit this decision. - if (result != download::DownloadParams::StartResult::ACCEPTED) + if (result != download::DownloadParams::StartResult::ACCEPTED) { OnDownloadFailed(download_id); + } else { + TRACE_EVENT_ASYNC_BEGIN1( + "offline_pages", "PrefetchDownloaderImpl: downloading article", + std::hash<std::string>{}(download_id), "download_id", download_id); + } } void PrefetchDownloaderImpl::CleanupDownloads(
diff --git a/components/offline_pages/core/prefetch/store/prefetch_store.h b/components/offline_pages/core/prefetch/store/prefetch_store.h index d316c64..355b1e3 100644 --- a/components/offline_pages/core/prefetch/store/prefetch_store.h +++ b/components/offline_pages/core/prefetch/store/prefetch_store.h
@@ -86,7 +86,7 @@ } TRACE_EVENT_ASYNC_BEGIN1( - "offline_pages", "Prefetch Store: Command execution", this, + "offline_pages", "Prefetch Store: task execution", this, "is store loaded", initialization_status_ == InitializationStatus::SUCCESS); // Ensure that any scheduled close operations are canceled. @@ -128,10 +128,16 @@ base::BindOnce(&PrefetchStore::CloseInternal, closing_weak_ptr_factory_.GetWeakPtr()), kClosingDelay); - TRACE_EVENT_ASYNC_END0("offline_pages", "Prefetch Store: Command execution", - this); + // Note: the time recorded for this trace step will include thread hop wait + // times to the background thread and back. + TRACE_EVENT_ASYNC_STEP_PAST0( + "offline_pages", "Prefetch Store: task execution", this, "Task"); std::move(result_callback).Run(std::move(result)); + TRACE_EVENT_ASYNC_STEP_PAST0( + "offline_pages", "Prefetch Store: task execution", this, "Callback"); + TRACE_EVENT_ASYNC_END0("offline_pages", "Prefetch Store: task execution", + this); } // Internal function initiating the closing.
diff --git a/components/omnibox/browser/BUILD.gn b/components/omnibox/browser/BUILD.gn index 45a9632..20bfe2ed 100644 --- a/components/omnibox/browser/BUILD.gn +++ b/components/omnibox/browser/BUILD.gn
@@ -31,6 +31,9 @@ "star.1x.icon", "star.icon", "tab.icon", + "touchable_bookmark.icon", + "touchable_page.icon", + "touchable_search.icon", ] }
diff --git a/components/omnibox/browser/autocomplete_match.cc b/components/omnibox/browser/autocomplete_match.cc index 6ec39ae9..8a72d58 100644 --- a/components/omnibox/browser/autocomplete_match.cc +++ b/components/omnibox/browser/autocomplete_match.cc
@@ -26,6 +26,7 @@ #include "components/search_engines/template_url.h" #include "components/search_engines/template_url_service.h" #include "net/base/registry_controlled_domains/registry_controlled_domain.h" +#include "ui/base/ui_base_features.h" #include "ui/gfx/vector_icon_types.h" #include "url/third_party/mozilla/url_parse.h" @@ -185,8 +186,15 @@ } // static -const gfx::VectorIcon& AutocompleteMatch::TypeToVectorIcon(Type type) { +const gfx::VectorIcon& AutocompleteMatch::TypeToVectorIcon(Type type, + bool is_bookmark) { #if (!defined(OS_ANDROID) || BUILDFLAG(ENABLE_VR)) && !defined(OS_IOS) + const bool is_touch_ui = + base::FeatureList::IsEnabled(features::kTouchableChrome); + + if (is_bookmark) + return is_touch_ui ? omnibox::kTouchableBookmarkIcon : omnibox::kStarIcon; + switch (type) { case Type::URL_WHAT_YOU_TYPED: case Type::HISTORY_URL: @@ -199,7 +207,7 @@ case Type::CLIPBOARD: case Type::PHYSICAL_WEB: case Type::PHYSICAL_WEB_OVERFLOW: - return omnibox::kHttpIcon; + return is_touch_ui ? omnibox::kTouchablePageIcon : omnibox::kHttpIcon; case Type::TAB_SEARCH: return omnibox::kTabIcon; @@ -213,7 +221,8 @@ case Type::SEARCH_OTHER_ENGINE: case Type::CONTACT_DEPRECATED: case Type::VOICE_SUGGEST: - return vector_icons::kSearchIcon; + return is_touch_ui ? omnibox::kTouchableSearchIcon + : vector_icons::kSearchIcon; case Type::EXTENSION_APP: return omnibox::kExtensionAppIcon;
diff --git a/components/omnibox/browser/autocomplete_match.h b/components/omnibox/browser/autocomplete_match.h index 8e4342f0..f1d3ba04 100644 --- a/components/omnibox/browser/autocomplete_match.h +++ b/components/omnibox/browser/autocomplete_match.h
@@ -114,8 +114,10 @@ // Converts |type| to a string representation. Used in logging and debugging. AutocompleteMatch& operator=(const AutocompleteMatch& match); - // Gets the vector icon identifier for the icon to be shown for |type|. - static const gfx::VectorIcon& TypeToVectorIcon(Type type); + // Gets the vector icon identifier for the icon to be shown for |type|. If + // |is_bookmark| is true, returns a bookmark icon rather than what the type + // would determine. + static const gfx::VectorIcon& TypeToVectorIcon(Type type, bool is_bookmark); // Comparison function for determining when one match is better than another. static bool MoreRelevant(const AutocompleteMatch& elem1,
diff --git a/components/omnibox/browser/omnibox_popup_model.cc b/components/omnibox/browser/omnibox_popup_model.cc index da1ed54..8a43604 100644 --- a/components/omnibox/browser/omnibox_popup_model.cc +++ b/components/omnibox/browser/omnibox_popup_model.cc
@@ -291,8 +291,7 @@ } const auto& vector_icon_type = - IsStarredMatch(match) ? omnibox::kStarIcon - : AutocompleteMatch::TypeToVectorIcon(match.type); + AutocompleteMatch::TypeToVectorIcon(match.type, IsStarredMatch(match)); return gfx::Image( gfx::CreateVectorIcon(vector_icon_type, 16, vector_icon_color)); }
diff --git a/components/omnibox/browser/omnibox_view.cc b/components/omnibox/browser/omnibox_view.cc index f07bc2a..98e7fdec 100644 --- a/components/omnibox/browser/omnibox_view.cc +++ b/components/omnibox/browser/omnibox_view.cc
@@ -107,7 +107,8 @@ return AutocompleteMatch::TypeToVectorIcon( model_ ? model_->CurrentTextType() - : AutocompleteMatchType::URL_WHAT_YOU_TYPED); + : AutocompleteMatchType::URL_WHAT_YOU_TYPED, + /*is_bookmark=*/false); } void OmniboxView::SetUserText(const base::string16& text) {
diff --git a/components/omnibox/browser/vector_icons/touchable_bookmark.icon b/components/omnibox/browser/vector_icons/touchable_bookmark.icon new file mode 100644 index 0000000..3610301 --- /dev/null +++ b/components/omnibox/browser/vector_icons/touchable_bookmark.icon
@@ -0,0 +1,22 @@ +// 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. + +CANVAS_DIMENSIONS, 20, +MOVE_TO, 10, 18, +R_ARC_TO, 8, 8, 0, 1, 1, 0, -16, +R_ARC_TO, 8, 8, 0, 0, 1, 0, 16, +CLOSE, +R_MOVE_TO, 0, -4.96f, +LINE_TO, 13.09f, 15, +R_LINE_TO, -0.82f, -3.7f, +LINE_TO, 15, 8.81f, +R_LINE_TO, -3.59f, -0.32f, +LINE_TO, 10, 5, +LINE_TO, 8.6f, 8.49f, +LINE_TO, 5, 8.81f, +R_LINE_TO, 2.73f, 2.49f, +R_LINE_TO, -0.82f, 3.7f, +LINE_TO, 10, 13.04f, +CLOSE, +END
diff --git a/components/omnibox/browser/vector_icons/touchable_page.icon b/components/omnibox/browser/vector_icons/touchable_page.icon new file mode 100644 index 0000000..8c809680 --- /dev/null +++ b/components/omnibox/browser/vector_icons/touchable_page.icon
@@ -0,0 +1,21 @@ +// 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. + +CANVAS_DIMENSIONS, 20, +MOVE_TO, 6, 16.93f, +CUBIC_TO, 3.61f, 15.55f, 2, 12.96f, 2, 10, +CUBIC_TO, 2, 5.58f, 5.58f, 2, 10, 2, +CUBIC_TO, 14.42f, 2, 18, 5.58f, 18, 10, +CUBIC_TO, 18, 12.96f, 16.39f, 15.55f, 14, 16.93f, +LINE_TO, 14, 9.5f, +LINE_TO, 10.5f, 6, +LINE_TO, 6, 6, +LINE_TO, 6, 16.93f, +CLOSE, +MOVE_TO, 13, 11, +LINE_TO, 9, 11, +LINE_TO, 9, 7, +LINE_TO, 13, 11, +CLOSE, +END
diff --git a/components/omnibox/browser/vector_icons/touchable_search.icon b/components/omnibox/browser/vector_icons/touchable_search.icon new file mode 100644 index 0000000..e19765a --- /dev/null +++ b/components/omnibox/browser/vector_icons/touchable_search.icon
@@ -0,0 +1,25 @@ +// 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. + +CANVAS_DIMENSIONS, 20, +MOVE_TO, 16.02f, 15.27f, +R_LINE_TO, -2.59f, -2.6f, +R_H_LINE_TO, -0.47f, +R_LINE_TO, -0.17f, -0.16f, +R_ARC_TO, 3.84f, 3.84f, 0, 0, 0, 0.93f, -2.51f, +R_ARC_TO, 3.86f, 3.86f, 0, 0, 0, -3.86f, -3.86f, +ARC_TO, 3.86f, 3.86f, 0, 0, 0, 6, 10, +R_ARC_TO, 3.86f, 3.86f, 0, 0, 0, 6.37f, 2.93f, +R_LINE_TO, 0.16f, 0.17f, +R_V_LINE_TO, 0.47f, +R_LINE_TO, 2.59f, 2.59f, +R_ARC_TO, 8, 8, 0, 1, 1, 0.9f, -0.87f, +CLOSE, +MOVE_TO, 9.86f, 12.67f, +ARC_TO, 2.67f, 2.67f, 0, 0, 1, 7.19f, 10, +ARC_TO, 2.67f, 2.67f, 0, 0, 1, 9.86f, 7.33f, +ARC_TO, 2.67f, 2.67f, 0, 0, 1, 12.53f, 10, +R_ARC_TO, 2.67f, 2.67f, 0, 0, 1, -2.67f, 2.67f, +CLOSE, +END
diff --git a/components/password_manager/core/browser/BUILD.gn b/components/password_manager/core/browser/BUILD.gn index b9214ba..2f260de 100644 --- a/components/password_manager/core/browser/BUILD.gn +++ b/components/password_manager/core/browser/BUILD.gn
@@ -175,7 +175,6 @@ deps = [ ":hash_password_manager", ":proto", - "//base", "//base:i18n", "//components/autofill/core/browser", "//components/autofill/core/browser/proto", @@ -426,6 +425,7 @@ ] deps = [ ":browser", + "//base:i18n", "//components/autofill/core/common:common", ] seed_corpus = "import/password_csv_reader_corpus"
diff --git a/components/password_manager/core/browser/import/password_csv_reader_fuzzer.cc b/components/password_manager/core/browser/import/password_csv_reader_fuzzer.cc index 6a6e228..3906e41 100644 --- a/components/password_manager/core/browser/import/password_csv_reader_fuzzer.cc +++ b/components/password_manager/core/browser/import/password_csv_reader_fuzzer.cc
@@ -8,11 +8,21 @@ #include <string> #include <vector> +#include "base/at_exit.h" +#include "base/i18n/icu_util.h" #include "components/autofill/core/common/password_form.h" #include "components/password_manager/core/browser/import/password_csv_reader.h" namespace password_manager { +struct IcuEnvironment { + IcuEnvironment() { CHECK(base::i18n::InitializeICU()); } + // used by ICU integration. + base::AtExitManager at_exit_manager; +}; + +IcuEnvironment* env = new IcuEnvironment(); + extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) { std::vector<autofill::PasswordForm> passwords; PasswordCSVReader reader;
diff --git a/components/password_manager/core/common/password_manager_features.cc b/components/password_manager/core/common/password_manager_features.cc index 8397e3d..471ea3a 100644 --- a/components/password_manager/core/common/password_manager_features.cc +++ b/components/password_manager/core/common/password_manager_features.cc
@@ -66,8 +66,13 @@ "ProtectSyncCredentialOnReauth", base::FEATURE_DISABLED_BY_DEFAULT}; // Controls the ability to export passwords from Chrome's settings page. +#if defined(OS_ANDROID) || defined(OS_IOS) const base::Feature kPasswordExport = {"PasswordExport", base::FEATURE_DISABLED_BY_DEFAULT}; +#else +const base::Feature kPasswordExport = {"PasswordExport", + base::FEATURE_ENABLED_BY_DEFAULT}; +#endif // Controls the ability to import passwords from Chrome's settings page. const base::Feature kPasswordImport = {"PasswordImport",
diff --git a/components/payments/content/manifest_verifier.cc b/components/payments/content/manifest_verifier.cc index 97485f0..80db40ac 100644 --- a/components/payments/content/manifest_verifier.cc +++ b/components/payments/content/manifest_verifier.cc
@@ -178,13 +178,29 @@ GURL method_manifest_url = it->second; cache_request_handles_.erase(it); - const std::vector<std::string>& supported_origin_strings = + const std::vector<std::string>& cached_strings = (static_cast<const WDResult<std::vector<std::string>>*>(result.get())) ->GetValue(); - bool all_origins_supported = std::find(supported_origin_strings.begin(), - supported_origin_strings.end(), - kAllOriginsSupportedIndicator) != - supported_origin_strings.end(); + + bool all_origins_supported = false; + std::vector<std::string> native_app_ids; + std::vector<std::string> supported_origin_strings; + for (const auto& origin_or_id : cached_strings) { + // The string could be "*", origin or native payment app package Id on + // Android. + if (origin_or_id == kAllOriginsSupportedIndicator) { + all_origins_supported = true; + continue; + } + + if (base::IsStringUTF8(origin_or_id) && GURL(origin_or_id).is_valid()) { + supported_origin_strings.emplace_back(origin_or_id); + } else { + native_app_ids.emplace_back(origin_or_id); + } + } + cached_supported_native_app_ids_[method_manifest_url] = native_app_ids; + EnableMethodManifestUrlForSupportedApps( method_manifest_url, supported_origin_strings, all_origins_supported, manifest_url_to_app_origins_map_[method_manifest_url], &apps_, @@ -256,6 +272,15 @@ if (all_origins_supported) supported_origin_strings.emplace_back(kAllOriginsSupportedIndicator); + + // Keep Android native payment app Ids in cache. + std::map<GURL, std::vector<std::string>>::const_iterator it = + cached_supported_native_app_ids_.find(method_manifest_url); + if (it != cached_supported_native_app_ids_.end()) { + supported_origin_strings.insert(supported_origin_strings.end(), + it->second.begin(), it->second.end()); + } + cache_->AddPaymentMethodManifest(method_manifest_url.spec(), supported_origin_strings);
diff --git a/components/payments/content/manifest_verifier.h b/components/payments/content/manifest_verifier.h index a8bdaac9..081829a7 100644 --- a/components/payments/content/manifest_verifier.h +++ b/components/payments/content/manifest_verifier.h
@@ -134,6 +134,12 @@ // used. std::set<GURL> cached_manifest_urls_; + // The mapping of payment method names to cached native payment app Ids. + // Note that the supported native payment app Ids have been cached for a + // payment method in the same cache in PaymentManifestVerifier.java. Do not + // override them since we do not refresh them in this class. + std::map<GURL, std::vector<std::string>> cached_supported_native_app_ids_; + // The number of manifests that have not been verified yet. A manifest can be // either be retrieved from cache or downloaded for verification. Once this // number reaches 0, the verification callback is invoked.
diff --git a/components/payments/content/utility/BUILD.gn b/components/payments/content/utility/BUILD.gn index 84d14aa9..81ba337 100644 --- a/components/payments/content/utility/BUILD.gn +++ b/components/payments/content/utility/BUILD.gn
@@ -42,6 +42,7 @@ deps = [ ":utility", "//base", + "//base:i18n", "//url", ] dict = "payment_manifest_json.dict"
diff --git a/components/payments/content/utility/payment_method_manifest_parser_fuzzer.cc b/components/payments/content/utility/payment_method_manifest_parser_fuzzer.cc index 12d0884..c3b6d35b 100644 --- a/components/payments/content/utility/payment_method_manifest_parser_fuzzer.cc +++ b/components/payments/content/utility/payment_method_manifest_parser_fuzzer.cc
@@ -7,17 +7,24 @@ #include <string> #include <vector> +#include "base/at_exit.h" +#include "base/i18n/icu_util.h" #include "base/json/json_reader.h" #include "base/logging.h" #include "components/payments/content/utility/payment_manifest_parser.h" #include "url/gurl.h" #include "url/origin.h" -struct Environment { - Environment() { logging::SetMinLogLevel(logging::LOG_FATAL); } +struct IcuEnvironment { + IcuEnvironment() { + logging::SetMinLogLevel(logging::LOG_FATAL); + CHECK(base::i18n::InitializeICU()); + } + // used by ICU integration. + base::AtExitManager at_exit_manager; }; -Environment* env = new Environment(); +IcuEnvironment* env = new IcuEnvironment(); extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) { std::vector<GURL> web_app_manifest_urls;
diff --git a/components/policy/core/browser/browser_policy_connector_base.cc b/components/policy/core/browser/browser_policy_connector_base.cc index 35ce760..ccac080 100644 --- a/components/policy/core/browser/browser_policy_connector_base.cc +++ b/components/policy/core/browser/browser_policy_connector_base.cc
@@ -26,8 +26,7 @@ } // namespace BrowserPolicyConnectorBase::BrowserPolicyConnectorBase( - const HandlerListFactory& handler_list_factory) - : is_initialized_(false) { + const HandlerListFactory& handler_list_factory) { // GetPolicyService() must be ready after the constructor is done. // The connector is created very early during startup, when the browser // threads aren't running yet; initialize components that need local_state, @@ -56,10 +55,11 @@ is_initialized_ = false; if (g_testing_provider) g_testing_provider->Shutdown(); - if (policy_providers_) { - for (const auto& provider : *policy_providers_) - provider->Shutdown(); - } + for (const auto& provider : policy_providers_) + provider->Shutdown(); + // Drop g_testing_provider so that tests executed with --single_process can + // call SetPolicyProviderForTesting() again. It is still owned by the test. + g_testing_provider = nullptr; g_created_policy_service = false; } @@ -72,12 +72,23 @@ } PolicyService* BrowserPolicyConnectorBase::GetPolicyService() { - if (!policy_service_) { - g_created_policy_service = true; - policy_service_ = std::make_unique<PolicyServiceImpl>(); - if (policy_providers_ || g_testing_provider) - policy_service_->SetProviders(GetProvidersForPolicyService()); - } + if (policy_service_) + return policy_service_.get(); + + DCHECK(!is_initialized_); + is_initialized_ = true; + + policy_providers_ = CreatePolicyProviders(); + + if (g_testing_provider) + g_testing_provider->Init(GetSchemaRegistry()); + + for (const auto& provider : policy_providers_) + provider->Init(GetSchemaRegistry()); + + g_created_policy_service = true; + policy_service_ = + std::make_unique<PolicyServiceImpl>(GetProvidersForPolicyService()); return policy_service_.get(); } @@ -108,32 +119,6 @@ return g_testing_provider; } -void BrowserPolicyConnectorBase::SetPolicyProviders( - std::vector<std::unique_ptr<ConfigurationPolicyProvider>> providers) { - // SetPolicyProviders() should only called once. - DCHECK(!is_initialized_); - policy_providers_ = std::move(providers); - - if (g_testing_provider) - g_testing_provider->Init(GetSchemaRegistry()); - - for (const auto& provider : *policy_providers_) - provider->Init(GetSchemaRegistry()); - - is_initialized_ = true; - - if (policy_service_) { - if (!policy_service_->has_providers()) { - policy_service_->SetProviders(GetProvidersForPolicyService()); - } else { - // GetPolicyService() triggers calling SetProviders() if - // |g_testing_provider| has been set. That's the only way that should - // result in ending up in this branch. - DCHECK(g_testing_provider); - } - } -} - std::vector<ConfigurationPolicyProvider*> BrowserPolicyConnectorBase::GetProvidersForPolicyService() { std::vector<ConfigurationPolicyProvider*> providers; @@ -141,12 +126,17 @@ providers.push_back(g_testing_provider); return providers; } - providers.reserve(policy_providers_->size()); - for (const auto& policy : *policy_providers_) + providers.reserve(policy_providers_.size()); + for (const auto& policy : policy_providers_) providers.push_back(policy.get()); return providers; } +std::vector<std::unique_ptr<ConfigurationPolicyProvider>> +BrowserPolicyConnectorBase::CreatePolicyProviders() { + return {}; +} + void BrowserPolicyConnectorBase::OnResourceBundleCreated() { std::vector<base::OnceClosure> resource_bundle_callbacks; std::swap(resource_bundle_callbacks, resource_bundle_callbacks_);
diff --git a/components/policy/core/browser/browser_policy_connector_base.h b/components/policy/core/browser/browser_policy_connector_base.h index a7674b5..d2d05f7 100644 --- a/components/policy/core/browser/browser_policy_connector_base.h +++ b/components/policy/core/browser/browser_policy_connector_base.h
@@ -10,7 +10,6 @@ #include "base/callback_forward.h" #include "base/macros.h" -#include "base/optional.h" #include "components/policy/core/browser/configuration_policy_handler_list.h" #include "components/policy/core/common/schema.h" #include "components/policy/core/common/schema_registry.h" @@ -73,10 +72,11 @@ explicit BrowserPolicyConnectorBase( const HandlerListFactory& handler_list_factory); - // Sets the set of providers, in decreasing order of priority. May only be - // called once. - void SetPolicyProviders( - std::vector<std::unique_ptr<ConfigurationPolicyProvider>> providers); + // Called from GetPolicyService() to create the set of + // ConfigurationPolicyProviders that are used, in decreasing order of + // priority. + virtual std::vector<std::unique_ptr<ConfigurationPolicyProvider>> + CreatePolicyProviders(); // Must be called when ui::ResourceBundle has been loaded, results in running // any callbacks scheduled in NotifyWhenResourceBundleReady(). @@ -88,8 +88,10 @@ // called. std::vector<ConfigurationPolicyProvider*> GetProvidersForPolicyService(); - // Whether SetPolicyProviders() but not Shutdown() has been invoked. - bool is_initialized_; + // Set to true when the PolicyService has been created, and false in + // Shutdown(). Once created the PolicyService is destroyed in the destructor, + // not Shutdown(). + bool is_initialized_ = false; // Used to convert policies to preferences. The providers declared below // may trigger policy updates during shutdown, which will result in @@ -105,8 +107,7 @@ CombinedSchemaRegistry schema_registry_; // The browser-global policy providers, in decreasing order of priority. - base::Optional<std::vector<std::unique_ptr<ConfigurationPolicyProvider>>> - policy_providers_; + std::vector<std::unique_ptr<ConfigurationPolicyProvider>> policy_providers_; // Must be deleted before all the policy providers. std::unique_ptr<PolicyServiceImpl> policy_service_;
diff --git a/components/policy/core/browser/configuration_policy_pref_store_test.cc b/components/policy/core/browser/configuration_policy_pref_store_test.cc index fbdc51e9..efd4559 100644 --- a/components/policy/core/browser/configuration_policy_pref_store_test.cc +++ b/components/policy/core/browser/configuration_policy_pref_store_test.cc
@@ -30,8 +30,7 @@ .WillRepeatedly(Return(false)); provider_.Init(); providers_.push_back(&provider_); - policy_service_ = std::make_unique<PolicyServiceImpl>(); - policy_service_->SetProviders(providers_); + policy_service_ = std::make_unique<PolicyServiceImpl>(providers_); store_ = new ConfigurationPolicyPrefStore( nullptr, policy_service_.get(), &handler_list_, POLICY_LEVEL_MANDATORY); }
diff --git a/components/policy/core/browser/proxy_policy_handler_unittest.cc b/components/policy/core/browser/proxy_policy_handler_unittest.cc index 8ee3593..6bd9bd5 100644 --- a/components/policy/core/browser/proxy_policy_handler_unittest.cc +++ b/components/policy/core/browser/proxy_policy_handler_unittest.cc
@@ -32,8 +32,7 @@ // preprocessor. The previous store must be nulled out first so that it // removes itself from the service's observer list. store_ = nullptr; - policy_service_ = std::make_unique<PolicyServiceImpl>(); - policy_service_->SetProviders(providers_); + policy_service_ = std::make_unique<PolicyServiceImpl>(providers_); store_ = new ConfigurationPolicyPrefStore( nullptr, policy_service_.get(), &handler_list_, POLICY_LEVEL_MANDATORY); }
diff --git a/components/policy/core/common/policy_service_impl.cc b/components/policy/core/common/policy_service_impl.cc index 42b6138c..dd555a14 100644 --- a/components/policy/core/common/policy_service_impl.cc +++ b/components/policy/core/common/policy_service_impl.cc
@@ -72,25 +72,12 @@ } // namespace -PolicyServiceImpl::PolicyServiceImpl() : update_task_ptr_factory_(this) { - for (int domain = 0; domain < POLICY_DOMAIN_SIZE; ++domain) - initialization_complete_[domain] = false; -} - -PolicyServiceImpl::~PolicyServiceImpl() { - DCHECK(thread_checker_.CalledOnValidThread()); - if (providers_) { - for (auto* provider : *providers_) - provider->RemoveObserver(this); - } -} - -void PolicyServiceImpl::SetProviders(Providers providers) { - DCHECK(!providers_); +PolicyServiceImpl::PolicyServiceImpl(Providers providers) + : update_task_ptr_factory_(this) { providers_ = std::move(providers); for (int domain = 0; domain < POLICY_DOMAIN_SIZE; ++domain) initialization_complete_[domain] = true; - for (auto* provider : *providers_) { + for (auto* provider : providers_) { provider->AddObserver(this); for (int domain = 0; domain < POLICY_DOMAIN_SIZE; ++domain) { initialization_complete_[domain] &= @@ -102,6 +89,12 @@ MergeAndTriggerUpdates(); } +PolicyServiceImpl::~PolicyServiceImpl() { + DCHECK(thread_checker_.CalledOnValidThread()); + for (auto* provider : providers_) + provider->RemoveObserver(this); +} + void PolicyServiceImpl::AddObserver(PolicyDomain domain, PolicyService::Observer* observer) { DCHECK(thread_checker_.CalledOnValidThread()); @@ -143,7 +136,7 @@ if (!callback.is_null()) refresh_callbacks_.push_back(callback); - if (!providers_ || providers_->empty()) { + if (providers_.empty()) { // Refresh is immediately complete if there are no providers. See the note // on OnUpdatePolicy() about why this is a posted task. update_task_ptr_factory_.InvalidateWeakPtrs(); @@ -153,15 +146,15 @@ } else { // Some providers might invoke OnUpdatePolicy synchronously while handling // RefreshPolicies. Mark all as pending before refreshing. - for (auto* provider : *providers_) + for (auto* provider : providers_) refresh_pending_.insert(provider); - for (auto* provider : *providers_) + for (auto* provider : providers_) provider->RefreshPolicies(); } } void PolicyServiceImpl::OnUpdatePolicy(ConfigurationPolicyProvider* provider) { - DCHECK_EQ(1, std::count(providers_->begin(), providers_->end(), provider)); + DCHECK_EQ(1, std::count(providers_.begin(), providers_.end(), provider)); refresh_pending_.erase(provider); // Note: a policy change may trigger further policy changes in some providers. @@ -194,13 +187,11 @@ // Merge from each provider in their order of priority. const PolicyNamespace chrome_namespace(POLICY_DOMAIN_CHROME, std::string()); PolicyBundle bundle; - if (providers_) { - for (auto* provider : *providers_) { - PolicyBundle provided_bundle; - provided_bundle.CopyFrom(provider->policies()); - RemapProxyPolicies(&provided_bundle.Get(chrome_namespace)); - bundle.MergeFrom(provided_bundle); - } + for (auto* provider : providers_) { + PolicyBundle provided_bundle; + provided_bundle.CopyFrom(provider->policies()); + RemapProxyPolicies(&provided_bundle.Get(chrome_namespace)); + bundle.MergeFrom(provided_bundle); } // Swap first, so that observers that call GetPolicies() see the current @@ -247,9 +238,6 @@ void PolicyServiceImpl::CheckInitializationComplete() { DCHECK(thread_checker_.CalledOnValidThread()); - if (!providers_) - return; - // Check if all the providers just became initialized for each domain; if so, // notify that domain's observers. for (int domain = 0; domain < POLICY_DOMAIN_SIZE; ++domain) { @@ -259,7 +247,7 @@ PolicyDomain policy_domain = static_cast<PolicyDomain>(domain); bool all_complete = true; - for (auto* provider : *providers_) { + for (auto* provider : providers_) { if (!provider->IsInitializationComplete(policy_domain)) { all_complete = false; break;
diff --git a/components/policy/core/common/policy_service_impl.h b/components/policy/core/common/policy_service_impl.h index 0e6003e..985b27e 100644 --- a/components/policy/core/common/policy_service_impl.h +++ b/components/policy/core/common/policy_service_impl.h
@@ -15,7 +15,6 @@ #include "base/macros.h" #include "base/memory/weak_ptr.h" #include "base/observer_list.h" -#include "base/optional.h" #include "base/threading/thread_checker.h" #include "components/policy/core/common/configuration_policy_provider.h" #include "components/policy/core/common/policy_bundle.h" @@ -32,18 +31,11 @@ public: using Providers = std::vector<ConfigurationPolicyProvider*>; - // Creates a new PolicyServiceImpl, it is expected SetProviders() is called - // once to complete initialization. - PolicyServiceImpl(); - + // Creates a new PolicyServiceImpl with the list of + // ConfigurationPolicyProviders, in order of decreasing priority. + explicit PolicyServiceImpl(Providers providers); ~PolicyServiceImpl() override; - // Sets the providers; see description of constructor for details. - void SetProviders(Providers providers); - - // Returns true if SetProviders() was called. - bool has_providers() const { return providers_.has_value(); } - // PolicyService overrides: void AddObserver(PolicyDomain domain, PolicyService::Observer* observer) override; @@ -76,8 +68,8 @@ // Invokes all the refresh callbacks if there are no more refreshes pending. void CheckRefreshComplete(); - // The providers set via SetProviders(), in order of decreasing priority. - base::Optional<Providers> providers_; + // The providers, in order of decreasing priority. + Providers providers_; // Maps each policy namespace to its current policies. PolicyBundle policy_bundle_;
diff --git a/components/policy/core/common/policy_service_impl_unittest.cc b/components/policy/core/common/policy_service_impl_unittest.cc index 857e382..bc84baa9 100644 --- a/components/policy/core/common/policy_service_impl_unittest.cc +++ b/components/policy/core/common/policy_service_impl_unittest.cc
@@ -120,8 +120,7 @@ providers.push_back(&provider0_); providers.push_back(&provider1_); providers.push_back(&provider2_); - policy_service_ = std::make_unique<PolicyServiceImpl>(); - policy_service_->SetProviders(providers); + policy_service_ = std::make_unique<PolicyServiceImpl>(std::move(providers)); } void TearDown() override { @@ -561,8 +560,7 @@ providers.push_back(&provider0_); providers.push_back(&provider1_); providers.push_back(&provider2_); - policy_service_ = std::make_unique<PolicyServiceImpl>(); - policy_service_->SetProviders(providers); + policy_service_ = std::make_unique<PolicyServiceImpl>(std::move(providers)); EXPECT_FALSE(policy_service_->IsInitializationComplete(POLICY_DOMAIN_CHROME)); EXPECT_FALSE( policy_service_->IsInitializationComplete(POLICY_DOMAIN_EXTENSIONS));
diff --git a/components/policy/resources/policy_templates.gni b/components/policy/resources/policy_templates.gni index 7159dfc6..37b97378 100644 --- a/components/policy/resources/policy_templates.gni +++ b/components/policy/resources/policy_templates.gni
@@ -11,62 +11,123 @@ policy_templates_base_dir = "$root_gen_dir/chrome/app/policy" -# Languages we're going to process. +# Languages we're going to process. Should match the XX-YY of the translated +# policy_templates_XX-YY.json files, see policy_templates.grd. policy_templates_languages = [ "am", - "ar", - "bg", - "bn", - "ca", - "cs", - "da", - "de", - "el", + "ar-EG", + "bg-BG", + "ms-BN", + "ca-ES", + "cs-CZ", + "da-DK", + "de-DE", + "el-GR", "en-GB", "en-US", - "es", + "es-ES", "es-419", - "et", - "fa", - "fi", + "et-EE", + "fa-IR", + "fi-FI", "fil", - "fr", - "gu", - "he", - "hi", - "hr", - "hu", - "id", - "it", - "ja", - "kn", - "ko", - "lt", - "lv", + "fr-FR", + "gu-IN", + "he-IL", + "hi-IN", + "hr-HR", + "hu-HU", + "id-ID", + "it-IT", + "ja-JP", + "kn-IN", + "ko-KR", + "lt-LT", + "lv-LV", "ml", - "mr", - "ms", - "nl", - "nb", - "pl", + "mr-IN", + "ms-MY", + "nl-NL", + "nb-NO", + "pl-PL", "pt-BR", "pt-PT", - "ro", - "ru", - "sk", - "sl", - "sr", - "sv", - "sw", - "ta", - "te", - "th", - "tr", - "uk", - "vi", + "ro-RO", + "ru-RU", + "sk-SK", + "sl-SI", + "Cy-sr-SP", + "sv-SE", + "sw-KE", + "ta-IN", + "te-IN", + "th-TH", + "tr-TR", + "uk-UA", + "vi-VN", "zh-CN", "zh-TW", ] + +# Macs use a slightly different naming convention: +# - '_' instead of '-' +# - 'en' instead of 'en-US' +mac_policy_templates_languages = [ + "am", + "ar_EG", + "bg_BG", + "ms_BN", + "ca_ES", + "cs_CZ", + "da_DK", + "de_DE", + "el_GR", + "en_GB", + "en", + "es_ES", + "es_419", + "et_EE", + "fa_IR", + "fi_FI", + "fil", + "fr_FR", + "gu_IN", + "he_IL", + "hi_IN", + "hr_HR", + "hu_HU", + "id_ID", + "it_IT", + "ja_JP", + "kn_IN", + "ko_KR", + "lt_LT", + "lv_LV", + "ml", + "mr_IN", + "ms_MY", + "nl_NL", + "nb_NO", + "pl_PL", + "pt_BR", + "pt_PT", + "ro_RO", + "ru_RU", + "sk_SK", + "sl_SI", + "Cy_sr_SP", + "sv_SE", + "sw_KE", + "ta_IN", + "te_IN", + "th_TH", + "tr_TR", + "uk_UA", + "vi_VN", + "zh_CN", + "zh_TW", +] + policy_templates_languages_str = "" foreach(lang, policy_templates_languages) { # Note: The final , is filtered out by scripts. There's no string.join here... @@ -78,7 +139,9 @@ "$policy_templates_base_dir/translations/policy_templates_\${lang}.json" policy_templates_translation_outputs = [] foreach(lang, policy_templates_languages) { - policy_templates_translation_outputs += [ "$policy_templates_base_dir/translations/policy_templates_${lang}.json" ] + policy_templates_translation_outputs += [ + "$policy_templates_base_dir/translations/policy_templates_${lang}.json", + ] } # Android outputs. @@ -91,7 +154,9 @@ "$policy_templates_base_dir/common/html/\${lang}/chrome_policy_list.html" policy_templates_common_outputs = [] foreach(lang, policy_templates_languages) { - policy_templates_common_outputs += [ "$policy_templates_base_dir/common/html/${lang}/chrome_policy_list.html" ] + policy_templates_common_outputs += [ + "$policy_templates_base_dir/common/html/${lang}/chrome_policy_list.html", + ] } # Linux outputs. @@ -105,24 +170,10 @@ policy_templates_plist_strings_path = "$policy_templates_base_dir/mac/strings/\${lang}.lproj/Localizable.strings" policy_templates_mac_outputs = [ policy_templates_plist_path ] -foreach(lang, policy_templates_languages) { - # Mac uses a slightly different naming convention for languages. - if (lang == "en-US") { - lang = "en" - } else if (lang == "en-GB") { - lang = "en_GB" - } else if (lang == "es-419") { - lang = "es_419" - } else if (lang == "pt-BR") { - lang = "pt_BR" - } else if (lang == "pt-PT") { - lang = "pt_PT" - } else if (lang == "zh-CN") { - lang = "zh_CN" - } else if (lang == "zh-TW") { - lang = "zh_TW" - } - policy_templates_mac_outputs += [ "$policy_templates_base_dir/mac/strings/${lang}.lproj/Localizable.strings" ] +foreach(lang, mac_policy_templates_languages) { + policy_templates_mac_outputs += [ + "$policy_templates_base_dir/mac/strings/${lang}.lproj/Localizable.strings", + ] } # Windows outputs.
diff --git a/components/policy/resources/policy_templates.grd b/components/policy/resources/policy_templates.grd index 73b69f5cb..f934523 100644 --- a/components/policy/resources/policy_templates.grd +++ b/components/policy/resources/policy_templates.grd
@@ -1,63 +1,64 @@ <?xml version="1.0" encoding="UTF-8"?> <!-- This file contains definitions of resources that are used in policy -templates and will be translated for each locale. --> +templates and will be translated for each locale. +For the mapping 'lang' to policy_templates filename see crbug.com/806577. +--> <grit base_dir="." latest_public_release="0" current_release="1" output_all_resource_defines="false" source_lang_id="en" enc_check="möl"> <outputs> <output filename="app/policy/translations/policy_templates_am.json" type="policy_templates" lang="am" /> - <output filename="app/policy/translations/policy_templates_ar.json" type="policy_templates" lang="ar" /> - <output filename="app/policy/translations/policy_templates_bg.json" type="policy_templates" lang="bg" /> - <output filename="app/policy/translations/policy_templates_bn.json" type="policy_templates" lang="bn" /> - <output filename="app/policy/translations/policy_templates_ca.json" type="policy_templates" lang="ca" /> - <output filename="app/policy/translations/policy_templates_cs.json" type="policy_templates" lang="cs" /> - <output filename="app/policy/translations/policy_templates_da.json" type="policy_templates" lang="da" /> - <output filename="app/policy/translations/policy_templates_de.json" type="policy_templates" lang="de" /> - <output filename="app/policy/translations/policy_templates_el.json" type="policy_templates" lang="el" /> + <output filename="app/policy/translations/policy_templates_ar-EG.json" type="policy_templates" lang="ar" /> + <output filename="app/policy/translations/policy_templates_bg-BG.json" type="policy_templates" lang="bg" /> + <output filename="app/policy/translations/policy_templates_ms-BN.json" type="policy_templates" lang="bn" /> + <output filename="app/policy/translations/policy_templates_ca-ES.json" type="policy_templates" lang="ca" /> + <output filename="app/policy/translations/policy_templates_cs-CZ.json" type="policy_templates" lang="cs" /> + <output filename="app/policy/translations/policy_templates_da-DK.json" type="policy_templates" lang="da" /> + <output filename="app/policy/translations/policy_templates_de-DE.json" type="policy_templates" lang="de" /> + <output filename="app/policy/translations/policy_templates_el-GR.json" type="policy_templates" lang="el" /> <output filename="app/policy/translations/policy_templates_en-GB.json" type="policy_templates" lang="en-GB" /> <output filename="app/policy/translations/policy_templates_en-US.json" type="policy_templates" lang="en" /> - <output filename="app/policy/translations/policy_templates_es.json" type="policy_templates" lang="es" /> + <output filename="app/policy/translations/policy_templates_es-ES.json" type="policy_templates" lang="es" /> <output filename="app/policy/translations/policy_templates_es-419.json" type="policy_templates" lang="es-419" /> - <output filename="app/policy/translations/policy_templates_et.json" type="policy_templates" lang="et" /> - <output filename="app/policy/translations/policy_templates_fa.json" type="policy_templates" lang="fa" /> - <output filename="app/policy/translations/policy_templates_fi.json" type="policy_templates" lang="fi" /> + <output filename="app/policy/translations/policy_templates_et-EE.json" type="policy_templates" lang="et" /> + <output filename="app/policy/translations/policy_templates_fa-IR.json" type="policy_templates" lang="fa" /> + <output filename="app/policy/translations/policy_templates_fi-FI.json" type="policy_templates" lang="fi" /> <output filename="app/policy/translations/policy_templates_fil.json" type="policy_templates" lang="fil" /> - <output filename="app/policy/translations/policy_templates_fr.json" type="policy_templates" lang="fr" /> - <output filename="app/policy/translations/policy_templates_gu.json" type="policy_templates" lang="gu" /> - <output filename="app/policy/translations/policy_templates_he.json" type="policy_templates" lang="he" /> - <output filename="app/policy/translations/policy_templates_hi.json" type="policy_templates" lang="hi" /> - <output filename="app/policy/translations/policy_templates_hr.json" type="policy_templates" lang="hr" /> - <output filename="app/policy/translations/policy_templates_hu.json" type="policy_templates" lang="hu" /> - <output filename="app/policy/translations/policy_templates_id.json" type="policy_templates" lang="id" /> - <output filename="app/policy/translations/policy_templates_it.json" type="policy_templates" lang="it" /> - <output filename="app/policy/translations/policy_templates_ja.json" type="policy_templates" lang="ja" /> - <output filename="app/policy/translations/policy_templates_kn.json" type="policy_templates" lang="kn" /> - <output filename="app/policy/translations/policy_templates_ko.json" type="policy_templates" lang="ko" /> - <output filename="app/policy/translations/policy_templates_lt.json" type="policy_templates" lang="lt" /> - <output filename="app/policy/translations/policy_templates_lv.json" type="policy_templates" lang="lv" /> + <output filename="app/policy/translations/policy_templates_fr-FR.json" type="policy_templates" lang="fr" /> + <output filename="app/policy/translations/policy_templates_gu-IN.json" type="policy_templates" lang="gu" /> + <output filename="app/policy/translations/policy_templates_he-IL.json" type="policy_templates" lang="he" /> + <output filename="app/policy/translations/policy_templates_hi-IN.json" type="policy_templates" lang="hi" /> + <output filename="app/policy/translations/policy_templates_hr-HR.json" type="policy_templates" lang="hr" /> + <output filename="app/policy/translations/policy_templates_hu-HU.json" type="policy_templates" lang="hu" /> + <output filename="app/policy/translations/policy_templates_id-ID.json" type="policy_templates" lang="id" /> + <output filename="app/policy/translations/policy_templates_it-IT.json" type="policy_templates" lang="it" /> + <output filename="app/policy/translations/policy_templates_ja-JP.json" type="policy_templates" lang="ja" /> + <output filename="app/policy/translations/policy_templates_kn-IN.json" type="policy_templates" lang="kn" /> + <output filename="app/policy/translations/policy_templates_ko-KR.json" type="policy_templates" lang="ko" /> + <output filename="app/policy/translations/policy_templates_lt-LT.json" type="policy_templates" lang="lt" /> + <output filename="app/policy/translations/policy_templates_lv-LV.json" type="policy_templates" lang="lv" /> <output filename="app/policy/translations/policy_templates_ml.json" type="policy_templates" lang="ml" /> - <output filename="app/policy/translations/policy_templates_mr.json" type="policy_templates" lang="mr" /> - <output filename="app/policy/translations/policy_templates_ms.json" type="policy_templates" lang="ms" /> - <output filename="app/policy/translations/policy_templates_nl.json" type="policy_templates" lang="nl" /> - <output filename="app/policy/translations/policy_templates_nb.json" type="policy_templates" lang="no" /> - <!-- 'no' for Norwegian Bokmål. It should be 'nb'. --> - <output filename="app/policy/translations/policy_templates_pl.json" type="policy_templates" lang="pl" /> + <output filename="app/policy/translations/policy_templates_mr-IN.json" type="policy_templates" lang="mr" /> + <output filename="app/policy/translations/policy_templates_ms-MY.json" type="policy_templates" lang="ms" /> + <output filename="app/policy/translations/policy_templates_nl-NL.json" type="policy_templates" lang="nl" /> + <output filename="app/policy/translations/policy_templates_nb-NO.json" type="policy_templates" lang="no" /> + <output filename="app/policy/translations/policy_templates_pl-PL.json" type="policy_templates" lang="pl" /> <output filename="app/policy/translations/policy_templates_pt-BR.json" type="policy_templates" lang="pt-BR" /> <output filename="app/policy/translations/policy_templates_pt-PT.json" type="policy_templates" lang="pt-PT" /> - <output filename="app/policy/translations/policy_templates_ro.json" type="policy_templates" lang="ro" /> - <output filename="app/policy/translations/policy_templates_ru.json" type="policy_templates" lang="ru" /> - <output filename="app/policy/translations/policy_templates_sk.json" type="policy_templates" lang="sk" /> - <output filename="app/policy/translations/policy_templates_sl.json" type="policy_templates" lang="sl" /> - <output filename="app/policy/translations/policy_templates_sr.json" type="policy_templates" lang="sr" /> - <output filename="app/policy/translations/policy_templates_sv.json" type="policy_templates" lang="sv" /> - <output filename="app/policy/translations/policy_templates_sw.json" type="policy_templates" lang="sw" /> - <output filename="app/policy/translations/policy_templates_ta.json" type="policy_templates" lang="ta" /> - <output filename="app/policy/translations/policy_templates_te.json" type="policy_templates" lang="te" /> - <output filename="app/policy/translations/policy_templates_th.json" type="policy_templates" lang="th" /> - <output filename="app/policy/translations/policy_templates_tr.json" type="policy_templates" lang="tr" /> - <output filename="app/policy/translations/policy_templates_uk.json" type="policy_templates" lang="uk" /> - <output filename="app/policy/translations/policy_templates_vi.json" type="policy_templates" lang="vi" /> + <output filename="app/policy/translations/policy_templates_ro-RO.json" type="policy_templates" lang="ro" /> + <output filename="app/policy/translations/policy_templates_ru-RU.json" type="policy_templates" lang="ru" /> + <output filename="app/policy/translations/policy_templates_sk-SK.json" type="policy_templates" lang="sk" /> + <output filename="app/policy/translations/policy_templates_sl-SI.json" type="policy_templates" lang="sl" /> + <output filename="app/policy/translations/policy_templates_Cy-sr-SP.json" type="policy_templates" lang="sr" /> + <output filename="app/policy/translations/policy_templates_sv-SE.json" type="policy_templates" lang="sv" /> + <output filename="app/policy/translations/policy_templates_sw-KE.json" type="policy_templates" lang="sw" /> + <output filename="app/policy/translations/policy_templates_ta-IN.json" type="policy_templates" lang="ta" /> + <output filename="app/policy/translations/policy_templates_te-IN.json" type="policy_templates" lang="te" /> + <output filename="app/policy/translations/policy_templates_th-TH.json" type="policy_templates" lang="th" /> + <output filename="app/policy/translations/policy_templates_tr-TR.json" type="policy_templates" lang="tr" /> + <output filename="app/policy/translations/policy_templates_uk-UA.json" type="policy_templates" lang="uk" /> + <output filename="app/policy/translations/policy_templates_vi-VN.json" type="policy_templates" lang="vi" /> <output filename="app/policy/translations/policy_templates_zh-CN.json" type="policy_templates" lang="zh-CN" /> <output filename="app/policy/translations/policy_templates_zh-TW.json" type="policy_templates" lang="zh-TW" /> </outputs>
diff --git a/components/printing/common/print_messages.cc b/components/printing/common/print_messages.cc index 42e23b1..6df9855 100644 --- a/components/printing/common/print_messages.cc +++ b/components/printing/common/print_messages.cc
@@ -95,7 +95,8 @@ header_template(), footer_template(), should_print_backgrounds(false), - printed_doc_type(printing::SkiaDocumentType::PDF) {} + printed_doc_type(printing::SkiaDocumentType::PDF), + prefer_css_page_size(false) {} PrintMsg_Print_Params::PrintMsg_Print_Params( const PrintMsg_Print_Params& other) = default; @@ -126,6 +127,7 @@ footer_template = base::string16(); should_print_backgrounds = false; printed_doc_type = printing::SkiaDocumentType::PDF; + prefer_css_page_size = false; } PrintMsg_PrintPages_Params::PrintMsg_PrintPages_Params()
diff --git a/components/printing/common/print_messages.h b/components/printing/common/print_messages.h index 8a4033b..64317d4 100644 --- a/components/printing/common/print_messages.h +++ b/components/printing/common/print_messages.h
@@ -64,6 +64,7 @@ base::string16 footer_template; bool should_print_backgrounds; printing::SkiaDocumentType printed_doc_type; + bool prefer_css_page_size; }; struct PrintMsg_PrintPages_Params { @@ -190,6 +191,9 @@ // The document type of printed page(s) from render. IPC_STRUCT_TRAITS_MEMBER(printed_doc_type) + + // True if page size defined by css should be preferred. + IPC_STRUCT_TRAITS_MEMBER(prefer_css_page_size) IPC_STRUCT_TRAITS_END() IPC_STRUCT_TRAITS_BEGIN(printing::PageRange)
diff --git a/components/printing/renderer/print_render_frame_helper.cc b/components/printing/renderer/print_render_frame_helper.cc index 64a158e1..1f85f2e 100644 --- a/components/printing/renderer/print_render_frame_helper.cc +++ b/components/printing/renderer/print_render_frame_helper.cc
@@ -1503,7 +1503,10 @@ if (!self) return; - print_settings.params.print_scaling_option = scaling_option; + print_settings.params.print_scaling_option = + print_settings.params.prefer_css_page_size + ? blink::kWebPrintScalingOptionSourceSize + : scaling_option; SetPrintPagesParams(print_settings); if (print_settings.params.dpi.IsEmpty() || !print_settings.params.document_cookie) {
diff --git a/components/safe_browsing/proto/csd.proto b/components/safe_browsing/proto/csd.proto index 84263717..f844538 100644 --- a/components/safe_browsing/proto/csd.proto +++ b/components/safe_browsing/proto/csd.proto
@@ -1146,3 +1146,18 @@ // (even if the image URL is cross-origin). Otherwise a website could mislead // Safe Browsing into associating phishing image bitmaps with safe image URLs. } + +// Protobuf for Chrome extension webstore install request. +message ExtensionWebStoreInstallRequest { + // If we can find the complete referrer chain, this field will contain URL + // transitions from landing referrer to event in reverse chronological + // order, i.e. event url comes first in this list, and landing referrer + // comes last. + // For Safe Browsing Extended Reporting or Scout users, if the referrer + // chain is empty or partially missing, we will add/append recent navigation + // events to this list. The type of these entries will be RECENT_NAVIGATION. + repeated ReferrerChainEntry referrer_chain = 1; + + // Options and metadata about the above referrer chain. + optional ReferrerChainOptions referrer_chain_options = 2; +}
diff --git a/components/signin/core/browser/about_signin_internals.cc b/components/signin/core/browser/about_signin_internals.cc index 10f9e14..1abf3ed 100644 --- a/components/signin/core/browser/about_signin_internals.cc +++ b/components/signin/core/browser/about_signin_internals.cc
@@ -22,7 +22,6 @@ #include "components/pref_registry/pref_registry_syncable.h" #include "components/prefs/pref_service.h" #include "components/signin/core/browser/account_tracker_service.h" -#include "components/signin/core/browser/profile_management_switches.h" #include "components/signin/core/browser/profile_oauth2_token_service.h" #include "components/signin/core/browser/signin_client.h" #include "components/signin/core/browser/signin_internals_util.h" @@ -164,8 +163,9 @@ prefs->ClearPref(time_pref); } -std::string GetAccountConsistencyDescription() { - switch (signin::GetAccountConsistencyMethod()) { +std::string GetAccountConsistencyDescription( + signin::AccountConsistencyMethod method) { + switch (method) { case signin::AccountConsistencyMethod::kDisabled: return "None"; case signin::AccountConsistencyMethod::kMirror: @@ -190,13 +190,15 @@ AccountTrackerService* account_tracker, SigninManagerBase* signin_manager, SigninErrorController* signin_error_controller, - GaiaCookieManagerService* cookie_manager_service) + GaiaCookieManagerService* cookie_manager_service, + signin::AccountConsistencyMethod account_consistency) : token_service_(token_service), account_tracker_(account_tracker), signin_manager_(signin_manager), client_(nullptr), signin_error_controller_(signin_error_controller), - cookie_manager_service_(cookie_manager_service) {} + cookie_manager_service_(cookie_manager_service), + account_consistency_(account_consistency) {} AboutSigninInternals::~AboutSigninInternals() {} @@ -312,16 +314,17 @@ std::unique_ptr<base::DictionaryValue> signin_status_value = signin_status_.ToValue(account_tracker_, signin_manager_, signin_error_controller_, token_service_, - cookie_manager_service_, client_); + cookie_manager_service_, client_, + account_consistency_); for (auto& observer : signin_observers_) observer.OnSigninStateChanged(signin_status_value.get()); } std::unique_ptr<base::DictionaryValue> AboutSigninInternals::GetSigninStatus() { - return signin_status_.ToValue(account_tracker_, signin_manager_, - signin_error_controller_, token_service_, - cookie_manager_service_, client_); + return signin_status_.ToValue( + account_tracker_, signin_manager_, signin_error_controller_, + token_service_, cookie_manager_service_, client_, account_consistency_); } void AboutSigninInternals::OnAccessTokenRequested( @@ -521,7 +524,8 @@ SigninErrorController* signin_error_controller, ProfileOAuth2TokenService* token_service, GaiaCookieManagerService* cookie_manager_service, - SigninClient* signin_client) { + SigninClient* signin_client, + signin::AccountConsistencyMethod account_consistency) { auto signin_status = std::make_unique<base::DictionaryValue>(); auto signin_info = std::make_unique<base::ListValue>(); @@ -531,7 +535,7 @@ AddSectionEntry(basic_info, "Chrome Version", signin_client->GetProductVersion()); AddSectionEntry(basic_info, "Account Consistency", - GetAccountConsistencyDescription()); + GetAccountConsistencyDescription(account_consistency)); AddSectionEntry(basic_info, "Signin Status", signin_manager->IsAuthenticated() ? "Signed In" : "Not Signed In"); OAuth2TokenServiceDelegate::LoadCredentialsState load_tokens_state = @@ -652,7 +656,7 @@ signin_status->Set("accountInfo", std::move(account_info)); #if BUILDFLAG(ENABLE_DICE_SUPPORT) - if (signin::IsDiceEnabledForProfile(signin_client->GetPrefs())) { + if (account_consistency == signin::AccountConsistencyMethod::kDice) { auto dice_info = std::make_unique<base::DictionaryValue>(); dice_info->SetBoolean("isSignedIn", signin_manager->IsAuthenticated()); signin_status->Set("dice", std::move(dice_info));
diff --git a/components/signin/core/browser/about_signin_internals.h b/components/signin/core/browser/about_signin_internals.h index 8e530ab5..5ae815e9 100644 --- a/components/signin/core/browser/about_signin_internals.h +++ b/components/signin/core/browser/about_signin_internals.h
@@ -57,7 +57,8 @@ AccountTrackerService* account_tracker, SigninManagerBase* signin_manager, SigninErrorController* signin_error_controller, - GaiaCookieManagerService* cookie_manager_service); + GaiaCookieManagerService* cookie_manager_service, + signin::AccountConsistencyMethod account_consistency); ~AboutSigninInternals() override; // Registers the preferences used by AboutSigninInternals. @@ -164,7 +165,8 @@ SigninErrorController* signin_error_controller, ProfileOAuth2TokenService* token_service, GaiaCookieManagerService* cookie_manager_service_, - SigninClient* signin_client); + SigninClient* signin_client, + signin::AccountConsistencyMethod account_consistency); }; // SigninManager::SigninDiagnosticsObserver implementation. @@ -223,6 +225,8 @@ // Most of the values are mirrored in the prefs for persistence. SigninStatus signin_status_; + signin::AccountConsistencyMethod account_consistency_; + base::ObserverList<Observer> signin_observers_; DISALLOW_COPY_AND_ASSIGN(AboutSigninInternals);
diff --git a/components/signin/core/browser/account_reconcilor_unittest.cc b/components/signin/core/browser/account_reconcilor_unittest.cc index 9612e76..0fbc532 100644 --- a/components/signin/core/browser/account_reconcilor_unittest.cc +++ b/components/signin/core/browser/account_reconcilor_unittest.cc
@@ -25,7 +25,6 @@ #include "components/signin/core/browser/mirror_account_reconcilor_delegate.h" #include "components/signin/core/browser/profile_management_switches.h" #include "components/signin/core/browser/profile_oauth2_token_service.h" -#include "components/signin/core/browser/scoped_account_consistency.h" #include "components/signin/core/browser/signin_features.h" #include "components/signin/core/browser/signin_manager.h" #include "components/signin/core/browser/signin_metrics.h" @@ -160,7 +159,7 @@ case signin::AccountConsistencyMethod::kDice: #if BUILDFLAG(ENABLE_DICE_SUPPORT) return std::make_unique<signin::DiceAccountReconcilorDelegate>( - signin_client); + signin_client, account_consistency); #else NOTREACHED(); return nullptr; @@ -275,7 +274,6 @@ private: base::MessageLoop loop; signin::AccountConsistencyMethod account_consistency_; - std::unique_ptr<signin::ScopedAccountConsistency> scoped_account_consistency_; sync_preferences::TestingPrefServiceSyncable pref_service_; FakeProfileOAuth2TokenService token_service_; DiceTestSigninClient test_signin_client_; @@ -388,8 +386,6 @@ void AccountReconcilorTest::SetAccountConsistency( signin::AccountConsistencyMethod method) { account_consistency_ = method; - scoped_account_consistency_ = - std::make_unique<signin::ScopedAccountConsistency>(method); } TEST_F(AccountReconcilorTest, Basic) { @@ -1027,7 +1023,6 @@ "12345"); AccountReconcilor* reconcilor = GetMockReconcilor(); // Dice is not enabled by default. - ASSERT_FALSE(signin::IsDiceEnabledForProfile(pref_service())); EXPECT_FALSE(reconcilor->delegate_->IsAccountConsistencyEnforced()); // No-op reconcile. @@ -1055,7 +1050,6 @@ AccountReconcilor* reconcilor = GetMockReconcilor(); // Dice is not enabled by default. - ASSERT_FALSE(signin::IsDiceEnabledForProfile(pref_service())); EXPECT_FALSE(reconcilor->delegate_->IsAccountConsistencyEnforced()); // Busy reconcile.
diff --git a/components/signin/core/browser/chrome_connected_header_helper.cc b/components/signin/core/browser/chrome_connected_header_helper.cc index 2c050d11..58c60a4 100644 --- a/components/signin/core/browser/chrome_connected_header_helper.cc +++ b/components/signin/core/browser/chrome_connected_header_helper.cc
@@ -11,7 +11,6 @@ #include "base/strings/string_util.h" #include "base/strings/stringprintf.h" #include "components/google/core/browser/google_util.h" -#include "components/signin/core/browser/profile_management_switches.h" #include "google_apis/gaia/gaia_auth_util.h" #include "net/base/registry_controlled_domains/registry_controlled_domain.h" #include "url/gurl.h" @@ -49,17 +48,18 @@ } // namespace -ChromeConnectedHeaderHelper::ChromeConnectedHeaderHelper(bool is_mirror_enabled) - : is_mirror_enabled_(is_mirror_enabled) {} +ChromeConnectedHeaderHelper::ChromeConnectedHeaderHelper( + AccountConsistencyMethod account_consistency) + : account_consistency_(account_consistency) {} // static std::string ChromeConnectedHeaderHelper::BuildRequestCookieIfPossible( const GURL& url, const std::string& account_id, + AccountConsistencyMethod account_consistency, const content_settings::CookieSettings* cookie_settings, int profile_mode_mask) { - ChromeConnectedHeaderHelper chrome_connected_helper( - IsAccountConsistencyMirrorEnabled()); + ChromeConnectedHeaderHelper chrome_connected_helper(account_consistency); if (!chrome_connected_helper.ShouldBuildRequestHeader(url, cookie_settings)) return ""; return chrome_connected_helper.BuildRequestHeader( @@ -141,7 +141,9 @@ google_util::DISALLOW_NON_STANDARD_PORTS) || google_util::IsYoutubeDomainUrl(url, google_util::ALLOW_SUBDOMAIN, google_util::DISALLOW_NON_STANDARD_PORTS); - return (is_mirror_enabled_ && is_google_url) || IsDriveOrigin(origin) || + bool is_mirror_enabled = + account_consistency_ == AccountConsistencyMethod::kMirror; + return (is_mirror_enabled && is_google_url) || IsDriveOrigin(origin) || gaia::IsGaiaSignonRealm(origin); } @@ -172,8 +174,10 @@ parts.push_back( base::StringPrintf("%s=%s", kProfileModeAttrName, base::IntToString(profile_mode_mask).c_str())); + bool is_mirror_enabled = + account_consistency_ == AccountConsistencyMethod::kMirror; parts.push_back(base::StringPrintf("%s=%s", kEnableAccountConsistencyAttrName, - is_mirror_enabled_ ? "true" : "false")); + is_mirror_enabled ? "true" : "false")); return base::JoinString(parts, is_header_request ? "," : ":"); }
diff --git a/components/signin/core/browser/chrome_connected_header_helper.h b/components/signin/core/browser/chrome_connected_header_helper.h index fab3eed..034de4fb 100644 --- a/components/signin/core/browser/chrome_connected_header_helper.h +++ b/components/signin/core/browser/chrome_connected_header_helper.h
@@ -7,6 +7,7 @@ #include <string> +#include "components/signin/core/browser/profile_management_switches.h" #include "components/signin/core/browser/signin_header_helper.h" class GURL; @@ -16,7 +17,8 @@ // SigninHeaderHelper implementation managing the "X-Chrome-Connected" header. class ChromeConnectedHeaderHelper : public SigninHeaderHelper { public: - ChromeConnectedHeaderHelper(bool is_mirror_enabled); + explicit ChromeConnectedHeaderHelper( + AccountConsistencyMethod account_consistency); ~ChromeConnectedHeaderHelper() override {} // Returns the Chrome-Connected cookie, or an empty string if it should not be @@ -24,6 +26,7 @@ static std::string BuildRequestCookieIfPossible( const GURL& url, const std::string& account_id, + AccountConsistencyMethod account_consistency, const content_settings::CookieSettings* cookie_settings, int profile_mode_mask); @@ -41,7 +44,7 @@ private: // Whether mirror account consistency should be used. - bool is_mirror_enabled_ = false; + AccountConsistencyMethod account_consistency_; // Returns whether the URL is eligible for the Gaia ID parameter. bool IsUrlEligibleToIncludeGaiaId(const GURL& url, bool is_header_request);
diff --git a/components/signin/core/browser/dice_account_reconcilor_delegate.cc b/components/signin/core/browser/dice_account_reconcilor_delegate.cc index dd10ef5..764ea333 100644 --- a/components/signin/core/browser/dice_account_reconcilor_delegate.cc +++ b/components/signin/core/browser/dice_account_reconcilor_delegate.cc
@@ -9,23 +9,24 @@ #include "base/logging.h" #include "base/metrics/histogram_macros.h" #include "base/stl_util.h" -#include "components/signin/core/browser/profile_management_switches.h" #include "components/signin/core/browser/signin_client.h" namespace signin { DiceAccountReconcilorDelegate::DiceAccountReconcilorDelegate( - SigninClient* signin_client) - : signin_client_(signin_client) { + SigninClient* signin_client, + AccountConsistencyMethod account_consistency) + : signin_client_(signin_client), account_consistency_(account_consistency) { DCHECK(signin_client_); } bool DiceAccountReconcilorDelegate::IsReconcileEnabled() const { - return IsDicePrepareMigrationEnabled(); + return DiceMethodGreaterOrEqual( + account_consistency_, AccountConsistencyMethod::kDicePrepareMigration); } bool DiceAccountReconcilorDelegate::IsAccountConsistencyEnforced() const { - return IsDiceEnabledForProfile(signin_client_->GetPrefs()); + return account_consistency_ == AccountConsistencyMethod::kDice; } // - On first execution, the candidates are examined in this order: @@ -102,8 +103,10 @@ const std::vector<gaia::ListedAccount>& gaia_accounts) { // During the Dice migration step, before Dice is actually enabled, chrome // tokens must be cleared when the cookies are cleared. - return signin::IsDicePrepareMigrationEnabled() && - !signin::IsDiceEnabledForProfile(signin_client_->GetPrefs()) && + return DiceMethodGreaterOrEqual( + account_consistency_, + AccountConsistencyMethod::kDicePrepareMigration) && + (account_consistency_ != AccountConsistencyMethod::kDice) && gaia_accounts.empty(); } @@ -113,8 +116,11 @@ last_known_first_account_ = first_account; // Migration happens on startup if the last reconcile was a no-op. - if (IsDicePrepareMigrationEnabled()) + if (DiceMethodGreaterOrEqual( + account_consistency_, + AccountConsistencyMethod::kDicePrepareMigration)) { signin_client_->SetReadyForDiceMigration(reconcile_is_noop); + } } } // namespace signin
diff --git a/components/signin/core/browser/dice_account_reconcilor_delegate.h b/components/signin/core/browser/dice_account_reconcilor_delegate.h index 9fd0785..7acc626 100644 --- a/components/signin/core/browser/dice_account_reconcilor_delegate.h +++ b/components/signin/core/browser/dice_account_reconcilor_delegate.h
@@ -9,6 +9,7 @@ #include "base/macros.h" #include "components/signin/core/browser/account_reconcilor_delegate.h" +#include "components/signin/core/browser/profile_management_switches.h" class SigninClient; @@ -17,7 +18,8 @@ // AccountReconcilorDelegate specialized for Dice. class DiceAccountReconcilorDelegate : public AccountReconcilorDelegate { public: - DiceAccountReconcilorDelegate(SigninClient* signin_client); + DiceAccountReconcilorDelegate(SigninClient* signin_client, + AccountConsistencyMethod account_consistency); ~DiceAccountReconcilorDelegate() override {} // AccountReconcilorDelegate: @@ -35,6 +37,7 @@ private: SigninClient* signin_client_; + AccountConsistencyMethod account_consistency_; // Last known "first account". Used when cookies are lost as a best guess. std::string last_known_first_account_;
diff --git a/components/signin/core/browser/dice_account_reconcilor_delegate_unittest.cc b/components/signin/core/browser/dice_account_reconcilor_delegate_unittest.cc index be3753a..b6dbbc5 100644 --- a/components/signin/core/browser/dice_account_reconcilor_delegate_unittest.cc +++ b/components/signin/core/browser/dice_account_reconcilor_delegate_unittest.cc
@@ -7,25 +7,26 @@ #include <vector> #include "components/signin/core/browser/profile_management_switches.h" -#include "components/signin/core/browser/scoped_account_consistency.h" #include "components/signin/core/browser/test_signin_client.h" #include "components/sync_preferences/testing_pref_service_syncable.h" #include "google_apis/gaia/gaia_auth_util.h" #include "testing/gtest/include/gtest/gtest.h" +namespace signin { + TEST(DiceAccountReconcilorDelegateTest, RevokeTokens) { sync_preferences::TestingPrefServiceSyncable pref_service; - signin::RegisterAccountConsistencyProfilePrefs(pref_service.registry()); TestSigninClient client(&pref_service); - signin::DiceAccountReconcilorDelegate delegate(&client); { // Dice is enabled, don't revoke. - signin::ScopedAccountConsistencyDice scoped_dice; + DiceAccountReconcilorDelegate delegate(&client, + AccountConsistencyMethod::kDice); EXPECT_FALSE(delegate.ShouldRevokeAllSecondaryTokensBeforeReconcile( std::vector<gaia::ListedAccount>())); } { - signin::ScopedAccountConsistencyDiceMigration scoped_dice_migration; + DiceAccountReconcilorDelegate delegate( + &client, AccountConsistencyMethod::kDiceMigration); // Gaia accounts are not empty, don't revoke. gaia::ListedAccount gaia_account; gaia_account.id = "other"; @@ -36,3 +37,5 @@ std::vector<gaia::ListedAccount>())); } } + +} // namespace signin
diff --git a/components/signin/core/browser/dice_header_helper.cc b/components/signin/core/browser/dice_header_helper.cc index 186d3b7..3f9b76cf 100644 --- a/components/signin/core/browser/dice_header_helper.cc +++ b/components/signin/core/browser/dice_header_helper.cc
@@ -9,7 +9,6 @@ #include "base/strings/string_number_conversions.h" #include "base/strings/string_util.h" #include "base/strings/stringprintf.h" -#include "components/signin/core/browser/profile_management_switches.h" #include "google_apis/gaia/gaia_auth_util.h" #include "google_apis/gaia/gaia_urls.h" @@ -51,8 +50,10 @@ } // namespace -DiceHeaderHelper::DiceHeaderHelper(bool signed_in_with_auth_error) - : signed_in_with_auth_error_(signed_in_with_auth_error) {} +DiceHeaderHelper::DiceHeaderHelper(bool signed_in_with_auth_error, + AccountConsistencyMethod account_consistency) + : signed_in_with_auth_error_(signed_in_with_auth_error), + account_consistency_(account_consistency) {} // static DiceResponseParams DiceHeaderHelper::BuildDiceSigninResponseParams( @@ -181,14 +182,15 @@ } bool DiceHeaderHelper::IsUrlEligibleForRequestHeader(const GURL& url) { - if (!IsDiceFixAuthErrorsEnabled()) + if (account_consistency_ == AccountConsistencyMethod::kDisabled || + account_consistency_ == AccountConsistencyMethod::kMirror) { return false; + } // With kDiceFixAuthError, only set the request header if the user is signed // in and has an authentication error. if (!signed_in_with_auth_error_ && - (GetAccountConsistencyMethod() == - AccountConsistencyMethod::kDiceFixAuthErrors)) { + (account_consistency_ == AccountConsistencyMethod::kDiceFixAuthErrors)) { return false; } @@ -196,13 +198,12 @@ } std::string DiceHeaderHelper::BuildRequestHeader( - const std::string& sync_account_id, - SignoutMode signout_mode) { + const std::string& sync_account_id) { // When fixing auth errors, only add the header when Sync is actually in error // state. - DCHECK(signed_in_with_auth_error_ || - (GetAccountConsistencyMethod() != - AccountConsistencyMethod::kDiceFixAuthErrors)); + DCHECK( + signed_in_with_auth_error_ || + (account_consistency_ != AccountConsistencyMethod::kDiceFixAuthErrors)); DCHECK(!(sync_account_id.empty() && signed_in_with_auth_error_)); std::vector<std::string> parts; @@ -213,23 +214,17 @@ parts.push_back("sync_account_id=" + sync_account_id); // Restrict Signin to Sync account only when fixing auth errors. - std::string signin_mode = (GetAccountConsistencyMethod() == - AccountConsistencyMethod::kDiceFixAuthErrors) - ? kRequestSigninSyncAccount - : kRequestSigninAll; + std::string signin_mode = + (account_consistency_ == AccountConsistencyMethod::kDiceFixAuthErrors) + ? kRequestSigninSyncAccount + : kRequestSigninAll; parts.push_back("signin_mode=" + signin_mode); // Show the signout confirmation only when Dice is fully enabled. - const char* signout_mode_value = nullptr; - switch (signout_mode) { - case SignoutMode::kNoSignoutConfirmation: - signout_mode_value = kRequestSignoutNoConfirmation; - break; - case SignoutMode::kShowSignoutConfirmation: - signout_mode_value = kRequestSignoutShowConfirmation; - break; - } - DCHECK(signout_mode_value); + const char* signout_mode_value = + (account_consistency_ == AccountConsistencyMethod::kDice) + ? kRequestSignoutShowConfirmation + : kRequestSignoutNoConfirmation; parts.push_back(base::StringPrintf("signout_mode=%s", signout_mode_value)); return base::JoinString(parts, ",");
diff --git a/components/signin/core/browser/dice_header_helper.h b/components/signin/core/browser/dice_header_helper.h index 3cd0b31..e7b51f6 100644 --- a/components/signin/core/browser/dice_header_helper.h +++ b/components/signin/core/browser/dice_header_helper.h
@@ -8,6 +8,7 @@ #include <string> #include "base/macros.h" +#include "components/signin/core/browser/profile_management_switches.h" #include "components/signin/core/browser/signin_header_helper.h" class GURL; @@ -20,15 +21,8 @@ // SigninHeaderHelper implementation managing the Dice header. class DiceHeaderHelper : public SigninHeaderHelper { public: - // Signout mode for Gaia. - enum class SignoutMode { - // Gaia does not show a signout confirmation dialog. - kNoSignoutConfirmation, - // Gaia shows a signout confirmation dialog for the Sync account. - kShowSignoutConfirmation - }; - - explicit DiceHeaderHelper(bool signed_in_with_auth_error); + explicit DiceHeaderHelper(bool signed_in_with_auth_error, + AccountConsistencyMethod account_consistency); ~DiceHeaderHelper() override {} // Returns the parameters contained in the X-Chrome-ID-Consistency-Response @@ -47,14 +41,14 @@ // account. // |show_signout_confirmation| is true if Gaia must display the signout // confirmation dialog. - std::string BuildRequestHeader(const std::string& sync_account_id, - SignoutMode signout_mode); + std::string BuildRequestHeader(const std::string& sync_account_id); private: // SigninHeaderHelper implementation: bool IsUrlEligibleForRequestHeader(const GURL& url) override; bool signed_in_with_auth_error_; + AccountConsistencyMethod account_consistency_; DISALLOW_COPY_AND_ASSIGN(DiceHeaderHelper); };
diff --git a/components/signin/core/browser/fake_signin_manager.cc b/components/signin/core/browser/fake_signin_manager.cc index 80a50eb..ab4c9747 100644 --- a/components/signin/core/browser/fake_signin_manager.cc +++ b/components/signin/core/browser/fake_signin_manager.cc
@@ -36,7 +36,8 @@ token_service, account_tracker_service, cookie_manager_service, - signin_error_controller), + signin_error_controller, + signin::AccountConsistencyMethod::kDisabled), token_service_(token_service) {} FakeSigninManager::~FakeSigninManager() {}
diff --git a/components/signin/core/browser/gaia_cookie_manager_service.cc b/components/signin/core/browser/gaia_cookie_manager_service.cc index ab43c8c..30b7c29 100644 --- a/components/signin/core/browser/gaia_cookie_manager_service.cc +++ b/components/signin/core/browser/gaia_cookie_manager_service.cc
@@ -544,18 +544,6 @@ case net::CookieStore::ChangeCause::EXPLICIT: source += "EXPLICIT"; break; - case net::CookieStore::ChangeCause::EXPLICIT_DELETE_BETWEEN: - source += "EXPLICIT_DELETE_BETWEEN"; - break; - case net::CookieStore::ChangeCause::EXPLICIT_DELETE_PREDICATE: - source += "EXPLICIT_DELETE_PREDICATE"; - break; - case net::CookieStore::ChangeCause::EXPLICIT_DELETE_SINGLE: - source += "EXPLICIT_DELETE_SINGLE"; - break; - case net::CookieStore::ChangeCause::EXPLICIT_DELETE_CANONICAL: - source += "EXPLICIT_DELETE_CANONICAL"; - break; case net::CookieStore::ChangeCause::UNKNOWN_DELETION: source += "UNKNOWN_DELETION"; break;
diff --git a/components/signin/core/browser/profile_management_switches.cc b/components/signin/core/browser/profile_management_switches.cc index e2a1950e..851bf9f 100644 --- a/components/signin/core/browser/profile_management_switches.cc +++ b/components/signin/core/browser/profile_management_switches.cc
@@ -74,6 +74,13 @@ const char kAccountConsistencyFeatureMethodDiceMigration[] = "dice_migration"; const char kAccountConsistencyFeatureMethodDice[] = "dice"; +bool DiceMethodGreaterOrEqual(AccountConsistencyMethod a, + AccountConsistencyMethod b) { + DCHECK_NE(AccountConsistencyMethod::kMirror, a); + DCHECK_NE(AccountConsistencyMethod::kMirror, b); + return AccountConsistencyMethodGreaterOrEqual(a, b); +} + void RegisterAccountConsistencyProfilePrefs( user_prefs::PrefRegistrySyncable* registry) { #if defined(OS_CHROMEOS)
diff --git a/components/signin/core/browser/profile_management_switches.h b/components/signin/core/browser/profile_management_switches.h index 90c240d..330a1a3 100644 --- a/components/signin/core/browser/profile_management_switches.h +++ b/components/signin/core/browser/profile_management_switches.h
@@ -65,9 +65,17 @@ kDice }; +// Returns true if the |a| comes after |b| in the AccountConsistencyMethod enum. +// Should not be used for Mirror. +bool DiceMethodGreaterOrEqual(AccountConsistencyMethod a, + AccountConsistencyMethod b); + //////////////////////////////////////////////////////////////////////////////// // AccountConsistencyMethod related functions: +// WARNING: DEPRECATED. These methods are global, but account consistency is per +// profile. + // Returns the account consistency method. AccountConsistencyMethod GetAccountConsistencyMethod();
diff --git a/components/signin/core/browser/signin_header_helper.cc b/components/signin/core/browser/signin_header_helper.cc index f889e63..6c5a0ec 100644 --- a/components/signin/core/browser/signin_header_helper.cc +++ b/components/signin/core/browser/signin_header_helper.cc
@@ -12,7 +12,6 @@ #include "components/content_settings/core/browser/cookie_settings.h" #include "components/google/core/browser/google_util.h" #include "components/signin/core/browser/chrome_connected_header_helper.h" -#include "components/signin/core/browser/profile_management_switches.h" #include "google_apis/gaia/gaia_auth_util.h" #include "google_apis/gaia/gaia_urls.h" #include "net/base/escape.h" @@ -79,10 +78,11 @@ std::string BuildMirrorRequestCookieIfPossible( const GURL& url, const std::string& account_id, + AccountConsistencyMethod account_consistency, const content_settings::CookieSettings* cookie_settings, int profile_mode_mask) { - return signin::ChromeConnectedHeaderHelper::BuildRequestCookieIfPossible( - url, account_id, cookie_settings, profile_mode_mask); + return ChromeConnectedHeaderHelper::BuildRequestCookieIfPossible( + url, account_id, account_consistency, cookie_settings, profile_mode_mask); } bool SigninHeaderHelper::AppendOrRemoveRequestHeader( @@ -147,11 +147,11 @@ net::URLRequest* request, const GURL& redirect_url, const std::string& account_id, + AccountConsistencyMethod account_consistency, const content_settings::CookieSettings* cookie_settings, - bool is_mirror_enabled, int profile_mode_mask) { const GURL& url = redirect_url.is_empty() ? request->url() : redirect_url; - ChromeConnectedHeaderHelper chrome_connected_helper(is_mirror_enabled); + ChromeConnectedHeaderHelper chrome_connected_helper(account_consistency); std::string chrome_connected_header_value; if (chrome_connected_helper.ShouldBuildRequestHeader(url, cookie_settings)) { chrome_connected_header_value = chrome_connected_helper.BuildRequestHeader( @@ -168,20 +168,17 @@ const std::string& account_id, bool sync_enabled, bool sync_has_auth_error, - BooleanPrefMember* dice_pref_member, + AccountConsistencyMethod account_consistency, const content_settings::CookieSettings* cookie_settings) { #if BUILDFLAG(ENABLE_DICE_SUPPORT) const GURL& url = redirect_url.is_empty() ? request->url() : redirect_url; - DiceHeaderHelper dice_helper(!account_id.empty() && sync_has_auth_error && - sync_enabled); + DiceHeaderHelper dice_helper( + !account_id.empty() && sync_has_auth_error && sync_enabled, + account_consistency); std::string dice_header_value; if (dice_helper.ShouldBuildRequestHeader(url, cookie_settings)) { - DiceHeaderHelper::SignoutMode signout_mode = - IsDiceEnabled(dice_pref_member) - ? DiceHeaderHelper::SignoutMode::kShowSignoutConfirmation - : DiceHeaderHelper::SignoutMode::kNoSignoutConfirmation; dice_header_value = dice_helper.BuildRequestHeader( - sync_enabled ? account_id : std::string(), signout_mode); + sync_enabled ? account_id : std::string()); } return dice_helper.AppendOrRemoveRequestHeader( request, redirect_url, kDiceRequestHeader, dice_header_value);
diff --git a/components/signin/core/browser/signin_header_helper.h b/components/signin/core/browser/signin_header_helper.h index 4eef05de..2d0f0b2 100644 --- a/components/signin/core/browser/signin_header_helper.h +++ b/components/signin/core/browser/signin_header_helper.h
@@ -10,6 +10,7 @@ #include <vector> #include "components/prefs/pref_member.h" +#include "components/signin/core/browser/profile_management_switches.h" #include "components/signin/core/browser/signin_features.h" #include "url/gurl.h" @@ -186,6 +187,7 @@ std::string BuildMirrorRequestCookieIfPossible( const GURL& url, const std::string& account_id, + AccountConsistencyMethod account_consistency, const content_settings::CookieSettings* cookie_settings, int profile_mode_mask); @@ -196,8 +198,8 @@ net::URLRequest* request, const GURL& redirect_url, const std::string& account_id, + AccountConsistencyMethod account_consistency, const content_settings::CookieSettings* cookie_settings, - bool is_mirror_enabled, int profile_mode_mask); // Adds the Dice to all Gaia requests from a connected profile, with the @@ -210,7 +212,7 @@ const std::string& account_id, bool sync_enabled, bool sync_has_auth_error, - BooleanPrefMember* dice_pref_member, + AccountConsistencyMethod account_consistency, const content_settings::CookieSettings* cookie_settings); // Returns the parameters contained in the X-Chrome-Manage-Accounts response
diff --git a/components/signin/core/browser/signin_header_helper_unittest.cc b/components/signin/core/browser/signin_header_helper_unittest.cc index e3ff9791..9056b83e 100644 --- a/components/signin/core/browser/signin_header_helper_unittest.cc +++ b/components/signin/core/browser/signin_header_helper_unittest.cc
@@ -14,7 +14,6 @@ #include "components/prefs/pref_member.h" #include "components/signin/core/browser/chrome_connected_header_helper.h" #include "components/signin/core/browser/profile_management_switches.h" -#include "components/signin/core/browser/scoped_account_consistency.h" #include "components/signin/core/browser/signin_features.h" #include "components/sync_preferences/testing_pref_service_syncable.h" #include "google_apis/gaia/gaia_urls.h" @@ -34,14 +33,12 @@ void SetUp() override { content_settings::CookieSettings::RegisterProfilePrefs(prefs_.registry()); HostContentSettingsMap::RegisterProfilePrefs(prefs_.registry()); - signin::RegisterAccountConsistencyProfilePrefs(prefs_.registry()); settings_map_ = new HostContentSettingsMap( &prefs_, false /* incognito_profile */, false /* guest_profile */, false /* store_last_modified */); cookie_settings_ = new content_settings::CookieSettings(settings_map_.get(), &prefs_, ""); - dice_enabled_pref_member_ = signin::CreateDicePrefMember(&prefs_); } void TearDown() override { settings_map_->ShutdownOnUIThread(); } @@ -49,10 +46,10 @@ void CheckMirrorCookieRequest(const GURL& url, const std::string& account_id, const std::string& expected_request) { - EXPECT_EQ( - BuildMirrorRequestCookieIfPossible( - url, account_id, cookie_settings_.get(), PROFILE_MODE_DEFAULT), - expected_request); + EXPECT_EQ(BuildMirrorRequestCookieIfPossible( + url, account_id, account_consistency_, cookie_settings_.get(), + PROFILE_MODE_DEFAULT), + expected_request); } std::unique_ptr<net::URLRequest> CreateRequest( @@ -62,12 +59,11 @@ url_request_context_.CreateRequest(url, net::DEFAULT_PRIORITY, nullptr, TRAFFIC_ANNOTATION_FOR_TESTS); AppendOrRemoveMirrorRequestHeader( - url_request.get(), GURL(), account_id, cookie_settings_.get(), - IsAccountConsistencyMirrorEnabled(), PROFILE_MODE_DEFAULT); - AppendOrRemoveDiceRequestHeader(url_request.get(), GURL(), account_id, - sync_enabled_, sync_has_auth_error_, - dice_enabled_pref_member_.get(), - cookie_settings_.get()); + url_request.get(), GURL(), account_id, account_consistency_, + cookie_settings_.get(), PROFILE_MODE_DEFAULT); + AppendOrRemoveDiceRequestHeader( + url_request.get(), GURL(), account_id, sync_enabled_, + sync_has_auth_error_, account_consistency_, cookie_settings_.get()); return url_request; } @@ -113,20 +109,21 @@ bool sync_enabled_ = false; bool sync_has_auth_error_ = false; + AccountConsistencyMethod account_consistency_ = + AccountConsistencyMethod::kDisabled; sync_preferences::TestingPrefServiceSyncable prefs_; net::TestURLRequestContext url_request_context_; scoped_refptr<HostContentSettingsMap> settings_map_; scoped_refptr<content_settings::CookieSettings> cookie_settings_; - std::unique_ptr<BooleanPrefMember> dice_enabled_pref_member_; }; #if defined(OS_CHROMEOS) // Tests that Mirror request is returned on Chrome OS for Public Sessions (no // account id). TEST_F(SigninHeaderHelperTest, TestMirrorRequestNoAccountIdChromeOS) { - ScopedAccountConsistencyMirror scoped_mirror; + account_consistency_ = AccountConsistencyMethod::kMirror; CheckMirrorHeaderRequest(GURL("https://docs.google.com"), "", "mode=0,enable_account_consistency=true"); CheckMirrorCookieRequest(GURL("https://docs.google.com"), "", @@ -136,7 +133,7 @@ // Tests that no Mirror request is returned when the user is not signed in (no // account id), for non Chrome OS platforms. TEST_F(SigninHeaderHelperTest, TestNoMirrorRequestNoAccountId) { - ScopedAccountConsistencyMirror scoped_mirror; + account_consistency_ = AccountConsistencyMethod::kMirror; CheckMirrorHeaderRequest(GURL("https://docs.google.com"), "", ""); CheckMirrorCookieRequest(GURL("https://docs.google.com"), "", ""); } @@ -145,7 +142,7 @@ // Tests that no Mirror request is returned when the cookies aren't allowed to // be set. TEST_F(SigninHeaderHelperTest, TestNoMirrorRequestCookieSettingBlocked) { - ScopedAccountConsistencyMirror scoped_mirror; + account_consistency_ = AccountConsistencyMethod::kMirror; cookie_settings_->SetDefaultCookieSetting(CONTENT_SETTING_BLOCK); CheckMirrorHeaderRequest(GURL("https://docs.google.com"), "0123456789", ""); CheckMirrorCookieRequest(GURL("https://docs.google.com"), "0123456789", ""); @@ -153,7 +150,7 @@ // Tests that no Mirror request is returned when the target is a non-Google URL. TEST_F(SigninHeaderHelperTest, TestNoMirrorRequestExternalURL) { - ScopedAccountConsistencyMirror scoped_mirror; + account_consistency_ = AccountConsistencyMethod::kMirror; CheckMirrorHeaderRequest(GURL("https://foo.com"), "0123456789", ""); CheckMirrorCookieRequest(GURL("https://foo.com"), "0123456789", ""); } @@ -161,7 +158,7 @@ // Tests that the Mirror request is returned without the GAIA Id when the target // is a google TLD domain. TEST_F(SigninHeaderHelperTest, TestMirrorRequestGoogleTLD) { - ScopedAccountConsistencyMirror scoped_mirror; + account_consistency_ = AccountConsistencyMethod::kMirror; CheckMirrorHeaderRequest(GURL("https://google.fr"), "0123456789", "mode=0,enable_account_consistency=true"); CheckMirrorCookieRequest(GURL("https://google.de"), "0123456789", @@ -171,7 +168,7 @@ // Tests that the Mirror request is returned when the target is the domain // google.com, and that the GAIA Id is only attached for the cookie. TEST_F(SigninHeaderHelperTest, TestMirrorRequestGoogleCom) { - ScopedAccountConsistencyMirror scoped_mirror; + account_consistency_ = AccountConsistencyMethod::kMirror; CheckMirrorHeaderRequest(GURL("https://www.google.com"), "0123456789", "mode=0,enable_account_consistency=true"); CheckMirrorCookieRequest( @@ -186,21 +183,22 @@ net::DEFAULT_PRIORITY, nullptr, TRAFFIC_ANNOTATION_FOR_TESTS); AppendOrRemoveMirrorRequestHeader( - url_request.get(), GURL(), "0123456789", cookie_settings_.get(), - false /* is_mirror_enabled */, PROFILE_MODE_DEFAULT); + url_request.get(), GURL(), "0123456789", account_consistency_, + cookie_settings_.get(), PROFILE_MODE_DEFAULT); CheckAccountConsistencyHeaderRequest(url_request.get(), kChromeConnectedHeader, ""); } // Tests that header sent when mirror account consistency is requested. TEST_F(SigninHeaderHelperTest, TestMirrorRequestGoogleComProfileConsistency) { + account_consistency_ = AccountConsistencyMethod::kMirror; std::unique_ptr<net::URLRequest> url_request = url_request_context_.CreateRequest(GURL("https://www.google.com"), net::DEFAULT_PRIORITY, nullptr, TRAFFIC_ANNOTATION_FOR_TESTS); AppendOrRemoveMirrorRequestHeader( - url_request.get(), GURL(), "0123456789", cookie_settings_.get(), - true /* is_mirror_enabled */, PROFILE_MODE_DEFAULT); + url_request.get(), GURL(), "0123456789", account_consistency_, + cookie_settings_.get(), PROFILE_MODE_DEFAULT); CheckAccountConsistencyHeaderRequest( url_request.get(), kChromeConnectedHeader, "mode=0,enable_account_consistency=true"); @@ -213,8 +211,6 @@ // Tests that the Mirror request is returned when the target is a Gaia URL, even // if account consistency is disabled. TEST_F(SigninHeaderHelperTest, TestMirrorRequestGaiaURL) { - ScopedAccountConsistencyDiceFixAuthErrors scoped_dice_fix_auth_errors; - ASSERT_FALSE(IsAccountConsistencyMirrorEnabled()); CheckMirrorHeaderRequest(GURL("https://accounts.google.com"), "0123456789", "mode=0,enable_account_consistency=false"); CheckMirrorCookieRequest( @@ -224,7 +220,7 @@ // Tests Dice requests. TEST_F(SigninHeaderHelperTest, TestDiceRequest) { - ScopedAccountConsistencyDice scoped_dice; + account_consistency_ = AccountConsistencyMethod::kDice; // ChromeConnected but no Dice for Docs URLs. CheckDiceHeaderRequest( GURL("https://docs.google.com"), "0123456789", @@ -258,7 +254,7 @@ // Tests that no Dice request is returned when Dice is not enabled. TEST_F(SigninHeaderHelperTest, TestNoDiceRequestWhenDisabled) { - ScopedAccountConsistencyMirror scoped_mirror; + account_consistency_ = AccountConsistencyMethod::kMirror; CheckDiceHeaderRequest(GURL("https://accounts.google.com"), "0123456789", "mode=0,enable_account_consistency=true", ""); } @@ -266,7 +262,7 @@ // Tests that the signout confirmation is requested iff the Dice migration is // complete. TEST_F(SigninHeaderHelperTest, TestDiceMigration) { - ScopedAccountConsistencyDiceMigration scoped_dice_migration; + account_consistency_ = AccountConsistencyMethod::kDiceMigration; std::string client_id = GaiaUrls::GetInstance()->oauth2_chrome_client_id(); ASSERT_FALSE(client_id.empty()); @@ -279,7 +275,7 @@ kDiceProtocolVersion, client_id.c_str())); // Signout confirmation after the migration is complete. - MigrateProfileToDice(&prefs_); + account_consistency_ = AccountConsistencyMethod::kDice; CheckDiceHeaderRequest( GURL("https://accounts.google.com"), "0123456789", "mode=0,enable_account_consistency=false", @@ -291,7 +287,7 @@ // Tests that a Dice request is returned only when there is an authentication // error if the method is kDiceFixAuthErrors. TEST_F(SigninHeaderHelperTest, TestDiceFixAuthError) { - ScopedAccountConsistencyDiceFixAuthErrors scoped_dice_fix_auth_errors; + account_consistency_ = AccountConsistencyMethod::kDiceFixAuthErrors; // No Dice request unless all conditions are met. CheckDiceHeaderRequest(GURL("https://accounts.google.com"), "0123456789", "mode=0,enable_account_consistency=false", ""); @@ -322,8 +318,6 @@ // Tests that the Mirror request is returned with the GAIA Id on Drive origin, // even if account consistency is disabled. TEST_F(SigninHeaderHelperTest, TestMirrorRequestDrive) { - ScopedAccountConsistencyDiceFixAuthErrors scoped_dice_fix_auth_errors; - ASSERT_FALSE(IsAccountConsistencyMirrorEnabled()); CheckMirrorHeaderRequest( GURL("https://docs.google.com/document"), "0123456789", "id=0123456789,mode=0,enable_account_consistency=false"); @@ -332,7 +326,7 @@ "id=0123456789:mode=0:enable_account_consistency=false"); // Enable Account Consistency will override the disable. - ScopedAccountConsistencyMirror scoped_mirror; + account_consistency_ = AccountConsistencyMethod::kMirror; CheckMirrorHeaderRequest( GURL("https://docs.google.com/document"), "0123456789", "id=0123456789,mode=0,enable_account_consistency=true"); @@ -452,7 +446,7 @@ // Tests that the Mirror header request is returned normally when the redirect // URL is eligible. TEST_F(SigninHeaderHelperTest, TestMirrorHeaderEligibleRedirectURL) { - ScopedAccountConsistencyMirror scoped_mirror; + account_consistency_ = AccountConsistencyMethod::kMirror; const GURL url("https://docs.google.com/document"); const GURL redirect_url("https://www.google.com"); const std::string account_id = "0123456789"; @@ -460,8 +454,8 @@ url_request_context_.CreateRequest(url, net::DEFAULT_PRIORITY, nullptr, TRAFFIC_ANNOTATION_FOR_TESTS); AppendOrRemoveMirrorRequestHeader( - url_request.get(), redirect_url, account_id, cookie_settings_.get(), - IsAccountConsistencyMirrorEnabled(), PROFILE_MODE_DEFAULT); + url_request.get(), redirect_url, account_id, account_consistency_, + cookie_settings_.get(), PROFILE_MODE_DEFAULT); EXPECT_TRUE( url_request->extra_request_headers().HasHeader(kChromeConnectedHeader)); } @@ -469,7 +463,7 @@ // Tests that the Mirror header request is stripped when the redirect URL is not // eligible. TEST_F(SigninHeaderHelperTest, TestMirrorHeaderNonEligibleRedirectURL) { - ScopedAccountConsistencyMirror scoped_mirror; + account_consistency_ = AccountConsistencyMethod::kMirror; const GURL url("https://docs.google.com/document"); const GURL redirect_url("http://www.foo.com"); const std::string account_id = "0123456789"; @@ -477,8 +471,8 @@ url_request_context_.CreateRequest(url, net::DEFAULT_PRIORITY, nullptr, TRAFFIC_ANNOTATION_FOR_TESTS); AppendOrRemoveMirrorRequestHeader( - url_request.get(), redirect_url, account_id, cookie_settings_.get(), - IsAccountConsistencyMirrorEnabled(), PROFILE_MODE_DEFAULT); + url_request.get(), redirect_url, account_id, account_consistency_, + cookie_settings_.get(), PROFILE_MODE_DEFAULT); EXPECT_FALSE( url_request->extra_request_headers().HasHeader(kChromeConnectedHeader)); } @@ -486,7 +480,7 @@ // Tests that the Mirror header, whatever its value is, is untouched when both // the current and the redirect URL are non-eligible. TEST_F(SigninHeaderHelperTest, TestIgnoreMirrorHeaderNonEligibleURLs) { - ScopedAccountConsistencyMirror scoped_mirror; + account_consistency_ = AccountConsistencyMethod::kMirror; const GURL url("https://www.bar.com"); const GURL redirect_url("http://www.foo.com"); const std::string account_id = "0123456789"; @@ -497,8 +491,8 @@ url_request->SetExtraRequestHeaderByName(kChromeConnectedHeader, fake_header, false); AppendOrRemoveMirrorRequestHeader( - url_request.get(), redirect_url, account_id, cookie_settings_.get(), - IsAccountConsistencyMirrorEnabled(), PROFILE_MODE_DEFAULT); + url_request.get(), redirect_url, account_id, account_consistency_, + cookie_settings_.get(), PROFILE_MODE_DEFAULT); std::string header; EXPECT_TRUE(url_request->extra_request_headers().GetHeader( kChromeConnectedHeader, &header));
diff --git a/components/signin/core/browser/signin_manager.cc b/components/signin/core/browser/signin_manager.cc index f793a7ab..0907735 100644 --- a/components/signin/core/browser/signin_manager.cc +++ b/components/signin/core/browser/signin_manager.cc
@@ -15,7 +15,6 @@ #include "components/prefs/pref_service.h" #include "components/signin/core/browser/account_tracker_service.h" #include "components/signin/core/browser/gaia_cookie_manager_service.h" -#include "components/signin/core/browser/profile_management_switches.h" #include "components/signin/core/browser/signin_client.h" #include "components/signin/core/browser/signin_internals_util.h" #include "components/signin/core/browser/signin_metrics.h" @@ -28,11 +27,13 @@ using namespace signin_internals_util; -SigninManager::SigninManager(SigninClient* client, - ProfileOAuth2TokenService* token_service, - AccountTrackerService* account_tracker_service, - GaiaCookieManagerService* cookie_manager_service, - SigninErrorController* signin_error_controller) +SigninManager::SigninManager( + SigninClient* client, + ProfileOAuth2TokenService* token_service, + AccountTrackerService* account_tracker_service, + GaiaCookieManagerService* cookie_manager_service, + SigninErrorController* signin_error_controller, + signin::AccountConsistencyMethod account_consistency) : SigninManagerBase(client, account_tracker_service, signin_error_controller), @@ -42,6 +43,7 @@ diagnostics_client_(nullptr), token_service_(token_service), cookie_manager_service_(cookie_manager_service), + account_consistency_(account_consistency), signin_manager_signed_in_(false), user_info_fetched_by_account_tracker_(false), weak_pointer_factory_(this) {} @@ -159,7 +161,7 @@ signin_metrics::ProfileSignout signout_source_metric, signin_metrics::SignoutDelete signout_delete_metric) { StartSignOut(signout_source_metric, signout_delete_metric, - !signin::IsDiceEnabledForProfile(client_->GetPrefs())); + account_consistency_ != signin::AccountConsistencyMethod::kDice); } void SigninManager::SignOutAndRemoveAllAccounts(
diff --git a/components/signin/core/browser/signin_manager.h b/components/signin/core/browser/signin_manager.h index 862fc97..f0d3fc0 100644 --- a/components/signin/core/browser/signin_manager.h +++ b/components/signin/core/browser/signin_manager.h
@@ -34,6 +34,7 @@ #include "components/prefs/pref_member.h" #include "components/signin/core/browser/account_info.h" #include "components/signin/core/browser/account_tracker_service.h" +#include "components/signin/core/browser/profile_management_switches.h" #include "components/signin/core/browser/profile_oauth2_token_service.h" #include "components/signin/core/browser/signin_internals_util.h" #include "components/signin/core/browser/signin_manager_base.h" @@ -72,7 +73,8 @@ ProfileOAuth2TokenService* token_service, AccountTrackerService* account_tracker_service, GaiaCookieManagerService* cookie_manager_service, - SigninErrorController* signin_error_controller); + SigninErrorController* signin_error_controller, + signin::AccountConsistencyMethod account_consistency); ~SigninManager() override; // Returns true if the username is allowed based on the policy string. @@ -298,6 +300,8 @@ // Helper object to listen for changes to the signin allowed preference. BooleanPrefMember signin_allowed_; + signin::AccountConsistencyMethod account_consistency_; + // Two gate conditions for when PostSignedIn should be called. Verify // that the SigninManager has reached OnSignedIn() and the AccountTracker // has completed calling GetUserInfo.
diff --git a/components/signin/core/browser/signin_manager_unittest.cc b/components/signin/core/browser/signin_manager_unittest.cc index c69565a..7fa807de 100644 --- a/components/signin/core/browser/signin_manager_unittest.cc +++ b/components/signin/core/browser/signin_manager_unittest.cc
@@ -88,9 +88,7 @@ url_fetcher_factory_(nullptr) { test_signin_client_.SetURLRequestContext( new net::TestURLRequestContextGetter(loop_.task_runner())); - signin::SetGaiaOriginIsolatedCallback(base::Bind([] { return true; })); cookie_manager_service_.Init(&url_fetcher_factory_); - signin::RegisterAccountConsistencyProfilePrefs(user_prefs_.registry()); AccountFetcherService::RegisterPrefs(user_prefs_.registry()); AccountTrackerService::RegisterPrefs(user_prefs_.registry()); SigninManagerBase::RegisterProfilePrefs(user_prefs_.registry()); @@ -132,7 +130,8 @@ DCHECK(!manager_); manager_ = std::make_unique<SigninManager>( &test_signin_client_, &token_service_, &account_tracker_, - &cookie_manager_service_, nullptr /* signin_error_controller */); + &cookie_manager_service_, nullptr /* signin_error_controller */, + signin::AccountConsistencyMethod::kDisabled); manager_->Initialize(&local_state_); manager_->AddObserver(&test_observer_); }
diff --git a/components/signin/ios/browser/account_consistency_service.mm b/components/signin/ios/browser/account_consistency_service.mm index a5305e1..570e188 100644 --- a/components/signin/ios/browser/account_consistency_service.mm +++ b/components/signin/ios/browser/account_consistency_service.mm
@@ -14,6 +14,7 @@ #include "components/pref_registry/pref_registry_syncable.h" #include "components/prefs/scoped_user_pref_update.h" #include "components/signin/core/browser/account_reconcilor.h" +#include "components/signin/core/browser/profile_management_switches.h" #include "components/signin/core/browser/signin_client.h" #include "components/signin/core/browser/signin_header_helper.h" #include "ios/web/public/browser_state.h" @@ -364,7 +365,8 @@ case ADD_CHROME_CONNECTED_COOKIE: cookie_value = signin::BuildMirrorRequestCookieIfPossible( url, signin_manager_->GetAuthenticatedAccountInfo().gaia, - cookie_settings_.get(), signin::PROFILE_MODE_DEFAULT); + signin::AccountConsistencyMethod::kMirror, cookie_settings_.get(), + signin::PROFILE_MODE_DEFAULT); if (cookie_value.empty()) { // Don't add the cookie. Tentatively correct |last_cookie_update_map_|. last_cookie_update_map_.erase(cookie_requests_.front().domain);
diff --git a/components/storage_monitor/media_transfer_protocol_device_observer_chromeos.cc b/components/storage_monitor/media_transfer_protocol_device_observer_chromeos.cc index 803a451..87bf7b41 100644 --- a/components/storage_monitor/media_transfer_protocol_device_observer_chromeos.cc +++ b/components/storage_monitor/media_transfer_protocol_device_observer_chromeos.cc
@@ -78,33 +78,27 @@ // TODO(thestig): Change this to tell the mtp manager to eject the device. - StorageChanged(false, location); + StorageDetached(location); callback.Run(StorageMonitor::EJECT_OK); } // device::MediaTransferProtocolManager::Observer override. -void MediaTransferProtocolDeviceObserverChromeOS::StorageChanged( - bool is_attached, +void MediaTransferProtocolDeviceObserverChromeOS::StorageAttached( + const device::mojom::MtpStorageInfo& mtp_storage_info) { + DoAttachStorage(&mtp_storage_info); +} + +// device::MediaTransferProtocolManager::Observer override. +void MediaTransferProtocolDeviceObserverChromeOS::StorageDetached( const std::string& storage_name) { DCHECK(!storage_name.empty()); - // Existing storage is detached. - if (!is_attached) { - StorageLocationToInfoMap::iterator it = - storage_map_.find(GetDeviceLocationFromStorageName(storage_name)); - if (it == storage_map_.end()) - return; - notifications_->ProcessDetach(it->second.device_id()); - storage_map_.erase(it); + StorageLocationToInfoMap::iterator it = + storage_map_.find(GetDeviceLocationFromStorageName(storage_name)); + if (it == storage_map_.end()) return; - } - - // New storage is attached. - get_mtp_storage_info_cb_.Run( - storage_name, - base::BindOnce( - &MediaTransferProtocolDeviceObserverChromeOS::DoAttachStorage, - weak_ptr_factory_.GetWeakPtr())); + notifications_->ProcessDetach(it->second.device_id()); + storage_map_.erase(it); } void MediaTransferProtocolDeviceObserverChromeOS::DoAttachStorage( @@ -142,7 +136,11 @@ typedef std::vector<std::string> StorageList; for (StorageList::const_iterator storage_iter = storages.begin(); storage_iter != storages.end(); ++storage_iter) { - StorageChanged(true, *storage_iter); + get_mtp_storage_info_cb_.Run( + *storage_iter, + base::BindOnce( + &MediaTransferProtocolDeviceObserverChromeOS::DoAttachStorage, + weak_ptr_factory_.GetWeakPtr())); } }
diff --git a/components/storage_monitor/media_transfer_protocol_device_observer_chromeos.h b/components/storage_monitor/media_transfer_protocol_device_observer_chromeos.h index 48b80d6..2e2570c 100644 --- a/components/storage_monitor/media_transfer_protocol_device_observer_chromeos.h +++ b/components/storage_monitor/media_transfer_protocol_device_observer_chromeos.h
@@ -52,8 +52,9 @@ // device::MediaTransferProtocolManager::Observer implementation. // Exposed for unit tests. - void StorageChanged(bool is_attached, - const std::string& storage_name) override; + void StorageAttached( + const device::mojom::MtpStorageInfo& storage_info) override; + void StorageDetached(const std::string& storage_name) override; private: // Mapping of storage location and mtp storage info object.
diff --git a/components/storage_monitor/media_transfer_protocol_device_observer_chromeos_unittest.cc b/components/storage_monitor/media_transfer_protocol_device_observer_chromeos_unittest.cc index 27f0f40..17aaaf9 100644 --- a/components/storage_monitor/media_transfer_protocol_device_observer_chromeos_unittest.cc +++ b/components/storage_monitor/media_transfer_protocol_device_observer_chromeos_unittest.cc
@@ -93,7 +93,10 @@ // of // mtp storage device given the |storage_name|. void MtpStorageAttached(const std::string& storage_name) { - StorageChanged(true, storage_name); + auto* storage_info = GetFakeMtpStorageInfoSync(storage_name); + DCHECK(storage_info); + + StorageAttached(*storage_info); base::RunLoop().RunUntilIdle(); } @@ -101,7 +104,7 @@ // of // mtp storage device given the |storage_name|. void MtpStorageDetached(const std::string& storage_name) { - StorageChanged(false, storage_name); + StorageDetached(storage_name); base::RunLoop().RunUntilIdle(); }
diff --git a/components/subresource_filter/core/common/BUILD.gn b/components/subresource_filter/core/common/BUILD.gn index 55111b61..907ebf8e 100644 --- a/components/subresource_filter/core/common/BUILD.gn +++ b/components/subresource_filter/core/common/BUILD.gn
@@ -58,6 +58,18 @@ ] } +static_library("tools_lib") { + sources = [ + "tools/indexing_tool.cc", + "tools/indexing_tool.h", + ] + deps = [ + ":common", + "//base", + "//components/url_pattern_index:util", + ] +} + source_set("unit_tests") { testonly = true sources = [ @@ -65,10 +77,12 @@ "first_party_origin_unittest.cc", "indexed_ruleset_unittest.cc", "scoped_timers_unittest.cc", + "tools/indexing_tool_unittest.cc", ] deps = [ ":common", ":test_support", + ":tools_lib", "//base", "//base/test:test_support", "//components/url_pattern_index:test_support", @@ -77,3 +91,16 @@ "//url", ] } + +if (is_linux || is_mac || is_win) { + executable("subresource_indexing_tool") { + sources = [ + "tools/indexing_tool_main.cc", + ] + deps = [ + ":tools_lib", + "//base", + "//build/config:exe_and_shlib_deps", + ] + } +}
diff --git a/components/subresource_filter/core/common/test_ruleset_utils.cc b/components/subresource_filter/core/common/test_ruleset_utils.cc index 9ea5f66..644f8bf 100644 --- a/components/subresource_filter/core/common/test_ruleset_utils.cc +++ b/components/subresource_filter/core/common/test_ruleset_utils.cc
@@ -4,6 +4,8 @@ #include "components/subresource_filter/core/common/test_ruleset_utils.h" +#include <utility> + namespace subresource_filter { namespace testing { @@ -21,6 +23,18 @@ return rule; } +proto::UrlRule CreateWhitelistSuffixRule(base::StringPiece suffix) { + proto::UrlRule rule; + rule.set_semantics(proto::RULE_SEMANTICS_WHITELIST); + rule.set_source_type(proto::SOURCE_TYPE_ANY); + rule.set_element_types(proto::ELEMENT_TYPE_ALL); + rule.set_url_pattern_type(proto::URL_PATTERN_TYPE_SUBSTRING); + rule.set_anchor_left(proto::ANCHOR_TYPE_NONE); + rule.set_anchor_right(proto::ANCHOR_TYPE_BOUNDARY); + rule.set_url_pattern(suffix.as_string()); + return rule; +} + proto::UrlRule CreateWhitelistRuleForDocument( base::StringPiece pattern, int32_t activation_types,
diff --git a/components/subresource_filter/core/common/test_ruleset_utils.h b/components/subresource_filter/core/common/test_ruleset_utils.h index 5c001c9..3c137c2 100644 --- a/components/subresource_filter/core/common/test_ruleset_utils.h +++ b/components/subresource_filter/core/common/test_ruleset_utils.h
@@ -19,6 +19,11 @@ // the resource URL ends with |suffix|. url_pattern_index::proto::UrlRule CreateSuffixRule(base::StringPiece suffix); +// Creates a white URL rule which targets subresources of any type such that +// the resource URL ends with |suffix|. +url_pattern_index::proto::UrlRule CreateWhitelistSuffixRule( + base::StringPiece suffix); + // Same as CreateUrlRule(pattern, proto::URL_PATTERN_TYPE_WILDCARDED), but the // rule applies to the specified |activation_types|, and to no element types. // Additionally, it is restricted to a set of |domains| (if provided).
diff --git a/components/subresource_filter/core/common/tools/indexing_tool.cc b/components/subresource_filter/core/common/tools/indexing_tool.cc new file mode 100644 index 0000000..832a5728 --- /dev/null +++ b/components/subresource_filter/core/common/tools/indexing_tool.cc
@@ -0,0 +1,53 @@ +// 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 "components/subresource_filter/core/common/tools/indexing_tool.h" + +#include <utility> + +#include "base/files/file.h" +#include "base/files/file_util.h" +#include "base/numerics/safe_conversions.h" +#include "components/subresource_filter/core/common/indexed_ruleset.h" +#include "components/url_pattern_index/copying_file_stream.h" +#include "components/url_pattern_index/proto/rules.pb.h" +#include "components/url_pattern_index/unindexed_ruleset.h" + +namespace subresource_filter { + +bool IndexAndWriteRuleset(const base::FilePath& unindexed_path, + const base::FilePath& indexed_path) { + if (!base::PathExists(unindexed_path) || + !base::DirectoryExists(indexed_path.DirName())) { + return false; + } + + base::File unindexed_file(unindexed_path, + base::File::FLAG_OPEN | base::File::FLAG_READ); + + subresource_filter::RulesetIndexer indexer; + + url_pattern_index::CopyingFileInputStream copying_stream( + std::move(unindexed_file)); + google::protobuf::io::CopyingInputStreamAdaptor zero_copy_stream_adaptor( + ©ing_stream, 4096 /* buffer_size */); + url_pattern_index::UnindexedRulesetReader reader(&zero_copy_stream_adaptor); + + url_pattern_index::proto::FilteringRules ruleset_chunk; + + while (reader.ReadNextChunk(&ruleset_chunk)) { + for (const auto& rule : ruleset_chunk.url_rules()) { + indexer.AddUrlRule(rule); + } + } + + indexer.Finish(); + + base::WriteFile(indexed_path, reinterpret_cast<const char*>(indexer.data()), + base::checked_cast<int>(indexer.size())); + + return true; +} + +} // namespace subresource_filter
diff --git a/components/subresource_filter/core/common/tools/indexing_tool.h b/components/subresource_filter/core/common/tools/indexing_tool.h new file mode 100644 index 0000000..3dbade98 --- /dev/null +++ b/components/subresource_filter/core/common/tools/indexing_tool.h
@@ -0,0 +1,21 @@ +// 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. + +#ifndef COMPONENTS_SUBRESOURCE_FILTER_CORE_COMMON_TOOLS_INDEXING_TOOL_H_ +#define COMPONENTS_SUBRESOURCE_FILTER_CORE_COMMON_TOOLS_INDEXING_TOOL_H_ + +#include "base/command_line.h" +#include "base/files/file_path.h" + +namespace subresource_filter { + +// Given |unindexed_path|, which is a path to an unindexed ruleset, writes the +// indexed (flatbuffer) version to |indexed_path|. Returns false if there was +// something wrong with the given paths. +bool IndexAndWriteRuleset(const base::FilePath& unindexed_path, + const base::FilePath& indexed_path); + +} // namespace subresource_filter + +#endif // COMPONENTS_SUBRESOURCE_FILTER_CORE_COMMON_TOOLS_INDEXING_TOOL_H_
diff --git a/components/subresource_filter/core/common/tools/indexing_tool_main.cc b/components/subresource_filter/core/common/tools/indexing_tool_main.cc new file mode 100644 index 0000000..2d335d52 --- /dev/null +++ b/components/subresource_filter/core/common/tools/indexing_tool_main.cc
@@ -0,0 +1,41 @@ +// 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 "base/command_line.h" +#include "base/files/file_path.h" +#include "base/files/file_util.h" +#include "base/logging.h" +#include "components/subresource_filter/core/common/tools/indexing_tool.h" + +const char kHelpMsg[] = R"( + subresource_indexing_tool <unindexed_ruleset_file> <output_file> + + subresource_indexing_tool will open the |unindexed_ruleset_file| and output + an indexed version in |output_file|. +)"; + +void PrintHelp() { + printf("%s\n\n", kHelpMsg); +} + +int main(int argc, char* argv[]) { + base::CommandLine::Init(argc, argv); + const base::CommandLine& command_line = + *base::CommandLine::ForCurrentProcess(); + base::CommandLine::StringVector args = command_line.GetArgs(); + + if (args.size() < 2U) { + PrintHelp(); + return 1; + } + + base::FilePath unindexed_path(args[0]); + base::FilePath indexed_path(args[1]); + + if (!subresource_filter::IndexAndWriteRuleset(unindexed_path, indexed_path)) { + LOG(ERROR) << "There was an error. Be sure that the first argument points " + "to a valid unindexed file and that the second argument is " + "in an existing directory."; + } +}
diff --git a/components/subresource_filter/core/common/tools/indexing_tool_unittest.cc b/components/subresource_filter/core/common/tools/indexing_tool_unittest.cc new file mode 100644 index 0000000..807f4d94 --- /dev/null +++ b/components/subresource_filter/core/common/tools/indexing_tool_unittest.cc
@@ -0,0 +1,117 @@ +// 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 "components/subresource_filter/core/common/tools/indexing_tool.h" + +#include <memory> +#include <string> +#include <vector> + +#include "base/files/file_util.h" +#include "base/files/scoped_temp_dir.h" +#include "base/macros.h" +#include "base/numerics/safe_conversions.h" +#include "base/strings/string_number_conversions.h" +#include "components/subresource_filter/core/common/test_ruleset_creator.h" +#include "components/subresource_filter/core/common/test_ruleset_utils.h" +#include "testing/gtest/include/gtest/gtest.h" + +namespace subresource_filter { + +namespace proto = url_pattern_index::proto; + +namespace { + +std::vector<uint8_t> ReadFileContents(const base::FilePath& file_path) { + base::File file(file_path, base::File::FLAG_OPEN | base::File::FLAG_READ); + + size_t length = base::checked_cast<size_t>(file.GetLength()); + std::vector<uint8_t> contents(length); + static_assert(sizeof(uint8_t) == sizeof(char), "Expected char = byte."); + file.Read(0, reinterpret_cast<char*>(contents.data()), + base::checked_cast<int>(length)); + return contents; +} + +class IndexingToolTest : public ::testing::Test { + public: + IndexingToolTest() {} + + protected: + void SetUp() override { ASSERT_TRUE(scoped_temp_dir_.CreateUniqueTempDir()); } + + base::FilePath GetUniquePath() { + base::FilePath path = scoped_temp_dir_.GetPath().AppendASCII( + base::IntToString(file_count_++)); + return path; + } + + void CreateSimpleRuleset() { + std::vector<proto::UrlRule> rules; + rules.push_back(testing::CreateSuffixRule("disallowed1.png")); + rules.push_back(testing::CreateSuffixRule("disallowed2.png")); + rules.push_back(testing::CreateSuffixRule("disallowed3.png")); + rules.push_back( + testing::CreateWhitelistSuffixRule("whitelist/disallowed1.png")); + rules.push_back( + testing::CreateWhitelistSuffixRule("whitelist/disallowed2.png")); + + ASSERT_NO_FATAL_FAILURE(test_ruleset_creator_.CreateRulesetWithRules( + rules, &test_ruleset_pair_)); + } + + void WriteUnindexedRulesetToFile(const base::FilePath& path) { + // Write the test unindexed data to a file. + const std::vector<uint8_t>& unindexed_data = + test_ruleset_pair_.unindexed.contents; + base::WriteFile(path, reinterpret_cast<const char*>(unindexed_data.data()), + base::checked_cast<int>(unindexed_data.size())); + } + + int file_count_ = 0; + base::ScopedTempDir scoped_temp_dir_; + testing::TestRulesetCreator test_ruleset_creator_; + testing::TestRulesetPair test_ruleset_pair_; + + DISALLOW_COPY_AND_ASSIGN(IndexingToolTest); +}; + +TEST_F(IndexingToolTest, UnindexedFileDoesNotExist) { + // There is no file at the unindexed position, so it should return false. + EXPECT_FALSE(IndexAndWriteRuleset(GetUniquePath(), GetUniquePath())); +} + +TEST_F(IndexingToolTest, IndexedDirectoryDoesNotExist) { + // Create a valid unindexed file. + base::FilePath unindexed_path = GetUniquePath(); + CreateSimpleRuleset(); + WriteUnindexedRulesetToFile(unindexed_path); + + // The indexed path is in a non-existant directory. + base::FilePath indexed_path = + scoped_temp_dir_.GetPath().AppendASCII("foo/bar"); + + // This should fail because the directory for indexed_path doesn't exist. + EXPECT_FALSE(IndexAndWriteRuleset(unindexed_path, indexed_path)); +} + +TEST_F(IndexingToolTest, VerifyOutput) { + base::FilePath unindexed_path = GetUniquePath(); + base::FilePath indexed_path = GetUniquePath(); + + CreateSimpleRuleset(); + WriteUnindexedRulesetToFile(unindexed_path); + + // Convert the unindexed data to indexed data, and write the result to + // indexed_path. + EXPECT_TRUE(IndexAndWriteRuleset(unindexed_path, indexed_path)); + + // Verify that the output equals the test indexed data. + std::vector<uint8_t> indexed_data = ReadFileContents(indexed_path); + EXPECT_EQ(test_ruleset_pair_.indexed.contents, indexed_data); +} + +} // namespace + +} // namespace subresource_filter
diff --git a/components/sync/syncable/model_type.cc b/components/sync/syncable/model_type.cc index e67fdac..3386480 100644 --- a/components/sync/syncable/model_type.cc +++ b/components/sync/syncable/model_type.cc
@@ -236,6 +236,7 @@ break; case SUPERVISED_USER_SHARED_SETTINGS: specifics->mutable_managed_user_shared_setting(); + break; case ARTICLES: specifics->mutable_article(); break;
diff --git a/components/translate/core/browser/BUILD.gn b/components/translate/core/browser/BUILD.gn index e1b185f..d4a3cbe 100644 --- a/components/translate/core/browser/BUILD.gn +++ b/components/translate/core/browser/BUILD.gn
@@ -50,6 +50,7 @@ "//components/data_use_measurement/core", "//components/keyed_service/core", "//components/language/core/browser", + "//components/language/core/common", "//components/language_usage_metrics", "//components/metrics", "//components/pref_registry",
diff --git a/components/translate/core/browser/translate_prefs.cc b/components/translate/core/browser/translate_prefs.cc index 7e4373cd..de42244 100644 --- a/components/translate/core/browser/translate_prefs.cc +++ b/components/translate/core/browser/translate_prefs.cc
@@ -17,6 +17,7 @@ #include "base/strings/utf_string_conversions.h" #include "base/values.h" #include "build/build_config.h" +#include "components/language/core/common/locale_util.h" #include "components/pref_registry/pref_registry_syncable.h" #include "components/prefs/pref_service.h" #include "components/prefs/scoped_user_pref_update.h" @@ -100,6 +101,9 @@ const base::Feature kImprovedLanguageSettings{"ImprovedLanguageSettings", base::FEATURE_ENABLED_BY_DEFAULT}; +const base::Feature kRegionalLocalesAsDisplayUI{ + "RegionalLocalesAsDisplayUI", base::FEATURE_DISABLED_BY_DEFAULT}; + const base::Feature kTranslateRecentTarget{"TranslateRecentTarget", base::FEATURE_ENABLED_BY_DEFAULT}; @@ -234,7 +238,7 @@ // language with the same base language. const bool should_block = !base::FeatureList::IsEnabled(kImprovedLanguageSettings) || - !ContainsSameBaseLanguage(languages, chrome_language); + !language::ContainsSameBaseLanguage(languages, chrome_language); if (force_blocked || should_block) { BlockLanguage(input_language); @@ -267,7 +271,7 @@ if (base::FeatureList::IsEnabled(kImprovedLanguageSettings)) { // We should unblock the language if this was the last one from the same // language family. - if (!ContainsSameBaseLanguage(languages, chrome_language)) { + if (!language::ContainsSameBaseLanguage(languages, chrome_language)) { UnblockLanguage(input_language); } }
diff --git a/components/translate/core/browser/translate_prefs.h b/components/translate/core/browser/translate_prefs.h index b00b6bd..0d4b44e 100644 --- a/components/translate/core/browser/translate_prefs.h +++ b/components/translate/core/browser/translate_prefs.h
@@ -35,6 +35,10 @@ // These settings support the new UI. extern const base::Feature kImprovedLanguageSettings; +// Enables or disables the regional locales as valid selection for the display +// UI. +extern const base::Feature kRegionalLocalesAsDisplayUI; + // Enables or disables using the most recent target language as the default // target language option. extern const base::Feature kTranslateRecentTarget;
diff --git a/components/translate/core/common/BUILD.gn b/components/translate/core/common/BUILD.gn index 6e59b894..94491e2 100644 --- a/components/translate/core/common/BUILD.gn +++ b/components/translate/core/common/BUILD.gn
@@ -23,6 +23,7 @@ deps = [ "//base", + "//components/language/core/common", "//components/sync/protocol", "//third_party/metrics_proto", "//url",
diff --git a/components/translate/core/common/translate_util.cc b/components/translate/core/common/translate_util.cc index d45cb77..6e1ec09c 100644 --- a/components/translate/core/common/translate_util.cc +++ b/components/translate/core/common/translate_util.cc
@@ -5,35 +5,17 @@ #include "components/translate/core/common/translate_util.h" #include <stddef.h> +#include <algorithm> +#include <set> +#include <vector> #include "base/command_line.h" #include "base/logging.h" #include "base/macros.h" -#include "base/strings/string_split.h" +#include "components/language/core/common/locale_util.h" #include "components/translate/core/common/translate_switches.h" #include "url/gurl.h" -namespace { - -// Split the |language| into two parts. For example, if |language| is 'en-US', -// this will be split into the main part 'en' and the tail part '-US'. -void SplitIntoMainAndTail(const std::string& language, - std::string* main_part, - std::string* tail_part) { - DCHECK(main_part); - DCHECK(tail_part); - - std::vector<base::StringPiece> chunks = base::SplitStringPiece( - language, "-", base::TRIM_WHITESPACE, base::SPLIT_WANT_ALL); - if (chunks.empty()) - return; - - chunks[0].CopyToString(main_part); - *tail_part = language.substr(main_part->size()); -} - -} // namespace - namespace translate { struct LanguageCodePair { @@ -86,7 +68,7 @@ } std::string main_part, tail_part; - SplitIntoMainAndTail(*language, &main_part, &tail_part); + language::SplitIntoMainAndTail(*language, &main_part, &tail_part); if (main_part.empty()) return; @@ -127,7 +109,7 @@ } std::string main_part, tail_part; - SplitIntoMainAndTail(*language, &main_part, &tail_part); + language::SplitIntoMainAndTail(*language, &main_part, &tail_part); if (main_part.empty()) return; @@ -152,19 +134,4 @@ return GURL(security_origin); } -bool ContainsSameBaseLanguage(const std::vector<std::string>& list, - const std::string& language_code) { - std::string base_language; - std::string unused_str; - SplitIntoMainAndTail(language_code, &base_language, &unused_str); - for (const auto& item : list) { - std::string compare_base; - SplitIntoMainAndTail(item, &compare_base, &unused_str); - if (compare_base == base_language) - return true; - } - - return false; -} - } // namespace translate
diff --git a/components/translate/core/common/translate_util.h b/components/translate/core/common/translate_util.h index e3af8b1d..a7036c5 100644 --- a/components/translate/core/common/translate_util.h +++ b/components/translate/core/common/translate_util.h
@@ -28,12 +28,6 @@ // language checks and to obtain the list of available languages. GURL GetTranslateSecurityOrigin(); -// Returns whether or not the given list includes at least a language with the -// same base as the input language. -// For example: "en-US" and "en-UK" share the same base "en". -bool ContainsSameBaseLanguage(const std::vector<std::string>& list, - const std::string& language_code); - } // namespace translate #endif // COMPONENTS_TRANSLATE_CORE_COMMON_TRANSLATE_UTIL_H_
diff --git a/components/translate/core/common/translate_util_unittest.cc b/components/translate/core/common/translate_util_unittest.cc index 4e6091b..d29f92e1 100644 --- a/components/translate/core/common/translate_util_unittest.cc +++ b/components/translate/core/common/translate_util_unittest.cc
@@ -79,40 +79,3 @@ EXPECT_EQ(running_origin, modified_origin.spec()); } -TEST_F(TranslateUtilTest, ContainsSameBaseLanguage) { - std::vector<std::string> list; - - // Empty input. - EXPECT_EQ(false, translate::ContainsSameBaseLanguage(list, "")); - - // Empty list. - EXPECT_EQ(false, translate::ContainsSameBaseLanguage(list, "fr-FR")); - - // Empty language. - list = {"en-US"}; - EXPECT_EQ(false, translate::ContainsSameBaseLanguage(list, "")); - - // One element, no match. - list = {"en-US"}; - EXPECT_EQ(false, translate::ContainsSameBaseLanguage(list, "fr-FR")); - - // One element, with match. - list = {"fr-CA"}; - EXPECT_EQ(true, translate::ContainsSameBaseLanguage(list, "fr-FR")); - - // Multiple elements, no match. - list = {"en-US", "es-AR", "en-UK"}; - EXPECT_EQ(false, translate::ContainsSameBaseLanguage(list, "fr-FR")); - - // Multiple elements, with match. - list = {"en-US", "fr-CA", "es-AR"}; - EXPECT_EQ(true, translate::ContainsSameBaseLanguage(list, "fr-FR")); - - // Multiple elements matching. - list = {"en-US", "fr-CA", "es-AR", "fr-FR"}; - EXPECT_EQ(true, translate::ContainsSameBaseLanguage(list, "fr-FR")); - - // List includes base language. - list = {"en-US", "fr", "es-AR", "fr-FR"}; - EXPECT_EQ(true, translate::ContainsSameBaseLanguage(list, "fr-FR")); -}
diff --git a/components/user_manager/known_user.cc b/components/user_manager/known_user.cc index 8763f42..b218adb 100644 --- a/components/user_manager/known_user.cc +++ b/components/user_manager/known_user.cc
@@ -61,6 +61,9 @@ // attempted. const char kMinimalMigrationAttempted[] = "minimal_migration_attempted"; +// Key of the boolean flag telling if user session requires policy. +const char kProfileRequiresPolicy[] = "profile_requires_policy"; + PrefService* GetLocalState() { if (!UserManager::IsInitialized()) return nullptr; @@ -480,6 +483,22 @@ SetBooleanPref(account_id, kProfileEverInitialized, initialized); } +void SetProfileRequiresPolicy(const AccountId& account_id, + ProfileRequiresPolicy required) { + DCHECK_NE(required, ProfileRequiresPolicy::kUnknown); + SetBooleanPref(account_id, kProfileRequiresPolicy, + required == ProfileRequiresPolicy::kPolicyRequired); +} + +ProfileRequiresPolicy GetProfileRequiresPolicy(const AccountId& account_id) { + bool requires_policy; + if (GetBooleanPref(account_id, kProfileRequiresPolicy, &requires_policy)) { + return requires_policy ? ProfileRequiresPolicy::kPolicyRequired + : ProfileRequiresPolicy::kNoPolicyRequired; + } + return ProfileRequiresPolicy::kUnknown; +} + void UpdateReauthReason(const AccountId& account_id, const int reauth_reason) { SetIntegerPref(account_id, kReauthReasonKey, reauth_reason); }
diff --git a/components/user_manager/known_user.h b/components/user_manager/known_user.h index 3c3473d..38fed5e 100644 --- a/components/user_manager/known_user.h +++ b/components/user_manager/known_user.h
@@ -138,6 +138,26 @@ void USER_MANAGER_EXPORT SetProfileEverInitialized(const AccountId& account_id, bool initialized); +// Enum describing whether a user's profile requires policy. If kPolicyRequired, +// the profile initialization code will ensure that valid policy is loaded +// before session initialization completes. +enum class ProfileRequiresPolicy { + kUnknown, + kPolicyRequired, + kNoPolicyRequired +}; + +// Returns whether the current profile requires policy or not (returns UNKNOWN +// if the profile has never been initialized and so the policy status is +// not yet known). +ProfileRequiresPolicy USER_MANAGER_EXPORT +GetProfileRequiresPolicy(const AccountId& account_id); + +// Sets whether the profile requires policy or not. +void USER_MANAGER_EXPORT +SetProfileRequiresPolicy(const AccountId& account_id, + ProfileRequiresPolicy policy_required); + // Saves why the user has to go through re-auth flow. void USER_MANAGER_EXPORT UpdateReauthReason(const AccountId& account_id, const int reauth_reason);
diff --git a/components/user_manager/user.h b/components/user_manager/user.h index 1d8fa68..3136871 100644 --- a/components/user_manager/user.h +++ b/components/user_manager/user.h
@@ -158,6 +158,11 @@ // Whether the user's session has completed initialization yet. bool profile_ever_initialized() const { return profile_ever_initialized_; } + // Public so it can be called via tests. + void set_profile_ever_initialized(bool profile_ever_initialized) { + profile_ever_initialized_ = profile_ever_initialized; + } + // True if the user's session can be locked (i.e. the user has a password with // which to unlock the session). bool can_lock() const; @@ -178,6 +183,12 @@ return CreatePublicAccountUser(account_id); } + static User* CreateRegularUserForTesting(const AccountId& account_id) { + User* user = CreateRegularUser(account_id, USER_TYPE_REGULAR); + user->SetImage(std::unique_ptr<UserImage>(new UserImage), 0); + return user; + } + void AddProfileCreatedObserver(base::OnceClosure on_profile_created); protected: @@ -245,10 +256,6 @@ force_online_signin_ = force_online_signin; } - void set_profile_ever_initialized(bool profile_ever_initialized) { - profile_ever_initialized_ = profile_ever_initialized; - } - void set_username_hash(const std::string& username_hash) { username_hash_ = username_hash; }
diff --git a/components/variations/BUILD.gn b/components/variations/BUILD.gn index 991ea3f..9952ce1 100644 --- a/components/variations/BUILD.gn +++ b/components/variations/BUILD.gn
@@ -151,7 +151,6 @@ "proto", "//base/test:test_support", "//components/prefs:test_support", - "//components/variations/field_trial_config:unit_tests", "//testing/gtest", "//third_party/zlib/google:compression_utils", ] @@ -165,6 +164,7 @@ deps = [ ":unit_tests", "//components/test:test_support", + "//components/variations/field_trial_config:unit_tests", "//components/variations/service:unit_tests", ] }
diff --git a/components/variations/pref_names.cc b/components/variations/pref_names.cc index dd4fdea..29ae37e 100644 --- a/components/variations/pref_names.cc +++ b/components/variations/pref_names.cc
@@ -24,7 +24,7 @@ "variations_failed_to_fetch_seed_streak"; // The serialized base::Time from the last successful seed fetch (i.e. when the -// Variations server responds with 200 or 304). +// Variations server responds with 200 or 304). This is a client timestamp. const char kVariationsLastFetchTime[] = "variations_last_fetch_time"; // Pair of <Chrome version string, country code string> representing the country @@ -49,11 +49,22 @@ // https://docs.google.com/document/d/17UN2pLSa5JZqk8f3LeYZIftXewxqcITotgalTrJvGSY const char kVariationsSafeCompressedSeed[] = "variations_safe_compressed_seed"; -// The serialized base::Time at which the last known "safe" seed was received. -// An empty/default-constructed base::Time time if there is no known "safe" -// seed. +// The serialized base::Time used for safe seed expiry checks. This is usually +// the time at which the last known "safe" seed was received, though it could +// potentially be a build timestamp instead, if the received date is unknown. An +// empty (default-constructed) base::Time if there is no known "safe" seed. This +// is a server-provided timestamp. const char kVariationsSafeSeedDate[] = "variations_safe_seed_date"; +// The serialized base::Time from the fetch corresponding to the safe seed, i.e. +// a copy of the last value stored to the |kVariationsLastFetchTime| pref that +// corresponded to the same seed contents as the safe seed. This is a client +// timestamp. +// Note: This pref was added about a milestone after most of the other safe seed +// prefs, and so might be missing for some clients that otherwise have safe seed +// data. +const char kVariationsSafeSeedFetchTime[] = "variations_safe_seed_fetch_time"; + // The active client locale that was successfully used in association with the // last known "safe" seed. const char kVariationsSafeSeedLocale[] = "variations_safe_seed_locale"; @@ -74,7 +85,8 @@ // base64-encoded. Empty if there is no known "safe" seed. const char kVariationsSafeSeedSignature[] = "variations_safe_seed_signature"; -// The serialized base::Time from the last seed received. +// The serialized base::Time from the last seed received. This is a +// server-provided timestamp. const char kVariationsSeedDate[] = "variations_seed_date"; // Digital signature of the binary variations seed data, base64-encoded.
diff --git a/components/variations/pref_names.h b/components/variations/pref_names.h index c9d18c5d..8cc76f3 100644 --- a/components/variations/pref_names.h +++ b/components/variations/pref_names.h
@@ -21,6 +21,7 @@ extern const char kVariationsRestrictParameter[]; extern const char kVariationsSafeCompressedSeed[]; extern const char kVariationsSafeSeedDate[]; +extern const char kVariationsSafeSeedFetchTime[]; extern const char kVariationsSafeSeedLocale[]; extern const char kVariationsSafeSeedPermanentConsistencyCountry[]; extern const char kVariationsSafeSeedSessionConsistencyCountry[];
diff --git a/components/variations/service/safe_seed_manager.cc b/components/variations/service/safe_seed_manager.cc index 8aa6b18..2ab7760 100644 --- a/components/variations/service/safe_seed_manager.cc +++ b/components/variations/service/safe_seed_manager.cc
@@ -65,12 +65,14 @@ void SafeSeedManager::SetActiveSeedState( const std::string& seed_data, const std::string& base64_seed_signature, - std::unique_ptr<ClientFilterableState> client_filterable_state) { + std::unique_ptr<ClientFilterableState> client_filterable_state, + base::Time seed_fetch_time) { DCHECK(!has_set_active_seed_state_); has_set_active_seed_state_ = true; active_seed_state_ = std::make_unique<ActiveSeedState>( - seed_data, base64_seed_signature, std::move(client_filterable_state)); + seed_data, base64_seed_signature, std::move(client_filterable_state), + seed_fetch_time); } void SafeSeedManager::RecordFetchStarted() { @@ -92,7 +94,8 @@ if (active_seed_state_) { seed_store->StoreSafeSeed(active_seed_state_->seed_data, active_seed_state_->base64_seed_signature, - *active_seed_state_->client_filterable_state); + *active_seed_state_->client_filterable_state, + active_seed_state_->seed_fetch_time); // The active seed state is only needed for the first time this code path is // reached, so free up its memory once the data is no longer needed. @@ -110,10 +113,12 @@ SafeSeedManager::ActiveSeedState::ActiveSeedState( const std::string& seed_data, const std::string& base64_seed_signature, - std::unique_ptr<ClientFilterableState> client_filterable_state) + std::unique_ptr<ClientFilterableState> client_filterable_state, + base::Time seed_fetch_time) : seed_data(seed_data), base64_seed_signature(base64_seed_signature), - client_filterable_state(std::move(client_filterable_state)) {} + client_filterable_state(std::move(client_filterable_state)), + seed_fetch_time(seed_fetch_time) {} SafeSeedManager::ActiveSeedState::~ActiveSeedState() = default;
diff --git a/components/variations/service/safe_seed_manager.h b/components/variations/service/safe_seed_manager.h index 7efd6cc6..5855f7a0 100644 --- a/components/variations/service/safe_seed_manager.h +++ b/components/variations/service/safe_seed_manager.h
@@ -9,6 +9,7 @@ #include <string> #include "base/macros.h" +#include "base/time/time.h" class PrefRegistrySimple; class PrefService; @@ -41,7 +42,8 @@ virtual void SetActiveSeedState( const std::string& seed_data, const std::string& base64_seed_signature, - std::unique_ptr<ClientFilterableState> client_filterable_state); + std::unique_ptr<ClientFilterableState> client_filterable_state, + base::Time seed_fetch_time); // Records that a fetch has started: pessimistically increments the // corresponding failure streak for safe mode. @@ -59,7 +61,8 @@ ActiveSeedState( const std::string& seed_data, const std::string& base64_seed_signature, - std::unique_ptr<ClientFilterableState> client_filterable_state); + std::unique_ptr<ClientFilterableState> client_filterable_state, + base::Time seed_fetch_time); ~ActiveSeedState(); // The serialized variations seed data. @@ -70,6 +73,10 @@ // The client state which is used for filtering studies. const std::unique_ptr<ClientFilterableState> client_filterable_state; + + // The latest timestamp at which this seed was fetched. This is always a + // client-side timestamp, never a server-provided timestamp. + const base::Time seed_fetch_time; }; std::unique_ptr<ActiveSeedState> active_seed_state_;
diff --git a/components/variations/service/safe_seed_manager_unittest.cc b/components/variations/service/safe_seed_manager_unittest.cc index c564cb22..5820e41e 100644 --- a/components/variations/service/safe_seed_manager_unittest.cc +++ b/components/variations/service/safe_seed_manager_unittest.cc
@@ -27,6 +27,10 @@ const char kTestPermanentConsistencyCountry[] = "US"; const char kTestSessionConsistencyCountry[] = "CA"; +base::Time GetTestFetchTime() { + return base::Time::FromDeltaSinceWindowsEpoch(base::TimeDelta::FromDays(123)); +} + // A simple fake data store. class FakeSeedStore : public VariationsSeedStore { public: @@ -35,13 +39,15 @@ bool StoreSafeSeed(const std::string& seed_data, const std::string& base64_seed_signature, - const ClientFilterableState& client_state) override { + const ClientFilterableState& client_state, + base::Time seed_fetch_time) override { seed_data_ = seed_data; signature_ = base64_seed_signature; date_ = client_state.reference_date; locale_ = client_state.locale; permanent_consistency_country_ = client_state.permanent_consistency_country; session_consistency_country_ = client_state.session_consistency_country; + fetch_time_ = seed_fetch_time; return true; } @@ -55,6 +61,7 @@ const std::string& session_consistency_country() const { return session_consistency_country_; } + const base::Time& fetch_time() const { return fetch_time_; } private: // The stored data. @@ -64,6 +71,7 @@ std::string locale_; std::string permanent_consistency_country_; std::string session_consistency_country_; + base::Time fetch_time_; DISALLOW_COPY_AND_ASSIGN(FakeSeedStore); }; @@ -79,8 +87,8 @@ client_state->session_consistency_country = kTestSessionConsistencyCountry; client_state->reference_date = base::Time::UnixEpoch(); - safe_seed_manager->SetActiveSeedState(kTestSeed, kTestSignature, - std::move(client_state)); + safe_seed_manager->SetActiveSeedState( + kTestSeed, kTestSignature, std::move(client_state), GetTestFetchTime()); } // Verifies that the default test values were written to the seed store. @@ -93,6 +101,7 @@ EXPECT_EQ(kTestSessionConsistencyCountry, seed_store.session_consistency_country()); EXPECT_EQ(base::Time::UnixEpoch(), seed_store.date()); + EXPECT_EQ(GetTestFetchTime(), seed_store.fetch_time()); } } // namespace @@ -142,6 +151,7 @@ EXPECT_EQ(std::string(), seed_store.permanent_consistency_country()); EXPECT_EQ(std::string(), seed_store.session_consistency_country()); EXPECT_EQ(base::Time(), seed_store.date()); + EXPECT_EQ(base::Time(), seed_store.fetch_time()); } TEST_F(SafeSeedManagerTest, StreakMetrics_NoPrefs) {
diff --git a/components/variations/service/variations_field_trial_creator.cc b/components/variations/service/variations_field_trial_creator.cc index fb2ba6b..59df076 100644 --- a/components/variations/service/variations_field_trial_creator.cc +++ b/components/variations/service/variations_field_trial_creator.cc
@@ -33,6 +33,7 @@ #include "ui/base/device_form_factor.h" namespace variations { +namespace { // Maximum age permitted for a variations seed, in days. const int kMaxVariationsSeedAgeDays = 30; @@ -141,6 +142,14 @@ VARIATIONS_SEED_EXPIRY_ENUM_SIZE); } +// Records the loaded seed's age to an UMA histogram. +void RecordSeedFreshness(base::TimeDelta seed_age) { + UMA_HISTOGRAM_CUSTOM_COUNTS("Variations.SeedFreshness", seed_age.InMinutes(), + 1, base::TimeDelta::FromDays(30).InMinutes(), 50); +} + +} // namespace + VariationsFieldTrialCreator::VariationsFieldTrialCreator( PrefService* local_state, VariationsServiceClient* client, @@ -181,11 +190,9 @@ std::unique_ptr<ClientFilterableState> client_filterable_state = GetClientFilterableStateForVersion(current_version); - // TODO(isherman): Record the seed freshness when running in safe mode. VariationsSeed seed; - bool run_in_safe_mode = - safe_seed_manager->ShouldRunInSafeMode() && - GetSeedStore()->LoadSafeSeed(&seed, client_filterable_state.get()); + bool run_in_safe_mode = safe_seed_manager->ShouldRunInSafeMode() && + LoadSafeSeed(&seed, client_filterable_state.get()); std::string seed_data; std::string base64_seed_signature; @@ -211,7 +218,8 @@ // to save the active state to the safe seed prefs. if (!run_in_safe_mode) { safe_seed_manager->SetActiveSeedState(seed_data, base64_seed_signature, - std::move(client_filterable_state)); + std::move(client_filterable_state), + seed_store_.GetLastFetchTime()); } UMA_HISTOGRAM_TIMES("Variations.SeedProcessingTime", @@ -331,12 +339,6 @@ new_list_value); } -void VariationsFieldTrialCreator::RecordLastFetchTime() { - DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); - - local_state()->SetTime(prefs::kVariationsLastFetchTime, base::Time::Now()); -} - void VariationsFieldTrialCreator::OverrideVariationsPlatform( Study::Platform platform_override) { has_platform_override_ = true; @@ -349,12 +351,11 @@ if (!GetSeedStore()->LoadSeed(seed, seed_data, base64_signature)) return false; - const base::Time last_fetch_time = - local_state()->GetTime(prefs::kVariationsLastFetchTime); + const base::Time last_fetch_time = seed_store_.GetLastFetchTime(); if (last_fetch_time.is_null()) { // If the last fetch time is missing and we have a seed, then this must be // the first run of Chrome. Store the current time as the last fetch time. - RecordLastFetchTime(); + seed_store_.RecordLastFetchTime(); RecordCreateTrialsSeedExpiry(VARIATIONS_SEED_EXPIRY_FETCH_TIME_MISSING); return true; } @@ -368,8 +369,24 @@ // Record that a suitably fresh seed was loaded. RecordCreateTrialsSeedExpiry(VARIATIONS_SEED_EXPIRY_NOT_EXPIRED); - UMA_HISTOGRAM_CUSTOM_COUNTS("Variations.SeedFreshness", seed_age.InMinutes(), - 1, base::TimeDelta::FromDays(30).InMinutes(), 50); + RecordSeedFreshness(seed_age); + return true; +} + +bool VariationsFieldTrialCreator::LoadSafeSeed( + VariationsSeed* seed, + ClientFilterableState* client_state) { + base::Time safe_seed_fetch_time; + if (!GetSeedStore()->LoadSafeSeed(seed, client_state, &safe_seed_fetch_time)) + return false; + + // Record the safe seed's age. Note, however, that the safe seed fetch time + // pref was added about a milestone later than most of the other safe seed + // prefs, so it might be absent. If it's absent, don't attempt to guess what + // value to record; just skip recording the metric. + if (!safe_seed_fetch_time.is_null()) + RecordSeedFreshness(base::Time::Now() - safe_seed_fetch_time); + return true; }
diff --git a/components/variations/service/variations_field_trial_creator.h b/components/variations/service/variations_field_trial_creator.h index 23b7c0b2..25f205c 100644 --- a/components/variations/service/variations_field_trial_creator.h +++ b/components/variations/service/variations_field_trial_creator.h
@@ -94,7 +94,13 @@ // contain the raw pref values. bool LoadSeed(VariationsSeed* seed, std::string* seed_data, - std::string* base64_signature); + std::string* base64_signature) WARN_UNUSED_RESULT; + + // Loads the safe seed from the variations store into |seed| and updates any + // relevant fields in |client_state|. If the load succeeds, records metrics + // about the loaded seed. Returns whether the load succeeded. + bool LoadSafeSeed(VariationsSeed* seed, + ClientFilterableState* client_state) WARN_UNUSED_RESULT; // Creates field trials based on the variations seed loaded from local state. // If there is a problem loading the seed data, all trials specified by the
diff --git a/components/variations/service/variations_field_trial_creator_unittest.cc b/components/variations/service/variations_field_trial_creator_unittest.cc index 920b1b1..2c2e5a44 100644 --- a/components/variations/service/variations_field_trial_creator_unittest.cc +++ b/components/variations/service/variations_field_trial_creator_unittest.cc
@@ -22,6 +22,7 @@ #include "testing/gtest/include/gtest/gtest.h" using testing::_; +using testing::Ge; using testing::Return; namespace variations { @@ -89,17 +90,19 @@ ~MockSafeSeedManager() override = default; MOCK_CONST_METHOD0(ShouldRunInSafeMode, bool()); - MOCK_METHOD3(DoSetActiveSeedState, + MOCK_METHOD4(DoSetActiveSeedState, void(const std::string& seed_data, const std::string& base64_seed_signature, - ClientFilterableState* client_filterable_state)); + ClientFilterableState* client_filterable_state, + base::Time seed_fetch_time)); void SetActiveSeedState( const std::string& seed_data, const std::string& base64_seed_signature, - std::unique_ptr<ClientFilterableState> client_filterable_state) override { + std::unique_ptr<ClientFilterableState> client_filterable_state, + base::Time seed_fetch_time) override { DoSetActiveSeedState(seed_data, base64_seed_signature, - client_filterable_state.get()); + client_filterable_state.get(), seed_fetch_time); } private: @@ -146,7 +149,7 @@ class TestVariationsSeedStore : public VariationsSeedStore { public: TestVariationsSeedStore(PrefService* local_state) - : VariationsSeedStore(local_state) {} + : VariationsSeedStore(local_state), local_state_(local_state) {} ~TestVariationsSeedStore() override = default; bool LoadSeed(VariationsSeed* seed, @@ -159,11 +162,14 @@ } bool LoadSafeSeed(VariationsSeed* seed, - ClientFilterableState* client_state) override { + ClientFilterableState* client_state, + base::Time* seed_fetch_time) override { if (has_corrupted_safe_seed_) return false; *seed = CreateTestSafeSeed(); + *seed_fetch_time = + local_state_->GetTime(prefs::kVariationsSafeSeedFetchTime); return true; } @@ -175,6 +181,8 @@ // Whether to simulate having a corrupted safe seed. bool has_corrupted_safe_seed_ = false; + PrefService* local_state_; + DISALLOW_COPY_AND_ASSIGN(TestVariationsSeedStore); }; @@ -244,43 +252,49 @@ TEST_F(FieldTrialCreatorTest, SetupFieldTrials_ValidSeed) { // With a valid seed, the safe seed manager should be informed of the active // seed state. + const base::Time now = base::Time::Now(); + const base::Time recent_time = now - base::TimeDelta::FromMinutes(17); testing::NiceMock<MockSafeSeedManager> safe_seed_manager(&prefs_); ON_CALL(safe_seed_manager, ShouldRunInSafeMode()) .WillByDefault(Return(false)); - EXPECT_CALL(safe_seed_manager, - DoSetActiveSeedState(kTestSeedData, kTestSeedSignature, _)) + EXPECT_CALL( + safe_seed_manager, + DoSetActiveSeedState(kTestSeedData, kTestSeedSignature, _, recent_time)) .Times(1); - base::HistogramTester histogram_tester; TestVariationsServiceClient variations_service_client; TestVariationsFieldTrialCreator field_trial_creator( &prefs_, &variations_service_client, &safe_seed_manager); // Simulate a seed having been stored recently. - prefs_.SetTime(prefs::kVariationsLastFetchTime, base::Time::Now()); + prefs_.SetTime(prefs::kVariationsLastFetchTime, recent_time); // Check that field trials are created from the seed. Since the test study has // only 1 experiment with 100% probability weight, we must be part of it. + base::HistogramTester histogram_tester; EXPECT_TRUE(field_trial_creator.SetupFieldTrials()); EXPECT_EQ(kTestSeedExperimentName, base::FieldTrialList::FindFullName(kTestSeedStudyName)); // Verify metrics. + histogram_tester.ExpectUniqueSample("Variations.SeedFreshness", 17, 1); histogram_tester.ExpectUniqueSample("Variations.SafeMode.FellBackToSafeMode2", false, 1); } TEST_F(FieldTrialCreatorTest, SetupFieldTrials_NoLastFetchTime) { // With a valid seed on first run, the safe seed manager should be informed of - // the active seed state. + // the active seed state. The last fetch time in this case is expected to be + // inferred to be recent. testing::NiceMock<MockSafeSeedManager> safe_seed_manager(&prefs_); ON_CALL(safe_seed_manager, ShouldRunInSafeMode()) .WillByDefault(Return(false)); + const base::Time start_time = base::Time::Now(); EXPECT_CALL(safe_seed_manager, - DoSetActiveSeedState(kTestSeedData, kTestSeedSignature, _)) + DoSetActiveSeedState(kTestSeedData, kTestSeedSignature, _, + Ge(start_time))) .Times(1); - base::HistogramTester histogram_tester; TestVariationsServiceClient variations_service_client; TestVariationsFieldTrialCreator field_trial_creator( &prefs_, &variations_service_client, &safe_seed_manager); @@ -290,11 +304,14 @@ // Check that field trials are created from the seed. Since the test study has // only 1 experiment with 100% probability weight, we must be part of it. + base::HistogramTester histogram_tester; EXPECT_TRUE(field_trial_creator.SetupFieldTrials()); EXPECT_EQ(base::FieldTrialList::FindFullName(kTestSeedStudyName), kTestSeedExperimentName); - // Verify metrics. + // Verify metrics. The seed freshness metric should not be recorded on first + // run. + histogram_tester.ExpectTotalCount("Variations.SeedFreshness", 0); histogram_tester.ExpectUniqueSample("Variations.SafeMode.FellBackToSafeMode2", false, 1); } @@ -305,9 +322,8 @@ testing::NiceMock<MockSafeSeedManager> safe_seed_manager(&prefs_); ON_CALL(safe_seed_manager, ShouldRunInSafeMode()) .WillByDefault(Return(false)); - EXPECT_CALL(safe_seed_manager, DoSetActiveSeedState(_, _, _)).Times(0); + EXPECT_CALL(safe_seed_manager, DoSetActiveSeedState(_, _, _, _)).Times(0); - base::HistogramTester histogram_tester; TestVariationsServiceClient variations_service_client; TestVariationsFieldTrialCreator field_trial_creator( &prefs_, &variations_service_client, &safe_seed_manager); @@ -318,10 +334,13 @@ prefs_.SetTime(prefs::kVariationsLastFetchTime, seed_date); // Check that field trials are not created from the expired seed. + base::HistogramTester histogram_tester; EXPECT_FALSE(field_trial_creator.SetupFieldTrials()); EXPECT_TRUE(base::FieldTrialList::FindFullName(kTestSeedStudyName).empty()); - // Verify metrics. + // Verify metrics. The seed freshness metric should not be recorded for an + // expired seed. + histogram_tester.ExpectTotalCount("Variations.SeedFreshness", 0); histogram_tester.ExpectTotalCount("Variations.SafeMode.FellBackToSafeMode2", 0); } @@ -332,21 +351,26 @@ // when already running in safe mode. testing::NiceMock<MockSafeSeedManager> safe_seed_manager(&prefs_); ON_CALL(safe_seed_manager, ShouldRunInSafeMode()).WillByDefault(Return(true)); - EXPECT_CALL(safe_seed_manager, DoSetActiveSeedState(_, _, _)).Times(0); + EXPECT_CALL(safe_seed_manager, DoSetActiveSeedState(_, _, _, _)).Times(0); - base::HistogramTester histogram_tester; + const base::Time now = base::Time::Now(); + const base::Time earlier = now - base::TimeDelta::FromMinutes(17); TestVariationsServiceClient variations_service_client; TestVariationsFieldTrialCreator field_trial_creator( &prefs_, &variations_service_client, &safe_seed_manager); + prefs_.SetTime(prefs::kVariationsLastFetchTime, now); + prefs_.SetTime(prefs::kVariationsSafeSeedFetchTime, earlier); // Check that field trials are created from the safe seed. Since the test // study has only 1 experiment with 100% probability weight, we must be part // of it. + base::HistogramTester histogram_tester; EXPECT_TRUE(field_trial_creator.SetupFieldTrials()); EXPECT_EQ(kTestSafeSeedExperimentName, base::FieldTrialList::FindFullName(kTestSeedStudyName)); // Verify metrics. + histogram_tester.ExpectUniqueSample("Variations.SeedFreshness", 17, 1); histogram_tester.ExpectUniqueSample("Variations.SafeMode.FellBackToSafeMode2", true, 1); } @@ -356,26 +380,33 @@ // With a corrupted safe seed, the field trial creator should fall back to the // latest seed. Hence, the safe seed manager *should* be informed of the // active seed state. + const base::Time now = base::Time::Now(); + const base::Time recent_time = now - base::TimeDelta::FromMinutes(17); testing::NiceMock<MockSafeSeedManager> safe_seed_manager(&prefs_); ON_CALL(safe_seed_manager, ShouldRunInSafeMode()).WillByDefault(Return(true)); - EXPECT_CALL(safe_seed_manager, - DoSetActiveSeedState(kTestSeedData, kTestSeedSignature, _)) + EXPECT_CALL( + safe_seed_manager, + DoSetActiveSeedState(kTestSeedData, kTestSeedSignature, _, recent_time)) .Times(1); - base::HistogramTester histogram_tester; TestVariationsServiceClient variations_service_client; TestVariationsFieldTrialCreator field_trial_creator( &prefs_, &variations_service_client, &safe_seed_manager); field_trial_creator.seed_store()->set_has_corrupted_safe_seed(true); + prefs_.SetTime(prefs::kVariationsLastFetchTime, recent_time); + prefs_.SetTime(prefs::kVariationsSafeSeedFetchTime, + now - base::TimeDelta::FromDays(4)); // Check that field trials are created from the latest seed. Since the test // study has only 1 experiment with 100% probability weight, we must be part // of it. + base::HistogramTester histogram_tester; EXPECT_TRUE(field_trial_creator.SetupFieldTrials()); EXPECT_EQ(kTestSeedExperimentName, base::FieldTrialList::FindFullName(kTestSeedStudyName)); // Verify metrics. + histogram_tester.ExpectUniqueSample("Variations.SeedFreshness", 17, 1); histogram_tester.ExpectUniqueSample("Variations.SafeMode.FellBackToSafeMode2", false, 1); }
diff --git a/components/variations/service/variations_service.cc b/components/variations/service/variations_service.cc index 4159d2c..11f36e5 100644 --- a/components/variations/service/variations_service.cc +++ b/components/variations/service/variations_service.cc
@@ -376,7 +376,6 @@ SafeSeedManager::RegisterPrefs(registry); VariationsSeedStore::RegisterPrefs(registry); - registry->RegisterTimePref(prefs::kVariationsLastFetchTime, base::Time()); // This preference will only be written by the policy service, which will fill // it according to a value stored in the User Policy. registry->RegisterStringPref(prefs::kVariationsRestrictParameter, @@ -738,7 +737,7 @@ } void VariationsService::RecordSuccessfulFetch() { - field_trial_creator_.RecordLastFetchTime(); + field_trial_creator_.seed_store()->RecordLastFetchTime(); safe_seed_manager_.RecordSuccessfulFetch(field_trial_creator_.seed_store()); }
diff --git a/components/variations/variations_seed_store.cc b/components/variations/variations_seed_store.cc index 7358eb2..a48d473 100644 --- a/components/variations/variations_seed_store.cc +++ b/components/variations/variations_seed_store.cc
@@ -26,7 +26,6 @@ #endif // OS_ANDROID namespace variations { - namespace { // The ECDSA public key of the variations server for verifying variations seed @@ -41,6 +40,11 @@ 0x2b, 0xff, 0x82, 0x4d, 0xd3, 0xfe, 0xc5, 0xef, 0x20, 0xc6, 0xa3, 0x10, 0xbf, }; +// A sentinel value that may be stored as the latest variations seed value in +// prefs to indicate that the latest seed is identical to the safe seed. Used to +// avoid duplicating storage space. +constexpr char kIdenticalToSafeSeedSentinel[] = "safe_seed_content"; + // Verifies a variations seed (the serialized proto bytes) with the specified // base-64 encoded signature that was received from the server and returns the // result. The signature is assumed to be an "ECDSA with SHA-256" signature @@ -210,7 +214,8 @@ } bool VariationsSeedStore::LoadSafeSeed(VariationsSeed* seed, - ClientFilterableState* client_state) { + ClientFilterableState* client_state, + base::Time* seed_fetch_time) { std::string unused_seed_data; std::string unused_base64_seed_signature; LoadSeedResult result = LoadSeedImpl(SeedType::SAFE, seed, &unused_seed_data, @@ -227,13 +232,15 @@ prefs::kVariationsSafeSeedPermanentConsistencyCountry); client_state->session_consistency_country = local_state_->GetString( prefs::kVariationsSafeSeedSessionConsistencyCountry); + *seed_fetch_time = local_state_->GetTime(prefs::kVariationsSafeSeedFetchTime); return true; } bool VariationsSeedStore::StoreSafeSeed( const std::string& seed_data, const std::string& base64_seed_signature, - const ClientFilterableState& client_state) { + const ClientFilterableState& client_state, + base::Time seed_fetch_time) { std::string base64_seed_data; StoreSeedResult result = VerifyAndCompressSeedData( seed_data, base64_seed_signature, false /* fetched_insecurely */, @@ -243,11 +250,43 @@ if (result != StoreSeedResult::SUCCESS) return false; - local_state_->SetString(prefs::kVariationsSafeCompressedSeed, - base64_seed_data); + // The sentinel value should only ever be saved in place of the latest seed -- + // it should never be saved in place of the safe seed. + DCHECK_NE(base64_seed_data, kIdenticalToSafeSeedSentinel); + + // As a performance optimization, avoid an expensive no-op of overwriting the + // previous safe seed with an identical copy. + std::string previous_safe_seed = + local_state_->GetString(prefs::kVariationsSafeCompressedSeed); + if (base64_seed_data != previous_safe_seed) { + // It's theoretically possible to overwrite an existing safe seed value, + // which was identical to the latest seed, with a new value. This could + // happen, for example, if: + // (1) Seed A is received from the server and saved as both the safe and + // latest seed value. + // (2) Seed B is received from the server and saved as the latest seed + // value. + // (3) The user restarts Chrome, which is now running with the + // configuration from seed B. + // (4) Seed A is received again from the server, perhaps due to a + // rollback. + // In this situation, seed A should be saved as the latest seed, while seed + // B should be saved as the safe seed, i.e. the previously saved values + // should be swapped. Indeed, it is guaranteed that the latest seed value + // should be overwritten in this case, as a seed should not be considered + // safe unless a new seed can be both received *and saved* from the server. + std::string latest_seed = + local_state_->GetString(prefs::kVariationsCompressedSeed); + if (latest_seed == kIdenticalToSafeSeedSentinel) { + local_state_->SetString(prefs::kVariationsCompressedSeed, + previous_safe_seed); + } + local_state_->SetString(prefs::kVariationsSafeCompressedSeed, + base64_seed_data); + } + local_state_->SetString(prefs::kVariationsSafeSeedSignature, base64_seed_signature); - local_state_->SetTime(prefs::kVariationsSafeSeedDate, client_state.reference_date); local_state_->SetString(prefs::kVariationsSafeSeedLocale, @@ -256,9 +295,39 @@ client_state.permanent_consistency_country); local_state_->SetString(prefs::kVariationsSafeSeedSessionConsistencyCountry, client_state.session_consistency_country); + + // As a space optimization, overwrite the stored latest seed data with an + // alias to the safe seed, if they are identical. + if (base64_seed_data == + local_state_->GetString(prefs::kVariationsCompressedSeed)) { + local_state_->SetString(prefs::kVariationsCompressedSeed, + kIdenticalToSafeSeedSentinel); + + // Moreover, in this case, the last fetch time for the safe seed should + // match the latest seed's. + seed_fetch_time = GetLastFetchTime(); + } + local_state_->SetTime(prefs::kVariationsSafeSeedFetchTime, seed_fetch_time); + return true; } +base::Time VariationsSeedStore::GetLastFetchTime() const { + return local_state_->GetTime(prefs::kVariationsLastFetchTime); +} + +void VariationsSeedStore::RecordLastFetchTime() { + base::Time now = base::Time::Now(); + local_state_->SetTime(prefs::kVariationsLastFetchTime, now); + + // If the latest and safe seeds are identical, update the fetch time for the + // safe seed as well. + if (local_state_->GetString(prefs::kVariationsCompressedSeed) == + kIdenticalToSafeSeedSentinel) { + local_state_->SetTime(prefs::kVariationsSafeSeedFetchTime, now); + } +} + void VariationsSeedStore::UpdateSeedDateAndLogDayChange( const base::Time& server_date_fetched) { UpdateSeedDateResult result = UpdateSeedDateResult::NO_OLD_DATE; @@ -297,6 +366,7 @@ void VariationsSeedStore::RegisterPrefs(PrefRegistrySimple* registry) { registry->RegisterStringPref(prefs::kVariationsCompressedSeed, std::string()); registry->RegisterStringPref(prefs::kVariationsCountry, std::string()); + registry->RegisterTimePref(prefs::kVariationsLastFetchTime, base::Time()); registry->RegisterTimePref(prefs::kVariationsSeedDate, base::Time()); registry->RegisterStringPref(prefs::kVariationsSeedSignature, std::string()); @@ -304,6 +374,7 @@ registry->RegisterStringPref(prefs::kVariationsSafeCompressedSeed, std::string()); registry->RegisterTimePref(prefs::kVariationsSafeSeedDate, base::Time()); + registry->RegisterTimePref(prefs::kVariationsSafeSeedFetchTime, base::Time()); registry->RegisterStringPref(prefs::kVariationsSafeSeedLocale, std::string()); registry->RegisterStringPref( prefs::kVariationsSafeSeedPermanentConsistencyCountry, std::string()); @@ -327,6 +398,7 @@ void VariationsSeedStore::ClearPrefs(SeedType seed_type) { if (seed_type == SeedType::LATEST) { local_state_->ClearPref(prefs::kVariationsCompressedSeed); + local_state_->ClearPref(prefs::kVariationsLastFetchTime); local_state_->ClearPref(prefs::kVariationsSeedDate); local_state_->ClearPref(prefs::kVariationsSeedSignature); return; @@ -335,6 +407,7 @@ DCHECK_EQ(seed_type, SeedType::SAFE); local_state_->ClearPref(prefs::kVariationsSafeCompressedSeed); local_state_->ClearPref(prefs::kVariationsSafeSeedDate); + local_state_->ClearPref(prefs::kVariationsSafeSeedFetchTime); local_state_->ClearPref(prefs::kVariationsSafeSeedLocale); local_state_->ClearPref( prefs::kVariationsSafeSeedPermanentConsistencyCountry); @@ -423,6 +496,13 @@ if (base64_seed_data.empty()) return LoadSeedResult::EMPTY; + // As a space optimization, the latest seed might not be stored directly, but + // rather aliased to the safe seed. + if (seed_type == SeedType::LATEST && + base64_seed_data == kIdenticalToSafeSeedSentinel) { + return ReadSeedData(SeedType::SAFE, seed_data); + } + // If the decode process fails, assume the pref value is corrupt and clear it. std::string decoded_data; if (!base::Base64Decode(base64_seed_data, &decoded_data)) { @@ -469,6 +549,13 @@ if (!country_code.empty()) local_state_->SetString(prefs::kVariationsCountry, country_code); + // As a space optimization, store an alias to the safe seed if the contents + // are identical. + if (base64_seed_data == + local_state_->GetString(prefs::kVariationsSafeCompressedSeed)) { + base64_seed_data = kIdenticalToSafeSeedSentinel; + } + local_state_->SetString(prefs::kVariationsCompressedSeed, base64_seed_data); UpdateSeedDateAndLogDayChange(date_fetched); local_state_->SetString(prefs::kVariationsSeedSignature,
diff --git a/components/variations/variations_seed_store.h b/components/variations/variations_seed_store.h index 1e83570..56bd21d 100644 --- a/components/variations/variations_seed_store.h +++ b/components/variations/variations_seed_store.h
@@ -59,15 +59,16 @@ VariationsSeed* parsed_seed) WARN_UNUSED_RESULT; // Loads the safe variations seed data from local state into |seed| and - // updates any relevant fields in |client_state|. Returns true iff the safe - // seed was read successfully from prefs. If the safe seed could not be - // loaded, it is guaranteed that no fields in |client_state| are modified. + // updates any relevant fields in |client_state| and stores the + // |seed_fetch_time|. Returns true iff the safe seed was read successfully + // from prefs. If the safe seed could not be loaded, it is guaranteed that no + // fields in |client_state| are modified. // Side-effect: Upon any failure to read or validate the safe seed, clears all // of the safe seed pref values. This occurs iff the method returns false. // Virtual for testing. virtual bool LoadSafeSeed(VariationsSeed* seed, - ClientFilterableState* client_state) - WARN_UNUSED_RESULT; + ClientFilterableState* client_state, + base::Time* seed_fetch_time) WARN_UNUSED_RESULT; // Stores the given |seed_data| (a serialized protobuf) to local state as a // safe seed, along with a base64-encoded digital signature for seed and any @@ -76,7 +77,17 @@ // Virtual for testing. virtual bool StoreSafeSeed(const std::string& seed_data, const std::string& base64_seed_signature, - const ClientFilterableState& client_state); + const ClientFilterableState& client_state, + base::Time seed_fetch_time); + + // Loads the last fetch time (for the latest seed) that was persisted to the + // store. + base::Time GetLastFetchTime() const; + + // Records the current time as the last time at which a seed was fetched + // successfully. Also updates the safe seed's fetch time if the latest and + // safe seeds are identical. + void RecordLastFetchTime(); // Updates |kVariationsSeedDate| and logs when previous date was from a // different day. @@ -97,7 +108,6 @@ static void RegisterPrefs(PrefRegistrySimple* registry); PrefService* local_state() { return local_state_; } - const PrefService* local_state() const { return local_state_; } protected:
diff --git a/components/variations/variations_seed_store_unittest.cc b/components/variations/variations_seed_store_unittest.cc index ce77e3c..8173ec6 100644 --- a/components/variations/variations_seed_store_unittest.cc +++ b/components/variations/variations_seed_store_unittest.cc
@@ -40,6 +40,14 @@ "MEQCIDD1IVxjzWYncun+9IGzqYjZvqxxujQEayJULTlbTGA/AiAr0oVmEgVUQZBYq5VLOSvy" "96JkMYgzTkHPwbv7K/CmgA=="; +// The sentinel value that may be stored as the latest variations seed value in +// prefs to indicate that the latest seed is identical to the safe seed. +// Note: This constant is intentionally duplicated in the test because it is +// persisted to disk. In order to maintain backward-compatibility, it's +// important that code continue to correctly handle this specific constant, even +// if the constant used internally in the implementation changes. +constexpr char kIdenticalToSafeSeedSentinel[] = "safe_seed_content"; + class TestVariationsSeedStore : public VariationsSeedStore { public: explicit TestVariationsSeedStore(PrefService* local_state) @@ -72,6 +80,14 @@ DISALLOW_COPY_AND_ASSIGN(SignatureVerifyingVariationsSeedStore); }; +// Creates a base::Time object from the corresponding raw value. The specific +// implementation is not important; it's only important that distinct inputs map +// to distinct outputs. +base::Time WrapTime(int64_t time) { + return base::Time::FromDeltaSinceWindowsEpoch( + base::TimeDelta::FromMicroseconds(time)); +} + // Populates |seed| with simple test data. The resulting seed will contain one // study called "test", which contains one experiment called "abc" with // probability weight 100. |seed|'s study field will be cleared before adding @@ -94,8 +110,7 @@ std::unique_ptr<ClientFilterableState> client_state = std::make_unique<ClientFilterableState>(); client_state->locale = "es-MX"; - client_state->reference_date = - base::Time::FromDeltaSinceWindowsEpoch(base::TimeDelta::FromDays(12345)); + client_state->reference_date = WrapTime(1234554321); client_state->version = base::Version("1.2.3.4"); client_state->channel = Study::CANARY; client_state->form_factor = Study::PHONE; @@ -140,8 +155,11 @@ prefs->SetString(prefs::kVariationsSafeSeedSessionConsistencyCountry, "e"); prefs->SetString(prefs::kVariationsSafeSeedSignature, "f"); prefs->SetString(prefs::kVariationsSeedSignature, "g"); - prefs->SetTime(prefs::kVariationsSafeSeedDate, base::Time::Now()); - prefs->SetTime(prefs::kVariationsSeedDate, base::Time::Now()); + const base::Time now = base::Time::Now(); + const base::TimeDelta delta = base::TimeDelta::FromDays(1); + prefs->SetTime(prefs::kVariationsSafeSeedDate, now - delta); + prefs->SetTime(prefs::kVariationsSafeSeedFetchTime, now - delta * 2); + prefs->SetTime(prefs::kVariationsSeedDate, now - delta * 3); } // Checks whether the pref with name |pref_name| is at its default value in @@ -204,6 +222,7 @@ EXPECT_FALSE( PrefHasDefaultValue(prefs, prefs::kVariationsSafeCompressedSeed)); EXPECT_FALSE(PrefHasDefaultValue(prefs, prefs::kVariationsSafeSeedDate)); + EXPECT_FALSE(PrefHasDefaultValue(prefs, prefs::kVariationsSafeSeedFetchTime)); EXPECT_FALSE(PrefHasDefaultValue(prefs, prefs::kVariationsSafeSeedLocale)); EXPECT_FALSE(PrefHasDefaultValue( prefs, prefs::kVariationsSafeSeedPermanentConsistencyCountry)); @@ -240,6 +259,7 @@ EXPECT_FALSE( PrefHasDefaultValue(prefs, prefs::kVariationsSafeCompressedSeed)); EXPECT_FALSE(PrefHasDefaultValue(prefs, prefs::kVariationsSafeSeedDate)); + EXPECT_FALSE(PrefHasDefaultValue(prefs, prefs::kVariationsSafeSeedFetchTime)); EXPECT_FALSE(PrefHasDefaultValue(prefs, prefs::kVariationsSafeSeedLocale)); EXPECT_FALSE(PrefHasDefaultValue( prefs, prefs::kVariationsSafeSeedPermanentConsistencyCountry)); @@ -261,6 +281,35 @@ &loaded_base64_seed_signature)); } +TEST(VariationsSeedStoreTest, LoadSeed_IdenticalToSafeSeed) { + // Store good seed data to the safe seed prefs, and store a sentinel value to + // the latest seed pref, to verify that loading via the alias works. + const VariationsSeed seed = CreateTestSeed(); + const std::string base64_seed = SerializeSeedBase64(seed); + const std::string base64_seed_signature = "a test signature, ignored."; + + TestingPrefServiceSimple prefs; + VariationsSeedStore::RegisterPrefs(prefs.registry()); + prefs.SetString(prefs::kVariationsCompressedSeed, + kIdenticalToSafeSeedSentinel); + prefs.SetString(prefs::kVariationsSafeCompressedSeed, base64_seed); + prefs.SetString(prefs::kVariationsSeedSignature, base64_seed_signature); + + TestVariationsSeedStore seed_store(&prefs); + + VariationsSeed loaded_seed; + std::string loaded_seed_data; + std::string loaded_base64_seed_signature; + // Check that loading the seed works correctly. + EXPECT_TRUE(seed_store.LoadSeed(&loaded_seed, &loaded_seed_data, + &loaded_base64_seed_signature)); + + // Check that the loaded data is the same as the original. + EXPECT_EQ(SerializeSeed(seed), SerializeSeed(loaded_seed)); + EXPECT_EQ(SerializeSeed(seed), loaded_seed_data); + EXPECT_EQ(base64_seed_signature, loaded_base64_seed_signature); +} + TEST(VariationsSeedStoreTest, StoreSeedData) { const VariationsSeed seed = CreateTestSeed(); const std::string serialized_seed = SerializeSeed(seed); @@ -339,12 +388,40 @@ EXPECT_EQ(serialized_seed, SerializeSeed(parsed_seed)); } +TEST(VariationsSeedStoreTest, StoreSeedData_IdenticalToSafeSeed) { + const VariationsSeed seed = CreateTestSeed(); + const std::string serialized_seed = SerializeSeed(seed); + const std::string base64_seed = SerializeSeedBase64(seed); + + TestingPrefServiceSimple prefs; + VariationsSeedStore::RegisterPrefs(prefs.registry()); + prefs.SetString(prefs::kVariationsSafeCompressedSeed, base64_seed); + + TestVariationsSeedStore seed_store(&prefs); + EXPECT_TRUE(seed_store.StoreSeedForTesting(serialized_seed)); + + // Verify that the pref has a sentinel value, rather than the full string. + EXPECT_EQ(kIdenticalToSafeSeedSentinel, + prefs.GetString(prefs::kVariationsCompressedSeed)); + + // Verify that loading the stored seed returns the original seed value. + VariationsSeed loaded_seed; + std::string loaded_seed_data; + std::string unused_loaded_base64_seed_signature; + EXPECT_TRUE(seed_store.LoadSeed(&loaded_seed, &loaded_seed_data, + &unused_loaded_base64_seed_signature)); + + EXPECT_EQ(SerializeSeed(seed), SerializeSeed(loaded_seed)); + EXPECT_EQ(SerializeSeed(seed), loaded_seed_data); +} + TEST(VariationsSeedStoreTest, LoadSafeSeed_ValidSeed) { // Store good seed data to test if loading from prefs works. const VariationsSeed seed = CreateTestSeed(); const std::string base64_seed = SerializeSeedBase64(seed); const std::string base64_seed_signature = "a test signature, ignored."; const base::Time reference_date = base::Time::Now(); + const base::Time fetch_time = reference_date - base::TimeDelta::FromDays(3); const std::string locale = "en-US"; const std::string permanent_consistency_country = "us"; const std::string session_consistency_country = "ca"; @@ -354,6 +431,7 @@ prefs.SetString(prefs::kVariationsSafeCompressedSeed, base64_seed); prefs.SetString(prefs::kVariationsSafeSeedSignature, base64_seed_signature); prefs.SetTime(prefs::kVariationsSafeSeedDate, reference_date); + prefs.SetTime(prefs::kVariationsSafeSeedFetchTime, fetch_time); prefs.SetString(prefs::kVariationsSafeSeedLocale, locale); prefs.SetString(prefs::kVariationsSafeSeedPermanentConsistencyCountry, permanent_consistency_country); @@ -364,7 +442,9 @@ VariationsSeed loaded_seed; std::unique_ptr<ClientFilterableState> client_state = CreateTestClientFilterableState(); - EXPECT_TRUE(seed_store.LoadSafeSeed(&loaded_seed, client_state.get())); + base::Time loaded_fetch_time; + EXPECT_TRUE(seed_store.LoadSafeSeed(&loaded_seed, client_state.get(), + &loaded_fetch_time)); // Check that the loaded data is the same as the original. EXPECT_EQ(SerializeSeed(seed), SerializeSeed(loaded_seed)); @@ -374,6 +454,7 @@ client_state->permanent_consistency_country); EXPECT_EQ(session_consistency_country, client_state->session_consistency_country); + EXPECT_EQ(fetch_time, loaded_fetch_time); // Make sure that other data in the |client_state| hasn't been changed. std::unique_ptr<ClientFilterableState> original_state = @@ -402,9 +483,12 @@ VariationsSeed loaded_seed; std::unique_ptr<ClientFilterableState> client_state = CreateTestClientFilterableState(); - EXPECT_FALSE(seed_store.LoadSafeSeed(&loaded_seed, client_state.get())); + base::Time fetch_time; + EXPECT_FALSE( + seed_store.LoadSafeSeed(&loaded_seed, client_state.get(), &fetch_time)); EXPECT_TRUE(PrefHasDefaultValue(prefs, prefs::kVariationsSafeCompressedSeed)); EXPECT_TRUE(PrefHasDefaultValue(prefs, prefs::kVariationsSafeSeedDate)); + EXPECT_TRUE(PrefHasDefaultValue(prefs, prefs::kVariationsSafeSeedFetchTime)); EXPECT_TRUE(PrefHasDefaultValue(prefs, prefs::kVariationsSafeSeedLocale)); EXPECT_TRUE(PrefHasDefaultValue( prefs, prefs::kVariationsSafeSeedPermanentConsistencyCountry)); @@ -447,9 +531,12 @@ VariationsSeed loaded_seed; std::unique_ptr<ClientFilterableState> client_state = CreateTestClientFilterableState(); - EXPECT_FALSE(seed_store.LoadSafeSeed(&loaded_seed, client_state.get())); + base::Time fetch_time; + EXPECT_FALSE( + seed_store.LoadSafeSeed(&loaded_seed, client_state.get(), &fetch_time)); EXPECT_TRUE(PrefHasDefaultValue(prefs, prefs::kVariationsSafeCompressedSeed)); EXPECT_TRUE(PrefHasDefaultValue(prefs, prefs::kVariationsSafeSeedDate)); + EXPECT_TRUE(PrefHasDefaultValue(prefs, prefs::kVariationsSafeSeedFetchTime)); EXPECT_TRUE(PrefHasDefaultValue(prefs, prefs::kVariationsSafeSeedLocale)); EXPECT_TRUE(PrefHasDefaultValue( prefs, prefs::kVariationsSafeSeedPermanentConsistencyCountry)); @@ -482,7 +569,9 @@ TestVariationsSeedStore seed_store(&prefs); VariationsSeed loaded_seed; ClientFilterableState client_state; - EXPECT_FALSE(seed_store.LoadSafeSeed(&loaded_seed, &client_state)); + base::Time fetch_time; + EXPECT_FALSE( + seed_store.LoadSafeSeed(&loaded_seed, &client_state, &fetch_time)); } TEST(VariationsSeedStoreTest, StoreSafeSeed_ValidSeed) { @@ -491,18 +580,18 @@ const std::string signature = "a completely ignored signature"; ClientFilterableState client_state; client_state.locale = "en-US"; - client_state.reference_date = - base::Time() + base::TimeDelta::FromMicroseconds(12345); + client_state.reference_date = WrapTime(12345); client_state.session_consistency_country = "US"; client_state.permanent_consistency_country = "CA"; + const base::Time fetch_time = WrapTime(99999); TestingPrefServiceSimple prefs; VariationsSeedStore::RegisterPrefs(prefs.registry()); TestVariationsSeedStore seed_store(&prefs); base::HistogramTester histogram_tester; - EXPECT_TRUE( - seed_store.StoreSafeSeed(serialized_seed, signature, client_state)); + EXPECT_TRUE(seed_store.StoreSafeSeed(serialized_seed, signature, client_state, + fetch_time)); // Verify the stored data. std::string loaded_compressed_seed = @@ -513,7 +602,9 @@ EXPECT_EQ(Compress(serialized_seed), decoded_compressed_seed); EXPECT_EQ(signature, prefs.GetString(prefs::kVariationsSafeSeedSignature)); EXPECT_EQ("en-US", prefs.GetString(prefs::kVariationsSafeSeedLocale)); - EXPECT_EQ(12345, prefs.GetInt64(prefs::kVariationsSafeSeedDate)); + EXPECT_EQ(WrapTime(12345), prefs.GetTime(prefs::kVariationsSafeSeedDate)); + EXPECT_EQ(WrapTime(99999), + prefs.GetTime(prefs::kVariationsSafeSeedFetchTime)); EXPECT_EQ("US", prefs.GetString( prefs::kVariationsSafeSeedSessionConsistencyCountry)); EXPECT_EQ("CA", prefs.GetString( @@ -529,10 +620,10 @@ const std::string signature = "a completely ignored signature"; ClientFilterableState client_state; client_state.locale = "en-US"; - client_state.reference_date = - base::Time() + base::TimeDelta::FromMicroseconds(12345); + client_state.reference_date = WrapTime(54321); client_state.session_consistency_country = "US"; client_state.permanent_consistency_country = "CA"; + base::Time fetch_time = WrapTime(99999); TestingPrefServiceSimple prefs; VariationsSeedStore::RegisterPrefs(prefs.registry()); @@ -541,13 +632,14 @@ prefs.SetString(prefs::kVariationsSafeSeedLocale, "en-US"); prefs.SetString(prefs::kVariationsSafeSeedPermanentConsistencyCountry, "CA"); prefs.SetString(prefs::kVariationsSafeSeedSessionConsistencyCountry, "US"); - prefs.SetInt64(prefs::kVariationsSafeSeedDate, 12345); + prefs.SetTime(prefs::kVariationsSafeSeedDate, WrapTime(12345)); + prefs.SetTime(prefs::kVariationsSafeSeedFetchTime, WrapTime(34567)); TestVariationsSeedStore seed_store(&prefs); base::HistogramTester histogram_tester; - EXPECT_FALSE( - seed_store.StoreSafeSeed(serialized_seed, signature, client_state)); + EXPECT_FALSE(seed_store.StoreSafeSeed(serialized_seed, signature, + client_state, fetch_time)); // Verify that none of the prefs were overwritten. EXPECT_EQ("a seed", prefs.GetString(prefs::kVariationsSafeCompressedSeed)); @@ -558,7 +650,9 @@ prefs::kVariationsSafeSeedPermanentConsistencyCountry)); EXPECT_EQ("US", prefs.GetString( prefs::kVariationsSafeSeedSessionConsistencyCountry)); - EXPECT_EQ(12345, prefs.GetInt64(prefs::kVariationsSafeSeedDate)); + EXPECT_EQ(WrapTime(12345), prefs.GetTime(prefs::kVariationsSafeSeedDate)); + EXPECT_EQ(WrapTime(34567), + prefs.GetTime(prefs::kVariationsSafeSeedFetchTime)); // Verify metrics. histogram_tester.ExpectUniqueSample( @@ -571,10 +665,10 @@ const std::string signature = "a completely ignored signature"; ClientFilterableState client_state; client_state.locale = "en-US"; - client_state.reference_date = - base::Time() + base::TimeDelta::FromMicroseconds(12345); + client_state.reference_date = WrapTime(12345); client_state.session_consistency_country = "US"; client_state.permanent_consistency_country = "CA"; + base::Time fetch_time = WrapTime(54321); TestingPrefServiceSimple prefs; VariationsSeedStore::RegisterPrefs(prefs.registry()); @@ -583,13 +677,14 @@ prefs.SetString(prefs::kVariationsSafeSeedLocale, "en-CA"); prefs.SetString(prefs::kVariationsSafeSeedPermanentConsistencyCountry, "IN"); prefs.SetString(prefs::kVariationsSafeSeedSessionConsistencyCountry, "MX"); - prefs.SetInt64(prefs::kVariationsSafeSeedDate, 67890); + prefs.SetTime(prefs::kVariationsSafeSeedDate, WrapTime(67890)); + prefs.SetTime(prefs::kVariationsSafeSeedFetchTime, WrapTime(13579)); SignatureVerifyingVariationsSeedStore seed_store(&prefs); base::HistogramTester histogram_tester; - EXPECT_FALSE( - seed_store.StoreSafeSeed(serialized_seed, signature, client_state)); + EXPECT_FALSE(seed_store.StoreSafeSeed(serialized_seed, signature, + client_state, fetch_time)); // Verify that none of the prefs were overwritten. EXPECT_EQ("a previous seed", @@ -601,7 +696,9 @@ prefs::kVariationsSafeSeedPermanentConsistencyCountry)); EXPECT_EQ("MX", prefs.GetString( prefs::kVariationsSafeSeedSessionConsistencyCountry)); - EXPECT_EQ(67890, prefs.GetInt64(prefs::kVariationsSafeSeedDate)); + EXPECT_EQ(WrapTime(67890), prefs.GetTime(prefs::kVariationsSafeSeedDate)); + EXPECT_EQ(WrapTime(13579), + prefs.GetTime(prefs::kVariationsSafeSeedFetchTime)); // Verify metrics. histogram_tester.ExpectUniqueSample( @@ -616,10 +713,10 @@ const std::string signature = kBase64SeedSignature; ClientFilterableState client_state; client_state.locale = "en-US"; - client_state.reference_date = - base::Time() + base::TimeDelta::FromMicroseconds(12345); + client_state.reference_date = WrapTime(12345); client_state.session_consistency_country = "US"; client_state.permanent_consistency_country = "CA"; + const base::Time fetch_time = WrapTime(34567); TestingPrefServiceSimple prefs; VariationsSeedStore::RegisterPrefs(prefs.registry()); @@ -628,13 +725,14 @@ prefs.SetString(prefs::kVariationsSafeSeedLocale, "en-CA"); prefs.SetString(prefs::kVariationsSafeSeedPermanentConsistencyCountry, "IN"); prefs.SetString(prefs::kVariationsSafeSeedSessionConsistencyCountry, "MX"); - prefs.SetInt64(prefs::kVariationsSafeSeedDate, 67890); + prefs.SetTime(prefs::kVariationsSafeSeedDate, WrapTime(67890)); + prefs.SetTime(prefs::kVariationsSafeSeedFetchTime, WrapTime(24680)); SignatureVerifyingVariationsSeedStore seed_store(&prefs); base::HistogramTester histogram_tester; - EXPECT_FALSE( - seed_store.StoreSafeSeed(serialized_seed, signature, client_state)); + EXPECT_FALSE(seed_store.StoreSafeSeed(serialized_seed, signature, + client_state, fetch_time)); // Verify that none of the prefs were overwritten. EXPECT_EQ("a previous seed", @@ -646,7 +744,9 @@ prefs::kVariationsSafeSeedPermanentConsistencyCountry)); EXPECT_EQ("MX", prefs.GetString( prefs::kVariationsSafeSeedSessionConsistencyCountry)); - EXPECT_EQ(67890, prefs.GetInt64(prefs::kVariationsSafeSeedDate)); + EXPECT_EQ(WrapTime(67890), prefs.GetTime(prefs::kVariationsSafeSeedDate)); + EXPECT_EQ(WrapTime(24680), + prefs.GetTime(prefs::kVariationsSafeSeedFetchTime)); // Verify metrics. histogram_tester.ExpectUniqueSample( @@ -664,18 +764,18 @@ const std::string signature = kBase64SeedSignature; ClientFilterableState client_state; client_state.locale = "en-US"; - client_state.reference_date = - base::Time() + base::TimeDelta::FromMicroseconds(12345); + client_state.reference_date = WrapTime(12345); client_state.session_consistency_country = "US"; client_state.permanent_consistency_country = "CA"; + const base::Time fetch_time = WrapTime(34567); TestingPrefServiceSimple prefs; VariationsSeedStore::RegisterPrefs(prefs.registry()); SignatureVerifyingVariationsSeedStore seed_store(&prefs); base::HistogramTester histogram_tester; - EXPECT_TRUE( - seed_store.StoreSafeSeed(serialized_seed, signature, client_state)); + EXPECT_TRUE(seed_store.StoreSafeSeed(serialized_seed, signature, client_state, + fetch_time)); // Verify the stored data. std::string loaded_compressed_seed = @@ -686,7 +786,9 @@ EXPECT_EQ(Compress(serialized_seed), decoded_compressed_seed); EXPECT_EQ(signature, prefs.GetString(prefs::kVariationsSafeSeedSignature)); EXPECT_EQ("en-US", prefs.GetString(prefs::kVariationsSafeSeedLocale)); - EXPECT_EQ(12345, prefs.GetInt64(prefs::kVariationsSafeSeedDate)); + EXPECT_EQ(WrapTime(12345), prefs.GetTime(prefs::kVariationsSafeSeedDate)); + EXPECT_EQ(WrapTime(34567), + prefs.GetTime(prefs::kVariationsSafeSeedFetchTime)); EXPECT_EQ("US", prefs.GetString( prefs::kVariationsSafeSeedSessionConsistencyCountry)); EXPECT_EQ("CA", prefs.GetString( @@ -700,6 +802,112 @@ VerifySignatureResult::VALID_SIGNATURE, 1); } +TEST(VariationsSeedStoreTest, StoreSafeSeed_IdenticalToLatestSeed) { + const VariationsSeed seed = CreateTestSeed(); + const std::string serialized_seed = SerializeSeed(seed); + const std::string base64_seed = SerializeSeedBase64(seed); + const std::string signature = "a completely ignored signature"; + ClientFilterableState unused_client_state; + const base::Time fetch_time = WrapTime(12345); + + TestingPrefServiceSimple prefs; + VariationsSeedStore::RegisterPrefs(prefs.registry()); + prefs.SetString(prefs::kVariationsCompressedSeed, base64_seed); + prefs.SetTime(prefs::kVariationsLastFetchTime, WrapTime(99999)); + + TestVariationsSeedStore seed_store(&prefs); + base::HistogramTester histogram_tester; + EXPECT_TRUE(seed_store.StoreSafeSeed(serialized_seed, signature, + unused_client_state, fetch_time)); + + // Verify the latest seed value was migrated to a sentinel value, rather than + // the full string. + EXPECT_EQ(kIdenticalToSafeSeedSentinel, + prefs.GetString(prefs::kVariationsCompressedSeed)); + + // Verify that loading the stored seed returns the original seed value. + VariationsSeed loaded_seed; + std::string loaded_seed_data; + std::string unused_loaded_base64_seed_signature; + EXPECT_TRUE(seed_store.LoadSeed(&loaded_seed, &loaded_seed_data, + &unused_loaded_base64_seed_signature)); + + EXPECT_EQ(SerializeSeed(seed), SerializeSeed(loaded_seed)); + EXPECT_EQ(SerializeSeed(seed), loaded_seed_data); + + // Verify that the safe seed prefs indeed contain the serialized seed value + // and that the last fetch time was copied from the latest seed. + EXPECT_EQ(base64_seed, prefs.GetString(prefs::kVariationsSafeCompressedSeed)); + VariationsSeed loaded_safe_seed; + base::Time loaded_fetch_time; + EXPECT_TRUE(seed_store.LoadSafeSeed(&loaded_safe_seed, &unused_client_state, + &loaded_fetch_time)); + EXPECT_EQ(SerializeSeed(seed), SerializeSeed(loaded_safe_seed)); + EXPECT_EQ(WrapTime(99999), loaded_fetch_time); + + // Verify metrics. + histogram_tester.ExpectUniqueSample( + "Variations.SafeMode.StoreSafeSeed.Result", StoreSeedResult::SUCCESS, 1); +} + +TEST(VariationsSeedStoreTest, StoreSafeSeed_PreviouslyIdenticalToLatestSeed) { + // Create two distinct seeds: an old one saved as both the safe and the latest + // seed value, and a new one that should overwrite only the stored safe seed + // value. + const VariationsSeed old_seed = CreateTestSeed(); + VariationsSeed new_seed = CreateTestSeed(); + new_seed.set_serial_number("12345678"); + ASSERT_NE(SerializeSeed(old_seed), SerializeSeed(new_seed)); + + const std::string serialized_old_seed = SerializeSeed(old_seed); + const std::string base64_old_seed = SerializeSeedBase64(old_seed); + const std::string serialized_new_seed = SerializeSeed(new_seed); + const std::string base64_new_seed = SerializeSeedBase64(new_seed); + const std::string signature = "a completely ignored signature"; + const base::Time fetch_time = WrapTime(12345); + ClientFilterableState unused_client_state; + + TestingPrefServiceSimple prefs; + VariationsSeedStore::RegisterPrefs(prefs.registry()); + prefs.SetString(prefs::kVariationsSafeCompressedSeed, base64_old_seed); + prefs.SetString(prefs::kVariationsCompressedSeed, + kIdenticalToSafeSeedSentinel); + + TestVariationsSeedStore seed_store(&prefs); + base::HistogramTester histogram_tester; + EXPECT_TRUE(seed_store.StoreSafeSeed(serialized_new_seed, signature, + unused_client_state, fetch_time)); + + // Verify the latest seed value was copied before the safe seed was + // overwritten. + EXPECT_EQ(base64_old_seed, prefs.GetString(prefs::kVariationsCompressedSeed)); + + // Verify that loading the stored seed returns the old seed value. + VariationsSeed loaded_seed; + std::string loaded_seed_data; + std::string unused_loaded_base64_seed_signature; + EXPECT_TRUE(seed_store.LoadSeed(&loaded_seed, &loaded_seed_data, + &unused_loaded_base64_seed_signature)); + + EXPECT_EQ(SerializeSeed(old_seed), SerializeSeed(loaded_seed)); + EXPECT_EQ(SerializeSeed(old_seed), loaded_seed_data); + + // Verify that the safe seed prefs indeed contain the new seed's serialized + // value. + EXPECT_EQ(base64_new_seed, + prefs.GetString(prefs::kVariationsSafeCompressedSeed)); + VariationsSeed loaded_safe_seed; + base::Time loaded_fetch_time; + EXPECT_TRUE(seed_store.LoadSafeSeed(&loaded_safe_seed, &unused_client_state, + &loaded_fetch_time)); + EXPECT_EQ(SerializeSeed(new_seed), SerializeSeed(loaded_safe_seed)); + EXPECT_EQ(fetch_time, loaded_fetch_time); + + // Verify metrics. + histogram_tester.ExpectUniqueSample( + "Variations.SafeMode.StoreSafeSeed.Result", StoreSeedResult::SUCCESS, 1); +} + TEST(VariationsSeedStoreTest, StoreSeedData_GzippedEmptySeed) { std::string empty_seed; std::string compressed_seed; @@ -869,6 +1077,52 @@ EXPECT_EQ(after_seed_data, output); } +TEST(VariationsSeedStoreTest, LastFetchTime_DistinctSeeds) { + TestingPrefServiceSimple prefs; + VariationsSeedStore::RegisterPrefs(prefs.registry()); + prefs.SetString(prefs::kVariationsCompressedSeed, "one"); + prefs.SetString(prefs::kVariationsSafeCompressedSeed, "not one"); + prefs.SetTime(prefs::kVariationsLastFetchTime, WrapTime(1)); + prefs.SetTime(prefs::kVariationsSafeSeedFetchTime, WrapTime(0)); + + base::Time start_time = base::Time::Now(); + TestVariationsSeedStore seed_store(&prefs); + seed_store.RecordLastFetchTime(); + + // Verify that the last fetch time was updated. + const base::Time last_fetch_time = + prefs.GetTime(prefs::kVariationsLastFetchTime); + EXPECT_NE(WrapTime(1), last_fetch_time); + EXPECT_GE(last_fetch_time, start_time); + + // Verify that the safe seed's fetch time was *not* updated. + EXPECT_EQ(WrapTime(0), prefs.GetTime(prefs::kVariationsSafeSeedFetchTime)); +} + +TEST(VariationsSeedStoreTest, LastFetchTime_IdenticalSeeds) { + TestingPrefServiceSimple prefs; + VariationsSeedStore::RegisterPrefs(prefs.registry()); + prefs.SetString(prefs::kVariationsSafeCompressedSeed, "some seed"); + prefs.SetString(prefs::kVariationsCompressedSeed, + kIdenticalToSafeSeedSentinel); + prefs.SetTime(prefs::kVariationsLastFetchTime, WrapTime(1)); + prefs.SetTime(prefs::kVariationsSafeSeedFetchTime, WrapTime(0)); + + base::Time start_time = base::Time::Now(); + TestVariationsSeedStore seed_store(&prefs); + seed_store.RecordLastFetchTime(); + + // Verify that the last fetch time was updated. + const base::Time last_fetch_time = + prefs.GetTime(prefs::kVariationsLastFetchTime); + EXPECT_NE(WrapTime(1), last_fetch_time); + EXPECT_GE(last_fetch_time, start_time); + + // Verify that the safe seed's fetch time *was* also updated. + EXPECT_EQ(last_fetch_time, + prefs.GetTime(prefs::kVariationsSafeSeedFetchTime)); +} + TEST(VariationsSeedStoreTest, GetLatestSerialNumber_LoadsInitialValue) { // Store good seed data to test if loading from prefs works. const VariationsSeed seed = CreateTestSeed();
diff --git a/components/viz/README.md b/components/viz/README.md index c73a9ba..946f2fe 100644 --- a/components/viz/README.md +++ b/components/viz/README.md
@@ -120,9 +120,13 @@ compositor (typically thought of as SwapBuffers), as well as the use of overlays. -| Can depend on: | -|:---------------| -| viz/common/* | +| Can depend on: | +|:--------------------------------------| +| viz/common/* | +| viz/service/display/<some_interfaces> | + +Dependencies onto viz/service/display should generally only be for interfaces +that the embedder must provide to the display. #### service/frame_sinks **Frame sinks**: This component implements the Mojo interfaces to send frames, @@ -130,11 +134,13 @@ compositing service. It receives and organizes relationships between what should be composited. -| Can depend on: | -|:----------------------| -| viz/common/* | -| viz/service/display/ | -| viz/service/surfaces/ | +| Can depend on: | +|:------------------------------| +| viz/common/* | +| viz/service/display/ | +| viz/service/display_embedder/ | +| viz/service/hit_test/ | +| viz/service/surfaces/ | #### service/gl **GL**: This component implements the Mojo interfaces for allocating (and
diff --git a/components/viz/service/DEPS b/components/viz/service/DEPS index 1ca3921..4ec64970 100644 --- a/components/viz/service/DEPS +++ b/components/viz/service/DEPS
@@ -4,7 +4,8 @@ "+cc", "-components/viz/common/features.h", "-components/viz/common/switches.h", - "+components/viz/service", + "-components/viz/service", + "+components/viz/service/viz_service_export.h", "+services/viz/privileged/interfaces", "+services/viz/public/interfaces", "+third_party/skia",
diff --git a/components/viz/service/display/DEPS b/components/viz/service/display/DEPS index b74307f..314ebb3a 100644 --- a/components/viz/service/display/DEPS +++ b/components/viz/service/display/DEPS
@@ -7,6 +7,7 @@ "+cc/output", "+cc/resources", "+cc/scheduler", + "+components/viz/service/surfaces", "+gpu/command_buffer/client", "+gpu/command_buffer/common", "+gpu/GLES2", @@ -28,6 +29,7 @@ ], ".*_(unit|pixel|perf)test\.cc": [ "+cc/test", + "+components/viz/service/display_embedder", "+components/viz/service/frame_sinks", "+components/viz/test", "+gpu/GLES2",
diff --git a/components/viz/service/display/surface_aggregator.cc b/components/viz/service/display/surface_aggregator.cc index 1b9a653..5adca05e 100644 --- a/components/viz/service/display/surface_aggregator.cc +++ b/components/viz/service/display/surface_aggregator.cc
@@ -25,7 +25,6 @@ #include "components/viz/common/quads/solid_color_draw_quad.h" #include "components/viz/common/quads/surface_draw_quad.h" #include "components/viz/common/quads/texture_draw_quad.h" -#include "components/viz/service/frame_sinks/compositor_frame_sink_support.h" #include "components/viz/service/surfaces/surface.h" #include "components/viz/service/surfaces/surface_client.h" #include "components/viz/service/surfaces/surface_manager.h"
diff --git a/components/viz/service/display_embedder/DEPS b/components/viz/service/display_embedder/DEPS index be26d401..5fc1a52 100644 --- a/components/viz/service/display_embedder/DEPS +++ b/components/viz/service/display_embedder/DEPS
@@ -6,6 +6,11 @@ "+cc/output", "+cc/resources", "+cc/scheduler", + "+components/viz/service/display/output_surface_client.h", + "+components/viz/service/display/output_surface_frame.h", + "+components/viz/service/display/output_surface.h", + "+components/viz/service/display/overlay_candidate_validator.h", + "+components/viz/service/display/software_output_device.h", "+gpu/GLES2", "+gpu/command_buffer/client", "+gpu/command_buffer/common", @@ -23,6 +28,13 @@ "+ui/gl", "+ui/latency", "+ui/ozone/public", + + # TODO(danakj): Double check the layering for these dependencies. + "+components/viz/service/display/overlay_processor.h", + "+components/viz/service/display/overlay_strategy_fullscreen.h", + "+components/viz/service/display/overlay_strategy_single_on_top.h", + "+components/viz/service/display/overlay_strategy_underlay_cast.h", + "+components/viz/service/display/overlay_strategy_underlay.h", ] specific_include_rules = { @@ -30,6 +42,15 @@ "+cc/test", "+third_party/khronos/GLES2", ], + # TODO(kylechar): Move this class to components/viz/service/frame_sinks/. + "external_begin_frame_controller_impl.h": [ + "+components/viz/service/display/display.h", + ], + # TODO(kylechar): Break these dependencies. + "gpu_display_provider.cc": [ + "+components/viz/service/display/display.h", + "+components/viz/service/display/display_scheduler.h", + ], "software_output_device_ozone_unittest.cc": [ "+ui/compositor", "+ui/gl",
diff --git a/components/viz/service/frame_sinks/DEPS b/components/viz/service/frame_sinks/DEPS index 5d81f748..a10db77 100644 --- a/components/viz/service/frame_sinks/DEPS +++ b/components/viz/service/frame_sinks/DEPS
@@ -4,6 +4,9 @@ "+cc/base", "+cc/ipc", "+cc/scheduler", + "+components/viz/service/display", + "+components/viz/service/display_embedder", + "+components/viz/service/hit_test", "+components/viz/service/surfaces", "+gpu/ipc/common", "+mojo/public/cpp/bindings",
diff --git a/components/viz/service/hit_test/DEPS b/components/viz/service/hit_test/DEPS index 9c6b105..601a5c8 100644 --- a/components/viz/service/hit_test/DEPS +++ b/components/viz/service/hit_test/DEPS
@@ -5,7 +5,12 @@ ] specific_include_rules = { + # TODO(riajiang): This dependency needs to be removed. + "hit_test_manager.cc": [ + "+components/viz/service/frame_sinks/frame_sink_manager_impl.h", + ], "hit_test_aggregator_unittest.cc": [ "+components/viz/host/host_frame_sink_manager.h", - ] + "+components/viz/service/frame_sinks", + ], }
diff --git a/content/browser/BUILD.gn b/content/browser/BUILD.gn index 49759752..7284306 100644 --- a/content/browser/BUILD.gn +++ b/content/browser/BUILD.gn
@@ -44,6 +44,7 @@ "//components/discardable_memory/common", "//components/discardable_memory/service", "//components/download/downloader/in_progress", + "//components/download/public/common:public", "//components/filesystem:lib", "//components/leveldb:lib", "//components/link_header_util", @@ -978,6 +979,8 @@ "loader/loader_delegate.h", "loader/loader_io_thread_notifier.cc", "loader/loader_io_thread_notifier.h", + "loader/merkle_integrity_source_stream.cc", + "loader/merkle_integrity_source_stream.h", "loader/mime_sniffing_resource_handler.cc", "loader/mime_sniffing_resource_handler.h", "loader/mojo_async_resource_handler.cc",
diff --git a/content/browser/DEPS b/content/browser/DEPS index bcce3dab..0d4a677 100644 --- a/content/browser/DEPS +++ b/content/browser/DEPS
@@ -4,6 +4,7 @@ "+components/discardable_memory/common", "+components/discardable_memory/service", "+components/download/downloader/in_progress", + "+components/download/public/common", "+components/filesystem", "+components/leveldb", "+components/link_header_util",
diff --git a/content/browser/accessibility/browser_accessibility_android.cc b/content/browser/accessibility/browser_accessibility_android.cc index f699119..5e548a2 100644 --- a/content/browser/accessibility/browser_accessibility_android.cc +++ b/content/browser/accessibility/browser_accessibility_android.cc
@@ -631,6 +631,12 @@ case ax::mojom::Role::kLabelText: // No role description. break; + case ax::mojom::Role::kLayoutTable: + case ax::mojom::Role::kLayoutTableCell: + case ax::mojom::Role::kLayoutTableColumn: + case ax::mojom::Role::kLayoutTableRow: + // No role description. + break; case ax::mojom::Role::kLegend: // No role description. break;
diff --git a/content/browser/accessibility/browser_accessibility_cocoa.mm b/content/browser/accessibility/browser_accessibility_cocoa.mm index 079b544..bdb1aa2 100644 --- a/content/browser/accessibility/browser_accessibility_cocoa.mm +++ b/content/browser/accessibility/browser_accessibility_cocoa.mm
@@ -760,6 +760,8 @@ - (NSArray*)children { if (![self instanceActive]) return nil; + if ([self internalRole] == ax::mojom::Role::kLayoutTableColumn) + return nil; if (!children_) { uint32_t childCount = browserAccessibility_->PlatformChildCount(); children_.reset([[NSMutableArray alloc] initWithCapacity:childCount]);
diff --git a/content/browser/accessibility/dump_accessibility_tree_browsertest.cc b/content/browser/accessibility/dump_accessibility_tree_browsertest.cc index 23c44b2..6f636a0 100644 --- a/content/browser/accessibility/dump_accessibility_tree_browsertest.cc +++ b/content/browser/accessibility/dump_accessibility_tree_browsertest.cc
@@ -192,6 +192,8 @@ AddFilter(filters, "FOCUSED", Filter::DENY); AddFilter(filters, "HOTTRACKED", Filter::DENY); AddFilter(filters, "OFFSCREEN", Filter::DENY); + // Object attributes. + AddFilter(filters, "layout-guess:*", Filter::ALLOW); // // Blink @@ -1667,6 +1669,15 @@ RunHtmlTest(FILE_PATH_LITERAL("table-simple.html")); } +IN_PROC_BROWSER_TEST_F(DumpAccessibilityTreeTest, AccessibilityTableLayout) { + RunHtmlTest(FILE_PATH_LITERAL("table-layout.html")); +} + +IN_PROC_BROWSER_TEST_F(DumpAccessibilityTreeTest, + AccessibilityTablePresentation) { + RunHtmlTest(FILE_PATH_LITERAL("table-presentation.html")); +} + IN_PROC_BROWSER_TEST_F(DumpAccessibilityTreeTest, AccessibilityTableThColHeader) { RunHtmlTest(FILE_PATH_LITERAL("table-th-colheader.html"));
diff --git a/content/browser/android/overscroll_controller_android_unittest.cc b/content/browser/android/overscroll_controller_android_unittest.cc index e9de8e7..d43297d7 100644 --- a/content/browser/android/overscroll_controller_android_unittest.cc +++ b/content/browser/android/overscroll_controller_android_unittest.cc
@@ -7,6 +7,7 @@ #include "base/macros.h" #include "base/memory/ptr_util.h" #include "cc/layers/layer.h" +#include "content/public/common/use_zoom_for_dsf_policy.h" #include "testing/gmock/include/gmock/gmock.h" #include "testing/gtest/include/gtest/gtest.h" #include "third_party/WebKit/public/platform/WebGestureEvent.h" @@ -78,13 +79,15 @@ class OverscrollControllerAndroidUnitTest : public testing::Test { public: OverscrollControllerAndroidUnitTest() { + dip_scale_ = 560; std::unique_ptr<MockGlow> glow_ptr = std::make_unique<MockGlow>(); std::unique_ptr<MockRefresh> refresh_ptr = std::make_unique<MockRefresh>(); compositor_ = std::make_unique<MockCompositor>(); glow_ = glow_ptr.get(); refresh_ = refresh_ptr.get(); controller_ = OverscrollControllerAndroid::CreateForTests( - compositor_.get(), 560, std::move(glow_ptr), std::move(refresh_ptr)); + compositor_.get(), dip_scale_, std::move(glow_ptr), + std::move(refresh_ptr)); } ui::DidOverscrollParams CreateVerticalOverscrollParams() { @@ -93,6 +96,12 @@ params.latest_overscroll_delta = gfx::Vector2dF(0, 1); params.current_fling_velocity = gfx::Vector2dF(0, 1); params.causal_event_viewport_point = gfx::PointF(100, 100); + if (IsUseZoomForDSFEnabled()) { + params.accumulated_overscroll.Scale(dip_scale_); + params.latest_overscroll_delta.Scale(dip_scale_); + params.current_fling_velocity.Scale(dip_scale_); + params.causal_event_viewport_point.Scale(dip_scale_); + } return params; } @@ -101,6 +110,7 @@ MockRefresh* refresh_; std::unique_ptr<MockCompositor> compositor_; std::unique_ptr<OverscrollControllerAndroid> controller_; + float dip_scale_; }; TEST_F(OverscrollControllerAndroidUnitTest, @@ -174,6 +184,11 @@ params.accumulated_overscroll = gfx::Vector2dF(1, 1); params.latest_overscroll_delta = gfx::Vector2dF(1, 1); params.current_fling_velocity = gfx::Vector2dF(1, 1); + if (IsUseZoomForDSFEnabled()) { + params.accumulated_overscroll.Scale(dip_scale_); + params.latest_overscroll_delta.Scale(dip_scale_); + params.current_fling_velocity.Scale(dip_scale_); + } EXPECT_CALL(*refresh_, OnOverscrolled()).Times(0); EXPECT_CALL(*refresh_, Reset());
diff --git a/content/browser/appcache/appcache_request_handler.cc b/content/browser/appcache/appcache_request_handler.cc index a72a03e..63cc984b 100644 --- a/content/browser/appcache/appcache_request_handler.cc +++ b/content/browser/appcache/appcache_request_handler.cc
@@ -475,13 +475,13 @@ // NetworkService loading: void AppCacheRequestHandler::RunLoaderCallbackForMainResource( LoaderCallback callback, - StartLoaderCallback start_loader_callback) { + SingleRequestURLLoaderFactory::RequestHandler handler) { // For now let |this| always also return the subresource loader // if (and only if) this returns a non-null |start_loader_callback| // for handling the main resource. - if (start_loader_callback) + if (handler) should_create_subresource_loader_ = true; - std::move(callback).Run(std::move(start_loader_callback)); + std::move(callback).Run(std::move(handler)); } // Sub-resource handling ---------------------------------------------- @@ -591,10 +591,9 @@ MaybeLoadResource(nullptr); // If a job is created, the job assumes ownership of the callback and // the responsibility to call it. If no job is created, we call it with - // an empty StartLoaderCallback to let our client we have no loader for - // this resource request. + // a null callback to let our client know we have no loader for this request. if (loader_callback_) - std::move(loader_callback_).Run(StartLoaderCallback()); + std::move(loader_callback_).Run({}); } bool AppCacheRequestHandler::MaybeCreateLoaderForResponse( @@ -610,12 +609,12 @@ loader_callback_ = base::BindOnce( [](network::mojom::URLLoaderPtr* loader, network::mojom::URLLoaderClientRequest* client_request, - bool* was_called, StartLoaderCallback start_function) { + bool* was_called, + SingleRequestURLLoaderFactory::RequestHandler handler) { *was_called = true; network::mojom::URLLoaderClientPtr client; *client_request = mojo::MakeRequest(&client); - std::move(start_function) - .Run(mojo::MakeRequest(loader), std::move(client)); + std::move(handler).Run(mojo::MakeRequest(loader), std::move(client)); }, loader, client_request, &was_called); request_->AsURLLoaderRequest()->set_response(response); @@ -662,7 +661,7 @@ request_->AsURLLoaderRequest()->set_response(response); MaybeLoadFallbackForResponse(nullptr); if (loader_callback_) - std::move(loader_callback_).Run(StartLoaderCallback()); + std::move(loader_callback_).Run({}); } void AppCacheRequestHandler::MaybeFallbackForSubresourceRedirect( @@ -673,7 +672,7 @@ loader_callback_ = std::move(loader_callback); MaybeLoadFallbackForRedirect(nullptr, redirect_info.new_url); if (loader_callback_) - std::move(loader_callback_).Run(StartLoaderCallback()); + std::move(loader_callback_).Run({}); } void AppCacheRequestHandler::MaybeFollowSubresourceRedirect( @@ -685,7 +684,7 @@ request_->AsURLLoaderRequest()->UpdateWithRedirectInfo(redirect_info); MaybeLoadResource(nullptr); if (loader_callback_) - std::move(loader_callback_).Run(StartLoaderCallback()); + std::move(loader_callback_).Run({}); } // static
diff --git a/content/browser/appcache/appcache_request_handler.h b/content/browser/appcache/appcache_request_handler.h index 46d87255..96ecfa5 100644 --- a/content/browser/appcache/appcache_request_handler.h +++ b/content/browser/appcache/appcache_request_handler.h
@@ -188,14 +188,12 @@ const GURL& mainfest_url) override; // NetworkService loading: - // Called when a |callback| that is originally given to - // MaybeCreateLoader() runs for the main resource. - // This flips should_create_subresource_loader_ if non-null - // |start_loader_callback| is given, and then (always) run - // |callback| passing in |start_loader_callback|. + // Called when a |callback| that is originally given to |MaybeCreateLoader()| + // runs for the main resource. This flips |should_create_subresource_loader_| + // if a non-null |handler| is given. Always invokes |callback| with |handler|. void RunLoaderCallbackForMainResource( LoaderCallback callback, - StartLoaderCallback start_loader_callback); + SingleRequestURLLoaderFactory::RequestHandler handler); // Sub-resource loading ------------------------------------- // Dedicated worker and all manner of sub-resources are handled here. @@ -272,8 +270,8 @@ LoaderCallback loader_callback_; // Flipped to true if AppCache wants to handle subresource requests - // (i.e. when |loader_callback_| is fired with a non-null callback for - // non-error cases. + // (i.e. when |loader_callback_| is fired with a non-null + // RequestHandler for non-error cases. bool should_create_subresource_loader_ = false; // Points to the getter for the network URL loader.
diff --git a/content/browser/appcache/appcache_subresource_url_factory.cc b/content/browser/appcache/appcache_subresource_url_factory.cc index 7d251e9..49415e7 100644 --- a/content/browser/appcache/appcache_subresource_url_factory.cc +++ b/content/browser/appcache/appcache_subresource_url_factory.cc
@@ -12,6 +12,7 @@ #include "content/browser/appcache/appcache_url_loader_request.h" #include "content/browser/url_loader_factory_getter.h" #include "content/public/browser/browser_thread.h" +#include "content/public/common/shared_url_loader_factory.h" #include "mojo/public/cpp/bindings/binding.h" #include "mojo/public/cpp/bindings/binding_set.h" #include "mojo/public/cpp/bindings/interface_ptr.h" @@ -89,16 +90,17 @@ weak_factory_.GetWeakPtr())); } - void ContinueStart(StartLoaderCallback start_function) { - if (start_function) - CreateAndStartAppCacheLoader(std::move(start_function)); + void ContinueStart(SingleRequestURLLoaderFactory::RequestHandler handler) { + if (handler) + CreateAndStartAppCacheLoader(std::move(handler)); else CreateAndStartNetworkLoader(); } - void CreateAndStartAppCacheLoader(StartLoaderCallback start_function) { + void CreateAndStartAppCacheLoader( + SingleRequestURLLoaderFactory::RequestHandler handler) { DCHECK(!appcache_loader_) << "only expected to be called onced"; - DCHECK(start_function); + DCHECK(handler); // Disconnect from the network loader first. local_client_binding_.Close(); @@ -106,8 +108,8 @@ network::mojom::URLLoaderClientPtr client_ptr; local_client_binding_.Bind(mojo::MakeRequest(&client_ptr)); - std::move(start_function) - .Run(mojo::MakeRequest(&appcache_loader_), std::move(client_ptr)); + std::move(handler).Run(mojo::MakeRequest(&appcache_loader_), + std::move(client_ptr)); } void CreateAndStartNetworkLoader() { @@ -141,9 +143,10 @@ // network::mojom::URLLoader implementation void ProceedWithResponse() override { NOTREACHED(); } - void ContinueFollowRedirect(StartLoaderCallback start_function) { - if (start_function) - CreateAndStartAppCacheLoader(std::move(start_function)); + void ContinueFollowRedirect( + SingleRequestURLLoaderFactory::RequestHandler handler) { + if (handler) + CreateAndStartAppCacheLoader(std::move(handler)); else network_loader_->FollowRedirect(); } @@ -194,9 +197,9 @@ const network::ResourceResponseHead& response_head, const base::Optional<net::SSLInfo>& ssl_info, network::mojom::DownloadedTempFilePtr downloaded_file, - StartLoaderCallback start_function) { - if (start_function) { - CreateAndStartAppCacheLoader(std::move(start_function)); + SingleRequestURLLoaderFactory::RequestHandler handler) { + if (handler) { + CreateAndStartAppCacheLoader(std::move(handler)); } else { remote_client_->OnReceiveResponse(response_head, ssl_info, std::move(downloaded_file)); @@ -225,9 +228,9 @@ void ContinueOnReceiveRedirect( const network::ResourceResponseHead& response_head, - StartLoaderCallback start_function) { - if (start_function) - CreateAndStartAppCacheLoader(std::move(start_function)); + SingleRequestURLLoaderFactory::RequestHandler handler) { + if (handler) + CreateAndStartAppCacheLoader(std::move(handler)); else remote_client_->OnReceiveRedirect(redirect_info_, response_head); } @@ -268,10 +271,11 @@ weak_factory_.GetWeakPtr(), status)); } - void ContinueOnComplete(const network::URLLoaderCompletionStatus& status, - StartLoaderCallback start_function) { - if (start_function) - CreateAndStartAppCacheLoader(std::move(start_function)); + void ContinueOnComplete( + const network::URLLoaderCompletionStatus& status, + SingleRequestURLLoaderFactory::RequestHandler handler) { + if (handler) + CreateAndStartAppCacheLoader(std::move(handler)); else remote_client_->OnComplete(status); }
diff --git a/content/browser/appcache/appcache_url_loader_job.cc b/content/browser/appcache/appcache_url_loader_job.cc index 312c1c6..92f5e83 100644 --- a/content/browser/appcache/appcache_url_loader_job.cc +++ b/content/browser/appcache/appcache_url_loader_job.cc
@@ -72,7 +72,7 @@ // We signal our caller with an empy callback that it needs to perform // the network load. DCHECK(loader_callback_ && !binding_.is_bound()); - std::move(loader_callback_).Run(StartLoaderCallback()); + std::move(loader_callback_).Run({}); weak_factory_.InvalidateWeakPtrs(); is_deleting_soon_ = true; base::ThreadTaskRunnerHandle::Get()->DeleteSoon(FROM_HERE, this); @@ -138,7 +138,7 @@ AppCacheURLLoaderJob::AppCacheURLLoaderJob( AppCacheURLLoaderRequest* appcache_request, AppCacheStorage* storage, - LoaderCallback loader_callback) + URLLoaderRequestHandler::LoaderCallback loader_callback) : storage_(storage->GetWeakPtr()), start_time_tick_(base::TimeTicks::Now()), cache_id_(kAppCacheNoCacheId),
diff --git a/content/browser/appcache/appcache_url_loader_job.h b/content/browser/appcache/appcache_url_loader_job.h index 66f0747..689738db 100644 --- a/content/browser/appcache/appcache_url_loader_job.h +++ b/content/browser/appcache/appcache_url_loader_job.h
@@ -70,7 +70,7 @@ AppCacheURLLoaderJob(AppCacheURLLoaderRequest* appcache_request, AppCacheStorage* storage, - LoaderCallback loader_callback); + URLLoaderRequestHandler::LoaderCallback loader_callback); // Invokes the loader callback which is expected to setup the mojo binding. void CallLoaderCallback(); @@ -121,7 +121,7 @@ // The Callback to be invoked in the network service land to indicate if // the resource request can be serviced via the AppCache. - LoaderCallback loader_callback_; + URLLoaderRequestHandler::LoaderCallback loader_callback_; // The AppCacheRequest instance, used to inform the loader job about range // request headers. Not owned by this class.
diff --git a/content/browser/browser_side_navigation_browsertest.cc b/content/browser/browser_side_navigation_browsertest.cc index cd5a4c0f..5baa8a6 100644 --- a/content/browser/browser_side_navigation_browsertest.cc +++ b/content/browser/browser_side_navigation_browsertest.cc
@@ -23,7 +23,6 @@ #include "content/public/test/browser_test_utils.h" #include "content/public/test/content_browser_test.h" #include "content/public/test/content_browser_test_utils.h" -#include "content/public/test/controllable_http_response.h" #include "content/public/test/navigation_handle_observer.h" #include "content/public/test/test_navigation_observer.h" #include "content/shell/browser/shell.h" @@ -33,6 +32,7 @@ #include "net/base/filename_util.h" #include "net/base/load_flags.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/url_request/url_request_failed_job.h" #include "services/network/public/cpp/features.h" @@ -533,7 +533,8 @@ if (base::FeatureList::IsEnabled(network::features::kNetworkService)) return; - ControllableHttpResponse response(embedded_test_server(), "/main_document"); + net::test_server::ControllableHttpResponse response(embedded_test_server(), + "/main_document"); ASSERT_TRUE(embedded_test_server()->Start()); // 1) Load a new document. Commit the navigation but do not send the full @@ -799,4 +800,53 @@ EXPECT_EQ("#foo", reference_fragment); } +// Regression test for https://crbug.com/796561. +// 1) Start on a document with history.length == 1. +// 2) Create an iframe and call history.pushState at the same time. +// 3) history.back() must work. +IN_PROC_BROWSER_TEST_F(BrowserSideNavigationBrowserTest, + IframeAndPushStateSimultaneously) { + GURL main_url = embedded_test_server()->GetURL("/simple_page.html"); + GURL iframe_url = embedded_test_server()->GetURL("/hello.html"); + + // 1) Start on a new document such that history.length == 1. + { + EXPECT_TRUE(NavigateToURL(shell(), main_url)); + + int history_length; + EXPECT_TRUE(ExecuteScriptAndExtractInt( + shell(), "window.domAutomationController.send(history.length)", + &history_length)); + EXPECT_EQ(1, history_length); + } + + // 2) Create an iframe and call history.pushState at the same time. + { + TestNavigationManager iframe_navigation(shell()->web_contents(), + iframe_url); + ExecuteScriptAsync(shell(), + "let iframe = document.createElement('iframe');" + "iframe.src = '/hello.html';" + "document.body.appendChild(iframe);"); + EXPECT_TRUE(iframe_navigation.WaitForRequestStart()); + + // The iframe navigation is paused. In the meantime, a pushState navigation + // begins and ends. + TestNavigationManager push_state_navigation(shell()->web_contents(), + main_url); + ExecuteScriptAsync(shell(), "window.history.pushState({}, null);"); + push_state_navigation.WaitForNavigationFinished(); + + // The iframe navigation is resumed. + iframe_navigation.WaitForNavigationFinished(); + } + + // 3) history.back() must work. + { + TestNavigationObserver navigation_observer(shell()->web_contents()); + EXPECT_TRUE(ExecuteScript(shell()->web_contents(), "history.back();")); + navigation_observer.Wait(); + } +} + } // namespace content
diff --git a/content/browser/devtools/devtools_agent_host_impl.cc b/content/browser/devtools/devtools_agent_host_impl.cc index cc78fcd..775bec8 100644 --- a/content/browser/devtools/devtools_agent_host_impl.cc +++ b/content/browser/devtools/devtools_agent_host_impl.cc
@@ -79,13 +79,14 @@ // static std::string DevToolsAgentHost::GetProtocolVersion() { // TODO(dgozman): generate this. - return "1.2"; + return "1.3"; } // static bool DevToolsAgentHost::IsSupportedProtocolVersion(const std::string& version) { // TODO(dgozman): generate this. - return version == "1.0" || version == "1.1" || version == "1.2"; + return version == "1.0" || version == "1.1" || version == "1.2" || + version == "1.3"; } // static
diff --git a/content/browser/devtools/protocol/devtools_download_manager_delegate.cc b/content/browser/devtools/protocol/devtools_download_manager_delegate.cc index 860585d..aa386f2 100644 --- a/content/browser/devtools/protocol/devtools_download_manager_delegate.cc +++ b/content/browser/devtools/protocol/devtools_download_manager_delegate.cc
@@ -100,7 +100,7 @@ base::FilePath empty_path = base::FilePath(); callback.Run(empty_path, content::DownloadItem::TARGET_DISPOSITION_OVERWRITE, - content::DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS, empty_path, + download::DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS, empty_path, content::DOWNLOAD_INTERRUPT_REASON_FILE_BLOCKED); return true; } @@ -177,7 +177,7 @@ callback.Run(suggested_path, content::DownloadItem::TARGET_DISPOSITION_OVERWRITE, - content::DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS, + download::DOWNLOAD_DANGER_TYPE_MAYBE_DANGEROUS_CONTENT, suggested_path.AddExtension(FILE_PATH_LITERAL(".crdownload")), content::DOWNLOAD_INTERRUPT_REASON_NONE); }
diff --git a/content/browser/devtools/protocol/devtools_protocol_browsertest.cc b/content/browser/devtools/protocol/devtools_protocol_browsertest.cc index da5ac22..700feac 100644 --- a/content/browser/devtools/protocol/devtools_protocol_browsertest.cc +++ b/content/browser/devtools/protocol/devtools_protocol_browsertest.cc
@@ -2387,7 +2387,7 @@ class CountingDownloadFile : public DownloadFileImpl { public: - CountingDownloadFile(std::unique_ptr<DownloadSaveInfo> save_info, + CountingDownloadFile(std::unique_ptr<download::DownloadSaveInfo> save_info, const base::FilePath& default_downloads_directory, std::unique_ptr<DownloadManager::InputStream> stream, uint32_t download_id, @@ -2444,7 +2444,7 @@ // DownloadFileFactory interface. DownloadFile* CreateFile( - std::unique_ptr<DownloadSaveInfo> save_info, + std::unique_ptr<download::DownloadSaveInfo> save_info, const base::FilePath& default_downloads_directory, std::unique_ptr<DownloadManager::InputStream> stream, uint32_t download_id,
diff --git a/content/browser/devtools/protocol/page_handler.cc b/content/browser/devtools/protocol/page_handler.cc index 2b8fd1f..040572b 100644 --- a/content/browser/devtools/protocol/page_handler.cc +++ b/content/browser/devtools/protocol/page_handler.cc
@@ -631,6 +631,7 @@ Maybe<bool> ignore_invalid_page_ranges, Maybe<String> header_template, Maybe<String> footer_template, + Maybe<bool> prefer_css_page_size, std::unique_ptr<PrintToPDFCallback> callback) { callback->sendFailure(Response::Error("PrintToPDF is not implemented")); return;
diff --git a/content/browser/devtools/protocol/page_handler.h b/content/browser/devtools/protocol/page_handler.h index 6c1e447..b775b58 100644 --- a/content/browser/devtools/protocol/page_handler.h +++ b/content/browser/devtools/protocol/page_handler.h
@@ -124,6 +124,7 @@ Maybe<bool> ignore_invalid_page_ranges, Maybe<String> header_template, Maybe<String> footer_template, + Maybe<bool> prefer_css_page_size, std::unique_ptr<PrintToPDFCallback> callback) override; Response StartScreencast(Maybe<std::string> format, Maybe<int> quality,
diff --git a/content/browser/devtools/protocol/target_auto_attacher.cc b/content/browser/devtools/protocol/target_auto_attacher.cc index 60d8584..b460c7f 100644 --- a/content/browser/devtools/protocol/target_auto_attacher.cc +++ b/content/browser/devtools/protocol/target_auto_attacher.cc
@@ -92,8 +92,7 @@ detach_callback_(detach_callback), render_frame_host_(nullptr), auto_attach_(false), - wait_for_debugger_on_start_(false), - attach_to_frames_(false) {} + wait_for_debugger_on_start_(false) {} TargetAutoAttacher::~TargetAutoAttacher() {} @@ -109,7 +108,7 @@ } void TargetAutoAttacher::UpdateFrames() { - if (!auto_attach_ || !attach_to_frames_) + if (!auto_attach_) return; Hosts new_hosts; @@ -141,7 +140,7 @@ } bool TargetAutoAttacher::ShouldThrottleFramesNavigation() { - return auto_attach_ && attach_to_frames_; + return auto_attach_; } DevToolsAgentHost* TargetAutoAttacher::AutoAttachToFrame( @@ -244,18 +243,6 @@ } } -void TargetAutoAttacher::SetAttachToFrames(bool attach_to_frames) { - if (attach_to_frames_ == attach_to_frames) - return; - attach_to_frames_ = attach_to_frames; - if (attach_to_frames_) { - UpdateFrames(); - } else { - Hosts empty; - ReattachTargetsOfType(empty, DevToolsAgentHost::kTypeFrame, false); - } -} - // -------- ServiceWorkerDevToolsManager::Observer ---------- void TargetAutoAttacher::WorkerCreated(ServiceWorkerDevToolsAgentHost* host,
diff --git a/content/browser/devtools/protocol/target_auto_attacher.h b/content/browser/devtools/protocol/target_auto_attacher.h index 930dbec..aa8d657f 100644 --- a/content/browser/devtools/protocol/target_auto_attacher.h +++ b/content/browser/devtools/protocol/target_auto_attacher.h
@@ -28,7 +28,6 @@ void SetRenderFrameHost(RenderFrameHostImpl* host); void SetAutoAttach(bool auto_attach, bool wait_for_debugger_on_start); - void SetAttachToFrames(bool attach_to_frames); void UpdateServiceWorkers(); void AgentHostClosed(DevToolsAgentHost* host); @@ -60,7 +59,6 @@ bool auto_attach_; bool wait_for_debugger_on_start_; - bool attach_to_frames_; bool auto_attaching_service_workers_ = false; Hosts auto_attached_hosts_;
diff --git a/content/browser/devtools/protocol/target_handler.cc b/content/browser/devtools/protocol/target_handler.cc index 3071bff..371456d 100644 --- a/content/browser/devtools/protocol/target_handler.cc +++ b/content/browser/devtools/protocol/target_handler.cc
@@ -314,13 +314,6 @@ return browser_only_ ? Response::OK() : Response::FallThrough(); } -Response TargetHandler::SetAttachToFrames(bool value) { - auto_attacher_.SetAttachToFrames(value); - if (!auto_attacher_.ShouldThrottleFramesNavigation()) - ClearThrottles(); - return Response::OK(); -} - Response TargetHandler::SetRemoteLocations( std::unique_ptr<protocol::Array<Target::RemoteLocation>>) { return Response::Error("Not supported");
diff --git a/content/browser/devtools/protocol/target_handler.h b/content/browser/devtools/protocol/target_handler.h index c0a83a6..6bb18ca 100644 --- a/content/browser/devtools/protocol/target_handler.h +++ b/content/browser/devtools/protocol/target_handler.h
@@ -47,7 +47,6 @@ Response SetDiscoverTargets(bool discover) override; Response SetAutoAttach(bool auto_attach, bool wait_for_debugger_on_start) override; - Response SetAttachToFrames(bool value) override; Response SetRemoteLocations( std::unique_ptr<protocol::Array<Target::RemoteLocation>>) override; Response AttachToTarget(const std::string& target_id,
diff --git a/content/browser/devtools/render_frame_devtools_agent_host_browsertest.cc b/content/browser/devtools/render_frame_devtools_agent_host_browsertest.cc index 1b3e4f9..97ad017 100644 --- a/content/browser/devtools/render_frame_devtools_agent_host_browsertest.cc +++ b/content/browser/devtools/render_frame_devtools_agent_host_browsertest.cc
@@ -14,10 +14,10 @@ #include "content/public/test/browser_test_utils.h" #include "content/public/test/content_browser_test.h" #include "content/public/test/content_browser_test_utils.h" -#include "content/public/test/controllable_http_response.h" #include "content/public/test/test_navigation_observer.h" #include "content/shell/browser/shell.h" #include "net/dns/mock_host_resolver.h" +#include "net/test/embedded_test_server/controllable_http_response.h" namespace content { @@ -49,8 +49,10 @@ // See https://crbug.com/695203. IN_PROC_BROWSER_TEST_F(RenderFrameDevToolsAgentHostBrowserTest, CancelCrossOriginNavigationAfterReadyToCommit) { - ControllableHttpResponse response_b(embedded_test_server(), "/response_b"); - ControllableHttpResponse response_c(embedded_test_server(), "/response_c"); + net::test_server::ControllableHttpResponse response_b(embedded_test_server(), + "/response_b"); + net::test_server::ControllableHttpResponse response_c(embedded_test_server(), + "/response_c"); EXPECT_TRUE(embedded_test_server()->Start()); // 1) Loads a document.
diff --git a/content/browser/download/download_browsertest.cc b/content/browser/download/download_browsertest.cc index 3955f1c..81a7409 100644 --- a/content/browser/download/download_browsertest.cc +++ b/content/browser/download/download_browsertest.cc
@@ -31,6 +31,7 @@ #include "base/threading/thread_restrictions.h" #include "base/time/time.h" #include "build/build_config.h" +#include "components/download/public/common/download_danger_type.h" #include "content/browser/byte_stream.h" #include "content/browser/download/download_file_factory.h" #include "content/browser/download/download_file_impl.h" @@ -40,7 +41,6 @@ #include "content/browser/download/download_task_runner.h" #include "content/browser/download/parallel_download_utils.h" #include "content/browser/web_contents/web_contents_impl.h" -#include "content/public/browser/download_danger_type.h" #include "content/public/browser/resource_throttle.h" #include "content/public/common/content_features.h" #include "content/public/common/content_paths.h" @@ -165,7 +165,7 @@ class DownloadFileWithDelay : public DownloadFileImpl { public: - DownloadFileWithDelay(std::unique_ptr<DownloadSaveInfo> save_info, + DownloadFileWithDelay(std::unique_ptr<download::DownloadSaveInfo> save_info, const base::FilePath& default_download_directory, std::unique_ptr<DownloadManager::InputStream> stream, uint32_t download_id, @@ -210,7 +210,7 @@ // DownloadFileFactory interface. DownloadFile* CreateFile( - std::unique_ptr<DownloadSaveInfo> save_info, + std::unique_ptr<download::DownloadSaveInfo> save_info, const base::FilePath& default_download_directory, std::unique_ptr<DownloadManager::InputStream> stream, uint32_t download_id, @@ -231,7 +231,7 @@ }; DownloadFileWithDelay::DownloadFileWithDelay( - std::unique_ptr<DownloadSaveInfo> save_info, + std::unique_ptr<download::DownloadSaveInfo> save_info, const base::FilePath& default_download_directory, std::unique_ptr<DownloadManager::InputStream> stream, uint32_t download_id, @@ -290,7 +290,7 @@ DownloadFileWithDelayFactory::~DownloadFileWithDelayFactory() {} DownloadFile* DownloadFileWithDelayFactory::CreateFile( - std::unique_ptr<DownloadSaveInfo> save_info, + std::unique_ptr<download::DownloadSaveInfo> save_info, const base::FilePath& default_download_directory, std::unique_ptr<DownloadManager::InputStream> stream, uint32_t download_id, @@ -325,7 +325,7 @@ class CountingDownloadFile : public DownloadFileImpl { public: - CountingDownloadFile(std::unique_ptr<DownloadSaveInfo> save_info, + CountingDownloadFile(std::unique_ptr<download::DownloadSaveInfo> save_info, const base::FilePath& default_downloads_directory, std::unique_ptr<DownloadManager::InputStream> stream, uint32_t download_id, @@ -383,7 +383,7 @@ // DownloadFileFactory interface. DownloadFile* CreateFile( - std::unique_ptr<DownloadSaveInfo> save_info, + std::unique_ptr<download::DownloadSaveInfo> save_info, const base::FilePath& default_downloads_directory, std::unique_ptr<DownloadManager::InputStream> stream, uint32_t download_id, @@ -397,7 +397,7 @@ class ErrorInjectionDownloadFile : public DownloadFileImpl { public: ErrorInjectionDownloadFile( - std::unique_ptr<DownloadSaveInfo> save_info, + std::unique_ptr<download::DownloadSaveInfo> save_info, const base::FilePath& default_downloads_directory, std::unique_ptr<DownloadManager::InputStream> stream, uint32_t download_id, @@ -444,7 +444,7 @@ // DownloadFileFactory interface. DownloadFile* CreateFile( - std::unique_ptr<DownloadSaveInfo> save_info, + std::unique_ptr<download::DownloadSaveInfo> save_info, const base::FilePath& default_download_directory, std::unique_ptr<DownloadManager::InputStream> stream, uint32_t download_id, @@ -2050,7 +2050,7 @@ "application/octet-stream", "application/octet-stream", base::Time::Now(), base::Time(), parameters.etag, std::string(), kIntermediateSize, parameters.size, std::string(), DownloadItem::INTERRUPTED, - DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS, + download::DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS, DOWNLOAD_INTERRUPT_REASON_NETWORK_FAILED, false, base::Time(), false, std::vector<DownloadItem::ReceivedSlice>()); @@ -2113,7 +2113,7 @@ "application/octet-stream", "application/octet-stream", base::Time::Now(), base::Time(), parameters.etag, std::string(), kIntermediateSize, parameters.size, std::string(), DownloadItem::INTERRUPTED, - DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS, + download::DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS, DOWNLOAD_INTERRUPT_REASON_NETWORK_FAILED, false, base::Time(), false, std::vector<DownloadItem::ReceivedSlice>()); @@ -2163,7 +2163,7 @@ "application/octet-stream", "application/octet-stream", base::Time::Now(), base::Time(), "fake-etag", std::string(), kIntermediateSize, parameters.size, std::string(), DownloadItem::INTERRUPTED, - DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS, + download::DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS, DOWNLOAD_INTERRUPT_REASON_NETWORK_FAILED, false, base::Time(), false, std::vector<DownloadItem::ReceivedSlice>()); @@ -2219,7 +2219,7 @@ base::Time(), parameters.etag, std::string(), kIntermediateSize, parameters.size, std::string(std::begin(kPartialHash), std::end(kPartialHash)), - DownloadItem::INTERRUPTED, DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS, + DownloadItem::INTERRUPTED, download::DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS, DOWNLOAD_INTERRUPT_REASON_NETWORK_FAILED, false, base::Time(), false, std::vector<DownloadItem::ReceivedSlice>()); @@ -2282,7 +2282,7 @@ base::Time(), parameters.etag, std::string(), kIntermediateSize, parameters.size, std::string(std::begin(kPartialHash), std::end(kPartialHash)), - DownloadItem::INTERRUPTED, DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS, + DownloadItem::INTERRUPTED, download::DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS, DOWNLOAD_INTERRUPT_REASON_NETWORK_FAILED, false, base::Time(), false, std::vector<DownloadItem::ReceivedSlice>()); @@ -2353,7 +2353,7 @@ "application/octet-stream", "application/octet-stream", base::Time::Now(), base::Time(), parameters.etag, std::string(), kIntermediateSize, parameters.size, std::string(), DownloadItem::INTERRUPTED, - DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS, + download::DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS, DOWNLOAD_INTERRUPT_REASON_NETWORK_FAILED, false, base::Time(), false, std::vector<DownloadItem::ReceivedSlice>()); @@ -2422,7 +2422,7 @@ "application/octet-stream", "application/octet-stream", base::Time::Now(), base::Time(), parameters.etag, std::string(), kIntermediateSize, parameters.size, std::string(), DownloadItem::INTERRUPTED, - DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS, + download::DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS, DOWNLOAD_INTERRUPT_REASON_NETWORK_FAILED, false, base::Time(), false, std::vector<DownloadItem::ReceivedSlice>()); @@ -2984,7 +2984,7 @@ "application/octet-stream", "application/octet-stream", base::Time::Now(), base::Time(), parameters.etag, parameters.last_modified, kIntermediateSize * 3, parameters.size, std::string(), - DownloadItem::INTERRUPTED, DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS, + DownloadItem::INTERRUPTED, download::DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS, DOWNLOAD_INTERRUPT_REASON_NETWORK_FAILED, false, base::Time(), false, received_slices);
diff --git a/content/browser/download/download_create_info.cc b/content/browser/download/download_create_info.cc index c982cc7..f11d0cf 100644 --- a/content/browser/download/download_create_info.cc +++ b/content/browser/download/download_create_info.cc
@@ -15,7 +15,7 @@ DownloadCreateInfo::DownloadCreateInfo( const base::Time& start_time, - std::unique_ptr<DownloadSaveInfo> save_info) + std::unique_ptr<download::DownloadSaveInfo> save_info) : download_id(DownloadItem::kInvalidId), start_time(start_time), total_bytes(0), @@ -31,7 +31,7 @@ DownloadCreateInfo::DownloadCreateInfo() : DownloadCreateInfo(base::Time(), - base::WrapUnique(new DownloadSaveInfo)) {} + base::WrapUnique(new download::DownloadSaveInfo)) {} DownloadCreateInfo::~DownloadCreateInfo() {}
diff --git a/content/browser/download/download_create_info.h b/content/browser/download/download_create_info.h index 6fee6ed..dfe88e2 100644 --- a/content/browser/download/download_create_info.h +++ b/content/browser/download/download_create_info.h
@@ -15,12 +15,12 @@ #include "base/memory/ref_counted.h" #include "base/optional.h" #include "base/time/time.h" +#include "components/download/public/common/download_save_info.h" +#include "components/download/public/common/download_source.h" #include "content/browser/download/download_file.h" #include "content/browser/download/download_request_handle.h" #include "content/common/content_export.h" #include "content/public/browser/download_interrupt_reasons.h" -#include "content/public/browser/download_save_info.h" -#include "content/public/browser/download_source.h" #include "net/http/http_response_info.h" #include "services/metrics/public/cpp/ukm_source_id.h" #include "ui/base/page_transition_types.h" @@ -36,7 +36,7 @@ // want to pass |DownloadItem|s between threads. struct CONTENT_EXPORT DownloadCreateInfo { DownloadCreateInfo(const base::Time& start_time, - std::unique_ptr<DownloadSaveInfo> save_info); + std::unique_ptr<download::DownloadSaveInfo> save_info); DownloadCreateInfo(); ~DownloadCreateInfo(); @@ -100,7 +100,7 @@ DownloadInterruptReason result; // The download file save info. - std::unique_ptr<DownloadSaveInfo> save_info; + std::unique_ptr<download::DownloadSaveInfo> save_info; // The handle to the URLRequest sourcing this download. std::unique_ptr<DownloadRequestHandleInterface> request_handle; @@ -148,7 +148,7 @@ ukm::SourceId ukm_source_id; // Source of the download, used in metrics. - DownloadSource download_source = DownloadSource::UNKNOWN; + download::DownloadSource download_source = download::DownloadSource::UNKNOWN; private: DISALLOW_COPY_AND_ASSIGN(DownloadCreateInfo);
diff --git a/content/browser/download/download_file_factory.cc b/content/browser/download/download_file_factory.cc index 9030353..1b457ea 100644 --- a/content/browser/download/download_file_factory.cc +++ b/content/browser/download/download_file_factory.cc
@@ -13,7 +13,7 @@ DownloadFileFactory::~DownloadFileFactory() {} DownloadFile* DownloadFileFactory::CreateFile( - std::unique_ptr<DownloadSaveInfo> save_info, + std::unique_ptr<download::DownloadSaveInfo> save_info, const base::FilePath& default_downloads_directory, std::unique_ptr<DownloadManager::InputStream> stream, uint32_t download_id,
diff --git a/content/browser/download/download_file_factory.h b/content/browser/download/download_file_factory.h index bad3ad2..6dcf3c5bc 100644 --- a/content/browser/download/download_file_factory.h +++ b/content/browser/download/download_file_factory.h
@@ -16,18 +16,21 @@ #include "content/common/content_export.h" #include "url/gurl.h" +namespace download { +struct DownloadSaveInfo; +} + namespace content { class DownloadDestinationObserver; class DownloadFile; -struct DownloadSaveInfo; class CONTENT_EXPORT DownloadFileFactory { public: virtual ~DownloadFileFactory(); virtual DownloadFile* CreateFile( - std::unique_ptr<DownloadSaveInfo> save_info, + std::unique_ptr<download::DownloadSaveInfo> save_info, const base::FilePath& default_downloads_directory, std::unique_ptr<DownloadManager::InputStream> stream, uint32_t download_id,
diff --git a/content/browser/download/download_file_impl.cc b/content/browser/download/download_file_impl.cc index 6edb2d4..37385f7 100644 --- a/content/browser/download/download_file_impl.cc +++ b/content/browser/download/download_file_impl.cc
@@ -119,7 +119,7 @@ return; } - if (length_ == DownloadSaveInfo::kLengthFullContent || + if (length_ == download::DownloadSaveInfo::kLengthFullContent || length_ > offset - offset_) { length_ = offset - offset_; } @@ -194,7 +194,7 @@ } DownloadFileImpl::DownloadFileImpl( - std::unique_ptr<DownloadSaveInfo> save_info, + std::unique_ptr<download::DownloadSaveInfo> save_info, const base::FilePath& default_download_directory, std::unique_ptr<DownloadManager::InputStream> stream, uint32_t download_id, @@ -208,7 +208,7 @@ } DownloadFileImpl::DownloadFileImpl( - std::unique_ptr<DownloadSaveInfo> save_info, + std::unique_ptr<download::DownloadSaveInfo> save_info, const base::FilePath& default_download_directory, uint32_t download_id, base::WeakPtr<DownloadDestinationObserver> observer) @@ -345,7 +345,8 @@ } } - if (source_stream->length() != DownloadSaveInfo::kLengthFullContent && + if (source_stream->length() != + download::DownloadSaveInfo::kLengthFullContent && source_stream->bytes_written() + static_cast<int64_t>(bytes_available_to_write) > source_stream->length()) { @@ -398,7 +399,8 @@ DownloadInterruptReason DownloadFileImpl::HandleStreamCompletionStatus( SourceStream* source_stream) { DownloadInterruptReason reason = source_stream->GetCompletionStatus(); - if (source_stream->length() == DownloadSaveInfo::kLengthFullContent && + if (source_stream->length() == + download::DownloadSaveInfo::kLengthFullContent && !received_slices_.empty() && (source_stream->offset() == received_slices_.back().offset + received_slices_.back().received_bytes) && @@ -651,7 +653,8 @@ source_stream->set_finished(true); if (should_terminate) CancelRequest(source_stream->offset()); - if (source_stream->length() == DownloadSaveInfo::kLengthFullContent) { + if (source_stream->length() == + download::DownloadSaveInfo::kLengthFullContent) { SetPotentialFileLength(source_stream->offset() + source_stream->bytes_written()); } @@ -793,7 +796,7 @@ int64_t upper_range = source_stream->offset() + source_stream->length(); if ((!preceding_neighbor->is_finished() && (preceding_neighbor->length() == - DownloadSaveInfo::kLengthFullContent || + download::DownloadSaveInfo::kLengthFullContent || preceding_neighbor->offset() + preceding_neighbor->length() >= upper_range)) || (preceding_neighbor->offset() + preceding_neighbor->bytes_written() >=
diff --git a/content/browser/download/download_file_impl.h b/content/browser/download/download_file_impl.h index 3285a64..af486915 100644 --- a/content/browser/download/download_file_impl.h +++ b/content/browser/download/download_file_impl.h
@@ -22,11 +22,11 @@ #include "base/sequence_checker.h" #include "base/time/time.h" #include "base/timer/timer.h" +#include "components/download/public/common/download_save_info.h" #include "content/browser/byte_stream.h" #include "content/browser/download/base_file.h" #include "content/browser/download/rate_estimator.h" #include "content/public/browser/download_item.h" -#include "content/public/browser/download_save_info.h" #include "content/public/common/download_stream.mojom.h" #include "mojo/public/cpp/bindings/binding.h" #include "mojo/public/cpp/system/simple_watcher.h" @@ -45,7 +45,7 @@ // Note that the DownloadFileImpl automatically reads from the passed in // |stream|, and sends updates and status of those reads to the // DownloadDestinationObserver. - DownloadFileImpl(std::unique_ptr<DownloadSaveInfo> save_info, + DownloadFileImpl(std::unique_ptr<download::DownloadSaveInfo> save_info, const base::FilePath& default_downloads_directory, std::unique_ptr<DownloadManager::InputStream> stream, uint32_t download_id, @@ -203,7 +203,7 @@ private: friend class DownloadFileTest; - DownloadFileImpl(std::unique_ptr<DownloadSaveInfo> save_info, + DownloadFileImpl(std::unique_ptr<download::DownloadSaveInfo> save_info, const base::FilePath& default_downloads_directory, uint32_t download_id, base::WeakPtr<DownloadDestinationObserver> observer); @@ -311,7 +311,7 @@ // DownloadSaveInfo provided during construction. Since the DownloadFileImpl // can be created on any thread, this holds the save_info_ until it can be // used to initialize file_ on the download sequence. - std::unique_ptr<DownloadSaveInfo> save_info_; + std::unique_ptr<download::DownloadSaveInfo> save_info_; // The default directory for creating the download file. base::FilePath default_download_directory_;
diff --git a/content/browser/download/download_file_unittest.cc b/content/browser/download/download_file_unittest.cc index 9b7b0d0..9ff49c9a 100644 --- a/content/browser/download/download_file_unittest.cc +++ b/content/browser/download/download_file_unittest.cc
@@ -117,7 +117,7 @@ // retries renames failed due to ACCESS_DENIED. class TestDownloadFileImpl : public DownloadFileImpl { public: - TestDownloadFileImpl(std::unique_ptr<DownloadSaveInfo> save_info, + TestDownloadFileImpl(std::unique_ptr<download::DownloadSaveInfo> save_info, const base::FilePath& default_downloads_directory, std::unique_ptr<DownloadManager::InputStream> stream, uint32_t download_id, @@ -221,7 +221,8 @@ .WillOnce(Invoke(this, &DownloadFileTest::RegisterCallback)) .RetiresOnSaturation(); - std::unique_ptr<DownloadSaveInfo> save_info(new DownloadSaveInfo()); + std::unique_ptr<download::DownloadSaveInfo> save_info( + new download::DownloadSaveInfo()); save_info->offset = offset; save_info->length = length; @@ -920,7 +921,7 @@ download_file_->AddInputStream( std::make_unique<DownloadManager::InputStream>( std::unique_ptr<ByteStreamReader>(additional_streams_[0])), - stream_0_length, DownloadSaveInfo::kLengthFullContent); + stream_0_length, download::DownloadSaveInfo::kLengthFullContent); sink_callback_.Run(); base::RunLoop().RunUntilIdle(); @@ -971,7 +972,8 @@ download_file_->AddInputStream( std::make_unique<DownloadManager::InputStream>( std::unique_ptr<ByteStreamReader>(additional_streams_[1])), - stream_0_length + stream_1_length, DownloadSaveInfo::kLengthFullContent); + stream_0_length + stream_1_length, + download::DownloadSaveInfo::kLengthFullContent); sink_callback_.Run(); base::RunLoop().RunUntilIdle(); @@ -995,8 +997,9 @@ TEST_F(DownloadFileTest, MutipleStreamsFirstStreamWriteAllData) { int64_t stream_0_length = GetBuffersLength(kTestData8, 4); - ASSERT_TRUE(CreateDownloadFile(0, DownloadSaveInfo::kLengthFullContent, true, - DownloadItem::ReceivedSlices())); + ASSERT_TRUE(CreateDownloadFile(0, + download::DownloadSaveInfo::kLengthFullContent, + true, DownloadItem::ReceivedSlices())); PrepareStream(&input_stream_, 0, false, true, kTestData8, 4); @@ -1013,7 +1016,7 @@ download_file_->AddInputStream( std::make_unique<DownloadManager::InputStream>( std::unique_ptr<ByteStreamReader>(additional_streams_[0])), - stream_0_length - 1, DownloadSaveInfo::kLengthFullContent); + stream_0_length - 1, download::DownloadSaveInfo::kLengthFullContent); base::RunLoop().RunUntilIdle(); SourceStreamTestData stream_data_0(0, stream_0_length, true); @@ -1054,7 +1057,7 @@ download_file_->AddInputStream( std::make_unique<DownloadManager::InputStream>( std::unique_ptr<ByteStreamReader>(additional_streams_[0])), - 0, DownloadSaveInfo::kLengthFullContent); + 0, download::DownloadSaveInfo::kLengthFullContent); // The stream should get terminated and reset the callback. EXPECT_TRUE(sink_callback_.is_null());
diff --git a/content/browser/download/download_item_factory.h b/content/browser/download/download_item_factory.h index a1f64a8..661f9a4 100644 --- a/content/browser/download/download_item_factory.h +++ b/content/browser/download/download_item_factory.h
@@ -56,7 +56,7 @@ int64_t total_bytes, const std::string& hash, DownloadItem::DownloadState state, - DownloadDangerType danger_type, + download::DownloadDangerType danger_type, DownloadInterruptReason interrupt_reason, bool opened, base::Time last_access_time,
diff --git a/content/browser/download/download_item_impl.cc b/content/browser/download/download_item_impl.cc index 09bf3aa..ffc352d0 100644 --- a/content/browser/download/download_item_impl.cc +++ b/content/browser/download/download_item_impl.cc
@@ -40,6 +40,7 @@ #include "base/strings/utf_string_conversions.h" #include "base/task_runner_util.h" #include "components/download/downloader/in_progress/in_progress_cache.h" +#include "components/download/public/common/download_danger_type.h" #include "content/browser/download/download_create_info.h" #include "content/browser/download/download_file.h" #include "content/browser/download/download_interrupt_reasons_impl.h" @@ -57,7 +58,6 @@ #include "content/public/browser/browser_context.h" #include "content/public/browser/browser_thread.h" #include "content/public/browser/content_browser_client.h" -#include "content/public/browser/download_danger_type.h" #include "content/public/browser/download_interrupt_reasons.h" #include "content/public/browser/download_url_parameters.h" #include "content/public/browser/storage_partition.h" @@ -141,25 +141,25 @@ } } -std::string GetDownloadDangerNames(DownloadDangerType type) { +std::string GetDownloadDangerNames(download::DownloadDangerType type) { switch (type) { - case DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS: + case download::DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS: return "NOT_DANGEROUS"; - case DOWNLOAD_DANGER_TYPE_DANGEROUS_FILE: + case download::DOWNLOAD_DANGER_TYPE_DANGEROUS_FILE: return "DANGEROUS_FILE"; - case DOWNLOAD_DANGER_TYPE_DANGEROUS_URL: + case download::DOWNLOAD_DANGER_TYPE_DANGEROUS_URL: return "DANGEROUS_URL"; - case DOWNLOAD_DANGER_TYPE_DANGEROUS_CONTENT: + case download::DOWNLOAD_DANGER_TYPE_DANGEROUS_CONTENT: return "DANGEROUS_CONTENT"; - case DOWNLOAD_DANGER_TYPE_MAYBE_DANGEROUS_CONTENT: + case download::DOWNLOAD_DANGER_TYPE_MAYBE_DANGEROUS_CONTENT: return "MAYBE_DANGEROUS_CONTENT"; - case DOWNLOAD_DANGER_TYPE_UNCOMMON_CONTENT: + case download::DOWNLOAD_DANGER_TYPE_UNCOMMON_CONTENT: return "UNCOMMON_CONTENT"; - case DOWNLOAD_DANGER_TYPE_USER_VALIDATED: + case download::DOWNLOAD_DANGER_TYPE_USER_VALIDATED: return "USER_VALIDATED"; - case DOWNLOAD_DANGER_TYPE_DANGEROUS_HOST: + case download::DOWNLOAD_DANGER_TYPE_DANGEROUS_HOST: return "DANGEROUS_HOST"; - case DOWNLOAD_DANGER_TYPE_POTENTIALLY_UNWANTED: + case download::DOWNLOAD_DANGER_TYPE_POTENTIALLY_UNWANTED: return "POTENTIALLY_UNWANTED"; default: NOTREACHED(); @@ -175,7 +175,7 @@ std::string original_url, std::string final_url, std::string file_name, - DownloadDangerType danger_type, + download::DownloadDangerType danger_type, int64_t start_offset, bool has_user_gesture) : download_type_(download_type), @@ -216,7 +216,7 @@ std::string original_url_; std::string final_url_; std::string file_name_; - DownloadDangerType danger_type_; + download::DownloadDangerType danger_type_; int64_t start_offset_; bool has_user_gesture_; DISALLOW_COPY_AND_ASSIGN(DownloadItemActivatedData); @@ -310,7 +310,7 @@ int64_t total_bytes, const std::string& hash, DownloadItem::DownloadState state, - DownloadDangerType danger_type, + download::DownloadDangerType danger_type, DownloadInterruptReason interrupt_reason, bool opened, base::Time last_access_time, @@ -479,7 +479,7 @@ RecordDangerousDownloadAccept(GetDangerType(), GetTargetFilePath()); - danger_type_ = DOWNLOAD_DANGER_TYPE_USER_VALIDATED; + danger_type_ = download::DOWNLOAD_DANGER_TYPE_USER_VALIDATED; TRACE_EVENT_INSTANT1("download", "DownloadItemSaftyStateUpdated", TRACE_EVENT_SCOPE_THREAD, "danger_type", @@ -858,15 +858,15 @@ } bool DownloadItemImpl::IsDangerous() const { - return (danger_type_ == DOWNLOAD_DANGER_TYPE_DANGEROUS_FILE || - danger_type_ == DOWNLOAD_DANGER_TYPE_DANGEROUS_URL || - danger_type_ == DOWNLOAD_DANGER_TYPE_DANGEROUS_CONTENT || - danger_type_ == DOWNLOAD_DANGER_TYPE_UNCOMMON_CONTENT || - danger_type_ == DOWNLOAD_DANGER_TYPE_DANGEROUS_HOST || - danger_type_ == DOWNLOAD_DANGER_TYPE_POTENTIALLY_UNWANTED); + return (danger_type_ == download::DOWNLOAD_DANGER_TYPE_DANGEROUS_FILE || + danger_type_ == download::DOWNLOAD_DANGER_TYPE_DANGEROUS_URL || + danger_type_ == download::DOWNLOAD_DANGER_TYPE_DANGEROUS_CONTENT || + danger_type_ == download::DOWNLOAD_DANGER_TYPE_UNCOMMON_CONTENT || + danger_type_ == download::DOWNLOAD_DANGER_TYPE_DANGEROUS_HOST || + danger_type_ == download::DOWNLOAD_DANGER_TYPE_POTENTIALLY_UNWANTED); } -DownloadDangerType DownloadItemImpl::GetDangerType() const { +download::DownloadDangerType DownloadItemImpl::GetDangerType() const { return danger_type_; } @@ -977,8 +977,9 @@ return nullptr; } -void DownloadItemImpl::OnContentCheckCompleted(DownloadDangerType danger_type, - DownloadInterruptReason reason) { +void DownloadItemImpl::OnContentCheckCompleted( + download::DownloadDangerType danger_type, + DownloadInterruptReason reason) { DCHECK_CURRENTLY_ON(BrowserThread::UI); DCHECK(AllDataSaved()); @@ -1390,7 +1391,7 @@ // Read data from in-progress cache. auto in_progress_entry = GetInProgressEntry(guid_, GetBrowserContext()); if (in_progress_entry) - download_source_ = ToDownloadSource(in_progress_entry->download_source); + download_source_ = in_progress_entry->download_source; } DVLOG(20) << __func__ << "() " << DebugString(true); @@ -1536,7 +1537,7 @@ void DownloadItemImpl::OnDownloadTargetDetermined( const base::FilePath& target_path, TargetDisposition disposition, - DownloadDangerType danger_type, + download::DownloadDangerType danger_type, const base::FilePath& intermediate_path, DownloadInterruptReason interrupt_reason) { DCHECK_CURRENTLY_ON(BrowserThread::UI); @@ -2223,7 +2224,7 @@ } } -void DownloadItemImpl::SetDangerType(DownloadDangerType danger_type) { +void DownloadItemImpl::SetDangerType(download::DownloadDangerType danger_type) { if (danger_type != danger_type_) { TRACE_EVENT_INSTANT1("download", "DownloadItemSaftyStateUpdated", TRACE_EVENT_SCOPE_THREAD, "danger_type", @@ -2231,14 +2232,15 @@ } // Only record the Malicious UMA stat if it's going from {not malicious} -> // {malicious}. - if ((danger_type_ == DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS || - danger_type_ == DOWNLOAD_DANGER_TYPE_DANGEROUS_FILE || - danger_type_ == DOWNLOAD_DANGER_TYPE_UNCOMMON_CONTENT || - danger_type_ == DOWNLOAD_DANGER_TYPE_MAYBE_DANGEROUS_CONTENT) && - (danger_type == DOWNLOAD_DANGER_TYPE_DANGEROUS_HOST || - danger_type == DOWNLOAD_DANGER_TYPE_DANGEROUS_URL || - danger_type == DOWNLOAD_DANGER_TYPE_DANGEROUS_CONTENT || - danger_type == DOWNLOAD_DANGER_TYPE_POTENTIALLY_UNWANTED)) { + if ((danger_type_ == download::DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS || + danger_type_ == download::DOWNLOAD_DANGER_TYPE_DANGEROUS_FILE || + danger_type_ == download::DOWNLOAD_DANGER_TYPE_UNCOMMON_CONTENT || + danger_type_ == + download::DOWNLOAD_DANGER_TYPE_MAYBE_DANGEROUS_CONTENT) && + (danger_type == download::DOWNLOAD_DANGER_TYPE_DANGEROUS_HOST || + danger_type == download::DOWNLOAD_DANGER_TYPE_DANGEROUS_URL || + danger_type == download::DOWNLOAD_DANGER_TYPE_DANGEROUS_CONTENT || + danger_type == download::DOWNLOAD_DANGER_TYPE_POTENTIALLY_UNWANTED)) { RecordMaliciousDownloadClassified(danger_type); } danger_type_ = danger_type;
diff --git a/content/browser/download/download_item_impl.h b/content/browser/download/download_item_impl.h index 98ee3b4..a089909 100644 --- a/content/browser/download/download_item_impl.h +++ b/content/browser/download/download_item_impl.h
@@ -172,7 +172,7 @@ int64_t total_bytes, const std::string& hash, DownloadItem::DownloadState state, - DownloadDangerType danger_type, + download::DownloadDangerType danger_type, DownloadInterruptReason interrupt_reason, bool opened, base::Time last_access_time, @@ -246,7 +246,7 @@ bool GetFileExternallyRemoved() const override; void DeleteFile(const base::Callback<void(bool)>& callback) override; bool IsDangerous() const override; - DownloadDangerType GetDangerType() const override; + download::DownloadDangerType GetDangerType() const override; bool TimeRemaining(base::TimeDelta* remaining) const override; int64_t CurrentSpeed() const override; int PercentComplete() const override; @@ -267,7 +267,7 @@ bool IsTransient() const override; BrowserContext* GetBrowserContext() const override; WebContents* GetWebContents() const override; - void OnContentCheckCompleted(DownloadDangerType danger_type, + void OnContentCheckCompleted(download::DownloadDangerType danger_type, DownloadInterruptReason reason) override; void SetOpenWhenComplete(bool open) override; void SetOpened(bool opened) override; @@ -316,7 +316,7 @@ // should be considered complete. virtual void MarkAsComplete(); - DownloadSource download_source() const { return download_source_; } + download::DownloadSource download_source() const { return download_source_; } // DownloadDestinationObserver void DestinationUpdate( @@ -511,7 +511,7 @@ virtual void OnDownloadTargetDetermined( const base::FilePath& target_path, TargetDisposition disposition, - DownloadDangerType danger_type, + download::DownloadDangerType danger_type, const base::FilePath& intermediate_path, DownloadInterruptReason interrupt_reason); @@ -578,7 +578,7 @@ void TransitionTo(DownloadInternalState new_state); // Set the |danger_type_| and invoke observers if necessary. - void SetDangerType(DownloadDangerType danger_type); + void SetDangerType(download::DownloadDangerType danger_type); void SetFullPath(const base::FilePath& new_path); @@ -659,7 +659,8 @@ DownloadInternalState state_ = INITIAL_INTERNAL; // Current danger type for the download. - DownloadDangerType danger_type_ = DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS; + download::DownloadDangerType danger_type_ = + download::DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS; // The views of this item in the download shelf and download contents. base::ObserverList<Observer> observers_; @@ -748,7 +749,7 @@ bool fetch_error_body_ = false; // Source of the download, used in metrics. - DownloadSource download_source_ = DownloadSource::UNKNOWN; + download::DownloadSource download_source_ = download::DownloadSource::UNKNOWN; base::WeakPtrFactory<DownloadItemImpl> weak_ptr_factory_;
diff --git a/content/browser/download/download_item_impl_delegate.cc b/content/browser/download/download_item_impl_delegate.cc index 73424b5f..78775f8 100644 --- a/content/browser/download/download_item_impl_delegate.cc +++ b/content/browser/download/download_item_impl_delegate.cc
@@ -5,6 +5,7 @@ #include "content/browser/download/download_item_impl_delegate.h" #include "base/logging.h" +#include "components/download/public/common/download_danger_type.h" #include "content/browser/download/download_item_impl.h" namespace content { @@ -32,7 +33,7 @@ // TODO(rdsmith/asanka): Do something useful if forced file path is null. base::FilePath target_path(download->GetForcedFilePath()); callback.Run(target_path, DownloadItem::TARGET_DISPOSITION_OVERWRITE, - DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS, target_path, + download::DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS, target_path, DOWNLOAD_INTERRUPT_REASON_NONE); }
diff --git a/content/browser/download/download_item_impl_delegate.h b/content/browser/download/download_item_impl_delegate.h index 9e6fe97..2778d40f 100644 --- a/content/browser/download/download_item_impl_delegate.h +++ b/content/browser/download/download_item_impl_delegate.h
@@ -11,7 +11,6 @@ #include "base/files/file_path.h" #include "base/macros.h" #include "content/common/content_export.h" -#include "content/public/browser/download_danger_type.h" #include "content/public/browser/download_item.h" #include "content/public/browser/download_manager_delegate.h" #include "content/public/browser/download_url_parameters.h"
diff --git a/content/browser/download/download_item_impl_unittest.cc b/content/browser/download/download_item_impl_unittest.cc index 6b0e71b..da9375b 100644 --- a/content/browser/download/download_item_impl_unittest.cc +++ b/content/browser/download/download_item_impl_unittest.cc
@@ -268,8 +268,8 @@ base::test::ScopedTaskEnvironment::ExecutionMode::QUEUED), next_download_id_(DownloadItem::kInvalidId + 1) { create_info_.reset(new DownloadCreateInfo()); - create_info_->save_info = - std::unique_ptr<DownloadSaveInfo>(new DownloadSaveInfo()); + create_info_->save_info = std::unique_ptr<download::DownloadSaveInfo>( + new download::DownloadSaveInfo()); create_info_->save_info->prompt_for_save_location = false; create_info_->url_chain.push_back(GURL("http://example.com/download")); create_info_->etag = "SomethingToSatisfyResumption"; @@ -341,8 +341,9 @@ // Perform the intermediate rename for |item|. The target path for the // download will be set to kDummyTargetPath. Returns the MockDownloadFile* // that was added to the DownloadItem. - MockDownloadFile* DoIntermediateRename(DownloadItemImpl* item, - DownloadDangerType danger_type) { + MockDownloadFile* DoIntermediateRename( + DownloadItemImpl* item, + download::DownloadDangerType danger_type) { EXPECT_EQ(DownloadItem::IN_PROGRESS, item->GetState()); EXPECT_TRUE(item->GetTargetFilePath().empty()); DownloadTargetCallback callback; @@ -429,7 +430,7 @@ TEST_F(DownloadItemTest, NotificationAfterUpdate) { DownloadItemImpl* item = CreateDownloadItem(); MockDownloadFile* file = - DoIntermediateRename(item, DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS); + DoIntermediateRename(item, download::DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS); ASSERT_EQ(DownloadItem::IN_PROGRESS, item->GetState()); TestDownloadItemObserver observer(item); @@ -464,7 +465,7 @@ DownloadItemImpl* item = CreateDownloadItem(); TestDownloadItemObserver observer(item); MockDownloadFile* download_file = - DoIntermediateRename(item, DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS); + DoIntermediateRename(item, download::DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS); ASSERT_TRUE(observer.CheckAndResetDownloadUpdated()); DoDestinationComplete(item, download_file); ASSERT_TRUE(observer.CheckAndResetDownloadUpdated()); @@ -481,7 +482,7 @@ TEST_F(DownloadItemTest, NotificationAfterInterrupted) { DownloadItemImpl* item = CreateDownloadItem(); MockDownloadFile* download_file = - DoIntermediateRename(item, DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS); + DoIntermediateRename(item, download::DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS); EXPECT_CALL(*download_file, Cancel()); TestDownloadItemObserver observer(item); @@ -518,27 +519,29 @@ TEST_F(DownloadItemTest, NotificationAfterOnContentCheckCompleted) { // Setting to NOT_DANGEROUS does not trigger a notification. DownloadItemImpl* safe_item = CreateDownloadItem(); - MockDownloadFile* download_file = - DoIntermediateRename(safe_item, DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS); + MockDownloadFile* download_file = DoIntermediateRename( + safe_item, download::DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS); TestDownloadItemObserver safe_observer(safe_item); safe_item->OnAllDataSaved(0, std::unique_ptr<crypto::SecureHash>()); EXPECT_TRUE(safe_observer.CheckAndResetDownloadUpdated()); - safe_item->OnContentCheckCompleted(DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS, - DOWNLOAD_INTERRUPT_REASON_NONE); + safe_item->OnContentCheckCompleted( + download::DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS, + DOWNLOAD_INTERRUPT_REASON_NONE); EXPECT_TRUE(safe_observer.CheckAndResetDownloadUpdated()); CleanupItem(safe_item, download_file, DownloadItem::IN_PROGRESS); // Setting to unsafe url or unsafe file should trigger a notification. DownloadItemImpl* unsafeurl_item = CreateDownloadItem(); - download_file = - DoIntermediateRename(unsafeurl_item, DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS); + download_file = DoIntermediateRename( + unsafeurl_item, download::DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS); TestDownloadItemObserver unsafeurl_observer(unsafeurl_item); unsafeurl_item->OnAllDataSaved(0, std::unique_ptr<crypto::SecureHash>()); EXPECT_TRUE(unsafeurl_observer.CheckAndResetDownloadUpdated()); - unsafeurl_item->OnContentCheckCompleted(DOWNLOAD_DANGER_TYPE_DANGEROUS_URL, - DOWNLOAD_INTERRUPT_REASON_NONE); + unsafeurl_item->OnContentCheckCompleted( + download::DOWNLOAD_DANGER_TYPE_DANGEROUS_URL, + DOWNLOAD_INTERRUPT_REASON_NONE); EXPECT_TRUE(unsafeurl_observer.CheckAndResetDownloadUpdated()); EXPECT_CALL(*mock_delegate(), ShouldCompleteDownload(_, _)) @@ -549,14 +552,15 @@ CleanupItem(unsafeurl_item, download_file, DownloadItem::IN_PROGRESS); DownloadItemImpl* unsafefile_item = CreateDownloadItem(); - download_file = - DoIntermediateRename(unsafefile_item, DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS); + download_file = DoIntermediateRename( + unsafefile_item, download::DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS); TestDownloadItemObserver unsafefile_observer(unsafefile_item); unsafefile_item->OnAllDataSaved(0, std::unique_ptr<crypto::SecureHash>()); EXPECT_TRUE(unsafefile_observer.CheckAndResetDownloadUpdated()); - unsafefile_item->OnContentCheckCompleted(DOWNLOAD_DANGER_TYPE_DANGEROUS_FILE, - DOWNLOAD_INTERRUPT_REASON_NONE); + unsafefile_item->OnContentCheckCompleted( + download::DOWNLOAD_DANGER_TYPE_DANGEROUS_FILE, + DOWNLOAD_INTERRUPT_REASON_NONE); EXPECT_TRUE(unsafefile_observer.CheckAndResetDownloadUpdated()); EXPECT_CALL(*mock_delegate(), ShouldCompleteDownload(_, _)) @@ -588,7 +592,7 @@ // Currently, a notification would be generated if the danger type is anything // other than NOT_DANGEROUS. callback.Run(target_path, DownloadItem::TARGET_DISPOSITION_OVERWRITE, - DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS, intermediate_path, + download::DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS, intermediate_path, DOWNLOAD_INTERRUPT_REASON_NONE); EXPECT_FALSE(observer.CheckAndResetDownloadUpdated()); task_environment_.RunUntilIdle(); @@ -629,7 +633,7 @@ DownloadItemImpl* item = CreateDownloadItem(); TestDownloadItemObserver observer(item); MockDownloadFile* download_file = - DoIntermediateRename(item, DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS); + DoIntermediateRename(item, download::DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS); // Interrupt the download using a continuable interrupt after writing a single // byte. An intermediate file with data shouldn't be discarding after a @@ -684,7 +688,7 @@ DownloadItemImpl* item = CreateDownloadItem(); TestDownloadItemObserver observer(item); MockDownloadFile* download_file = - DoIntermediateRename(item, DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS); + DoIntermediateRename(item, download::DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS); // Interrupt the download, using a restartable interrupt. EXPECT_CALL(*download_file, Cancel()); @@ -724,7 +728,7 @@ DownloadItemImpl* item = CreateDownloadItem(); TestDownloadItemObserver observer(item); MockDownloadFile* download_file = - DoIntermediateRename(item, DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS); + DoIntermediateRename(item, download::DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS); // Interrupt the download, using a restartable interrupt. EXPECT_CALL(*download_file, Cancel()); @@ -751,7 +755,7 @@ DownloadItemImpl* item = CreateDownloadItem(); TestDownloadItemObserver observer(item); MockDownloadFile* download_file = - DoIntermediateRename(item, DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS); + DoIntermediateRename(item, download::DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS); // Interrupt the download with content length mismatch error. The intermediate // file with data shouldn't be discarded. @@ -794,7 +798,7 @@ DownloadItemImpl* item = CreateDownloadItem(); TestDownloadItemObserver observer(item); MockDownloadFile* download_file = - DoIntermediateRename(item, DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS); + DoIntermediateRename(item, download::DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS); // Fail final rename with unresumable reason. EXPECT_CALL(*mock_delegate(), ShouldCompleteDownload(item, _)) @@ -879,7 +883,7 @@ ASSERT_FALSE(callback.is_null()); base::ResetAndReturn(&callback).Run( target_path, DownloadItem::TARGET_DISPOSITION_OVERWRITE, - DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS, intermediate_path, + download::DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS, intermediate_path, DOWNLOAD_INTERRUPT_REASON_NONE); task_environment_.RunUntilIdle(); @@ -922,7 +926,7 @@ DownloadItemImpl* item = CreateDownloadItem(); MockDownloadFile* download_file = - DoIntermediateRename(item, DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS); + DoIntermediateRename(item, download::DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS); ASSERT_TRUE(item->GetResponseHeaders()); EXPECT_EQ(kFirstResponseCode, item->GetResponseHeaders()->response_code()); EXPECT_EQ(kContentDisposition, item->GetContentDisposition()); @@ -971,7 +975,7 @@ ASSERT_FALSE(target_callback.is_null()); target_callback.Run(base::FilePath(kDummyTargetPath), DownloadItem::TARGET_DISPOSITION_OVERWRITE, - DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS, + download::DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS, base::FilePath(kDummyIntermediatePath), DOWNLOAD_INTERRUPT_REASON_NONE); task_environment_.RunUntilIdle(); @@ -1007,7 +1011,7 @@ DownloadItemImpl* item = CreateDownloadItem(); MockDownloadFile* download_file = - DoIntermediateRename(item, DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS); + DoIntermediateRename(item, download::DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS); EXPECT_CALL(*mock_delegate(), MockResumeInterruptedDownload(_, _)); EXPECT_CALL(*download_file, Detach()); item->DestinationObserverAsWeakPtr()->DestinationError( @@ -1057,7 +1061,7 @@ DownloadItemImpl* item = CreateDownloadItem(); MockDownloadFile* download_file = - DoIntermediateRename(item, DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS); + DoIntermediateRename(item, download::DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS); EXPECT_CALL(*mock_delegate(), MockResumeInterruptedDownload(_, _)); EXPECT_CALL(*download_file, Detach()); @@ -1096,7 +1100,7 @@ DownloadItemImpl* item = CreateDownloadItem(); TestDownloadItemObserver observer(item); MockDownloadFile* download_file = - DoIntermediateRename(item, DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS); + DoIntermediateRename(item, download::DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS); // Interrupt the download, using a continuable interrupt. EXPECT_CALL(*download_file, FullPath()) @@ -1135,7 +1139,7 @@ .WillOnce(ScheduleRenameAndUniquifyCallback( DOWNLOAD_INTERRUPT_REASON_NONE, intermediate_path)); callback.Run(target_path, DownloadItem::TARGET_DISPOSITION_OVERWRITE, - DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS, intermediate_path, + download::DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS, intermediate_path, DOWNLOAD_INTERRUPT_REASON_NONE); task_environment_.RunUntilIdle(); EXPECT_EQ(FILE_PATH_LITERAL("foo.bar"), @@ -1186,7 +1190,7 @@ download_target_callback.Run(base::FilePath(kDummyTargetPath), DownloadItem::TARGET_DISPOSITION_OVERWRITE, - DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS, + download::DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS, base::FilePath(kDummyIntermediatePath), DOWNLOAD_INTERRUPT_REASON_NONE); task_environment_.RunUntilIdle(); @@ -1229,8 +1233,8 @@ base::FilePath target_path(FILE_PATH_LITERAL("foo")); download_target_callback.Run(target_path, DownloadItem::TARGET_DISPOSITION_OVERWRITE, - DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS, target_path, - DOWNLOAD_INTERRUPT_REASON_NONE); + download::DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS, + target_path, DOWNLOAD_INTERRUPT_REASON_NONE); task_environment_.RunUntilIdle(); // Interrupt reason carried in create info should be recorded. @@ -1258,7 +1262,7 @@ DOWNLOAD_INTERRUPT_REASON_NONE, new_intermediate_path)); callback.Run(final_path, DownloadItem::TARGET_DISPOSITION_OVERWRITE, - DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS, intermediate_path, + download::DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS, intermediate_path, DOWNLOAD_INTERRUPT_REASON_NONE); task_environment_.RunUntilIdle(); // All the callbacks should have happened by now. @@ -1299,7 +1303,7 @@ .Times(1); callback.Run(final_path, DownloadItem::TARGET_DISPOSITION_OVERWRITE, - DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS, intermediate_path, + download::DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS, intermediate_path, DOWNLOAD_INTERRUPT_REASON_NONE); task_environment_.RunUntilIdle(); // All the callbacks should have happened by now. @@ -1315,7 +1319,7 @@ base::HistogramTester histogram_tester; DownloadItemImpl* item = CreateDownloadItem(); MockDownloadFile* download_file = - DoIntermediateRename(item, DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS); + DoIntermediateRename(item, download::DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS); const DownloadInterruptReason reason( DOWNLOAD_INTERRUPT_REASON_FILE_ACCESS_DENIED); @@ -1362,7 +1366,7 @@ .Times(1); callback.Run(final_path, DownloadItem::TARGET_DISPOSITION_OVERWRITE, - DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS, intermediate_path, + download::DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS, intermediate_path, DOWNLOAD_INTERRUPT_REASON_NONE); task_environment_.RunUntilIdle(); // All the callbacks should have happened by now. @@ -1406,7 +1410,7 @@ EXPECT_CALL(*download_file, Detach()); callback.Run(final_path, DownloadItem::TARGET_DISPOSITION_OVERWRITE, - DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS, intermediate_path, + download::DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS, intermediate_path, DOWNLOAD_INTERRUPT_REASON_NONE); task_environment_.RunUntilIdle(); // All the callbacks should have happened by now. @@ -1446,7 +1450,7 @@ .Times(1); callback.Run(final_path, DownloadItem::TARGET_DISPOSITION_OVERWRITE, - DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS, intermediate_path, + download::DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS, intermediate_path, DOWNLOAD_INTERRUPT_REASON_NONE); task_environment_.RunUntilIdle(); // All the callbacks should have happened by now. @@ -1487,7 +1491,7 @@ EXPECT_CALL(*download_file, Cancel()); callback.Run(base::FilePath(FILE_PATH_LITERAL("foo")), DownloadItem::TARGET_DISPOSITION_OVERWRITE, - DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS, + download::DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS, base::FilePath(FILE_PATH_LITERAL("bar")), DOWNLOAD_INTERRUPT_REASON_USER_CANCELED); EXPECT_EQ(DownloadItem::CANCELLED, item->GetState()); @@ -1500,7 +1504,7 @@ EXPECT_CALL(*download_file, Cancel()); callback.Run(base::FilePath(), DownloadItem::TARGET_DISPOSITION_OVERWRITE, - DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS, base::FilePath(), + download::DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS, base::FilePath(), DOWNLOAD_INTERRUPT_REASON_NONE); EXPECT_EQ(DownloadItem::CANCELLED, item->GetState()); } @@ -1513,7 +1517,7 @@ EXPECT_CALL(*download_file, Cancel()); callback.Run(target_path, DownloadItem::TARGET_DISPOSITION_OVERWRITE, - DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS, target_path, + download::DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS, target_path, DOWNLOAD_INTERRUPT_REASON_FILE_SAME_AS_SOURCE); EXPECT_EQ(DownloadItem::INTERRUPTED, item->GetState()); EXPECT_EQ(DOWNLOAD_INTERRUPT_REASON_FILE_SAME_AS_SOURCE, @@ -1531,7 +1535,7 @@ TEST_F(DownloadItemTest, DestinationUpdate) { DownloadItemImpl* item = CreateDownloadItem(); MockDownloadFile* file = - DoIntermediateRename(item, DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS); + DoIntermediateRename(item, download::DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS); base::WeakPtr<DownloadDestinationObserver> as_observer( item->DestinationObserverAsWeakPtr()); TestDownloadItemObserver observer(item); @@ -1567,7 +1571,7 @@ base::HistogramTester histogram_tester; DownloadItemImpl* item = CreateDownloadItem(); MockDownloadFile* download_file = - DoIntermediateRename(item, DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS); + DoIntermediateRename(item, download::DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS); base::WeakPtr<DownloadDestinationObserver> as_observer( item->DestinationObserverAsWeakPtr()); TestDownloadItemObserver observer(item); @@ -1601,7 +1605,7 @@ base::HistogramTester histogram_tester; DownloadItemImpl* item = CreateDownloadItem(); MockDownloadFile* download_file = - DoIntermediateRename(item, DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS); + DoIntermediateRename(item, download::DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS); base::WeakPtr<DownloadDestinationObserver> as_observer( item->DestinationObserverAsWeakPtr()); TestDownloadItemObserver observer(item); @@ -1632,7 +1636,7 @@ base::HistogramTester histogram_tester; DownloadItemImpl* item = CreateDownloadItem(); MockDownloadFile* download_file = - DoIntermediateRename(item, DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS); + DoIntermediateRename(item, download::DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS); base::WeakPtr<DownloadDestinationObserver> as_observer( item->DestinationObserverAsWeakPtr()); TestDownloadItemObserver observer(item); @@ -1675,7 +1679,7 @@ TEST_F(DownloadItemTest, EnabledActionsForNormalDownload) { DownloadItemImpl* item = CreateDownloadItem(); MockDownloadFile* download_file = - DoIntermediateRename(item, DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS); + DoIntermediateRename(item, download::DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS); // InProgress ASSERT_EQ(DownloadItem::IN_PROGRESS, item->GetState()); @@ -1707,7 +1711,7 @@ create_info()->save_info->file_path = base::FilePath(kDummyTargetPath); DownloadItemImpl* item = CreateDownloadItem(); MockDownloadFile* download_file = - DoIntermediateRename(item, DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS); + DoIntermediateRename(item, download::DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS); // InProgress Temporary ASSERT_EQ(DownloadItem::IN_PROGRESS, item->GetState()); @@ -1737,7 +1741,7 @@ TEST_F(DownloadItemTest, EnabledActionsForInterruptedDownload) { DownloadItemImpl* item = CreateDownloadItem(); MockDownloadFile* download_file = - DoIntermediateRename(item, DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS); + DoIntermediateRename(item, download::DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS); EXPECT_CALL(*download_file, Cancel()); item->DestinationObserverAsWeakPtr()->DestinationError( @@ -1754,7 +1758,7 @@ TEST_F(DownloadItemTest, EnabledActionsForCancelledDownload) { DownloadItemImpl* item = CreateDownloadItem(); MockDownloadFile* download_file = - DoIntermediateRename(item, DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS); + DoIntermediateRename(item, download::DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS); EXPECT_CALL(*download_file, Cancel()); item->Cancel(true); @@ -1773,7 +1777,7 @@ // we complete immediately. DownloadItemImpl* item = CreateDownloadItem(); MockDownloadFile* download_file = - DoIntermediateRename(item, DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS); + DoIntermediateRename(item, download::DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS); // Drive the delegate interaction. EXPECT_CALL(*mock_delegate(), ShouldCompleteDownload(item, _)) @@ -1804,7 +1808,7 @@ DownloadItemImpl* item = CreateDownloadItem(); MockDownloadFile* download_file = - DoIntermediateRename(item, DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS); + DoIntermediateRename(item, download::DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS); base::Closure delegate_callback; base::Closure copy_delegate_callback; @@ -1843,7 +1847,7 @@ // we complete immediately. DownloadItemImpl* item = CreateDownloadItem(); MockDownloadFile* download_file = - DoIntermediateRename(item, DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS); + DoIntermediateRename(item, download::DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS); // Drive the delegate interaction. base::Closure delegate_callback; @@ -1858,7 +1862,7 @@ copy_delegate_callback = delegate_callback; delegate_callback.Reset(); EXPECT_FALSE(item->IsDangerous()); - item->OnContentCheckCompleted(content::DOWNLOAD_DANGER_TYPE_DANGEROUS_FILE, + item->OnContentCheckCompleted(download::DOWNLOAD_DANGER_TYPE_DANGEROUS_FILE, DOWNLOAD_INTERRUPT_REASON_NONE); EXPECT_EQ(DownloadItem::IN_PROGRESS, item->GetState()); copy_delegate_callback.Run(); @@ -1881,7 +1885,8 @@ EXPECT_TRUE(item->IsDangerous()); item->ValidateDangerousDownload(); - EXPECT_EQ(DOWNLOAD_DANGER_TYPE_USER_VALIDATED, item->GetDangerType()); + EXPECT_EQ(download::DOWNLOAD_DANGER_TYPE_USER_VALIDATED, + item->GetDangerType()); task_environment_.RunUntilIdle(); EXPECT_EQ(DownloadItem::COMPLETE, item->GetState()); } @@ -1892,7 +1897,7 @@ // we complete immediately. DownloadItemImpl* item = CreateDownloadItem(); MockDownloadFile* download_file = - DoIntermediateRename(item, DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS); + DoIntermediateRename(item, download::DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS); // Drive the delegate interaction. base::Closure delegate_callback; @@ -1936,7 +1941,7 @@ TEST_F(DownloadItemTest, StealDangerousDownloadAndDiscard) { DownloadItemImpl* item = CreateDownloadItem(); MockDownloadFile* download_file = - DoIntermediateRename(item, DOWNLOAD_DANGER_TYPE_DANGEROUS_FILE); + DoIntermediateRename(item, download::DOWNLOAD_DANGER_TYPE_DANGEROUS_FILE); ASSERT_TRUE(item->IsDangerous()); base::FilePath full_path(FILE_PATH_LITERAL("foo.txt")); base::FilePath returned_path; @@ -1958,7 +1963,7 @@ TEST_F(DownloadItemTest, StealDangerousDownloadAndKeep) { DownloadItemImpl* item = CreateDownloadItem(); MockDownloadFile* download_file = - DoIntermediateRename(item, DOWNLOAD_DANGER_TYPE_DANGEROUS_FILE); + DoIntermediateRename(item, download::DOWNLOAD_DANGER_TYPE_DANGEROUS_FILE); ASSERT_TRUE(item->IsDangerous()); base::FilePath full_path(FILE_PATH_LITERAL("foo.txt")); base::FilePath returned_path; @@ -1979,7 +1984,7 @@ base::FilePath returned_path; DownloadItemImpl* item = CreateDownloadItem(); MockDownloadFile* download_file = - DoIntermediateRename(item, DOWNLOAD_DANGER_TYPE_DANGEROUS_FILE); + DoIntermediateRename(item, download::DOWNLOAD_DANGER_TYPE_DANGEROUS_FILE); base::FilePath full_path = item->GetFullPath(); EXPECT_FALSE(full_path.empty()); EXPECT_CALL(*download_file, FullPath()).WillOnce(ReturnRefOfCopy(full_path)); @@ -2004,7 +2009,7 @@ base::FilePath returned_path; DownloadItemImpl* item = CreateDownloadItem(); MockDownloadFile* download_file = - DoIntermediateRename(item, DOWNLOAD_DANGER_TYPE_DANGEROUS_FILE); + DoIntermediateRename(item, download::DOWNLOAD_DANGER_TYPE_DANGEROUS_FILE); EXPECT_CALL(*download_file, Cancel()); item->DestinationObserverAsWeakPtr()->DestinationError( DOWNLOAD_INTERRUPT_REASON_FILE_FAILED, 1, @@ -2288,8 +2293,8 @@ destination_observer); target_callback.Run(base::FilePath(), DownloadItem::TARGET_DISPOSITION_OVERWRITE, - DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS, base::FilePath(), - DOWNLOAD_INTERRUPT_REASON_NONE); + download::DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS, + base::FilePath(), DOWNLOAD_INTERRUPT_REASON_NONE); EXPECT_EQ(DownloadItem::CANCELLED, item_->GetState()); task_environment_.RunUntilIdle(); } @@ -2334,7 +2339,7 @@ destination_observer); target_callback.Run(base::FilePath(kDummyTargetPath), DownloadItem::TARGET_DISPOSITION_OVERWRITE, - DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS, + download::DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS, base::FilePath(kDummyIntermediatePath), DOWNLOAD_INTERRUPT_REASON_NONE); @@ -2397,7 +2402,7 @@ destination_observer); target_callback.Run(base::FilePath(kDummyTargetPath), DownloadItem::TARGET_DISPOSITION_OVERWRITE, - DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS, + download::DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS, base::FilePath(kDummyIntermediatePath), DOWNLOAD_INTERRUPT_REASON_NONE);
diff --git a/content/browser/download/download_job.h b/content/browser/download/download_job.h index dcf15e6..0a68c4ed 100644 --- a/content/browser/download/download_job.h +++ b/content/browser/download/download_job.h
@@ -12,7 +12,6 @@ #include "content/browser/download/download_file.h" #include "content/browser/download/download_request_handle.h" #include "content/common/content_export.h" -#include "content/public/browser/download_danger_type.h" #include "content/public/browser/download_interrupt_reasons.h" namespace content {
diff --git a/content/browser/download/download_manager_impl.cc b/content/browser/download/download_manager_impl.cc index 916b58dc..950aac0 100644 --- a/content/browser/download/download_manager_impl.cc +++ b/content/browser/download/download_manager_impl.cc
@@ -108,7 +108,7 @@ DCHECK_CURRENTLY_ON(BrowserThread::IO); std::unique_ptr<DownloadCreateInfo> failed_created_info( new DownloadCreateInfo(base::Time::Now(), - base::WrapUnique(new DownloadSaveInfo))); + base::WrapUnique(new download::DownloadSaveInfo))); failed_created_info->url_chain.push_back(params->url()); failed_created_info->result = reason; std::unique_ptr<ByteStreamReader> empty_byte_stream; @@ -129,8 +129,8 @@ download_id = base::RandUint64(); } while (download_id == 0); - return download::DownloadEntry( - item.GetGuid(), ToDownloadSource(item.download_source()), download_id); + return download::DownloadEntry(item.GetGuid(), item.download_source(), + download_id); } DownloadManagerImpl::UniqueUrlDownloadHandlerPtr BeginDownload( @@ -235,7 +235,7 @@ int64_t total_bytes, const std::string& hash, DownloadItem::DownloadState state, - DownloadDangerType danger_type, + download::DownloadDangerType danger_type, DownloadInterruptReason interrupt_reason, bool opened, base::Time last_access_time, @@ -379,7 +379,7 @@ base::FilePath target_path = item->GetForcedFilePath(); // TODO(asanka): Determine a useful path if |target_path| is empty. callback.Run(target_path, DownloadItem::TARGET_DISPOSITION_OVERWRITE, - DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS, target_path, + download::DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS, target_path, DOWNLOAD_INTERRUPT_REASON_NONE); } } @@ -872,7 +872,7 @@ int64_t total_bytes, const std::string& hash, DownloadItem::DownloadState state, - DownloadDangerType danger_type, + download::DownloadDangerType danger_type, DownloadInterruptReason interrupt_reason, bool opened, base::Time last_access_time, @@ -943,11 +943,14 @@ int count = 0; for (const auto& it : downloads_) { if (it.second->GetState() == DownloadItem::IN_PROGRESS && - it.second->GetDangerType() != DOWNLOAD_DANGER_TYPE_DANGEROUS_URL && - it.second->GetDangerType() != DOWNLOAD_DANGER_TYPE_DANGEROUS_CONTENT && - it.second->GetDangerType() != DOWNLOAD_DANGER_TYPE_DANGEROUS_HOST && it.second->GetDangerType() != - DOWNLOAD_DANGER_TYPE_POTENTIALLY_UNWANTED) { + download::DOWNLOAD_DANGER_TYPE_DANGEROUS_URL && + it.second->GetDangerType() != + download::DOWNLOAD_DANGER_TYPE_DANGEROUS_CONTENT && + it.second->GetDangerType() != + download::DOWNLOAD_DANGER_TYPE_DANGEROUS_HOST && + it.second->GetDangerType() != + download::DOWNLOAD_DANGER_TYPE_POTENTIALLY_UNWANTED) { ++count; } }
diff --git a/content/browser/download/download_manager_impl.h b/content/browser/download/download_manager_impl.h index a4b9830a..f95aa741 100644 --- a/content/browser/download/download_manager_impl.h +++ b/content/browser/download/download_manager_impl.h
@@ -102,7 +102,7 @@ int64_t total_bytes, const std::string& hash, content::DownloadItem::DownloadState state, - DownloadDangerType danger_type, + download::DownloadDangerType danger_type, DownloadInterruptReason interrupt_reason, bool opened, base::Time last_access_time,
diff --git a/content/browser/download/download_manager_impl_unittest.cc b/content/browser/download/download_manager_impl_unittest.cc index 9d6350c..f8b8ac6 100644 --- a/content/browser/download/download_manager_impl_unittest.cc +++ b/content/browser/download/download_manager_impl_unittest.cc
@@ -152,7 +152,7 @@ int64_t total_bytes, const std::string& hash, DownloadItem::DownloadState state, - DownloadDangerType danger_type, + download::DownloadDangerType danger_type, DownloadInterruptReason interrupt_reason, bool opened, base::Time last_access_time, @@ -229,7 +229,7 @@ int64_t total_bytes, const std::string& hash, DownloadItem::DownloadState state, - DownloadDangerType danger_type, + download::DownloadDangerType danger_type, DownloadInterruptReason interrupt_reason, bool opened, base::Time last_access_time, @@ -299,11 +299,11 @@ // Overridden method from DownloadFileFactory MOCK_METHOD2(MockCreateFile, - MockDownloadFile*(const DownloadSaveInfo&, + MockDownloadFile*(const download::DownloadSaveInfo&, DownloadManager::InputStream*)); DownloadFile* CreateFile( - std::unique_ptr<DownloadSaveInfo> save_info, + std::unique_ptr<download::DownloadSaveInfo> save_info, const base::FilePath& default_download_directory, std::unique_ptr<DownloadManager::InputStream> stream, uint32_t download_id, @@ -395,7 +395,7 @@ DownloadManagerTest() : callback_called_(false), target_disposition_(DownloadItem::TARGET_DISPOSITION_OVERWRITE), - danger_type_(DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS), + danger_type_(download::DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS), interrupt_reason_(DOWNLOAD_INTERRUPT_REASON_NONE), next_download_id_(0) {} @@ -499,7 +499,7 @@ void DownloadTargetDeterminedCallback( const base::FilePath& target_path, DownloadItem::TargetDisposition disposition, - DownloadDangerType danger_type, + download::DownloadDangerType danger_type, const base::FilePath& intermediate_path, DownloadInterruptReason interrupt_reason) { callback_called_ = true; @@ -530,7 +530,7 @@ bool callback_called_; base::FilePath target_path_; DownloadItem::TargetDisposition target_disposition_; - DownloadDangerType danger_type_; + download::DownloadDangerType danger_type_; base::FilePath intermediate_path_; DownloadInterruptReason interrupt_reason_; @@ -616,7 +616,7 @@ EXPECT_TRUE(callback_called_); EXPECT_EQ(path, target_path_); EXPECT_EQ(DownloadItem::TARGET_DISPOSITION_OVERWRITE, target_disposition_); - EXPECT_EQ(DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS, danger_type_); + EXPECT_EQ(download::DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS, danger_type_); EXPECT_EQ(path, intermediate_path_); EXPECT_EQ(DOWNLOAD_INTERRUPT_REASON_NONE, interrupt_reason_); } @@ -639,7 +639,7 @@ GURL("http://example.com/a"), GURL("http://example.com/a"), "application/octet-stream", "application/octet-stream", base::Time::Now(), base::Time::Now(), std::string(), std::string(), 10, 10, std::string(), - DownloadItem::INTERRUPTED, DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS, + DownloadItem::INTERRUPTED, download::DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS, DOWNLOAD_INTERRUPT_REASON_SERVER_FAILED, false, base::Time::Now(), true, std::vector<DownloadItem::ReceivedSlice>()); ASSERT_TRUE(persisted_item);
diff --git a/content/browser/download/download_request_core.cc b/content/browser/download/download_request_core.cc index 2c9f7a2..4f16405 100644 --- a/content/browser/download/download_request_core.cc +++ b/content/browser/download/download_request_core.cc
@@ -61,7 +61,7 @@ static DownloadRequestData* Get(const net::URLRequest* request); static void Detach(net::URLRequest* request); - std::unique_ptr<DownloadSaveInfo> TakeSaveInfo() { + std::unique_ptr<download::DownloadSaveInfo> TakeSaveInfo() { return std::move(save_info_); } uint32_t download_id() const { return download_id_; } @@ -76,7 +76,7 @@ private: static const int kKey; - std::unique_ptr<DownloadSaveInfo> save_info_; + std::unique_ptr<download::DownloadSaveInfo> save_info_; uint32_t download_id_ = DownloadItem::kInvalidId; std::string guid_; bool fetch_error_body_ = false; @@ -94,7 +94,7 @@ uint32_t download_id) { auto request_data = std::make_unique<DownloadRequestData>(); request_data->save_info_.reset( - new DownloadSaveInfo(parameters->GetSaveInfo())); + new download::DownloadSaveInfo(parameters->GetSaveInfo())); request_data->download_id_ = download_id; request_data->guid_ = parameters->guid(); request_data->fetch_error_body_ = parameters->fetch_error_body(); @@ -142,10 +142,11 @@ return std::string(); // Empty string if data does not exist. } -DownloadRequestCore::DownloadRequestCore(net::URLRequest* request, - Delegate* delegate, - bool is_parallel_request, - DownloadSource download_source) +DownloadRequestCore::DownloadRequestCore( + net::URLRequest* request, + Delegate* delegate, + bool is_parallel_request, + download::DownloadSource download_source) : delegate_(delegate), request_(request), download_id_(DownloadItem::kInvalidId), @@ -191,7 +192,7 @@ DownloadRequestData::Detach(request_); is_partial_request_ = save_info_->offset > 0; } else { - save_info_.reset(new DownloadSaveInfo); + save_info_.reset(new download::DownloadSaveInfo); ResourceRequestInfoImpl* request_info = ResourceRequestInfoImpl::ForRequest(request_); if (request_info && request_info->suggested_filename().has_value()) {
diff --git a/content/browser/download/download_request_core.h b/content/browser/download/download_request_core.h index df2f7a1..c2965c9 100644 --- a/content/browser/download/download_request_core.h +++ b/content/browser/download/download_request_core.h
@@ -14,9 +14,9 @@ #include "base/callback.h" #include "base/macros.h" #include "base/memory/weak_ptr.h" +#include "components/download/public/common/download_save_info.h" #include "content/browser/loader/resource_handler.h" #include "content/public/browser/download_interrupt_reasons.h" -#include "content/public/browser/download_save_info.h" #include "content/public/browser/download_url_parameters.h" #include "services/device/public/interfaces/wake_lock.mojom.h" @@ -54,7 +54,7 @@ DownloadRequestCore(net::URLRequest* request, Delegate* delegate, bool is_parallel_request, - DownloadSource download_source); + download::DownloadSource download_source); ~DownloadRequestCore(); // Should be called when the URLRequest::Delegate receives OnResponseStarted. @@ -124,7 +124,7 @@ // "Passthrough" fields. These are only kept here so that they can be used to // populate the DownloadCreateInfo when the time comes. - std::unique_ptr<DownloadSaveInfo> save_info_; + std::unique_ptr<download::DownloadSaveInfo> save_info_; uint32_t download_id_; std::string guid_; bool fetch_error_body_; @@ -160,7 +160,7 @@ DownloadInterruptReason abort_reason_; // Source of the download, used in metrics. - DownloadSource download_source_; + download::DownloadSource download_source_; // Each successful OnWillRead will yield a buffer of this size. static const int kReadBufSize = 32768; // bytes
diff --git a/content/browser/download/download_request_core_unittest.cc b/content/browser/download/download_request_core_unittest.cc index d2adc595..f51d8b1 100644 --- a/content/browser/download/download_request_core_unittest.cc +++ b/content/browser/download/download_request_core_unittest.cc
@@ -77,7 +77,7 @@ BuildDownloadParameters("example.com"); // Check initial states. - EXPECT_EQ(DownloadSaveInfo::kLengthFullContent, params->length()); + EXPECT_EQ(download::DownloadSaveInfo::kLengthFullContent, params->length()); EXPECT_EQ(0, params->offset()); EXPECT_TRUE(params->use_if_range());
diff --git a/content/browser/download/download_resource_handler.cc b/content/browser/download/download_resource_handler.cc index ee61c0a..f47af18 100644 --- a/content/browser/download/download_resource_handler.cc +++ b/content/browser/download/download_resource_handler.cc
@@ -111,8 +111,9 @@ } // namespace -DownloadResourceHandler::DownloadResourceHandler(net::URLRequest* request, - DownloadSource download_source) +DownloadResourceHandler::DownloadResourceHandler( + net::URLRequest* request, + download::DownloadSource download_source) : ResourceHandler(request), tab_info_(new DownloadTabInfo()), core_(request, this, false, download_source) { @@ -143,15 +144,15 @@ std::unique_ptr<ResourceHandler> DownloadResourceHandler::Create( net::URLRequest* request) { DCHECK_CURRENTLY_ON(BrowserThread::IO); - std::unique_ptr<ResourceHandler> handler( - new DownloadResourceHandler(request, DownloadSource::NAVIGATION)); + std::unique_ptr<ResourceHandler> handler(new DownloadResourceHandler( + request, download::DownloadSource::NAVIGATION)); return handler; } // static std::unique_ptr<ResourceHandler> DownloadResourceHandler::CreateForNewRequest( net::URLRequest* request, - DownloadSource download_source) { + download::DownloadSource download_source) { DCHECK_CURRENTLY_ON(BrowserThread::IO); std::unique_ptr<ResourceHandler> handler( new DownloadResourceHandler(request, download_source));
diff --git a/content/browser/download/download_resource_handler.h b/content/browser/download/download_resource_handler.h index 4fe98af..7734cc7 100644 --- a/content/browser/download/download_resource_handler.h +++ b/content/browser/download/download_resource_handler.h
@@ -16,7 +16,6 @@ #include "content/browser/loader/resource_handler.h" #include "content/public/browser/download_interrupt_reasons.h" #include "content/public/browser/download_manager.h" -#include "content/public/browser/download_save_info.h" #include "content/public/browser/download_url_parameters.h" #include "content/public/browser/web_contents.h" #include "services/metrics/public/cpp/ukm_recorder.h" @@ -41,7 +40,7 @@ // started_cb will be called exactly once on the UI thread. // |id| should be invalid if the id should be automatically assigned. DownloadResourceHandler(net::URLRequest* request, - DownloadSource download_source); + download::DownloadSource download_source); // static // This function is passed into ResourceDispatcherHostImpl during its @@ -57,7 +56,7 @@ // navigation. static std::unique_ptr<ResourceHandler> CreateForNewRequest( net::URLRequest* request, - DownloadSource download_source); + download::DownloadSource download_source); void OnRequestRedirected( const net::RedirectInfo& redirect_info,
diff --git a/content/browser/download/download_response_handler.cc b/content/browser/download/download_response_handler.cc index d2d198a..3938f0fc 100644 --- a/content/browser/download/download_response_handler.cc +++ b/content/browser/download/download_response_handler.cc
@@ -50,11 +50,11 @@ DownloadResponseHandler::DownloadResponseHandler( network::ResourceRequest* resource_request, Delegate* delegate, - std::unique_ptr<DownloadSaveInfo> save_info, + std::unique_ptr<download::DownloadSaveInfo> save_info, bool is_parallel_request, bool is_transient, bool fetch_error_body, - DownloadSource download_source, + download::DownloadSource download_source, std::vector<GURL> url_chain) : delegate_(delegate), started_(false),
diff --git a/content/browser/download/download_response_handler.h b/content/browser/download/download_response_handler.h index 7f608bc8..d1d55f7f 100644 --- a/content/browser/download/download_response_handler.h +++ b/content/browser/download/download_response_handler.h
@@ -7,8 +7,8 @@ #include <vector> +#include "components/download/public/common/download_source.h" #include "content/browser/download/download_create_info.h" -#include "content/public/browser/download_source.h" #include "content/public/common/download_stream.mojom.h" #include "content/public/common/referrer.h" #include "net/cert/cert_status_flags.h" @@ -37,11 +37,11 @@ DownloadResponseHandler(network::ResourceRequest* resource_request, Delegate* delegate, - std::unique_ptr<DownloadSaveInfo> save_info, + std::unique_ptr<download::DownloadSaveInfo> save_info, bool is_parallel_request, bool is_transient, bool fetch_error_body, - DownloadSource download_source, + download::DownloadSource download_source, std::vector<GURL> url_chain); ~DownloadResponseHandler() override; @@ -76,13 +76,13 @@ bool started_; // Information needed to create DownloadCreateInfo when the time comes. - std::unique_ptr<DownloadSaveInfo> save_info_; + std::unique_ptr<download::DownloadSaveInfo> save_info_; std::vector<GURL> url_chain_; std::string method_; GURL referrer_; bool is_transient_; bool fetch_error_body_; - DownloadSource download_source_; + download::DownloadSource download_source_; net::CertStatus cert_status_; bool has_strong_validators_; GURL origin_;
diff --git a/content/browser/download/download_stats.cc b/content/browser/download/download_stats.cc index 9a2fd84..ad99589 100644 --- a/content/browser/download/download_stats.cc +++ b/content/browser/download/download_stats.cc
@@ -266,38 +266,39 @@ } // Records a histogram with download source suffix. -std::string CreateHistogramNameWithSuffix(const std::string& name, - DownloadSource download_source) { +std::string CreateHistogramNameWithSuffix( + const std::string& name, + download::DownloadSource download_source) { std::string suffix; switch (download_source) { - case DownloadSource::UNKNOWN: + case download::DownloadSource::UNKNOWN: suffix = "UnknownSource"; break; - case DownloadSource::NAVIGATION: + case download::DownloadSource::NAVIGATION: suffix = "Navigation"; break; - case DownloadSource::DRAG_AND_DROP: + case download::DownloadSource::DRAG_AND_DROP: suffix = "DragAndDrop"; break; - case DownloadSource::FROM_RENDERER: + case download::DownloadSource::FROM_RENDERER: suffix = "FromRenderer"; break; - case DownloadSource::EXTENSION_API: + case download::DownloadSource::EXTENSION_API: suffix = "ExtensionAPI"; break; - case DownloadSource::EXTENSION_INSTALLER: + case download::DownloadSource::EXTENSION_INSTALLER: suffix = "ExtensionInstaller"; break; - case DownloadSource::INTERNAL_API: + case download::DownloadSource::INTERNAL_API: suffix = "InternalAPI"; break; - case DownloadSource::WEB_CONTENTS_API: + case download::DownloadSource::WEB_CONTENTS_API: suffix = "WebContentsAPI"; break; - case DownloadSource::OFFLINE_PAGE: + case download::DownloadSource::OFFLINE_PAGE: suffix = "OfflinePage"; break; - case DownloadSource::CONTEXT_MENU: + case download::DownloadSource::CONTEXT_MENU: suffix = "ContextMenu"; break; } @@ -313,7 +314,7 @@ } void RecordDownloadCountWithSource(DownloadCountTypes type, - DownloadSource download_source) { + download::DownloadSource download_source) { RecordDownloadCount(type); std::string name = @@ -324,7 +325,7 @@ void RecordDownloadCompleted(const base::TimeTicks& start, int64_t download_len, bool is_parallelizable, - DownloadSource download_source) { + download::DownloadSource download_source) { RecordDownloadCountWithSource(COMPLETED_COUNT, download_source); UMA_HISTOGRAM_LONG_TIMES("Download.Time", (base::TimeTicks::Now() - start)); int64_t max = 1024 * 1024 * 1024; // One Terabyte. @@ -345,7 +346,7 @@ int64_t total, bool is_parallelizable, bool is_parallel_download_enabled, - DownloadSource download_source) { + download::DownloadSource download_source) { RecordDownloadCountWithSource(INTERRUPTED_COUNT, download_source); if (is_parallelizable) { RecordParallelizableDownloadCount(INTERRUPTED_COUNT, @@ -439,18 +440,17 @@ UMA_HISTOGRAM_BOOLEAN("Download.InterruptedUnknownSize", unknown_size); } -void RecordMaliciousDownloadClassified(DownloadDangerType danger_type) { - UMA_HISTOGRAM_ENUMERATION("Download.MaliciousDownloadClassified", - danger_type, - DOWNLOAD_DANGER_TYPE_MAX); +void RecordMaliciousDownloadClassified( + download::DownloadDangerType danger_type) { + UMA_HISTOGRAM_ENUMERATION("Download.MaliciousDownloadClassified", danger_type, + download::DOWNLOAD_DANGER_TYPE_MAX); } -void RecordDangerousDownloadAccept(DownloadDangerType danger_type, +void RecordDangerousDownloadAccept(download::DownloadDangerType danger_type, const base::FilePath& file_path) { - UMA_HISTOGRAM_ENUMERATION("Download.DangerousDownloadValidated", - danger_type, - DOWNLOAD_DANGER_TYPE_MAX); - if (danger_type == DOWNLOAD_DANGER_TYPE_DANGEROUS_FILE) { + UMA_HISTOGRAM_ENUMERATION("Download.DangerousDownloadValidated", danger_type, + download::DOWNLOAD_DANGER_TYPE_MAX); + if (danger_type == download::DOWNLOAD_DANGER_TYPE_DANGEROUS_FILE) { base::UmaHistogramSparse( "Download.DangerousFile.DangerousDownloadValidated", GetDangerousFileType(file_path)); @@ -458,21 +458,21 @@ } void RecordDangerousDownloadDiscard(DownloadDiscardReason reason, - DownloadDangerType danger_type, + download::DownloadDangerType danger_type, const base::FilePath& file_path) { switch (reason) { case DOWNLOAD_DISCARD_DUE_TO_USER_ACTION: - UMA_HISTOGRAM_ENUMERATION( - "Download.UserDiscard", danger_type, DOWNLOAD_DANGER_TYPE_MAX); - if (danger_type == DOWNLOAD_DANGER_TYPE_DANGEROUS_FILE) { + UMA_HISTOGRAM_ENUMERATION("Download.UserDiscard", danger_type, + download::DOWNLOAD_DANGER_TYPE_MAX); + if (danger_type == download::DOWNLOAD_DANGER_TYPE_DANGEROUS_FILE) { base::UmaHistogramSparse("Download.DangerousFile.UserDiscard", GetDangerousFileType(file_path)); } break; case DOWNLOAD_DISCARD_DUE_TO_SHUTDOWN: - UMA_HISTOGRAM_ENUMERATION( - "Download.Discard", danger_type, DOWNLOAD_DANGER_TYPE_MAX); - if (danger_type == DOWNLOAD_DANGER_TYPE_DANGEROUS_FILE) { + UMA_HISTOGRAM_ENUMERATION("Download.Discard", danger_type, + download::DOWNLOAD_DANGER_TYPE_MAX); + if (danger_type == download::DOWNLOAD_DANGER_TYPE_DANGEROUS_FILE) { base::UmaHistogramSparse("Download.DangerousFile.Discard", GetDangerousFileType(file_path)); }
diff --git a/content/browser/download/download_stats.h b/content/browser/download/download_stats.h index 9049dcb..d07573c 100644 --- a/content/browser/download/download_stats.h +++ b/content/browser/download/download_stats.h
@@ -14,11 +14,11 @@ #include <vector> #include "base/optional.h" +#include "components/download/public/common/download_danger_type.h" +#include "components/download/public/common/download_source.h" #include "content/browser/download/download_content.h" #include "content/common/content_export.h" -#include "content/public/browser/download_danger_type.h" #include "content/public/browser/download_interrupt_reasons.h" -#include "content/public/browser/download_source.h" #include "ui/base/page_transition_types.h" #include "url/gurl.h" @@ -190,13 +190,13 @@ // Record download count with download source. void RecordDownloadCountWithSource(DownloadCountTypes type, - DownloadSource download_source); + download::DownloadSource download_source); // Record COMPLETED_COUNT and how long the download took. void RecordDownloadCompleted(const base::TimeTicks& start, int64_t download_len, bool is_parallelizable, - DownloadSource download_source); + download::DownloadSource download_source); // Record INTERRUPTED_COUNT, |reason|, |received| and |total| bytes. void RecordDownloadInterrupted(DownloadInterruptReason reason, @@ -204,21 +204,20 @@ int64_t total, bool is_parallelizable, bool is_parallel_download_enabled, - DownloadSource download_source); + download::DownloadSource download_source); // Record that a download has been classified as malicious. -void RecordMaliciousDownloadClassified(DownloadDangerType danger_type); +void RecordMaliciousDownloadClassified( + download::DownloadDangerType danger_type); // Record a dangerous download accept event. -void RecordDangerousDownloadAccept( - DownloadDangerType danger_type, - const base::FilePath& file_path); +void RecordDangerousDownloadAccept(download::DownloadDangerType danger_type, + const base::FilePath& file_path); // Record a dangerous download discard event. -void RecordDangerousDownloadDiscard( - DownloadDiscardReason reason, - DownloadDangerType danger_type, - const base::FilePath& file_path); +void RecordDangerousDownloadDiscard(DownloadDiscardReason reason, + download::DownloadDangerType danger_type, + const base::FilePath& file_path); // Returns the type of download. DownloadContent DownloadContentFromMimeType(const std::string& mime_type_string,
diff --git a/content/browser/download/download_ukm_helper.cc b/content/browser/download/download_ukm_helper.cc index 3628aaa7..29570ea 100644 --- a/content/browser/download/download_ukm_helper.cc +++ b/content/browser/download/download_ukm_helper.cc
@@ -20,10 +20,11 @@ return static_cast<int>(floor(log10(value + 1) / CalcBucketIncrement())); } -void DownloadUkmHelper::RecordDownloadStarted(int download_id, - ukm::SourceId source_id, - DownloadContent file_type, - DownloadSource download_source) { +void DownloadUkmHelper::RecordDownloadStarted( + int download_id, + ukm::SourceId source_id, + DownloadContent file_type, + download::DownloadSource download_source) { ukm::builders::Download_Started(source_id) .SetDownloadId(download_id) .SetFileType(static_cast<int>(file_type))
diff --git a/content/browser/download/download_ukm_helper.h b/content/browser/download/download_ukm_helper.h index 698f7bb..abda68b5 100644 --- a/content/browser/download/download_ukm_helper.h +++ b/content/browser/download/download_ukm_helper.h
@@ -7,10 +7,10 @@ #ifndef CONTENT_BROWSER_DOWNLOAD_DOWNLOAD_UKM_HELPER_H_ #define CONTENT_BROWSER_DOWNLOAD_DOWNLOAD_UKM_HELPER_H_ +#include "components/download/public/common/download_source.h" #include "content/browser/download/download_content.h" #include "content/browser/download/resume_mode.h" #include "content/public/browser/download_interrupt_reasons.h" -#include "content/public/browser/download_source.h" #include "content/public/browser/web_contents.h" #include "services/metrics/public/cpp/ukm_recorder.h" @@ -27,7 +27,7 @@ static void RecordDownloadStarted(int download_id, ukm::SourceId source_id, DownloadContent file_type, - DownloadSource download_source); + download::DownloadSource download_source); // Record when the download is interrupted. static void RecordDownloadInterrupted(
diff --git a/content/browser/download/download_ukm_helper_unittest.cc b/content/browser/download/download_ukm_helper_unittest.cc index 1830fe5..e3ac9cb 100644 --- a/content/browser/download/download_ukm_helper_unittest.cc +++ b/content/browser/download/download_ukm_helper_unittest.cc
@@ -55,7 +55,7 @@ // RecordDownloadStarted ukm::SourceId source_id = ukm::UkmRecorder::GetNewSourceID(); DownloadContent file_type = DownloadContent::AUDIO; - DownloadSource download_source = DownloadSource::UNKNOWN; + download::DownloadSource download_source = download::DownloadSource::UNKNOWN; DownloadUkmHelper::RecordDownloadStarted(download_id_, source_id, file_type, download_source);
diff --git a/content/browser/download/download_utils.cc b/content/browser/download/download_utils.cc index 92c6c6ed..b8450524 100644 --- a/content/browser/download/download_utils.cc +++ b/content/browser/download/download_utils.cc
@@ -10,13 +10,13 @@ #include "base/strings/stringprintf.h" #include "components/download/downloader/in_progress/download_entry.h" #include "components/download/downloader/in_progress/in_progress_cache.h" +#include "components/download/public/common/download_save_info.h" #include "content/browser/download/download_create_info.h" #include "content/browser/download/download_interrupt_reasons_impl.h" #include "content/browser/download/download_stats.h" #include "content/public/browser/browser_context.h" #include "content/public/browser/browser_thread.h" #include "content/public/browser/download_manager_delegate.h" -#include "content/public/browser/download_save_info.h" #include "content/public/browser/download_url_parameters.h" #include "content/public/browser/render_frame_host.h" #include "content/public/browser/render_process_host.h" @@ -59,7 +59,7 @@ DownloadUrlParameters* params) { auto headers = std::make_unique<net::HttpRequestHeaders>(); if (params->offset() == 0 && - params->length() == DownloadSaveInfo::kLengthFullContent) { + params->length() == download::DownloadSaveInfo::kLengthFullContent) { AppendExtraHeaders(headers.get(), params); return headers; } @@ -78,7 +78,7 @@ // Add "Range" header. std::string range_header = - (params->length() == DownloadSaveInfo::kLengthFullContent) + (params->length() == download::DownloadSaveInfo::kLengthFullContent) ? base::StringPrintf("bytes=%" PRId64 "-", params->offset()) : base::StringPrintf("bytes=%" PRId64 "-%" PRId64, params->offset(), params->offset() + params->length() - 1); @@ -268,7 +268,7 @@ DownloadInterruptReason HandleSuccessfulServerResponse( const net::HttpResponseHeaders& http_headers, - DownloadSaveInfo* save_info, + download::DownloadSaveInfo* save_info, bool fetch_error_body) { DownloadInterruptReason result = DOWNLOAD_INTERRUPT_REASON_NONE; switch (http_headers.response_code()) { @@ -333,7 +333,7 @@ // Server should send partial content when "If-Match" or // "If-Unmodified-Since" check passes, and the range request header has // last byte position. e.g. "Range:bytes=50-99". - if (save_info->length != DownloadSaveInfo::kLengthFullContent && + if (save_info->length != download::DownloadSaveInfo::kLengthFullContent && !fetch_error_body) return DOWNLOAD_INTERRUPT_REASON_SERVER_BAD_CONTENT; @@ -411,61 +411,6 @@ headers->response_code() == net::HTTP_PARTIAL_CONTENT); } -download::DownloadSource ToDownloadSource( - content::DownloadSource download_source) { - switch (download_source) { - case DownloadSource::UNKNOWN: - return download::DownloadSource::UNKNOWN; - case DownloadSource::NAVIGATION: - return download::DownloadSource::NAVIGATION; - case DownloadSource::DRAG_AND_DROP: - return download::DownloadSource::DRAG_AND_DROP; - case DownloadSource::FROM_RENDERER: - return download::DownloadSource::FROM_RENDERER; - case DownloadSource::EXTENSION_API: - return download::DownloadSource::EXTENSION_API; - case DownloadSource::EXTENSION_INSTALLER: - return download::DownloadSource::EXTENSION_INSTALLER; - case DownloadSource::INTERNAL_API: - return download::DownloadSource::INTERNAL_API; - case DownloadSource::WEB_CONTENTS_API: - return download::DownloadSource::WEB_CONTENTS_API; - case DownloadSource::OFFLINE_PAGE: - return download::DownloadSource::OFFLINE_PAGE; - case DownloadSource::CONTEXT_MENU: - return download::DownloadSource::CONTEXT_MENU; - } - NOTREACHED(); - return download::DownloadSource::UNKNOWN; -} - -DownloadSource ToDownloadSource(download::DownloadSource download_source) { - switch (download_source) { - case download::DownloadSource::UNKNOWN: - return DownloadSource::UNKNOWN; - case download::DownloadSource::NAVIGATION: - return DownloadSource::NAVIGATION; - case download::DownloadSource::DRAG_AND_DROP: - return DownloadSource::DRAG_AND_DROP; - case download::DownloadSource::FROM_RENDERER: - return DownloadSource::FROM_RENDERER; - case download::DownloadSource::EXTENSION_API: - return DownloadSource::EXTENSION_API; - case download::DownloadSource::EXTENSION_INSTALLER: - return DownloadSource::EXTENSION_INSTALLER; - case download::DownloadSource::INTERNAL_API: - return DownloadSource::INTERNAL_API; - case download::DownloadSource::WEB_CONTENTS_API: - return DownloadSource::WEB_CONTENTS_API; - case download::DownloadSource::OFFLINE_PAGE: - return DownloadSource::OFFLINE_PAGE; - case download::DownloadSource::CONTEXT_MENU: - return DownloadSource::CONTEXT_MENU; - } - NOTREACHED(); - return DownloadSource::UNKNOWN; -} - base::Optional<download::DownloadEntry> GetInProgressEntry( const std::string& guid, BrowserContext* browser_context) {
diff --git a/content/browser/download/download_utils.h b/content/browser/download/download_utils.h index 93e95fe..bdaef11 100644 --- a/content/browser/download/download_utils.h +++ b/content/browser/download/download_utils.h
@@ -6,15 +6,14 @@ #define CONTENT_BROWSER_DOWNLOAD_DOWNLOAD_UTILS_H_ #include "base/optional.h" -#include "components/download/downloader/in_progress/download_source.h" #include "content/public/browser/download_interrupt_reasons.h" -#include "content/public/browser/download_source.h" #include "net/base/net_errors.h" #include "net/cert/cert_status_flags.h" #include "net/http/http_response_headers.h" namespace download { struct DownloadEntry; +struct DownloadSaveInfo; } // namespace download namespace net { @@ -30,7 +29,6 @@ class BrowserContext; class DownloadUrlParameters; struct DownloadCreateInfo; -struct DownloadSaveInfo; // Handle the url request completion status and return the interrupt reasons. // |cert_status| is ignored if error_code is not net::ERR_ABORTED. @@ -51,7 +49,7 @@ // as successful response. DownloadInterruptReason CONTENT_EXPORT HandleSuccessfulServerResponse(const net::HttpResponseHeaders& http_headers, - DownloadSaveInfo* save_info, + download::DownloadSaveInfo* save_info, bool fetch_error_body); // Parse response headers and update |create_info| accordingly. @@ -59,14 +57,6 @@ const net::HttpResponseHeaders* headers, DownloadCreateInfo* create_info); -// Converts content::DownloadSource to download::DownloadSource. -CONTENT_EXPORT download::DownloadSource ToDownloadSource( - content::DownloadSource download_source); - -// Converts download::DownloadSource to content::DownloadSource. -CONTENT_EXPORT content::DownloadSource ToDownloadSource( - download::DownloadSource download_source); - // Get the entry based on |guid| from in progress cache. CONTENT_EXPORT base::Optional<download::DownloadEntry> GetInProgressEntry( const std::string& guid,
diff --git a/content/browser/download/drag_download_file.cc b/content/browser/download/drag_download_file.cc index 43461c54ee..a90cb83 100644 --- a/content/browser/download/drag_download_file.cc +++ b/content/browser/download/drag_download_file.cc
@@ -18,7 +18,6 @@ #include "content/public/browser/browser_context.h" #include "content/public/browser/browser_thread.h" #include "content/public/browser/download_item.h" -#include "content/public/browser/download_save_info.h" #include "content/public/browser/download_url_parameters.h" #include "net/traffic_annotation/network_traffic_annotation.h" @@ -99,7 +98,7 @@ weak_ptr_factory_.GetWeakPtr())); params->set_file_path(file_path); params->set_file(std::move(file)); // Nulls file. - params->set_download_source(DownloadSource::DRAG_AND_DROP); + params->set_download_source(download::DownloadSource::DRAG_AND_DROP); BrowserContext::GetDownloadManager(web_contents_->GetBrowserContext()) ->DownloadUrl(std::move(params)); }
diff --git a/content/browser/download/mock_download_item_impl.cc b/content/browser/download/mock_download_item_impl.cc index ab1eb1f..6f381a8 100644 --- a/content/browser/download/mock_download_item_impl.cc +++ b/content/browser/download/mock_download_item_impl.cc
@@ -27,7 +27,7 @@ 0, std::string(), DownloadItem::COMPLETE, - DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS, + download::DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS, DOWNLOAD_INTERRUPT_REASON_NONE, false, base::Time(),
diff --git a/content/browser/download/mock_download_item_impl.h b/content/browser/download/mock_download_item_impl.h index 02fd1c8..b93afb1 100644 --- a/content/browser/download/mock_download_item_impl.h +++ b/content/browser/download/mock_download_item_impl.h
@@ -31,7 +31,7 @@ MOCK_METHOD5(OnDownloadTargetDetermined, void(const base::FilePath&, TargetDisposition, - DownloadDangerType, + download::DownloadDangerType, const base::FilePath&, DownloadInterruptReason)); MOCK_METHOD1(AddObserver, void(DownloadItem::Observer*)); @@ -70,7 +70,7 @@ MOCK_CONST_METHOD0(GetTargetFilePath, const base::FilePath&()); MOCK_CONST_METHOD0(GetTargetDisposition, TargetDisposition()); MOCK_METHOD2(OnContentCheckCompleted, - void(DownloadDangerType, DownloadInterruptReason)); + void(download::DownloadDangerType, DownloadInterruptReason)); MOCK_CONST_METHOD0(GetState, DownloadState()); MOCK_CONST_METHOD0(GetUrlChain, const std::vector<GURL>&()); MOCK_METHOD1(SetTotalBytes, void(int64_t)); @@ -99,7 +99,7 @@ MOCK_CONST_METHOD0(GetOpenWhenComplete, bool()); MOCK_METHOD1(SetOpenWhenComplete, void(bool)); MOCK_CONST_METHOD0(GetFileExternallyRemoved, bool()); - MOCK_CONST_METHOD0(GetDangerType, DownloadDangerType()); + MOCK_CONST_METHOD0(GetDangerType, download::DownloadDangerType()); MOCK_CONST_METHOD0(IsDangerous, bool()); MOCK_METHOD0(GetAutoOpened, bool()); MOCK_CONST_METHOD0(GetForcedFilePath, const base::FilePath&());
diff --git a/content/browser/download/parallel_download_job.cc b/content/browser/download/parallel_download_job.cc index 89ea7d2..1108321c 100644 --- a/content/browser/download/parallel_download_job.cc +++ b/content/browser/download/parallel_download_job.cc
@@ -193,7 +193,7 @@ DCHECK(!slices_to_download.empty()); DCHECK_EQ(slices_to_download.back().received_bytes, - DownloadSaveInfo::kLengthFullContent); + download::DownloadSaveInfo::kLengthFullContent); ForkSubRequests(slices_to_download); RecordParallelDownloadRequestCount(
diff --git a/content/browser/download/parallel_download_job_unittest.cc b/content/browser/download/parallel_download_job_unittest.cc index eaaa07e9..57514b0 100644 --- a/content/browser/download/parallel_download_job_unittest.cc +++ b/content/browser/download/parallel_download_job_unittest.cc
@@ -441,7 +441,7 @@ // Test that parallel request is not created until download file is initialized. TEST_F(ParallelDownloadJobTest, ParallelRequestNotCreatedUntilFileInitialized) { - auto save_info = std::make_unique<DownloadSaveInfo>(); + auto save_info = std::make_unique<download::DownloadSaveInfo>(); StrictMock<MockByteStreamReader>* input_stream = new StrictMock<MockByteStreamReader>(); auto observer =
diff --git a/content/browser/download/parallel_download_utils.cc b/content/browser/download/parallel_download_utils.cc index 1f6b98b..365ecf33 100644 --- a/content/browser/download/parallel_download_utils.cc +++ b/content/browser/download/parallel_download_utils.cc
@@ -7,7 +7,7 @@ #include "base/metrics/field_trial_params.h" #include "base/strings/string_number_conversions.h" #include "base/time/time.h" -#include "content/public/browser/download_save_info.h" +#include "components/download/public/common/download_save_info.h" #include "content/public/common/content_features.h" namespace content { @@ -54,7 +54,8 @@ // Last slice is a half open slice, which results in sending range request // like "Range:50-" to fetch from 50 bytes to the end of the file. - new_slices.emplace_back(current_offset, DownloadSaveInfo::kLengthFullContent); + new_slices.emplace_back(current_offset, + download::DownloadSaveInfo::kLengthFullContent); return new_slices; } @@ -62,7 +63,7 @@ const std::vector<DownloadItem::ReceivedSlice>& received_slices) { std::vector<DownloadItem::ReceivedSlice> result; if (received_slices.empty()) { - result.emplace_back(0, DownloadSaveInfo::kLengthFullContent); + result.emplace_back(0, download::DownloadSaveInfo::kLengthFullContent); return result; } @@ -77,7 +78,8 @@ std::vector<DownloadItem::ReceivedSlice>::const_iterator next = std::next(iter); if (next == received_slices.end()) { - result.emplace_back(offset, DownloadSaveInfo::kLengthFullContent); + result.emplace_back(offset, + download::DownloadSaveInfo::kLengthFullContent); break; }
diff --git a/content/browser/download/parallel_download_utils_unittest.cc b/content/browser/download/parallel_download_utils_unittest.cc index 10bbf44..2995141 100644 --- a/content/browser/download/parallel_download_utils_unittest.cc +++ b/content/browser/download/parallel_download_utils_unittest.cc
@@ -8,7 +8,7 @@ #include "base/strings/string_number_conversions.h" #include "base/test/scoped_feature_list.h" -#include "content/public/browser/download_save_info.h" +#include "components/download/public/common/download_save_info.h" #include "content/public/common/content_features.h" #include "testing/gtest/include/gtest/gtest.h" @@ -20,14 +20,14 @@ FindSlicesToDownload(downloaded_slices); EXPECT_EQ(1u, slices_to_download.size()); EXPECT_EQ(0, slices_to_download[0].offset); - EXPECT_EQ(DownloadSaveInfo::kLengthFullContent, + EXPECT_EQ(download::DownloadSaveInfo::kLengthFullContent, slices_to_download[0].received_bytes); downloaded_slices.emplace_back(0, 500); slices_to_download = FindSlicesToDownload(downloaded_slices); EXPECT_EQ(1u, slices_to_download.size()); EXPECT_EQ(500, slices_to_download[0].offset); - EXPECT_EQ(DownloadSaveInfo::kLengthFullContent, + EXPECT_EQ(download::DownloadSaveInfo::kLengthFullContent, slices_to_download[0].received_bytes); // Create a gap between slices. @@ -37,7 +37,7 @@ EXPECT_EQ(500, slices_to_download[0].offset); EXPECT_EQ(500, slices_to_download[0].received_bytes); EXPECT_EQ(1500, slices_to_download[1].offset); - EXPECT_EQ(DownloadSaveInfo::kLengthFullContent, + EXPECT_EQ(download::DownloadSaveInfo::kLengthFullContent, slices_to_download[1].received_bytes); // Fill the gap. @@ -46,7 +46,7 @@ slices_to_download = FindSlicesToDownload(downloaded_slices); EXPECT_EQ(1u, slices_to_download.size()); EXPECT_EQ(1500, slices_to_download[0].offset); - EXPECT_EQ(DownloadSaveInfo::kLengthFullContent, + EXPECT_EQ(download::DownloadSaveInfo::kLengthFullContent, slices_to_download[0].received_bytes); // Create a new gap at the beginning. @@ -56,7 +56,7 @@ EXPECT_EQ(0, slices_to_download[0].offset); EXPECT_EQ(500, slices_to_download[0].received_bytes); EXPECT_EQ(1500, slices_to_download[1].offset); - EXPECT_EQ(DownloadSaveInfo::kLengthFullContent, + EXPECT_EQ(download::DownloadSaveInfo::kLengthFullContent, slices_to_download[1].received_bytes); }
diff --git a/content/browser/download/resource_downloader.cc b/content/browser/download/resource_downloader.cc index 1310ed342..614b2f1 100644 --- a/content/browser/download/resource_downloader.cc +++ b/content/browser/download/resource_downloader.cc
@@ -152,7 +152,7 @@ // Set up the URLLoaderClient. url_loader_client_ = std::make_unique<DownloadResponseHandler>( resource_request_.get(), this, - std::make_unique<DownloadSaveInfo>( + std::make_unique<download::DownloadSaveInfo>( download_url_parameters->GetSaveInfo()), is_parallel_request, download_url_parameters->is_transient(), download_url_parameters->fetch_error_body(), @@ -195,12 +195,12 @@ url_loader_.Bind(std::move(endpoints->url_loader)); // Create the new URLLoaderClient that will intercept the navigation. - auto save_info = std::make_unique<DownloadSaveInfo>(); + auto save_info = std::make_unique<download::DownloadSaveInfo>(); if (suggested_filename.has_value()) save_info->suggested_name = base::UTF8ToUTF16(suggested_filename.value()); url_loader_client_ = std::make_unique<DownloadResponseHandler>( resource_request_.get(), this, std::move(save_info), false, false, false, - DownloadSource::NAVIGATION, std::move(url_chain)); + download::DownloadSource::NAVIGATION, std::move(url_chain)); // Simulate on the new URLLoaderClient calls that happened on the old client. net::SSLInfo info;
diff --git a/content/browser/download/url_downloader.cc b/content/browser/download/url_downloader.cc index 79a1701a..f94c6b14 100644 --- a/content/browser/download/url_downloader.cc +++ b/content/browser/download/url_downloader.cc
@@ -89,7 +89,7 @@ std::unique_ptr<net::URLRequest> request, base::WeakPtr<UrlDownloadHandler::Delegate> delegate, bool is_parallel_request, - DownloadSource download_source) + download::DownloadSource download_source) : request_(std::move(request)), delegate_(delegate), core_(request_.get(), this, is_parallel_request, download_source),
diff --git a/content/browser/download/url_downloader.h b/content/browser/download/url_downloader.h index 18348b9..6372dea 100644 --- a/content/browser/download/url_downloader.h +++ b/content/browser/download/url_downloader.h
@@ -13,7 +13,6 @@ #include "content/browser/download/download_request_core.h" #include "content/browser/download/url_download_handler.h" #include "content/public/browser/download_interrupt_reasons.h" -#include "content/public/browser/download_save_info.h" #include "content/public/browser/download_url_parameters.h" #include "content/public/common/referrer.h" #include "net/url_request/redirect_info.h" @@ -30,7 +29,7 @@ UrlDownloader(std::unique_ptr<net::URLRequest> request, base::WeakPtr<UrlDownloadHandler::Delegate> delegate, bool is_parallel_request, - DownloadSource download_source); + download::DownloadSource download_source); ~UrlDownloader() override; static std::unique_ptr<UrlDownloader> BeginDownload(
diff --git a/content/browser/frame_host/frame_tree_node.h b/content/browser/frame_host/frame_tree_node.h index e71b0b6..5b5c942 100644 --- a/content/browser/frame_host/frame_tree_node.h +++ b/content/browser/frame_host/frame_tree_node.h
@@ -375,6 +375,11 @@ // applied to the frame. void UpdateActiveSandboxFlags(blink::WebSandboxFlags sandbox_flags); + // Returns whether the frame received a user gesture. + bool has_received_user_gesture() const { + return replication_state_.has_received_user_gesture; + } + private: FRIEND_TEST_ALL_PREFIXES(SitePerProcessFeaturePolicyBrowserTest, ContainerPolicyDynamic);
diff --git a/content/browser/frame_host/navigation_controller_impl.cc b/content/browser/frame_host/navigation_controller_impl.cc index bea094d1..c188b46 100644 --- a/content/browser/frame_host/navigation_controller_impl.cc +++ b/content/browser/frame_host/navigation_controller_impl.cc
@@ -780,13 +780,23 @@ entry->set_transferred_global_request_id( params.transferred_global_request_id); +// Always propagate `has_user_gesture` on Android but only when the request +// was originated by the renderer on other platforms. This is merely for +// backward compatibility as browser process user gestures create confusion +// in many tests. +#if defined(OS_ANDROID) + entry->set_has_user_gesture(params.has_user_gesture); +#else + if (params.is_renderer_initiated) + entry->set_has_user_gesture(params.has_user_gesture); +#endif + #if defined(OS_ANDROID) if (params.intent_received_timestamp > 0) { entry->set_intent_received_timestamp( base::TimeTicks() + base::TimeDelta::FromMilliseconds(params.intent_received_timestamp)); } - entry->set_has_user_gesture(params.has_user_gesture); #endif switch (params.load_type) {
diff --git a/content/browser/frame_host/navigation_controller_impl_browsertest.cc b/content/browser/frame_host/navigation_controller_impl_browsertest.cc index 5428172..4dde791 100644 --- a/content/browser/frame_host/navigation_controller_impl_browsertest.cc +++ b/content/browser/frame_host/navigation_controller_impl_browsertest.cc
@@ -47,7 +47,6 @@ #include "content/public/test/browser_test_utils.h" #include "content/public/test/content_browser_test.h" #include "content/public/test/content_browser_test_utils.h" -#include "content/public/test/controllable_http_response.h" #include "content/public/test/test_navigation_observer.h" #include "content/public/test/test_utils.h" #include "content/shell/browser/shell.h" @@ -55,6 +54,7 @@ #include "content/test/content_browser_test_utils_internal.h" #include "content/test/did_commit_provisional_load_interceptor.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/url_request/url_request_failed_job.h" @@ -7861,9 +7861,10 @@ // See https://crbug.com/769645. // See https://crbug.com/773683. IN_PROC_BROWSER_TEST_F(ContentBrowserTest, HistoryBackInUnloadCancelsReload) { - ControllableHttpResponse response_1(embedded_test_server(), "/main_document"); - ControllableHttpResponse response_2(embedded_test_server(), - "/main_document?attribute=1"); + net::test_server::ControllableHttpResponse response_1(embedded_test_server(), + "/main_document"); + net::test_server::ControllableHttpResponse response_2( + embedded_test_server(), "/main_document?attribute=1"); EXPECT_TRUE(embedded_test_server()->Start());
diff --git a/content/browser/frame_host/navigation_entry_impl.cc b/content/browser/frame_host/navigation_entry_impl.cc index 9067e8b..039906c 100644 --- a/content/browser/frame_host/navigation_entry_impl.cc +++ b/content/browser/frame_host/navigation_entry_impl.cc
@@ -271,13 +271,10 @@ should_clear_history_list_(false), can_load_local_resources_(false), frame_tree_node_id_(-1), + has_user_gesture_(false), reload_type_(ReloadType::NONE), started_from_context_menu_(false), - ssl_error_(false) { -#if defined(OS_ANDROID) - has_user_gesture_ = false; -#endif -} + ssl_error_(false) {} NavigationEntryImpl::~NavigationEntryImpl() { } @@ -653,9 +650,7 @@ // ResetForCommit: should_clear_history_list_ // ResetForCommit: frame_tree_node_id_ // ResetForCommit: intent_received_timestamp_ -#if defined(OS_ANDROID) copy->has_user_gesture_ = has_user_gesture_; -#endif // ResetForCommit: reload_type_ copy->extra_data_ = extra_data_; copy->replaced_entry_data_ = replaced_entry_data_; @@ -675,13 +670,11 @@ FrameMsg_UILoadMetricsReportType::Value report_type = FrameMsg_UILoadMetricsReportType::NO_REPORT; base::TimeTicks ui_timestamp = base::TimeTicks(); - bool user_gesture = false; #if defined(OS_ANDROID) if (!intent_received_timestamp().is_null()) report_type = FrameMsg_UILoadMetricsReportType::REPORT_INTENT; ui_timestamp = intent_received_timestamp(); - user_gesture = has_user_gesture(); #endif std::string method; @@ -700,7 +693,7 @@ navigation_start, method, post_body ? post_body : post_data_, base::Optional<SourceLocation>(), CSPDisposition::CHECK /* should_check_main_world_csp */, - has_started_from_context_menu(), user_gesture, suggested_filename_); + has_started_from_context_menu(), has_user_gesture(), suggested_filename_); } RequestNavigationParams NavigationEntryImpl::ConstructRequestNavigationParams(
diff --git a/content/browser/frame_host/navigation_entry_impl.h b/content/browser/frame_host/navigation_entry_impl.h index cece16c..5d711d1 100644 --- a/content/browser/frame_host/navigation_entry_impl.h +++ b/content/browser/frame_host/navigation_entry_impl.h
@@ -414,6 +414,7 @@ const base::TimeTicks intent_received_timestamp) { intent_received_timestamp_ = intent_received_timestamp; } +#endif bool has_user_gesture() const { return has_user_gesture_; @@ -422,7 +423,6 @@ void set_has_user_gesture(bool has_user_gesture) { has_user_gesture_ = has_user_gesture; } -#endif // Stores a record of the what was committed in this NavigationEntry's main // frame before it was replaced (e.g. by history.replaceState()). @@ -553,10 +553,10 @@ // The time at which Chrome received the Android Intent that triggered this // URL load operation. Reset at commit and not persisted. base::TimeTicks intent_received_timestamp_; +#endif // Whether the URL load carries a user gesture. bool has_user_gesture_; -#endif // Used to store ReloadType for the entry. This is ReloadType::NONE for // non-reload navigations. Reset at commit and not persisted.
diff --git a/content/browser/frame_host/navigation_request.cc b/content/browser/frame_host/navigation_request.cc index c2d290e..a860a3e5 100644 --- a/content/browser/frame_host/navigation_request.cc +++ b/content/browser/frame_host/navigation_request.cc
@@ -52,6 +52,7 @@ #include "content/public/common/web_preferences.h" #include "net/base/load_flags.h" #include "net/base/net_errors.h" +#include "net/base/registry_controlled_domains/registry_controlled_domain.h" #include "net/base/url_util.h" #include "net/http/http_request_headers.h" #include "net/url_request/redirect_info.h" @@ -201,6 +202,28 @@ return url.SchemeIs(url::kFtpScheme) || url.SchemeIs(url::kGopherScheme); } +bool ShouldPropagateUserActivation(const url::Origin& previous_origin, + const url::Origin& new_origin) { + if ((previous_origin.scheme() != "http" && + previous_origin.scheme() != "https") || + (new_origin.scheme() != "http" && new_origin.scheme() != "https")) { + return false; + } + + if (previous_origin.host() == new_origin.host()) + return true; + + std::string previous_domain = + net::registry_controlled_domains::GetDomainAndRegistry( + previous_origin.host(), + net::registry_controlled_domains::INCLUDE_PRIVATE_REGISTRIES); + std::string new_domain = + net::registry_controlled_domains::GetDomainAndRegistry( + new_origin.host(), + net::registry_controlled_domains::INCLUDE_PRIVATE_REGISTRIES); + return !previous_domain.empty() && previous_domain == new_domain; +} + } // namespace // static @@ -773,6 +796,42 @@ ? navigation_handle_->appcache_handle()->appcache_host_id() : kAppCacheNoHostId; + // A navigation is user activated if it contains a user gesture or the frame + // received a gesture and the navigation is renderer initiated. If the + // navigation is browser initiated, it has to come from the context menu. + // In all cases, the previous and new URLs have to match the + // `ShouldPropagateUserActivation` requirements (same eTLD+1). + // There are two different checks: + // 1. if the `frame_tree_node_` has an origin and is following the rules above + // with the target URL, it is used and the bit is set iif the navigation is + // renderer initiated and the `frame_tree_node_` had a gesture. This should + // apply to same page navigations and is preferred over using the referrer + // as it can be changed. + // 2. if referrer and the target url are following the rules above, two + // conditions will set the bit: navigation comes from a gesture and is + // renderer initiated (middle click/ctrl+click) or it is coming from a + // context menu. This should apply to pages that open in a new tab and we + // have to follow the referrer. It means that the activation might not be + // transmitted if it should have. + request_params_.was_activated = false; + if (navigation_handle_->IsRendererInitiated() && + frame_tree_node_->has_received_user_gesture() && + ShouldPropagateUserActivation( + frame_tree_node_->current_origin(), + url::Origin::Create(navigation_handle_->GetURL()))) { + request_params_.was_activated = true; + // TODO(805871): the next check is relying on + // navigation_handle_->GetReferrer() but should ideally use a more reliable + // source for the originating URL when the navigation is renderer initiated. + } else if (((navigation_handle_->HasUserGesture() && + navigation_handle_->IsRendererInitiated()) || + navigation_handle_->WasStartedFromContextMenu()) && + ShouldPropagateUserActivation( + url::Origin::Create(navigation_handle_->GetReferrer().url), + url::Origin::Create(navigation_handle_->GetURL()))) { + request_params_.was_activated = true; + } + // Update the previews state of the request. common_params_.previews_state = static_cast<PreviewsState>(response->head.previews_state); @@ -1238,6 +1297,7 @@ void NavigationRequest::CommitErrorPage( RenderFrameHostImpl* render_frame_host, const base::Optional<std::string>& error_page_content) { + UpdateRequestNavigationParamsHistory(); frame_tree_node_->TransferNavigationRequestOwnership(render_frame_host); navigation_handle_->ReadyToCommitNavigation(render_frame_host); render_frame_host->FailedNavigation(common_params_, request_params_, @@ -1246,6 +1306,7 @@ } void NavigationRequest::CommitNavigation() { + UpdateRequestNavigationParamsHistory(); DCHECK(response_ || !IsURLHandledByNetworkStack(common_params_.url) || navigation_handle_->IsSameDocument()); DCHECK(!common_params_.url.SchemeIs(url::kJavaScriptScheme)); @@ -1393,4 +1454,13 @@ return LegacyProtocolInSubresourceCheckResult::BLOCK_REQUEST; } +void NavigationRequest::UpdateRequestNavigationParamsHistory() { + NavigationController* navigation_controller = + frame_tree_node_->navigator()->GetController(); + request_params_.current_history_list_offset = + navigation_controller->GetCurrentEntryIndex(); + request_params_.current_history_list_length = + navigation_controller->GetEntryCount(); +} + } // namespace content
diff --git a/content/browser/frame_host/navigation_request.h b/content/browser/frame_host/navigation_request.h index 925a71b8..176920602 100644 --- a/content/browser/frame_host/navigation_request.h +++ b/content/browser/frame_host/navigation_request.h
@@ -294,6 +294,11 @@ LegacyProtocolInSubresourceCheckResult CheckLegacyProtocolInSubresource() const; + // Called before a commit. Updates the history index and length held in + // RequestNavigationParams. This is used to update this shared state with the + // renderer process. + void UpdateRequestNavigationParamsHistory(); + FrameTreeNode* frame_tree_node_; // Initialized on creation of the NavigationRequest. Sent to the renderer when
diff --git a/content/browser/frame_host/render_frame_host_android.cc b/content/browser/frame_host/render_frame_host_android.cc index a042afe..9f36fd67 100644 --- a/content/browser/frame_host/render_frame_host_android.cc +++ b/content/browser/frame_host/render_frame_host_android.cc
@@ -93,4 +93,10 @@ env, render_frame_host_->GetOverlayRoutingToken()); } +void RenderFrameHostAndroid::SetHasReceivedUserGesture( + JNIEnv* env, + const base::android::JavaParamRef<jobject>&) { + render_frame_host_->SetHasReceivedUserGesture(); +} + } // namespace content
diff --git a/content/browser/frame_host/render_frame_host_android.h b/content/browser/frame_host/render_frame_host_android.h index 686f208..2e4e233 100644 --- a/content/browser/frame_host/render_frame_host_android.h +++ b/content/browser/frame_host/render_frame_host_android.h
@@ -49,6 +49,9 @@ JNIEnv* env, const base::android::JavaParamRef<jobject>&) const; + void SetHasReceivedUserGesture(JNIEnv* env, + const base::android::JavaParamRef<jobject>&); + private: RenderFrameHostImpl* const render_frame_host_; service_manager::mojom::InterfaceProviderPtr interface_provider_ptr_;
diff --git a/content/browser/frame_host/render_frame_host_impl.cc b/content/browser/frame_host/render_frame_host_impl.cc index c8b3e57a..f375b141 100644 --- a/content/browser/frame_host/render_frame_host_impl.cc +++ b/content/browser/frame_host/render_frame_host_impl.cc
@@ -1568,6 +1568,14 @@ OnBeforeUnloadACK(true, approx_renderer_start_time, base::TimeTicks::Now()); } + // If we're waiting for an unload ack from this renderer and we receive a + // Navigate message, then the renderer was navigating before it received the + // unload request. It will either respond to the unload request soon or our + // timer will expire. Either way, we should ignore this message, because we + // have already committed to closing this renderer. + if (IsWaitingForUnloadACK()) + return; + // Retroactive sanity check: // - If this is the first real load committing in this frame, then by this // time the RenderFrameHost's InterfaceProvider implementation should have @@ -1614,14 +1622,6 @@ // therefore the global object is not replaced. } - // If we're waiting for an unload ack from this renderer and we receive a - // Navigate message, then the renderer was navigating before it received the - // unload request. It will either respond to the unload request soon or our - // timer will expire. Either way, we should ignore this message, because we - // have already committed to closing this renderer. - if (IsWaitingForUnloadACK()) - return; - if (validated_params->report_type == FrameMsg_UILoadMetricsReportType::REPORT_LINK) { UMA_HISTOGRAM_CUSTOM_TIMES( @@ -2801,6 +2801,10 @@ bounds_in_frame_widget.size())); } +void RenderFrameHostImpl::SetHasReceivedUserGesture() { + Send(new FrameMsg_SetHasReceivedUserGesture(routing_id_)); +} + void RenderFrameHostImpl::OnSetHasReceivedUserGesture() { frame_tree_node_->OnSetHasReceivedUserGesture(); }
diff --git a/content/browser/frame_host/render_frame_host_impl.h b/content/browser/frame_host/render_frame_host_impl.h index 9e02cfd..bccb083 100644 --- a/content/browser/frame_host/render_frame_host_impl.h +++ b/content/browser/frame_host/render_frame_host_impl.h
@@ -682,6 +682,9 @@ // received by the other end. For test use only. void FlushNetworkAndNavigationInterfacesForTesting(); + // Notifies the render frame that a user gesture was received. + void SetHasReceivedUserGesture(); + protected: friend class RenderFrameHostFactory;
diff --git a/content/browser/frame_host/render_frame_host_impl_browsertest.cc b/content/browser/frame_host/render_frame_host_impl_browsertest.cc index 4c12cfc..695831e8 100644 --- a/content/browser/frame_host/render_frame_host_impl_browsertest.cc +++ b/content/browser/frame_host/render_frame_host_impl_browsertest.cc
@@ -25,7 +25,6 @@ #include "content/public/test/browser_test_utils.h" #include "content/public/test/content_browser_test.h" #include "content/public/test/content_browser_test_utils.h" -#include "content/public/test/controllable_http_response.h" #include "content/public/test/test_navigation_observer.h" #include "content/public/test/test_utils.h" #include "content/shell/browser/shell.h" @@ -33,6 +32,7 @@ #include "content/test/frame_host_test_interface.mojom.h" #include "content/test/test_content_browser_client.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 "services/network/public/cpp/features.h" @@ -719,7 +719,8 @@ IN_PROC_BROWSER_TEST_F( ContentBrowserTest, AbortedRendererInitiatedNavigationDoNotCancelPendingXHR) { - ControllableHttpResponse xhr_response(embedded_test_server(), "/xhr_request"); + net::test_server::ControllableHttpResponse xhr_response( + embedded_test_server(), "/xhr_request"); EXPECT_TRUE(embedded_test_server()->Start()); GURL main_url(embedded_test_server()->GetURL("/title1.html")); @@ -771,8 +772,8 @@ // See https://crbug.com/766149. IN_PROC_BROWSER_TEST_F(ContentBrowserTest, BrowserInitiatedJavascriptUrlDoNotPreventLoading) { - ControllableHttpResponse main_document_response(embedded_test_server(), - "/main_document"); + net::test_server::ControllableHttpResponse main_document_response( + embedded_test_server(), "/main_document"); EXPECT_TRUE(embedded_test_server()->Start()); GURL main_document_url(embedded_test_server()->GetURL("/main_document")); @@ -831,7 +832,8 @@ IN_PROC_BROWSER_TEST_F( ContentBrowserTest, SameDocumentBrowserInitiatedNavigationWhileDocumentIsLoading) { - ControllableHttpResponse response(embedded_test_server(), "/main_document"); + net::test_server::ControllableHttpResponse response(embedded_test_server(), + "/main_document"); EXPECT_TRUE(embedded_test_server()->Start()); // 1) Load a new document. It reaches the ReadyToCommit stage and then is slow
diff --git a/content/browser/frame_host/render_frame_host_manager_browsertest.cc b/content/browser/frame_host/render_frame_host_manager_browsertest.cc index b05d2a4..fb1e3c50 100644 --- a/content/browser/frame_host/render_frame_host_manager_browsertest.cc +++ b/content/browser/frame_host/render_frame_host_manager_browsertest.cc
@@ -47,13 +47,13 @@ #include "content/public/test/browser_test_utils.h" #include "content/public/test/content_browser_test.h" #include "content/public/test/content_browser_test_utils.h" -#include "content/public/test/controllable_http_response.h" #include "content/public/test/test_frame_navigation_observer.h" #include "content/public/test/test_navigation_observer.h" #include "content/public/test/test_utils.h" #include "content/shell/browser/shell.h" #include "content/test/content_browser_test_utils_internal.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/request_handler_util.h" #include "testing/gmock/include/gmock/gmock-matchers.h" @@ -1488,8 +1488,10 @@ return; const std::string kVictimPath = "/victim.html"; const std::string kAttackPath = "/attack.html"; - ControllableHttpResponse victim_response(embedded_test_server(), kVictimPath); - ControllableHttpResponse attack_response(embedded_test_server(), kAttackPath); + net::test_server::ControllableHttpResponse victim_response( + embedded_test_server(), kVictimPath); + net::test_server::ControllableHttpResponse attack_response( + embedded_test_server(), kAttackPath); EXPECT_TRUE(embedded_test_server()->Start()); const GURL kVictimURL = embedded_test_server()->GetURL("a.com", kVictimPath); @@ -1586,16 +1588,16 @@ const std::string kOriginalPath = "/original.html"; const std::string kFirstRedirectPath = "/redirect1.html"; const std::string kSecondRedirectPath = "/reidrect2.html"; - ControllableHttpResponse original_response1(embedded_test_server(), - kOriginalPath); - ControllableHttpResponse original_response2(embedded_test_server(), - kOriginalPath); - ControllableHttpResponse original_response3(embedded_test_server(), - kOriginalPath); - ControllableHttpResponse first_redirect_response(embedded_test_server(), - kFirstRedirectPath); - ControllableHttpResponse second_redirect_response(embedded_test_server(), - kSecondRedirectPath); + net::test_server::ControllableHttpResponse original_response1( + embedded_test_server(), kOriginalPath); + net::test_server::ControllableHttpResponse original_response2( + embedded_test_server(), kOriginalPath); + net::test_server::ControllableHttpResponse original_response3( + embedded_test_server(), kOriginalPath); + net::test_server::ControllableHttpResponse first_redirect_response( + embedded_test_server(), kFirstRedirectPath); + net::test_server::ControllableHttpResponse second_redirect_response( + embedded_test_server(), kSecondRedirectPath); EXPECT_TRUE(embedded_test_server()->Start()); const GURL kOriginalURL = @@ -1704,12 +1706,12 @@ DeleteSpeculativeRFHPendingCommitOfPendingEntryOnInterrupted2) { const std::string kOriginalPath = "/original.html"; const std::string kRedirectPath = "/redirect.html"; - ControllableHttpResponse original_response1(embedded_test_server(), - kOriginalPath); - ControllableHttpResponse original_response2(embedded_test_server(), - kOriginalPath); - ControllableHttpResponse redirect_response(embedded_test_server(), - kRedirectPath); + net::test_server::ControllableHttpResponse original_response1( + embedded_test_server(), kOriginalPath); + net::test_server::ControllableHttpResponse original_response2( + embedded_test_server(), kOriginalPath); + net::test_server::ControllableHttpResponse redirect_response( + embedded_test_server(), kRedirectPath); EXPECT_TRUE(embedded_test_server()->Start()); const GURL kOriginalURL =
diff --git a/content/browser/frame_host/render_frame_message_filter.cc b/content/browser/frame_host/render_frame_message_filter.cc index 5a4a13b2..8070b33 100644 --- a/content/browser/frame_host/render_frame_message_filter.cc +++ b/content/browser/frame_host/render_frame_message_filter.cc
@@ -107,7 +107,7 @@ BrowserContext* browser_context = render_process_host->GetBrowserContext(); DownloadManager* download_manager = BrowserContext::GetDownloadManager(browser_context); - parameters->set_download_source(DownloadSource::FROM_RENDERER); + parameters->set_download_source(download::DownloadSource::FROM_RENDERER); download_manager->DownloadUrl(std::move(parameters)); }
diff --git a/content/browser/loader/merkle_integrity_source_stream.cc b/content/browser/loader/merkle_integrity_source_stream.cc new file mode 100644 index 0000000..6657b3d1 --- /dev/null +++ b/content/browser/loader/merkle_integrity_source_stream.cc
@@ -0,0 +1,119 @@ +// 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 "content/browser/loader/merkle_integrity_source_stream.h" + +#include "base/base64url.h" +#include "base/big_endian.h" +#include "crypto/sha2.h" +#include "net/base/io_buffer.h" + +namespace content { + +namespace { + +// Limit the record size to 5MiB to prevent browser OOM. +constexpr uint64_t kMaxRecordSize = 5 * 1024 * 1024; + +constexpr char kMiSha256Header[] = "mi-sha256="; +constexpr int kMiSha256HeaderLength = sizeof(kMiSha256Header) - 1; + +} // namespace + +MerkleIntegritySourceStream::MerkleIntegritySourceStream( + const std::string& mi_header_value, + std::unique_ptr<SourceStream> upstream) + // TODO(ksakamoto): Use appropriate SourceType. + : net::FilterSourceStream(SourceStream::TYPE_NONE, std::move(upstream)), + record_size_(0), + failed_(false) { + // TODO(ksakamoto): Support quoted parameter value. + if (mi_header_value.substr(0, kMiSha256HeaderLength) != kMiSha256Header || + !base::Base64UrlDecode(mi_header_value.substr(kMiSha256HeaderLength), + base::Base64UrlDecodePolicy::DISALLOW_PADDING, + &next_proof_) || + next_proof_.size() != crypto::kSHA256Length) { + failed_ = true; + } +} + +int MerkleIntegritySourceStream::FilterData(net::IOBuffer* output_buffer, + int output_buffer_size, + net::IOBuffer* input_buffer, + int input_buffer_size, + int* consumed_bytes, + bool upstream_eof_reached) { + if (failed_) + return net::ERR_CONTENT_DECODING_FAILED; + + // TODO(ksakamoto): Avoid unnecessary buffer copying. + input_.append(input_buffer->data(), input_buffer_size); + *consumed_bytes = input_buffer_size; + + if (!ProcessInput(upstream_eof_reached)) { + failed_ = true; + return net::ERR_CONTENT_DECODING_FAILED; + } + + int bytes_out = + std::min(output_.size(), static_cast<size_t>(output_buffer_size)); + output_.copy(output_buffer->data(), bytes_out); + output_.erase(0, bytes_out); + return bytes_out; +} + +bool MerkleIntegritySourceStream::ProcessInput(bool upstream_eof_reached) { + // TODO(ksakamoto): Use shift iterator or StringPiece instead of substr/erase. + + // Read the record size (the first 8 octets of the stream). + if (!record_size_) { + if (input_.size() < 8) + return !upstream_eof_reached; + + base::ReadBigEndian(input_.data(), &record_size_); + input_.erase(0, 8); + if (record_size_ == 0) + return false; + if (record_size_ > kMaxRecordSize) { + DVLOG(1) + << "Rejecting MI content encoding because record size is too big: " + << record_size_; + return false; + } + } + + // Process records other than the last. + while (input_.size() >= record_size_ + crypto::kSHA256Length) { + std::string chunk = input_.substr(0, record_size_ + crypto::kSHA256Length); + input_.erase(0, record_size_ + crypto::kSHA256Length); + chunk.push_back('\x01'); + std::string hash = crypto::SHA256HashString(chunk); + if (next_proof_ != hash) + return false; + output_.append(chunk.substr(0, record_size_)); + next_proof_ = chunk.substr(record_size_, crypto::kSHA256Length); + } + + // Process the last record. + if (upstream_eof_reached && !next_proof_.empty()) { + if (input_.size() > record_size_) + return false; + + input_.push_back('\0'); + std::string hash = crypto::SHA256HashString(input_); + if (next_proof_ != hash) + return false; + + output_.append(input_.substr(0, input_.size() - 1)); + input_.clear(); + next_proof_.clear(); + } + return true; +} + +std::string MerkleIntegritySourceStream::GetTypeAsString() const { + return "MI-256"; +} + +} // namespace content
diff --git a/content/browser/loader/merkle_integrity_source_stream.h b/content/browser/loader/merkle_integrity_source_stream.h new file mode 100644 index 0000000..135d24c --- /dev/null +++ b/content/browser/loader/merkle_integrity_source_stream.h
@@ -0,0 +1,51 @@ +// 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. + +#ifndef CONTENT_BROWSER_LOADER_MERKLE_INTEGRITY_SOURCE_STREAM_H_ +#define CONTENT_BROWSER_LOADER_MERKLE_INTEGRITY_SOURCE_STREAM_H_ + +#include <stdint.h> +#include <string> + +#include "base/macros.h" +#include "content/common/content_export.h" +#include "net/filter/filter_source_stream.h" + +namespace content { + +// MerkleIntegritySourceStream decodes and validates content encoded with the +// "mi-sha256" content encoding +// (https://tools.ietf.org/html/draft-thomson-http-mice-02). +// TODO(ksakamoto): This class should eventually live in src/net/filter/. +class CONTENT_EXPORT MerkleIntegritySourceStream + : public net::FilterSourceStream { + public: + MerkleIntegritySourceStream(const std::string& mi_header_value, + std::unique_ptr<SourceStream> upstream); + + // net::FilterSourceStream + int FilterData(net::IOBuffer* output_buffer, + int output_buffer_size, + net::IOBuffer* input_buffer, + int input_buffer_size, + int* consumed_bytes, + bool upstream_eof_reached) override; + std::string GetTypeAsString() const override; + + private: + bool ProcessInput(bool upstream_eof_reached); + + std::string input_; + std::string output_; + // SHA-256 hash for the next record, or empty if validation is completed. + std::string next_proof_; + uint64_t record_size_; + bool failed_; + + DISALLOW_COPY_AND_ASSIGN(MerkleIntegritySourceStream); +}; + +} // namespace content + +#endif // CONTENT_BROWSER_LOADER_MERKLE_INTEGRITY_SOURCE_STREAM_H_
diff --git a/content/browser/loader/merkle_integrity_source_stream_unittest.cc b/content/browser/loader/merkle_integrity_source_stream_unittest.cc new file mode 100644 index 0000000..732bded --- /dev/null +++ b/content/browser/loader/merkle_integrity_source_stream_unittest.cc
@@ -0,0 +1,287 @@ +// 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 "content/browser/loader/merkle_integrity_source_stream.h" +#include "base/base64url.h" +#include "net/base/io_buffer.h" +#include "net/base/test_completion_callback.h" +#include "net/filter/mock_source_stream.h" +#include "testing/gtest/include/gtest/gtest.h" + +namespace content { + +namespace { + +const int kBigBufferSize = 4096; +const int kSmallBufferSize = 1; + +const char kMIEmptyBody[] = + "mi-sha256=bjQLnP-zepicpUTmu3gKLHiQHT-zNzh2hRGjBhevoB0"; +const char kMISingleRecord[] = + "mi-sha256=dcRDgR2GM35DluAV13PzgnG6-pvQwPywfFvAu1UeFrs"; +const char kMIMultipleRecords[] = + "mi-sha256=IVa9shfs0nyKEhHqtB3WVNANJ2Njm5KjQLjRtnbkYJ4"; + +enum class ReadResultType { + // Each call to AddReadResult is a separate read from the lower layer + // SourceStream. + EVERYTHING_AT_ONCE, + // Whenever AddReadResult is called, each byte is actually a separate read + // result. + ONE_BYTE_AT_A_TIME, +}; + +struct MerkleIntegrityTestParam { + MerkleIntegrityTestParam(int buf_size, + net::MockSourceStream::Mode read_mode, + ReadResultType read_result_type) + : buffer_size(buf_size), + mode(read_mode), + read_result_type(read_result_type) {} + + const int buffer_size; + const net::MockSourceStream::Mode mode; + const ReadResultType read_result_type; +}; + +} // namespace + +class MerkleIntegritySourceStreamTest + : public ::testing::TestWithParam<MerkleIntegrityTestParam> { + protected: + MerkleIntegritySourceStreamTest() + : output_buffer_size_(GetParam().buffer_size) {} + + void Init(const std::string& mi_header_value) { + output_buffer_ = new net::IOBuffer(output_buffer_size_); + std::unique_ptr<net::MockSourceStream> source(new net::MockSourceStream()); + if (GetParam().read_result_type == ReadResultType::ONE_BYTE_AT_A_TIME) + source->set_read_one_byte_at_a_time(true); + source_ = source.get(); + stream_ = std::make_unique<MerkleIntegritySourceStream>(mi_header_value, + std::move(source)); + } + + // If MockSourceStream::Mode is ASYNC, completes reads from |mock_stream| + // until there's no pending read, and then returns |callback|'s result, once + // it's invoked. If Mode is not ASYNC, does nothing and returns + // |previous_result|. + int CompleteReadsIfAsync(int previous_result, + net::TestCompletionCallback* callback, + net::MockSourceStream* mock_stream) { + if (GetParam().mode == net::MockSourceStream::ASYNC) { + EXPECT_EQ(net::ERR_IO_PENDING, previous_result); + while (mock_stream->awaiting_completion()) + mock_stream->CompleteNextRead(); + return callback->WaitForResult(); + } + return previous_result; + } + + net::IOBuffer* output_buffer() { return output_buffer_.get(); } + char* output_data() { return output_buffer_->data(); } + size_t output_buffer_size() { return output_buffer_size_; } + + net::MockSourceStream* source() { return source_; } + MerkleIntegritySourceStream* stream() { return stream_.get(); } + + // Reads from |stream_| until an error occurs or the EOF is reached. + // When an error occurs, returns the net error code. When an EOF is reached, + // returns the number of bytes read and appends data read to |output|. + int ReadStream(std::string* output) { + int bytes_read = 0; + while (true) { + net::TestCompletionCallback callback; + int rv = stream_->Read(output_buffer(), output_buffer_size(), + callback.callback()); + if (rv == net::ERR_IO_PENDING) + rv = CompleteReadsIfAsync(rv, &callback, source()); + if (rv == net::OK) + break; + if (rv < net::OK) + return rv; + EXPECT_GT(rv, net::OK); + bytes_read += rv; + output->append(output_data(), rv); + } + return bytes_read; + } + + std::string Base64Decode(const char* hash) { + std::string out; + EXPECT_TRUE(base::Base64UrlDecode( + hash, base::Base64UrlDecodePolicy::DISALLOW_PADDING, &out)); + EXPECT_EQ(32u, out.size()); + return out; + } + + private: + scoped_refptr<net::IOBuffer> output_buffer_; + int output_buffer_size_; + + net::MockSourceStream* source_; + std::unique_ptr<MerkleIntegritySourceStream> stream_; +}; + +INSTANTIATE_TEST_CASE_P( + MerkleIntegritySourceStreamTests, + MerkleIntegritySourceStreamTest, + ::testing::Values( + MerkleIntegrityTestParam(kBigBufferSize, + net::MockSourceStream::SYNC, + ReadResultType::EVERYTHING_AT_ONCE), + MerkleIntegrityTestParam(kSmallBufferSize, + net::MockSourceStream::SYNC, + ReadResultType::EVERYTHING_AT_ONCE), + MerkleIntegrityTestParam(kBigBufferSize, + net::MockSourceStream::ASYNC, + ReadResultType::EVERYTHING_AT_ONCE), + MerkleIntegrityTestParam(kSmallBufferSize, + net::MockSourceStream::ASYNC, + ReadResultType::EVERYTHING_AT_ONCE), + MerkleIntegrityTestParam(kBigBufferSize, + net::MockSourceStream::SYNC, + ReadResultType::ONE_BYTE_AT_A_TIME), + MerkleIntegrityTestParam(kSmallBufferSize, + net::MockSourceStream::SYNC, + ReadResultType::ONE_BYTE_AT_A_TIME), + MerkleIntegrityTestParam(kBigBufferSize, + net::MockSourceStream::ASYNC, + ReadResultType::ONE_BYTE_AT_A_TIME), + MerkleIntegrityTestParam(kSmallBufferSize, + net::MockSourceStream::ASYNC, + ReadResultType::ONE_BYTE_AT_A_TIME))); + +TEST_P(MerkleIntegritySourceStreamTest, EmptyStream) { + Init(kMIEmptyBody); + source()->AddReadResult(nullptr, 0, net::OK, GetParam().mode); + std::string actual_output; + int result = ReadStream(&actual_output); + EXPECT_EQ(net::ERR_CONTENT_DECODING_FAILED, result); +} + +TEST_P(MerkleIntegritySourceStreamTest, MalformedMIHeader) { + Init("invalid-MI-header-value"); + source()->AddReadResult(nullptr, 0, net::OK, GetParam().mode); + std::string actual_output; + int result = ReadStream(&actual_output); + EXPECT_EQ(net::ERR_CONTENT_DECODING_FAILED, result); +} + +TEST_P(MerkleIntegritySourceStreamTest, RecordSizeOnly) { + Init(kMIEmptyBody); + const uint8_t record_size[] = {0, 0, 0, 0, 0, 0, 0, 10}; + source()->AddReadResult(reinterpret_cast<const char*>(record_size), + sizeof(record_size), net::OK, GetParam().mode); + source()->AddReadResult(nullptr, 0, net::OK, GetParam().mode); + std::string actual_output; + int result = ReadStream(&actual_output); + EXPECT_EQ(net::OK, result); +} + +TEST_P(MerkleIntegritySourceStreamTest, RecordSizeOnlyWrongHash) { + Init(kMISingleRecord); + const uint8_t record_size[] = {0, 0, 0, 0, 0, 0, 0, 10}; + source()->AddReadResult(reinterpret_cast<const char*>(record_size), + sizeof(record_size), net::OK, GetParam().mode); + source()->AddReadResult(nullptr, 0, net::OK, GetParam().mode); + std::string actual_output; + int result = ReadStream(&actual_output); + EXPECT_EQ(net::ERR_CONTENT_DECODING_FAILED, result); +} + +TEST_P(MerkleIntegritySourceStreamTest, RecordSizeTooBig) { + Init(kMIEmptyBody); + const uint8_t record_size[] = {0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff}; + source()->AddReadResult(reinterpret_cast<const char*>(record_size), + sizeof(record_size), net::OK, GetParam().mode); + std::string actual_output; + int result = ReadStream(&actual_output); + EXPECT_EQ(net::ERR_CONTENT_DECODING_FAILED, result); +} + +// https://tools.ietf.org/html/draft-thomson-http-mice-02#section-4.1 +TEST_P(MerkleIntegritySourceStreamTest, SingleRecord) { + Init(kMISingleRecord); + const uint8_t record_size[] = {0, 0, 0, 0, 0, 0, 0, 0x29}; + const std::string message("When I grow up, I want to be a watermelon"); + source()->AddReadResult(reinterpret_cast<const char*>(record_size), + sizeof(record_size), net::OK, GetParam().mode); + source()->AddReadResult(message.data(), message.size(), net::OK, + GetParam().mode); + source()->AddReadResult(nullptr, 0, net::OK, GetParam().mode); + std::string actual_output; + int rv = ReadStream(&actual_output); + EXPECT_EQ(static_cast<int>(message.size()), rv); + EXPECT_EQ(message, actual_output); +} + +TEST_P(MerkleIntegritySourceStreamTest, SingleRecordWrongHash) { + Init(kMIEmptyBody); + const uint8_t record_size[] = {0, 0, 0, 0, 0, 0, 0, 0x29}; + const std::string message("When I grow up, I want to be a watermelon"); + source()->AddReadResult(reinterpret_cast<const char*>(record_size), + sizeof(record_size), net::OK, GetParam().mode); + source()->AddReadResult(message.data(), message.size(), net::OK, + GetParam().mode); + source()->AddReadResult(nullptr, 0, net::OK, GetParam().mode); + std::string actual_output; + int rv = ReadStream(&actual_output); + EXPECT_EQ(net::ERR_CONTENT_DECODING_FAILED, rv); + EXPECT_EQ(0u, actual_output.size()); +} + +// https://tools.ietf.org/html/draft-thomson-http-mice-02#section-4.2 +TEST_P(MerkleIntegritySourceStreamTest, MultipleRecords) { + Init(kMIMultipleRecords); + const uint8_t record_size[] = {0, 0, 0, 0, 0, 0, 0, 16}; + const std::string message("When I grow up, I want to be a watermelon"); + + source()->AddReadResult(reinterpret_cast<const char*>(record_size), + sizeof(record_size), net::OK, GetParam().mode); + source()->AddReadResult(message.data(), 16, net::OK, GetParam().mode); + std::string hash1 = + Base64Decode("OElbplJlPK-Rv6JNK6p5_515IaoPoZo-2elWL7OQ60A"); + source()->AddReadResult(hash1.data(), 32, net::OK, GetParam().mode); + source()->AddReadResult(message.data() + 16, 16, net::OK, GetParam().mode); + std::string hash2 = + Base64Decode("iPMpmgExHPrbEX3_RvwP4d16fWlK4l--p75PUu_KyN0"); + source()->AddReadResult(hash2.data(), 32, net::OK, GetParam().mode); + source()->AddReadResult(message.data() + 32, message.size() - 32, net::OK, + GetParam().mode); + + source()->AddReadResult(nullptr, 0, net::OK, GetParam().mode); + std::string actual_output; + int rv = ReadStream(&actual_output); + EXPECT_EQ(static_cast<int>(message.size()), rv); + EXPECT_EQ(message, actual_output); +} + +TEST_P(MerkleIntegritySourceStreamTest, MultipleRecordsWrongLastRecordHash) { + Init(kMIMultipleRecords); + const uint8_t record_size[] = {0, 0, 0, 0, 0, 0, 0, 16}; + const std::string message("When I grow up, I want to be a watermelon!"); + + source()->AddReadResult(reinterpret_cast<const char*>(record_size), + sizeof(record_size), net::OK, GetParam().mode); + source()->AddReadResult(message.data(), 16, net::OK, GetParam().mode); + std::string hash1 = + Base64Decode("OElbplJlPK-Rv6JNK6p5_515IaoPoZo-2elWL7OQ60A"); + source()->AddReadResult(hash1.data(), 32, net::OK, GetParam().mode); + source()->AddReadResult(message.data() + 16, 16, net::OK, GetParam().mode); + std::string hash2 = + Base64Decode("iPMpmgExHPrbEX3_RvwP4d16fWlK4l--p75PUu_KyN0"); + source()->AddReadResult(hash2.data(), 32, net::OK, GetParam().mode); + source()->AddReadResult(message.data() + 32, message.size() - 32, net::OK, + GetParam().mode); + source()->AddReadResult(nullptr, 0, net::OK, GetParam().mode); + + std::string actual_output; + int rv = ReadStream(&actual_output); + EXPECT_EQ(net::ERR_CONTENT_DECODING_FAILED, rv); + EXPECT_EQ(message.substr(0, 32), actual_output); +} + +} // namespace content
diff --git a/content/browser/loader/mime_sniffing_resource_handler.cc b/content/browser/loader/mime_sniffing_resource_handler.cc index 7febaba..178b178 100644 --- a/content/browser/loader/mime_sniffing_resource_handler.cc +++ b/content/browser/loader/mime_sniffing_resource_handler.cc
@@ -24,7 +24,6 @@ #include "content/browser/loader/web_package_request_handler.h" #include "content/public/browser/content_browser_client.h" #include "content/public/browser/download_item.h" -#include "content/public/browser/download_save_info.h" #include "content/public/browser/download_url_parameters.h" #include "content/public/browser/plugin_service.h" #include "content/public/browser/resource_context.h"
diff --git a/content/browser/loader/navigation_url_loader_network_service.cc b/content/browser/loader/navigation_url_loader_network_service.cc index 8588ddb78..349cfd8a 100644 --- a/content/browser/loader/navigation_url_loader_network_service.cc +++ b/content/browser/loader/navigation_url_loader_network_service.cc
@@ -342,7 +342,7 @@ DCHECK(!started_); started_ = true; - StartLoaderCallback create_url_loader = base::BindOnce( + auto load_single_request = base::BindOnce( &URLLoaderRequestController::CreateNonNetworkServiceURLLoader, weak_factory_.GetWeakPtr(), base::Unretained(url_request_context_getter), @@ -353,9 +353,11 @@ network::ResourceRequest resource_request; url_loader_ = ThrottlingURLLoader::CreateLoaderAndStart( - std::move(create_url_loader), + base::MakeRefCounted<SingleRequestURLLoaderFactory>( + std::move(load_single_request)), std::vector<std::unique_ptr<content::URLLoaderThrottle>>(), - /* routing_id = */ -1, &resource_request, + -1 /* routing_id = */, 0 /* request_id */, + network::mojom::kURLLoadOptionNone, &resource_request, /* client = */ this, kNavigationUrlLoaderTrafficAnnotation, base::ThreadTaskRunnerHandle::Get()); } @@ -449,27 +451,30 @@ url_loader_.reset(); handler_index_ = 0; received_response_ = false; - MaybeStartLoader(nullptr /* handler */, StartLoaderCallback()); + MaybeStartLoader(nullptr /* handler */, {} /* single_request_handler */); } // |handler| is the one who called this method (as a LoaderCallback), nullptr // if this method is not called by a handler. - // |start_loader_callback| is the callback given by the |handler|, non-null - // if the |handler| wants to handle the request. - void MaybeStartLoader(URLLoaderRequestHandler* handler, - StartLoaderCallback start_loader_callback) { + // |single_request_handler| is the RequestHandler given by the |handler|, + // non-null if the handler wants to handle the request. + void MaybeStartLoader( + URLLoaderRequestHandler* handler, + SingleRequestURLLoaderFactory::RequestHandler single_request_handler) { DCHECK(IsRequestHandlerEnabled()); - if (start_loader_callback) { + if (single_request_handler) { // |handler| wants to handle the request. DCHECK(handler); default_loader_used_ = false; url_loader_ = ThrottlingURLLoader::CreateLoaderAndStart( - std::move(start_loader_callback), + base::MakeRefCounted<SingleRequestURLLoaderFactory>( + std::move(single_request_handler)), base::FeatureList::IsEnabled(network::features::kNetworkService) ? GetContentClient()->browser()->CreateURLLoaderThrottles( web_contents_getter_, navigation_ui_data_.get()) : std::vector<std::unique_ptr<content::URLLoaderThrottle>>(), - frame_tree_node_id_, resource_request_.get(), this, + frame_tree_node_id_, 0 /* request_id? */, + network::mojom::kURLLoadOptionNone, resource_request_.get(), this, kNavigationUrlLoaderTrafficAnnotation, base::ThreadTaskRunnerHandle::Get()); @@ -486,7 +491,7 @@ // to the child process. This is necessary for correctness in the cases // where, e.g. there's a controlling ServiceWorker that doesn't handle main // resource loading, but may still want to control the page and/or handle - // subresource loading. In that case we want to skip APpCache. + // subresource loading. In that case we want to skip AppCache. if (handler) { subresource_loader_params_ = handler->MaybeCreateSubresourceLoaderParams(); @@ -904,17 +909,13 @@ weak_factory_.GetWeakPtr()); BrowserThread::PostTask( BrowserThread::IO, FROM_HERE, - base::BindOnce(&URLLoaderRequestController::Start, - base::Unretained(request_controller_.get()), - base::Unretained(service_worker_navigation_handle_core), - base::Unretained(appcache_handle_core), - base::Passed(std::move(request_info)), - base::Passed(std::move(navigation_ui_data)), - base::Passed(std::move(factory_for_webui)), - frame_tree_node_id, - base::Passed(ServiceManagerConnection::GetForProcess() - ->GetConnector() - ->Clone()))); + base::BindOnce( + &URLLoaderRequestController::Start, + base::Unretained(request_controller_.get()), + service_worker_navigation_handle_core, appcache_handle_core, + std::move(request_info), std::move(navigation_ui_data), + std::move(factory_for_webui), frame_tree_node_id, + ServiceManagerConnection::GetForProcess()->GetConnector()->Clone())); non_network_url_loader_factories_[url::kFileScheme] = std::make_unique<FileURLLoaderFactory>(
diff --git a/content/browser/loader/navigation_url_loader_network_service_unittest.cc b/content/browser/loader/navigation_url_loader_network_service_unittest.cc index a0eff0a..0a9794f 100644 --- a/content/browser/loader/navigation_url_loader_network_service_unittest.cc +++ b/content/browser/loader/navigation_url_loader_network_service_unittest.cc
@@ -33,6 +33,7 @@ namespace content { namespace { + class TestURLLoaderRequestHandler : public URLLoaderRequestHandler { public: explicit TestURLLoaderRequestHandler( @@ -45,8 +46,8 @@ ResourceContext* resource_context, LoaderCallback callback) override { std::move(callback).Run( - base::Bind(&TestURLLoaderRequestHandler::StartLoader, - base::Unretained(this), resource_request)); + base::BindOnce(&TestURLLoaderRequestHandler::StartLoader, + base::Unretained(this), resource_request)); } void StartLoader(network::ResourceRequest resource_request,
diff --git a/content/browser/loader/redirect_to_file_resource_handler_unittest.cc b/content/browser/loader/redirect_to_file_resource_handler_unittest.cc index ae7a525f..afdb0ef 100644 --- a/content/browser/loader/redirect_to_file_resource_handler_unittest.cc +++ b/content/browser/loader/redirect_to_file_resource_handler_unittest.cc
@@ -28,6 +28,7 @@ #include "content/browser/loader/test_resource_handler.h" #include "content/public/test/test_browser_thread_bundle.h" #include "net/base/completion_callback.h" +#include "net/base/completion_once_callback.h" #include "net/base/file_stream.h" #include "net/base/io_buffer.h" #include "net/base/mime_sniffer.h" @@ -91,16 +92,16 @@ int Open(const base::FilePath& path, int open_flags, - const net::CompletionCallback& callback) override { - return ReturnResult(open_result_, callback); + net::CompletionOnceCallback callback) override { + return ReturnResult(open_result_, std::move(callback)); } - int Close(const net::CompletionCallback& callback) override { + int Close(net::CompletionOnceCallback callback) override { EXPECT_FALSE(closed_); int result = ReturnResult( close_result_, - base::BindRepeating(&MockFileStream::SetClosedAndRunCallback, - base::Unretained(this), callback)); + base::BindOnce(&MockFileStream::SetClosedAndRunCallback, + base::Unretained(this), std::move(callback))); if (result != net::ERR_IO_PENDING) closed_ = true; return result; @@ -111,22 +112,21 @@ return false; } - int Seek(int64_t offset, - const net::Int64CompletionCallback& callback) override { + int Seek(int64_t offset, net::Int64CompletionOnceCallback callback) override { NOTREACHED(); return net::ERR_UNEXPECTED; } int Read(net::IOBuffer* buf, int buf_len, - const net::CompletionCallback& callback) override { + net::CompletionOnceCallback callback) override { NOTREACHED(); return net::ERR_UNEXPECTED; } int Write(net::IOBuffer* buf, int buf_len, - const net::CompletionCallback& callback) override { + net::CompletionOnceCallback callback) override { // 0-byte writes aren't allowed. EXPECT_GT(buf_len, 0); @@ -137,10 +137,10 @@ if (write_result.result > 0) written_data_ += std::string(buf->data(), write_result.result); - return ReturnResult(write_result, callback); + return ReturnResult(write_result, std::move(callback)); } - int Flush(const net::CompletionCallback& callback) override { + int Flush(net::CompletionOnceCallback callback) override { NOTREACHED(); return net::ERR_UNEXPECTED; } @@ -172,19 +172,19 @@ void set_expect_closed(bool expect_closed) { expect_closed_ = expect_closed; } private: - void SetClosedAndRunCallback(const net::CompletionCallback& callback, + void SetClosedAndRunCallback(net::CompletionOnceCallback callback, int result) { EXPECT_FALSE(closed_); closed_ = true; - callback.Run(result); + std::move(callback).Run(result); } int ReturnResult(OperationResult result, - const net::CompletionCallback& callback) { + net::CompletionOnceCallback callback) { if (result.completion_mode == CompletionMode::SYNC) return result.result; base::ThreadTaskRunnerHandle::Get()->PostTask( - FROM_HERE, base::BindOnce(callback, result.result)); + FROM_HERE, base::BindOnce(std::move(callback), result.result)); return net::ERR_IO_PENDING; }
diff --git a/content/browser/loader/url_loader_request_handler.h b/content/browser/loader/url_loader_request_handler.h index aed7dbf7..8356eab6 100644 --- a/content/browser/loader/url_loader_request_handler.h +++ b/content/browser/loader/url_loader_request_handler.h
@@ -6,10 +6,12 @@ #define CONTENT_BROWSER_LOADER_URL_LOADER_REQUEST_HANDLER_H_ #include <memory> + #include "base/callback_forward.h" #include "base/macros.h" #include "base/optional.h" #include "content/common/content_export.h" +#include "content/common/single_request_url_loader_factory.h" #include "net/url_request/redirect_info.h" #include "services/network/public/interfaces/url_loader.mojom.h" #include "services/network/public/interfaces/url_loader_factory.mojom.h" @@ -21,12 +23,6 @@ struct SubresourceLoaderParams; class ThrottlingURLLoader; -using StartLoaderCallback = - base::OnceCallback<void(network::mojom::URLLoaderRequest request, - network::mojom::URLLoaderClientPtr client)>; - -using LoaderCallback = base::OnceCallback<void(StartLoaderCallback)>; - // An instance of this class is a per-request object and kept around during // the lifetime of a request (including multiple redirect legs) on IO thread. class CONTENT_EXPORT URLLoaderRequestHandler { @@ -34,8 +30,13 @@ URLLoaderRequestHandler() = default; virtual ~URLLoaderRequestHandler() = default; - // Calls |callback| with a non-null StartLoaderCallback if this handler - // can handle the request, calls it with null callback otherwise. + using LoaderCallback = + base::OnceCallback<void(SingleRequestURLLoaderFactory::RequestHandler)>; + + // Asks this handler to handle this resource load request. + // The handler must invoke |callback| eventually with either a non-null + // RequestHandler indicating its willingness to handle the request, or a null + // RequestHandler to indicate that someone else should handle the request. virtual void MaybeCreateLoader( const network::ResourceRequest& resource_request, ResourceContext* resource_context,
diff --git a/content/browser/loader/web_package_request_handler.cc b/content/browser/loader/web_package_request_handler.cc index d9c81430..8959eb3 100644 --- a/content/browser/loader/web_package_request_handler.cc +++ b/content/browser/loader/web_package_request_handler.cc
@@ -38,7 +38,7 @@ // WebPackagePrefetcher. if (!web_package_loader_) { - std::move(callback).Run(StartLoaderCallback()); + std::move(callback).Run({}); return; }
diff --git a/content/browser/locks/lock_manager.cc b/content/browser/locks/lock_manager.cc index e33507d..033ac3b 100644 --- a/content/browser/locks/lock_manager.cc +++ b/content/browser/locks/lock_manager.cc
@@ -232,10 +232,13 @@ DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); const url::Origin& origin = bindings_.dispatch_context().origin; - if (!base::ContainsKey(origins_, origin)) + if (!base::ContainsKey(origins_, origin)) { + std::move(callback).Run(std::vector<blink::mojom::LockInfoPtr>(), + std::vector<blink::mojom::LockInfoPtr>()); return; - OriginState& state = origins_[origin]; + } + OriginState& state = origins_[origin]; std::move(callback).Run(state.SnapshotRequested(), state.SnapshotHeld()); }
diff --git a/content/browser/network_service_restart_browsertest.cc b/content/browser/network_service_restart_browsertest.cc index 7661eca..e4f5a758 100644 --- a/content/browser/network_service_restart_browsertest.cc +++ b/content/browser/network_service_restart_browsertest.cc
@@ -83,6 +83,9 @@ } void SetUpOnMainThread() override { + embedded_test_server()->RegisterRequestMonitor( + base::BindRepeating(&NetworkServiceRestartBrowserTest::MonitorRequest, + base::Unretained(this))); EXPECT_TRUE(embedded_test_server()->Start()); ContentBrowserTest::SetUpOnMainThread(); } @@ -97,7 +100,45 @@ return shell()->web_contents()->GetBrowserContext(); } + RenderFrameHostImpl* main_frame() { + return static_cast<RenderFrameHostImpl*>( + shell()->web_contents()->GetMainFrame()); + } + + bool CheckCanLoadHttp(const std::string& relative_url) { + GURL test_url = embedded_test_server()->GetURL(relative_url); + std::string script( + "var xhr = new XMLHttpRequest();" + "xhr.open('GET', '"); + script += test_url.spec() + + "', true);" + "xhr.onload = function (e) {" + " if (xhr.readyState === 4) {" + " window.domAutomationController.send(xhr.status === 200);" + " }" + "};" + "xhr.onerror = function () {" + " window.domAutomationController.send(false);" + "};" + "xhr.send(null)"; + bool xhr_result = false; + // The JS call will fail if disallowed because the process will be killed. + bool execute_result = + ExecuteScriptAndExtractBool(shell(), script, &xhr_result); + return xhr_result && execute_result; + } + + // Called by |embedded_test_server()|. + void MonitorRequest(const net::test_server::HttpRequest& request) { + last_request_relative_url_ = request.relative_url; + } + + std::string last_request_relative_url() const { + return last_request_relative_url_; + } + private: + std::string last_request_relative_url_; base::test::ScopedFeatureList scoped_feature_list_; DISALLOW_COPY_AND_ASSIGN(NetworkServiceRestartBrowserTest); @@ -197,76 +238,12 @@ NavigateToURL(shell(), embedded_test_server()->GetURL("/title2.html"))); } -class NetworkServiceRestartDisableWebSecurityTest - : public NetworkServiceRestartBrowserTest { - public: - NetworkServiceRestartDisableWebSecurityTest() {} - - void SetUpCommandLine(base::CommandLine* command_line) override { - // Simulate a compromised renderer, otherwise the cross-origin request is - // blocked. - command_line->AppendSwitch(switches::kDisableWebSecurity); - NetworkServiceRestartBrowserTest::SetUpCommandLine(command_line); - } - - void SetUpOnMainThread() override { - host_resolver()->AddRule("*", "127.0.0.1"); - embedded_test_server()->RegisterRequestMonitor(base::BindRepeating( - &NetworkServiceRestartDisableWebSecurityTest::MonitorRequest, - base::Unretained(this))); - NetworkServiceRestartBrowserTest::SetUpOnMainThread(); - } - - RenderFrameHostImpl* main_frame() { - return static_cast<RenderFrameHostImpl*>( - shell()->web_contents()->GetMainFrame()); - } - - bool CheckCanLoadHttp(const std::string& relative_url) { - GURL test_url = embedded_test_server()->GetURL(relative_url); - std::string script( - "var xhr = new XMLHttpRequest();" - "xhr.open('GET', '"); - script += test_url.spec() + - "', true);" - "xhr.onload = function (e) {" - " if (xhr.readyState === 4) {" - " window.domAutomationController.send(xhr.status === 200);" - " }" - "};" - "xhr.onerror = function () {" - " window.domAutomationController.send(false);" - "};" - "xhr.send(null)"; - bool xhr_result = false; - // The JS call will fail if disallowed because the process will be killed. - bool execute_result = - ExecuteScriptAndExtractBool(shell(), script, &xhr_result); - return xhr_result && execute_result; - } - - // Called by |embedded_test_server()|. - void MonitorRequest(const net::test_server::HttpRequest& request) { - last_request_relative_url_ = request.relative_url; - } - - std::string last_request_relative_url() const { - return last_request_relative_url_; - } - - private: - std::string last_request_relative_url_; - - DISALLOW_COPY_AND_ASSIGN(NetworkServiceRestartDisableWebSecurityTest); -}; - // Make sure basic XHR works after crash. -IN_PROC_BROWSER_TEST_F(NetworkServiceRestartDisableWebSecurityTest, BasicXHR) { +IN_PROC_BROWSER_TEST_F(NetworkServiceRestartBrowserTest, BasicXHR) { StoragePartitionImpl* partition = static_cast<StoragePartitionImpl*>( BrowserContext::GetDefaultStoragePartition(browser_context())); - EXPECT_TRUE(NavigateToURL( - shell(), embedded_test_server()->GetURL("foo.com", "/echo"))); + EXPECT_TRUE(NavigateToURL(shell(), embedded_test_server()->GetURL("/echo"))); EXPECT_TRUE(CheckCanLoadHttp("/title1.html")); EXPECT_EQ(last_request_relative_url(), "/title1.html");
diff --git a/content/browser/renderer_host/browser_compositor_view_mac.h b/content/browser/renderer_host/browser_compositor_view_mac.h index ad54fab..696bafa 100644 --- a/content/browser/renderer_host/browser_compositor_view_mac.h +++ b/content/browser/renderer_host/browser_compositor_view_mac.h
@@ -63,13 +63,20 @@ void OnDidNotProduceFrame(const viz::BeginFrameAck& ack); void SetBackgroundColor(SkColor background_color); void SetDisplayColorSpace(const gfx::ColorSpace& color_space); - void OnNSViewWasResized(); - bool HasFrameOfSize(const gfx::Size& desired_size); void UpdateVSyncParameters(const base::TimeTicks& timebase, const base::TimeDelta& interval); void SetNeedsBeginFrames(bool needs_begin_frames); void SetWantsAnimateOnlyBeginFrames(); + // Update the renderer's SurfaceId to reflect the current dimensions of the + // NSView. This will allocate a new SurfaceId if the dimensions have indeed + // changed. + void OnNSViewWasResized(); + + // Update the renderer's SurfaceId to reflect |size_dip| in anticipation of + // the NSView resizing during auto-resize. + void OnNSViewWillAutoResize(const gfx::Size& size_dip); + // This is used to ensure that the ui::Compositor be attached to the // DelegatedFrameHost while the RWHImpl is visible. // Note: This should be called before the RWHImpl is made visible and after @@ -119,6 +126,10 @@ void DidNavigate(); + void BeginPauseForFrame(bool auto_resize_enabled); + void EndPauseForFrame(); + bool ShouldContinueToPauseForFrame() const; + private: // The state of |delegated_frame_host_| and |recyclable_compositor_| to // manage being visible, hidden, or occluded. @@ -184,7 +195,9 @@ nullptr; // The surface for the delegated frame host, rendered into by the renderer - // process. Updated by OnNSViewWasResized. + // process. + void UpdateDelegatedFrameHostSurface(const gfx::Size& size_dip, + float scale_factor); viz::LocalSurfaceId delegated_frame_host_surface_id_; gfx::Size delegated_frame_host_size_pixels_; gfx::Size delegated_frame_host_size_dip_; @@ -197,6 +210,19 @@ gfx::Size compositor_size_pixels_; float compositor_scale_factor_ = 1.f; + // Used to disable screen updates while resizing (because frames are drawn in + // the GPU process, they can end up appearing on-screen before our window + // resizes). + enum class RepaintState { + // No repaint in progress. + None, + // Synchronously waiting for a new frame. + Paused, + // Screen updates are disabled while a new frame is swapped in. + ScreenUpdatesDisabled, + } repaint_state_ = RepaintState::None; + bool repaint_auto_resize_enabled_ = false; + viz::ParentLocalSurfaceIdAllocator parent_local_surface_id_allocator_; base::WeakPtrFactory<BrowserCompositorMac> weak_factory_;
diff --git a/content/browser/renderer_host/browser_compositor_view_mac.mm b/content/browser/renderer_host/browser_compositor_view_mac.mm index eac60704d..21c9b5f 100644 --- a/content/browser/renderer_host/browser_compositor_view_mac.mm +++ b/content/browser/renderer_host/browser_compositor_view_mac.mm
@@ -323,19 +323,27 @@ } void BrowserCompositorMac::OnNSViewWasResized() { - // Update the parameters we will send to the renderer via the - // DelgatedFrameHost. - gfx::Size dip_size; + gfx::Size size_dip; float scale_factor = 1.f; - GetViewProperties(&dip_size, &scale_factor, nullptr); - if (dip_size == delegated_frame_host_size_dip_ && + GetViewProperties(&size_dip, &scale_factor, nullptr); + UpdateDelegatedFrameHostSurface(size_dip, scale_factor); +} + +void BrowserCompositorMac::OnNSViewWillAutoResize(const gfx::Size& size_dip) { + UpdateDelegatedFrameHostSurface(size_dip, delegated_frame_host_scale_factor_); +} + +void BrowserCompositorMac::UpdateDelegatedFrameHostSurface( + const gfx::Size& size_dip, + float scale_factor) { + if (size_dip == delegated_frame_host_size_dip_ && scale_factor == delegated_frame_host_scale_factor_) { return; } delegated_frame_host_surface_id_ = parent_local_surface_id_allocator_.GenerateId(); - delegated_frame_host_size_dip_ = dip_size; + delegated_frame_host_size_dip_ = size_dip; delegated_frame_host_size_pixels_ = gfx::ConvertSizeToPixel( delegated_frame_host_scale_factor_, delegated_frame_host_size_dip_); delegated_frame_host_scale_factor_ = scale_factor; @@ -344,14 +352,6 @@ cc::DeadlinePolicy::UseExistingDeadline()); } -bool BrowserCompositorMac::HasFrameOfSize(const gfx::Size& desired_size) { - if (recyclable_compositor_) { - return recyclable_compositor_->accelerated_widget_mac()->HasFrameOfSize( - desired_size); - } - return false; -} - void BrowserCompositorMac::UpdateVSyncParameters( const base::TimeTicks& timebase, const base::TimeDelta& interval) { @@ -538,6 +538,18 @@ recyclable_compositor_->compositor()->SetScaleAndSize( compositor_scale_factor_, compositor_size_pixels_, compositor_surface_id_); + + // Disable screen updates until the frame of the new size appears (because the + // content is drawn in the GPU process, it may change before we want it to). + if (repaint_state_ == RepaintState::Paused) { + gfx::Size compositor_size_dip = gfx::ConvertSizeToDIP( + compositor_scale_factor_, compositor_size_pixels_); + if (compositor_size_dip == delegated_frame_host_size_pixels_ || + repaint_auto_resize_enabled_) { + NSDisableScreenUpdates(); + repaint_state_ = RepaintState::ScreenUpdatesDisabled; + } + } } void BrowserCompositorMac::OnBeginFrame(base::TimeTicks frame_time) { @@ -569,4 +581,23 @@ client_->DidReceiveFirstFrameAfterNavigation(); } +void BrowserCompositorMac::BeginPauseForFrame(bool auto_resize_enabled) { + repaint_auto_resize_enabled_ = auto_resize_enabled; + repaint_state_ = RepaintState::Paused; +} + +void BrowserCompositorMac::EndPauseForFrame() { + if (repaint_state_ == RepaintState::ScreenUpdatesDisabled) + NSEnableScreenUpdates(); + repaint_state_ = RepaintState::None; +} + +bool BrowserCompositorMac::ShouldContinueToPauseForFrame() const { + if (!recyclable_compositor_) + return false; + + return !recyclable_compositor_->accelerated_widget_mac()->HasFrameOfSize( + delegated_frame_host_size_dip_); +} + } // namespace content
diff --git a/content/browser/renderer_host/p2p/socket_host_udp.cc b/content/browser/renderer_host/p2p/socket_host_udp.cc index 319cd41..cc5e0d4 100644 --- a/content/browser/renderer_host/p2p/socket_host_udp.cc +++ b/content/browser/renderer_host/p2p/socket_host_udp.cc
@@ -6,10 +6,8 @@ #include "base/bind.h" #include "base/memory/ptr_util.h" -#include "base/metrics/field_trial.h" #include "base/metrics/histogram_macros.h" #include "base/stl_util.h" -#include "base/strings/string_number_conversions.h" #include "base/strings/stringprintf.h" #include "base/trace_event/trace_event.h" #include "build/build_config.h" @@ -29,6 +27,8 @@ const int kUdpReadBufferSize = 65536; // Socket receive buffer size. const int kUdpRecvSocketBufferSize = 65536; // 64K +// Socket send buffer size. +const int kUdpSendSocketBufferSize = 65536; // Defines set of transient errors. These errors are ignored when we get them // from sendto() or recvfrom() calls. @@ -106,7 +106,6 @@ send_pending_(false), last_dscp_(net::DSCP_CS0), throttler_(throttler), - send_buffer_size_(0), net_log_(net_log), socket_factory_(socket_factory) {} @@ -127,23 +126,6 @@ } } -void P2PSocketHostUdp::SetSendBufferSize() { - unsigned int send_buffer_size = 0; - - base::StringToUint( - base::FieldTrialList::FindFullName("WebRTC-SystemUDPSendSocketSize"), - &send_buffer_size); - - if (send_buffer_size > 0) { - if (!SetOption(P2P_SOCKET_OPT_SNDBUF, send_buffer_size)) { - LOG(WARNING) << "Failed to set socket send buffer size to " - << send_buffer_size; - } else { - send_buffer_size_ = send_buffer_size; - } - } -} - bool P2PSocketHostUdp::Init(const net::IPEndPoint& local_address, uint16_t min_port, uint16_t max_port, @@ -182,6 +164,12 @@ << kUdpRecvSocketBufferSize; } + // Setting socket send buffer size. + if (socket_->SetSendBufferSize(kUdpSendSocketBufferSize) != net::OK) { + LOG(WARNING) << "Failed to set socket send buffer size to " + << kUdpSendSocketBufferSize; + } + net::IPEndPoint address; result = socket_->GetLocalAddress(&address); if (result < 0) { @@ -194,8 +182,6 @@ state_ = STATE_OPEN; - SetSendBufferSize(); - // NOTE: Remote address will be same as what renderer provided. message_sender_->Send(new P2PMsg_OnSocketCreated( id_, address, remote_address.ip_address)); @@ -441,11 +427,6 @@ case P2P_SOCKET_OPT_RCVBUF: return socket_->SetReceiveBufferSize(value) == net::OK; case P2P_SOCKET_OPT_SNDBUF: - // Ignore any following call to set the send buffer size if we're under - // experiment. - if (send_buffer_size_ > 0) { - return true; - } return socket_->SetSendBufferSize(value) == net::OK; case P2P_SOCKET_OPT_DSCP: return (net::OK == socket_->SetDiffServCodePoint(
diff --git a/content/browser/renderer_host/p2p/socket_host_udp.h b/content/browser/renderer_host/p2p/socket_host_udp.h index 401dfa6..1ceef05 100644 --- a/content/browser/renderer_host/p2p/socket_host_udp.h +++ b/content/browser/renderer_host/p2p/socket_host_udp.h
@@ -89,8 +89,6 @@ void OnError(); - void SetSendBufferSize(); - void DoRead(); void OnRecv(int result); void HandleReadResult(int result); @@ -120,9 +118,6 @@ ConnectedPeerSet connected_peers_; P2PMessageThrottler* throttler_; - // Keep track of the send socket buffer size under experiment. - size_t send_buffer_size_; - net::NetLog* net_log_; // Callback object that returns a new socket when invoked.
diff --git a/content/browser/renderer_host/render_widget_host_impl.cc b/content/browser/renderer_host/render_widget_host_impl.cc index 05e8fa5..9fea212 100644 --- a/content/browser/renderer_host/render_widget_host_impl.cc +++ b/content/browser/renderer_host/render_widget_host_impl.cc
@@ -944,54 +944,26 @@ TRACE_EVENT0("browser", "RenderWidgetHostImpl::PauseForPendingResizeOrRepaints"); - if (!CanPauseForPendingResizeOrRepaints()) - return; - - WaitForSurface(); -} - -bool RenderWidgetHostImpl::CanPauseForPendingResizeOrRepaints() { // Do not pause if the view is hidden. if (is_hidden()) - return false; + return; // Do not pause if there is not a paint or resize already coming. if (!repaint_ack_pending_ && !resize_ack_pending_) - return false; + return; if (!renderer_compositor_frame_sink_.is_bound()) - return false; + return; - return true; -} + if (!view_) + return; -void RenderWidgetHostImpl::WaitForSurface() { // How long to (synchronously) wait for the renderer to respond with a // new frame when our current frame doesn't exist or is the wrong size. // This timeout impacts the "choppiness" of our window resize. const int kPaintMsgTimeoutMS = 167; - if (!view_) - return; - - // The view_size will be current_size_ for auto-sized views and otherwise the - // size of the view_. (For auto-sized views, current_size_ is updated during - // ResizeACK messages.) - gfx::Size view_size = current_size_; - if (!auto_resize_enabled_) { - // Get the desired size from the current view bounds. - gfx::Rect view_rect = view_->GetViewBounds(); - if (view_rect.IsEmpty()) - return; - view_size = view_rect.size(); - } - - TRACE_EVENT2("renderer_host", - "RenderWidgetHostImpl::WaitForSurface", - "width", - base::IntToString(view_size.width()), - "height", - base::IntToString(view_size.height())); + TRACE_EVENT0("renderer_host", "RenderWidgetHostImpl::WaitForSurface"); // We should not be asked to paint while we are hidden. If we are hidden, // then it means that our consumer failed to call WasShown. @@ -1004,19 +976,9 @@ &in_get_backing_store_, true); // We might have a surface that we can use already. - if (view_->HasAcceleratedSurface(view_size)) + if (!view_->ShouldContinueToPauseForFrame()) return; - // Request that the renderer produce a frame of the right size, if it - // hasn't been requested already. - if (!repaint_ack_pending_ && !resize_ack_pending_) { - repaint_start_time_ = TimeTicks::Now(); - repaint_ack_pending_ = true; - TRACE_EVENT_ASYNC_BEGIN0( - "renderer_host", "RenderWidgetHostImpl::repaint_ack_pending_", this); - Send(new ViewMsg_Repaint(routing_id_, view_size)); - } - // Pump a nested run loop until we time out or get a frame of the right // size. TimeTicks start_time = TimeTicks::Now(); @@ -1025,11 +987,7 @@ while (1) { TRACE_EVENT0("renderer_host", "WaitForSurface::WaitForSingleTaskToRun"); if (ui::WindowResizeHelperMac::Get()->WaitForSingleTaskToRun(time_left)) { - // For auto-resized views, current_size_ determines the view_size and it - // may have changed during the handling of an ResizeACK message. - if (auto_resize_enabled_) - view_size = current_size_; - if (view_->HasAcceleratedSurface(view_size)) + if (!view_->ShouldContinueToPauseForFrame()) break; } time_left = timeout_time - TimeTicks::Now();
diff --git a/content/browser/renderer_host/render_widget_host_impl.h b/content/browser/renderer_host/render_widget_host_impl.h index 4140b75..a0f11ee 100644 --- a/content/browser/renderer_host/render_widget_host_impl.h +++ b/content/browser/renderer_host/render_widget_host_impl.h
@@ -337,13 +337,6 @@ // the renderer to arrive. If pending resize messages are for an old window // size, then also pump through a new resize message if there is time. void PauseForPendingResizeOrRepaints(); - - // Whether pausing may be useful. - bool CanPauseForPendingResizeOrRepaints(); - - // Wait for a surface matching the size of the widget's view, possibly - // blocking until the renderer sends a new frame. - void WaitForSurface(); #endif bool resize_ack_pending_for_testing() { return resize_ack_pending_; }
diff --git a/content/browser/renderer_host/render_widget_host_view_android.cc b/content/browser/renderer_host/render_widget_host_view_android.cc index e2a0aab6..be5dbf99 100644 --- a/content/browser/renderer_host/render_widget_host_view_android.cc +++ b/content/browser/renderer_host/render_widget_host_view_android.cc
@@ -1461,12 +1461,23 @@ gesture_provider_.SetDoubleTapSupportForPageEnabled(!is_mobile_optimized); float dip_scale = view_.GetDipScale(); + gfx::SizeF root_layer_size_dip = frame_metadata.root_layer_size; + gfx::SizeF scrollable_viewport_size_dip = + frame_metadata.scrollable_viewport_size; + gfx::Vector2dF root_scroll_offset_dip = frame_metadata.root_scroll_offset; + if (IsUseZoomForDSFEnabled()) { + float pix_to_dip = 1 / dip_scale; + root_layer_size_dip.Scale(pix_to_dip); + scrollable_viewport_size_dip.Scale(pix_to_dip); + root_scroll_offset_dip.Scale(pix_to_dip); + } + float to_pix = IsUseZoomForDSFEnabled() ? 1.f : dip_scale; float top_controls_pix = frame_metadata.top_controls_height * to_pix; - // |top_content_offset| is its CSS pixels * DSF if --use-zoom-for-dsf is - // enabled. Otherwise, it is in CSS pixels. + // |top_content_offset| is in physical pixels if --use-zoom-for-dsf is + // enabled. Otherwise, it is in DIPs. // Note that the height of browser control is not affected by page scale - // factor. Thus, |top_content_offset| in CSS pixels is also in DIP pixels. + // factor. Thus, |top_content_offset| in CSS pixels is also in DIPs. float top_content_offset = frame_metadata.top_controls_height * frame_metadata.top_controls_shown_ratio; float top_shown_pix = top_content_offset * to_pix; @@ -1494,7 +1505,7 @@ frame_metadata.page_scale_factor); // Set parameters for adaptive handle orientation. - gfx::SizeF viewport_size(frame_metadata.scrollable_viewport_size); + gfx::SizeF viewport_size(scrollable_viewport_size_dip); viewport_size.Scale(frame_metadata.page_scale_factor); gfx::RectF viewport_rect(0.0f, frame_metadata.top_controls_height * frame_metadata.top_controls_shown_ratio, @@ -1506,11 +1517,10 @@ : frame_metadata.root_background_color); // ViewAndroid::content_offset() must be in CSS scale - float top_content_offset_css = IsUseZoomForDSFEnabled() + float top_content_offset_dip = IsUseZoomForDSFEnabled() ? top_content_offset / dip_scale : top_content_offset; - view_.UpdateFrameInfo( - {frame_metadata.scrollable_viewport_size, top_content_offset}); + view_.UpdateFrameInfo({scrollable_viewport_size_dip, top_content_offset}); bool top_changed = !FloatEquals(top_shown_pix, prev_top_shown_pix_); if (top_changed) { @@ -1535,11 +1545,11 @@ // All offsets and sizes except |top_shown_pix| are in CSS pixels. content_view_core_->UpdateFrameInfo( - frame_metadata.root_scroll_offset, frame_metadata.page_scale_factor, + root_scroll_offset_dip, frame_metadata.page_scale_factor, frame_metadata.min_page_scale_factor, - frame_metadata.max_page_scale_factor, frame_metadata.root_layer_size, - frame_metadata.scrollable_viewport_size, top_content_offset_css, - top_shown_pix, top_changed, is_mobile_optimized); + frame_metadata.max_page_scale_factor, root_layer_size_dip, + scrollable_viewport_size_dip, top_content_offset_dip, top_shown_pix, + top_changed, is_mobile_optimized); EvictFrameIfNecessary(); } @@ -1723,12 +1733,6 @@ DestroyDelegatedContent(); } -bool RenderWidgetHostViewAndroid::HasAcceleratedSurface( - const gfx::Size& desired_size) { - NOTREACHED(); - return false; -} - // TODO(jrg): Find out the implications and answer correctly here, // as we are returning the WebView and not root window bounds. gfx::Rect RenderWidgetHostViewAndroid::GetBoundsInRootWindow() {
diff --git a/content/browser/renderer_host/render_widget_host_view_android.h b/content/browser/renderer_host/render_widget_host_view_android.h index bcee907..ce2afa5 100644 --- a/content/browser/renderer_host/render_widget_host_view_android.h +++ b/content/browser/renderer_host/render_widget_host_view_android.h
@@ -135,7 +135,6 @@ int error_code) override; void Destroy() override; void SetTooltipText(const base::string16& tooltip_text) override; - bool HasAcceleratedSurface(const gfx::Size& desired_size) override; void SetBackgroundColor(SkColor color) override; SkColor background_color() const override; gfx::Rect GetBoundsInRootWindow() override;
diff --git a/content/browser/renderer_host/render_widget_host_view_aura.cc b/content/browser/renderer_host/render_widget_host_view_aura.cc index c04004e..0ecea5f1 100644 --- a/content/browser/renderer_host/render_widget_host_view_aura.cc +++ b/content/browser/renderer_host/render_widget_host_view_aura.cc
@@ -993,14 +993,6 @@ selection_controller_client_->OnScrollCompleted(); } -bool RenderWidgetHostViewAura::HasAcceleratedSurface( - const gfx::Size& desired_size) { - // Aura doesn't use GetBackingStore for accelerated pages, so it doesn't - // matter what is returned here as GetBackingStore is the only caller of this - // method. TODO(jbates) implement this if other Aura code needs it. - return false; -} - gfx::Rect RenderWidgetHostViewAura::GetBoundsInRootWindow() { aura::Window* top_level = window_->GetToplevelWindow(); gfx::Rect bounds(top_level->GetBoundsInScreen());
diff --git a/content/browser/renderer_host/render_widget_host_view_aura.h b/content/browser/renderer_host/render_widget_host_view_aura.h index 0e9fd5bf..040f075a 100644 --- a/content/browser/renderer_host/render_widget_host_view_aura.h +++ b/content/browser/renderer_host/render_widget_host_view_aura.h
@@ -153,7 +153,6 @@ void BeginFrameSubscription( std::unique_ptr<RenderWidgetHostViewFrameSubscriber> subscriber) override; void EndFrameSubscription() override; - bool HasAcceleratedSurface(const gfx::Size& desired_size) override; gfx::Rect GetBoundsInRootWindow() override; void WheelEventAck(const blink::WebMouseWheelEvent& event, InputEventAckState ack_result) override;
diff --git a/content/browser/renderer_host/render_widget_host_view_base.cc b/content/browser/renderer_host/render_widget_host_view_base.cc index 6dc8047..48c0eb72 100644 --- a/content/browser/renderer_host/render_widget_host_view_base.cc +++ b/content/browser/renderer_host/render_widget_host_view_base.cc
@@ -651,4 +651,10 @@ #endif +#if defined(OS_MACOSX) +bool RenderWidgetHostViewBase::ShouldContinueToPauseForFrame() { + return false; +} +#endif + } // namespace content
diff --git a/content/browser/renderer_host/render_widget_host_view_base.h b/content/browser/renderer_host/render_widget_host_view_base.h index 1301db1..49b6c7c 100644 --- a/content/browser/renderer_host/render_widget_host_view_base.h +++ b/content/browser/renderer_host/render_widget_host_view_base.h
@@ -435,11 +435,6 @@ // the page has changed. virtual void SetTooltipText(const base::string16& tooltip_text) = 0; - // Return true if the view has an accelerated surface that contains the last - // presented frame for the view. If |desired_size| is non-empty, true is - // returned only if the accelerated surface size matches. - virtual bool HasAcceleratedSurface(const gfx::Size& desired_size) = 0; - // Compute the orientation type of the display assuming it is a mobile device. static ScreenOrientationValues GetOrientationTypeForMobile( const display::Display& display); @@ -507,6 +502,12 @@ void OnChildFrameDestroyed(int routing_id); #endif +#if defined(OS_MACOSX) + // Use only for resize on macOS. Returns true if there is not currently a + // frame of the view's size being displayed. + virtual bool ShouldContinueToPauseForFrame(); +#endif + virtual void DidNavigate() {} protected:
diff --git a/content/browser/renderer_host/render_widget_host_view_child_frame.cc b/content/browser/renderer_host/render_widget_host_view_child_frame.cc index e71eb01..3f736fa 100644 --- a/content/browser/renderer_host/render_widget_host_view_child_frame.cc +++ b/content/browser/renderer_host/render_widget_host_view_child_frame.cc
@@ -887,11 +887,6 @@ support_->RequestCopyOfSurface(std::move(request)); } -bool RenderWidgetHostViewChildFrame::HasAcceleratedSurface( - const gfx::Size& desired_size) { - return false; -} - void RenderWidgetHostViewChildFrame::ReclaimResources( const std::vector<viz::ReturnedResource>& resources) { if (renderer_compositor_frame_sink_)
diff --git a/content/browser/renderer_host/render_widget_host_view_child_frame.h b/content/browser/renderer_host/render_widget_host_view_child_frame.h index c280259..ae1b582 100644 --- a/content/browser/renderer_host/render_widget_host_view_child_frame.h +++ b/content/browser/renderer_host/render_widget_host_view_child_frame.h
@@ -122,7 +122,6 @@ int error_code) override; void Destroy() override; void SetTooltipText(const base::string16& tooltip_text) override; - bool HasAcceleratedSurface(const gfx::Size& desired_size) override; void GestureEventAck(const blink::WebGestureEvent& event, InputEventAckState ack_result) override; void DidCreateNewRendererCompositorFrameSink(
diff --git a/content/browser/renderer_host/render_widget_host_view_mac.h b/content/browser/renderer_host/render_widget_host_view_mac.h index 6b5658c..2718f520 100644 --- a/content/browser/renderer_host/render_widget_host_view_mac.h +++ b/content/browser/renderer_host/render_widget_host_view_mac.h
@@ -340,9 +340,11 @@ gfx::Point AccessibilityOriginInScreen(const gfx::Rect& bounds) override; gfx::AcceleratedWidget AccessibilityGetAcceleratedWidget() override; - bool HasAcceleratedSurface(const gfx::Size& desired_size) override; + bool ShouldContinueToPauseForFrame() override; gfx::Rect GetBoundsInRootWindow() override; void OnSynchronizedDisplayPropertiesChanged() override; + void ResizeDueToAutoResize(const gfx::Size& new_size, + uint64_t sequence_number) override; void DidNavigate() override; bool LockMouse() override; @@ -618,17 +620,6 @@ std::unique_ptr<CursorManager> cursor_manager_; - enum class RepaintState { - // No repaint in progress. - None, - - // Synchronously waiting for a new frame. - Paused, - - // Screen updates are disabled while a new frame is swapped in. - ScreenUpdatesDisabled, - } repaint_state_ = RepaintState::None; - // Factory used to safely scope delayed calls to ShutdownHost(). base::WeakPtrFactory<RenderWidgetHostViewMac> weak_factory_;
diff --git a/content/browser/renderer_host/render_widget_host_view_mac.mm b/content/browser/renderer_host/render_widget_host_view_mac.mm index 053e9a9..7588bd4 100644 --- a/content/browser/renderer_host/render_widget_host_view_mac.mm +++ b/content/browser/renderer_host/render_widget_host_view_mac.mm
@@ -1092,6 +1092,12 @@ browser_compositor_->OnNSViewWasResized(); } +void RenderWidgetHostViewMac::ResizeDueToAutoResize(const gfx::Size& new_size, + uint64_t sequence_number) { + browser_compositor_->OnNSViewWillAutoResize(new_size); + RenderWidgetHostViewBase::ResizeDueToAutoResize(new_size, sequence_number); +} + void RenderWidgetHostViewMac::DidNavigate() { browser_compositor_->DidNavigate(); } @@ -1161,8 +1167,8 @@ clickCount:0 pressure:0]; WebMouseEvent web_event = WebMouseEventBuilder::Build(event, cocoa_view_); - if (showing) - web_event.SetType(WebInputEvent::kMouseLeave); + web_event.SetModifiers(web_event.GetModifiers() | + WebInputEvent::kRelativeMotionEvent); ForwardMouseEvent(web_event); } @@ -1398,9 +1404,8 @@ return true; } -bool RenderWidgetHostViewMac::HasAcceleratedSurface( - const gfx::Size& desired_size) { - return browser_compositor_->HasFrameOfSize(desired_size); +bool RenderWidgetHostViewMac::ShouldContinueToPauseForFrame() { + return browser_compositor_->ShouldContinueToPauseForFrame(); } void RenderWidgetHostViewMac::FocusedNodeChanged( @@ -1430,16 +1435,6 @@ viz::mojom::HitTestRegionListPtr hit_test_region_list) { TRACE_EVENT0("browser", "RenderWidgetHostViewMac::OnSwapCompositorFrame"); - if (repaint_state_ == RepaintState::Paused) { - gfx::Size frame_size = gfx::ConvertSizeToDIP( - frame.metadata.device_scale_factor, frame.size_in_pixels()); - gfx::Size view_size = gfx::Size(cocoa_view_.bounds.size); - if (frame_size == view_size || render_widget_host_->auto_resize_enabled()) { - NSDisableScreenUpdates(); - repaint_state_ = RepaintState::ScreenUpdatesDisabled; - } - } - last_frame_root_background_color_ = frame.metadata.root_background_color; last_scroll_offset_ = frame.metadata.root_scroll_offset; @@ -1731,11 +1726,10 @@ return; // Wait for a frame of the right size to come in. - repaint_state_ = RepaintState::Paused; + browser_compositor_->BeginPauseForFrame( + render_widget_host_->auto_resize_enabled()); render_widget_host_->PauseForPendingResizeOrRepaints(); - if (repaint_state_ == RepaintState::ScreenUpdatesDisabled) - NSEnableScreenUpdates(); - repaint_state_ = RepaintState::None; + browser_compositor_->EndPauseForFrame(); } //////////////////////////////////////////////////////////////////////////////// @@ -2850,6 +2844,11 @@ if (!renderWidgetHostView_->render_widget_host_) return; + // During auto-resize it is the responsibility of the caller to ensure that + // the NSView and RenderWidgetHostImpl are kept in sync. + if (renderWidgetHostView_->render_widget_host_->auto_resize_enabled()) + return; + if (renderWidgetHostView_->render_widget_host_->delegate()) renderWidgetHostView_->render_widget_host_->delegate()->SendScreenRects(); else
diff --git a/content/browser/renderer_host/render_widget_host_view_mac_unittest.mm b/content/browser/renderer_host/render_widget_host_view_mac_unittest.mm index 6f52479..a9ed2c8 100644 --- a/content/browser/renderer_host/render_widget_host_view_mac_unittest.mm +++ b/content/browser/renderer_host/render_widget_host_view_mac_unittest.mm
@@ -1111,6 +1111,21 @@ GetPointerType(events)); } +TEST_F(RenderWidgetHostViewMacTest, SendMouseMoveOnShowingContextMenu) { + rwhv_mac_->SetShowingContextMenu(true); + base::RunLoop().RunUntilIdle(); + MockWidgetInputHandler::MessageVector events = + host_->GetAndResetDispatchedMessages(); + ASSERT_EQ("MouseMove", GetMessageNames(events)); + + events.clear(); + + rwhv_mac_->SetShowingContextMenu(false); + base::RunLoop().RunUntilIdle(); + events = host_->GetAndResetDispatchedMessages(); + ASSERT_EQ("MouseMove", GetMessageNames(events)); +} + void RenderWidgetHostViewMacTest:: IgnoreEmptyUnhandledWheelEventWithWheelGestures() { // Add a delegate to the view.
diff --git a/content/browser/service_worker/service_worker_controllee_request_handler.cc b/content/browser/service_worker/service_worker_controllee_request_handler.cc index 9840c9d3..959e2673 100644 --- a/content/browser/service_worker/service_worker_controllee_request_handler.cc +++ b/content/browser/service_worker/service_worker_controllee_request_handler.cc
@@ -205,7 +205,7 @@ if (!context_ || !provider_host_) { // We can't do anything other than to fall back to network. - std::move(callback).Run(StartLoaderCallback()); + std::move(callback).Run({}); return; } @@ -217,7 +217,7 @@ // Fall back for the subsequent offline page interceptor to load the offline // snapshot of the page if required. if (ShouldFallbackToLoadOfflinePage(resource_request.headers)) { - std::move(callback).Run(StartLoaderCallback()); + std::move(callback).Run({}); return; } #endif // BUILDFLAG(ENABLE_OFFLINE_PAGES) @@ -400,8 +400,7 @@ DCHECK_NE(active_version->fetch_handler_existence(), ServiceWorkerVersion::FetchHandlerExistence::UNKNOWN); ServiceWorkerMetrics::CountControlledPageLoad( - active_version->site_for_uma(), stripped_url_, is_main_frame_load_, - url_job_->GetPageTransition(), url_job_->GetURLChainSize()); + active_version->site_for_uma(), stripped_url_, is_main_frame_load_); bool is_forwarded = MaybeForwardToServiceWorker(url_job_.get(), active_version.get()); @@ -433,8 +432,7 @@ DCHECK_NE(version->fetch_handler_existence(), ServiceWorkerVersion::FetchHandlerExistence::UNKNOWN); ServiceWorkerMetrics::CountControlledPageLoad( - version->site_for_uma(), stripped_url_, is_main_frame_load_, - url_job_->GetPageTransition(), url_job_->GetURLChainSize()); + version->site_for_uma(), stripped_url_, is_main_frame_load_); provider_host_->AssociateRegistration(registration, false /* notify_controllerchange */);
diff --git a/content/browser/service_worker/service_worker_metrics.cc b/content/browser/service_worker/service_worker_metrics.cc index 40562df..8113762 100644 --- a/content/browser/service_worker/service_worker_metrics.cc +++ b/content/browser/service_worker/service_worker_metrics.cc
@@ -453,12 +453,9 @@ result, NUM_DELETE_AND_START_OVER_RESULT_TYPES); } -void ServiceWorkerMetrics::CountControlledPageLoad( - Site site, - const GURL& url, - bool is_main_frame_load, - ui::PageTransition page_transition, - size_t redirect_chain_length) { +void ServiceWorkerMetrics::CountControlledPageLoad(Site site, + const GURL& url, + bool is_main_frame_load) { DCHECK_NE(site, Site::OTHER); UMA_HISTOGRAM_ENUMERATION("ServiceWorker.PageLoad", static_cast<int>(site), static_cast<int>(Site::NUM_TYPES)); @@ -470,19 +467,6 @@ if (ShouldExcludeSiteFromHistogram(site)) return; - if (is_main_frame_load) { - UMA_HISTOGRAM_ENUMERATION( - "ServiceWorker.MainFramePageLoad.CoreTransition", - static_cast<int>(ui::PageTransitionStripQualifier(page_transition)), - static_cast<int>(ui::PAGE_TRANSITION_LAST_CORE) + 1); - // Currently the max number of HTTP redirects is 20 as defined in - // net::URLRequest::kMaxRedirects in - // net/url_request/url_request.h. So the max number of the chain - // length is 21. - UMA_HISTOGRAM_EXACT_LINEAR( - "ServiceWorker.MainFramePageLoad.RedirectChainLength", - redirect_chain_length, net::URLRequest::kMaxRedirects + 1); - } BrowserThread::PostTask( BrowserThread::UI, FROM_HERE, base::BindOnce(&RecordURLMetricOnUI, "ServiceWorker.ControlledPageUrl",
diff --git a/content/browser/service_worker/service_worker_metrics.h b/content/browser/service_worker/service_worker_metrics.h index 80d21e78..59f8fac 100644 --- a/content/browser/service_worker/service_worker_metrics.h +++ b/content/browser/service_worker/service_worker_metrics.h
@@ -262,9 +262,7 @@ // Counts the number of page loads controlled by a Service Worker. static void CountControlledPageLoad(Site site, const GURL& url, - bool is_main_frame_load, - ui::PageTransition page_transition, - size_t redirect_chain_length); + bool is_main_frame_load); // Records the result of trying to start a worker. |is_installed| indicates // whether the version has been installed.
diff --git a/content/browser/service_worker/service_worker_provider_host.cc b/content/browser/service_worker/service_worker_provider_host.cc index 47787e55..b54f0af 100644 --- a/content/browser/service_worker/service_worker_provider_host.cc +++ b/content/browser/service_worker/service_worker_provider_host.cc
@@ -99,7 +99,7 @@ provider_host_->SetDocumentUrl(stripped_url); provider_host_->SetTopmostFrameUrl(resource_request.site_for_cookies); // Fall back to network. - std::move(callback).Run(StartLoaderCallback()); + std::move(callback).Run({}); } private:
diff --git a/content/browser/service_worker/service_worker_request_handler.cc b/content/browser/service_worker/service_worker_request_handler.cc index 3ec4a3d..2003ecb 100644 --- a/content/browser/service_worker/service_worker_request_handler.cc +++ b/content/browser/service_worker/service_worker_request_handler.cc
@@ -265,7 +265,7 @@ ResourceContext* resource_context, LoaderCallback callback) { NOTREACHED(); - std::move(callback).Run(StartLoaderCallback()); + std::move(callback).Run({}); } void ServiceWorkerRequestHandler::PrepareForCrossSiteTransfer(
diff --git a/content/browser/service_worker/service_worker_url_job_wrapper.cc b/content/browser/service_worker/service_worker_url_job_wrapper.cc index c44a45f58..1f1d36e 100644 --- a/content/browser/service_worker/service_worker_url_job_wrapper.cc +++ b/content/browser/service_worker/service_worker_url_job_wrapper.cc
@@ -61,27 +61,6 @@ } } -ui::PageTransition ServiceWorkerURLJobWrapper::GetPageTransition() { - if (url_loader_job_) { - return url_loader_job_->GetPageTransition(); - } else { - const ResourceRequestInfo* info = - ResourceRequestInfo::ForRequest(url_request_job_->request()); - // ResourceRequestInfo may not be set in some tests. - if (!info) - return ui::PAGE_TRANSITION_LINK; - return info->GetPageTransition(); - } -} - -size_t ServiceWorkerURLJobWrapper::GetURLChainSize() const { - if (url_loader_job_) { - return url_loader_job_->GetURLChainSize(); - } else { - return url_request_job_->request()->url_chain().size(); - } -} - void ServiceWorkerURLJobWrapper::FailDueToLostController() { if (url_loader_job_) { url_loader_job_->FailDueToLostController();
diff --git a/content/browser/service_worker/service_worker_url_job_wrapper.h b/content/browser/service_worker/service_worker_url_job_wrapper.h index 316936e..dba6341d 100644 --- a/content/browser/service_worker/service_worker_url_job_wrapper.h +++ b/content/browser/service_worker/service_worker_url_job_wrapper.h
@@ -76,14 +76,6 @@ // if needed later. void FailDueToLostController(); - // Determines from the ResourceRequestInfo (or similar) the type of page - // transition used (for metrics purposes). - ui::PageTransition GetPageTransition(); - - // Determines the number of redirects used to handle the job (for metrics - // purposes). - size_t GetURLChainSize() const; - // Returns true if the underlying job has been canceled or destroyed. bool WasCanceled() const;
diff --git a/content/browser/service_worker/service_worker_url_loader_job.cc b/content/browser/service_worker/service_worker_url_loader_job.cc index 0290056..b9a45d7d 100644 --- a/content/browser/service_worker/service_worker_url_loader_job.cc +++ b/content/browser/service_worker/service_worker_url_loader_job.cc
@@ -71,7 +71,7 @@ }; ServiceWorkerURLLoaderJob::ServiceWorkerURLLoaderJob( - LoaderCallback callback, + URLLoaderRequestHandler::LoaderCallback callback, Delegate* delegate, const network::ResourceRequest& resource_request, scoped_refptr<URLLoaderFactoryGetter> url_loader_factory_getter) @@ -101,8 +101,8 @@ // call this synchronously here and don't wait for a separate async // StartRequest cue like what URLRequestJob case does. // TODO(kinuko): Make sure this is ok or we need to make this async. - if (!loader_callback_.is_null()) - std::move(loader_callback_).Run(StartLoaderCallback()); + if (loader_callback_) + std::move(loader_callback_).Run({}); } void ServiceWorkerURLLoaderJob::FallbackToNetworkOrRenderer() { @@ -119,16 +119,6 @@ return response_type_ == ResponseType::FALLBACK_TO_NETWORK; } -ui::PageTransition ServiceWorkerURLLoaderJob::GetPageTransition() { - NOTIMPLEMENTED(); - return ui::PAGE_TRANSITION_LINK; -} - -size_t ServiceWorkerURLLoaderJob::GetURLChainSize() const { - NOTIMPLEMENTED(); - return 0; -} - void ServiceWorkerURLLoaderJob::FailDueToLostController() { NOTIMPLEMENTED(); }
diff --git a/content/browser/service_worker/service_worker_url_loader_job.h b/content/browser/service_worker/service_worker_url_loader_job.h index bc839ec8..ee07ac7 100644 --- a/content/browser/service_worker/service_worker_url_loader_job.h +++ b/content/browser/service_worker/service_worker_url_loader_job.h
@@ -49,25 +49,24 @@ // URLJobWrapper by ServiceWorkerControlleeRequestHandler, which // determines how the request should be served (e.g. should fallback // to network or should be sent to the SW). If it decides to fallback - // to the network this will call |loader_callback| with null - // StartLoaderCallback (which will be then handled by - // NavigationURLLoaderNetworkService). + // to the network this will call |loader_callback| with a null + // RequestHandler, which will be then handled by + // NavigationURLLoaderNetworkService. // 2. If it is decided that the request should be sent to the SW, // this job dispatches a FetchEvent in StartRequest. // 3. In DidDispatchFetchEvent() this job determines the request's // final destination, and may still call |loader_callback| with null - // StartLoaderCallback if it turns out that we need to fallback to - // the network. + // RequestHandler if it turns out that we need to fallback to the network. // 4. Otherwise if the SW returned a stream or blob as a response - // this job calls |loader_callback| with a bound method for + // this job calls |loader_callback| with a RequestHandler bound from // StartResponse(). - // 5. Then StartResponse() will be called with - // network::mojom::URLLoaderClientPtr - // that is connected to NavigationURLLoaderNetworkService (for resource - // loading for navigation). This forwards the blob/stream data pipe to the - // NavigationURLLoader if the response body was sent as a blob/stream. + // 5. Then StartResponse() will be called with a + // network::mojom::URLLoaderClientPtr that is connected to + // NavigationURLLoaderNetworkService (for resource loading for navigation). + // This forwards the blob/stream data pipe to the NavigationURLLoader if + // the response body was sent as a blob/stream. ServiceWorkerURLLoaderJob( - LoaderCallback loader_callback, + URLLoaderRequestHandler::LoaderCallback loader_callback, Delegate* delegate, const network::ResourceRequest& resource_request, scoped_refptr<URLLoaderFactoryGetter> url_loader_factory_getter); @@ -80,8 +79,6 @@ void ForwardToServiceWorker(); bool ShouldFallbackToNetwork(); void FailDueToLostController(); - ui::PageTransition GetPageTransition(); - size_t GetURLChainSize() const; void Cancel(); bool WasCanceled() const; @@ -106,10 +103,10 @@ blink::mojom::BlobPtr body_as_blob, scoped_refptr<ServiceWorkerVersion> version); - // Used as the StartLoaderCallback passed to |loader_callback_| when the - // service worker provided a response. Returns the response to |client|. - // |body_as_blob| is kept around until BlobDataHandle is created from - // blob_uuid just to make sure the blob is kept alive. + // Used as the RequestHandler passed to |loader_callback_| when the service + // worker chooses to handle a resource request. Returns the response to + // |client|. |body_as_blob| is kept around until BlobDataHandle is created + // from blob_uuid just to make sure the blob is kept alive. void StartResponse(const ServiceWorkerResponse& response, scoped_refptr<ServiceWorkerVersion> version, blink::mojom::ServiceWorkerStreamHandlePtr body_as_stream, @@ -117,8 +114,8 @@ network::mojom::URLLoaderRequest request, network::mojom::URLLoaderClientPtr client); - // Used as the StartLoaderCallback passed to |loader_callback_| on error. - // Returns a network error to |client|. + // Used as the RequestHandler passed to |loader_callback_| on error. Returns a + // network error to |client|. void StartErrorResponse(network::mojom::URLLoaderRequest request, network::mojom::URLLoaderClientPtr client); @@ -145,7 +142,7 @@ void DeleteIfNeeded(); ResponseType response_type_ = ResponseType::NOT_DETERMINED; - LoaderCallback loader_callback_; + URLLoaderRequestHandler::LoaderCallback loader_callback_; Delegate* delegate_; network::ResourceRequest resource_request_;
diff --git a/content/browser/service_worker/service_worker_url_loader_job_unittest.cc b/content/browser/service_worker/service_worker_url_loader_job_unittest.cc index 0fd80caa..f9ac963 100644 --- a/content/browser/service_worker/service_worker_url_loader_job_unittest.cc +++ b/content/browser/service_worker/service_worker_url_loader_job_unittest.cc
@@ -14,6 +14,7 @@ #include "content/browser/service_worker/service_worker_version.h" #include "content/common/service_worker/service_worker_event_dispatcher.mojom.h" #include "content/common/service_worker/service_worker_utils.h" +#include "content/common/single_request_url_loader_factory.h" #include "content/public/test/test_browser_thread_bundle.h" #include "mojo/common/data_pipe_utils.h" #include "mojo/public/cpp/bindings/strong_binding.h" @@ -36,9 +37,10 @@ namespace content { namespace service_worker_url_loader_job_unittest { -void ReceiveStartLoaderCallback(StartLoaderCallback* out_callback, - StartLoaderCallback callback) { - *out_callback = std::move(callback); +void ReceiveRequestHandler( + SingleRequestURLLoaderFactory::RequestHandler* out_handler, + SingleRequestURLLoaderFactory::RequestHandler handler) { + *out_handler = std::move(handler); } // NavigationPreloadLoaderClient mocks the renderer-side URLLoaderClient for the @@ -60,8 +62,8 @@ // 5. NavigationPreloadLoaderClient calls OnFetchEvent()'s callbacks // with the response. // 6. Like all FetchEvent responses, the response is sent to -// ServiceWorkerURLLoaderJob::DidDispatchFetchEvent, and the -// StartLoaderCallback is returned. +// ServiceWorkerURLLoaderJob::DidDispatchFetchEvent, and the RequestHandler +// is returned. class NavigationPreloadLoaderClient final : public network::mojom::URLLoaderClient { public: @@ -525,7 +527,7 @@ ServiceWorkerStorage* storage() { return helper_->context()->storage(); } // Indicates whether ServiceWorkerURLLoaderJob decided to handle a request, - // i.e., it returned a non-null StartLoaderCallback for the request. + // i.e., it returned a non-null RequestHandler for the request. enum class JobResult { kHandledRequest, kDidNotHandleRequest, @@ -536,20 +538,20 @@ // functions like client_.RunUntilComplete() to wait for completion. JobResult StartRequest(std::unique_ptr<network::ResourceRequest> request) { // Start a ServiceWorkerURLLoaderJob. It should return a - // StartLoaderCallback. - StartLoaderCallback callback; + // RequestHandler. + SingleRequestURLLoaderFactory::RequestHandler handler; job_ = std::make_unique<ServiceWorkerURLLoaderJob>( - base::BindOnce(&ReceiveStartLoaderCallback, &callback), this, *request, + base::BindOnce(&ReceiveRequestHandler, &handler), this, *request, base::WrapRefCounted<URLLoaderFactoryGetter>( helper_->context()->loader_factory_getter())); job_->ForwardToServiceWorker(); base::RunLoop().RunUntilIdle(); - if (!callback) + if (!handler) return JobResult::kDidNotHandleRequest; - // Start the loader. It will load |request.url|. - std::move(callback).Run(mojo::MakeRequest(&loader_), - client_.CreateInterfacePtr()); + // Run the handler. It will load |request.url|. + std::move(handler).Run(mojo::MakeRequest(&loader_), + client_.CreateInterfacePtr()); return JobResult::kHandledRequest; } @@ -913,16 +915,16 @@ network::mojom::FetchCredentialsMode::kInclude; request.fetch_redirect_mode = network::mojom::FetchRedirectMode::kManual; - StartLoaderCallback callback; + SingleRequestURLLoaderFactory::RequestHandler handler; auto job = std::make_unique<ServiceWorkerURLLoaderJob>( - base::BindOnce(&ReceiveStartLoaderCallback, &callback), this, request, + base::BindOnce(&ReceiveRequestHandler, &handler), this, request, base::WrapRefCounted<URLLoaderFactoryGetter>( helper_->context()->loader_factory_getter())); // Ask the job to fallback to network. In production code, // ServiceWorkerControlleeRequestHandler calls FallbackToNetwork() to do this. job->FallbackToNetwork(); base::RunLoop().RunUntilIdle(); - EXPECT_FALSE(callback); + EXPECT_FALSE(handler); } // Test responding to the fetch event with the navigation preload response.
diff --git a/content/browser/site_per_process_browsertest.cc b/content/browser/site_per_process_browsertest.cc index 916d67c..ad61932 100644 --- a/content/browser/site_per_process_browsertest.cc +++ b/content/browser/site_per_process_browsertest.cc
@@ -31,6 +31,7 @@ #include "base/strings/string_split.h" #include "base/strings/stringprintf.h" #include "base/strings/utf_string_conversions.h" +#include "base/test/bind_test_util.h" #include "base/test/test_timeouts.h" #include "base/threading/sequenced_task_runner_handle.h" #include "base/threading/thread_task_runner_handle.h" @@ -81,6 +82,7 @@ #include "content/shell/browser/shell.h" #include "content/shell/common/shell_switches.h" #include "content/test/content_browser_test_utils_internal.h" +#include "content/test/did_commit_provisional_load_interceptor.h" #include "ipc/constants.mojom.h" #include "ipc/ipc_security_test_util.h" #include "media/base/media_switches.h" @@ -495,6 +497,21 @@ } #endif // defined (OS_ANDROID) +void OpenURLBlockUntilNavigationComplete(Shell* shell, const GURL& url) { + WaitForLoadStop(shell->web_contents()); + TestNavigationObserver same_tab_observer(shell->web_contents(), 1); + + OpenURLParams params( + url, + content::Referrer(shell->web_contents()->GetLastCommittedURL(), + blink::kWebReferrerPolicyAlways), + WindowOpenDisposition::CURRENT_TAB, ui::PAGE_TRANSITION_LINK, + true /* is_renderer_initiated */); + shell->OpenURLFromTab(shell->web_contents(), params); + + same_tab_observer.Wait(); +} + } // namespace // @@ -3260,7 +3277,7 @@ "test.example.com", "/media/autoplay/autoplay-disabled.html")); // Load a page with an iframe that has autoplay. - NavigateToURLBlockUntilNavigationsComplete(shell(), main_url, 1); + OpenURLBlockUntilNavigationComplete(shell(), main_url); FrameTreeNode* root = web_contents()->GetFrameTree()->root(); // Navigate the subframes to cross-origin pages. @@ -3274,7 +3291,7 @@ EXPECT_TRUE(AutoplayAllowed(root->child_at(0)->child_at(0), false)); // Navigate to a new page on the same origin. - NavigateToURLBlockUntilNavigationsComplete(shell(), secondary_url, 1); + OpenURLBlockUntilNavigationComplete(shell(), secondary_url); root = web_contents()->GetFrameTree()->root(); // Navigate the subframes to cross-origin pages. @@ -3288,7 +3305,7 @@ EXPECT_TRUE(AutoplayAllowed(root->child_at(0)->child_at(0), false)); // Navigate to a page with autoplay disabled. - NavigateToURLBlockUntilNavigationsComplete(shell(), disabled_url, 1); + OpenURLBlockUntilNavigationComplete(shell(), disabled_url); NavigateFrameAndWait(root->child_at(0), foo_url); // Test that autoplay is no longer allowed. @@ -3296,7 +3313,7 @@ EXPECT_FALSE(AutoplayAllowed(root->child_at(0), false)); // Navigate to another origin and make sure autoplay is disabled. - NavigateToURLBlockUntilNavigationsComplete(shell(), foo_url, 1); + OpenURLBlockUntilNavigationComplete(shell(), foo_url); NavigateFrameAndWait(root->child_at(0), bar_url); EXPECT_FALSE(AutoplayAllowed(shell(), false)); EXPECT_FALSE(AutoplayAllowed(shell(), false)); @@ -10255,4 +10272,161 @@ EXPECT_NE(third_shell_instance->GetProcess(), bar_process); } +namespace { + +// Intercepts the next DidCommitProvisionalLoad message for |deferred_url| in +// any frame of the |web_contents|, and holds off on dispatching it until +// *after* the DidCommitProvisionalLoad message for the next navigation in the +// |web_contents| has been dispatched. +// +// Reversing the order in which the commit messages are dispatched simulates a +// busy renderer that takes a very long time to actually commit the navigation +// to |deferred_url| after receiving FrameNavigationControl::CommitNavigation; +// whereas there is a fast cross-site navigation taking place in the same +// frame which starts second but finishes first. +class CommitMessageOrderReverser : public DidCommitProvisionalLoadInterceptor { + public: + using DidStartDeferringCommitCallback = + base::OnceCallback<void(RenderFrameHost*)>; + + CommitMessageOrderReverser( + WebContents* web_contents, + const GURL& deferred_url, + DidStartDeferringCommitCallback deferred_url_triggered_action) + : DidCommitProvisionalLoadInterceptor(web_contents), + deferred_url_(deferred_url), + deferred_url_triggered_action_( + std::move(deferred_url_triggered_action)) {} + ~CommitMessageOrderReverser() override = default; + + void WaitForBothCommits() { outer_run_loop.Run(); } + + protected: + void WillDispatchDidCommitProvisionalLoad( + RenderFrameHost* render_frame_host, + ::FrameHostMsg_DidCommitProvisionalLoad_Params* params, + service_manager::mojom::InterfaceProviderRequest* + interface_provider_request) override { + // The DidCommitProvisionalLoad message is dispatched once this method + // returns, so to defer committing the the navigation to |deferred_url_|, + // run a nested message loop until the subsequent other commit message is + // dispatched. + if (params->url == deferred_url_) { + std::move(deferred_url_triggered_action_).Run(render_frame_host); + + base::MessageLoop::ScopedNestableTaskAllower allow( + base::MessageLoop::current()); + base::RunLoop nested_run_loop; + nested_loop_quit_ = nested_run_loop.QuitClosure(); + nested_run_loop.Run(); + outer_run_loop.Quit(); + } else if (nested_loop_quit_) { + std::move(nested_loop_quit_).Run(); + } + } + + private: + base::RunLoop outer_run_loop; + base::OnceClosure nested_loop_quit_; + + const GURL deferred_url_; + DidStartDeferringCommitCallback deferred_url_triggered_action_; + + DISALLOW_COPY_AND_ASSIGN(CommitMessageOrderReverser); +}; + +} // namespace + +// Regression test for https://crbug.com/877239, simulating the following +// scenario: +// +// 1) http://a.com/empty.html is loaded in a main frame. +// 2) Dynamically by JS, a same-site child frame is added: +// <iframe 'src=http://a.com/title1.html'/>. +// 3) The initial byte of the response for `title1.html` arrives, causing +// FrameMsg_CommitNavigation to be sent to the same renderer. +// 4) Just before processing this message, however, `main.html` navigates +// the iframe to http://baz.com/title2.html, which results in mojom::Frame:: +// BeginNavigation being called on the RenderFrameHost. +// 5) Suppose that immediately afterwards, `main.html` enters a busy-loop. +// 6) The cross site navigation in the child frame starts, the first response +// byte arrives quickly, and thus the navigation commits quickly. +// 6.1) FrameTreeNode::has_committed_real_load is set to true for the child. +// 6.2) The same-site RenderFrame in the child FrameTreeNode is swapped out, +// i.e. FrameMsg_SwapOut is sent. +// 7) The renderer for site instance `a.com` exits from the busy loop, +// and starts processing messages in order: +// 7.1) The first being processed is FrameMsg_CommitNavigation, so a +// provisional load is created and immediately committed to +// http://a.com/title1.html. +// 7.2) Because at the time the same-site child RenderFrame was created, +// there had been no real load committed in the child frame, and because +// the navigation from the initial empty document to the first real +// document was same-origin, the global object is reused and the +// RemoteInterfaceProvider of the RenderFrame is not rebound. +// 7.3) The obsoleted load in the same-site child frame commits, calling +// mojom::Frame::DidCommitProvisionalLoad, however, with +// |interface_provider_request| being null. +// 8) RenderFrameHostImpl::DidCommitProvisionalLoad sees that a real load was +// already committed in the frame, but |interface_provider_request| is +// missing. However, it also sees that the frame was waiting for a swap-out +// ACK, so ignores the commit, and does not kill the renderer process. +// +// In the simulation of this scenario, we simulate (5) not by delaying +// renderer-side processing of the CommmitNavigation message, but by delaying +// browser-side processing of the response to it, of DidCommitProvisionalLoad. +IN_PROC_BROWSER_TEST_F(SitePerProcessBrowserTest, + InterfaceProviderRequestIsOptionalForRaceyFirstCommits) { + const GURL kMainFrameUrl( + embedded_test_server()->GetURL("a.com", "/empty.html")); + const GURL kSubframeSameSiteUrl( + embedded_test_server()->GetURL("a.com", "/title1.html")); + const GURL kCrossSiteSubframeUrl( + embedded_test_server()->GetURL("baz.com", "/title2.html")); + + const auto kAddSameSiteDynamicSubframe = base::StringPrintf( + "var f = document.createElement(\"iframe\");" + "f.src=\"%s\";" + "document.body.append(f);", + kSubframeSameSiteUrl.spec().c_str()); + const auto kNavigateSubframeCrossSite = base::StringPrintf( + "f.src = \"%s\";", kCrossSiteSubframeUrl.spec().c_str()); + const std::string kExtractSubframeUrl = + "window.domAutomationController.send(f.src);"; + + ASSERT_TRUE(NavigateToURL(shell(), kMainFrameUrl)); + + const auto* main_rfh_site_instance = + shell()->web_contents()->GetMainFrame()->GetSiteInstance(); + + auto did_start_deferring_commit_callback = + base::BindLambdaForTesting([&](RenderFrameHost* subframe_rfh) { + // Verify that the subframe starts out as same-process with its parent. + ASSERT_EQ(main_rfh_site_instance, subframe_rfh->GetSiteInstance()); + + // Trigger the second commit now that we are deferring the first one. + ASSERT_TRUE(ExecuteScript(shell(), kNavigateSubframeCrossSite)); + }); + + CommitMessageOrderReverser commit_order_reverser( + shell()->web_contents(), kSubframeSameSiteUrl /* deferred_url */, + did_start_deferring_commit_callback); + + ASSERT_TRUE(ExecuteScript(shell(), kAddSameSiteDynamicSubframe)); + commit_order_reverser.WaitForBothCommits(); + + // Verify that: + // - The cross-site navigation in the sub-frame was committed and the + // same-site navigation was ignored. + // - The parent frame thinks so, too. + // - The renderer process corresponding to the sub-frame with the ignored + // commit was not killed. This is verified implicitly: this is the same + // renderer process where the parent RenderFrame lives, so if the call to + // ExecuteScriptAndExtractString succeeds here, the process is still alive. + std::string actual_subframe_url; + ASSERT_TRUE(ExecuteScriptAndExtractString(shell(), kExtractSubframeUrl, + &actual_subframe_url)); + EXPECT_EQ(kCrossSiteSubframeUrl.spec(), actual_subframe_url); +} + } // namespace content
diff --git a/content/browser/site_per_process_hit_test_browsertest.cc b/content/browser/site_per_process_hit_test_browsertest.cc index 5d591b7..a390c7d 100644 --- a/content/browser/site_per_process_hit_test_browsertest.cc +++ b/content/browser/site_per_process_hit_test_browsertest.cc
@@ -1600,6 +1600,7 @@ InputEventAckWaiter waiter(expected_target->GetRenderWidgetHost(), blink::WebInputEvent::kMouseWheel); + waiter.Reset(); SendMouseWheel(pos); waiter.Wait(); @@ -1609,7 +1610,9 @@ EXPECT_TRUE(msg_queue.WaitForMessage(&reply)); EXPECT_EQ("\"scroll: 1\"", reply); + waiter.Reset(); SendMouseWheel(pos); + waiter.Wait(); // If async_wheel_events is disabled, this time only the wheel handler // fires, since even numbered scrolls are prevent-defaulted. If it is @@ -1624,7 +1627,9 @@ EXPECT_EQ("\"scroll: 2\"", reply); } + waiter.Reset(); SendMouseWheel(pos); + waiter.Wait(); // Odd number of wheels, expect both wheel and scroll handlers to fire // again.
diff --git a/content/browser/web_contents/web_contents_impl.cc b/content/browser/web_contents/web_contents_impl.cc index e827b7e..27b496c 100644 --- a/content/browser/web_contents/web_contents_impl.cc +++ b/content/browser/web_contents/web_contents_impl.cc
@@ -3368,7 +3368,7 @@ params->add_request_header(key_value.first, key_value.second); } } - params->set_download_source(DownloadSource::WEB_CONTENTS_API); + params->set_download_source(download::DownloadSource::WEB_CONTENTS_API); BrowserContext::GetDownloadManager(GetBrowserContext()) ->DownloadUrl(std::move(params)); }
diff --git a/content/browser/webrtc/webrtc_image_capture_browsertest.cc b/content/browser/webrtc/webrtc_image_capture_browsertest.cc index b37329f..e2ab80a 100644 --- a/content/browser/webrtc/webrtc_image_capture_browsertest.cc +++ b/content/browser/webrtc/webrtc_image_capture_browsertest.cc
@@ -23,16 +23,7 @@ namespace content { -#if defined(OS_WIN) -// These tests are flaky on WebRTC Windows bots: https://crbug.com/633242. -#define MAYBE_GetPhotoCapabilities DISABLED_GetPhotoCapabilities -#define MAYBE_GetPhotoSettings DISABLED_GetPhotoSettings -#define MAYBE_TakePhoto DISABLED_TakePhoto -#define MAYBE_GrabFrame DISABLED_GrabFrame -#define MAYBE_GetTrackCapabilities DISABLED_GetTrackCapabilities -#define MAYBE_GetTrackSettings DISABLED_GetTrackSettings -#define MAYBE_ManipulateZoom DISABLED_ManipulateZoom -#elif defined(OS_ANDROID) +#if defined(OS_ANDROID) // TODO(chfremer): Re-enable test on Android as soon as the cause for // https://crbug.com/793859 is understood and fixed. #define MAYBE_GetPhotoCapabilities GetPhotoCapabilities
diff --git a/content/child/runtime_features.cc b/content/child/runtime_features.cc index 2216cba75..e3aad65 100644 --- a/content/child/runtime_features.cc +++ b/content/child/runtime_features.cc
@@ -424,6 +424,12 @@ WebRuntimeFeatures::EnablePictureInPicture( base::FeatureList::IsEnabled(media::kPictureInPicture)); + + WebRuntimeFeatures::EnableCodeCacheAfterExecute( + base::FeatureList::IsEnabled(features::kCodeCacheAfterExecute)); + + if (base::FeatureList::IsEnabled(features::kUnifiedTouchAdjustment)) + WebRuntimeFeatures::EnableUnifiedTouchAdjustment(true); }; } // namespace content
diff --git a/content/common/BUILD.gn b/content/common/BUILD.gn index fcd79ef0..64543eaf 100644 --- a/content/common/BUILD.gn +++ b/content/common/BUILD.gn
@@ -284,6 +284,8 @@ "service_worker/service_worker_types.h", "service_worker/service_worker_utils.cc", "service_worker/service_worker_utils.h", + "single_request_url_loader_factory.cc", + "single_request_url_loader_factory.h", "speech_recognition_messages.h", "swapped_out_messages.cc", "swapped_out_messages.h",
diff --git a/content/common/content_security_policy/content_security_policy.cc b/content/common/content_security_policy/content_security_policy.cc index f0e93a50..c0b29bb 100644 --- a/content/common/content_security_policy/content_security_policy.cc +++ b/content/common/content_security_policy/content_security_policy.cc
@@ -86,8 +86,9 @@ context->ReportContentSecurityPolicyViolation(CSPViolationParams( CSPDirective::NameToString(directive.name), CSPDirective::NameToString(directive_name), message.str(), safe_url, - policy.report_endpoints, policy.header.header_value, policy.header.type, - is_redirect, safe_source_location)); + policy.report_endpoints, policy.use_reporting_api, + policy.header.header_value, policy.header.type, is_redirect, + safe_source_location)); } bool AllowDirective(CSPContext* context, @@ -123,21 +124,21 @@ } // namespace -ContentSecurityPolicy::ContentSecurityPolicy() - : header(std::string(), - blink::kWebContentSecurityPolicyTypeEnforce, - blink::kWebContentSecurityPolicySourceHTTP) {} +ContentSecurityPolicy::ContentSecurityPolicy() = default; ContentSecurityPolicy::ContentSecurityPolicy( const ContentSecurityPolicyHeader& header, const std::vector<CSPDirective>& directives, - const std::vector<std::string>& report_endpoints) + const std::vector<std::string>& report_endpoints, + bool use_reporting_api) : header(header), directives(directives), - report_endpoints(report_endpoints) {} + report_endpoints(report_endpoints), + use_reporting_api(use_reporting_api) {} -ContentSecurityPolicy::ContentSecurityPolicy(const ContentSecurityPolicy&) = - default; +ContentSecurityPolicy::ContentSecurityPolicy( + const ContentSecurityPolicy& other) = default; + ContentSecurityPolicy::~ContentSecurityPolicy() = default; // static
diff --git a/content/common/content_security_policy/content_security_policy.h b/content/common/content_security_policy/content_security_policy.h index d531b4c..7366f00 100644 --- a/content/common/content_security_policy/content_security_policy.h +++ b/content/common/content_security_policy/content_security_policy.h
@@ -26,13 +26,15 @@ ContentSecurityPolicy(); ContentSecurityPolicy(const ContentSecurityPolicyHeader& header, const std::vector<CSPDirective>& directives, - const std::vector<std::string>& report_endpoints); + const std::vector<std::string>& report_endpoints, + bool use_reporting_api); ContentSecurityPolicy(const ContentSecurityPolicy&); ~ContentSecurityPolicy(); ContentSecurityPolicyHeader header; std::vector<CSPDirective> directives; std::vector<std::string> report_endpoints; + bool use_reporting_api; std::string ToString() const;
diff --git a/content/common/content_security_policy/content_security_policy_unittest.cc b/content/common/content_security_policy/content_security_policy_unittest.cc index e14a041..a8596b39 100644 --- a/content/common/content_security_policy/content_security_policy_unittest.cc +++ b/content/common/content_security_policy/content_security_policy_unittest.cc
@@ -48,7 +48,7 @@ CSPContextTest context; std::vector<std::string> report_end_points; // empty ContentSecurityPolicy policy(EmptyCspHeader(), std::vector<CSPDirective>(), - report_end_points); + report_end_points, false); EXPECT_TRUE(ContentSecurityPolicy::Allow(policy, CSPDirective::FormAction, GURL("http://www.example.com"), @@ -65,8 +65,8 @@ CSPSourceList source_list(false, false, {source}); CSPDirective directive(CSPDirective::FormAction, source_list); std::vector<std::string> report_end_points; // empty - ContentSecurityPolicy policy(EmptyCspHeader(), {directive}, - report_end_points); + ContentSecurityPolicy policy(EmptyCspHeader(), {directive}, report_end_points, + false); EXPECT_FALSE(ContentSecurityPolicy::Allow(policy, CSPDirective::FormAction, GURL("http://www.not-example.com"), @@ -93,7 +93,7 @@ ContentSecurityPolicy policy( EmptyCspHeader(), {CSPDirective(CSPDirective::DefaultSrc, source_list_a)}, - report_end_points); + report_end_points, false); EXPECT_FALSE(ContentSecurityPolicy::Allow(policy, CSPDirective::FrameSrc, GURL("http://b.com"), false, &context, SourceLocation())); @@ -112,7 +112,7 @@ CSPContextTest context; ContentSecurityPolicy policy( EmptyCspHeader(), {CSPDirective(CSPDirective::ChildSrc, source_list_a)}, - report_end_points); + report_end_points, false); EXPECT_FALSE(ContentSecurityPolicy::Allow(policy, CSPDirective::FrameSrc, GURL("http://b.com"), false, &context, SourceLocation())); @@ -134,7 +134,7 @@ EmptyCspHeader(), {CSPDirective(CSPDirective::FrameSrc, {source_list_a}), CSPDirective(CSPDirective::ChildSrc, {source_list_b})}, - report_end_points); + report_end_points, false); EXPECT_TRUE(ContentSecurityPolicy::Allow(policy, CSPDirective::FrameSrc, GURL("http://a.com"), false, &context, SourceLocation())); @@ -158,7 +158,7 @@ CSPSourceList source_list(false, false, {source}); ContentSecurityPolicy policy( EmptyCspHeader(), {CSPDirective(CSPDirective::DefaultSrc, source_list)}, - report_end_points); + report_end_points, false); EXPECT_TRUE(ContentSecurityPolicy::Allow(policy, CSPDirective::FrameSrc, GURL("https://example.com/"), false, @@ -186,7 +186,7 @@ CSPSourceList source_list(false, false, {source}); ContentSecurityPolicy policy( EmptyCspHeader(), {CSPDirective(CSPDirective::DefaultSrc, source_list)}, - report_end_points); + report_end_points, false); EXPECT_FALSE(ContentSecurityPolicy::Allow( policy, CSPDirective::FrameSrc, @@ -218,7 +218,7 @@ CSPSourceList source_list(false, false, {source}); ContentSecurityPolicy policy( EmptyCspHeader(), {CSPDirective(CSPDirective::DefaultSrc, source_list)}, - report_end_points); + report_end_points, false); EXPECT_FALSE(ContentSecurityPolicy::Allow(policy, CSPDirective::FrameSrc, GURL("blob:https://example.com/"), @@ -245,7 +245,7 @@ CSPSourceList source_list(false, false, {source}); ContentSecurityPolicy policy( EmptyCspHeader(), {CSPDirective(CSPDirective::DefaultSrc, source_list)}, - report_end_points); + report_end_points, false); EXPECT_FALSE(ContentSecurityPolicy::ShouldUpgradeInsecureRequest(policy));
diff --git a/content/common/content_security_policy/csp_context.cc b/content/common/content_security_policy/csp_context.cc index 4fd6b8a..99b8ef4 100644 --- a/content/common/content_security_policy/csp_context.cc +++ b/content/common/content_security_policy/csp_context.cc
@@ -113,6 +113,7 @@ const std::string& console_message, const GURL& blocked_url, const std::vector<std::string>& report_endpoints, + bool use_reporting_api, const std::string& header, const blink::WebContentSecurityPolicyType& disposition, bool after_redirect, @@ -122,6 +123,7 @@ console_message(console_message), blocked_url(blocked_url), report_endpoints(report_endpoints), + use_reporting_api(use_reporting_api), header(header), disposition(disposition), after_redirect(after_redirect), @@ -129,7 +131,6 @@ CSPViolationParams::CSPViolationParams(const CSPViolationParams& other) = default; - CSPViolationParams::~CSPViolationParams() {} } // namespace content
diff --git a/content/common/content_security_policy/csp_context.h b/content/common/content_security_policy/csp_context.h index 78b7a090..3697e14 100644 --- a/content/common/content_security_policy/csp_context.h +++ b/content/common/content_security_policy/csp_context.h
@@ -108,6 +108,7 @@ const std::string& console_message, const GURL& blocked_url, const std::vector<std::string>& report_endpoints, + bool use_reporting_api, const std::string& header, const blink::WebContentSecurityPolicyType& disposition, bool after_redirect, @@ -128,10 +129,15 @@ // The URL that was blocked by the policy. GURL blocked_url; - // The set of URI where a JSON-formatted report of the violation should be - // sent. + // The set of endpoints where a report of the violation should be sent. + // Based on 'use_reporting_api' it can be either a set of group_names (when + // 'use_reporting_api' = true) or a set of URLs. This means that it's not + // possible to use both methods of reporting. This is by design. std::vector<std::string> report_endpoints; + // Whether to use the reporting api or not. + bool use_reporting_api; + // The raw content security policy header that was violated. std::string header;
diff --git a/content/common/content_security_policy/csp_context_unittest.cc b/content/common/content_security_policy/csp_context_unittest.cc index ae5d6b965..d5cf578 100644 --- a/content/common/content_security_policy/csp_context_unittest.cc +++ b/content/common/content_security_policy/csp_context_unittest.cc
@@ -61,7 +61,7 @@ blink::kWebContentSecurityPolicyTypeEnforce, blink::kWebContentSecurityPolicySourceHTTP), {CSPDirective(directive_name, CSPSourceList(false, false, sources))}, - std::vector<std::string>()); // report_end_points + std::vector<std::string>(), false); // report_end_points } } // namespace
diff --git a/content/common/frame_messages.h b/content/common/frame_messages.h index 02b164a..152b4d9 100644 --- a/content/common/frame_messages.h +++ b/content/common/frame_messages.h
@@ -499,6 +499,7 @@ IPC_STRUCT_TRAITS_MEMBER(navigation_timing) IPC_STRUCT_TRAITS_MEMBER(service_worker_provider_id) IPC_STRUCT_TRAITS_MEMBER(appcache_host_id) + IPC_STRUCT_TRAITS_MEMBER(was_activated) #if defined(OS_ANDROID) IPC_STRUCT_TRAITS_MEMBER(data_url_as_string) #endif @@ -670,6 +671,7 @@ IPC_STRUCT_TRAITS_MEMBER(header) IPC_STRUCT_TRAITS_MEMBER(directives) IPC_STRUCT_TRAITS_MEMBER(report_endpoints) + IPC_STRUCT_TRAITS_MEMBER(use_reporting_api) IPC_STRUCT_TRAITS_END() IPC_STRUCT_TRAITS_BEGIN(content::ContentSecurityPolicyHeader) @@ -684,6 +686,7 @@ IPC_STRUCT_TRAITS_MEMBER(console_message) IPC_STRUCT_TRAITS_MEMBER(blocked_url) IPC_STRUCT_TRAITS_MEMBER(report_endpoints) + IPC_STRUCT_TRAITS_MEMBER(use_reporting_api) IPC_STRUCT_TRAITS_MEMBER(header) IPC_STRUCT_TRAITS_MEMBER(disposition) IPC_STRUCT_TRAITS_MEMBER(after_redirect)
diff --git a/content/common/navigation_params.cc b/content/common/navigation_params.cc index 16469b3..67f50ba 100644 --- a/content/common/navigation_params.cc +++ b/content/common/navigation_params.cc
@@ -104,7 +104,8 @@ should_clear_history_list(false), should_create_service_worker(false), service_worker_provider_id(kInvalidServiceWorkerProviderId), - appcache_host_id(kAppCacheNoHostId) {} + appcache_host_id(kAppCacheNoHostId), + was_activated(false) {} RequestNavigationParams::RequestNavigationParams( bool is_overriding_user_agent, @@ -139,7 +140,8 @@ should_clear_history_list(should_clear_history_list), should_create_service_worker(false), service_worker_provider_id(kInvalidServiceWorkerProviderId), - appcache_host_id(kAppCacheNoHostId) {} + appcache_host_id(kAppCacheNoHostId), + was_activated(false) {} RequestNavigationParams::RequestNavigationParams( const RequestNavigationParams& other) = default;
diff --git a/content/common/navigation_params.h b/content/common/navigation_params.h index 1301400..b844acff 100644 --- a/content/common/navigation_params.h +++ b/content/common/navigation_params.h
@@ -294,6 +294,16 @@ // The AppCache host id to be used to identify this navigation. int appcache_host_id; + // True if a navigation is following the rules of user activation propagation. + // This is different from |has_user_gesture| (in CommonNavigationParams) as + // the activation may have happened before the navigation was triggered, for + // example. + // In other words, the distinction isn't regarding user activation and user + // gesture but whether there was an activation prior to the navigation or to + // start it. `was_activated` will answer the former question while + // `user_gesture` will answer the latter. + bool was_activated; + #if defined(OS_ANDROID) // The real content of the data: URL. Only used in Android WebView for // implementing LoadDataWithBaseUrl API method to circumvent the restriction
diff --git a/content/common/single_request_url_loader_factory.cc b/content/common/single_request_url_loader_factory.cc new file mode 100644 index 0000000..0e53210a1 --- /dev/null +++ b/content/common/single_request_url_loader_factory.cc
@@ -0,0 +1,104 @@ +// 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 "content/common/single_request_url_loader_factory.h" + +#include <memory> +#include <utility> + +#include "base/macros.h" +#include "base/memory/ptr_util.h" +#include "base/memory/ref_counted.h" +#include "base/sequenced_task_runner.h" +#include "base/threading/sequenced_task_runner_handle.h" +#include "services/network/public/interfaces/url_loader.mojom.h" + +namespace content { + +class SingleRequestURLLoaderFactory::HandlerState + : public base::RefCountedThreadSafe< + SingleRequestURLLoaderFactory::HandlerState> { + public: + explicit HandlerState(RequestHandler handler) + : handler_(std::move(handler)), + handler_task_runner_(base::SequencedTaskRunnerHandle::Get()) {} + + void HandleRequest(network::mojom::URLLoaderRequest loader, + network::mojom::URLLoaderClientPtr client) { + if (!handler_task_runner_->RunsTasksInCurrentSequence()) { + handler_task_runner_->PostTask( + FROM_HERE, base::BindOnce(&HandlerState::HandleRequest, this, + std::move(loader), std::move(client))); + return; + } + + DCHECK(handler_); + std::move(handler_).Run(std::move(loader), std::move(client)); + } + + private: + friend class base::RefCountedThreadSafe<HandlerState>; + + ~HandlerState() { + if (handler_) { + handler_task_runner_->PostTask( + FROM_HERE, + base::BindOnce(&DropHandlerOnHandlerSequence, std::move(handler_))); + } + } + + static void DropHandlerOnHandlerSequence(RequestHandler handler) {} + + RequestHandler handler_; + const scoped_refptr<base::SequencedTaskRunner> handler_task_runner_; + + DISALLOW_COPY_AND_ASSIGN(HandlerState); +}; + +class SingleRequestURLLoaderFactory::FactoryInfo + : public SharedURLLoaderFactoryInfo { + public: + explicit FactoryInfo(scoped_refptr<HandlerState> state) + : state_(std::move(state)) {} + ~FactoryInfo() override = default; + + // SharedURLLoaderFactoryInfo: + scoped_refptr<SharedURLLoaderFactory> CreateFactory() override { + return new SingleRequestURLLoaderFactory(std::move(state_)); + } + + private: + scoped_refptr<HandlerState> state_; + + DISALLOW_COPY_AND_ASSIGN(FactoryInfo); +}; + +SingleRequestURLLoaderFactory::SingleRequestURLLoaderFactory( + RequestHandler handler) + : state_(base::MakeRefCounted<HandlerState>(std::move(handler))) {} + +void SingleRequestURLLoaderFactory::CreateLoaderAndStart( + network::mojom::URLLoaderRequest loader, + int32_t routing_id, + int32_t request_id, + uint32_t options, + const network::ResourceRequest& request, + network::mojom::URLLoaderClientPtr client, + const net::MutableNetworkTrafficAnnotationTag& traffic_annotation, + const Constraints& constraints) { + state_->HandleRequest(std::move(loader), std::move(client)); +} + +std::unique_ptr<SharedURLLoaderFactoryInfo> +SingleRequestURLLoaderFactory::Clone() { + return std::make_unique<FactoryInfo>(state_); +} + +SingleRequestURLLoaderFactory::SingleRequestURLLoaderFactory( + scoped_refptr<HandlerState> state) + : state_(std::move(state)) {} + +SingleRequestURLLoaderFactory::~SingleRequestURLLoaderFactory() = default; + +} // namespace content
diff --git a/content/common/single_request_url_loader_factory.h b/content/common/single_request_url_loader_factory.h new file mode 100644 index 0000000..4b0206b --- /dev/null +++ b/content/common/single_request_url_loader_factory.h
@@ -0,0 +1,52 @@ +// 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. + +#ifndef CONTENT_COMMON_SINGLE_REQUEST_URL_LOADER_FACTORY_H_ +#define CONTENT_COMMON_SINGLE_REQUEST_URL_LOADER_FACTORY_H_ + +#include "content/public/common/shared_url_loader_factory.h" + +#include "base/memory/ref_counted.h" +#include "services/network/public/interfaces/url_loader.mojom.h" + +namespace content { + +// An implementation of SharedURLLoaderFactory which handles only a single +// request. It's an error to call CreateLoaderAndStart() more than a total of +// one time across this object or any of its clones. +class SingleRequestURLLoaderFactory : public SharedURLLoaderFactory { + public: + using RequestHandler = + base::OnceCallback<void(network::mojom::URLLoaderRequest, + network::mojom::URLLoaderClientPtr)>; + + explicit SingleRequestURLLoaderFactory(RequestHandler handler); + + // SharedURLLoaderFactory: + void CreateLoaderAndStart( + network::mojom::URLLoaderRequest loader, + int32_t routing_id, + int32_t request_id, + uint32_t options, + const network::ResourceRequest& request, + network::mojom::URLLoaderClientPtr client, + const net::MutableNetworkTrafficAnnotationTag& traffic_annotation, + const Constraints& constraints) override; + std::unique_ptr<SharedURLLoaderFactoryInfo> Clone() override; + + private: + class FactoryInfo; + class HandlerState; + + explicit SingleRequestURLLoaderFactory(scoped_refptr<HandlerState> state); + ~SingleRequestURLLoaderFactory() override; + + scoped_refptr<HandlerState> state_; + + DISALLOW_COPY_AND_ASSIGN(SingleRequestURLLoaderFactory); +}; + +} // namespace content + +#endif // CONTENT_COMMON_SINGLE_REQUEST_URL_LOADER_FACTORY_H_
diff --git a/content/common/throttling_url_loader.cc b/content/common/throttling_url_loader.cc index 890cd9d..03019acf 100644 --- a/content/common/throttling_url_loader.cc +++ b/content/common/throttling_url_loader.cc
@@ -98,14 +98,12 @@ int32_t in_routing_id, int32_t in_request_id, uint32_t in_options, - StartLoaderCallback in_start_loader_callback, network::ResourceRequest* in_url_request, scoped_refptr<base::SingleThreadTaskRunner> in_task_runner) : url_loader_factory(std::move(in_url_loader_factory)), routing_id(in_routing_id), request_id(in_request_id), options(in_options), - start_loader_callback(std::move(in_start_loader_callback)), url_request(*in_url_request), task_runner(std::move(in_task_runner)) {} @@ -149,24 +147,7 @@ std::unique_ptr<ThrottlingURLLoader> loader(new ThrottlingURLLoader( std::move(throttles), client, traffic_annotation)); loader->Start(std::move(factory), routing_id, request_id, options, - StartLoaderCallback(), url_request, std::move(task_runner)); - return loader; -} - -// static -std::unique_ptr<ThrottlingURLLoader> ThrottlingURLLoader::CreateLoaderAndStart( - StartLoaderCallback start_loader_callback, - std::vector<std::unique_ptr<URLLoaderThrottle>> throttles, - int32_t routing_id, - network::ResourceRequest* url_request, - network::mojom::URLLoaderClient* client, - const net::NetworkTrafficAnnotationTag& traffic_annotation, - scoped_refptr<base::SingleThreadTaskRunner> task_runner) { - std::unique_ptr<ThrottlingURLLoader> loader(new ThrottlingURLLoader( - std::move(throttles), client, traffic_annotation)); - loader->Start(nullptr, routing_id, 0, network::mojom::kURLLoadOptionNone, - std::move(start_loader_callback), url_request, - std::move(task_runner)); + url_request, std::move(task_runner)); return loader; } @@ -233,7 +214,6 @@ int32_t routing_id, int32_t request_id, uint32_t options, - StartLoaderCallback start_loader_callback, network::ResourceRequest* url_request, scoped_refptr<base::SingleThreadTaskRunner> task_runner) { DCHECK_EQ(DEFERRED_NONE, deferred_stage_); @@ -256,15 +236,13 @@ if (deferred) { deferred_stage_ = DEFERRED_START; start_info_ = std::make_unique<StartInfo>( - std::move(factory), routing_id, request_id, options, - std::move(start_loader_callback), url_request, + std::move(factory), routing_id, request_id, options, url_request, std::move(task_runner)); return; } } - StartNow(factory.get(), routing_id, request_id, options, - std::move(start_loader_callback), url_request, + StartNow(factory.get(), routing_id, request_id, options, url_request, std::move(task_runner)); } @@ -273,7 +251,6 @@ int32_t routing_id, int32_t request_id, uint32_t options, - StartLoaderCallback start_loader_callback, network::ResourceRequest* url_request, scoped_refptr<base::SingleThreadTaskRunner> task_runner) { network::mojom::URLLoaderClientPtr client; @@ -281,17 +258,11 @@ client_binding_.set_connection_error_handler(base::Bind( &ThrottlingURLLoader::OnClientConnectionError, base::Unretained(this))); - if (factory) { - DCHECK(!start_loader_callback); - - factory->CreateLoaderAndStart( - mojo::MakeRequest(&url_loader_), routing_id, request_id, options, - *url_request, std::move(client), - net::MutableNetworkTrafficAnnotationTag(traffic_annotation_)); - } else { - std::move(start_loader_callback) - .Run(mojo::MakeRequest(&url_loader_), std::move(client)); - } + DCHECK(factory); + factory->CreateLoaderAndStart( + mojo::MakeRequest(&url_loader_), routing_id, request_id, options, + *url_request, std::move(client), + net::MutableNetworkTrafficAnnotationTag(traffic_annotation_)); if (!pausing_reading_body_from_net_throttles_.empty()) url_loader_->PauseReadingBodyFromNet(); @@ -482,7 +453,6 @@ case DEFERRED_START: { StartNow(start_info_->url_loader_factory.get(), start_info_->routing_id, start_info_->request_id, start_info_->options, - std::move(start_info_->start_loader_callback), &start_info_->url_request, std::move(start_info_->task_runner)); break; }
diff --git a/content/common/throttling_url_loader.h b/content/common/throttling_url_loader.h index 2939fa4..2689572 100644 --- a/content/common/throttling_url_loader.h +++ b/content/common/throttling_url_loader.h
@@ -25,10 +25,6 @@ namespace content { -namespace mojom { -class URLLoaderFactory; -} - // ThrottlingURLLoader is a wrapper around the // network::mojom::URLLoader[Factory] interfaces. It applies a list of // URLLoaderThrottle instances which could defer, resume or cancel the URL @@ -51,22 +47,6 @@ const net::NetworkTrafficAnnotationTag& traffic_annotation, scoped_refptr<base::SingleThreadTaskRunner> task_runner); - using StartLoaderCallback = - base::OnceCallback<void(network::mojom::URLLoaderRequest request, - network::mojom::URLLoaderClientPtr client)>; - - // Similar to the method above, but uses a |start_loader_callback| instead of - // a network::mojom::URLLoaderFactory to start the loader. The callback must - // be safe to call during the lifetime of the returned object. - static std::unique_ptr<ThrottlingURLLoader> CreateLoaderAndStart( - StartLoaderCallback start_loader_callback, - std::vector<std::unique_ptr<URLLoaderThrottle>> throttles, - int32_t routing_id, - network::ResourceRequest* url_request, - network::mojom::URLLoaderClient* client, - const net::NetworkTrafficAnnotationTag& traffic_annotation, - scoped_refptr<base::SingleThreadTaskRunner> task_runner); - ~ThrottlingURLLoader() override; void FollowRedirect(); @@ -92,14 +72,10 @@ network::mojom::URLLoaderClient* client, const net::NetworkTrafficAnnotationTag& traffic_annotation); - // Either of the two sets of arguments below is valid but not both: - // - |factory|, |routing_id|, |request_id| and |options|; - // - |start_loader_callback|. void Start(scoped_refptr<SharedURLLoaderFactory> factory, int32_t routing_id, int32_t request_id, uint32_t options, - StartLoaderCallback start_loader_callback, network::ResourceRequest* url_request, scoped_refptr<base::SingleThreadTaskRunner> task_runner); @@ -107,7 +83,6 @@ int32_t routing_id, int32_t request_id, uint32_t options, - StartLoaderCallback start_loader_callback, network::ResourceRequest* url_request, scoped_refptr<base::SingleThreadTaskRunner> task_runner); @@ -192,7 +167,6 @@ int32_t in_routing_id, int32_t in_request_id, uint32_t in_options, - StartLoaderCallback in_start_loader_callback, network::ResourceRequest* in_url_request, scoped_refptr<base::SingleThreadTaskRunner> in_task_runner); ~StartInfo(); @@ -202,8 +176,6 @@ int32_t request_id; uint32_t options; - StartLoaderCallback start_loader_callback; - network::ResourceRequest url_request; // |task_runner_| is used to set up |client_binding_|. scoped_refptr<base::SingleThreadTaskRunner> task_runner;
diff --git a/content/network/BUILD.gn b/content/network/BUILD.gn index 78c542c..485e9e8 100644 --- a/content/network/BUILD.gn +++ b/content/network/BUILD.gn
@@ -23,9 +23,6 @@ visibility = [ ":network", "//content", # For the component build. - "//content/app:*", - "//content/utility:utility", - "//services/network/public/cpp/*", # For use by StoragePartition. # TODO(mmenke): Remove when network service ships. @@ -47,11 +44,8 @@ "//base", "//content:export", "//content/common", - "//content/common:mojo_bindings", "//content/public/common:common_sources", "//net", - "//services/network:network_service", "//services/network/public/cpp", - "//services/proxy_resolver/public/interfaces", ] }
diff --git a/content/network/DEPS b/content/network/DEPS index a57bd0d6..78570aa 100644 --- a/content/network/DEPS +++ b/content/network/DEPS
@@ -7,16 +7,6 @@ "+content/public/common/request_context_type.h", "+content/public/common/resource_type.h", "+content/public/common/service_worker_modes.h", - "+content/public/network", "+services/network", "+services/service_manager/public", ] - -specific_include_rules = { - '.*_[a-z]*test.*': [ - "+content/public/common/content_paths.h", - "+content/public/common/service_names.mojom.h", - "+content/public/test/controllable_http_response.h", - "+content/public/test/test_url_loader_client.h", - ], -}
diff --git a/content/public/android/java/src/org/chromium/content/browser/ContentViewCore.java b/content/public/android/java/src/org/chromium/content/browser/ContentViewCore.java index 75cb551..6a1a4f68 100644 --- a/content/public/android/java/src/org/chromium/content/browser/ContentViewCore.java +++ b/content/public/android/java/src/org/chromium/content/browser/ContentViewCore.java
@@ -13,7 +13,6 @@ import org.chromium.base.VisibleForTesting; import org.chromium.content.browser.input.SelectPopup; -import org.chromium.content.browser.input.TextSuggestionHost; import org.chromium.content_public.browser.WebContents; import org.chromium.ui.base.ViewAndroidDelegate; import org.chromium.ui.base.WindowAndroid; @@ -379,15 +378,6 @@ // Test-only methods /** - * @return The TextSuggestionHost that handles displaying the text suggestion menu. - */ - @VisibleForTesting - TextSuggestionHost getTextSuggestionHostForTesting(); - - @VisibleForTesting - void setTextSuggestionHostForTesting(TextSuggestionHost textSuggestionHost); - - /** * @return The amount of the top controls height if controls are in the state * of shrinking Blink's view size, otherwise 0. */
diff --git a/content/public/android/java/src/org/chromium/content/browser/ContentViewCoreImpl.java b/content/public/android/java/src/org/chromium/content/browser/ContentViewCoreImpl.java index b090d20..9cf67902 100644 --- a/content/public/android/java/src/org/chromium/content/browser/ContentViewCoreImpl.java +++ b/content/public/android/java/src/org/chromium/content/browser/ContentViewCoreImpl.java
@@ -158,8 +158,6 @@ private SelectPopup mSelectPopup; private long mNativeSelectPopupSourceFrame; - private TextSuggestionHost mTextSuggestionHost; - // Cached copy of all positions and scales as reported by the renderer. private RenderCoordinates mRenderCoordinates; @@ -254,22 +252,10 @@ } @VisibleForTesting - @Override - public TextSuggestionHost getTextSuggestionHostForTesting() { - return mTextSuggestionHost; - } - - @VisibleForTesting void setWebContentsForTesting(WebContentsImpl webContents) { mWebContents = webContents; } - @VisibleForTesting - @Override - public void setTextSuggestionHostForTesting(TextSuggestionHost textSuggestionHost) { - mTextSuggestionHost = textSuggestionHost; - } - /** * Add {@link WindowAndroidChangeObserver} object. * @param observer Observer instance to add. @@ -321,9 +307,9 @@ mWebContents, mContainerView, new InputMethodManagerWrapper(mContext)); imeAdapter.addEventObserver(this); imeAdapter.addEventObserver(TapDisambiguator.create(mContext, mWebContents, containerView)); - mTextSuggestionHost = - new TextSuggestionHost(mContext, mWebContents, windowAndroid, mContainerView); - addWindowAndroidChangedObserver(mTextSuggestionHost); + TextSuggestionHost textSuggestionHost = + TextSuggestionHost.create(mContext, mWebContents, windowAndroid, containerView); + addWindowAndroidChangedObserver(textSuggestionHost); mWebContentsObserver = new ContentViewWebContentsObserver(this); @@ -334,7 +320,7 @@ mWindowEventObservers.addObserver(controller); mWindowEventObservers.addObserver(getGestureListenerManager()); - mWindowEventObservers.addObserver(mTextSuggestionHost); + mWindowEventObservers.addObserver(textSuggestionHost); mWindowEventObservers.addObserver(imeAdapter); mWindowEventObservers.addObserver(wcax); } @@ -385,7 +371,7 @@ if (mContainerView != null) { hideSelectPopupWithCancelMessage(); getImeAdapter().setContainerView(containerView); - mTextSuggestionHost.setContainerView(containerView); + getTextSuggestionHost().setContainerView(containerView); } mContainerView = containerView; @@ -416,6 +402,10 @@ return WebContentsAccessibilityImpl.fromWebContents(mWebContents); } + private TextSuggestionHost getTextSuggestionHost() { + return TextSuggestionHost.fromWebContents(mWebContents); + } + @CalledByNative private void onNativeContentViewCoreDestroyed(long nativeContentViewCore) { assert nativeContentViewCore == mNativeContentViewCore; @@ -436,7 +426,7 @@ mWebContentsObserver.destroy(); mWebContentsObserver = null; getImeAdapter().resetAndHideKeyboard(); - removeWindowAndroidChangedObserver(mTextSuggestionHost); + removeWindowAndroidChangedObserver(getTextSuggestionHost()); mWindowEventObservers.clear(); hidePopupsAndPreserveSelection(); mWebContents = null; @@ -558,8 +548,6 @@ private void hidePopupsAndClearSelection() { if (mWebContents != null) { getSelectionPopupController().destroyActionModeAndUnselect(); - destroyPastePopup(); - getTapDisambiguator().hidePopup(false); mWebContents.dismissTextHandles(); } hidePopups(); @@ -569,15 +557,17 @@ private void hidePopupsAndPreserveSelection() { if (mWebContents != null) { getSelectionPopupController().destroyActionModeAndKeepSelection(); - destroyPastePopup(); - getTapDisambiguator().hidePopup(false); } hidePopups(); } private void hidePopups() { + if (mWebContents != null) { + destroyPastePopup(); + getTapDisambiguator().hidePopup(false); + getTextSuggestionHost().hidePopups(); + } hideSelectPopupWithCancelMessage(); - mTextSuggestionHost.hidePopups(); } private void restoreSelectionPopupsIfNecessary() { @@ -1141,7 +1131,7 @@ hidePopupsAndPreserveSelection(); getSelectionPopupController().showActionModeOrClearOnFailure(); } - mTextSuggestionHost.hidePopups(); + getTextSuggestionHost().hidePopups(); int rotationDegrees = 0; switch (rotation) {
diff --git a/content/public/android/java/src/org/chromium/content/browser/framehost/RenderFrameHostImpl.java b/content/public/android/java/src/org/chromium/content/browser/framehost/RenderFrameHostImpl.java index 4c53a88..b5a59b7 100644 --- a/content/public/android/java/src/org/chromium/content/browser/framehost/RenderFrameHostImpl.java +++ b/content/public/android/java/src/org/chromium/content/browser/framehost/RenderFrameHostImpl.java
@@ -91,6 +91,11 @@ return mIncognito; } + @Override + public void setHasReceivedUserGesture() { + nativeSetHasReceivedUserGesture(mNativeRenderFrameHostAndroid); + } + /** * Return the AndroidOverlay routing token for this RenderFrameHostImpl. */ @@ -104,4 +109,5 @@ long nativeRenderFrameHostAndroid, Callback<String> callback); private native UnguessableToken nativeGetAndroidOverlayRoutingToken( long nativeRenderFrameHostAndroid); + private native void nativeSetHasReceivedUserGesture(long nativeRenderFrameHostAndroid); }
diff --git a/content/public/android/java/src/org/chromium/content/browser/input/ImeAdapterImpl.java b/content/public/android/java/src/org/chromium/content/browser/input/ImeAdapterImpl.java index 9500d87..6f6b30e 100644 --- a/content/public/android/java/src/org/chromium/content/browser/input/ImeAdapterImpl.java +++ b/content/public/android/java/src/org/chromium/content/browser/input/ImeAdapterImpl.java
@@ -131,9 +131,6 @@ // True if ImeAdapter is connected to render process. private boolean mIsConnected; - // True if the instance is properly initialized with |init|. - private boolean mInitialized; - /** * {@ResultReceiver} passed in InputMethodManager#showSoftInput}. We need this to scroll to the * editable node at the right timing, which is after input method window shows up. @@ -181,7 +178,7 @@ } private boolean initialized() { - return mInitialized; + return mNativeImeAdapterAndroid != 0; } /** @@ -244,7 +241,6 @@ mCursorAnchorInfoController = null; } mNativeImeAdapterAndroid = nativeInit(mWebContents); - mInitialized = true; } @Override @@ -468,6 +464,7 @@ * Show soft keyboard only if it is the current keyboard configuration. */ private void showSoftKeyboard() { + if (!isValid()) return; if (DEBUG_LOGS) Log.i(TAG, "showSoftKeyboard"); mInputMethodManagerWrapper.showSoftInput(mContainerView, 0, getNewShowKeyboardReceiver()); if (mContainerView.getResources().getConfiguration().keyboard @@ -531,6 +528,7 @@ * Hide soft keyboard. */ private void hideKeyboard() { + if (!isValid()) return; if (DEBUG_LOGS) Log.i(TAG, "hideKeyboard"); View view = mContainerView; if (mInputMethodManagerWrapper.isActive(view)) { @@ -553,6 +551,7 @@ * Call this when keyboard configuration has changed. */ public void onKeyboardConfigurationChanged(Configuration newConfig) { + if (!isValid()) return; // If configuration unchanged, do nothing. if (mCurrentConfig.keyboard == newConfig.keyboard && mCurrentConfig.keyboardHidden == newConfig.keyboardHidden @@ -675,6 +674,7 @@ * Restart input (finish composition and change EditorInfo, such as input type). */ void restartInput() { + if (!isValid()) return; // This will eventually cause input method manager to call View#onCreateInputConnection(). mInputMethodManagerWrapper.restartInput(mContainerView); if (mInputConnection != null) mInputConnection.onRestartInputOnUiThread();
diff --git a/content/public/android/java/src/org/chromium/content/browser/input/TextSuggestionHost.java b/content/public/android/java/src/org/chromium/content/browser/input/TextSuggestionHost.java index 80d01ee..e706f9e 100644 --- a/content/public/android/java/src/org/chromium/content/browser/input/TextSuggestionHost.java +++ b/content/public/android/java/src/org/chromium/content/browser/input/TextSuggestionHost.java
@@ -13,6 +13,8 @@ import org.chromium.content.browser.WindowAndroidChangedObserver; import org.chromium.content.browser.WindowEventObserver; import org.chromium.content.browser.webcontents.WebContentsImpl; +import org.chromium.content.browser.webcontents.WebContentsUserData; +import org.chromium.content.browser.webcontents.WebContentsUserData.UserDataFactory; import org.chromium.content_public.browser.WebContents; import org.chromium.ui.base.WindowAndroid; @@ -24,9 +26,9 @@ @JNINamespace("content") public class TextSuggestionHost implements WindowEventObserver, WindowAndroidChangedObserver { private long mNativeTextSuggestionHost; - private final Context mContext; private final WebContentsImpl mWebContents; + private Context mContext; private View mContainerView; private boolean mIsAttachedToWindow; private WindowAndroid mWindowAndroid; @@ -34,13 +36,58 @@ private SpellCheckPopupWindow mSpellCheckPopupWindow; private TextSuggestionsPopupWindow mTextSuggestionsPopupWindow; - public TextSuggestionHost( - Context context, WebContentsImpl webContents, WindowAndroid windowAndroid, View view) { + private boolean mInitialized; + + private static final class UserDataFactoryLazyHolder { + private static final UserDataFactory<TextSuggestionHost> INSTANCE = TextSuggestionHost::new; + } + + /** + * Create {@link TextSuggestionHost} instance. + * @param context Context for action mode. + * @param webContents WebContents instance. + * @param windowAndroid The current WindowAndroid instance. + * @param view Container view. + */ + public static TextSuggestionHost create( + Context context, WebContents webContents, WindowAndroid windowAndroid, View view) { + TextSuggestionHost host = WebContentsUserData.fromWebContents( + webContents, TextSuggestionHost.class, UserDataFactoryLazyHolder.INSTANCE); + assert host != null; + assert !host.initialized(); + host.init(context, windowAndroid, view); + return host; + } + + /** + * Get {@link TextSuggestionHost} object used for the give WebContents. + * {@link #create()} should precede any calls to this. + * @param webContents {@link WebContents} object. + * @return {@link TextSuggestionHost} object. {@code null} if not available because + * {@link #create()} is not called yet. + */ + public static TextSuggestionHost fromWebContents(WebContents webContents) { + return WebContentsUserData.fromWebContents(webContents, TextSuggestionHost.class, null); + } + + /** + * Create {@link TextSuggestionHost} instance. + * @param webContents WebContents instance. + */ + public TextSuggestionHost(WebContents webContents) { + mWebContents = (WebContentsImpl) webContents; + } + + private void init(Context context, WindowAndroid windowAndroid, View view) { mContext = context; - mWebContents = webContents; mWindowAndroid = windowAndroid; mContainerView = view; - mNativeTextSuggestionHost = nativeInit(webContents); + mNativeTextSuggestionHost = nativeInit(mWebContents); + mInitialized = true; + } + + private boolean initialized() { + return mInitialized; } private float getContentOffsetYPix() {
diff --git a/content/public/android/java/src/org/chromium/content/browser/remoteobjects/RemoteObjectImpl.java b/content/public/android/java/src/org/chromium/content/browser/remoteobjects/RemoteObjectImpl.java index 6a59f0b..ed6b692 100644 --- a/content/public/android/java/src/org/chromium/content/browser/remoteobjects/RemoteObjectImpl.java +++ b/content/public/android/java/src/org/chromium/content/browser/remoteobjects/RemoteObjectImpl.java
@@ -12,6 +12,7 @@ import java.lang.annotation.Annotation; import java.lang.ref.WeakReference; +import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.List; @@ -133,9 +134,25 @@ Object result = null; try { result = method.invoke(target, args); - } catch (Exception e) { - // TODO(jbroman): Handle this. (IllegalAccessException and ones thrown by the method - // internally.) + } catch (IllegalAccessException | IllegalArgumentException | NullPointerException e) { + // These should never happen. + // + // IllegalAccessException: + // java.lang.Class#getMethods returns only public members, so |mMethods| should never + // contain any method for which IllegalAccessException would be thrown. + // + // IllegalArgumentException: + // Argument coercion logic is responsible for creating objects of a suitable Java + // type. + // TODO(jbroman): Actually write said coercion logic. + // + // NullPointerException: + // A user of this class is responsible for ensuring that the target is not collected. + throw new RuntimeException(e); + } catch (InvocationTargetException e) { + e.getCause().printStackTrace(); + callback.call(makeErrorResult(RemoteInvocationError.EXCEPTION_THROWN)); + return; } RemoteInvocationResult mojoResult = convertResult(result);
diff --git a/content/public/android/java/src/org/chromium/content_public/browser/RenderFrameHost.java b/content/public/android/java/src/org/chromium/content_public/browser/RenderFrameHost.java index 503b0bc..e87bda0 100644 --- a/content/public/android/java/src/org/chromium/content_public/browser/RenderFrameHost.java +++ b/content/public/android/java/src/org/chromium/content_public/browser/RenderFrameHost.java
@@ -33,4 +33,9 @@ * @return The InterfaceProvider for the frame. */ InterfaceProvider getRemoteInterfaces(); + + /** + * Notifies the native RenderFrameHost of a user gesture. + */ + void setHasReceivedUserGesture(); }
diff --git a/content/public/android/java/src/org/chromium/content_public/browser/WebContentsObserver.java b/content/public/android/java/src/org/chromium/content_public/browser/WebContentsObserver.java index 0e8426cf..5f66f1b 100644 --- a/content/public/android/java/src/org/chromium/content_public/browser/WebContentsObserver.java +++ b/content/public/android/java/src/org/chromium/content_public/browser/WebContentsObserver.java
@@ -16,7 +16,7 @@ // TODO(jdduke): Remove the destroy method and hold observer embedders // responsible for explicit observer detachment. // Using a weak reference avoids cycles that might prevent GC of WebView's WebContents. - private WeakReference<WebContents> mWebContents; + protected WeakReference<WebContents> mWebContents; public WebContentsObserver(WebContents webContents) { mWebContents = new WeakReference<WebContents>(webContents);
diff --git a/content/public/android/javatests/src/org/chromium/content/browser/PopupZoomerTest.java b/content/public/android/javatests/src/org/chromium/content/browser/PopupZoomerTest.java index 9ac1bbe..3e326573 100644 --- a/content/public/android/javatests/src/org/chromium/content/browser/PopupZoomerTest.java +++ b/content/public/android/javatests/src/org/chromium/content/browser/PopupZoomerTest.java
@@ -23,11 +23,8 @@ import org.chromium.base.ThreadUtils; import org.chromium.base.test.util.Feature; -import org.chromium.content.browser.input.TextSuggestionHost; import org.chromium.content.browser.test.ContentJUnit4ClassRunner; -import org.chromium.content.browser.test.util.TestInputMethodManagerWrapper; import org.chromium.content.browser.webcontents.WebContentsImpl; -import org.chromium.content_public.browser.ImeAdapter; import org.chromium.content_public.browser.WebContents; import org.chromium.content_shell_apk.ContentShellActivityTestRule; @@ -101,15 +98,9 @@ WebContents webContents = mActivityTestRule.getContentViewCore().getWebContents(); mContentViewCore = (ContentViewCoreImpl) ContentViewCore.create(context, ""); mContentViewCore.setWebContentsForTesting((WebContentsImpl) webContents); - ViewGroup containerView = mActivityTestRule.getContentViewCore().getContainerView(); - ImeAdapter imeAdapter = ImeAdapter.fromWebContents(webContents); - imeAdapter.setInputMethodManagerWrapperForTest( - TestInputMethodManagerWrapper.create(imeAdapter)); - mPopupZoomer = createPopupZoomerForTest( - InstrumentationRegistry.getTargetContext(), containerView); + mPopupZoomer = createPopupZoomerForTest(InstrumentationRegistry.getTargetContext(), + mActivityTestRule.getContentViewCore().getContainerView()); TapDisambiguator.fromWebContents(webContents).setPopupZoomerForTest(mPopupZoomer); - mContentViewCore.setTextSuggestionHostForTesting(new TextSuggestionHost( - context, (WebContentsImpl) webContents, null, containerView)); } }); }
diff --git a/content/public/android/javatests/src/org/chromium/content/browser/ScreenOrientationListenerTest.java b/content/public/android/javatests/src/org/chromium/content/browser/ScreenOrientationListenerTest.java index 295b2f5..3b2d3c1 100644 --- a/content/public/android/javatests/src/org/chromium/content/browser/ScreenOrientationListenerTest.java +++ b/content/public/android/javatests/src/org/chromium/content/browser/ScreenOrientationListenerTest.java
@@ -257,6 +257,7 @@ @Test @MediumTest @Feature({"ScreenOrientation"}) + @DisabledTest(message = "crbug.com/807356") public void testBasicValues() throws Exception { int rotation = lockOrientationValueAndWait(ScreenOrientationValues.LANDSCAPE_PRIMARY); Assert.assertEquals(
diff --git a/content/public/android/javatests/src/org/chromium/content/browser/input/TextSuggestionMenuTest.java b/content/public/android/javatests/src/org/chromium/content/browser/input/TextSuggestionMenuTest.java index 82e65c90..0a8f80e8 100644 --- a/content/public/android/javatests/src/org/chromium/content/browser/input/TextSuggestionMenuTest.java +++ b/content/public/android/javatests/src/org/chromium/content/browser/input/TextSuggestionMenuTest.java
@@ -55,7 +55,7 @@ public void testDeleteWordMarkedWithSuggestionMarker() throws InterruptedException, Throwable, TimeoutException { final ContentViewCore cvc = mRule.getContentViewCore(); - WebContents webContents = cvc.getWebContents(); + WebContents webContents = mRule.getWebContents(); DOMUtils.focusNode(webContents, "div"); @@ -66,22 +66,22 @@ mRule.commitText(textToCommit, 1); DOMUtils.clickNode(cvc, "div"); - waitForMenuToShow(cvc); + waitForMenuToShow(webContents); - TouchCommon.singleClickView(getDeleteButton(cvc)); + TouchCommon.singleClickView(getDeleteButton(webContents)); CriteriaHelper.pollInstrumentationThread(new Criteria() { @Override public boolean isSatisfied() { try { - return DOMUtils.getNodeContents(cvc.getWebContents(), "div").equals(""); + return DOMUtils.getNodeContents(webContents, "div").equals(""); } catch (InterruptedException | TimeoutException e) { return false; } } }); - waitForMenuToHide(cvc); + waitForMenuToHide(webContents); } @Test @@ -89,7 +89,7 @@ public void testDeleteWordMarkedWithSpellingMarker() throws InterruptedException, Throwable, TimeoutException { final ContentViewCore cvc = mRule.getContentViewCore(); - WebContents webContents = cvc.getWebContents(); + WebContents webContents = mRule.getWebContents(); DOMUtils.focusNode(webContents, "div"); @@ -121,29 +121,29 @@ + "internals.setMarker(document, range, 'spelling');"); DOMUtils.clickNode(cvc, "div"); - waitForMenuToShow(cvc); + waitForMenuToShow(webContents); - TouchCommon.singleClickView(getDeleteButton(cvc)); + TouchCommon.singleClickView(getDeleteButton(webContents)); CriteriaHelper.pollInstrumentationThread(new Criteria() { @Override public boolean isSatisfied() { try { - return DOMUtils.getNodeContents(cvc.getWebContents(), "div").equals(""); + return DOMUtils.getNodeContents(mRule.getWebContents(), "div").equals(""); } catch (InterruptedException | TimeoutException e) { return false; } } }); - waitForMenuToHide(cvc); + waitForMenuToHide(webContents); } @Test @LargeTest public void testApplySuggestion() throws InterruptedException, Throwable, TimeoutException { final ContentViewCore cvc = mRule.getContentViewCore(); - WebContents webContents = cvc.getWebContents(); + WebContents webContents = mRule.getWebContents(); DOMUtils.focusNode(webContents, "div"); @@ -187,27 +187,27 @@ }); DOMUtils.clickNode(cvc, "span"); - waitForMenuToShow(cvc); + waitForMenuToShow(webContents); // There should be 5 child views: 4 suggestions plus the list footer. - Assert.assertEquals(5, getSuggestionList(cvc).getChildCount()); + Assert.assertEquals(5, getSuggestionList(webContents).getChildCount()); - Assert.assertEquals( - "hello suggestion1", ((TextView) getSuggestionButton(cvc, 0)).getText().toString()); - Assert.assertEquals( - "hello suggestion2", ((TextView) getSuggestionButton(cvc, 1)).getText().toString()); - Assert.assertEquals( - "suggestion3", ((TextView) getSuggestionButton(cvc, 2)).getText().toString()); - Assert.assertEquals( - "suggestion4", ((TextView) getSuggestionButton(cvc, 3)).getText().toString()); + Assert.assertEquals("hello suggestion1", + ((TextView) getSuggestionButton(webContents, 0)).getText().toString()); + Assert.assertEquals("hello suggestion2", + ((TextView) getSuggestionButton(webContents, 1)).getText().toString()); + Assert.assertEquals("suggestion3", + ((TextView) getSuggestionButton(webContents, 2)).getText().toString()); + Assert.assertEquals("suggestion4", + ((TextView) getSuggestionButton(webContents, 3)).getText().toString()); - TouchCommon.singleClickView(getSuggestionButton(cvc, 2)); + TouchCommon.singleClickView(getSuggestionButton(webContents, 2)); CriteriaHelper.pollInstrumentationThread(new Criteria() { @Override public boolean isSatisfied() { try { - return DOMUtils.getNodeContents(cvc.getWebContents(), "div") + return DOMUtils.getNodeContents(mRule.getWebContents(), "div") .equals("suggestion3"); } catch (InterruptedException | TimeoutException e) { return false; @@ -215,7 +215,7 @@ } }); - waitForMenuToHide(cvc); + waitForMenuToHide(webContents); } @Test @@ -223,7 +223,7 @@ public void testApplyMisspellingSuggestion() throws InterruptedException, Throwable, TimeoutException { final ContentViewCore cvc = mRule.getContentViewCore(); - WebContents webContents = cvc.getWebContents(); + WebContents webContents = mRule.getWebContents(); DOMUtils.focusNode(webContents, "div"); @@ -237,21 +237,21 @@ mRule.commitText(textToCommit, 1); DOMUtils.clickNode(cvc, "span"); - waitForMenuToShow(cvc); + waitForMenuToShow(webContents); // There should be 2 child views: 1 suggestion plus the list footer. - Assert.assertEquals(2, getSuggestionList(cvc).getChildCount()); + Assert.assertEquals(2, getSuggestionList(webContents).getChildCount()); - Assert.assertEquals( - "replacement", ((TextView) getSuggestionButton(cvc, 0)).getText().toString()); + Assert.assertEquals("replacement", + ((TextView) getSuggestionButton(webContents, 0)).getText().toString()); - TouchCommon.singleClickView(getSuggestionButton(cvc, 0)); + TouchCommon.singleClickView(getSuggestionButton(webContents, 0)); CriteriaHelper.pollInstrumentationThread(new Criteria() { @Override public boolean isSatisfied() { try { - return DOMUtils.getNodeContents(cvc.getWebContents(), "div") + return DOMUtils.getNodeContents(mRule.getWebContents(), "div") .equals("replacement"); } catch (InterruptedException | TimeoutException e) { return false; @@ -259,7 +259,7 @@ } }); - waitForMenuToHide(cvc); + waitForMenuToHide(webContents); // Verify that the suggestion marker was replaced. Assert.assertEquals("0", @@ -272,7 +272,7 @@ @LargeTest public void suggestionMenuDismissal() throws InterruptedException, Throwable, TimeoutException { final ContentViewCore cvc = mRule.getContentViewCore(); - WebContents webContents = cvc.getWebContents(); + WebContents webContents = mRule.getWebContents(); DOMUtils.focusNode(webContents, "div"); @@ -283,24 +283,24 @@ mRule.commitText(textToCommit, 1); DOMUtils.clickNode(cvc, "div"); - waitForMenuToShow(cvc); + waitForMenuToShow(webContents); ThreadUtils.runOnUiThreadBlocking(new Runnable() { @Override public void run() { - cvc.getTextSuggestionHostForTesting() + TextSuggestionHost.fromWebContents(webContents) .getTextSuggestionsPopupWindowForTesting() .dismiss(); } }); - waitForMenuToHide(cvc); + waitForMenuToHide(webContents); } - private void waitForMenuToShow(ContentViewCore cvc) { + private void waitForMenuToShow(WebContents webContents) { CriteriaHelper.pollUiThread(new Criteria() { @Override public boolean isSatisfied() { - View deleteButton = getDeleteButton(cvc); + View deleteButton = getDeleteButton(webContents); if (deleteButton == null) { return false; } @@ -314,32 +314,35 @@ }); } - private void waitForMenuToHide(ContentViewCore cvc) { + private void waitForMenuToHide(WebContents webContents) { CriteriaHelper.pollUiThread(new Criteria() { @Override public boolean isSatisfied() { SuggestionsPopupWindow suggestionsPopupWindow = - cvc.getTextSuggestionHostForTesting() + TextSuggestionHost.fromWebContents(webContents) .getTextSuggestionsPopupWindowForTesting(); SuggestionsPopupWindow spellCheckPopupWindow = - cvc.getTextSuggestionHostForTesting().getSpellCheckPopupWindowForTesting(); + TextSuggestionHost.fromWebContents(webContents) + .getSpellCheckPopupWindowForTesting(); return suggestionsPopupWindow == null && spellCheckPopupWindow == null; } }); } - private View getContentView(ContentViewCore cvc) { + private View getContentView(WebContents webContents) { SuggestionsPopupWindow suggestionsPopupWindow = - cvc.getTextSuggestionHostForTesting().getTextSuggestionsPopupWindowForTesting(); + TextSuggestionHost.fromWebContents(webContents) + .getTextSuggestionsPopupWindowForTesting(); if (suggestionsPopupWindow != null) { return suggestionsPopupWindow.getContentViewForTesting(); } SuggestionsPopupWindow spellCheckPopupWindow = - cvc.getTextSuggestionHostForTesting().getSpellCheckPopupWindowForTesting(); + TextSuggestionHost.fromWebContents(webContents) + .getSpellCheckPopupWindowForTesting(); if (spellCheckPopupWindow != null) { return spellCheckPopupWindow.getContentViewForTesting(); @@ -348,17 +351,17 @@ return null; } - private ListView getSuggestionList(ContentViewCore cvc) { - View contentView = getContentView(cvc); + private ListView getSuggestionList(WebContents webContents) { + View contentView = getContentView(webContents); return (ListView) contentView.findViewById(R.id.suggestionContainer); } - private View getSuggestionButton(ContentViewCore cvc, int suggestionIndex) { - return getSuggestionList(cvc).getChildAt(suggestionIndex); + private View getSuggestionButton(WebContents webContents, int suggestionIndex) { + return getSuggestionList(webContents).getChildAt(suggestionIndex); } - private View getDeleteButton(ContentViewCore cvc) { - View contentView = getContentView(cvc); + private View getDeleteButton(WebContents webContents) { + View contentView = getContentView(webContents); if (contentView == null) { return null; }
diff --git a/content/public/android/junit/src/org/chromium/content/browser/remoteobjects/RemoteObjectImplTest.java b/content/public/android/junit/src/org/chromium/content/browser/remoteobjects/RemoteObjectImplTest.java index 6092cf8..0b7919a 100644 --- a/content/public/android/junit/src/org/chromium/content/browser/remoteobjects/RemoteObjectImplTest.java +++ b/content/public/android/junit/src/org/chromium/content/browser/remoteobjects/RemoteObjectImplTest.java
@@ -179,6 +179,45 @@ verify(response, times(2)).call(resultIsOk()); } + /** + * Reports to the runnable it is given when its static method is called. + * Works around the fact that a static method cannot capture variables. + */ + static class ObjectWithStaticMethod { + static Runnable sRunnable; + + @TestJavascriptInterface + public static void staticMethod() { + sRunnable.run(); + } + } + + @Test + public void testStaticMethod() { + // Static methods should work just like non-static ones. + + Object target = new ObjectWithStaticMethod(); + RemoteObject remoteObject = new RemoteObjectImpl(target, TestJavascriptInterface.class); + + Runnable runnable = mock(Runnable.class); + ObjectWithStaticMethod.sRunnable = runnable; + RemoteObject.InvokeMethodResponse response = mock(RemoteObject.InvokeMethodResponse.class); + remoteObject.invokeMethod("staticMethod", new RemoteInvocationArgument[] {}, response); + ObjectWithStaticMethod.sRunnable = null; + verify(runnable).run(); + verify(response).call(resultIsOk()); + + RemoteObject.HasMethodResponse hasMethodResponse = + mock(RemoteObject.HasMethodResponse.class); + remoteObject.hasMethod("staticMethod", hasMethodResponse); + verify(hasMethodResponse).call(true); + + RemoteObject.GetMethodsResponse getMethodsResponse = + mock(RemoteObject.GetMethodsResponse.class); + remoteObject.getMethods(getMethodsResponse); + verify(getMethodsResponse).call(aryEq(new String[] {"staticMethod"})); + } + @Test public void testInvokeMethodNotFound() { Object target = new Object() { @@ -234,6 +273,23 @@ verify(auditor, never()).onObjectGetClassInvocationAttempt(); } + @Test + public void testInvocationTargetException() { + Object target = new Object() { + @TestJavascriptInterface + public void exceptionThrowingMethod() throws Exception { + throw new Exception("This exception is expected during test. Do not be alarmed."); + } + }; + + RemoteObject remoteObject = new RemoteObjectImpl(target, TestJavascriptInterface.class); + RemoteObject.InvokeMethodResponse response = mock(RemoteObject.InvokeMethodResponse.class); + remoteObject.invokeMethod( + "exceptionThrowingMethod", new RemoteInvocationArgument[] {}, response); + + verify(response).call(resultHasError(RemoteInvocationError.EXCEPTION_THROWN)); + } + private RemoteInvocationResult resultHasError(final int error) { return ArgumentMatchers.argThat(result -> result.error == error); }
diff --git a/content/public/browser/BUILD.gn b/content/public/browser/BUILD.gn index 0bcde10..05eeca8 100644 --- a/content/public/browser/BUILD.gn +++ b/content/public/browser/BUILD.gn
@@ -107,7 +107,6 @@ "devtools_socket_factory.h", "discardable_shared_memory_manager.h", "dom_storage_context.h", - "download_danger_type.h", "download_interrupt_reason_values.h", "download_interrupt_reasons.h", "download_item.h", @@ -116,9 +115,6 @@ "download_manager_delegate.cc", "download_manager_delegate.h", "download_request_utils.h", - "download_save_info.cc", - "download_save_info.h", - "download_source.h", "download_url_parameters.cc", "download_url_parameters.h", "favicon_status.cc", @@ -310,6 +306,7 @@ ] public_deps = [ + "//components/download/public/common:public", "//content/public/common:common_sources", "//ipc", "//mojo/public/cpp/bindings",
diff --git a/content/public/browser/DEPS b/content/public/browser/DEPS index d3c499c4..29b8442 100644 --- a/content/public/browser/DEPS +++ b/content/public/browser/DEPS
@@ -1,4 +1,7 @@ include_rules = [ + # components/download are needed for providing the download feature. + # TODO(qinmin): move it to services/download when download becomes a service. + "+components/download/public/common", "+components/viz/common", "+device/geolocation/public/cpp", "+device/usb/public/interfaces",
diff --git a/content/public/browser/download_item.h b/content/public/browser/download_item.h index bb4e5da..85b6a22 100644 --- a/content/public/browser/download_item.h +++ b/content/public/browser/download_item.h
@@ -28,7 +28,7 @@ #include "base/memory/ref_counted.h" #include "base/strings/string16.h" #include "base/supports_user_data.h" -#include "content/public/browser/download_danger_type.h" +#include "components/download/public/common/download_danger_type.h" #include "content/public/browser/download_interrupt_reasons.h" #include "ui/base/page_transition_types.h" @@ -353,7 +353,7 @@ virtual bool IsDangerous() const = 0; // Why |safety_state_| is not SAFE. - virtual DownloadDangerType GetDangerType() const = 0; + virtual download::DownloadDangerType GetDangerType() const = 0; // Progress State accessors ----------------------------------------------- @@ -447,7 +447,7 @@ // TODO(crbug.com/733291): Move DownloadInterruptReason out of here and add a // new Interrupt method instead. Same for other methods supporting // interruptions. - virtual void OnContentCheckCompleted(DownloadDangerType danger_type, + virtual void OnContentCheckCompleted(download::DownloadDangerType danger_type, DownloadInterruptReason reason) = 0; // Mark the download to be auto-opened when completed.
diff --git a/content/public/browser/download_manager.h b/content/public/browser/download_manager.h index fbd510d4..7e734ba 100644 --- a/content/public/browser/download_manager.h +++ b/content/public/browser/download_manager.h
@@ -165,7 +165,7 @@ int64_t total_bytes, const std::string& hash, DownloadItem::DownloadState state, - DownloadDangerType danger_type, + download::DownloadDangerType danger_type, DownloadInterruptReason interrupt_reason, bool opened, base::Time last_access_time,
diff --git a/content/public/browser/download_manager_delegate.h b/content/public/browser/download_manager_delegate.h index 7194560..bb7eeb3 100644 --- a/content/public/browser/download_manager_delegate.h +++ b/content/public/browser/download_manager_delegate.h
@@ -11,8 +11,8 @@ #include "base/files/file_path.h" #include "base/logging.h" #include "base/time/time.h" +#include "components/download/public/common/download_danger_type.h" #include "content/common/content_export.h" -#include "content/public/browser/download_danger_type.h" #include "content/public/browser/download_item.h" #include "content/public/browser/resource_request_info.h" #include "content/public/browser/save_page_type.h" @@ -61,7 +61,7 @@ using DownloadTargetCallback = base::Callback<void(const base::FilePath& target_path, DownloadItem::TargetDisposition disposition, - DownloadDangerType danger_type, + download::DownloadDangerType danger_type, const base::FilePath& intermediate_path, DownloadInterruptReason interrupt_reason)>;
diff --git a/content/public/browser/download_url_parameters.cc b/content/public/browser/download_url_parameters.cc index 3151376..3aa576cac 100644 --- a/content/public/browser/download_url_parameters.cc +++ b/content/public/browser/download_url_parameters.cc
@@ -5,8 +5,8 @@ #include "content/public/browser/download_url_parameters.h" #include "base/callback.h" +#include "components/download/public/common/download_save_info.h" #include "content/public/browser/browser_context.h" -#include "content/public/browser/download_save_info.h" #include "content/public/browser/render_frame_host.h" #include "content/public/browser/render_process_host.h" #include "content/public/browser/render_view_host.h" @@ -48,7 +48,7 @@ fetch_error_body_(false), transient_(false), traffic_annotation_(traffic_annotation), - download_source_(DownloadSource::UNKNOWN) {} + download_source_(download::DownloadSource::UNKNOWN) {} DownloadUrlParameters::~DownloadUrlParameters() { }
diff --git a/content/public/browser/download_url_parameters.h b/content/public/browser/download_url_parameters.h index f1584852..f658106 100644 --- a/content/public/browser/download_url_parameters.h +++ b/content/public/browser/download_url_parameters.h
@@ -16,9 +16,9 @@ #include "base/macros.h" #include "base/memory/ref_counted.h" #include "base/optional.h" +#include "components/download/public/common/download_save_info.h" +#include "components/download/public/common/download_source.h" #include "content/public/browser/download_interrupt_reasons.h" -#include "content/public/browser/download_save_info.h" -#include "content/public/browser/download_source.h" #include "content/public/common/referrer.h" #include "net/traffic_annotation/network_traffic_annotation.h" #include "net/url_request/url_request_context_getter.h" @@ -246,7 +246,7 @@ } // Sets the download source, which will be used in metrics recording. - void set_download_source(DownloadSource download_source) { + void set_download_source(download::DownloadSource download_source) { download_source_ = download_source; } @@ -301,13 +301,13 @@ // STATE CHANGING: All save_info_ sub-objects will be in an indeterminate // state following this call. - DownloadSaveInfo GetSaveInfo() { return std::move(save_info_); } + download::DownloadSaveInfo GetSaveInfo() { return std::move(save_info_); } const net::NetworkTrafficAnnotationTag& GetNetworkTrafficAnnotation() { return traffic_annotation_; } - DownloadSource download_source() const { return download_source_; } + download::DownloadSource download_source() const { return download_source_; } private: OnStartedCallback callback_; @@ -327,7 +327,7 @@ int render_view_host_routing_id_; int render_frame_host_routing_id_; scoped_refptr<net::URLRequestContextGetter> url_request_context_getter_; - DownloadSaveInfo save_info_; + download::DownloadSaveInfo save_info_; GURL url_; bool do_not_prompt_for_login_; bool fetch_error_body_; @@ -336,7 +336,7 @@ std::unique_ptr<storage::BlobDataHandle> blob_data_handle_; const net::NetworkTrafficAnnotationTag traffic_annotation_; std::string request_origin_; - DownloadSource download_source_; + download::DownloadSource download_source_; DISALLOW_COPY_AND_ASSIGN(DownloadUrlParameters); };
diff --git a/content/public/browser/navigation_controller.cc b/content/public/browser/navigation_controller.cc index 9347868..a6850f2 100644 --- a/content/public/browser/navigation_controller.cc +++ b/content/public/browser/navigation_controller.cc
@@ -21,8 +21,8 @@ should_replace_current_entry(false), #if defined(OS_ANDROID) intent_received_timestamp(0), - has_user_gesture(false), #endif + has_user_gesture(false), should_clear_history_list(false), started_from_context_menu(false) { } @@ -47,8 +47,8 @@ should_replace_current_entry(false), #if defined(OS_ANDROID) intent_received_timestamp(other.intent_received_timestamp), - has_user_gesture(other.has_user_gesture), #endif + has_user_gesture(other.has_user_gesture), should_clear_history_list(false), started_from_context_menu(other.started_from_context_menu) { } @@ -73,8 +73,8 @@ should_clear_history_list = other.should_clear_history_list; #if defined(OS_ANDROID) intent_received_timestamp = other.intent_received_timestamp; - has_user_gesture = other.has_user_gesture; #endif + has_user_gesture = other.has_user_gesture; started_from_context_menu = other.started_from_context_menu; return *this;
diff --git a/content/public/browser/navigation_controller.h b/content/public/browser/navigation_controller.h index 3ac1454..aacd0d1c 100644 --- a/content/public/browser/navigation_controller.h +++ b/content/public/browser/navigation_controller.h
@@ -178,12 +178,11 @@ // the original intent that prompted the load (in milliseconds active time // since boot). int64_t intent_received_timestamp; - - // When Chrome launches the intent chooser, user can select Chrome itself to - // open the intent. In this case, we should carry over the user gesture. - bool has_user_gesture; #endif + // Indicates that the navigation was triggered by a user gesture. + bool has_user_gesture; + // Indicates that during this navigation, the session history should be // cleared such that the resulting page is the first and only entry of the // session history.
diff --git a/content/public/common/BUILD.gn b/content/public/common/BUILD.gn index 3898737..e5c26e1 100644 --- a/content/public/common/BUILD.gn +++ b/content/public/common/BUILD.gn
@@ -261,6 +261,7 @@ "//ipc", "//media/capture:capture_base", "//mojo/edk/system", + "//mojo/public/cpp/base:mojom_traits", "//mojo/public/cpp/bindings", "//net", "//services/network/public/cpp",
diff --git a/content/public/common/content_features.cc b/content/public/common/content_features.cc index 69112355..03c678f 100644 --- a/content/public/common/content_features.cc +++ b/content/public/common/content_features.cc
@@ -381,6 +381,11 @@ "TurnOff2DAndOpacityCompositorAnimations", base::FEATURE_DISABLED_BY_DEFAULT}; +// Enables unified touch adjustment which adjusts touch events target to a best +// nearby node. +const base::Feature kUnifiedTouchAdjustment{"UnifiedTouchAdjustment", + base::FEATURE_DISABLED_BY_DEFAULT}; + // Use Feature Policy to gate the use of permission features like midi, // geolocation, camera, microphone, etc. const base::Feature kUseFeaturePolicyForPermissions{ @@ -564,4 +569,8 @@ #endif } +// Enables code caching after executing the script. +const base::Feature kCodeCacheAfterExecute{"CodeCacheAfterExecute", + base::FEATURE_DISABLED_BY_DEFAULT}; + } // namespace features
diff --git a/content/public/common/content_features.h b/content/public/common/content_features.h index da1fb29..23dc5824 100644 --- a/content/public/common/content_features.h +++ b/content/public/common/content_features.h
@@ -95,6 +95,7 @@ CONTENT_EXPORT extern const base::Feature kTouchpadAndWheelScrollLatching; CONTENT_EXPORT extern const base::Feature kTurnOff2DAndOpacityCompositorAnimations; +CONTENT_EXPORT extern const base::Feature kUnifiedTouchAdjustment; CONTENT_EXPORT extern const base::Feature kUseFeaturePolicyForPermissions; CONTENT_EXPORT extern const base::Feature kUseMojoAudioInputStreamFactory; CONTENT_EXPORT extern const base::Feature kUseMojoAudioOutputStreamFactory; @@ -102,6 +103,7 @@ CONTENT_EXPORT extern const base::Feature kV8ContextSnapshot; CONTENT_EXPORT extern const base::Feature kV8BackgroundCompile; CONTENT_EXPORT extern const base::Feature kV8VmFuture; +CONTENT_EXPORT extern const base::Feature kCodeCacheAfterExecute; CONTENT_EXPORT extern const base::Feature kVibrateRequiresUserGesture; CONTENT_EXPORT extern const base::Feature kWebAssembly; CONTENT_EXPORT extern const base::Feature kWebAssemblyStreaming;
diff --git a/content/public/common/shared_url_loader_factory.h b/content/public/common/shared_url_loader_factory.h index 0871edc..6fd9dcb 100644 --- a/content/public/common/shared_url_loader_factory.h +++ b/content/public/common/shared_url_loader_factory.h
@@ -51,6 +51,7 @@ // Skip appcache and service worker if this flag is set to true. bool bypass_custom_network_loader = false; }; + static scoped_refptr<SharedURLLoaderFactory> Create( std::unique_ptr<SharedURLLoaderFactoryInfo> info); @@ -62,7 +63,7 @@ const network::ResourceRequest& request, network::mojom::URLLoaderClientPtr client, const net::MutableNetworkTrafficAnnotationTag& traffic_annotation, - const Constraints& constaints = kDefaultConstraints) = 0; + const Constraints& constraints = kDefaultConstraints) = 0; virtual std::unique_ptr<SharedURLLoaderFactoryInfo> Clone() = 0;
diff --git a/content/public/common/simple_url_loader_unittest.cc b/content/public/common/simple_url_loader_unittest.cc index d757b75..053edb2d 100644 --- a/content/public/common/simple_url_loader_unittest.cc +++ b/content/public/common/simple_url_loader_unittest.cc
@@ -1347,8 +1347,10 @@ status.error_code = net::OK; status.decoded_body_length = CountBytesToSend() - 1; client_->OnComplete(status); + break; } case TestLoaderEvent::kClientPipeClosed: { + DCHECK(client_); EXPECT_TRUE(binding_.is_bound()); client_.reset(); break;
diff --git a/content/public/test/DEPS b/content/public/test/DEPS index cb21546..cbdd1829 100644 --- a/content/public/test/DEPS +++ b/content/public/test/DEPS
@@ -1,6 +1,7 @@ include_rules = [ "-content", "+content/public", + "+components/download/public/common", "+components/viz/common", "+components/viz/service", "+device/geolocation/android/geolocation_jni_registrar.h",
diff --git a/content/public/test/android/BUILD.gn b/content/public/test/android/BUILD.gn index a5781ed9..5088ed38 100644 --- a/content/public/test/android/BUILD.gn +++ b/content/public/test/android/BUILD.gn
@@ -32,7 +32,6 @@ java_files = [ "javatests/src/org/chromium/content/browser/test/ChildProcessAllocatorSettings.java", "javatests/src/org/chromium/content/browser/test/ChildProcessAllocatorSettingsHook.java", - "javatests/src/org/chromium/content/browser/test/ContentInstrumentationTestRunner.java", "javatests/src/org/chromium/content/browser/test/ContentJUnit4ClassRunner.java", "javatests/src/org/chromium/content/browser/test/NativeLibraryTestRule.java", "javatests/src/org/chromium/content/browser/test/util/ClickUtils.java",
diff --git a/content/public/test/android/javatests/src/org/chromium/content/browser/test/ContentInstrumentationTestRunner.java b/content/public/test/android/javatests/src/org/chromium/content/browser/test/ContentInstrumentationTestRunner.java deleted file mode 100644 index df0c3ab..0000000 --- a/content/public/test/android/javatests/src/org/chromium/content/browser/test/ContentInstrumentationTestRunner.java +++ /dev/null
@@ -1,20 +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. - -package org.chromium.content.browser.test; - -import org.chromium.base.test.BaseChromiumInstrumentationTestRunner; -import org.chromium.base.test.BaseTestResult; - -/** - * An instrumentation test runner similar to BaseInstrumentationTestRunner but which also registers - * content specific annotations. - */ -public class ContentInstrumentationTestRunner extends BaseChromiumInstrumentationTestRunner { - @Override - protected void addTestHooks(BaseTestResult result) { - super.addTestHooks(result); - result.addPreTestHook(new ChildProcessAllocatorSettingsHook()); - } -}
diff --git a/content/public/test/android/javatests/src/org/chromium/content/browser/test/util/DOMUtils.java b/content/public/test/android/javatests/src/org/chromium/content/browser/test/util/DOMUtils.java index 0eef38d..3b9a5f56 100644 --- a/content/public/test/android/javatests/src/org/chromium/content/browser/test/util/DOMUtils.java +++ b/content/public/test/android/javatests/src/org/chromium/content/browser/test/util/DOMUtils.java
@@ -8,6 +8,7 @@ import android.graphics.Rect; import android.util.JsonReader; +import android.view.View; import org.junit.Assert; @@ -233,10 +234,32 @@ */ public static boolean clickNode(final ContentViewCore viewCore, String nodeId) throws InterruptedException, TimeoutException { + return clickNode(viewCore, nodeId, true /* goThroughRootAndroidView */); + } + + /** + * Click a DOM node by its id, scrolling it into view first. + * @param viewCore The ContentViewCore in which the node lives. + * @param nodeId The id of the node. + * @param goThroughRootAndroidView Whether the input should be routed through the Root View for + * the CVC. + */ + public static boolean clickNode(final ContentViewCore viewCore, String nodeId, + boolean goThroughRootAndroidView) throws InterruptedException, TimeoutException { scrollNodeIntoView(viewCore.getWebContents(), nodeId); int[] clickTarget = getClickTargetForNode(viewCore, nodeId); - return TouchCommon.singleClickView( - viewCore.getContainerView(), clickTarget[0], clickTarget[1]); + if (goThroughRootAndroidView) { + return TouchCommon.singleClickView( + viewCore.getContainerView(), clickTarget[0], clickTarget[1]); + } else { + // TODO(mthiesse): It should be sufficient to use viewCore.getContainerView() here + // directly, but content offsets are only updated in the EventForwarder when the + // CompositorViewHolder intercepts touch events. + View target = + viewCore.getContainerView().getRootView().findViewById(android.R.id.content); + return TouchCommon.singleClickViewThroughTarget( + viewCore.getContainerView(), target, clickTarget[0], clickTarget[1]); + } } /** @@ -256,8 +279,7 @@ * @param viewCore The ContentViewCore in which the node lives. * @param rect The rect to click. */ - public static boolean clickRect(final ContentViewCore viewCore, Rect rect) - throws InterruptedException, TimeoutException { + public static boolean clickRect(final ContentViewCore viewCore, Rect rect) { int[] clickTarget = getClickTargetForBounds(viewCore, rect); return TouchCommon.singleClickView( viewCore.getContainerView(), clickTarget[0], clickTarget[1]); @@ -280,7 +302,7 @@ * <p>Note that content view should be located in the current position for a foreseeable * amount of time because this involves sleep to simulate touch to long press transition. * @param viewCore The ContentViewCore in which the node lives. - * @param nodeId The id of the node. + * @param jsCode js code that returns an element. */ public static void longPressNodeByJs(final ContentViewCore viewCore, String jsCode) throws InterruptedException, TimeoutException {
diff --git a/content/public/test/android/javatests/src/org/chromium/content/browser/test/util/TestContentViewCore.java b/content/public/test/android/javatests/src/org/chromium/content/browser/test/util/TestContentViewCore.java index 1b973fd6..7338bd9f 100644 --- a/content/public/test/android/javatests/src/org/chromium/content/browser/test/util/TestContentViewCore.java +++ b/content/public/test/android/javatests/src/org/chromium/content/browser/test/util/TestContentViewCore.java
@@ -13,7 +13,6 @@ import org.chromium.content.browser.ContentViewCore; import org.chromium.content.browser.ContentViewCore.InternalAccessDelegate; import org.chromium.content.browser.input.SelectPopup; -import org.chromium.content.browser.input.TextSuggestionHost; import org.chromium.content_public.browser.WebContents; import org.chromium.ui.base.ViewAndroidDelegate; import org.chromium.ui.base.WindowAndroid; @@ -46,14 +45,6 @@ } @Override - public TextSuggestionHost getTextSuggestionHostForTesting() { - return null; - } - - @Override - public void setTextSuggestionHostForTesting(TextSuggestionHost textSuggestionHost) {} - - @Override public void initialize(ViewAndroidDelegate viewDelegate, InternalAccessDelegate internalDispatcher, WebContents webContents, WindowAndroid windowAndroid) {}
diff --git a/content/public/test/android/javatests/src/org/chromium/content/browser/test/util/TouchCommon.java b/content/public/test/android/javatests/src/org/chromium/content/browser/test/util/TouchCommon.java index 827ee504..08d4af9 100644 --- a/content/public/test/android/javatests/src/org/chromium/content/browser/test/util/TouchCommon.java +++ b/content/public/test/android/javatests/src/org/chromium/content/browser/test/util/TouchCommon.java
@@ -109,10 +109,26 @@ * @param y Y coordinate, relative to v. */ public static boolean singleClickView(View v, int x, int y) { - int windowXY[] = viewToWindowCoordinates(v, x, y); + return singleClickViewThroughTarget(v, v.getRootView(), x, y); + } + + /** + * Sends a click event to the specified view, not going through the root view. + * + * This is mostly useful for tests in VR, where inputs to the root view are (in a sense) + * consumed by the platform, but the java test still wants to interact with, say, WebContents. + * + * @param view The view to be clicked. + * @param target The view to inject the input into. + * @param x X coordinate, relative to view. + * @param y Y coordinate, relative to view. + */ + /* package */ static boolean singleClickViewThroughTarget( + View view, View target, int x, int y) { + int windowXY[] = viewToWindowCoordinates(view, x, y); int windowX = windowXY[0]; int windowY = windowXY[1]; - return singleClickInternal(v.getRootView(), windowX, windowY); + return singleClickInternal(target, windowX, windowY); } /**
diff --git a/content/public/test/fake_download_item.cc b/content/public/test/fake_download_item.cc index 6ed55ad..b3d5cde 100644 --- a/content/public/test/fake_download_item.cc +++ b/content/public/test/fake_download_item.cc
@@ -345,9 +345,9 @@ return false; } -DownloadDangerType FakeDownloadItem::GetDangerType() const { +download::DownloadDangerType FakeDownloadItem::GetDangerType() const { NOTREACHED(); - return DownloadDangerType(); + return download::DownloadDangerType(); } bool FakeDownloadItem::TimeRemaining(base::TimeDelta* remaining) const { @@ -421,8 +421,9 @@ return nullptr; } -void FakeDownloadItem::OnContentCheckCompleted(DownloadDangerType danger_type, - DownloadInterruptReason reason) { +void FakeDownloadItem::OnContentCheckCompleted( + download::DownloadDangerType danger_type, + DownloadInterruptReason reason) { NOTREACHED(); }
diff --git a/content/public/test/fake_download_item.h b/content/public/test/fake_download_item.h index 5b01658f..57c3544 100644 --- a/content/public/test/fake_download_item.h +++ b/content/public/test/fake_download_item.h
@@ -11,7 +11,7 @@ #include "base/callback_forward.h" #include "base/files/file_path.h" #include "base/observer_list.h" -#include "content/public/browser/download_danger_type.h" +#include "components/download/public/common/download_danger_type.h" #include "content/public/browser/download_interrupt_reasons.h" #include "content/public/browser/download_item.h" #include "ui/base/page_transition_types.h" @@ -132,7 +132,7 @@ const std::string& GetHash() const override; void DeleteFile(const base::Callback<void(bool)>& callback) override; bool IsDangerous() const override; - DownloadDangerType GetDangerType() const override; + download::DownloadDangerType GetDangerType() const override; bool TimeRemaining(base::TimeDelta* remaining) const override; int64_t CurrentSpeed() const override; int PercentComplete() const override; @@ -147,7 +147,7 @@ bool GetOpened() const override; BrowserContext* GetBrowserContext() const override; WebContents* GetWebContents() const override; - void OnContentCheckCompleted(DownloadDangerType danger_type, + void OnContentCheckCompleted(download::DownloadDangerType danger_type, DownloadInterruptReason reason) override; void SetOpenWhenComplete(bool open) override; void SetOpened(bool opened) override;
diff --git a/content/public/test/mock_download_item.h b/content/public/test/mock_download_item.h index fc06bb2..a80ea5f9 100644 --- a/content/public/test/mock_download_item.h +++ b/content/public/test/mock_download_item.h
@@ -86,7 +86,7 @@ MOCK_CONST_METHOD0(GetFileExternallyRemoved, bool()); MOCK_METHOD1(DeleteFile, void(const base::Callback<void(bool)>&)); MOCK_CONST_METHOD0(IsDangerous, bool()); - MOCK_CONST_METHOD0(GetDangerType, DownloadDangerType()); + MOCK_CONST_METHOD0(GetDangerType, download::DownloadDangerType()); MOCK_CONST_METHOD1(TimeRemaining, bool(base::TimeDelta*)); MOCK_CONST_METHOD0(CurrentSpeed, int64_t()); MOCK_CONST_METHOD0(PercentComplete, int()); @@ -108,7 +108,7 @@ MOCK_CONST_METHOD0(GetBrowserContext, BrowserContext*()); MOCK_CONST_METHOD0(GetWebContents, WebContents*()); MOCK_METHOD2(OnContentCheckCompleted, - void(DownloadDangerType, DownloadInterruptReason)); + void(download::DownloadDangerType, DownloadInterruptReason)); MOCK_METHOD1(SetOpenWhenComplete, void(bool)); MOCK_METHOD1(SetOpened, void(bool)); MOCK_METHOD1(SetLastAccessTime, void(base::Time));
diff --git a/content/public/test/mock_download_manager.cc b/content/public/test/mock_download_manager.cc index 495cad2..d9f6b41a 100644 --- a/content/public/test/mock_download_manager.cc +++ b/content/public/test/mock_download_manager.cc
@@ -29,7 +29,7 @@ int64_t total_bytes, const std::string& hash, DownloadItem::DownloadState state, - DownloadDangerType danger_type, + download::DownloadDangerType danger_type, DownloadInterruptReason interrupt_reason, bool opened, base::Time last_access_time, @@ -135,7 +135,7 @@ int64_t total_bytes, const std::string& hash, DownloadItem::DownloadState state, - DownloadDangerType danger_type, + download::DownloadDangerType danger_type, DownloadInterruptReason interrupt_reason, bool opened, base::Time last_access_time,
diff --git a/content/public/test/mock_download_manager.h b/content/public/test/mock_download_manager.h index fb96ef1e..e6a1064 100644 --- a/content/public/test/mock_download_manager.h +++ b/content/public/test/mock_download_manager.h
@@ -11,7 +11,6 @@ #include <vector> #include "content/public/browser/download_manager.h" -#include "content/public/browser/download_save_info.h" #include "content/public/browser/download_url_parameters.h" #include "testing/gmock/include/gmock/gmock.h" #include "testing/gtest/include/gtest/gtest.h" @@ -49,7 +48,7 @@ int64_t total_bytes; std::string hash; DownloadItem::DownloadState state; - DownloadDangerType danger_type; + download::DownloadDangerType danger_type; DownloadInterruptReason interrupt_reason; bool opened; base::Time last_access_time; @@ -76,7 +75,7 @@ int64_t total_bytes, const std::string& hash, DownloadItem::DownloadState state, - DownloadDangerType danger_type, + download::DownloadDangerType danger_type, DownloadInterruptReason interrupt_reason, bool opened, base::Time last_access_time, @@ -139,7 +138,7 @@ int64_t total_bytes, const std::string& hash, DownloadItem::DownloadState state, - DownloadDangerType danger_type, + download::DownloadDangerType danger_type, DownloadInterruptReason interrupt_reason, bool opened, base::Time last_access_time,
diff --git a/content/public/test/test_file_error_injector.cc b/content/public/test/test_file_error_injector.cc index ce195bf..036f905 100644 --- a/content/public/test/test_file_error_injector.cc +++ b/content/public/test/test_file_error_injector.cc
@@ -31,7 +31,7 @@ // A class that performs file operations and injects errors. class DownloadFileWithError: public DownloadFileImpl { public: - DownloadFileWithError(std::unique_ptr<DownloadSaveInfo> save_info, + DownloadFileWithError(std::unique_ptr<download::DownloadSaveInfo> save_info, const base::FilePath& default_download_directory, std::unique_ptr<DownloadManager::InputStream> stream, uint32_t download_id, @@ -108,7 +108,7 @@ } DownloadFileWithError::DownloadFileWithError( - std::unique_ptr<DownloadSaveInfo> save_info, + std::unique_ptr<download::DownloadSaveInfo> save_info, const base::FilePath& default_download_directory, std::unique_ptr<DownloadManager::InputStream> stream, uint32_t download_id, @@ -283,7 +283,7 @@ // DownloadFileFactory interface. DownloadFile* CreateFile( - std::unique_ptr<DownloadSaveInfo> save_info, + std::unique_ptr<download::DownloadSaveInfo> save_info, const base::FilePath& default_download_directory, std::unique_ptr<DownloadManager::InputStream> stream, uint32_t download_id, @@ -309,7 +309,7 @@ DownloadFileWithErrorFactory::~DownloadFileWithErrorFactory() {} DownloadFile* DownloadFileWithErrorFactory::CreateFile( - std::unique_ptr<DownloadSaveInfo> save_info, + std::unique_ptr<download::DownloadSaveInfo> save_info, const base::FilePath& default_download_directory, std::unique_ptr<DownloadManager::InputStream> stream, uint32_t download_id,
diff --git a/content/renderer/accessibility/blink_ax_enum_conversion.cc b/content/renderer/accessibility/blink_ax_enum_conversion.cc index 268e803f..b1ddcad 100644 --- a/content/renderer/accessibility/blink_ax_enum_conversion.cc +++ b/content/renderer/accessibility/blink_ax_enum_conversion.cc
@@ -172,6 +172,14 @@ return ax::mojom::Role::kInputTime; case blink::kWebAXRoleLabel: return ax::mojom::Role::kLabelText; + case blink::kWebAXRoleLayoutTable: + return ax::mojom::Role::kLayoutTable; + case blink::kWebAXRoleLayoutTableCell: + return ax::mojom::Role::kLayoutTableCell; + case blink::kWebAXRoleLayoutTableColumn: + return ax::mojom::Role::kLayoutTableColumn; + case blink::kWebAXRoleLayoutTableRow: + return ax::mojom::Role::kLayoutTableRow; case blink::kWebAXRoleLegend: return ax::mojom::Role::kLegend; case blink::kWebAXRoleLink:
diff --git a/content/renderer/content_security_policy_util.cc b/content/renderer/content_security_policy_util.cc index 28ab7a1..825ecbe7 100644 --- a/content/renderer/content_security_policy_util.cc +++ b/content/renderer/content_security_policy_util.cc
@@ -49,7 +49,7 @@ return ContentSecurityPolicy( ContentSecurityPolicyHeader(policy.header.Utf8(), policy.disposition, policy.source), - directives, report_endpoints); + directives, report_endpoints, policy.use_reporting_api); } blink::WebContentSecurityPolicyViolation BuildWebContentSecurityPolicyViolation( @@ -67,6 +67,7 @@ violation.report_endpoints[i] = blink::WebString::FromASCII(violation_params.report_endpoints[i]); } + violation.use_reporting_api = violation_params.use_reporting_api; violation.header = blink::WebString::FromASCII(violation_params.header); violation.disposition = violation_params.disposition; violation.after_redirect = violation_params.after_redirect;
diff --git a/content/renderer/loader/shared_memory_data_consumer_handle.cc b/content/renderer/loader/shared_memory_data_consumer_handle.cc index e57f2d5..f216a6e0 100644 --- a/content/renderer/loader/shared_memory_data_consumer_handle.cc +++ b/content/renderer/loader/shared_memory_data_consumer_handle.cc
@@ -54,12 +54,12 @@ class SharedMemoryDataConsumerHandle::Context final : public base::RefCountedThreadSafe<Context> { public: - explicit Context(base::OnceClosure on_reader_detached) + explicit Context(const base::Closure& on_reader_detached) : result_(kOk), first_offset_(0), client_(nullptr), writer_task_runner_(base::ThreadTaskRunnerHandle::Get()), - on_reader_detached_(std::move(on_reader_detached)), + on_reader_detached_(on_reader_detached), is_on_reader_detached_valid_(!on_reader_detached_.is_null()), is_handle_active_(true), is_two_phase_read_in_progress_(false) {} @@ -76,9 +76,7 @@ // We post a task even in the writer thread in order to avoid a // reentrance problem as calling |on_reader_detached_| may manipulate // the context synchronously. - is_on_reader_detached_valid_ = false; - writer_task_runner_->PostTask(FROM_HERE, - std::move(on_reader_detached_)); + writer_task_runner_->PostTask(FROM_HERE, on_reader_detached_); } Clear(); } @@ -252,7 +250,7 @@ Client* client_; scoped_refptr<base::SingleThreadTaskRunner> notification_task_runner_; scoped_refptr<base::SingleThreadTaskRunner> writer_task_runner_; - base::OnceClosure on_reader_detached_; + base::Closure on_reader_detached_; // We need this boolean variable to remember if |on_reader_detached_| is // callable because we need to reset |on_reader_detached_| only on the writer // thread and hence |on_reader_detached_.is_null()| is untrustworthy on @@ -265,8 +263,10 @@ }; SharedMemoryDataConsumerHandle::Writer::Writer( - const scoped_refptr<Context>& context) - : context_(context) {} + const scoped_refptr<Context>& context, + BackpressureMode mode) + : context_(context), mode_(mode) { +} SharedMemoryDataConsumerHandle::Writer::~Writer() { Close(); @@ -290,8 +290,14 @@ } needs_notification = context_->IsEmpty(); - context_->Push( - std::make_unique<DelegateThreadSafeReceivedData>(std::move(data))); + std::unique_ptr<RequestPeer::ThreadSafeReceivedData> data_to_pass; + if (mode_ == kApplyBackpressure) { + data_to_pass = + std::make_unique<DelegateThreadSafeReceivedData>(std::move(data)); + } else { + data_to_pass = std::make_unique<FixedReceivedData>(data.get()); + } + context_->Push(std::move(data_to_pass)); } if (needs_notification) { @@ -430,14 +436,16 @@ } SharedMemoryDataConsumerHandle::SharedMemoryDataConsumerHandle( + BackpressureMode mode, std::unique_ptr<Writer>* writer) - : SharedMemoryDataConsumerHandle(base::OnceClosure(), writer) {} + : SharedMemoryDataConsumerHandle(mode, base::Closure(), writer) {} SharedMemoryDataConsumerHandle::SharedMemoryDataConsumerHandle( - base::OnceClosure on_reader_detached, + BackpressureMode mode, + const base::Closure& on_reader_detached, std::unique_ptr<Writer>* writer) - : context_(new Context(std::move(on_reader_detached))) { - writer->reset(new Writer(context_)); + : context_(new Context(on_reader_detached)) { + writer->reset(new Writer(context_, mode)); } SharedMemoryDataConsumerHandle::~SharedMemoryDataConsumerHandle() {
diff --git a/content/renderer/loader/shared_memory_data_consumer_handle.h b/content/renderer/loader/shared_memory_data_consumer_handle.h index d3271698..c5afb38 100644 --- a/content/renderer/loader/shared_memory_data_consumer_handle.h +++ b/content/renderer/loader/shared_memory_data_consumer_handle.h
@@ -25,9 +25,14 @@ class Context; public: + enum BackpressureMode { + kApplyBackpressure, + kDoNotApplyBackpressure, + }; + class CONTENT_EXPORT Writer final { public: - explicit Writer(const scoped_refptr<Context>& context); + Writer(const scoped_refptr<Context>& context, BackpressureMode mode); ~Writer(); // Note: Writer assumes |AddData| is not called in a client's didGetReadable // callback. There isn't such assumption for |Close| and |Fail|. @@ -38,6 +43,7 @@ private: scoped_refptr<Context> context_; + BackpressureMode mode_; DISALLOW_COPY_AND_ASSIGN(Writer); }; @@ -63,13 +69,15 @@ // Creates a handle and a writer associated with the handle. The created // writer should be used on the calling thread. - explicit SharedMemoryDataConsumerHandle(std::unique_ptr<Writer>* writer); + SharedMemoryDataConsumerHandle(BackpressureMode mode, + std::unique_ptr<Writer>* writer); // |on_reader_detached| will be called aynchronously on the calling thread // when the reader (including the handle) is detached (i.e. both the handle // and the reader are destructed). The callback will be reset in the internal // context when the writer is detached, i.e. |Close| or |Fail| is called, // and the callback will never be called. - SharedMemoryDataConsumerHandle(base::OnceClosure on_reader_detached, + SharedMemoryDataConsumerHandle(BackpressureMode mode, + const base::Closure& on_reader_detached, std::unique_ptr<Writer>* writer); ~SharedMemoryDataConsumerHandle() override;
diff --git a/content/renderer/loader/shared_memory_data_consumer_handle_unittest.cc b/content/renderer/loader/shared_memory_data_consumer_handle_unittest.cc index 4195ea2..9a8f620 100644 --- a/content/renderer/loader/shared_memory_data_consumer_handle_unittest.cc +++ b/content/renderer/loader/shared_memory_data_consumer_handle_unittest.cc
@@ -34,6 +34,11 @@ using blink::WebDataConsumerHandle; using Result = WebDataConsumerHandle::Result; using Writer = SharedMemoryDataConsumerHandle::Writer; +using BackpressureMode = SharedMemoryDataConsumerHandle::BackpressureMode; +const BackpressureMode kApplyBackpressure = + SharedMemoryDataConsumerHandle::kApplyBackpressure; +const BackpressureMode kDoNotApplyBackpressure = + SharedMemoryDataConsumerHandle::kDoNotApplyBackpressure; const WebDataConsumerHandle::Flags kNone = WebDataConsumerHandle::kFlagNone; const Result kOk = WebDataConsumerHandle::kOk; @@ -176,7 +181,8 @@ }; void SetUp() override { - handle_.reset(new SharedMemoryDataConsumerHandle(&writer_)); + handle_.reset( + new SharedMemoryDataConsumerHandle(kApplyBackpressure, &writer_)); } StrictMock<MockClient> client_; @@ -185,10 +191,11 @@ base::MessageLoop loop_; }; -class SharedMemoryDataConsumerHandleTest : public ::testing::Test { +class SharedMemoryDataConsumerHandleTest + : public ::testing::TestWithParam<BackpressureMode> { protected: void SetUp() override { - handle_.reset(new SharedMemoryDataConsumerHandle(&writer_)); + handle_.reset(new SharedMemoryDataConsumerHandle(GetParam(), &writer_)); } std::unique_ptr<FixedReceivedData> NewFixedData(const char* s) { return std::make_unique<FixedReceivedData>(s, strlen(s)); @@ -207,7 +214,7 @@ run_loop.Run(); } -TEST_F(SharedMemoryDataConsumerHandleTest, ReadFromEmpty) { +TEST_P(SharedMemoryDataConsumerHandleTest, ReadFromEmpty) { char buffer[4]; size_t read = 88; auto reader = handle_->ObtainReader(nullptr); @@ -217,7 +224,7 @@ EXPECT_EQ(0u, read); } -TEST_F(SharedMemoryDataConsumerHandleTest, AutoClose) { +TEST_P(SharedMemoryDataConsumerHandleTest, AutoClose) { char buffer[4]; size_t read = 88; @@ -229,7 +236,7 @@ EXPECT_EQ(0u, read); } -TEST_F(SharedMemoryDataConsumerHandleTest, ReadSimple) { +TEST_P(SharedMemoryDataConsumerHandleTest, ReadSimple) { writer_->AddData(NewFixedData("hello")); char buffer[4] = {}; @@ -257,7 +264,7 @@ EXPECT_EQ(0u, read); } -TEST_F(SharedMemoryDataConsumerHandleTest, ReadAfterHandleIsGone) { +TEST_P(SharedMemoryDataConsumerHandleTest, ReadAfterHandleIsGone) { writer_->AddData(NewFixedData("hello")); char buffer[8] = {}; @@ -283,7 +290,7 @@ EXPECT_EQ(0u, read); } -TEST_F(SharedMemoryDataConsumerHandleTest, ReObtainReader) { +TEST_P(SharedMemoryDataConsumerHandleTest, ReObtainReader) { writer_->AddData(NewFixedData("hello")); char buffer[4] = {}; @@ -314,7 +321,7 @@ EXPECT_EQ(0u, read); } -TEST_F(SharedMemoryDataConsumerHandleTest, CloseBeforeReading) { +TEST_P(SharedMemoryDataConsumerHandleTest, CloseBeforeReading) { writer_->AddData(NewFixedData("hello")); writer_->Close(); @@ -332,7 +339,7 @@ EXPECT_EQ(0u, read); } -TEST_F(SharedMemoryDataConsumerHandleTest, CloseWithDataBeforeZeroRead) { +TEST_P(SharedMemoryDataConsumerHandleTest, CloseWithDataBeforeZeroRead) { writer_->AddData(NewFixedData("hello")); writer_->Close(); @@ -344,7 +351,7 @@ EXPECT_EQ(0u, read); } -TEST_F(SharedMemoryDataConsumerHandleTest, CloseWithoutDataBeforeZeroRead) { +TEST_P(SharedMemoryDataConsumerHandleTest, CloseWithoutDataBeforeZeroRead) { writer_->Close(); size_t read = 88; @@ -354,7 +361,7 @@ EXPECT_EQ(kDone, result); } -TEST_F(SharedMemoryDataConsumerHandleTest, AddMultipleData) { +TEST_P(SharedMemoryDataConsumerHandleTest, AddMultipleData) { writer_->AddData(NewFixedData("Once ")); writer_->AddData(NewFixedData("upon ")); writer_->AddData(NewFixedData("a ")); @@ -404,7 +411,7 @@ EXPECT_EQ(0u, read); } -TEST_F(SharedMemoryDataConsumerHandleTest, AddMultipleDataInteractively) { +TEST_P(SharedMemoryDataConsumerHandleTest, AddMultipleDataInteractively) { writer_->AddData(NewFixedData("Once ")); writer_->AddData(NewFixedData("upon ")); @@ -462,7 +469,7 @@ EXPECT_EQ(0u, read); } -TEST_F(SharedMemoryDataConsumerHandleTest, RegisterClient) { +TEST_P(SharedMemoryDataConsumerHandleTest, RegisterClient) { Checkpoint checkpoint; InSequence s; @@ -484,7 +491,7 @@ checkpoint.Call(4); } -TEST_F(SharedMemoryDataConsumerHandleTest, RegisterClientWhenDataExists) { +TEST_P(SharedMemoryDataConsumerHandleTest, RegisterClientWhenDataExists) { Checkpoint checkpoint; InSequence s; @@ -503,7 +510,7 @@ checkpoint.Call(3); } -TEST_F(SharedMemoryDataConsumerHandleTest, AddDataWhenClientIsRegistered) { +TEST_P(SharedMemoryDataConsumerHandleTest, AddDataWhenClientIsRegistered) { Checkpoint checkpoint; char buffer[20]; Result result; @@ -534,7 +541,7 @@ checkpoint.Call(5); } -TEST_F(SharedMemoryDataConsumerHandleTest, CloseWithClientAndData) { +TEST_P(SharedMemoryDataConsumerHandleTest, CloseWithClientAndData) { Checkpoint checkpoint; InSequence s; @@ -553,7 +560,7 @@ checkpoint.Call(3); } -TEST_F(SharedMemoryDataConsumerHandleTest, ReleaseReader) { +TEST_P(SharedMemoryDataConsumerHandleTest, ReleaseReader) { Checkpoint checkpoint; InSequence s; @@ -569,7 +576,7 @@ checkpoint.Call(2); } -TEST_F(SharedMemoryDataConsumerHandleTest, TwoPhaseReadShouldWait) { +TEST_P(SharedMemoryDataConsumerHandleTest, TwoPhaseReadShouldWait) { Result result; const void* buffer = &result; size_t size = 99; @@ -581,7 +588,7 @@ EXPECT_EQ(0u, size); } -TEST_F(SharedMemoryDataConsumerHandleTest, TwoPhaseReadSimple) { +TEST_P(SharedMemoryDataConsumerHandleTest, TwoPhaseReadSimple) { writer_->AddData(NewFixedData("Once ")); Result result; @@ -616,7 +623,7 @@ EXPECT_EQ(nullptr, buffer); } -TEST_F(SharedMemoryDataConsumerHandleTest, CallOnClearWhenDestructed1) { +TEST_P(SharedMemoryDataConsumerHandleTest, CallOnClearWhenDestructed1) { // Call |on_clear| when the handle is gone and if there is no reader. Checkpoint checkpoint; scoped_refptr<DestructionTrackingFunction> on_clear( @@ -631,6 +638,7 @@ checkpoint.Call(0); handle_.reset(new SharedMemoryDataConsumerHandle( + kApplyBackpressure, base::Bind(&DestructionTrackingFunction::Call, on_clear), &writer_)); handle_.reset(); on_clear = nullptr; @@ -639,7 +647,7 @@ checkpoint.Call(2); } -TEST_F(SharedMemoryDataConsumerHandleTest, CallOnClearWhenDestructed2) { +TEST_P(SharedMemoryDataConsumerHandleTest, CallOnClearWhenDestructed2) { // Call |on_clear| when the reader is gone if the handle is alredy gone. Checkpoint checkpoint; scoped_refptr<DestructionTrackingFunction> on_clear( @@ -656,6 +664,7 @@ checkpoint.Call(0); handle_.reset(new SharedMemoryDataConsumerHandle( + kApplyBackpressure, base::Bind(&DestructionTrackingFunction::Call, on_clear), &writer_)); auto reader = handle_->ObtainReader(nullptr); handle_.reset(); @@ -669,7 +678,7 @@ checkpoint.Call(4); } -TEST_F(SharedMemoryDataConsumerHandleTest, DoNotCallOnClearWhenDone) { +TEST_P(SharedMemoryDataConsumerHandleTest, DoNotCallOnClearWhenDone) { Checkpoint checkpoint; scoped_refptr<DestructionTrackingFunction> on_clear( new StrictMock<DestructionTrackingFunction>); @@ -684,6 +693,7 @@ checkpoint.Call(0); handle_.reset(new SharedMemoryDataConsumerHandle( + kApplyBackpressure, base::Bind(&DestructionTrackingFunction::Call, on_clear), &writer_)); on_clear = nullptr; checkpoint.Call(1); @@ -695,7 +705,7 @@ checkpoint.Call(4); } -TEST_F(SharedMemoryDataConsumerHandleTest, DoNotCallOnClearWhenErrored) { +TEST_P(SharedMemoryDataConsumerHandleTest, DoNotCallOnClearWhenErrored) { Checkpoint checkpoint; scoped_refptr<DestructionTrackingFunction> on_clear( new StrictMock<DestructionTrackingFunction>); @@ -710,6 +720,7 @@ checkpoint.Call(0); handle_.reset(new SharedMemoryDataConsumerHandle( + kApplyBackpressure, base::Bind(&DestructionTrackingFunction::Call, on_clear), &writer_)); on_clear = nullptr; checkpoint.Call(1); @@ -721,7 +732,7 @@ checkpoint.Call(4); } -TEST_F(SharedMemoryDataConsumerHandleTest, TwoPhaseReadWithMultipleData) { +TEST_P(SharedMemoryDataConsumerHandleTest, TwoPhaseReadWithMultipleData) { writer_->AddData(NewFixedData("Once ")); writer_->AddData(NewFixedData("upon ")); @@ -764,7 +775,7 @@ EXPECT_EQ(nullptr, buffer); } -TEST_F(SharedMemoryDataConsumerHandleTest, ErrorRead) { +TEST_P(SharedMemoryDataConsumerHandleTest, ErrorRead) { Checkpoint checkpoint; Result result; char buffer[20] = {}; @@ -778,7 +789,7 @@ EXPECT_EQ(0u, read); } -TEST_F(SharedMemoryDataConsumerHandleTest, ErrorTwoPhaseRead) { +TEST_P(SharedMemoryDataConsumerHandleTest, ErrorTwoPhaseRead) { Result result; const void* pointer = &result; size_t size = 99; @@ -792,7 +803,7 @@ EXPECT_EQ(0u, size); } -TEST_F(SharedMemoryDataConsumerHandleTest, FailWhileTwoPhaseReadIsInProgress) { +TEST_P(SharedMemoryDataConsumerHandleTest, FailWhileTwoPhaseReadIsInProgress) { Result result; const void* pointer = nullptr; size_t size = 0; @@ -821,7 +832,7 @@ EXPECT_EQ(kUnexpectedError, reader->BeginRead(&pointer, kNone, &size)); } -TEST_F(SharedMemoryDataConsumerHandleTest, FailWithClient) { +TEST_P(SharedMemoryDataConsumerHandleTest, FailWithClient) { Checkpoint checkpoint; InSequence s; @@ -840,7 +851,7 @@ checkpoint.Call(3); } -TEST_F(SharedMemoryDataConsumerHandleTest, FailWithClientAndData) { +TEST_P(SharedMemoryDataConsumerHandleTest, FailWithClientAndData) { Checkpoint checkpoint; InSequence s; @@ -863,7 +874,7 @@ checkpoint.Call(4); } -TEST_F(SharedMemoryDataConsumerHandleTest, RecursiveErrorNotification) { +TEST_P(SharedMemoryDataConsumerHandleTest, RecursiveErrorNotification) { Checkpoint checkpoint; InSequence s; @@ -891,7 +902,8 @@ size_t size; std::unique_ptr<Writer> writer; - auto handle = std::make_unique<SharedMemoryDataConsumerHandle>(&writer); + auto handle = std::make_unique<SharedMemoryDataConsumerHandle>( + kApplyBackpressure, &writer); scoped_refptr<Logger> logger(new Logger); writer->AddData( std::make_unique<LoggingFixedReceivedData>("data1", "Once ", logger)); @@ -935,7 +947,8 @@ size_t size; std::unique_ptr<Writer> writer; - auto handle = std::make_unique<SharedMemoryDataConsumerHandle>(&writer); + auto handle = std::make_unique<SharedMemoryDataConsumerHandle>( + kApplyBackpressure, &writer); scoped_refptr<Logger> logger(new Logger); writer->AddData( std::make_unique<LoggingFixedReceivedData>("data1", "Once ", logger)); @@ -974,6 +987,30 @@ EXPECT_EQ(destruction_entries[2], "data3 is destructed."); } +TEST(SharedMemoryDataConsumerHandleWithoutBackpressureTest, AddData) { + base::MessageLoop loop; + std::unique_ptr<Writer> writer; + auto handle = std::make_unique<SharedMemoryDataConsumerHandle>( + kDoNotApplyBackpressure, &writer); + scoped_refptr<Logger> logger(new Logger); + + logger->Add("1"); + writer->AddData( + std::make_unique<LoggingFixedReceivedData>("data1", "Once ", logger)); + logger->Add("2"); + writer->AddData( + std::make_unique<LoggingFixedReceivedData>("data2", "upon ", logger)); + logger->Add("3"); + + EXPECT_EQ( + "1\n" + "data1 is destructed.\n" + "2\n" + "data2 is destructed.\n" + "3\n", + logger->log()); +} + TEST_F(ThreadedSharedMemoryDataConsumerHandleTest, Read) { base::RunLoop run_loop; auto operation = std::make_unique<ReadDataOperation>( @@ -1016,6 +1053,10 @@ logger->log()); } +INSTANTIATE_TEST_CASE_P(SharedMemoryDataConsumerHandleTest, + SharedMemoryDataConsumerHandleTest, + ::testing::Values(kApplyBackpressure, + kDoNotApplyBackpressure)); } // namespace } // namespace content
diff --git a/content/renderer/loader/web_url_loader_impl.cc b/content/renderer/loader/web_url_loader_impl.cc index ba304c4..222aeb88 100644 --- a/content/renderer/loader/web_url_loader_impl.cc +++ b/content/renderer/loader/web_url_loader_impl.cc
@@ -852,8 +852,15 @@ } if (use_stream_on_response_) { + SharedMemoryDataConsumerHandle::BackpressureMode mode = + SharedMemoryDataConsumerHandle::kDoNotApplyBackpressure; + if (info.headers && + info.headers->HasHeaderValue("Cache-Control", "no-store")) { + mode = SharedMemoryDataConsumerHandle::kApplyBackpressure; + } + auto read_handle = std::make_unique<SharedMemoryDataConsumerHandle>( - base::BindOnce(&Context::CancelBodyStreaming, this), + mode, base::Bind(&Context::CancelBodyStreaming, this), &body_stream_writer_); // Here |body_stream_writer_| has an indirect reference to |this| and that
diff --git a/content/renderer/media/gpu/gpu_video_accelerator_factories_impl.cc b/content/renderer/media/gpu/gpu_video_accelerator_factories_impl.cc index 99503456..ca07dad 100644 --- a/content/renderer/media/gpu/gpu_video_accelerator_factories_impl.cc +++ b/content/renderer/media/gpu/gpu_video_accelerator_factories_impl.cc
@@ -305,9 +305,9 @@ if (rendering_color_space_.IsHDR()) return media::GpuVideoAcceleratorFactories::OutputFormat::UNDEFINED; -#if defined(OS_MACOSX) +#if defined(OS_MACOSX) || defined(OS_LINUX) // TODO(mcasas): enable other platforms https://crbug.com/776093 - // https://crbug.com/803451, https://crbug.com/803975. + // https://crbug.com/803451. // TODO(mcasas): remove the |bit_depth| check when libyuv supports more than // just x010ToAR30 conversions, https://crbug.com/libyuv/751. if (capabilities.image_xr30 && bit_depth == 10)
diff --git a/content/renderer/media/gpu/rtc_video_encoder.cc b/content/renderer/media/gpu/rtc_video_encoder.cc index 8a2a2d3..9dfd192 100644 --- a/content/renderer/media/gpu/rtc_video_encoder.cc +++ b/content/renderer/media/gpu/rtc_video_encoder.cc
@@ -42,10 +42,15 @@ namespace { struct RTCTimestamps { - RTCTimestamps(const base::TimeDelta& media_timestamp, int32_t rtp_timestamp) - : media_timestamp_(media_timestamp), rtp_timestamp(rtp_timestamp) {} + RTCTimestamps(const base::TimeDelta& media_timestamp, + int32_t rtp_timestamp, + int64_t capture_time_ms) + : media_timestamp_(media_timestamp), + rtp_timestamp(rtp_timestamp), + capture_time_ms(capture_time_ms) {} const base::TimeDelta media_timestamp_; const int32_t rtp_timestamp; + const int64_t capture_time_ms; }; webrtc::VideoCodecType ProfileToWebRtcVideoCodecType( @@ -255,10 +260,6 @@ // 15 bits running index of the VP8 frames. See VP8 RTP spec for details. uint16_t picture_id_; - // |capture_time_ms_| field of the last returned webrtc::EncodedImage from - // BitstreamBufferReady(). - int64_t last_capture_time_ms_; - // webrtc::VideoEncoder encode complete callback. webrtc::EncodedImageCallback* encoded_image_callback_; @@ -287,7 +288,6 @@ input_next_frame_(nullptr), input_next_frame_keyframe_(false), output_buffers_free_count_(0), - last_capture_time_ms_(-1), encoded_image_callback_(nullptr), video_codec_type_(video_codec_type), status_(WEBRTC_VIDEO_CODEC_UNINITIALIZED) { @@ -500,23 +500,17 @@ } output_buffers_free_count_--; - // Derive the capture time in ms from system clock. Make sure that it is - // greater than the last. - const int64_t capture_time_us = rtc::TimeMicros(); - int64_t capture_time_ms = - capture_time_us / base::Time::kMicrosecondsPerMillisecond; - capture_time_ms = std::max(capture_time_ms, last_capture_time_ms_ + 1); - last_capture_time_ms_ = capture_time_ms; - - // Find RTP timestamp by going through |pending_timestamps_|. Derive it from - // capture time otherwise. + // Find RTP and capture timestamps by going through |pending_timestamps_|. + // Derive it from current time otherwise. base::Optional<uint32_t> rtp_timestamp; + base::Optional<int64_t> capture_timestamp_ms; if (!failed_timestamp_match_) { // Pop timestamps until we have a match. while (!pending_timestamps_.empty()) { const auto& front_timestamps = pending_timestamps_.front(); if (front_timestamps.media_timestamp_ == timestamp) { rtp_timestamp = front_timestamps.rtp_timestamp; + capture_timestamp_ms = front_timestamps.capture_time_ms; pending_timestamps_.pop_front(); break; } @@ -524,12 +518,14 @@ } DCHECK(rtp_timestamp.has_value()); } - if (!rtp_timestamp.has_value()) { + if (!rtp_timestamp.has_value() || !capture_timestamp_ms.has_value()) { failed_timestamp_match_ = true; pending_timestamps_.clear(); + const int64_t current_time_ms = + rtc::TimeMicros() / base::Time::kMicrosecondsPerMillisecond; // RTP timestamp can wrap around. Get the lower 32 bits. - rtp_timestamp = static_cast<uint32_t>( - capture_time_us * 90 / base::Time::kMicrosecondsPerMillisecond); + rtp_timestamp = static_cast<uint32_t>(current_time_ms * 90); + capture_timestamp_ms = current_time_ms; } webrtc::EncodedImage image( @@ -538,7 +534,7 @@ image._encodedWidth = input_visible_size_.width(); image._encodedHeight = input_visible_size_.height(); image._timeStamp = rtp_timestamp.value(); - image.capture_time_ms_ = capture_time_ms; + image.capture_time_ms_ = capture_timestamp_ms.value(); image._frameType = (key_frame ? webrtc::kVideoFrameKey : webrtc::kVideoFrameDelta); image._completeFrame = true; @@ -670,7 +666,8 @@ return entry.media_timestamp_ == frame->timestamp(); }) == pending_timestamps_.end()); pending_timestamps_.emplace_back(frame->timestamp(), - next_frame->timestamp()); + next_frame->timestamp(), + next_frame->render_time_ms()); } video_encoder_->Encode(frame, next_frame_keyframe); input_buffers_free_.pop_back();
diff --git a/content/renderer/media/gpu/rtc_video_encoder_unittest.cc b/content/renderer/media/gpu/rtc_video_encoder_unittest.cc index 31bccb0..95d66ddf 100644 --- a/content/renderer/media/gpu/rtc_video_encoder_unittest.cc +++ b/content/renderer/media/gpu/rtc_video_encoder_unittest.cc
@@ -185,11 +185,13 @@ } void VerifyTimestamp(uint32_t rtp_timestamp, + int64_t capture_time_ms, const webrtc::EncodedImage& encoded_image, const webrtc::CodecSpecificInfo* codec_specific_info, const webrtc::RTPFragmentationHeader* fragmentation) { DVLOG(3) << __func__; EXPECT_EQ(rtp_timestamp, encoded_image._timeStamp); + EXPECT_EQ(capture_time_ms, encoded_image.capture_time_ms_); } protected: @@ -299,9 +301,10 @@ EXPECT_EQ(WEBRTC_VIDEO_CODEC_OK, rtc_encoder_->InitEncode(&codec, 1, 12345)); const uint32_t rtp_timestamp = 1234567; + const uint32_t capture_time_ms = 3456789; RegisterEncodeCompleteCallback( base::Bind(&RTCVideoEncoderTest::VerifyTimestamp, base::Unretained(this), - rtp_timestamp)); + rtp_timestamp, capture_time_ms)); EXPECT_CALL(*mock_vea_, Encode(_, _)) .WillOnce(Invoke(this, &RTCVideoEncoderTest::ReturnFrameWithTimeStamp)); @@ -311,6 +314,7 @@ std::vector<webrtc::FrameType> frame_types; webrtc::VideoFrame rtc_frame(buffer, rtp_timestamp, 0, webrtc::kVideoRotation_0); + rtc_frame.set_timestamp_us(capture_time_ms * rtc::kNumMicrosecsPerMillisec); // We need to set ntp_time_ms because it will be used to derive // media::VideoFrame timestamp. rtc_frame.set_ntp_time_ms(4567891);
diff --git a/content/renderer/media/rtc_peer_connection_handler.cc b/content/renderer/media/rtc_peer_connection_handler.cc index 5be773b..5762472 100644 --- a/content/renderer/media/rtc_peer_connection_handler.cc +++ b/content/renderer/media/rtc_peer_connection_handler.cc
@@ -820,8 +820,13 @@ UMA_HISTOGRAM_EXACT_LINEAR("WebRTC.PeerConnection.IceRegatheringReason", counter, counter_max); break; + case webrtc::kEnumCounterKeyProtocol: + UMA_HISTOGRAM_ENUMERATION( + "WebRTC.PeerConnection.KeyProtocol", + static_cast<webrtc::KeyExchangeProtocolType>(counter), + webrtc::kEnumCounterKeyProtocolMax); default: - // The default clause is expected to reach when new enum types are + // The default clause is expected to be reached when new enum types are // added. break; }
diff --git a/content/renderer/p2p/ipc_socket_factory.cc b/content/renderer/p2p/ipc_socket_factory.cc index ee546f51..4c7c512 100644 --- a/content/renderer/p2p/ipc_socket_factory.cc +++ b/content/renderer/p2p/ipc_socket_factory.cc
@@ -14,7 +14,6 @@ #include "base/macros.h" #include "base/metrics/histogram_macros.h" #include "base/sequence_checker.h" -#include "base/strings/string_number_conversions.h" #include "base/strings/stringprintf.h" #include "base/threading/thread_checker.h" #include "base/trace_event/trace_event.h"
diff --git a/content/renderer/pepper/content_renderer_pepper_host_factory.cc b/content/renderer/pepper/content_renderer_pepper_host_factory.cc index d859446..a96902f 100644 --- a/content/renderer/pepper/content_renderer_pepper_host_factory.cc +++ b/content/renderer/pepper/content_renderer_pepper_host_factory.cc
@@ -197,10 +197,12 @@ if (CanUseMediaStreamAPI(host_, instance)) return std::make_unique<PepperVideoDestinationHost>(host_, instance, resource); + return nullptr; case PpapiHostMsg_VideoSource_Create::ID: if (CanUseMediaStreamAPI(host_, instance)) return std::make_unique<PepperVideoSourceHost>(host_, instance, resource); + return nullptr; #endif // BUILDFLAG(ENABLE_WEBRTC) }
diff --git a/content/renderer/pepper/pepper_graphics_2d_host.cc b/content/renderer/pepper/pepper_graphics_2d_host.cc index c2bf6bb4..1f0fcfa 100644 --- a/content/renderer/pepper/pepper_graphics_2d_host.cc +++ b/content/renderer/pepper/pepper_graphics_2d_host.cc
@@ -886,9 +886,11 @@ void PepperGraphics2DHost::ExecuteTransform(const float& scale, const gfx::PointF& translate, gfx::Rect* invalidated_rect) { - bound_instance_->SetGraphics2DTransform(scale, translate); - *invalidated_rect = - gfx::Rect(0, 0, image_data_->width(), image_data_->height()); + if (bound_instance_) { + bound_instance_->SetGraphics2DTransform(scale, translate); + *invalidated_rect = + gfx::Rect(0, 0, image_data_->width(), image_data_->height()); + } } void PepperGraphics2DHost::ExecutePaintImageData(PPB_ImageData_Impl* image,
diff --git a/content/renderer/render_frame_impl.cc b/content/renderer/render_frame_impl.cc index 603c5b4..4f8f4d8 100644 --- a/content/renderer/render_frame_impl.cc +++ b/content/renderer/render_frame_impl.cc
@@ -1765,6 +1765,8 @@ IPC_MESSAGE_HANDLER(FrameMsg_MixedContentFound, OnMixedContentFound) IPC_MESSAGE_HANDLER(FrameMsg_SetOverlayRoutingToken, OnSetOverlayRoutingToken) + IPC_MESSAGE_HANDLER(FrameMsg_SetHasReceivedUserGesture, + OnSetHasReceivedUserGesture) #if defined(OS_ANDROID) IPC_MESSAGE_HANDLER(FrameMsg_ActivateNearestFindResult, OnActivateNearestFindResult) @@ -4019,15 +4021,8 @@ document_loader->SetSourceLocation(source_location); } - // Mark the loader as user activated if started from a context menu and the - // URLs are matching the user activation persistence rules. - if (navigation_state->common_params().started_from_context_menu && - WebDocumentLoader::ShouldPersistUserActivation( - url::Origin::Create(navigation_state->common_params().url), - url::Origin::Create( - navigation_state->common_params().referrer.url))) { + if (navigation_state->request_params().was_activated) document_loader->SetUserActivated(); - } // Create the serviceworker's per-document network observing object if it // does not exist (When navigation happens within a page, the provider already @@ -5526,7 +5521,10 @@ current_history_item_.SetTarget( blink::WebString::FromUTF8(unique_name_helper_.value())); bool is_new_navigation = commit_type == blink::kWebStandardCommit; - if (is_new_navigation) { + if (request_params.should_clear_history_list) { + render_view_->history_list_offset_ = 0; + render_view_->history_list_length_ = 1; + } else if (is_new_navigation) { DCHECK(!navigation_state->common_params().should_replace_current_entry || render_view_->history_list_length_ > 0); if (!navigation_state->common_params().should_replace_current_entry) { @@ -6290,6 +6288,10 @@ pending_routing_token_callbacks_.clear(); } +void RenderFrameImpl::OnSetHasReceivedUserGesture() { + frame_->SetHasReceivedUserGesture(); +} + void RenderFrameImpl::RequestOverlayRoutingToken( media::RoutingTokenCallback callback) { if (overlay_routing_token_.has_value()) { @@ -6601,10 +6603,6 @@ request_params.current_history_list_offset; render_view_->history_list_length_ = request_params.current_history_list_length; - if (request_params.should_clear_history_list) { - CHECK_EQ(-1, render_view_->history_list_offset_); - CHECK_EQ(0, render_view_->history_list_length_); - } } void RenderFrameImpl::BeginNavigation(const NavigationPolicyInfo& info) {
diff --git a/content/renderer/render_frame_impl.h b/content/renderer/render_frame_impl.h index fceb931..3643835 100644 --- a/content/renderer/render_frame_impl.h +++ b/content/renderer/render_frame_impl.h
@@ -1064,6 +1064,7 @@ void OnFindMatchRects(int current_version); #endif void OnSetOverlayRoutingToken(const base::UnguessableToken& token); + void OnSetHasReceivedUserGesture(); #if BUILDFLAG(USE_EXTERNAL_POPUP_MENU) #if defined(OS_MACOSX)
diff --git a/content/renderer/render_view_browsertest.cc b/content/renderer/render_view_browsertest.cc index 171b78e6..3a7f90af 100644 --- a/content/renderer/render_view_browsertest.cc +++ b/content/renderer/render_view_browsertest.cc
@@ -73,6 +73,7 @@ #include "third_party/WebKit/public/web/WebDeviceEmulationParams.h" #include "third_party/WebKit/public/web/WebDocumentLoader.h" #include "third_party/WebKit/public/web/WebFrameContentDumper.h" +#include "third_party/WebKit/public/web/WebGlobalObjectReusePolicy.h" #include "third_party/WebKit/public/web/WebHistoryCommitType.h" #include "third_party/WebKit/public/web/WebHistoryItem.h" #include "third_party/WebKit/public/web/WebInputMethodController.h" @@ -2224,19 +2225,59 @@ EXPECT_EQ(0, view()->HistoryBackListCount() + view()->HistoryForwardListCount() + 1); - // Receive a Navigate message with history parameters. + // Receive a CommitNavigation message with history parameters. RequestNavigationParams request_params; - request_params.current_history_list_length = 2; request_params.current_history_list_offset = 1; - request_params.pending_history_list_offset = 2; + request_params.current_history_list_length = 2; frame()->Navigate(CommonNavigationParams(), request_params); - // The history list in RenderView should have been updated. + // The current history list in RenderView is updated. EXPECT_EQ(1, view()->HistoryBackListCount()); EXPECT_EQ(2, view()->HistoryBackListCount() + view()->HistoryForwardListCount() + 1); } +// Ensure the RenderViewImpl history list is properly updated when starting a +// new history browser-initiated navigation. +TEST_F(RenderViewImplTest, HistoryIsProperlyUpdatedOnHistoryNavigation) { + EXPECT_EQ(0, view()->HistoryBackListCount()); + EXPECT_EQ(0, view()->HistoryBackListCount() + + view()->HistoryForwardListCount() + 1); + + // Receive a CommitNavigation message with history parameters. + RequestNavigationParams request_params; + request_params.current_history_list_offset = 1; + request_params.current_history_list_length = 25; + request_params.pending_history_list_offset = 12; + request_params.nav_entry_id = 777; + frame()->Navigate(CommonNavigationParams(), request_params); + + // The current history list in RenderView is updated. + EXPECT_EQ(12, view()->HistoryBackListCount()); + EXPECT_EQ(25, view()->HistoryBackListCount() + + view()->HistoryForwardListCount() + 1); +} + +// Ensure the RenderViewImpl history list is properly updated when starting a +// new history browser-initiated navigation with should_clear_history_list +TEST_F(RenderViewImplTest, HistoryIsProperlyUpdatedOnShouldClearHistoryList) { + EXPECT_EQ(0, view()->HistoryBackListCount()); + EXPECT_EQ(0, view()->HistoryBackListCount() + + view()->HistoryForwardListCount() + 1); + + // Receive a CommitNavigation message with history parameters. + RequestNavigationParams request_params; + request_params.current_history_list_offset = 12; + request_params.current_history_list_length = 25; + request_params.should_clear_history_list = true; + frame()->Navigate(CommonNavigationParams(), request_params); + + // The current history list in RenderView is updated. + EXPECT_EQ(0, view()->HistoryBackListCount()); + EXPECT_EQ(1, view()->HistoryBackListCount() + + view()->HistoryForwardListCount() + 1); +} + // IPC Listener that runs a callback when a console.log() is executed from // javascript. class ConsoleCallbackFilter : public IPC::Listener {
diff --git a/content/renderer/render_view_impl.cc b/content/renderer/render_view_impl.cc index 953c4dc7..514a629 100644 --- a/content/renderer/render_view_impl.cc +++ b/content/renderer/render_view_impl.cc
@@ -1045,7 +1045,11 @@ observers_.RemoveObserver(observer); } -blink::WebView* RenderViewImpl::webview() const { +blink::WebView* RenderViewImpl::webview() { + return webview_; +} + +const blink::WebView* RenderViewImpl::webview() const { return webview_; } @@ -1207,8 +1211,10 @@ void RenderViewImpl::OnSetHistoryOffsetAndLength(int history_offset, int history_length) { - DCHECK_GE(history_offset, -1); - DCHECK_GE(history_length, 0); + // -1 <= history_offset < history_length <= kMaxSessionHistoryEntries(50). + DCHECK_LE(-1, history_offset); + DCHECK_LT(history_offset, history_length); + DCHECK_LE(history_length, kMaxSessionHistoryEntries); history_list_offset_ = history_offset; history_list_length_ = history_length; @@ -1819,8 +1825,8 @@ return RenderWidget::Send(message); } -RenderWidget* RenderViewImpl::GetWidget() const { - return const_cast<RenderWidget*>(static_cast<const RenderWidget*>(this)); +RenderWidget* RenderViewImpl::GetWidget() { + return this; } RenderFrameImpl* RenderViewImpl::GetMainRenderFrame() {
diff --git a/content/renderer/render_view_impl.h b/content/renderer/render_view_impl.h index 326d883..051994ec 100644 --- a/content/renderer/render_view_impl.h +++ b/content/renderer/render_view_impl.h
@@ -139,10 +139,11 @@ static RenderViewImpl* FromRoutingID(int routing_id); // May return NULL when the view is closing. - blink::WebView* webview() const; + blink::WebView* webview(); + const blink::WebView* webview() const; // Returns the RenderWidget for this RenderView. - RenderWidget* GetWidget() const; + RenderWidget* GetWidget(); const WebPreferences& webkit_preferences() const { return webkit_preferences_; @@ -543,7 +544,6 @@ void OnSelectWordAroundCaret(); void OnAudioStateChanged(bool is_audio_playing); #if defined(OS_ANDROID) - void OnUndoScrollFocusedEditableNodeIntoRect(); void OnUpdateBrowserControlsState(bool enable_hiding, bool enable_showing, bool animate);
diff --git a/content/shell/BUILD.gn b/content/shell/BUILD.gn index 8b965f6..ceb7b0e2 100644 --- a/content/shell/BUILD.gn +++ b/content/shell/BUILD.gn
@@ -267,7 +267,7 @@ "//ppapi/features", "//sandbox", "//services/device/public/interfaces", - "//services/network/public/cpp:network_features", + "//services/network/public/cpp", "//services/service_manager/public/cpp", "//services/test/echo:lib", "//services/test/echo/public/interfaces",
diff --git a/content/shell/app/blink_test_platform_support_fuchsia.cc b/content/shell/app/blink_test_platform_support_fuchsia.cc index bb7a1db..659030f 100644 --- a/content/shell/app/blink_test_platform_support_fuchsia.cc +++ b/content/shell/app/blink_test_platform_support_fuchsia.cc
@@ -7,12 +7,11 @@ namespace content { bool CheckLayoutSystemDeps() { - return false; + return true; } bool BlinkTestPlatformInitialize() { - // TODO(fuchsia): Support Blink's layout test platform (crbug.com/778467). - return false; + return true; } } // namespace content
diff --git a/content/shell/browser/layout_test/test_info_extractor.cc b/content/shell/browser/layout_test/test_info_extractor.cc index 2f3aaa2..89e86ac7 100644 --- a/content/shell/browser/layout_test/test_info_extractor.cc +++ b/content/shell/browser/layout_test/test_info_extractor.cc
@@ -28,28 +28,6 @@ namespace { -#if defined(OS_ANDROID) -// On Android, all passed tests will be paths to a local temporary directory. -// However, because we can't transfer all test files to the device, translate -// those paths to a local, forwarded URL so the host can serve them. -bool GetTestUrlForAndroid(std::string& path_or_url, GURL* url) { - // Path to search for when translating a layout test path to an URL. - const char kAndroidLayoutTestPath[] = - "/data/local/tmp/third_party/WebKit/LayoutTests/"; - // The base URL from which layout tests are being served on Android. - const char kAndroidLayoutTestBase[] = "http://127.0.0.1:8000/all-tests/"; - - if (path_or_url.find(kAndroidLayoutTestPath) == std::string::npos) - return false; - - std::string test_location(kAndroidLayoutTestBase); - test_location.append(path_or_url.substr(strlen(kAndroidLayoutTestPath))); - - *url = GURL(test_location); - return true; -} -#endif // defined(OS_ANDROID) - #if defined(OS_FUCHSIA) // Fuchsia doesn't support stdin stream for packaged apps. This means that when // running content_shell on Fuchsia it's not possible to use stdin to pass list @@ -106,15 +84,7 @@ const bool enable_pixel_dumping = (pixel_switch == "--pixel-test" || pixel_switch == "-p"); - GURL test_url; -#if defined(OS_ANDROID) - if (GetTestUrlForAndroid(path_or_url, &test_url)) { - return std::make_unique<TestInfo>(test_url, enable_pixel_dumping, - expected_pixel_hash, base::FilePath()); - } -#endif - - test_url = GURL(path_or_url); + GURL test_url(path_or_url); if (!(test_url.is_valid() && test_url.has_scheme())) { // We're outside of the message loop here, and this is a test. base::ScopedAllowBlockingForTesting allow_blocking;
diff --git a/content/shell/browser/shell_download_manager_delegate.cc b/content/shell/browser/shell_download_manager_delegate.cc index ebefd9c..90a6a0f 100644 --- a/content/shell/browser/shell_download_manager_delegate.cc +++ b/content/shell/browser/shell_download_manager_delegate.cc
@@ -73,7 +73,7 @@ if (!download->GetForcedFilePath().empty()) { callback.Run(download->GetForcedFilePath(), DownloadItem::TARGET_DISPOSITION_OVERWRITE, - DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS, + download::DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS, download->GetForcedFilePath(), DOWNLOAD_INTERRUPT_REASON_NONE); return true; } @@ -138,7 +138,7 @@ if (suppress_prompting_) { // Testing exit. callback.Run(suggested_path, DownloadItem::TARGET_DISPOSITION_OVERWRITE, - DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS, + download::DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS, suggested_path.AddExtension(FILE_PATH_LITERAL(".crdownload")), DOWNLOAD_INTERRUPT_REASON_NONE); return; @@ -184,7 +184,7 @@ #endif callback.Run(result, DownloadItem::TARGET_DISPOSITION_PROMPT, - DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS, result, + download::DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS, result, DOWNLOAD_INTERRUPT_REASON_NONE); }
diff --git a/content/shell/test_runner/web_ax_object_proxy.cc b/content/shell/test_runner/web_ax_object_proxy.cc index 9781cec..3d7cb13 100644 --- a/content/shell/test_runner/web_ax_object_proxy.cc +++ b/content/shell/test_runner/web_ax_object_proxy.cc
@@ -124,6 +124,14 @@ return result.append("InputTime"); case blink::kWebAXRoleLabel: return result.append("Label"); + case blink::kWebAXRoleLayoutTable: + return result.append("LayoutTable"); + case blink::kWebAXRoleLayoutTableCell: + return result.append("LayoutTableCell"); + case blink::kWebAXRoleLayoutTableColumn: + return result.append("LayoutTableColumn"); + case blink::kWebAXRoleLayoutTableRow: + return result.append("LayoutTableRow"); case blink::kWebAXRoleLegend: return result.append("Legend"); case blink::kWebAXRoleLink:
diff --git a/content/test/BUILD.gn b/content/test/BUILD.gn index cb4a48a..9e10ddf 100644 --- a/content/test/BUILD.gn +++ b/content/test/BUILD.gn
@@ -71,8 +71,6 @@ "../public/test/cache_test_util.h", "../public/test/content_test_suite_base.cc", "../public/test/content_test_suite_base.h", - "../public/test/controllable_http_response.cc", - "../public/test/controllable_http_response.h", "../public/test/download_test_observer.cc", "../public/test/download_test_observer.h", "../public/test/fake_download_item.cc", @@ -1305,6 +1303,7 @@ "../browser/loader/cross_site_document_resource_handler_unittest.cc", "../browser/loader/detachable_resource_handler_unittest.cc", "../browser/loader/intercepting_resource_handler_unittest.cc", + "../browser/loader/merkle_integrity_source_stream_unittest.cc", "../browser/loader/mime_sniffing_resource_handler_unittest.cc", "../browser/loader/mock_resource_loader.cc", "../browser/loader/mock_resource_loader.h", @@ -1525,9 +1524,7 @@ # TODO(jam): move these network/ tests to services/network. "../network/cors/cors_url_loader_unittest.cc", - "../network/network_service_unittest.cc", "../network/resource_scheduler_unittest.cc", - "../network/url_loader_unittest.cc", "../public/common/drop_data_unittest.cc", "../public/common/network_connection_tracker_unittest.cc", "../public/common/simple_url_loader_unittest.cc", @@ -1715,7 +1712,6 @@ "//services/network:network_service", "//services/network:test_support", "//services/network/public/cpp", - "//services/network/public/cpp:network_features", "//services/network/public/interfaces:interfaces", "//services/proxy_resolver/:lib", "//services/service_manager/public/cpp:service_test_support", @@ -2050,10 +2046,7 @@ service_manifest("content_unittests_manifest") { name = "content_unittests" source = "unittests_manifest.json" - packaged_services = [ - "//services/file:manifest", - "//services/network:manifest", - ] + packaged_services = [ "//services/file:manifest" ] } catalog("content_unittests_catalog") {
diff --git a/content/test/data/accessibility/aria/aria-sort-html-table-expected-mac.txt b/content/test/data/accessibility/aria/aria-sort-html-table-expected-mac.txt index f715133..d49f6c8 100644 --- a/content/test/data/accessibility/aria/aria-sort-html-table-expected-mac.txt +++ b/content/test/data/accessibility/aria/aria-sort-html-table-expected-mac.txt
@@ -132,4 +132,4 @@ ++++AXColumn ++++AXGroup ++AXGroup -++++AXStaticText AXValue='Alphabet' +++++AXStaticText AXValue='Alphabet' \ No newline at end of file
diff --git a/content/test/data/accessibility/aria/aria-sort-html-table-expected-win.txt b/content/test/data/accessibility/aria/aria-sort-html-table-expected-win.txt index 3111d24..243eb8d 100644 --- a/content/test/data/accessibility/aria/aria-sort-html-table-expected-win.txt +++ b/content/test/data/accessibility/aria/aria-sort-html-table-expected-win.txt
@@ -132,4 +132,4 @@ ++++ROLE_SYSTEM_COLUMN ++++IA2_ROLE_SECTION ++IA2_ROLE_SECTION -++++ROLE_SYSTEM_STATICTEXT name='Alphabet' +++++ROLE_SYSTEM_STATICTEXT name='Alphabet' \ No newline at end of file
diff --git a/content/test/data/accessibility/aria/aria-sort-html-table.html b/content/test/data/accessibility/aria/aria-sort-html-table.html index 10fabe4..16c3b1b 100644 --- a/content/test/data/accessibility/aria/aria-sort-html-table.html +++ b/content/test/data/accessibility/aria/aria-sort-html-table.html
@@ -138,7 +138,7 @@ <!-- Non-data table: aria-sort should not be exposed. --> -<table> +<table role="none"> <tr> <th aria-sort="ascending">Alphabet</th> </tr>
diff --git a/content/test/data/accessibility/html/landmark-expected-android.txt b/content/test/data/accessibility/html/landmark-expected-android.txt index 55ae28d2..9b5f5bf 100644 --- a/content/test/data/accessibility/html/landmark-expected-android.txt +++ b/content/test/data/accessibility/html/landmark-expected-android.txt
@@ -30,7 +30,8 @@ ++++android.view.View name='This should NOT have banner role.' ++android.view.View role_description='graphic' ++++android.view.View name='This should NOT have banner role.' -++android.view.View name='This should NOT have banner role.' +++android.view.View +++++android.view.View name='This should NOT have banner role.' ++android.view.View role_description='main' ++++android.view.View name='This should NOT have banner role.' ++android.view.View role_description='article' @@ -87,6 +88,7 @@ ++++android.view.View name='This should NOT have footer role.' ++android.view.View role_description='graphic' ++++android.view.View name='This should NOT have footer role.' -++android.view.View name='This should NOT have footer role.' +++android.view.View +++++android.view.View name='This should NOT have footer role.' ++android.view.View role_description='main' ++++android.view.View name='This should NOT have footer role.' \ No newline at end of file
diff --git a/content/test/data/accessibility/html/landmark-expected-blink.txt b/content/test/data/accessibility/html/landmark-expected-blink.txt index 5776927..3ff926d 100644 --- a/content/test/data/accessibility/html/landmark-expected-blink.txt +++ b/content/test/data/accessibility/html/landmark-expected-blink.txt
@@ -76,9 +76,10 @@ ++++genericContainer ++++++staticText name='This should NOT have banner role.' ++++++++inlineTextBox name='This should NOT have banner role.' -++genericContainer -++++staticText name='This should NOT have banner role.' -++++++inlineTextBox name='This should NOT have banner role.' +++group +++++genericContainer +++++++staticText name='This should NOT have banner role.' +++++++++inlineTextBox name='This should NOT have banner role.' ++main ++++genericContainer ++++++staticText name='This should NOT have banner role.' @@ -193,10 +194,11 @@ ++++genericContainer ++++++staticText name='This should NOT have footer role.' ++++++++inlineTextBox name='This should NOT have footer role.' -++genericContainer -++++staticText name='This should NOT have footer role.' -++++++inlineTextBox name='This should NOT have footer role.' +++group +++++genericContainer +++++++staticText name='This should NOT have footer role.' +++++++++inlineTextBox name='This should NOT have footer role.' ++main ++++genericContainer ++++++staticText name='This should NOT have footer role.' -++++++++inlineTextBox name='This should NOT have footer role.' \ No newline at end of file +++++++++inlineTextBox name='This should NOT have footer role.'
diff --git a/content/test/data/accessibility/html/landmark-expected-mac.txt b/content/test/data/accessibility/html/landmark-expected-mac.txt index bb6fee1..5e45a8dd 100644 --- a/content/test/data/accessibility/html/landmark-expected-mac.txt +++ b/content/test/data/accessibility/html/landmark-expected-mac.txt
@@ -54,7 +54,8 @@ ++++AXGroup AXRoleDescription='group' ++++++AXStaticText AXRoleDescription='text' AXValue='This should NOT have banner role.' ++AXGroup AXRoleDescription='group' -++++AXStaticText AXRoleDescription='text' AXValue='This should NOT have banner role.' +++++AXGroup AXRoleDescription='group' +++++++AXStaticText AXRoleDescription='text' AXValue='This should NOT have banner role.' ++AXGroup AXSubrole=AXLandmarkMain AXRoleDescription='main' ++++AXGroup AXRoleDescription='group' ++++++AXStaticText AXRoleDescription='text' AXValue='This should NOT have banner role.' @@ -141,7 +142,8 @@ ++++AXGroup AXRoleDescription='group' ++++++AXStaticText AXRoleDescription='text' AXValue='This should NOT have footer role.' ++AXGroup AXRoleDescription='group' -++++AXStaticText AXRoleDescription='text' AXValue='This should NOT have footer role.' +++++AXGroup AXRoleDescription='group' +++++++AXStaticText AXRoleDescription='text' AXValue='This should NOT have footer role.' ++AXGroup AXSubrole=AXLandmarkMain AXRoleDescription='main' ++++AXGroup AXRoleDescription='group' ++++++AXStaticText AXRoleDescription='text' AXValue='This should NOT have footer role.' \ No newline at end of file
diff --git a/content/test/data/accessibility/html/landmark-expected-win.txt b/content/test/data/accessibility/html/landmark-expected-win.txt index 85d90fc..5ff09a39 100644 --- a/content/test/data/accessibility/html/landmark-expected-win.txt +++ b/content/test/data/accessibility/html/landmark-expected-win.txt
@@ -53,8 +53,9 @@ ++ROLE_SYSTEM_GROUPING xml-roles:figure ++++IA2_ROLE_SECTION ++++++ROLE_SYSTEM_STATICTEXT name='This should NOT have banner role.' -++IA2_ROLE_SECTION -++++ROLE_SYSTEM_STATICTEXT name='This should NOT have banner role.' +++ROLE_SYSTEM_GROUPING xml-roles:group +++++IA2_ROLE_SECTION +++++++ROLE_SYSTEM_STATICTEXT name='This should NOT have banner role.' ++IA2_ROLE_PARAGRAPH xml-roles:main ++++IA2_ROLE_SECTION ++++++ROLE_SYSTEM_STATICTEXT name='This should NOT have banner role.' @@ -140,8 +141,9 @@ ++ROLE_SYSTEM_GROUPING xml-roles:figure ++++IA2_ROLE_SECTION ++++++ROLE_SYSTEM_STATICTEXT name='This should NOT have footer role.' -++IA2_ROLE_SECTION -++++ROLE_SYSTEM_STATICTEXT name='This should NOT have footer role.' +++ROLE_SYSTEM_GROUPING xml-roles:group +++++IA2_ROLE_SECTION +++++++ROLE_SYSTEM_STATICTEXT name='This should NOT have footer role.' ++IA2_ROLE_PARAGRAPH xml-roles:main ++++IA2_ROLE_SECTION ++++++ROLE_SYSTEM_STATICTEXT name='This should NOT have footer role.' \ No newline at end of file
diff --git a/content/test/data/accessibility/html/landmark.html b/content/test/data/accessibility/html/landmark.html index cc061ce..2d26215 100644 --- a/content/test/data/accessibility/html/landmark.html +++ b/content/test/data/accessibility/html/landmark.html
@@ -31,7 +31,7 @@ <details><header>This should NOT header role.</header></details> <fieldset><header>This should NOT have banner role.</header></fieldset> <figure><header>This should NOT have banner role.</header></figure> - <table><tr><td><header>This should NOT have banner role.</header></td></tr></table> + <table role="group"><tr><td><header>This should NOT have banner role.</header></td></tr></table> <main><header>This should NOT have banner role.</header></main> <article><div><header>This should NOT banner role.</header></div></article> @@ -42,7 +42,7 @@ <details><div><header>This should NOT header role.</header></div></details> <fieldset><div><header>This should NOT have banner role.</header></div></fieldset> <figure><div><header>This should NOT have banner role.</header></div></figure> - <table><tr><td><div><header>This should NOT have banner role.</header><div></td></tr></table> + <table role="none"><tr><td><div><header>This should NOT have banner role.</header><div></td></tr></table> <main><div><header>This should NOT have banner role.</header></div></main> <article><footer>This should NOT footer role.</footer></article> @@ -53,7 +53,7 @@ <details><footer>This should NOT footer role.</footer></details> <fieldset><footer>This should NOT have footer role.</footer></fieldset> <figure><footer>This should NOT have footer role.</footer></figure> - <table><tr><td><footer>This should NOT have footer role.</footer></td></tr></table> + <table role="none"><tr><td><footer>This should NOT have footer role.</footer></td></tr></table> <main><footer>This should NOT have footer role.</footer></main> <article><div><footer>This should NOT footer role.</footer></div></article> @@ -64,7 +64,7 @@ <details><div><footer>This should NOT footer role.</footer></div></details> <fieldset><div><footer>This should NOT have footer role.</footer></div></fieldset> <figure><div><footer>This should NOT have footer role.</footer></div></figure> - <table><tr><td><div><footer>This should NOT have footer role.</footer><div></td></tr></table> + <table role="group"><tr><td><div><footer>This should NOT have footer role.</footer><div></td></tr></table> <main><div><footer>This should NOT have footer role.</footer></div></main> </body> </html>
diff --git a/content/test/data/accessibility/html/modal-dialog-opened-expected-android.txt b/content/test/data/accessibility/html/modal-dialog-opened-expected-android.txt index 9cd4c7f2..badc901b 100644 --- a/content/test/data/accessibility/html/modal-dialog-opened-expected-android.txt +++ b/content/test/data/accessibility/html/modal-dialog-opened-expected-android.txt
@@ -1,4 +1,5 @@ android.webkit.WebView focusable scrollable +++android.view.View ++android.app.Dialog role_description='dialog' ++++android.view.View name='The dialog subtree should be the only text content in the accessibility tree. ' -++++android.view.View role_description='link' clickable focusable focused link name='Link inside the dialog.' \ No newline at end of file +++++android.view.View role_description='link' clickable focusable focused link name='Link inside the dialog.'
diff --git a/content/test/data/accessibility/html/modal-dialog-opened-expected-blink.txt b/content/test/data/accessibility/html/modal-dialog-opened-expected-blink.txt index a47840b..7bf19fc 100644 --- a/content/test/data/accessibility/html/modal-dialog-opened-expected-blink.txt +++ b/content/test/data/accessibility/html/modal-dialog-opened-expected-blink.txt
@@ -1,7 +1,8 @@ rootWebArea +++genericContainer ++dialog ++++staticText name='The dialog subtree should be the only text content in the accessibility tree. ' ++++++inlineTextBox name='The dialog subtree should be the only text content in the accessibility tree. ' ++++link name='Link inside the dialog.' ++++++staticText name='Link inside the dialog.' -++++++++inlineTextBox name='Link inside the dialog.' \ No newline at end of file +++++++++inlineTextBox name='Link inside the dialog.'
diff --git a/content/test/data/accessibility/html/modal-dialog-opened-expected-mac.txt b/content/test/data/accessibility/html/modal-dialog-opened-expected-mac.txt index e64c731..e3e9609b 100644 --- a/content/test/data/accessibility/html/modal-dialog-opened-expected-mac.txt +++ b/content/test/data/accessibility/html/modal-dialog-opened-expected-mac.txt
@@ -1,4 +1,5 @@ AXWebArea +++AXGroup ++AXGroup AXSubrole=AXApplicationDialog ++++AXStaticText AXValue='The dialog subtree should be the only text content in the accessibility tree. ' ++++AXLink AXTitle='Link inside the dialog.'
diff --git a/content/test/data/accessibility/html/modal-dialog-opened-expected-win.txt b/content/test/data/accessibility/html/modal-dialog-opened-expected-win.txt index 523860d..09ab3cb 100644 --- a/content/test/data/accessibility/html/modal-dialog-opened-expected-win.txt +++ b/content/test/data/accessibility/html/modal-dialog-opened-expected-win.txt
@@ -1,5 +1,6 @@ ROLE_SYSTEM_DOCUMENT READONLY FOCUSABLE +++IA2_ROLE_SECTION ++ROLE_SYSTEM_DIALOG IA2_STATE_MODAL ++++ROLE_SYSTEM_STATICTEXT name='The dialog subtree should be the only text content in the accessibility tree. ' ++++ROLE_SYSTEM_LINK name='Link inside the dialog.' FOCUSABLE -++++++ROLE_SYSTEM_STATICTEXT name='Link inside the dialog.' \ No newline at end of file +++++++ROLE_SYSTEM_STATICTEXT name='Link inside the dialog.'
diff --git a/content/test/data/accessibility/html/modal-dialog-stack-expected-android.txt b/content/test/data/accessibility/html/modal-dialog-stack-expected-android.txt index c5778ff..75cb37a 100644 --- a/content/test/data/accessibility/html/modal-dialog-stack-expected-android.txt +++ b/content/test/data/accessibility/html/modal-dialog-stack-expected-android.txt
@@ -1,4 +1,5 @@ android.webkit.WebView focusable focused scrollable +++android.view.View ++android.app.Dialog role_description='dialog' ++++android.view.View name='This is the now active dialog. Of course it should be in the tree. ' -++++android.widget.Button role_description='button' clickable focusable name='This is in the active dialog and should be in the tree.' \ No newline at end of file +++++android.widget.Button role_description='button' clickable focusable name='This is in the active dialog and should be in the tree.'
diff --git a/content/test/data/accessibility/html/modal-dialog-stack-expected-blink.txt b/content/test/data/accessibility/html/modal-dialog-stack-expected-blink.txt index 96ef96fa..127caf8 100644 --- a/content/test/data/accessibility/html/modal-dialog-stack-expected-blink.txt +++ b/content/test/data/accessibility/html/modal-dialog-stack-expected-blink.txt
@@ -1,5 +1,6 @@ rootWebArea +++genericContainer ++dialog ++++staticText name='This is the now active dialog. Of course it should be in the tree. ' ++++++inlineTextBox name='This is the now active dialog. Of course it should be in the tree. ' -++++button name='This is in the active dialog and should be in the tree.' \ No newline at end of file +++++button name='This is in the active dialog and should be in the tree.'
diff --git a/content/test/data/accessibility/html/modal-dialog-stack-expected-mac.txt b/content/test/data/accessibility/html/modal-dialog-stack-expected-mac.txt index 8ce8fe3..fd373b1 100644 --- a/content/test/data/accessibility/html/modal-dialog-stack-expected-mac.txt +++ b/content/test/data/accessibility/html/modal-dialog-stack-expected-mac.txt
@@ -1,4 +1,5 @@ AXWebArea +++AXGroup ++AXGroup AXSubrole=AXApplicationDialog ++++AXStaticText AXValue='This is the now active dialog. Of course it should be in the tree. ' ++++AXButton AXTitle='This is in the active dialog and should be in the tree.'
diff --git a/content/test/data/accessibility/html/modal-dialog-stack-expected-win.txt b/content/test/data/accessibility/html/modal-dialog-stack-expected-win.txt index d278bd9..df25937bd 100644 --- a/content/test/data/accessibility/html/modal-dialog-stack-expected-win.txt +++ b/content/test/data/accessibility/html/modal-dialog-stack-expected-win.txt
@@ -1,4 +1,5 @@ ROLE_SYSTEM_DOCUMENT READONLY FOCUSABLE +++IA2_ROLE_SECTION ++ROLE_SYSTEM_DIALOG IA2_STATE_MODAL ++++ROLE_SYSTEM_STATICTEXT name='This is the now active dialog. Of course it should be in the tree. ' -++++ROLE_SYSTEM_PUSHBUTTON name='This is in the active dialog and should be in the tree.' FOCUSABLE \ No newline at end of file +++++ROLE_SYSTEM_PUSHBUTTON name='This is in the active dialog and should be in the tree.' FOCUSABLE
diff --git a/content/test/data/accessibility/html/table-layout-expected-android.txt b/content/test/data/accessibility/html/table-layout-expected-android.txt new file mode 100644 index 0000000..784ded61 --- /dev/null +++ b/content/test/data/accessibility/html/table-layout-expected-android.txt
@@ -0,0 +1,18 @@ +android.webkit.WebView focusable focused scrollable name='Table example #2' +++android.view.View +++++android.view.View +++++++android.view.View name='1' +++++++android.view.View name='2' +++++++android.view.View name='3' +++++android.view.View +++++++android.view.View name='4' +++++++android.view.View name='5' +++++++android.view.View name='6' +++++android.view.View +++++++android.view.View name='7' +++++++android.view.View name='8' +++++++android.view.View name='9' +++++android.view.View +++++android.view.View +++++android.view.View +++++android.view.View
diff --git a/content/test/data/accessibility/html/table-layout-expected-blink.txt b/content/test/data/accessibility/html/table-layout-expected-blink.txt new file mode 100644 index 0000000..457f970d --- /dev/null +++ b/content/test/data/accessibility/html/table-layout-expected-blink.txt
@@ -0,0 +1,36 @@ +rootWebArea name='Table example #2' +++layoutTable +++++layoutTableRow +++++++layoutTableCell name='1' +++++++++staticText name='1' +++++++++++inlineTextBox name='1' +++++++layoutTableCell name='2' +++++++++staticText name='2' +++++++++++inlineTextBox name='2' +++++++layoutTableCell name='3' +++++++++staticText name='3' +++++++++++inlineTextBox name='3' +++++layoutTableRow +++++++layoutTableCell name='4' +++++++++staticText name='4' +++++++++++inlineTextBox name='4' +++++++layoutTableCell name='5' +++++++++staticText name='5' +++++++++++inlineTextBox name='5' +++++++layoutTableCell name='6' +++++++++staticText name='6' +++++++++++inlineTextBox name='6' +++++layoutTableRow +++++++layoutTableCell name='7' +++++++++staticText name='7' +++++++++++inlineTextBox name='7' +++++++layoutTableCell name='8' +++++++++staticText name='8' +++++++++++inlineTextBox name='8' +++++++layoutTableCell name='9' +++++++++staticText name='9' +++++++++++inlineTextBox name='9' +++++layoutTableColumn +++++layoutTableColumn +++++layoutTableColumn +++++tableHeaderContainer
diff --git a/content/test/data/accessibility/html/table-layout-expected-mac.txt b/content/test/data/accessibility/html/table-layout-expected-mac.txt new file mode 100644 index 0000000..24f105a0 --- /dev/null +++ b/content/test/data/accessibility/html/table-layout-expected-mac.txt
@@ -0,0 +1,27 @@ +AXWebArea AXTitle='Table example #2' +++AXGroup +++++AXGroup +++++++AXGroup AXTitle='1' +++++++++AXStaticText AXValue='1' +++++++AXGroup AXTitle='2' +++++++++AXStaticText AXValue='2' +++++++AXGroup AXTitle='3' +++++++++AXStaticText AXValue='3' +++++AXGroup +++++++AXGroup AXTitle='4' +++++++++AXStaticText AXValue='4' +++++++AXGroup AXTitle='5' +++++++++AXStaticText AXValue='5' +++++++AXGroup AXTitle='6' +++++++++AXStaticText AXValue='6' +++++AXGroup +++++++AXGroup AXTitle='7' +++++++++AXStaticText AXValue='7' +++++++AXGroup AXTitle='8' +++++++++AXStaticText AXValue='8' +++++++AXGroup AXTitle='9' +++++++++AXStaticText AXValue='9' +++++AXGroup +++++AXGroup +++++AXGroup +++++AXGroup
diff --git a/content/test/data/accessibility/html/table-layout-expected-win.txt b/content/test/data/accessibility/html/table-layout-expected-win.txt new file mode 100644 index 0000000..c82f123c --- /dev/null +++ b/content/test/data/accessibility/html/table-layout-expected-win.txt
@@ -0,0 +1,27 @@ +ROLE_SYSTEM_DOCUMENT name='Table example #2' READONLY FOCUSABLE +++ROLE_SYSTEM_TABLE layout-guess:true +++++ROLE_SYSTEM_ROW +++++++ROLE_SYSTEM_CELL name='1' +++++++++ROLE_SYSTEM_STATICTEXT name='1' +++++++ROLE_SYSTEM_CELL name='2' +++++++++ROLE_SYSTEM_STATICTEXT name='2' +++++++ROLE_SYSTEM_CELL name='3' +++++++++ROLE_SYSTEM_STATICTEXT name='3' +++++ROLE_SYSTEM_ROW +++++++ROLE_SYSTEM_CELL name='4' +++++++++ROLE_SYSTEM_STATICTEXT name='4' +++++++ROLE_SYSTEM_CELL name='5' +++++++++ROLE_SYSTEM_STATICTEXT name='5' +++++++ROLE_SYSTEM_CELL name='6' +++++++++ROLE_SYSTEM_STATICTEXT name='6' +++++ROLE_SYSTEM_ROW +++++++ROLE_SYSTEM_CELL name='7' +++++++++ROLE_SYSTEM_STATICTEXT name='7' +++++++ROLE_SYSTEM_CELL name='8' +++++++++ROLE_SYSTEM_STATICTEXT name='8' +++++++ROLE_SYSTEM_CELL name='9' +++++++++ROLE_SYSTEM_STATICTEXT name='9' +++++ROLE_SYSTEM_COLUMN +++++ROLE_SYSTEM_COLUMN +++++ROLE_SYSTEM_COLUMN +++++IA2_ROLE_SECTION
diff --git a/content/test/data/accessibility/html/table-layout.html b/content/test/data/accessibility/html/table-layout.html new file mode 100644 index 0000000..26b47c1 --- /dev/null +++ b/content/test/data/accessibility/html/table-layout.html
@@ -0,0 +1,26 @@ +<!-- +@MAC-ALLOW:AXIndex=* +@MAC-ALLOW:AXColumnIndexRange=* +@MAC-ALLOW:AXRowIndexRange=* +--> +<!DOCTYPE html> +<html> +<head> + <title>Table example #2</title> +</head> +<body> + +<table> +<tr> +<td>1</td><td>2</td><td>3</td> +</tr> +<tr> +<td>4</td><td>5</td><td>6</td> +</tr> +<tr> +<td>7</td><td>8</td><td>9</td> +</tr> +</table> + +</body> +</html>
diff --git a/content/test/data/accessibility/html/table-presentation-expected-blink.txt b/content/test/data/accessibility/html/table-presentation-expected-blink.txt new file mode 100644 index 0000000..fc19af8 --- /dev/null +++ b/content/test/data/accessibility/html/table-presentation-expected-blink.txt
@@ -0,0 +1,13 @@ +rootWebArea name='Table with role=presentation' +++genericContainer +++++staticText name='1' +++++++inlineTextBox name='1' +++genericContainer +++++staticText name='2' +++++++inlineTextBox name='2' +++genericContainer +++++staticText name='4' +++++++inlineTextBox name='4' +++genericContainer +++++staticText name='5' +++++++inlineTextBox name='5' \ No newline at end of file
diff --git a/content/test/data/accessibility/html/table-presentation-expected-mac.txt b/content/test/data/accessibility/html/table-presentation-expected-mac.txt new file mode 100644 index 0000000..b82f125 --- /dev/null +++ b/content/test/data/accessibility/html/table-presentation-expected-mac.txt
@@ -0,0 +1,9 @@ +AXWebArea AXTitle='Table with role=presentation' +++AXGroup +++++AXStaticText AXValue='1' +++AXGroup +++++AXStaticText AXValue='2' +++AXGroup +++++AXStaticText AXValue='4' +++AXGroup +++++AXStaticText AXValue='5' \ No newline at end of file
diff --git a/content/test/data/accessibility/html/table-presentation-expected-win.txt b/content/test/data/accessibility/html/table-presentation-expected-win.txt new file mode 100644 index 0000000..1a48cbb --- /dev/null +++ b/content/test/data/accessibility/html/table-presentation-expected-win.txt
@@ -0,0 +1,9 @@ +ROLE_SYSTEM_DOCUMENT name='Table with role=presentation' READONLY FOCUSABLE +++IA2_ROLE_SECTION +++++ROLE_SYSTEM_STATICTEXT name='1' +++IA2_ROLE_SECTION +++++ROLE_SYSTEM_STATICTEXT name='2' +++IA2_ROLE_SECTION +++++ROLE_SYSTEM_STATICTEXT name='4' +++IA2_ROLE_SECTION +++++ROLE_SYSTEM_STATICTEXT name='5' \ No newline at end of file
diff --git a/content/test/data/accessibility/html/table-presentation.html b/content/test/data/accessibility/html/table-presentation.html new file mode 100644 index 0000000..afc67f3 --- /dev/null +++ b/content/test/data/accessibility/html/table-presentation.html
@@ -0,0 +1,23 @@ +<!-- +@MAC-ALLOW:AXIndex=* +@MAC-ALLOW:AXColumnIndexRange=* +@MAC-ALLOW:AXRowIndexRange=* +--> +<!DOCTYPE html> +<html> +<head> + <title>Table with role=presentation</title> +</head> +<body> + +<table role="presentation"> +<tr> +<td>1</td><td>2</td> +</tr> +<tr> +<td>4</td><td>5</td> +</tr> +</table> + +</body> +</html>
diff --git a/content/test/data/accessibility/html/table-simple-2.html b/content/test/data/accessibility/html/table-simple-2.html new file mode 100644 index 0000000..26b47c1 --- /dev/null +++ b/content/test/data/accessibility/html/table-simple-2.html
@@ -0,0 +1,26 @@ +<!-- +@MAC-ALLOW:AXIndex=* +@MAC-ALLOW:AXColumnIndexRange=* +@MAC-ALLOW:AXRowIndexRange=* +--> +<!DOCTYPE html> +<html> +<head> + <title>Table example #2</title> +</head> +<body> + +<table> +<tr> +<td>1</td><td>2</td><td>3</td> +</tr> +<tr> +<td>4</td><td>5</td><td>6</td> +</tr> +<tr> +<td>7</td><td>8</td><td>9</td> +</tr> +</table> + +</body> +</html>
diff --git a/content/test/gpu/generate_buildbot_json.py b/content/test/gpu/generate_buildbot_json.py index 89f44db..ea64ebd4 100755 --- a/content/test/gpu/generate_buildbot_json.py +++ b/content/test/gpu/generate_buildbot_json.py
@@ -2562,7 +2562,9 @@ 'args': [ '--gpu-trigger-configs', json.dumps(tester_config['swarming_dimensions'] + - tester_config.get('alternate_swarming_dimensions', [])) + tester_config.get('alternate_swarming_dimensions', [])), + '--gpu-trigger-script-verbose', + 'True' ], }
diff --git a/content/test/gpu/gpu_tests/pixel_test_pages.py b/content/test/gpu/gpu_tests/pixel_test_pages.py index 44d6ee5..f54b5049 100644 --- a/content/test/gpu/gpu_tests/pixel_test_pages.py +++ b/content/test/gpu/gpu_tests/pixel_test_pages.py
@@ -51,6 +51,39 @@ p.CopyWithNewBrowserArgsAndPrefix(browser_args, prefix) for p in pages] +# TODO(kbr): consider refactoring this into pixel_integration_test.py. +SCALE_FACTOR_OVERRIDES = { + "comment": "scale factor overrides", + "scale_factor_overrides": [ + { + "device_type": "Nexus 5", + "scale_factor": 1.105 + }, + { + "device_type": "Nexus 5X", + "scale_factor": 1.105 + }, + { + "device_type": "Nexus 6", + "scale_factor": 1.47436 + }, + { + "device_type": "Nexus 6P", + "scale_factor": 1.472 + }, + { + "device_type": "Nexus 9", + "scale_factor": 1.566 + }, + { + "comment": "NVIDIA Shield", + "device_type": "sb_na_wf", + "scale_factor": 1.226 + } + ] +} + + def DefaultPages(base_name): return [ PixelTestPage( @@ -160,38 +193,7 @@ test_rect=[0, 0, 150, 150], revision=0, # This is not used. expected_colors=[ - # TODO(kbr): if this works, then factor it out so it applies - # to all pixel tests that use programmatic expectations. - { - "comment": "scale factor overrides", - "scale_factor_overrides": [ - { - "device_type": "Nexus 5", - "scale_factor": 1.105 - }, - { - "device_type": "Nexus 5X", - "scale_factor": 1.105 - }, - { - "device_type": "Nexus 6", - "scale_factor": 1.47436 - }, - { - "device_type": "Nexus 6P", - "scale_factor": 1.472 - }, - { - "device_type": "Nexus 9", - "scale_factor": 1.566 - }, - { - "comment": "NVIDIA Shield", - "device_type": "sb_na_wf", - "scale_factor": 1.226 - } - ] - }, + SCALE_FACTOR_OVERRIDES, { 'comment': 'brown', 'location': [1, 1], @@ -211,38 +213,7 @@ test_rect=[0, 0, 200, 200], revision=0, # This is not used. expected_colors=[ - # TODO(kbr): if this works, then factor it out so it applies - # to all pixel tests that use programmatic expectations. - { - "comment": "scale factor overrides", - "scale_factor_overrides": [ - { - "device_type": "Nexus 5", - "scale_factor": 1.105 - }, - { - "device_type": "Nexus 5X", - "scale_factor": 1.105 - }, - { - "device_type": "Nexus 6", - "scale_factor": 1.47436 - }, - { - "device_type": "Nexus 6P", - "scale_factor": 1.472 - }, - { - "device_type": "Nexus 9", - "scale_factor": 1.566 - }, - { - "comment": "NVIDIA Shield", - "device_type": "sb_na_wf", - "scale_factor": 1.226 - } - ] - }, + SCALE_FACTOR_OVERRIDES, { 'comment': 'green', 'location': [1, 1], @@ -258,38 +229,7 @@ test_rect=[0, 0, 200, 200], revision=0, # This is not used. expected_colors=[ - # TODO(kbr): if this works, then factor it out so it applies - # to all pixel tests that use programmatic expectations. - { - "comment": "scale factor overrides", - "scale_factor_overrides": [ - { - "device_type": "Nexus 5", - "scale_factor": 1.105 - }, - { - "device_type": "Nexus 5X", - "scale_factor": 1.105 - }, - { - "device_type": "Nexus 6", - "scale_factor": 1.47436 - }, - { - "device_type": "Nexus 6P", - "scale_factor": 1.472 - }, - { - "device_type": "Nexus 9", - "scale_factor": 1.566 - }, - { - "comment": "NVIDIA Shield", - "device_type": "sb_na_wf", - "scale_factor": 1.226 - } - ] - }, + SCALE_FACTOR_OVERRIDES, { 'comment': 'green', 'location': [1, 1], @@ -652,6 +592,11 @@ non_chromium_image_args = ['--disable-webgl-image-chromium'] + # This disables the Core Animation compositor, falling back to the + # old GLRenderer path, but continuing to allocate IOSurfaces for + # WebGL's back buffer. + no_overlays_args = ['--disable-mac-overlays'] + return [ # On macOS, test the IOSurface 2D Canvas compositing path. PixelTestPage( @@ -705,7 +650,29 @@ test_rect=[0, 0, 300, 300], revision=7, tolerance=10, - browser_args=['--disable-mac-overlays']), + browser_args=no_overlays_args), + + # Test WebGL's premultipliedAlpha:false without the CA compositor. + PixelTestPage( + 'pixel_webgl_premultiplied_alpha_false.html', + base_name + '_WebGL_PremultipliedAlpha_False_NoOverlays', + test_rect=[0, 0, 150, 150], + revision=0, # This is not used. + browser_args=no_overlays_args, + expected_colors=[ + SCALE_FACTOR_OVERRIDES, + { + 'comment': 'brown', + 'location': [1, 1], + 'size': [148, 148], + # This is the color on an NVIDIA based MacBook Pro if the + # sRGB profile's applied correctly. + 'color': [102, 77, 0], + # This is the color if it isn't. + # 'color': [101, 76, 12], + 'tolerance': 3 + }, + ]), ] def DirectCompositionPages(base_name):
diff --git a/content/test/gpu/trigger_gpu_test.py b/content/test/gpu/trigger_gpu_test.py index 667cbe53..d8371498 100755 --- a/content/test/gpu/trigger_gpu_test.py +++ b/content/test/gpu/trigger_gpu_test.py
@@ -150,7 +150,7 @@ if not all(isinstance(entry, dict) for entry in self._gpu_configs): raise ValueError('GPU configurations must all be dictionaries') - def query_swarming_for_gpu_configs(self): + def query_swarming_for_gpu_configs(self, verbose): # Query Swarming to figure out which bots are available. for config in self._gpu_configs: values = [] @@ -172,7 +172,8 @@ '0', '--json', temp_file, - ('bots/count?%s' % query_arg)]) + ('bots/count?%s' % query_arg)], + verbose) if ret: raise Exception('Error running swarming.py') with open(temp_file) as fp: @@ -182,10 +183,15 @@ # Be robust against errors in computation. available = max(0, count - int(query_result['busy'])) self._bot_statuses.append({'total': count, 'available': available}) + if verbose: + idx = len(self._bot_statuses) - 1 + print 'GPU config %d: %s' % (idx, str(self._bot_statuses[idx])) finally: self.delete_temp_file(temp_file) # Sum up the total count of all bots. self._total_bots = sum(x['total'] for x in self._bot_statuses) + if verbose: + print 'Total bots: %d' % (self._total_bots) def remove_swarming_dimension(self, args, dimension): for i in xrange(len(args)): @@ -196,7 +202,7 @@ def choose_random_int(self, max_num): return random.randint(1, max_num) - def pick_gpu_configuration(self): + def pick_gpu_configuration(self, verbose): # These are the rules used: # 1. If any configuration has bots available, pick the configuration with # the most bots available. @@ -216,6 +222,8 @@ max_val = avail self._bot_statuses[max_index]['available'] -= 1 assert self._bot_statuses[max_index]['available'] >= 0 + if verbose: + print 'Chose GPU config %d because bots were available' % (max_index) return max_index # Case 2. # We want to choose a bot uniformly at random from all of the bots specified @@ -225,6 +233,8 @@ r = self.choose_random_int(self._total_bots) for i, status in enumerate(self._bot_statuses): if r <= status['total']: + if verbose: + print 'Chose GPU config %d stochastically' % (i) return i r -= status['total'] raise Exception('Should not reach here') @@ -247,7 +257,10 @@ with open(output_file, 'w') as f: json.dump(merged_json, f) - def run_swarming(self, args): + def run_swarming(self, args, verbose): + if verbose: + print 'Running Swarming with args:' + print str(args) return subprocess.call([sys.executable, SWARMING_PY] + args) def trigger_tasks(self, args, remaining): @@ -262,8 +275,9 @@ Exit code for the script. """ remaining = self.filter_swarming_py_path_arg(remaining) + verbose = args.gpu_trigger_script_verbose self.parse_gpu_configs(args) - self.query_swarming_for_gpu_configs() + self.query_swarming_for_gpu_configs(verbose) # In the remaining arguments, find the Swarming dimensions that are # specified by the GPU configs and remove them, because for each shard, @@ -282,14 +296,14 @@ # 1. Pick which GPU configuration to use. # 2. Insert that GPU configuration's dimensions as command line # arguments, and invoke "swarming.py trigger". - gpu_index = self.pick_gpu_configuration() + gpu_index = self.pick_gpu_configuration(verbose) # Holds the results of the swarming.py trigger call. try: json_temp = self.make_temp_file(prefix='trigger_gpu_test', suffix='.json') args_to_pass = self.modify_args(filtered_remaining_args, gpu_index, i, args.shards, json_temp) - ret = self.run_swarming(args_to_pass) + ret = self.run_swarming(args_to_pass, verbose) if ret: sys.stderr.write('Failed to trigger a task, aborting\n') return ret @@ -318,6 +332,8 @@ help='The GPU configurations to trigger tasks on, in the' ' form of a JSON array of dictionaries. At least one' ' entry in this dictionary is required.') + parser.add_argument('--gpu-trigger-script-verbose', type=bool, default=False, + help='Turn on verbose logging') parser.add_argument('--dump-json', required=True, help='(Swarming Trigger Script API) Where to dump the' ' resulting json which indicates which tasks were'
diff --git a/content/test/gpu/trigger_gpu_test_unittest.py b/content/test/gpu/trigger_gpu_test_unittest.py index 3999dc9..7d485893 100755 --- a/content/test/gpu/trigger_gpu_test_unittest.py +++ b/content/test/gpu/trigger_gpu_test_unittest.py
@@ -53,11 +53,11 @@ def parse_gpu_configs(self, args): pass - def query_swarming_for_gpu_configs(self): + def query_swarming_for_gpu_configs(self, verbose): # Sum up the total count of all bots. self._total_bots = sum(x['total'] for x in self._bot_statuses) - def run_swarming(self, args): + def run_swarming(self, args, verbose): self._swarming_runs.append(args) @@ -119,6 +119,7 @@ args = Args() args.shards = 2 args.dump_json = 'output.json' + args.gpu_trigger_script_verbose = False triggerer.trigger_tasks( args, [
diff --git a/content/test/test_render_view_host.cc b/content/test/test_render_view_host.cc index 17cfb63..668629f 100644 --- a/content/test/test_render_view_host.cc +++ b/content/test/test_render_view_host.cc
@@ -161,11 +161,6 @@ return background_color_; } -bool TestRenderWidgetHostView::HasAcceleratedSurface( - const gfx::Size& desired_size) { - return false; -} - #if defined(OS_MACOSX) void TestRenderWidgetHostView::SetActive(bool active) {
diff --git a/content/test/test_render_view_host.h b/content/test/test_render_view_host.h index b941e7d..10ceb21 100644 --- a/content/test/test_render_view_host.h +++ b/content/test/test_render_view_host.h
@@ -114,7 +114,6 @@ int error_code) override; void Destroy() override; void SetTooltipText(const base::string16& tooltip_text) override {} - bool HasAcceleratedSurface(const gfx::Size& desired_size) override; gfx::Rect GetBoundsInRootWindow() override; bool LockMouse() override; void UnlockMouse() override;
diff --git a/content/test/unittests_manifest.json b/content/test/unittests_manifest.json index 7246822..94cb81e 100644 --- a/content/test/unittests_manifest.json +++ b/content/test/unittests_manifest.json
@@ -9,8 +9,7 @@ ] }, "requires": { - "file": [ "file:filesystem", "file:leveldb" ], - "network": [ "network_service" ] + "file": [ "file:filesystem", "file:leveldb" ] } } }
diff --git a/content/utility/BUILD.gn b/content/utility/BUILD.gn index 68a95c4..8770194 100644 --- a/content/utility/BUILD.gn +++ b/content/utility/BUILD.gn
@@ -32,7 +32,6 @@ "//base", "//content:export", "//content/child", - "//content/network:network_sources", "//content/public/child:child_sources", "//content/public/common:common_sources", "//media:media_features",
diff --git a/device/bluetooth/test/bluetooth_test_bluez.cc b/device/bluetooth/test/bluetooth_test_bluez.cc index 7e3ab3d9b..0df0601 100644 --- a/device/bluetooth/test/bluetooth_test_bluez.cc +++ b/device/bluetooth/test/bluetooth_test_bluez.cc
@@ -148,6 +148,7 @@ break; case 5: device_name = base::nullopt; + break; case 6: device_address = kTestDeviceAddress2; device_type = BLUETOOTH_TRANSPORT_DUAL;
diff --git a/device/gamepad/BUILD.gn b/device/gamepad/BUILD.gn index 157e762..8e1ffa1 100644 --- a/device/gamepad/BUILD.gn +++ b/device/gamepad/BUILD.gn
@@ -66,6 +66,8 @@ "raw_input_data_fetcher_win.h", "raw_input_gamepad_device_win.cc", "raw_input_gamepad_device_win.h", + "switch_pro_controller_base.cc", + "switch_pro_controller_base.h", "udev_gamepad_linux.cc", "udev_gamepad_linux.h", "xbox_controller_mac.h",
diff --git a/device/gamepad/switch_pro_controller_base.cc b/device/gamepad/switch_pro_controller_base.cc new file mode 100644 index 0000000..e4e611c2 --- /dev/null +++ b/device/gamepad/switch_pro_controller_base.cc
@@ -0,0 +1,189 @@ +// 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 "device/gamepad/switch_pro_controller_base.h" + +namespace { +const uint32_t kVendorNintendo = 0x057e; +const uint32_t kProductSwitchProController = 0x2009; +const uint8_t kRumbleMagnitudeMax = 0xff; + +enum ControllerType { UNKNOWN_CONTROLLER, SWITCH_PRO_CONTROLLER }; + +ControllerType ControllerTypeFromDeviceIds(int vendor_id, int product_id) { + if (vendor_id == kVendorNintendo) { + switch (product_id) { + case kProductSwitchProController: + return SWITCH_PRO_CONTROLLER; + default: + break; + } + } + return UNKNOWN_CONTROLLER; +} + +double NormalizeAxis(int value, int min, int max) { + return (2.0 * (value - min) / static_cast<double>(max - min)) - 1.0; +} + +} // namespace + +namespace device { + +SwitchProControllerBase::~SwitchProControllerBase() = default; + +// static +bool SwitchProControllerBase::IsSwitchPro(int vendor_id, int product_id) { + return ControllerTypeFromDeviceIds(vendor_id, product_id) != + UNKNOWN_CONTROLLER; +} + +// static +void SwitchProControllerBase::UpdatePadStateFromControllerData( + const ControllerDataReport& report, + Gamepad* pad) { + pad->buttons[BUTTON_INDEX_PRIMARY].pressed = report.button_b; + pad->buttons[BUTTON_INDEX_PRIMARY].value = report.button_b ? 1.0 : 0.0; + + pad->buttons[BUTTON_INDEX_SECONDARY].pressed = report.button_a; + pad->buttons[BUTTON_INDEX_SECONDARY].value = report.button_a ? 1.0 : 0.0; + + pad->buttons[BUTTON_INDEX_TERTIARY].pressed = report.button_y; + pad->buttons[BUTTON_INDEX_TERTIARY].value = report.button_y ? 1.0 : 0.0; + + pad->buttons[BUTTON_INDEX_QUATERNARY].pressed = report.button_x; + pad->buttons[BUTTON_INDEX_QUATERNARY].value = report.button_x ? 1.0 : 0.0; + + pad->buttons[BUTTON_INDEX_LEFT_SHOULDER].pressed = report.button_l; + pad->buttons[BUTTON_INDEX_LEFT_SHOULDER].value = report.button_l ? 1.0 : 0.0; + + pad->buttons[BUTTON_INDEX_RIGHT_SHOULDER].pressed = report.button_r; + pad->buttons[BUTTON_INDEX_RIGHT_SHOULDER].value = report.button_r ? 1.0 : 0.0; + + pad->buttons[BUTTON_INDEX_LEFT_TRIGGER].pressed = report.button_zl; + pad->buttons[BUTTON_INDEX_LEFT_TRIGGER].value = report.button_zl ? 1.0 : 0.0; + + pad->buttons[BUTTON_INDEX_RIGHT_TRIGGER].pressed = report.button_zr; + pad->buttons[BUTTON_INDEX_RIGHT_TRIGGER].value = report.button_zr ? 1.0 : 0.0; + + pad->buttons[BUTTON_INDEX_BACK_SELECT].pressed = report.button_minus; + pad->buttons[BUTTON_INDEX_BACK_SELECT].value = + report.button_minus ? 1.0 : 0.0; + + pad->buttons[BUTTON_INDEX_START].pressed = report.button_plus; + pad->buttons[BUTTON_INDEX_START].value = report.button_plus ? 1.0 : 0.0; + + pad->buttons[BUTTON_INDEX_LEFT_THUMBSTICK].pressed = report.button_thumb_l; + pad->buttons[BUTTON_INDEX_LEFT_THUMBSTICK].value = + report.button_thumb_l ? 1.0 : 0.0; + + pad->buttons[BUTTON_INDEX_RIGHT_THUMBSTICK].pressed = report.button_thumb_r; + pad->buttons[BUTTON_INDEX_RIGHT_THUMBSTICK].value = + report.button_thumb_r ? 1.0 : 0.0; + + pad->buttons[BUTTON_INDEX_DPAD_UP].pressed = report.dpad_up; + pad->buttons[BUTTON_INDEX_DPAD_UP].value = report.dpad_up ? 1.0 : 0.0; + + pad->buttons[BUTTON_INDEX_DPAD_DOWN].pressed = report.dpad_down; + pad->buttons[BUTTON_INDEX_DPAD_DOWN].value = report.dpad_down ? 1.0 : 0.0; + + pad->buttons[BUTTON_INDEX_DPAD_LEFT].pressed = report.dpad_left; + pad->buttons[BUTTON_INDEX_DPAD_LEFT].value = report.dpad_left ? 1.0 : 0.0; + + pad->buttons[BUTTON_INDEX_DPAD_RIGHT].pressed = report.dpad_right; + pad->buttons[BUTTON_INDEX_DPAD_RIGHT].value = report.dpad_right ? 1.0 : 0.0; + + pad->buttons[BUTTON_INDEX_META].pressed = report.button_home; + pad->buttons[BUTTON_INDEX_META].value = report.button_home ? 1.0 : 0.0; + + pad->buttons[BUTTON_INDEX_META + 1].pressed = report.button_capture; + pad->buttons[BUTTON_INDEX_META + 1].value = report.button_capture ? 1.0 : 0.0; + + int8_t axis_lx = + (((report.analog[1] & 0x0F) << 4) | ((report.analog[0] & 0xF0) >> 4)) + + 127; + int8_t axis_ly = report.analog[2] + 127; + int8_t axis_rx = + (((report.analog[4] & 0x0F) << 4) | ((report.analog[3] & 0xF0) >> 4)) + + 127; + int8_t axis_ry = report.analog[5] + 127; + pad->axes[AXIS_INDEX_LEFT_STICK_X] = + NormalizeAxis(axis_lx, kAxisMin, kAxisMax); + pad->axes[AXIS_INDEX_LEFT_STICK_Y] = + NormalizeAxis(-axis_ly, kAxisMin, kAxisMax); + pad->axes[AXIS_INDEX_RIGHT_STICK_X] = + NormalizeAxis(axis_rx, kAxisMin, kAxisMax); + pad->axes[AXIS_INDEX_RIGHT_STICK_Y] = + NormalizeAxis(-axis_ry, kAxisMin, kAxisMax); + + pad->buttons_length = BUTTON_INDEX_COUNT + 1; + pad->axes_length = AXIS_INDEX_COUNT; +} + +void SwitchProControllerBase::SendConnectionStatusQuery() { + // Requests the current connection status and info about the connected + // controller. The controller will respond with a status packet. + const size_t report_length = 2; + uint8_t report[report_length]; + memset(report, 0, report_length); + report[0] = 0x80; + report[1] = 0x01; + + WriteOutputReport(report, report_length); +} + +void SwitchProControllerBase::SendHandshake() { + // Sends handshaking packets over UART. This command can only be called once + // per session. The controller will respond with a status packet. + uint8_t report[kReportSize]; + memset(report, 0, kReportSize); + report[0] = 0x80; + report[1] = 0x02; + + WriteOutputReport(report, kReportSize); +} + +void SwitchProControllerBase::SendForceUsbHid(bool enable) { + // By default, the controller will revert to Bluetooth mode if it does not + // receive any USB HID commands within a timeout window. Enabling the + // ForceUsbHid mode forces all communication to go through USB HID and + // disables the timeout. + uint8_t report[kReportSize]; + memset(report, 0, kReportSize); + report[0] = 0x80; + report[1] = (enable ? 0x04 : 0x05); + + WriteOutputReport(report, kReportSize); +} + +void SwitchProControllerBase::SetVibration(double strong_magnitude, + double weak_magnitude) { + uint8_t strong_magnitude_scaled = + static_cast<uint8_t>(strong_magnitude * kRumbleMagnitudeMax); + uint8_t weak_magnitude_scaled = + static_cast<uint8_t>(weak_magnitude * kRumbleMagnitudeMax); + + uint8_t report[kReportSize]; + memset(report, 0, kReportSize); + report[0] = 0x10; + report[1] = static_cast<uint8_t>(counter_++ & 0x0F); + report[2] = 0x80; + report[6] = 0x80; + if (strong_magnitude_scaled > 0) { + report[2] = 0x80; + report[3] = 0x20; + report[4] = 0x62; + report[5] = strong_magnitude_scaled >> 2; + } + if (weak_magnitude_scaled > 0) { + report[6] = 0x98; + report[7] = 0x20; + report[8] = 0x62; + report[9] = weak_magnitude_scaled >> 2; + } + + WriteOutputReport(report, kReportSize); +} + +} // namespace device
diff --git a/device/gamepad/switch_pro_controller_base.h b/device/gamepad/switch_pro_controller_base.h new file mode 100644 index 0000000..6d0923d --- /dev/null +++ b/device/gamepad/switch_pro_controller_base.h
@@ -0,0 +1,82 @@ +// 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. + +#ifndef DEVICE_GAMEPAD_SWITCH_PRO_CONTROLLER_BASE_ +#define DEVICE_GAMEPAD_SWITCH_PRO_CONTROLLER_BASE_ + +#include "device/gamepad/abstract_haptic_gamepad.h" +#include "device/gamepad/gamepad_standard_mappings.h" + +namespace device { + +class SwitchProControllerBase : public AbstractHapticGamepad { + public: + // Switch Pro Controller USB packet types. + static const uint8_t kPacketTypeStatus = 0x81; + static const uint8_t kPacketTypeControllerData = 0x30; + + // Status packet subtypes. + static const uint8_t kStatusTypeSerial = 0x01; + static const uint8_t kStatusTypeInit = 0x02; + + // Axis extents, used for normalization. + static const int kAxisMin = -128; + static const int kAxisMax = 127; + + // Maximum size of a Switch HID report, in bytes. + static const int kReportSize = 64; + +#pragma pack(push, 1) + struct ControllerDataReport { + uint8_t type; // must be kPacketTypeControllerData + uint8_t timestamp; + uint8_t dummy1; + bool button_y : 1; + bool button_x : 1; + bool button_b : 1; + bool button_a : 1; + bool dummy2 : 2; + bool button_r : 1; + bool button_zr : 1; + bool button_minus : 1; + bool button_plus : 1; + bool button_thumb_r : 1; + bool button_thumb_l : 1; + bool button_home : 1; + bool button_capture : 1; + bool dummy3 : 2; + bool dpad_down : 1; + bool dpad_up : 1; + bool dpad_right : 1; + bool dpad_left : 1; + bool dummy4 : 2; + bool button_l : 1; + bool button_zl : 1; + uint8_t analog[6]; + }; +#pragma pack(pop) + + SwitchProControllerBase() = default; + ~SwitchProControllerBase() override; + + static bool IsSwitchPro(int vendor_id, int product_id); + + static void UpdatePadStateFromControllerData( + const ControllerDataReport& report, + Gamepad* pad); + + void SendConnectionStatusQuery(); + void SendHandshake(); + void SendForceUsbHid(bool enable); + void SetVibration(double strong_magnitude, double weak_magnitude) override; + + virtual void WriteOutputReport(void* report, size_t report_length) {} + + private: + uint32_t counter_ = 0; +}; + +} // namespace device + +#endif // DEVICE_GAMEPAD_SWITCH_PRO_CONTROLLER_BASE_
diff --git a/device/media_transfer_protocol/media_transfer_protocol_manager.cc b/device/media_transfer_protocol/media_transfer_protocol_manager.cc index 433957cc..811b04b4 100644 --- a/device/media_transfer_protocol/media_transfer_protocol_manager.cc +++ b/device/media_transfer_protocol/media_transfer_protocol_manager.cc
@@ -338,7 +338,7 @@ return; } for (auto& observer : observers_) - observer.StorageChanged(false /* detach */, storage_name); + observer.StorageDetached(storage_name); } void OnStorageChanged(bool is_attach, const std::string& storage_name) { @@ -379,8 +379,9 @@ // New storage. Add it and let the observers know. storage_info_map_.insert(std::make_pair(storage_name, storage_info)); + for (auto& observer : observers_) - observer.StorageChanged(true /* is attach */, storage_name); + observer.StorageAttached(storage_info); } void OnGetStorageInfoFromDevice(const mojom::MtpStorageInfo& storage_info) {
diff --git a/device/media_transfer_protocol/media_transfer_protocol_manager.h b/device/media_transfer_protocol/media_transfer_protocol_manager.h index a32d265..1d40106 100644 --- a/device/media_transfer_protocol/media_transfer_protocol_manager.h +++ b/device/media_transfer_protocol/media_transfer_protocol_manager.h
@@ -99,9 +99,10 @@ public: virtual ~Observer() {} - // A function called after a MTP storage has been attached / detached. - virtual void StorageChanged(bool is_attached, - const std::string& storage_name) = 0; + // Functions called after a MTP storage has been attached / detached. + virtual void StorageAttached( + const device::mojom::MtpStorageInfo& storage_info) = 0; + virtual void StorageDetached(const std::string& storage_name) = 0; }; virtual ~MediaTransferProtocolManager() {}
diff --git a/docs/design/gpu_synchronization.md b/docs/design/gpu_synchronization.md index ada04ad9..80dd874b 100644 --- a/docs/design/gpu_synchronization.md +++ b/docs/design/gpu_synchronization.md
@@ -92,26 +92,24 @@ See [issue 510232](http://crbug.com/510243#c23) for an example of a problematic sequence: -> In one thread: -> -> ``` -> MakeCurrent(A); -> Render1(); -> MakeCurrent(B); -> Render2(); -> CreateSync(X);``` -> ->And in another thread: -> -> ``` -> MakeCurrent(C); -> WaitSync(X); -> Render3(); -> MakeCurrent(D); -> Render4();``` -> -> The only serialization guarantee is between Render2 and Render3, while Render4 -> could theoretically complete before Render1. +``` +// In one thread: +MakeCurrent(A); +Render1(); +MakeCurrent(B); +Render2(); +CreateSync(X); + +// And in another thread: +MakeCurrent(C); +WaitSync(X); +Render3(); +MakeCurrent(D); +Render4(); +``` + +The only serialization guarantee is that Render2 will complete before Render3, +but Render4 could theoretically complete before Render1. Chrome assumes that the render steps happen in order Render1, Render2, Render3, and Render4, and requires this behavior to ensure security. If the driver doesn't
diff --git a/docs/fuchsia_sdk_updates.md b/docs/fuchsia_sdk_updates.md index 8d3ca2d..212fcec7 100644 --- a/docs/fuchsia_sdk_updates.md +++ b/docs/fuchsia_sdk_updates.md
@@ -4,7 +4,7 @@ job](https://luci-scheduler.appspot.com/jobs/fuchsia/sdk-x86_64-linux) for a recent green archive. On the "SUCCEEDED" link, copy the SHA-1 from the `gsutil.upload` link of the `upload fuchsia-sdk` step. -0. Put that into Chromium's src.git DEPS in the `fuchsia_sdk` step. +0. Put that into Chromium's src.git `build/fuchsia/update_sdk.py` as `SDK_HASH`. 0. `gclient sync && ninja ...` and make sure things go OK locally. 0. Upload the roll CL, making sure to include the `fuchsia` trybot. Tag the roll with `Bug: 707030`.
diff --git a/docs/network_traffic_annotations.md b/docs/network_traffic_annotations.md index dc5d180..1cdba8b 100644 --- a/docs/network_traffic_annotations.md +++ b/docs/network_traffic_annotations.md
@@ -123,9 +123,6 @@ points to `OTHER`. * `TrafficPolicy`: These set of fields specify the controls that a user may have on disabling or limiting the network request and its trace. - * `empty_policy_justification`: If traffic policy cannot be specified, like - when the request originates from inside network stack and none of the below - control policies applies to it, a plain text here can specify it. * `cookies_allowed`: Specifies if this request stores and uses cookies or not. Use values `YES` or `NO`. * `cookies_store`: If a request sends or stores cookies/channel IDs/... (i.e. @@ -149,8 +146,7 @@ request. This would be a text serialized protobuf of any enterprise policy. See policy list or chrome_settings.proto for the full list of policies. * `policy_exception_justification`: If there is no policy to disable or limit - this request, a justification can be presented here. In case ‘Empty Policy - Justification’ is presented, this field is not required. + this request, a justification can be presented here. * `comments`: If required, any human readable extra comments. ### Format and Examples @@ -259,7 +255,6 @@ destination: WEBSITE/GOOGLE_OWNED_SERVICE/OTHER } policy { - empty_policy_justification = "..." cookies_allowed: NO/YES cookies_store: "..." setting: "..."
diff --git a/extensions/BUILD.gn b/extensions/BUILD.gn index 174ffa6..25ef0de 100644 --- a/extensions/BUILD.gn +++ b/extensions/BUILD.gn
@@ -71,6 +71,8 @@ "browser/api_unittest.h", "browser/app_window/test_app_window_contents.cc", "browser/app_window/test_app_window_contents.h", + "browser/content_verifier/test_utils.cc", + "browser/content_verifier/test_utils.h", "browser/extension_error_test_util.cc", "browser/extension_error_test_util.h", "browser/extensions_test.cc",
diff --git a/extensions/browser/api/management/management_api.cc b/extensions/browser/api/management/management_api.cc index ee9b5a2..f8373eb6 100644 --- a/extensions/browser/api/management/management_api.cc +++ b/extensions/browser/api/management/management_api.cc
@@ -214,6 +214,7 @@ break; case Manifest::NUM_LOCATIONS: NOTREACHED(); + FALLTHROUGH; case Manifest::INVALID_LOCATION: case Manifest::COMPONENT: case Manifest::EXTERNAL_COMPONENT: @@ -388,6 +389,10 @@ std::unique_ptr<management::LaunchApp::Params> params( management::LaunchApp::Params::Create(*args_)); EXTENSION_FUNCTION_VALIDATE(params.get()); + + if (ExtensionsBrowserClient::Get()->IsRunningInForcedAppMode()) + return RespondNow(Error(keys::kNotAllowedInKioskError)); + const Extension* extension = ExtensionRegistry::Get(browser_context()) ->GetExtensionById(params->id, ExtensionRegistry::EVERYTHING); @@ -413,24 +418,28 @@ std::unique_ptr<management::SetEnabled::Params> params( management::SetEnabled::Params::Create(*args_)); EXTENSION_FUNCTION_VALIDATE(params.get()); + extension_id_ = params->id; + + if (ExtensionsBrowserClient::Get()->IsAppModeForcedForApp(extension_id_)) + return RespondNow(Error(keys::kCannotChangePrimaryKioskAppError)); + ExtensionRegistry* registry = ExtensionRegistry::Get(browser_context()); const ManagementAPIDelegate* delegate = ManagementAPI::GetFactoryInstance() ->Get(browser_context()) ->GetDelegate(); - extension_id_ = params->id; - - const Extension* extension = + const Extension* target_extension = registry->GetExtensionById(extension_id_, ExtensionRegistry::EVERYTHING); - if (!extension || !extension->ShouldExposeViaManagementAPI()) + if (!target_extension || !target_extension->ShouldExposeViaManagementAPI()) return RespondNow(Error(keys::kNoExtensionError, extension_id_)); bool enabled = params->enabled; const ManagementPolicy* policy = ExtensionSystem::Get(browser_context())->management_policy(); - if (!policy->UserMayModifySettings(extension, nullptr) || - (!enabled && policy->MustRemainEnabled(extension, nullptr)) || - (enabled && policy->MustRemainDisabled(extension, nullptr, nullptr))) { + if (!policy->UserMayModifySettings(target_extension, nullptr) || + (!enabled && policy->MustRemainEnabled(target_extension, nullptr)) || + (enabled && + policy->MustRemainDisabled(target_extension, nullptr, nullptr))) { return RespondNow(Error(keys::kUserCantModifyError, extension_id_)); } @@ -446,14 +455,15 @@ AddRef(); // Matched in OnInstallPromptDone(). install_prompt_ = delegate->SetEnabledFunctionDelegate( - GetSenderWebContents(), browser_context(), extension, + GetSenderWebContents(), browser_context(), target_extension, base::Bind(&ManagementSetEnabledFunction::OnInstallPromptDone, this)); return RespondLater(); } if (prefs->GetDisableReasons(extension_id_) & disable_reason::DISABLE_UNSUPPORTED_REQUIREMENT) { // Recheck the requirements. - requirements_checker_ = std::make_unique<RequirementsChecker>(extension); + requirements_checker_ = + std::make_unique<RequirementsChecker>(target_extension); requirements_checker_->Start( base::Bind(&ManagementSetEnabledFunction::OnRequirementsChecked, this)); // This bind creates a reference. @@ -504,6 +514,9 @@ ExtensionFunction::ResponseAction ManagementUninstallFunctionBase::Uninstall( const std::string& target_extension_id, bool show_confirm_dialog) { + if (ExtensionsBrowserClient::Get()->IsRunningInForcedAppMode()) + return RespondNow(Error(keys::kNotAllowedInKioskError)); + const ManagementAPIDelegate* delegate = ManagementAPI::GetFactoryInstance() ->Get(browser_context()) ->GetDelegate(); @@ -641,6 +654,9 @@ } ExtensionFunction::ResponseAction ManagementCreateAppShortcutFunction::Run() { + if (ExtensionsBrowserClient::Get()->IsRunningInForcedAppMode()) + return RespondNow(Error(keys::kNotAllowedInKioskError)); + if (!user_gesture()) return RespondNow(Error(keys::kGestureNeededForCreateAppShortcutError)); @@ -689,6 +705,9 @@ } ExtensionFunction::ResponseAction ManagementSetLaunchTypeFunction::Run() { + if (ExtensionsBrowserClient::Get()->IsRunningInForcedAppMode()) + return RespondNow(Error(keys::kNotAllowedInKioskError)); + if (!user_gesture()) return RespondNow(Error(keys::kGestureNeededForSetLaunchTypeError)); @@ -756,6 +775,9 @@ } ExtensionFunction::ResponseAction ManagementGenerateAppForLinkFunction::Run() { + if (ExtensionsBrowserClient::Get()->IsRunningInForcedAppMode()) + return RespondNow(Error(keys::kNotAllowedInKioskError)); + if (!user_gesture()) return RespondNow(Error(keys::kGestureNeededForGenerateAppForLinkError));
diff --git a/extensions/browser/api/management/management_api_constants.cc b/extensions/browser/api/management/management_api_constants.cc index 924b3576..c062cda 100644 --- a/extensions/browser/api/management/management_api_constants.cc +++ b/extensions/browser/api/management/management_api_constants.cc
@@ -44,5 +44,8 @@ const char kEmptyTitleError[] = "The title can not be empty."; const char kGenerateAppForLinkInstallError[] = "Failed to install the generated app."; +const char kNotAllowedInKioskError[] = "Not allowed in kiosk."; +const char kCannotChangePrimaryKioskAppError[] = + "Cannot change the primary kiosk app state."; } // namespace extension_management_api_constants
diff --git a/extensions/browser/api/management/management_api_constants.h b/extensions/browser/api/management/management_api_constants.h index bdbeffb..cf72e07 100644 --- a/extensions/browser/api/management/management_api_constants.h +++ b/extensions/browser/api/management/management_api_constants.h
@@ -34,6 +34,8 @@ extern const char kInvalidURLError[]; extern const char kEmptyTitleError[]; extern const char kGenerateAppForLinkInstallError[]; +extern const char kNotAllowedInKioskError[]; +extern const char kCannotChangePrimaryKioskAppError[]; } // namespace extension_management_api_constants
diff --git a/extensions/browser/api/media_perception_private/conversion_utils.cc b/extensions/browser/api/media_perception_private/conversion_utils.cc index 0b9606a..d106312 100644 --- a/extensions/browser/api/media_perception_private/conversion_utils.cc +++ b/extensions/browser/api/media_perception_private/conversion_utils.cc
@@ -12,6 +12,127 @@ namespace { +std::unique_ptr<AudioSpectrogram> AudioSpectrogramProtoToIdl( + const mri::AudioSpectrogram& spectrogram) { + std::unique_ptr<AudioSpectrogram> spectrogram_result = + std::make_unique<AudioSpectrogram>(); + if (spectrogram.values_size() > 0) { + spectrogram_result->values = std::make_unique<std::vector<double>>(); + for (const auto& value : spectrogram.values()) { + spectrogram_result->values->emplace_back(value); + } + } + return spectrogram_result; +} + +std::unique_ptr<AudioHumanPresenceDetection> +AudioHumanPresenceDetectionProtoToIdl( + const mri::AudioHumanPresenceDetection& detection) { + std::unique_ptr<AudioHumanPresenceDetection> detection_result = + std::make_unique<AudioHumanPresenceDetection>(); + if (detection.has_human_presence_likelihood()) { + detection_result->human_presence_likelihood = + std::make_unique<double>(detection.human_presence_likelihood()); + } + if (detection.has_noise_spectrogram()) { + detection_result->noise_spectrogram = + AudioSpectrogramProtoToIdl(detection.noise_spectrogram()); + } + if (detection.has_frame_spectrogram()) { + detection_result->frame_spectrogram = + AudioSpectrogramProtoToIdl(detection.frame_spectrogram()); + } + return detection_result; +} + +std::unique_ptr<AudioLocalization> AudioLocalizationProtoToIdl( + const mri::AudioLocalization& localization) { + std::unique_ptr<AudioLocalization> localization_result = + std::make_unique<AudioLocalization>(); + if (localization.has_azimuth_radians()) { + localization_result->azimuth_radians = + std::make_unique<double>(localization.azimuth_radians()); + } + if (localization.azimuth_scores_size() > 0) { + localization_result->azimuth_scores = + std::make_unique<std::vector<double>>(); + for (const auto& score : localization.azimuth_scores()) { + localization_result->azimuth_scores->emplace_back(score); + } + } + return localization_result; +} + +AudioPerception AudioPerceptionProtoToIdl( + const mri::AudioPerception& perception) { + AudioPerception perception_result; + if (perception.has_timestamp_us()) { + perception_result.timestamp_us = + std::make_unique<double>(perception.timestamp_us()); + } + if (perception.has_audio_localization()) { + perception_result.audio_localization = + AudioLocalizationProtoToIdl(perception.audio_localization()); + } + if (perception.has_audio_human_presence_detection()) { + perception_result.audio_human_presence_detection = + AudioHumanPresenceDetectionProtoToIdl( + perception.audio_human_presence_detection()); + } + return perception_result; +} + +LightCondition LightConditionProtoToIdl( + const mri::VideoHumanPresenceDetection::LightCondition& condition) { + switch (condition) { + case mri::VideoHumanPresenceDetection::UNSPECIFIED: + return LIGHT_CONDITION_UNSPECIFIED; + case mri::VideoHumanPresenceDetection::NO_CHANGE: + return LIGHT_CONDITION_NO_CHANGE; + case mri::VideoHumanPresenceDetection::TURNED_ON: + return LIGHT_CONDITION_TURNED_ON; + case mri::VideoHumanPresenceDetection::TURNED_OFF: + return LIGHT_CONDITION_TURNED_OFF; + case mri::VideoHumanPresenceDetection::DIMMER: + return LIGHT_CONDITION_DIMMER; + case mri::VideoHumanPresenceDetection::BRIGHTER: + return LIGHT_CONDITION_BRIGHTER; + case mri::VideoHumanPresenceDetection::BLACK_FRAME: + return LIGHT_CONDITION_BLACK_FRAME; + default: + NOTREACHED() << "Unknown light condition: " << condition; + return LIGHT_CONDITION_UNSPECIFIED; + } +} + +std::unique_ptr<VideoHumanPresenceDetection> +VideoHumanPresenceDetectionProtoToIdl( + const mri::VideoHumanPresenceDetection& detection) { + std::unique_ptr<VideoHumanPresenceDetection> detection_result = + std::make_unique<VideoHumanPresenceDetection>(); + if (detection.has_human_presence_likelihood()) { + detection_result->human_presence_likelihood = + std::make_unique<double>(detection.human_presence_likelihood()); + } + + if (detection.has_motion_detected_likelihood()) { + detection_result->motion_detected_likelihood = + std::make_unique<double>(detection.motion_detected_likelihood()); + } + + if (detection.has_light_condition()) { + detection_result->light_condition = + LightConditionProtoToIdl(detection.light_condition()); + } + + if (detection.has_light_condition_likelihood()) { + detection_result->light_condition_likelihood = + std::make_unique<double>(detection.light_condition_likelihood()); + } + + return detection_result; +} + std::unique_ptr<Point> PointProtoToIdl(const mri::Point& point) { std::unique_ptr<Point> point_result = std::make_unique<Point>(); if (point.has_x()) @@ -157,6 +278,11 @@ PacketLatencyProtoToIdl(packet_latency)); } } + if (frame_perception.has_video_human_presence_detection()) { + frame_perception_result.video_human_presence_detection = + VideoHumanPresenceDetectionProtoToIdl( + frame_perception.video_human_presence_detection()); + } return frame_perception_result; } @@ -211,6 +337,11 @@ perception_sample_result.image_frame = std::make_unique<ImageFrame>( ImageFrameProtoToIdl(perception_sample.image_frame())); } + if (perception_sample.has_audio_perception()) { + perception_sample_result.audio_perception = + std::make_unique<AudioPerception>( + AudioPerceptionProtoToIdl(perception_sample.audio_perception())); + } return perception_sample_result; } @@ -330,6 +461,16 @@ FramePerceptionProtoToIdl(frame_perception)); } } + + if (media_perception.audio_perception_size() > 0) { + media_perception_result.audio_perceptions = + std::make_unique<std::vector<AudioPerception>>(); + for (const auto& audio_perception : media_perception.audio_perception()) { + media_perception_result.audio_perceptions->emplace_back( + AudioPerceptionProtoToIdl(audio_perception)); + } + } + return media_perception_result; }
diff --git a/extensions/browser/api/media_perception_private/conversion_utils_unittest.cc b/extensions/browser/api/media_perception_private/conversion_utils_unittest.cc index a19f6358c..483898e0 100644 --- a/extensions/browser/api/media_perception_private/conversion_utils_unittest.cc +++ b/extensions/browser/api/media_perception_private/conversion_utils_unittest.cc
@@ -40,6 +40,29 @@ param.frame_rate = std::make_unique<int>(frame_rate); } +void InitializeFakeAudioPerception(mri::AudioPerception* audio_perception) { + audio_perception->set_timestamp_us(10086); + + mri::AudioLocalization* audio_localization = + audio_perception->mutable_audio_localization(); + audio_localization->set_azimuth_radians(1.5); + audio_localization->add_azimuth_scores(2.0); + audio_localization->add_azimuth_scores(5.0); + + mri::AudioHumanPresenceDetection* detection = + audio_perception->mutable_audio_human_presence_detection(); + detection->set_human_presence_likelihood(0.4); + + mri::AudioSpectrogram* noise_spectrogram = + detection->mutable_noise_spectrogram(); + noise_spectrogram->add_values(0.1); + noise_spectrogram->add_values(0.2); + + mri::AudioSpectrogram* frame_spectrogram = + detection->mutable_frame_spectrogram(); + frame_spectrogram->add_values(0.3); +} + void InitializeFakeFramePerception(const int index, mri::FramePerception* frame_perception) { frame_perception->set_frame_id(index); @@ -92,6 +115,14 @@ mri::Entity* entity_three = frame_perception->add_entity(); entity_three->set_type(mri::Entity::LABELED_REGION); entity_three->set_label(kFakeEntityLabel3); + + // Add fake video human presence detection. + mri::VideoHumanPresenceDetection* detection = + frame_perception->mutable_video_human_presence_detection(); + detection->set_human_presence_likelihood(0.1); + detection->set_motion_detected_likelihood(0.2); + detection->set_light_condition(mri::VideoHumanPresenceDetection::BLACK_FRAME); + detection->set_light_condition_likelihood(0.3); } void ValidateFramePerceptionResult( @@ -178,6 +209,54 @@ EXPECT_EQ(*entity_result_three.entity_label, kFakeEntityLabel3); EXPECT_EQ(entity_result_three.type, media_perception::ENTITY_TYPE_LABELED_REGION); + + // Validate video human presence detection. + const media_perception::VideoHumanPresenceDetection* detection_result = + frame_perception_result.video_human_presence_detection.get(); + ASSERT_TRUE(detection_result->human_presence_likelihood); + EXPECT_EQ(*detection_result->human_presence_likelihood, 0.1); + ASSERT_TRUE(detection_result->motion_detected_likelihood); + EXPECT_EQ(*detection_result->motion_detected_likelihood, 0.2); + EXPECT_EQ(detection_result->light_condition, + media_perception::LIGHT_CONDITION_BLACK_FRAME); + ASSERT_TRUE(detection_result->light_condition_likelihood); + EXPECT_EQ(*detection_result->light_condition_likelihood, 0.3); +} + +void ValidateAudioPerceptionResult( + const media_perception::AudioPerception& audio_perception_result) { + ASSERT_TRUE(audio_perception_result.timestamp_us); + EXPECT_EQ(*audio_perception_result.timestamp_us, 10086); + + // Validate audio localization. + const media_perception::AudioLocalization* audio_localization = + audio_perception_result.audio_localization.get(); + ASSERT_TRUE(audio_localization); + ASSERT_TRUE(audio_localization->azimuth_radians); + EXPECT_EQ(*audio_localization->azimuth_radians, 1.5); + ASSERT_EQ(2u, audio_localization->azimuth_scores->size()); + EXPECT_EQ(audio_localization->azimuth_scores->at(0), 2.0); + EXPECT_EQ(audio_localization->azimuth_scores->at(1), 5.0); + + // Validate audio human presence detection. + const media_perception::AudioHumanPresenceDetection* presence_detection = + audio_perception_result.audio_human_presence_detection.get(); + ASSERT_TRUE(presence_detection); + ASSERT_TRUE(presence_detection->human_presence_likelihood); + EXPECT_EQ(*presence_detection->human_presence_likelihood, 0.4); + + const media_perception::AudioSpectrogram* noise_spectrogram = + presence_detection->noise_spectrogram.get(); + ASSERT_TRUE(noise_spectrogram); + ASSERT_EQ(2u, noise_spectrogram->values->size()); + EXPECT_EQ(noise_spectrogram->values->at(0), 0.1); + EXPECT_EQ(noise_spectrogram->values->at(1), 0.2); + + const media_perception::AudioSpectrogram* frame_spectrogram = + presence_detection->frame_spectrogram.get(); + ASSERT_TRUE(frame_spectrogram); + ASSERT_EQ(1u, frame_spectrogram->values->size()); + EXPECT_EQ(frame_spectrogram->values->at(0), 0.3); } void InitializeFakeImageFrameData(mri::ImageFrame* image_frame) { @@ -214,13 +293,20 @@ mri::FramePerception* frame_perception = media_perception.add_frame_perception(); InitializeFakeFramePerception(kFrameId, frame_perception); + mri::AudioPerception* audio_perception = + media_perception.add_audio_perception(); + InitializeFakeAudioPerception(audio_perception); media_perception::MediaPerception media_perception_result = media_perception::MediaPerceptionProtoToIdl(media_perception); EXPECT_EQ(*media_perception_result.timestamp, 1); ASSERT_TRUE(media_perception_result.frame_perceptions); ASSERT_EQ(1u, media_perception_result.frame_perceptions->size()); + ASSERT_TRUE(media_perception_result.audio_perceptions); + ASSERT_EQ(1u, media_perception_result.audio_perceptions->size()); ValidateFramePerceptionResult( kFrameId, media_perception_result.frame_perceptions->at(0)); + ValidateAudioPerceptionResult( + media_perception_result.audio_perceptions->at(0)); } TEST(MediaPerceptionConversionUtilsTest, DiagnosticsProtoToIdl) {
diff --git a/extensions/browser/api/networking_private/networking_private_api.cc b/extensions/browser/api/networking_private/networking_private_api.cc index cf18952d..a961493 100644 --- a/extensions/browser/api/networking_private/networking_private_api.cc +++ b/extensions/browser/api/networking_private/networking_private_api.cc
@@ -606,17 +606,6 @@ void NetworkingPrivateStartConnectFunction::Failure(const std::string& guid, const std::string& error) { - // TODO(stevenjb): Temporary workaround to show the configuration UI. - // Eventually the caller (e.g. Settings) should handle any failures and - // show its own configuration UI. crbug.com/380937. - if (source_context_type() == Feature::WEBUI_CONTEXT) { - const NetworkingPrivateDelegate::UIDelegate* ui_delegate = - GetDelegate(browser_context())->ui_delegate(); - if (ui_delegate && ui_delegate->HandleConnectFailed(guid, error)) { - Success(); - return; - } - } Respond(Error(error)); }
diff --git a/extensions/browser/api/networking_private/networking_private_chromeos.cc b/extensions/browser/api/networking_private/networking_private_chromeos.cc index 29e4028..404b908 100644 --- a/extensions/browser/api/networking_private/networking_private_chromeos.cc +++ b/extensions/browser/api/networking_private/networking_private_chromeos.cc
@@ -545,11 +545,10 @@ return; } - const bool check_error_state = false; NetworkHandler::Get()->network_connection_handler()->ConnectToNetwork( service_path, success_callback, base::Bind(&NetworkHandlerFailureCallback, failure_callback), - check_error_state, chromeos::ConnectCallbackMode::ON_STARTED); + true /* check_error_state */, chromeos::ConnectCallbackMode::ON_STARTED); } void NetworkingPrivateChromeOS::StartDisconnect(
diff --git a/extensions/browser/api/networking_private/networking_private_delegate.h b/extensions/browser/api/networking_private/networking_private_delegate.h index 1d1fe42..35b4bf2e 100644 --- a/extensions/browser/api/networking_private/networking_private_delegate.h +++ b/extensions/browser/api/networking_private/networking_private_delegate.h
@@ -45,11 +45,6 @@ // with |guid|. virtual void ShowAccountDetails(const std::string& guid) const = 0; - // Possibly handle a connection failure, e.g. by showing the configuration - // UI. Returns true if the error was handled, i.e. the UI was shown. - virtual bool HandleConnectFailed(const std::string& guid, - const std::string error) const = 0; - private: DISALLOW_COPY_AND_ASSIGN(UIDelegate); };
diff --git a/extensions/browser/content_verifier/test_utils.cc b/extensions/browser/content_verifier/test_utils.cc new file mode 100644 index 0000000..35be5af --- /dev/null +++ b/extensions/browser/content_verifier/test_utils.cc
@@ -0,0 +1,62 @@ +// 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 "extensions/browser/content_verifier/test_utils.h" + +#include "extensions/common/extension.h" +#include "extensions/common/file_util.h" +#include "testing/gtest/include/gtest/gtest.h" +#include "third_party/zlib/google/zip.h" + +namespace extensions { + +TestContentVerifyJobObserver::TestContentVerifyJobObserver( + const ExtensionId& extension_id, + const base::FilePath& relative_path) + : extension_id_(extension_id), relative_path_(relative_path) { + ContentVerifyJob::SetObserverForTests(this); +} + +TestContentVerifyJobObserver::~TestContentVerifyJobObserver() { + ContentVerifyJob::SetObserverForTests(nullptr); +} + +void TestContentVerifyJobObserver::JobFinished( + const ExtensionId& extension_id, + const base::FilePath& relative_path, + ContentVerifyJob::FailureReason reason) { + if (extension_id != extension_id_ || relative_path != relative_path_) + return; + EXPECT_FALSE(failure_reason_.has_value()); + failure_reason_ = reason; + run_loop_.Quit(); +} + +ContentVerifyJob::FailureReason +TestContentVerifyJobObserver::WaitAndGetFailureReason() { + // Run() returns immediately if Quit() has already been called. + run_loop_.Run(); + EXPECT_TRUE(failure_reason_.has_value()); + return failure_reason_.value_or(ContentVerifyJob::FAILURE_REASON_MAX); +} + +namespace content_verifier_test_utils { + +scoped_refptr<Extension> UnzipToDirAndLoadExtension( + const base::FilePath& extension_zip, + const base::FilePath& unzip_dir) { + if (!zip::Unzip(extension_zip, unzip_dir)) { + ADD_FAILURE() << "Failed to unzip path."; + return nullptr; + } + std::string error; + scoped_refptr<Extension> extension = file_util::LoadExtension( + unzip_dir, Manifest::INTERNAL, 0 /* flags */, &error); + EXPECT_NE(nullptr, extension.get()) << " error:'" << error << "'"; + return extension; +} + +} // namespace content_verifier_test_utils + +} // namespace extensions
diff --git a/extensions/browser/content_verifier/test_utils.h b/extensions/browser/content_verifier/test_utils.h new file mode 100644 index 0000000..5a2a21b --- /dev/null +++ b/extensions/browser/content_verifier/test_utils.h
@@ -0,0 +1,61 @@ +// 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. + +#ifndef EXTENSIONS_BROWSER_CONTENT_VERIFIER_TEST_UTILS_H_ +#define EXTENSIONS_BROWSER_CONTENT_VERIFIER_TEST_UTILS_H_ + +#include "base/files/file_path.h" +#include "base/optional.h" +#include "base/run_loop.h" +#include "extensions/browser/content_verify_job.h" +#include "extensions/common/extension_id.h" + +namespace extensions { + +class Extension; + +// Test class to observe a particular extension resource's ContentVerifyJob +// lifetime. Provides a way to wait for a job to finish and return +// the job's result. +class TestContentVerifyJobObserver : ContentVerifyJob::TestObserver { + public: + TestContentVerifyJobObserver(const ExtensionId& extension_id, + const base::FilePath& relative_path); + ~TestContentVerifyJobObserver(); + + void JobStarted(const std::string& extension_id, + const base::FilePath& relative_path) override {} + + void JobFinished(const std::string& extension_id, + const base::FilePath& relative_path, + ContentVerifyJob::FailureReason reason) override; + + // Waits for a ContentVerifyJob to finish and returns job's status. + ContentVerifyJob::FailureReason WaitAndGetFailureReason(); + + private: + base::RunLoop run_loop_; + ExtensionId extension_id_; + base::FilePath relative_path_; + base::Optional<ContentVerifyJob::FailureReason> failure_reason_; + + DISALLOW_COPY_AND_ASSIGN(TestContentVerifyJobObserver); +}; + +namespace content_verifier_test_utils { + +// Unzips the extension source from |extension_zip| into |unzip_dir| +// directory and loads it. Returns the resulting Extension object. +// |destination| points to the path where the extension was extracted. +// +// TODO(lazyboy): Move this function to a generic file. +scoped_refptr<Extension> UnzipToDirAndLoadExtension( + const base::FilePath& extension_zip, + const base::FilePath& unzip_dir); + +} // namespace content_verifier_test_utils + +} // namespace extensions + +#endif // EXTENSIONS_BROWSER_CONTENT_VERIFIER_TEST_UTILS_H_
diff --git a/extensions/browser/content_verify_job.cc b/extensions/browser/content_verify_job.cc index 008da0c..cfdc93f 100644 --- a/extensions/browser/content_verify_job.cc +++ b/extensions/browser/content_verify_job.cc
@@ -18,7 +18,7 @@ namespace { -ContentVerifyJob::TestDelegate* g_test_delegate = NULL; +bool g_ignore_verification_for_tests = false; ContentVerifyJob::TestObserver* g_content_verify_job_test_observer = NULL; class ScopedElapsedTimer { @@ -72,13 +72,8 @@ base::AutoLock auto_lock(lock_); if (failed_) return; - if (g_test_delegate) { - FailureReason reason = - g_test_delegate->BytesRead(hash_reader_->extension_id(), count, data); - if (reason != NONE) - DispatchFailureCallback(reason); + if (g_ignore_verification_for_tests) return; - } if (!hashes_ready_) { queue_.append(data, count); return; @@ -119,13 +114,8 @@ base::AutoLock auto_lock(lock_); if (failed_) return; - if (g_test_delegate) { - FailureReason reason = - g_test_delegate->DoneReading(hash_reader_->extension_id()); - if (reason != NONE) - DispatchFailureCallback(reason); + if (g_ignore_verification_for_tests) return; - } done_reading_ = true; if (hashes_ready_) { if (!FinishBlock()) { @@ -168,7 +158,9 @@ } void ContentVerifyJob::OnHashesReady(bool success) { - if (!success && !g_test_delegate) { + if (g_ignore_verification_for_tests) + return; + if (!success) { // TODO(lazyboy): Make ContentHashReader::Init return an enum instead of // bool. This should make the following checks on |hash_reader_| easier // to digest and will avoid future bugs from creeping up. @@ -211,15 +203,16 @@ } // static -void ContentVerifyJob::SetDelegateForTests(TestDelegate* delegate) { - DCHECK(delegate == nullptr || g_test_delegate == nullptr) - << "SetDelegateForTests does not support interleaving. Delegates should " - << "be set and then cleared one at a time."; - g_test_delegate = delegate; +void ContentVerifyJob::SetIgnoreVerificationForTests(bool value) { + DCHECK_NE(g_ignore_verification_for_tests, value); + g_ignore_verification_for_tests = value; } // static void ContentVerifyJob::SetObserverForTests(TestObserver* observer) { + DCHECK(observer == nullptr || g_content_verify_job_test_observer == nullptr) + << "SetObserverForTests does not support interleaving. Observers should " + << "be set and then cleared one at a time."; g_content_verify_job_test_observer = observer; }
diff --git a/extensions/browser/content_verify_job.h b/extensions/browser/content_verify_job.h index b93e34fd5..917783e1 100644 --- a/extensions/browser/content_verify_job.h +++ b/extensions/browser/content_verify_job.h
@@ -69,19 +69,6 @@ // Call once when finished adding bytes via BytesRead. void DoneReading(); - class TestDelegate { - public: - virtual ~TestDelegate() {} - - // These methods will be called inside BytesRead/DoneReading respectively. - // If either return something other than NONE, then the failure callback - // will be dispatched with that reason. - virtual FailureReason BytesRead(const std::string& extension_id, - int count, - const char* data) = 0; - virtual FailureReason DoneReading(const std::string& extension_id) = 0; - }; - class TestObserver { public: virtual void JobStarted(const std::string& extension_id, @@ -92,9 +79,9 @@ FailureReason failure_reason) = 0; }; - // Note: having interleaved delegates is not supported. - static void SetDelegateForTests(TestDelegate* delegate); + static void SetIgnoreVerificationForTests(bool value); + // Note: having interleaved observer is not supported. static void SetObserverForTests(TestObserver* observer); private:
diff --git a/extensions/browser/content_verify_job_unittest.cc b/extensions/browser/content_verify_job_unittest.cc index 78c7b17a..85d07ec 100644 --- a/extensions/browser/content_verify_job_unittest.cc +++ b/extensions/browser/content_verify_job_unittest.cc
@@ -7,11 +7,11 @@ #include "base/files/scoped_temp_dir.h" #include "base/memory/ptr_util.h" #include "base/path_service.h" -#include "base/run_loop.h" #include "base/version.h" #include "content/public/browser/browser_thread.h" #include "content/public/test/test_browser_thread_bundle.h" #include "extensions/browser/content_hash_reader.h" +#include "extensions/browser/content_verifier/test_utils.h" #include "extensions/browser/extensions_test.h" #include "extensions/common/constants.h" #include "extensions/common/extension_paths.h" @@ -35,43 +35,6 @@ void DoNothingWithReasonParam(ContentVerifyJob::FailureReason reason) {} -class JobTestObserver : public ContentVerifyJob::TestObserver { - public: - JobTestObserver(const std::string& extension_id, - const base::FilePath& relative_path) - : extension_id_(extension_id), relative_path_(relative_path) { - ContentVerifyJob::SetObserverForTests(this); - } - ~JobTestObserver() { ContentVerifyJob::SetObserverForTests(nullptr); } - - void JobStarted(const std::string& extension_id, - const base::FilePath& relative_path) override {} - - void JobFinished(const std::string& extension_id, - const base::FilePath& relative_path, - ContentVerifyJob::FailureReason reason) override { - if (extension_id != extension_id_ || relative_path != relative_path_) - return; - failure_reason_ = reason; - run_loop_.Quit(); - } - - ContentVerifyJob::FailureReason WaitAndGetFailureReason() { - // Run() returns immediately if Quit() has already been called. - run_loop_.Run(); - EXPECT_TRUE(failure_reason_.has_value()); - return failure_reason_.value_or(ContentVerifyJob::FAILURE_REASON_MAX); - } - - private: - base::RunLoop run_loop_; - std::string extension_id_; - base::FilePath relative_path_; - base::Optional<ContentVerifyJob::FailureReason> failure_reason_; - - DISALLOW_COPY_AND_ASSIGN(JobTestObserver); -}; - } // namespace class ContentVerifyJobUnittest : public ExtensionsTest { @@ -91,29 +54,12 @@ return base_path.Append(relative_path); } - // Unzips the extension source from |extension_zip| into a temporary - // directory and loads it. Returns the resuling Extension object. - // |destination| points to the path where the extension was extracted. - scoped_refptr<Extension> UnzipToTempDirAndLoad( - const base::FilePath& extension_zip, - base::FilePath* destination) { - EXPECT_TRUE(temp_dir_.CreateUniqueTempDir()); - *destination = temp_dir_.GetPath(); - EXPECT_TRUE(zip::Unzip(extension_zip, *destination)); - - std::string error; - scoped_refptr<Extension> extension = file_util::LoadExtension( - *destination, Manifest::INTERNAL, 0 /* flags */, &error); - EXPECT_NE(nullptr, extension.get()) << " error:'" << error << "'"; - return extension; - } - protected: ContentVerifyJob::FailureReason RunContentVerifyJob( const Extension& extension, const base::FilePath& resource_path, std::string& resource_contents) { - JobTestObserver observer(extension.id(), resource_path); + TestContentVerifyJobObserver observer(extension.id(), resource_path); scoped_refptr<ContentHashReader> content_hash_reader = CreateContentHashReader(extension, resource_path); scoped_refptr<ContentVerifyJob> verify_job = new ContentVerifyJob( @@ -134,11 +80,13 @@ // modification. void RunContentMismatchTest( const std::string& content_to_append_for_mismatch) { - base::FilePath unzipped_path; + ASSERT_TRUE(temp_dir_.CreateUniqueTempDir()); + base::FilePath unzipped_path = temp_dir_.GetPath(); base::FilePath test_dir_base = GetTestPath( base::FilePath(FILE_PATH_LITERAL("with_verified_contents"))); - scoped_refptr<Extension> extension = UnzipToTempDirAndLoad( - test_dir_base.AppendASCII("source_all.zip"), &unzipped_path); + scoped_refptr<Extension> extension = + content_verifier_test_utils::UnzipToDirAndLoadExtension( + test_dir_base.AppendASCII("source_all.zip"), unzipped_path); ASSERT_TRUE(extension.get()); // Make sure there is a verified_contents.json file there as this test // cannot fetch it. @@ -160,9 +108,9 @@ } } - private: base::ScopedTempDir temp_dir_; + private: DISALLOW_COPY_AND_ASSIGN(ContentVerifyJobUnittest); }; @@ -170,11 +118,13 @@ // Also tests that non-existent file request does not trigger content // verification failure. TEST_F(ContentVerifyJobUnittest, DeletedAndMissingFiles) { - base::FilePath unzipped_path; + ASSERT_TRUE(temp_dir_.CreateUniqueTempDir()); + base::FilePath unzipped_path = temp_dir_.GetPath(); base::FilePath test_dir_base = GetTestPath(base::FilePath(FILE_PATH_LITERAL("with_verified_contents"))); - scoped_refptr<Extension> extension = UnzipToTempDirAndLoad( - test_dir_base.AppendASCII("source_all.zip"), &unzipped_path); + scoped_refptr<Extension> extension = + content_verifier_test_utils::UnzipToDirAndLoadExtension( + test_dir_base.AppendASCII("source_all.zip"), unzipped_path); ASSERT_TRUE(extension.get()); // Make sure there is a verified_contents.json file there as this test cannot // fetch it. @@ -268,12 +218,14 @@ // Tests that extension resources that are originally 0 byte behave correctly // with content verification. TEST_F(ContentVerifyJobUnittest, LegitimateZeroByteFile) { - base::FilePath unzipped_path; + ASSERT_TRUE(temp_dir_.CreateUniqueTempDir()); + base::FilePath unzipped_path = temp_dir_.GetPath(); base::FilePath test_dir_base = GetTestPath(base::FilePath(FILE_PATH_LITERAL("zero_byte_file"))); // |extension| has a 0 byte background.js file in it. - scoped_refptr<Extension> extension = UnzipToTempDirAndLoad( - test_dir_base.AppendASCII("source.zip"), &unzipped_path); + scoped_refptr<Extension> extension = + content_verifier_test_utils::UnzipToDirAndLoadExtension( + test_dir_base.AppendASCII("source.zip"), unzipped_path); ASSERT_TRUE(extension.get()); // Make sure there is a verified_contents.json file there as this test cannot // fetch it. @@ -305,11 +257,13 @@ // Regression test for https://crbug.com/720597, where content verification // always failed for sizes multiple of content hash's block size (4096 bytes). TEST_F(ContentVerifyJobUnittest, DifferentSizedFiles) { + ASSERT_TRUE(temp_dir_.CreateUniqueTempDir()); + base::FilePath unzipped_path = temp_dir_.GetPath(); base::FilePath test_dir_base = GetTestPath(base::FilePath(FILE_PATH_LITERAL("different_sized_files"))); - base::FilePath unzipped_path; - scoped_refptr<Extension> extension = UnzipToTempDirAndLoad( - test_dir_base.AppendASCII("source.zip"), &unzipped_path); + scoped_refptr<Extension> extension = + content_verifier_test_utils::UnzipToDirAndLoadExtension( + test_dir_base.AppendASCII("source.zip"), unzipped_path); ASSERT_TRUE(extension.get()); // Make sure there is a verified_contents.json file there as this test cannot // fetch it.
diff --git a/extensions/browser/extensions_browser_client.h b/extensions/browser/extensions_browser_client.h index 267a4012..0d0e8ce 100644 --- a/extensions/browser/extensions_browser_client.h +++ b/extensions/browser/extensions_browser_client.h
@@ -15,6 +15,7 @@ #include "content/public/common/resource_type.h" #include "extensions/browser/extension_event_histogram_value.h" #include "extensions/browser/extension_prefs_observer.h" +#include "extensions/common/extension_id.h" #include "extensions/common/view_type.h" #include "services/network/public/interfaces/url_loader.mojom.h" #include "services/service_manager/public/cpp/binder_registry.h" @@ -186,6 +187,10 @@ // Return true if the system is run in forced app mode. virtual bool IsRunningInForcedAppMode() = 0; + // Returns whether the system is run in forced app mode for app with the + // provided extension ID. + virtual bool IsAppModeForcedForApp(const ExtensionId& id) = 0; + // Return true if the user is logged in as a public session. virtual bool IsLoggedInAsPublicAccount() = 0;
diff --git a/extensions/browser/scoped_ignore_content_verifier_for_test.cc b/extensions/browser/scoped_ignore_content_verifier_for_test.cc index 2d67aeb8..83c5423 100644 --- a/extensions/browser/scoped_ignore_content_verifier_for_test.cc +++ b/extensions/browser/scoped_ignore_content_verifier_for_test.cc
@@ -4,26 +4,16 @@ #include "extensions/browser/scoped_ignore_content_verifier_for_test.h" +#include "extensions/browser/content_verify_job.h" + namespace extensions { ScopedIgnoreContentVerifierForTest::ScopedIgnoreContentVerifierForTest() { - ContentVerifyJob::SetDelegateForTests(this); + ContentVerifyJob::SetIgnoreVerificationForTests(true); } ScopedIgnoreContentVerifierForTest::~ScopedIgnoreContentVerifierForTest() { - ContentVerifyJob::SetDelegateForTests(nullptr); -} - -ContentVerifyJob::FailureReason ScopedIgnoreContentVerifierForTest::BytesRead( - const std::string& extension_id, - int count, - const char* data) { - return ContentVerifyJob::NONE; -} - -ContentVerifyJob::FailureReason ScopedIgnoreContentVerifierForTest::DoneReading( - const std::string& extension_id) { - return ContentVerifyJob::NONE; + ContentVerifyJob::SetIgnoreVerificationForTests(false); } } // namespace extensions
diff --git a/extensions/browser/scoped_ignore_content_verifier_for_test.h b/extensions/browser/scoped_ignore_content_verifier_for_test.h index c295a3b6..eff3071 100644 --- a/extensions/browser/scoped_ignore_content_verifier_for_test.h +++ b/extensions/browser/scoped_ignore_content_verifier_for_test.h
@@ -5,28 +5,17 @@ #ifndef EXTENSIONS_BROWSER_SCOPED_IGNORE_CONTENT_VERIFIER_FOR_TEST_H_ #define EXTENSIONS_BROWSER_SCOPED_IGNORE_CONTENT_VERIFIER_FOR_TEST_H_ -#include <string> - -#include "extensions/browser/content_verify_job.h" +#include "base/macros.h" namespace extensions { // A class for use in tests to make content verification failures be ignored // during the lifetime of an instance of it. Note that only one instance should -// be alive at any given time, and that it is not compatible with other -// concurrent objects using the ContentVerifyJob::TestDelegate interface. -class ScopedIgnoreContentVerifierForTest - : public ContentVerifyJob::TestDelegate { +// be alive at any given time. +class ScopedIgnoreContentVerifierForTest { public: ScopedIgnoreContentVerifierForTest(); - ~ScopedIgnoreContentVerifierForTest() override; - - // ContentVerifyJob::TestDelegate interface - ContentVerifyJob::FailureReason BytesRead(const std::string& extension_id, - int count, - const char* data) override; - ContentVerifyJob::FailureReason DoneReading( - const std::string& extension_id) override; + ~ScopedIgnoreContentVerifierForTest(); private: DISALLOW_COPY_AND_ASSIGN(ScopedIgnoreContentVerifierForTest);
diff --git a/extensions/browser/test_extensions_browser_client.cc b/extensions/browser/test_extensions_browser_client.cc index 13e9718..d0d5dff5 100644 --- a/extensions/browser/test_extensions_browser_client.cc +++ b/extensions/browser/test_extensions_browser_client.cc
@@ -171,6 +171,11 @@ bool TestExtensionsBrowserClient::IsRunningInForcedAppMode() { return false; } +bool TestExtensionsBrowserClient::IsAppModeForcedForApp( + const ExtensionId& extension_id) { + return false; +} + bool TestExtensionsBrowserClient::IsLoggedInAsPublicAccount() { return false; }
diff --git a/extensions/browser/test_extensions_browser_client.h b/extensions/browser/test_extensions_browser_client.h index 8cac8ff2..3afe7ea7 100644 --- a/extensions/browser/test_extensions_browser_client.h +++ b/extensions/browser/test_extensions_browser_client.h
@@ -105,6 +105,7 @@ bool DidVersionUpdate(content::BrowserContext* context) override; void PermitExternalProtocolHandler() override; bool IsRunningInForcedAppMode() override; + bool IsAppModeForcedForApp(const ExtensionId& extension_id) override; bool IsLoggedInAsPublicAccount() override; ExtensionSystemProvider* GetExtensionSystemFactory() override; void RegisterExtensionFunctions(
diff --git a/extensions/common/api/media_perception_private.idl b/extensions/common/api/media_perception_private.idl index 5925c021..0d196d0 100644 --- a/extensions/common/api/media_perception_private.idl +++ b/extensions/common/api/media_perception_private.idl
@@ -192,6 +192,47 @@ long? latencyUsec; }; + // Type of lighting conditions. + enum LightCondition { + UNSPECIFIED, + + // No noticeable change occurred. + NO_CHANGE, + + // Light was switched on in the room. + TURNED_ON, + + // Light was switched off in the room. + TURNED_OFF, + + // Light gradually got dimmer (for example, due to a sunset). + DIMMER, + + // Light gradually got brighter (for example, due to a sunrise). + BRIGHTER, + + // Black frame was detected - the current frame contains only noise. + BLACK_FRAME + }; + + // Detection of human presence close to the camera. + dictionary VideoHumanPresenceDetection { + // Indicates a probability in [0, 1] interval that a human is present in + // the video frame. + double? humanPresenceLikelihood; + + // Indicates a probability in [0, 1] that motion has been detected in the + // video frame. + double? motionDetectedLikelihood; + + // Indicates lighting condition in the video frame. + LightCondition? lightCondition; + + // Indicates a probablity in [0, 1] interval that + // <code>lightCondition</code> value is correct. + double? lightConditionLikelihood; + }; + // The set of computer vision metadata for an image frame. dictionary FramePerception { long? frameId; @@ -208,6 +249,53 @@ // Processing latency for a list of packets. PacketLatency[]? packetLatency; + + // Human presence detection results for a video frame. + VideoHumanPresenceDetection? videoHumanPresenceDetection; + }; + + // An estimate of the direction that the sound is coming from. + dictionary AudioLocalization { + // An angle in radians in the horizontal plane. It roughly points to the + // peak in the probability distribution of azimuth defined below. + double? azimuthRadians; + + // A probability distribution for the current snapshot in time that shows + // the likelihood of a sound source being at a particular azimuth. For + // example, <code>azimuthScores = [0.1, 0.2, 0.3, 0.4]</code> means that + // the probability that the sound is coming from an azimuth of 0, pi/2, pi, + // 3*pi/2 is 0.1, 0.2, 0.3 and 0.4, respectively. + double[]? azimuthScores; + }; + + // Spectrogram of an audio frame. + dictionary AudioSpectrogram { + double[]? values; + }; + + // Detection of human presence close to the microphone. + dictionary AudioHumanPresenceDetection { + // Indicates a probability in [0, 1] interval that a human has caused a + // sound close to the microphone. + double? humanPresenceLikelihood; + + // Estimate of the noise spectrogram. + AudioSpectrogram? noiseSpectrogram; + + // Spectrogram of an audio frame. + AudioSpectrogram? frameSpectrogram; + }; + + // Audio perception results for an audio frame. + dictionary AudioPerception { + // A timestamp in microseconds attached when this message was generated. + double? timestampUs; + + // Audio localization results for an audio frame. + AudioLocalization? audioLocalization; + + // Audio human presence detection results for an audio frame. + AudioHumanPresenceDetection? audioHumanPresenceDetection; }; dictionary MediaPerception { @@ -219,6 +307,9 @@ // An array of framePerceptions. FramePerception[]? framePerceptions; + + // An array of audio perceptions. + AudioPerception[]? audioPerceptions; }; enum ImageFormat { @@ -247,6 +338,9 @@ // The image frame data for the associated FramePerception object. ImageFrame? imageFrame; + + // The audio perception results for an audio frame. + AudioPerception? audioPerception; }; dictionary Diagnostics {
diff --git a/extensions/common/manifest.h b/extensions/common/manifest.h index 8752470..0ea03aa 100644 --- a/extensions/common/manifest.h +++ b/extensions/common/manifest.h
@@ -9,6 +9,7 @@ #include <memory> #include <set> #include <string> +#include <vector> #include "base/macros.h" #include "base/strings/string16.h" @@ -54,19 +55,19 @@ NUM_LOCATIONS }; - // Do not change the order of entries or remove entries in this list - // as this is used in UMA_HISTOGRAM_ENUMERATIONs about extensions. + // Do not change the order of entries or remove entries in this list as this + // is used in ExtensionType enum in tools/metrics/histograms/enums.xml. enum Type { TYPE_UNKNOWN = 0, - TYPE_EXTENSION, - TYPE_THEME, - TYPE_USER_SCRIPT, - TYPE_HOSTED_APP, + TYPE_EXTENSION = 1, + TYPE_THEME = 2, + TYPE_USER_SCRIPT = 3, + TYPE_HOSTED_APP = 4, // This is marked legacy because platform apps are preferred. For // backwards compatibility, we can't remove support for packaged apps - TYPE_LEGACY_PACKAGED_APP, - TYPE_PLATFORM_APP, - TYPE_SHARED_MODULE, + TYPE_LEGACY_PACKAGED_APP = 5, + TYPE_PLATFORM_APP = 6, + TYPE_SHARED_MODULE = 7, // New enum values must go above here. NUM_LOAD_TYPES
diff --git a/extensions/common/permissions/permission_set.cc b/extensions/common/permissions/permission_set.cc index 137af80..c94a210 100644 --- a/extensions/common/permissions/permission_set.cc +++ b/extensions/common/permissions/permission_set.cc
@@ -185,14 +185,6 @@ return explicit_hosts().MatchesURL(origin); } -bool PermissionSet::HasScriptableAccessToURL( - const GURL& origin) const { - // We only need to check our host list to verify access. The host list should - // already reflect any special rules (such as chrome://favicon, all hosts - // access, etc.). - return scriptable_hosts().MatchesURL(origin); -} - bool PermissionSet::HasEffectiveAccessToAllHosts() const { // There are two ways this set can have effective access to all hosts: // 1) it has an <all_urls> URL pattern.
diff --git a/extensions/common/permissions/permission_set.h b/extensions/common/permissions/permission_set.h index f1b2593..26a5289 100644 --- a/extensions/common/permissions/permission_set.h +++ b/extensions/common/permissions/permission_set.h
@@ -93,9 +93,6 @@ // Returns true if this includes permission to access |origin|. bool HasExplicitAccessToOrigin(const GURL& origin) const; - // Returns true if this permission set includes access to script |url|. - bool HasScriptableAccessToURL(const GURL& url) const; - // Returns true if this permission set includes effective access to all // origins. bool HasEffectiveAccessToAllHosts() const;
diff --git a/extensions/common/view_type.h b/extensions/common/view_type.h index f60a934..a58524f 100644 --- a/extensions/common/view_type.h +++ b/extensions/common/view_type.h
@@ -12,19 +12,26 @@ // Icky RTTI used by a few systems to distinguish the host type of a given // WebContents. // +// Do not change the order of entries or remove entries in this list as this +// is used in ExtensionViewType enum in tools/metrics/histograms/enums.xml. +// // TODO(aa): Remove this and teach those systems to keep track of their own // data. enum ViewType { - VIEW_TYPE_INVALID, - VIEW_TYPE_APP_WINDOW, - VIEW_TYPE_BACKGROUND_CONTENTS, - VIEW_TYPE_COMPONENT, // For custom parts of Chrome if no other type applies. - VIEW_TYPE_EXTENSION_BACKGROUND_PAGE, - VIEW_TYPE_EXTENSION_DIALOG, - VIEW_TYPE_EXTENSION_GUEST, - VIEW_TYPE_EXTENSION_POPUP, - VIEW_TYPE_PANEL, - VIEW_TYPE_TAB_CONTENTS, + VIEW_TYPE_INVALID = 0, + VIEW_TYPE_APP_WINDOW = 1, + VIEW_TYPE_BACKGROUND_CONTENTS = 2, + + // For custom parts of Chrome if no other type applies. + VIEW_TYPE_COMPONENT = 3, + + VIEW_TYPE_EXTENSION_BACKGROUND_PAGE = 4, + VIEW_TYPE_EXTENSION_DIALOG = 5, + VIEW_TYPE_EXTENSION_GUEST = 6, + VIEW_TYPE_EXTENSION_POPUP = 7, + VIEW_TYPE_PANEL = 8, + VIEW_TYPE_TAB_CONTENTS = 9, + VIEW_TYPE_LAST = VIEW_TYPE_TAB_CONTENTS };
diff --git a/extensions/renderer/extension_frame_helper.cc b/extensions/renderer/extension_frame_helper.cc index c594a57..749f9ba6 100644 --- a/extensions/renderer/extension_frame_helper.cc +++ b/extensions/renderer/extension_frame_helper.cc
@@ -200,17 +200,43 @@ if (!extension) return nullptr; - for (const ExtensionFrameHelper* helper : g_frame_helpers.Get()) { + for (const ExtensionFrameHelper* target : g_frame_helpers.Get()) { + // Skip frames with a mismatched name. + if (target->render_frame()->GetWebFrame()->AssignedName().Utf8() != name) + continue; + // Only pierce browsing instance boundaries if the target frame is from the // same extension (but not when another extension shares the same renderer // process because of reuse trigerred by process limit). - // TODO(lukasza): https://crbug.com/764487: Investigate if we can further - // restrict scenarios that allow piercing of browsing instance boundaries. - if (extension != GetExtensionFromFrame(helper->render_frame())) + if (extension != GetExtensionFromFrame(target->render_frame())) continue; - if (helper->render_frame()->GetWebFrame()->AssignedName().Utf8() == name) - return helper->render_frame(); + // TODO(lukasza): https://crbug.com/764487: Investigate if we can further + // restrict scenarios that allow piercing of browsing instance boundaries. + // We hope that the piercing is only needed if the source or target frames + // are for background contents or background page. + ViewType target_view_type = target->view_type(); + ViewType source_view_type = + ExtensionFrameHelper::Get(relative_to_frame)->view_type(); + UMA_HISTOGRAM_ENUMERATION( + "Extensions.BrowsingInstanceViolation.ExtensionType", + extension->GetType(), Manifest::NUM_LOAD_TYPES); + UMA_HISTOGRAM_ENUMERATION( + "Extensions.BrowsingInstanceViolation.SourceExtensionViewType", + source_view_type, VIEW_TYPE_LAST + 1); + UMA_HISTOGRAM_ENUMERATION( + "Extensions.BrowsingInstanceViolation.TargetExtensionViewType", + target_view_type, VIEW_TYPE_LAST + 1); + bool is_background_source_or_target = + source_view_type == VIEW_TYPE_EXTENSION_BACKGROUND_PAGE || + source_view_type == VIEW_TYPE_BACKGROUND_CONTENTS || + target_view_type == VIEW_TYPE_EXTENSION_BACKGROUND_PAGE || + target_view_type == VIEW_TYPE_BACKGROUND_CONTENTS; + UMA_HISTOGRAM_BOOLEAN( + "Extensions.BrowsingInstanceViolation.IsBackgroundSourceOrTarget", + is_background_source_or_target); + + return target->render_frame(); } return nullptr;
diff --git a/extensions/renderer/i18n_custom_bindings.cc b/extensions/renderer/i18n_custom_bindings.cc index fb5e6ccb..57aa102 100644 --- a/extensions/renderer/i18n_custom_bindings.cc +++ b/extensions/renderer/i18n_custom_bindings.cc
@@ -21,6 +21,7 @@ #include "extensions/common/message_bundle.h" #include "extensions/renderer/script_context.h" #include "extensions/renderer/v8_helpers.h" +#include "gin/data_object_builder.h" #include "third_party/cld_3/src/src/nnet_language_identifier.h" namespace extensions { @@ -39,17 +40,13 @@ struct DetectedLanguage { DetectedLanguage(const std::string& language, int percentage) : language(language), percentage(percentage) {} - ~DetectedLanguage() {} // Returns a new v8::Local<v8::Value> representing the serialized form of // this DetectedLanguage object. - std::unique_ptr<base::DictionaryValue> ToDictionary() const; + v8::Local<v8::Value> ToV8(v8::Isolate* isolate) const; std::string language; int percentage; - - private: - DISALLOW_COPY_AND_ASSIGN(DetectedLanguage); }; // LanguageDetectionResult object that holds detected langugae reliability and @@ -62,50 +59,49 @@ // Returns a new v8::Local<v8::Value> representing the serialized form of // this Result object. - v8::Local<v8::Value> ToValue(ScriptContext* context); + v8::Local<v8::Value> ToV8(v8::Local<v8::Context> context) const; // CLD detected language reliability bool is_reliable; // Array of detectedLanguage of size 1-3. The null is returned if // there were no languages detected - std::vector<std::unique_ptr<DetectedLanguage>> languages; + std::vector<DetectedLanguage> languages; private: DISALLOW_COPY_AND_ASSIGN(LanguageDetectionResult); }; -std::unique_ptr<base::DictionaryValue> DetectedLanguage::ToDictionary() const { - std::unique_ptr<base::DictionaryValue> dict_value( - new base::DictionaryValue()); - dict_value->SetString("language", language.c_str()); - dict_value->SetInteger("percentage", percentage); - return dict_value; +v8::Local<v8::Value> DetectedLanguage::ToV8(v8::Isolate* isolate) const { + return gin::DataObjectBuilder(isolate) + .Set("language", language) + .Set("percentage", percentage) + .Build(); } -v8::Local<v8::Value> LanguageDetectionResult::ToValue(ScriptContext* context) { - base::DictionaryValue dict_value; - dict_value.SetBoolean("isReliable", is_reliable); - std::unique_ptr<base::ListValue> languages_list(new base::ListValue()); - for (const auto& language : languages) - languages_list->Append(language->ToDictionary()); - dict_value.Set("languages", std::move(languages_list)); +v8::Local<v8::Value> LanguageDetectionResult::ToV8( + v8::Local<v8::Context> context) const { + v8::Isolate* isolate = context->GetIsolate(); + DCHECK(isolate->GetCurrentContext() == context); - v8::Local<v8::Context> v8_context = context->v8_context(); - v8::Isolate* isolate = v8_context->GetIsolate(); - v8::EscapableHandleScope handle_scope(isolate); - - v8::Local<v8::Value> result = - content::V8ValueConverter::Create()->ToV8Value(&dict_value, v8_context); - return handle_scope.Escape(result); + v8::Local<v8::Array> v8_languages = v8::Array::New(isolate, languages.size()); + for (uint32_t i = 0; i < languages.size(); ++i) { + bool success = + v8_languages->CreateDataProperty(context, i, languages[i].ToV8(isolate)) + .ToChecked(); + DCHECK(success) << "CreateDataProperty() should never fail."; + } + return gin::DataObjectBuilder(isolate) + .Set("isReliable", is_reliable) + .Set("languages", v8_languages.As<v8::Value>()) + .Build(); } void InitDetectedLanguages( const std::vector<chrome_lang_id::NNetLanguageIdentifier::Result>& lang_results, LanguageDetectionResult* result) { - std::vector<std::unique_ptr<DetectedLanguage>>* detected_languages = - &result->languages; + std::vector<DetectedLanguage>* detected_languages = &result->languages; DCHECK(detected_languages->empty()); bool* is_reliable = &result->is_reliable; @@ -136,13 +132,11 @@ *is_reliable = *is_reliable && lang_result.is_reliable; const int percent = static_cast<int>(100 * lang_result.proportion); - detected_languages->push_back( - std::make_unique<DetectedLanguage>(language_code, percent)); + detected_languages->emplace_back(language_code, percent); } - if (detected_languages->empty()) { + if (detected_languages->empty()) *is_reliable = false; - } } } // namespace @@ -256,7 +250,7 @@ // Populate LanguageDetectionResult with prediction reliability, languages, // and the corresponding percentages. InitDetectedLanguages(lang_results, &result); - args.GetReturnValue().Set(result.ToValue(context())); + args.GetReturnValue().Set(result.ToV8(context()->v8_context())); } } // namespace extensions
diff --git a/extensions/shell/browser/shell_extensions_browser_client.cc b/extensions/shell/browser/shell_extensions_browser_client.cc index e2c35d0..fb8f78e 100644 --- a/extensions/shell/browser/shell_extensions_browser_client.cc +++ b/extensions/shell/browser/shell_extensions_browser_client.cc
@@ -178,6 +178,11 @@ return false; } +bool ShellExtensionsBrowserClient::IsAppModeForcedForApp( + const ExtensionId& extension_id) { + return false; +} + bool ShellExtensionsBrowserClient::IsLoggedInAsPublicAccount() { return false; }
diff --git a/extensions/shell/browser/shell_extensions_browser_client.h b/extensions/shell/browser/shell_extensions_browser_client.h index 398aea7..df9a5a7 100644 --- a/extensions/shell/browser/shell_extensions_browser_client.h +++ b/extensions/shell/browser/shell_extensions_browser_client.h
@@ -76,6 +76,7 @@ bool DidVersionUpdate(content::BrowserContext* context) override; void PermitExternalProtocolHandler() override; bool IsRunningInForcedAppMode() override; + bool IsAppModeForcedForApp(const ExtensionId& extension_id) override; bool IsLoggedInAsPublicAccount() override; ExtensionSystemProvider* GetExtensionSystemFactory() override; void RegisterExtensionFunctions(
diff --git a/gpu/config/gpu_driver_bug_list.json b/gpu/config/gpu_driver_bug_list.json index 9b1314a8..b2f4074 100644 --- a/gpu/config/gpu_driver_bug_list.json +++ b/gpu/config/gpu_driver_bug_list.json
@@ -2795,6 +2795,21 @@ "features": [ "max_msaa_sample_count_4" ] + }, + { + "id": 255, + "description": "Fullscreen video crashes macOS 10.11 WindowServer.", + "cr_bugs": [806506], + "os": { + "type": "macosx", + "version": { + "op": "<", + "value": "10.12" + } + }, + "features": [ + "disable_av_sample_buffer_display_layer" + ] } ] }
diff --git a/gpu/ipc/client/gpu_memory_buffer_impl_io_surface.cc b/gpu/ipc/client/gpu_memory_buffer_impl_io_surface.cc index 40e592b..fbeaf65 100644 --- a/gpu/ipc/client/gpu_memory_buffer_impl_io_surface.cc +++ b/gpu/ipc/client/gpu_memory_buffer_impl_io_surface.cc
@@ -55,10 +55,17 @@ gfx::BufferFormat format, gfx::BufferUsage usage, const DestructionCallback& callback) { + if (!handle.mach_port) { + LOG(ERROR) << "Invalid IOSurface mach port returned to client."; + return nullptr; + } + base::ScopedCFTypeRef<IOSurfaceRef> io_surface( IOSurfaceLookupFromMachPort(handle.mach_port.get())); - if (!io_surface) + if (!io_surface) { + LOG(ERROR) << "Failed to open IOSurface via mach port returned to client."; return nullptr; + } return base::WrapUnique( new GpuMemoryBufferImplIOSurface(handle.id, size, format, callback,
diff --git a/gpu/ipc/common/gpu_memory_buffer_support.cc b/gpu/ipc/common/gpu_memory_buffer_support.cc index 069db4b..18bb4fd 100644 --- a/gpu/ipc/common/gpu_memory_buffer_support.cc +++ b/gpu/ipc/common/gpu_memory_buffer_support.cc
@@ -41,18 +41,13 @@ case gfx::BufferUsage::GPU_READ: case gfx::BufferUsage::SCANOUT: case gfx::BufferUsage::SCANOUT_CPU_READ_WRITE: + case gfx::BufferUsage::GPU_READ_CPU_READ_WRITE: + case gfx::BufferUsage::GPU_READ_CPU_READ_WRITE_PERSISTENT: return format == gfx::BufferFormat::BGRA_8888 || format == gfx::BufferFormat::RGBA_8888 || format == gfx::BufferFormat::BGRX_8888 || format == gfx::BufferFormat::R_8 || format == gfx::BufferFormat::RGBA_F16 || - format == gfx::BufferFormat::UYVY_422 || - format == gfx::BufferFormat::YUV_420_BIPLANAR; - case gfx::BufferUsage::GPU_READ_CPU_READ_WRITE: - case gfx::BufferUsage::GPU_READ_CPU_READ_WRITE_PERSISTENT: - return format == gfx::BufferFormat::R_8 || - format == gfx::BufferFormat::BGRA_8888 || - format == gfx::BufferFormat::RGBA_F16 || format == gfx::BufferFormat::BGRX_1010102 || format == gfx::BufferFormat::UYVY_422 || format == gfx::BufferFormat::YUV_420_BIPLANAR;
diff --git a/gpu/ipc/host/gpu_memory_buffer_support.cc b/gpu/ipc/host/gpu_memory_buffer_support.cc index 78c7c82..ffc9579 100644 --- a/gpu/ipc/host/gpu_memory_buffer_support.cc +++ b/gpu/ipc/host/gpu_memory_buffer_support.cc
@@ -47,8 +47,10 @@ gfx::BufferFormat::RGBA_F16, gfx::BufferFormat::UYVY_422, gfx::BufferFormat::YVU_420, gfx::BufferFormat::YUV_420_BIPLANAR}; const gfx::BufferUsage kNativeUsages[] = { - gfx::BufferUsage::GPU_READ, gfx::BufferUsage::SCANOUT, + gfx::BufferUsage::GPU_READ, + gfx::BufferUsage::SCANOUT, gfx::BufferUsage::SCANOUT_CAMERA_READ_WRITE, + gfx::BufferUsage::SCANOUT_CPU_READ_WRITE, gfx::BufferUsage::GPU_READ_CPU_READ_WRITE, gfx::BufferUsage::GPU_READ_CPU_READ_WRITE_PERSISTENT}; for (auto format : kNativeFormats) {
diff --git a/gpu/ipc/service/direct_composition_surface_win.cc b/gpu/ipc/service/direct_composition_surface_win.cc index 0df3457..9b009bb 100644 --- a/gpu/ipc/service/direct_composition_surface_win.cc +++ b/gpu/ipc/service/direct_composition_surface_win.cc
@@ -35,6 +35,7 @@ #include "ui/gl/gl_image_dxgi.h" #include "ui/gl/gl_image_memory.h" #include "ui/gl/gl_surface_egl.h" +#include "ui/gl/gl_surface_presentation_helper.h" #include "ui/gl/scoped_make_current.h" #ifndef EGL_ANGLE_flexible_surface_compatibility @@ -1205,10 +1206,16 @@ return false; } - return RecreateRootSurface(); + if (!RecreateRootSurface()) + return false; + + presentation_helper_ = + std::make_unique<gl::GLSurfacePresentationHelper>(vsync_provider_.get()); + return true; } void DirectCompositionSurfaceWin::Destroy() { + presentation_helper_ = nullptr; if (default_surface_) { if (!eglDestroySurface(GetDisplay(), default_surface_)) { DLOG(ERROR) << "eglDestroySurface failed with error " @@ -1254,12 +1261,15 @@ gfx::SwapResult DirectCompositionSurfaceWin::SwapBuffers( const PresentationCallback& callback) { + gl::GLSurfacePresentationHelper::ScopedSwapBuffers scoped_swap_buffers( + presentation_helper_.get(), callback); ui::ScopedReleaseCurrent release_current; - root_surface_->SwapBuffers(callback); + root_surface_->SwapBuffers(PresentationCallback()); layer_tree_->CommitAndClearPendingOverlays(); child_window_.ClearInvalidContents(); - return release_current.Restore() ? gfx::SwapResult::SWAP_ACK - : gfx::SwapResult::SWAP_FAILED; + if (!release_current.Restore()) + scoped_swap_buffers.set_result(gfx::SwapResult::SWAP_FAILED); + return scoped_swap_buffers.result(); } gfx::SwapResult DirectCompositionSurfaceWin::PostSubBuffer( @@ -1298,6 +1308,8 @@ } bool DirectCompositionSurfaceWin::OnMakeCurrent(gl::GLContext* context) { + if (presentation_helper_) + presentation_helper_->OnMakeCurrent(context, this); if (root_surface_) return root_surface_->OnMakeCurrent(context); return true;
diff --git a/gpu/ipc/service/direct_composition_surface_win.h b/gpu/ipc/service/direct_composition_surface_win.h index f135c1d..a7c1b0d5 100644 --- a/gpu/ipc/service/direct_composition_surface_win.h +++ b/gpu/ipc/service/direct_composition_surface_win.h
@@ -18,6 +18,10 @@ #include "ui/gl/gl_image.h" #include "ui/gl/gl_surface_egl.h" +namespace gl { +class GLSurfacePresentationHelper; +} + namespace gpu { class DCLayerTree; @@ -107,6 +111,7 @@ bool is_hdr_ = false; bool has_alpha_ = true; std::unique_ptr<gfx::VSyncProvider> vsync_provider_; + std::unique_ptr<gl::GLSurfacePresentationHelper> presentation_helper_; scoped_refptr<DirectCompositionChildSurfaceWin> root_surface_; std::unique_ptr<DCLayerTree> layer_tree_;
diff --git a/gpu/ipc/service/gpu_memory_buffer_factory_io_surface.cc b/gpu/ipc/service/gpu_memory_buffer_factory_io_surface.cc index f502262..9d328bb 100644 --- a/gpu/ipc/service/gpu_memory_buffer_factory_io_surface.cc +++ b/gpu/ipc/service/gpu_memory_buffer_factory_io_surface.cc
@@ -34,7 +34,7 @@ int client_id, SurfaceHandle surface_handle) { // Don't clear anonymous io surfaces. - bool should_clear = (client_id != 0); + bool should_clear = (client_id != kAnonymousClientId); base::ScopedCFTypeRef<IOSurfaceRef> io_surface( gfx::CreateIOSurface(size, format, should_clear)); if (!io_surface) { @@ -54,6 +54,17 @@ handle.type = gfx::IO_SURFACE_BUFFER; handle.id = id; handle.mach_port.reset(IOSurfaceCreateMachPort(io_surface)); + + // TODO(ccameron): This should never happen, but a similar call to + // IOSurfaceLookupFromMachPort is failing below. This should determine if + // the lifetime of the underlying IOSurface determines the failure. + // https://crbug.com/795649 + CHECK(handle.mach_port); + base::ScopedCFTypeRef<IOSurfaceRef> io_surface_recreated( + IOSurfaceLookupFromMachPort(handle.mach_port.get())); + CHECK_NE(nullptr, io_surface_recreated.get()) + << "Failed to reconstitute still-existing IOSurface from mach port."; + return handle; } @@ -112,10 +123,17 @@ gfx::GpuMemoryBufferHandle handle = CreateGpuMemoryBuffer( gfx::GpuMemoryBufferId(next_anonymous_image_id_++), size, format, usage, kAnonymousClientId, gpu::kNullSurfaceHandle); + if (handle.is_null()) + return scoped_refptr<gl::GLImage>(); - base::ScopedCFTypeRef<IOSurfaceRef> io_surface; - io_surface.reset(IOSurfaceLookupFromMachPort(handle.mach_port.get())); - DCHECK_NE(nullptr, io_surface.get()); + base::ScopedCFTypeRef<IOSurfaceRef> io_surface( + IOSurfaceLookupFromMachPort(handle.mach_port.get())); + // TODO(ccameron): This should never happen, but has been seen in the wild. If + // this happens frequently, it can be replaced by directly using the allocated + // IOSurface, rather than going through the handle creation. + // https://crbug.com/795649 + CHECK_NE(nullptr, io_surface.get()) + << "Failed to reconstitute just-created IOSurface from mach port."; scoped_refptr<gl::GLImageIOSurface> image( gl::GLImageIOSurface::Create(size, internalformat));
diff --git a/gpu/perftests/texture_upload_perftest.cc b/gpu/perftests/texture_upload_perftest.cc index 6ad71c7..bc683b1 100644 --- a/gpu/perftests/texture_upload_perftest.cc +++ b/gpu/perftests/texture_upload_perftest.cc
@@ -149,6 +149,7 @@ case GL_LUMINANCE: // (L_t, L_t, L_t, 1) expected[1] = pixels[pixels_index]; expected[2] = pixels[pixels_index]; + FALLTHROUGH; case GL_RED: // (R_t, 0, 0, 1) expected[0] = pixels[pixels_index]; expected[3] = 255;
diff --git a/headless/app/headless_shell.cc b/headless/app/headless_shell.cc index 2755fefb..31313f8 100644 --- a/headless/app/headless_shell.cc +++ b/headless/app/headless_shell.cc
@@ -487,6 +487,7 @@ page::PrintToPDFParams::Builder() .SetDisplayHeaderFooter(true) .SetPrintBackground(true) + .SetPreferCSSPageSize(true) .Build(), base::Bind(&HeadlessShell::OnPDFCreated, weak_factory_.GetWeakPtr())); }
diff --git a/headless/lib/browser/headless_devtools_manager_delegate.cc b/headless/lib/browser/headless_devtools_manager_delegate.cc index 485be57..55e023e 100644 --- a/headless/lib/browser/headless_devtools_manager_delegate.cc +++ b/headless/lib/browser/headless_devtools_manager_delegate.cc
@@ -273,6 +273,11 @@ settings->margins_in_points.right = margin_right_in_inch * printing::kPointsPerInch; + if (const base::Value* prefer_css_page_size = + params->FindKey("preferCSSPageSize")) { + settings->prefer_css_page_size = prefer_css_page_size->GetBool(); + } + return nullptr; } #endif
diff --git a/headless/lib/browser/headless_print_manager.cc b/headless/lib/browser/headless_print_manager.cc index a81cad3..0900625 100644 --- a/headless/lib/browser/headless_print_manager.cc +++ b/headless/lib/browser/headless_print_manager.cc
@@ -40,7 +40,8 @@ }; HeadlessPrintSettings::HeadlessPrintSettings() - : landscape(false), + : prefer_css_page_size(false), + landscape(false), display_header_footer(false), should_print_backgrounds(false), scale(1), @@ -204,6 +205,7 @@ base::UTF8ToUTF16(settings.header_template); print_params->params.footer_template = base::UTF8ToUTF16(settings.footer_template); + print_params->params.prefer_css_page_size = settings.prefer_css_page_size; return print_params; }
diff --git a/headless/lib/browser/headless_print_manager.h b/headless/lib/browser/headless_print_manager.h index f83555b6..8dc8007d 100644 --- a/headless/lib/browser/headless_print_manager.h +++ b/headless/lib/browser/headless_print_manager.h
@@ -27,6 +27,7 @@ gfx::Size paper_size_in_points; printing::PageMargins margins_in_points; + bool prefer_css_page_size; bool landscape; bool display_header_footer;
diff --git a/headless/lib/browser/headless_printing_unittest.cc b/headless/lib/browser/headless_printing_unittest.cc index ad7caa7..862b408 100644 --- a/headless/lib/browser/headless_printing_unittest.cc +++ b/headless/lib/browser/headless_printing_unittest.cc
@@ -13,6 +13,18 @@ namespace headless { +TEST(ParsePrintSettingsTest, PreferCSSPageSize) { + HeadlessPrintSettings settings; + EXPECT_FALSE(settings.prefer_css_page_size); + + auto params = std::make_unique<base::DictionaryValue>(); + params->SetBoolean("preferCSSPageSize", true); + std::unique_ptr<base::DictionaryValue> response = + ParsePrintSettings(0, params.get(), &settings); + EXPECT_TRUE(settings.prefer_css_page_size); + EXPECT_EQ(nullptr, response); +} + TEST(ParsePrintSettingsTest, Landscape) { HeadlessPrintSettings settings; EXPECT_FALSE(settings.landscape);
diff --git a/ios/chrome/app/application_delegate/app_state.mm b/ios/chrome/app/application_delegate/app_state.mm index ad20bcba..1c4a009 100644 --- a/ios/chrome/app/application_delegate/app_state.mm +++ b/ios/chrome/app/application_delegate/app_state.mm
@@ -116,11 +116,6 @@ _shouldPerformAdditionalDelegateHandling; @synthesize userInteracted = _userInteracted; -- (instancetype)init { - NOTREACHED(); - return nil; -} - - (instancetype) initWithBrowserLauncher:(id<BrowserLauncher>)browserLauncher startupInformation:(id<StartupInformation>)startupInformation
diff --git a/ios/chrome/app/application_delegate/url_opener.mm b/ios/chrome/app/application_delegate/url_opener.mm index 5424575..d018eff 100644 --- a/ios/chrome/app/application_delegate/url_opener.mm +++ b/ios/chrome/app/application_delegate/url_opener.mm
@@ -25,11 +25,6 @@ @implementation URLOpener -- (instancetype)init { - NOTREACHED(); - return nil; -} - #pragma mark - ApplicationDelegate - URL Opening methods + (BOOL)openURL:(NSURL*)url
diff --git a/ios/chrome/app/deferred_initialization_runner.mm b/ios/chrome/app/deferred_initialization_runner.mm index 01fa251..0556484 100644 --- a/ios/chrome/app/deferred_initialization_runner.mm +++ b/ios/chrome/app/deferred_initialization_runner.mm
@@ -38,12 +38,6 @@ ProceduralBlock _runBlock; } -// Overrides default designated initializer. -- (instancetype)init { - NOTREACHED(); - return nil; -} - - (instancetype)initWithName:(NSString*)name block:(ProceduralBlock)block { DCHECK(block); self = [super init];
diff --git a/ios/chrome/app/spotlight/base_spotlight_manager.mm b/ios/chrome/app/spotlight/base_spotlight_manager.mm index c30fb6f..6fe17a1 100644 --- a/ios/chrome/app/spotlight/base_spotlight_manager.mm +++ b/ios/chrome/app/spotlight/base_spotlight_manager.mm
@@ -87,11 +87,6 @@ return self; } -- (instancetype)init { - NOTREACHED(); - return nil; -} - - (void)dealloc { DCHECK(_shutdownCalled); }
diff --git a/ios/chrome/app/spotlight/spotlight_manager.h b/ios/chrome/app/spotlight/spotlight_manager.h index 6dfb4d8..b0a3eb94 100644 --- a/ios/chrome/app/spotlight/spotlight_manager.h +++ b/ios/chrome/app/spotlight/spotlight_manager.h
@@ -35,6 +35,8 @@ // by the subclasses and de-activate the instance. - (void)shutdown; +- (instancetype)init NS_UNAVAILABLE; + @end #endif // IOS_CHROME_APP_SPOTLIGHT_SPOTLIGHT_MANAGER_H_
diff --git a/ios/chrome/app/spotlight/spotlight_manager.mm b/ios/chrome/app/spotlight/spotlight_manager.mm index 4f494a5..af5e336 100644 --- a/ios/chrome/app/spotlight/spotlight_manager.mm +++ b/ios/chrome/app/spotlight/spotlight_manager.mm
@@ -24,7 +24,6 @@ - (instancetype)initWithBrowserState:(ios::ChromeBrowserState*)browserState NS_DESIGNATED_INITIALIZER; -- (instancetype)init NS_UNAVAILABLE; @end @implementation SpotlightManager @@ -52,11 +51,6 @@ return self; } -- (instancetype)init { - NOTREACHED(); - return nil; -} - - (void)dealloc { DCHECK(!_bookmarkManager); DCHECK(!_topSitesManager);
diff --git a/ios/chrome/browser/about_flags.mm b/ios/chrome/browser/about_flags.mm index 2310565..c0c65aa 100644 --- a/ios/chrome/browser/about_flags.mm +++ b/ios/chrome/browser/about_flags.mm
@@ -202,6 +202,9 @@ {"new-pass-kit-download", flag_descriptions::kNewPassKitDownloadName, flag_descriptions::kNewPassKitDownloadDescription, flags_ui::kOsIos, FEATURE_VALUE_TYPE(web::features::kNewPassKitDownload)}, + {"new-file-download", flag_descriptions::kNewFileDownloadName, + flag_descriptions::kNewFileDownloadDescription, flags_ui::kOsIos, + FEATURE_VALUE_TYPE(web::features::kNewFileDownload)}, {"ios-share-canonical-url", flag_descriptions::kShareCanonicalURLName, flag_descriptions::kShareCanonicalURLDescription, flags_ui::kOsIos, FEATURE_VALUE_TYPE(activity_services::kShareCanonicalURL)},
diff --git a/ios/chrome/browser/autofill/autofill_controller.mm b/ios/chrome/browser/autofill/autofill_controller.mm index f256f09..a8b5335 100644 --- a/ios/chrome/browser/autofill/autofill_controller.mm +++ b/ios/chrome/browser/autofill/autofill_controller.mm
@@ -106,11 +106,6 @@ downloadEnabled:YES]; } -- (instancetype)init { - NOTREACHED(); - return nil; -} - - (void)dealloc { DCHECK(!_autofillAgent); // detachFromWebController must have been called. }
diff --git a/ios/chrome/browser/crash_report/crash_report_multi_parameter.mm b/ios/chrome/browser/crash_report/crash_report_multi_parameter.mm index 3648e129..4a8d9fb 100644 --- a/ios/chrome/browser/crash_report/crash_report_multi_parameter.mm +++ b/ios/chrome/browser/crash_report/crash_report_multi_parameter.mm
@@ -28,11 +28,6 @@ std::unique_ptr<base::DictionaryValue> dictionary_; } -- (instancetype)init { - NOTREACHED(); - return nil; -} - - (instancetype)initWithKey:(NSString*)key { if ((self = [super init])) { DCHECK([key length] && ([key length] <= kMaximumBreakpadValueSize));
diff --git a/ios/chrome/browser/download/download_manager_tab_helper_delegate.h b/ios/chrome/browser/download/download_manager_tab_helper_delegate.h index 26c9664f..5ee194f 100644 --- a/ios/chrome/browser/download/download_manager_tab_helper_delegate.h +++ b/ios/chrome/browser/download/download_manager_tab_helper_delegate.h
@@ -18,7 +18,7 @@ // Informs the delegate that a DownloadTask was created. - (void)downloadManagerTabHelper:(nonnull DownloadManagerTabHelper*)tabHelper didCreateDownload:(nonnull web::DownloadTask*)download - webStateIsVisible:(BOOL)vebStateIsVisible; + webStateIsVisible:(BOOL)webStateIsVisible; // Informs the delegate that a DownloadTask was updated (download progress was // changed, or download has reached a terminal state).
diff --git a/ios/chrome/browser/geolocation/omnibox_geolocation_local_state.mm b/ios/chrome/browser/geolocation/omnibox_geolocation_local_state.mm index 82f8988..a34d99f 100644 --- a/ios/chrome/browser/geolocation/omnibox_geolocation_local_state.mm +++ b/ios/chrome/browser/geolocation/omnibox_geolocation_local_state.mm
@@ -47,11 +47,6 @@ return self; } -- (instancetype)init { - NOTREACHED(); - return nil; -} - - (geolocation::AuthorizationState)authorizationState { int authorizationState = [self intForPath:prefs::kOmniboxGeolocationAuthorizationState];
diff --git a/ios/chrome/browser/infobars/infobar_controller.mm b/ios/chrome/browser/infobars/infobar_controller.mm index c8eef7c..adca4565 100644 --- a/ios/chrome/browser/infobars/infobar_controller.mm +++ b/ios/chrome/browser/infobars/infobar_controller.mm
@@ -30,11 +30,6 @@ return self; } -- (instancetype)init { - NOTREACHED(); - return nil; -} - - (void)dealloc { [_infoBarView removeFromSuperview]; }
diff --git a/ios/chrome/browser/mailto/BUILD.gn b/ios/chrome/browser/mailto/BUILD.gn new file mode 100644 index 0000000..9af0174 --- /dev/null +++ b/ios/chrome/browser/mailto/BUILD.gn
@@ -0,0 +1,14 @@ +# 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. + +source_set("features") { + configs += [ "//build/config/compiler:enable_arc" ] + sources = [ + "features.h", + "features.mm", + ] + deps = [ + "//base", + ] +}
diff --git a/ios/chrome/browser/mailto/features.h b/ios/chrome/browser/mailto/features.h new file mode 100644 index 0000000..e53c2d73 --- /dev/null +++ b/ios/chrome/browser/mailto/features.h
@@ -0,0 +1,13 @@ +// 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. + +#ifndef IOS_CHROME_BROWSER_MAILTO_FEATURES_H_ +#define IOS_CHROME_BROWSER_MAILTO_FEATURES_H_ + +#include "base/feature_list.h" + +// Feature flag to enable Mailto handling. +extern const base::Feature kMailtoHandledWithGoogleUI; + +#endif // IOS_CHROME_BROWSER_MAILTO_FEATURES_H_
diff --git a/ios/chrome/browser/mailto/features.mm b/ios/chrome/browser/mailto/features.mm new file mode 100644 index 0000000..c1c403e --- /dev/null +++ b/ios/chrome/browser/mailto/features.mm
@@ -0,0 +1,12 @@ +// 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 "ios/chrome/browser/mailto/features.h" + +#if !defined(__has_feature) || !__has_feature(objc_arc) +#error "This file requires ARC support." +#endif + +const base::Feature kMailtoHandledWithGoogleUI{ + "kMailtoHandledWithGoogleUI", base::FEATURE_DISABLED_BY_DEFAULT};
diff --git a/ios/chrome/browser/ntp_snippets/BUILD.gn b/ios/chrome/browser/ntp_snippets/BUILD.gn index 1edd553..83f64df 100644 --- a/ios/chrome/browser/ntp_snippets/BUILD.gn +++ b/ios/chrome/browser/ntp_snippets/BUILD.gn
@@ -33,5 +33,6 @@ "//ios/chrome/common", "//ios/web", "//net", + "//services/identity/public/cpp", ] }
diff --git a/ios/chrome/browser/ntp_snippets/ios_chrome_content_suggestions_service_factory.cc b/ios/chrome/browser/ntp_snippets/ios_chrome_content_suggestions_service_factory.cc index c2467bc..9e1e0832 100644 --- a/ios/chrome/browser/ntp_snippets/ios_chrome_content_suggestions_service_factory.cc +++ b/ios/chrome/browser/ntp_snippets/ios_chrome_content_suggestions_service_factory.cc
@@ -15,6 +15,7 @@ #include "ios/chrome/browser/ntp_snippets/ios_chrome_content_suggestions_service_factory_util.h" #include "ios/chrome/browser/pref_names.h" #include "ios/chrome/browser/reading_list/reading_list_model_factory.h" +#include "ios/chrome/browser/signin/identity_manager_factory.h" #include "ios/chrome/browser/signin/oauth2_token_service_factory.h" #include "ios/chrome/browser/signin/signin_manager_factory.h" @@ -46,6 +47,7 @@ : BrowserStateKeyedServiceFactory( "ContentSuggestionsService", BrowserStateDependencyManager::GetInstance()) { + DependsOn(IdentityManagerFactory::GetInstance()); DependsOn(ios::HistoryServiceFactory::GetInstance()); DependsOn(IOSChromeLargeIconServiceFactory::GetInstance()); DependsOn(OAuth2TokenServiceFactory::GetInstance());
diff --git a/ios/chrome/browser/ntp_snippets/ios_chrome_content_suggestions_service_factory_util.cc b/ios/chrome/browser/ntp_snippets/ios_chrome_content_suggestions_service_factory_util.cc index 04b2566..308b861 100644 --- a/ios/chrome/browser/ntp_snippets/ios_chrome_content_suggestions_service_factory_util.cc +++ b/ios/chrome/browser/ntp_snippets/ios_chrome_content_suggestions_service_factory_util.cc
@@ -44,7 +44,7 @@ #include "ios/chrome/browser/history/history_service_factory.h" #include "ios/chrome/browser/pref_names.h" #include "ios/chrome/browser/reading_list/reading_list_model_factory.h" -#include "ios/chrome/browser/signin/oauth2_token_service_factory.h" +#include "ios/chrome/browser/signin/identity_manager_factory.h" #include "ios/chrome/browser/signin/signin_manager_factory.h" #include "ios/chrome/common/channel_info.h" #include "ios/web/public/browser_state.h" @@ -160,9 +160,8 @@ PrefService* prefs = chrome_browser_state->GetPrefs(); SigninManager* signin_manager = ios::SigninManagerFactory::GetForBrowserState(chrome_browser_state); - - OAuth2TokenService* token_service = - OAuth2TokenServiceFactory::GetForBrowserState(chrome_browser_state); + identity::IdentityManager* identity_manager = + IdentityManagerFactory::GetForBrowserState(chrome_browser_state); scoped_refptr<net::URLRequestContextGetter> request_context = browser_state->GetRequestContext(); base::FilePath database_dir( @@ -177,7 +176,7 @@ : google_apis::GetNonStableAPIKey(); } auto suggestions_fetcher = std::make_unique<RemoteSuggestionsFetcherImpl>( - signin_manager, token_service, request_context, prefs, nullptr, + identity_manager, request_context, prefs, nullptr, base::BindRepeating(&ParseJson), GetFetchEndpoint(GetChannel()), api_key, service->user_classifier());
diff --git a/ios/chrome/browser/passwords/password_controller.mm b/ios/chrome/browser/passwords/password_controller.mm index 11a2036..d9047e0 100644 --- a/ios/chrome/browser/passwords/password_controller.mm +++ b/ios/chrome/browser/passwords/password_controller.mm
@@ -348,11 +348,6 @@ return self; } -- (instancetype)init { - NOTREACHED(); - return nil; -} - - (void)dealloc { [self detach];
diff --git a/ios/chrome/browser/signin/about_signin_internals_factory.cc b/ios/chrome/browser/signin/about_signin_internals_factory.cc index 3e2cc4b..5b87fb3 100644 --- a/ios/chrome/browser/signin/about_signin_internals_factory.cc +++ b/ios/chrome/browser/signin/about_signin_internals_factory.cc
@@ -9,6 +9,7 @@ #include "base/memory/singleton.h" #include "components/keyed_service/ios/browser_state_dependency_manager.h" #include "components/signin/core/browser/about_signin_internals.h" +#include "components/signin/core/browser/profile_management_switches.h" #include "ios/chrome/browser/browser_state/chrome_browser_state.h" #include "ios/chrome/browser/signin/account_tracker_service_factory.h" #include "ios/chrome/browser/signin/gaia_cookie_manager_service_factory.h" @@ -55,8 +56,8 @@ AccountTrackerServiceFactory::GetForBrowserState(chrome_browser_state), SigninManagerFactory::GetForBrowserState(chrome_browser_state), SigninErrorControllerFactory::GetForBrowserState(chrome_browser_state), - GaiaCookieManagerServiceFactory::GetForBrowserState( - chrome_browser_state))); + GaiaCookieManagerServiceFactory::GetForBrowserState(chrome_browser_state), + signin::AccountConsistencyMethod::kMirror)); service->Initialize( SigninClientFactory::GetForBrowserState(chrome_browser_state)); return service;
diff --git a/ios/chrome/browser/signin/signin_manager_factory.cc b/ios/chrome/browser/signin/signin_manager_factory.cc index 3388ea2..e5ff45d9 100644 --- a/ios/chrome/browser/signin/signin_manager_factory.cc +++ b/ios/chrome/browser/signin/signin_manager_factory.cc
@@ -11,6 +11,7 @@ #include "components/keyed_service/ios/browser_state_dependency_manager.h" #include "components/pref_registry/pref_registry_syncable.h" #include "components/prefs/pref_registry_simple.h" +#include "components/signin/core/browser/profile_management_switches.h" #include "components/signin/core/browser/signin_manager.h" #include "components/signin/core/browser/signin_pref_names.h" #include "ios/chrome/browser/application_context.h" @@ -93,7 +94,8 @@ ios::GaiaCookieManagerServiceFactory::GetForBrowserState( chrome_browser_state), ios::SigninErrorControllerFactory::GetForBrowserState( - chrome_browser_state))); + chrome_browser_state), + signin::AccountConsistencyMethod::kMirror)); service->Initialize(GetApplicationContext()->GetLocalState()); for (auto& observer : observer_list_) observer.SigninManagerCreated(service.get());
diff --git a/ios/chrome/browser/tabs/tab_model.mm b/ios/chrome/browser/tabs/tab_model.mm index 221a4e2..747aee17 100644 --- a/ios/chrome/browser/tabs/tab_model.mm +++ b/ios/chrome/browser/tabs/tab_model.mm
@@ -435,11 +435,6 @@ return self; } -- (instancetype)init { - NOTREACHED(); - return nil; -} - - (BOOL)restoreSessionWindow:(SessionWindowIOS*)window { return [self restoreSessionWindow:window persistState:YES]; }
diff --git a/ios/chrome/browser/ui/activity_services/chrome_activity_item_source.mm b/ios/chrome/browser/ui/activity_services/chrome_activity_item_source.mm index 85e4f55..42468f4 100644 --- a/ios/chrome/browser/ui/activity_services/chrome_activity_item_source.mm +++ b/ios/chrome/browser/ui/activity_services/chrome_activity_item_source.mm
@@ -25,11 +25,6 @@ @implementation UIActivityImageSource -- (instancetype)init { - NOTREACHED(); - return nil; -} - - (instancetype)initWithImage:(UIImage*)image { DCHECK(image); self = [super init]; @@ -72,11 +67,6 @@ @synthesize shareURL = _shareURL; @synthesize passwordManagerURL = _passwordManagerURL; -- (instancetype)init { - NOTREACHED(); - return nil; -} - - (instancetype)initWithShareURL:(NSURL*)shareURL passwordManagerURL:(NSURL*)passwordManagerURL subject:(NSString*)subject
diff --git a/ios/chrome/browser/ui/activity_services/share_to_data.mm b/ios/chrome/browser/ui/activity_services/share_to_data.mm index 3ddf9097..fe6a29b 100644 --- a/ios/chrome/browser/ui/activity_services/share_to_data.mm +++ b/ios/chrome/browser/ui/activity_services/share_to_data.mm
@@ -45,11 +45,6 @@ @synthesize isOriginalTitle = isOriginalTitle_; @synthesize isPagePrintable = isPagePrintable_; -- (id)init { - NOTREACHED(); - return nil; -} - - (id)initWithShareURL:(const GURL&)shareURL passwordManagerURL:(const GURL&)passwordManagerURL title:(NSString*)title
diff --git a/ios/chrome/browser/ui/authentication/chrome_signin_view_controller.mm b/ios/chrome/browser/ui/authentication/chrome_signin_view_controller.mm index a22a790..9124e8e 100644 --- a/ios/chrome/browser/ui/authentication/chrome_signin_view_controller.mm +++ b/ios/chrome/browser/ui/authentication/chrome_signin_view_controller.mm
@@ -840,10 +840,10 @@ } - (void)layoutButtons:(const AuthenticationViewConstants&)constants { - [_primaryButton titleLabel].font = + UIFont* font = [[MDCTypography fontLoader] mediumFontOfSize:constants.SecondaryFontSize]; - [_secondaryButton titleLabel].font = - [[MDCTypography fontLoader] mediumFontOfSize:constants.SecondaryFontSize]; + [_primaryButton setTitleFont:font forState:UIControlStateNormal]; + [_secondaryButton setTitleFont:font forState:UIControlStateNormal]; LayoutRect primaryButtonLayout = LayoutRectZero; primaryButtonLayout.boundingWidth = CGRectGetWidth(self.view.bounds);
diff --git a/ios/chrome/browser/ui/bookmarks/undo_manager_wrapper.mm b/ios/chrome/browser/ui/bookmarks/undo_manager_wrapper.mm index e99489d..6ef830ba 100644 --- a/ios/chrome/browser/ui/bookmarks/undo_manager_wrapper.mm +++ b/ios/chrome/browser/ui/bookmarks/undo_manager_wrapper.mm
@@ -27,11 +27,6 @@ @synthesize hasUndoManagerChanged = _hasUndoManagerChanged; @synthesize undoManager = _undoManager; -- (id)init { - NOTREACHED(); - return nil; -} - - (instancetype)initWithBrowserState:(ios::ChromeBrowserState*)browserState { self = [super init]; if (self) {
diff --git a/ios/chrome/browser/ui/browser_view_controller.mm b/ios/chrome/browser/ui/browser_view_controller.mm index 220cd062..9961578 100644 --- a/ios/chrome/browser/ui/browser_view_controller.mm +++ b/ios/chrome/browser/ui/browser_view_controller.mm
@@ -60,6 +60,7 @@ #include "ios/chrome/browser/browser_state/chrome_browser_state.h" #include "ios/chrome/browser/chrome_url_constants.h" #include "ios/chrome/browser/chrome_url_util.h" +#import "ios/chrome/browser/download/download_manager_tab_helper.h" #import "ios/chrome/browser/download/pass_kit_tab_helper.h" #include "ios/chrome/browser/experimental_flags.h" #import "ios/chrome/browser/favicon/favicon_loader.h" @@ -139,6 +140,7 @@ #import "ios/chrome/browser/ui/context_menu/context_menu_coordinator.h" #import "ios/chrome/browser/ui/dialogs/dialog_presenter.h" #import "ios/chrome/browser/ui/dialogs/java_script_dialog_presenter_impl.h" +#import "ios/chrome/browser/ui/download/download_manager_coordinator.h" #import "ios/chrome/browser/ui/download/legacy_download_manager_controller.h" #import "ios/chrome/browser/ui/download/pass_kit_coordinator.h" #import "ios/chrome/browser/ui/elements/activity_overlay_coordinator.h" @@ -149,6 +151,7 @@ #import "ios/chrome/browser/ui/fullscreen/fullscreen_controller.h" #import "ios/chrome/browser/ui/fullscreen/fullscreen_controller_factory.h" #import "ios/chrome/browser/ui/fullscreen/fullscreen_features.h" +#import "ios/chrome/browser/ui/fullscreen/fullscreen_foreground_animator.h" #import "ios/chrome/browser/ui/fullscreen/fullscreen_scroll_end_animator.h" #import "ios/chrome/browser/ui/fullscreen/fullscreen_scroll_to_top_animator.h" #import "ios/chrome/browser/ui/fullscreen/fullscreen_ui_element.h" @@ -599,6 +602,9 @@ // Coordinator for the External Search UI. ExternalSearchCoordinator* _externalSearchCoordinator; + // Coordinator for the Download Manager UI. + DownloadManagerCoordinator* _downloadManagerCoordinator; + // Coordinator for the language selection UI. LanguageSelectionCoordinator* _languageSelectionCoordinator; @@ -986,6 +992,11 @@ _snackbarCoordinator.dispatcher = _dispatcher; [_snackbarCoordinator start]; + _downloadManagerCoordinator = + [[DownloadManagerCoordinator alloc] initWithBaseViewController:self]; + _downloadManagerCoordinator.presenter = + [[VerticalAnimationContainer alloc] init]; + _languageSelectionCoordinator = [[LanguageSelectionCoordinator alloc] initWithBaseViewController:self]; _languageSelectionCoordinator.presenter = @@ -2927,6 +2938,8 @@ AppLauncherTabHelper::CreateForWebState( tab.webState, [[ExternalAppsLaunchPolicyDecider alloc] init], _appLauncherCoordinator); + DownloadManagerTabHelper::CreateForWebState(tab.webState, + _downloadManagerCoordinator); // The language detection helper accepts a callback from the translate // client, so must be created after it. @@ -3996,13 +4009,26 @@ }]; } +- (void)showToolbarForForgroundWithAnimator: + (FullscreenForegroundAnimator*)animator { + CGFloat finalProgress = animator.finalProgress; + [animator addAnimations:^{ + [self updateForFullscreenProgress:finalProgress]; + }]; +} + #pragma mark - FullscreenUIElement helpers // Translates the header views up and down according to |progress|, where a // progress of 1.0 fully shows the headers and a progress of 0.0 fully hides // them. - (void)updateHeadersForFullscreenProgress:(CGFloat)progress { - CGFloat offset = AlignValueToPixel((1.0 - progress) * [self toolbarHeight]); + CGFloat toolbarHeightFullscreen = 0; + if (IsUIRefreshPhase1Enabled()) { + toolbarHeightFullscreen = kToolbarHeightFullscreen; + } + CGFloat offset = AlignValueToPixel( + (1.0 - progress) * ([self toolbarHeight] - toolbarHeightFullscreen)); [self setFramesForHeaders:[self headerViews] atOffset:offset]; } @@ -4847,6 +4873,8 @@ } [self updateVoiceSearchBarVisibilityAnimated:NO]; + self.currentWebState->GetWebViewProxy().scrollViewProxy.clipsToBounds = NO; + [_paymentRequestManager setActiveWebState:newTab.webState]; [self tabSelected:newTab notifyToolbar:YES];
diff --git a/ios/chrome/browser/ui/commands/generic_chrome_command.mm b/ios/chrome/browser/ui/commands/generic_chrome_command.mm index 23df36fd..5096e10 100644 --- a/ios/chrome/browser/ui/commands/generic_chrome_command.mm +++ b/ios/chrome/browser/ui/commands/generic_chrome_command.mm
@@ -29,11 +29,6 @@ return self; } -- (instancetype)init { - NOTREACHED(); - return nil; -} - - (void)executeOnMainWindow { UIWindow* mainWindow = [[UIApplication sharedApplication] keyWindow]; DCHECK(mainWindow);
diff --git a/ios/chrome/browser/ui/contextual_search/touch_to_search_permissions_mediator.mm b/ios/chrome/browser/ui/contextual_search/touch_to_search_permissions_mediator.mm index ff831bb..583b1e5 100644 --- a/ios/chrome/browser/ui/contextual_search/touch_to_search_permissions_mediator.mm +++ b/ios/chrome/browser/ui/contextual_search/touch_to_search_permissions_mediator.mm
@@ -100,11 +100,6 @@ return self; } -- (instancetype)init { - NOTREACHED(); - return nil; -} - - (void)dealloc { // Set audience to nil to stop observation. self.audience = nil;
diff --git a/ios/chrome/browser/ui/download/BUILD.gn b/ios/chrome/browser/ui/download/BUILD.gn index 26b3dc7..1109576 100644 --- a/ios/chrome/browser/ui/download/BUILD.gn +++ b/ios/chrome/browser/ui/download/BUILD.gn
@@ -5,6 +5,8 @@ source_set("download") { configs += [ "//build/config/compiler:enable_arc" ] sources = [ + "download_manager_coordinator.h", + "download_manager_coordinator.mm", "download_manager_view_controller.h", "download_manager_view_controller.mm", "legacy_download_manager_controller.h", @@ -30,6 +32,7 @@ "//ios/chrome/browser/ui/alert_coordinator", "//ios/chrome/browser/ui/colors", "//ios/chrome/browser/ui/coordinators:chrome_coordinators", + "//ios/chrome/browser/ui/presenters", "//ios/chrome/browser/ui/util", "//ios/chrome/browser/web:web_internal", "//ios/third_party/material_components_ios", @@ -47,6 +50,7 @@ configs += [ "//build/config/compiler:enable_arc" ] testonly = true sources = [ + "download_manager_coordinator_unittest.mm", "download_manager_view_controller_unittest.mm", "legacy_download_manager_controller_unittest.mm", "pass_kit_coordinator_unittest.mm",
diff --git a/ios/chrome/browser/ui/download/download_manager_coordinator.h b/ios/chrome/browser/ui/download/download_manager_coordinator.h new file mode 100644 index 0000000..699ddd8 --- /dev/null +++ b/ios/chrome/browser/ui/download/download_manager_coordinator.h
@@ -0,0 +1,33 @@ +// 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. + +#ifndef IOS_CHROME_BROWSER_UI_DOWNLOAD_DOWNLOAD_MANAGER_COORDINATOR_H_ +#define IOS_CHROME_BROWSER_UI_DOWNLOAD_DOWNLOAD_MANAGER_COORDINATOR_H_ + +#import "ios/chrome/browser/download/download_manager_tab_helper_delegate.h" +#import "ios/chrome/browser/ui/coordinators/chrome_coordinator.h" + +namespace web { +class DownloadTask; +} // namespace web + +@protocol ContainedPresenter; + +// Coordinates presentation of Download Manager UI. +@interface DownloadManagerCoordinator + : ChromeCoordinator<DownloadManagerTabHelperDelegate> + +// Presents the receiver's view controller. +@property(nonatomic) id<ContainedPresenter> presenter; + +// YES if presentation should be animated. Default is NO. +@property(nonatomic) BOOL animatesPresentation; + +// Download Manager supports only one download task at a time. Set to null when +// stop method is called. +@property(nonatomic) web::DownloadTask* downloadTask; + +@end + +#endif // IOS_CHROME_BROWSER_UI_DOWNLOAD_DOWNLOAD_MANAGER_COORDINATOR_H_
diff --git a/ios/chrome/browser/ui/download/download_manager_coordinator.mm b/ios/chrome/browser/ui/download/download_manager_coordinator.mm new file mode 100644 index 0000000..5e17936 --- /dev/null +++ b/ios/chrome/browser/ui/download/download_manager_coordinator.mm
@@ -0,0 +1,233 @@ +// 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. + +#import "ios/chrome/browser/ui/download/download_manager_coordinator.h" + +#include <memory> + +#include "base/files/file_util.h" +#import "base/logging.h" +#import "base/mac/bind_objc_block.h" +#include "base/strings/sys_string_conversions.h" +#include "base/strings/utf_string_conversions.h" +#include "base/task_scheduler/post_task.h" +#include "base/task_scheduler/task_traits.h" +#include "ios/chrome/browser/download/download_directory_util.h" +#import "ios/chrome/browser/download/download_manager_tab_helper.h" +#import "ios/chrome/browser/ui/download/download_manager_view_controller.h" +#import "ios/chrome/browser/ui/presenters/contained_presenter.h" +#import "ios/chrome/browser/ui/presenters/contained_presenter_delegate.h" +#import "ios/web/public/download/download_task.h" +#include "ios/web/public/web_thread.h" +#include "net/url_request/url_fetcher_response_writer.h" + +#if !defined(__has_feature) || !__has_feature(objc_arc) +#error "This file requires ARC support." +#endif + +using web::WebThread; + +@interface DownloadManagerCoordinator ()< + ContainedPresenterDelegate, + DownloadManagerViewControllerDelegate> { + // View controller for presenting Download Manager UI. + DownloadManagerViewController* _viewController; + // View controller for presenting "Open In.." dialog. + UIDocumentInteractionController* _openInController; +} +@end + +@implementation DownloadManagerCoordinator + +@synthesize presenter = _presenter; +@synthesize animatesPresentation = _animatesPresentation; +@synthesize downloadTask = _downloadTask; + +- (void)start { + DCHECK(self.presenter); + + _viewController = [[DownloadManagerViewController alloc] init]; + _viewController.delegate = self; + [self updateViewController]; + + self.presenter.baseViewController = self.baseViewController; + self.presenter.presentedViewController = _viewController; + self.presenter.delegate = self; + + [self.presenter prepareForPresentation]; + + [self.presenter presentAnimated:self.animatesPresentation]; +} + +- (void)stop { + if (_viewController) { + [self.presenter dismissAnimated:YES]; + _viewController = nil; + } + _downloadTask = nullptr; +} + +#pragma mark - DownloadManagerTabHelperDelegate + +- (void)downloadManagerTabHelper:(nonnull DownloadManagerTabHelper*)tabHelper + didCreateDownload:(nonnull web::DownloadTask*)download + webStateIsVisible:(BOOL)vebStateIsVisible { + if (!vebStateIsVisible) { + // Do nothing if a background Tab requested download UI presentation. + return; + } + + _downloadTask = download; + self.animatesPresentation = YES; + [self start]; +} + +- (void)downloadManagerTabHelper:(nonnull DownloadManagerTabHelper*)tabHelper + didUpdateDownload:(nonnull web::DownloadTask*)download { + if (_downloadTask != download) { + // Do nothing if download was updated for a background Tab. + return; + } + + [self updateViewController]; +} + +- (void)downloadManagerTabHelper:(nonnull DownloadManagerTabHelper*)tabHelper + didHideDownload:(nonnull web::DownloadTask*)download { + if (!_downloadTask) { + // TODO(crbug.com/805653): This callback can be called multiple times. + return; + } + + DCHECK_EQ(_downloadTask, download); + [self stop]; +} + +- (void)downloadManagerTabHelper:(nonnull DownloadManagerTabHelper*)tabHelper + didShowDownload:(nonnull web::DownloadTask*)download { + DCHECK_NE(_downloadTask, download); + _downloadTask = download; + self.animatesPresentation = NO; + [self start]; +} + +#pragma mark - ContainedPresenterDelegate + +- (void)containedPresenterDidDismiss:(id<ContainedPresenter>)presenter { + DCHECK(presenter == self.presenter); +} + +#pragma mark - DownloadManagerViewControllerDelegate + +- (void)downloadManagerViewControllerDidClose: + (DownloadManagerViewController*)controller { + _downloadTask->Cancel(); + [self stop]; +} + +- (void)downloadManagerViewControllerDidStartDownload: + (DownloadManagerViewController*)controller { + [self startDownload]; +} + +- (void)downloadManagerViewController:(DownloadManagerViewController*)controller + presentOpenInMenuWithLayoutGuide:(UILayoutGuide*)layoutGuide { + base::FilePath path = + _downloadTask->GetResponseWriter()->AsFileWriter()->file_path(); + NSURL* URL = [NSURL fileURLWithPath:base::SysUTF8ToNSString(path.value())]; + _openInController = + [UIDocumentInteractionController interactionControllerWithURL:URL]; + + BOOL menuShown = + [_openInController presentOpenInMenuFromRect:layoutGuide.layoutFrame + inView:layoutGuide.owningView + animated:YES]; + DCHECK(menuShown); +} + +#pragma mark - Private + +// Updates presented view controller with web::DownloadTask data. +- (void)updateViewController { + _viewController.state = [self downloadManagerState]; + _viewController.countOfBytesReceived = _downloadTask->GetReceivedBytes(); + _viewController.countOfBytesExpectedToReceive = + _downloadTask->GetTotalBytes(); + _viewController.fileName = + base::SysUTF16ToNSString(_downloadTask->GetSuggestedFilename()); +} + +// Returns DownloadManagerState for the current download task. +- (DownloadManagerState)downloadManagerState { + switch (_downloadTask->GetState()) { + case web::DownloadTask::State::kNotStarted: + return kDownloadManagerStateNotStarted; + case web::DownloadTask::State::kInProgress: + return kDownloadManagerStateInProgress; + case web::DownloadTask::State::kComplete: + return _downloadTask->GetErrorCode() ? kDownloadManagerStateFailed + : kDownloadManagerStateSuceeded; + case web::DownloadTask::State::kCancelled: + // Download Manager should dismiss the UI after download cancellation. + NOTREACHED(); + return kDownloadManagerStateNotStarted; + } +} + +// Asynchronously starts download operation. +- (void)startDownload { + base::FilePath downloadDir; + if (!GetDownloadsDirectory(&downloadDir)) { + [self didFailFileWriterCreation]; + return; + } + + // Download will start once writer is created by background task, however it + // OK to change view controller state now to preven further user interactions + // with "Start Download" button. + _viewController.state = kDownloadManagerStateInProgress; + + base::string16 suggestedFileName = _downloadTask->GetSuggestedFilename(); + __weak DownloadManagerCoordinator* weakSelf = self; + base::PostTaskWithTraits( + FROM_HERE, {base::MayBlock(), base::TaskPriority::USER_VISIBLE}, + base::BindBlockArc(^{ + if (!weakSelf) + return; + + if (!base::CreateDirectory(downloadDir)) { + WebThread::PostTask(WebThread::UI, FROM_HERE, base::BindBlockArc(^{ + [weakSelf didFailFileWriterCreation]; + })); + return; + } + + base::FilePath downloadFilePath = + downloadDir.Append(base::UTF16ToUTF8(suggestedFileName)); + auto taskRunner = base::CreateSequencedTaskRunnerWithTraits( + {base::MayBlock(), base::TaskPriority::BACKGROUND}); + __block auto writer = std::make_unique<net::URLFetcherFileWriter>( + taskRunner, downloadFilePath); + WebThread::PostTask(WebThread::UI, FROM_HERE, base::BindBlockArc(^{ + writer->Initialize(base::BindBlockArc(^(int error) { + DownloadManagerCoordinator* strongSelf = weakSelf; + if (!strongSelf) + return; + + if (!error) { + strongSelf.downloadTask->Start(std::move(writer)); + } else { + [strongSelf didFailFileWriterCreation]; + } + })); + })); + })); +} + +// Called when coordinator failed to create file writer. +- (void)didFailFileWriterCreation { + _viewController.state = kDownloadManagerStateFailed; +} + +@end
diff --git a/ios/chrome/browser/ui/download/download_manager_coordinator_unittest.mm b/ios/chrome/browser/ui/download/download_manager_coordinator_unittest.mm new file mode 100644 index 0000000..dfa2e21 --- /dev/null +++ b/ios/chrome/browser/ui/download/download_manager_coordinator_unittest.mm
@@ -0,0 +1,364 @@ +// 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. + +#import "ios/chrome/browser/ui/download/download_manager_coordinator.h" + +#import <UIKit/UIKit.h> + +#include "base/files/file_util.h" +#include "base/run_loop.h" +#include "base/strings/sys_string_conversions.h" +#include "ios/chrome/browser/download/download_directory_util.h" +#import "ios/chrome/browser/download/download_manager_tab_helper.h" +#import "ios/chrome/browser/ui/download/download_manager_view_controller.h" +#import "ios/chrome/test/fakes/fake_contained_presenter.h" +#import "ios/chrome/test/scoped_key_window.h" +#import "ios/testing/wait_util.h" +#import "ios/web/public/test/fakes/fake_download_task.h" +#import "ios/web/public/test/fakes/test_web_state.h" +#include "ios/web/public/test/test_web_thread_bundle.h" +#include "net/base/net_errors.h" +#include "net/url_request/url_fetcher_response_writer.h" +#include "testing/gtest_mac.h" +#include "testing/platform_test.h" + +#if !defined(__has_feature) || !__has_feature(objc_arc) +#error "This file requires ARC support." +#endif + +using testing::WaitUntilConditionOrTimeout; + +namespace { + +// Constants for configuring a fake download task. +const char kTestUrl[] = "https://chromium.test/download.txt"; +const char kTestMimeType[] = "text/html"; +const int64_t kTestTotalBytes = 10; +const int64_t kTestReceivedBytes = 0; +NSString* const kTestSuggestedFileName = @"important_file.zip"; + +// Creates a fake download task for testing. +std::unique_ptr<web::FakeDownloadTask> CreateTestTask() { + auto task = + std::make_unique<web::FakeDownloadTask>(GURL(kTestUrl), kTestMimeType); + task->SetTotalBytes(kTestTotalBytes); + task->SetReceivedBytes(kTestReceivedBytes); + task->SetSuggestedFilename(base::SysNSStringToUTF16(kTestSuggestedFileName)); + return task; +} + +// Substitutes real TabHelper for testing. +class StubTabHelper : public DownloadManagerTabHelper { + public: + StubTabHelper(web::WebState* web_state) + : DownloadManagerTabHelper(web_state, /*delegate=*/nullptr) {} + DISALLOW_COPY_AND_ASSIGN(StubTabHelper); +}; + +} // namespace + +// Test fixture for testing DownloadManagerCoordinator class. +class DownloadManagerCoordinatorTest : public PlatformTest { + protected: + DownloadManagerCoordinatorTest() + : presenter_([[FakeContainedPresenter alloc] init]), + base_view_controller_([[UIViewController alloc] init]), + tab_helper_(&web_state_), + coordinator_([[DownloadManagerCoordinator alloc] + initWithBaseViewController:base_view_controller_]) { + [scoped_key_window_.Get() setRootViewController:base_view_controller_]; + coordinator_.presenter = presenter_; + } + + FakeContainedPresenter* presenter_; + UIViewController* base_view_controller_; + ScopedKeyWindow scoped_key_window_; + web::TestWebState web_state_; + StubTabHelper tab_helper_; + DownloadManagerCoordinator* coordinator_; +}; + +// Tests starting the coordinator. Verifies that view controller is presented +// without animation (default configuration) and that +// DownloadManagerViewController is propertly configured and presented. +TEST_F(DownloadManagerCoordinatorTest, Start) { + auto task = CreateTestTask(); + coordinator_.downloadTask = task.get(); + [coordinator_ start]; + + // By default coordinator presents without animation. + EXPECT_FALSE(presenter_.lastPresentationWasAnimated); + + // Verify that presented view controller is DownloadManagerViewController. + EXPECT_EQ(1U, base_view_controller_.childViewControllers.count); + DownloadManagerViewController* viewController = + base_view_controller_.childViewControllers.firstObject; + ASSERT_EQ([DownloadManagerViewController class], [viewController class]); + + // Verify that DownloadManagerViewController configuration matches download + // task. + EXPECT_EQ(kDownloadManagerStateNotStarted, viewController.state); + EXPECT_EQ(kTestReceivedBytes, viewController.countOfBytesReceived); + EXPECT_EQ(kTestTotalBytes, viewController.countOfBytesExpectedToReceive); + EXPECT_NSEQ(kTestSuggestedFileName, viewController.fileName); +} + +// Tests stopping coordinator. Verifies that hiding web states dismisses the +// presented view controller and download task is reset to null (to prevent a +// stale raw pointer). +TEST_F(DownloadManagerCoordinatorTest, Stop) { + web::FakeDownloadTask task(GURL(kTestUrl), kTestMimeType); + coordinator_.downloadTask = &task; + [coordinator_ start]; + [coordinator_ stop]; + + // Verify that child view controller is removed and download task is set to + // null. + EXPECT_EQ(0U, base_view_controller_.childViewControllers.count); + EXPECT_FALSE(coordinator_.downloadTask); +} + +// Tests downloadManagerTabHelper:didCreateDownload:webStateIsVisible: callback +// for visible web state. Verifies that coordinator's properties are set up and +// that DownloadManagerViewController is properly configured and presented with +// animation. +TEST_F(DownloadManagerCoordinatorTest, DelegateCreatedDownload) { + auto task = CreateTestTask(); + [coordinator_ downloadManagerTabHelper:&tab_helper_ + didCreateDownload:task.get() + webStateIsVisible:YES]; + + // Verify that coordinator's properties are set up. + EXPECT_EQ(task.get(), coordinator_.downloadTask); + EXPECT_TRUE(coordinator_.animatesPresentation); + + // First presentation of Download Manager UI should be animated. + EXPECT_TRUE(presenter_.lastPresentationWasAnimated); + + // Verify that presented view controller is DownloadManagerViewController. + EXPECT_EQ(1U, base_view_controller_.childViewControllers.count); + DownloadManagerViewController* viewController = + base_view_controller_.childViewControllers.firstObject; + ASSERT_EQ([DownloadManagerViewController class], [viewController class]); + + // Verify that DownloadManagerViewController configuration matches download + // task. + EXPECT_EQ(kDownloadManagerStateNotStarted, viewController.state); + EXPECT_EQ(kTestReceivedBytes, viewController.countOfBytesReceived); + EXPECT_EQ(kTestTotalBytes, viewController.countOfBytesExpectedToReceive); + EXPECT_NSEQ(kTestSuggestedFileName, viewController.fileName); +} + +// Tests downloadManagerTabHelper:didCreateDownload:webStateIsVisible: callback +// for hidden web state. Verifies that coordinator ignores callback from +// a background tab. +TEST_F(DownloadManagerCoordinatorTest, + DelegateCreatedDownloadForHiddenWebState) { + auto task = CreateTestTask(); + [coordinator_ downloadManagerTabHelper:&tab_helper_ + didCreateDownload:task.get() + webStateIsVisible:NO]; + + // Background tab should not present Download Manager UI. + EXPECT_EQ(0U, base_view_controller_.childViewControllers.count); +} + +// Tests downloadManagerTabHelper:didUpdateDownload: callback for download task +// completion. Verifies that DownloadManagerViewController state is changed to +// kDownloadManagerStateSuceeded. +TEST_F(DownloadManagerCoordinatorTest, DelegateCompletedDownload) { + auto task = CreateTestTask(); + [coordinator_ downloadManagerTabHelper:&tab_helper_ + didCreateDownload:task.get() + webStateIsVisible:YES]; + task->SetDone(true); + [coordinator_ downloadManagerTabHelper:&tab_helper_ + didUpdateDownload:task.get()]; + + // Verify that DownloadManagerViewController state is set to suceeded. + EXPECT_EQ(1U, base_view_controller_.childViewControllers.count); + DownloadManagerViewController* viewController = + base_view_controller_.childViewControllers.firstObject; + ASSERT_EQ([DownloadManagerViewController class], [viewController class]); + EXPECT_EQ(kDownloadManagerStateSuceeded, viewController.state); +} + +// Tests downloadManagerTabHelper:didUpdateDownload: callback for download task +// failure. Verifies that DownloadManagerViewController state is changed to +// kDownloadManagerStateFailed. +TEST_F(DownloadManagerCoordinatorTest, DelegateFailedDownload) { + auto task = CreateTestTask(); + [coordinator_ downloadManagerTabHelper:&tab_helper_ + didCreateDownload:task.get() + webStateIsVisible:YES]; + task->SetErrorCode(net::ERR_INTERNET_DISCONNECTED); + task->SetDone(true); + [coordinator_ downloadManagerTabHelper:&tab_helper_ + didUpdateDownload:task.get()]; + + // Verify that DownloadManagerViewController state is set to failed. + EXPECT_EQ(1U, base_view_controller_.childViewControllers.count); + DownloadManagerViewController* viewController = + base_view_controller_.childViewControllers.firstObject; + ASSERT_EQ([DownloadManagerViewController class], [viewController class]); + EXPECT_EQ(kDownloadManagerStateFailed, viewController.state); +} + +// Tests downloadManagerTabHelper:didUpdateDownload: callback for download task +// progress. Verifies that DownloadManagerViewController state is changed to +// kDownloadManagerStateInProgress. +TEST_F(DownloadManagerCoordinatorTest, DelegateProgressedDownload) { + auto task = CreateTestTask(); + [coordinator_ downloadManagerTabHelper:&tab_helper_ + didCreateDownload:task.get() + webStateIsVisible:YES]; + task->Start(std::make_unique<net::URLFetcherStringWriter>()); + [coordinator_ downloadManagerTabHelper:&tab_helper_ + didUpdateDownload:task.get()]; + + // Verify that DownloadManagerViewController state is set to "in progress". + EXPECT_EQ(1U, base_view_controller_.childViewControllers.count); + DownloadManagerViewController* viewController = + base_view_controller_.childViewControllers.firstObject; + ASSERT_EQ([DownloadManagerViewController class], [viewController class]); + EXPECT_EQ(kDownloadManagerStateInProgress, viewController.state); +} + +// Tests downloadManagerTabHelper:didUpdateDownload: callback for background +// download task when web state is not visible. Verifies that coordinator +// ignores callback from a background tab. +TEST_F(DownloadManagerCoordinatorTest, DelegateCompletedBackgroundDownload) { + auto task = CreateTestTask(); + [coordinator_ downloadManagerTabHelper:&tab_helper_ + didCreateDownload:task.get() + webStateIsVisible:YES]; + auto background_task = CreateTestTask(); + background_task->SetDone(true); + [coordinator_ downloadManagerTabHelper:&tab_helper_ + didUpdateDownload:background_task.get()]; + + // Background tab download progress should not affect presented Download + // Manager UI. + EXPECT_EQ(1U, base_view_controller_.childViewControllers.count); + DownloadManagerViewController* viewController = + base_view_controller_.childViewControllers.firstObject; + ASSERT_EQ([DownloadManagerViewController class], [viewController class]); + EXPECT_EQ(kDownloadManagerStateNotStarted, viewController.state); +} + +// Tests downloadManagerTabHelper:didHideDownload: callback. Verifies that +// hiding web states dismisses the presented view controller and download task +// is reset to null (to prevent a stale raw pointer). +TEST_F(DownloadManagerCoordinatorTest, DelegateHideDownload) { + auto task = CreateTestTask(); + [coordinator_ downloadManagerTabHelper:&tab_helper_ + didCreateDownload:task.get() + webStateIsVisible:YES]; + [coordinator_ downloadManagerTabHelper:&tab_helper_ + didHideDownload:task.get()]; + + // Verify that child view controller is removed and download task is set to + // null. + EXPECT_EQ(0U, base_view_controller_.childViewControllers.count); + EXPECT_FALSE(coordinator_.downloadTask); +} + +// Tests downloadManagerTabHelper:didShowDownload: callback. Verifies that +// showing web state presents download manager UI for that web state. +TEST_F(DownloadManagerCoordinatorTest, DelegateShowDownload) { + auto task = CreateTestTask(); + [coordinator_ downloadManagerTabHelper:&tab_helper_ + didShowDownload:task.get()]; + + // Only first presentation is animated. Switching between tab should create + // the impression that UI was never dismissed. + EXPECT_FALSE(presenter_.lastPresentationWasAnimated); + + // Verify that presented view controller is DownloadManagerViewController. + EXPECT_EQ(1U, base_view_controller_.childViewControllers.count); + DownloadManagerViewController* viewController = + base_view_controller_.childViewControllers.firstObject; + ASSERT_EQ([DownloadManagerViewController class], [viewController class]); + + // Verify that DownloadManagerViewController configuration matches download + // task for shown web state. + EXPECT_EQ(kDownloadManagerStateNotStarted, viewController.state); + EXPECT_EQ(kTestReceivedBytes, viewController.countOfBytesReceived); + EXPECT_EQ(kTestTotalBytes, viewController.countOfBytesExpectedToReceive); + EXPECT_NSEQ(kTestSuggestedFileName, viewController.fileName); +} + +// Tests closing view controller. Coordinator should be stopped and task +// cancelled. +TEST_F(DownloadManagerCoordinatorTest, Close) { + web::FakeDownloadTask task(GURL(kTestUrl), kTestMimeType); + coordinator_.downloadTask = &task; + [coordinator_ start]; + + EXPECT_EQ(1U, base_view_controller_.childViewControllers.count); + DownloadManagerViewController* viewController = + base_view_controller_.childViewControllers.firstObject; + ASSERT_EQ([DownloadManagerViewController class], [viewController class]); + [viewController.delegate + downloadManagerViewControllerDidClose:viewController]; + + // Verify that child view controller is removed, download task is set to null + // and download task is cancelled. + EXPECT_EQ(0U, base_view_controller_.childViewControllers.count); + EXPECT_FALSE(coordinator_.downloadTask); + EXPECT_EQ(web::DownloadTask::State::kCancelled, task.GetState()); +} + +// Tests starting the download. Verifies that download task is started and its +// file writer is configured to write into download directory. +TEST_F(DownloadManagerCoordinatorTest, StartDownload) { + web::TestWebThreadBundle thread_bundle; + + web::FakeDownloadTask task(GURL(kTestUrl), kTestMimeType); + task.SetSuggestedFilename(base::SysNSStringToUTF16(kTestSuggestedFileName)); + web::DownloadTask* task_ptr = &task; + coordinator_.downloadTask = &task; + [coordinator_ start]; + + DownloadManagerViewController* viewController = + base_view_controller_.childViewControllers.firstObject; + ASSERT_EQ([DownloadManagerViewController class], [viewController class]); + [viewController.delegate + downloadManagerViewControllerDidStartDownload:viewController]; + + // Starting download is async for model and sync for view controller. + EXPECT_EQ(kDownloadManagerStateInProgress, viewController.state); + ASSERT_TRUE(WaitUntilConditionOrTimeout(testing::kWaitForDownloadTimeout, ^{ + base::RunLoop().RunUntilIdle(); + return task_ptr->GetState() == web::DownloadTask::State::kInProgress; + })); + + // Download file should be located in download directory. + base::FilePath file = task.GetResponseWriter()->AsFileWriter()->file_path(); + base::FilePath download_dir; + ASSERT_TRUE(GetDownloadsDirectory(&download_dir)); + EXPECT_TRUE(download_dir.IsParent(file)); +} + +// Tests starting and failing the download. Simulates download failure from +// inability to create a file writer. +TEST_F(DownloadManagerCoordinatorTest, StartDownloadFailure) { + web::TestWebThreadBundle thread_bundle; + web::FakeDownloadTask task(GURL(kTestUrl), kTestMimeType); + // Writer can not be created without file name, which will fail the download. + coordinator_.downloadTask = &task; + [coordinator_ start]; + + DownloadManagerViewController* viewController = + base_view_controller_.childViewControllers.firstObject; + ASSERT_EQ([DownloadManagerViewController class], [viewController class]); + [viewController.delegate + downloadManagerViewControllerDidStartDownload:viewController]; + + // Writer is created by a background task, so wait for failure. + ASSERT_TRUE(WaitUntilConditionOrTimeout(testing::kWaitForDownloadTimeout, ^{ + base::RunLoop().RunUntilIdle(); + return viewController.state == kDownloadManagerStateFailed; + })); +}
diff --git a/ios/chrome/browser/ui/first_run/welcome_to_chrome_view.mm b/ios/chrome/browser/ui/first_run/welcome_to_chrome_view.mm index 02bb8d0..8502475 100644 --- a/ios/chrome/browser/ui/first_run/welcome_to_chrome_view.mm +++ b/ios/chrome/browser/ui/first_run/welcome_to_chrome_view.mm
@@ -555,8 +555,9 @@ } - (void)configureOKButton { - self.OKButton.titleLabel.font = [[MDCTypography fontLoader] + UIFont* font = [[MDCTypography fontLoader] mediumFontOfSize:kOKButtonTitleLabelFontSize[self.cr_widthSizeClass]]; + [self.OKButton setTitleFont:font forState:UIControlStateNormal]; CGSize size = [self.OKButton sizeThatFits:CGSizeMake(CGFLOAT_MAX, kOKButtonHeight[self.cr_widthSizeClass])];
diff --git a/ios/chrome/browser/ui/fullscreen/BUILD.gn b/ios/chrome/browser/ui/fullscreen/BUILD.gn index dfd0519..50e470c 100644 --- a/ios/chrome/browser/ui/fullscreen/BUILD.gn +++ b/ios/chrome/browser/ui/fullscreen/BUILD.gn
@@ -67,6 +67,8 @@ "fullscreen_model.h", "fullscreen_model.mm", "fullscreen_model_observer.h", + "fullscreen_system_notification_observer.h", + "fullscreen_system_notification_observer.mm", "fullscreen_ui_updater.mm", "fullscreen_web_state_list_observer.h", "fullscreen_web_state_list_observer.mm", @@ -76,8 +78,6 @@ "fullscreen_web_view_proxy_observer.mm", "fullscreen_web_view_scroll_view_replacement_util.h", "fullscreen_web_view_scroll_view_replacement_util.mm", - "system_notification_fullscreen_disabler.h", - "system_notification_fullscreen_disabler.mm", ] configs += [ "//build/config/compiler:enable_arc" ] @@ -100,6 +100,8 @@ sources = [ "fullscreen_animator.h", "fullscreen_animator.mm", + "fullscreen_foreground_animator.h", + "fullscreen_foreground_animator.mm", "fullscreen_scroll_end_animator.h", "fullscreen_scroll_end_animator.mm", "fullscreen_scroll_to_top_animator.h",
diff --git a/ios/chrome/browser/ui/fullscreen/fullscreen_controller_impl.h b/ios/chrome/browser/ui/fullscreen/fullscreen_controller_impl.h index a29650d..3f4360e5 100644 --- a/ios/chrome/browser/ui/fullscreen/fullscreen_controller_impl.h +++ b/ios/chrome/browser/ui/fullscreen/fullscreen_controller_impl.h
@@ -13,7 +13,7 @@ class FullscreenMediator; class FullscreenModel; class FullscreenWebStateListObserver; -@class SystemNotificationFullscreenDisabler; +@class FullscreenSystemNotificationObserver; // Implementation of FullscreenController. class FullscreenControllerImpl : public FullscreenController { @@ -41,12 +41,12 @@ WebStateList* web_state_list_ = nullptr; // The model used to calculate fullscreen state. std::unique_ptr<FullscreenModel> model_; - // The bridge used to forward brodcasted UI to |model_|. - __strong ChromeBroadcastOberverBridge* bridge_ = nil; - // A helper object that disables fullscreen for system notifications. - __strong SystemNotificationFullscreenDisabler* disabler_ = nil; // Object that manages sending signals to FullscreenControllerImplObservers. std::unique_ptr<FullscreenMediator> mediator_; + // The bridge used to forward brodcasted UI to |model_|. + __strong ChromeBroadcastOberverBridge* bridge_ = nil; + // A helper object that listens for system notifications. + __strong FullscreenSystemNotificationObserver* notification_observer_ = nil; // A WebStateListObserver that updates |model_| for WebStateList changes. std::unique_ptr<FullscreenWebStateListObserver> web_state_list_observer_;
diff --git a/ios/chrome/browser/ui/fullscreen/fullscreen_controller_impl.mm b/ios/chrome/browser/ui/fullscreen/fullscreen_controller_impl.mm index d31ef26..b169878 100644 --- a/ios/chrome/browser/ui/fullscreen/fullscreen_controller_impl.mm +++ b/ios/chrome/browser/ui/fullscreen/fullscreen_controller_impl.mm
@@ -8,8 +8,8 @@ #import "ios/chrome/browser/ui/broadcaster/chrome_broadcaster.h" #import "ios/chrome/browser/ui/fullscreen/fullscreen_mediator.h" #import "ios/chrome/browser/ui/fullscreen/fullscreen_model.h" +#import "ios/chrome/browser/ui/fullscreen/fullscreen_system_notification_observer.h" #import "ios/chrome/browser/ui/fullscreen/fullscreen_web_state_list_observer.h" -#import "ios/chrome/browser/ui/fullscreen/system_notification_fullscreen_disabler.h" #if !defined(__has_feature) || !__has_feature(objc_arc) #error "This file requires ARC support." @@ -19,11 +19,12 @@ : FullscreenController(), broadcaster_([[ChromeBroadcaster alloc] init]), model_(std::make_unique<FullscreenModel>()), + mediator_(std::make_unique<FullscreenMediator>(this, model_.get())), bridge_( [[ChromeBroadcastOberverBridge alloc] initWithObserver:model_.get()]), - disabler_([[SystemNotificationFullscreenDisabler alloc] - initWithController:this]), - mediator_(std::make_unique<FullscreenMediator>(this, model_.get())) { + notification_observer_([[FullscreenSystemNotificationObserver alloc] + initWithController:this + mediator:mediator_.get()]) { DCHECK(broadcaster_); [broadcaster_ addObserver:bridge_ forSelector:@selector(broadcastContentScrollOffset:)]; @@ -76,7 +77,7 @@ void FullscreenControllerImpl::Shutdown() { mediator_->Disconnect(); - [disabler_ disconnect]; + [notification_observer_ disconnect]; if (web_state_list_observer_) web_state_list_observer_->Disconnect(); [broadcaster_ removeObserver:bridge_
diff --git a/ios/chrome/browser/ui/fullscreen/fullscreen_controller_observer.h b/ios/chrome/browser/ui/fullscreen/fullscreen_controller_observer.h index 91c6ce3..01d5b6c 100644 --- a/ios/chrome/browser/ui/fullscreen/fullscreen_controller_observer.h +++ b/ios/chrome/browser/ui/fullscreen/fullscreen_controller_observer.h
@@ -10,6 +10,7 @@ #include "base/macros.h" class FullscreenController; +@class FullscreenForegroundAnimator; @class FullscreenScrollEndAnimator; @class FullscreenScrollToTopAnimator; @@ -43,6 +44,13 @@ FullscreenController* controller, FullscreenScrollToTopAnimator* animator) {} + // Invoked when the application is about to enter the foreground. + // FullscreenUIElements are expected to add animations to |animator| to show + // the toolbar. + virtual void FullscreenWillEnterForeground( + FullscreenController* controller, + FullscreenForegroundAnimator* animator) {} + private: DISALLOW_COPY_AND_ASSIGN(FullscreenControllerObserver); };
diff --git a/ios/chrome/browser/ui/fullscreen/fullscreen_foreground_animator.h b/ios/chrome/browser/ui/fullscreen/fullscreen_foreground_animator.h new file mode 100644 index 0000000..d723df7 --- /dev/null +++ b/ios/chrome/browser/ui/fullscreen/fullscreen_foreground_animator.h
@@ -0,0 +1,22 @@ +// 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. + +#ifndef IOS_CHROME_BROWSER_UI_FULLSCREEN_FULLSCREEN_FOREGROUND_ANIMATOR_H_ +#define IOS_CHROME_BROWSER_UI_FULLSCREEN_FULLSCREEN_FOREGROUND_ANIMATOR_H_ + +#import "ios/chrome/browser/ui/fullscreen/fullscreen_animator.h" + +// When the application is foregrounded, the toolbar is expected to animate into +// view. This animator is used by FullscreenController to coordinate this +// animation. +@interface FullscreenForegroundAnimator : FullscreenAnimator + +- (instancetype)initWithStartProgress:(CGFloat)startProgress + NS_DESIGNATED_INITIALIZER; +- (instancetype)initWithStartProgress:(CGFloat)startProgress + duration:(NSTimeInterval)duration NS_UNAVAILABLE; + +@end + +#endif // IOS_CHROME_BROWSER_UI_FULLSCREEN_FULLSCREEN_FOREGROUND_ANIMATOR_H_
diff --git a/ios/chrome/browser/ui/fullscreen/fullscreen_foreground_animator.mm b/ios/chrome/browser/ui/fullscreen/fullscreen_foreground_animator.mm new file mode 100644 index 0000000..86137e86 --- /dev/null +++ b/ios/chrome/browser/ui/fullscreen/fullscreen_foreground_animator.mm
@@ -0,0 +1,25 @@ +// 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. + +#import "ios/chrome/browser/ui/fullscreen/fullscreen_foreground_animator.h" + +#import "ios/chrome/common/material_timing.h" + +#if !defined(__has_feature) || !__has_feature(objc_arc) +#error "This file requires ARC support." +#endif + +@implementation FullscreenForegroundAnimator +@synthesize finalProgress = _finalProgress; + +- (instancetype)initWithStartProgress:(CGFloat)startProgress { + if (self = [super initWithStartProgress:startProgress + duration:ios::material::kDuration1]) { + // The toolbar should be shown when the app is foregrounded. + _finalProgress = 1.0; + } + return self; +} + +@end
diff --git a/ios/chrome/browser/ui/fullscreen/fullscreen_mediator.h b/ios/chrome/browser/ui/fullscreen/fullscreen_mediator.h index d946228..6961fe0 100644 --- a/ios/chrome/browser/ui/fullscreen/fullscreen_mediator.h +++ b/ios/chrome/browser/ui/fullscreen/fullscreen_mediator.h
@@ -15,6 +15,7 @@ @class FullscreenAnimator; class FullscreenController; class FullscreenControllerObserver; +@class FullscreenForegroundAnimator; @class FullscreenScrollEndAnimator; @class FullscreenScrollToTopAnimator; @@ -36,6 +37,9 @@ // Instructs the mediator that a scroll-to-top animation has been triggered. void ScrollToTop(); + // Instructs the mediator that the app will be foregrounded. + void WillEnterForeground(); + // Instructs the mediator to stop observing its model. void Disconnect(); @@ -71,6 +75,8 @@ __strong FullscreenScrollEndAnimator* scroll_end_animator_ = nil; // The scroll to top animator passed to observers. __strong FullscreenScrollToTopAnimator* scroll_to_top_animator_ = nil; + // The toolbar reveal animator for foreground events. + __strong FullscreenForegroundAnimator* foreground_animator_ = nil; // The FullscreenControllerObservers that need to get notified of model // changes. base::ObserverList<FullscreenControllerObserver> observers_;
diff --git a/ios/chrome/browser/ui/fullscreen/fullscreen_mediator.mm b/ios/chrome/browser/ui/fullscreen/fullscreen_mediator.mm index 8ce99e8..a4d1788 100644 --- a/ios/chrome/browser/ui/fullscreen/fullscreen_mediator.mm +++ b/ios/chrome/browser/ui/fullscreen/fullscreen_mediator.mm
@@ -8,6 +8,7 @@ #include "base/memory/ptr_util.h" #import "ios/chrome/browser/ui/fullscreen/fullscreen_animator.h" #import "ios/chrome/browser/ui/fullscreen/fullscreen_controller_observer.h" +#import "ios/chrome/browser/ui/fullscreen/fullscreen_foreground_animator.h" #import "ios/chrome/browser/ui/fullscreen/fullscreen_model.h" #import "ios/chrome/browser/ui/fullscreen/fullscreen_scroll_end_animator.h" #import "ios/chrome/browser/ui/fullscreen/fullscreen_scroll_to_top_animator.h" @@ -43,6 +44,18 @@ [scroll_to_top_animator_ startAnimation]; } +void FullscreenMediator::WillEnterForeground() { + DCHECK(!foreground_animator_); + CGFloat progress = model_->progress(); + foreground_animator_ = + [[FullscreenForegroundAnimator alloc] initWithStartProgress:progress]; + SetUpAnimator(&foreground_animator_); + for (auto& observer : observers_) { + observer.FullscreenWillEnterForeground(controller_, foreground_animator_); + } + [foreground_animator_ startAnimation]; +} + void FullscreenMediator::Disconnect() { [scroll_end_animator_ stopAnimation:YES]; scroll_end_animator_ = nil; @@ -101,7 +114,8 @@ DCHECK(animator); DCHECK(*animator); DCHECK(*animator == scroll_end_animator_ || - *animator == scroll_to_top_animator_); + *animator == scroll_to_top_animator_ || + *animator == foreground_animator_); [*animator addCompletion:^(UIViewAnimatingPosition finalPosition) { DCHECK_EQ(finalPosition, UIViewAnimatingPositionEnd); model_->AnimationEndedWithProgress( @@ -111,16 +125,22 @@ } void FullscreenMediator::StopAnimating(bool update_model) { - if (!scroll_end_animator_ && !scroll_to_top_animator_) + if (!scroll_end_animator_ && !scroll_to_top_animator_ && + !foreground_animator_) { return; + } // At most one animator should be non-nil. - DCHECK(!!scroll_end_animator_ != !!scroll_to_top_animator_); + DCHECK_EQ((scroll_end_animator_ ? 1 : 0) + (scroll_to_top_animator_ ? 1 : 0) + + (foreground_animator_ ? 1 : 0), + 1); if (scroll_end_animator_) StopAnimator(&scroll_end_animator_, update_model); if (scroll_to_top_animator_) StopAnimator(&scroll_to_top_animator_, update_model); + if (foreground_animator_) + StopAnimator(&foreground_animator_, update_model); } void FullscreenMediator::StopAnimator(__strong FullscreenAnimator** animator, @@ -128,7 +148,8 @@ DCHECK(animator); DCHECK(*animator); DCHECK(*animator == scroll_end_animator_ || - *animator == scroll_to_top_animator_); + *animator == scroll_to_top_animator_ || + *animator == foreground_animator_); DCHECK_EQ((*animator).state, UIViewAnimatingStateActive); if (update_model) model_->AnimationEndedWithProgress((*animator).currentProgress);
diff --git a/ios/chrome/browser/ui/fullscreen/fullscreen_system_notification_observer.h b/ios/chrome/browser/ui/fullscreen/fullscreen_system_notification_observer.h new file mode 100644 index 0000000..3919328c --- /dev/null +++ b/ios/chrome/browser/ui/fullscreen/fullscreen_system_notification_observer.h
@@ -0,0 +1,33 @@ +// 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. + +#ifndef IOS_CHROME_BROWSER_UI_FULLSCREEN_FULLSCREEN_SYSTEM_NOTIFICATION_OBSERVER_H_ +#define IOS_CHROME_BROWSER_UI_FULLSCREEN_FULLSCREEN_SYSTEM_NOTIFICATION_OBSERVER_H_ + +#import <UIKit/UIKit.h> + +class FullscreenController; +class FullscreenMediator; + +// Helper class that listens for system notifications. This class will disable +// fullscreen when: +// - voice over is enabled +// - the keyboard is visible +// Additionally, this object notifies the mediator of foreground events. +@interface FullscreenSystemNotificationObserver : NSObject + +// Designated initializer that updates |controller| and |mediator| for system +// notifications. +- (nullable instancetype) +initWithController:(nonnull FullscreenController*)controller + mediator:(nonnull FullscreenMediator*)mediator + NS_DESIGNATED_INITIALIZER; +- (nullable instancetype)init NS_UNAVAILABLE; + +// Stops observing notifications. +- (void)disconnect; + +@end + +#endif // IOS_CHROME_BROWSER_UI_FULLSCREEN_FULLSCREEN_SYSTEM_NOTIFICATION_OBSERVER_H_
diff --git a/ios/chrome/browser/ui/fullscreen/fullscreen_system_notification_observer.mm b/ios/chrome/browser/ui/fullscreen/fullscreen_system_notification_observer.mm new file mode 100644 index 0000000..f1f4312 --- /dev/null +++ b/ios/chrome/browser/ui/fullscreen/fullscreen_system_notification_observer.mm
@@ -0,0 +1,122 @@ +// 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. + +#import "ios/chrome/browser/ui/fullscreen/fullscreen_system_notification_observer.h" + +#include <memory> + +#include "base/logging.h" +#import "ios/chrome/browser/ui/fullscreen/fullscreen_controller.h" +#import "ios/chrome/browser/ui/fullscreen/fullscreen_mediator.h" +#import "ios/chrome/browser/ui/fullscreen/scoped_fullscreen_disabler.h" + +#if !defined(__has_feature) || !__has_feature(objc_arc) +#error "This file requires ARC support." +#endif + +@interface FullscreenSystemNotificationObserver () { + // The disabler created when VoiceOver is enabled. + std::unique_ptr<ScopedFullscreenDisabler> _voiceOverDisabler; + // The disabler created when the keyboard is visible. + std::unique_ptr<ScopedFullscreenDisabler> _keyboardDisabler; +} +// The FullscreenController being enabled/disabled for system events. +@property(nonatomic, readonly, nonnull) FullscreenController* controller; +// The FullscreenMediator through which foreground events are propagated to +// FullscreenControllerObservers. +@property(nonatomic, readonly, nonnull) FullscreenMediator* mediator; +// Creates or destroys |_voiceOverDisabler| depending on whether VoiceOver is +// enabled. +- (void)voiceOverStatusChanged; +// Called when the keyboard is shown/hidden to reset |_keyboardDisabler|. +- (void)keyboardWillShow; +- (void)keyboardDidHide; +// Called when the application is foregrounded. +- (void)applicationWillEnterForeground; +@end + +@implementation FullscreenSystemNotificationObserver +@synthesize controller = _controller; +@synthesize mediator = _mediator; + +- (instancetype)initWithController:(FullscreenController*)controller + mediator:(FullscreenMediator*)mediator { + if (self = [super init]) { + _controller = controller; + DCHECK(_controller); + _mediator = mediator; + DCHECK(_mediator); + // Register for VoiceOVer status change notifications. The notification + // name has been updated in iOS 11. + NSNotificationCenter* defaultCenter = [NSNotificationCenter defaultCenter]; + if (@available(iOS 11, *)) { + [defaultCenter + addObserver:self + selector:@selector(voiceOverStatusChanged) + name:UIAccessibilityVoiceOverStatusDidChangeNotification + object:nil]; + } else { + [defaultCenter addObserver:self + selector:@selector(voiceOverStatusChanged) + name:UIAccessibilityVoiceOverStatusChanged + object:nil]; + } + // Create a disabler if VoiceOver is enabled. + if (UIAccessibilityIsVoiceOverRunning()) { + _voiceOverDisabler = + std::make_unique<ScopedFullscreenDisabler>(_controller); + } + // Register for keyboard visibility notifications. + [defaultCenter addObserver:self + selector:@selector(keyboardWillShow) + name:UIKeyboardWillShowNotification + object:nil]; + [defaultCenter addObserver:self + selector:@selector(keyboardDidHide) + name:UIKeyboardDidHideNotification + object:nil]; + // Register for application lifecycle events. + [defaultCenter addObserver:self + selector:@selector(applicationWillEnterForeground) + name:UIApplicationWillEnterForegroundNotification + object:nil]; + } + return self; +} + +- (void)dealloc { + // |-disconnect| should be called before deallocation. + DCHECK(!_controller); +} + +#pragma mark Public + +- (void)disconnect { + [[NSNotificationCenter defaultCenter] removeObserver:self]; + _controller = nullptr; +} + +#pragma mark Private + +- (void)voiceOverStatusChanged { + _voiceOverDisabler = + UIAccessibilityIsVoiceOverRunning() + ? std::make_unique<ScopedFullscreenDisabler>(self.controller) + : nullptr; +} + +- (void)keyboardWillShow { + _keyboardDisabler = + std::make_unique<ScopedFullscreenDisabler>(self.controller); +} + +- (void)keyboardDidHide { + _keyboardDisabler = nullptr; +} + +- (void)applicationWillEnterForeground { + self.mediator->WillEnterForeground(); +} + +@end
diff --git a/ios/chrome/browser/ui/fullscreen/fullscreen_ui_element.h b/ios/chrome/browser/ui/fullscreen/fullscreen_ui_element.h index 7e1e085..b69e917 100644 --- a/ios/chrome/browser/ui/fullscreen/fullscreen_ui_element.h +++ b/ios/chrome/browser/ui/fullscreen/fullscreen_ui_element.h
@@ -7,6 +7,7 @@ #import <Foundation/Foundation.h> +@class FullscreenForegroundAnimator; @class FullscreenScrollEndAnimator; @class FullscreenScrollToTopAnimator; @@ -34,6 +35,11 @@ - (void)scrollFullscreenToTopWithAnimator: (FullscreenScrollToTopAnimator*)animator; +// Called when fullscreen detects a foreground event. UI elements that react +// to fullscreen events can configure |animator| with aniamtions. +- (void)showToolbarForForgroundWithAnimator: + (FullscreenForegroundAnimator*)animator; + @end #endif // IOS_CLEAN_CHROME_BROWSER_UI_FULLSCREEN_FULLSCREEN_UI_ELEMENT_H_
diff --git a/ios/chrome/browser/ui/fullscreen/fullscreen_ui_updater.h b/ios/chrome/browser/ui/fullscreen/fullscreen_ui_updater.h index 0914e5f7..4e06f87 100644 --- a/ios/chrome/browser/ui/fullscreen/fullscreen_ui_updater.h +++ b/ios/chrome/browser/ui/fullscreen/fullscreen_ui_updater.h
@@ -28,6 +28,9 @@ void FullscreenWillScrollToTop( FullscreenController* controller, FullscreenScrollToTopAnimator* animator) override; + void FullscreenWillEnterForeground( + FullscreenController* controller, + FullscreenForegroundAnimator* animator) override; // The UI element being updated by this observer. __weak id<FullscreenUIElement> ui_element_;
diff --git a/ios/chrome/browser/ui/fullscreen/fullscreen_ui_updater.mm b/ios/chrome/browser/ui/fullscreen/fullscreen_ui_updater.mm index 684b905d..3ccb4839 100644 --- a/ios/chrome/browser/ui/fullscreen/fullscreen_ui_updater.mm +++ b/ios/chrome/browser/ui/fullscreen/fullscreen_ui_updater.mm
@@ -36,3 +36,9 @@ FullscreenScrollToTopAnimator* animator) { [ui_element_ scrollFullscreenToTopWithAnimator:animator]; } + +void FullscreenUIUpdater::FullscreenWillEnterForeground( + FullscreenController* controller, + FullscreenForegroundAnimator* animator) { + [ui_element_ showToolbarForForgroundWithAnimator:animator]; +}
diff --git a/ios/chrome/browser/ui/fullscreen/fullscreen_ui_updater_unittest.mm b/ios/chrome/browser/ui/fullscreen/fullscreen_ui_updater_unittest.mm index b8dd2c2b..b22e07c 100644 --- a/ios/chrome/browser/ui/fullscreen/fullscreen_ui_updater_unittest.mm +++ b/ios/chrome/browser/ui/fullscreen/fullscreen_ui_updater_unittest.mm
@@ -5,6 +5,7 @@ #import "ios/chrome/browser/ui/fullscreen/fullscreen_ui_updater.h" #import "ios/chrome/browser/ui/fullscreen/fullscreen_animator.h" +#import "ios/chrome/browser/ui/fullscreen/fullscreen_foreground_animator.h" #import "ios/chrome/browser/ui/fullscreen/fullscreen_scroll_end_animator.h" #import "ios/chrome/browser/ui/fullscreen/fullscreen_scroll_to_top_animator.h" #import "ios/chrome/browser/ui/fullscreen/fullscreen_ui_element.h" @@ -47,6 +48,11 @@ _animator = animator; } +- (void)showToolbarForForgroundWithAnimator: + (FullscreenForegroundAnimator*)animator { + _animator = animator; +} + @end #pragma mark - FullscreenUIUpdaterTest
diff --git a/ios/chrome/browser/ui/fullscreen/system_notification_fullscreen_disabler.h b/ios/chrome/browser/ui/fullscreen/system_notification_fullscreen_disabler.h deleted file mode 100644 index a7bcd3b..0000000 --- a/ios/chrome/browser/ui/fullscreen/system_notification_fullscreen_disabler.h +++ /dev/null
@@ -1,28 +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. - -#ifndef IOS_CHROME_BROWSER_UI_FULLSCREEN_SYSTEM_NOTIFICATION_FULLSCREEN_DISABLER_H_ -#define IOS_CHROME_BROWSER_UI_FULLSCREEN_SYSTEM_NOTIFICATION_FULLSCREEN_DISABLER_H_ - -#import <UIKit/UIKit.h> - -class FullscreenController; - -// Helper class that handles disabling fullscreen due to NSNotifications sent -// by system frameworks. This class disables fullscreen: -// - when VoiceOver is enabled, -// - when the software keyboard is visible. -@interface SystemNotificationFullscreenDisabler : NSObject - -// Designated initializer that disables |controller| for system notifications. -- (nullable instancetype)initWithController: - (nonnull FullscreenController*)controller NS_DESIGNATED_INITIALIZER; -- (nullable instancetype)init NS_UNAVAILABLE; - -// Stops observing VoiceOver notifications. -- (void)disconnect; - -@end - -#endif // IOS_CHROME_BROWSER_UI_FULLSCREEN_SYSTEM_NOTIFICATION_FULLSCREEN_DISABLER_H_
diff --git a/ios/chrome/browser/ui/fullscreen/system_notification_fullscreen_disabler.mm b/ios/chrome/browser/ui/fullscreen/system_notification_fullscreen_disabler.mm deleted file mode 100644 index 0754f9e6..0000000 --- a/ios/chrome/browser/ui/fullscreen/system_notification_fullscreen_disabler.mm +++ /dev/null
@@ -1,105 +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. - -#import "ios/chrome/browser/ui/fullscreen/system_notification_fullscreen_disabler.h" - -#include <memory> - -#include "base/logging.h" -#import "ios/chrome/browser/ui/fullscreen/fullscreen_controller.h" -#import "ios/chrome/browser/ui/fullscreen/scoped_fullscreen_disabler.h" - -#if !defined(__has_feature) || !__has_feature(objc_arc) -#error "This file requires ARC support." -#endif - -@interface SystemNotificationFullscreenDisabler () { - // The disabler created when VoiceOver is enabled. - std::unique_ptr<ScopedFullscreenDisabler> _voiceOverDisabler; - // The disabler created when the keyboard is visible. - std::unique_ptr<ScopedFullscreenDisabler> _keyboardDisabler; -} -// The FullscreenController being enabled/disabled for VoiceOver. -@property(nonatomic, readonly, nonnull) FullscreenController* controller; -// Creates or destroys |_voiceOverDisabler| depending on whether VoiceOver is -// enabled. -- (void)voiceOverStatusChanged; -// Called when the keyboard is shown/hidden to reset |_keyboardDisabler|. -- (void)keyboardWillShow; -- (void)keyboardDidHide; -@end - -@implementation SystemNotificationFullscreenDisabler -@synthesize controller = _controller; - -- (instancetype)initWithController:(FullscreenController*)controller { - if (self = [super init]) { - _controller = controller; - DCHECK(_controller); - // Register for VoiceOVer status change notifications. The notification - // name has been updated in iOS 11. - if (@available(iOS 11, *)) { - [[NSNotificationCenter defaultCenter] - addObserver:self - selector:@selector(voiceOverStatusChanged) - name:UIAccessibilityVoiceOverStatusDidChangeNotification - object:nil]; - } else { - [[NSNotificationCenter defaultCenter] - addObserver:self - selector:@selector(voiceOverStatusChanged) - name:UIAccessibilityVoiceOverStatusChanged - object:nil]; - } - // Create a disabler if VoiceOver is enabled. - if (UIAccessibilityIsVoiceOverRunning()) { - _voiceOverDisabler = - std::make_unique<ScopedFullscreenDisabler>(_controller); - } - // Regsiter for keyboard visibility notifications. - [[NSNotificationCenter defaultCenter] - addObserver:self - selector:@selector(keyboardWillShow) - name:UIKeyboardWillShowNotification - object:nil]; - [[NSNotificationCenter defaultCenter] - addObserver:self - selector:@selector(keyboardDidHide) - name:UIKeyboardDidHideNotification - object:nil]; - } - return self; -} - -- (void)dealloc { - // |-disconnect| should be called before deallocation. - DCHECK(!_controller); -} - -#pragma mark Public - -- (void)disconnect { - [[NSNotificationCenter defaultCenter] removeObserver:self]; - _controller = nullptr; -} - -#pragma mark Private - -- (void)voiceOverStatusChanged { - _voiceOverDisabler = - UIAccessibilityIsVoiceOverRunning() - ? std::make_unique<ScopedFullscreenDisabler>(self.controller) - : nullptr; -} - -- (void)keyboardWillShow { - _keyboardDisabler = - std::make_unique<ScopedFullscreenDisabler>(self.controller); -} - -- (void)keyboardDidHide { - _keyboardDisabler = nullptr; -} - -@end
diff --git a/ios/chrome/browser/ui/location_bar/BUILD.gn b/ios/chrome/browser/ui/location_bar/BUILD.gn index d97d84d1..fca6215 100644 --- a/ios/chrome/browser/ui/location_bar/BUILD.gn +++ b/ios/chrome/browser/ui/location_bar/BUILD.gn
@@ -19,24 +19,31 @@ deps = [ "//base", "//components/google/core/browser", + "//components/google/core/browser", "//components/omnibox/browser", + "//components/search_engines", "//components/strings", "//components/toolbar", "//ios/chrome/app/strings", "//ios/chrome/app/theme", "//ios/chrome/browser", + "//ios/chrome/browser/autocomplete", "//ios/chrome/browser/browser_state:browser_state", + "//ios/chrome/browser/search_engines", "//ios/chrome/browser/ui", "//ios/chrome/browser/ui/commands", "//ios/chrome/browser/ui/omnibox:omnibox", "//ios/chrome/browser/ui/omnibox:omnibox_internal", "//ios/chrome/browser/ui/omnibox/popup", + "//ios/chrome/browser/ui/qr_scanner/requirements", "//ios/chrome/browser/ui/toolbar/clean:toolbar_components_ui", "//ios/chrome/browser/ui/toolbar/keyboard_assist:keyboard_assist", "//ios/chrome/browser/ui/toolbar/public", "//ios/chrome/browser/ui/toolbar/public:toolbar_base_feature", + "//ios/chrome/browser/ui/voice", "//ios/chrome/browser/web_state_list", "//ios/chrome/common:timing", + "//ios/public/provider/chrome/browser/voice", "//ios/third_party/material_components_ios", "//ios/third_party/material_roboto_font_loader_ios", "//ios/web/public:public",
diff --git a/ios/chrome/browser/ui/location_bar/location_bar_coordinator.h b/ios/chrome/browser/ui/location_bar/location_bar_coordinator.h index cad97cf6..d885f42 100644 --- a/ios/chrome/browser/ui/location_bar/location_bar_coordinator.h +++ b/ios/chrome/browser/ui/location_bar/location_bar_coordinator.h
@@ -8,9 +8,10 @@ #import <UIKit/UIKit.h> #import "ios/chrome/browser/ui/location_bar/location_bar_url_loader.h" -#include "ios/chrome/browser/ui/location_bar/location_bar_view.h" #import "ios/chrome/browser/ui/omnibox/location_bar_delegate.h" +#include "ios/chrome/browser/ui/qr_scanner/requirements/qr_scanner_result_loading.h" #import "ios/chrome/browser/ui/toolbar/public/omnibox_focuser.h" +#include "ios/public/provider/chrome/browser/voice/voice_search_controller_delegate.h" namespace ios { class ChromeBrowserState; @@ -22,11 +23,13 @@ @protocol ToolbarCoordinatorDelegate; @protocol UrlLoader; -@interface LocationBarCoordinator - : NSObject<LocationBarURLLoader, OmniboxFocuser, LocationBarDelegate> +@interface LocationBarCoordinator : NSObject<LocationBarURLLoader, + OmniboxFocuser, + VoiceSearchControllerDelegate, + QRScannerResultLoading> -// LocationBarView containing the omnibox. -@property(nonatomic, strong) LocationBarView* locationBarView; +// View containing the omnibox. +@property(nonatomic, strong, readonly) UIView* view; // Weak reference to ChromeBrowserState; @property(nonatomic, assign) ios::ChromeBrowserState* browserState; // The dispatcher for this view controller. @@ -56,6 +59,24 @@ // the fakebox on NTP. - (void)focusOmniboxFromFakebox; +// Indicates when the omnibox is the first responder. +- (BOOL)isOmniboxFirstResponder; + +// Perform animations for expanding the omnibox. This animation can be seen on +// an iPhone when the omnibox is focused. It involves sliding the leading button +// out and fading its alpha. +// The trailing button is faded-in in the |completionAnimator| animations. +- (void)addExpandOmniboxAnimations:(UIViewPropertyAnimator*)animator + completionAnimator:(UIViewPropertyAnimator*)completionAnimator; + +// Perform animations for expanding the omnibox. This animation can be seen on +// an iPhone when the omnibox is defocused. It involves sliding the leading +// button in and fading its alpha. +- (void)addContractOmniboxAnimations:(UIViewPropertyAnimator*)animator; + +// Updates omnibox state, including the displayed text and the cursor position. +- (void)updateOmniboxState; + @end #endif // IOS_CHROME_BROWSER_UI_LOCATION_BAR_LOCATION_BAR_COORDINATOR_H_
diff --git a/ios/chrome/browser/ui/location_bar/location_bar_coordinator.mm b/ios/chrome/browser/ui/location_bar/location_bar_coordinator.mm index 5123013..77910d71 100644 --- a/ios/chrome/browser/ui/location_bar/location_bar_coordinator.mm +++ b/ios/chrome/browser/ui/location_bar/location_bar_coordinator.mm
@@ -11,11 +11,15 @@ #include "base/strings/sys_string_conversions.h" #include "components/google/core/browser/google_util.h" #include "components/omnibox/browser/omnibox_edit_model.h" +#include "components/search_engines/util.h" #include "components/strings/grit/components_strings.h" +#include "ios/chrome/browser/autocomplete/autocomplete_scheme_classifier_impl.h" #include "ios/chrome/browser/browser_state/chrome_browser_state.h" +#include "ios/chrome/browser/search_engines/template_url_service_factory.h" #import "ios/chrome/browser/ui/location_bar/location_bar_consumer.h" #import "ios/chrome/browser/ui/location_bar/location_bar_mediator.h" #import "ios/chrome/browser/ui/location_bar/location_bar_url_loader.h" +#include "ios/chrome/browser/ui/location_bar/location_bar_view.h" #include "ios/chrome/browser/ui/omnibox/location_bar_controller.h" #include "ios/chrome/browser/ui/omnibox/location_bar_controller_impl.h" #include "ios/chrome/browser/ui/omnibox/location_bar_delegate.h" @@ -37,7 +41,7 @@ #error "This file requires ARC support." #endif -@interface LocationBarCoordinator ()<LocationBarConsumer> { +@interface LocationBarCoordinator ()<LocationBarConsumer, LocationBarDelegate> { std::unique_ptr<LocationBarControllerImpl> _locationBarController; } // Object taking care of adding the accessory views to the keyboard. @@ -46,6 +50,9 @@ // Coordinator for the omnibox popup. @property(nonatomic, strong) OmniboxPopupCoordinator* omniboxPopupCoordinator; @property(nonatomic, strong) LocationBarMediator* mediator; +// Redefined as readwrite and as LocationBarView. +@property(nonatomic, strong, readwrite) LocationBarView* locationBarView; + @end @implementation LocationBarCoordinator @@ -62,6 +69,10 @@ #pragma mark - public +- (UIView*)view { + return self.locationBarView; +} + - (void)start { BOOL isIncognito = self.browserState->IsOffTheRecord(); @@ -127,6 +138,8 @@ #pragma mark - LocationBarConsumer - (void)updateOmniboxState { + if (!_locationBarController) + return; _locationBarController->SetShouldShowHintText( [self.delegate toolbarModelIOS]->ShouldDisplayHintText()); _locationBarController->OnToolbarUpdated(); @@ -149,6 +162,46 @@ model->SetCaretVisibility(false); } +- (BOOL)isOmniboxFirstResponder { + return [self.locationBarView.textField isFirstResponder]; +} + +- (void)addExpandOmniboxAnimations:(UIViewPropertyAnimator*)animator + completionAnimator:(UIViewPropertyAnimator*)completionAnimator { + [self.locationBarView addExpandOmniboxAnimations:animator + completionAnimator:completionAnimator]; +} + +- (void)addContractOmniboxAnimations:(UIViewPropertyAnimator*)animator { + [self.locationBarView addContractOmniboxAnimations:animator]; +} + +#pragma mark - VoiceSearchControllerDelegate + +- (void)receiveVoiceSearchResult:(NSString*)result { + DCHECK(result); + [self loadURLForQuery:result]; +} + +#pragma mark - QRScannerResultLoading + +- (void)receiveQRScannerResult:(NSString*)result loadImmediately:(BOOL)load { + DCHECK(result); + if (load) { + [self loadURLForQuery:result]; + } else { + [self focusOmnibox]; + [self.locationBarView.textField insertTextWhileEditing:result]; + // The call to |setText| shouldn't be needed, but without it the "Go" button + // of the keyboard is disabled. + [self.locationBarView.textField setText:result]; + // Notify the accessibility system to start reading the new contents of the + // Omnibox. + UIAccessibilityPostNotification(UIAccessibilityScreenChangedNotification, + self.locationBarView.textField); + } +} + #pragma mark - LocationBarURLLoader - (void)loadGURLFromLocationBar:(const GURL&)url @@ -217,4 +270,30 @@ return toolbarModelIOS ? toolbarModelIOS->GetToolbarModel() : nullptr; } +#pragma mark - private + +// Navigate to |query| from omnibox. +- (void)loadURLForQuery:(NSString*)query { + GURL searchURL; + metrics::OmniboxInputType type = AutocompleteInput::Parse( + base::SysNSStringToUTF16(query), std::string(), + AutocompleteSchemeClassifierImpl(), nullptr, nullptr, &searchURL); + if (type != metrics::OmniboxInputType::URL || !searchURL.is_valid()) { + searchURL = GetDefaultSearchURLForSearchTerms( + ios::TemplateURLServiceFactory::GetForBrowserState(self.browserState), + base::SysNSStringToUTF16(query)); + } + if (searchURL.is_valid()) { + // It is necessary to include PAGE_TRANSITION_FROM_ADDRESS_BAR in the + // transition type is so that query-in-the-omnibox is triggered for the + // URL. + ui::PageTransition transition = ui::PageTransitionFromInt( + ui::PAGE_TRANSITION_LINK | ui::PAGE_TRANSITION_FROM_ADDRESS_BAR); + [self.URLLoader loadURL:GURL(searchURL) + referrer:web::Referrer() + transition:transition + rendererInitiated:NO]; + } +} + @end
diff --git a/ios/chrome/browser/ui/location_bar/location_bar_coordinator_unittest.mm b/ios/chrome/browser/ui/location_bar/location_bar_coordinator_unittest.mm index a95fafa..dd4276b9 100644 --- a/ios/chrome/browser/ui/location_bar/location_bar_coordinator_unittest.mm +++ b/ios/chrome/browser/ui/location_bar/location_bar_coordinator_unittest.mm
@@ -80,11 +80,11 @@ }; TEST_F(LocationBarCoordinatorTest, Stops) { - EXPECT_TRUE(coordinator_.locationBarView == nil); + EXPECT_TRUE(coordinator_.view == nil); [coordinator_ start]; - EXPECT_TRUE(coordinator_.locationBarView != nil); + EXPECT_TRUE(coordinator_.view != nil); [coordinator_ stop]; - EXPECT_TRUE(coordinator_.locationBarView == nil); + EXPECT_TRUE(coordinator_.view == nil); } } // namespace
diff --git a/ios/chrome/browser/ui/main/browser_view_wrangler.mm b/ios/chrome/browser/ui/main/browser_view_wrangler.mm index 6c21791..f5c10df 100644 --- a/ios/chrome/browser/ui/main/browser_view_wrangler.mm +++ b/ios/chrome/browser/ui/main/browser_view_wrangler.mm
@@ -79,11 +79,6 @@ return self; } -- (instancetype)init { - NOTREACHED(); - return nil; -} - - (void)dealloc { DCHECK(_isShutdown) << "-shutdown must be called before -dealloc"; }
diff --git a/ios/chrome/browser/ui/ntp/new_tab_page_view.mm b/ios/chrome/browser/ui/ntp/new_tab_page_view.mm index ef93f31c..c6a7250 100644 --- a/ios/chrome/browser/ui/ntp/new_tab_page_view.mm +++ b/ios/chrome/browser/ui/ntp/new_tab_page_view.mm
@@ -69,7 +69,9 @@ - (void)layoutSubviews { [super layoutSubviews]; - self.tabBar.hidden = !self.tabBar.items.count; + // TODO(crbug.com/807330) Completely remove tabbar once + // IsUIRefreshPhase1Enabled is defaulted on. + self.tabBar.hidden = !self.tabBar.items.count || IsUIRefreshPhase1Enabled(); if (self.tabBar.hidden) { self.contentView.frame = self.bounds; } else {
diff --git a/ios/chrome/browser/ui/ntp/recent_tabs/recent_tabs_table_view_controller.mm b/ios/chrome/browser/ui/ntp/recent_tabs/recent_tabs_table_view_controller.mm index 87d5c0cb..f3aade4 100644 --- a/ios/chrome/browser/ui/ntp/recent_tabs/recent_tabs_table_view_controller.mm +++ b/ios/chrome/browser/ui/ntp/recent_tabs/recent_tabs_table_view_controller.mm
@@ -171,11 +171,6 @@ @synthesize dispatcher = _dispatcher; @synthesize handsetCommandHandler = _handsetCommandHandler; -- (instancetype)init { - NOTREACHED(); - return nil; -} - - (instancetype)initWithBrowserState:(ios::ChromeBrowserState*)browserState loader:(id<UrlLoader>)loader dispatcher:(id<ApplicationCommands>)dispatcher {
diff --git a/ios/chrome/browser/ui/omnibox/location_bar_controller_impl.mm b/ios/chrome/browser/ui/omnibox/location_bar_controller_impl.mm index d2e4739..c604dc4 100644 --- a/ios/chrome/browser/ui/omnibox/location_bar_controller_impl.mm +++ b/ios/chrome/browser/ui/omnibox/location_bar_controller_impl.mm
@@ -107,11 +107,6 @@ return self; } -- (instancetype)init { - NOTREACHED(); - return nil; -} - - (void)clearText { _omniboxView->ClearText(); }
diff --git a/ios/chrome/browser/ui/payments/payment_request_manager.mm b/ios/chrome/browser/ui/payments/payment_request_manager.mm index 0d39745..142b077 100644 --- a/ios/chrome/browser/ui/payments/payment_request_manager.mm +++ b/ios/chrome/browser/ui/payments/payment_request_manager.mm
@@ -283,11 +283,6 @@ return self; } -- (instancetype)init { - NOTREACHED(); - return nil; -} - - (void)dealloc { if (_activeWebState) { _paymentRequestJsManager = nil;
diff --git a/ios/chrome/browser/ui/print/print_controller.mm b/ios/chrome/browser/ui/print/print_controller.mm index 50a49483..99f7301 100644 --- a/ios/chrome/browser/ui/print/print_controller.mm +++ b/ios/chrome/browser/ui/print/print_controller.mm
@@ -192,11 +192,6 @@ return self; } -- (instancetype)init { - NOTREACHED(); - return nil; -} - - (void)printView:(UIView*)view withTitle:(NSString*)title viewController:(UIViewController*)viewController {
diff --git a/ios/chrome/browser/ui/sad_tab/sad_tab_view.mm b/ios/chrome/browser/ui/sad_tab/sad_tab_view.mm index 3b90644..58ff8dd 100644 --- a/ios/chrome/browser/ui/sad_tab/sad_tab_view.mm +++ b/ios/chrome/browser/ui/sad_tab/sad_tab_view.mm
@@ -149,21 +149,6 @@ return self; } -- (instancetype)init { - NOTREACHED(); - return nil; -} - -- (instancetype)initWithFrame:(CGRect)frame { - NOTREACHED(); - return nil; -} - -- (instancetype)initWithCoder:(NSCoder*)aDecoder { - NOTREACHED(); - return nil; -} - #pragma mark - Text Utilities + (nonnull NSAttributedString*)bulletedAttributedStringFromStrings:
diff --git a/ios/chrome/browser/ui/settings/content_settings_collection_view_controller.mm b/ios/chrome/browser/ui/settings/content_settings_collection_view_controller.mm index fa734f5..810a938 100644 --- a/ios/chrome/browser/ui/settings/content_settings_collection_view_controller.mm +++ b/ios/chrome/browser/ui/settings/content_settings_collection_view_controller.mm
@@ -121,11 +121,6 @@ [_disablePopupsSetting setObserver:nil]; } -- (instancetype)init { - NOTREACHED(); - return nil; -} - - (void)loadModel { [super loadModel];
diff --git a/ios/chrome/browser/ui/settings/password_details_collection_view_controller.mm b/ios/chrome/browser/ui/settings/password_details_collection_view_controller.mm index 17a8052..1d3ffb2 100644 --- a/ios/chrome/browser/ui/settings/password_details_collection_view_controller.mm +++ b/ios/chrome/browser/ui/settings/password_details_collection_view_controller.mm
@@ -480,8 +480,6 @@ // Show a MD snack bar with |message| and provide haptic feedback. The haptic // feedback is either for success or for error, depending on |success|. - (void)showToast:(NSString*)message forSuccess:(BOOL)success { - // TODO(crbug.com/159166): Route this through some delegate API to be able - // to mock it in the unittest, and avoid having an EGTest just for that? TriggerHapticFeedbackForNotification(success ? UINotificationFeedbackTypeSuccess : UINotificationFeedbackTypeError);
diff --git a/ios/chrome/browser/ui/settings/passwords_settings_egtest.mm b/ios/chrome/browser/ui/settings/passwords_settings_egtest.mm index 920d6d5..5f42d8d 100644 --- a/ios/chrome/browser/ui/settings/passwords_settings_egtest.mm +++ b/ios/chrome/browser/ui/settings/passwords_settings_egtest.mm
@@ -47,9 +47,6 @@ // password_details_collection_view_controller_unittest.mm. Very simple // integration tests and features which are not currently unittestable should // go here, the rest into the unittest. -// This test only uses the new UI which allows viewing passwords. -// TODO(crbug.com/159166): Remove the above sentence once the new UI is the -// default one. using autofill::PasswordForm; using chrome_test_util::ButtonWithAccessibilityLabel;
diff --git a/ios/chrome/browser/ui/signin_interaction/signin_interaction_controller.mm b/ios/chrome/browser/ui/signin_interaction/signin_interaction_controller.mm index a9d140f..53b4507d 100644 --- a/ios/chrome/browser/ui/signin_interaction/signin_interaction_controller.mm +++ b/ios/chrome/browser/ui/signin_interaction/signin_interaction_controller.mm
@@ -57,11 +57,6 @@ @synthesize dispatcher = dispatcher_; @synthesize presenter = presenter_; -- (id)init { - NOTREACHED(); - return nil; -} - - (instancetype)initWithBrowserState:(ios::ChromeBrowserState*)browserState presentationProvider:(id<SigninInteractionPresenting>)presenter accessPoint:(signin_metrics::AccessPoint)accessPoint
diff --git a/ios/chrome/browser/ui/stack_view/stack_card.mm b/ios/chrome/browser/ui/stack_view/stack_card.mm index a530736..5919f2f3 100644 --- a/ios/chrome/browser/ui/stack_view/stack_card.mm +++ b/ios/chrome/browser/ui/stack_view/stack_card.mm
@@ -43,11 +43,6 @@ return self; } -- (instancetype)init { - NOTREACHED(); - return nil; -} - - (void)releaseView { if (self.viewIsLive) _view = nil;
diff --git a/ios/chrome/browser/ui/tabs/tab_strip_controller.mm b/ios/chrome/browser/ui/tabs/tab_strip_controller.mm index 01b30570..94e9646 100644 --- a/ios/chrome/browser/ui/tabs/tab_strip_controller.mm +++ b/ios/chrome/browser/ui/tabs/tab_strip_controller.mm
@@ -454,11 +454,6 @@ return self; } -- (instancetype)init { - NOTREACHED(); - return nil; -} - - (void)dealloc { [_tabStripView setDelegate:nil]; [_tabStripView setLayoutDelegate:nil];
diff --git a/ios/chrome/browser/ui/toolbar/adaptive/adaptive_toolbar_coordinator.mm b/ios/chrome/browser/ui/toolbar/adaptive/adaptive_toolbar_coordinator.mm index a757d24..63db3d0 100644 --- a/ios/chrome/browser/ui/toolbar/adaptive/adaptive_toolbar_coordinator.mm +++ b/ios/chrome/browser/ui/toolbar/adaptive/adaptive_toolbar_coordinator.mm
@@ -57,8 +57,6 @@ self.started = YES; - self.viewController.dispatcher = self.dispatcher; - self.mediator = [[ToolbarMediator alloc] init]; self.mediator.voiceSearchProvider = ios::GetChromeBrowserProvider()->GetVoiceSearchProvider();
diff --git a/ios/chrome/browser/ui/toolbar/adaptive/adaptive_toolbar_view.h b/ios/chrome/browser/ui/toolbar/adaptive/adaptive_toolbar_view.h index 95fa692..aed7ce9f 100644 --- a/ios/chrome/browser/ui/toolbar/adaptive/adaptive_toolbar_view.h +++ b/ios/chrome/browser/ui/toolbar/adaptive/adaptive_toolbar_view.h
@@ -36,6 +36,8 @@ @property(nonatomic, strong, readonly) ToolbarButton* bookmarkButton; // Button to display the tools menu. @property(nonatomic, strong, readonly) ToolbarToolsMenuButton* toolsMenuButton; +// Button to display the tools menu. +@property(nonatomic, strong, readonly) ToolbarButton* omniboxButton; // The following 2 properties are for the two buttons to navigate forward that // are visible in various mutually exclusive configurations of the toolbar.
diff --git a/ios/chrome/browser/ui/toolbar/adaptive/adaptive_toolbar_view_controller.h b/ios/chrome/browser/ui/toolbar/adaptive/adaptive_toolbar_view_controller.h index 7764265b..388a3c4 100644 --- a/ios/chrome/browser/ui/toolbar/adaptive/adaptive_toolbar_view_controller.h +++ b/ios/chrome/browser/ui/toolbar/adaptive/adaptive_toolbar_view_controller.h
@@ -17,6 +17,11 @@ // ViewController for the adaptive toolbar. This ViewController is the super // class of the different implementation (primary or secondary). +// This class and its subclasses are constraining some named layout guides to +// their buttons. All of those constraints are dropped upon size class changes +// and rotations. Any view constrained to a layout guide is expected to be +// dismissed on such events. For example, the tools menu is closed upon +// rotation. @interface AdaptiveToolbarViewController : UIViewController<ToolbarConsumer> // Button factory.
diff --git a/ios/chrome/browser/ui/toolbar/adaptive/adaptive_toolbar_view_controller.mm b/ios/chrome/browser/ui/toolbar/adaptive/adaptive_toolbar_view_controller.mm index 1bfe13f..ffec65b 100644 --- a/ios/chrome/browser/ui/toolbar/adaptive/adaptive_toolbar_view_controller.mm +++ b/ios/chrome/browser/ui/toolbar/adaptive/adaptive_toolbar_view_controller.mm
@@ -5,12 +5,14 @@ #import "ios/chrome/browser/ui/toolbar/adaptive/adaptive_toolbar_view_controller.h" #import "base/logging.h" +#include "base/metrics/user_metrics.h" #import "ios/chrome/browser/ui/toolbar/adaptive/adaptive_toolbar_view.h" #import "ios/chrome/browser/ui/toolbar/clean/toolbar_button.h" #import "ios/chrome/browser/ui/toolbar/clean/toolbar_button_factory.h" #import "ios/chrome/browser/ui/toolbar/clean/toolbar_constants.h" #import "ios/chrome/browser/ui/toolbar/clean/toolbar_tab_grid_button.h" #import "ios/chrome/browser/ui/toolbar/clean/toolbar_tools_menu_button.h" +#import "ios/chrome/browser/ui/toolbar/public/omnibox_focuser.h" #import "ios/chrome/browser/ui/toolbar/public/toolbar_controller_constants.h" #import "ios/third_party/material_components_ios/src/components/ProgressView/src/MaterialProgressView.h" #import "ios/third_party/material_components_ios/src/components/Typography/src/MaterialTypography.h" @@ -54,6 +56,11 @@ [self updateAllButtonsVisibility]; } +- (void)viewDidLoad { + [super viewDidLoad]; + [self addStandardActionsForAllButtons]; +} + - (void)traitCollectionDidChange:(UITraitCollection*)previousTraitCollection { [super traitCollectionDidChange:previousTraitCollection]; [self updateAllButtonsVisibility]; @@ -139,4 +146,44 @@ } } +// Registers the actions which will be triggered when tapping a button. +- (void)addStandardActionsForAllButtons { + for (ToolbarButton* button in self.view.allButtons) { + if (button != self.view.toolsMenuButton) { + [button addTarget:self.dispatcher + action:@selector(cancelOmniboxEdit) + forControlEvents:UIControlEventTouchUpInside]; + } + [button addTarget:self + action:@selector(recordUserMetrics:) + forControlEvents:UIControlEventTouchUpInside]; + } +} + +// Records the use of a button. +- (IBAction)recordUserMetrics:(id)sender { + if (sender == self.view.backButton) { + base::RecordAction(base::UserMetricsAction("MobileToolbarBack")); + } else if (sender == self.view.forwardLeadingButton || + sender == self.view.forwardTrailingButton) { + base::RecordAction(base::UserMetricsAction("MobileToolbarForward")); + } else if (sender == self.view.reloadButton) { + base::RecordAction(base::UserMetricsAction("MobileToolbarReload")); + } else if (sender == self.view.stopButton) { + base::RecordAction(base::UserMetricsAction("MobileToolbarStop")); + } else if (sender == self.view.bookmarkButton) { + base::RecordAction(base::UserMetricsAction("MobileToolbarToggleBookmark")); + } else if (sender == self.view.toolsMenuButton) { + base::RecordAction(base::UserMetricsAction("MobileToolbarShowMenu")); + } else if (sender == self.view.tabGridButton) { + base::RecordAction(base::UserMetricsAction("MobileToolbarShowStackView")); + } else if (sender == self.view.shareButton) { + base::RecordAction(base::UserMetricsAction("MobileToolbarShareMenu")); + } else if (sender == self.view.omniboxButton) { + base::RecordAction(base::UserMetricsAction("MobileToolbarOmniboxShortcut")); + } else { + NOTREACHED(); + } +} + @end
diff --git a/ios/chrome/browser/ui/toolbar/adaptive/primary_toolbar_coordinator.mm b/ios/chrome/browser/ui/toolbar/adaptive/primary_toolbar_coordinator.mm index 7c179301..5ce0b4d 100644 --- a/ios/chrome/browser/ui/toolbar/adaptive/primary_toolbar_coordinator.mm +++ b/ios/chrome/browser/ui/toolbar/adaptive/primary_toolbar_coordinator.mm
@@ -55,11 +55,10 @@ - (void)start { self.viewController = [[PrimaryToolbarViewController alloc] init]; self.viewController.buttonFactory = [self buttonFactoryWithType:PRIMARY]; + self.viewController.dispatcher = self.dispatcher; [self setUpLocationBar]; - self.viewController.locationBarView = - self.locationBarCoordinator.locationBarView; - + self.viewController.locationBarView = self.locationBarCoordinator.view; [super start]; _fullscreenObserver = @@ -72,13 +71,11 @@ #pragma mark - PrimaryToolbarCoordinator - (id<VoiceSearchControllerDelegate>)voiceSearchDelegate { - // TODO(crbug.com/799446): This code should be moved to the location bar. - return nil; + return self.locationBarCoordinator; } - (id<QRScannerResultLoading>)QRScannerResultLoader { - // TODO(crbug.com/799446): This code should be moved to the location bar. - return nil; + return self.locationBarCoordinator; } - (id<TabHistoryUIUpdater>)tabHistoryUIUpdater { @@ -98,8 +95,7 @@ } - (BOOL)isOmniboxFirstResponder { - return - [self.locationBarCoordinator.locationBarView.textField isFirstResponder]; + return [self.locationBarCoordinator isOmniboxFirstResponder]; } - (BOOL)showingOmniboxPopup { @@ -156,16 +152,16 @@ // Don't do anything for a live non-ntp tab. if (webState == self.webStateList->GetActiveWebState() && !isNTP) { - [self.locationBarCoordinator.locationBarView setHidden:NO]; + [self.locationBarCoordinator.view setHidden:NO]; } else { self.viewController.view.hidden = NO; - [self.locationBarCoordinator.locationBarView setHidden:YES]; + [self.locationBarCoordinator.view setHidden:YES]; } } - (void)resetToolbarAfterSideSwipeSnapshot { [super resetToolbarAfterSideSwipeSnapshot]; - [self.locationBarCoordinator.locationBarView setHidden:NO]; + [self.locationBarCoordinator.view setHidden:NO]; } #pragma mark - Private
diff --git a/ios/chrome/browser/ui/toolbar/adaptive/primary_toolbar_view.h b/ios/chrome/browser/ui/toolbar/adaptive/primary_toolbar_view.h index 28ad5426..a5e6c23 100644 --- a/ios/chrome/browser/ui/toolbar/adaptive/primary_toolbar_view.h +++ b/ios/chrome/browser/ui/toolbar/adaptive/primary_toolbar_view.h
@@ -24,15 +24,13 @@ - (instancetype)initWithCoder:(NSCoder*)aDecoder NS_UNAVAILABLE; - (instancetype)init NS_UNAVAILABLE; -// Top anchor at the bottom of the safeAreaLayoutGuide. Used so views don't -// overlap with the Status Bar. -@property(nonatomic, strong) NSLayoutYAxisAnchor* topSafeAnchor; - // The location bar view, containing the omnibox. @property(nonatomic, strong) UIView* locationBarView; // Container for the location bar. @property(nonatomic, strong, readonly) UIView* locationBarContainer; +// The height of the container for the location bar. +@property(nonatomic, strong, readonly) NSLayoutConstraint* locationBarHeight; // StackView containing the leading buttons (relative to the location bar). // It should only contain ToolbarButtons.
diff --git a/ios/chrome/browser/ui/toolbar/adaptive/primary_toolbar_view.mm b/ios/chrome/browser/ui/toolbar/adaptive/primary_toolbar_view.mm index bd213a9..a06be65 100644 --- a/ios/chrome/browser/ui/toolbar/adaptive/primary_toolbar_view.mm +++ b/ios/chrome/browser/ui/toolbar/adaptive/primary_toolbar_view.mm
@@ -24,6 +24,8 @@ // Container for the location bar, redefined as readwrite. @property(nonatomic, strong, readwrite) UIView* locationBarContainer; +// The height of the container for the location bar, redefined as readwrite. +@property(nonatomic, strong, readwrite) NSLayoutConstraint* locationBarHeight; // StackView containing the leading buttons (relative to the location bar). It // should only contain ToolbarButtons. Redefined as readwrite. @@ -66,7 +68,7 @@ @implementation PrimaryToolbarView @synthesize locationBarView = _locationBarView; -@synthesize topSafeAnchor = _topSafeAnchor; +@synthesize locationBarHeight = _locationBarHeight; @synthesize buttonFactory = _buttonFactory; @synthesize allButtons = _allButtons; @synthesize progressBar = _progressBar; @@ -101,7 +103,6 @@ return; } DCHECK(self.buttonFactory); - DCHECK(self.topSafeAnchor); self.backgroundColor = self.buttonFactory.toolbarConfiguration.backgroundColor; @@ -115,6 +116,12 @@ [self setUpConstraints]; } +#pragma mark - UIView + +- (CGSize)intrinsicContentSize { + return CGSizeMake(UIViewNoIntrinsicMetric, kToolbarHeight); +} + #pragma mark - Setup // Sets the location bar container and its view if present. @@ -189,11 +196,14 @@ constraintEqualToAnchor:safeArea.leadingAnchor], [self.leadingStackView.bottomAnchor constraintEqualToAnchor:safeArea.bottomAnchor], - [self.leadingStackView.topAnchor - constraintEqualToAnchor:self.topSafeAnchor], + [self.leadingStackView.heightAnchor + constraintEqualToConstant:kToolbarHeight], ]]; // LocationBar constraints. + self.locationBarHeight = [self.locationBarContainer.heightAnchor + constraintEqualToConstant:kToolbarHeight - + 2 * kLocationBarVerticalMargin]; [NSLayoutConstraint activateConstraints:@[ [self.locationBarContainer.leadingAnchor constraintEqualToAnchor:self.leadingStackView.trailingAnchor], @@ -202,12 +212,7 @@ [self.locationBarContainer.bottomAnchor constraintEqualToAnchor:self.bottomAnchor constant:-kLocationBarVerticalMargin], - [self.locationBarContainer.topAnchor - constraintEqualToAnchor:self.topSafeAnchor - constant:kLocationBarVerticalMargin], - [self.locationBarContainer.heightAnchor - constraintEqualToConstant:kToolbarHeight - - 2 * kLocationBarVerticalMargin], + self.locationBarHeight, ]]; // Trailing StackView constraints. @@ -216,8 +221,8 @@ constraintEqualToAnchor:safeArea.trailingAnchor], [self.trailingStackView.bottomAnchor constraintEqualToAnchor:safeArea.bottomAnchor], - [self.trailingStackView.topAnchor - constraintEqualToAnchor:self.topSafeAnchor], + [self.trailingStackView.heightAnchor + constraintEqualToConstant:kToolbarHeight], ]]; // locationBarView constraints, if present. @@ -264,4 +269,10 @@ return _allButtons; } +#pragma mark - AdaptiveToolbarView + +- (ToolbarButton*)omniboxButton { + return nil; +} + @end
diff --git a/ios/chrome/browser/ui/toolbar/adaptive/primary_toolbar_view_controller.mm b/ios/chrome/browser/ui/toolbar/adaptive/primary_toolbar_view_controller.mm index 0823759..3add9df 100644 --- a/ios/chrome/browser/ui/toolbar/adaptive/primary_toolbar_view_controller.mm +++ b/ios/chrome/browser/ui/toolbar/adaptive/primary_toolbar_view_controller.mm
@@ -6,12 +6,15 @@ #import "base/logging.h" #import "ios/chrome/browser/ui/commands/browser_commands.h" +#import "ios/chrome/browser/ui/fullscreen/fullscreen_foreground_animator.h" #import "ios/chrome/browser/ui/fullscreen/fullscreen_scroll_end_animator.h" #import "ios/chrome/browser/ui/fullscreen/fullscreen_scroll_to_top_animator.h" #import "ios/chrome/browser/ui/history_popup/requirements/tab_history_constants.h" #import "ios/chrome/browser/ui/toolbar/adaptive/adaptive_toolbar_view_controller+subclassing.h" #import "ios/chrome/browser/ui/toolbar/adaptive/primary_toolbar_view.h" #import "ios/chrome/browser/ui/toolbar/clean/toolbar_button.h" +#import "ios/chrome/browser/ui/toolbar/clean/toolbar_button_factory.h" +#import "ios/chrome/browser/ui/toolbar/clean/toolbar_configuration.h" #import "ios/chrome/browser/ui/toolbar/clean/toolbar_constants.h" #import "ios/chrome/browser/ui/toolbar/clean/toolbar_tools_menu_button.h" #import "ios/chrome/browser/ui/util/named_guide.h" @@ -65,12 +68,6 @@ self.view = [[PrimaryToolbarView alloc] initWithButtonFactory:self.buttonFactory]; - if (@available(iOS 11, *)) { - self.view.topSafeAnchor = self.view.safeAreaLayoutGuide.topAnchor; - } else { - self.view.topSafeAnchor = self.topLayoutGuide.bottomAnchor; - } - // This method cannot be called from the init as the topSafeAnchor can only be // set to topLayoutGuide after the view creation on iOS 10. [self.view setUp]; @@ -79,21 +76,11 @@ - (void)viewDidLoad { [super viewDidLoad]; - // Adds the layout guide to the buttons. Adds the priorities such as the - // layout guide constraints does not conflict with others set by other - // toolbar. + // Adds the layout guide to the buttons. self.view.toolsMenuButton.guideName = kTabSwitcherGuide; - self.view.toolsMenuButton.constraintPriority = - kPrimaryToolbarTrailingButtonPriority; self.view.forwardLeadingButton.guideName = kForwardButtonGuide; - self.view.forwardLeadingButton.constraintPriority = - kPrimaryToolbarLeadingButtonPriority; self.view.forwardTrailingButton.guideName = kForwardButtonGuide; - self.view.forwardTrailingButton.constraintPriority = - kPrimaryToolbarTrailingButtonPriority; self.view.backButton.guideName = kBackButtonGuide; - self.view.backButton.constraintPriority = - kPrimaryToolbarLeadingButtonPriority; // Add navigation popup menu triggers. [self addLongPressGestureToView:self.view.backButton]; @@ -138,9 +125,16 @@ #pragma mark - FullscreenUIElement - (void)updateForFullscreenProgress:(CGFloat)progress { - self.view.leadingStackView.alpha = progress; - self.view.trailingStackView.alpha = progress; - // TODO(crbug.com/804731): Update the location bar constraints. + CGFloat alphaValue = fmax(progress * 2 - 1, 0); + self.view.leadingStackView.alpha = alphaValue; + self.view.trailingStackView.alpha = alphaValue; + self.view.locationBarHeight.constant = + AlignValueToPixel(kToolbarHeightFullscreen + + (kToolbarHeight - kToolbarHeightFullscreen) * progress - + 2 * kLocationBarVerticalMargin); + self.view.locationBarContainer.backgroundColor = + [self.buttonFactory.toolbarConfiguration.omniboxBackgroundColor + colorWithAlphaComponent:alphaValue]; } - (void)updateForFullscreenEnabled:(BOOL)enabled { @@ -158,6 +152,11 @@ [self addFullscreenAnimationsToAnimator:animator]; } +- (void)showToolbarForForgroundWithAnimator: + (FullscreenForegroundAnimator*)animator { + [self addFullscreenAnimationsToAnimator:animator]; +} + #pragma mark - FullscreenUIElement helpers - (void)addFullscreenAnimationsToAnimator:(FullscreenAnimator*)animator {
diff --git a/ios/chrome/browser/ui/toolbar/adaptive/secondary_toolbar_coordinator.mm b/ios/chrome/browser/ui/toolbar/adaptive/secondary_toolbar_coordinator.mm index a0d0918..266ce16 100644 --- a/ios/chrome/browser/ui/toolbar/adaptive/secondary_toolbar_coordinator.mm +++ b/ios/chrome/browser/ui/toolbar/adaptive/secondary_toolbar_coordinator.mm
@@ -24,6 +24,8 @@ - (void)start { self.viewController = [[SecondaryToolbarViewController alloc] init]; self.viewController.buttonFactory = [self buttonFactoryWithType:SECONDARY]; + self.viewController.dispatcher = self.dispatcher; + [super start]; }
diff --git a/ios/chrome/browser/ui/toolbar/adaptive/secondary_toolbar_view_controller.mm b/ios/chrome/browser/ui/toolbar/adaptive/secondary_toolbar_view_controller.mm index 51d04e1..5bb93af5 100644 --- a/ios/chrome/browser/ui/toolbar/adaptive/secondary_toolbar_view_controller.mm +++ b/ios/chrome/browser/ui/toolbar/adaptive/secondary_toolbar_view_controller.mm
@@ -31,8 +31,6 @@ - (void)viewDidLoad { [super viewDidLoad]; self.view.toolsMenuButton.guideName = kTabSwitcherGuide; - self.view.toolsMenuButton.constraintPriority = - kSecondaryToolbarButtonPriority; } @end
diff --git a/ios/chrome/browser/ui/toolbar/clean/BUILD.gn b/ios/chrome/browser/ui/toolbar/clean/BUILD.gn index 74fecdb..7305fd8 100644 --- a/ios/chrome/browser/ui/toolbar/clean/BUILD.gn +++ b/ios/chrome/browser/ui/toolbar/clean/BUILD.gn
@@ -18,14 +18,12 @@ ":toolbar_ui", "//base", "//components/bookmarks/browser", - "//components/google/core/browser", - "//components/search_engines", "//components/strings", + "//ios/chrome/browser", "//ios/chrome/browser/autocomplete", "//ios/chrome/browser/bookmarks", "//ios/chrome/browser/browser_state", "//ios/chrome/browser/reading_list", - "//ios/chrome/browser/search_engines", "//ios/chrome/browser/ui", "//ios/chrome/browser/ui/bookmarks", "//ios/chrome/browser/ui/broadcaster", @@ -40,7 +38,6 @@ "//ios/chrome/browser/ui/ntp:util", "//ios/chrome/browser/ui/omnibox", "//ios/chrome/browser/ui/omnibox:omnibox_internal", - "//ios/chrome/browser/ui/qr_scanner/requirements", "//ios/chrome/browser/ui/toolbar/keyboard_assist", "//ios/chrome/browser/ui/toolbar/public", "//ios/chrome/browser/ui/tools_menu:configuration",
diff --git a/ios/chrome/browser/ui/toolbar/clean/toolbar_button.h b/ios/chrome/browser/ui/toolbar/clean/toolbar_button.h index 0160fdf..65f40ecd 100644 --- a/ios/chrome/browser/ui/toolbar/clean/toolbar_button.h +++ b/ios/chrome/browser/ui/toolbar/clean/toolbar_button.h
@@ -21,11 +21,12 @@ // or WebState. @property(nonatomic, assign) BOOL hiddenInCurrentState; // Named of the layout guide this button should be constrained to, if not nil. +// The constraints to the layout guide are only valid when the button is +// displayed. Also, they can be dropped/changed upon size class changes or +// rotations. Any view constrained to them is expected to be dismissed on such +// events. @property(nonatomic, strong) GuideName* guideName; -// Priority of the constraints between the layout guide and the button, when -// activated. Use different priorities to avoid having conflicting constraints -// when moving the layout guide from one button to another. -@property(nonatomic, assign) UILayoutPriority constraintPriority; + // Returns a ToolbarButton using the three images parameters for their // respective state. + (instancetype)toolbarButtonWithImageForNormalState:(UIImage*)normalImage
diff --git a/ios/chrome/browser/ui/toolbar/clean/toolbar_button.mm b/ios/chrome/browser/ui/toolbar/clean/toolbar_button.mm index cd35541..806779b 100644 --- a/ios/chrome/browser/ui/toolbar/clean/toolbar_button.mm +++ b/ios/chrome/browser/ui/toolbar/clean/toolbar_button.mm
@@ -5,24 +5,17 @@ #import "ios/chrome/browser/ui/toolbar/clean/toolbar_button.h" #import "ios/chrome/browser/ui/uikit_ui_util.h" +#import "ios/chrome/browser/ui/util/constraints_ui_util.h" #if !defined(__has_feature) || !__has_feature(objc_arc) #error "This file requires ARC support." #endif -@interface ToolbarButton () -// Constraints for the named layout guide. -@property(nonatomic, strong) - NSArray<NSLayoutConstraint*>* namedGuideConstraints; -@end - @implementation ToolbarButton @synthesize visibilityMask = _visibilityMask; @synthesize guideName = _guideName; -@synthesize constraintPriority = _constraintPriority; @synthesize hiddenInCurrentSizeClass = _hiddenInCurrentSizeClass; @synthesize hiddenInCurrentState = _hiddenInCurrentState; -@synthesize namedGuideConstraints = _namedGuideConstraints; + (instancetype)toolbarButtonWithImageForNormalState:(UIImage*)normalImage imageForHighlightedState:(UIImage*)highlightedImage @@ -34,7 +27,6 @@ [button setImage:highlightedImage forState:UIControlStateSelected]; button.titleLabel.textAlignment = NSTextAlignmentCenter; button.translatesAutoresizingMaskIntoConstraints = NO; - button.constraintPriority = UILayoutPriorityRequired; return button; } @@ -52,14 +44,6 @@ } } -#pragma mark - Property accessors - -- (void)setGuideName:(GuideName*)guideName { - _guideName = guideName; - [NSLayoutConstraint deactivateConstraints:self.namedGuideConstraints]; - self.namedGuideConstraints = nil; -} - #pragma mark - Public Methods - (void)updateHiddenInCurrentSizeClass { @@ -113,30 +97,29 @@ // Checks if the button should be visible based on its hiddenInCurrentSizeClass // and hiddenInCurrentState properties, then updates its visibility accordingly. - (void)setHiddenForCurrentStateAndSizeClass { + BOOL previouslyHidden = self.hidden; self.hidden = self.hiddenInCurrentState || self.hiddenInCurrentSizeClass; - if (!self.namedGuideConstraints && self.guideName) { - // The guide name can be set before the button is added to the view - // hierarchy. Checking here if the constraints are set to prevent it. - UILayoutGuide* guide = FindNamedGuide(_guideName, self); + if (!self.hidden && previouslyHidden != self.hidden && self.guideName) { + // The button is appearing. At this point, if it has a layout guide + // associated, it should constraint it to itself. + UILayoutGuide* guide = FindNamedGuide(self.guideName, self); if (!guide) return; - self.namedGuideConstraints = @[ - [guide.leadingAnchor constraintEqualToAnchor:self.leadingAnchor], - [guide.trailingAnchor constraintEqualToAnchor:self.trailingAnchor], - [guide.topAnchor constraintEqualToAnchor:self.topAnchor], - [guide.bottomAnchor constraintEqualToAnchor:self.bottomAnchor] - ]; - for (NSLayoutConstraint* constraint in self.namedGuideConstraints) { - constraint.priority = self.constraintPriority; - } - } + // Removes the layout guide from its superview and re-add it to deactivate + // all constraints associated with this layout guide. As the layout guide is + // supposed to be associated only with this button and all components using + // those layout guide should close themselves when size class is changing, + // it should work. + UIView* guideOwner = guide.owningView; + [guideOwner removeLayoutGuide:guide]; + [guideOwner addLayoutGuide:guide]; - if (self.hidden) { - [NSLayoutConstraint deactivateConstraints:self.namedGuideConstraints]; - } else { - [NSLayoutConstraint activateConstraints:self.namedGuideConstraints]; + AddSameConstraints(guide, self); + + // Make sure the constraints are taken into account. + [guideOwner layoutIfNeeded]; } }
diff --git a/ios/chrome/browser/ui/toolbar/clean/toolbar_constants.h b/ios/chrome/browser/ui/toolbar/clean/toolbar_constants.h index ff445b1e..e92359d 100644 --- a/ios/chrome/browser/ui/toolbar/clean/toolbar_constants.h +++ b/ios/chrome/browser/ui/toolbar/clean/toolbar_constants.h
@@ -50,15 +50,6 @@ extern const CGFloat kForwardButtonImageInset; extern const CGFloat kLeadingLocationBarButtonImageInset; -// Priorities for the constraints between the buttons and their layout guide. -// The constraint priorities for the different toolbars' buttons are not the -// same to prevent conflicting constraints when a layout guide is changing the -// button to which it is constrained (there might be a short time during which -// it is constrained to both buttons). -extern const UILayoutPriority kPrimaryToolbarLeadingButtonPriority; -extern const UILayoutPriority kPrimaryToolbarTrailingButtonPriority; -extern const UILayoutPriority kSecondaryToolbarButtonPriority; - // Maximum number of tabs displayed by the button containing the tab count. extern const NSInteger kShowTabStripButtonMaxTabCount;
diff --git a/ios/chrome/browser/ui/toolbar/clean/toolbar_constants.mm b/ios/chrome/browser/ui/toolbar/clean/toolbar_constants.mm index 686662ca..7a37185 100644 --- a/ios/chrome/browser/ui/toolbar/clean/toolbar_constants.mm +++ b/ios/chrome/browser/ui/toolbar/clean/toolbar_constants.mm
@@ -39,17 +39,6 @@ const CGFloat kForwardButtonImageInset = -7; const CGFloat kLeadingLocationBarButtonImageInset = 15; -// The priority is not UILayoutPriorityHigh as it should be -// UILayoutPriorityRequired aside from the very small time interval during -// which they are conflicting. Also, it allows to have potentially more -// priorities. -const UILayoutPriority kPrimaryToolbarLeadingButtonPriority = - UILayoutPriorityRequired; -const UILayoutPriority kPrimaryToolbarTrailingButtonPriority = - kPrimaryToolbarLeadingButtonPriority - 1; -const UILayoutPriority kSecondaryToolbarButtonPriority = - kPrimaryToolbarTrailingButtonPriority - 1; - const NSInteger kShowTabStripButtonMaxTabCount = 99; const LayoutOffset kToolbarButtonAnimationOffset = -10.0;
diff --git a/ios/chrome/browser/ui/toolbar/clean/toolbar_coordinator.h b/ios/chrome/browser/ui/toolbar/clean/toolbar_coordinator.h index 6784332..a6b05402 100644 --- a/ios/chrome/browser/ui/toolbar/clean/toolbar_coordinator.h +++ b/ios/chrome/browser/ui/toolbar/clean/toolbar_coordinator.h
@@ -7,11 +7,9 @@ #import <UIKit/UIKit.h> -#include "ios/chrome/browser/ui/qr_scanner/requirements/qr_scanner_result_loading.h" #import "ios/chrome/browser/ui/toolbar/public/fakebox_focuser.h" #import "ios/chrome/browser/ui/toolbar/public/omnibox_focuser.h" #import "ios/chrome/browser/ui/tools_menu/public/tools_menu_presentation_provider.h" -#include "ios/public/provider/chrome/browser/voice/voice_search_controller_delegate.h" @protocol ActivityServicePositioner; @protocol ApplicationCommands; @@ -21,6 +19,8 @@ @protocol ToolbarCommands; @protocol ToolbarCoordinatorDelegate; @protocol UrlLoader; +@protocol VoiceSearchControllerDelegate; +@protocol QRScannerResultLoading; class WebStateList; namespace ios { class ChromeBrowserState; @@ -30,10 +30,8 @@ } // Coordinator to run a toolbar -- a UI element housing controls. -@interface ToolbarCoordinator : NSObject<FakeboxFocuser, - QRScannerResultLoading, - ToolsMenuPresentationProvider, - VoiceSearchControllerDelegate> +@interface ToolbarCoordinator + : NSObject<FakeboxFocuser, ToolsMenuPresentationProvider> // Weak reference to ChromeBrowserState; @property(nonatomic, assign) ios::ChromeBrowserState* browserState; @@ -60,6 +58,10 @@ // Returns the OmniboxFocuser for this toolbar. - (id<OmniboxFocuser>)omniboxFocuser; +// Returns the VoiceSearchControllerDelegate for this toolbar. +- (id<VoiceSearchControllerDelegate>)voiceSearchControllerDelegate; +// Returns the QRScannerResultLoading for this toolbar. +- (id<QRScannerResultLoading>)QRScannerResultLoader; // Start this coordinator. - (void)start;
diff --git a/ios/chrome/browser/ui/toolbar/clean/toolbar_coordinator.mm b/ios/chrome/browser/ui/toolbar/clean/toolbar_coordinator.mm index 3a267a6..22328e6 100644 --- a/ios/chrome/browser/ui/toolbar/clean/toolbar_coordinator.mm +++ b/ios/chrome/browser/ui/toolbar/clean/toolbar_coordinator.mm
@@ -10,14 +10,10 @@ #include "base/metrics/user_metrics.h" #include "base/metrics/user_metrics_action.h" #include "base/strings/sys_string_conversions.h" -#include "components/omnibox/browser/autocomplete_input.h" -#include "components/search_engines/util.h" #include "components/strings/grit/components_strings.h" -#include "ios/chrome/browser/autocomplete/autocomplete_scheme_classifier_impl.h" #include "ios/chrome/browser/bookmarks/bookmark_model_factory.h" #include "ios/chrome/browser/browser_state/chrome_browser_state.h" #include "ios/chrome/browser/reading_list/reading_list_model_factory.h" -#include "ios/chrome/browser/search_engines/template_url_service_factory.h" #import "ios/chrome/browser/ui/fullscreen/fullscreen_controller.h" #import "ios/chrome/browser/ui/fullscreen/fullscreen_controller_factory.h" #import "ios/chrome/browser/ui/fullscreen/fullscreen_features.h" @@ -139,8 +135,7 @@ buttonFactory:factory buttonUpdater:self.buttonUpdater omniboxFocuser:self.locationBarCoordinator]; - self.toolbarViewController.locationBarView = - self.locationBarCoordinator.locationBarView; + self.toolbarViewController.locationBarView = self.locationBarCoordinator.view; self.toolbarViewController.dispatcher = self.dispatcher; if (base::FeatureList::IsEnabled(fullscreen::features::kNewFullscreen)) { @@ -196,17 +191,31 @@ return self.locationBarCoordinator; } +- (id<VoiceSearchControllerDelegate>)voiceSearchControllerDelegate { + return self.locationBarCoordinator; +} + +- (id<QRScannerResultLoading>)QRScannerResultLoader { + return self.locationBarCoordinator; +} + +- (void)updateToolbarState { + // TODO(crbug.com/803383): This should be done inside the location bar. + // Updates the omnibox. + [self.locationBarCoordinator updateOmniboxState]; +} + - (void)updateToolbarForSideSwipeSnapshot:(web::WebState*)webState { BOOL isNTP = IsVisibleUrlNewTabPage(webState); // Don't do anything for a live non-ntp tab. if (webState == self.webStateList->GetActiveWebState() && !isNTP) { - [self.locationBarCoordinator.locationBarView setHidden:NO]; + [self.locationBarCoordinator.view setHidden:NO]; return; } self.viewController.view.hidden = NO; - [self.locationBarCoordinator.locationBarView setHidden:YES]; + [self.locationBarCoordinator.view setHidden:YES]; [self.mediator updateConsumerForWebState:webState]; [self.toolbarViewController updateForSideSwipeSnapshotOnNTP:isNTP]; } @@ -214,7 +223,7 @@ - (void)resetToolbarAfterSideSwipeSnapshot { [self.mediator updateConsumerForWebState:self.webStateList->GetActiveWebState()]; - [self.locationBarCoordinator.locationBarView setHidden:NO]; + [self.locationBarCoordinator.view setHidden:NO]; [self.toolbarViewController resetAfterSideSwipeSnapshot]; } @@ -235,8 +244,7 @@ } - (BOOL)isOmniboxFirstResponder { - return - [self.locationBarCoordinator.locationBarView.textField isFirstResponder]; + return [self.locationBarCoordinator isOmniboxFirstResponder]; } - (BOOL)showingOmniboxPopup { @@ -318,34 +326,6 @@ self.viewController.view.hidden = NO; } -#pragma mark - VoiceSearchControllerDelegate - -- (void)receiveVoiceSearchResult:(NSString*)result { - DCHECK(result); - [self loadURLForQuery:result]; -} - -#pragma mark - QRScannerResultLoading - -- (void)receiveQRScannerResult:(NSString*)result loadImmediately:(BOOL)load { - DCHECK(result); - if (load) { - [self loadURLForQuery:result]; - } else { - [self.locationBarCoordinator focusOmnibox]; - [self.locationBarCoordinator.locationBarView.textField - insertTextWhileEditing:result]; - // The call to |setText| shouldn't be needed, but without it the "Go" button - // of the keyboard is disabled. - [self.locationBarCoordinator.locationBarView.textField setText:result]; - // Notify the accessibility system to start reading the new contents of the - // Omnibox. - UIAccessibilityPostNotification( - UIAccessibilityScreenChangedNotification, - self.locationBarCoordinator.locationBarView.textField); - } -} - #pragma mark - ToolsMenuPresentationProvider - (UIButton*)presentingButtonForToolsMenuCoordinator: @@ -418,30 +398,6 @@ #pragma mark - Private -// Navigate to |query| from omnibox. -- (void)loadURLForQuery:(NSString*)query { - GURL searchURL; - metrics::OmniboxInputType type = AutocompleteInput::Parse( - base::SysNSStringToUTF16(query), std::string(), - AutocompleteSchemeClassifierImpl(), nullptr, nullptr, &searchURL); - if (type != metrics::OmniboxInputType::URL || !searchURL.is_valid()) { - searchURL = GetDefaultSearchURLForSearchTerms( - ios::TemplateURLServiceFactory::GetForBrowserState(self.browserState), - base::SysNSStringToUTF16(query)); - } - if (searchURL.is_valid()) { - // It is necessary to include PAGE_TRANSITION_FROM_ADDRESS_BAR in the - // transition type is so that query-in-the-omnibox is triggered for the - // URL. - ui::PageTransition transition = ui::PageTransitionFromInt( - ui::PAGE_TRANSITION_LINK | ui::PAGE_TRANSITION_FROM_ADDRESS_BAR); - [self.URLLoader loadURL:GURL(searchURL) - referrer:web::Referrer() - transition:transition - rendererInitiated:NO]; - } -} - // Animates |_toolbar| and |_locationBarView| for omnibox expansion. If // |animated| is NO the animation will happen instantly. - (void)expandOmniboxAnimated:(BOOL)animated { @@ -460,9 +416,8 @@ [completionAnimator startAnimationAfterDelay:ios::material::kDuration4]; }]; - [self.locationBarCoordinator.locationBarView - addExpandOmniboxAnimations:animator - completionAnimator:completionAnimator]; + [self.locationBarCoordinator addExpandOmniboxAnimations:animator + completionAnimator:completionAnimator]; [self.toolbarViewController addToolbarExpansionAnimations:animator completionAnimator:completionAnimator]; [animator startAnimation]; @@ -483,8 +438,7 @@ curve:UIViewAnimationCurveEaseInOut animations:^{ }]; - [self.locationBarCoordinator.locationBarView - addContractOmniboxAnimations:animator]; + [self.locationBarCoordinator addContractOmniboxAnimations:animator]; [self.toolbarViewController addToolbarContractionAnimations:animator]; [animator startAnimation]; }
diff --git a/ios/chrome/browser/ui/toolbar/clean/toolbar_tools_menu_button.mm b/ios/chrome/browser/ui/toolbar/clean/toolbar_tools_menu_button.mm index fc62a54..488dc9c 100644 --- a/ios/chrome/browser/ui/toolbar/clean/toolbar_tools_menu_button.mm +++ b/ios/chrome/browser/ui/toolbar/clean/toolbar_tools_menu_button.mm
@@ -9,19 +9,31 @@ #include "base/logging.h" #include "ios/chrome/browser/ui/toolbar/clean/toolbar_button_tints.h" +#include "ios/chrome/browser/ui/ui_util.h" #if !defined(__has_feature) || !__has_feature(objc_arc) #error "This file requires ARC support." #endif namespace { -// The number of dots drawn. -const int kNumberOfDots = 3; +// *** Constants for the non-adaptive toolbar, 3 vertical dots. *** // Position of the topmost dot. -const CGFloat kDotOffsetX = 22; -const CGFloat kDotOffsetY = 18; +const CGFloat kDotOffsetXVertical = 22; +const CGFloat kDotOffsetYVertical = 18; // Vertical space between dots. const CGFloat kVerticalSpaceBetweenDots = 6; + +// *** Constants for the adaptive toolbar, 3 horizontal dots. *** +// Position of the left most dot. +const CGFloat kDotOffsetXHorizontal = 22; +const CGFloat kDotOffsetYHorizontal = 18; +// Horizontal space between dots. +const CGFloat kHorizontalSpaceBetweenDots = 6; + +// The maximum width of the segment/dots. +const CGFloat kMaxWidthOfStroke = 7.4; +// The number of dots drawn. +const int kNumberOfDots = 3; // The duration of the animation, in seconds. const CFTimeInterval kAnimationDuration = 1; // The frame offset at which the animation to the intermediary value finishes. @@ -32,8 +44,6 @@ const int kFinalValueBeginFrame = 37; // The number of frames between the start of each dot's animation. const double kFramesBetweenAnimationOfEachDot = 3; -// The maximum width of the segment/dots. -const CGFloat kMaxWidthOfSegment = 7.4; // Constants for the properties of the stroke during the animations. // The strokeEnd is slightly more than 0.5, because if the strokeEnd is // exactly equal to strokeStart, the line is not drawn. @@ -158,12 +168,14 @@ pathLayers_ = [[NSMutableArray alloc] initWithCapacity:kNumberOfDots]; for (NSUInteger i = 0; i < kNumberOfDots; i++) { - const CGFloat x = kDotOffsetX; - const CGFloat y = kDotOffsetY + kVerticalSpaceBetweenDots * i; + const CGFloat x = [self firstDotXOffset] + [self horizontalSpacing] * i; + const CGFloat y = [self firstDotYOffset] + [self verticalSpacing] * i; UIBezierPath* path = [UIBezierPath bezierPath]; - [path moveToPoint:CGPointMake(x - kMaxWidthOfSegment * 0.5, y)]; - [path addLineToPoint:CGPointMake(x + kMaxWidthOfSegment * 0.5, y)]; + [path moveToPoint:CGPointMake(x - [self segmentWidth] * 0.5, + y - [self segmentHeight] * 0.5)]; + [path addLineToPoint:CGPointMake(x + [self segmentWidth] * 0.5, + y + [self segmentHeight] * 0.5)]; CAShapeLayer* pathLayer = [CAShapeLayer layer]; [pathLayer setFrame:self.bounds]; @@ -339,4 +351,60 @@ [self initializeShapeLayers]; } +#pragma mark - Private + +// Returns the X offset of the first dot. +- (CGFloat)firstDotXOffset { + if (IsUIRefreshPhase1Enabled()) { + return kDotOffsetXHorizontal; + } else { + return kDotOffsetXVertical; + } +} + +// Returns the Y offset of the first dot. +- (CGFloat)firstDotYOffset { + if (IsUIRefreshPhase1Enabled()) { + return kDotOffsetYHorizontal; + } else { + return kDotOffsetYVertical; + } +} + +// Returns the vertical spacing between two dots. +- (CGFloat)verticalSpacing { + if (IsUIRefreshPhase1Enabled()) { + return 0; + } else { + return kVerticalSpaceBetweenDots; + } +} + +// Returns the horizontal spacing between two dots. +- (CGFloat)horizontalSpacing { + if (IsUIRefreshPhase1Enabled()) { + return kHorizontalSpaceBetweenDots; + } else { + return 0; + } +} + +// Returns the width of a segment used in animation. +- (CGFloat)segmentWidth { + if (IsUIRefreshPhase1Enabled()) { + return 0; + } else { + return kMaxWidthOfStroke; + } +} + +// Returns the height of a segment used in animation. +- (CGFloat)segmentHeight { + if (IsUIRefreshPhase1Enabled()) { + return kMaxWidthOfStroke; + } else { + return 0; + } +} + @end
diff --git a/ios/chrome/browser/ui/toolbar/clean/toolbar_view_controller.mm b/ios/chrome/browser/ui/toolbar/clean/toolbar_view_controller.mm index 877d39c..9d5d6fc 100644 --- a/ios/chrome/browser/ui/toolbar/clean/toolbar_view_controller.mm +++ b/ios/chrome/browser/ui/toolbar/clean/toolbar_view_controller.mm
@@ -12,6 +12,7 @@ #import "ios/chrome/browser/ui/commands/history_popup_commands.h" #import "ios/chrome/browser/ui/commands/start_voice_search_command.h" #import "ios/chrome/browser/ui/fullscreen/fullscreen_animator.h" +#import "ios/chrome/browser/ui/fullscreen/fullscreen_foreground_animator.h" #import "ios/chrome/browser/ui/fullscreen/fullscreen_scroll_end_animator.h" #import "ios/chrome/browser/ui/fullscreen/fullscreen_scroll_to_top_animator.h" #include "ios/chrome/browser/ui/rtl_geometry.h" @@ -583,6 +584,11 @@ [self addFullscreenAnimationsToAnimator:animator]; } +- (void)showToolbarForForgroundWithAnimator: + (FullscreenForegroundAnimator*)animator { + [self addFullscreenAnimationsToAnimator:animator]; +} + #pragma mark - FullscreenUIElement helpers - (void)addFullscreenAnimationsToAnimator:(FullscreenAnimator*)animator {
diff --git a/ios/chrome/browser/ui/toolbar/public/toolbar_controller_constants.h b/ios/chrome/browser/ui/toolbar/public/toolbar_controller_constants.h index 206c339..51521b2 100644 --- a/ios/chrome/browser/ui/toolbar/public/toolbar_controller_constants.h +++ b/ios/chrome/browser/ui/toolbar/public/toolbar_controller_constants.h
@@ -13,6 +13,8 @@ // Height of the toolbar. extern const CGFloat kToolbarHeight; +// Height of the toolbar when in fullscreen. +extern const CGFloat kToolbarHeightFullscreen; // The time delay before non-initial button images are loaded. extern const int64_t kNonInitialImageAdditionDelayNanosec;
diff --git a/ios/chrome/browser/ui/toolbar/public/toolbar_controller_constants.mm b/ios/chrome/browser/ui/toolbar/public/toolbar_controller_constants.mm index 23a5f05..95b24eb2 100644 --- a/ios/chrome/browser/ui/toolbar/public/toolbar_controller_constants.mm +++ b/ios/chrome/browser/ui/toolbar/public/toolbar_controller_constants.mm
@@ -9,6 +9,7 @@ #endif const CGFloat kToolbarHeight = 56; +const CGFloat kToolbarHeightFullscreen = 35; const int64_t kNonInitialImageAdditionDelayNanosec = 500000LL;
diff --git a/ios/chrome/browser/ui/toolbar/toolbar_adapter.mm b/ios/chrome/browser/ui/toolbar/toolbar_adapter.mm index 8e003e4..015df94 100644 --- a/ios/chrome/browser/ui/toolbar/toolbar_adapter.mm +++ b/ios/chrome/browser/ui/toolbar/toolbar_adapter.mm
@@ -166,7 +166,8 @@ #pragma mark - VoiceSearchControllerDelegate - (void)receiveVoiceSearchResult:(NSString*)voiceResult { - [self.toolbarCoordinator receiveVoiceSearchResult:voiceResult]; + [self.toolbarCoordinator.voiceSearchControllerDelegate + receiveVoiceSearchResult:voiceResult]; } #pragma mark - ActivityServicePositioner @@ -179,8 +180,9 @@ - (void)receiveQRScannerResult:(NSString*)qrScannerResult loadImmediately:(BOOL)load { - [self.toolbarCoordinator receiveQRScannerResult:qrScannerResult - loadImmediately:load]; + [self.toolbarCoordinator.QRScannerResultLoader + receiveQRScannerResult:qrScannerResult + loadImmediately:load]; } #pragma mark - BubbleViewAnchorPointProvider @@ -214,6 +216,10 @@ (FullscreenScrollToTopAnimator*)animator { } +- (void)showToolbarForForgroundWithAnimator: + (FullscreenForegroundAnimator*)animator { +} + #pragma mark - ToolsMenuPresentationProvider - (UIButton*)presentingButtonForToolsMenuCoordinator:
diff --git a/ios/chrome/browser/ui/toolbar/toolbar_controller.mm b/ios/chrome/browser/ui/toolbar/toolbar_controller.mm index 54ce312..a86430a 100644 --- a/ios/chrome/browser/ui/toolbar/toolbar_controller.mm +++ b/ios/chrome/browser/ui/toolbar/toolbar_controller.mm
@@ -19,6 +19,7 @@ #import "ios/chrome/browser/ui/commands/application_commands.h" #import "ios/chrome/browser/ui/commands/browser_commands.h" #import "ios/chrome/browser/ui/fullscreen/fullscreen_animator.h" +#import "ios/chrome/browser/ui/fullscreen/fullscreen_foreground_animator.h" #import "ios/chrome/browser/ui/fullscreen/fullscreen_scroll_end_animator.h" #import "ios/chrome/browser/ui/fullscreen/fullscreen_scroll_to_top_animator.h" #import "ios/chrome/browser/ui/image_util/image_util.h" @@ -784,6 +785,11 @@ [self addFullscreenAnimationsToAnimator:animator]; } +- (void)showToolbarForForgroundWithAnimator: + (FullscreenForegroundAnimator*)animator { + [self addFullscreenAnimationsToAnimator:animator]; +} + #pragma mark - FullscreenUIElement helpers - (void)addFullscreenAnimationsToAnimator:(FullscreenAnimator*)animator {
diff --git a/ios/chrome/browser/ui/tools_menu/tools_menu_configuration.mm b/ios/chrome/browser/ui/tools_menu/tools_menu_configuration.mm index 5a7d53ca..c884276 100644 --- a/ios/chrome/browser/ui/tools_menu/tools_menu_configuration.mm +++ b/ios/chrome/browser/ui/tools_menu/tools_menu_configuration.mm
@@ -39,11 +39,6 @@ return self; } -- (instancetype)init { - NOTREACHED(); - return nil; -} - - (UIEdgeInsets)toolsButtonInsets { return self.toolsMenuButton ? [self.toolsMenuButton imageEdgeInsets] : UIEdgeInsetsZero;
diff --git a/ios/chrome/browser/ui/util/text_region_mapper.mm b/ios/chrome/browser/ui/util/text_region_mapper.mm index bddc24ee..0ed2a40 100644 --- a/ios/chrome/browser/ui/util/text_region_mapper.mm +++ b/ios/chrome/browser/ui/util/text_region_mapper.mm
@@ -52,11 +52,6 @@ return self; } -- (instancetype)init { - NOTREACHED(); - return nil; -} - - (NSArray*)rectsForRange:(NSRange)range { NSRange framedRange = self.textFrame.framedRange; if (!range.length || range.location + range.length > framedRange.length)
diff --git a/ios/chrome/test/fakes/BUILD.gn b/ios/chrome/test/fakes/BUILD.gn index a849777..dcae7e9 100644 --- a/ios/chrome/test/fakes/BUILD.gn +++ b/ios/chrome/test/fakes/BUILD.gn
@@ -7,6 +7,8 @@ testonly = true sources = [ + "fake_contained_presenter.h", + "fake_contained_presenter.mm", "fake_download_manager_tab_helper_delegate.h", "fake_download_manager_tab_helper_delegate.mm", "fake_pass_kit_tab_helper_delegate.h", @@ -14,7 +16,9 @@ ] deps = [ + "//base", "//ios/chrome/browser/download", + "//ios/chrome/browser/ui/presenters", "//ios/web/public", "//ios/web/public/download", ]
diff --git a/ios/chrome/test/fakes/fake_contained_presenter.h b/ios/chrome/test/fakes/fake_contained_presenter.h new file mode 100644 index 0000000..f0b526fd --- /dev/null +++ b/ios/chrome/test/fakes/fake_contained_presenter.h
@@ -0,0 +1,18 @@ +// 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. + +#ifndef IOS_CHROME_TEST_FAKES_FAKE_CONTAINED_PRESENTER_H_ +#define IOS_CHROME_TEST_FAKES_FAKE_CONTAINED_PRESENTER_H_ + +#import <Foundation/Foundation.h> + +#import "ios/chrome/browser/ui/presenters/contained_presenter.h" + +// ContainedPresenter used for testing. +@interface FakeContainedPresenter : NSObject<ContainedPresenter> +// YES if |presentAnimated:| was called with YES. +@property(nonatomic, assign) BOOL lastPresentationWasAnimated; +@end + +#endif // IOS_CHROME_TEST_FAKES_FAKE_CONTAINED_PRESENTER_H_
diff --git a/ios/chrome/test/fakes/fake_contained_presenter.mm b/ios/chrome/test/fakes/fake_contained_presenter.mm new file mode 100644 index 0000000..d662b30 --- /dev/null +++ b/ios/chrome/test/fakes/fake_contained_presenter.mm
@@ -0,0 +1,46 @@ +// 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. + +#import "ios/chrome/test/fakes/fake_contained_presenter.h" + +#include "base/logging.h" +#import "ios/chrome/browser/ui/presenters/contained_presenter_delegate.h" + +#if !defined(__has_feature) || !__has_feature(objc_arc) +#error "This file requires ARC support." +#endif + +@implementation FakeContainedPresenter +@synthesize baseViewController = _baseViewController; +@synthesize presentedViewController = _presentedViewController; +@synthesize delegate = _delegate; +@synthesize lastPresentationWasAnimated = _lastPresentationWasAnimated; + +- (void)prepareForPresentation { + DCHECK(self.presentedViewController); + DCHECK(self.baseViewController); + + [self.baseViewController addChildViewController:self.presentedViewController]; + [self.baseViewController.view addSubview:self.presentedViewController.view]; + + [self.presentedViewController.view updateConstraints]; + [self.presentedViewController.view layoutIfNeeded]; + + [self.presentedViewController + didMoveToParentViewController:self.baseViewController]; +} + +- (void)presentAnimated:(BOOL)animated { + self.lastPresentationWasAnimated = animated; +} + +- (void)dismissAnimated:(BOOL)animated { + DCHECK(self.presentedViewController); + [self.presentedViewController willMoveToParentViewController:nil]; + [self.presentedViewController.view removeFromSuperview]; + [self.presentedViewController removeFromParentViewController]; + [self.delegate containedPresenterDidDismiss:self]; +} + +@end
diff --git a/ios/chrome/test/fakes/fake_download_manager_tab_helper_delegate.mm b/ios/chrome/test/fakes/fake_download_manager_tab_helper_delegate.mm index 2c7bd26..0ccecbe3 100644 --- a/ios/chrome/test/fakes/fake_download_manager_tab_helper_delegate.mm +++ b/ios/chrome/test/fakes/fake_download_manager_tab_helper_delegate.mm
@@ -18,8 +18,8 @@ - (void)downloadManagerTabHelper:(nonnull DownloadManagerTabHelper*)tabHelper didCreateDownload:(nonnull web::DownloadTask*)download - webStateIsVisible:(BOOL)vebStateIsVisible { - if (vebStateIsVisible) { + webStateIsVisible:(BOOL)webStateIsVisible { + if (webStateIsVisible) { _state = std::make_unique<web::DownloadTask::State>(download->GetState()); } }
diff --git a/ios/web/app/web_main_loop.h b/ios/web/app/web_main_loop.h index 89882be..c3d00be 100644 --- a/ios/web/app/web_main_loop.h +++ b/ios/web/app/web_main_loop.h
@@ -14,7 +14,6 @@ namespace base { class PowerMonitor; -class SystemMonitor; } // namespace base namespace web { @@ -72,7 +71,6 @@ // The MessageLoop and NetworkChangeNotifier are not owned by the WebMainLoop // but still need to be destroyed in correct order so use ScopedClosureRunner. base::ScopedClosureRunner destroy_message_loop_; - std::unique_ptr<base::SystemMonitor> system_monitor_; std::unique_ptr<base::PowerMonitor> power_monitor_; base::ScopedClosureRunner destroy_network_change_notifier_;
diff --git a/ios/web/app/web_main_loop.mm b/ios/web/app/web_main_loop.mm index 2ea239b..b5f96c7 100644 --- a/ios/web/app/web_main_loop.mm +++ b/ios/web/app/web_main_loop.mm
@@ -17,7 +17,6 @@ #include "base/power_monitor/power_monitor.h" #include "base/power_monitor/power_monitor_device_source.h" #include "base/process/process_metrics.h" -#include "base/system_monitor/system_monitor.h" #include "base/task_scheduler/scheduler_worker_pool_params.h" #include "base/task_scheduler/task_scheduler.h" #include "base/threading/sequenced_worker_pool.h" @@ -77,11 +76,8 @@ InitializeMainThread(); -#if 0 - // TODO(crbug.com/228014): SystemMonitor is not working properly on iOS. - system_monitor_.reset(new base::SystemMonitor); -#endif - // TODO(rohitrao): Do we need PowerMonitor on iOS, or can we get rid of it? + // TODO(crbug.com/807279): Do we need PowerMonitor on iOS, or can we get rid + // of it? std::unique_ptr<base::PowerMonitorSource> power_monitor_source( new base::PowerMonitorDeviceSource()); power_monitor_.reset(new base::PowerMonitor(std::move(power_monitor_source)));
diff --git a/ios/web/download/download_controller_impl.mm b/ios/web/download/download_controller_impl.mm index 38848fa..871dc6e 100644 --- a/ios/web/download/download_controller_impl.mm +++ b/ios/web/download/download_controller_impl.mm
@@ -7,7 +7,9 @@ #include "base/strings/sys_string_conversions.h" #include "ios/web/public/browser_state.h" #import "ios/web/public/download/download_controller_delegate.h" +#import "ios/web/public/web_client.h" #import "net/base/mac/url_conversions.h" +#include "net/http/http_request_headers.h" #if !defined(__has_feature) || !__has_feature(objc_arc) #error "This file requires ARC support." @@ -86,6 +88,13 @@ NSOperationQueue* delegate_queue) { NSURLSessionConfiguration* configuration = [NSURLSessionConfiguration backgroundSessionConfigurationWithIdentifier:identifier]; + + std::string user_agent = GetWebClient()->GetUserAgent(UserAgentType::MOBILE); + configuration.HTTPAdditionalHeaders = @{ + base::SysUTF8ToNSString(net::HttpRequestHeaders::kUserAgent) : + base::SysUTF8ToNSString(user_agent), + }; + return [NSURLSession sessionWithConfiguration:configuration delegate:delegate delegateQueue:delegate_queue];
diff --git a/ios/web/download/download_inttest.mm b/ios/web/download/download_inttest.mm index 88db63c..916c766 100644 --- a/ios/web/download/download_inttest.mm +++ b/ios/web/download/download_inttest.mm
@@ -12,8 +12,11 @@ #import "ios/web/public/navigation_manager.h" #include "ios/web/public/test/fakes/fake_download_controller_delegate.h" #import "ios/web/public/test/web_test_with_web_state.h" +#import "ios/web/public/web_client.h" #import "ios/web/public/web_state/web_state.h" +#include "net/http/http_request_headers.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" #include "net/url_request/url_fetcher_response_writer.h" @@ -35,10 +38,15 @@ std::unique_ptr<net::test_server::HttpResponse> GetDownloadResponse( const net::test_server::HttpRequest& request) { auto result = std::make_unique<net::test_server::BasicHttpResponse>(); - result->set_code(net::HTTP_OK); - result->set_content(kContent); - result->AddCustomHeader("Content-Type", kMimeType); - result->AddCustomHeader("Content-Disposition", kContentDisposition); + + std::string user_agent = + request.headers.at(net::HttpRequestHeaders::kUserAgent); + if (user_agent == GetWebClient()->GetUserAgent(UserAgentType::MOBILE)) { + result->set_code(net::HTTP_OK); + result->set_content(kContent); + result->AddCustomHeader("Content-Type", kMimeType); + result->AddCustomHeader("Content-Disposition", kContentDisposition); + } return result; }
diff --git a/ios/web/navigation/navigation_item_impl.mm b/ios/web/navigation/navigation_item_impl.mm index 649d350a..7a48b9e 100644 --- a/ios/web/navigation/navigation_item_impl.mm +++ b/ios/web/navigation/navigation_item_impl.mm
@@ -290,6 +290,9 @@ } void NavigationItemImpl::SetErrorRetryState(ErrorRetryState state) { + if (state == error_retry_state_) + return; + switch (state) { case ErrorRetryState::kNoNavigationError: DCHECK_EQ(ErrorRetryState::kRetryFailedNavigationItem,
diff --git a/ios/web/navigation/session_storage_builder.mm b/ios/web/navigation/session_storage_builder.mm index 795b14b3..05d7a5c 100644 --- a/ios/web/navigation/session_storage_builder.mm +++ b/ios/web/navigation/session_storage_builder.mm
@@ -43,7 +43,6 @@ ++index) { web::NavigationItemImpl* item = navigation_manager->GetNavigationItemImplAtIndex(index); - ; [item_storages addObject:item_storage_builder.BuildStorage(item)]; } session_storage.itemStorages = item_storages;
diff --git a/ios/web/navigation/wk_based_navigation_manager_impl.mm b/ios/web/navigation/wk_based_navigation_manager_impl.mm index 67f1fd6..ad4f896 100644 --- a/ios/web/navigation/wk_based_navigation_manager_impl.mm +++ b/ios/web/navigation/wk_based_navigation_manager_impl.mm
@@ -430,8 +430,8 @@ params.transition_type = ui::PAGE_TRANSITION_RELOAD; LoadURLWithParams(params); - GetPendingItemImpl()->SetVirtualURL( - items[last_committed_item_index]->GetVirtualURL()); + // This pending item will become the first item in the restored history. + GetPendingItemImpl()->SetVirtualURL(items[0]->GetVirtualURL()); } NavigationItemImpl* WKBasedNavigationManagerImpl::GetNavigationItemImplAtIndex(
diff --git a/ios/web/navigation/wk_based_navigation_manager_impl_unittest.mm b/ios/web/navigation/wk_based_navigation_manager_impl_unittest.mm index a8159a5..7193489 100644 --- a/ios/web/navigation/wk_based_navigation_manager_impl_unittest.mm +++ b/ios/web/navigation/wk_based_navigation_manager_impl_unittest.mm
@@ -579,7 +579,7 @@ items.push_back(std::move(item0)); items.push_back(std::move(item1)); - manager_->Restore(0 /* last_committed_item_index */, std::move(items)); + manager_->Restore(1 /* last_committed_item_index */, std::move(items)); NavigationItem* pending_item = manager_->GetPendingItem(); ASSERT_TRUE(pending_item != nullptr); @@ -592,7 +592,7 @@ net::GetValueForKeyInQuery(pending_url, kRestoreSessionSessionQueryKey, &session_json); EXPECT_EQ( - "{\"offset\":-1,\"titles\":[\"Test Website 0\",\"\"]," + "{\"offset\":0,\"titles\":[\"Test Website 0\",\"\"]," "\"urls\":[\"http://www.0.com/\",\"http://www.1.com/\"]}", session_json); }
diff --git a/ios/web/navigation/wk_based_restore_session_util.mm b/ios/web/navigation/wk_based_restore_session_util.mm index be5788b6..880b5d00 100644 --- a/ios/web/navigation/wk_based_restore_session_util.mm +++ b/ios/web/navigation/wk_based_restore_session_util.mm
@@ -8,7 +8,9 @@ #include "base/mac/bundle_locations.h" #include "base/strings/sys_string_conversions.h" #include "base/values.h" +#include "ios/web/navigation/placeholder_navigation_util.h" #import "ios/web/public/navigation_item.h" +#import "ios/web/public/web_client.h" #include "net/base/url_util.h" #include "url/url_constants.h" @@ -41,8 +43,13 @@ restored_urls.GetList().reserve(items.size()); restored_titles.GetList().reserve(items.size()); for (size_t index = 0; index < items.size(); index++) { - restored_urls.GetList().push_back( - base::Value(items[index]->GetURL().spec())); + GURL original_url = items[index]->GetURL(); + GURL restored_url = original_url; + if (web::GetWebClient()->IsAppSpecificURL(original_url)) { + restored_url = + placeholder_navigation_util::CreatePlaceholderUrlForUrl(original_url); + } + restored_urls.GetList().push_back(base::Value(restored_url.spec())); restored_titles.GetList().push_back(base::Value(items[index]->GetTitle())); } base::Value session(base::Value::Type::DICTIONARY);
diff --git a/ios/web/navigation/wk_based_restore_session_util_unittest.mm b/ios/web/navigation/wk_based_restore_session_util_unittest.mm index ebc6fd3..f49ad183 100644 --- a/ios/web/navigation/wk_based_restore_session_util_unittest.mm +++ b/ios/web/navigation/wk_based_restore_session_util_unittest.mm
@@ -9,6 +9,7 @@ #include "base/strings/utf_string_conversions.h" #import "ios/web/navigation/navigation_item_impl.h" +#include "ios/web/test/test_url_constants.h" #include "net/base/url_util.h" #include "testing/gtest/include/gtest/gtest.h" #include "testing/platform_test.h" @@ -23,10 +24,17 @@ item0->SetTitle(base::ASCIIToUTF16("Test Website 0")); auto item1 = std::make_unique<NavigationItemImpl>(); item1->SetURL(GURL("http://www.1.com")); + // Create an App-specific URL + auto item2 = std::make_unique<NavigationItemImpl>(); + GURL url2("http://webui"); + GURL::Replacements scheme_replacements; + scheme_replacements.SetSchemeStr(kTestWebUIScheme); + item2->SetURL(url2.ReplaceComponents(scheme_replacements)); std::vector<std::unique_ptr<NavigationItem>> items; items.push_back(std::move(item0)); items.push_back(std::move(item1)); + items.push_back(std::move(item2)); GURL restore_session_url = CreateRestoreSessionUrl(0 /* last_committed_item_index */, items); @@ -36,8 +44,9 @@ net::GetValueForKeyInQuery(restore_session_url, kRestoreSessionSessionQueryKey, &session_json); EXPECT_EQ( - "{\"offset\":-1,\"titles\":[\"Test Website 0\",\"\"]," - "\"urls\":[\"http://www.0.com/\",\"http://www.1.com/\"]}", + "{\"offset\":-2,\"titles\":[\"Test Website 0\",\"\",\"\"]," + "\"urls\":[\"http://www.0.com/\",\"http://www.1.com/\"," + "\"about:blank?for=testwebui%3A%2F%2Fwebui%2F\"]}", session_json); }
diff --git a/ios/web/net/crw_cert_verification_controller.mm b/ios/web/net/crw_cert_verification_controller.mm index 86bc9b9..76f37ff0 100644 --- a/ios/web/net/crw_cert_verification_controller.mm +++ b/ios/web/net/crw_cert_verification_controller.mm
@@ -63,11 +63,6 @@ #pragma mark - Public -- (instancetype)init { - NOTREACHED(); - return nil; -} - - (instancetype)initWithBrowserState:(web::BrowserState*)browserState { DCHECK(browserState); DCHECK_CURRENTLY_ON(web::WebThread::UI);
diff --git a/ios/web/public/test/fakes/test_web_client.h b/ios/web/public/test/fakes/test_web_client.h index f82b5cd..c0004f0 100644 --- a/ios/web/public/test/fakes/test_web_client.h +++ b/ios/web/public/test/fakes/test_web_client.h
@@ -27,6 +27,7 @@ void AddAdditionalSchemes(Schemes* schemes) const override; // Returns true for kTestWebUIScheme and kTestNativeContentScheme URL schemes. bool IsAppSpecificURL(const GURL& url) const override; + std::string GetUserAgent(UserAgentType type) const override; base::RefCountedMemory* GetDataResourceBytes(int id) const override; NSString* GetDocumentStartScriptForMainFrame( BrowserState* browser_state) const override;
diff --git a/ios/web/public/test/fakes/test_web_client.mm b/ios/web/public/test/fakes/test_web_client.mm index 0aff96a..da5e4023 100644 --- a/ios/web/public/test/fakes/test_web_client.mm +++ b/ios/web/public/test/fakes/test_web_client.mm
@@ -31,6 +31,10 @@ url.SchemeIs(kTestNativeContentScheme); } +std::string TestWebClient::GetUserAgent(UserAgentType type) const { + return "Chromium/66.0.3333.0 CFNetwork/893.14 Darwin/16.7.0"; +} + base::RefCountedMemory* TestWebClient::GetDataResourceBytes( int resource_id) const { if (!ui::ResourceBundle::HasSharedInstance())
diff --git a/ios/web/public/web_state/ui/crw_web_view_scroll_view_proxy.h b/ios/web/public/web_state/ui/crw_web_view_scroll_view_proxy.h index e3605b2..4c131d5 100644 --- a/ios/web/public/web_state/ui/crw_web_view_scroll_view_proxy.h +++ b/ios/web/public/web_state/ui/crw_web_view_scroll_view_proxy.h
@@ -35,6 +35,7 @@ @property(nonatomic, getter=isScrollEnabled) BOOL scrollEnabled; @property(nonatomic, assign) BOOL bounces; @property(nonatomic, assign) BOOL scrollsToTop; +@property(nonatomic, assign) BOOL clipsToBounds; @property(nonatomic, assign) UIScrollViewContentInsetAdjustmentBehavior contentInsetAdjustmentBehavior API_AVAILABLE(ios(11.0));
diff --git a/ios/web/web_state/crw_pass_kit_downloader.mm b/ios/web/web_state/crw_pass_kit_downloader.mm index 779e70f..61469f8d 100644 --- a/ios/web/web_state/crw_pass_kit_downloader.mm +++ b/ios/web/web_state/crw_pass_kit_downloader.mm
@@ -111,11 +111,6 @@ return self; } -- (instancetype)init { - NOTREACHED(); - return nil; -} - - (BOOL)isMIMETypePassKitType:(NSString*)MIMEType { return [MIMEType isEqualToString:@"application/vnd.apple.pkpass"]; }
diff --git a/ios/web/web_state/favicon_callbacks_inttest.mm b/ios/web/web_state/favicon_callbacks_inttest.mm index c3314107..9ca1d549 100644 --- a/ios/web/web_state/favicon_callbacks_inttest.mm +++ b/ios/web/web_state/favicon_callbacks_inttest.mm
@@ -161,6 +161,24 @@ ASSERT_TRUE(favicons[0].icon_sizes.empty()); }; +// Tests page without favicon link but with a query and a ref in the URL. +TEST_F(FaviconCallbackTest, NoFaviconWithQuery) { + ASSERT_TRUE(observer()->favicon_url_candidates().empty()); + LoadHtml(@"<html></html>", + GURL("https://chromium.test/test/test.html?q1#h1")); + + WaitForCondition(^{ + return observer()->favicon_url_updated(); + }); + + const std::vector<FaviconURL>& favicons = + observer()->favicon_url_candidates(); + ASSERT_EQ(1U, favicons.size()); + EXPECT_EQ(GURL("https://chromium.test/favicon.ico"), favicons[0].icon_url); + EXPECT_EQ(FaviconURL::IconType::kFavicon, favicons[0].icon_type); + ASSERT_TRUE(favicons[0].icon_sizes.empty()); +}; + // Tests page with multiple favicon links. TEST_F(FaviconCallbackTest, MultipleFavicons) { ASSERT_TRUE(observer()->favicon_url_candidates().empty());
diff --git a/ios/web/web_state/js/crw_js_injection_receiver.mm b/ios/web/web_state/js/crw_js_injection_receiver.mm index 532a98f..75e27b8 100644 --- a/ios/web/web_state/js/crw_js_injection_receiver.mm +++ b/ios/web/web_state/js/crw_js_injection_receiver.mm
@@ -21,11 +21,6 @@ NSMutableDictionary* _managers; } -- (id)init { - NOTREACHED(); - return [super init]; -} - - (id)initWithEvaluator:(id<CRWJSInjectionEvaluator>)evaluator { DCHECK(evaluator); self = [super init];
diff --git a/ios/web/web_state/ui/crw_web_controller.mm b/ios/web/web_state/ui/crw_web_controller.mm index 7e42fa2..1343cdc 100644 --- a/ios/web/web_state/ui/crw_web_controller.mm +++ b/ios/web/web_state/ui/crw_web_controller.mm
@@ -43,6 +43,7 @@ #import "ios/web/navigation/navigation_manager_impl.h" #include "ios/web/navigation/navigation_manager_util.h" #include "ios/web/navigation/placeholder_navigation_util.h" +#include "ios/web/navigation/wk_based_restore_session_util.h" #include "ios/web/net/cert_host_pair.h" #import "ios/web/net/crw_cert_verification_controller.h" #import "ios/web/net/crw_ssl_status_updater.h" @@ -1185,13 +1186,15 @@ - (GURL)currentURLWithTrustLevel:(web::URLVerificationTrustLevel*)trustLevel { DCHECK(trustLevel) << "Verification of the trustLevel state is mandatory"; - // The web view URL is the current URL only if it is not a placeholder URL. - // In case of a placeholder navigation, the visible URL is the app-specific - // one in the native controller. + // The web view URL is the current URL only if it is neither a placeholder URL + // (used to hold WKBackForwardListItem for WebUI and Native Content views) nor + // a restore_session.html (used to replay session history in WKWebView). // TODO(crbug.com/738020): Investigate if this method is still needed and if // it can be implemented using NavigationManager API after removal of legacy // navigation stack. - if (_webView && !IsPlaceholderUrl(net::GURLWithNSURL(_webView.URL))) { + GURL webViewURL = net::GURLWithNSURL(_webView.URL); + if (_webView && !IsPlaceholderUrl(webViewURL) && + !web::IsRestoreSessionUrl(webViewURL)) { return [self webURLWithTrustLevel:trustLevel]; } // Any non-web URL source is trusted. @@ -1632,8 +1635,7 @@ - (NSMutableURLRequest*)requestForCurrentNavigationItem { web::NavigationItem* item = self.currentNavItem; - const GURL currentNavigationURL = - item ? item->GetVirtualURL() : GURL::EmptyGURL(); + const GURL currentNavigationURL = item ? item->GetURL() : GURL::EmptyGURL(); NSMutableURLRequest* request = [NSMutableURLRequest requestWithURL:net::NSURLWithGURL(currentNavigationURL)]; const web::Referrer referrer(self.currentNavItemReferrer); @@ -2459,6 +2461,8 @@ if (originGURL.is_valid() && originGURL.SchemeIsHTTPOrHTTPS()) { GURL::Replacements replacements; replacements.SetPathStr("/favicon.ico"); + replacements.ClearQuery(); + replacements.ClearRef(); urls.push_back(web::FaviconURL( originGURL.ReplaceComponents(replacements), web::FaviconURL::IconType::kFavicon, std::vector<gfx::Size>())); @@ -4646,10 +4650,17 @@ web::ErrorRetryState errorRetryState = item->GetErrorRetryState(); if (IsPlaceholderUrl(webViewURL)) { - // The |didFinishNavigation| callback can arrive after another - // navigation has started. Abort in this case. - if (CreatePlaceholderUrlForUrl(item->GetVirtualURL()) != webViewURL) + GURL originalURL = ExtractUrlFromPlaceholderUrl(webViewURL); + if (item->GetURL() == webViewURL) { + // Current navigation item is restored from a placeholder URL as part + // of session restoration. It is now safe to update the navigation + // item URL to the original app-specific URL. + item->SetURL(originalURL); + } else if (item->GetURL() != originalURL) { + // The |didFinishNavigation| callback can arrive after another + // navigation has started. Abort in this case. return; + } const bool isWebUIURL = web::GetWebClient()->IsAppSpecificURL(item->GetURL()) &&
diff --git a/ios/web/web_state/ui/crw_web_view_scroll_view_proxy.mm b/ios/web/web_state/ui/crw_web_view_scroll_view_proxy.mm index 31f1b96..b6be344 100644 --- a/ios/web/web_state/ui/crw_web_view_scroll_view_proxy.mm +++ b/ios/web/web_state/ui/crw_web_view_scroll_view_proxy.mm
@@ -21,6 +21,7 @@ id _observers; std::unique_ptr<UIScrollViewContentInsetAdjustmentBehavior> _pendingContentInsetAdjustmentBehavior API_AVAILABLE(ios(11.0)); + std::unique_ptr<BOOL> _pendingClipsToBounds; } // Returns the key paths that need to be observed for UIScrollView. @@ -73,6 +74,10 @@ scrollView.delegate = self; [self startObservingScrollView:scrollView]; _scrollView = scrollView; + if (_pendingClipsToBounds) { + scrollView.clipsToBounds = *_pendingClipsToBounds; + _pendingClipsToBounds.reset(); + } // Assigns |contentInsetAdjustmentBehavior| which was set before setting the // scroll view. @@ -107,6 +112,21 @@ [_scrollView setBounces:bounces]; } +- (BOOL)clipsToBounds { + if (_pendingClipsToBounds) { + return *_pendingClipsToBounds; + } + return _scrollView.clipsToBounds; +} + +- (void)setClipsToBounds:(BOOL)clipsToBounds { + if (_scrollView) { + _scrollView.clipsToBounds = clipsToBounds; + } else { + _pendingClipsToBounds = std::make_unique<BOOL>(clipsToBounds); + } +} + - (BOOL)isDecelerating { return [_scrollView isDecelerating]; }
diff --git a/ios/web/web_state/ui/crw_web_view_scroll_view_proxy_unittest.mm b/ios/web/web_state/ui/crw_web_view_scroll_view_proxy_unittest.mm index 127571d..60f14e9 100644 --- a/ios/web/web_state/ui/crw_web_view_scroll_view_proxy_unittest.mm +++ b/ios/web/web_state/ui/crw_web_view_scroll_view_proxy_unittest.mm
@@ -143,6 +143,10 @@ EXPECT_EQ(UIScrollViewContentInsetAdjustmentNever, [webViewScrollViewProxy_ contentInsetAdjustmentBehavior]); } + [[[mockScrollView_ expect] andReturnValue:@(NO)] clipsToBounds]; + EXPECT_FALSE([webViewScrollViewProxy_ clipsToBounds]); + [[[mockScrollView_ expect] andReturnValue:@(YES)] clipsToBounds]; + EXPECT_TRUE([webViewScrollViewProxy_ clipsToBounds]); } // Tests that CRWWebViewScrollViewProxy returns the correct property values when @@ -168,6 +172,7 @@ EXPECT_EQ(UIScrollViewContentInsetAdjustmentAutomatic, [webViewScrollViewProxy_ contentInsetAdjustmentBehavior]); } + EXPECT_FALSE([webViewScrollViewProxy_ clipsToBounds]); // Make sure setting the properties is fine too. // Arbitrary point. @@ -244,4 +249,16 @@ } } +// Tests that -setClipsToBounds: works even if it is called before setting the +// scroll view. +TEST_F(CRWWebViewScrollViewProxyTest, SetClipsToBoundsBeforeSettingScrollView) { + [[mockScrollView_ expect] setClipsToBounds:YES]; + + [webViewScrollViewProxy_ setScrollView:nil]; + [webViewScrollViewProxy_ setClipsToBounds:YES]; + [webViewScrollViewProxy_ setScrollView:mockScrollView_]; + + [mockScrollView_ verify]; +} + } // namespace
diff --git a/ios/web/web_state/ui/crw_wk_script_message_router.mm b/ios/web/web_state/ui/crw_wk_script_message_router.mm index e1836872..ac9fbe8 100644 --- a/ios/web/web_state/ui/crw_wk_script_message_router.mm +++ b/ios/web/web_state/ui/crw_wk_script_message_router.mm
@@ -33,11 +33,6 @@ return _userContentController; } -- (instancetype)init { - NOTREACHED(); - return nil; -} - - (instancetype)initWithUserContentController: (WKUserContentController*)userContentController { DCHECK(userContentController);
diff --git a/ios/web/webui/crw_web_ui_manager.mm b/ios/web/webui/crw_web_ui_manager.mm index 1ffdd745..0bbd108 100644 --- a/ios/web/webui/crw_web_ui_manager.mm +++ b/ios/web/webui/crw_web_ui_manager.mm
@@ -65,11 +65,6 @@ web::WebStateImpl* _webState; } -- (instancetype)init { - NOTREACHED(); - return self; -} - - (instancetype)initWithWebState:(web::WebStateImpl*)webState { if (self = [super init]) { DCHECK(webState);
diff --git a/ios/web/webui/crw_web_ui_page_builder.mm b/ios/web/webui/crw_web_ui_page_builder.mm index 6533cb3..fdca2bb9 100644 --- a/ios/web/webui/crw_web_ui_page_builder.mm +++ b/ios/web/webui/crw_web_ui_page_builder.mm
@@ -99,11 +99,6 @@ #pragma mark - Public Methods -- (instancetype)init { - NOTREACHED(); - return self; -} - - (instancetype)initWithDelegate:(id<CRWWebUIPageBuilderDelegate>)delegate { if (self = [super init]) { _delegate = delegate;
diff --git a/ios/web_view/internal/signin/web_view_signin_manager_factory.mm b/ios/web_view/internal/signin/web_view_signin_manager_factory.mm index de59957..b2472e8 100644 --- a/ios/web_view/internal/signin/web_view_signin_manager_factory.mm +++ b/ios/web_view/internal/signin/web_view_signin_manager_factory.mm
@@ -11,6 +11,7 @@ #include "components/keyed_service/ios/browser_state_dependency_manager.h" #include "components/pref_registry/pref_registry_syncable.h" #include "components/prefs/pref_registry_simple.h" +#include "components/signin/core/browser/profile_management_switches.h" #include "components/signin/core/browser/signin_manager.h" #include "components/signin/core/browser/signin_pref_names.h" #include "ios/web_view/internal/app/application_context.h" @@ -73,7 +74,8 @@ WebViewOAuth2TokenServiceFactory::GetForBrowserState(browser_state), WebViewAccountTrackerServiceFactory::GetForBrowserState(browser_state), WebViewGaiaCookieManagerServiceFactory::GetForBrowserState(browser_state), - WebViewSigninErrorControllerFactory::GetForBrowserState(browser_state)); + WebViewSigninErrorControllerFactory::GetForBrowserState(browser_state), + signin::AccountConsistencyMethod::kMirror); service->Initialize(ApplicationContext::GetInstance()->GetLocalState()); return service; }
diff --git a/media/OWNERS b/media/OWNERS index 4474165..8dc8852 100644 --- a/media/OWNERS +++ b/media/OWNERS
@@ -21,4 +21,8 @@ # For Fuchsia-specific changes: per-file *_fuchsia*=file://build/fuchsia/OWNERS +# For GpuMemoryBuffer-related changes: +per-file *gpu_memory_buffer*=dcastagna@chromium.org +per-file *gpu_memory_buffer*=reveman@chromium.org + # COMPONENT: Internals>Media
diff --git a/media/audio/win/core_audio_util_win.cc b/media/audio/win/core_audio_util_win.cc index d8a20c84..5541849 100644 --- a/media/audio/win/core_audio_util_win.cc +++ b/media/audio/win/core_audio_util_win.cc
@@ -672,7 +672,8 @@ return hr; size_t bytes = sizeof(WAVEFORMATEX) + format_pcmex->Format.cbSize; - DCHECK_EQ(bytes, sizeof(WAVEFORMATPCMEX)); + DCHECK_EQ(bytes, sizeof(WAVEFORMATPCMEX)) + << "Format tag: 0x" << std::hex << format_pcmex->Format.wFormatTag; memcpy(format, format_pcmex, bytes); DVLOG(2) << *format;
diff --git a/media/filters/demuxer_perftest.cc b/media/filters/demuxer_perftest.cc index d48a2e4..a216a3d 100644 --- a/media/filters/demuxer_perftest.cc +++ b/media/filters/demuxer_perftest.cc
@@ -216,24 +216,24 @@ "runs/s", true); } -#if defined(OS_WIN) -// http://crbug.com/399002 -#define MAYBE_Demuxer DISABLED_Demuxer -#else -#define MAYBE_Demuxer Demuxer -#endif -TEST(DemuxerPerfTest, MAYBE_Demuxer) { - RunDemuxerBenchmark("bear.ogv"); - RunDemuxerBenchmark("bear-640x360.webm"); - RunDemuxerBenchmark("sfx_s16le.wav"); - RunDemuxerBenchmark("bear.flac"); -#if BUILDFLAG(USE_PROPRIETARY_CODECS) - RunDemuxerBenchmark("bear-1280x720.mp4"); - RunDemuxerBenchmark("sfx.mp3"); -#endif -#if BUILDFLAG(USE_PROPRIETARY_CODECS) && defined(OS_CHROMEOS) - RunDemuxerBenchmark("bear.avi"); -#endif +class DemuxerPerfTest : public testing::TestWithParam<const char*> {}; + +TEST_P(DemuxerPerfTest, Demuxer) { + RunDemuxerBenchmark(GetParam()); } +static const char* kDemuxerTestFiles[] { + "bear.ogv", "bear-640x360.webm", "sfx.mp3", +#if BUILDFLAG(USE_PROPRIETARY_CODECS) + "bear-1280x720.mp4", +#endif +}; + +// For simplicity we only test containers with above 2% daily usage as measured +// by the Media.DetectedContainer histogram. +INSTANTIATE_TEST_CASE_P( + /* no prefix */, + DemuxerPerfTest, + testing::ValuesIn(kDemuxerTestFiles)); + } // namespace media
diff --git a/media/gpu/android/media_codec_video_decoder.cc b/media/gpu/android/media_codec_video_decoder.cc index 002d4fd..a8ba053 100644 --- a/media/gpu/android/media_codec_video_decoder.cc +++ b/media/gpu/android/media_codec_video_decoder.cc
@@ -357,8 +357,10 @@ } // Reset the target bundle if it is the one being destroyed. - if (target_surface_bundle_->overlay.get() == overlay) + if (target_surface_bundle_ && + target_surface_bundle_->overlay.get() == overlay) { target_surface_bundle_ = surface_texture_bundle_; + } // Transition the codec away from the overlay if necessary. if (SurfaceTransitionPending())
diff --git a/media/test/pipeline_integration_perftest.cc b/media/test/pipeline_integration_perftest.cc index 2ad62fc..648d2517 100644 --- a/media/test/pipeline_integration_perftest.cc +++ b/media/test/pipeline_integration_perftest.cc
@@ -38,12 +38,8 @@ } } - perf_test::PrintResult(name, - "", - filename, - iterations / time_seconds, - "runs/s", - true); + perf_test::PrintResult(name, "", filename, iterations / time_seconds, + "runs/s", true); } static void RunVideoPlaybackBenchmark(const std::string& filename, @@ -56,18 +52,27 @@ RunPlaybackBenchmark(filename, name, kBenchmarkIterationsAudio, true); } -TEST(PipelineIntegrationPerfTest, AudioPlaybackBenchmark) { - RunAudioPlaybackBenchmark("sfx_f32le.wav", "clockless_playback"); - RunAudioPlaybackBenchmark("sfx_s24le.wav", "clockless_playback"); - RunAudioPlaybackBenchmark("sfx_s16le.wav", "clockless_playback"); - RunAudioPlaybackBenchmark("sfx_u8.wav", "clockless_playback"); - RunAudioPlaybackBenchmark("sfx.flac", "clockless_playback"); -#if BUILDFLAG(USE_PROPRIETARY_CODECS) - RunAudioPlaybackBenchmark("sfx.mp3", "clockless_playback"); - RunAudioPlaybackBenchmark("sfx-flac.mp4", "clockless_playback"); -#endif +class ClocklessAudioPipelineIntegrationPerfTest + : public testing::TestWithParam<const char*> {}; + +TEST_P(ClocklessAudioPipelineIntegrationPerfTest, PlaybackBenchmark) { + RunAudioPlaybackBenchmark(GetParam(), "clockless_playback"); } +static const char* kAudioTestFiles[] { + "sfx_s16le.wav", "sfx.ogg", "sfx.mp3", +#if BUILDFLAG(USE_PROPRIETARY_CODECS) + "sfx.m4a", +#endif +}; + +// For simplicity we only test codecs with above 2% daily usage as measured by +// the Media.AudioCodec histogram. +INSTANTIATE_TEST_CASE_P( + /* no prefix */, + ClocklessAudioPipelineIntegrationPerfTest, + testing::ValuesIn(kAudioTestFiles)); + TEST(PipelineIntegrationPerfTest, VP8PlaybackBenchmark) { RunVideoPlaybackBenchmark("bear_silent.webm", "clockless_video_playback_vp8"); } @@ -76,16 +81,7 @@ RunVideoPlaybackBenchmark("bear-vp9.webm", "clockless_video_playback_vp9"); } -// Android doesn't build Theora support. -#if !defined(OS_ANDROID) -TEST(PipelineIntegrationPerfTest, TheoraPlaybackBenchmark) { - RunVideoPlaybackBenchmark("bear_silent.ogv", - "clockless_video_playback_theora"); -} -#endif - -// PipelineIntegrationTests can't play h264 content. -#if BUILDFLAG(USE_PROPRIETARY_CODECS) && !defined(OS_ANDROID) +#if BUILDFLAG(USE_PROPRIETARY_CODECS) && BUILDFLAG(ENABLE_FFMPEG_VIDEO_DECODERS) TEST(PipelineIntegrationPerfTest, MP4PlaybackBenchmark) { RunVideoPlaybackBenchmark("bear_silent.mp4", "clockless_video_playback_mp4"); }
diff --git a/mojo/public/cpp/base/BUILD.gn b/mojo/public/cpp/base/BUILD.gn index ac71e08..ff1386b 100644 --- a/mojo/public/cpp/base/BUILD.gn +++ b/mojo/public/cpp/base/BUILD.gn
@@ -41,15 +41,29 @@ ] } +source_set("mojom_traits") { + sources = [ + "big_string_mojom_traits.cc", + "big_string_mojom_traits.h", + ] + deps = [ + ":base", + ":shared_typemap_traits", + "//mojo/public/mojom/base", + ] +} + source_set("tests") { testonly = true sources = [ "big_buffer_unittest.cc", + "big_string_unittest.cc", ] public_deps = [ ":base", + ":mojom_traits", ":shared_typemap_traits", "//base", "//mojo/public/cpp/test_support:test_utils",
diff --git a/mojo/public/cpp/base/OWNERS b/mojo/public/cpp/base/OWNERS index 868378c..7826f8c 100644 --- a/mojo/public/cpp/base/OWNERS +++ b/mojo/public/cpp/base/OWNERS
@@ -1,4 +1,6 @@ per-file *.typemap=set noparent per-file *.typemap=file://ipc/SECURITY_OWNERS +per-file *_mojom_traits*.*=set noparent +per-file *_mojom_traits*.*=file://ipc/SECURITY_OWNERS per-file *_struct_traits*.*=set noparent per-file *_struct_traits*.*=file://ipc/SECURITY_OWNERS
diff --git a/mojo/public/cpp/base/big_string.typemap b/mojo/public/cpp/base/big_string.typemap new file mode 100644 index 0000000..3f5f954 --- /dev/null +++ b/mojo/public/cpp/base/big_string.typemap
@@ -0,0 +1,12 @@ +# 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. + +mojom = "//mojo/public/mojom/base/big_string.mojom" +public_headers = [] +traits_headers = [ "//mojo/public/cpp/base/big_string_mojom_traits.h" ] +public_deps = [ + "//mojo/public/cpp/base", + "//mojo/public/cpp/base:shared_typemap_traits", +] +type_mappings = [ "mojo_base.mojom.BigString=std::string" ]
diff --git a/mojo/public/cpp/base/big_string_mojom_traits.cc b/mojo/public/cpp/base/big_string_mojom_traits.cc new file mode 100644 index 0000000..436ab60 --- /dev/null +++ b/mojo/public/cpp/base/big_string_mojom_traits.cc
@@ -0,0 +1,33 @@ +// 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 "mojo/public/cpp/base/big_string_mojom_traits.h" + +#include "mojo/public/cpp/base/big_buffer_struct_traits.h" + +namespace mojo { + +// static +mojo_base::BigBuffer StructTraits<mojo_base::mojom::BigStringDataView, + std::string>::data(const std::string& str) { + const auto* bytes = reinterpret_cast<const uint8_t*>(str.data()); + return mojo_base::BigBuffer( + base::make_span(bytes, str.size() * sizeof(char))); +} + +// static +bool StructTraits<mojo_base::mojom::BigStringDataView, std::string>::Read( + mojo_base::mojom::BigStringDataView data, + std::string* out) { + mojo_base::BigBuffer buffer; + if (!data.ReadData(&buffer)) + return false; + if (buffer.size() % sizeof(char)) + return false; + *out = std::string(reinterpret_cast<const char*>(buffer.data()), + buffer.size() / sizeof(char)); + return true; +} + +} // namespace mojo
diff --git a/mojo/public/cpp/base/big_string_mojom_traits.h b/mojo/public/cpp/base/big_string_mojom_traits.h new file mode 100644 index 0000000..74f1d553 --- /dev/null +++ b/mojo/public/cpp/base/big_string_mojom_traits.h
@@ -0,0 +1,25 @@ +// 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. + +#ifndef MOJO_PUBLIC_CPP_BASE_BIG_STRING_MOJOM_TRAITS_H_ +#define MOJO_PUBLIC_CPP_BASE_BIG_STRING_MOJOM_TRAITS_H_ + +#include <string> + +#include "mojo/public/cpp/base/big_buffer.h" +#include "mojo/public/cpp/bindings/struct_traits.h" +#include "mojo/public/mojom/base/big_string.mojom-shared.h" + +namespace mojo { + +template <> +struct StructTraits<mojo_base::mojom::BigStringDataView, std::string> { + static mojo_base::BigBuffer data(const std::string& str); + + static bool Read(mojo_base::mojom::BigStringDataView data, std::string* out); +}; + +} // namespace mojo + +#endif // MOJO_PUBLIC_CPP_BASE_BIG_STRING_MOJOM_TRAITS_H_
diff --git a/mojo/public/cpp/base/big_string_unittest.cc b/mojo/public/cpp/base/big_string_unittest.cc new file mode 100644 index 0000000..7d28b30 --- /dev/null +++ b/mojo/public/cpp/base/big_string_unittest.cc
@@ -0,0 +1,43 @@ +// 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 <string> + +#include "base/rand_util.h" +#include "mojo/public/cpp/base/big_buffer_struct_traits.h" +#include "mojo/public/cpp/base/big_string_mojom_traits.h" +#include "mojo/public/cpp/test_support/test_utils.h" +#include "mojo/public/mojom/base/big_string.mojom.h" +#include "testing/gtest/include/gtest/gtest.h" + +namespace mojo_base { +namespace big_string_unittest { + +TEST(BigStringTest, Empty) { + std::string in; + std::string out; + ASSERT_TRUE(mojo::test::SerializeAndDeserialize<mojom::BigString>(&in, &out)); + EXPECT_EQ(in, out); +} + +TEST(BigStringTest, Short) { + std::string in("hello world"); + std::string out; + ASSERT_TRUE(mojo::test::SerializeAndDeserialize<mojom::BigString>(&in, &out)); + EXPECT_EQ(in, out); +} + +TEST(BigStringTest, Long) { + constexpr size_t kLargeStringSize = 1024 * 1024; + + std::string in(kLargeStringSize, 0); + base::RandBytes(&in[0], kLargeStringSize); + + std::string out; + ASSERT_TRUE(mojo::test::SerializeAndDeserialize<mojom::BigString>(&in, &out)); + EXPECT_EQ(in, out); +} + +} // namespace big_string_unittest +} // namespace mojo_base
diff --git a/mojo/public/cpp/base/typemaps.gni b/mojo/public/cpp/base/typemaps.gni index 0b0f97b0..824f457d 100644 --- a/mojo/public/cpp/base/typemaps.gni +++ b/mojo/public/cpp/base/typemaps.gni
@@ -2,4 +2,7 @@ # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. -typemaps = [ "//mojo/public/cpp/base/big_buffer.typemap" ] +typemaps = [ + "//mojo/public/cpp/base/big_buffer.typemap", + "//mojo/public/cpp/base/big_string.typemap", +]
diff --git a/mojo/public/mojom/base/BUILD.gn b/mojo/public/mojom/base/BUILD.gn index 94ed346e..a64401c 100644 --- a/mojo/public/mojom/base/BUILD.gn +++ b/mojo/public/mojom/base/BUILD.gn
@@ -7,6 +7,7 @@ mojom_component("base") { sources = [ "big_buffer.mojom", + "big_string.mojom", ] output_prefix = "mojo_base_mojom"
diff --git a/mojo/public/mojom/base/big_string.mojom b/mojo/public/mojom/base/big_string.mojom new file mode 100644 index 0000000..c971caf --- /dev/null +++ b/mojo/public/mojom/base/big_string.mojom
@@ -0,0 +1,19 @@ +// 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. + +module mojo_base.mojom; + +import "mojo/public/mojom/base/big_buffer.mojom"; + +// Corresponds to |std::string| in <string>. +// Corresponds to |WTF::String| in +// third_party/WebKit/Source/platform/wtf/text/WTFString.h. +// This type should be used in place of string whenever the contents of the +// string may realistically exceed 64 kB in size. This string is safe to store +// an arbitrarily large amount of data (available memory permitting) without +// negatively impacting IPC performance or hitting hard message size +// boundaries. +struct BigString { + mojo_base.mojom.BigBuffer data; +};
diff --git a/net/BUILD.gn b/net/BUILD.gn index dd99fa7..5a6e0c3 100644 --- a/net/BUILD.gn +++ b/net/BUILD.gn
@@ -108,6 +108,7 @@ "base/auth.cc", "base/auth.h", "base/completion_callback.h", + "base/completion_once_callback.h", "base/escape.cc", "base/escape.h", "base/hash_value.cc", @@ -1233,6 +1234,8 @@ "quic/core/crypto/quic_tls_adapter.h", "quic/core/crypto/scoped_evp_aead_ctx.cc", "quic/core/crypto/scoped_evp_aead_ctx.h", + "quic/core/crypto/transport_parameters.cc", + "quic/core/crypto/transport_parameters.h", "quic/core/frames/quic_ack_frame.cc", "quic/core/frames/quic_ack_frame.h", "quic/core/frames/quic_blocked_frame.cc", @@ -2608,6 +2611,8 @@ "test/channel_id_test_util.h", "test/ct_test_util.cc", "test/ct_test_util.h", + "test/embedded_test_server/controllable_http_response.cc", + "test/embedded_test_server/controllable_http_response.h", "test/embedded_test_server/default_handlers.cc", "test/embedded_test_server/default_handlers.h", "test/embedded_test_server/embedded_test_server.cc", @@ -5061,6 +5066,7 @@ "quic/core/crypto/quic_crypto_server_config_test.cc", "quic/core/crypto/quic_random_test.cc", "quic/core/crypto/quic_tls_adapter_test.cc", + "quic/core/crypto/transport_parameters_test.cc", "quic/core/frames/quic_frames_test.cc", "quic/core/packet_number_indexed_queue_test.cc", "quic/core/quic_alarm_test.cc", @@ -5623,6 +5629,7 @@ "proxy_resolution/proxy_resolver_v8_unittest.cc", "url_request/url_request_job_unittest.cc", ] + deps += [ "//url:url_java" ] } # Unit tests that are not supported by the current ICU alternatives on iOS.
diff --git a/net/base/completion_callback.h b/net/base/completion_callback.h index a41caa5..78658bd8 100644 --- a/net/base/completion_callback.h +++ b/net/base/completion_callback.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 NET_BASE_COMPLETION_CALLBACK_H__ -#define NET_BASE_COMPLETION_CALLBACK_H__ +#ifndef NET_BASE_COMPLETION_CALLBACK_H_ +#define NET_BASE_COMPLETION_CALLBACK_H_ #include <stdint.h> @@ -25,4 +25,4 @@ } // namespace net -#endif // NET_BASE_COMPLETION_CALLBACK_H__ +#endif // NET_BASE_COMPLETION_CALLBACK_H_
diff --git a/net/base/completion_once_callback.h b/net/base/completion_once_callback.h new file mode 100644 index 0000000..bfe4e7c7 --- /dev/null +++ b/net/base/completion_once_callback.h
@@ -0,0 +1,29 @@ +// 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. + +#ifndef NET_BASE_COMPLETION_ONCE_CALLBACK_H_ +#define NET_BASE_COMPLETION_ONCE_CALLBACK_H_ + +#include <stdint.h> + +#include "base/callback.h" +#include "base/cancelable_callback.h" + +namespace net { + +// A OnceCallback specialization that takes a single int parameter. Usually this +// is used to report a byte count or network error code. +typedef base::OnceCallback<void(int)> CompletionOnceCallback; + +// 64bit version of the OnceCallback specialization that takes a single int64_t +// parameter. Usually this is used to report a file offset, size or network +// error code. +typedef base::OnceCallback<void(int64_t)> Int64CompletionOnceCallback; + +typedef base::CancelableOnceCallback<void(int)> + CancelableCompletionOnceCallback; + +} // namespace net + +#endif // NET_BASE_COMPLETION_ONCE_CALLBACK_H_
diff --git a/net/base/file_stream.cc b/net/base/file_stream.cc index fe05146..038f60c 100644 --- a/net/base/file_stream.cc +++ b/net/base/file_stream.cc
@@ -22,20 +22,21 @@ context_.release()->Orphan(); } -int FileStream::Open(const base::FilePath& path, int open_flags, - const CompletionCallback& callback) { +int FileStream::Open(const base::FilePath& path, + int open_flags, + CompletionOnceCallback callback) { if (IsOpen()) { DLOG(FATAL) << "File is already open!"; return ERR_UNEXPECTED; } DCHECK(open_flags & base::File::FLAG_ASYNC); - context_->Open(path, open_flags, callback); + context_->Open(path, open_flags, std::move(callback)); return ERR_IO_PENDING; } -int FileStream::Close(const CompletionCallback& callback) { - context_->Close(callback); +int FileStream::Close(CompletionOnceCallback callback) { + context_->Close(std::move(callback)); return ERR_IO_PENDING; } @@ -43,50 +44,50 @@ return context_->IsOpen(); } -int FileStream::Seek(int64_t offset, const Int64CompletionCallback& callback) { +int FileStream::Seek(int64_t offset, Int64CompletionOnceCallback callback) { if (!IsOpen()) return ERR_UNEXPECTED; - context_->Seek(offset, callback); + context_->Seek(offset, std::move(callback)); return ERR_IO_PENDING; } int FileStream::Read(IOBuffer* buf, int buf_len, - const CompletionCallback& callback) { + CompletionOnceCallback callback) { if (!IsOpen()) return ERR_UNEXPECTED; // read(..., 0) will return 0, which indicates end-of-file. DCHECK_GT(buf_len, 0); - return context_->Read(buf, buf_len, callback); + return context_->Read(buf, buf_len, std::move(callback)); } int FileStream::Write(IOBuffer* buf, int buf_len, - const CompletionCallback& callback) { + CompletionOnceCallback callback) { if (!IsOpen()) return ERR_UNEXPECTED; DCHECK_GE(buf_len, 0); - return context_->Write(buf, buf_len, callback); + return context_->Write(buf, buf_len, std::move(callback)); } int FileStream::GetFileInfo(base::File::Info* file_info, - const CompletionCallback& callback) { + CompletionOnceCallback callback) { if (!IsOpen()) return ERR_UNEXPECTED; - context_->GetFileInfo(file_info, callback); + context_->GetFileInfo(file_info, std::move(callback)); return ERR_IO_PENDING; } -int FileStream::Flush(const CompletionCallback& callback) { +int FileStream::Flush(CompletionOnceCallback callback) { if (!IsOpen()) return ERR_UNEXPECTED; - context_->Flush(callback); + context_->Flush(std::move(callback)); return ERR_IO_PENDING; }
diff --git a/net/base/file_stream.h b/net/base/file_stream.h index 925f1250..501bc975 100644 --- a/net/base/file_stream.h +++ b/net/base/file_stream.h
@@ -16,7 +16,7 @@ #include "base/files/file.h" #include "base/macros.h" -#include "net/base/completion_callback.h" +#include "net/base/completion_once_callback.h" #include "net/base/net_export.h" namespace base { @@ -56,14 +56,15 @@ // automatically closed when FileStream is destructed in an asynchronous // manner (i.e. the file stream is closed in the background but you don't // know when). - virtual int Open(const base::FilePath& path, int open_flags, - const CompletionCallback& callback); + virtual int Open(const base::FilePath& path, + int open_flags, + CompletionOnceCallback callback); // Returns ERR_IO_PENDING and closes the file asynchronously, calling // |callback| when done. // It is invalid to request any asynchronous operations while there is an // in-flight asynchronous operation. - virtual int Close(const CompletionCallback& callback); + virtual int Close(CompletionOnceCallback callback); // Returns true if Open succeeded and Close has not been called. virtual bool IsOpen() const; @@ -74,7 +75,7 @@ // position relative to the start of the file. Otherwise, an error code is // returned. It is invalid to request any asynchronous operations while there // is an in-flight asynchronous operation. - virtual int Seek(int64_t offset, const Int64CompletionCallback& callback); + virtual int Seek(int64_t offset, Int64CompletionOnceCallback callback); // Call this method to read data from the current stream position // asynchronously. Up to buf_len bytes will be copied into buf. (In @@ -96,8 +97,7 @@ // in-flight asynchronous operation. // // This method must not be called if the stream was opened WRITE_ONLY. - virtual int Read(IOBuffer* buf, int buf_len, - const CompletionCallback& callback); + virtual int Read(IOBuffer* buf, int buf_len, CompletionOnceCallback callback); // Call this method to write data at the current stream position // asynchronously. Up to buf_len bytes will be written from buf. (In @@ -121,8 +121,9 @@ // This method must not be called if the stream was opened READ_ONLY. // // Zero byte writes are not allowed. - virtual int Write(IOBuffer* buf, int buf_len, - const CompletionCallback& callback); + virtual int Write(IOBuffer* buf, + int buf_len, + CompletionOnceCallback callback); // Gets status information about File. May fail synchronously, but never // succeeds synchronously. @@ -132,7 +133,7 @@ // // |file_info| must remain valid until |callback| is invoked. virtual int GetFileInfo(base::File::Info* file_info, - const CompletionCallback& callback); + CompletionOnceCallback callback); // Forces out a filesystem sync on this file to make sure that the file was // written out to disk and is not currently sitting in the buffer. This does @@ -153,7 +154,7 @@ // in-flight asynchronous operation. // // This method should not be called if the stream was opened READ_ONLY. - virtual int Flush(const CompletionCallback& callback); + virtual int Flush(CompletionOnceCallback callback); private: class Context;
diff --git a/net/base/file_stream_context.cc b/net/base/file_stream_context.cc index 9745e291..ecb497b0 100644 --- a/net/base/file_stream_context.cc +++ b/net/base/file_stream_context.cc
@@ -23,8 +23,8 @@ namespace { -void CallInt64ToInt(const CompletionCallback& callback, int64_t result) { - callback.Run(static_cast<int>(result)); +void CallInt64ToInt(CompletionOnceCallback callback, int64_t result) { + std::move(callback).Run(static_cast<int>(result)); } } // namespace @@ -81,30 +81,28 @@ void FileStream::Context::Open(const base::FilePath& path, int open_flags, - const CompletionCallback& callback) { + CompletionOnceCallback callback) { CheckNoAsyncInProgress(); bool posted = base::PostTaskAndReplyWithResult( - task_runner_.get(), - FROM_HERE, - base::Bind( - &Context::OpenFileImpl, base::Unretained(this), path, open_flags), - base::Bind(&Context::OnOpenCompleted, base::Unretained(this), callback)); + task_runner_.get(), FROM_HERE, + base::BindOnce(&Context::OpenFileImpl, base::Unretained(this), path, + open_flags), + base::BindOnce(&Context::OnOpenCompleted, base::Unretained(this), + std::move(callback))); DCHECK(posted); last_operation_ = OPEN; async_in_progress_ = true; } -void FileStream::Context::Close(const CompletionCallback& callback) { +void FileStream::Context::Close(CompletionOnceCallback callback) { CheckNoAsyncInProgress(); bool posted = base::PostTaskAndReplyWithResult( - task_runner_.get(), - FROM_HERE, - base::Bind(&Context::CloseFileImpl, base::Unretained(this)), - base::Bind(&Context::OnAsyncCompleted, - base::Unretained(this), - IntToInt64(callback))); + task_runner_.get(), FROM_HERE, + base::BindOnce(&Context::CloseFileImpl, base::Unretained(this)), + base::BindOnce(&Context::OnAsyncCompleted, base::Unretained(this), + IntToInt64(std::move(callback)))); DCHECK(posted); last_operation_ = CLOSE; @@ -112,13 +110,14 @@ } void FileStream::Context::Seek(int64_t offset, - const Int64CompletionCallback& callback) { + Int64CompletionOnceCallback callback) { CheckNoAsyncInProgress(); bool posted = base::PostTaskAndReplyWithResult( task_runner_.get(), FROM_HERE, - base::Bind(&Context::SeekFileImpl, base::Unretained(this), offset), - base::Bind(&Context::OnAsyncCompleted, base::Unretained(this), callback)); + base::BindOnce(&Context::SeekFileImpl, base::Unretained(this), offset), + base::BindOnce(&Context::OnAsyncCompleted, base::Unretained(this), + std::move(callback))); DCHECK(posted); last_operation_ = SEEK; @@ -126,29 +125,27 @@ } void FileStream::Context::GetFileInfo(base::File::Info* file_info, - const CompletionCallback& callback) { + CompletionOnceCallback callback) { CheckNoAsyncInProgress(); base::PostTaskAndReplyWithResult( task_runner_.get(), FROM_HERE, - base::Bind(&Context::GetFileInfoImpl, base::Unretained(this), - base::Unretained(file_info)), - base::Bind(&Context::OnAsyncCompleted, base::Unretained(this), - IntToInt64(callback))); + base::BindOnce(&Context::GetFileInfoImpl, base::Unretained(this), + base::Unretained(file_info)), + base::BindOnce(&Context::OnAsyncCompleted, base::Unretained(this), + IntToInt64(std::move(callback)))); async_in_progress_ = true; } -void FileStream::Context::Flush(const CompletionCallback& callback) { +void FileStream::Context::Flush(CompletionOnceCallback callback) { CheckNoAsyncInProgress(); bool posted = base::PostTaskAndReplyWithResult( - task_runner_.get(), - FROM_HERE, - base::Bind(&Context::FlushFileImpl, base::Unretained(this)), - base::Bind(&Context::OnAsyncCompleted, - base::Unretained(this), - IntToInt64(callback))); + task_runner_.get(), FROM_HERE, + base::BindOnce(&Context::FlushFileImpl, base::Unretained(this)), + base::BindOnce(&Context::OnAsyncCompleted, base::Unretained(this), + IntToInt64(std::move(callback)))); DCHECK(posted); last_operation_ = FLUSH; @@ -223,13 +220,13 @@ return IOResult::FromOSError(logging::GetLastSystemErrorCode()); } -void FileStream::Context::OnOpenCompleted(const CompletionCallback& callback, +void FileStream::Context::OnOpenCompleted(CompletionOnceCallback callback, OpenResult open_result) { file_ = std::move(open_result.file); if (file_.IsValid() && !orphaned_) OnFileOpened(); - OnAsyncCompleted(IntToInt64(callback), open_result.error_code); + OnAsyncCompleted(IntToInt64(std::move(callback)), open_result.error_code); } void FileStream::Context::CloseAndDelete() { @@ -240,31 +237,31 @@ if (file_.IsValid()) { bool posted = task_runner_.get()->PostTask( - FROM_HERE, base::Bind(base::IgnoreResult(&Context::CloseFileImpl), - base::Owned(this))); + FROM_HERE, base::BindOnce(base::IgnoreResult(&Context::CloseFileImpl), + base::Owned(this))); DCHECK(posted); } else { delete this; } } -Int64CompletionCallback FileStream::Context::IntToInt64( - const CompletionCallback& callback) { - return base::Bind(&CallInt64ToInt, callback); +Int64CompletionOnceCallback FileStream::Context::IntToInt64( + CompletionOnceCallback callback) { + return base::BindOnce(&CallInt64ToInt, std::move(callback)); } -void FileStream::Context::OnAsyncCompleted( - const Int64CompletionCallback& callback, - const IOResult& result) { +void FileStream::Context::OnAsyncCompleted(Int64CompletionOnceCallback callback, + const IOResult& result) { // Reset this before Run() as Run() may issue a new async operation. Also it // should be reset before Close() because it shouldn't run if any async // operation is in progress. async_in_progress_ = false; last_operation_ = NONE; - if (orphaned_) + if (orphaned_) { CloseAndDelete(); - else - callback.Run(result.result); + } else { + std::move(callback).Run(result.result); + } } } // namespace net
diff --git a/net/base/file_stream_context.h b/net/base/file_stream_context.h index 105cbd4..7a34aad 100644 --- a/net/base/file_stream_context.h +++ b/net/base/file_stream_context.h
@@ -35,7 +35,7 @@ #include "base/message_loop/message_loop.h" #include "base/single_thread_task_runner.h" #include "base/task_runner.h" -#include "net/base/completion_callback.h" +#include "net/base/completion_once_callback.h" #include "net/base/file_stream.h" #if defined(OS_POSIX) @@ -69,13 +69,9 @@ ~Context(); #endif - int Read(IOBuffer* buf, - int buf_len, - const CompletionCallback& callback); + int Read(IOBuffer* buf, int buf_len, CompletionOnceCallback callback); - int Write(IOBuffer* buf, - int buf_len, - const CompletionCallback& callback); + int Write(IOBuffer* buf, int buf_len, CompletionOnceCallback callback); bool async_in_progress() const { return async_in_progress_; } @@ -90,17 +86,17 @@ void Open(const base::FilePath& path, int open_flags, - const CompletionCallback& callback); + CompletionOnceCallback callback); - void Close(const CompletionCallback& callback); + void Close(CompletionOnceCallback callback); // Seeks |offset| bytes from the start of the file. - void Seek(int64_t offset, const Int64CompletionCallback& callback); + void Seek(int64_t offset, Int64CompletionOnceCallback callback); void GetFileInfo(base::File::Info* file_info, - const CompletionCallback& callback); + CompletionOnceCallback callback); - void Flush(const CompletionCallback& callback); + void Flush(CompletionOnceCallback callback); bool IsOpen() const; @@ -161,16 +157,15 @@ IOResult FlushFileImpl(); - void OnOpenCompleted(const CompletionCallback& callback, - OpenResult open_result); + void OnOpenCompleted(CompletionOnceCallback callback, OpenResult open_result); void CloseAndDelete(); - Int64CompletionCallback IntToInt64(const CompletionCallback& callback); + Int64CompletionOnceCallback IntToInt64(CompletionOnceCallback callback); // Called when Open() or Seek() completes. |result| contains the result or a // network error code. - void OnAsyncCompleted(const Int64CompletionCallback& callback, + void OnAsyncCompleted(Int64CompletionOnceCallback callback, const IOResult& result); //////////////////////////////////////////////////////////////////////////// @@ -184,7 +179,7 @@ void OnFileOpened(); #if defined(OS_WIN) - void IOCompletionIsPending(const CompletionCallback& callback, IOBuffer* buf); + void IOCompletionIsPending(CompletionOnceCallback callback, IOBuffer* buf); // Implementation of MessageLoopForIO::IOHandler. void OnIOCompleted(base::MessageLoopForIO::IOContext* context, @@ -252,7 +247,7 @@ #if defined(OS_WIN) base::MessageLoopForIO::IOContext io_context_; - CompletionCallback callback_; + CompletionOnceCallback callback_; scoped_refptr<IOBuffer> in_flight_buf_; // This flag is set to true when we receive a Read request which is queued to // the thread pool.
diff --git a/net/base/file_stream_context_posix.cc b/net/base/file_stream_context_posix.cc index 20dc04d..1880b95a 100644 --- a/net/base/file_stream_context_posix.cc +++ b/net/base/file_stream_context_posix.cc
@@ -39,17 +39,16 @@ int FileStream::Context::Read(IOBuffer* in_buf, int buf_len, - const CompletionCallback& callback) { + CompletionOnceCallback callback) { CheckNoAsyncInProgress(); scoped_refptr<IOBuffer> buf = in_buf; const bool posted = base::PostTaskAndReplyWithResult( - task_runner_.get(), - FROM_HERE, - base::Bind(&Context::ReadFileImpl, base::Unretained(this), buf, buf_len), - base::Bind(&Context::OnAsyncCompleted, - base::Unretained(this), - IntToInt64(callback))); + task_runner_.get(), FROM_HERE, + base::BindOnce(&Context::ReadFileImpl, base::Unretained(this), buf, + buf_len), + base::BindOnce(&Context::OnAsyncCompleted, base::Unretained(this), + IntToInt64(std::move(callback)))); DCHECK(posted); async_in_progress_ = true; @@ -59,17 +58,16 @@ int FileStream::Context::Write(IOBuffer* in_buf, int buf_len, - const CompletionCallback& callback) { + CompletionOnceCallback callback) { CheckNoAsyncInProgress(); scoped_refptr<IOBuffer> buf = in_buf; const bool posted = base::PostTaskAndReplyWithResult( - task_runner_.get(), - FROM_HERE, - base::Bind(&Context::WriteFileImpl, base::Unretained(this), buf, buf_len), - base::Bind(&Context::OnAsyncCompleted, - base::Unretained(this), - IntToInt64(callback))); + task_runner_.get(), FROM_HERE, + base::BindOnce(&Context::WriteFileImpl, base::Unretained(this), buf, + buf_len), + base::BindOnce(&Context::OnAsyncCompleted, base::Unretained(this), + IntToInt64(std::move(callback)))); DCHECK(posted); async_in_progress_ = true;
diff --git a/net/base/file_stream_context_win.cc b/net/base/file_stream_context_win.cc index 974835a1..cf4947f 100644 --- a/net/base/file_stream_context_win.cc +++ b/net/base/file_stream_context_win.cc
@@ -68,7 +68,7 @@ int FileStream::Context::Read(IOBuffer* buf, int buf_len, - const CompletionCallback& callback) { + CompletionOnceCallback callback) { CheckNoAsyncInProgress(); DCHECK(!async_read_initiated_); @@ -76,7 +76,7 @@ DCHECK(!io_complete_for_read_received_); last_operation_ = READ; - IOCompletionIsPending(callback, buf); + IOCompletionIsPending(std::move(callback), buf); async_read_initiated_ = true; result_ = 0; @@ -91,7 +91,7 @@ int FileStream::Context::Write(IOBuffer* buf, int buf_len, - const CompletionCallback& callback) { + CompletionOnceCallback callback) { CheckNoAsyncInProgress(); last_operation_ = WRITE; @@ -101,14 +101,15 @@ if (!WriteFile(file_.GetPlatformFile(), buf->data(), buf_len, &bytes_written, &io_context_.overlapped)) { IOResult error = IOResult::FromOSError(GetLastError()); - if (error.os_error == ERROR_IO_PENDING) - IOCompletionIsPending(callback, buf); - else + if (error.os_error == ERROR_IO_PENDING) { + IOCompletionIsPending(std::move(callback), buf); + } else { LOG(WARNING) << "WriteFile failed: " << error.os_error; + } return static_cast<int>(error.result); } - IOCompletionIsPending(callback, buf); + IOCompletionIsPending(std::move(callback), buf); return ERR_IO_PENDING; } @@ -125,11 +126,10 @@ this); } -void FileStream::Context::IOCompletionIsPending( - const CompletionCallback& callback, - IOBuffer* buf) { +void FileStream::Context::IOCompletionIsPending(CompletionOnceCallback callback, + IOBuffer* buf) { DCHECK(callback_.is_null()); - callback_ = callback; + callback_ = std::move(callback); in_flight_buf_ = buf; // Hold until the async operation ends. async_in_progress_ = true; } @@ -188,11 +188,9 @@ last_operation_ = NONE; async_in_progress_ = false; } - CompletionCallback temp_callback = callback_; - callback_.Reset(); scoped_refptr<IOBuffer> temp_buf = in_flight_buf_; in_flight_buf_ = NULL; - temp_callback.Run(result_); + std::move(callback_).Run(result_); } void FileStream::Context::DeleteOrphanedContext() {
diff --git a/net/base/mock_file_stream.cc b/net/base/mock_file_stream.cc index 67b8eff..4cff945 100644 --- a/net/base/mock_file_stream.cc +++ b/net/base/mock_file_stream.cc
@@ -35,45 +35,44 @@ MockFileStream::~MockFileStream() = default; -int MockFileStream::Seek(int64_t offset, - const Int64CompletionCallback& callback) { - Int64CompletionCallback wrapped_callback = - base::Bind(&MockFileStream::DoCallback64, - weak_factory_.GetWeakPtr(), callback); +int MockFileStream::Seek(int64_t offset, Int64CompletionOnceCallback callback) { + Int64CompletionOnceCallback wrapped_callback = + base::BindOnce(&MockFileStream::DoCallback64, weak_factory_.GetWeakPtr(), + std::move(callback)); if (forced_error_ == OK) - return FileStream::Seek(offset, wrapped_callback); - return ErrorCallback64(wrapped_callback); + return FileStream::Seek(offset, std::move(wrapped_callback)); + return ErrorCallback64(std::move(wrapped_callback)); } int MockFileStream::Read(IOBuffer* buf, int buf_len, - const CompletionCallback& callback) { - CompletionCallback wrapped_callback = base::Bind(&MockFileStream::DoCallback, - weak_factory_.GetWeakPtr(), - callback); + CompletionOnceCallback callback) { + CompletionOnceCallback wrapped_callback = + base::BindOnce(&MockFileStream::DoCallback, weak_factory_.GetWeakPtr(), + std::move(callback)); if (forced_error_ == OK) - return FileStream::Read(buf, buf_len, wrapped_callback); - return ErrorCallback(wrapped_callback); + return FileStream::Read(buf, buf_len, std::move(wrapped_callback)); + return ErrorCallback(std::move(wrapped_callback)); } int MockFileStream::Write(IOBuffer* buf, int buf_len, - const CompletionCallback& callback) { - CompletionCallback wrapped_callback = base::Bind(&MockFileStream::DoCallback, - weak_factory_.GetWeakPtr(), - callback); + CompletionOnceCallback callback) { + CompletionOnceCallback wrapped_callback = + base::BindOnce(&MockFileStream::DoCallback, weak_factory_.GetWeakPtr(), + std::move(callback)); if (forced_error_ == OK) - return FileStream::Write(buf, buf_len, wrapped_callback); - return ErrorCallback(wrapped_callback); + return FileStream::Write(buf, buf_len, std::move(wrapped_callback)); + return ErrorCallback(std::move(wrapped_callback)); } -int MockFileStream::Flush(const CompletionCallback& callback) { - CompletionCallback wrapped_callback = base::Bind(&MockFileStream::DoCallback, - weak_factory_.GetWeakPtr(), - callback); +int MockFileStream::Flush(CompletionOnceCallback callback) { + CompletionOnceCallback wrapped_callback = + base::BindOnce(&MockFileStream::DoCallback, weak_factory_.GetWeakPtr(), + std::move(callback)); if (forced_error_ == OK) - return FileStream::Flush(wrapped_callback); - return ErrorCallback(wrapped_callback); + return FileStream::Flush(std::move(wrapped_callback)); + return ErrorCallback(std::move(wrapped_callback)); } void MockFileStream::ThrottleCallbacks() { @@ -86,37 +85,35 @@ throttled_ = false; if (!throttled_task_.is_null()) { - base::Closure throttled_task = throttled_task_; - throttled_task_.Reset(); - base::ThreadTaskRunnerHandle::Get()->PostTask(FROM_HERE, throttled_task); + base::ThreadTaskRunnerHandle::Get()->PostTask(FROM_HERE, + std::move(throttled_task_)); } } -void MockFileStream::DoCallback(const CompletionCallback& callback, - int result) { +void MockFileStream::DoCallback(CompletionOnceCallback callback, int result) { if (!throttled_) { - callback.Run(result); + std::move(callback).Run(result); return; } CHECK(throttled_task_.is_null()); - throttled_task_ = base::Bind(callback, result); + throttled_task_ = base::BindOnce(std::move(callback), result); } -void MockFileStream::DoCallback64(const Int64CompletionCallback& callback, +void MockFileStream::DoCallback64(Int64CompletionOnceCallback callback, int64_t result) { if (!throttled_) { - callback.Run(result); + std::move(callback).Run(result); return; } CHECK(throttled_task_.is_null()); - throttled_task_ = base::Bind(callback, result); + throttled_task_ = base::BindOnce(std::move(callback), result); } -int MockFileStream::ErrorCallback(const CompletionCallback& callback) { +int MockFileStream::ErrorCallback(CompletionOnceCallback callback) { CHECK_NE(OK, forced_error_); if (async_error_) { base::ThreadTaskRunnerHandle::Get()->PostTask( - FROM_HERE, base::Bind(callback, forced_error_)); + FROM_HERE, base::BindOnce(std::move(callback), forced_error_)); clear_forced_error(); return ERR_IO_PENDING; } @@ -125,12 +122,11 @@ return ret; } -int64_t MockFileStream::ErrorCallback64( - const Int64CompletionCallback& callback) { +int64_t MockFileStream::ErrorCallback64(Int64CompletionOnceCallback callback) { CHECK_NE(OK, forced_error_); if (async_error_) { base::ThreadTaskRunnerHandle::Get()->PostTask( - FROM_HERE, base::Bind(callback, forced_error_)); + FROM_HERE, base::BindOnce(std::move(callback), forced_error_)); clear_forced_error(); return ERR_IO_PENDING; }
diff --git a/net/base/mock_file_stream.h b/net/base/mock_file_stream.h index ca5e030..9f1eb98 100644 --- a/net/base/mock_file_stream.h +++ b/net/base/mock_file_stream.h
@@ -12,6 +12,7 @@ #include "base/compiler_specific.h" #include "base/files/file_path.h" #include "base/memory/weak_ptr.h" +#include "net/base/completion_once_callback.h" #include "net/base/file_stream.h" #include "net/base/net_errors.h" @@ -29,14 +30,14 @@ ~MockFileStream() override; // FileStream methods. - int Seek(int64_t offset, const Int64CompletionCallback& callback) override; + int Seek(int64_t offset, Int64CompletionOnceCallback callback) override; int Read(IOBuffer* buf, int buf_len, - const CompletionCallback& callback) override; + CompletionOnceCallback callback) override; int Write(IOBuffer* buf, int buf_len, - const CompletionCallback& callback) override; - int Flush(const CompletionCallback& callback) override; + CompletionOnceCallback callback) override; + int Flush(CompletionOnceCallback callback) override; void set_forced_error_async(int error) { forced_error_ = error; @@ -83,18 +84,18 @@ // Wrappers for callbacks to make them honor ThrottleCallbacks and // ReleaseCallbacks. - void DoCallback(const CompletionCallback& callback, int result); - void DoCallback64(const Int64CompletionCallback& callback, int64_t result); + void DoCallback(CompletionOnceCallback callback, int result); + void DoCallback64(Int64CompletionOnceCallback callback, int64_t result); // Depending on |async_error_|, either synchronously returns |forced_error_| // asynchronously calls |callback| with |async_error_|. - int ErrorCallback(const CompletionCallback& callback); - int64_t ErrorCallback64(const Int64CompletionCallback& callback); + int ErrorCallback(CompletionOnceCallback callback); + int64_t ErrorCallback64(Int64CompletionOnceCallback callback); int forced_error_; bool async_error_; bool throttled_; - base::Closure throttled_task_; + base::OnceClosure throttled_task_; base::FilePath path_; base::WeakPtrFactory<MockFileStream> weak_factory_;
diff --git a/net/cert/internal/ocsp.cc b/net/cert/internal/ocsp.cc index b8e99f1..3f7c723 100644 --- a/net/cert/internal/ocsp.cc +++ b/net/cert/internal/ocsp.cc
@@ -901,7 +901,7 @@ if (!EVP_marshal_digest_algorithm(&req_cert, md)) return false; - AppendHashAsOctetString(md, &req_cert, issuer->tbs().issuer_tlv); + AppendHashAsOctetString(md, &req_cert, issuer->tbs().subject_tlv); der::Input key_tlv; if (!GetSubjectPublicKeyBytes(issuer->tbs().spki_tlv, &key_tlv))
diff --git a/net/cookies/cookie_monster.cc b/net/cookies/cookie_monster.cc index 1fb9cb71..85aa1e7b 100644 --- a/net/cookies/cookie_monster.cc +++ b/net/cookies/cookie_monster.cc
@@ -344,14 +344,6 @@ {CookieStore::ChangeCause::EVICTED, true}, // DELETE_COOKIE_NON_SECURE {CookieStore::ChangeCause::EVICTED, true}, - // DELETE_COOKIE_CREATED_BETWEEN - {CookieStore::ChangeCause::EXPLICIT_DELETE_BETWEEN, true}, - // DELETE_COOKIE_CREATED_BETWEEN_WITH_PREDICATE - {CookieStore::ChangeCause::EXPLICIT_DELETE_PREDICATE, true}, - // DELETE_COOKIE_SINGLE - {CookieStore::ChangeCause::EXPLICIT_DELETE_SINGLE, true}, - // DELETE_COOKIE_CANONICAL - {CookieStore::ChangeCause::EXPLICIT_DELETE_CANONICAL, true}, // DELETE_COOKIE_LAST_ENTRY {CookieStore::ChangeCause::EXPLICIT, false}}; @@ -742,7 +734,7 @@ if (cc->CreationDate() >= delete_begin && (delete_end.is_null() || cc->CreationDate() < delete_end)) { InternalDeleteCookie(curit, true, /*sync_to_store*/ - DELETE_COOKIE_CREATED_BETWEEN); + DELETE_COOKIE_EXPLICIT); ++num_deleted; } } @@ -770,7 +762,7 @@ (delete_end.is_null() || cc->CreationDate() < delete_end) && predicate.Run(*cc)) { InternalDeleteCookie(curit, true, /*sync_to_store*/ - DELETE_COOKIE_CREATED_BETWEEN_WITH_PREDICATE); + DELETE_COOKIE_EXPLICIT); ++num_deleted; } } @@ -846,7 +838,7 @@ CookieMap::iterator curit = it; ++it; if (matching_cookies.find(curit->second.get()) != matching_cookies.end()) { - InternalDeleteCookie(curit, true, DELETE_COOKIE_SINGLE); + InternalDeleteCookie(curit, true, DELETE_COOKIE_EXPLICIT); } } @@ -867,7 +859,7 @@ its.first != its.second; ++its.first) { // The creation date acts as the unique index... if (its.first->second->CreationDate() == cookie.CreationDate()) { - InternalDeleteCookie(its.first, true, DELETE_COOKIE_CANONICAL); + InternalDeleteCookie(its.first, true, DELETE_COOKIE_EXPLICIT); result = 1u; break; } @@ -1430,7 +1422,7 @@ // Nuke the existing store. while (!cookies_.empty()) { // TODO(rdsmith): The CANONICAL is a lie. - InternalDeleteCookie(cookies_.begin(), true, DELETE_COOKIE_CANONICAL); + InternalDeleteCookie(cookies_.begin(), true, DELETE_COOKIE_EXPLICIT); } // Set all passed in cookies.
diff --git a/net/cookies/cookie_monster.h b/net/cookies/cookie_monster.h index e51fc744..e97586f 100644 --- a/net/cookies/cookie_monster.h +++ b/net/cookies/cookie_monster.h
@@ -253,14 +253,10 @@ // and to provide a public cause for onCookieChange notifications. // // If you add or remove causes from this list, please be sure to also update - // the CookieStore::ChangeCause mapping inside ChangeCauseMapping. - // Moreover, these are used as array indexes, so avoid reordering to keep the - // histogram buckets consistent. New items (if necessary) should be added - // at the end of the list, before DELETE_COOKIE_LAST_ENTRY and the temporary - // values added for debugging. + // the CookieStore::ChangeCause mapping inside ChangeCauseMapping. New items + // (if necessary) should be added at the end of the list, just before + // DELETE_COOKIE_LAST_ENTRY. enum DeletionCause { - // DELETE_COOKIE_EXPLICIT is temporarily unused (except for logging to the - // histogram) - see values 13-16 below. DELETE_COOKIE_EXPLICIT = 0, DELETE_COOKIE_OVERWRITE = 1, DELETE_COOKIE_EXPIRED = 2, @@ -292,18 +288,7 @@ // right after expired cookies. DELETE_COOKIE_NON_SECURE = 12, - // The following values are temporary and being used to track down a bug. - // They should be treated the same as DELETE_COOKIE_EXPLICIT, and are logged - // to the histogram as DELETE_COOKIE_EXPLICIT. - DELETE_COOKIE_CREATED_BETWEEN = 13, - DELETE_COOKIE_CREATED_BETWEEN_WITH_PREDICATE = 14, - DELETE_COOKIE_SINGLE = 15, - DELETE_COOKIE_CANONICAL = 16, - - // Do not add new values between DELETE_COOKIE_CREATED_BETWEEN and - // DELETE_COOKIE_LAST_ENTRY, as the above values are temporary. Instead, new - // values should go before DELETE_COOKIE_CREATED_BETWEEN. - DELETE_COOKIE_LAST_ENTRY = 17 + DELETE_COOKIE_LAST_ENTRY = 13 }; // This enum is used to generate a histogramed bitmask measureing the types
diff --git a/net/cookies/cookie_monster_unittest.cc b/net/cookies/cookie_monster_unittest.cc index 5d45b30..e2948857 100644 --- a/net/cookies/cookie_monster_unittest.cc +++ b/net/cookies/cookie_monster_unittest.cc
@@ -3184,7 +3184,7 @@ EXPECT_EQ("abc", cookies[1].Name()); EXPECT_EQ("def", cookies[1].Value()); - EXPECT_EQ(CookieStore::ChangeCause::EXPLICIT_DELETE_SINGLE, causes[1]); + EXPECT_EQ(CookieStore::ChangeCause::EXPLICIT, causes[1]); } TEST_F(CookieMonsterNotificationTest, NotifyOnUpdate) {
diff --git a/net/cookies/cookie_store.h b/net/cookies/cookie_store.h index 7e376c1e..5a664d3 100644 --- a/net/cookies/cookie_store.h +++ b/net/cookies/cookie_store.h
@@ -39,14 +39,6 @@ INSERTED, // The cookie was changed directly by a consumer's action. EXPLICIT, - // The following four values have the same meaning as EXPLICIT, but are - // being used to track down where a bug is coming from. - // TODO(nharper): Remove the following four values once the one of interest - // has been found. See http://crbug.com/548423. - EXPLICIT_DELETE_BETWEEN, - EXPLICIT_DELETE_PREDICATE, - EXPLICIT_DELETE_SINGLE, - EXPLICIT_DELETE_CANONICAL, // The cookie was deleted, but no more details are known. UNKNOWN_DELETION, // The cookie was automatically removed due to an insert operation that
diff --git a/net/cookies/cookie_store_unittest.h b/net/cookies/cookie_store_unittest.h index bb97c9c..5b40963 100644 --- a/net/cookies/cookie_store_unittest.h +++ b/net/cookies/cookie_store_unittest.h
@@ -1717,8 +1717,7 @@ base::RunLoop().RunUntilIdle(); ASSERT_EQ(1u, cookie_changes.size()); EXPECT_EQ(this->http_www_foo_.url().host(), cookie_changes[0].first.Domain()); - EXPECT_EQ(CookieStore::ChangeCause::EXPLICIT_DELETE_CANONICAL, - cookie_changes[0].second); + EXPECT_EQ(CookieStore::ChangeCause::EXPLICIT, cookie_changes[0].second); EXPECT_EQ("C", cookie_changes[0].first.Name()); EXPECT_EQ("D", cookie_changes[0].first.Value()); }
diff --git a/net/data/ocsp_unittest/annotate_test_data.py b/net/data/ocsp_unittest/annotate_test_data.py index 5d933ffc..a84b6da 100755 --- a/net/data/ocsp_unittest/annotate_test_data.py +++ b/net/data/ocsp_unittest/annotate_test_data.py
@@ -69,8 +69,8 @@ if block_name == "OCSP RESPONSE": tmp_file_path = "tmp_ocsp.der" WriteStringToFile(block_data, tmp_file_path) - p = subprocess.Popen(["openssl", "ocsp", "-resp_text", "-respin", - tmp_file_path], + p = subprocess.Popen(["openssl", "ocsp", "-noverify", "-resp_text", + "-respin", tmp_file_path], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE) @@ -85,6 +85,7 @@ stdout_data = stdout_data.replace("-----", "~~~~~") return '$ openssl ocsp -resp_text -respin <([%s])\n%s' % (block_name, stdout_data) + print 'Error pretty printing OCSP response:\n',stderr_data # Otherwise try pretty printing using asn1parse.
diff --git a/net/data/ocsp_unittest/bad_ocsp_type.pem b/net/data/ocsp_unittest/bad_ocsp_type.pem index b3bd6f23..c2d6861 100644 --- a/net/data/ocsp_unittest/bad_ocsp_type.pem +++ b/net/data/ocsp_unittest/bad_ocsp_type.pem
@@ -1,132 +1,132 @@ Has an invalid OCSP OID $ openssl asn1parse -i < [OCSP RESPONSE] - 0:d=0 hl=4 l= 299 cons: SEQUENCE + 0:d=0 hl=4 l= 313 cons: SEQUENCE 4:d=1 hl=2 l= 1 prim: ENUMERATED :00 - 7:d=1 hl=4 l= 292 cons: cont [ 0 ] - 11:d=2 hl=4 l= 288 cons: SEQUENCE + 7:d=1 hl=4 l= 306 cons: cont [ 0 ] + 11:d=2 hl=4 l= 302 cons: SEQUENCE 15:d=3 hl=2 l= 9 prim: OBJECT :OCSP Nonce - 26:d=3 hl=4 l= 273 prim: OCTET STRING - 0:d=0 hl=4 l= 269 cons: SEQUENCE - 4:d=1 hl=2 l= 120 cons: SEQUENCE - 6:d=2 hl=2 l= 20 cons: cont [ 1 ] - 8:d=3 hl=2 l= 18 cons: SEQUENCE - 10:d=4 hl=2 l= 16 cons: SET - 12:d=5 hl=2 l= 14 cons: SEQUENCE - 14:d=6 hl=2 l= 3 prim: OBJECT :commonName - 19:d=6 hl=2 l= 7 prim: PRINTABLESTRING :Test CA - 28:d=2 hl=2 l= 15 prim: GENERALIZEDTIME :20170302000000Z - 45:d=2 hl=2 l= 79 cons: SEQUENCE - 47:d=3 hl=2 l= 77 cons: SEQUENCE - 49:d=4 hl=2 l= 56 cons: SEQUENCE - 51:d=5 hl=2 l= 7 cons: SEQUENCE - 53:d=6 hl=2 l= 5 prim: OBJECT :sha1 - 60:d=5 hl=2 l= 20 prim: OCTET STRING [HEX DUMP]:02FF75DA24DE8ADD150FAB689DCCE6E6636D0901 - 82:d=5 hl=2 l= 20 prim: OCTET STRING [HEX DUMP]:84E1BA52A25C543CA972491224BC8B1ECA8B9FF4 - 104:d=5 hl=2 l= 1 prim: INTEGER :03 - 107:d=4 hl=2 l= 0 prim: cont [ 0 ] - 109:d=4 hl=2 l= 15 prim: GENERALIZEDTIME :20170301000000Z - 126:d=1 hl=2 l= 13 cons: SEQUENCE - 128:d=2 hl=2 l= 9 prim: OBJECT :sha1WithRSAEncryption - 139:d=2 hl=2 l= 0 prim: NULL - 141:d=1 hl=3 l= 129 prim: BIT STRING + 26:d=3 hl=4 l= 287 prim: OCTET STRING + 0:d=0 hl=4 l= 283 cons: SEQUENCE + 4:d=1 hl=3 l= 133 cons: SEQUENCE + 7:d=2 hl=2 l= 33 cons: cont [ 1 ] + 9:d=3 hl=2 l= 31 cons: SEQUENCE + 11:d=4 hl=2 l= 29 cons: SET + 13:d=5 hl=2 l= 27 cons: SEQUENCE + 15:d=6 hl=2 l= 3 prim: OBJECT :commonName + 20:d=6 hl=2 l= 20 prim: UTF8STRING :Test Intermediate CA + 42:d=2 hl=2 l= 15 prim: GENERALIZEDTIME :20170302000000Z + 59:d=2 hl=2 l= 79 cons: SEQUENCE + 61:d=3 hl=2 l= 77 cons: SEQUENCE + 63:d=4 hl=2 l= 56 cons: SEQUENCE + 65:d=5 hl=2 l= 7 cons: SEQUENCE + 67:d=6 hl=2 l= 5 prim: OBJECT :sha1 + 74:d=5 hl=2 l= 20 prim: OCTET STRING [HEX DUMP]:449B1C5B31C6E9990966523E49C3F773C024190A + 96:d=5 hl=2 l= 20 prim: OCTET STRING [HEX DUMP]:FC6D3387CC3B39B049C755C46DF4395548930BCE + 118:d=5 hl=2 l= 1 prim: INTEGER :04 + 121:d=4 hl=2 l= 0 prim: cont [ 0 ] + 123:d=4 hl=2 l= 15 prim: GENERALIZEDTIME :20170301000000Z + 140:d=1 hl=2 l= 13 cons: SEQUENCE + 142:d=2 hl=2 l= 9 prim: OBJECT :sha1WithRSAEncryption + 153:d=2 hl=2 l= 0 prim: NULL + 155:d=1 hl=3 l= 129 prim: BIT STRING -----BEGIN OCSP RESPONSE----- -MIIBKwoBAKCCASQwggEgBgkrBgEFBQcwAQIEggERMIIBDTB4oRQwEjEQMA4GA1UEAxMHVGVzdCB -DQRgPMjAxNzAzMDIwMDAwMDBaME8wTTA4MAcGBSsOAwIaBBQC/3XaJN6K3RUPq2idzObmY20JAQ -QUhOG6UqJcVDypckkSJLyLHsqLn/QCAQOAABgPMjAxNzAzMDEwMDAwMDBaMA0GCSqGSIb3DQEBB -QUAA4GBAA6CkY2Sr0XLmOgOCAQVl5o6z8xy7s23PrBAtf2NfWwvSqYynjc7f9PviZ6NNMJFG5uZ -Te3jmpRiF1lLOr74wKeYveBpj5hH6XYl0x+UU9fC21aiquNrGTiXM6e2RW5SaSxibpi22HUADBb -Ji4RB9Jk+qQyn1JhRRYlM4sKOW+gm +MIIBOQoBAKCCATIwggEuBgkrBgEFBQcwAQIEggEfMIIBGzCBhaEhMB8xHTAbBgNVBAMMFFRlc3Q +gSW50ZXJtZWRpYXRlIENBGA8yMDE3MDMwMjAwMDAwMFowTzBNMDgwBwYFKw4DAhoEFESbHFsxxu +mZCWZSPknD93PAJBkKBBT8bTOHzDs5sEnHVcRt9DlVSJMLzgIBBIAAGA8yMDE3MDMwMTAwMDAwM +FowDQYJKoZIhvcNAQEFBQADgYEAm3y7IACGkmFtj21wh1IbrNUKl852e8S0p6gd6iwVzNQufaKM +U0qCBkq24tmbqsRjZpR6cbrZTryQEVZ1Vqp8NHMdrRwbpiiB6vmgheZPBy5DY0kej3i2lvSLTX9 +YsoYYRTpyXn/V9fBmg1iSA03iHa+ZKvTJECSox4cWf7l2sbo= -----END OCSP RESPONSE----- $ openssl x509 -text < [CA CERTIFICATE] Certificate: Data: Version: 3 (0x2) - Serial Number: 0 (0x0) + Serial Number: 1 (0x1) Signature Algorithm: sha1WithRSAEncryption - Issuer: CN=Test CA + Issuer: CN = Test CA Validity Not Before: Jan 1 00:00:00 2017 GMT Not After : Jan 1 00:00:00 2018 GMT - Subject: CN=Test CA + Subject: CN = Test Intermediate CA Subject Public Key Info: Public Key Algorithm: rsaEncryption Public-Key: (1024 bit) Modulus: - 00:b8:25:2b:ee:59:9a:9d:bc:b4:48:ae:09:ce:0d: - ba:c5:83:57:03:92:fd:52:32:55:f5:e4:2e:a6:cf: - 9e:4b:c4:10:af:24:da:d5:dd:44:a8:d6:28:38:9c: - a5:11:c9:0b:70:a1:b5:71:cf:a4:35:c2:6a:17:b1: - b5:c7:cf:74:83:ac:7a:d5:3b:12:66:74:f2:4b:15: - b0:c2:59:af:0c:78:2c:42:3c:3f:8b:83:b3:1d:9a: - c8:bc:ce:b0:c8:f2:1a:a8:0a:1c:bb:6e:6e:d4:c6: - 10:66:3c:a8:ec:e3:c4:63:40:f6:79:ec:8b:14:ff: - 85:9e:2d:1a:e7:e8:31:56:81 + 00:b9:32:09:de:33:4a:4f:e2:04:73:49:d5:2e:2b: + 83:92:3a:94:e4:1b:0c:27:1b:f8:43:83:17:b8:75: + f5:a4:af:e3:4c:84:3e:6c:48:79:76:df:4d:f5:39: + af:92:4b:c5:a0:86:ab:35:cc:19:6b:93:82:c0:f8: + 44:4d:1a:14:5d:48:87:65:02:0e:b0:a8:96:d9:06: + 19:3f:aa:85:2d:84:c0:78:19:a6:96:ab:26:56:f7: + 6f:5a:1a:97:a2:01:88:00:99:10:8a:97:39:c8:22: + 6e:de:e5:56:f4:a6:23:cd:ea:48:0e:65:67:a4:73: + a0:50:91:de:ba:cf:54:08:8f Exponent: 65537 (0x10001) Signature Algorithm: sha1WithRSAEncryption - 35:fe:ee:96:31:c7:3d:91:eb:22:53:1f:bf:cc:20:cc:aa:f4: - 04:92:3c:8b:50:06:ea:a1:cc:b7:c2:4a:d6:02:af:53:a7:a4: - 71:81:78:bc:95:f3:2d:46:c4:83:4c:d5:92:11:7c:c7:67:d3: - 47:f6:06:9f:1c:46:da:d6:20:72:47:c2:57:d7:fb:66:d3:35: - 82:07:61:13:4e:4d:e6:0c:93:e6:f3:be:98:ff:e8:de:60:a7: - 06:94:cd:bb:f5:6e:b3:4e:0b:d6:e9:2b:72:bd:6e:ae:86:23: - 2d:44:33:c4:3b:a7:52:12:46:d2:76:95:06:3e:69:0f:72:60: - 16:d6 + 48:d5:9f:8d:90:bc:4a:59:38:1d:2b:83:2d:71:1c:74:9d:01: + 73:a0:b6:98:e7:1c:c2:22:66:23:33:0a:8f:64:ff:9c:6b:37: + 09:12:1c:15:12:cb:c3:61:d9:ab:cd:96:dd:95:fa:a6:02:67: + 3c:4c:ec:98:38:5c:fc:48:cc:85:a9:5b:49:2c:2b:06:66:07: + 9e:31:0f:93:10:ab:3e:9f:97:60:64:01:61:7e:86:15:bb:5e: + f1:90:31:a3:54:d0:86:0e:80:05:87:09:2e:65:b6:95:89:5c: + c1:e5:80:d9:b8:81:b6:ed:1a:20:b8:9b:22:ce:ef:d0:26:47: + 9d:57 -----BEGIN CA CERTIFICATE----- -MIIBnDCCAQWgAwIBAgIBADANBgkqhkiG9w0BAQUFADASMRAwDgYDVQQDEwdUZXN0IENBMCIYDzI -wMTcwMTAxMDAwMDAwWhgPMjAxODAxMDEwMDAwMDBaMBIxEDAOBgNVBAMTB1Rlc3QgQ0EwgZ8wDQ -YJKoZIhvcNAQEBBQADgY0AMIGJAoGBALglK+5Zmp28tEiuCc4NusWDVwOS/VIyVfXkLqbPnkvEE -K8k2tXdRKjWKDicpRHJC3ChtXHPpDXCahextcfPdIOsetU7EmZ08ksVsMJZrwx4LEI8P4uDsx2a -yLzOsMjyGqgKHLtubtTGEGY8qOzjxGNA9nnsixT/hZ4tGufoMVaBAgMBAAEwDQYJKoZIhvcNAQE -FBQADgYEANf7uljHHPZHrIlMfv8wgzKr0BJI8i1AG6qHMt8JK1gKvU6ekcYF4vJXzLUbEg0zVkh -F8x2fTR/YGnxxG2tYgckfCV9f7ZtM1ggdhE05N5gyT5vO+mP/o3mCnBpTNu/Vus04L1ukrcr1ur -oYjLUQzxDunUhJG0naVBj5pD3JgFtY= +MIIBqTCCARKgAwIBAgIBATANBgkqhkiG9w0BAQUFADASMRAwDgYDVQQDDAdUZXN0IENBMCIYDzI +wMTcwMTAxMDAwMDAwWhgPMjAxODAxMDEwMDAwMDBaMB8xHTAbBgNVBAMMFFRlc3QgSW50ZXJtZW +RpYXRlIENBMIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQC5MgneM0pP4gRzSdUuK4OSOpTkG +wwnG/hDgxe4dfWkr+NMhD5sSHl23031Oa+SS8Wghqs1zBlrk4LA+ERNGhRdSIdlAg6wqJbZBhk/ +qoUthMB4GaaWqyZW929aGpeiAYgAmRCKlznIIm7e5Vb0piPN6kgOZWekc6BQkd66z1QIjwIDAQA +BMA0GCSqGSIb3DQEBBQUAA4GBAEjVn42QvEpZOB0rgy1xHHSdAXOgtpjnHMIiZiMzCo9k/5xrNw +kSHBUSy8Nh2avNlt2V+qYCZzxM7Jg4XPxIzIWpW0ksKwZmB54xD5MQqz6fl2BkAWF+hhW7XvGQM +aNU0IYOgAWHCS5ltpWJXMHlgNm4gbbtGiC4myLO79AmR51X -----END CA CERTIFICATE----- $ openssl x509 -text < [CERTIFICATE] Certificate: Data: Version: 3 (0x2) - Serial Number: 3 (0x3) + Serial Number: 4 (0x4) Signature Algorithm: sha1WithRSAEncryption - Issuer: CN=Test CA + Issuer: CN = Test Intermediate CA Validity Not Before: Jan 1 00:00:00 2017 GMT Not After : Jan 1 00:00:00 2018 GMT - Subject: CN=Test Cert + Subject: CN = Test Cert Subject Public Key Info: Public Key Algorithm: rsaEncryption Public-Key: (1024 bit) Modulus: - 00:d5:12:3f:22:6f:b0:e1:43:c5:93:b3:c3:5b:70: - 52:b2:8b:10:ec:11:c4:c4:aa:aa:43:92:c8:d0:f3: - 35:23:e3:76:2d:b4:ea:93:26:6f:6a:79:1c:64:51: - d3:4d:21:4a:73:83:35:dc:a0:16:74:db:f0:b9:a5: - 46:35:8d:53:e8:7d:37:5b:4d:ad:a3:df:d6:ae:01: - 38:ad:16:09:6e:fd:65:ad:1c:4b:48:12:1e:48:a7: - ff:5b:47:c4:c9:3b:74:85:63:1a:0a:06:b2:9f:b9: - cb:ad:dc:3f:24:8b:a4:a7:8a:13:15:45:89:24:c1: - a7:3b:c2:a2:c8:74:f1:3f:6f + 00:bc:4c:d5:b3:8d:92:fa:66:ac:32:43:1a:9e:eb: + 17:e0:aa:76:35:1b:1d:10:48:4e:3e:22:8b:75:2e: + e8:6f:a4:55:1e:0a:5e:60:c0:61:f1:7d:29:58:7e: + 0b:ef:29:be:ad:f8:f7:43:c8:58:95:14:5b:1d:af: + 4a:b8:90:9e:4e:ec:4e:b3:86:7a:b9:96:c1:34:d3: + b9:a6:57:df:9b:bd:d9:dd:67:15:54:d4:9f:65:b8: + 33:29:59:ba:9a:c6:75:ea:a5:76:3d:a4:57:0f:e2: + e4:c3:91:35:1d:6e:ff:61:7d:c2:53:23:66:b2:a8: + 0b:e1:c7:55:48:c5:2b:4d:7d Exponent: 65537 (0x10001) Signature Algorithm: sha1WithRSAEncryption - 04:21:70:de:14:92:27:13:e8:d2:b0:51:f0:af:34:75:0b:a7: - ff:84:cb:c6:96:30:80:01:f5:c1:3a:c6:81:ee:ba:89:60:33: - c3:e5:0f:43:cc:ac:81:8d:09:fb:25:e1:67:40:64:a3:ca:fd: - bd:9c:c4:73:e4:bc:4d:8e:e2:70:f1:17:ce:b4:ab:a0:b2:63: - 72:25:27:ae:d5:8e:18:73:0d:dc:12:5a:32:1c:b7:da:cd:23: - 5b:c8:87:58:08:3e:95:0c:fd:c8:48:a2:75:6e:79:f2:00:82: - 6e:b5:cc:71:e3:79:ca:68:85:9b:1b:5c:52:bf:a2:5a:71:e3: - 05:b5 + 18:bb:93:d9:2a:e0:34:69:2f:96:57:ac:55:ac:a7:83:04:b4: + bc:22:7f:5f:f7:c0:dc:ac:af:13:9b:86:7e:ac:02:8c:44:83: + 2e:c0:fa:a1:77:1d:dd:86:31:7e:98:93:c0:4f:b2:3d:be:30: + 6f:a5:fc:c7:2e:b1:b8:08:d2:17:cb:60:55:bf:5a:e0:94:f3: + 1d:44:fa:b1:2f:1a:24:c5:33:e1:d4:f0:ac:d5:2c:67:da:a7: + 5d:ee:eb:d6:7a:a7:41:e8:94:7a:34:43:b2:1f:ab:e9:cf:5d: + 25:49:56:18:d2:a9:49:1a:37:34:43:c7:06:96:4a:29:38:cc: + f2:1c -----BEGIN CERTIFICATE----- -MIIBnjCCAQegAwIBAgIBAzANBgkqhkiG9w0BAQUFADASMRAwDgYDVQQDEwdUZXN0IENBMCIYDzI -wMTcwMTAxMDAwMDAwWhgPMjAxODAxMDEwMDAwMDBaMBQxEjAQBgNVBAMTCVRlc3QgQ2VydDCBnz -ANBgkqhkiG9w0BAQEFAAOBjQAwgYkCgYEA1RI/Im+w4UPFk7PDW3BSsosQ7BHExKqqQ5LI0PM1I -+N2LbTqkyZvankcZFHTTSFKc4M13KAWdNvwuaVGNY1T6H03W02to9/WrgE4rRYJbv1lrRxLSBIe -SKf/W0fEyTt0hWMaCgayn7nLrdw/JIukp4oTFUWJJMGnO8KiyHTxP28CAwEAATANBgkqhkiG9w0 -BAQUFAAOBgQAEIXDeFJInE+jSsFHwrzR1C6f/hMvGljCAAfXBOsaB7rqJYDPD5Q9DzKyBjQn7Je -FnQGSjyv29nMRz5LxNjuJw8RfOtKugsmNyJSeu1Y4Ycw3cEloyHLfazSNbyIdYCD6VDP3ISKJ1b -nnyAIJutcxx43nKaIWbG1xSv6JaceMFtQ== +MIIBqzCCARSgAwIBAgIBBDANBgkqhkiG9w0BAQUFADAfMR0wGwYDVQQDDBRUZXN0IEludGVybWV +kaWF0ZSBDQTAiGA8yMDE3MDEwMTAwMDAwMFoYDzIwMTgwMTAxMDAwMDAwWjAUMRIwEAYDVQQDDA +lUZXN0IENlcnQwgZ8wDQYJKoZIhvcNAQEBBQADgY0AMIGJAoGBALxM1bONkvpmrDJDGp7rF+Cqd +jUbHRBITj4ii3Uu6G+kVR4KXmDAYfF9KVh+C+8pvq3490PIWJUUWx2vSriQnk7sTrOGermWwTTT +uaZX35u92d1nFVTUn2W4MylZuprGdeqldj2kVw/i5MORNR1u/2F9wlMjZrKoC+HHVUjFK019AgM +BAAEwDQYJKoZIhvcNAQEFBQADgYEAGLuT2SrgNGkvllesVayngwS0vCJ/X/fA3KyvE5uGfqwCjE +SDLsD6oXcd3YYxfpiTwE+yPb4wb6X8xy6xuAjSF8tgVb9a4JTzHUT6sS8aJMUz4dTwrNUsZ9qnX +e7r1nqnQeiUejRDsh+r6c9dJUlWGNKpSRo3NEPHBpZKKTjM8hw= -----END CERTIFICATE----- $ openssl asn1parse -i < [OCSP REQUEST] @@ -138,10 +138,10 @@ 10:d=5 hl=2 l= 9 cons: SEQUENCE 12:d=6 hl=2 l= 5 prim: OBJECT :sha1 19:d=6 hl=2 l= 0 prim: NULL - 21:d=5 hl=2 l= 20 prim: OCTET STRING [HEX DUMP]:02FF75DA24DE8ADD150FAB689DCCE6E6636D0901 - 43:d=5 hl=2 l= 20 prim: OCTET STRING [HEX DUMP]:84E1BA52A25C543CA972491224BC8B1ECA8B9FF4 - 65:d=5 hl=2 l= 1 prim: INTEGER :03 + 21:d=5 hl=2 l= 20 prim: OCTET STRING [HEX DUMP]:449B1C5B31C6E9990966523E49C3F773C024190A + 43:d=5 hl=2 l= 20 prim: OCTET STRING [HEX DUMP]:FC6D3387CC3B39B049C755C46DF4395548930BCE + 65:d=5 hl=2 l= 1 prim: INTEGER :04 -----BEGIN OCSP REQUEST----- -MEIwQDA+MDwwOjAJBgUrDgMCGgUABBQC/3XaJN6K3RUPq2idzObmY20JAQQUhOG6UqJcVDypckk -SJLyLHsqLn/QCAQM= +MEIwQDA+MDwwOjAJBgUrDgMCGgUABBREmxxbMcbpmQlmUj5Jw/dzwCQZCgQU/G0zh8w7ObBJx1X +EbfQ5VUiTC84CAQQ= -----END OCSP REQUEST-----
diff --git a/net/data/ocsp_unittest/bad_signature.pem b/net/data/ocsp_unittest/bad_signature.pem index f2f0ae7..ab1034c1c 100644 --- a/net/data/ocsp_unittest/bad_signature.pem +++ b/net/data/ocsp_unittest/bad_signature.pem
@@ -5,114 +5,114 @@ OCSP Response Status: successful (0x0) Response Type: Basic OCSP Response Version: 1 (0x0) - Responder Id: CN = Test CA + Responder Id: CN = Test Intermediate CA Produced At: Mar 2 00:00:00 2017 GMT Responses: Certificate ID: Hash Algorithm: sha1 - Issuer Name Hash: 02FF75DA24DE8ADD150FAB689DCCE6E6636D0901 - Issuer Key Hash: 84E1BA52A25C543CA972491224BC8B1ECA8B9FF4 - Serial Number: 03 + Issuer Name Hash: 449B1C5B31C6E9990966523E49C3F773C024190A + Issuer Key Hash: FC6D3387CC3B39B049C755C46DF4395548930BCE + Serial Number: 04 Cert Status: good This Update: Mar 1 00:00:00 2017 GMT Signature Algorithm: sha1WithRSAEncryption de:ad:be:ef -----BEGIN OCSP RESPONSE----- -MIGqCgEAoIGkMIGhBgkrBgEFBQcwAQEEgZMwgZAweKEUMBIxEDAOBgNVBAMTB1Rlc3QgQ0EYDzI -wMTcwMzAyMDAwMDAwWjBPME0wODAHBgUrDgMCGgQUAv912iTeit0VD6tonczm5mNtCQEEFIThul -KiXFQ8qXJJEiS8ix7Ki5/0AgEDgAAYDzIwMTcwMzAxMDAwMDAwWjANBgkqhkiG9w0BAQUFAAMFA -N6tvu8= +MIG4CgEAoIGyMIGvBgkrBgEFBQcwAQEEgaEwgZ4wgYWhITAfMR0wGwYDVQQDDBRUZXN0IEludGV +ybWVkaWF0ZSBDQRgPMjAxNzAzMDIwMDAwMDBaME8wTTA4MAcGBSsOAwIaBBREmxxbMcbpmQlmUj +5Jw/dzwCQZCgQU/G0zh8w7ObBJx1XEbfQ5VUiTC84CAQSAABgPMjAxNzAzMDEwMDAwMDBaMA0GC +SqGSIb3DQEBBQUAAwUA3q2+7w== -----END OCSP RESPONSE----- $ openssl x509 -text < [CA CERTIFICATE] Certificate: Data: Version: 3 (0x2) - Serial Number: 0 (0x0) + Serial Number: 1 (0x1) Signature Algorithm: sha1WithRSAEncryption - Issuer: CN=Test CA + Issuer: CN = Test CA Validity Not Before: Jan 1 00:00:00 2017 GMT Not After : Jan 1 00:00:00 2018 GMT - Subject: CN=Test CA + Subject: CN = Test Intermediate CA Subject Public Key Info: Public Key Algorithm: rsaEncryption Public-Key: (1024 bit) Modulus: - 00:b8:25:2b:ee:59:9a:9d:bc:b4:48:ae:09:ce:0d: - ba:c5:83:57:03:92:fd:52:32:55:f5:e4:2e:a6:cf: - 9e:4b:c4:10:af:24:da:d5:dd:44:a8:d6:28:38:9c: - a5:11:c9:0b:70:a1:b5:71:cf:a4:35:c2:6a:17:b1: - b5:c7:cf:74:83:ac:7a:d5:3b:12:66:74:f2:4b:15: - b0:c2:59:af:0c:78:2c:42:3c:3f:8b:83:b3:1d:9a: - c8:bc:ce:b0:c8:f2:1a:a8:0a:1c:bb:6e:6e:d4:c6: - 10:66:3c:a8:ec:e3:c4:63:40:f6:79:ec:8b:14:ff: - 85:9e:2d:1a:e7:e8:31:56:81 + 00:b9:32:09:de:33:4a:4f:e2:04:73:49:d5:2e:2b: + 83:92:3a:94:e4:1b:0c:27:1b:f8:43:83:17:b8:75: + f5:a4:af:e3:4c:84:3e:6c:48:79:76:df:4d:f5:39: + af:92:4b:c5:a0:86:ab:35:cc:19:6b:93:82:c0:f8: + 44:4d:1a:14:5d:48:87:65:02:0e:b0:a8:96:d9:06: + 19:3f:aa:85:2d:84:c0:78:19:a6:96:ab:26:56:f7: + 6f:5a:1a:97:a2:01:88:00:99:10:8a:97:39:c8:22: + 6e:de:e5:56:f4:a6:23:cd:ea:48:0e:65:67:a4:73: + a0:50:91:de:ba:cf:54:08:8f Exponent: 65537 (0x10001) Signature Algorithm: sha1WithRSAEncryption - 35:fe:ee:96:31:c7:3d:91:eb:22:53:1f:bf:cc:20:cc:aa:f4: - 04:92:3c:8b:50:06:ea:a1:cc:b7:c2:4a:d6:02:af:53:a7:a4: - 71:81:78:bc:95:f3:2d:46:c4:83:4c:d5:92:11:7c:c7:67:d3: - 47:f6:06:9f:1c:46:da:d6:20:72:47:c2:57:d7:fb:66:d3:35: - 82:07:61:13:4e:4d:e6:0c:93:e6:f3:be:98:ff:e8:de:60:a7: - 06:94:cd:bb:f5:6e:b3:4e:0b:d6:e9:2b:72:bd:6e:ae:86:23: - 2d:44:33:c4:3b:a7:52:12:46:d2:76:95:06:3e:69:0f:72:60: - 16:d6 + 48:d5:9f:8d:90:bc:4a:59:38:1d:2b:83:2d:71:1c:74:9d:01: + 73:a0:b6:98:e7:1c:c2:22:66:23:33:0a:8f:64:ff:9c:6b:37: + 09:12:1c:15:12:cb:c3:61:d9:ab:cd:96:dd:95:fa:a6:02:67: + 3c:4c:ec:98:38:5c:fc:48:cc:85:a9:5b:49:2c:2b:06:66:07: + 9e:31:0f:93:10:ab:3e:9f:97:60:64:01:61:7e:86:15:bb:5e: + f1:90:31:a3:54:d0:86:0e:80:05:87:09:2e:65:b6:95:89:5c: + c1:e5:80:d9:b8:81:b6:ed:1a:20:b8:9b:22:ce:ef:d0:26:47: + 9d:57 -----BEGIN CA CERTIFICATE----- -MIIBnDCCAQWgAwIBAgIBADANBgkqhkiG9w0BAQUFADASMRAwDgYDVQQDEwdUZXN0IENBMCIYDzI -wMTcwMTAxMDAwMDAwWhgPMjAxODAxMDEwMDAwMDBaMBIxEDAOBgNVBAMTB1Rlc3QgQ0EwgZ8wDQ -YJKoZIhvcNAQEBBQADgY0AMIGJAoGBALglK+5Zmp28tEiuCc4NusWDVwOS/VIyVfXkLqbPnkvEE -K8k2tXdRKjWKDicpRHJC3ChtXHPpDXCahextcfPdIOsetU7EmZ08ksVsMJZrwx4LEI8P4uDsx2a -yLzOsMjyGqgKHLtubtTGEGY8qOzjxGNA9nnsixT/hZ4tGufoMVaBAgMBAAEwDQYJKoZIhvcNAQE -FBQADgYEANf7uljHHPZHrIlMfv8wgzKr0BJI8i1AG6qHMt8JK1gKvU6ekcYF4vJXzLUbEg0zVkh -F8x2fTR/YGnxxG2tYgckfCV9f7ZtM1ggdhE05N5gyT5vO+mP/o3mCnBpTNu/Vus04L1ukrcr1ur -oYjLUQzxDunUhJG0naVBj5pD3JgFtY= +MIIBqTCCARKgAwIBAgIBATANBgkqhkiG9w0BAQUFADASMRAwDgYDVQQDDAdUZXN0IENBMCIYDzI +wMTcwMTAxMDAwMDAwWhgPMjAxODAxMDEwMDAwMDBaMB8xHTAbBgNVBAMMFFRlc3QgSW50ZXJtZW +RpYXRlIENBMIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQC5MgneM0pP4gRzSdUuK4OSOpTkG +wwnG/hDgxe4dfWkr+NMhD5sSHl23031Oa+SS8Wghqs1zBlrk4LA+ERNGhRdSIdlAg6wqJbZBhk/ +qoUthMB4GaaWqyZW929aGpeiAYgAmRCKlznIIm7e5Vb0piPN6kgOZWekc6BQkd66z1QIjwIDAQA +BMA0GCSqGSIb3DQEBBQUAA4GBAEjVn42QvEpZOB0rgy1xHHSdAXOgtpjnHMIiZiMzCo9k/5xrNw +kSHBUSy8Nh2avNlt2V+qYCZzxM7Jg4XPxIzIWpW0ksKwZmB54xD5MQqz6fl2BkAWF+hhW7XvGQM +aNU0IYOgAWHCS5ltpWJXMHlgNm4gbbtGiC4myLO79AmR51X -----END CA CERTIFICATE----- $ openssl x509 -text < [CERTIFICATE] Certificate: Data: Version: 3 (0x2) - Serial Number: 3 (0x3) + Serial Number: 4 (0x4) Signature Algorithm: sha1WithRSAEncryption - Issuer: CN=Test CA + Issuer: CN = Test Intermediate CA Validity Not Before: Jan 1 00:00:00 2017 GMT Not After : Jan 1 00:00:00 2018 GMT - Subject: CN=Test Cert + Subject: CN = Test Cert Subject Public Key Info: Public Key Algorithm: rsaEncryption Public-Key: (1024 bit) Modulus: - 00:d5:12:3f:22:6f:b0:e1:43:c5:93:b3:c3:5b:70: - 52:b2:8b:10:ec:11:c4:c4:aa:aa:43:92:c8:d0:f3: - 35:23:e3:76:2d:b4:ea:93:26:6f:6a:79:1c:64:51: - d3:4d:21:4a:73:83:35:dc:a0:16:74:db:f0:b9:a5: - 46:35:8d:53:e8:7d:37:5b:4d:ad:a3:df:d6:ae:01: - 38:ad:16:09:6e:fd:65:ad:1c:4b:48:12:1e:48:a7: - ff:5b:47:c4:c9:3b:74:85:63:1a:0a:06:b2:9f:b9: - cb:ad:dc:3f:24:8b:a4:a7:8a:13:15:45:89:24:c1: - a7:3b:c2:a2:c8:74:f1:3f:6f + 00:bc:4c:d5:b3:8d:92:fa:66:ac:32:43:1a:9e:eb: + 17:e0:aa:76:35:1b:1d:10:48:4e:3e:22:8b:75:2e: + e8:6f:a4:55:1e:0a:5e:60:c0:61:f1:7d:29:58:7e: + 0b:ef:29:be:ad:f8:f7:43:c8:58:95:14:5b:1d:af: + 4a:b8:90:9e:4e:ec:4e:b3:86:7a:b9:96:c1:34:d3: + b9:a6:57:df:9b:bd:d9:dd:67:15:54:d4:9f:65:b8: + 33:29:59:ba:9a:c6:75:ea:a5:76:3d:a4:57:0f:e2: + e4:c3:91:35:1d:6e:ff:61:7d:c2:53:23:66:b2:a8: + 0b:e1:c7:55:48:c5:2b:4d:7d Exponent: 65537 (0x10001) Signature Algorithm: sha1WithRSAEncryption - 04:21:70:de:14:92:27:13:e8:d2:b0:51:f0:af:34:75:0b:a7: - ff:84:cb:c6:96:30:80:01:f5:c1:3a:c6:81:ee:ba:89:60:33: - c3:e5:0f:43:cc:ac:81:8d:09:fb:25:e1:67:40:64:a3:ca:fd: - bd:9c:c4:73:e4:bc:4d:8e:e2:70:f1:17:ce:b4:ab:a0:b2:63: - 72:25:27:ae:d5:8e:18:73:0d:dc:12:5a:32:1c:b7:da:cd:23: - 5b:c8:87:58:08:3e:95:0c:fd:c8:48:a2:75:6e:79:f2:00:82: - 6e:b5:cc:71:e3:79:ca:68:85:9b:1b:5c:52:bf:a2:5a:71:e3: - 05:b5 + 18:bb:93:d9:2a:e0:34:69:2f:96:57:ac:55:ac:a7:83:04:b4: + bc:22:7f:5f:f7:c0:dc:ac:af:13:9b:86:7e:ac:02:8c:44:83: + 2e:c0:fa:a1:77:1d:dd:86:31:7e:98:93:c0:4f:b2:3d:be:30: + 6f:a5:fc:c7:2e:b1:b8:08:d2:17:cb:60:55:bf:5a:e0:94:f3: + 1d:44:fa:b1:2f:1a:24:c5:33:e1:d4:f0:ac:d5:2c:67:da:a7: + 5d:ee:eb:d6:7a:a7:41:e8:94:7a:34:43:b2:1f:ab:e9:cf:5d: + 25:49:56:18:d2:a9:49:1a:37:34:43:c7:06:96:4a:29:38:cc: + f2:1c -----BEGIN CERTIFICATE----- -MIIBnjCCAQegAwIBAgIBAzANBgkqhkiG9w0BAQUFADASMRAwDgYDVQQDEwdUZXN0IENBMCIYDzI -wMTcwMTAxMDAwMDAwWhgPMjAxODAxMDEwMDAwMDBaMBQxEjAQBgNVBAMTCVRlc3QgQ2VydDCBnz -ANBgkqhkiG9w0BAQEFAAOBjQAwgYkCgYEA1RI/Im+w4UPFk7PDW3BSsosQ7BHExKqqQ5LI0PM1I -+N2LbTqkyZvankcZFHTTSFKc4M13KAWdNvwuaVGNY1T6H03W02to9/WrgE4rRYJbv1lrRxLSBIe -SKf/W0fEyTt0hWMaCgayn7nLrdw/JIukp4oTFUWJJMGnO8KiyHTxP28CAwEAATANBgkqhkiG9w0 -BAQUFAAOBgQAEIXDeFJInE+jSsFHwrzR1C6f/hMvGljCAAfXBOsaB7rqJYDPD5Q9DzKyBjQn7Je -FnQGSjyv29nMRz5LxNjuJw8RfOtKugsmNyJSeu1Y4Ycw3cEloyHLfazSNbyIdYCD6VDP3ISKJ1b -nnyAIJutcxx43nKaIWbG1xSv6JaceMFtQ== +MIIBqzCCARSgAwIBAgIBBDANBgkqhkiG9w0BAQUFADAfMR0wGwYDVQQDDBRUZXN0IEludGVybWV +kaWF0ZSBDQTAiGA8yMDE3MDEwMTAwMDAwMFoYDzIwMTgwMTAxMDAwMDAwWjAUMRIwEAYDVQQDDA +lUZXN0IENlcnQwgZ8wDQYJKoZIhvcNAQEBBQADgY0AMIGJAoGBALxM1bONkvpmrDJDGp7rF+Cqd +jUbHRBITj4ii3Uu6G+kVR4KXmDAYfF9KVh+C+8pvq3490PIWJUUWx2vSriQnk7sTrOGermWwTTT +uaZX35u92d1nFVTUn2W4MylZuprGdeqldj2kVw/i5MORNR1u/2F9wlMjZrKoC+HHVUjFK019AgM +BAAEwDQYJKoZIhvcNAQEFBQADgYEAGLuT2SrgNGkvllesVayngwS0vCJ/X/fA3KyvE5uGfqwCjE +SDLsD6oXcd3YYxfpiTwE+yPb4wb6X8xy6xuAjSF8tgVb9a4JTzHUT6sS8aJMUz4dTwrNUsZ9qnX +e7r1nqnQeiUejRDsh+r6c9dJUlWGNKpSRo3NEPHBpZKKTjM8hw= -----END CERTIFICATE----- $ openssl asn1parse -i < [OCSP REQUEST] @@ -124,10 +124,10 @@ 10:d=5 hl=2 l= 9 cons: SEQUENCE 12:d=6 hl=2 l= 5 prim: OBJECT :sha1 19:d=6 hl=2 l= 0 prim: NULL - 21:d=5 hl=2 l= 20 prim: OCTET STRING [HEX DUMP]:02FF75DA24DE8ADD150FAB689DCCE6E6636D0901 - 43:d=5 hl=2 l= 20 prim: OCTET STRING [HEX DUMP]:84E1BA52A25C543CA972491224BC8B1ECA8B9FF4 - 65:d=5 hl=2 l= 1 prim: INTEGER :03 + 21:d=5 hl=2 l= 20 prim: OCTET STRING [HEX DUMP]:449B1C5B31C6E9990966523E49C3F773C024190A + 43:d=5 hl=2 l= 20 prim: OCTET STRING [HEX DUMP]:FC6D3387CC3B39B049C755C46DF4395548930BCE + 65:d=5 hl=2 l= 1 prim: INTEGER :04 -----BEGIN OCSP REQUEST----- -MEIwQDA+MDwwOjAJBgUrDgMCGgUABBQC/3XaJN6K3RUPq2idzObmY20JAQQUhOG6UqJcVDypckk -SJLyLHsqLn/QCAQM= +MEIwQDA+MDwwOjAJBgUrDgMCGgUABBREmxxbMcbpmQlmUj5Jw/dzwCQZCgQU/G0zh8w7ObBJx1X +EbfQ5VUiTC84CAQQ= -----END OCSP REQUEST-----
diff --git a/net/data/ocsp_unittest/bad_status.pem b/net/data/ocsp_unittest/bad_status.pem index db6157f..7ac26b6 100644 --- a/net/data/ocsp_unittest/bad_status.pem +++ b/net/data/ocsp_unittest/bad_status.pem
@@ -10,90 +10,90 @@ Certificate: Data: Version: 3 (0x2) - Serial Number: 0 (0x0) + Serial Number: 1 (0x1) Signature Algorithm: sha1WithRSAEncryption - Issuer: CN=Test CA + Issuer: CN = Test CA Validity Not Before: Jan 1 00:00:00 2017 GMT Not After : Jan 1 00:00:00 2018 GMT - Subject: CN=Test CA + Subject: CN = Test Intermediate CA Subject Public Key Info: Public Key Algorithm: rsaEncryption Public-Key: (1024 bit) Modulus: - 00:b8:25:2b:ee:59:9a:9d:bc:b4:48:ae:09:ce:0d: - ba:c5:83:57:03:92:fd:52:32:55:f5:e4:2e:a6:cf: - 9e:4b:c4:10:af:24:da:d5:dd:44:a8:d6:28:38:9c: - a5:11:c9:0b:70:a1:b5:71:cf:a4:35:c2:6a:17:b1: - b5:c7:cf:74:83:ac:7a:d5:3b:12:66:74:f2:4b:15: - b0:c2:59:af:0c:78:2c:42:3c:3f:8b:83:b3:1d:9a: - c8:bc:ce:b0:c8:f2:1a:a8:0a:1c:bb:6e:6e:d4:c6: - 10:66:3c:a8:ec:e3:c4:63:40:f6:79:ec:8b:14:ff: - 85:9e:2d:1a:e7:e8:31:56:81 + 00:b9:32:09:de:33:4a:4f:e2:04:73:49:d5:2e:2b: + 83:92:3a:94:e4:1b:0c:27:1b:f8:43:83:17:b8:75: + f5:a4:af:e3:4c:84:3e:6c:48:79:76:df:4d:f5:39: + af:92:4b:c5:a0:86:ab:35:cc:19:6b:93:82:c0:f8: + 44:4d:1a:14:5d:48:87:65:02:0e:b0:a8:96:d9:06: + 19:3f:aa:85:2d:84:c0:78:19:a6:96:ab:26:56:f7: + 6f:5a:1a:97:a2:01:88:00:99:10:8a:97:39:c8:22: + 6e:de:e5:56:f4:a6:23:cd:ea:48:0e:65:67:a4:73: + a0:50:91:de:ba:cf:54:08:8f Exponent: 65537 (0x10001) Signature Algorithm: sha1WithRSAEncryption - 35:fe:ee:96:31:c7:3d:91:eb:22:53:1f:bf:cc:20:cc:aa:f4: - 04:92:3c:8b:50:06:ea:a1:cc:b7:c2:4a:d6:02:af:53:a7:a4: - 71:81:78:bc:95:f3:2d:46:c4:83:4c:d5:92:11:7c:c7:67:d3: - 47:f6:06:9f:1c:46:da:d6:20:72:47:c2:57:d7:fb:66:d3:35: - 82:07:61:13:4e:4d:e6:0c:93:e6:f3:be:98:ff:e8:de:60:a7: - 06:94:cd:bb:f5:6e:b3:4e:0b:d6:e9:2b:72:bd:6e:ae:86:23: - 2d:44:33:c4:3b:a7:52:12:46:d2:76:95:06:3e:69:0f:72:60: - 16:d6 + 48:d5:9f:8d:90:bc:4a:59:38:1d:2b:83:2d:71:1c:74:9d:01: + 73:a0:b6:98:e7:1c:c2:22:66:23:33:0a:8f:64:ff:9c:6b:37: + 09:12:1c:15:12:cb:c3:61:d9:ab:cd:96:dd:95:fa:a6:02:67: + 3c:4c:ec:98:38:5c:fc:48:cc:85:a9:5b:49:2c:2b:06:66:07: + 9e:31:0f:93:10:ab:3e:9f:97:60:64:01:61:7e:86:15:bb:5e: + f1:90:31:a3:54:d0:86:0e:80:05:87:09:2e:65:b6:95:89:5c: + c1:e5:80:d9:b8:81:b6:ed:1a:20:b8:9b:22:ce:ef:d0:26:47: + 9d:57 -----BEGIN CA CERTIFICATE----- -MIIBnDCCAQWgAwIBAgIBADANBgkqhkiG9w0BAQUFADASMRAwDgYDVQQDEwdUZXN0IENBMCIYDzI -wMTcwMTAxMDAwMDAwWhgPMjAxODAxMDEwMDAwMDBaMBIxEDAOBgNVBAMTB1Rlc3QgQ0EwgZ8wDQ -YJKoZIhvcNAQEBBQADgY0AMIGJAoGBALglK+5Zmp28tEiuCc4NusWDVwOS/VIyVfXkLqbPnkvEE -K8k2tXdRKjWKDicpRHJC3ChtXHPpDXCahextcfPdIOsetU7EmZ08ksVsMJZrwx4LEI8P4uDsx2a -yLzOsMjyGqgKHLtubtTGEGY8qOzjxGNA9nnsixT/hZ4tGufoMVaBAgMBAAEwDQYJKoZIhvcNAQE -FBQADgYEANf7uljHHPZHrIlMfv8wgzKr0BJI8i1AG6qHMt8JK1gKvU6ekcYF4vJXzLUbEg0zVkh -F8x2fTR/YGnxxG2tYgckfCV9f7ZtM1ggdhE05N5gyT5vO+mP/o3mCnBpTNu/Vus04L1ukrcr1ur -oYjLUQzxDunUhJG0naVBj5pD3JgFtY= +MIIBqTCCARKgAwIBAgIBATANBgkqhkiG9w0BAQUFADASMRAwDgYDVQQDDAdUZXN0IENBMCIYDzI +wMTcwMTAxMDAwMDAwWhgPMjAxODAxMDEwMDAwMDBaMB8xHTAbBgNVBAMMFFRlc3QgSW50ZXJtZW +RpYXRlIENBMIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQC5MgneM0pP4gRzSdUuK4OSOpTkG +wwnG/hDgxe4dfWkr+NMhD5sSHl23031Oa+SS8Wghqs1zBlrk4LA+ERNGhRdSIdlAg6wqJbZBhk/ +qoUthMB4GaaWqyZW929aGpeiAYgAmRCKlznIIm7e5Vb0piPN6kgOZWekc6BQkd66z1QIjwIDAQA +BMA0GCSqGSIb3DQEBBQUAA4GBAEjVn42QvEpZOB0rgy1xHHSdAXOgtpjnHMIiZiMzCo9k/5xrNw +kSHBUSy8Nh2avNlt2V+qYCZzxM7Jg4XPxIzIWpW0ksKwZmB54xD5MQqz6fl2BkAWF+hhW7XvGQM +aNU0IYOgAWHCS5ltpWJXMHlgNm4gbbtGiC4myLO79AmR51X -----END CA CERTIFICATE----- $ openssl x509 -text < [CERTIFICATE] Certificate: Data: Version: 3 (0x2) - Serial Number: 3 (0x3) + Serial Number: 4 (0x4) Signature Algorithm: sha1WithRSAEncryption - Issuer: CN=Test CA + Issuer: CN = Test Intermediate CA Validity Not Before: Jan 1 00:00:00 2017 GMT Not After : Jan 1 00:00:00 2018 GMT - Subject: CN=Test Cert + Subject: CN = Test Cert Subject Public Key Info: Public Key Algorithm: rsaEncryption Public-Key: (1024 bit) Modulus: - 00:d5:12:3f:22:6f:b0:e1:43:c5:93:b3:c3:5b:70: - 52:b2:8b:10:ec:11:c4:c4:aa:aa:43:92:c8:d0:f3: - 35:23:e3:76:2d:b4:ea:93:26:6f:6a:79:1c:64:51: - d3:4d:21:4a:73:83:35:dc:a0:16:74:db:f0:b9:a5: - 46:35:8d:53:e8:7d:37:5b:4d:ad:a3:df:d6:ae:01: - 38:ad:16:09:6e:fd:65:ad:1c:4b:48:12:1e:48:a7: - ff:5b:47:c4:c9:3b:74:85:63:1a:0a:06:b2:9f:b9: - cb:ad:dc:3f:24:8b:a4:a7:8a:13:15:45:89:24:c1: - a7:3b:c2:a2:c8:74:f1:3f:6f + 00:bc:4c:d5:b3:8d:92:fa:66:ac:32:43:1a:9e:eb: + 17:e0:aa:76:35:1b:1d:10:48:4e:3e:22:8b:75:2e: + e8:6f:a4:55:1e:0a:5e:60:c0:61:f1:7d:29:58:7e: + 0b:ef:29:be:ad:f8:f7:43:c8:58:95:14:5b:1d:af: + 4a:b8:90:9e:4e:ec:4e:b3:86:7a:b9:96:c1:34:d3: + b9:a6:57:df:9b:bd:d9:dd:67:15:54:d4:9f:65:b8: + 33:29:59:ba:9a:c6:75:ea:a5:76:3d:a4:57:0f:e2: + e4:c3:91:35:1d:6e:ff:61:7d:c2:53:23:66:b2:a8: + 0b:e1:c7:55:48:c5:2b:4d:7d Exponent: 65537 (0x10001) Signature Algorithm: sha1WithRSAEncryption - 04:21:70:de:14:92:27:13:e8:d2:b0:51:f0:af:34:75:0b:a7: - ff:84:cb:c6:96:30:80:01:f5:c1:3a:c6:81:ee:ba:89:60:33: - c3:e5:0f:43:cc:ac:81:8d:09:fb:25:e1:67:40:64:a3:ca:fd: - bd:9c:c4:73:e4:bc:4d:8e:e2:70:f1:17:ce:b4:ab:a0:b2:63: - 72:25:27:ae:d5:8e:18:73:0d:dc:12:5a:32:1c:b7:da:cd:23: - 5b:c8:87:58:08:3e:95:0c:fd:c8:48:a2:75:6e:79:f2:00:82: - 6e:b5:cc:71:e3:79:ca:68:85:9b:1b:5c:52:bf:a2:5a:71:e3: - 05:b5 + 18:bb:93:d9:2a:e0:34:69:2f:96:57:ac:55:ac:a7:83:04:b4: + bc:22:7f:5f:f7:c0:dc:ac:af:13:9b:86:7e:ac:02:8c:44:83: + 2e:c0:fa:a1:77:1d:dd:86:31:7e:98:93:c0:4f:b2:3d:be:30: + 6f:a5:fc:c7:2e:b1:b8:08:d2:17:cb:60:55:bf:5a:e0:94:f3: + 1d:44:fa:b1:2f:1a:24:c5:33:e1:d4:f0:ac:d5:2c:67:da:a7: + 5d:ee:eb:d6:7a:a7:41:e8:94:7a:34:43:b2:1f:ab:e9:cf:5d: + 25:49:56:18:d2:a9:49:1a:37:34:43:c7:06:96:4a:29:38:cc: + f2:1c -----BEGIN CERTIFICATE----- -MIIBnjCCAQegAwIBAgIBAzANBgkqhkiG9w0BAQUFADASMRAwDgYDVQQDEwdUZXN0IENBMCIYDzI -wMTcwMTAxMDAwMDAwWhgPMjAxODAxMDEwMDAwMDBaMBQxEjAQBgNVBAMTCVRlc3QgQ2VydDCBnz -ANBgkqhkiG9w0BAQEFAAOBjQAwgYkCgYEA1RI/Im+w4UPFk7PDW3BSsosQ7BHExKqqQ5LI0PM1I -+N2LbTqkyZvankcZFHTTSFKc4M13KAWdNvwuaVGNY1T6H03W02to9/WrgE4rRYJbv1lrRxLSBIe -SKf/W0fEyTt0hWMaCgayn7nLrdw/JIukp4oTFUWJJMGnO8KiyHTxP28CAwEAATANBgkqhkiG9w0 -BAQUFAAOBgQAEIXDeFJInE+jSsFHwrzR1C6f/hMvGljCAAfXBOsaB7rqJYDPD5Q9DzKyBjQn7Je -FnQGSjyv29nMRz5LxNjuJw8RfOtKugsmNyJSeu1Y4Ycw3cEloyHLfazSNbyIdYCD6VDP3ISKJ1b -nnyAIJutcxx43nKaIWbG1xSv6JaceMFtQ== +MIIBqzCCARSgAwIBAgIBBDANBgkqhkiG9w0BAQUFADAfMR0wGwYDVQQDDBRUZXN0IEludGVybWV +kaWF0ZSBDQTAiGA8yMDE3MDEwMTAwMDAwMFoYDzIwMTgwMTAxMDAwMDAwWjAUMRIwEAYDVQQDDA +lUZXN0IENlcnQwgZ8wDQYJKoZIhvcNAQEBBQADgY0AMIGJAoGBALxM1bONkvpmrDJDGp7rF+Cqd +jUbHRBITj4ii3Uu6G+kVR4KXmDAYfF9KVh+C+8pvq3490PIWJUUWx2vSriQnk7sTrOGermWwTTT +uaZX35u92d1nFVTUn2W4MylZuprGdeqldj2kVw/i5MORNR1u/2F9wlMjZrKoC+HHVUjFK019AgM +BAAEwDQYJKoZIhvcNAQEFBQADgYEAGLuT2SrgNGkvllesVayngwS0vCJ/X/fA3KyvE5uGfqwCjE +SDLsD6oXcd3YYxfpiTwE+yPb4wb6X8xy6xuAjSF8tgVb9a4JTzHUT6sS8aJMUz4dTwrNUsZ9qnX +e7r1nqnQeiUejRDsh+r6c9dJUlWGNKpSRo3NEPHBpZKKTjM8hw= -----END CERTIFICATE----- $ openssl asn1parse -i < [OCSP REQUEST] @@ -105,10 +105,10 @@ 10:d=5 hl=2 l= 9 cons: SEQUENCE 12:d=6 hl=2 l= 5 prim: OBJECT :sha1 19:d=6 hl=2 l= 0 prim: NULL - 21:d=5 hl=2 l= 20 prim: OCTET STRING [HEX DUMP]:02FF75DA24DE8ADD150FAB689DCCE6E6636D0901 - 43:d=5 hl=2 l= 20 prim: OCTET STRING [HEX DUMP]:84E1BA52A25C543CA972491224BC8B1ECA8B9FF4 - 65:d=5 hl=2 l= 1 prim: INTEGER :03 + 21:d=5 hl=2 l= 20 prim: OCTET STRING [HEX DUMP]:449B1C5B31C6E9990966523E49C3F773C024190A + 43:d=5 hl=2 l= 20 prim: OCTET STRING [HEX DUMP]:FC6D3387CC3B39B049C755C46DF4395548930BCE + 65:d=5 hl=2 l= 1 prim: INTEGER :04 -----BEGIN OCSP REQUEST----- -MEIwQDA+MDwwOjAJBgUrDgMCGgUABBQC/3XaJN6K3RUPq2idzObmY20JAQQUhOG6UqJcVDypckk -SJLyLHsqLn/QCAQM= +MEIwQDA+MDwwOjAJBgUrDgMCGgUABBREmxxbMcbpmQlmUj5Jw/dzwCQZCgQU/G0zh8w7ObBJx1X +EbfQ5VUiTC84CAQQ= -----END OCSP REQUEST-----
diff --git a/net/data/ocsp_unittest/good_response.pem b/net/data/ocsp_unittest/good_response.pem index e594fceb..5ef5bb7 100644 --- a/net/data/ocsp_unittest/good_response.pem +++ b/net/data/ocsp_unittest/good_response.pem
@@ -5,123 +5,123 @@ OCSP Response Status: successful (0x0) Response Type: Basic OCSP Response Version: 1 (0x0) - Responder Id: CN = Test CA + Responder Id: CN = Test Intermediate CA Produced At: Mar 2 00:00:00 2017 GMT Responses: Certificate ID: Hash Algorithm: sha1 - Issuer Name Hash: 02FF75DA24DE8ADD150FAB689DCCE6E6636D0901 - Issuer Key Hash: 84E1BA52A25C543CA972491224BC8B1ECA8B9FF4 - Serial Number: 03 + Issuer Name Hash: 449B1C5B31C6E9990966523E49C3F773C024190A + Issuer Key Hash: FC6D3387CC3B39B049C755C46DF4395548930BCE + Serial Number: 04 Cert Status: good This Update: Mar 1 00:00:00 2017 GMT Signature Algorithm: sha1WithRSAEncryption - 0e:82:91:8d:92:af:45:cb:98:e8:0e:08:04:15:97:9a:3a:cf: - cc:72:ee:cd:b7:3e:b0:40:b5:fd:8d:7d:6c:2f:4a:a6:32:9e: - 37:3b:7f:d3:ef:89:9e:8d:34:c2:45:1b:9b:99:4d:ed:e3:9a: - 94:62:17:59:4b:3a:be:f8:c0:a7:98:bd:e0:69:8f:98:47:e9: - 76:25:d3:1f:94:53:d7:c2:db:56:a2:aa:e3:6b:19:38:97:33: - a7:b6:45:6e:52:69:2c:62:6e:98:b6:d8:75:00:0c:16:c9:8b: - 84:41:f4:99:3e:a9:0c:a7:d4:98:51:45:89:4c:e2:c2:8e:5b: - e8:26 + 9b:7c:bb:20:00:86:92:61:6d:8f:6d:70:87:52:1b:ac:d5:0a: + 97:ce:76:7b:c4:b4:a7:a8:1d:ea:2c:15:cc:d4:2e:7d:a2:8c: + 53:4a:82:06:4a:b6:e2:d9:9b:aa:c4:63:66:94:7a:71:ba:d9: + 4e:bc:90:11:56:75:56:aa:7c:34:73:1d:ad:1c:1b:a6:28:81: + ea:f9:a0:85:e6:4f:07:2e:43:63:49:1e:8f:78:b6:96:f4:8b: + 4d:7f:58:b2:86:18:45:3a:72:5e:7f:d5:f5:f0:66:83:58:92: + 03:4d:e2:1d:af:99:2a:f4:c9:10:24:a8:c7:87:16:7f:b9:76: + b1:ba -----BEGIN OCSP RESPONSE----- -MIIBKwoBAKCCASQwggEgBgkrBgEFBQcwAQEEggERMIIBDTB4oRQwEjEQMA4GA1UEAxMHVGVzdCB -DQRgPMjAxNzAzMDIwMDAwMDBaME8wTTA4MAcGBSsOAwIaBBQC/3XaJN6K3RUPq2idzObmY20JAQ -QUhOG6UqJcVDypckkSJLyLHsqLn/QCAQOAABgPMjAxNzAzMDEwMDAwMDBaMA0GCSqGSIb3DQEBB -QUAA4GBAA6CkY2Sr0XLmOgOCAQVl5o6z8xy7s23PrBAtf2NfWwvSqYynjc7f9PviZ6NNMJFG5uZ -Te3jmpRiF1lLOr74wKeYveBpj5hH6XYl0x+UU9fC21aiquNrGTiXM6e2RW5SaSxibpi22HUADBb -Ji4RB9Jk+qQyn1JhRRYlM4sKOW+gm +MIIBOQoBAKCCATIwggEuBgkrBgEFBQcwAQEEggEfMIIBGzCBhaEhMB8xHTAbBgNVBAMMFFRlc3Q +gSW50ZXJtZWRpYXRlIENBGA8yMDE3MDMwMjAwMDAwMFowTzBNMDgwBwYFKw4DAhoEFESbHFsxxu +mZCWZSPknD93PAJBkKBBT8bTOHzDs5sEnHVcRt9DlVSJMLzgIBBIAAGA8yMDE3MDMwMTAwMDAwM +FowDQYJKoZIhvcNAQEFBQADgYEAm3y7IACGkmFtj21wh1IbrNUKl852e8S0p6gd6iwVzNQufaKM +U0qCBkq24tmbqsRjZpR6cbrZTryQEVZ1Vqp8NHMdrRwbpiiB6vmgheZPBy5DY0kej3i2lvSLTX9 +YsoYYRTpyXn/V9fBmg1iSA03iHa+ZKvTJECSox4cWf7l2sbo= -----END OCSP RESPONSE----- $ openssl x509 -text < [CA CERTIFICATE] Certificate: Data: Version: 3 (0x2) - Serial Number: 0 (0x0) + Serial Number: 1 (0x1) Signature Algorithm: sha1WithRSAEncryption - Issuer: CN=Test CA + Issuer: CN = Test CA Validity Not Before: Jan 1 00:00:00 2017 GMT Not After : Jan 1 00:00:00 2018 GMT - Subject: CN=Test CA + Subject: CN = Test Intermediate CA Subject Public Key Info: Public Key Algorithm: rsaEncryption Public-Key: (1024 bit) Modulus: - 00:b8:25:2b:ee:59:9a:9d:bc:b4:48:ae:09:ce:0d: - ba:c5:83:57:03:92:fd:52:32:55:f5:e4:2e:a6:cf: - 9e:4b:c4:10:af:24:da:d5:dd:44:a8:d6:28:38:9c: - a5:11:c9:0b:70:a1:b5:71:cf:a4:35:c2:6a:17:b1: - b5:c7:cf:74:83:ac:7a:d5:3b:12:66:74:f2:4b:15: - b0:c2:59:af:0c:78:2c:42:3c:3f:8b:83:b3:1d:9a: - c8:bc:ce:b0:c8:f2:1a:a8:0a:1c:bb:6e:6e:d4:c6: - 10:66:3c:a8:ec:e3:c4:63:40:f6:79:ec:8b:14:ff: - 85:9e:2d:1a:e7:e8:31:56:81 + 00:b9:32:09:de:33:4a:4f:e2:04:73:49:d5:2e:2b: + 83:92:3a:94:e4:1b:0c:27:1b:f8:43:83:17:b8:75: + f5:a4:af:e3:4c:84:3e:6c:48:79:76:df:4d:f5:39: + af:92:4b:c5:a0:86:ab:35:cc:19:6b:93:82:c0:f8: + 44:4d:1a:14:5d:48:87:65:02:0e:b0:a8:96:d9:06: + 19:3f:aa:85:2d:84:c0:78:19:a6:96:ab:26:56:f7: + 6f:5a:1a:97:a2:01:88:00:99:10:8a:97:39:c8:22: + 6e:de:e5:56:f4:a6:23:cd:ea:48:0e:65:67:a4:73: + a0:50:91:de:ba:cf:54:08:8f Exponent: 65537 (0x10001) Signature Algorithm: sha1WithRSAEncryption - 35:fe:ee:96:31:c7:3d:91:eb:22:53:1f:bf:cc:20:cc:aa:f4: - 04:92:3c:8b:50:06:ea:a1:cc:b7:c2:4a:d6:02:af:53:a7:a4: - 71:81:78:bc:95:f3:2d:46:c4:83:4c:d5:92:11:7c:c7:67:d3: - 47:f6:06:9f:1c:46:da:d6:20:72:47:c2:57:d7:fb:66:d3:35: - 82:07:61:13:4e:4d:e6:0c:93:e6:f3:be:98:ff:e8:de:60:a7: - 06:94:cd:bb:f5:6e:b3:4e:0b:d6:e9:2b:72:bd:6e:ae:86:23: - 2d:44:33:c4:3b:a7:52:12:46:d2:76:95:06:3e:69:0f:72:60: - 16:d6 + 48:d5:9f:8d:90:bc:4a:59:38:1d:2b:83:2d:71:1c:74:9d:01: + 73:a0:b6:98:e7:1c:c2:22:66:23:33:0a:8f:64:ff:9c:6b:37: + 09:12:1c:15:12:cb:c3:61:d9:ab:cd:96:dd:95:fa:a6:02:67: + 3c:4c:ec:98:38:5c:fc:48:cc:85:a9:5b:49:2c:2b:06:66:07: + 9e:31:0f:93:10:ab:3e:9f:97:60:64:01:61:7e:86:15:bb:5e: + f1:90:31:a3:54:d0:86:0e:80:05:87:09:2e:65:b6:95:89:5c: + c1:e5:80:d9:b8:81:b6:ed:1a:20:b8:9b:22:ce:ef:d0:26:47: + 9d:57 -----BEGIN CA CERTIFICATE----- -MIIBnDCCAQWgAwIBAgIBADANBgkqhkiG9w0BAQUFADASMRAwDgYDVQQDEwdUZXN0IENBMCIYDzI -wMTcwMTAxMDAwMDAwWhgPMjAxODAxMDEwMDAwMDBaMBIxEDAOBgNVBAMTB1Rlc3QgQ0EwgZ8wDQ -YJKoZIhvcNAQEBBQADgY0AMIGJAoGBALglK+5Zmp28tEiuCc4NusWDVwOS/VIyVfXkLqbPnkvEE -K8k2tXdRKjWKDicpRHJC3ChtXHPpDXCahextcfPdIOsetU7EmZ08ksVsMJZrwx4LEI8P4uDsx2a -yLzOsMjyGqgKHLtubtTGEGY8qOzjxGNA9nnsixT/hZ4tGufoMVaBAgMBAAEwDQYJKoZIhvcNAQE -FBQADgYEANf7uljHHPZHrIlMfv8wgzKr0BJI8i1AG6qHMt8JK1gKvU6ekcYF4vJXzLUbEg0zVkh -F8x2fTR/YGnxxG2tYgckfCV9f7ZtM1ggdhE05N5gyT5vO+mP/o3mCnBpTNu/Vus04L1ukrcr1ur -oYjLUQzxDunUhJG0naVBj5pD3JgFtY= +MIIBqTCCARKgAwIBAgIBATANBgkqhkiG9w0BAQUFADASMRAwDgYDVQQDDAdUZXN0IENBMCIYDzI +wMTcwMTAxMDAwMDAwWhgPMjAxODAxMDEwMDAwMDBaMB8xHTAbBgNVBAMMFFRlc3QgSW50ZXJtZW +RpYXRlIENBMIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQC5MgneM0pP4gRzSdUuK4OSOpTkG +wwnG/hDgxe4dfWkr+NMhD5sSHl23031Oa+SS8Wghqs1zBlrk4LA+ERNGhRdSIdlAg6wqJbZBhk/ +qoUthMB4GaaWqyZW929aGpeiAYgAmRCKlznIIm7e5Vb0piPN6kgOZWekc6BQkd66z1QIjwIDAQA +BMA0GCSqGSIb3DQEBBQUAA4GBAEjVn42QvEpZOB0rgy1xHHSdAXOgtpjnHMIiZiMzCo9k/5xrNw +kSHBUSy8Nh2avNlt2V+qYCZzxM7Jg4XPxIzIWpW0ksKwZmB54xD5MQqz6fl2BkAWF+hhW7XvGQM +aNU0IYOgAWHCS5ltpWJXMHlgNm4gbbtGiC4myLO79AmR51X -----END CA CERTIFICATE----- $ openssl x509 -text < [CERTIFICATE] Certificate: Data: Version: 3 (0x2) - Serial Number: 3 (0x3) + Serial Number: 4 (0x4) Signature Algorithm: sha1WithRSAEncryption - Issuer: CN=Test CA + Issuer: CN = Test Intermediate CA Validity Not Before: Jan 1 00:00:00 2017 GMT Not After : Jan 1 00:00:00 2018 GMT - Subject: CN=Test Cert + Subject: CN = Test Cert Subject Public Key Info: Public Key Algorithm: rsaEncryption Public-Key: (1024 bit) Modulus: - 00:d5:12:3f:22:6f:b0:e1:43:c5:93:b3:c3:5b:70: - 52:b2:8b:10:ec:11:c4:c4:aa:aa:43:92:c8:d0:f3: - 35:23:e3:76:2d:b4:ea:93:26:6f:6a:79:1c:64:51: - d3:4d:21:4a:73:83:35:dc:a0:16:74:db:f0:b9:a5: - 46:35:8d:53:e8:7d:37:5b:4d:ad:a3:df:d6:ae:01: - 38:ad:16:09:6e:fd:65:ad:1c:4b:48:12:1e:48:a7: - ff:5b:47:c4:c9:3b:74:85:63:1a:0a:06:b2:9f:b9: - cb:ad:dc:3f:24:8b:a4:a7:8a:13:15:45:89:24:c1: - a7:3b:c2:a2:c8:74:f1:3f:6f + 00:bc:4c:d5:b3:8d:92:fa:66:ac:32:43:1a:9e:eb: + 17:e0:aa:76:35:1b:1d:10:48:4e:3e:22:8b:75:2e: + e8:6f:a4:55:1e:0a:5e:60:c0:61:f1:7d:29:58:7e: + 0b:ef:29:be:ad:f8:f7:43:c8:58:95:14:5b:1d:af: + 4a:b8:90:9e:4e:ec:4e:b3:86:7a:b9:96:c1:34:d3: + b9:a6:57:df:9b:bd:d9:dd:67:15:54:d4:9f:65:b8: + 33:29:59:ba:9a:c6:75:ea:a5:76:3d:a4:57:0f:e2: + e4:c3:91:35:1d:6e:ff:61:7d:c2:53:23:66:b2:a8: + 0b:e1:c7:55:48:c5:2b:4d:7d Exponent: 65537 (0x10001) Signature Algorithm: sha1WithRSAEncryption - 04:21:70:de:14:92:27:13:e8:d2:b0:51:f0:af:34:75:0b:a7: - ff:84:cb:c6:96:30:80:01:f5:c1:3a:c6:81:ee:ba:89:60:33: - c3:e5:0f:43:cc:ac:81:8d:09:fb:25:e1:67:40:64:a3:ca:fd: - bd:9c:c4:73:e4:bc:4d:8e:e2:70:f1:17:ce:b4:ab:a0:b2:63: - 72:25:27:ae:d5:8e:18:73:0d:dc:12:5a:32:1c:b7:da:cd:23: - 5b:c8:87:58:08:3e:95:0c:fd:c8:48:a2:75:6e:79:f2:00:82: - 6e:b5:cc:71:e3:79:ca:68:85:9b:1b:5c:52:bf:a2:5a:71:e3: - 05:b5 + 18:bb:93:d9:2a:e0:34:69:2f:96:57:ac:55:ac:a7:83:04:b4: + bc:22:7f:5f:f7:c0:dc:ac:af:13:9b:86:7e:ac:02:8c:44:83: + 2e:c0:fa:a1:77:1d:dd:86:31:7e:98:93:c0:4f:b2:3d:be:30: + 6f:a5:fc:c7:2e:b1:b8:08:d2:17:cb:60:55:bf:5a:e0:94:f3: + 1d:44:fa:b1:2f:1a:24:c5:33:e1:d4:f0:ac:d5:2c:67:da:a7: + 5d:ee:eb:d6:7a:a7:41:e8:94:7a:34:43:b2:1f:ab:e9:cf:5d: + 25:49:56:18:d2:a9:49:1a:37:34:43:c7:06:96:4a:29:38:cc: + f2:1c -----BEGIN CERTIFICATE----- -MIIBnjCCAQegAwIBAgIBAzANBgkqhkiG9w0BAQUFADASMRAwDgYDVQQDEwdUZXN0IENBMCIYDzI -wMTcwMTAxMDAwMDAwWhgPMjAxODAxMDEwMDAwMDBaMBQxEjAQBgNVBAMTCVRlc3QgQ2VydDCBnz -ANBgkqhkiG9w0BAQEFAAOBjQAwgYkCgYEA1RI/Im+w4UPFk7PDW3BSsosQ7BHExKqqQ5LI0PM1I -+N2LbTqkyZvankcZFHTTSFKc4M13KAWdNvwuaVGNY1T6H03W02to9/WrgE4rRYJbv1lrRxLSBIe -SKf/W0fEyTt0hWMaCgayn7nLrdw/JIukp4oTFUWJJMGnO8KiyHTxP28CAwEAATANBgkqhkiG9w0 -BAQUFAAOBgQAEIXDeFJInE+jSsFHwrzR1C6f/hMvGljCAAfXBOsaB7rqJYDPD5Q9DzKyBjQn7Je -FnQGSjyv29nMRz5LxNjuJw8RfOtKugsmNyJSeu1Y4Ycw3cEloyHLfazSNbyIdYCD6VDP3ISKJ1b -nnyAIJutcxx43nKaIWbG1xSv6JaceMFtQ== +MIIBqzCCARSgAwIBAgIBBDANBgkqhkiG9w0BAQUFADAfMR0wGwYDVQQDDBRUZXN0IEludGVybWV +kaWF0ZSBDQTAiGA8yMDE3MDEwMTAwMDAwMFoYDzIwMTgwMTAxMDAwMDAwWjAUMRIwEAYDVQQDDA +lUZXN0IENlcnQwgZ8wDQYJKoZIhvcNAQEBBQADgY0AMIGJAoGBALxM1bONkvpmrDJDGp7rF+Cqd +jUbHRBITj4ii3Uu6G+kVR4KXmDAYfF9KVh+C+8pvq3490PIWJUUWx2vSriQnk7sTrOGermWwTTT +uaZX35u92d1nFVTUn2W4MylZuprGdeqldj2kVw/i5MORNR1u/2F9wlMjZrKoC+HHVUjFK019AgM +BAAEwDQYJKoZIhvcNAQEFBQADgYEAGLuT2SrgNGkvllesVayngwS0vCJ/X/fA3KyvE5uGfqwCjE +SDLsD6oXcd3YYxfpiTwE+yPb4wb6X8xy6xuAjSF8tgVb9a4JTzHUT6sS8aJMUz4dTwrNUsZ9qnX +e7r1nqnQeiUejRDsh+r6c9dJUlWGNKpSRo3NEPHBpZKKTjM8hw= -----END CERTIFICATE----- $ openssl asn1parse -i < [OCSP REQUEST] @@ -133,10 +133,10 @@ 10:d=5 hl=2 l= 9 cons: SEQUENCE 12:d=6 hl=2 l= 5 prim: OBJECT :sha1 19:d=6 hl=2 l= 0 prim: NULL - 21:d=5 hl=2 l= 20 prim: OCTET STRING [HEX DUMP]:02FF75DA24DE8ADD150FAB689DCCE6E6636D0901 - 43:d=5 hl=2 l= 20 prim: OCTET STRING [HEX DUMP]:84E1BA52A25C543CA972491224BC8B1ECA8B9FF4 - 65:d=5 hl=2 l= 1 prim: INTEGER :03 + 21:d=5 hl=2 l= 20 prim: OCTET STRING [HEX DUMP]:449B1C5B31C6E9990966523E49C3F773C024190A + 43:d=5 hl=2 l= 20 prim: OCTET STRING [HEX DUMP]:FC6D3387CC3B39B049C755C46DF4395548930BCE + 65:d=5 hl=2 l= 1 prim: INTEGER :04 -----BEGIN OCSP REQUEST----- -MEIwQDA+MDwwOjAJBgUrDgMCGgUABBQC/3XaJN6K3RUPq2idzObmY20JAQQUhOG6UqJcVDypckk -SJLyLHsqLn/QCAQM= +MEIwQDA+MDwwOjAJBgUrDgMCGgUABBREmxxbMcbpmQlmUj5Jw/dzwCQZCgQU/G0zh8w7ObBJx1X +EbfQ5VUiTC84CAQQ= -----END OCSP REQUEST-----
diff --git a/net/data/ocsp_unittest/good_response_next_update.pem b/net/data/ocsp_unittest/good_response_next_update.pem index 1531b60..f1c0a20 100644 --- a/net/data/ocsp_unittest/good_response_next_update.pem +++ b/net/data/ocsp_unittest/good_response_next_update.pem
@@ -5,124 +5,124 @@ OCSP Response Status: successful (0x0) Response Type: Basic OCSP Response Version: 1 (0x0) - Responder Id: CN = Test CA + Responder Id: CN = Test Intermediate CA Produced At: Mar 2 00:00:00 2017 GMT Responses: Certificate ID: Hash Algorithm: sha1 - Issuer Name Hash: 02FF75DA24DE8ADD150FAB689DCCE6E6636D0901 - Issuer Key Hash: 84E1BA52A25C543CA972491224BC8B1ECA8B9FF4 - Serial Number: 03 + Issuer Name Hash: 449B1C5B31C6E9990966523E49C3F773C024190A + Issuer Key Hash: FC6D3387CC3B39B049C755C46DF4395548930BCE + Serial Number: 04 Cert Status: good This Update: Mar 1 00:00:00 2017 GMT Next Update: Jun 1 00:00:00 2017 GMT Signature Algorithm: sha1WithRSAEncryption - 3f:c0:c3:7b:09:f2:7a:e9:66:02:68:f7:73:4a:f1:7c:31:b1: - 90:ba:47:6e:5d:b1:31:16:9c:5a:33:3e:c3:aa:05:80:7b:7e: - 6e:32:a0:42:8f:7f:c0:8d:4a:2c:7e:b0:20:f1:56:f4:c8:c5: - a2:bf:8e:47:39:34:f0:51:86:20:4c:86:bb:0e:c2:5d:d8:87: - 5a:bc:c4:eb:8a:ab:80:6d:d5:ba:66:8d:3b:fe:f0:6d:a4:ed: - 19:0a:12:d2:63:7a:ca:24:8a:13:0a:00:65:ae:4d:0e:92:6c: - 18:b8:9a:e7:22:37:38:22:8d:3c:42:ad:62:df:67:30:13:9d: - 50:e1 + 86:77:0f:dd:c2:53:e7:a1:90:8b:32:e2:e3:c2:d1:b7:ea:fe: + 83:b3:95:f3:69:31:8b:14:e6:f2:05:4c:d9:d7:43:ed:8d:8e: + 12:17:61:6a:13:07:cd:cb:12:f1:b8:da:2d:73:5e:d1:ad:e3: + 7f:49:5f:79:a4:ad:7f:b0:0e:ee:8a:cc:a2:ce:5f:02:93:9e: + 3b:41:ed:82:2f:c6:f0:60:0a:ee:49:b3:c8:2e:09:f4:17:b3: + c1:f6:f0:51:fc:6f:75:bc:9a:36:17:02:db:5b:a6:57:5d:77: + 00:15:d9:98:22:a1:86:5a:5e:e8:88:7f:52:61:09:b6:f5:75: + b0:e9 -----BEGIN OCSP RESPONSE----- -MIIBPwoBAKCCATgwggE0BgkrBgEFBQcwAQEEggElMIIBITCBi6EUMBIxEDAOBgNVBAMTB1Rlc3Q -gQ0EYDzIwMTcwMzAyMDAwMDAwWjBiMGAwODAHBgUrDgMCGgQUAv912iTeit0VD6tonczm5mNtCQ -EEFIThulKiXFQ8qXJJEiS8ix7Ki5/0AgEDgAAYDzIwMTcwMzAxMDAwMDAwWqARGA8yMDE3MDYwM -TAwMDAwMFowDQYJKoZIhvcNAQEFBQADgYEAP8DDewnyeulmAmj3c0rxfDGxkLpHbl2xMRacWjM+ -w6oFgHt+bjKgQo9/wI1KLH6wIPFW9MjFor+ORzk08FGGIEyGuw7CXdiHWrzE64qrgG3VumaNO/7 -wbaTtGQoS0mN6yiSKEwoAZa5NDpJsGLia5yI3OCKNPEKtYt9nMBOdUOE= +MIIBTAoBAKCCAUUwggFBBgkrBgEFBQcwAQEEggEyMIIBLjCBmKEhMB8xHTAbBgNVBAMMFFRlc3Q +gSW50ZXJtZWRpYXRlIENBGA8yMDE3MDMwMjAwMDAwMFowYjBgMDgwBwYFKw4DAhoEFESbHFsxxu +mZCWZSPknD93PAJBkKBBT8bTOHzDs5sEnHVcRt9DlVSJMLzgIBBIAAGA8yMDE3MDMwMTAwMDAwM +FqgERgPMjAxNzA2MDEwMDAwMDBaMA0GCSqGSIb3DQEBBQUAA4GBAIZ3D93CU+ehkIsy4uPC0bfq +/oOzlfNpMYsU5vIFTNnXQ+2NjhIXYWoTB83LEvG42i1zXtGt439JX3mkrX+wDu6KzKLOXwKTnjt +B7YIvxvBgCu5Js8guCfQXs8H28FH8b3W8mjYXAttbpldddwAV2ZgioYZaXuiIf1JhCbb1dbDp -----END OCSP RESPONSE----- $ openssl x509 -text < [CA CERTIFICATE] Certificate: Data: Version: 3 (0x2) - Serial Number: 0 (0x0) + Serial Number: 1 (0x1) Signature Algorithm: sha1WithRSAEncryption - Issuer: CN=Test CA + Issuer: CN = Test CA Validity Not Before: Jan 1 00:00:00 2017 GMT Not After : Jan 1 00:00:00 2018 GMT - Subject: CN=Test CA + Subject: CN = Test Intermediate CA Subject Public Key Info: Public Key Algorithm: rsaEncryption Public-Key: (1024 bit) Modulus: - 00:b8:25:2b:ee:59:9a:9d:bc:b4:48:ae:09:ce:0d: - ba:c5:83:57:03:92:fd:52:32:55:f5:e4:2e:a6:cf: - 9e:4b:c4:10:af:24:da:d5:dd:44:a8:d6:28:38:9c: - a5:11:c9:0b:70:a1:b5:71:cf:a4:35:c2:6a:17:b1: - b5:c7:cf:74:83:ac:7a:d5:3b:12:66:74:f2:4b:15: - b0:c2:59:af:0c:78:2c:42:3c:3f:8b:83:b3:1d:9a: - c8:bc:ce:b0:c8:f2:1a:a8:0a:1c:bb:6e:6e:d4:c6: - 10:66:3c:a8:ec:e3:c4:63:40:f6:79:ec:8b:14:ff: - 85:9e:2d:1a:e7:e8:31:56:81 + 00:b9:32:09:de:33:4a:4f:e2:04:73:49:d5:2e:2b: + 83:92:3a:94:e4:1b:0c:27:1b:f8:43:83:17:b8:75: + f5:a4:af:e3:4c:84:3e:6c:48:79:76:df:4d:f5:39: + af:92:4b:c5:a0:86:ab:35:cc:19:6b:93:82:c0:f8: + 44:4d:1a:14:5d:48:87:65:02:0e:b0:a8:96:d9:06: + 19:3f:aa:85:2d:84:c0:78:19:a6:96:ab:26:56:f7: + 6f:5a:1a:97:a2:01:88:00:99:10:8a:97:39:c8:22: + 6e:de:e5:56:f4:a6:23:cd:ea:48:0e:65:67:a4:73: + a0:50:91:de:ba:cf:54:08:8f Exponent: 65537 (0x10001) Signature Algorithm: sha1WithRSAEncryption - 35:fe:ee:96:31:c7:3d:91:eb:22:53:1f:bf:cc:20:cc:aa:f4: - 04:92:3c:8b:50:06:ea:a1:cc:b7:c2:4a:d6:02:af:53:a7:a4: - 71:81:78:bc:95:f3:2d:46:c4:83:4c:d5:92:11:7c:c7:67:d3: - 47:f6:06:9f:1c:46:da:d6:20:72:47:c2:57:d7:fb:66:d3:35: - 82:07:61:13:4e:4d:e6:0c:93:e6:f3:be:98:ff:e8:de:60:a7: - 06:94:cd:bb:f5:6e:b3:4e:0b:d6:e9:2b:72:bd:6e:ae:86:23: - 2d:44:33:c4:3b:a7:52:12:46:d2:76:95:06:3e:69:0f:72:60: - 16:d6 + 48:d5:9f:8d:90:bc:4a:59:38:1d:2b:83:2d:71:1c:74:9d:01: + 73:a0:b6:98:e7:1c:c2:22:66:23:33:0a:8f:64:ff:9c:6b:37: + 09:12:1c:15:12:cb:c3:61:d9:ab:cd:96:dd:95:fa:a6:02:67: + 3c:4c:ec:98:38:5c:fc:48:cc:85:a9:5b:49:2c:2b:06:66:07: + 9e:31:0f:93:10:ab:3e:9f:97:60:64:01:61:7e:86:15:bb:5e: + f1:90:31:a3:54:d0:86:0e:80:05:87:09:2e:65:b6:95:89:5c: + c1:e5:80:d9:b8:81:b6:ed:1a:20:b8:9b:22:ce:ef:d0:26:47: + 9d:57 -----BEGIN CA CERTIFICATE----- -MIIBnDCCAQWgAwIBAgIBADANBgkqhkiG9w0BAQUFADASMRAwDgYDVQQDEwdUZXN0IENBMCIYDzI -wMTcwMTAxMDAwMDAwWhgPMjAxODAxMDEwMDAwMDBaMBIxEDAOBgNVBAMTB1Rlc3QgQ0EwgZ8wDQ -YJKoZIhvcNAQEBBQADgY0AMIGJAoGBALglK+5Zmp28tEiuCc4NusWDVwOS/VIyVfXkLqbPnkvEE -K8k2tXdRKjWKDicpRHJC3ChtXHPpDXCahextcfPdIOsetU7EmZ08ksVsMJZrwx4LEI8P4uDsx2a -yLzOsMjyGqgKHLtubtTGEGY8qOzjxGNA9nnsixT/hZ4tGufoMVaBAgMBAAEwDQYJKoZIhvcNAQE -FBQADgYEANf7uljHHPZHrIlMfv8wgzKr0BJI8i1AG6qHMt8JK1gKvU6ekcYF4vJXzLUbEg0zVkh -F8x2fTR/YGnxxG2tYgckfCV9f7ZtM1ggdhE05N5gyT5vO+mP/o3mCnBpTNu/Vus04L1ukrcr1ur -oYjLUQzxDunUhJG0naVBj5pD3JgFtY= +MIIBqTCCARKgAwIBAgIBATANBgkqhkiG9w0BAQUFADASMRAwDgYDVQQDDAdUZXN0IENBMCIYDzI +wMTcwMTAxMDAwMDAwWhgPMjAxODAxMDEwMDAwMDBaMB8xHTAbBgNVBAMMFFRlc3QgSW50ZXJtZW +RpYXRlIENBMIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQC5MgneM0pP4gRzSdUuK4OSOpTkG +wwnG/hDgxe4dfWkr+NMhD5sSHl23031Oa+SS8Wghqs1zBlrk4LA+ERNGhRdSIdlAg6wqJbZBhk/ +qoUthMB4GaaWqyZW929aGpeiAYgAmRCKlznIIm7e5Vb0piPN6kgOZWekc6BQkd66z1QIjwIDAQA +BMA0GCSqGSIb3DQEBBQUAA4GBAEjVn42QvEpZOB0rgy1xHHSdAXOgtpjnHMIiZiMzCo9k/5xrNw +kSHBUSy8Nh2avNlt2V+qYCZzxM7Jg4XPxIzIWpW0ksKwZmB54xD5MQqz6fl2BkAWF+hhW7XvGQM +aNU0IYOgAWHCS5ltpWJXMHlgNm4gbbtGiC4myLO79AmR51X -----END CA CERTIFICATE----- $ openssl x509 -text < [CERTIFICATE] Certificate: Data: Version: 3 (0x2) - Serial Number: 3 (0x3) + Serial Number: 4 (0x4) Signature Algorithm: sha1WithRSAEncryption - Issuer: CN=Test CA + Issuer: CN = Test Intermediate CA Validity Not Before: Jan 1 00:00:00 2017 GMT Not After : Jan 1 00:00:00 2018 GMT - Subject: CN=Test Cert + Subject: CN = Test Cert Subject Public Key Info: Public Key Algorithm: rsaEncryption Public-Key: (1024 bit) Modulus: - 00:d5:12:3f:22:6f:b0:e1:43:c5:93:b3:c3:5b:70: - 52:b2:8b:10:ec:11:c4:c4:aa:aa:43:92:c8:d0:f3: - 35:23:e3:76:2d:b4:ea:93:26:6f:6a:79:1c:64:51: - d3:4d:21:4a:73:83:35:dc:a0:16:74:db:f0:b9:a5: - 46:35:8d:53:e8:7d:37:5b:4d:ad:a3:df:d6:ae:01: - 38:ad:16:09:6e:fd:65:ad:1c:4b:48:12:1e:48:a7: - ff:5b:47:c4:c9:3b:74:85:63:1a:0a:06:b2:9f:b9: - cb:ad:dc:3f:24:8b:a4:a7:8a:13:15:45:89:24:c1: - a7:3b:c2:a2:c8:74:f1:3f:6f + 00:bc:4c:d5:b3:8d:92:fa:66:ac:32:43:1a:9e:eb: + 17:e0:aa:76:35:1b:1d:10:48:4e:3e:22:8b:75:2e: + e8:6f:a4:55:1e:0a:5e:60:c0:61:f1:7d:29:58:7e: + 0b:ef:29:be:ad:f8:f7:43:c8:58:95:14:5b:1d:af: + 4a:b8:90:9e:4e:ec:4e:b3:86:7a:b9:96:c1:34:d3: + b9:a6:57:df:9b:bd:d9:dd:67:15:54:d4:9f:65:b8: + 33:29:59:ba:9a:c6:75:ea:a5:76:3d:a4:57:0f:e2: + e4:c3:91:35:1d:6e:ff:61:7d:c2:53:23:66:b2:a8: + 0b:e1:c7:55:48:c5:2b:4d:7d Exponent: 65537 (0x10001) Signature Algorithm: sha1WithRSAEncryption - 04:21:70:de:14:92:27:13:e8:d2:b0:51:f0:af:34:75:0b:a7: - ff:84:cb:c6:96:30:80:01:f5:c1:3a:c6:81:ee:ba:89:60:33: - c3:e5:0f:43:cc:ac:81:8d:09:fb:25:e1:67:40:64:a3:ca:fd: - bd:9c:c4:73:e4:bc:4d:8e:e2:70:f1:17:ce:b4:ab:a0:b2:63: - 72:25:27:ae:d5:8e:18:73:0d:dc:12:5a:32:1c:b7:da:cd:23: - 5b:c8:87:58:08:3e:95:0c:fd:c8:48:a2:75:6e:79:f2:00:82: - 6e:b5:cc:71:e3:79:ca:68:85:9b:1b:5c:52:bf:a2:5a:71:e3: - 05:b5 + 18:bb:93:d9:2a:e0:34:69:2f:96:57:ac:55:ac:a7:83:04:b4: + bc:22:7f:5f:f7:c0:dc:ac:af:13:9b:86:7e:ac:02:8c:44:83: + 2e:c0:fa:a1:77:1d:dd:86:31:7e:98:93:c0:4f:b2:3d:be:30: + 6f:a5:fc:c7:2e:b1:b8:08:d2:17:cb:60:55:bf:5a:e0:94:f3: + 1d:44:fa:b1:2f:1a:24:c5:33:e1:d4:f0:ac:d5:2c:67:da:a7: + 5d:ee:eb:d6:7a:a7:41:e8:94:7a:34:43:b2:1f:ab:e9:cf:5d: + 25:49:56:18:d2:a9:49:1a:37:34:43:c7:06:96:4a:29:38:cc: + f2:1c -----BEGIN CERTIFICATE----- -MIIBnjCCAQegAwIBAgIBAzANBgkqhkiG9w0BAQUFADASMRAwDgYDVQQDEwdUZXN0IENBMCIYDzI -wMTcwMTAxMDAwMDAwWhgPMjAxODAxMDEwMDAwMDBaMBQxEjAQBgNVBAMTCVRlc3QgQ2VydDCBnz -ANBgkqhkiG9w0BAQEFAAOBjQAwgYkCgYEA1RI/Im+w4UPFk7PDW3BSsosQ7BHExKqqQ5LI0PM1I -+N2LbTqkyZvankcZFHTTSFKc4M13KAWdNvwuaVGNY1T6H03W02to9/WrgE4rRYJbv1lrRxLSBIe -SKf/W0fEyTt0hWMaCgayn7nLrdw/JIukp4oTFUWJJMGnO8KiyHTxP28CAwEAATANBgkqhkiG9w0 -BAQUFAAOBgQAEIXDeFJInE+jSsFHwrzR1C6f/hMvGljCAAfXBOsaB7rqJYDPD5Q9DzKyBjQn7Je -FnQGSjyv29nMRz5LxNjuJw8RfOtKugsmNyJSeu1Y4Ycw3cEloyHLfazSNbyIdYCD6VDP3ISKJ1b -nnyAIJutcxx43nKaIWbG1xSv6JaceMFtQ== +MIIBqzCCARSgAwIBAgIBBDANBgkqhkiG9w0BAQUFADAfMR0wGwYDVQQDDBRUZXN0IEludGVybWV +kaWF0ZSBDQTAiGA8yMDE3MDEwMTAwMDAwMFoYDzIwMTgwMTAxMDAwMDAwWjAUMRIwEAYDVQQDDA +lUZXN0IENlcnQwgZ8wDQYJKoZIhvcNAQEBBQADgY0AMIGJAoGBALxM1bONkvpmrDJDGp7rF+Cqd +jUbHRBITj4ii3Uu6G+kVR4KXmDAYfF9KVh+C+8pvq3490PIWJUUWx2vSriQnk7sTrOGermWwTTT +uaZX35u92d1nFVTUn2W4MylZuprGdeqldj2kVw/i5MORNR1u/2F9wlMjZrKoC+HHVUjFK019AgM +BAAEwDQYJKoZIhvcNAQEFBQADgYEAGLuT2SrgNGkvllesVayngwS0vCJ/X/fA3KyvE5uGfqwCjE +SDLsD6oXcd3YYxfpiTwE+yPb4wb6X8xy6xuAjSF8tgVb9a4JTzHUT6sS8aJMUz4dTwrNUsZ9qnX +e7r1nqnQeiUejRDsh+r6c9dJUlWGNKpSRo3NEPHBpZKKTjM8hw= -----END CERTIFICATE----- $ openssl asn1parse -i < [OCSP REQUEST] @@ -134,10 +134,10 @@ 10:d=5 hl=2 l= 9 cons: SEQUENCE 12:d=6 hl=2 l= 5 prim: OBJECT :sha1 19:d=6 hl=2 l= 0 prim: NULL - 21:d=5 hl=2 l= 20 prim: OCTET STRING [HEX DUMP]:02FF75DA24DE8ADD150FAB689DCCE6E6636D0901 - 43:d=5 hl=2 l= 20 prim: OCTET STRING [HEX DUMP]:84E1BA52A25C543CA972491224BC8B1ECA8B9FF4 - 65:d=5 hl=2 l= 1 prim: INTEGER :03 + 21:d=5 hl=2 l= 20 prim: OCTET STRING [HEX DUMP]:449B1C5B31C6E9990966523E49C3F773C024190A + 43:d=5 hl=2 l= 20 prim: OCTET STRING [HEX DUMP]:FC6D3387CC3B39B049C755C46DF4395548930BCE + 65:d=5 hl=2 l= 1 prim: INTEGER :04 -----BEGIN OCSP REQUEST----- -MEIwQDA+MDwwOjAJBgUrDgMCGgUABBQC/3XaJN6K3RUPq2idzObmY20JAQQUhOG6UqJcVDypckk -SJLyLHsqLn/QCAQM= +MEIwQDA+MDwwOjAJBgUrDgMCGgUABBREmxxbMcbpmQlmUj5Jw/dzwCQZCgQU/G0zh8w7ObBJx1X +EbfQ5VUiTC84CAQQ= -----END OCSP REQUEST-----
diff --git a/net/data/ocsp_unittest/good_response_sha256.pem b/net/data/ocsp_unittest/good_response_sha256.pem index 9e091150..ccf3863d 100644 --- a/net/data/ocsp_unittest/good_response_sha256.pem +++ b/net/data/ocsp_unittest/good_response_sha256.pem
@@ -5,123 +5,123 @@ OCSP Response Status: successful (0x0) Response Type: Basic OCSP Response Version: 1 (0x0) - Responder Id: CN = Test CA + Responder Id: CN = Test Intermediate CA Produced At: Mar 2 00:00:00 2017 GMT Responses: Certificate ID: Hash Algorithm: sha1 - Issuer Name Hash: 02FF75DA24DE8ADD150FAB689DCCE6E6636D0901 - Issuer Key Hash: 84E1BA52A25C543CA972491224BC8B1ECA8B9FF4 - Serial Number: 03 + Issuer Name Hash: 449B1C5B31C6E9990966523E49C3F773C024190A + Issuer Key Hash: FC6D3387CC3B39B049C755C46DF4395548930BCE + Serial Number: 04 Cert Status: good This Update: Mar 1 00:00:00 2017 GMT Signature Algorithm: sha256WithRSAEncryption - 29:ee:e5:8b:dd:01:0f:ed:15:42:9d:58:2f:0e:3a:50:f0:0d: - 65:5a:0e:f0:92:3f:40:00:4f:bb:9c:36:ee:30:74:7e:c7:8b: - f1:8e:83:e2:08:7a:ba:31:e2:bb:e0:a9:a8:11:ee:5a:e7:2e: - c8:0d:95:aa:2a:a0:d2:f0:dd:d2:d6:24:c9:57:03:b7:09:17: - f9:9f:78:6e:ee:e0:41:35:21:94:36:a1:03:66:d8:ec:76:de: - 42:bb:cc:04:66:f7:ae:15:7f:c9:07:cc:75:6f:c3:7f:fb:af: - e4:6e:6c:c6:f6:82:ae:05:4c:33:60:b3:c4:dc:0b:4c:ce:e1: - 09:f0 + 98:ea:a9:43:05:8e:89:c8:ba:9d:c0:85:bb:ce:5a:79:d1:5a: + cf:58:62:9d:c6:6d:dc:17:39:7c:47:2a:3b:ce:7d:e0:3d:07: + 05:ee:83:aa:37:21:17:de:8e:a3:38:b2:f2:09:cc:f6:6a:dc: + bc:67:3c:bf:15:10:18:08:27:2f:66:c0:27:e2:d0:99:9c:7f: + 5f:3b:e4:64:e5:db:63:53:50:a5:ce:ef:c7:f3:1d:b9:11:be: + d3:fc:68:be:cd:c3:8a:4d:88:ce:c7:e7:f3:a2:f7:6f:f6:8e: + a7:bb:82:b2:cd:b5:2d:f9:75:d5:be:95:03:53:39:4c:08:0b: + 8d:bc -----BEGIN OCSP RESPONSE----- -MIIBKwoBAKCCASQwggEgBgkrBgEFBQcwAQEEggERMIIBDTB4oRQwEjEQMA4GA1UEAxMHVGVzdCB -DQRgPMjAxNzAzMDIwMDAwMDBaME8wTTA4MAcGBSsOAwIaBBQC/3XaJN6K3RUPq2idzObmY20JAQ -QUhOG6UqJcVDypckkSJLyLHsqLn/QCAQOAABgPMjAxNzAzMDEwMDAwMDBaMA0GCSqGSIb3DQEBC -wUAA4GBACnu5YvdAQ/tFUKdWC8OOlDwDWVaDvCSP0AAT7ucNu4wdH7Hi/GOg+IIerox4rvgqagR -7lrnLsgNlaoqoNLw3dLWJMlXA7cJF/mfeG7u4EE1IZQ2oQNm2Ox23kK7zARm964Vf8kHzHVvw3/ -7r+RubMb2gq4FTDNgs8TcC0zO4Qnw +MIIBOQoBAKCCATIwggEuBgkrBgEFBQcwAQEEggEfMIIBGzCBhaEhMB8xHTAbBgNVBAMMFFRlc3Q +gSW50ZXJtZWRpYXRlIENBGA8yMDE3MDMwMjAwMDAwMFowTzBNMDgwBwYFKw4DAhoEFESbHFsxxu +mZCWZSPknD93PAJBkKBBT8bTOHzDs5sEnHVcRt9DlVSJMLzgIBBIAAGA8yMDE3MDMwMTAwMDAwM +FowDQYJKoZIhvcNAQELBQADgYEAmOqpQwWOici6ncCFu85aedFaz1hincZt3Bc5fEcqO8594D0H +Be6DqjchF96Ooziy8gnM9mrcvGc8vxUQGAgnL2bAJ+LQmZx/XzvkZOXbY1NQpc7vx/MduRG+0/x +ovs3Dik2Izsfn86L3b/aOp7uCss21Lfl11b6VA1M5TAgLjbw= -----END OCSP RESPONSE----- $ openssl x509 -text < [CA CERTIFICATE] Certificate: Data: Version: 3 (0x2) - Serial Number: 0 (0x0) + Serial Number: 1 (0x1) Signature Algorithm: sha1WithRSAEncryption - Issuer: CN=Test CA + Issuer: CN = Test CA Validity Not Before: Jan 1 00:00:00 2017 GMT Not After : Jan 1 00:00:00 2018 GMT - Subject: CN=Test CA + Subject: CN = Test Intermediate CA Subject Public Key Info: Public Key Algorithm: rsaEncryption Public-Key: (1024 bit) Modulus: - 00:b8:25:2b:ee:59:9a:9d:bc:b4:48:ae:09:ce:0d: - ba:c5:83:57:03:92:fd:52:32:55:f5:e4:2e:a6:cf: - 9e:4b:c4:10:af:24:da:d5:dd:44:a8:d6:28:38:9c: - a5:11:c9:0b:70:a1:b5:71:cf:a4:35:c2:6a:17:b1: - b5:c7:cf:74:83:ac:7a:d5:3b:12:66:74:f2:4b:15: - b0:c2:59:af:0c:78:2c:42:3c:3f:8b:83:b3:1d:9a: - c8:bc:ce:b0:c8:f2:1a:a8:0a:1c:bb:6e:6e:d4:c6: - 10:66:3c:a8:ec:e3:c4:63:40:f6:79:ec:8b:14:ff: - 85:9e:2d:1a:e7:e8:31:56:81 + 00:b9:32:09:de:33:4a:4f:e2:04:73:49:d5:2e:2b: + 83:92:3a:94:e4:1b:0c:27:1b:f8:43:83:17:b8:75: + f5:a4:af:e3:4c:84:3e:6c:48:79:76:df:4d:f5:39: + af:92:4b:c5:a0:86:ab:35:cc:19:6b:93:82:c0:f8: + 44:4d:1a:14:5d:48:87:65:02:0e:b0:a8:96:d9:06: + 19:3f:aa:85:2d:84:c0:78:19:a6:96:ab:26:56:f7: + 6f:5a:1a:97:a2:01:88:00:99:10:8a:97:39:c8:22: + 6e:de:e5:56:f4:a6:23:cd:ea:48:0e:65:67:a4:73: + a0:50:91:de:ba:cf:54:08:8f Exponent: 65537 (0x10001) Signature Algorithm: sha1WithRSAEncryption - 35:fe:ee:96:31:c7:3d:91:eb:22:53:1f:bf:cc:20:cc:aa:f4: - 04:92:3c:8b:50:06:ea:a1:cc:b7:c2:4a:d6:02:af:53:a7:a4: - 71:81:78:bc:95:f3:2d:46:c4:83:4c:d5:92:11:7c:c7:67:d3: - 47:f6:06:9f:1c:46:da:d6:20:72:47:c2:57:d7:fb:66:d3:35: - 82:07:61:13:4e:4d:e6:0c:93:e6:f3:be:98:ff:e8:de:60:a7: - 06:94:cd:bb:f5:6e:b3:4e:0b:d6:e9:2b:72:bd:6e:ae:86:23: - 2d:44:33:c4:3b:a7:52:12:46:d2:76:95:06:3e:69:0f:72:60: - 16:d6 + 48:d5:9f:8d:90:bc:4a:59:38:1d:2b:83:2d:71:1c:74:9d:01: + 73:a0:b6:98:e7:1c:c2:22:66:23:33:0a:8f:64:ff:9c:6b:37: + 09:12:1c:15:12:cb:c3:61:d9:ab:cd:96:dd:95:fa:a6:02:67: + 3c:4c:ec:98:38:5c:fc:48:cc:85:a9:5b:49:2c:2b:06:66:07: + 9e:31:0f:93:10:ab:3e:9f:97:60:64:01:61:7e:86:15:bb:5e: + f1:90:31:a3:54:d0:86:0e:80:05:87:09:2e:65:b6:95:89:5c: + c1:e5:80:d9:b8:81:b6:ed:1a:20:b8:9b:22:ce:ef:d0:26:47: + 9d:57 -----BEGIN CA CERTIFICATE----- -MIIBnDCCAQWgAwIBAgIBADANBgkqhkiG9w0BAQUFADASMRAwDgYDVQQDEwdUZXN0IENBMCIYDzI -wMTcwMTAxMDAwMDAwWhgPMjAxODAxMDEwMDAwMDBaMBIxEDAOBgNVBAMTB1Rlc3QgQ0EwgZ8wDQ -YJKoZIhvcNAQEBBQADgY0AMIGJAoGBALglK+5Zmp28tEiuCc4NusWDVwOS/VIyVfXkLqbPnkvEE -K8k2tXdRKjWKDicpRHJC3ChtXHPpDXCahextcfPdIOsetU7EmZ08ksVsMJZrwx4LEI8P4uDsx2a -yLzOsMjyGqgKHLtubtTGEGY8qOzjxGNA9nnsixT/hZ4tGufoMVaBAgMBAAEwDQYJKoZIhvcNAQE -FBQADgYEANf7uljHHPZHrIlMfv8wgzKr0BJI8i1AG6qHMt8JK1gKvU6ekcYF4vJXzLUbEg0zVkh -F8x2fTR/YGnxxG2tYgckfCV9f7ZtM1ggdhE05N5gyT5vO+mP/o3mCnBpTNu/Vus04L1ukrcr1ur -oYjLUQzxDunUhJG0naVBj5pD3JgFtY= +MIIBqTCCARKgAwIBAgIBATANBgkqhkiG9w0BAQUFADASMRAwDgYDVQQDDAdUZXN0IENBMCIYDzI +wMTcwMTAxMDAwMDAwWhgPMjAxODAxMDEwMDAwMDBaMB8xHTAbBgNVBAMMFFRlc3QgSW50ZXJtZW +RpYXRlIENBMIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQC5MgneM0pP4gRzSdUuK4OSOpTkG +wwnG/hDgxe4dfWkr+NMhD5sSHl23031Oa+SS8Wghqs1zBlrk4LA+ERNGhRdSIdlAg6wqJbZBhk/ +qoUthMB4GaaWqyZW929aGpeiAYgAmRCKlznIIm7e5Vb0piPN6kgOZWekc6BQkd66z1QIjwIDAQA +BMA0GCSqGSIb3DQEBBQUAA4GBAEjVn42QvEpZOB0rgy1xHHSdAXOgtpjnHMIiZiMzCo9k/5xrNw +kSHBUSy8Nh2avNlt2V+qYCZzxM7Jg4XPxIzIWpW0ksKwZmB54xD5MQqz6fl2BkAWF+hhW7XvGQM +aNU0IYOgAWHCS5ltpWJXMHlgNm4gbbtGiC4myLO79AmR51X -----END CA CERTIFICATE----- $ openssl x509 -text < [CERTIFICATE] Certificate: Data: Version: 3 (0x2) - Serial Number: 3 (0x3) + Serial Number: 4 (0x4) Signature Algorithm: sha1WithRSAEncryption - Issuer: CN=Test CA + Issuer: CN = Test Intermediate CA Validity Not Before: Jan 1 00:00:00 2017 GMT Not After : Jan 1 00:00:00 2018 GMT - Subject: CN=Test Cert + Subject: CN = Test Cert Subject Public Key Info: Public Key Algorithm: rsaEncryption Public-Key: (1024 bit) Modulus: - 00:d5:12:3f:22:6f:b0:e1:43:c5:93:b3:c3:5b:70: - 52:b2:8b:10:ec:11:c4:c4:aa:aa:43:92:c8:d0:f3: - 35:23:e3:76:2d:b4:ea:93:26:6f:6a:79:1c:64:51: - d3:4d:21:4a:73:83:35:dc:a0:16:74:db:f0:b9:a5: - 46:35:8d:53:e8:7d:37:5b:4d:ad:a3:df:d6:ae:01: - 38:ad:16:09:6e:fd:65:ad:1c:4b:48:12:1e:48:a7: - ff:5b:47:c4:c9:3b:74:85:63:1a:0a:06:b2:9f:b9: - cb:ad:dc:3f:24:8b:a4:a7:8a:13:15:45:89:24:c1: - a7:3b:c2:a2:c8:74:f1:3f:6f + 00:bc:4c:d5:b3:8d:92:fa:66:ac:32:43:1a:9e:eb: + 17:e0:aa:76:35:1b:1d:10:48:4e:3e:22:8b:75:2e: + e8:6f:a4:55:1e:0a:5e:60:c0:61:f1:7d:29:58:7e: + 0b:ef:29:be:ad:f8:f7:43:c8:58:95:14:5b:1d:af: + 4a:b8:90:9e:4e:ec:4e:b3:86:7a:b9:96:c1:34:d3: + b9:a6:57:df:9b:bd:d9:dd:67:15:54:d4:9f:65:b8: + 33:29:59:ba:9a:c6:75:ea:a5:76:3d:a4:57:0f:e2: + e4:c3:91:35:1d:6e:ff:61:7d:c2:53:23:66:b2:a8: + 0b:e1:c7:55:48:c5:2b:4d:7d Exponent: 65537 (0x10001) Signature Algorithm: sha1WithRSAEncryption - 04:21:70:de:14:92:27:13:e8:d2:b0:51:f0:af:34:75:0b:a7: - ff:84:cb:c6:96:30:80:01:f5:c1:3a:c6:81:ee:ba:89:60:33: - c3:e5:0f:43:cc:ac:81:8d:09:fb:25:e1:67:40:64:a3:ca:fd: - bd:9c:c4:73:e4:bc:4d:8e:e2:70:f1:17:ce:b4:ab:a0:b2:63: - 72:25:27:ae:d5:8e:18:73:0d:dc:12:5a:32:1c:b7:da:cd:23: - 5b:c8:87:58:08:3e:95:0c:fd:c8:48:a2:75:6e:79:f2:00:82: - 6e:b5:cc:71:e3:79:ca:68:85:9b:1b:5c:52:bf:a2:5a:71:e3: - 05:b5 + 18:bb:93:d9:2a:e0:34:69:2f:96:57:ac:55:ac:a7:83:04:b4: + bc:22:7f:5f:f7:c0:dc:ac:af:13:9b:86:7e:ac:02:8c:44:83: + 2e:c0:fa:a1:77:1d:dd:86:31:7e:98:93:c0:4f:b2:3d:be:30: + 6f:a5:fc:c7:2e:b1:b8:08:d2:17:cb:60:55:bf:5a:e0:94:f3: + 1d:44:fa:b1:2f:1a:24:c5:33:e1:d4:f0:ac:d5:2c:67:da:a7: + 5d:ee:eb:d6:7a:a7:41:e8:94:7a:34:43:b2:1f:ab:e9:cf:5d: + 25:49:56:18:d2:a9:49:1a:37:34:43:c7:06:96:4a:29:38:cc: + f2:1c -----BEGIN CERTIFICATE----- -MIIBnjCCAQegAwIBAgIBAzANBgkqhkiG9w0BAQUFADASMRAwDgYDVQQDEwdUZXN0IENBMCIYDzI -wMTcwMTAxMDAwMDAwWhgPMjAxODAxMDEwMDAwMDBaMBQxEjAQBgNVBAMTCVRlc3QgQ2VydDCBnz -ANBgkqhkiG9w0BAQEFAAOBjQAwgYkCgYEA1RI/Im+w4UPFk7PDW3BSsosQ7BHExKqqQ5LI0PM1I -+N2LbTqkyZvankcZFHTTSFKc4M13KAWdNvwuaVGNY1T6H03W02to9/WrgE4rRYJbv1lrRxLSBIe -SKf/W0fEyTt0hWMaCgayn7nLrdw/JIukp4oTFUWJJMGnO8KiyHTxP28CAwEAATANBgkqhkiG9w0 -BAQUFAAOBgQAEIXDeFJInE+jSsFHwrzR1C6f/hMvGljCAAfXBOsaB7rqJYDPD5Q9DzKyBjQn7Je -FnQGSjyv29nMRz5LxNjuJw8RfOtKugsmNyJSeu1Y4Ycw3cEloyHLfazSNbyIdYCD6VDP3ISKJ1b -nnyAIJutcxx43nKaIWbG1xSv6JaceMFtQ== +MIIBqzCCARSgAwIBAgIBBDANBgkqhkiG9w0BAQUFADAfMR0wGwYDVQQDDBRUZXN0IEludGVybWV +kaWF0ZSBDQTAiGA8yMDE3MDEwMTAwMDAwMFoYDzIwMTgwMTAxMDAwMDAwWjAUMRIwEAYDVQQDDA +lUZXN0IENlcnQwgZ8wDQYJKoZIhvcNAQEBBQADgY0AMIGJAoGBALxM1bONkvpmrDJDGp7rF+Cqd +jUbHRBITj4ii3Uu6G+kVR4KXmDAYfF9KVh+C+8pvq3490PIWJUUWx2vSriQnk7sTrOGermWwTTT +uaZX35u92d1nFVTUn2W4MylZuprGdeqldj2kVw/i5MORNR1u/2F9wlMjZrKoC+HHVUjFK019AgM +BAAEwDQYJKoZIhvcNAQEFBQADgYEAGLuT2SrgNGkvllesVayngwS0vCJ/X/fA3KyvE5uGfqwCjE +SDLsD6oXcd3YYxfpiTwE+yPb4wb6X8xy6xuAjSF8tgVb9a4JTzHUT6sS8aJMUz4dTwrNUsZ9qnX +e7r1nqnQeiUejRDsh+r6c9dJUlWGNKpSRo3NEPHBpZKKTjM8hw= -----END CERTIFICATE----- $ openssl asn1parse -i < [OCSP REQUEST] @@ -133,10 +133,10 @@ 10:d=5 hl=2 l= 9 cons: SEQUENCE 12:d=6 hl=2 l= 5 prim: OBJECT :sha1 19:d=6 hl=2 l= 0 prim: NULL - 21:d=5 hl=2 l= 20 prim: OCTET STRING [HEX DUMP]:02FF75DA24DE8ADD150FAB689DCCE6E6636D0901 - 43:d=5 hl=2 l= 20 prim: OCTET STRING [HEX DUMP]:84E1BA52A25C543CA972491224BC8B1ECA8B9FF4 - 65:d=5 hl=2 l= 1 prim: INTEGER :03 + 21:d=5 hl=2 l= 20 prim: OCTET STRING [HEX DUMP]:449B1C5B31C6E9990966523E49C3F773C024190A + 43:d=5 hl=2 l= 20 prim: OCTET STRING [HEX DUMP]:FC6D3387CC3B39B049C755C46DF4395548930BCE + 65:d=5 hl=2 l= 1 prim: INTEGER :04 -----BEGIN OCSP REQUEST----- -MEIwQDA+MDwwOjAJBgUrDgMCGgUABBQC/3XaJN6K3RUPq2idzObmY20JAQQUhOG6UqJcVDypckk -SJLyLHsqLn/QCAQM= +MEIwQDA+MDwwOjAJBgUrDgMCGgUABBREmxxbMcbpmQlmUj5Jw/dzwCQZCgQU/G0zh8w7ObBJx1X +EbfQ5VUiTC84CAQQ= -----END OCSP REQUEST-----
diff --git a/net/data/ocsp_unittest/has_extension.pem b/net/data/ocsp_unittest/has_extension.pem index a9c3f88..f8259a2 100644 --- a/net/data/ocsp_unittest/has_extension.pem +++ b/net/data/ocsp_unittest/has_extension.pem
@@ -1,133 +1,133 @@ Includes an x509v3 extension $ openssl asn1parse -i < [OCSP RESPONSE] - 0:d=0 hl=4 l= 319 cons: SEQUENCE + 0:d=0 hl=4 l= 332 cons: SEQUENCE 4:d=1 hl=2 l= 1 prim: ENUMERATED :00 - 7:d=1 hl=4 l= 312 cons: cont [ 0 ] - 11:d=2 hl=4 l= 308 cons: SEQUENCE + 7:d=1 hl=4 l= 325 cons: cont [ 0 ] + 11:d=2 hl=4 l= 321 cons: SEQUENCE 15:d=3 hl=2 l= 9 prim: OBJECT :Basic OCSP Response - 26:d=3 hl=4 l= 293 prim: OCTET STRING - 0:d=0 hl=4 l= 289 cons: SEQUENCE - 4:d=1 hl=3 l= 139 cons: SEQUENCE - 7:d=2 hl=2 l= 20 cons: cont [ 1 ] - 9:d=3 hl=2 l= 18 cons: SEQUENCE - 11:d=4 hl=2 l= 16 cons: SET - 13:d=5 hl=2 l= 14 cons: SEQUENCE + 26:d=3 hl=4 l= 306 prim: OCTET STRING + 0:d=0 hl=4 l= 302 cons: SEQUENCE + 4:d=1 hl=3 l= 152 cons: SEQUENCE + 7:d=2 hl=2 l= 33 cons: cont [ 1 ] + 9:d=3 hl=2 l= 31 cons: SEQUENCE + 11:d=4 hl=2 l= 29 cons: SET + 13:d=5 hl=2 l= 27 cons: SEQUENCE 15:d=6 hl=2 l= 3 prim: OBJECT :commonName - 20:d=6 hl=2 l= 7 prim: PRINTABLESTRING :Test CA - 29:d=2 hl=2 l= 15 prim: GENERALIZEDTIME :20170302000000Z - 46:d=2 hl=2 l= 79 cons: SEQUENCE - 48:d=3 hl=2 l= 77 cons: SEQUENCE - 50:d=4 hl=2 l= 56 cons: SEQUENCE - 52:d=5 hl=2 l= 7 cons: SEQUENCE - 54:d=6 hl=2 l= 5 prim: OBJECT :sha1 - 61:d=5 hl=2 l= 20 prim: OCTET STRING [HEX DUMP]:02FF75DA24DE8ADD150FAB689DCCE6E6636D0901 - 83:d=5 hl=2 l= 20 prim: OCTET STRING [HEX DUMP]:84E1BA52A25C543CA972491224BC8B1ECA8B9FF4 - 105:d=5 hl=2 l= 1 prim: INTEGER :03 - 108:d=4 hl=2 l= 0 prim: cont [ 0 ] - 110:d=4 hl=2 l= 15 prim: GENERALIZEDTIME :20170301000000Z - 127:d=2 hl=2 l= 17 cons: cont [ 1 ] - 129:d=3 hl=2 l= 15 cons: SEQUENCE - 131:d=4 hl=2 l= 13 cons: SEQUENCE - 133:d=5 hl=2 l= 3 prim: OBJECT :1.2.3.4 + 20:d=6 hl=2 l= 20 prim: UTF8STRING :Test Intermediate CA + 42:d=2 hl=2 l= 15 prim: GENERALIZEDTIME :20170302000000Z + 59:d=2 hl=2 l= 79 cons: SEQUENCE + 61:d=3 hl=2 l= 77 cons: SEQUENCE + 63:d=4 hl=2 l= 56 cons: SEQUENCE + 65:d=5 hl=2 l= 7 cons: SEQUENCE + 67:d=6 hl=2 l= 5 prim: OBJECT :sha1 + 74:d=5 hl=2 l= 20 prim: OCTET STRING [HEX DUMP]:449B1C5B31C6E9990966523E49C3F773C024190A + 96:d=5 hl=2 l= 20 prim: OCTET STRING [HEX DUMP]:FC6D3387CC3B39B049C755C46DF4395548930BCE + 118:d=5 hl=2 l= 1 prim: INTEGER :04 + 121:d=4 hl=2 l= 0 prim: cont [ 0 ] + 123:d=4 hl=2 l= 15 prim: GENERALIZEDTIME :20170301000000Z + 140:d=2 hl=2 l= 17 cons: cont [ 1 ] + 142:d=3 hl=2 l= 15 cons: SEQUENCE + 144:d=4 hl=2 l= 13 cons: SEQUENCE + 146:d=5 hl=2 l= 3 prim: OBJECT :1.2.3.4 Error in encoding -----BEGIN OCSP RESPONSE----- -MIIBPwoBAKCCATgwggE0BgkrBgEFBQcwAQEEggElMIIBITCBi6EUMBIxEDAOBgNVBAMTB1Rlc3Q -gQ0EYDzIwMTcwMzAyMDAwMDAwWjBPME0wODAHBgUrDgMCGgQUAv912iTeit0VD6tonczm5mNtCQ -EEFIThulKiXFQ8qXJJEiS8ix7Ki5/0AgEDgAAYDzIwMTcwMzAxMDAwMDAwWqERMA8wDQYDKgMER -EVBREJFRUYwDQYJKoZIhvcNAQEFBQADgYEAXpfXey/89yO0EqFOf7BaqWr1baC1yGQqZQfUbJ0P -oMel2u3CqMbH/HsC2hMnbQuOPI4tcLzlIomNbqyC/8xBeCLB7FElNbXgBG9wxQmErN5uLjipjdw -WPujw2XXczLjRSEHoSE70T/l5B7pP4u9BmUfiesJ3GTQPMd4DPLpYdJw= +MIIBTAoBAKCCAUUwggFBBgkrBgEFBQcwAQEEggEyMIIBLjCBmKEhMB8xHTAbBgNVBAMMFFRlc3Q +gSW50ZXJtZWRpYXRlIENBGA8yMDE3MDMwMjAwMDAwMFowTzBNMDgwBwYFKw4DAhoEFESbHFsxxu +mZCWZSPknD93PAJBkKBBT8bTOHzDs5sEnHVcRt9DlVSJMLzgIBBIAAGA8yMDE3MDMwMTAwMDAwM +FqhETAPMA0GAyoDBERFQURCRUVGMA0GCSqGSIb3DQEBBQUAA4GBADYEfDXJe8NqCfIq6MQvpDJ8 +HthKjJw45zwcvf28Elp+Yv7HFDYLL75b/X34n/Ib3Uw8bwI7wnPwBn2qJ4ss+blGvfj5mWihAvA +lK5Vf6bygpwo0wRn+UmrPP/5+AfMIC87lZgvKii6Y6/UNKtaxOG7TzyzFxHZI42up+04gmMM3 -----END OCSP RESPONSE----- $ openssl x509 -text < [CA CERTIFICATE] Certificate: Data: Version: 3 (0x2) - Serial Number: 0 (0x0) + Serial Number: 1 (0x1) Signature Algorithm: sha1WithRSAEncryption - Issuer: CN=Test CA + Issuer: CN = Test CA Validity Not Before: Jan 1 00:00:00 2017 GMT Not After : Jan 1 00:00:00 2018 GMT - Subject: CN=Test CA + Subject: CN = Test Intermediate CA Subject Public Key Info: Public Key Algorithm: rsaEncryption Public-Key: (1024 bit) Modulus: - 00:b8:25:2b:ee:59:9a:9d:bc:b4:48:ae:09:ce:0d: - ba:c5:83:57:03:92:fd:52:32:55:f5:e4:2e:a6:cf: - 9e:4b:c4:10:af:24:da:d5:dd:44:a8:d6:28:38:9c: - a5:11:c9:0b:70:a1:b5:71:cf:a4:35:c2:6a:17:b1: - b5:c7:cf:74:83:ac:7a:d5:3b:12:66:74:f2:4b:15: - b0:c2:59:af:0c:78:2c:42:3c:3f:8b:83:b3:1d:9a: - c8:bc:ce:b0:c8:f2:1a:a8:0a:1c:bb:6e:6e:d4:c6: - 10:66:3c:a8:ec:e3:c4:63:40:f6:79:ec:8b:14:ff: - 85:9e:2d:1a:e7:e8:31:56:81 + 00:b9:32:09:de:33:4a:4f:e2:04:73:49:d5:2e:2b: + 83:92:3a:94:e4:1b:0c:27:1b:f8:43:83:17:b8:75: + f5:a4:af:e3:4c:84:3e:6c:48:79:76:df:4d:f5:39: + af:92:4b:c5:a0:86:ab:35:cc:19:6b:93:82:c0:f8: + 44:4d:1a:14:5d:48:87:65:02:0e:b0:a8:96:d9:06: + 19:3f:aa:85:2d:84:c0:78:19:a6:96:ab:26:56:f7: + 6f:5a:1a:97:a2:01:88:00:99:10:8a:97:39:c8:22: + 6e:de:e5:56:f4:a6:23:cd:ea:48:0e:65:67:a4:73: + a0:50:91:de:ba:cf:54:08:8f Exponent: 65537 (0x10001) Signature Algorithm: sha1WithRSAEncryption - 35:fe:ee:96:31:c7:3d:91:eb:22:53:1f:bf:cc:20:cc:aa:f4: - 04:92:3c:8b:50:06:ea:a1:cc:b7:c2:4a:d6:02:af:53:a7:a4: - 71:81:78:bc:95:f3:2d:46:c4:83:4c:d5:92:11:7c:c7:67:d3: - 47:f6:06:9f:1c:46:da:d6:20:72:47:c2:57:d7:fb:66:d3:35: - 82:07:61:13:4e:4d:e6:0c:93:e6:f3:be:98:ff:e8:de:60:a7: - 06:94:cd:bb:f5:6e:b3:4e:0b:d6:e9:2b:72:bd:6e:ae:86:23: - 2d:44:33:c4:3b:a7:52:12:46:d2:76:95:06:3e:69:0f:72:60: - 16:d6 + 48:d5:9f:8d:90:bc:4a:59:38:1d:2b:83:2d:71:1c:74:9d:01: + 73:a0:b6:98:e7:1c:c2:22:66:23:33:0a:8f:64:ff:9c:6b:37: + 09:12:1c:15:12:cb:c3:61:d9:ab:cd:96:dd:95:fa:a6:02:67: + 3c:4c:ec:98:38:5c:fc:48:cc:85:a9:5b:49:2c:2b:06:66:07: + 9e:31:0f:93:10:ab:3e:9f:97:60:64:01:61:7e:86:15:bb:5e: + f1:90:31:a3:54:d0:86:0e:80:05:87:09:2e:65:b6:95:89:5c: + c1:e5:80:d9:b8:81:b6:ed:1a:20:b8:9b:22:ce:ef:d0:26:47: + 9d:57 -----BEGIN CA CERTIFICATE----- -MIIBnDCCAQWgAwIBAgIBADANBgkqhkiG9w0BAQUFADASMRAwDgYDVQQDEwdUZXN0IENBMCIYDzI -wMTcwMTAxMDAwMDAwWhgPMjAxODAxMDEwMDAwMDBaMBIxEDAOBgNVBAMTB1Rlc3QgQ0EwgZ8wDQ -YJKoZIhvcNAQEBBQADgY0AMIGJAoGBALglK+5Zmp28tEiuCc4NusWDVwOS/VIyVfXkLqbPnkvEE -K8k2tXdRKjWKDicpRHJC3ChtXHPpDXCahextcfPdIOsetU7EmZ08ksVsMJZrwx4LEI8P4uDsx2a -yLzOsMjyGqgKHLtubtTGEGY8qOzjxGNA9nnsixT/hZ4tGufoMVaBAgMBAAEwDQYJKoZIhvcNAQE -FBQADgYEANf7uljHHPZHrIlMfv8wgzKr0BJI8i1AG6qHMt8JK1gKvU6ekcYF4vJXzLUbEg0zVkh -F8x2fTR/YGnxxG2tYgckfCV9f7ZtM1ggdhE05N5gyT5vO+mP/o3mCnBpTNu/Vus04L1ukrcr1ur -oYjLUQzxDunUhJG0naVBj5pD3JgFtY= +MIIBqTCCARKgAwIBAgIBATANBgkqhkiG9w0BAQUFADASMRAwDgYDVQQDDAdUZXN0IENBMCIYDzI +wMTcwMTAxMDAwMDAwWhgPMjAxODAxMDEwMDAwMDBaMB8xHTAbBgNVBAMMFFRlc3QgSW50ZXJtZW +RpYXRlIENBMIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQC5MgneM0pP4gRzSdUuK4OSOpTkG +wwnG/hDgxe4dfWkr+NMhD5sSHl23031Oa+SS8Wghqs1zBlrk4LA+ERNGhRdSIdlAg6wqJbZBhk/ +qoUthMB4GaaWqyZW929aGpeiAYgAmRCKlznIIm7e5Vb0piPN6kgOZWekc6BQkd66z1QIjwIDAQA +BMA0GCSqGSIb3DQEBBQUAA4GBAEjVn42QvEpZOB0rgy1xHHSdAXOgtpjnHMIiZiMzCo9k/5xrNw +kSHBUSy8Nh2avNlt2V+qYCZzxM7Jg4XPxIzIWpW0ksKwZmB54xD5MQqz6fl2BkAWF+hhW7XvGQM +aNU0IYOgAWHCS5ltpWJXMHlgNm4gbbtGiC4myLO79AmR51X -----END CA CERTIFICATE----- $ openssl x509 -text < [CERTIFICATE] Certificate: Data: Version: 3 (0x2) - Serial Number: 3 (0x3) + Serial Number: 4 (0x4) Signature Algorithm: sha1WithRSAEncryption - Issuer: CN=Test CA + Issuer: CN = Test Intermediate CA Validity Not Before: Jan 1 00:00:00 2017 GMT Not After : Jan 1 00:00:00 2018 GMT - Subject: CN=Test Cert + Subject: CN = Test Cert Subject Public Key Info: Public Key Algorithm: rsaEncryption Public-Key: (1024 bit) Modulus: - 00:d5:12:3f:22:6f:b0:e1:43:c5:93:b3:c3:5b:70: - 52:b2:8b:10:ec:11:c4:c4:aa:aa:43:92:c8:d0:f3: - 35:23:e3:76:2d:b4:ea:93:26:6f:6a:79:1c:64:51: - d3:4d:21:4a:73:83:35:dc:a0:16:74:db:f0:b9:a5: - 46:35:8d:53:e8:7d:37:5b:4d:ad:a3:df:d6:ae:01: - 38:ad:16:09:6e:fd:65:ad:1c:4b:48:12:1e:48:a7: - ff:5b:47:c4:c9:3b:74:85:63:1a:0a:06:b2:9f:b9: - cb:ad:dc:3f:24:8b:a4:a7:8a:13:15:45:89:24:c1: - a7:3b:c2:a2:c8:74:f1:3f:6f + 00:bc:4c:d5:b3:8d:92:fa:66:ac:32:43:1a:9e:eb: + 17:e0:aa:76:35:1b:1d:10:48:4e:3e:22:8b:75:2e: + e8:6f:a4:55:1e:0a:5e:60:c0:61:f1:7d:29:58:7e: + 0b:ef:29:be:ad:f8:f7:43:c8:58:95:14:5b:1d:af: + 4a:b8:90:9e:4e:ec:4e:b3:86:7a:b9:96:c1:34:d3: + b9:a6:57:df:9b:bd:d9:dd:67:15:54:d4:9f:65:b8: + 33:29:59:ba:9a:c6:75:ea:a5:76:3d:a4:57:0f:e2: + e4:c3:91:35:1d:6e:ff:61:7d:c2:53:23:66:b2:a8: + 0b:e1:c7:55:48:c5:2b:4d:7d Exponent: 65537 (0x10001) Signature Algorithm: sha1WithRSAEncryption - 04:21:70:de:14:92:27:13:e8:d2:b0:51:f0:af:34:75:0b:a7: - ff:84:cb:c6:96:30:80:01:f5:c1:3a:c6:81:ee:ba:89:60:33: - c3:e5:0f:43:cc:ac:81:8d:09:fb:25:e1:67:40:64:a3:ca:fd: - bd:9c:c4:73:e4:bc:4d:8e:e2:70:f1:17:ce:b4:ab:a0:b2:63: - 72:25:27:ae:d5:8e:18:73:0d:dc:12:5a:32:1c:b7:da:cd:23: - 5b:c8:87:58:08:3e:95:0c:fd:c8:48:a2:75:6e:79:f2:00:82: - 6e:b5:cc:71:e3:79:ca:68:85:9b:1b:5c:52:bf:a2:5a:71:e3: - 05:b5 + 18:bb:93:d9:2a:e0:34:69:2f:96:57:ac:55:ac:a7:83:04:b4: + bc:22:7f:5f:f7:c0:dc:ac:af:13:9b:86:7e:ac:02:8c:44:83: + 2e:c0:fa:a1:77:1d:dd:86:31:7e:98:93:c0:4f:b2:3d:be:30: + 6f:a5:fc:c7:2e:b1:b8:08:d2:17:cb:60:55:bf:5a:e0:94:f3: + 1d:44:fa:b1:2f:1a:24:c5:33:e1:d4:f0:ac:d5:2c:67:da:a7: + 5d:ee:eb:d6:7a:a7:41:e8:94:7a:34:43:b2:1f:ab:e9:cf:5d: + 25:49:56:18:d2:a9:49:1a:37:34:43:c7:06:96:4a:29:38:cc: + f2:1c -----BEGIN CERTIFICATE----- -MIIBnjCCAQegAwIBAgIBAzANBgkqhkiG9w0BAQUFADASMRAwDgYDVQQDEwdUZXN0IENBMCIYDzI -wMTcwMTAxMDAwMDAwWhgPMjAxODAxMDEwMDAwMDBaMBQxEjAQBgNVBAMTCVRlc3QgQ2VydDCBnz -ANBgkqhkiG9w0BAQEFAAOBjQAwgYkCgYEA1RI/Im+w4UPFk7PDW3BSsosQ7BHExKqqQ5LI0PM1I -+N2LbTqkyZvankcZFHTTSFKc4M13KAWdNvwuaVGNY1T6H03W02to9/WrgE4rRYJbv1lrRxLSBIe -SKf/W0fEyTt0hWMaCgayn7nLrdw/JIukp4oTFUWJJMGnO8KiyHTxP28CAwEAATANBgkqhkiG9w0 -BAQUFAAOBgQAEIXDeFJInE+jSsFHwrzR1C6f/hMvGljCAAfXBOsaB7rqJYDPD5Q9DzKyBjQn7Je -FnQGSjyv29nMRz5LxNjuJw8RfOtKugsmNyJSeu1Y4Ycw3cEloyHLfazSNbyIdYCD6VDP3ISKJ1b -nnyAIJutcxx43nKaIWbG1xSv6JaceMFtQ== +MIIBqzCCARSgAwIBAgIBBDANBgkqhkiG9w0BAQUFADAfMR0wGwYDVQQDDBRUZXN0IEludGVybWV +kaWF0ZSBDQTAiGA8yMDE3MDEwMTAwMDAwMFoYDzIwMTgwMTAxMDAwMDAwWjAUMRIwEAYDVQQDDA +lUZXN0IENlcnQwgZ8wDQYJKoZIhvcNAQEBBQADgY0AMIGJAoGBALxM1bONkvpmrDJDGp7rF+Cqd +jUbHRBITj4ii3Uu6G+kVR4KXmDAYfF9KVh+C+8pvq3490PIWJUUWx2vSriQnk7sTrOGermWwTTT +uaZX35u92d1nFVTUn2W4MylZuprGdeqldj2kVw/i5MORNR1u/2F9wlMjZrKoC+HHVUjFK019AgM +BAAEwDQYJKoZIhvcNAQEFBQADgYEAGLuT2SrgNGkvllesVayngwS0vCJ/X/fA3KyvE5uGfqwCjE +SDLsD6oXcd3YYxfpiTwE+yPb4wb6X8xy6xuAjSF8tgVb9a4JTzHUT6sS8aJMUz4dTwrNUsZ9qnX +e7r1nqnQeiUejRDsh+r6c9dJUlWGNKpSRo3NEPHBpZKKTjM8hw= -----END CERTIFICATE----- $ openssl asn1parse -i < [OCSP REQUEST] @@ -139,10 +139,10 @@ 10:d=5 hl=2 l= 9 cons: SEQUENCE 12:d=6 hl=2 l= 5 prim: OBJECT :sha1 19:d=6 hl=2 l= 0 prim: NULL - 21:d=5 hl=2 l= 20 prim: OCTET STRING [HEX DUMP]:02FF75DA24DE8ADD150FAB689DCCE6E6636D0901 - 43:d=5 hl=2 l= 20 prim: OCTET STRING [HEX DUMP]:84E1BA52A25C543CA972491224BC8B1ECA8B9FF4 - 65:d=5 hl=2 l= 1 prim: INTEGER :03 + 21:d=5 hl=2 l= 20 prim: OCTET STRING [HEX DUMP]:449B1C5B31C6E9990966523E49C3F773C024190A + 43:d=5 hl=2 l= 20 prim: OCTET STRING [HEX DUMP]:FC6D3387CC3B39B049C755C46DF4395548930BCE + 65:d=5 hl=2 l= 1 prim: INTEGER :04 -----BEGIN OCSP REQUEST----- -MEIwQDA+MDwwOjAJBgUrDgMCGgUABBQC/3XaJN6K3RUPq2idzObmY20JAQQUhOG6UqJcVDypckk -SJLyLHsqLn/QCAQM= +MEIwQDA+MDwwOjAJBgUrDgMCGgUABBREmxxbMcbpmQlmUj5Jw/dzwCQZCgQU/G0zh8w7ObBJx1X +EbfQ5VUiTC84CAQQ= -----END OCSP REQUEST-----
diff --git a/net/data/ocsp_unittest/has_single_extension.pem b/net/data/ocsp_unittest/has_single_extension.pem index 48de4d5..9173185 100644 --- a/net/data/ocsp_unittest/has_single_extension.pem +++ b/net/data/ocsp_unittest/has_single_extension.pem
@@ -1,133 +1,133 @@ Has an extension in the SingleResponse $ openssl asn1parse -i < [OCSP RESPONSE] - 0:d=0 hl=4 l= 319 cons: SEQUENCE + 0:d=0 hl=4 l= 332 cons: SEQUENCE 4:d=1 hl=2 l= 1 prim: ENUMERATED :00 - 7:d=1 hl=4 l= 312 cons: cont [ 0 ] - 11:d=2 hl=4 l= 308 cons: SEQUENCE + 7:d=1 hl=4 l= 325 cons: cont [ 0 ] + 11:d=2 hl=4 l= 321 cons: SEQUENCE 15:d=3 hl=2 l= 9 prim: OBJECT :Basic OCSP Response - 26:d=3 hl=4 l= 293 prim: OCTET STRING - 0:d=0 hl=4 l= 289 cons: SEQUENCE - 4:d=1 hl=3 l= 139 cons: SEQUENCE - 7:d=2 hl=2 l= 20 cons: cont [ 1 ] - 9:d=3 hl=2 l= 18 cons: SEQUENCE - 11:d=4 hl=2 l= 16 cons: SET - 13:d=5 hl=2 l= 14 cons: SEQUENCE + 26:d=3 hl=4 l= 306 prim: OCTET STRING + 0:d=0 hl=4 l= 302 cons: SEQUENCE + 4:d=1 hl=3 l= 152 cons: SEQUENCE + 7:d=2 hl=2 l= 33 cons: cont [ 1 ] + 9:d=3 hl=2 l= 31 cons: SEQUENCE + 11:d=4 hl=2 l= 29 cons: SET + 13:d=5 hl=2 l= 27 cons: SEQUENCE 15:d=6 hl=2 l= 3 prim: OBJECT :commonName - 20:d=6 hl=2 l= 7 prim: PRINTABLESTRING :Test CA - 29:d=2 hl=2 l= 15 prim: GENERALIZEDTIME :20170302000000Z - 46:d=2 hl=2 l= 98 cons: SEQUENCE - 48:d=3 hl=2 l= 96 cons: SEQUENCE - 50:d=4 hl=2 l= 56 cons: SEQUENCE - 52:d=5 hl=2 l= 7 cons: SEQUENCE - 54:d=6 hl=2 l= 5 prim: OBJECT :sha1 - 61:d=5 hl=2 l= 20 prim: OCTET STRING [HEX DUMP]:02FF75DA24DE8ADD150FAB689DCCE6E6636D0901 - 83:d=5 hl=2 l= 20 prim: OCTET STRING [HEX DUMP]:84E1BA52A25C543CA972491224BC8B1ECA8B9FF4 - 105:d=5 hl=2 l= 1 prim: INTEGER :03 - 108:d=4 hl=2 l= 0 prim: cont [ 0 ] - 110:d=4 hl=2 l= 15 prim: GENERALIZEDTIME :20170301000000Z - 127:d=4 hl=2 l= 17 cons: cont [ 1 ] - 129:d=5 hl=2 l= 15 cons: SEQUENCE - 131:d=6 hl=2 l= 13 cons: SEQUENCE - 133:d=7 hl=2 l= 3 prim: OBJECT :1.2.3.4 + 20:d=6 hl=2 l= 20 prim: UTF8STRING :Test Intermediate CA + 42:d=2 hl=2 l= 15 prim: GENERALIZEDTIME :20170302000000Z + 59:d=2 hl=2 l= 98 cons: SEQUENCE + 61:d=3 hl=2 l= 96 cons: SEQUENCE + 63:d=4 hl=2 l= 56 cons: SEQUENCE + 65:d=5 hl=2 l= 7 cons: SEQUENCE + 67:d=6 hl=2 l= 5 prim: OBJECT :sha1 + 74:d=5 hl=2 l= 20 prim: OCTET STRING [HEX DUMP]:449B1C5B31C6E9990966523E49C3F773C024190A + 96:d=5 hl=2 l= 20 prim: OCTET STRING [HEX DUMP]:FC6D3387CC3B39B049C755C46DF4395548930BCE + 118:d=5 hl=2 l= 1 prim: INTEGER :04 + 121:d=4 hl=2 l= 0 prim: cont [ 0 ] + 123:d=4 hl=2 l= 15 prim: GENERALIZEDTIME :20170301000000Z + 140:d=4 hl=2 l= 17 cons: cont [ 1 ] + 142:d=5 hl=2 l= 15 cons: SEQUENCE + 144:d=6 hl=2 l= 13 cons: SEQUENCE + 146:d=7 hl=2 l= 3 prim: OBJECT :1.2.3.4 Error in encoding -----BEGIN OCSP RESPONSE----- -MIIBPwoBAKCCATgwggE0BgkrBgEFBQcwAQEEggElMIIBITCBi6EUMBIxEDAOBgNVBAMTB1Rlc3Q -gQ0EYDzIwMTcwMzAyMDAwMDAwWjBiMGAwODAHBgUrDgMCGgQUAv912iTeit0VD6tonczm5mNtCQ -EEFIThulKiXFQ8qXJJEiS8ix7Ki5/0AgEDgAAYDzIwMTcwMzAxMDAwMDAwWqERMA8wDQYDKgMER -EVBREJFRUYwDQYJKoZIhvcNAQEFBQADgYEAD6oq+q3t5FJ5OkCyunN7NSJqNlaKkM7J9i49lTRK -6PZiNxTA1L2HAJSLmORjjnOxDRicoyDbcXF8RwktKwcCIUUpN9GZyXAqHYhbgRjHAzScm9wujzf -5qPtrJN+C+5H+lMfVHQakew0PNDnUk60hEyjLwXnErI32zpVtzTv1x14= +MIIBTAoBAKCCAUUwggFBBgkrBgEFBQcwAQEEggEyMIIBLjCBmKEhMB8xHTAbBgNVBAMMFFRlc3Q +gSW50ZXJtZWRpYXRlIENBGA8yMDE3MDMwMjAwMDAwMFowYjBgMDgwBwYFKw4DAhoEFESbHFsxxu +mZCWZSPknD93PAJBkKBBT8bTOHzDs5sEnHVcRt9DlVSJMLzgIBBIAAGA8yMDE3MDMwMTAwMDAwM +FqhETAPMA0GAyoDBERFQURCRUVGMA0GCSqGSIb3DQEBBQUAA4GBAEP+Qy6l2R3P6wrudbD8Nmhm +3XjWnVQtYalUcXbGQOv4icswUlUofI9lesxjbbbQIfJOsYS0ZSgUDBEoU2JbCdD3fd78gruS63k +o0KrU+bVAXZfzVlT3rPUyRktpIAQx+Jt8zI1OZzaQcDAkVSUUvo0INdqunF74EwJGc29rinPr -----END OCSP RESPONSE----- $ openssl x509 -text < [CA CERTIFICATE] Certificate: Data: Version: 3 (0x2) - Serial Number: 0 (0x0) + Serial Number: 1 (0x1) Signature Algorithm: sha1WithRSAEncryption - Issuer: CN=Test CA + Issuer: CN = Test CA Validity Not Before: Jan 1 00:00:00 2017 GMT Not After : Jan 1 00:00:00 2018 GMT - Subject: CN=Test CA + Subject: CN = Test Intermediate CA Subject Public Key Info: Public Key Algorithm: rsaEncryption Public-Key: (1024 bit) Modulus: - 00:b8:25:2b:ee:59:9a:9d:bc:b4:48:ae:09:ce:0d: - ba:c5:83:57:03:92:fd:52:32:55:f5:e4:2e:a6:cf: - 9e:4b:c4:10:af:24:da:d5:dd:44:a8:d6:28:38:9c: - a5:11:c9:0b:70:a1:b5:71:cf:a4:35:c2:6a:17:b1: - b5:c7:cf:74:83:ac:7a:d5:3b:12:66:74:f2:4b:15: - b0:c2:59:af:0c:78:2c:42:3c:3f:8b:83:b3:1d:9a: - c8:bc:ce:b0:c8:f2:1a:a8:0a:1c:bb:6e:6e:d4:c6: - 10:66:3c:a8:ec:e3:c4:63:40:f6:79:ec:8b:14:ff: - 85:9e:2d:1a:e7:e8:31:56:81 + 00:b9:32:09:de:33:4a:4f:e2:04:73:49:d5:2e:2b: + 83:92:3a:94:e4:1b:0c:27:1b:f8:43:83:17:b8:75: + f5:a4:af:e3:4c:84:3e:6c:48:79:76:df:4d:f5:39: + af:92:4b:c5:a0:86:ab:35:cc:19:6b:93:82:c0:f8: + 44:4d:1a:14:5d:48:87:65:02:0e:b0:a8:96:d9:06: + 19:3f:aa:85:2d:84:c0:78:19:a6:96:ab:26:56:f7: + 6f:5a:1a:97:a2:01:88:00:99:10:8a:97:39:c8:22: + 6e:de:e5:56:f4:a6:23:cd:ea:48:0e:65:67:a4:73: + a0:50:91:de:ba:cf:54:08:8f Exponent: 65537 (0x10001) Signature Algorithm: sha1WithRSAEncryption - 35:fe:ee:96:31:c7:3d:91:eb:22:53:1f:bf:cc:20:cc:aa:f4: - 04:92:3c:8b:50:06:ea:a1:cc:b7:c2:4a:d6:02:af:53:a7:a4: - 71:81:78:bc:95:f3:2d:46:c4:83:4c:d5:92:11:7c:c7:67:d3: - 47:f6:06:9f:1c:46:da:d6:20:72:47:c2:57:d7:fb:66:d3:35: - 82:07:61:13:4e:4d:e6:0c:93:e6:f3:be:98:ff:e8:de:60:a7: - 06:94:cd:bb:f5:6e:b3:4e:0b:d6:e9:2b:72:bd:6e:ae:86:23: - 2d:44:33:c4:3b:a7:52:12:46:d2:76:95:06:3e:69:0f:72:60: - 16:d6 + 48:d5:9f:8d:90:bc:4a:59:38:1d:2b:83:2d:71:1c:74:9d:01: + 73:a0:b6:98:e7:1c:c2:22:66:23:33:0a:8f:64:ff:9c:6b:37: + 09:12:1c:15:12:cb:c3:61:d9:ab:cd:96:dd:95:fa:a6:02:67: + 3c:4c:ec:98:38:5c:fc:48:cc:85:a9:5b:49:2c:2b:06:66:07: + 9e:31:0f:93:10:ab:3e:9f:97:60:64:01:61:7e:86:15:bb:5e: + f1:90:31:a3:54:d0:86:0e:80:05:87:09:2e:65:b6:95:89:5c: + c1:e5:80:d9:b8:81:b6:ed:1a:20:b8:9b:22:ce:ef:d0:26:47: + 9d:57 -----BEGIN CA CERTIFICATE----- -MIIBnDCCAQWgAwIBAgIBADANBgkqhkiG9w0BAQUFADASMRAwDgYDVQQDEwdUZXN0IENBMCIYDzI -wMTcwMTAxMDAwMDAwWhgPMjAxODAxMDEwMDAwMDBaMBIxEDAOBgNVBAMTB1Rlc3QgQ0EwgZ8wDQ -YJKoZIhvcNAQEBBQADgY0AMIGJAoGBALglK+5Zmp28tEiuCc4NusWDVwOS/VIyVfXkLqbPnkvEE -K8k2tXdRKjWKDicpRHJC3ChtXHPpDXCahextcfPdIOsetU7EmZ08ksVsMJZrwx4LEI8P4uDsx2a -yLzOsMjyGqgKHLtubtTGEGY8qOzjxGNA9nnsixT/hZ4tGufoMVaBAgMBAAEwDQYJKoZIhvcNAQE -FBQADgYEANf7uljHHPZHrIlMfv8wgzKr0BJI8i1AG6qHMt8JK1gKvU6ekcYF4vJXzLUbEg0zVkh -F8x2fTR/YGnxxG2tYgckfCV9f7ZtM1ggdhE05N5gyT5vO+mP/o3mCnBpTNu/Vus04L1ukrcr1ur -oYjLUQzxDunUhJG0naVBj5pD3JgFtY= +MIIBqTCCARKgAwIBAgIBATANBgkqhkiG9w0BAQUFADASMRAwDgYDVQQDDAdUZXN0IENBMCIYDzI +wMTcwMTAxMDAwMDAwWhgPMjAxODAxMDEwMDAwMDBaMB8xHTAbBgNVBAMMFFRlc3QgSW50ZXJtZW +RpYXRlIENBMIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQC5MgneM0pP4gRzSdUuK4OSOpTkG +wwnG/hDgxe4dfWkr+NMhD5sSHl23031Oa+SS8Wghqs1zBlrk4LA+ERNGhRdSIdlAg6wqJbZBhk/ +qoUthMB4GaaWqyZW929aGpeiAYgAmRCKlznIIm7e5Vb0piPN6kgOZWekc6BQkd66z1QIjwIDAQA +BMA0GCSqGSIb3DQEBBQUAA4GBAEjVn42QvEpZOB0rgy1xHHSdAXOgtpjnHMIiZiMzCo9k/5xrNw +kSHBUSy8Nh2avNlt2V+qYCZzxM7Jg4XPxIzIWpW0ksKwZmB54xD5MQqz6fl2BkAWF+hhW7XvGQM +aNU0IYOgAWHCS5ltpWJXMHlgNm4gbbtGiC4myLO79AmR51X -----END CA CERTIFICATE----- $ openssl x509 -text < [CERTIFICATE] Certificate: Data: Version: 3 (0x2) - Serial Number: 3 (0x3) + Serial Number: 4 (0x4) Signature Algorithm: sha1WithRSAEncryption - Issuer: CN=Test CA + Issuer: CN = Test Intermediate CA Validity Not Before: Jan 1 00:00:00 2017 GMT Not After : Jan 1 00:00:00 2018 GMT - Subject: CN=Test Cert + Subject: CN = Test Cert Subject Public Key Info: Public Key Algorithm: rsaEncryption Public-Key: (1024 bit) Modulus: - 00:d5:12:3f:22:6f:b0:e1:43:c5:93:b3:c3:5b:70: - 52:b2:8b:10:ec:11:c4:c4:aa:aa:43:92:c8:d0:f3: - 35:23:e3:76:2d:b4:ea:93:26:6f:6a:79:1c:64:51: - d3:4d:21:4a:73:83:35:dc:a0:16:74:db:f0:b9:a5: - 46:35:8d:53:e8:7d:37:5b:4d:ad:a3:df:d6:ae:01: - 38:ad:16:09:6e:fd:65:ad:1c:4b:48:12:1e:48:a7: - ff:5b:47:c4:c9:3b:74:85:63:1a:0a:06:b2:9f:b9: - cb:ad:dc:3f:24:8b:a4:a7:8a:13:15:45:89:24:c1: - a7:3b:c2:a2:c8:74:f1:3f:6f + 00:bc:4c:d5:b3:8d:92:fa:66:ac:32:43:1a:9e:eb: + 17:e0:aa:76:35:1b:1d:10:48:4e:3e:22:8b:75:2e: + e8:6f:a4:55:1e:0a:5e:60:c0:61:f1:7d:29:58:7e: + 0b:ef:29:be:ad:f8:f7:43:c8:58:95:14:5b:1d:af: + 4a:b8:90:9e:4e:ec:4e:b3:86:7a:b9:96:c1:34:d3: + b9:a6:57:df:9b:bd:d9:dd:67:15:54:d4:9f:65:b8: + 33:29:59:ba:9a:c6:75:ea:a5:76:3d:a4:57:0f:e2: + e4:c3:91:35:1d:6e:ff:61:7d:c2:53:23:66:b2:a8: + 0b:e1:c7:55:48:c5:2b:4d:7d Exponent: 65537 (0x10001) Signature Algorithm: sha1WithRSAEncryption - 04:21:70:de:14:92:27:13:e8:d2:b0:51:f0:af:34:75:0b:a7: - ff:84:cb:c6:96:30:80:01:f5:c1:3a:c6:81:ee:ba:89:60:33: - c3:e5:0f:43:cc:ac:81:8d:09:fb:25:e1:67:40:64:a3:ca:fd: - bd:9c:c4:73:e4:bc:4d:8e:e2:70:f1:17:ce:b4:ab:a0:b2:63: - 72:25:27:ae:d5:8e:18:73:0d:dc:12:5a:32:1c:b7:da:cd:23: - 5b:c8:87:58:08:3e:95:0c:fd:c8:48:a2:75:6e:79:f2:00:82: - 6e:b5:cc:71:e3:79:ca:68:85:9b:1b:5c:52:bf:a2:5a:71:e3: - 05:b5 + 18:bb:93:d9:2a:e0:34:69:2f:96:57:ac:55:ac:a7:83:04:b4: + bc:22:7f:5f:f7:c0:dc:ac:af:13:9b:86:7e:ac:02:8c:44:83: + 2e:c0:fa:a1:77:1d:dd:86:31:7e:98:93:c0:4f:b2:3d:be:30: + 6f:a5:fc:c7:2e:b1:b8:08:d2:17:cb:60:55:bf:5a:e0:94:f3: + 1d:44:fa:b1:2f:1a:24:c5:33:e1:d4:f0:ac:d5:2c:67:da:a7: + 5d:ee:eb:d6:7a:a7:41:e8:94:7a:34:43:b2:1f:ab:e9:cf:5d: + 25:49:56:18:d2:a9:49:1a:37:34:43:c7:06:96:4a:29:38:cc: + f2:1c -----BEGIN CERTIFICATE----- -MIIBnjCCAQegAwIBAgIBAzANBgkqhkiG9w0BAQUFADASMRAwDgYDVQQDEwdUZXN0IENBMCIYDzI -wMTcwMTAxMDAwMDAwWhgPMjAxODAxMDEwMDAwMDBaMBQxEjAQBgNVBAMTCVRlc3QgQ2VydDCBnz -ANBgkqhkiG9w0BAQEFAAOBjQAwgYkCgYEA1RI/Im+w4UPFk7PDW3BSsosQ7BHExKqqQ5LI0PM1I -+N2LbTqkyZvankcZFHTTSFKc4M13KAWdNvwuaVGNY1T6H03W02to9/WrgE4rRYJbv1lrRxLSBIe -SKf/W0fEyTt0hWMaCgayn7nLrdw/JIukp4oTFUWJJMGnO8KiyHTxP28CAwEAATANBgkqhkiG9w0 -BAQUFAAOBgQAEIXDeFJInE+jSsFHwrzR1C6f/hMvGljCAAfXBOsaB7rqJYDPD5Q9DzKyBjQn7Je -FnQGSjyv29nMRz5LxNjuJw8RfOtKugsmNyJSeu1Y4Ycw3cEloyHLfazSNbyIdYCD6VDP3ISKJ1b -nnyAIJutcxx43nKaIWbG1xSv6JaceMFtQ== +MIIBqzCCARSgAwIBAgIBBDANBgkqhkiG9w0BAQUFADAfMR0wGwYDVQQDDBRUZXN0IEludGVybWV +kaWF0ZSBDQTAiGA8yMDE3MDEwMTAwMDAwMFoYDzIwMTgwMTAxMDAwMDAwWjAUMRIwEAYDVQQDDA +lUZXN0IENlcnQwgZ8wDQYJKoZIhvcNAQEBBQADgY0AMIGJAoGBALxM1bONkvpmrDJDGp7rF+Cqd +jUbHRBITj4ii3Uu6G+kVR4KXmDAYfF9KVh+C+8pvq3490PIWJUUWx2vSriQnk7sTrOGermWwTTT +uaZX35u92d1nFVTUn2W4MylZuprGdeqldj2kVw/i5MORNR1u/2F9wlMjZrKoC+HHVUjFK019AgM +BAAEwDQYJKoZIhvcNAQEFBQADgYEAGLuT2SrgNGkvllesVayngwS0vCJ/X/fA3KyvE5uGfqwCjE +SDLsD6oXcd3YYxfpiTwE+yPb4wb6X8xy6xuAjSF8tgVb9a4JTzHUT6sS8aJMUz4dTwrNUsZ9qnX +e7r1nqnQeiUejRDsh+r6c9dJUlWGNKpSRo3NEPHBpZKKTjM8hw= -----END CERTIFICATE----- $ openssl asn1parse -i < [OCSP REQUEST] @@ -139,10 +139,10 @@ 10:d=5 hl=2 l= 9 cons: SEQUENCE 12:d=6 hl=2 l= 5 prim: OBJECT :sha1 19:d=6 hl=2 l= 0 prim: NULL - 21:d=5 hl=2 l= 20 prim: OCTET STRING [HEX DUMP]:02FF75DA24DE8ADD150FAB689DCCE6E6636D0901 - 43:d=5 hl=2 l= 20 prim: OCTET STRING [HEX DUMP]:84E1BA52A25C543CA972491224BC8B1ECA8B9FF4 - 65:d=5 hl=2 l= 1 prim: INTEGER :03 + 21:d=5 hl=2 l= 20 prim: OCTET STRING [HEX DUMP]:449B1C5B31C6E9990966523E49C3F773C024190A + 43:d=5 hl=2 l= 20 prim: OCTET STRING [HEX DUMP]:FC6D3387CC3B39B049C755C46DF4395548930BCE + 65:d=5 hl=2 l= 1 prim: INTEGER :04 -----BEGIN OCSP REQUEST----- -MEIwQDA+MDwwOjAJBgUrDgMCGgUABBQC/3XaJN6K3RUPq2idzObmY20JAQQUhOG6UqJcVDypckk -SJLyLHsqLn/QCAQM= +MEIwQDA+MDwwOjAJBgUrDgMCGgUABBREmxxbMcbpmQlmUj5Jw/dzwCQZCgQU/G0zh8w7ObBJx1X +EbfQ5VUiTC84CAQQ= -----END OCSP REQUEST-----
diff --git a/net/data/ocsp_unittest/has_version.pem b/net/data/ocsp_unittest/has_version.pem index f6e9da58..667be32 100644 --- a/net/data/ocsp_unittest/has_version.pem +++ b/net/data/ocsp_unittest/has_version.pem
@@ -5,123 +5,123 @@ OCSP Response Status: successful (0x0) Response Type: Basic OCSP Response Version: 1 (0x0) - Responder Id: CN = Test CA + Responder Id: CN = Test Intermediate CA Produced At: Mar 2 00:00:00 2017 GMT Responses: Certificate ID: Hash Algorithm: sha1 - Issuer Name Hash: 02FF75DA24DE8ADD150FAB689DCCE6E6636D0901 - Issuer Key Hash: 84E1BA52A25C543CA972491224BC8B1ECA8B9FF4 - Serial Number: 03 + Issuer Name Hash: 449B1C5B31C6E9990966523E49C3F773C024190A + Issuer Key Hash: FC6D3387CC3B39B049C755C46DF4395548930BCE + Serial Number: 04 Cert Status: good This Update: Mar 1 00:00:00 2017 GMT Signature Algorithm: sha1WithRSAEncryption - 0e:82:91:8d:92:af:45:cb:98:e8:0e:08:04:15:97:9a:3a:cf: - cc:72:ee:cd:b7:3e:b0:40:b5:fd:8d:7d:6c:2f:4a:a6:32:9e: - 37:3b:7f:d3:ef:89:9e:8d:34:c2:45:1b:9b:99:4d:ed:e3:9a: - 94:62:17:59:4b:3a:be:f8:c0:a7:98:bd:e0:69:8f:98:47:e9: - 76:25:d3:1f:94:53:d7:c2:db:56:a2:aa:e3:6b:19:38:97:33: - a7:b6:45:6e:52:69:2c:62:6e:98:b6:d8:75:00:0c:16:c9:8b: - 84:41:f4:99:3e:a9:0c:a7:d4:98:51:45:89:4c:e2:c2:8e:5b: - e8:26 + 9b:7c:bb:20:00:86:92:61:6d:8f:6d:70:87:52:1b:ac:d5:0a: + 97:ce:76:7b:c4:b4:a7:a8:1d:ea:2c:15:cc:d4:2e:7d:a2:8c: + 53:4a:82:06:4a:b6:e2:d9:9b:aa:c4:63:66:94:7a:71:ba:d9: + 4e:bc:90:11:56:75:56:aa:7c:34:73:1d:ad:1c:1b:a6:28:81: + ea:f9:a0:85:e6:4f:07:2e:43:63:49:1e:8f:78:b6:96:f4:8b: + 4d:7f:58:b2:86:18:45:3a:72:5e:7f:d5:f5:f0:66:83:58:92: + 03:4d:e2:1d:af:99:2a:f4:c9:10:24:a8:c7:87:16:7f:b9:76: + b1:ba -----BEGIN OCSP RESPONSE----- -MIIBKwoBAKCCASQwggEgBgkrBgEFBQcwAQEEggERMIIBDTB4oRQwEjEQMA4GA1UEAxMHVGVzdCB -DQRgPMjAxNzAzMDIwMDAwMDBaME8wTTA4MAcGBSsOAwIaBBQC/3XaJN6K3RUPq2idzObmY20JAQ -QUhOG6UqJcVDypckkSJLyLHsqLn/QCAQOAABgPMjAxNzAzMDEwMDAwMDBaMA0GCSqGSIb3DQEBB -QUAA4GBAA6CkY2Sr0XLmOgOCAQVl5o6z8xy7s23PrBAtf2NfWwvSqYynjc7f9PviZ6NNMJFG5uZ -Te3jmpRiF1lLOr74wKeYveBpj5hH6XYl0x+UU9fC21aiquNrGTiXM6e2RW5SaSxibpi22HUADBb -Ji4RB9Jk+qQyn1JhRRYlM4sKOW+gm +MIIBOQoBAKCCATIwggEuBgkrBgEFBQcwAQEEggEfMIIBGzCBhaEhMB8xHTAbBgNVBAMMFFRlc3Q +gSW50ZXJtZWRpYXRlIENBGA8yMDE3MDMwMjAwMDAwMFowTzBNMDgwBwYFKw4DAhoEFESbHFsxxu +mZCWZSPknD93PAJBkKBBT8bTOHzDs5sEnHVcRt9DlVSJMLzgIBBIAAGA8yMDE3MDMwMTAwMDAwM +FowDQYJKoZIhvcNAQEFBQADgYEAm3y7IACGkmFtj21wh1IbrNUKl852e8S0p6gd6iwVzNQufaKM +U0qCBkq24tmbqsRjZpR6cbrZTryQEVZ1Vqp8NHMdrRwbpiiB6vmgheZPBy5DY0kej3i2lvSLTX9 +YsoYYRTpyXn/V9fBmg1iSA03iHa+ZKvTJECSox4cWf7l2sbo= -----END OCSP RESPONSE----- $ openssl x509 -text < [CA CERTIFICATE] Certificate: Data: Version: 3 (0x2) - Serial Number: 0 (0x0) + Serial Number: 1 (0x1) Signature Algorithm: sha1WithRSAEncryption - Issuer: CN=Test CA + Issuer: CN = Test CA Validity Not Before: Jan 1 00:00:00 2017 GMT Not After : Jan 1 00:00:00 2018 GMT - Subject: CN=Test CA + Subject: CN = Test Intermediate CA Subject Public Key Info: Public Key Algorithm: rsaEncryption Public-Key: (1024 bit) Modulus: - 00:b8:25:2b:ee:59:9a:9d:bc:b4:48:ae:09:ce:0d: - ba:c5:83:57:03:92:fd:52:32:55:f5:e4:2e:a6:cf: - 9e:4b:c4:10:af:24:da:d5:dd:44:a8:d6:28:38:9c: - a5:11:c9:0b:70:a1:b5:71:cf:a4:35:c2:6a:17:b1: - b5:c7:cf:74:83:ac:7a:d5:3b:12:66:74:f2:4b:15: - b0:c2:59:af:0c:78:2c:42:3c:3f:8b:83:b3:1d:9a: - c8:bc:ce:b0:c8:f2:1a:a8:0a:1c:bb:6e:6e:d4:c6: - 10:66:3c:a8:ec:e3:c4:63:40:f6:79:ec:8b:14:ff: - 85:9e:2d:1a:e7:e8:31:56:81 + 00:b9:32:09:de:33:4a:4f:e2:04:73:49:d5:2e:2b: + 83:92:3a:94:e4:1b:0c:27:1b:f8:43:83:17:b8:75: + f5:a4:af:e3:4c:84:3e:6c:48:79:76:df:4d:f5:39: + af:92:4b:c5:a0:86:ab:35:cc:19:6b:93:82:c0:f8: + 44:4d:1a:14:5d:48:87:65:02:0e:b0:a8:96:d9:06: + 19:3f:aa:85:2d:84:c0:78:19:a6:96:ab:26:56:f7: + 6f:5a:1a:97:a2:01:88:00:99:10:8a:97:39:c8:22: + 6e:de:e5:56:f4:a6:23:cd:ea:48:0e:65:67:a4:73: + a0:50:91:de:ba:cf:54:08:8f Exponent: 65537 (0x10001) Signature Algorithm: sha1WithRSAEncryption - 35:fe:ee:96:31:c7:3d:91:eb:22:53:1f:bf:cc:20:cc:aa:f4: - 04:92:3c:8b:50:06:ea:a1:cc:b7:c2:4a:d6:02:af:53:a7:a4: - 71:81:78:bc:95:f3:2d:46:c4:83:4c:d5:92:11:7c:c7:67:d3: - 47:f6:06:9f:1c:46:da:d6:20:72:47:c2:57:d7:fb:66:d3:35: - 82:07:61:13:4e:4d:e6:0c:93:e6:f3:be:98:ff:e8:de:60:a7: - 06:94:cd:bb:f5:6e:b3:4e:0b:d6:e9:2b:72:bd:6e:ae:86:23: - 2d:44:33:c4:3b:a7:52:12:46:d2:76:95:06:3e:69:0f:72:60: - 16:d6 + 48:d5:9f:8d:90:bc:4a:59:38:1d:2b:83:2d:71:1c:74:9d:01: + 73:a0:b6:98:e7:1c:c2:22:66:23:33:0a:8f:64:ff:9c:6b:37: + 09:12:1c:15:12:cb:c3:61:d9:ab:cd:96:dd:95:fa:a6:02:67: + 3c:4c:ec:98:38:5c:fc:48:cc:85:a9:5b:49:2c:2b:06:66:07: + 9e:31:0f:93:10:ab:3e:9f:97:60:64:01:61:7e:86:15:bb:5e: + f1:90:31:a3:54:d0:86:0e:80:05:87:09:2e:65:b6:95:89:5c: + c1:e5:80:d9:b8:81:b6:ed:1a:20:b8:9b:22:ce:ef:d0:26:47: + 9d:57 -----BEGIN CA CERTIFICATE----- -MIIBnDCCAQWgAwIBAgIBADANBgkqhkiG9w0BAQUFADASMRAwDgYDVQQDEwdUZXN0IENBMCIYDzI -wMTcwMTAxMDAwMDAwWhgPMjAxODAxMDEwMDAwMDBaMBIxEDAOBgNVBAMTB1Rlc3QgQ0EwgZ8wDQ -YJKoZIhvcNAQEBBQADgY0AMIGJAoGBALglK+5Zmp28tEiuCc4NusWDVwOS/VIyVfXkLqbPnkvEE -K8k2tXdRKjWKDicpRHJC3ChtXHPpDXCahextcfPdIOsetU7EmZ08ksVsMJZrwx4LEI8P4uDsx2a -yLzOsMjyGqgKHLtubtTGEGY8qOzjxGNA9nnsixT/hZ4tGufoMVaBAgMBAAEwDQYJKoZIhvcNAQE -FBQADgYEANf7uljHHPZHrIlMfv8wgzKr0BJI8i1AG6qHMt8JK1gKvU6ekcYF4vJXzLUbEg0zVkh -F8x2fTR/YGnxxG2tYgckfCV9f7ZtM1ggdhE05N5gyT5vO+mP/o3mCnBpTNu/Vus04L1ukrcr1ur -oYjLUQzxDunUhJG0naVBj5pD3JgFtY= +MIIBqTCCARKgAwIBAgIBATANBgkqhkiG9w0BAQUFADASMRAwDgYDVQQDDAdUZXN0IENBMCIYDzI +wMTcwMTAxMDAwMDAwWhgPMjAxODAxMDEwMDAwMDBaMB8xHTAbBgNVBAMMFFRlc3QgSW50ZXJtZW +RpYXRlIENBMIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQC5MgneM0pP4gRzSdUuK4OSOpTkG +wwnG/hDgxe4dfWkr+NMhD5sSHl23031Oa+SS8Wghqs1zBlrk4LA+ERNGhRdSIdlAg6wqJbZBhk/ +qoUthMB4GaaWqyZW929aGpeiAYgAmRCKlznIIm7e5Vb0piPN6kgOZWekc6BQkd66z1QIjwIDAQA +BMA0GCSqGSIb3DQEBBQUAA4GBAEjVn42QvEpZOB0rgy1xHHSdAXOgtpjnHMIiZiMzCo9k/5xrNw +kSHBUSy8Nh2avNlt2V+qYCZzxM7Jg4XPxIzIWpW0ksKwZmB54xD5MQqz6fl2BkAWF+hhW7XvGQM +aNU0IYOgAWHCS5ltpWJXMHlgNm4gbbtGiC4myLO79AmR51X -----END CA CERTIFICATE----- $ openssl x509 -text < [CERTIFICATE] Certificate: Data: Version: 3 (0x2) - Serial Number: 3 (0x3) + Serial Number: 4 (0x4) Signature Algorithm: sha1WithRSAEncryption - Issuer: CN=Test CA + Issuer: CN = Test Intermediate CA Validity Not Before: Jan 1 00:00:00 2017 GMT Not After : Jan 1 00:00:00 2018 GMT - Subject: CN=Test Cert + Subject: CN = Test Cert Subject Public Key Info: Public Key Algorithm: rsaEncryption Public-Key: (1024 bit) Modulus: - 00:d5:12:3f:22:6f:b0:e1:43:c5:93:b3:c3:5b:70: - 52:b2:8b:10:ec:11:c4:c4:aa:aa:43:92:c8:d0:f3: - 35:23:e3:76:2d:b4:ea:93:26:6f:6a:79:1c:64:51: - d3:4d:21:4a:73:83:35:dc:a0:16:74:db:f0:b9:a5: - 46:35:8d:53:e8:7d:37:5b:4d:ad:a3:df:d6:ae:01: - 38:ad:16:09:6e:fd:65:ad:1c:4b:48:12:1e:48:a7: - ff:5b:47:c4:c9:3b:74:85:63:1a:0a:06:b2:9f:b9: - cb:ad:dc:3f:24:8b:a4:a7:8a:13:15:45:89:24:c1: - a7:3b:c2:a2:c8:74:f1:3f:6f + 00:bc:4c:d5:b3:8d:92:fa:66:ac:32:43:1a:9e:eb: + 17:e0:aa:76:35:1b:1d:10:48:4e:3e:22:8b:75:2e: + e8:6f:a4:55:1e:0a:5e:60:c0:61:f1:7d:29:58:7e: + 0b:ef:29:be:ad:f8:f7:43:c8:58:95:14:5b:1d:af: + 4a:b8:90:9e:4e:ec:4e:b3:86:7a:b9:96:c1:34:d3: + b9:a6:57:df:9b:bd:d9:dd:67:15:54:d4:9f:65:b8: + 33:29:59:ba:9a:c6:75:ea:a5:76:3d:a4:57:0f:e2: + e4:c3:91:35:1d:6e:ff:61:7d:c2:53:23:66:b2:a8: + 0b:e1:c7:55:48:c5:2b:4d:7d Exponent: 65537 (0x10001) Signature Algorithm: sha1WithRSAEncryption - 04:21:70:de:14:92:27:13:e8:d2:b0:51:f0:af:34:75:0b:a7: - ff:84:cb:c6:96:30:80:01:f5:c1:3a:c6:81:ee:ba:89:60:33: - c3:e5:0f:43:cc:ac:81:8d:09:fb:25:e1:67:40:64:a3:ca:fd: - bd:9c:c4:73:e4:bc:4d:8e:e2:70:f1:17:ce:b4:ab:a0:b2:63: - 72:25:27:ae:d5:8e:18:73:0d:dc:12:5a:32:1c:b7:da:cd:23: - 5b:c8:87:58:08:3e:95:0c:fd:c8:48:a2:75:6e:79:f2:00:82: - 6e:b5:cc:71:e3:79:ca:68:85:9b:1b:5c:52:bf:a2:5a:71:e3: - 05:b5 + 18:bb:93:d9:2a:e0:34:69:2f:96:57:ac:55:ac:a7:83:04:b4: + bc:22:7f:5f:f7:c0:dc:ac:af:13:9b:86:7e:ac:02:8c:44:83: + 2e:c0:fa:a1:77:1d:dd:86:31:7e:98:93:c0:4f:b2:3d:be:30: + 6f:a5:fc:c7:2e:b1:b8:08:d2:17:cb:60:55:bf:5a:e0:94:f3: + 1d:44:fa:b1:2f:1a:24:c5:33:e1:d4:f0:ac:d5:2c:67:da:a7: + 5d:ee:eb:d6:7a:a7:41:e8:94:7a:34:43:b2:1f:ab:e9:cf:5d: + 25:49:56:18:d2:a9:49:1a:37:34:43:c7:06:96:4a:29:38:cc: + f2:1c -----BEGIN CERTIFICATE----- -MIIBnjCCAQegAwIBAgIBAzANBgkqhkiG9w0BAQUFADASMRAwDgYDVQQDEwdUZXN0IENBMCIYDzI -wMTcwMTAxMDAwMDAwWhgPMjAxODAxMDEwMDAwMDBaMBQxEjAQBgNVBAMTCVRlc3QgQ2VydDCBnz -ANBgkqhkiG9w0BAQEFAAOBjQAwgYkCgYEA1RI/Im+w4UPFk7PDW3BSsosQ7BHExKqqQ5LI0PM1I -+N2LbTqkyZvankcZFHTTSFKc4M13KAWdNvwuaVGNY1T6H03W02to9/WrgE4rRYJbv1lrRxLSBIe -SKf/W0fEyTt0hWMaCgayn7nLrdw/JIukp4oTFUWJJMGnO8KiyHTxP28CAwEAATANBgkqhkiG9w0 -BAQUFAAOBgQAEIXDeFJInE+jSsFHwrzR1C6f/hMvGljCAAfXBOsaB7rqJYDPD5Q9DzKyBjQn7Je -FnQGSjyv29nMRz5LxNjuJw8RfOtKugsmNyJSeu1Y4Ycw3cEloyHLfazSNbyIdYCD6VDP3ISKJ1b -nnyAIJutcxx43nKaIWbG1xSv6JaceMFtQ== +MIIBqzCCARSgAwIBAgIBBDANBgkqhkiG9w0BAQUFADAfMR0wGwYDVQQDDBRUZXN0IEludGVybWV +kaWF0ZSBDQTAiGA8yMDE3MDEwMTAwMDAwMFoYDzIwMTgwMTAxMDAwMDAwWjAUMRIwEAYDVQQDDA +lUZXN0IENlcnQwgZ8wDQYJKoZIhvcNAQEBBQADgY0AMIGJAoGBALxM1bONkvpmrDJDGp7rF+Cqd +jUbHRBITj4ii3Uu6G+kVR4KXmDAYfF9KVh+C+8pvq3490PIWJUUWx2vSriQnk7sTrOGermWwTTT +uaZX35u92d1nFVTUn2W4MylZuprGdeqldj2kVw/i5MORNR1u/2F9wlMjZrKoC+HHVUjFK019AgM +BAAEwDQYJKoZIhvcNAQEFBQADgYEAGLuT2SrgNGkvllesVayngwS0vCJ/X/fA3KyvE5uGfqwCjE +SDLsD6oXcd3YYxfpiTwE+yPb4wb6X8xy6xuAjSF8tgVb9a4JTzHUT6sS8aJMUz4dTwrNUsZ9qnX +e7r1nqnQeiUejRDsh+r6c9dJUlWGNKpSRo3NEPHBpZKKTjM8hw= -----END CERTIFICATE----- $ openssl asn1parse -i < [OCSP REQUEST] @@ -133,10 +133,10 @@ 10:d=5 hl=2 l= 9 cons: SEQUENCE 12:d=6 hl=2 l= 5 prim: OBJECT :sha1 19:d=6 hl=2 l= 0 prim: NULL - 21:d=5 hl=2 l= 20 prim: OCTET STRING [HEX DUMP]:02FF75DA24DE8ADD150FAB689DCCE6E6636D0901 - 43:d=5 hl=2 l= 20 prim: OCTET STRING [HEX DUMP]:84E1BA52A25C543CA972491224BC8B1ECA8B9FF4 - 65:d=5 hl=2 l= 1 prim: INTEGER :03 + 21:d=5 hl=2 l= 20 prim: OCTET STRING [HEX DUMP]:449B1C5B31C6E9990966523E49C3F773C024190A + 43:d=5 hl=2 l= 20 prim: OCTET STRING [HEX DUMP]:FC6D3387CC3B39B049C755C46DF4395548930BCE + 65:d=5 hl=2 l= 1 prim: INTEGER :04 -----BEGIN OCSP REQUEST----- -MEIwQDA+MDwwOjAJBgUrDgMCGgUABBQC/3XaJN6K3RUPq2idzObmY20JAQQUhOG6UqJcVDypckk -SJLyLHsqLn/QCAQM= +MEIwQDA+MDwwOjAJBgUrDgMCGgUABBREmxxbMcbpmQlmUj5Jw/dzwCQZCgQU/G0zh8w7ObBJx1X +EbfQ5VUiTC84CAQQ= -----END OCSP REQUEST-----
diff --git a/net/data/ocsp_unittest/make_ocsp.py b/net/data/ocsp_unittest/make_ocsp.py index 426674d..abbc5a47 100755 --- a/net/data/ocsp_unittest/make_ocsp.py +++ b/net/data/ocsp_unittest/make_ocsp.py
@@ -82,7 +82,8 @@ return ext -CA = CreateCert('Test CA', None) +ROOT_CA = CreateCert('Test CA', None) +CA = CreateCert('Test Intermediate CA', ROOT_CA) CA_LINK = CreateCert('Test OCSP Signer', CA, True) CA_BADLINK = CreateCert('Test False OCSP Signer', CA, False) CERT = CreateCert('Test Cert', CA) @@ -211,6 +212,10 @@ sa = rfc2459.AlgorithmIdentifier() sa.setComponentByName('algorithm', SigAlgOid(sigAlg)) + # TODO(mattm): If pyasn1 gives an error + # "Component value is tag-incompatible: Null() vs Any()", try hacking + # pyasn1_modules/rfc2459.py's AlgorithmIdentifier to specify univ.Null as the + # type for 'parameters'. (Which is an ugly hack, but lets the script work.) sa.setComponentByName('parameters', univ.Null()) basic = rfc2560.BasicOCSPResponse()
diff --git a/net/data/ocsp_unittest/malformed_request.pem b/net/data/ocsp_unittest/malformed_request.pem index 3e1ca9b..863054a3 100644 --- a/net/data/ocsp_unittest/malformed_request.pem +++ b/net/data/ocsp_unittest/malformed_request.pem
@@ -10,90 +10,90 @@ Certificate: Data: Version: 3 (0x2) - Serial Number: 0 (0x0) + Serial Number: 1 (0x1) Signature Algorithm: sha1WithRSAEncryption - Issuer: CN=Test CA + Issuer: CN = Test CA Validity Not Before: Jan 1 00:00:00 2017 GMT Not After : Jan 1 00:00:00 2018 GMT - Subject: CN=Test CA + Subject: CN = Test Intermediate CA Subject Public Key Info: Public Key Algorithm: rsaEncryption Public-Key: (1024 bit) Modulus: - 00:d4:aa:31:f4:1a:0d:9c:8d:de:4f:1b:34:72:2b: - 63:23:a4:87:4f:55:b2:b0:c0:cb:27:89:18:77:2e: - 0e:d3:11:90:3e:62:23:b5:ab:34:6d:5f:7a:34:56: - dd:65:86:ed:07:c2:3b:73:fc:e9:7d:a8:64:ce:9b: - 8a:09:e1:ed:08:7d:04:5f:b1:cf:3d:fd:ff:37:35: - d3:c2:fe:02:ab:d8:f6:1f:a5:58:9e:4e:43:b4:e7: - 8d:f9:6c:4c:71:14:32:5d:86:1d:ea:1a:3d:34:ad: - b4:1a:a0:13:c0:7c:cb:8e:f2:f3:d1:ec:fd:5f:ad: - db:13:c9:2e:9c:3a:39:02:a3 + 00:b9:32:09:de:33:4a:4f:e2:04:73:49:d5:2e:2b: + 83:92:3a:94:e4:1b:0c:27:1b:f8:43:83:17:b8:75: + f5:a4:af:e3:4c:84:3e:6c:48:79:76:df:4d:f5:39: + af:92:4b:c5:a0:86:ab:35:cc:19:6b:93:82:c0:f8: + 44:4d:1a:14:5d:48:87:65:02:0e:b0:a8:96:d9:06: + 19:3f:aa:85:2d:84:c0:78:19:a6:96:ab:26:56:f7: + 6f:5a:1a:97:a2:01:88:00:99:10:8a:97:39:c8:22: + 6e:de:e5:56:f4:a6:23:cd:ea:48:0e:65:67:a4:73: + a0:50:91:de:ba:cf:54:08:8f Exponent: 65537 (0x10001) Signature Algorithm: sha1WithRSAEncryption - 5e:9b:eb:b0:e8:7d:c6:e8:24:e3:b3:8f:3f:cd:4e:80:3e:77: - 58:c5:60:bc:40:e0:16:e2:17:ce:81:fd:0f:19:36:56:c5:a3: - df:49:5f:b7:a1:4c:44:d0:3e:06:e2:42:57:b7:be:fd:b7:bb: - 31:79:db:eb:ed:a3:c5:66:36:45:cb:4b:ba:6c:8d:53:89:98: - c5:e0:ee:48:ef:97:ce:4d:14:33:bf:24:61:29:b9:7d:4e:7e: - cf:14:cc:c9:fa:0b:9e:68:34:9c:34:79:08:36:e0:ed:4f:a1: - 9a:ac:c2:73:d3:2c:67:0e:23:5e:e0:9f:7f:05:ed:9a:b0:e1: - b7:93 + 48:d5:9f:8d:90:bc:4a:59:38:1d:2b:83:2d:71:1c:74:9d:01: + 73:a0:b6:98:e7:1c:c2:22:66:23:33:0a:8f:64:ff:9c:6b:37: + 09:12:1c:15:12:cb:c3:61:d9:ab:cd:96:dd:95:fa:a6:02:67: + 3c:4c:ec:98:38:5c:fc:48:cc:85:a9:5b:49:2c:2b:06:66:07: + 9e:31:0f:93:10:ab:3e:9f:97:60:64:01:61:7e:86:15:bb:5e: + f1:90:31:a3:54:d0:86:0e:80:05:87:09:2e:65:b6:95:89:5c: + c1:e5:80:d9:b8:81:b6:ed:1a:20:b8:9b:22:ce:ef:d0:26:47: + 9d:57 -----BEGIN CA CERTIFICATE----- -MIIBnDCCAQWgAwIBAgIBADANBgkqhkiG9w0BAQUFADASMRAwDgYDVQQDEwdUZXN0IENBMCIYDzI -wMTcwMTAxMDAwMDAwWhgPMjAxODAxMDEwMDAwMDBaMBIxEDAOBgNVBAMTB1Rlc3QgQ0EwgZ8wDQ -YJKoZIhvcNAQEBBQADgY0AMIGJAoGBANSqMfQaDZyN3k8bNHIrYyOkh09VsrDAyyeJGHcuDtMRk -D5iI7WrNG1fejRW3WWG7QfCO3P86X2oZM6bignh7Qh9BF+xzz39/zc108L+AqvY9h+lWJ5OQ7Tn -jflsTHEUMl2GHeoaPTSttBqgE8B8y47y89Hs/V+t2xPJLpw6OQKjAgMBAAEwDQYJKoZIhvcNAQE -FBQADgYEAXpvrsOh9xugk47OPP81OgD53WMVgvEDgFuIXzoH9Dxk2VsWj30lft6FMRNA+BuJCV7 -e+/be7MXnb6+2jxWY2RctLumyNU4mYxeDuSO+Xzk0UM78kYSm5fU5+zxTMyfoLnmg0nDR5CDbg7 -U+hmqzCc9MsZw4jXuCffwXtmrDht5M= +MIIBqTCCARKgAwIBAgIBATANBgkqhkiG9w0BAQUFADASMRAwDgYDVQQDDAdUZXN0IENBMCIYDzI +wMTcwMTAxMDAwMDAwWhgPMjAxODAxMDEwMDAwMDBaMB8xHTAbBgNVBAMMFFRlc3QgSW50ZXJtZW +RpYXRlIENBMIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQC5MgneM0pP4gRzSdUuK4OSOpTkG +wwnG/hDgxe4dfWkr+NMhD5sSHl23031Oa+SS8Wghqs1zBlrk4LA+ERNGhRdSIdlAg6wqJbZBhk/ +qoUthMB4GaaWqyZW929aGpeiAYgAmRCKlznIIm7e5Vb0piPN6kgOZWekc6BQkd66z1QIjwIDAQA +BMA0GCSqGSIb3DQEBBQUAA4GBAEjVn42QvEpZOB0rgy1xHHSdAXOgtpjnHMIiZiMzCo9k/5xrNw +kSHBUSy8Nh2avNlt2V+qYCZzxM7Jg4XPxIzIWpW0ksKwZmB54xD5MQqz6fl2BkAWF+hhW7XvGQM +aNU0IYOgAWHCS5ltpWJXMHlgNm4gbbtGiC4myLO79AmR51X -----END CA CERTIFICATE----- $ openssl x509 -text < [CERTIFICATE] Certificate: Data: Version: 3 (0x2) - Serial Number: 3 (0x3) + Serial Number: 4 (0x4) Signature Algorithm: sha1WithRSAEncryption - Issuer: CN=Test CA + Issuer: CN = Test Intermediate CA Validity Not Before: Jan 1 00:00:00 2017 GMT Not After : Jan 1 00:00:00 2018 GMT - Subject: CN=Test Cert + Subject: CN = Test Cert Subject Public Key Info: Public Key Algorithm: rsaEncryption Public-Key: (1024 bit) Modulus: - 00:ad:b1:4c:76:1c:d3:13:a5:62:e3:c9:2a:a0:18: - 88:8a:10:5b:37:0f:32:24:33:0b:db:9d:8c:96:e5: - 4d:c2:d5:ca:47:1f:19:a5:c8:27:b4:42:bf:fe:ad: - 96:8e:a0:73:50:2e:f2:35:d7:d1:9f:ba:41:59:8b: - 83:3d:2c:ab:68:7f:73:df:18:f1:ff:f4:3b:9c:68: - d9:8a:f0:df:c0:97:5c:e8:43:5f:14:fd:59:52:c2: - 91:62:5e:e9:e8:a8:22:07:b9:5b:b4:46:60:b4:ee: - 62:29:0e:df:35:4c:41:e0:5c:89:9e:9c:b3:d8:fb: - 6d:c3:02:61:31:a4:e8:86:af + 00:bc:4c:d5:b3:8d:92:fa:66:ac:32:43:1a:9e:eb: + 17:e0:aa:76:35:1b:1d:10:48:4e:3e:22:8b:75:2e: + e8:6f:a4:55:1e:0a:5e:60:c0:61:f1:7d:29:58:7e: + 0b:ef:29:be:ad:f8:f7:43:c8:58:95:14:5b:1d:af: + 4a:b8:90:9e:4e:ec:4e:b3:86:7a:b9:96:c1:34:d3: + b9:a6:57:df:9b:bd:d9:dd:67:15:54:d4:9f:65:b8: + 33:29:59:ba:9a:c6:75:ea:a5:76:3d:a4:57:0f:e2: + e4:c3:91:35:1d:6e:ff:61:7d:c2:53:23:66:b2:a8: + 0b:e1:c7:55:48:c5:2b:4d:7d Exponent: 65537 (0x10001) Signature Algorithm: sha1WithRSAEncryption - 90:f6:92:8b:41:fd:9e:29:8f:54:1e:c2:98:25:7e:19:ed:8e: - 9e:37:9a:ae:ce:83:5e:56:7e:48:be:75:d4:5c:61:ce:07:a7: - 0c:44:ed:ed:66:10:20:2e:ac:3e:93:2f:42:62:76:a1:07:eb: - 07:63:c3:e7:58:26:0b:67:72:31:d1:2c:b0:b5:fd:1b:ee:b5: - d0:11:99:55:06:02:17:8c:e5:f7:46:12:56:26:3f:6b:46:58: - a6:c6:02:2f:b8:bc:8d:ca:bd:57:f3:ce:8e:a4:a6:ad:80:4e: - 34:3f:3c:76:1e:d0:75:39:2c:2c:e7:fc:8b:83:d0:21:1d:04: - 62:51 + 18:bb:93:d9:2a:e0:34:69:2f:96:57:ac:55:ac:a7:83:04:b4: + bc:22:7f:5f:f7:c0:dc:ac:af:13:9b:86:7e:ac:02:8c:44:83: + 2e:c0:fa:a1:77:1d:dd:86:31:7e:98:93:c0:4f:b2:3d:be:30: + 6f:a5:fc:c7:2e:b1:b8:08:d2:17:cb:60:55:bf:5a:e0:94:f3: + 1d:44:fa:b1:2f:1a:24:c5:33:e1:d4:f0:ac:d5:2c:67:da:a7: + 5d:ee:eb:d6:7a:a7:41:e8:94:7a:34:43:b2:1f:ab:e9:cf:5d: + 25:49:56:18:d2:a9:49:1a:37:34:43:c7:06:96:4a:29:38:cc: + f2:1c -----BEGIN CERTIFICATE----- -MIIBnjCCAQegAwIBAgIBAzANBgkqhkiG9w0BAQUFADASMRAwDgYDVQQDEwdUZXN0IENBMCIYDzI -wMTcwMTAxMDAwMDAwWhgPMjAxODAxMDEwMDAwMDBaMBQxEjAQBgNVBAMTCVRlc3QgQ2VydDCBnz -ANBgkqhkiG9w0BAQEFAAOBjQAwgYkCgYEArbFMdhzTE6Vi48kqoBiIihBbNw8yJDML252MluVNw -tXKRx8ZpcgntEK//q2WjqBzUC7yNdfRn7pBWYuDPSyraH9z3xjx//Q7nGjZivDfwJdc6ENfFP1Z -UsKRYl7p6KgiB7lbtEZgtO5iKQ7fNUxB4FyJnpyz2PttwwJhMaTohq8CAwEAATANBgkqhkiG9w0 -BAQUFAAOBgQCQ9pKLQf2eKY9UHsKYJX4Z7Y6eN5quzoNeVn5IvnXUXGHOB6cMRO3tZhAgLqw+ky -9CYnahB+sHY8PnWCYLZ3Ix0Sywtf0b7rXQEZlVBgIXjOX3RhJWJj9rRlimxgIvuLyNyr1X886Op -KatgE40Pzx2HtB1OSws5/yLg9AhHQRiUQ== +MIIBqzCCARSgAwIBAgIBBDANBgkqhkiG9w0BAQUFADAfMR0wGwYDVQQDDBRUZXN0IEludGVybWV +kaWF0ZSBDQTAiGA8yMDE3MDEwMTAwMDAwMFoYDzIwMTgwMTAxMDAwMDAwWjAUMRIwEAYDVQQDDA +lUZXN0IENlcnQwgZ8wDQYJKoZIhvcNAQEBBQADgY0AMIGJAoGBALxM1bONkvpmrDJDGp7rF+Cqd +jUbHRBITj4ii3Uu6G+kVR4KXmDAYfF9KVh+C+8pvq3490PIWJUUWx2vSriQnk7sTrOGermWwTTT +uaZX35u92d1nFVTUn2W4MylZuprGdeqldj2kVw/i5MORNR1u/2F9wlMjZrKoC+HHVUjFK019AgM +BAAEwDQYJKoZIhvcNAQEFBQADgYEAGLuT2SrgNGkvllesVayngwS0vCJ/X/fA3KyvE5uGfqwCjE +SDLsD6oXcd3YYxfpiTwE+yPb4wb6X8xy6xuAjSF8tgVb9a4JTzHUT6sS8aJMUz4dTwrNUsZ9qnX +e7r1nqnQeiUejRDsh+r6c9dJUlWGNKpSRo3NEPHBpZKKTjM8hw= -----END CERTIFICATE----- $ openssl asn1parse -i < [OCSP REQUEST] @@ -105,10 +105,10 @@ 10:d=5 hl=2 l= 9 cons: SEQUENCE 12:d=6 hl=2 l= 5 prim: OBJECT :sha1 19:d=6 hl=2 l= 0 prim: NULL - 21:d=5 hl=2 l= 20 prim: OCTET STRING [HEX DUMP]:02FF75DA24DE8ADD150FAB689DCCE6E6636D0901 - 43:d=5 hl=2 l= 20 prim: OCTET STRING [HEX DUMP]:4661D5C5F8D956FD3D871758F8A42950F5BCF498 - 65:d=5 hl=2 l= 1 prim: INTEGER :03 + 21:d=5 hl=2 l= 20 prim: OCTET STRING [HEX DUMP]:449B1C5B31C6E9990966523E49C3F773C024190A + 43:d=5 hl=2 l= 20 prim: OCTET STRING [HEX DUMP]:FC6D3387CC3B39B049C755C46DF4395548930BCE + 65:d=5 hl=2 l= 1 prim: INTEGER :04 -----BEGIN OCSP REQUEST----- -MEIwQDA+MDwwOjAJBgUrDgMCGgUABBQC/3XaJN6K3RUPq2idzObmY20JAQQURmHVxfjZVv09hxd -Y+KQpUPW89JgCAQM= +MEIwQDA+MDwwOjAJBgUrDgMCGgUABBREmxxbMcbpmQlmUj5Jw/dzwCQZCgQU/G0zh8w7ObBJx1X +EbfQ5VUiTC84CAQQ= -----END OCSP REQUEST-----
diff --git a/net/data/ocsp_unittest/missing_response.pem b/net/data/ocsp_unittest/missing_response.pem index 86c9556..2dad4bf 100644 --- a/net/data/ocsp_unittest/missing_response.pem +++ b/net/data/ocsp_unittest/missing_response.pem
@@ -5,113 +5,114 @@ OCSP Response Status: successful (0x0) Response Type: Basic OCSP Response Version: 1 (0x0) - Responder Id: CN = Test CA + Responder Id: CN = Test Intermediate CA Produced At: Mar 2 00:00:00 2017 GMT Responses: Signature Algorithm: sha1WithRSAEncryption - 8a:e1:ee:17:c2:15:ba:18:ea:d2:61:9a:bc:fc:7c:06:c1:2a: - b1:46:7f:1f:4d:59:e7:a2:44:ea:a9:3d:05:be:3b:28:ab:51: - c1:12:d7:66:b1:6a:68:16:82:2c:e8:70:7a:e4:71:90:67:fd: - 76:0b:87:17:12:5a:14:dc:81:2b:5c:96:c4:0a:3f:19:b5:07: - fa:b1:90:e3:3a:a8:05:01:68:03:4c:8e:2a:c0:4e:2a:30:66: - 55:5b:72:15:d0:86:df:7e:c8:17:a0:48:d4:b4:38:f3:95:53: - 8a:5e:c6:9d:dc:2a:46:59:dd:a8:c6:d6:9b:92:8d:fe:a2:a4: - 32:b4 + 73:15:3c:c0:57:e4:26:f2:91:9a:3d:ec:03:0f:15:d2:24:c6: + 17:81:0f:5b:22:72:37:50:a8:e4:8e:19:4f:76:eb:d7:41:1c: + 45:a5:35:2d:57:25:53:1c:13:26:f4:f1:65:22:42:2a:e4:9a: + bb:e0:5b:aa:87:ea:4f:91:14:06:69:b2:67:90:7b:f9:63:87: + a1:21:14:bb:c9:48:03:8d:90:f4:39:1d:1f:d7:26:88:21:b4: + 12:38:31:33:78:21:ca:f7:f3:e6:2d:cb:f2:fc:43:ae:94:60: + 86:df:aa:44:cf:b9:26:01:24:35:a3:80:84:91:3e:da:73:88: + c6:06 -----BEGIN OCSP RESPONSE----- -MIHYCgEAoIHSMIHPBgkrBgEFBQcwAQEEgcEwgb4wKaEUMBIxEDAOBgNVBAMTB1Rlc3QgQ0EYDzI -wMTcwMzAyMDAwMDAwWjAAMA0GCSqGSIb3DQEBBQUAA4GBAIrh7hfCFboY6tJhmrz8fAbBKrFGfx -9NWeeiROqpPQW+OyirUcES12axamgWgizocHrkcZBn/XYLhxcSWhTcgStclsQKPxm1B/qxkOM6q -AUBaANMjirATiowZlVbchXQht9+yBegSNS0OPOVU4pexp3cKkZZ3ajG1puSjf6ipDK0 +MIHlCgEAoIHfMIHcBgkrBgEFBQcwAQEEgc4wgcswNqEhMB8xHTAbBgNVBAMMFFRlc3QgSW50ZXJ +tZWRpYXRlIENBGA8yMDE3MDMwMjAwMDAwMFowADANBgkqhkiG9w0BAQUFAAOBgQBzFTzAV+Qm8p +GaPewDDxXSJMYXgQ9bInI3UKjkjhlPduvXQRxFpTUtVyVTHBMm9PFlIkIq5Jq74Fuqh+pPkRQGa +bJnkHv5Y4ehIRS7yUgDjZD0OR0f1yaIIbQSODEzeCHK9/PmLcvy/EOulGCG36pEz7kmASQ1o4CE +kT7ac4jGBg== -----END OCSP RESPONSE----- $ openssl x509 -text < [CA CERTIFICATE] Certificate: Data: Version: 3 (0x2) - Serial Number: 0 (0x0) + Serial Number: 1 (0x1) Signature Algorithm: sha1WithRSAEncryption - Issuer: CN=Test CA + Issuer: CN = Test CA Validity Not Before: Jan 1 00:00:00 2017 GMT Not After : Jan 1 00:00:00 2018 GMT - Subject: CN=Test CA + Subject: CN = Test Intermediate CA Subject Public Key Info: Public Key Algorithm: rsaEncryption Public-Key: (1024 bit) Modulus: - 00:b8:25:2b:ee:59:9a:9d:bc:b4:48:ae:09:ce:0d: - ba:c5:83:57:03:92:fd:52:32:55:f5:e4:2e:a6:cf: - 9e:4b:c4:10:af:24:da:d5:dd:44:a8:d6:28:38:9c: - a5:11:c9:0b:70:a1:b5:71:cf:a4:35:c2:6a:17:b1: - b5:c7:cf:74:83:ac:7a:d5:3b:12:66:74:f2:4b:15: - b0:c2:59:af:0c:78:2c:42:3c:3f:8b:83:b3:1d:9a: - c8:bc:ce:b0:c8:f2:1a:a8:0a:1c:bb:6e:6e:d4:c6: - 10:66:3c:a8:ec:e3:c4:63:40:f6:79:ec:8b:14:ff: - 85:9e:2d:1a:e7:e8:31:56:81 + 00:b9:32:09:de:33:4a:4f:e2:04:73:49:d5:2e:2b: + 83:92:3a:94:e4:1b:0c:27:1b:f8:43:83:17:b8:75: + f5:a4:af:e3:4c:84:3e:6c:48:79:76:df:4d:f5:39: + af:92:4b:c5:a0:86:ab:35:cc:19:6b:93:82:c0:f8: + 44:4d:1a:14:5d:48:87:65:02:0e:b0:a8:96:d9:06: + 19:3f:aa:85:2d:84:c0:78:19:a6:96:ab:26:56:f7: + 6f:5a:1a:97:a2:01:88:00:99:10:8a:97:39:c8:22: + 6e:de:e5:56:f4:a6:23:cd:ea:48:0e:65:67:a4:73: + a0:50:91:de:ba:cf:54:08:8f Exponent: 65537 (0x10001) Signature Algorithm: sha1WithRSAEncryption - 35:fe:ee:96:31:c7:3d:91:eb:22:53:1f:bf:cc:20:cc:aa:f4: - 04:92:3c:8b:50:06:ea:a1:cc:b7:c2:4a:d6:02:af:53:a7:a4: - 71:81:78:bc:95:f3:2d:46:c4:83:4c:d5:92:11:7c:c7:67:d3: - 47:f6:06:9f:1c:46:da:d6:20:72:47:c2:57:d7:fb:66:d3:35: - 82:07:61:13:4e:4d:e6:0c:93:e6:f3:be:98:ff:e8:de:60:a7: - 06:94:cd:bb:f5:6e:b3:4e:0b:d6:e9:2b:72:bd:6e:ae:86:23: - 2d:44:33:c4:3b:a7:52:12:46:d2:76:95:06:3e:69:0f:72:60: - 16:d6 + 48:d5:9f:8d:90:bc:4a:59:38:1d:2b:83:2d:71:1c:74:9d:01: + 73:a0:b6:98:e7:1c:c2:22:66:23:33:0a:8f:64:ff:9c:6b:37: + 09:12:1c:15:12:cb:c3:61:d9:ab:cd:96:dd:95:fa:a6:02:67: + 3c:4c:ec:98:38:5c:fc:48:cc:85:a9:5b:49:2c:2b:06:66:07: + 9e:31:0f:93:10:ab:3e:9f:97:60:64:01:61:7e:86:15:bb:5e: + f1:90:31:a3:54:d0:86:0e:80:05:87:09:2e:65:b6:95:89:5c: + c1:e5:80:d9:b8:81:b6:ed:1a:20:b8:9b:22:ce:ef:d0:26:47: + 9d:57 -----BEGIN CA CERTIFICATE----- -MIIBnDCCAQWgAwIBAgIBADANBgkqhkiG9w0BAQUFADASMRAwDgYDVQQDEwdUZXN0IENBMCIYDzI -wMTcwMTAxMDAwMDAwWhgPMjAxODAxMDEwMDAwMDBaMBIxEDAOBgNVBAMTB1Rlc3QgQ0EwgZ8wDQ -YJKoZIhvcNAQEBBQADgY0AMIGJAoGBALglK+5Zmp28tEiuCc4NusWDVwOS/VIyVfXkLqbPnkvEE -K8k2tXdRKjWKDicpRHJC3ChtXHPpDXCahextcfPdIOsetU7EmZ08ksVsMJZrwx4LEI8P4uDsx2a -yLzOsMjyGqgKHLtubtTGEGY8qOzjxGNA9nnsixT/hZ4tGufoMVaBAgMBAAEwDQYJKoZIhvcNAQE -FBQADgYEANf7uljHHPZHrIlMfv8wgzKr0BJI8i1AG6qHMt8JK1gKvU6ekcYF4vJXzLUbEg0zVkh -F8x2fTR/YGnxxG2tYgckfCV9f7ZtM1ggdhE05N5gyT5vO+mP/o3mCnBpTNu/Vus04L1ukrcr1ur -oYjLUQzxDunUhJG0naVBj5pD3JgFtY= +MIIBqTCCARKgAwIBAgIBATANBgkqhkiG9w0BAQUFADASMRAwDgYDVQQDDAdUZXN0IENBMCIYDzI +wMTcwMTAxMDAwMDAwWhgPMjAxODAxMDEwMDAwMDBaMB8xHTAbBgNVBAMMFFRlc3QgSW50ZXJtZW +RpYXRlIENBMIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQC5MgneM0pP4gRzSdUuK4OSOpTkG +wwnG/hDgxe4dfWkr+NMhD5sSHl23031Oa+SS8Wghqs1zBlrk4LA+ERNGhRdSIdlAg6wqJbZBhk/ +qoUthMB4GaaWqyZW929aGpeiAYgAmRCKlznIIm7e5Vb0piPN6kgOZWekc6BQkd66z1QIjwIDAQA +BMA0GCSqGSIb3DQEBBQUAA4GBAEjVn42QvEpZOB0rgy1xHHSdAXOgtpjnHMIiZiMzCo9k/5xrNw +kSHBUSy8Nh2avNlt2V+qYCZzxM7Jg4XPxIzIWpW0ksKwZmB54xD5MQqz6fl2BkAWF+hhW7XvGQM +aNU0IYOgAWHCS5ltpWJXMHlgNm4gbbtGiC4myLO79AmR51X -----END CA CERTIFICATE----- $ openssl x509 -text < [CERTIFICATE] Certificate: Data: Version: 3 (0x2) - Serial Number: 3 (0x3) + Serial Number: 4 (0x4) Signature Algorithm: sha1WithRSAEncryption - Issuer: CN=Test CA + Issuer: CN = Test Intermediate CA Validity Not Before: Jan 1 00:00:00 2017 GMT Not After : Jan 1 00:00:00 2018 GMT - Subject: CN=Test Cert + Subject: CN = Test Cert Subject Public Key Info: Public Key Algorithm: rsaEncryption Public-Key: (1024 bit) Modulus: - 00:d5:12:3f:22:6f:b0:e1:43:c5:93:b3:c3:5b:70: - 52:b2:8b:10:ec:11:c4:c4:aa:aa:43:92:c8:d0:f3: - 35:23:e3:76:2d:b4:ea:93:26:6f:6a:79:1c:64:51: - d3:4d:21:4a:73:83:35:dc:a0:16:74:db:f0:b9:a5: - 46:35:8d:53:e8:7d:37:5b:4d:ad:a3:df:d6:ae:01: - 38:ad:16:09:6e:fd:65:ad:1c:4b:48:12:1e:48:a7: - ff:5b:47:c4:c9:3b:74:85:63:1a:0a:06:b2:9f:b9: - cb:ad:dc:3f:24:8b:a4:a7:8a:13:15:45:89:24:c1: - a7:3b:c2:a2:c8:74:f1:3f:6f + 00:bc:4c:d5:b3:8d:92:fa:66:ac:32:43:1a:9e:eb: + 17:e0:aa:76:35:1b:1d:10:48:4e:3e:22:8b:75:2e: + e8:6f:a4:55:1e:0a:5e:60:c0:61:f1:7d:29:58:7e: + 0b:ef:29:be:ad:f8:f7:43:c8:58:95:14:5b:1d:af: + 4a:b8:90:9e:4e:ec:4e:b3:86:7a:b9:96:c1:34:d3: + b9:a6:57:df:9b:bd:d9:dd:67:15:54:d4:9f:65:b8: + 33:29:59:ba:9a:c6:75:ea:a5:76:3d:a4:57:0f:e2: + e4:c3:91:35:1d:6e:ff:61:7d:c2:53:23:66:b2:a8: + 0b:e1:c7:55:48:c5:2b:4d:7d Exponent: 65537 (0x10001) Signature Algorithm: sha1WithRSAEncryption - 04:21:70:de:14:92:27:13:e8:d2:b0:51:f0:af:34:75:0b:a7: - ff:84:cb:c6:96:30:80:01:f5:c1:3a:c6:81:ee:ba:89:60:33: - c3:e5:0f:43:cc:ac:81:8d:09:fb:25:e1:67:40:64:a3:ca:fd: - bd:9c:c4:73:e4:bc:4d:8e:e2:70:f1:17:ce:b4:ab:a0:b2:63: - 72:25:27:ae:d5:8e:18:73:0d:dc:12:5a:32:1c:b7:da:cd:23: - 5b:c8:87:58:08:3e:95:0c:fd:c8:48:a2:75:6e:79:f2:00:82: - 6e:b5:cc:71:e3:79:ca:68:85:9b:1b:5c:52:bf:a2:5a:71:e3: - 05:b5 + 18:bb:93:d9:2a:e0:34:69:2f:96:57:ac:55:ac:a7:83:04:b4: + bc:22:7f:5f:f7:c0:dc:ac:af:13:9b:86:7e:ac:02:8c:44:83: + 2e:c0:fa:a1:77:1d:dd:86:31:7e:98:93:c0:4f:b2:3d:be:30: + 6f:a5:fc:c7:2e:b1:b8:08:d2:17:cb:60:55:bf:5a:e0:94:f3: + 1d:44:fa:b1:2f:1a:24:c5:33:e1:d4:f0:ac:d5:2c:67:da:a7: + 5d:ee:eb:d6:7a:a7:41:e8:94:7a:34:43:b2:1f:ab:e9:cf:5d: + 25:49:56:18:d2:a9:49:1a:37:34:43:c7:06:96:4a:29:38:cc: + f2:1c -----BEGIN CERTIFICATE----- -MIIBnjCCAQegAwIBAgIBAzANBgkqhkiG9w0BAQUFADASMRAwDgYDVQQDEwdUZXN0IENBMCIYDzI -wMTcwMTAxMDAwMDAwWhgPMjAxODAxMDEwMDAwMDBaMBQxEjAQBgNVBAMTCVRlc3QgQ2VydDCBnz -ANBgkqhkiG9w0BAQEFAAOBjQAwgYkCgYEA1RI/Im+w4UPFk7PDW3BSsosQ7BHExKqqQ5LI0PM1I -+N2LbTqkyZvankcZFHTTSFKc4M13KAWdNvwuaVGNY1T6H03W02to9/WrgE4rRYJbv1lrRxLSBIe -SKf/W0fEyTt0hWMaCgayn7nLrdw/JIukp4oTFUWJJMGnO8KiyHTxP28CAwEAATANBgkqhkiG9w0 -BAQUFAAOBgQAEIXDeFJInE+jSsFHwrzR1C6f/hMvGljCAAfXBOsaB7rqJYDPD5Q9DzKyBjQn7Je -FnQGSjyv29nMRz5LxNjuJw8RfOtKugsmNyJSeu1Y4Ycw3cEloyHLfazSNbyIdYCD6VDP3ISKJ1b -nnyAIJutcxx43nKaIWbG1xSv6JaceMFtQ== +MIIBqzCCARSgAwIBAgIBBDANBgkqhkiG9w0BAQUFADAfMR0wGwYDVQQDDBRUZXN0IEludGVybWV +kaWF0ZSBDQTAiGA8yMDE3MDEwMTAwMDAwMFoYDzIwMTgwMTAxMDAwMDAwWjAUMRIwEAYDVQQDDA +lUZXN0IENlcnQwgZ8wDQYJKoZIhvcNAQEBBQADgY0AMIGJAoGBALxM1bONkvpmrDJDGp7rF+Cqd +jUbHRBITj4ii3Uu6G+kVR4KXmDAYfF9KVh+C+8pvq3490PIWJUUWx2vSriQnk7sTrOGermWwTTT +uaZX35u92d1nFVTUn2W4MylZuprGdeqldj2kVw/i5MORNR1u/2F9wlMjZrKoC+HHVUjFK019AgM +BAAEwDQYJKoZIhvcNAQEFBQADgYEAGLuT2SrgNGkvllesVayngwS0vCJ/X/fA3KyvE5uGfqwCjE +SDLsD6oXcd3YYxfpiTwE+yPb4wb6X8xy6xuAjSF8tgVb9a4JTzHUT6sS8aJMUz4dTwrNUsZ9qnX +e7r1nqnQeiUejRDsh+r6c9dJUlWGNKpSRo3NEPHBpZKKTjM8hw= -----END CERTIFICATE----- $ openssl asn1parse -i < [OCSP REQUEST] @@ -123,10 +124,10 @@ 10:d=5 hl=2 l= 9 cons: SEQUENCE 12:d=6 hl=2 l= 5 prim: OBJECT :sha1 19:d=6 hl=2 l= 0 prim: NULL - 21:d=5 hl=2 l= 20 prim: OCTET STRING [HEX DUMP]:02FF75DA24DE8ADD150FAB689DCCE6E6636D0901 - 43:d=5 hl=2 l= 20 prim: OCTET STRING [HEX DUMP]:84E1BA52A25C543CA972491224BC8B1ECA8B9FF4 - 65:d=5 hl=2 l= 1 prim: INTEGER :03 + 21:d=5 hl=2 l= 20 prim: OCTET STRING [HEX DUMP]:449B1C5B31C6E9990966523E49C3F773C024190A + 43:d=5 hl=2 l= 20 prim: OCTET STRING [HEX DUMP]:FC6D3387CC3B39B049C755C46DF4395548930BCE + 65:d=5 hl=2 l= 1 prim: INTEGER :04 -----BEGIN OCSP REQUEST----- -MEIwQDA+MDwwOjAJBgUrDgMCGgUABBQC/3XaJN6K3RUPq2idzObmY20JAQQUhOG6UqJcVDypckk -SJLyLHsqLn/QCAQM= +MEIwQDA+MDwwOjAJBgUrDgMCGgUABBREmxxbMcbpmQlmUj5Jw/dzwCQZCgQU/G0zh8w7ObBJx1X +EbfQ5VUiTC84CAQQ= -----END OCSP REQUEST-----
diff --git a/net/data/ocsp_unittest/multiple_response.pem b/net/data/ocsp_unittest/multiple_response.pem index 4494e05e..7d528a2 100644 --- a/net/data/ocsp_unittest/multiple_response.pem +++ b/net/data/ocsp_unittest/multiple_response.pem
@@ -5,132 +5,133 @@ OCSP Response Status: successful (0x0) Response Type: Basic OCSP Response Version: 1 (0x0) - Responder Id: CN = Test CA + Responder Id: CN = Test Intermediate CA Produced At: Mar 2 00:00:00 2017 GMT Responses: Certificate ID: Hash Algorithm: sha1 - Issuer Name Hash: 02FF75DA24DE8ADD150FAB689DCCE6E6636D0901 - Issuer Key Hash: 84E1BA52A25C543CA972491224BC8B1ECA8B9FF4 - Serial Number: 03 + Issuer Name Hash: 449B1C5B31C6E9990966523E49C3F773C024190A + Issuer Key Hash: FC6D3387CC3B39B049C755C46DF4395548930BCE + Serial Number: 04 Cert Status: good This Update: Mar 1 00:00:00 2017 GMT Certificate ID: Hash Algorithm: sha1 - Issuer Name Hash: 02FF75DA24DE8ADD150FAB689DCCE6E6636D0901 - Issuer Key Hash: 84E1BA52A25C543CA972491224BC8B1ECA8B9FF4 - Serial Number: 03 + Issuer Name Hash: 449B1C5B31C6E9990966523E49C3F773C024190A + Issuer Key Hash: FC6D3387CC3B39B049C755C46DF4395548930BCE + Serial Number: 04 Cert Status: unknown This Update: Mar 1 00:00:00 2017 GMT Signature Algorithm: sha1WithRSAEncryption - 69:04:a5:b4:a2:4a:95:8c:24:96:df:39:e0:be:2d:1f:e0:7f: - f8:04:25:6e:36:78:36:fe:95:dc:f9:58:9c:58:27:90:1d:0c: - a1:85:e8:6c:7e:95:07:68:a5:f7:33:a4:85:28:e6:fb:97:d3: - 22:9e:c5:96:21:24:0f:3d:4f:bc:fd:1f:74:e8:71:22:95:72: - bd:34:79:1a:b0:11:b4:38:66:c4:c6:35:fd:27:5e:62:b3:d4: - 07:d9:0c:a3:15:83:fb:32:4c:61:ad:7b:dc:6d:54:8e:8c:75: - 6a:8a:8b:4f:fe:e5:83:32:c6:34:6f:b0:8b:14:bf:dc:48:7a: - 86:03 + 04:a7:43:86:0a:de:ed:da:98:17:52:3d:ba:cb:70:87:3b:43: + 23:fc:9d:d0:33:d1:75:b4:a5:e5:bc:8c:95:cc:ba:1f:2c:e2: + d3:32:35:c3:c6:ab:e6:5b:7c:a1:24:2e:68:21:b3:cb:00:29: + 7b:15:5c:27:7b:0c:07:fb:d0:dc:a2:37:2c:f6:ed:b5:c6:b0: + a3:59:ee:1c:08:48:01:dc:fa:cb:e0:c6:d0:79:c3:19:03:9b: + b3:26:1a:60:65:9c:cf:0b:a3:21:d3:d5:3e:83:ab:10:e6:f6: + 02:3a:4d:ee:3f:b9:38:62:ed:48:ae:f4:bd:bd:2b:d7:97:8f: + 05:67 -----BEGIN OCSP RESPONSE----- -MIIBfAoBAKCCAXUwggFxBgkrBgEFBQcwAQEEggFiMIIBXjCByKEUMBIxEDAOBgNVBAMTB1Rlc3Q -gQ0EYDzIwMTcwMzAyMDAwMDAwWjCBnjBNMDgwBwYFKw4DAhoEFAL/ddok3ordFQ+raJ3M5uZjbQ -kBBBSE4bpSolxUPKlySRIkvIseyouf9AIBA4AAGA8yMDE3MDMwMTAwMDAwMFowTTA4MAcGBSsOA -wIaBBQC/3XaJN6K3RUPq2idzObmY20JAQQUhOG6UqJcVDypckkSJLyLHsqLn/QCAQOCABgPMjAx -NzAzMDEwMDAwMDBaMA0GCSqGSIb3DQEBBQUAA4GBAGkEpbSiSpWMJJbfOeC+LR/gf/gEJW42eDb -+ldz5WJxYJ5AdDKGF6Gx+lQdopfczpIUo5vuX0yKexZYhJA89T7z9H3TocSKVcr00eRqwEbQ4Zs -TGNf0nXmKz1AfZDKMVg/syTGGte9xtVI6MdWqKi0/+5YMyxjRvsIsUv9xIeoYD +MIIBiQoBAKCCAYIwggF+BgkrBgEFBQcwAQEEggFvMIIBazCB1aEhMB8xHTAbBgNVBAMMFFRlc3Q +gSW50ZXJtZWRpYXRlIENBGA8yMDE3MDMwMjAwMDAwMFowgZ4wTTA4MAcGBSsOAwIaBBREmxxbMc +bpmQlmUj5Jw/dzwCQZCgQU/G0zh8w7ObBJx1XEbfQ5VUiTC84CAQSAABgPMjAxNzAzMDEwMDAwM +DBaME0wODAHBgUrDgMCGgQURJscWzHG6ZkJZlI+ScP3c8AkGQoEFPxtM4fMOzmwScdVxG30OVVI +kwvOAgEEggAYDzIwMTcwMzAxMDAwMDAwWjANBgkqhkiG9w0BAQUFAAOBgQAEp0OGCt7t2pgXUj2 +6y3CHO0Mj/J3QM9F1tKXlvIyVzLofLOLTMjXDxqvmW3yhJC5oIbPLACl7FVwnewwH+9Dcojcs9u +21xrCjWe4cCEgB3PrL4MbQecMZA5uzJhpgZZzPC6Mh09U+g6sQ5vYCOk3uP7k4Yu1IrvS9vSvXl +48FZw== -----END OCSP RESPONSE----- $ openssl x509 -text < [CA CERTIFICATE] Certificate: Data: Version: 3 (0x2) - Serial Number: 0 (0x0) + Serial Number: 1 (0x1) Signature Algorithm: sha1WithRSAEncryption - Issuer: CN=Test CA + Issuer: CN = Test CA Validity Not Before: Jan 1 00:00:00 2017 GMT Not After : Jan 1 00:00:00 2018 GMT - Subject: CN=Test CA + Subject: CN = Test Intermediate CA Subject Public Key Info: Public Key Algorithm: rsaEncryption Public-Key: (1024 bit) Modulus: - 00:b8:25:2b:ee:59:9a:9d:bc:b4:48:ae:09:ce:0d: - ba:c5:83:57:03:92:fd:52:32:55:f5:e4:2e:a6:cf: - 9e:4b:c4:10:af:24:da:d5:dd:44:a8:d6:28:38:9c: - a5:11:c9:0b:70:a1:b5:71:cf:a4:35:c2:6a:17:b1: - b5:c7:cf:74:83:ac:7a:d5:3b:12:66:74:f2:4b:15: - b0:c2:59:af:0c:78:2c:42:3c:3f:8b:83:b3:1d:9a: - c8:bc:ce:b0:c8:f2:1a:a8:0a:1c:bb:6e:6e:d4:c6: - 10:66:3c:a8:ec:e3:c4:63:40:f6:79:ec:8b:14:ff: - 85:9e:2d:1a:e7:e8:31:56:81 + 00:b9:32:09:de:33:4a:4f:e2:04:73:49:d5:2e:2b: + 83:92:3a:94:e4:1b:0c:27:1b:f8:43:83:17:b8:75: + f5:a4:af:e3:4c:84:3e:6c:48:79:76:df:4d:f5:39: + af:92:4b:c5:a0:86:ab:35:cc:19:6b:93:82:c0:f8: + 44:4d:1a:14:5d:48:87:65:02:0e:b0:a8:96:d9:06: + 19:3f:aa:85:2d:84:c0:78:19:a6:96:ab:26:56:f7: + 6f:5a:1a:97:a2:01:88:00:99:10:8a:97:39:c8:22: + 6e:de:e5:56:f4:a6:23:cd:ea:48:0e:65:67:a4:73: + a0:50:91:de:ba:cf:54:08:8f Exponent: 65537 (0x10001) Signature Algorithm: sha1WithRSAEncryption - 35:fe:ee:96:31:c7:3d:91:eb:22:53:1f:bf:cc:20:cc:aa:f4: - 04:92:3c:8b:50:06:ea:a1:cc:b7:c2:4a:d6:02:af:53:a7:a4: - 71:81:78:bc:95:f3:2d:46:c4:83:4c:d5:92:11:7c:c7:67:d3: - 47:f6:06:9f:1c:46:da:d6:20:72:47:c2:57:d7:fb:66:d3:35: - 82:07:61:13:4e:4d:e6:0c:93:e6:f3:be:98:ff:e8:de:60:a7: - 06:94:cd:bb:f5:6e:b3:4e:0b:d6:e9:2b:72:bd:6e:ae:86:23: - 2d:44:33:c4:3b:a7:52:12:46:d2:76:95:06:3e:69:0f:72:60: - 16:d6 + 48:d5:9f:8d:90:bc:4a:59:38:1d:2b:83:2d:71:1c:74:9d:01: + 73:a0:b6:98:e7:1c:c2:22:66:23:33:0a:8f:64:ff:9c:6b:37: + 09:12:1c:15:12:cb:c3:61:d9:ab:cd:96:dd:95:fa:a6:02:67: + 3c:4c:ec:98:38:5c:fc:48:cc:85:a9:5b:49:2c:2b:06:66:07: + 9e:31:0f:93:10:ab:3e:9f:97:60:64:01:61:7e:86:15:bb:5e: + f1:90:31:a3:54:d0:86:0e:80:05:87:09:2e:65:b6:95:89:5c: + c1:e5:80:d9:b8:81:b6:ed:1a:20:b8:9b:22:ce:ef:d0:26:47: + 9d:57 -----BEGIN CA CERTIFICATE----- -MIIBnDCCAQWgAwIBAgIBADANBgkqhkiG9w0BAQUFADASMRAwDgYDVQQDEwdUZXN0IENBMCIYDzI -wMTcwMTAxMDAwMDAwWhgPMjAxODAxMDEwMDAwMDBaMBIxEDAOBgNVBAMTB1Rlc3QgQ0EwgZ8wDQ -YJKoZIhvcNAQEBBQADgY0AMIGJAoGBALglK+5Zmp28tEiuCc4NusWDVwOS/VIyVfXkLqbPnkvEE -K8k2tXdRKjWKDicpRHJC3ChtXHPpDXCahextcfPdIOsetU7EmZ08ksVsMJZrwx4LEI8P4uDsx2a -yLzOsMjyGqgKHLtubtTGEGY8qOzjxGNA9nnsixT/hZ4tGufoMVaBAgMBAAEwDQYJKoZIhvcNAQE -FBQADgYEANf7uljHHPZHrIlMfv8wgzKr0BJI8i1AG6qHMt8JK1gKvU6ekcYF4vJXzLUbEg0zVkh -F8x2fTR/YGnxxG2tYgckfCV9f7ZtM1ggdhE05N5gyT5vO+mP/o3mCnBpTNu/Vus04L1ukrcr1ur -oYjLUQzxDunUhJG0naVBj5pD3JgFtY= +MIIBqTCCARKgAwIBAgIBATANBgkqhkiG9w0BAQUFADASMRAwDgYDVQQDDAdUZXN0IENBMCIYDzI +wMTcwMTAxMDAwMDAwWhgPMjAxODAxMDEwMDAwMDBaMB8xHTAbBgNVBAMMFFRlc3QgSW50ZXJtZW +RpYXRlIENBMIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQC5MgneM0pP4gRzSdUuK4OSOpTkG +wwnG/hDgxe4dfWkr+NMhD5sSHl23031Oa+SS8Wghqs1zBlrk4LA+ERNGhRdSIdlAg6wqJbZBhk/ +qoUthMB4GaaWqyZW929aGpeiAYgAmRCKlznIIm7e5Vb0piPN6kgOZWekc6BQkd66z1QIjwIDAQA +BMA0GCSqGSIb3DQEBBQUAA4GBAEjVn42QvEpZOB0rgy1xHHSdAXOgtpjnHMIiZiMzCo9k/5xrNw +kSHBUSy8Nh2avNlt2V+qYCZzxM7Jg4XPxIzIWpW0ksKwZmB54xD5MQqz6fl2BkAWF+hhW7XvGQM +aNU0IYOgAWHCS5ltpWJXMHlgNm4gbbtGiC4myLO79AmR51X -----END CA CERTIFICATE----- $ openssl x509 -text < [CERTIFICATE] Certificate: Data: Version: 3 (0x2) - Serial Number: 3 (0x3) + Serial Number: 4 (0x4) Signature Algorithm: sha1WithRSAEncryption - Issuer: CN=Test CA + Issuer: CN = Test Intermediate CA Validity Not Before: Jan 1 00:00:00 2017 GMT Not After : Jan 1 00:00:00 2018 GMT - Subject: CN=Test Cert + Subject: CN = Test Cert Subject Public Key Info: Public Key Algorithm: rsaEncryption Public-Key: (1024 bit) Modulus: - 00:d5:12:3f:22:6f:b0:e1:43:c5:93:b3:c3:5b:70: - 52:b2:8b:10:ec:11:c4:c4:aa:aa:43:92:c8:d0:f3: - 35:23:e3:76:2d:b4:ea:93:26:6f:6a:79:1c:64:51: - d3:4d:21:4a:73:83:35:dc:a0:16:74:db:f0:b9:a5: - 46:35:8d:53:e8:7d:37:5b:4d:ad:a3:df:d6:ae:01: - 38:ad:16:09:6e:fd:65:ad:1c:4b:48:12:1e:48:a7: - ff:5b:47:c4:c9:3b:74:85:63:1a:0a:06:b2:9f:b9: - cb:ad:dc:3f:24:8b:a4:a7:8a:13:15:45:89:24:c1: - a7:3b:c2:a2:c8:74:f1:3f:6f + 00:bc:4c:d5:b3:8d:92:fa:66:ac:32:43:1a:9e:eb: + 17:e0:aa:76:35:1b:1d:10:48:4e:3e:22:8b:75:2e: + e8:6f:a4:55:1e:0a:5e:60:c0:61:f1:7d:29:58:7e: + 0b:ef:29:be:ad:f8:f7:43:c8:58:95:14:5b:1d:af: + 4a:b8:90:9e:4e:ec:4e:b3:86:7a:b9:96:c1:34:d3: + b9:a6:57:df:9b:bd:d9:dd:67:15:54:d4:9f:65:b8: + 33:29:59:ba:9a:c6:75:ea:a5:76:3d:a4:57:0f:e2: + e4:c3:91:35:1d:6e:ff:61:7d:c2:53:23:66:b2:a8: + 0b:e1:c7:55:48:c5:2b:4d:7d Exponent: 65537 (0x10001) Signature Algorithm: sha1WithRSAEncryption - 04:21:70:de:14:92:27:13:e8:d2:b0:51:f0:af:34:75:0b:a7: - ff:84:cb:c6:96:30:80:01:f5:c1:3a:c6:81:ee:ba:89:60:33: - c3:e5:0f:43:cc:ac:81:8d:09:fb:25:e1:67:40:64:a3:ca:fd: - bd:9c:c4:73:e4:bc:4d:8e:e2:70:f1:17:ce:b4:ab:a0:b2:63: - 72:25:27:ae:d5:8e:18:73:0d:dc:12:5a:32:1c:b7:da:cd:23: - 5b:c8:87:58:08:3e:95:0c:fd:c8:48:a2:75:6e:79:f2:00:82: - 6e:b5:cc:71:e3:79:ca:68:85:9b:1b:5c:52:bf:a2:5a:71:e3: - 05:b5 + 18:bb:93:d9:2a:e0:34:69:2f:96:57:ac:55:ac:a7:83:04:b4: + bc:22:7f:5f:f7:c0:dc:ac:af:13:9b:86:7e:ac:02:8c:44:83: + 2e:c0:fa:a1:77:1d:dd:86:31:7e:98:93:c0:4f:b2:3d:be:30: + 6f:a5:fc:c7:2e:b1:b8:08:d2:17:cb:60:55:bf:5a:e0:94:f3: + 1d:44:fa:b1:2f:1a:24:c5:33:e1:d4:f0:ac:d5:2c:67:da:a7: + 5d:ee:eb:d6:7a:a7:41:e8:94:7a:34:43:b2:1f:ab:e9:cf:5d: + 25:49:56:18:d2:a9:49:1a:37:34:43:c7:06:96:4a:29:38:cc: + f2:1c -----BEGIN CERTIFICATE----- -MIIBnjCCAQegAwIBAgIBAzANBgkqhkiG9w0BAQUFADASMRAwDgYDVQQDEwdUZXN0IENBMCIYDzI -wMTcwMTAxMDAwMDAwWhgPMjAxODAxMDEwMDAwMDBaMBQxEjAQBgNVBAMTCVRlc3QgQ2VydDCBnz -ANBgkqhkiG9w0BAQEFAAOBjQAwgYkCgYEA1RI/Im+w4UPFk7PDW3BSsosQ7BHExKqqQ5LI0PM1I -+N2LbTqkyZvankcZFHTTSFKc4M13KAWdNvwuaVGNY1T6H03W02to9/WrgE4rRYJbv1lrRxLSBIe -SKf/W0fEyTt0hWMaCgayn7nLrdw/JIukp4oTFUWJJMGnO8KiyHTxP28CAwEAATANBgkqhkiG9w0 -BAQUFAAOBgQAEIXDeFJInE+jSsFHwrzR1C6f/hMvGljCAAfXBOsaB7rqJYDPD5Q9DzKyBjQn7Je -FnQGSjyv29nMRz5LxNjuJw8RfOtKugsmNyJSeu1Y4Ycw3cEloyHLfazSNbyIdYCD6VDP3ISKJ1b -nnyAIJutcxx43nKaIWbG1xSv6JaceMFtQ== +MIIBqzCCARSgAwIBAgIBBDANBgkqhkiG9w0BAQUFADAfMR0wGwYDVQQDDBRUZXN0IEludGVybWV +kaWF0ZSBDQTAiGA8yMDE3MDEwMTAwMDAwMFoYDzIwMTgwMTAxMDAwMDAwWjAUMRIwEAYDVQQDDA +lUZXN0IENlcnQwgZ8wDQYJKoZIhvcNAQEBBQADgY0AMIGJAoGBALxM1bONkvpmrDJDGp7rF+Cqd +jUbHRBITj4ii3Uu6G+kVR4KXmDAYfF9KVh+C+8pvq3490PIWJUUWx2vSriQnk7sTrOGermWwTTT +uaZX35u92d1nFVTUn2W4MylZuprGdeqldj2kVw/i5MORNR1u/2F9wlMjZrKoC+HHVUjFK019AgM +BAAEwDQYJKoZIhvcNAQEFBQADgYEAGLuT2SrgNGkvllesVayngwS0vCJ/X/fA3KyvE5uGfqwCjE +SDLsD6oXcd3YYxfpiTwE+yPb4wb6X8xy6xuAjSF8tgVb9a4JTzHUT6sS8aJMUz4dTwrNUsZ9qnX +e7r1nqnQeiUejRDsh+r6c9dJUlWGNKpSRo3NEPHBpZKKTjM8hw= -----END CERTIFICATE----- $ openssl asn1parse -i < [OCSP REQUEST] @@ -142,10 +143,10 @@ 10:d=5 hl=2 l= 9 cons: SEQUENCE 12:d=6 hl=2 l= 5 prim: OBJECT :sha1 19:d=6 hl=2 l= 0 prim: NULL - 21:d=5 hl=2 l= 20 prim: OCTET STRING [HEX DUMP]:02FF75DA24DE8ADD150FAB689DCCE6E6636D0901 - 43:d=5 hl=2 l= 20 prim: OCTET STRING [HEX DUMP]:84E1BA52A25C543CA972491224BC8B1ECA8B9FF4 - 65:d=5 hl=2 l= 1 prim: INTEGER :03 + 21:d=5 hl=2 l= 20 prim: OCTET STRING [HEX DUMP]:449B1C5B31C6E9990966523E49C3F773C024190A + 43:d=5 hl=2 l= 20 prim: OCTET STRING [HEX DUMP]:FC6D3387CC3B39B049C755C46DF4395548930BCE + 65:d=5 hl=2 l= 1 prim: INTEGER :04 -----BEGIN OCSP REQUEST----- -MEIwQDA+MDwwOjAJBgUrDgMCGgUABBQC/3XaJN6K3RUPq2idzObmY20JAQQUhOG6UqJcVDypckk -SJLyLHsqLn/QCAQM= +MEIwQDA+MDwwOjAJBgUrDgMCGgUABBREmxxbMcbpmQlmUj5Jw/dzwCQZCgQU/G0zh8w7ObBJx1X +EbfQ5VUiTC84CAQQ= -----END OCSP REQUEST-----
diff --git a/net/data/ocsp_unittest/no_response.pem b/net/data/ocsp_unittest/no_response.pem index d43a443..405cd30 100644 --- a/net/data/ocsp_unittest/no_response.pem +++ b/net/data/ocsp_unittest/no_response.pem
@@ -5,113 +5,114 @@ OCSP Response Status: successful (0x0) Response Type: Basic OCSP Response Version: 1 (0x0) - Responder Id: CN = Test CA + Responder Id: CN = Test Intermediate CA Produced At: Mar 2 00:00:00 2017 GMT Responses: Signature Algorithm: sha1WithRSAEncryption - 8a:e1:ee:17:c2:15:ba:18:ea:d2:61:9a:bc:fc:7c:06:c1:2a: - b1:46:7f:1f:4d:59:e7:a2:44:ea:a9:3d:05:be:3b:28:ab:51: - c1:12:d7:66:b1:6a:68:16:82:2c:e8:70:7a:e4:71:90:67:fd: - 76:0b:87:17:12:5a:14:dc:81:2b:5c:96:c4:0a:3f:19:b5:07: - fa:b1:90:e3:3a:a8:05:01:68:03:4c:8e:2a:c0:4e:2a:30:66: - 55:5b:72:15:d0:86:df:7e:c8:17:a0:48:d4:b4:38:f3:95:53: - 8a:5e:c6:9d:dc:2a:46:59:dd:a8:c6:d6:9b:92:8d:fe:a2:a4: - 32:b4 + 73:15:3c:c0:57:e4:26:f2:91:9a:3d:ec:03:0f:15:d2:24:c6: + 17:81:0f:5b:22:72:37:50:a8:e4:8e:19:4f:76:eb:d7:41:1c: + 45:a5:35:2d:57:25:53:1c:13:26:f4:f1:65:22:42:2a:e4:9a: + bb:e0:5b:aa:87:ea:4f:91:14:06:69:b2:67:90:7b:f9:63:87: + a1:21:14:bb:c9:48:03:8d:90:f4:39:1d:1f:d7:26:88:21:b4: + 12:38:31:33:78:21:ca:f7:f3:e6:2d:cb:f2:fc:43:ae:94:60: + 86:df:aa:44:cf:b9:26:01:24:35:a3:80:84:91:3e:da:73:88: + c6:06 -----BEGIN OCSP RESPONSE----- -MIHYCgEAoIHSMIHPBgkrBgEFBQcwAQEEgcEwgb4wKaEUMBIxEDAOBgNVBAMTB1Rlc3QgQ0EYDzI -wMTcwMzAyMDAwMDAwWjAAMA0GCSqGSIb3DQEBBQUAA4GBAIrh7hfCFboY6tJhmrz8fAbBKrFGfx -9NWeeiROqpPQW+OyirUcES12axamgWgizocHrkcZBn/XYLhxcSWhTcgStclsQKPxm1B/qxkOM6q -AUBaANMjirATiowZlVbchXQht9+yBegSNS0OPOVU4pexp3cKkZZ3ajG1puSjf6ipDK0 +MIHlCgEAoIHfMIHcBgkrBgEFBQcwAQEEgc4wgcswNqEhMB8xHTAbBgNVBAMMFFRlc3QgSW50ZXJ +tZWRpYXRlIENBGA8yMDE3MDMwMjAwMDAwMFowADANBgkqhkiG9w0BAQUFAAOBgQBzFTzAV+Qm8p +GaPewDDxXSJMYXgQ9bInI3UKjkjhlPduvXQRxFpTUtVyVTHBMm9PFlIkIq5Jq74Fuqh+pPkRQGa +bJnkHv5Y4ehIRS7yUgDjZD0OR0f1yaIIbQSODEzeCHK9/PmLcvy/EOulGCG36pEz7kmASQ1o4CE +kT7ac4jGBg== -----END OCSP RESPONSE----- $ openssl x509 -text < [CA CERTIFICATE] Certificate: Data: Version: 3 (0x2) - Serial Number: 0 (0x0) + Serial Number: 1 (0x1) Signature Algorithm: sha1WithRSAEncryption - Issuer: CN=Test CA + Issuer: CN = Test CA Validity Not Before: Jan 1 00:00:00 2017 GMT Not After : Jan 1 00:00:00 2018 GMT - Subject: CN=Test CA + Subject: CN = Test Intermediate CA Subject Public Key Info: Public Key Algorithm: rsaEncryption Public-Key: (1024 bit) Modulus: - 00:b8:25:2b:ee:59:9a:9d:bc:b4:48:ae:09:ce:0d: - ba:c5:83:57:03:92:fd:52:32:55:f5:e4:2e:a6:cf: - 9e:4b:c4:10:af:24:da:d5:dd:44:a8:d6:28:38:9c: - a5:11:c9:0b:70:a1:b5:71:cf:a4:35:c2:6a:17:b1: - b5:c7:cf:74:83:ac:7a:d5:3b:12:66:74:f2:4b:15: - b0:c2:59:af:0c:78:2c:42:3c:3f:8b:83:b3:1d:9a: - c8:bc:ce:b0:c8:f2:1a:a8:0a:1c:bb:6e:6e:d4:c6: - 10:66:3c:a8:ec:e3:c4:63:40:f6:79:ec:8b:14:ff: - 85:9e:2d:1a:e7:e8:31:56:81 + 00:b9:32:09:de:33:4a:4f:e2:04:73:49:d5:2e:2b: + 83:92:3a:94:e4:1b:0c:27:1b:f8:43:83:17:b8:75: + f5:a4:af:e3:4c:84:3e:6c:48:79:76:df:4d:f5:39: + af:92:4b:c5:a0:86:ab:35:cc:19:6b:93:82:c0:f8: + 44:4d:1a:14:5d:48:87:65:02:0e:b0:a8:96:d9:06: + 19:3f:aa:85:2d:84:c0:78:19:a6:96:ab:26:56:f7: + 6f:5a:1a:97:a2:01:88:00:99:10:8a:97:39:c8:22: + 6e:de:e5:56:f4:a6:23:cd:ea:48:0e:65:67:a4:73: + a0:50:91:de:ba:cf:54:08:8f Exponent: 65537 (0x10001) Signature Algorithm: sha1WithRSAEncryption - 35:fe:ee:96:31:c7:3d:91:eb:22:53:1f:bf:cc:20:cc:aa:f4: - 04:92:3c:8b:50:06:ea:a1:cc:b7:c2:4a:d6:02:af:53:a7:a4: - 71:81:78:bc:95:f3:2d:46:c4:83:4c:d5:92:11:7c:c7:67:d3: - 47:f6:06:9f:1c:46:da:d6:20:72:47:c2:57:d7:fb:66:d3:35: - 82:07:61:13:4e:4d:e6:0c:93:e6:f3:be:98:ff:e8:de:60:a7: - 06:94:cd:bb:f5:6e:b3:4e:0b:d6:e9:2b:72:bd:6e:ae:86:23: - 2d:44:33:c4:3b:a7:52:12:46:d2:76:95:06:3e:69:0f:72:60: - 16:d6 + 48:d5:9f:8d:90:bc:4a:59:38:1d:2b:83:2d:71:1c:74:9d:01: + 73:a0:b6:98:e7:1c:c2:22:66:23:33:0a:8f:64:ff:9c:6b:37: + 09:12:1c:15:12:cb:c3:61:d9:ab:cd:96:dd:95:fa:a6:02:67: + 3c:4c:ec:98:38:5c:fc:48:cc:85:a9:5b:49:2c:2b:06:66:07: + 9e:31:0f:93:10:ab:3e:9f:97:60:64:01:61:7e:86:15:bb:5e: + f1:90:31:a3:54:d0:86:0e:80:05:87:09:2e:65:b6:95:89:5c: + c1:e5:80:d9:b8:81:b6:ed:1a:20:b8:9b:22:ce:ef:d0:26:47: + 9d:57 -----BEGIN CA CERTIFICATE----- -MIIBnDCCAQWgAwIBAgIBADANBgkqhkiG9w0BAQUFADASMRAwDgYDVQQDEwdUZXN0IENBMCIYDzI -wMTcwMTAxMDAwMDAwWhgPMjAxODAxMDEwMDAwMDBaMBIxEDAOBgNVBAMTB1Rlc3QgQ0EwgZ8wDQ -YJKoZIhvcNAQEBBQADgY0AMIGJAoGBALglK+5Zmp28tEiuCc4NusWDVwOS/VIyVfXkLqbPnkvEE -K8k2tXdRKjWKDicpRHJC3ChtXHPpDXCahextcfPdIOsetU7EmZ08ksVsMJZrwx4LEI8P4uDsx2a -yLzOsMjyGqgKHLtubtTGEGY8qOzjxGNA9nnsixT/hZ4tGufoMVaBAgMBAAEwDQYJKoZIhvcNAQE -FBQADgYEANf7uljHHPZHrIlMfv8wgzKr0BJI8i1AG6qHMt8JK1gKvU6ekcYF4vJXzLUbEg0zVkh -F8x2fTR/YGnxxG2tYgckfCV9f7ZtM1ggdhE05N5gyT5vO+mP/o3mCnBpTNu/Vus04L1ukrcr1ur -oYjLUQzxDunUhJG0naVBj5pD3JgFtY= +MIIBqTCCARKgAwIBAgIBATANBgkqhkiG9w0BAQUFADASMRAwDgYDVQQDDAdUZXN0IENBMCIYDzI +wMTcwMTAxMDAwMDAwWhgPMjAxODAxMDEwMDAwMDBaMB8xHTAbBgNVBAMMFFRlc3QgSW50ZXJtZW +RpYXRlIENBMIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQC5MgneM0pP4gRzSdUuK4OSOpTkG +wwnG/hDgxe4dfWkr+NMhD5sSHl23031Oa+SS8Wghqs1zBlrk4LA+ERNGhRdSIdlAg6wqJbZBhk/ +qoUthMB4GaaWqyZW929aGpeiAYgAmRCKlznIIm7e5Vb0piPN6kgOZWekc6BQkd66z1QIjwIDAQA +BMA0GCSqGSIb3DQEBBQUAA4GBAEjVn42QvEpZOB0rgy1xHHSdAXOgtpjnHMIiZiMzCo9k/5xrNw +kSHBUSy8Nh2avNlt2V+qYCZzxM7Jg4XPxIzIWpW0ksKwZmB54xD5MQqz6fl2BkAWF+hhW7XvGQM +aNU0IYOgAWHCS5ltpWJXMHlgNm4gbbtGiC4myLO79AmR51X -----END CA CERTIFICATE----- $ openssl x509 -text < [CERTIFICATE] Certificate: Data: Version: 3 (0x2) - Serial Number: 3 (0x3) + Serial Number: 4 (0x4) Signature Algorithm: sha1WithRSAEncryption - Issuer: CN=Test CA + Issuer: CN = Test Intermediate CA Validity Not Before: Jan 1 00:00:00 2017 GMT Not After : Jan 1 00:00:00 2018 GMT - Subject: CN=Test Cert + Subject: CN = Test Cert Subject Public Key Info: Public Key Algorithm: rsaEncryption Public-Key: (1024 bit) Modulus: - 00:d5:12:3f:22:6f:b0:e1:43:c5:93:b3:c3:5b:70: - 52:b2:8b:10:ec:11:c4:c4:aa:aa:43:92:c8:d0:f3: - 35:23:e3:76:2d:b4:ea:93:26:6f:6a:79:1c:64:51: - d3:4d:21:4a:73:83:35:dc:a0:16:74:db:f0:b9:a5: - 46:35:8d:53:e8:7d:37:5b:4d:ad:a3:df:d6:ae:01: - 38:ad:16:09:6e:fd:65:ad:1c:4b:48:12:1e:48:a7: - ff:5b:47:c4:c9:3b:74:85:63:1a:0a:06:b2:9f:b9: - cb:ad:dc:3f:24:8b:a4:a7:8a:13:15:45:89:24:c1: - a7:3b:c2:a2:c8:74:f1:3f:6f + 00:bc:4c:d5:b3:8d:92:fa:66:ac:32:43:1a:9e:eb: + 17:e0:aa:76:35:1b:1d:10:48:4e:3e:22:8b:75:2e: + e8:6f:a4:55:1e:0a:5e:60:c0:61:f1:7d:29:58:7e: + 0b:ef:29:be:ad:f8:f7:43:c8:58:95:14:5b:1d:af: + 4a:b8:90:9e:4e:ec:4e:b3:86:7a:b9:96:c1:34:d3: + b9:a6:57:df:9b:bd:d9:dd:67:15:54:d4:9f:65:b8: + 33:29:59:ba:9a:c6:75:ea:a5:76:3d:a4:57:0f:e2: + e4:c3:91:35:1d:6e:ff:61:7d:c2:53:23:66:b2:a8: + 0b:e1:c7:55:48:c5:2b:4d:7d Exponent: 65537 (0x10001) Signature Algorithm: sha1WithRSAEncryption - 04:21:70:de:14:92:27:13:e8:d2:b0:51:f0:af:34:75:0b:a7: - ff:84:cb:c6:96:30:80:01:f5:c1:3a:c6:81:ee:ba:89:60:33: - c3:e5:0f:43:cc:ac:81:8d:09:fb:25:e1:67:40:64:a3:ca:fd: - bd:9c:c4:73:e4:bc:4d:8e:e2:70:f1:17:ce:b4:ab:a0:b2:63: - 72:25:27:ae:d5:8e:18:73:0d:dc:12:5a:32:1c:b7:da:cd:23: - 5b:c8:87:58:08:3e:95:0c:fd:c8:48:a2:75:6e:79:f2:00:82: - 6e:b5:cc:71:e3:79:ca:68:85:9b:1b:5c:52:bf:a2:5a:71:e3: - 05:b5 + 18:bb:93:d9:2a:e0:34:69:2f:96:57:ac:55:ac:a7:83:04:b4: + bc:22:7f:5f:f7:c0:dc:ac:af:13:9b:86:7e:ac:02:8c:44:83: + 2e:c0:fa:a1:77:1d:dd:86:31:7e:98:93:c0:4f:b2:3d:be:30: + 6f:a5:fc:c7:2e:b1:b8:08:d2:17:cb:60:55:bf:5a:e0:94:f3: + 1d:44:fa:b1:2f:1a:24:c5:33:e1:d4:f0:ac:d5:2c:67:da:a7: + 5d:ee:eb:d6:7a:a7:41:e8:94:7a:34:43:b2:1f:ab:e9:cf:5d: + 25:49:56:18:d2:a9:49:1a:37:34:43:c7:06:96:4a:29:38:cc: + f2:1c -----BEGIN CERTIFICATE----- -MIIBnjCCAQegAwIBAgIBAzANBgkqhkiG9w0BAQUFADASMRAwDgYDVQQDEwdUZXN0IENBMCIYDzI -wMTcwMTAxMDAwMDAwWhgPMjAxODAxMDEwMDAwMDBaMBQxEjAQBgNVBAMTCVRlc3QgQ2VydDCBnz -ANBgkqhkiG9w0BAQEFAAOBjQAwgYkCgYEA1RI/Im+w4UPFk7PDW3BSsosQ7BHExKqqQ5LI0PM1I -+N2LbTqkyZvankcZFHTTSFKc4M13KAWdNvwuaVGNY1T6H03W02to9/WrgE4rRYJbv1lrRxLSBIe -SKf/W0fEyTt0hWMaCgayn7nLrdw/JIukp4oTFUWJJMGnO8KiyHTxP28CAwEAATANBgkqhkiG9w0 -BAQUFAAOBgQAEIXDeFJInE+jSsFHwrzR1C6f/hMvGljCAAfXBOsaB7rqJYDPD5Q9DzKyBjQn7Je -FnQGSjyv29nMRz5LxNjuJw8RfOtKugsmNyJSeu1Y4Ycw3cEloyHLfazSNbyIdYCD6VDP3ISKJ1b -nnyAIJutcxx43nKaIWbG1xSv6JaceMFtQ== +MIIBqzCCARSgAwIBAgIBBDANBgkqhkiG9w0BAQUFADAfMR0wGwYDVQQDDBRUZXN0IEludGVybWV +kaWF0ZSBDQTAiGA8yMDE3MDEwMTAwMDAwMFoYDzIwMTgwMTAxMDAwMDAwWjAUMRIwEAYDVQQDDA +lUZXN0IENlcnQwgZ8wDQYJKoZIhvcNAQEBBQADgY0AMIGJAoGBALxM1bONkvpmrDJDGp7rF+Cqd +jUbHRBITj4ii3Uu6G+kVR4KXmDAYfF9KVh+C+8pvq3490PIWJUUWx2vSriQnk7sTrOGermWwTTT +uaZX35u92d1nFVTUn2W4MylZuprGdeqldj2kVw/i5MORNR1u/2F9wlMjZrKoC+HHVUjFK019AgM +BAAEwDQYJKoZIhvcNAQEFBQADgYEAGLuT2SrgNGkvllesVayngwS0vCJ/X/fA3KyvE5uGfqwCjE +SDLsD6oXcd3YYxfpiTwE+yPb4wb6X8xy6xuAjSF8tgVb9a4JTzHUT6sS8aJMUz4dTwrNUsZ9qnX +e7r1nqnQeiUejRDsh+r6c9dJUlWGNKpSRo3NEPHBpZKKTjM8hw= -----END CERTIFICATE----- $ openssl asn1parse -i < [OCSP REQUEST] @@ -123,10 +124,10 @@ 10:d=5 hl=2 l= 9 cons: SEQUENCE 12:d=6 hl=2 l= 5 prim: OBJECT :sha1 19:d=6 hl=2 l= 0 prim: NULL - 21:d=5 hl=2 l= 20 prim: OCTET STRING [HEX DUMP]:02FF75DA24DE8ADD150FAB689DCCE6E6636D0901 - 43:d=5 hl=2 l= 20 prim: OCTET STRING [HEX DUMP]:84E1BA52A25C543CA972491224BC8B1ECA8B9FF4 - 65:d=5 hl=2 l= 1 prim: INTEGER :03 + 21:d=5 hl=2 l= 20 prim: OCTET STRING [HEX DUMP]:449B1C5B31C6E9990966523E49C3F773C024190A + 43:d=5 hl=2 l= 20 prim: OCTET STRING [HEX DUMP]:FC6D3387CC3B39B049C755C46DF4395548930BCE + 65:d=5 hl=2 l= 1 prim: INTEGER :04 -----BEGIN OCSP REQUEST----- -MEIwQDA+MDwwOjAJBgUrDgMCGgUABBQC/3XaJN6K3RUPq2idzObmY20JAQQUhOG6UqJcVDypckk -SJLyLHsqLn/QCAQM= +MEIwQDA+MDwwOjAJBgUrDgMCGgUABBREmxxbMcbpmQlmUj5Jw/dzwCQZCgQU/G0zh8w7ObBJx1X +EbfQ5VUiTC84CAQQ= -----END OCSP REQUEST-----
diff --git a/net/data/ocsp_unittest/ocsp_extra_certs.pem b/net/data/ocsp_unittest/ocsp_extra_certs.pem index c430232..600b9ce 100644 --- a/net/data/ocsp_unittest/ocsp_extra_certs.pem +++ b/net/data/ocsp_unittest/ocsp_extra_certs.pem
@@ -5,70 +5,26 @@ OCSP Response Status: successful (0x0) Response Type: Basic OCSP Response Version: 1 (0x0) - Responder Id: CN = Test CA + Responder Id: CN = Test Intermediate CA Produced At: Mar 2 00:00:00 2017 GMT Responses: Certificate ID: Hash Algorithm: sha1 - Issuer Name Hash: 02FF75DA24DE8ADD150FAB689DCCE6E6636D0901 - Issuer Key Hash: 84E1BA52A25C543CA972491224BC8B1ECA8B9FF4 - Serial Number: 03 + Issuer Name Hash: 449B1C5B31C6E9990966523E49C3F773C024190A + Issuer Key Hash: FC6D3387CC3B39B049C755C46DF4395548930BCE + Serial Number: 04 Cert Status: good This Update: Mar 1 00:00:00 2017 GMT Signature Algorithm: sha1WithRSAEncryption - 0e:82:91:8d:92:af:45:cb:98:e8:0e:08:04:15:97:9a:3a:cf: - cc:72:ee:cd:b7:3e:b0:40:b5:fd:8d:7d:6c:2f:4a:a6:32:9e: - 37:3b:7f:d3:ef:89:9e:8d:34:c2:45:1b:9b:99:4d:ed:e3:9a: - 94:62:17:59:4b:3a:be:f8:c0:a7:98:bd:e0:69:8f:98:47:e9: - 76:25:d3:1f:94:53:d7:c2:db:56:a2:aa:e3:6b:19:38:97:33: - a7:b6:45:6e:52:69:2c:62:6e:98:b6:d8:75:00:0c:16:c9:8b: - 84:41:f4:99:3e:a9:0c:a7:d4:98:51:45:89:4c:e2:c2:8e:5b: - e8:26 -Certificate: - Data: - Version: 3 (0x2) - Serial Number: 0 (0x0) - Signature Algorithm: sha1WithRSAEncryption - Issuer: CN=Test CA - Validity - Not Before: Jan 1 00:00:00 2017 GMT - Not After : Jan 1 00:00:00 2018 GMT - Subject: CN=Test CA - Subject Public Key Info: - Public Key Algorithm: rsaEncryption - Public-Key: (1024 bit) - Modulus: - 00:b8:25:2b:ee:59:9a:9d:bc:b4:48:ae:09:ce:0d: - ba:c5:83:57:03:92:fd:52:32:55:f5:e4:2e:a6:cf: - 9e:4b:c4:10:af:24:da:d5:dd:44:a8:d6:28:38:9c: - a5:11:c9:0b:70:a1:b5:71:cf:a4:35:c2:6a:17:b1: - b5:c7:cf:74:83:ac:7a:d5:3b:12:66:74:f2:4b:15: - b0:c2:59:af:0c:78:2c:42:3c:3f:8b:83:b3:1d:9a: - c8:bc:ce:b0:c8:f2:1a:a8:0a:1c:bb:6e:6e:d4:c6: - 10:66:3c:a8:ec:e3:c4:63:40:f6:79:ec:8b:14:ff: - 85:9e:2d:1a:e7:e8:31:56:81 - Exponent: 65537 (0x10001) - Signature Algorithm: sha1WithRSAEncryption - 35:fe:ee:96:31:c7:3d:91:eb:22:53:1f:bf:cc:20:cc:aa:f4: - 04:92:3c:8b:50:06:ea:a1:cc:b7:c2:4a:d6:02:af:53:a7:a4: - 71:81:78:bc:95:f3:2d:46:c4:83:4c:d5:92:11:7c:c7:67:d3: - 47:f6:06:9f:1c:46:da:d6:20:72:47:c2:57:d7:fb:66:d3:35: - 82:07:61:13:4e:4d:e6:0c:93:e6:f3:be:98:ff:e8:de:60:a7: - 06:94:cd:bb:f5:6e:b3:4e:0b:d6:e9:2b:72:bd:6e:ae:86:23: - 2d:44:33:c4:3b:a7:52:12:46:d2:76:95:06:3e:69:0f:72:60: - 16:d6 -~~~~~BEGIN CERTIFICATE~~~~~ -MIIBnDCCAQWgAwIBAgIBADANBgkqhkiG9w0BAQUFADASMRAwDgYDVQQDEwdUZXN0 -IENBMCIYDzIwMTcwMTAxMDAwMDAwWhgPMjAxODAxMDEwMDAwMDBaMBIxEDAOBgNV -BAMTB1Rlc3QgQ0EwgZ8wDQYJKoZIhvcNAQEBBQADgY0AMIGJAoGBALglK+5Zmp28 -tEiuCc4NusWDVwOS/VIyVfXkLqbPnkvEEK8k2tXdRKjWKDicpRHJC3ChtXHPpDXC -ahextcfPdIOsetU7EmZ08ksVsMJZrwx4LEI8P4uDsx2ayLzOsMjyGqgKHLtubtTG -EGY8qOzjxGNA9nnsixT/hZ4tGufoMVaBAgMBAAEwDQYJKoZIhvcNAQEFBQADgYEA -Nf7uljHHPZHrIlMfv8wgzKr0BJI8i1AG6qHMt8JK1gKvU6ekcYF4vJXzLUbEg0zV -khF8x2fTR/YGnxxG2tYgckfCV9f7ZtM1ggdhE05N5gyT5vO+mP/o3mCnBpTNu/Vu -s04L1ukrcr1uroYjLUQzxDunUhJG0naVBj5pD3JgFtY= -~~~~~END CERTIFICATE~~~~~ + 9b:7c:bb:20:00:86:92:61:6d:8f:6d:70:87:52:1b:ac:d5:0a: + 97:ce:76:7b:c4:b4:a7:a8:1d:ea:2c:15:cc:d4:2e:7d:a2:8c: + 53:4a:82:06:4a:b6:e2:d9:9b:aa:c4:63:66:94:7a:71:ba:d9: + 4e:bc:90:11:56:75:56:aa:7c:34:73:1d:ad:1c:1b:a6:28:81: + ea:f9:a0:85:e6:4f:07:2e:43:63:49:1e:8f:78:b6:96:f4:8b: + 4d:7f:58:b2:86:18:45:3a:72:5e:7f:d5:f5:f0:66:83:58:92: + 03:4d:e2:1d:af:99:2a:f4:c9:10:24:a8:c7:87:16:7f:b9:76: + b1:ba Certificate: Data: Version: 3 (0x2) @@ -78,157 +34,202 @@ Validity Not Before: Jan 1 00:00:00 2017 GMT Not After : Jan 1 00:00:00 2018 GMT + Subject: CN=Test Intermediate CA + Subject Public Key Info: + Public Key Algorithm: rsaEncryption + Public-Key: (1024 bit) + Modulus: + 00:b9:32:09:de:33:4a:4f:e2:04:73:49:d5:2e:2b: + 83:92:3a:94:e4:1b:0c:27:1b:f8:43:83:17:b8:75: + f5:a4:af:e3:4c:84:3e:6c:48:79:76:df:4d:f5:39: + af:92:4b:c5:a0:86:ab:35:cc:19:6b:93:82:c0:f8: + 44:4d:1a:14:5d:48:87:65:02:0e:b0:a8:96:d9:06: + 19:3f:aa:85:2d:84:c0:78:19:a6:96:ab:26:56:f7: + 6f:5a:1a:97:a2:01:88:00:99:10:8a:97:39:c8:22: + 6e:de:e5:56:f4:a6:23:cd:ea:48:0e:65:67:a4:73: + a0:50:91:de:ba:cf:54:08:8f + Exponent: 65537 (0x10001) + Signature Algorithm: sha1WithRSAEncryption + 48:d5:9f:8d:90:bc:4a:59:38:1d:2b:83:2d:71:1c:74:9d:01: + 73:a0:b6:98:e7:1c:c2:22:66:23:33:0a:8f:64:ff:9c:6b:37: + 09:12:1c:15:12:cb:c3:61:d9:ab:cd:96:dd:95:fa:a6:02:67: + 3c:4c:ec:98:38:5c:fc:48:cc:85:a9:5b:49:2c:2b:06:66:07: + 9e:31:0f:93:10:ab:3e:9f:97:60:64:01:61:7e:86:15:bb:5e: + f1:90:31:a3:54:d0:86:0e:80:05:87:09:2e:65:b6:95:89:5c: + c1:e5:80:d9:b8:81:b6:ed:1a:20:b8:9b:22:ce:ef:d0:26:47: + 9d:57 +~~~~~BEGIN CERTIFICATE~~~~~ +MIIBqTCCARKgAwIBAgIBATANBgkqhkiG9w0BAQUFADASMRAwDgYDVQQDDAdUZXN0 +IENBMCIYDzIwMTcwMTAxMDAwMDAwWhgPMjAxODAxMDEwMDAwMDBaMB8xHTAbBgNV +BAMMFFRlc3QgSW50ZXJtZWRpYXRlIENBMIGfMA0GCSqGSIb3DQEBAQUAA4GNADCB +iQKBgQC5MgneM0pP4gRzSdUuK4OSOpTkGwwnG/hDgxe4dfWkr+NMhD5sSHl23031 +Oa+SS8Wghqs1zBlrk4LA+ERNGhRdSIdlAg6wqJbZBhk/qoUthMB4GaaWqyZW929a +GpeiAYgAmRCKlznIIm7e5Vb0piPN6kgOZWekc6BQkd66z1QIjwIDAQABMA0GCSqG +SIb3DQEBBQUAA4GBAEjVn42QvEpZOB0rgy1xHHSdAXOgtpjnHMIiZiMzCo9k/5xr +NwkSHBUSy8Nh2avNlt2V+qYCZzxM7Jg4XPxIzIWpW0ksKwZmB54xD5MQqz6fl2Bk +AWF+hhW7XvGQMaNU0IYOgAWHCS5ltpWJXMHlgNm4gbbtGiC4myLO79AmR51X +~~~~~END CERTIFICATE~~~~~ +Certificate: + Data: + Version: 3 (0x2) + Serial Number: 2 (0x2) + Signature Algorithm: sha1WithRSAEncryption + Issuer: CN=Test Intermediate CA + Validity + Not Before: Jan 1 00:00:00 2017 GMT + Not After : Jan 1 00:00:00 2018 GMT Subject: CN=Test OCSP Signer Subject Public Key Info: Public Key Algorithm: rsaEncryption Public-Key: (1024 bit) Modulus: - 00:e3:da:d4:26:f5:7c:81:83:52:76:02:1c:d1:fc: - fa:7f:ee:68:17:80:17:ed:83:49:4d:e5:b1:dd:7d: - 5d:2e:16:78:28:77:74:77:ee:53:cc:af:6c:f7:3b: - f7:9d:f0:4e:a7:2a:ec:43:d6:aa:d4:47:a4:ab:ab: - 92:53:ce:46:6d:ff:e9:f9:b3:a7:ee:b0:68:c5:de: - 5c:64:e3:ad:94:d0:92:44:81:2a:56:c7:af:d7:9c: - 90:fe:48:35:4e:e9:66:38:dc:38:b3:00:fe:42:0b: - b5:ce:d9:cf:d4:85:cd:13:3d:4a:b4:1f:4b:65:c3: - 14:08:ae:71:f4:84:9f:a3:e5 + 00:c4:e7:57:6f:76:06:30:1c:60:f3:d9:e2:0f:20: + 22:96:c4:2f:2e:3c:d6:96:3d:bf:08:09:b2:1a:ac: + 6b:a5:f6:89:a8:67:d1:f1:2c:31:69:ec:5c:56:b1: + b0:8a:62:8b:b8:fe:c4:01:26:b2:ce:3b:ec:e3:0b: + f2:08:96:84:3d:b9:87:57:40:82:4d:32:42:44:dc: + e3:47:e5:1e:ad:52:a7:9b:6f:cd:d0:d3:34:8f:18: + 59:01:0e:17:a3:4c:a0:20:c9:ff:bd:b4:93:6b:aa: + bd:b4:a5:c7:e8:7c:35:bd:5a:2a:f6:2d:d7:fe:29: + 86:79:75:a6:15:1b:99:24:cf Exponent: 65537 (0x10001) X509v3 extensions: X509v3 Extended Key Usage: OCSP Signing Signature Algorithm: sha1WithRSAEncryption - 55:64:b9:72:42:b4:aa:14:76:fd:81:bf:76:ce:26:0e:6c:dd: - aa:1f:77:d8:13:48:76:93:52:00:46:4b:9c:50:1b:b3:cd:87: - e9:f5:53:58:20:a6:b3:37:17:45:fd:46:93:34:b2:33:b5:84: - ac:97:28:46:03:d5:78:e0:06:e3:99:0e:fa:0c:b3:4b:ce:40: - 0a:94:34:94:9a:27:52:7a:3e:f3:61:42:1c:95:52:3b:10:6e: - 86:d5:80:cb:11:67:24:de:e7:62:87:b9:76:4f:88:69:4d:23: - 94:34:94:1c:00:aa:30:25:51:a3:10:5c:07:81:2d:74:86:f3: - e7:68 + 6a:17:94:55:d2:fd:d9:c3:d5:8e:78:cd:23:71:47:4d:bf:e4: + af:87:f8:b6:d7:43:4b:ee:76:61:5a:bf:ed:ff:3e:bc:06:fc: + d9:ed:3f:f9:4e:ea:90:fd:40:b9:2e:ee:25:a8:1f:c8:92:60: + 78:87:ad:45:c8:1a:0d:3d:d6:cc:fa:f6:79:fb:ec:a6:b9:17: + d1:ae:a2:76:f9:59:9d:df:f4:62:05:23:3a:ed:b9:66:57:db: + 04:95:d6:2e:73:98:77:c1:09:8f:97:95:3a:ec:71:33:54:70: + d8:d9:6a:00:5c:89:14:6c:39:c0:dd:5e:68:54:c0:c5:43:98: + 68:fc ~~~~~BEGIN CERTIFICATE~~~~~ -MIIBvjCCASegAwIBAgIBATANBgkqhkiG9w0BAQUFADASMRAwDgYDVQQDEwdUZXN0 -IENBMCIYDzIwMTcwMTAxMDAwMDAwWhgPMjAxODAxMDEwMDAwMDBaMBsxGTAXBgNV -BAMTEFRlc3QgT0NTUCBTaWduZXIwgZ8wDQYJKoZIhvcNAQEBBQADgY0AMIGJAoGB -AOPa1Cb1fIGDUnYCHNH8+n/uaBeAF+2DSU3lsd19XS4WeCh3dHfuU8yvbPc7953w -Tqcq7EPWqtRHpKurklPORm3/6fmzp+6waMXeXGTjrZTQkkSBKlbHr9eckP5INU7p -ZjjcOLMA/kILtc7Zz9SFzRM9SrQfS2XDFAiucfSEn6PlAgMBAAGjFzAVMBMGA1Ud -JQQMMAoGCCsGAQUFBwMJMA0GCSqGSIb3DQEBBQUAA4GBAFVkuXJCtKoUdv2Bv3bO -Jg5s3aofd9gTSHaTUgBGS5xQG7PNh+n1U1ggprM3F0X9RpM0sjO1hKyXKEYD1Xjg -BuOZDvoMs0vOQAqUNJSaJ1J6PvNhQhyVUjsQbobVgMsRZyTe52KHuXZPiGlNI5Q0 -lBwAqjAlUaMQXAeBLXSG8+do +MIIByzCCATSgAwIBAgIBAjANBgkqhkiG9w0BAQUFADAfMR0wGwYDVQQDDBRUZXN0 +IEludGVybWVkaWF0ZSBDQTAiGA8yMDE3MDEwMTAwMDAwMFoYDzIwMTgwMTAxMDAw +MDAwWjAbMRkwFwYDVQQDDBBUZXN0IE9DU1AgU2lnbmVyMIGfMA0GCSqGSIb3DQEB +AQUAA4GNADCBiQKBgQDE51dvdgYwHGDz2eIPICKWxC8uPNaWPb8ICbIarGul9omo +Z9HxLDFp7FxWsbCKYou4/sQBJrLOO+zjC/IIloQ9uYdXQIJNMkJE3ONH5R6tUqeb +b83Q0zSPGFkBDhejTKAgyf+9tJNrqr20pcfofDW9Wir2Ldf+KYZ5daYVG5kkzwID +AQABoxcwFTATBgNVHSUEDDAKBggrBgEFBQcDCTANBgkqhkiG9w0BAQUFAAOBgQBq +F5RV0v3Zw9WOeM0jcUdNv+Svh/i210NL7nZhWr/t/z68BvzZ7T/5TuqQ/UC5Lu4l +qB/IkmB4h61FyBoNPdbM+vZ5++ymuRfRrqJ2+Vmd3/RiBSM67blmV9sEldYuc5h3 +wQmPl5U67HEzVHDY2WoAXIkUbDnA3V5oVMDFQ5ho/A== ~~~~~END CERTIFICATE~~~~~ -----BEGIN OCSP RESPONSE----- -MIIElQoBAKCCBI4wggSKBgkrBgEFBQcwAQEEggR7MIIEdzB4oRQwEjEQMA4GA1UEAxMHVGVzdCB -DQRgPMjAxNzAzMDIwMDAwMDBaME8wTTA4MAcGBSsOAwIaBBQC/3XaJN6K3RUPq2idzObmY20JAQ -QUhOG6UqJcVDypckkSJLyLHsqLn/QCAQOAABgPMjAxNzAzMDEwMDAwMDBaMA0GCSqGSIb3DQEBB -QUAA4GBAA6CkY2Sr0XLmOgOCAQVl5o6z8xy7s23PrBAtf2NfWwvSqYynjc7f9PviZ6NNMJFG5uZ -Te3jmpRiF1lLOr74wKeYveBpj5hH6XYl0x+UU9fC21aiquNrGTiXM6e2RW5SaSxibpi22HUADBb -Ji4RB9Jk+qQyn1JhRRYlM4sKOW+gmoIIDZjCCA2IwggGcMIIBBaADAgECAgEAMA0GCSqGSIb3DQ -EBBQUAMBIxEDAOBgNVBAMTB1Rlc3QgQ0EwIhgPMjAxNzAxMDEwMDAwMDBaGA8yMDE4MDEwMTAwM -DAwMFowEjEQMA4GA1UEAxMHVGVzdCBDQTCBnzANBgkqhkiG9w0BAQEFAAOBjQAwgYkCgYEAuCUr -7lmanby0SK4Jzg26xYNXA5L9UjJV9eQups+eS8QQryTa1d1EqNYoOJylEckLcKG1cc+kNcJqF7G -1x890g6x61TsSZnTySxWwwlmvDHgsQjw/i4OzHZrIvM6wyPIaqAocu25u1MYQZjyo7OPEY0D2ee -yLFP+Fni0a5+gxVoECAwEAATANBgkqhkiG9w0BAQUFAAOBgQA1/u6WMcc9kesiUx+/zCDMqvQEk -jyLUAbqocy3wkrWAq9Tp6RxgXi8lfMtRsSDTNWSEXzHZ9NH9gafHEba1iByR8JX1/tm0zWCB2ET -Tk3mDJPm876Y/+jeYKcGlM279W6zTgvW6StyvW6uhiMtRDPEO6dSEkbSdpUGPmkPcmAW1jCCAb4 -wggEnoAMCAQICAQEwDQYJKoZIhvcNAQEFBQAwEjEQMA4GA1UEAxMHVGVzdCBDQTAiGA8yMDE3MD -EwMTAwMDAwMFoYDzIwMTgwMTAxMDAwMDAwWjAbMRkwFwYDVQQDExBUZXN0IE9DU1AgU2lnbmVyM -IGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDj2tQm9XyBg1J2AhzR/Pp/7mgXgBftg0lN5bHd -fV0uFngod3R37lPMr2z3O/ed8E6nKuxD1qrUR6Srq5JTzkZt/+n5s6fusGjF3lxk462U0JJEgSp -Wx6/XnJD+SDVO6WY43DizAP5CC7XO2c/Uhc0TPUq0H0tlwxQIrnH0hJ+j5QIDAQABoxcwFTATBg -NVHSUEDDAKBggrBgEFBQcDCTANBgkqhkiG9w0BAQUFAAOBgQBVZLlyQrSqFHb9gb92ziYObN2qH -3fYE0h2k1IARkucUBuzzYfp9VNYIKazNxdF/UaTNLIztYSslyhGA9V44AbjmQ76DLNLzkAKlDSU -midSej7zYUIclVI7EG6G1YDLEWck3udih7l2T4hpTSOUNJQcAKowJVGjEFwHgS10hvPnaA== +MIIEvQoBAKCCBLYwggSyBgkrBgEFBQcwAQEEggSjMIIEnzCBhaEhMB8xHTAbBgNVBAMMFFRlc3Q +gSW50ZXJtZWRpYXRlIENBGA8yMDE3MDMwMjAwMDAwMFowTzBNMDgwBwYFKw4DAhoEFESbHFsxxu +mZCWZSPknD93PAJBkKBBT8bTOHzDs5sEnHVcRt9DlVSJMLzgIBBIAAGA8yMDE3MDMwMTAwMDAwM +FowDQYJKoZIhvcNAQEFBQADgYEAm3y7IACGkmFtj21wh1IbrNUKl852e8S0p6gd6iwVzNQufaKM +U0qCBkq24tmbqsRjZpR6cbrZTryQEVZ1Vqp8NHMdrRwbpiiB6vmgheZPBy5DY0kej3i2lvSLTX9 +YsoYYRTpyXn/V9fBmg1iSA03iHa+ZKvTJECSox4cWf7l2sbqgggOAMIIDfDCCAakwggESoAMCAQ +ICAQEwDQYJKoZIhvcNAQEFBQAwEjEQMA4GA1UEAwwHVGVzdCBDQTAiGA8yMDE3MDEwMTAwMDAwM +FoYDzIwMTgwMTAxMDAwMDAwWjAfMR0wGwYDVQQDDBRUZXN0IEludGVybWVkaWF0ZSBDQTCBnzAN +BgkqhkiG9w0BAQEFAAOBjQAwgYkCgYEAuTIJ3jNKT+IEc0nVLiuDkjqU5BsMJxv4Q4MXuHX1pK/ +jTIQ+bEh5dt9N9TmvkkvFoIarNcwZa5OCwPhETRoUXUiHZQIOsKiW2QYZP6qFLYTAeBmmlqsmVv +dvWhqXogGIAJkQipc5yCJu3uVW9KYjzepIDmVnpHOgUJHeus9UCI8CAwEAATANBgkqhkiG9w0BA +QUFAAOBgQBI1Z+NkLxKWTgdK4MtcRx0nQFzoLaY5xzCImYjMwqPZP+cazcJEhwVEsvDYdmrzZbd +lfqmAmc8TOyYOFz8SMyFqVtJLCsGZgeeMQ+TEKs+n5dgZAFhfoYVu17xkDGjVNCGDoAFhwkuZba +ViVzB5YDZuIG27RoguJsizu/QJkedVzCCAcswggE0oAMCAQICAQIwDQYJKoZIhvcNAQEFBQAwHz +EdMBsGA1UEAwwUVGVzdCBJbnRlcm1lZGlhdGUgQ0EwIhgPMjAxNzAxMDEwMDAwMDBaGA8yMDE4M +DEwMTAwMDAwMFowGzEZMBcGA1UEAwwQVGVzdCBPQ1NQIFNpZ25lcjCBnzANBgkqhkiG9w0BAQEF +AAOBjQAwgYkCgYEAxOdXb3YGMBxg89niDyAilsQvLjzWlj2/CAmyGqxrpfaJqGfR8SwxaexcVrG +wimKLuP7EASayzjvs4wvyCJaEPbmHV0CCTTJCRNzjR+UerVKnm2/N0NM0jxhZAQ4Xo0ygIMn/vb +STa6q9tKXH6Hw1vVoq9i3X/imGeXWmFRuZJM8CAwEAAaMXMBUwEwYDVR0lBAwwCgYIKwYBBQUHA +wkwDQYJKoZIhvcNAQEFBQADgYEAaheUVdL92cPVjnjNI3FHTb/kr4f4ttdDS+52YVq/7f8+vAb8 +2e0/+U7qkP1AuS7uJagfyJJgeIetRcgaDT3WzPr2efvsprkX0a6idvlZnd/0YgUjOu25ZlfbBJX +WLnOYd8EJj5eVOuxxM1Rw2NlqAFyJFGw5wN1eaFTAxUOYaPw= -----END OCSP RESPONSE----- $ openssl x509 -text < [CA CERTIFICATE] Certificate: Data: Version: 3 (0x2) - Serial Number: 0 (0x0) + Serial Number: 1 (0x1) Signature Algorithm: sha1WithRSAEncryption - Issuer: CN=Test CA + Issuer: CN = Test CA Validity Not Before: Jan 1 00:00:00 2017 GMT Not After : Jan 1 00:00:00 2018 GMT - Subject: CN=Test CA + Subject: CN = Test Intermediate CA Subject Public Key Info: Public Key Algorithm: rsaEncryption Public-Key: (1024 bit) Modulus: - 00:b8:25:2b:ee:59:9a:9d:bc:b4:48:ae:09:ce:0d: - ba:c5:83:57:03:92:fd:52:32:55:f5:e4:2e:a6:cf: - 9e:4b:c4:10:af:24:da:d5:dd:44:a8:d6:28:38:9c: - a5:11:c9:0b:70:a1:b5:71:cf:a4:35:c2:6a:17:b1: - b5:c7:cf:74:83:ac:7a:d5:3b:12:66:74:f2:4b:15: - b0:c2:59:af:0c:78:2c:42:3c:3f:8b:83:b3:1d:9a: - c8:bc:ce:b0:c8:f2:1a:a8:0a:1c:bb:6e:6e:d4:c6: - 10:66:3c:a8:ec:e3:c4:63:40:f6:79:ec:8b:14:ff: - 85:9e:2d:1a:e7:e8:31:56:81 + 00:b9:32:09:de:33:4a:4f:e2:04:73:49:d5:2e:2b: + 83:92:3a:94:e4:1b:0c:27:1b:f8:43:83:17:b8:75: + f5:a4:af:e3:4c:84:3e:6c:48:79:76:df:4d:f5:39: + af:92:4b:c5:a0:86:ab:35:cc:19:6b:93:82:c0:f8: + 44:4d:1a:14:5d:48:87:65:02:0e:b0:a8:96:d9:06: + 19:3f:aa:85:2d:84:c0:78:19:a6:96:ab:26:56:f7: + 6f:5a:1a:97:a2:01:88:00:99:10:8a:97:39:c8:22: + 6e:de:e5:56:f4:a6:23:cd:ea:48:0e:65:67:a4:73: + a0:50:91:de:ba:cf:54:08:8f Exponent: 65537 (0x10001) Signature Algorithm: sha1WithRSAEncryption - 35:fe:ee:96:31:c7:3d:91:eb:22:53:1f:bf:cc:20:cc:aa:f4: - 04:92:3c:8b:50:06:ea:a1:cc:b7:c2:4a:d6:02:af:53:a7:a4: - 71:81:78:bc:95:f3:2d:46:c4:83:4c:d5:92:11:7c:c7:67:d3: - 47:f6:06:9f:1c:46:da:d6:20:72:47:c2:57:d7:fb:66:d3:35: - 82:07:61:13:4e:4d:e6:0c:93:e6:f3:be:98:ff:e8:de:60:a7: - 06:94:cd:bb:f5:6e:b3:4e:0b:d6:e9:2b:72:bd:6e:ae:86:23: - 2d:44:33:c4:3b:a7:52:12:46:d2:76:95:06:3e:69:0f:72:60: - 16:d6 + 48:d5:9f:8d:90:bc:4a:59:38:1d:2b:83:2d:71:1c:74:9d:01: + 73:a0:b6:98:e7:1c:c2:22:66:23:33:0a:8f:64:ff:9c:6b:37: + 09:12:1c:15:12:cb:c3:61:d9:ab:cd:96:dd:95:fa:a6:02:67: + 3c:4c:ec:98:38:5c:fc:48:cc:85:a9:5b:49:2c:2b:06:66:07: + 9e:31:0f:93:10:ab:3e:9f:97:60:64:01:61:7e:86:15:bb:5e: + f1:90:31:a3:54:d0:86:0e:80:05:87:09:2e:65:b6:95:89:5c: + c1:e5:80:d9:b8:81:b6:ed:1a:20:b8:9b:22:ce:ef:d0:26:47: + 9d:57 -----BEGIN CA CERTIFICATE----- -MIIBnDCCAQWgAwIBAgIBADANBgkqhkiG9w0BAQUFADASMRAwDgYDVQQDEwdUZXN0IENBMCIYDzI -wMTcwMTAxMDAwMDAwWhgPMjAxODAxMDEwMDAwMDBaMBIxEDAOBgNVBAMTB1Rlc3QgQ0EwgZ8wDQ -YJKoZIhvcNAQEBBQADgY0AMIGJAoGBALglK+5Zmp28tEiuCc4NusWDVwOS/VIyVfXkLqbPnkvEE -K8k2tXdRKjWKDicpRHJC3ChtXHPpDXCahextcfPdIOsetU7EmZ08ksVsMJZrwx4LEI8P4uDsx2a -yLzOsMjyGqgKHLtubtTGEGY8qOzjxGNA9nnsixT/hZ4tGufoMVaBAgMBAAEwDQYJKoZIhvcNAQE -FBQADgYEANf7uljHHPZHrIlMfv8wgzKr0BJI8i1AG6qHMt8JK1gKvU6ekcYF4vJXzLUbEg0zVkh -F8x2fTR/YGnxxG2tYgckfCV9f7ZtM1ggdhE05N5gyT5vO+mP/o3mCnBpTNu/Vus04L1ukrcr1ur -oYjLUQzxDunUhJG0naVBj5pD3JgFtY= +MIIBqTCCARKgAwIBAgIBATANBgkqhkiG9w0BAQUFADASMRAwDgYDVQQDDAdUZXN0IENBMCIYDzI +wMTcwMTAxMDAwMDAwWhgPMjAxODAxMDEwMDAwMDBaMB8xHTAbBgNVBAMMFFRlc3QgSW50ZXJtZW +RpYXRlIENBMIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQC5MgneM0pP4gRzSdUuK4OSOpTkG +wwnG/hDgxe4dfWkr+NMhD5sSHl23031Oa+SS8Wghqs1zBlrk4LA+ERNGhRdSIdlAg6wqJbZBhk/ +qoUthMB4GaaWqyZW929aGpeiAYgAmRCKlznIIm7e5Vb0piPN6kgOZWekc6BQkd66z1QIjwIDAQA +BMA0GCSqGSIb3DQEBBQUAA4GBAEjVn42QvEpZOB0rgy1xHHSdAXOgtpjnHMIiZiMzCo9k/5xrNw +kSHBUSy8Nh2avNlt2V+qYCZzxM7Jg4XPxIzIWpW0ksKwZmB54xD5MQqz6fl2BkAWF+hhW7XvGQM +aNU0IYOgAWHCS5ltpWJXMHlgNm4gbbtGiC4myLO79AmR51X -----END CA CERTIFICATE----- $ openssl x509 -text < [CERTIFICATE] Certificate: Data: Version: 3 (0x2) - Serial Number: 3 (0x3) + Serial Number: 4 (0x4) Signature Algorithm: sha1WithRSAEncryption - Issuer: CN=Test CA + Issuer: CN = Test Intermediate CA Validity Not Before: Jan 1 00:00:00 2017 GMT Not After : Jan 1 00:00:00 2018 GMT - Subject: CN=Test Cert + Subject: CN = Test Cert Subject Public Key Info: Public Key Algorithm: rsaEncryption Public-Key: (1024 bit) Modulus: - 00:d5:12:3f:22:6f:b0:e1:43:c5:93:b3:c3:5b:70: - 52:b2:8b:10:ec:11:c4:c4:aa:aa:43:92:c8:d0:f3: - 35:23:e3:76:2d:b4:ea:93:26:6f:6a:79:1c:64:51: - d3:4d:21:4a:73:83:35:dc:a0:16:74:db:f0:b9:a5: - 46:35:8d:53:e8:7d:37:5b:4d:ad:a3:df:d6:ae:01: - 38:ad:16:09:6e:fd:65:ad:1c:4b:48:12:1e:48:a7: - ff:5b:47:c4:c9:3b:74:85:63:1a:0a:06:b2:9f:b9: - cb:ad:dc:3f:24:8b:a4:a7:8a:13:15:45:89:24:c1: - a7:3b:c2:a2:c8:74:f1:3f:6f + 00:bc:4c:d5:b3:8d:92:fa:66:ac:32:43:1a:9e:eb: + 17:e0:aa:76:35:1b:1d:10:48:4e:3e:22:8b:75:2e: + e8:6f:a4:55:1e:0a:5e:60:c0:61:f1:7d:29:58:7e: + 0b:ef:29:be:ad:f8:f7:43:c8:58:95:14:5b:1d:af: + 4a:b8:90:9e:4e:ec:4e:b3:86:7a:b9:96:c1:34:d3: + b9:a6:57:df:9b:bd:d9:dd:67:15:54:d4:9f:65:b8: + 33:29:59:ba:9a:c6:75:ea:a5:76:3d:a4:57:0f:e2: + e4:c3:91:35:1d:6e:ff:61:7d:c2:53:23:66:b2:a8: + 0b:e1:c7:55:48:c5:2b:4d:7d Exponent: 65537 (0x10001) Signature Algorithm: sha1WithRSAEncryption - 04:21:70:de:14:92:27:13:e8:d2:b0:51:f0:af:34:75:0b:a7: - ff:84:cb:c6:96:30:80:01:f5:c1:3a:c6:81:ee:ba:89:60:33: - c3:e5:0f:43:cc:ac:81:8d:09:fb:25:e1:67:40:64:a3:ca:fd: - bd:9c:c4:73:e4:bc:4d:8e:e2:70:f1:17:ce:b4:ab:a0:b2:63: - 72:25:27:ae:d5:8e:18:73:0d:dc:12:5a:32:1c:b7:da:cd:23: - 5b:c8:87:58:08:3e:95:0c:fd:c8:48:a2:75:6e:79:f2:00:82: - 6e:b5:cc:71:e3:79:ca:68:85:9b:1b:5c:52:bf:a2:5a:71:e3: - 05:b5 + 18:bb:93:d9:2a:e0:34:69:2f:96:57:ac:55:ac:a7:83:04:b4: + bc:22:7f:5f:f7:c0:dc:ac:af:13:9b:86:7e:ac:02:8c:44:83: + 2e:c0:fa:a1:77:1d:dd:86:31:7e:98:93:c0:4f:b2:3d:be:30: + 6f:a5:fc:c7:2e:b1:b8:08:d2:17:cb:60:55:bf:5a:e0:94:f3: + 1d:44:fa:b1:2f:1a:24:c5:33:e1:d4:f0:ac:d5:2c:67:da:a7: + 5d:ee:eb:d6:7a:a7:41:e8:94:7a:34:43:b2:1f:ab:e9:cf:5d: + 25:49:56:18:d2:a9:49:1a:37:34:43:c7:06:96:4a:29:38:cc: + f2:1c -----BEGIN CERTIFICATE----- -MIIBnjCCAQegAwIBAgIBAzANBgkqhkiG9w0BAQUFADASMRAwDgYDVQQDEwdUZXN0IENBMCIYDzI -wMTcwMTAxMDAwMDAwWhgPMjAxODAxMDEwMDAwMDBaMBQxEjAQBgNVBAMTCVRlc3QgQ2VydDCBnz -ANBgkqhkiG9w0BAQEFAAOBjQAwgYkCgYEA1RI/Im+w4UPFk7PDW3BSsosQ7BHExKqqQ5LI0PM1I -+N2LbTqkyZvankcZFHTTSFKc4M13KAWdNvwuaVGNY1T6H03W02to9/WrgE4rRYJbv1lrRxLSBIe -SKf/W0fEyTt0hWMaCgayn7nLrdw/JIukp4oTFUWJJMGnO8KiyHTxP28CAwEAATANBgkqhkiG9w0 -BAQUFAAOBgQAEIXDeFJInE+jSsFHwrzR1C6f/hMvGljCAAfXBOsaB7rqJYDPD5Q9DzKyBjQn7Je -FnQGSjyv29nMRz5LxNjuJw8RfOtKugsmNyJSeu1Y4Ycw3cEloyHLfazSNbyIdYCD6VDP3ISKJ1b -nnyAIJutcxx43nKaIWbG1xSv6JaceMFtQ== +MIIBqzCCARSgAwIBAgIBBDANBgkqhkiG9w0BAQUFADAfMR0wGwYDVQQDDBRUZXN0IEludGVybWV +kaWF0ZSBDQTAiGA8yMDE3MDEwMTAwMDAwMFoYDzIwMTgwMTAxMDAwMDAwWjAUMRIwEAYDVQQDDA +lUZXN0IENlcnQwgZ8wDQYJKoZIhvcNAQEBBQADgY0AMIGJAoGBALxM1bONkvpmrDJDGp7rF+Cqd +jUbHRBITj4ii3Uu6G+kVR4KXmDAYfF9KVh+C+8pvq3490PIWJUUWx2vSriQnk7sTrOGermWwTTT +uaZX35u92d1nFVTUn2W4MylZuprGdeqldj2kVw/i5MORNR1u/2F9wlMjZrKoC+HHVUjFK019AgM +BAAEwDQYJKoZIhvcNAQEFBQADgYEAGLuT2SrgNGkvllesVayngwS0vCJ/X/fA3KyvE5uGfqwCjE +SDLsD6oXcd3YYxfpiTwE+yPb4wb6X8xy6xuAjSF8tgVb9a4JTzHUT6sS8aJMUz4dTwrNUsZ9qnX +e7r1nqnQeiUejRDsh+r6c9dJUlWGNKpSRo3NEPHBpZKKTjM8hw= -----END CERTIFICATE----- $ openssl asn1parse -i < [OCSP REQUEST] @@ -240,10 +241,10 @@ 10:d=5 hl=2 l= 9 cons: SEQUENCE 12:d=6 hl=2 l= 5 prim: OBJECT :sha1 19:d=6 hl=2 l= 0 prim: NULL - 21:d=5 hl=2 l= 20 prim: OCTET STRING [HEX DUMP]:02FF75DA24DE8ADD150FAB689DCCE6E6636D0901 - 43:d=5 hl=2 l= 20 prim: OCTET STRING [HEX DUMP]:84E1BA52A25C543CA972491224BC8B1ECA8B9FF4 - 65:d=5 hl=2 l= 1 prim: INTEGER :03 + 21:d=5 hl=2 l= 20 prim: OCTET STRING [HEX DUMP]:449B1C5B31C6E9990966523E49C3F773C024190A + 43:d=5 hl=2 l= 20 prim: OCTET STRING [HEX DUMP]:FC6D3387CC3B39B049C755C46DF4395548930BCE + 65:d=5 hl=2 l= 1 prim: INTEGER :04 -----BEGIN OCSP REQUEST----- -MEIwQDA+MDwwOjAJBgUrDgMCGgUABBQC/3XaJN6K3RUPq2idzObmY20JAQQUhOG6UqJcVDypckk -SJLyLHsqLn/QCAQM= +MEIwQDA+MDwwOjAJBgUrDgMCGgUABBREmxxbMcbpmQlmUj5Jw/dzwCQZCgQU/G0zh8w7ObBJx1X +EbfQ5VUiTC84CAQQ= -----END OCSP REQUEST-----
diff --git a/net/data/ocsp_unittest/ocsp_sign_bad_indirect.pem b/net/data/ocsp_unittest/ocsp_sign_bad_indirect.pem index 639f03d..668fa76 100644 --- a/net/data/ocsp_unittest/ocsp_sign_bad_indirect.pem +++ b/net/data/ocsp_unittest/ocsp_sign_bad_indirect.pem
@@ -10,27 +10,27 @@ Responses: Certificate ID: Hash Algorithm: sha1 - Issuer Name Hash: 02FF75DA24DE8ADD150FAB689DCCE6E6636D0901 - Issuer Key Hash: 84E1BA52A25C543CA972491224BC8B1ECA8B9FF4 - Serial Number: 03 + Issuer Name Hash: 449B1C5B31C6E9990966523E49C3F773C024190A + Issuer Key Hash: FC6D3387CC3B39B049C755C46DF4395548930BCE + Serial Number: 04 Cert Status: good This Update: Mar 1 00:00:00 2017 GMT Signature Algorithm: sha1WithRSAEncryption - 1f:a6:2c:01:7f:5e:12:ae:0f:6c:96:5b:ce:0c:05:d1:a4:90: - fa:11:0f:75:2b:7b:6a:b3:e5:3c:c3:03:bc:b9:0e:34:b2:ae: - 76:04:73:f6:de:83:14:4e:1d:7e:3b:1b:b2:0c:d3:5c:be:fb: - 1e:b1:f6:78:17:a3:c6:b0:a6:44:20:ae:30:6a:0c:d9:d4:ee: - 8c:db:c6:aa:10:8f:f2:6a:6e:a4:11:0d:1e:3f:cb:4a:6e:bd: - fa:a8:07:42:b3:2f:e6:e1:38:15:a6:bb:fb:ec:dc:f9:79:07: - 77:bf:fa:82:f3:99:0c:4e:64:0c:cb:9f:d6:b8:b6:3d:af:df: - 17:82 + 77:44:df:f9:65:b0:0b:16:16:87:90:26:3e:e0:1b:ab:b7:c8: + b0:97:b0:81:e1:7d:df:5d:17:5c:49:a7:bf:ec:fd:a3:12:cb: + ee:35:4d:e2:29:35:06:9d:9c:52:32:aa:6a:7a:39:5a:e8:7d: + dd:1c:33:04:78:fb:50:62:b5:d1:1b:4c:75:32:7d:3f:8d:17: + 2f:8b:b2:81:db:7a:0e:28:8a:b7:5d:4d:9f:96:8d:e4:f8:2e: + bc:d8:96:bb:73:1a:6b:fa:57:59:5a:2f:c5:2c:5e:4c:4e:82: + 18:fe:a1:68:fd:99:d9:06:fa:0a:f7:e1:e3:ed:e3:95:c7:04: + 97:68 Certificate: Data: Version: 3 (0x2) - Serial Number: 2 (0x2) + Serial Number: 3 (0x3) Signature Algorithm: sha1WithRSAEncryption - Issuer: CN=Test CA + Issuer: CN=Test Intermediate CA Validity Not Before: Jan 1 00:00:00 2017 GMT Not After : Jan 1 00:00:00 2018 GMT @@ -39,141 +39,142 @@ Public Key Algorithm: rsaEncryption Public-Key: (1024 bit) Modulus: - 00:cb:12:ed:16:13:02:3b:00:37:02:d6:31:a1:01: - 3e:3d:7b:f6:f1:39:49:17:28:04:40:c6:98:fc:73: - ae:c1:35:79:a2:d8:3a:f9:7a:2c:51:17:17:89:a2: - ee:77:7a:23:95:7e:53:a3:95:c2:7a:1b:fc:36:78: - 69:87:ab:fe:da:07:bb:4e:d1:4a:c3:e1:5f:74:0c: - 0d:6e:0e:4a:22:1c:31:65:c6:50:a1:39:d6:58:5e: - cc:d9:f2:cc:26:98:1e:f0:1a:f6:ee:8c:a5:e0:00: - 5a:c9:0a:f5:17:b2:eb:cb:2f:4e:13:38:1a:a4:94: - 26:9a:95:ec:e7:d7:eb:a2:43 + 00:bf:28:fa:03:ec:a6:42:94:4d:f0:86:5e:7d:bf: + 1a:a0:c5:99:4a:4a:43:44:6a:42:d5:bb:ec:b5:1f: + 12:44:b1:7a:8a:07:b8:c2:7f:17:27:12:68:6c:48: + 8e:6d:2a:e6:17:96:64:71:d4:bf:81:c7:9b:d4:8b: + 5f:b6:31:d4:53:50:e6:b2:66:f3:37:38:5a:8c:dd: + 79:12:36:c6:c0:c2:85:ab:75:77:5d:97:84:e3:3e: + 6c:5a:ad:3c:bf:07:95:f2:0c:e4:e7:f4:2c:95:8e: + bd:1c:00:9f:a0:5b:c3:b0:c0:98:d3:5b:38:31:a2: + bd:f7:1a:a7:d8:b9:55:62:b1 Exponent: 65537 (0x10001) Signature Algorithm: sha1WithRSAEncryption - 9a:e4:4b:9d:2f:38:60:c6:c3:e1:dc:c3:8f:24:48:4b:4f:cc: - 18:f5:85:43:1d:f0:36:21:39:29:84:a1:5d:f9:df:69:5b:a7: - 62:35:56:5d:e0:2c:bb:74:2e:6f:19:7b:32:6a:aa:9a:5f:ab: - ee:ff:2e:8c:45:e6:3a:09:58:c5:05:0e:89:49:b6:e9:14:0d: - c8:e2:0d:bd:74:32:97:7c:e4:f2:0f:10:d4:88:0b:23:69:44: - 91:2d:e3:e6:28:3e:ee:05:14:59:6e:49:c9:ea:76:f7:c1:61: - dc:13:98:9c:65:6d:94:28:a2:98:24:b6:6d:8e:b4:d2:45:57: - bd:bf + 77:de:f7:c8:6d:ca:5e:ef:6f:e8:7a:94:aa:a6:05:f4:c1:a8: + 4d:8a:8b:f0:c8:fc:6f:0f:c4:55:5b:13:d5:90:31:fb:99:fa: + f0:30:81:b4:33:a3:f0:fb:49:8c:bb:a4:64:85:1a:83:48:ca: + 78:a9:74:23:b7:60:d2:b4:67:db:10:db:12:a2:d5:1c:9b:17: + 7f:3b:69:da:2c:df:8c:4e:aa:a6:19:41:b8:8f:58:af:59:7f: + 84:87:d1:08:fb:bb:40:88:db:ea:06:da:94:22:51:64:a7:69: + 0b:4b:2a:53:2c:86:d7:72:e7:1f:21:73:e6:b4:2d:25:46:f1: + 55:e2 ~~~~~BEGIN CERTIFICATE~~~~~ -MIIBqzCCARSgAwIBAgIBAjANBgkqhkiG9w0BAQUFADASMRAwDgYDVQQDEwdUZXN0 -IENBMCIYDzIwMTcwMTAxMDAwMDAwWhgPMjAxODAxMDEwMDAwMDBaMCExHzAdBgNV -BAMTFlRlc3QgRmFsc2UgT0NTUCBTaWduZXIwgZ8wDQYJKoZIhvcNAQEBBQADgY0A -MIGJAoGBAMsS7RYTAjsANwLWMaEBPj179vE5SRcoBEDGmPxzrsE1eaLYOvl6LFEX -F4mi7nd6I5V+U6OVwnob/DZ4aYer/toHu07RSsPhX3QMDW4OSiIcMWXGUKE51lhe -zNnyzCaYHvAa9u6MpeAAWskK9Rey68svThM4GqSUJpqV7OfX66JDAgMBAAEwDQYJ -KoZIhvcNAQEFBQADgYEAmuRLnS84YMbD4dzDjyRIS0/MGPWFQx3wNiE5KYShXfnf -aVunYjVWXeAsu3Qubxl7Mmqqml+r7v8ujEXmOglYxQUOiUm26RQNyOINvXQyl3zk -8g8Q1IgLI2lEkS3j5ig+7gUUWW5Jyep298Fh3BOYnGVtlCiimCS2bY600kVXvb8= +MIIBuDCCASGgAwIBAgIBAzANBgkqhkiG9w0BAQUFADAfMR0wGwYDVQQDDBRUZXN0 +IEludGVybWVkaWF0ZSBDQTAiGA8yMDE3MDEwMTAwMDAwMFoYDzIwMTgwMTAxMDAw +MDAwWjAhMR8wHQYDVQQDDBZUZXN0IEZhbHNlIE9DU1AgU2lnbmVyMIGfMA0GCSqG +SIb3DQEBAQUAA4GNADCBiQKBgQC/KPoD7KZClE3whl59vxqgxZlKSkNEakLVu+y1 +HxJEsXqKB7jCfxcnEmhsSI5tKuYXlmRx1L+Bx5vUi1+2MdRTUOayZvM3OFqM3XkS +NsbAwoWrdXddl4TjPmxarTy/B5XyDOTn9CyVjr0cAJ+gW8OwwJjTWzgxor33GqfY +uVVisQIDAQABMA0GCSqGSIb3DQEBBQUAA4GBAHfe98htyl7vb+h6lKqmBfTBqE2K +i/DI/G8PxFVbE9WQMfuZ+vAwgbQzo/D7SYy7pGSFGoNIynipdCO3YNK0Z9sQ2xKi +1RybF387ados34xOqqYZQbiPWK9Zf4SH0Qj7u0CI2+oG2pQiUWSnaQtLKlMshtdy +5x8hc+a0LSVG8VXi ~~~~~END CERTIFICATE~~~~~ -----BEGIN OCSP RESPONSE----- -MIIC8goBAKCCAuswggLnBgkrBgEFBQcwAQEEggLYMIIC1DCBh6EjMCExHzAdBgNVBAMTFlRlc3Q -gRmFsc2UgT0NTUCBTaWduZXIYDzIwMTcwMzAyMDAwMDAwWjBPME0wODAHBgUrDgMCGgQUAv912i -Teit0VD6tonczm5mNtCQEEFIThulKiXFQ8qXJJEiS8ix7Ki5/0AgEDgAAYDzIwMTcwMzAxMDAwM -DAwWjANBgkqhkiG9w0BAQUFAAOBgQAfpiwBf14Srg9sllvODAXRpJD6EQ91K3tqs+U8wwO8uQ40 -sq52BHP23oMUTh1+OxuyDNNcvvsesfZ4F6PGsKZEIK4wagzZ1O6M28aqEI/yam6kEQ0eP8tKbr3 -6qAdCsy/m4TgVprv77Nz5eQd3v/qC85kMTmQMy5/WuLY9r98XgqCCAbMwggGvMIIBqzCCARSgAw -IBAgIBAjANBgkqhkiG9w0BAQUFADASMRAwDgYDVQQDEwdUZXN0IENBMCIYDzIwMTcwMTAxMDAwM -DAwWhgPMjAxODAxMDEwMDAwMDBaMCExHzAdBgNVBAMTFlRlc3QgRmFsc2UgT0NTUCBTaWduZXIw -gZ8wDQYJKoZIhvcNAQEBBQADgY0AMIGJAoGBAMsS7RYTAjsANwLWMaEBPj179vE5SRcoBEDGmPx -zrsE1eaLYOvl6LFEXF4mi7nd6I5V+U6OVwnob/DZ4aYer/toHu07RSsPhX3QMDW4OSiIcMWXGUK -E51lhezNnyzCaYHvAa9u6MpeAAWskK9Rey68svThM4GqSUJpqV7OfX66JDAgMBAAEwDQYJKoZIh -vcNAQEFBQADgYEAmuRLnS84YMbD4dzDjyRIS0/MGPWFQx3wNiE5KYShXfnfaVunYjVWXeAsu3Qu -bxl7Mmqqml+r7v8ujEXmOglYxQUOiUm26RQNyOINvXQyl3zk8g8Q1IgLI2lEkS3j5ig+7gUUWW5 -Jyep298Fh3BOYnGVtlCiimCS2bY600kVXvb8= +MIIC/woBAKCCAvgwggL0BgkrBgEFBQcwAQEEggLlMIIC4TCBh6EjMCExHzAdBgNVBAMMFlRlc3Q +gRmFsc2UgT0NTUCBTaWduZXIYDzIwMTcwMzAyMDAwMDAwWjBPME0wODAHBgUrDgMCGgQURJscWz +HG6ZkJZlI+ScP3c8AkGQoEFPxtM4fMOzmwScdVxG30OVVIkwvOAgEEgAAYDzIwMTcwMzAxMDAwM +DAwWjANBgkqhkiG9w0BAQUFAAOBgQB3RN/5ZbALFhaHkCY+4Burt8iwl7CB4X3fXRdcSae/7P2j +EsvuNU3iKTUGnZxSMqpqejla6H3dHDMEePtQYrXRG0x1Mn0/jRcvi7KB23oOKIq3XU2flo3k+C6 +82Ja7cxpr+ldZWi/FLF5MToIY/qFo/ZnZBvoK9+Hj7eOVxwSXaKCCAcAwggG8MIIBuDCCASGgAw +IBAgIBAzANBgkqhkiG9w0BAQUFADAfMR0wGwYDVQQDDBRUZXN0IEludGVybWVkaWF0ZSBDQTAiG +A8yMDE3MDEwMTAwMDAwMFoYDzIwMTgwMTAxMDAwMDAwWjAhMR8wHQYDVQQDDBZUZXN0IEZhbHNl +IE9DU1AgU2lnbmVyMIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQC/KPoD7KZClE3whl59vxq +gxZlKSkNEakLVu+y1HxJEsXqKB7jCfxcnEmhsSI5tKuYXlmRx1L+Bx5vUi1+2MdRTUOayZvM3OF +qM3XkSNsbAwoWrdXddl4TjPmxarTy/B5XyDOTn9CyVjr0cAJ+gW8OwwJjTWzgxor33GqfYuVVis +QIDAQABMA0GCSqGSIb3DQEBBQUAA4GBAHfe98htyl7vb+h6lKqmBfTBqE2Ki/DI/G8PxFVbE9WQ +MfuZ+vAwgbQzo/D7SYy7pGSFGoNIynipdCO3YNK0Z9sQ2xKi1RybF387ados34xOqqYZQbiPWK9 +Zf4SH0Qj7u0CI2+oG2pQiUWSnaQtLKlMshtdy5x8hc+a0LSVG8VXi -----END OCSP RESPONSE----- $ openssl x509 -text < [CA CERTIFICATE] Certificate: Data: Version: 3 (0x2) - Serial Number: 0 (0x0) + Serial Number: 1 (0x1) Signature Algorithm: sha1WithRSAEncryption - Issuer: CN=Test CA + Issuer: CN = Test CA Validity Not Before: Jan 1 00:00:00 2017 GMT Not After : Jan 1 00:00:00 2018 GMT - Subject: CN=Test CA + Subject: CN = Test Intermediate CA Subject Public Key Info: Public Key Algorithm: rsaEncryption Public-Key: (1024 bit) Modulus: - 00:b8:25:2b:ee:59:9a:9d:bc:b4:48:ae:09:ce:0d: - ba:c5:83:57:03:92:fd:52:32:55:f5:e4:2e:a6:cf: - 9e:4b:c4:10:af:24:da:d5:dd:44:a8:d6:28:38:9c: - a5:11:c9:0b:70:a1:b5:71:cf:a4:35:c2:6a:17:b1: - b5:c7:cf:74:83:ac:7a:d5:3b:12:66:74:f2:4b:15: - b0:c2:59:af:0c:78:2c:42:3c:3f:8b:83:b3:1d:9a: - c8:bc:ce:b0:c8:f2:1a:a8:0a:1c:bb:6e:6e:d4:c6: - 10:66:3c:a8:ec:e3:c4:63:40:f6:79:ec:8b:14:ff: - 85:9e:2d:1a:e7:e8:31:56:81 + 00:b9:32:09:de:33:4a:4f:e2:04:73:49:d5:2e:2b: + 83:92:3a:94:e4:1b:0c:27:1b:f8:43:83:17:b8:75: + f5:a4:af:e3:4c:84:3e:6c:48:79:76:df:4d:f5:39: + af:92:4b:c5:a0:86:ab:35:cc:19:6b:93:82:c0:f8: + 44:4d:1a:14:5d:48:87:65:02:0e:b0:a8:96:d9:06: + 19:3f:aa:85:2d:84:c0:78:19:a6:96:ab:26:56:f7: + 6f:5a:1a:97:a2:01:88:00:99:10:8a:97:39:c8:22: + 6e:de:e5:56:f4:a6:23:cd:ea:48:0e:65:67:a4:73: + a0:50:91:de:ba:cf:54:08:8f Exponent: 65537 (0x10001) Signature Algorithm: sha1WithRSAEncryption - 35:fe:ee:96:31:c7:3d:91:eb:22:53:1f:bf:cc:20:cc:aa:f4: - 04:92:3c:8b:50:06:ea:a1:cc:b7:c2:4a:d6:02:af:53:a7:a4: - 71:81:78:bc:95:f3:2d:46:c4:83:4c:d5:92:11:7c:c7:67:d3: - 47:f6:06:9f:1c:46:da:d6:20:72:47:c2:57:d7:fb:66:d3:35: - 82:07:61:13:4e:4d:e6:0c:93:e6:f3:be:98:ff:e8:de:60:a7: - 06:94:cd:bb:f5:6e:b3:4e:0b:d6:e9:2b:72:bd:6e:ae:86:23: - 2d:44:33:c4:3b:a7:52:12:46:d2:76:95:06:3e:69:0f:72:60: - 16:d6 + 48:d5:9f:8d:90:bc:4a:59:38:1d:2b:83:2d:71:1c:74:9d:01: + 73:a0:b6:98:e7:1c:c2:22:66:23:33:0a:8f:64:ff:9c:6b:37: + 09:12:1c:15:12:cb:c3:61:d9:ab:cd:96:dd:95:fa:a6:02:67: + 3c:4c:ec:98:38:5c:fc:48:cc:85:a9:5b:49:2c:2b:06:66:07: + 9e:31:0f:93:10:ab:3e:9f:97:60:64:01:61:7e:86:15:bb:5e: + f1:90:31:a3:54:d0:86:0e:80:05:87:09:2e:65:b6:95:89:5c: + c1:e5:80:d9:b8:81:b6:ed:1a:20:b8:9b:22:ce:ef:d0:26:47: + 9d:57 -----BEGIN CA CERTIFICATE----- -MIIBnDCCAQWgAwIBAgIBADANBgkqhkiG9w0BAQUFADASMRAwDgYDVQQDEwdUZXN0IENBMCIYDzI -wMTcwMTAxMDAwMDAwWhgPMjAxODAxMDEwMDAwMDBaMBIxEDAOBgNVBAMTB1Rlc3QgQ0EwgZ8wDQ -YJKoZIhvcNAQEBBQADgY0AMIGJAoGBALglK+5Zmp28tEiuCc4NusWDVwOS/VIyVfXkLqbPnkvEE -K8k2tXdRKjWKDicpRHJC3ChtXHPpDXCahextcfPdIOsetU7EmZ08ksVsMJZrwx4LEI8P4uDsx2a -yLzOsMjyGqgKHLtubtTGEGY8qOzjxGNA9nnsixT/hZ4tGufoMVaBAgMBAAEwDQYJKoZIhvcNAQE -FBQADgYEANf7uljHHPZHrIlMfv8wgzKr0BJI8i1AG6qHMt8JK1gKvU6ekcYF4vJXzLUbEg0zVkh -F8x2fTR/YGnxxG2tYgckfCV9f7ZtM1ggdhE05N5gyT5vO+mP/o3mCnBpTNu/Vus04L1ukrcr1ur -oYjLUQzxDunUhJG0naVBj5pD3JgFtY= +MIIBqTCCARKgAwIBAgIBATANBgkqhkiG9w0BAQUFADASMRAwDgYDVQQDDAdUZXN0IENBMCIYDzI +wMTcwMTAxMDAwMDAwWhgPMjAxODAxMDEwMDAwMDBaMB8xHTAbBgNVBAMMFFRlc3QgSW50ZXJtZW +RpYXRlIENBMIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQC5MgneM0pP4gRzSdUuK4OSOpTkG +wwnG/hDgxe4dfWkr+NMhD5sSHl23031Oa+SS8Wghqs1zBlrk4LA+ERNGhRdSIdlAg6wqJbZBhk/ +qoUthMB4GaaWqyZW929aGpeiAYgAmRCKlznIIm7e5Vb0piPN6kgOZWekc6BQkd66z1QIjwIDAQA +BMA0GCSqGSIb3DQEBBQUAA4GBAEjVn42QvEpZOB0rgy1xHHSdAXOgtpjnHMIiZiMzCo9k/5xrNw +kSHBUSy8Nh2avNlt2V+qYCZzxM7Jg4XPxIzIWpW0ksKwZmB54xD5MQqz6fl2BkAWF+hhW7XvGQM +aNU0IYOgAWHCS5ltpWJXMHlgNm4gbbtGiC4myLO79AmR51X -----END CA CERTIFICATE----- $ openssl x509 -text < [CERTIFICATE] Certificate: Data: Version: 3 (0x2) - Serial Number: 3 (0x3) + Serial Number: 4 (0x4) Signature Algorithm: sha1WithRSAEncryption - Issuer: CN=Test CA + Issuer: CN = Test Intermediate CA Validity Not Before: Jan 1 00:00:00 2017 GMT Not After : Jan 1 00:00:00 2018 GMT - Subject: CN=Test Cert + Subject: CN = Test Cert Subject Public Key Info: Public Key Algorithm: rsaEncryption Public-Key: (1024 bit) Modulus: - 00:d5:12:3f:22:6f:b0:e1:43:c5:93:b3:c3:5b:70: - 52:b2:8b:10:ec:11:c4:c4:aa:aa:43:92:c8:d0:f3: - 35:23:e3:76:2d:b4:ea:93:26:6f:6a:79:1c:64:51: - d3:4d:21:4a:73:83:35:dc:a0:16:74:db:f0:b9:a5: - 46:35:8d:53:e8:7d:37:5b:4d:ad:a3:df:d6:ae:01: - 38:ad:16:09:6e:fd:65:ad:1c:4b:48:12:1e:48:a7: - ff:5b:47:c4:c9:3b:74:85:63:1a:0a:06:b2:9f:b9: - cb:ad:dc:3f:24:8b:a4:a7:8a:13:15:45:89:24:c1: - a7:3b:c2:a2:c8:74:f1:3f:6f + 00:bc:4c:d5:b3:8d:92:fa:66:ac:32:43:1a:9e:eb: + 17:e0:aa:76:35:1b:1d:10:48:4e:3e:22:8b:75:2e: + e8:6f:a4:55:1e:0a:5e:60:c0:61:f1:7d:29:58:7e: + 0b:ef:29:be:ad:f8:f7:43:c8:58:95:14:5b:1d:af: + 4a:b8:90:9e:4e:ec:4e:b3:86:7a:b9:96:c1:34:d3: + b9:a6:57:df:9b:bd:d9:dd:67:15:54:d4:9f:65:b8: + 33:29:59:ba:9a:c6:75:ea:a5:76:3d:a4:57:0f:e2: + e4:c3:91:35:1d:6e:ff:61:7d:c2:53:23:66:b2:a8: + 0b:e1:c7:55:48:c5:2b:4d:7d Exponent: 65537 (0x10001) Signature Algorithm: sha1WithRSAEncryption - 04:21:70:de:14:92:27:13:e8:d2:b0:51:f0:af:34:75:0b:a7: - ff:84:cb:c6:96:30:80:01:f5:c1:3a:c6:81:ee:ba:89:60:33: - c3:e5:0f:43:cc:ac:81:8d:09:fb:25:e1:67:40:64:a3:ca:fd: - bd:9c:c4:73:e4:bc:4d:8e:e2:70:f1:17:ce:b4:ab:a0:b2:63: - 72:25:27:ae:d5:8e:18:73:0d:dc:12:5a:32:1c:b7:da:cd:23: - 5b:c8:87:58:08:3e:95:0c:fd:c8:48:a2:75:6e:79:f2:00:82: - 6e:b5:cc:71:e3:79:ca:68:85:9b:1b:5c:52:bf:a2:5a:71:e3: - 05:b5 + 18:bb:93:d9:2a:e0:34:69:2f:96:57:ac:55:ac:a7:83:04:b4: + bc:22:7f:5f:f7:c0:dc:ac:af:13:9b:86:7e:ac:02:8c:44:83: + 2e:c0:fa:a1:77:1d:dd:86:31:7e:98:93:c0:4f:b2:3d:be:30: + 6f:a5:fc:c7:2e:b1:b8:08:d2:17:cb:60:55:bf:5a:e0:94:f3: + 1d:44:fa:b1:2f:1a:24:c5:33:e1:d4:f0:ac:d5:2c:67:da:a7: + 5d:ee:eb:d6:7a:a7:41:e8:94:7a:34:43:b2:1f:ab:e9:cf:5d: + 25:49:56:18:d2:a9:49:1a:37:34:43:c7:06:96:4a:29:38:cc: + f2:1c -----BEGIN CERTIFICATE----- -MIIBnjCCAQegAwIBAgIBAzANBgkqhkiG9w0BAQUFADASMRAwDgYDVQQDEwdUZXN0IENBMCIYDzI -wMTcwMTAxMDAwMDAwWhgPMjAxODAxMDEwMDAwMDBaMBQxEjAQBgNVBAMTCVRlc3QgQ2VydDCBnz -ANBgkqhkiG9w0BAQEFAAOBjQAwgYkCgYEA1RI/Im+w4UPFk7PDW3BSsosQ7BHExKqqQ5LI0PM1I -+N2LbTqkyZvankcZFHTTSFKc4M13KAWdNvwuaVGNY1T6H03W02to9/WrgE4rRYJbv1lrRxLSBIe -SKf/W0fEyTt0hWMaCgayn7nLrdw/JIukp4oTFUWJJMGnO8KiyHTxP28CAwEAATANBgkqhkiG9w0 -BAQUFAAOBgQAEIXDeFJInE+jSsFHwrzR1C6f/hMvGljCAAfXBOsaB7rqJYDPD5Q9DzKyBjQn7Je -FnQGSjyv29nMRz5LxNjuJw8RfOtKugsmNyJSeu1Y4Ycw3cEloyHLfazSNbyIdYCD6VDP3ISKJ1b -nnyAIJutcxx43nKaIWbG1xSv6JaceMFtQ== +MIIBqzCCARSgAwIBAgIBBDANBgkqhkiG9w0BAQUFADAfMR0wGwYDVQQDDBRUZXN0IEludGVybWV +kaWF0ZSBDQTAiGA8yMDE3MDEwMTAwMDAwMFoYDzIwMTgwMTAxMDAwMDAwWjAUMRIwEAYDVQQDDA +lUZXN0IENlcnQwgZ8wDQYJKoZIhvcNAQEBBQADgY0AMIGJAoGBALxM1bONkvpmrDJDGp7rF+Cqd +jUbHRBITj4ii3Uu6G+kVR4KXmDAYfF9KVh+C+8pvq3490PIWJUUWx2vSriQnk7sTrOGermWwTTT +uaZX35u92d1nFVTUn2W4MylZuprGdeqldj2kVw/i5MORNR1u/2F9wlMjZrKoC+HHVUjFK019AgM +BAAEwDQYJKoZIhvcNAQEFBQADgYEAGLuT2SrgNGkvllesVayngwS0vCJ/X/fA3KyvE5uGfqwCjE +SDLsD6oXcd3YYxfpiTwE+yPb4wb6X8xy6xuAjSF8tgVb9a4JTzHUT6sS8aJMUz4dTwrNUsZ9qnX +e7r1nqnQeiUejRDsh+r6c9dJUlWGNKpSRo3NEPHBpZKKTjM8hw= -----END CERTIFICATE----- $ openssl asn1parse -i < [OCSP REQUEST] @@ -185,10 +186,10 @@ 10:d=5 hl=2 l= 9 cons: SEQUENCE 12:d=6 hl=2 l= 5 prim: OBJECT :sha1 19:d=6 hl=2 l= 0 prim: NULL - 21:d=5 hl=2 l= 20 prim: OCTET STRING [HEX DUMP]:02FF75DA24DE8ADD150FAB689DCCE6E6636D0901 - 43:d=5 hl=2 l= 20 prim: OCTET STRING [HEX DUMP]:84E1BA52A25C543CA972491224BC8B1ECA8B9FF4 - 65:d=5 hl=2 l= 1 prim: INTEGER :03 + 21:d=5 hl=2 l= 20 prim: OCTET STRING [HEX DUMP]:449B1C5B31C6E9990966523E49C3F773C024190A + 43:d=5 hl=2 l= 20 prim: OCTET STRING [HEX DUMP]:FC6D3387CC3B39B049C755C46DF4395548930BCE + 65:d=5 hl=2 l= 1 prim: INTEGER :04 -----BEGIN OCSP REQUEST----- -MEIwQDA+MDwwOjAJBgUrDgMCGgUABBQC/3XaJN6K3RUPq2idzObmY20JAQQUhOG6UqJcVDypckk -SJLyLHsqLn/QCAQM= +MEIwQDA+MDwwOjAJBgUrDgMCGgUABBREmxxbMcbpmQlmUj5Jw/dzwCQZCgQU/G0zh8w7ObBJx1X +EbfQ5VUiTC84CAQQ= -----END OCSP REQUEST-----
diff --git a/net/data/ocsp_unittest/ocsp_sign_direct.pem b/net/data/ocsp_unittest/ocsp_sign_direct.pem index 0d91c58..cd81e8d 100644 --- a/net/data/ocsp_unittest/ocsp_sign_direct.pem +++ b/net/data/ocsp_unittest/ocsp_sign_direct.pem
@@ -5,123 +5,123 @@ OCSP Response Status: successful (0x0) Response Type: Basic OCSP Response Version: 1 (0x0) - Responder Id: CN = Test CA + Responder Id: CN = Test Intermediate CA Produced At: Mar 2 00:00:00 2017 GMT Responses: Certificate ID: Hash Algorithm: sha1 - Issuer Name Hash: 02FF75DA24DE8ADD150FAB689DCCE6E6636D0901 - Issuer Key Hash: 84E1BA52A25C543CA972491224BC8B1ECA8B9FF4 - Serial Number: 03 + Issuer Name Hash: 449B1C5B31C6E9990966523E49C3F773C024190A + Issuer Key Hash: FC6D3387CC3B39B049C755C46DF4395548930BCE + Serial Number: 04 Cert Status: good This Update: Mar 1 00:00:00 2017 GMT Signature Algorithm: sha1WithRSAEncryption - 0e:82:91:8d:92:af:45:cb:98:e8:0e:08:04:15:97:9a:3a:cf: - cc:72:ee:cd:b7:3e:b0:40:b5:fd:8d:7d:6c:2f:4a:a6:32:9e: - 37:3b:7f:d3:ef:89:9e:8d:34:c2:45:1b:9b:99:4d:ed:e3:9a: - 94:62:17:59:4b:3a:be:f8:c0:a7:98:bd:e0:69:8f:98:47:e9: - 76:25:d3:1f:94:53:d7:c2:db:56:a2:aa:e3:6b:19:38:97:33: - a7:b6:45:6e:52:69:2c:62:6e:98:b6:d8:75:00:0c:16:c9:8b: - 84:41:f4:99:3e:a9:0c:a7:d4:98:51:45:89:4c:e2:c2:8e:5b: - e8:26 + 9b:7c:bb:20:00:86:92:61:6d:8f:6d:70:87:52:1b:ac:d5:0a: + 97:ce:76:7b:c4:b4:a7:a8:1d:ea:2c:15:cc:d4:2e:7d:a2:8c: + 53:4a:82:06:4a:b6:e2:d9:9b:aa:c4:63:66:94:7a:71:ba:d9: + 4e:bc:90:11:56:75:56:aa:7c:34:73:1d:ad:1c:1b:a6:28:81: + ea:f9:a0:85:e6:4f:07:2e:43:63:49:1e:8f:78:b6:96:f4:8b: + 4d:7f:58:b2:86:18:45:3a:72:5e:7f:d5:f5:f0:66:83:58:92: + 03:4d:e2:1d:af:99:2a:f4:c9:10:24:a8:c7:87:16:7f:b9:76: + b1:ba -----BEGIN OCSP RESPONSE----- -MIIBKwoBAKCCASQwggEgBgkrBgEFBQcwAQEEggERMIIBDTB4oRQwEjEQMA4GA1UEAxMHVGVzdCB -DQRgPMjAxNzAzMDIwMDAwMDBaME8wTTA4MAcGBSsOAwIaBBQC/3XaJN6K3RUPq2idzObmY20JAQ -QUhOG6UqJcVDypckkSJLyLHsqLn/QCAQOAABgPMjAxNzAzMDEwMDAwMDBaMA0GCSqGSIb3DQEBB -QUAA4GBAA6CkY2Sr0XLmOgOCAQVl5o6z8xy7s23PrBAtf2NfWwvSqYynjc7f9PviZ6NNMJFG5uZ -Te3jmpRiF1lLOr74wKeYveBpj5hH6XYl0x+UU9fC21aiquNrGTiXM6e2RW5SaSxibpi22HUADBb -Ji4RB9Jk+qQyn1JhRRYlM4sKOW+gm +MIIBOQoBAKCCATIwggEuBgkrBgEFBQcwAQEEggEfMIIBGzCBhaEhMB8xHTAbBgNVBAMMFFRlc3Q +gSW50ZXJtZWRpYXRlIENBGA8yMDE3MDMwMjAwMDAwMFowTzBNMDgwBwYFKw4DAhoEFESbHFsxxu +mZCWZSPknD93PAJBkKBBT8bTOHzDs5sEnHVcRt9DlVSJMLzgIBBIAAGA8yMDE3MDMwMTAwMDAwM +FowDQYJKoZIhvcNAQEFBQADgYEAm3y7IACGkmFtj21wh1IbrNUKl852e8S0p6gd6iwVzNQufaKM +U0qCBkq24tmbqsRjZpR6cbrZTryQEVZ1Vqp8NHMdrRwbpiiB6vmgheZPBy5DY0kej3i2lvSLTX9 +YsoYYRTpyXn/V9fBmg1iSA03iHa+ZKvTJECSox4cWf7l2sbo= -----END OCSP RESPONSE----- $ openssl x509 -text < [CA CERTIFICATE] Certificate: Data: Version: 3 (0x2) - Serial Number: 0 (0x0) + Serial Number: 1 (0x1) Signature Algorithm: sha1WithRSAEncryption - Issuer: CN=Test CA + Issuer: CN = Test CA Validity Not Before: Jan 1 00:00:00 2017 GMT Not After : Jan 1 00:00:00 2018 GMT - Subject: CN=Test CA + Subject: CN = Test Intermediate CA Subject Public Key Info: Public Key Algorithm: rsaEncryption Public-Key: (1024 bit) Modulus: - 00:b8:25:2b:ee:59:9a:9d:bc:b4:48:ae:09:ce:0d: - ba:c5:83:57:03:92:fd:52:32:55:f5:e4:2e:a6:cf: - 9e:4b:c4:10:af:24:da:d5:dd:44:a8:d6:28:38:9c: - a5:11:c9:0b:70:a1:b5:71:cf:a4:35:c2:6a:17:b1: - b5:c7:cf:74:83:ac:7a:d5:3b:12:66:74:f2:4b:15: - b0:c2:59:af:0c:78:2c:42:3c:3f:8b:83:b3:1d:9a: - c8:bc:ce:b0:c8:f2:1a:a8:0a:1c:bb:6e:6e:d4:c6: - 10:66:3c:a8:ec:e3:c4:63:40:f6:79:ec:8b:14:ff: - 85:9e:2d:1a:e7:e8:31:56:81 + 00:b9:32:09:de:33:4a:4f:e2:04:73:49:d5:2e:2b: + 83:92:3a:94:e4:1b:0c:27:1b:f8:43:83:17:b8:75: + f5:a4:af:e3:4c:84:3e:6c:48:79:76:df:4d:f5:39: + af:92:4b:c5:a0:86:ab:35:cc:19:6b:93:82:c0:f8: + 44:4d:1a:14:5d:48:87:65:02:0e:b0:a8:96:d9:06: + 19:3f:aa:85:2d:84:c0:78:19:a6:96:ab:26:56:f7: + 6f:5a:1a:97:a2:01:88:00:99:10:8a:97:39:c8:22: + 6e:de:e5:56:f4:a6:23:cd:ea:48:0e:65:67:a4:73: + a0:50:91:de:ba:cf:54:08:8f Exponent: 65537 (0x10001) Signature Algorithm: sha1WithRSAEncryption - 35:fe:ee:96:31:c7:3d:91:eb:22:53:1f:bf:cc:20:cc:aa:f4: - 04:92:3c:8b:50:06:ea:a1:cc:b7:c2:4a:d6:02:af:53:a7:a4: - 71:81:78:bc:95:f3:2d:46:c4:83:4c:d5:92:11:7c:c7:67:d3: - 47:f6:06:9f:1c:46:da:d6:20:72:47:c2:57:d7:fb:66:d3:35: - 82:07:61:13:4e:4d:e6:0c:93:e6:f3:be:98:ff:e8:de:60:a7: - 06:94:cd:bb:f5:6e:b3:4e:0b:d6:e9:2b:72:bd:6e:ae:86:23: - 2d:44:33:c4:3b:a7:52:12:46:d2:76:95:06:3e:69:0f:72:60: - 16:d6 + 48:d5:9f:8d:90:bc:4a:59:38:1d:2b:83:2d:71:1c:74:9d:01: + 73:a0:b6:98:e7:1c:c2:22:66:23:33:0a:8f:64:ff:9c:6b:37: + 09:12:1c:15:12:cb:c3:61:d9:ab:cd:96:dd:95:fa:a6:02:67: + 3c:4c:ec:98:38:5c:fc:48:cc:85:a9:5b:49:2c:2b:06:66:07: + 9e:31:0f:93:10:ab:3e:9f:97:60:64:01:61:7e:86:15:bb:5e: + f1:90:31:a3:54:d0:86:0e:80:05:87:09:2e:65:b6:95:89:5c: + c1:e5:80:d9:b8:81:b6:ed:1a:20:b8:9b:22:ce:ef:d0:26:47: + 9d:57 -----BEGIN CA CERTIFICATE----- -MIIBnDCCAQWgAwIBAgIBADANBgkqhkiG9w0BAQUFADASMRAwDgYDVQQDEwdUZXN0IENBMCIYDzI -wMTcwMTAxMDAwMDAwWhgPMjAxODAxMDEwMDAwMDBaMBIxEDAOBgNVBAMTB1Rlc3QgQ0EwgZ8wDQ -YJKoZIhvcNAQEBBQADgY0AMIGJAoGBALglK+5Zmp28tEiuCc4NusWDVwOS/VIyVfXkLqbPnkvEE -K8k2tXdRKjWKDicpRHJC3ChtXHPpDXCahextcfPdIOsetU7EmZ08ksVsMJZrwx4LEI8P4uDsx2a -yLzOsMjyGqgKHLtubtTGEGY8qOzjxGNA9nnsixT/hZ4tGufoMVaBAgMBAAEwDQYJKoZIhvcNAQE -FBQADgYEANf7uljHHPZHrIlMfv8wgzKr0BJI8i1AG6qHMt8JK1gKvU6ekcYF4vJXzLUbEg0zVkh -F8x2fTR/YGnxxG2tYgckfCV9f7ZtM1ggdhE05N5gyT5vO+mP/o3mCnBpTNu/Vus04L1ukrcr1ur -oYjLUQzxDunUhJG0naVBj5pD3JgFtY= +MIIBqTCCARKgAwIBAgIBATANBgkqhkiG9w0BAQUFADASMRAwDgYDVQQDDAdUZXN0IENBMCIYDzI +wMTcwMTAxMDAwMDAwWhgPMjAxODAxMDEwMDAwMDBaMB8xHTAbBgNVBAMMFFRlc3QgSW50ZXJtZW +RpYXRlIENBMIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQC5MgneM0pP4gRzSdUuK4OSOpTkG +wwnG/hDgxe4dfWkr+NMhD5sSHl23031Oa+SS8Wghqs1zBlrk4LA+ERNGhRdSIdlAg6wqJbZBhk/ +qoUthMB4GaaWqyZW929aGpeiAYgAmRCKlznIIm7e5Vb0piPN6kgOZWekc6BQkd66z1QIjwIDAQA +BMA0GCSqGSIb3DQEBBQUAA4GBAEjVn42QvEpZOB0rgy1xHHSdAXOgtpjnHMIiZiMzCo9k/5xrNw +kSHBUSy8Nh2avNlt2V+qYCZzxM7Jg4XPxIzIWpW0ksKwZmB54xD5MQqz6fl2BkAWF+hhW7XvGQM +aNU0IYOgAWHCS5ltpWJXMHlgNm4gbbtGiC4myLO79AmR51X -----END CA CERTIFICATE----- $ openssl x509 -text < [CERTIFICATE] Certificate: Data: Version: 3 (0x2) - Serial Number: 3 (0x3) + Serial Number: 4 (0x4) Signature Algorithm: sha1WithRSAEncryption - Issuer: CN=Test CA + Issuer: CN = Test Intermediate CA Validity Not Before: Jan 1 00:00:00 2017 GMT Not After : Jan 1 00:00:00 2018 GMT - Subject: CN=Test Cert + Subject: CN = Test Cert Subject Public Key Info: Public Key Algorithm: rsaEncryption Public-Key: (1024 bit) Modulus: - 00:d5:12:3f:22:6f:b0:e1:43:c5:93:b3:c3:5b:70: - 52:b2:8b:10:ec:11:c4:c4:aa:aa:43:92:c8:d0:f3: - 35:23:e3:76:2d:b4:ea:93:26:6f:6a:79:1c:64:51: - d3:4d:21:4a:73:83:35:dc:a0:16:74:db:f0:b9:a5: - 46:35:8d:53:e8:7d:37:5b:4d:ad:a3:df:d6:ae:01: - 38:ad:16:09:6e:fd:65:ad:1c:4b:48:12:1e:48:a7: - ff:5b:47:c4:c9:3b:74:85:63:1a:0a:06:b2:9f:b9: - cb:ad:dc:3f:24:8b:a4:a7:8a:13:15:45:89:24:c1: - a7:3b:c2:a2:c8:74:f1:3f:6f + 00:bc:4c:d5:b3:8d:92:fa:66:ac:32:43:1a:9e:eb: + 17:e0:aa:76:35:1b:1d:10:48:4e:3e:22:8b:75:2e: + e8:6f:a4:55:1e:0a:5e:60:c0:61:f1:7d:29:58:7e: + 0b:ef:29:be:ad:f8:f7:43:c8:58:95:14:5b:1d:af: + 4a:b8:90:9e:4e:ec:4e:b3:86:7a:b9:96:c1:34:d3: + b9:a6:57:df:9b:bd:d9:dd:67:15:54:d4:9f:65:b8: + 33:29:59:ba:9a:c6:75:ea:a5:76:3d:a4:57:0f:e2: + e4:c3:91:35:1d:6e:ff:61:7d:c2:53:23:66:b2:a8: + 0b:e1:c7:55:48:c5:2b:4d:7d Exponent: 65537 (0x10001) Signature Algorithm: sha1WithRSAEncryption - 04:21:70:de:14:92:27:13:e8:d2:b0:51:f0:af:34:75:0b:a7: - ff:84:cb:c6:96:30:80:01:f5:c1:3a:c6:81:ee:ba:89:60:33: - c3:e5:0f:43:cc:ac:81:8d:09:fb:25:e1:67:40:64:a3:ca:fd: - bd:9c:c4:73:e4:bc:4d:8e:e2:70:f1:17:ce:b4:ab:a0:b2:63: - 72:25:27:ae:d5:8e:18:73:0d:dc:12:5a:32:1c:b7:da:cd:23: - 5b:c8:87:58:08:3e:95:0c:fd:c8:48:a2:75:6e:79:f2:00:82: - 6e:b5:cc:71:e3:79:ca:68:85:9b:1b:5c:52:bf:a2:5a:71:e3: - 05:b5 + 18:bb:93:d9:2a:e0:34:69:2f:96:57:ac:55:ac:a7:83:04:b4: + bc:22:7f:5f:f7:c0:dc:ac:af:13:9b:86:7e:ac:02:8c:44:83: + 2e:c0:fa:a1:77:1d:dd:86:31:7e:98:93:c0:4f:b2:3d:be:30: + 6f:a5:fc:c7:2e:b1:b8:08:d2:17:cb:60:55:bf:5a:e0:94:f3: + 1d:44:fa:b1:2f:1a:24:c5:33:e1:d4:f0:ac:d5:2c:67:da:a7: + 5d:ee:eb:d6:7a:a7:41:e8:94:7a:34:43:b2:1f:ab:e9:cf:5d: + 25:49:56:18:d2:a9:49:1a:37:34:43:c7:06:96:4a:29:38:cc: + f2:1c -----BEGIN CERTIFICATE----- -MIIBnjCCAQegAwIBAgIBAzANBgkqhkiG9w0BAQUFADASMRAwDgYDVQQDEwdUZXN0IENBMCIYDzI -wMTcwMTAxMDAwMDAwWhgPMjAxODAxMDEwMDAwMDBaMBQxEjAQBgNVBAMTCVRlc3QgQ2VydDCBnz -ANBgkqhkiG9w0BAQEFAAOBjQAwgYkCgYEA1RI/Im+w4UPFk7PDW3BSsosQ7BHExKqqQ5LI0PM1I -+N2LbTqkyZvankcZFHTTSFKc4M13KAWdNvwuaVGNY1T6H03W02to9/WrgE4rRYJbv1lrRxLSBIe -SKf/W0fEyTt0hWMaCgayn7nLrdw/JIukp4oTFUWJJMGnO8KiyHTxP28CAwEAATANBgkqhkiG9w0 -BAQUFAAOBgQAEIXDeFJInE+jSsFHwrzR1C6f/hMvGljCAAfXBOsaB7rqJYDPD5Q9DzKyBjQn7Je -FnQGSjyv29nMRz5LxNjuJw8RfOtKugsmNyJSeu1Y4Ycw3cEloyHLfazSNbyIdYCD6VDP3ISKJ1b -nnyAIJutcxx43nKaIWbG1xSv6JaceMFtQ== +MIIBqzCCARSgAwIBAgIBBDANBgkqhkiG9w0BAQUFADAfMR0wGwYDVQQDDBRUZXN0IEludGVybWV +kaWF0ZSBDQTAiGA8yMDE3MDEwMTAwMDAwMFoYDzIwMTgwMTAxMDAwMDAwWjAUMRIwEAYDVQQDDA +lUZXN0IENlcnQwgZ8wDQYJKoZIhvcNAQEBBQADgY0AMIGJAoGBALxM1bONkvpmrDJDGp7rF+Cqd +jUbHRBITj4ii3Uu6G+kVR4KXmDAYfF9KVh+C+8pvq3490PIWJUUWx2vSriQnk7sTrOGermWwTTT +uaZX35u92d1nFVTUn2W4MylZuprGdeqldj2kVw/i5MORNR1u/2F9wlMjZrKoC+HHVUjFK019AgM +BAAEwDQYJKoZIhvcNAQEFBQADgYEAGLuT2SrgNGkvllesVayngwS0vCJ/X/fA3KyvE5uGfqwCjE +SDLsD6oXcd3YYxfpiTwE+yPb4wb6X8xy6xuAjSF8tgVb9a4JTzHUT6sS8aJMUz4dTwrNUsZ9qnX +e7r1nqnQeiUejRDsh+r6c9dJUlWGNKpSRo3NEPHBpZKKTjM8hw= -----END CERTIFICATE----- $ openssl asn1parse -i < [OCSP REQUEST] @@ -133,10 +133,10 @@ 10:d=5 hl=2 l= 9 cons: SEQUENCE 12:d=6 hl=2 l= 5 prim: OBJECT :sha1 19:d=6 hl=2 l= 0 prim: NULL - 21:d=5 hl=2 l= 20 prim: OCTET STRING [HEX DUMP]:02FF75DA24DE8ADD150FAB689DCCE6E6636D0901 - 43:d=5 hl=2 l= 20 prim: OCTET STRING [HEX DUMP]:84E1BA52A25C543CA972491224BC8B1ECA8B9FF4 - 65:d=5 hl=2 l= 1 prim: INTEGER :03 + 21:d=5 hl=2 l= 20 prim: OCTET STRING [HEX DUMP]:449B1C5B31C6E9990966523E49C3F773C024190A + 43:d=5 hl=2 l= 20 prim: OCTET STRING [HEX DUMP]:FC6D3387CC3B39B049C755C46DF4395548930BCE + 65:d=5 hl=2 l= 1 prim: INTEGER :04 -----BEGIN OCSP REQUEST----- -MEIwQDA+MDwwOjAJBgUrDgMCGgUABBQC/3XaJN6K3RUPq2idzObmY20JAQQUhOG6UqJcVDypckk -SJLyLHsqLn/QCAQM= +MEIwQDA+MDwwOjAJBgUrDgMCGgUABBREmxxbMcbpmQlmUj5Jw/dzwCQZCgQU/G0zh8w7ObBJx1X +EbfQ5VUiTC84CAQQ= -----END OCSP REQUEST-----
diff --git a/net/data/ocsp_unittest/ocsp_sign_indirect.pem b/net/data/ocsp_unittest/ocsp_sign_indirect.pem index 4090d398..66802e8 100644 --- a/net/data/ocsp_unittest/ocsp_sign_indirect.pem +++ b/net/data/ocsp_unittest/ocsp_sign_indirect.pem
@@ -10,27 +10,27 @@ Responses: Certificate ID: Hash Algorithm: sha1 - Issuer Name Hash: 02FF75DA24DE8ADD150FAB689DCCE6E6636D0901 - Issuer Key Hash: 84E1BA52A25C543CA972491224BC8B1ECA8B9FF4 - Serial Number: 03 + Issuer Name Hash: 449B1C5B31C6E9990966523E49C3F773C024190A + Issuer Key Hash: FC6D3387CC3B39B049C755C46DF4395548930BCE + Serial Number: 04 Cert Status: good This Update: Mar 1 00:00:00 2017 GMT Signature Algorithm: sha1WithRSAEncryption - 4a:aa:d4:b4:ae:4e:a0:63:0e:30:a6:35:04:9a:0d:a2:4d:c5: - 76:bb:42:6d:fc:ea:f3:ec:52:c5:b7:da:9b:51:08:bd:c3:24: - f6:e2:eb:8d:e0:ad:fe:76:c4:07:10:63:c9:0c:a9:1f:47:f1: - d8:bb:72:7c:a2:00:e0:a2:44:24:06:27:a0:9c:7f:26:db:4c: - e7:2c:61:09:02:b3:1c:fc:e6:0d:92:d7:21:d2:6b:7c:39:7b: - 80:e2:a0:18:20:bf:28:9b:48:99:2d:a3:07:5c:bf:53:99:06: - 40:11:ca:e1:9a:9a:a8:71:7c:c8:be:bd:c2:3c:5d:eb:9f:da: - 2d:eb + 9a:ae:eb:3b:9d:e8:80:d3:fc:2d:97:6d:b3:fe:47:7b:10:fa: + 40:ee:01:d1:0e:05:e3:49:e4:7c:ad:6b:f6:03:e5:7b:9f:73: + 33:62:4f:24:e5:11:c0:2f:fd:64:99:f7:b6:fa:5d:99:9f:01: + a1:95:4c:a9:60:f7:ea:de:f4:41:db:78:65:67:e0:0c:ae:5b: + 36:47:22:f0:ae:ce:f0:b9:c5:56:7b:6b:92:9e:23:04:1e:45: + 1e:ea:2f:2a:fd:76:59:82:8c:8b:74:ce:78:88:16:c4:42:9a: + d1:a3:f0:38:e9:63:da:49:2f:73:9f:04:e8:40:82:83:1b:66: + e5:49 Certificate: Data: Version: 3 (0x2) - Serial Number: 1 (0x1) + Serial Number: 2 (0x2) Signature Algorithm: sha1WithRSAEncryption - Issuer: CN=Test CA + Issuer: CN=Test Intermediate CA Validity Not Before: Jan 1 00:00:00 2017 GMT Not After : Jan 1 00:00:00 2018 GMT @@ -39,145 +39,145 @@ Public Key Algorithm: rsaEncryption Public-Key: (1024 bit) Modulus: - 00:e3:da:d4:26:f5:7c:81:83:52:76:02:1c:d1:fc: - fa:7f:ee:68:17:80:17:ed:83:49:4d:e5:b1:dd:7d: - 5d:2e:16:78:28:77:74:77:ee:53:cc:af:6c:f7:3b: - f7:9d:f0:4e:a7:2a:ec:43:d6:aa:d4:47:a4:ab:ab: - 92:53:ce:46:6d:ff:e9:f9:b3:a7:ee:b0:68:c5:de: - 5c:64:e3:ad:94:d0:92:44:81:2a:56:c7:af:d7:9c: - 90:fe:48:35:4e:e9:66:38:dc:38:b3:00:fe:42:0b: - b5:ce:d9:cf:d4:85:cd:13:3d:4a:b4:1f:4b:65:c3: - 14:08:ae:71:f4:84:9f:a3:e5 + 00:c4:e7:57:6f:76:06:30:1c:60:f3:d9:e2:0f:20: + 22:96:c4:2f:2e:3c:d6:96:3d:bf:08:09:b2:1a:ac: + 6b:a5:f6:89:a8:67:d1:f1:2c:31:69:ec:5c:56:b1: + b0:8a:62:8b:b8:fe:c4:01:26:b2:ce:3b:ec:e3:0b: + f2:08:96:84:3d:b9:87:57:40:82:4d:32:42:44:dc: + e3:47:e5:1e:ad:52:a7:9b:6f:cd:d0:d3:34:8f:18: + 59:01:0e:17:a3:4c:a0:20:c9:ff:bd:b4:93:6b:aa: + bd:b4:a5:c7:e8:7c:35:bd:5a:2a:f6:2d:d7:fe:29: + 86:79:75:a6:15:1b:99:24:cf Exponent: 65537 (0x10001) X509v3 extensions: X509v3 Extended Key Usage: OCSP Signing Signature Algorithm: sha1WithRSAEncryption - 55:64:b9:72:42:b4:aa:14:76:fd:81:bf:76:ce:26:0e:6c:dd: - aa:1f:77:d8:13:48:76:93:52:00:46:4b:9c:50:1b:b3:cd:87: - e9:f5:53:58:20:a6:b3:37:17:45:fd:46:93:34:b2:33:b5:84: - ac:97:28:46:03:d5:78:e0:06:e3:99:0e:fa:0c:b3:4b:ce:40: - 0a:94:34:94:9a:27:52:7a:3e:f3:61:42:1c:95:52:3b:10:6e: - 86:d5:80:cb:11:67:24:de:e7:62:87:b9:76:4f:88:69:4d:23: - 94:34:94:1c:00:aa:30:25:51:a3:10:5c:07:81:2d:74:86:f3: - e7:68 + 6a:17:94:55:d2:fd:d9:c3:d5:8e:78:cd:23:71:47:4d:bf:e4: + af:87:f8:b6:d7:43:4b:ee:76:61:5a:bf:ed:ff:3e:bc:06:fc: + d9:ed:3f:f9:4e:ea:90:fd:40:b9:2e:ee:25:a8:1f:c8:92:60: + 78:87:ad:45:c8:1a:0d:3d:d6:cc:fa:f6:79:fb:ec:a6:b9:17: + d1:ae:a2:76:f9:59:9d:df:f4:62:05:23:3a:ed:b9:66:57:db: + 04:95:d6:2e:73:98:77:c1:09:8f:97:95:3a:ec:71:33:54:70: + d8:d9:6a:00:5c:89:14:6c:39:c0:dd:5e:68:54:c0:c5:43:98: + 68:fc ~~~~~BEGIN CERTIFICATE~~~~~ -MIIBvjCCASegAwIBAgIBATANBgkqhkiG9w0BAQUFADASMRAwDgYDVQQDEwdUZXN0 -IENBMCIYDzIwMTcwMTAxMDAwMDAwWhgPMjAxODAxMDEwMDAwMDBaMBsxGTAXBgNV -BAMTEFRlc3QgT0NTUCBTaWduZXIwgZ8wDQYJKoZIhvcNAQEBBQADgY0AMIGJAoGB -AOPa1Cb1fIGDUnYCHNH8+n/uaBeAF+2DSU3lsd19XS4WeCh3dHfuU8yvbPc7953w -Tqcq7EPWqtRHpKurklPORm3/6fmzp+6waMXeXGTjrZTQkkSBKlbHr9eckP5INU7p -ZjjcOLMA/kILtc7Zz9SFzRM9SrQfS2XDFAiucfSEn6PlAgMBAAGjFzAVMBMGA1Ud -JQQMMAoGCCsGAQUFBwMJMA0GCSqGSIb3DQEBBQUAA4GBAFVkuXJCtKoUdv2Bv3bO -Jg5s3aofd9gTSHaTUgBGS5xQG7PNh+n1U1ggprM3F0X9RpM0sjO1hKyXKEYD1Xjg -BuOZDvoMs0vOQAqUNJSaJ1J6PvNhQhyVUjsQbobVgMsRZyTe52KHuXZPiGlNI5Q0 -lBwAqjAlUaMQXAeBLXSG8+do +MIIByzCCATSgAwIBAgIBAjANBgkqhkiG9w0BAQUFADAfMR0wGwYDVQQDDBRUZXN0 +IEludGVybWVkaWF0ZSBDQTAiGA8yMDE3MDEwMTAwMDAwMFoYDzIwMTgwMTAxMDAw +MDAwWjAbMRkwFwYDVQQDDBBUZXN0IE9DU1AgU2lnbmVyMIGfMA0GCSqGSIb3DQEB +AQUAA4GNADCBiQKBgQDE51dvdgYwHGDz2eIPICKWxC8uPNaWPb8ICbIarGul9omo +Z9HxLDFp7FxWsbCKYou4/sQBJrLOO+zjC/IIloQ9uYdXQIJNMkJE3ONH5R6tUqeb +b83Q0zSPGFkBDhejTKAgyf+9tJNrqr20pcfofDW9Wir2Ldf+KYZ5daYVG5kkzwID +AQABoxcwFTATBgNVHSUEDDAKBggrBgEFBQcDCTANBgkqhkiG9w0BAQUFAAOBgQBq +F5RV0v3Zw9WOeM0jcUdNv+Svh/i210NL7nZhWr/t/z68BvzZ7T/5TuqQ/UC5Lu4l +qB/IkmB4h61FyBoNPdbM+vZ5++ymuRfRrqJ2+Vmd3/RiBSM67blmV9sEldYuc5h3 +wQmPl5U67HEzVHDY2WoAXIkUbDnA3V5oVMDFQ5ho/A== ~~~~~END CERTIFICATE~~~~~ -----BEGIN OCSP RESPONSE----- -MIIC/woBAKCCAvgwggL0BgkrBgEFBQcwAQEEggLlMIIC4TCBgaEdMBsxGTAXBgNVBAMTEFRlc3Q -gT0NTUCBTaWduZXIYDzIwMTcwMzAyMDAwMDAwWjBPME0wODAHBgUrDgMCGgQUAv912iTeit0VD6 -tonczm5mNtCQEEFIThulKiXFQ8qXJJEiS8ix7Ki5/0AgEDgAAYDzIwMTcwMzAxMDAwMDAwWjANB -gkqhkiG9w0BAQUFAAOBgQBKqtS0rk6gYw4wpjUEmg2iTcV2u0Jt/Orz7FLFt9qbUQi9wyT24uuN -4K3+dsQHEGPJDKkfR/HYu3J8ogDgokQkBiegnH8m20znLGEJArMc/OYNktch0mt8OXuA4qAYIL8 -om0iZLaMHXL9TmQZAEcrhmpqocXzIvr3CPF3rn9ot66CCAcYwggHCMIIBvjCCASegAwIBAgIBAT -ANBgkqhkiG9w0BAQUFADASMRAwDgYDVQQDEwdUZXN0IENBMCIYDzIwMTcwMTAxMDAwMDAwWhgPM -jAxODAxMDEwMDAwMDBaMBsxGTAXBgNVBAMTEFRlc3QgT0NTUCBTaWduZXIwgZ8wDQYJKoZIhvcN -AQEBBQADgY0AMIGJAoGBAOPa1Cb1fIGDUnYCHNH8+n/uaBeAF+2DSU3lsd19XS4WeCh3dHfuU8y -vbPc7953wTqcq7EPWqtRHpKurklPORm3/6fmzp+6waMXeXGTjrZTQkkSBKlbHr9eckP5INU7pZj -jcOLMA/kILtc7Zz9SFzRM9SrQfS2XDFAiucfSEn6PlAgMBAAGjFzAVMBMGA1UdJQQMMAoGCCsGA -QUFBwMJMA0GCSqGSIb3DQEBBQUAA4GBAFVkuXJCtKoUdv2Bv3bOJg5s3aofd9gTSHaTUgBGS5xQ -G7PNh+n1U1ggprM3F0X9RpM0sjO1hKyXKEYD1XjgBuOZDvoMs0vOQAqUNJSaJ1J6PvNhQhyVUjs -QbobVgMsRZyTe52KHuXZPiGlNI5Q0lBwAqjAlUaMQXAeBLXSG8+do +MIIDDAoBAKCCAwUwggMBBgkrBgEFBQcwAQEEggLyMIIC7jCBgaEdMBsxGTAXBgNVBAMMEFRlc3Q +gT0NTUCBTaWduZXIYDzIwMTcwMzAyMDAwMDAwWjBPME0wODAHBgUrDgMCGgQURJscWzHG6ZkJZl +I+ScP3c8AkGQoEFPxtM4fMOzmwScdVxG30OVVIkwvOAgEEgAAYDzIwMTcwMzAxMDAwMDAwWjANB +gkqhkiG9w0BAQUFAAOBgQCarus7neiA0/wtl22z/kd7EPpA7gHRDgXjSeR8rWv2A+V7n3MzYk8k +5RHAL/1kmfe2+l2ZnwGhlUypYPfq3vRB23hlZ+AMrls2RyLwrs7wucVWe2uSniMEHkUe6i8q/XZ +ZgoyLdM54iBbEQprRo/A46WPaSS9znwToQIKDG2blSaCCAdMwggHPMIIByzCCATSgAwIBAgIBAj +ANBgkqhkiG9w0BAQUFADAfMR0wGwYDVQQDDBRUZXN0IEludGVybWVkaWF0ZSBDQTAiGA8yMDE3M +DEwMTAwMDAwMFoYDzIwMTgwMTAxMDAwMDAwWjAbMRkwFwYDVQQDDBBUZXN0IE9DU1AgU2lnbmVy +MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDE51dvdgYwHGDz2eIPICKWxC8uPNaWPb8ICbI +arGul9omoZ9HxLDFp7FxWsbCKYou4/sQBJrLOO+zjC/IIloQ9uYdXQIJNMkJE3ONH5R6tUqebb8 +3Q0zSPGFkBDhejTKAgyf+9tJNrqr20pcfofDW9Wir2Ldf+KYZ5daYVG5kkzwIDAQABoxcwFTATB +gNVHSUEDDAKBggrBgEFBQcDCTANBgkqhkiG9w0BAQUFAAOBgQBqF5RV0v3Zw9WOeM0jcUdNv+Sv +h/i210NL7nZhWr/t/z68BvzZ7T/5TuqQ/UC5Lu4lqB/IkmB4h61FyBoNPdbM+vZ5++ymuRfRrqJ +2+Vmd3/RiBSM67blmV9sEldYuc5h3wQmPl5U67HEzVHDY2WoAXIkUbDnA3V5oVMDFQ5ho/A== -----END OCSP RESPONSE----- $ openssl x509 -text < [CA CERTIFICATE] Certificate: Data: Version: 3 (0x2) - Serial Number: 0 (0x0) + Serial Number: 1 (0x1) Signature Algorithm: sha1WithRSAEncryption - Issuer: CN=Test CA + Issuer: CN = Test CA Validity Not Before: Jan 1 00:00:00 2017 GMT Not After : Jan 1 00:00:00 2018 GMT - Subject: CN=Test CA + Subject: CN = Test Intermediate CA Subject Public Key Info: Public Key Algorithm: rsaEncryption Public-Key: (1024 bit) Modulus: - 00:b8:25:2b:ee:59:9a:9d:bc:b4:48:ae:09:ce:0d: - ba:c5:83:57:03:92:fd:52:32:55:f5:e4:2e:a6:cf: - 9e:4b:c4:10:af:24:da:d5:dd:44:a8:d6:28:38:9c: - a5:11:c9:0b:70:a1:b5:71:cf:a4:35:c2:6a:17:b1: - b5:c7:cf:74:83:ac:7a:d5:3b:12:66:74:f2:4b:15: - b0:c2:59:af:0c:78:2c:42:3c:3f:8b:83:b3:1d:9a: - c8:bc:ce:b0:c8:f2:1a:a8:0a:1c:bb:6e:6e:d4:c6: - 10:66:3c:a8:ec:e3:c4:63:40:f6:79:ec:8b:14:ff: - 85:9e:2d:1a:e7:e8:31:56:81 + 00:b9:32:09:de:33:4a:4f:e2:04:73:49:d5:2e:2b: + 83:92:3a:94:e4:1b:0c:27:1b:f8:43:83:17:b8:75: + f5:a4:af:e3:4c:84:3e:6c:48:79:76:df:4d:f5:39: + af:92:4b:c5:a0:86:ab:35:cc:19:6b:93:82:c0:f8: + 44:4d:1a:14:5d:48:87:65:02:0e:b0:a8:96:d9:06: + 19:3f:aa:85:2d:84:c0:78:19:a6:96:ab:26:56:f7: + 6f:5a:1a:97:a2:01:88:00:99:10:8a:97:39:c8:22: + 6e:de:e5:56:f4:a6:23:cd:ea:48:0e:65:67:a4:73: + a0:50:91:de:ba:cf:54:08:8f Exponent: 65537 (0x10001) Signature Algorithm: sha1WithRSAEncryption - 35:fe:ee:96:31:c7:3d:91:eb:22:53:1f:bf:cc:20:cc:aa:f4: - 04:92:3c:8b:50:06:ea:a1:cc:b7:c2:4a:d6:02:af:53:a7:a4: - 71:81:78:bc:95:f3:2d:46:c4:83:4c:d5:92:11:7c:c7:67:d3: - 47:f6:06:9f:1c:46:da:d6:20:72:47:c2:57:d7:fb:66:d3:35: - 82:07:61:13:4e:4d:e6:0c:93:e6:f3:be:98:ff:e8:de:60:a7: - 06:94:cd:bb:f5:6e:b3:4e:0b:d6:e9:2b:72:bd:6e:ae:86:23: - 2d:44:33:c4:3b:a7:52:12:46:d2:76:95:06:3e:69:0f:72:60: - 16:d6 + 48:d5:9f:8d:90:bc:4a:59:38:1d:2b:83:2d:71:1c:74:9d:01: + 73:a0:b6:98:e7:1c:c2:22:66:23:33:0a:8f:64:ff:9c:6b:37: + 09:12:1c:15:12:cb:c3:61:d9:ab:cd:96:dd:95:fa:a6:02:67: + 3c:4c:ec:98:38:5c:fc:48:cc:85:a9:5b:49:2c:2b:06:66:07: + 9e:31:0f:93:10:ab:3e:9f:97:60:64:01:61:7e:86:15:bb:5e: + f1:90:31:a3:54:d0:86:0e:80:05:87:09:2e:65:b6:95:89:5c: + c1:e5:80:d9:b8:81:b6:ed:1a:20:b8:9b:22:ce:ef:d0:26:47: + 9d:57 -----BEGIN CA CERTIFICATE----- -MIIBnDCCAQWgAwIBAgIBADANBgkqhkiG9w0BAQUFADASMRAwDgYDVQQDEwdUZXN0IENBMCIYDzI -wMTcwMTAxMDAwMDAwWhgPMjAxODAxMDEwMDAwMDBaMBIxEDAOBgNVBAMTB1Rlc3QgQ0EwgZ8wDQ -YJKoZIhvcNAQEBBQADgY0AMIGJAoGBALglK+5Zmp28tEiuCc4NusWDVwOS/VIyVfXkLqbPnkvEE -K8k2tXdRKjWKDicpRHJC3ChtXHPpDXCahextcfPdIOsetU7EmZ08ksVsMJZrwx4LEI8P4uDsx2a -yLzOsMjyGqgKHLtubtTGEGY8qOzjxGNA9nnsixT/hZ4tGufoMVaBAgMBAAEwDQYJKoZIhvcNAQE -FBQADgYEANf7uljHHPZHrIlMfv8wgzKr0BJI8i1AG6qHMt8JK1gKvU6ekcYF4vJXzLUbEg0zVkh -F8x2fTR/YGnxxG2tYgckfCV9f7ZtM1ggdhE05N5gyT5vO+mP/o3mCnBpTNu/Vus04L1ukrcr1ur -oYjLUQzxDunUhJG0naVBj5pD3JgFtY= +MIIBqTCCARKgAwIBAgIBATANBgkqhkiG9w0BAQUFADASMRAwDgYDVQQDDAdUZXN0IENBMCIYDzI +wMTcwMTAxMDAwMDAwWhgPMjAxODAxMDEwMDAwMDBaMB8xHTAbBgNVBAMMFFRlc3QgSW50ZXJtZW +RpYXRlIENBMIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQC5MgneM0pP4gRzSdUuK4OSOpTkG +wwnG/hDgxe4dfWkr+NMhD5sSHl23031Oa+SS8Wghqs1zBlrk4LA+ERNGhRdSIdlAg6wqJbZBhk/ +qoUthMB4GaaWqyZW929aGpeiAYgAmRCKlznIIm7e5Vb0piPN6kgOZWekc6BQkd66z1QIjwIDAQA +BMA0GCSqGSIb3DQEBBQUAA4GBAEjVn42QvEpZOB0rgy1xHHSdAXOgtpjnHMIiZiMzCo9k/5xrNw +kSHBUSy8Nh2avNlt2V+qYCZzxM7Jg4XPxIzIWpW0ksKwZmB54xD5MQqz6fl2BkAWF+hhW7XvGQM +aNU0IYOgAWHCS5ltpWJXMHlgNm4gbbtGiC4myLO79AmR51X -----END CA CERTIFICATE----- $ openssl x509 -text < [CERTIFICATE] Certificate: Data: Version: 3 (0x2) - Serial Number: 3 (0x3) + Serial Number: 4 (0x4) Signature Algorithm: sha1WithRSAEncryption - Issuer: CN=Test CA + Issuer: CN = Test Intermediate CA Validity Not Before: Jan 1 00:00:00 2017 GMT Not After : Jan 1 00:00:00 2018 GMT - Subject: CN=Test Cert + Subject: CN = Test Cert Subject Public Key Info: Public Key Algorithm: rsaEncryption Public-Key: (1024 bit) Modulus: - 00:d5:12:3f:22:6f:b0:e1:43:c5:93:b3:c3:5b:70: - 52:b2:8b:10:ec:11:c4:c4:aa:aa:43:92:c8:d0:f3: - 35:23:e3:76:2d:b4:ea:93:26:6f:6a:79:1c:64:51: - d3:4d:21:4a:73:83:35:dc:a0:16:74:db:f0:b9:a5: - 46:35:8d:53:e8:7d:37:5b:4d:ad:a3:df:d6:ae:01: - 38:ad:16:09:6e:fd:65:ad:1c:4b:48:12:1e:48:a7: - ff:5b:47:c4:c9:3b:74:85:63:1a:0a:06:b2:9f:b9: - cb:ad:dc:3f:24:8b:a4:a7:8a:13:15:45:89:24:c1: - a7:3b:c2:a2:c8:74:f1:3f:6f + 00:bc:4c:d5:b3:8d:92:fa:66:ac:32:43:1a:9e:eb: + 17:e0:aa:76:35:1b:1d:10:48:4e:3e:22:8b:75:2e: + e8:6f:a4:55:1e:0a:5e:60:c0:61:f1:7d:29:58:7e: + 0b:ef:29:be:ad:f8:f7:43:c8:58:95:14:5b:1d:af: + 4a:b8:90:9e:4e:ec:4e:b3:86:7a:b9:96:c1:34:d3: + b9:a6:57:df:9b:bd:d9:dd:67:15:54:d4:9f:65:b8: + 33:29:59:ba:9a:c6:75:ea:a5:76:3d:a4:57:0f:e2: + e4:c3:91:35:1d:6e:ff:61:7d:c2:53:23:66:b2:a8: + 0b:e1:c7:55:48:c5:2b:4d:7d Exponent: 65537 (0x10001) Signature Algorithm: sha1WithRSAEncryption - 04:21:70:de:14:92:27:13:e8:d2:b0:51:f0:af:34:75:0b:a7: - ff:84:cb:c6:96:30:80:01:f5:c1:3a:c6:81:ee:ba:89:60:33: - c3:e5:0f:43:cc:ac:81:8d:09:fb:25:e1:67:40:64:a3:ca:fd: - bd:9c:c4:73:e4:bc:4d:8e:e2:70:f1:17:ce:b4:ab:a0:b2:63: - 72:25:27:ae:d5:8e:18:73:0d:dc:12:5a:32:1c:b7:da:cd:23: - 5b:c8:87:58:08:3e:95:0c:fd:c8:48:a2:75:6e:79:f2:00:82: - 6e:b5:cc:71:e3:79:ca:68:85:9b:1b:5c:52:bf:a2:5a:71:e3: - 05:b5 + 18:bb:93:d9:2a:e0:34:69:2f:96:57:ac:55:ac:a7:83:04:b4: + bc:22:7f:5f:f7:c0:dc:ac:af:13:9b:86:7e:ac:02:8c:44:83: + 2e:c0:fa:a1:77:1d:dd:86:31:7e:98:93:c0:4f:b2:3d:be:30: + 6f:a5:fc:c7:2e:b1:b8:08:d2:17:cb:60:55:bf:5a:e0:94:f3: + 1d:44:fa:b1:2f:1a:24:c5:33:e1:d4:f0:ac:d5:2c:67:da:a7: + 5d:ee:eb:d6:7a:a7:41:e8:94:7a:34:43:b2:1f:ab:e9:cf:5d: + 25:49:56:18:d2:a9:49:1a:37:34:43:c7:06:96:4a:29:38:cc: + f2:1c -----BEGIN CERTIFICATE----- -MIIBnjCCAQegAwIBAgIBAzANBgkqhkiG9w0BAQUFADASMRAwDgYDVQQDEwdUZXN0IENBMCIYDzI -wMTcwMTAxMDAwMDAwWhgPMjAxODAxMDEwMDAwMDBaMBQxEjAQBgNVBAMTCVRlc3QgQ2VydDCBnz -ANBgkqhkiG9w0BAQEFAAOBjQAwgYkCgYEA1RI/Im+w4UPFk7PDW3BSsosQ7BHExKqqQ5LI0PM1I -+N2LbTqkyZvankcZFHTTSFKc4M13KAWdNvwuaVGNY1T6H03W02to9/WrgE4rRYJbv1lrRxLSBIe -SKf/W0fEyTt0hWMaCgayn7nLrdw/JIukp4oTFUWJJMGnO8KiyHTxP28CAwEAATANBgkqhkiG9w0 -BAQUFAAOBgQAEIXDeFJInE+jSsFHwrzR1C6f/hMvGljCAAfXBOsaB7rqJYDPD5Q9DzKyBjQn7Je -FnQGSjyv29nMRz5LxNjuJw8RfOtKugsmNyJSeu1Y4Ycw3cEloyHLfazSNbyIdYCD6VDP3ISKJ1b -nnyAIJutcxx43nKaIWbG1xSv6JaceMFtQ== +MIIBqzCCARSgAwIBAgIBBDANBgkqhkiG9w0BAQUFADAfMR0wGwYDVQQDDBRUZXN0IEludGVybWV +kaWF0ZSBDQTAiGA8yMDE3MDEwMTAwMDAwMFoYDzIwMTgwMTAxMDAwMDAwWjAUMRIwEAYDVQQDDA +lUZXN0IENlcnQwgZ8wDQYJKoZIhvcNAQEBBQADgY0AMIGJAoGBALxM1bONkvpmrDJDGp7rF+Cqd +jUbHRBITj4ii3Uu6G+kVR4KXmDAYfF9KVh+C+8pvq3490PIWJUUWx2vSriQnk7sTrOGermWwTTT +uaZX35u92d1nFVTUn2W4MylZuprGdeqldj2kVw/i5MORNR1u/2F9wlMjZrKoC+HHVUjFK019AgM +BAAEwDQYJKoZIhvcNAQEFBQADgYEAGLuT2SrgNGkvllesVayngwS0vCJ/X/fA3KyvE5uGfqwCjE +SDLsD6oXcd3YYxfpiTwE+yPb4wb6X8xy6xuAjSF8tgVb9a4JTzHUT6sS8aJMUz4dTwrNUsZ9qnX +e7r1nqnQeiUejRDsh+r6c9dJUlWGNKpSRo3NEPHBpZKKTjM8hw= -----END CERTIFICATE----- $ openssl asn1parse -i < [OCSP REQUEST] @@ -189,10 +189,10 @@ 10:d=5 hl=2 l= 9 cons: SEQUENCE 12:d=6 hl=2 l= 5 prim: OBJECT :sha1 19:d=6 hl=2 l= 0 prim: NULL - 21:d=5 hl=2 l= 20 prim: OCTET STRING [HEX DUMP]:02FF75DA24DE8ADD150FAB689DCCE6E6636D0901 - 43:d=5 hl=2 l= 20 prim: OCTET STRING [HEX DUMP]:84E1BA52A25C543CA972491224BC8B1ECA8B9FF4 - 65:d=5 hl=2 l= 1 prim: INTEGER :03 + 21:d=5 hl=2 l= 20 prim: OCTET STRING [HEX DUMP]:449B1C5B31C6E9990966523E49C3F773C024190A + 43:d=5 hl=2 l= 20 prim: OCTET STRING [HEX DUMP]:FC6D3387CC3B39B049C755C46DF4395548930BCE + 65:d=5 hl=2 l= 1 prim: INTEGER :04 -----BEGIN OCSP REQUEST----- -MEIwQDA+MDwwOjAJBgUrDgMCGgUABBQC/3XaJN6K3RUPq2idzObmY20JAQQUhOG6UqJcVDypckk -SJLyLHsqLn/QCAQM= +MEIwQDA+MDwwOjAJBgUrDgMCGgUABBREmxxbMcbpmQlmUj5Jw/dzwCQZCgQU/G0zh8w7ObBJx1X +EbfQ5VUiTC84CAQQ= -----END OCSP REQUEST-----
diff --git a/net/data/ocsp_unittest/ocsp_sign_indirect_missing.pem b/net/data/ocsp_unittest/ocsp_sign_indirect_missing.pem index c65d1aac..161cf9c6 100644 --- a/net/data/ocsp_unittest/ocsp_sign_indirect_missing.pem +++ b/net/data/ocsp_unittest/ocsp_sign_indirect_missing.pem
@@ -10,118 +10,118 @@ Responses: Certificate ID: Hash Algorithm: sha1 - Issuer Name Hash: 02FF75DA24DE8ADD150FAB689DCCE6E6636D0901 - Issuer Key Hash: 84E1BA52A25C543CA972491224BC8B1ECA8B9FF4 - Serial Number: 03 + Issuer Name Hash: 449B1C5B31C6E9990966523E49C3F773C024190A + Issuer Key Hash: FC6D3387CC3B39B049C755C46DF4395548930BCE + Serial Number: 04 Cert Status: good This Update: Mar 1 00:00:00 2017 GMT Signature Algorithm: sha1WithRSAEncryption - 4a:aa:d4:b4:ae:4e:a0:63:0e:30:a6:35:04:9a:0d:a2:4d:c5: - 76:bb:42:6d:fc:ea:f3:ec:52:c5:b7:da:9b:51:08:bd:c3:24: - f6:e2:eb:8d:e0:ad:fe:76:c4:07:10:63:c9:0c:a9:1f:47:f1: - d8:bb:72:7c:a2:00:e0:a2:44:24:06:27:a0:9c:7f:26:db:4c: - e7:2c:61:09:02:b3:1c:fc:e6:0d:92:d7:21:d2:6b:7c:39:7b: - 80:e2:a0:18:20:bf:28:9b:48:99:2d:a3:07:5c:bf:53:99:06: - 40:11:ca:e1:9a:9a:a8:71:7c:c8:be:bd:c2:3c:5d:eb:9f:da: - 2d:eb + 9a:ae:eb:3b:9d:e8:80:d3:fc:2d:97:6d:b3:fe:47:7b:10:fa: + 40:ee:01:d1:0e:05:e3:49:e4:7c:ad:6b:f6:03:e5:7b:9f:73: + 33:62:4f:24:e5:11:c0:2f:fd:64:99:f7:b6:fa:5d:99:9f:01: + a1:95:4c:a9:60:f7:ea:de:f4:41:db:78:65:67:e0:0c:ae:5b: + 36:47:22:f0:ae:ce:f0:b9:c5:56:7b:6b:92:9e:23:04:1e:45: + 1e:ea:2f:2a:fd:76:59:82:8c:8b:74:ce:78:88:16:c4:42:9a: + d1:a3:f0:38:e9:63:da:49:2f:73:9f:04:e8:40:82:83:1b:66: + e5:49 -----BEGIN OCSP RESPONSE----- -MIIBNQoBAKCCAS4wggEqBgkrBgEFBQcwAQEEggEbMIIBFzCBgaEdMBsxGTAXBgNVBAMTEFRlc3Q -gT0NTUCBTaWduZXIYDzIwMTcwMzAyMDAwMDAwWjBPME0wODAHBgUrDgMCGgQUAv912iTeit0VD6 -tonczm5mNtCQEEFIThulKiXFQ8qXJJEiS8ix7Ki5/0AgEDgAAYDzIwMTcwMzAxMDAwMDAwWjANB -gkqhkiG9w0BAQUFAAOBgQBKqtS0rk6gYw4wpjUEmg2iTcV2u0Jt/Orz7FLFt9qbUQi9wyT24uuN -4K3+dsQHEGPJDKkfR/HYu3J8ogDgokQkBiegnH8m20znLGEJArMc/OYNktch0mt8OXuA4qAYIL8 -om0iZLaMHXL9TmQZAEcrhmpqocXzIvr3CPF3rn9ot6w== +MIIBNQoBAKCCAS4wggEqBgkrBgEFBQcwAQEEggEbMIIBFzCBgaEdMBsxGTAXBgNVBAMMEFRlc3Q +gT0NTUCBTaWduZXIYDzIwMTcwMzAyMDAwMDAwWjBPME0wODAHBgUrDgMCGgQURJscWzHG6ZkJZl +I+ScP3c8AkGQoEFPxtM4fMOzmwScdVxG30OVVIkwvOAgEEgAAYDzIwMTcwMzAxMDAwMDAwWjANB +gkqhkiG9w0BAQUFAAOBgQCarus7neiA0/wtl22z/kd7EPpA7gHRDgXjSeR8rWv2A+V7n3MzYk8k +5RHAL/1kmfe2+l2ZnwGhlUypYPfq3vRB23hlZ+AMrls2RyLwrs7wucVWe2uSniMEHkUe6i8q/XZ +ZgoyLdM54iBbEQprRo/A46WPaSS9znwToQIKDG2blSQ== -----END OCSP RESPONSE----- $ openssl x509 -text < [CA CERTIFICATE] Certificate: Data: Version: 3 (0x2) - Serial Number: 0 (0x0) + Serial Number: 1 (0x1) Signature Algorithm: sha1WithRSAEncryption - Issuer: CN=Test CA + Issuer: CN = Test CA Validity Not Before: Jan 1 00:00:00 2017 GMT Not After : Jan 1 00:00:00 2018 GMT - Subject: CN=Test CA + Subject: CN = Test Intermediate CA Subject Public Key Info: Public Key Algorithm: rsaEncryption Public-Key: (1024 bit) Modulus: - 00:b8:25:2b:ee:59:9a:9d:bc:b4:48:ae:09:ce:0d: - ba:c5:83:57:03:92:fd:52:32:55:f5:e4:2e:a6:cf: - 9e:4b:c4:10:af:24:da:d5:dd:44:a8:d6:28:38:9c: - a5:11:c9:0b:70:a1:b5:71:cf:a4:35:c2:6a:17:b1: - b5:c7:cf:74:83:ac:7a:d5:3b:12:66:74:f2:4b:15: - b0:c2:59:af:0c:78:2c:42:3c:3f:8b:83:b3:1d:9a: - c8:bc:ce:b0:c8:f2:1a:a8:0a:1c:bb:6e:6e:d4:c6: - 10:66:3c:a8:ec:e3:c4:63:40:f6:79:ec:8b:14:ff: - 85:9e:2d:1a:e7:e8:31:56:81 + 00:b9:32:09:de:33:4a:4f:e2:04:73:49:d5:2e:2b: + 83:92:3a:94:e4:1b:0c:27:1b:f8:43:83:17:b8:75: + f5:a4:af:e3:4c:84:3e:6c:48:79:76:df:4d:f5:39: + af:92:4b:c5:a0:86:ab:35:cc:19:6b:93:82:c0:f8: + 44:4d:1a:14:5d:48:87:65:02:0e:b0:a8:96:d9:06: + 19:3f:aa:85:2d:84:c0:78:19:a6:96:ab:26:56:f7: + 6f:5a:1a:97:a2:01:88:00:99:10:8a:97:39:c8:22: + 6e:de:e5:56:f4:a6:23:cd:ea:48:0e:65:67:a4:73: + a0:50:91:de:ba:cf:54:08:8f Exponent: 65537 (0x10001) Signature Algorithm: sha1WithRSAEncryption - 35:fe:ee:96:31:c7:3d:91:eb:22:53:1f:bf:cc:20:cc:aa:f4: - 04:92:3c:8b:50:06:ea:a1:cc:b7:c2:4a:d6:02:af:53:a7:a4: - 71:81:78:bc:95:f3:2d:46:c4:83:4c:d5:92:11:7c:c7:67:d3: - 47:f6:06:9f:1c:46:da:d6:20:72:47:c2:57:d7:fb:66:d3:35: - 82:07:61:13:4e:4d:e6:0c:93:e6:f3:be:98:ff:e8:de:60:a7: - 06:94:cd:bb:f5:6e:b3:4e:0b:d6:e9:2b:72:bd:6e:ae:86:23: - 2d:44:33:c4:3b:a7:52:12:46:d2:76:95:06:3e:69:0f:72:60: - 16:d6 + 48:d5:9f:8d:90:bc:4a:59:38:1d:2b:83:2d:71:1c:74:9d:01: + 73:a0:b6:98:e7:1c:c2:22:66:23:33:0a:8f:64:ff:9c:6b:37: + 09:12:1c:15:12:cb:c3:61:d9:ab:cd:96:dd:95:fa:a6:02:67: + 3c:4c:ec:98:38:5c:fc:48:cc:85:a9:5b:49:2c:2b:06:66:07: + 9e:31:0f:93:10:ab:3e:9f:97:60:64:01:61:7e:86:15:bb:5e: + f1:90:31:a3:54:d0:86:0e:80:05:87:09:2e:65:b6:95:89:5c: + c1:e5:80:d9:b8:81:b6:ed:1a:20:b8:9b:22:ce:ef:d0:26:47: + 9d:57 -----BEGIN CA CERTIFICATE----- -MIIBnDCCAQWgAwIBAgIBADANBgkqhkiG9w0BAQUFADASMRAwDgYDVQQDEwdUZXN0IENBMCIYDzI -wMTcwMTAxMDAwMDAwWhgPMjAxODAxMDEwMDAwMDBaMBIxEDAOBgNVBAMTB1Rlc3QgQ0EwgZ8wDQ -YJKoZIhvcNAQEBBQADgY0AMIGJAoGBALglK+5Zmp28tEiuCc4NusWDVwOS/VIyVfXkLqbPnkvEE -K8k2tXdRKjWKDicpRHJC3ChtXHPpDXCahextcfPdIOsetU7EmZ08ksVsMJZrwx4LEI8P4uDsx2a -yLzOsMjyGqgKHLtubtTGEGY8qOzjxGNA9nnsixT/hZ4tGufoMVaBAgMBAAEwDQYJKoZIhvcNAQE -FBQADgYEANf7uljHHPZHrIlMfv8wgzKr0BJI8i1AG6qHMt8JK1gKvU6ekcYF4vJXzLUbEg0zVkh -F8x2fTR/YGnxxG2tYgckfCV9f7ZtM1ggdhE05N5gyT5vO+mP/o3mCnBpTNu/Vus04L1ukrcr1ur -oYjLUQzxDunUhJG0naVBj5pD3JgFtY= +MIIBqTCCARKgAwIBAgIBATANBgkqhkiG9w0BAQUFADASMRAwDgYDVQQDDAdUZXN0IENBMCIYDzI +wMTcwMTAxMDAwMDAwWhgPMjAxODAxMDEwMDAwMDBaMB8xHTAbBgNVBAMMFFRlc3QgSW50ZXJtZW +RpYXRlIENBMIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQC5MgneM0pP4gRzSdUuK4OSOpTkG +wwnG/hDgxe4dfWkr+NMhD5sSHl23031Oa+SS8Wghqs1zBlrk4LA+ERNGhRdSIdlAg6wqJbZBhk/ +qoUthMB4GaaWqyZW929aGpeiAYgAmRCKlznIIm7e5Vb0piPN6kgOZWekc6BQkd66z1QIjwIDAQA +BMA0GCSqGSIb3DQEBBQUAA4GBAEjVn42QvEpZOB0rgy1xHHSdAXOgtpjnHMIiZiMzCo9k/5xrNw +kSHBUSy8Nh2avNlt2V+qYCZzxM7Jg4XPxIzIWpW0ksKwZmB54xD5MQqz6fl2BkAWF+hhW7XvGQM +aNU0IYOgAWHCS5ltpWJXMHlgNm4gbbtGiC4myLO79AmR51X -----END CA CERTIFICATE----- $ openssl x509 -text < [CERTIFICATE] Certificate: Data: Version: 3 (0x2) - Serial Number: 3 (0x3) + Serial Number: 4 (0x4) Signature Algorithm: sha1WithRSAEncryption - Issuer: CN=Test CA + Issuer: CN = Test Intermediate CA Validity Not Before: Jan 1 00:00:00 2017 GMT Not After : Jan 1 00:00:00 2018 GMT - Subject: CN=Test Cert + Subject: CN = Test Cert Subject Public Key Info: Public Key Algorithm: rsaEncryption Public-Key: (1024 bit) Modulus: - 00:d5:12:3f:22:6f:b0:e1:43:c5:93:b3:c3:5b:70: - 52:b2:8b:10:ec:11:c4:c4:aa:aa:43:92:c8:d0:f3: - 35:23:e3:76:2d:b4:ea:93:26:6f:6a:79:1c:64:51: - d3:4d:21:4a:73:83:35:dc:a0:16:74:db:f0:b9:a5: - 46:35:8d:53:e8:7d:37:5b:4d:ad:a3:df:d6:ae:01: - 38:ad:16:09:6e:fd:65:ad:1c:4b:48:12:1e:48:a7: - ff:5b:47:c4:c9:3b:74:85:63:1a:0a:06:b2:9f:b9: - cb:ad:dc:3f:24:8b:a4:a7:8a:13:15:45:89:24:c1: - a7:3b:c2:a2:c8:74:f1:3f:6f + 00:bc:4c:d5:b3:8d:92:fa:66:ac:32:43:1a:9e:eb: + 17:e0:aa:76:35:1b:1d:10:48:4e:3e:22:8b:75:2e: + e8:6f:a4:55:1e:0a:5e:60:c0:61:f1:7d:29:58:7e: + 0b:ef:29:be:ad:f8:f7:43:c8:58:95:14:5b:1d:af: + 4a:b8:90:9e:4e:ec:4e:b3:86:7a:b9:96:c1:34:d3: + b9:a6:57:df:9b:bd:d9:dd:67:15:54:d4:9f:65:b8: + 33:29:59:ba:9a:c6:75:ea:a5:76:3d:a4:57:0f:e2: + e4:c3:91:35:1d:6e:ff:61:7d:c2:53:23:66:b2:a8: + 0b:e1:c7:55:48:c5:2b:4d:7d Exponent: 65537 (0x10001) Signature Algorithm: sha1WithRSAEncryption - 04:21:70:de:14:92:27:13:e8:d2:b0:51:f0:af:34:75:0b:a7: - ff:84:cb:c6:96:30:80:01:f5:c1:3a:c6:81:ee:ba:89:60:33: - c3:e5:0f:43:cc:ac:81:8d:09:fb:25:e1:67:40:64:a3:ca:fd: - bd:9c:c4:73:e4:bc:4d:8e:e2:70:f1:17:ce:b4:ab:a0:b2:63: - 72:25:27:ae:d5:8e:18:73:0d:dc:12:5a:32:1c:b7:da:cd:23: - 5b:c8:87:58:08:3e:95:0c:fd:c8:48:a2:75:6e:79:f2:00:82: - 6e:b5:cc:71:e3:79:ca:68:85:9b:1b:5c:52:bf:a2:5a:71:e3: - 05:b5 + 18:bb:93:d9:2a:e0:34:69:2f:96:57:ac:55:ac:a7:83:04:b4: + bc:22:7f:5f:f7:c0:dc:ac:af:13:9b:86:7e:ac:02:8c:44:83: + 2e:c0:fa:a1:77:1d:dd:86:31:7e:98:93:c0:4f:b2:3d:be:30: + 6f:a5:fc:c7:2e:b1:b8:08:d2:17:cb:60:55:bf:5a:e0:94:f3: + 1d:44:fa:b1:2f:1a:24:c5:33:e1:d4:f0:ac:d5:2c:67:da:a7: + 5d:ee:eb:d6:7a:a7:41:e8:94:7a:34:43:b2:1f:ab:e9:cf:5d: + 25:49:56:18:d2:a9:49:1a:37:34:43:c7:06:96:4a:29:38:cc: + f2:1c -----BEGIN CERTIFICATE----- -MIIBnjCCAQegAwIBAgIBAzANBgkqhkiG9w0BAQUFADASMRAwDgYDVQQDEwdUZXN0IENBMCIYDzI -wMTcwMTAxMDAwMDAwWhgPMjAxODAxMDEwMDAwMDBaMBQxEjAQBgNVBAMTCVRlc3QgQ2VydDCBnz -ANBgkqhkiG9w0BAQEFAAOBjQAwgYkCgYEA1RI/Im+w4UPFk7PDW3BSsosQ7BHExKqqQ5LI0PM1I -+N2LbTqkyZvankcZFHTTSFKc4M13KAWdNvwuaVGNY1T6H03W02to9/WrgE4rRYJbv1lrRxLSBIe -SKf/W0fEyTt0hWMaCgayn7nLrdw/JIukp4oTFUWJJMGnO8KiyHTxP28CAwEAATANBgkqhkiG9w0 -BAQUFAAOBgQAEIXDeFJInE+jSsFHwrzR1C6f/hMvGljCAAfXBOsaB7rqJYDPD5Q9DzKyBjQn7Je -FnQGSjyv29nMRz5LxNjuJw8RfOtKugsmNyJSeu1Y4Ycw3cEloyHLfazSNbyIdYCD6VDP3ISKJ1b -nnyAIJutcxx43nKaIWbG1xSv6JaceMFtQ== +MIIBqzCCARSgAwIBAgIBBDANBgkqhkiG9w0BAQUFADAfMR0wGwYDVQQDDBRUZXN0IEludGVybWV +kaWF0ZSBDQTAiGA8yMDE3MDEwMTAwMDAwMFoYDzIwMTgwMTAxMDAwMDAwWjAUMRIwEAYDVQQDDA +lUZXN0IENlcnQwgZ8wDQYJKoZIhvcNAQEBBQADgY0AMIGJAoGBALxM1bONkvpmrDJDGp7rF+Cqd +jUbHRBITj4ii3Uu6G+kVR4KXmDAYfF9KVh+C+8pvq3490PIWJUUWx2vSriQnk7sTrOGermWwTTT +uaZX35u92d1nFVTUn2W4MylZuprGdeqldj2kVw/i5MORNR1u/2F9wlMjZrKoC+HHVUjFK019AgM +BAAEwDQYJKoZIhvcNAQEFBQADgYEAGLuT2SrgNGkvllesVayngwS0vCJ/X/fA3KyvE5uGfqwCjE +SDLsD6oXcd3YYxfpiTwE+yPb4wb6X8xy6xuAjSF8tgVb9a4JTzHUT6sS8aJMUz4dTwrNUsZ9qnX +e7r1nqnQeiUejRDsh+r6c9dJUlWGNKpSRo3NEPHBpZKKTjM8hw= -----END CERTIFICATE----- $ openssl asn1parse -i < [OCSP REQUEST] @@ -133,10 +133,10 @@ 10:d=5 hl=2 l= 9 cons: SEQUENCE 12:d=6 hl=2 l= 5 prim: OBJECT :sha1 19:d=6 hl=2 l= 0 prim: NULL - 21:d=5 hl=2 l= 20 prim: OCTET STRING [HEX DUMP]:02FF75DA24DE8ADD150FAB689DCCE6E6636D0901 - 43:d=5 hl=2 l= 20 prim: OCTET STRING [HEX DUMP]:84E1BA52A25C543CA972491224BC8B1ECA8B9FF4 - 65:d=5 hl=2 l= 1 prim: INTEGER :03 + 21:d=5 hl=2 l= 20 prim: OCTET STRING [HEX DUMP]:449B1C5B31C6E9990966523E49C3F773C024190A + 43:d=5 hl=2 l= 20 prim: OCTET STRING [HEX DUMP]:FC6D3387CC3B39B049C755C46DF4395548930BCE + 65:d=5 hl=2 l= 1 prim: INTEGER :04 -----BEGIN OCSP REQUEST----- -MEIwQDA+MDwwOjAJBgUrDgMCGgUABBQC/3XaJN6K3RUPq2idzObmY20JAQQUhOG6UqJcVDypckk -SJLyLHsqLn/QCAQM= +MEIwQDA+MDwwOjAJBgUrDgMCGgUABBREmxxbMcbpmQlmUj5Jw/dzwCQZCgQU/G0zh8w7ObBJx1X +EbfQ5VUiTC84CAQQ= -----END OCSP REQUEST-----
diff --git a/net/data/ocsp_unittest/other_response.pem b/net/data/ocsp_unittest/other_response.pem index 7f49ed4..3ce69846 100644 --- a/net/data/ocsp_unittest/other_response.pem +++ b/net/data/ocsp_unittest/other_response.pem
@@ -5,134 +5,134 @@ OCSP Response Status: successful (0x0) Response Type: Basic OCSP Response Version: 1 (0x0) - Responder Id: CN = Test CA + Responder Id: CN = Test Intermediate CA Produced At: Mar 2 00:00:00 2017 GMT Responses: Certificate ID: Hash Algorithm: sha1 - Issuer Name Hash: 99D6B1D2B9004AD4235ABC2407F6A911CF4744F5 - Issuer Key Hash: B642544CC440E86E9BAE629F694117A7022B6178 - Serial Number: 04 + Issuer Name Hash: 00F1CA5C7F4C394343B0D13EB6F6941F464C16C4 + Issuer Key Hash: 81EE0D00EEBC6B0993214B13419CA5BA2DE0CE6D + Serial Number: 05 Cert Status: good This Update: Mar 1 00:00:00 2017 GMT Certificate ID: Hash Algorithm: sha1 - Issuer Name Hash: 99D6B1D2B9004AD4235ABC2407F6A911CF4744F5 - Issuer Key Hash: B642544CC440E86E9BAE629F694117A7022B6178 - Serial Number: 04 + Issuer Name Hash: 00F1CA5C7F4C394343B0D13EB6F6941F464C16C4 + Issuer Key Hash: 81EE0D00EEBC6B0993214B13419CA5BA2DE0CE6D + Serial Number: 05 Cert Status: revoked Revocation Time: Feb 1 00:00:00 2017 GMT This Update: Mar 1 00:00:00 2017 GMT Signature Algorithm: sha1WithRSAEncryption - 7d:e7:06:e2:f6:f2:14:6b:9b:a0:05:fc:c1:a1:fe:f7:df:b8: - 8f:b4:29:7e:b5:6a:c9:d7:77:73:33:5f:b0:e3:0e:c5:88:fe: - b9:44:65:c5:0b:c0:7f:ef:7b:a5:7f:43:52:28:79:f1:e6:38: - 8e:d7:67:49:30:ad:3f:ac:6d:da:1a:3e:d4:c4:2d:2f:47:2c: - c0:75:61:fe:90:11:b8:d2:81:a7:e8:4b:db:29:02:89:2b:93: - 40:43:d1:8c:1b:b2:35:17:61:f6:d1:07:5a:a2:38:a2:e0:d2: - 15:7d:84:2b:bd:0f:83:6e:ae:78:56:7f:0e:2f:e0:54:10:44: - b5:e0 + 03:58:ea:f4:9f:6c:82:83:08:76:62:96:86:d1:d5:c0:58:b2: + f5:bb:14:1d:5d:2b:bc:e6:a6:31:7c:74:1a:5d:e9:b0:05:d9: + 1c:27:ab:e0:45:90:ff:4f:21:ab:17:d7:6d:5f:80:df:f5:f1: + 6d:0b:c6:bf:86:44:27:fb:7e:40:18:c2:34:b4:bd:02:02:b0: + 29:8d:a5:ab:cc:3c:82:8a:0f:a0:0c:9f:e1:7e:5a:5c:a6:29: + 5e:2c:d5:28:bf:f3:ff:f3:c4:56:52:98:b6:9a:e1:67:42:41: + 3c:e9:ec:d3:2e:dc:da:fd:fb:14:87:f6:8a:42:6d:18:d1:a9: + ad:3f -----BEGIN OCSP RESPONSE----- -MIIBjQoBAKCCAYYwggGCBgkrBgEFBQcwAQEEggFzMIIBbzCB2aEUMBIxEDAOBgNVBAMTB1Rlc3Q -gQ0EYDzIwMTcwMzAyMDAwMDAwWjCBrzBNMDgwBwYFKw4DAhoEFJnWsdK5AErUI1q8JAf2qRHPR0 -T1BBS2QlRMxEDobpuuYp9pQRenAitheAIBBIAAGA8yMDE3MDMwMTAwMDAwMFowXjA4MAcGBSsOA -wIaBBSZ1rHSuQBK1CNavCQH9qkRz0dE9QQUtkJUTMRA6G6brmKfaUEXpwIrYXgCAQShERgPMjAx -NzAyMDEwMDAwMDBaGA8yMDE3MDMwMTAwMDAwMFowDQYJKoZIhvcNAQEFBQADgYEAfecG4vbyFGu -boAX8waH+99+4j7QpfrVqydd3czNfsOMOxYj+uURlxQvAf+97pX9DUih58eY4jtdnSTCtP6xt2h -o+1MQtL0cswHVh/pARuNKBp+hL2ykCiSuTQEPRjBuyNRdh9tEHWqI4ouDSFX2EK70Pg26ueFZ/D -i/gVBBEteA= +MIIBmgoBAKCCAZMwggGPBgkrBgEFBQcwAQEEggGAMIIBfDCB5qEhMB8xHTAbBgNVBAMMFFRlc3Q +gSW50ZXJtZWRpYXRlIENBGA8yMDE3MDMwMjAwMDAwMFowga8wTTA4MAcGBSsOAwIaBBQA8cpcf0 +w5Q0Ow0T629pQfRkwWxAQUge4NAO68awmTIUsTQZylui3gzm0CAQWAABgPMjAxNzAzMDEwMDAwM +DBaMF4wODAHBgUrDgMCGgQUAPHKXH9MOUNDsNE+tvaUH0ZMFsQEFIHuDQDuvGsJkyFLE0Gcpbot +4M5tAgEFoREYDzIwMTcwMjAxMDAwMDAwWhgPMjAxNzAzMDEwMDAwMDBaMA0GCSqGSIb3DQEBBQU +AA4GBAANY6vSfbIKDCHZilobR1cBYsvW7FB1dK7zmpjF8dBpd6bAF2Rwnq+BFkP9PIasX121fgN +/18W0Lxr+GRCf7fkAYwjS0vQICsCmNpavMPIKKD6AMn+F+WlymKV4s1Si/8//zxFZSmLaa4WdCQ +Tzp7NMu3Nr9+xSH9opCbRjRqa0/ -----END OCSP RESPONSE----- $ openssl x509 -text < [CA CERTIFICATE] Certificate: Data: Version: 3 (0x2) - Serial Number: 0 (0x0) + Serial Number: 1 (0x1) Signature Algorithm: sha1WithRSAEncryption - Issuer: CN=Test CA + Issuer: CN = Test CA Validity Not Before: Jan 1 00:00:00 2017 GMT Not After : Jan 1 00:00:00 2018 GMT - Subject: CN=Test CA + Subject: CN = Test Intermediate CA Subject Public Key Info: Public Key Algorithm: rsaEncryption Public-Key: (1024 bit) Modulus: - 00:b8:25:2b:ee:59:9a:9d:bc:b4:48:ae:09:ce:0d: - ba:c5:83:57:03:92:fd:52:32:55:f5:e4:2e:a6:cf: - 9e:4b:c4:10:af:24:da:d5:dd:44:a8:d6:28:38:9c: - a5:11:c9:0b:70:a1:b5:71:cf:a4:35:c2:6a:17:b1: - b5:c7:cf:74:83:ac:7a:d5:3b:12:66:74:f2:4b:15: - b0:c2:59:af:0c:78:2c:42:3c:3f:8b:83:b3:1d:9a: - c8:bc:ce:b0:c8:f2:1a:a8:0a:1c:bb:6e:6e:d4:c6: - 10:66:3c:a8:ec:e3:c4:63:40:f6:79:ec:8b:14:ff: - 85:9e:2d:1a:e7:e8:31:56:81 + 00:b9:32:09:de:33:4a:4f:e2:04:73:49:d5:2e:2b: + 83:92:3a:94:e4:1b:0c:27:1b:f8:43:83:17:b8:75: + f5:a4:af:e3:4c:84:3e:6c:48:79:76:df:4d:f5:39: + af:92:4b:c5:a0:86:ab:35:cc:19:6b:93:82:c0:f8: + 44:4d:1a:14:5d:48:87:65:02:0e:b0:a8:96:d9:06: + 19:3f:aa:85:2d:84:c0:78:19:a6:96:ab:26:56:f7: + 6f:5a:1a:97:a2:01:88:00:99:10:8a:97:39:c8:22: + 6e:de:e5:56:f4:a6:23:cd:ea:48:0e:65:67:a4:73: + a0:50:91:de:ba:cf:54:08:8f Exponent: 65537 (0x10001) Signature Algorithm: sha1WithRSAEncryption - 35:fe:ee:96:31:c7:3d:91:eb:22:53:1f:bf:cc:20:cc:aa:f4: - 04:92:3c:8b:50:06:ea:a1:cc:b7:c2:4a:d6:02:af:53:a7:a4: - 71:81:78:bc:95:f3:2d:46:c4:83:4c:d5:92:11:7c:c7:67:d3: - 47:f6:06:9f:1c:46:da:d6:20:72:47:c2:57:d7:fb:66:d3:35: - 82:07:61:13:4e:4d:e6:0c:93:e6:f3:be:98:ff:e8:de:60:a7: - 06:94:cd:bb:f5:6e:b3:4e:0b:d6:e9:2b:72:bd:6e:ae:86:23: - 2d:44:33:c4:3b:a7:52:12:46:d2:76:95:06:3e:69:0f:72:60: - 16:d6 + 48:d5:9f:8d:90:bc:4a:59:38:1d:2b:83:2d:71:1c:74:9d:01: + 73:a0:b6:98:e7:1c:c2:22:66:23:33:0a:8f:64:ff:9c:6b:37: + 09:12:1c:15:12:cb:c3:61:d9:ab:cd:96:dd:95:fa:a6:02:67: + 3c:4c:ec:98:38:5c:fc:48:cc:85:a9:5b:49:2c:2b:06:66:07: + 9e:31:0f:93:10:ab:3e:9f:97:60:64:01:61:7e:86:15:bb:5e: + f1:90:31:a3:54:d0:86:0e:80:05:87:09:2e:65:b6:95:89:5c: + c1:e5:80:d9:b8:81:b6:ed:1a:20:b8:9b:22:ce:ef:d0:26:47: + 9d:57 -----BEGIN CA CERTIFICATE----- -MIIBnDCCAQWgAwIBAgIBADANBgkqhkiG9w0BAQUFADASMRAwDgYDVQQDEwdUZXN0IENBMCIYDzI -wMTcwMTAxMDAwMDAwWhgPMjAxODAxMDEwMDAwMDBaMBIxEDAOBgNVBAMTB1Rlc3QgQ0EwgZ8wDQ -YJKoZIhvcNAQEBBQADgY0AMIGJAoGBALglK+5Zmp28tEiuCc4NusWDVwOS/VIyVfXkLqbPnkvEE -K8k2tXdRKjWKDicpRHJC3ChtXHPpDXCahextcfPdIOsetU7EmZ08ksVsMJZrwx4LEI8P4uDsx2a -yLzOsMjyGqgKHLtubtTGEGY8qOzjxGNA9nnsixT/hZ4tGufoMVaBAgMBAAEwDQYJKoZIhvcNAQE -FBQADgYEANf7uljHHPZHrIlMfv8wgzKr0BJI8i1AG6qHMt8JK1gKvU6ekcYF4vJXzLUbEg0zVkh -F8x2fTR/YGnxxG2tYgckfCV9f7ZtM1ggdhE05N5gyT5vO+mP/o3mCnBpTNu/Vus04L1ukrcr1ur -oYjLUQzxDunUhJG0naVBj5pD3JgFtY= +MIIBqTCCARKgAwIBAgIBATANBgkqhkiG9w0BAQUFADASMRAwDgYDVQQDDAdUZXN0IENBMCIYDzI +wMTcwMTAxMDAwMDAwWhgPMjAxODAxMDEwMDAwMDBaMB8xHTAbBgNVBAMMFFRlc3QgSW50ZXJtZW +RpYXRlIENBMIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQC5MgneM0pP4gRzSdUuK4OSOpTkG +wwnG/hDgxe4dfWkr+NMhD5sSHl23031Oa+SS8Wghqs1zBlrk4LA+ERNGhRdSIdlAg6wqJbZBhk/ +qoUthMB4GaaWqyZW929aGpeiAYgAmRCKlznIIm7e5Vb0piPN6kgOZWekc6BQkd66z1QIjwIDAQA +BMA0GCSqGSIb3DQEBBQUAA4GBAEjVn42QvEpZOB0rgy1xHHSdAXOgtpjnHMIiZiMzCo9k/5xrNw +kSHBUSy8Nh2avNlt2V+qYCZzxM7Jg4XPxIzIWpW0ksKwZmB54xD5MQqz6fl2BkAWF+hhW7XvGQM +aNU0IYOgAWHCS5ltpWJXMHlgNm4gbbtGiC4myLO79AmR51X -----END CA CERTIFICATE----- $ openssl x509 -text < [CERTIFICATE] Certificate: Data: Version: 3 (0x2) - Serial Number: 3 (0x3) + Serial Number: 4 (0x4) Signature Algorithm: sha1WithRSAEncryption - Issuer: CN=Test CA + Issuer: CN = Test Intermediate CA Validity Not Before: Jan 1 00:00:00 2017 GMT Not After : Jan 1 00:00:00 2018 GMT - Subject: CN=Test Cert + Subject: CN = Test Cert Subject Public Key Info: Public Key Algorithm: rsaEncryption Public-Key: (1024 bit) Modulus: - 00:d5:12:3f:22:6f:b0:e1:43:c5:93:b3:c3:5b:70: - 52:b2:8b:10:ec:11:c4:c4:aa:aa:43:92:c8:d0:f3: - 35:23:e3:76:2d:b4:ea:93:26:6f:6a:79:1c:64:51: - d3:4d:21:4a:73:83:35:dc:a0:16:74:db:f0:b9:a5: - 46:35:8d:53:e8:7d:37:5b:4d:ad:a3:df:d6:ae:01: - 38:ad:16:09:6e:fd:65:ad:1c:4b:48:12:1e:48:a7: - ff:5b:47:c4:c9:3b:74:85:63:1a:0a:06:b2:9f:b9: - cb:ad:dc:3f:24:8b:a4:a7:8a:13:15:45:89:24:c1: - a7:3b:c2:a2:c8:74:f1:3f:6f + 00:bc:4c:d5:b3:8d:92:fa:66:ac:32:43:1a:9e:eb: + 17:e0:aa:76:35:1b:1d:10:48:4e:3e:22:8b:75:2e: + e8:6f:a4:55:1e:0a:5e:60:c0:61:f1:7d:29:58:7e: + 0b:ef:29:be:ad:f8:f7:43:c8:58:95:14:5b:1d:af: + 4a:b8:90:9e:4e:ec:4e:b3:86:7a:b9:96:c1:34:d3: + b9:a6:57:df:9b:bd:d9:dd:67:15:54:d4:9f:65:b8: + 33:29:59:ba:9a:c6:75:ea:a5:76:3d:a4:57:0f:e2: + e4:c3:91:35:1d:6e:ff:61:7d:c2:53:23:66:b2:a8: + 0b:e1:c7:55:48:c5:2b:4d:7d Exponent: 65537 (0x10001) Signature Algorithm: sha1WithRSAEncryption - 04:21:70:de:14:92:27:13:e8:d2:b0:51:f0:af:34:75:0b:a7: - ff:84:cb:c6:96:30:80:01:f5:c1:3a:c6:81:ee:ba:89:60:33: - c3:e5:0f:43:cc:ac:81:8d:09:fb:25:e1:67:40:64:a3:ca:fd: - bd:9c:c4:73:e4:bc:4d:8e:e2:70:f1:17:ce:b4:ab:a0:b2:63: - 72:25:27:ae:d5:8e:18:73:0d:dc:12:5a:32:1c:b7:da:cd:23: - 5b:c8:87:58:08:3e:95:0c:fd:c8:48:a2:75:6e:79:f2:00:82: - 6e:b5:cc:71:e3:79:ca:68:85:9b:1b:5c:52:bf:a2:5a:71:e3: - 05:b5 + 18:bb:93:d9:2a:e0:34:69:2f:96:57:ac:55:ac:a7:83:04:b4: + bc:22:7f:5f:f7:c0:dc:ac:af:13:9b:86:7e:ac:02:8c:44:83: + 2e:c0:fa:a1:77:1d:dd:86:31:7e:98:93:c0:4f:b2:3d:be:30: + 6f:a5:fc:c7:2e:b1:b8:08:d2:17:cb:60:55:bf:5a:e0:94:f3: + 1d:44:fa:b1:2f:1a:24:c5:33:e1:d4:f0:ac:d5:2c:67:da:a7: + 5d:ee:eb:d6:7a:a7:41:e8:94:7a:34:43:b2:1f:ab:e9:cf:5d: + 25:49:56:18:d2:a9:49:1a:37:34:43:c7:06:96:4a:29:38:cc: + f2:1c -----BEGIN CERTIFICATE----- -MIIBnjCCAQegAwIBAgIBAzANBgkqhkiG9w0BAQUFADASMRAwDgYDVQQDEwdUZXN0IENBMCIYDzI -wMTcwMTAxMDAwMDAwWhgPMjAxODAxMDEwMDAwMDBaMBQxEjAQBgNVBAMTCVRlc3QgQ2VydDCBnz -ANBgkqhkiG9w0BAQEFAAOBjQAwgYkCgYEA1RI/Im+w4UPFk7PDW3BSsosQ7BHExKqqQ5LI0PM1I -+N2LbTqkyZvankcZFHTTSFKc4M13KAWdNvwuaVGNY1T6H03W02to9/WrgE4rRYJbv1lrRxLSBIe -SKf/W0fEyTt0hWMaCgayn7nLrdw/JIukp4oTFUWJJMGnO8KiyHTxP28CAwEAATANBgkqhkiG9w0 -BAQUFAAOBgQAEIXDeFJInE+jSsFHwrzR1C6f/hMvGljCAAfXBOsaB7rqJYDPD5Q9DzKyBjQn7Je -FnQGSjyv29nMRz5LxNjuJw8RfOtKugsmNyJSeu1Y4Ycw3cEloyHLfazSNbyIdYCD6VDP3ISKJ1b -nnyAIJutcxx43nKaIWbG1xSv6JaceMFtQ== +MIIBqzCCARSgAwIBAgIBBDANBgkqhkiG9w0BAQUFADAfMR0wGwYDVQQDDBRUZXN0IEludGVybWV +kaWF0ZSBDQTAiGA8yMDE3MDEwMTAwMDAwMFoYDzIwMTgwMTAxMDAwMDAwWjAUMRIwEAYDVQQDDA +lUZXN0IENlcnQwgZ8wDQYJKoZIhvcNAQEBBQADgY0AMIGJAoGBALxM1bONkvpmrDJDGp7rF+Cqd +jUbHRBITj4ii3Uu6G+kVR4KXmDAYfF9KVh+C+8pvq3490PIWJUUWx2vSriQnk7sTrOGermWwTTT +uaZX35u92d1nFVTUn2W4MylZuprGdeqldj2kVw/i5MORNR1u/2F9wlMjZrKoC+HHVUjFK019AgM +BAAEwDQYJKoZIhvcNAQEFBQADgYEAGLuT2SrgNGkvllesVayngwS0vCJ/X/fA3KyvE5uGfqwCjE +SDLsD6oXcd3YYxfpiTwE+yPb4wb6X8xy6xuAjSF8tgVb9a4JTzHUT6sS8aJMUz4dTwrNUsZ9qnX +e7r1nqnQeiUejRDsh+r6c9dJUlWGNKpSRo3NEPHBpZKKTjM8hw= -----END CERTIFICATE----- $ openssl asn1parse -i < [OCSP REQUEST] @@ -144,10 +144,10 @@ 10:d=5 hl=2 l= 9 cons: SEQUENCE 12:d=6 hl=2 l= 5 prim: OBJECT :sha1 19:d=6 hl=2 l= 0 prim: NULL - 21:d=5 hl=2 l= 20 prim: OCTET STRING [HEX DUMP]:02FF75DA24DE8ADD150FAB689DCCE6E6636D0901 - 43:d=5 hl=2 l= 20 prim: OCTET STRING [HEX DUMP]:84E1BA52A25C543CA972491224BC8B1ECA8B9FF4 - 65:d=5 hl=2 l= 1 prim: INTEGER :03 + 21:d=5 hl=2 l= 20 prim: OCTET STRING [HEX DUMP]:449B1C5B31C6E9990966523E49C3F773C024190A + 43:d=5 hl=2 l= 20 prim: OCTET STRING [HEX DUMP]:FC6D3387CC3B39B049C755C46DF4395548930BCE + 65:d=5 hl=2 l= 1 prim: INTEGER :04 -----BEGIN OCSP REQUEST----- -MEIwQDA+MDwwOjAJBgUrDgMCGgUABBQC/3XaJN6K3RUPq2idzObmY20JAQQUhOG6UqJcVDypckk -SJLyLHsqLn/QCAQM= +MEIwQDA+MDwwOjAJBgUrDgMCGgUABBREmxxbMcbpmQlmUj5Jw/dzwCQZCgQU/G0zh8w7ObBJx1X +EbfQ5VUiTC84CAQQ= -----END OCSP REQUEST-----
diff --git a/net/data/ocsp_unittest/responder_id.pem b/net/data/ocsp_unittest/responder_id.pem index a3b3af28..8a6c17f 100644 --- a/net/data/ocsp_unittest/responder_id.pem +++ b/net/data/ocsp_unittest/responder_id.pem
@@ -5,123 +5,123 @@ OCSP Response Status: successful (0x0) Response Type: Basic OCSP Response Version: 1 (0x0) - Responder Id: 84E1BA52A25C543CA972491224BC8B1ECA8B9FF4 + Responder Id: FC6D3387CC3B39B049C755C46DF4395548930BCE Produced At: Mar 2 00:00:00 2017 GMT Responses: Certificate ID: Hash Algorithm: sha1 - Issuer Name Hash: 02FF75DA24DE8ADD150FAB689DCCE6E6636D0901 - Issuer Key Hash: 84E1BA52A25C543CA972491224BC8B1ECA8B9FF4 - Serial Number: 03 + Issuer Name Hash: 449B1C5B31C6E9990966523E49C3F773C024190A + Issuer Key Hash: FC6D3387CC3B39B049C755C46DF4395548930BCE + Serial Number: 04 Cert Status: good This Update: Mar 1 00:00:00 2017 GMT Signature Algorithm: sha1WithRSAEncryption - 5b:a5:14:49:10:88:86:24:f8:6b:b9:d2:99:fa:da:c1:7c:a5: - d5:40:6e:1a:ff:39:78:5c:ec:27:13:73:4a:4c:a3:ab:2b:a0: - 14:f5:54:ea:13:47:38:aa:bc:f8:2b:dc:84:a8:e3:8c:99:4b: - 40:b3:01:fb:48:03:32:b5:d5:8c:b5:8d:af:7a:ca:7d:cc:5d: - 61:f7:ed:05:8f:a3:81:56:33:82:77:dc:a1:55:69:0e:d8:da: - 04:1f:1b:09:8c:9f:67:ad:0f:8c:88:27:3f:a3:da:22:d1:a0: - b0:50:60:ab:9d:c7:c7:de:0a:44:ed:64:fe:0b:bb:e3:34:0e: - 22:72 + 94:f0:e1:bc:e4:81:70:2e:a8:7c:2d:85:c9:18:00:1f:0a:77: + e9:b8:8f:0e:b9:81:68:bd:84:17:0e:fd:06:ad:2f:f8:a1:c9: + d3:34:d6:d7:0a:54:59:e6:f5:c8:ee:c6:eb:e9:ba:7a:45:47: + 1d:af:86:41:d9:32:1c:14:6f:6f:e9:97:dc:d6:39:70:73:a4: + 13:c6:a4:29:33:f8:64:df:49:43:63:1d:84:06:f6:c8:30:79: + 75:29:f2:a5:6c:1b:df:ee:77:d3:0c:d7:08:8f:bc:bb:1e:39: + 63:c6:a1:4b:8f:9e:6f:39:5d:47:b4:5e:5b:39:fc:fc:2f:4d: + 37:b9 -----BEGIN OCSP RESPONSE----- -MIIBLQoBAKCCASYwggEiBgkrBgEFBQcwAQEEggETMIIBDzB6ohYEFIThulKiXFQ8qXJJEiS8ix7 -Ki5/0GA8yMDE3MDMwMjAwMDAwMFowTzBNMDgwBwYFKw4DAhoEFAL/ddok3ordFQ+raJ3M5uZjbQ -kBBBSE4bpSolxUPKlySRIkvIseyouf9AIBA4AAGA8yMDE3MDMwMTAwMDAwMFowDQYJKoZIhvcNA -QEFBQADgYEAW6UUSRCIhiT4a7nSmfrawXyl1UBuGv85eFzsJxNzSkyjqyugFPVU6hNHOKq8+Cvc -hKjjjJlLQLMB+0gDMrXVjLWNr3rKfcxdYfftBY+jgVYzgnfcoVVpDtjaBB8bCYyfZ60PjIgnP6P -aItGgsFBgq53Hx94KRO1k/gu74zQOInI= +MIIBLQoBAKCCASYwggEiBgkrBgEFBQcwAQEEggETMIIBDzB6ohYEFPxtM4fMOzmwScdVxG30OVV +IkwvOGA8yMDE3MDMwMjAwMDAwMFowTzBNMDgwBwYFKw4DAhoEFESbHFsxxumZCWZSPknD93PAJB +kKBBT8bTOHzDs5sEnHVcRt9DlVSJMLzgIBBIAAGA8yMDE3MDMwMTAwMDAwMFowDQYJKoZIhvcNA +QEFBQADgYEAlPDhvOSBcC6ofC2FyRgAHwp36biPDrmBaL2EFw79Bq0v+KHJ0zTW1wpUWeb1yO7G +6+m6ekVHHa+GQdkyHBRvb+mX3NY5cHOkE8akKTP4ZN9JQ2MdhAb2yDB5dSnypWwb3+530wzXCI+ +8ux45Y8ahS4+ebzldR7ReWzn8/C9NN7k= -----END OCSP RESPONSE----- $ openssl x509 -text < [CA CERTIFICATE] Certificate: Data: Version: 3 (0x2) - Serial Number: 0 (0x0) + Serial Number: 1 (0x1) Signature Algorithm: sha1WithRSAEncryption - Issuer: CN=Test CA + Issuer: CN = Test CA Validity Not Before: Jan 1 00:00:00 2017 GMT Not After : Jan 1 00:00:00 2018 GMT - Subject: CN=Test CA + Subject: CN = Test Intermediate CA Subject Public Key Info: Public Key Algorithm: rsaEncryption Public-Key: (1024 bit) Modulus: - 00:b8:25:2b:ee:59:9a:9d:bc:b4:48:ae:09:ce:0d: - ba:c5:83:57:03:92:fd:52:32:55:f5:e4:2e:a6:cf: - 9e:4b:c4:10:af:24:da:d5:dd:44:a8:d6:28:38:9c: - a5:11:c9:0b:70:a1:b5:71:cf:a4:35:c2:6a:17:b1: - b5:c7:cf:74:83:ac:7a:d5:3b:12:66:74:f2:4b:15: - b0:c2:59:af:0c:78:2c:42:3c:3f:8b:83:b3:1d:9a: - c8:bc:ce:b0:c8:f2:1a:a8:0a:1c:bb:6e:6e:d4:c6: - 10:66:3c:a8:ec:e3:c4:63:40:f6:79:ec:8b:14:ff: - 85:9e:2d:1a:e7:e8:31:56:81 + 00:b9:32:09:de:33:4a:4f:e2:04:73:49:d5:2e:2b: + 83:92:3a:94:e4:1b:0c:27:1b:f8:43:83:17:b8:75: + f5:a4:af:e3:4c:84:3e:6c:48:79:76:df:4d:f5:39: + af:92:4b:c5:a0:86:ab:35:cc:19:6b:93:82:c0:f8: + 44:4d:1a:14:5d:48:87:65:02:0e:b0:a8:96:d9:06: + 19:3f:aa:85:2d:84:c0:78:19:a6:96:ab:26:56:f7: + 6f:5a:1a:97:a2:01:88:00:99:10:8a:97:39:c8:22: + 6e:de:e5:56:f4:a6:23:cd:ea:48:0e:65:67:a4:73: + a0:50:91:de:ba:cf:54:08:8f Exponent: 65537 (0x10001) Signature Algorithm: sha1WithRSAEncryption - 35:fe:ee:96:31:c7:3d:91:eb:22:53:1f:bf:cc:20:cc:aa:f4: - 04:92:3c:8b:50:06:ea:a1:cc:b7:c2:4a:d6:02:af:53:a7:a4: - 71:81:78:bc:95:f3:2d:46:c4:83:4c:d5:92:11:7c:c7:67:d3: - 47:f6:06:9f:1c:46:da:d6:20:72:47:c2:57:d7:fb:66:d3:35: - 82:07:61:13:4e:4d:e6:0c:93:e6:f3:be:98:ff:e8:de:60:a7: - 06:94:cd:bb:f5:6e:b3:4e:0b:d6:e9:2b:72:bd:6e:ae:86:23: - 2d:44:33:c4:3b:a7:52:12:46:d2:76:95:06:3e:69:0f:72:60: - 16:d6 + 48:d5:9f:8d:90:bc:4a:59:38:1d:2b:83:2d:71:1c:74:9d:01: + 73:a0:b6:98:e7:1c:c2:22:66:23:33:0a:8f:64:ff:9c:6b:37: + 09:12:1c:15:12:cb:c3:61:d9:ab:cd:96:dd:95:fa:a6:02:67: + 3c:4c:ec:98:38:5c:fc:48:cc:85:a9:5b:49:2c:2b:06:66:07: + 9e:31:0f:93:10:ab:3e:9f:97:60:64:01:61:7e:86:15:bb:5e: + f1:90:31:a3:54:d0:86:0e:80:05:87:09:2e:65:b6:95:89:5c: + c1:e5:80:d9:b8:81:b6:ed:1a:20:b8:9b:22:ce:ef:d0:26:47: + 9d:57 -----BEGIN CA CERTIFICATE----- -MIIBnDCCAQWgAwIBAgIBADANBgkqhkiG9w0BAQUFADASMRAwDgYDVQQDEwdUZXN0IENBMCIYDzI -wMTcwMTAxMDAwMDAwWhgPMjAxODAxMDEwMDAwMDBaMBIxEDAOBgNVBAMTB1Rlc3QgQ0EwgZ8wDQ -YJKoZIhvcNAQEBBQADgY0AMIGJAoGBALglK+5Zmp28tEiuCc4NusWDVwOS/VIyVfXkLqbPnkvEE -K8k2tXdRKjWKDicpRHJC3ChtXHPpDXCahextcfPdIOsetU7EmZ08ksVsMJZrwx4LEI8P4uDsx2a -yLzOsMjyGqgKHLtubtTGEGY8qOzjxGNA9nnsixT/hZ4tGufoMVaBAgMBAAEwDQYJKoZIhvcNAQE -FBQADgYEANf7uljHHPZHrIlMfv8wgzKr0BJI8i1AG6qHMt8JK1gKvU6ekcYF4vJXzLUbEg0zVkh -F8x2fTR/YGnxxG2tYgckfCV9f7ZtM1ggdhE05N5gyT5vO+mP/o3mCnBpTNu/Vus04L1ukrcr1ur -oYjLUQzxDunUhJG0naVBj5pD3JgFtY= +MIIBqTCCARKgAwIBAgIBATANBgkqhkiG9w0BAQUFADASMRAwDgYDVQQDDAdUZXN0IENBMCIYDzI +wMTcwMTAxMDAwMDAwWhgPMjAxODAxMDEwMDAwMDBaMB8xHTAbBgNVBAMMFFRlc3QgSW50ZXJtZW +RpYXRlIENBMIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQC5MgneM0pP4gRzSdUuK4OSOpTkG +wwnG/hDgxe4dfWkr+NMhD5sSHl23031Oa+SS8Wghqs1zBlrk4LA+ERNGhRdSIdlAg6wqJbZBhk/ +qoUthMB4GaaWqyZW929aGpeiAYgAmRCKlznIIm7e5Vb0piPN6kgOZWekc6BQkd66z1QIjwIDAQA +BMA0GCSqGSIb3DQEBBQUAA4GBAEjVn42QvEpZOB0rgy1xHHSdAXOgtpjnHMIiZiMzCo9k/5xrNw +kSHBUSy8Nh2avNlt2V+qYCZzxM7Jg4XPxIzIWpW0ksKwZmB54xD5MQqz6fl2BkAWF+hhW7XvGQM +aNU0IYOgAWHCS5ltpWJXMHlgNm4gbbtGiC4myLO79AmR51X -----END CA CERTIFICATE----- $ openssl x509 -text < [CERTIFICATE] Certificate: Data: Version: 3 (0x2) - Serial Number: 3 (0x3) + Serial Number: 4 (0x4) Signature Algorithm: sha1WithRSAEncryption - Issuer: CN=Test CA + Issuer: CN = Test Intermediate CA Validity Not Before: Jan 1 00:00:00 2017 GMT Not After : Jan 1 00:00:00 2018 GMT - Subject: CN=Test Cert + Subject: CN = Test Cert Subject Public Key Info: Public Key Algorithm: rsaEncryption Public-Key: (1024 bit) Modulus: - 00:d5:12:3f:22:6f:b0:e1:43:c5:93:b3:c3:5b:70: - 52:b2:8b:10:ec:11:c4:c4:aa:aa:43:92:c8:d0:f3: - 35:23:e3:76:2d:b4:ea:93:26:6f:6a:79:1c:64:51: - d3:4d:21:4a:73:83:35:dc:a0:16:74:db:f0:b9:a5: - 46:35:8d:53:e8:7d:37:5b:4d:ad:a3:df:d6:ae:01: - 38:ad:16:09:6e:fd:65:ad:1c:4b:48:12:1e:48:a7: - ff:5b:47:c4:c9:3b:74:85:63:1a:0a:06:b2:9f:b9: - cb:ad:dc:3f:24:8b:a4:a7:8a:13:15:45:89:24:c1: - a7:3b:c2:a2:c8:74:f1:3f:6f + 00:bc:4c:d5:b3:8d:92:fa:66:ac:32:43:1a:9e:eb: + 17:e0:aa:76:35:1b:1d:10:48:4e:3e:22:8b:75:2e: + e8:6f:a4:55:1e:0a:5e:60:c0:61:f1:7d:29:58:7e: + 0b:ef:29:be:ad:f8:f7:43:c8:58:95:14:5b:1d:af: + 4a:b8:90:9e:4e:ec:4e:b3:86:7a:b9:96:c1:34:d3: + b9:a6:57:df:9b:bd:d9:dd:67:15:54:d4:9f:65:b8: + 33:29:59:ba:9a:c6:75:ea:a5:76:3d:a4:57:0f:e2: + e4:c3:91:35:1d:6e:ff:61:7d:c2:53:23:66:b2:a8: + 0b:e1:c7:55:48:c5:2b:4d:7d Exponent: 65537 (0x10001) Signature Algorithm: sha1WithRSAEncryption - 04:21:70:de:14:92:27:13:e8:d2:b0:51:f0:af:34:75:0b:a7: - ff:84:cb:c6:96:30:80:01:f5:c1:3a:c6:81:ee:ba:89:60:33: - c3:e5:0f:43:cc:ac:81:8d:09:fb:25:e1:67:40:64:a3:ca:fd: - bd:9c:c4:73:e4:bc:4d:8e:e2:70:f1:17:ce:b4:ab:a0:b2:63: - 72:25:27:ae:d5:8e:18:73:0d:dc:12:5a:32:1c:b7:da:cd:23: - 5b:c8:87:58:08:3e:95:0c:fd:c8:48:a2:75:6e:79:f2:00:82: - 6e:b5:cc:71:e3:79:ca:68:85:9b:1b:5c:52:bf:a2:5a:71:e3: - 05:b5 + 18:bb:93:d9:2a:e0:34:69:2f:96:57:ac:55:ac:a7:83:04:b4: + bc:22:7f:5f:f7:c0:dc:ac:af:13:9b:86:7e:ac:02:8c:44:83: + 2e:c0:fa:a1:77:1d:dd:86:31:7e:98:93:c0:4f:b2:3d:be:30: + 6f:a5:fc:c7:2e:b1:b8:08:d2:17:cb:60:55:bf:5a:e0:94:f3: + 1d:44:fa:b1:2f:1a:24:c5:33:e1:d4:f0:ac:d5:2c:67:da:a7: + 5d:ee:eb:d6:7a:a7:41:e8:94:7a:34:43:b2:1f:ab:e9:cf:5d: + 25:49:56:18:d2:a9:49:1a:37:34:43:c7:06:96:4a:29:38:cc: + f2:1c -----BEGIN CERTIFICATE----- -MIIBnjCCAQegAwIBAgIBAzANBgkqhkiG9w0BAQUFADASMRAwDgYDVQQDEwdUZXN0IENBMCIYDzI -wMTcwMTAxMDAwMDAwWhgPMjAxODAxMDEwMDAwMDBaMBQxEjAQBgNVBAMTCVRlc3QgQ2VydDCBnz -ANBgkqhkiG9w0BAQEFAAOBjQAwgYkCgYEA1RI/Im+w4UPFk7PDW3BSsosQ7BHExKqqQ5LI0PM1I -+N2LbTqkyZvankcZFHTTSFKc4M13KAWdNvwuaVGNY1T6H03W02to9/WrgE4rRYJbv1lrRxLSBIe -SKf/W0fEyTt0hWMaCgayn7nLrdw/JIukp4oTFUWJJMGnO8KiyHTxP28CAwEAATANBgkqhkiG9w0 -BAQUFAAOBgQAEIXDeFJInE+jSsFHwrzR1C6f/hMvGljCAAfXBOsaB7rqJYDPD5Q9DzKyBjQn7Je -FnQGSjyv29nMRz5LxNjuJw8RfOtKugsmNyJSeu1Y4Ycw3cEloyHLfazSNbyIdYCD6VDP3ISKJ1b -nnyAIJutcxx43nKaIWbG1xSv6JaceMFtQ== +MIIBqzCCARSgAwIBAgIBBDANBgkqhkiG9w0BAQUFADAfMR0wGwYDVQQDDBRUZXN0IEludGVybWV +kaWF0ZSBDQTAiGA8yMDE3MDEwMTAwMDAwMFoYDzIwMTgwMTAxMDAwMDAwWjAUMRIwEAYDVQQDDA +lUZXN0IENlcnQwgZ8wDQYJKoZIhvcNAQEBBQADgY0AMIGJAoGBALxM1bONkvpmrDJDGp7rF+Cqd +jUbHRBITj4ii3Uu6G+kVR4KXmDAYfF9KVh+C+8pvq3490PIWJUUWx2vSriQnk7sTrOGermWwTTT +uaZX35u92d1nFVTUn2W4MylZuprGdeqldj2kVw/i5MORNR1u/2F9wlMjZrKoC+HHVUjFK019AgM +BAAEwDQYJKoZIhvcNAQEFBQADgYEAGLuT2SrgNGkvllesVayngwS0vCJ/X/fA3KyvE5uGfqwCjE +SDLsD6oXcd3YYxfpiTwE+yPb4wb6X8xy6xuAjSF8tgVb9a4JTzHUT6sS8aJMUz4dTwrNUsZ9qnX +e7r1nqnQeiUejRDsh+r6c9dJUlWGNKpSRo3NEPHBpZKKTjM8hw= -----END CERTIFICATE----- $ openssl asn1parse -i < [OCSP REQUEST] @@ -133,10 +133,10 @@ 10:d=5 hl=2 l= 9 cons: SEQUENCE 12:d=6 hl=2 l= 5 prim: OBJECT :sha1 19:d=6 hl=2 l= 0 prim: NULL - 21:d=5 hl=2 l= 20 prim: OCTET STRING [HEX DUMP]:02FF75DA24DE8ADD150FAB689DCCE6E6636D0901 - 43:d=5 hl=2 l= 20 prim: OCTET STRING [HEX DUMP]:84E1BA52A25C543CA972491224BC8B1ECA8B9FF4 - 65:d=5 hl=2 l= 1 prim: INTEGER :03 + 21:d=5 hl=2 l= 20 prim: OCTET STRING [HEX DUMP]:449B1C5B31C6E9990966523E49C3F773C024190A + 43:d=5 hl=2 l= 20 prim: OCTET STRING [HEX DUMP]:FC6D3387CC3B39B049C755C46DF4395548930BCE + 65:d=5 hl=2 l= 1 prim: INTEGER :04 -----BEGIN OCSP REQUEST----- -MEIwQDA+MDwwOjAJBgUrDgMCGgUABBQC/3XaJN6K3RUPq2idzObmY20JAQQUhOG6UqJcVDypckk -SJLyLHsqLn/QCAQM= +MEIwQDA+MDwwOjAJBgUrDgMCGgUABBREmxxbMcbpmQlmUj5Jw/dzwCQZCgQU/G0zh8w7ObBJx1X +EbfQ5VUiTC84CAQQ= -----END OCSP REQUEST-----
diff --git a/net/data/ocsp_unittest/responder_name.pem b/net/data/ocsp_unittest/responder_name.pem index 8167a2c..b98bcc7 100644 --- a/net/data/ocsp_unittest/responder_name.pem +++ b/net/data/ocsp_unittest/responder_name.pem
@@ -5,123 +5,123 @@ OCSP Response Status: successful (0x0) Response Type: Basic OCSP Response Version: 1 (0x0) - Responder Id: CN = Test CA + Responder Id: CN = Test Intermediate CA Produced At: Mar 2 00:00:00 2017 GMT Responses: Certificate ID: Hash Algorithm: sha1 - Issuer Name Hash: 02FF75DA24DE8ADD150FAB689DCCE6E6636D0901 - Issuer Key Hash: 84E1BA52A25C543CA972491224BC8B1ECA8B9FF4 - Serial Number: 03 + Issuer Name Hash: 449B1C5B31C6E9990966523E49C3F773C024190A + Issuer Key Hash: FC6D3387CC3B39B049C755C46DF4395548930BCE + Serial Number: 04 Cert Status: good This Update: Mar 1 00:00:00 2017 GMT Signature Algorithm: sha1WithRSAEncryption - 0e:82:91:8d:92:af:45:cb:98:e8:0e:08:04:15:97:9a:3a:cf: - cc:72:ee:cd:b7:3e:b0:40:b5:fd:8d:7d:6c:2f:4a:a6:32:9e: - 37:3b:7f:d3:ef:89:9e:8d:34:c2:45:1b:9b:99:4d:ed:e3:9a: - 94:62:17:59:4b:3a:be:f8:c0:a7:98:bd:e0:69:8f:98:47:e9: - 76:25:d3:1f:94:53:d7:c2:db:56:a2:aa:e3:6b:19:38:97:33: - a7:b6:45:6e:52:69:2c:62:6e:98:b6:d8:75:00:0c:16:c9:8b: - 84:41:f4:99:3e:a9:0c:a7:d4:98:51:45:89:4c:e2:c2:8e:5b: - e8:26 + 9b:7c:bb:20:00:86:92:61:6d:8f:6d:70:87:52:1b:ac:d5:0a: + 97:ce:76:7b:c4:b4:a7:a8:1d:ea:2c:15:cc:d4:2e:7d:a2:8c: + 53:4a:82:06:4a:b6:e2:d9:9b:aa:c4:63:66:94:7a:71:ba:d9: + 4e:bc:90:11:56:75:56:aa:7c:34:73:1d:ad:1c:1b:a6:28:81: + ea:f9:a0:85:e6:4f:07:2e:43:63:49:1e:8f:78:b6:96:f4:8b: + 4d:7f:58:b2:86:18:45:3a:72:5e:7f:d5:f5:f0:66:83:58:92: + 03:4d:e2:1d:af:99:2a:f4:c9:10:24:a8:c7:87:16:7f:b9:76: + b1:ba -----BEGIN OCSP RESPONSE----- -MIIBKwoBAKCCASQwggEgBgkrBgEFBQcwAQEEggERMIIBDTB4oRQwEjEQMA4GA1UEAxMHVGVzdCB -DQRgPMjAxNzAzMDIwMDAwMDBaME8wTTA4MAcGBSsOAwIaBBQC/3XaJN6K3RUPq2idzObmY20JAQ -QUhOG6UqJcVDypckkSJLyLHsqLn/QCAQOAABgPMjAxNzAzMDEwMDAwMDBaMA0GCSqGSIb3DQEBB -QUAA4GBAA6CkY2Sr0XLmOgOCAQVl5o6z8xy7s23PrBAtf2NfWwvSqYynjc7f9PviZ6NNMJFG5uZ -Te3jmpRiF1lLOr74wKeYveBpj5hH6XYl0x+UU9fC21aiquNrGTiXM6e2RW5SaSxibpi22HUADBb -Ji4RB9Jk+qQyn1JhRRYlM4sKOW+gm +MIIBOQoBAKCCATIwggEuBgkrBgEFBQcwAQEEggEfMIIBGzCBhaEhMB8xHTAbBgNVBAMMFFRlc3Q +gSW50ZXJtZWRpYXRlIENBGA8yMDE3MDMwMjAwMDAwMFowTzBNMDgwBwYFKw4DAhoEFESbHFsxxu +mZCWZSPknD93PAJBkKBBT8bTOHzDs5sEnHVcRt9DlVSJMLzgIBBIAAGA8yMDE3MDMwMTAwMDAwM +FowDQYJKoZIhvcNAQEFBQADgYEAm3y7IACGkmFtj21wh1IbrNUKl852e8S0p6gd6iwVzNQufaKM +U0qCBkq24tmbqsRjZpR6cbrZTryQEVZ1Vqp8NHMdrRwbpiiB6vmgheZPBy5DY0kej3i2lvSLTX9 +YsoYYRTpyXn/V9fBmg1iSA03iHa+ZKvTJECSox4cWf7l2sbo= -----END OCSP RESPONSE----- $ openssl x509 -text < [CA CERTIFICATE] Certificate: Data: Version: 3 (0x2) - Serial Number: 0 (0x0) + Serial Number: 1 (0x1) Signature Algorithm: sha1WithRSAEncryption - Issuer: CN=Test CA + Issuer: CN = Test CA Validity Not Before: Jan 1 00:00:00 2017 GMT Not After : Jan 1 00:00:00 2018 GMT - Subject: CN=Test CA + Subject: CN = Test Intermediate CA Subject Public Key Info: Public Key Algorithm: rsaEncryption Public-Key: (1024 bit) Modulus: - 00:b8:25:2b:ee:59:9a:9d:bc:b4:48:ae:09:ce:0d: - ba:c5:83:57:03:92:fd:52:32:55:f5:e4:2e:a6:cf: - 9e:4b:c4:10:af:24:da:d5:dd:44:a8:d6:28:38:9c: - a5:11:c9:0b:70:a1:b5:71:cf:a4:35:c2:6a:17:b1: - b5:c7:cf:74:83:ac:7a:d5:3b:12:66:74:f2:4b:15: - b0:c2:59:af:0c:78:2c:42:3c:3f:8b:83:b3:1d:9a: - c8:bc:ce:b0:c8:f2:1a:a8:0a:1c:bb:6e:6e:d4:c6: - 10:66:3c:a8:ec:e3:c4:63:40:f6:79:ec:8b:14:ff: - 85:9e:2d:1a:e7:e8:31:56:81 + 00:b9:32:09:de:33:4a:4f:e2:04:73:49:d5:2e:2b: + 83:92:3a:94:e4:1b:0c:27:1b:f8:43:83:17:b8:75: + f5:a4:af:e3:4c:84:3e:6c:48:79:76:df:4d:f5:39: + af:92:4b:c5:a0:86:ab:35:cc:19:6b:93:82:c0:f8: + 44:4d:1a:14:5d:48:87:65:02:0e:b0:a8:96:d9:06: + 19:3f:aa:85:2d:84:c0:78:19:a6:96:ab:26:56:f7: + 6f:5a:1a:97:a2:01:88:00:99:10:8a:97:39:c8:22: + 6e:de:e5:56:f4:a6:23:cd:ea:48:0e:65:67:a4:73: + a0:50:91:de:ba:cf:54:08:8f Exponent: 65537 (0x10001) Signature Algorithm: sha1WithRSAEncryption - 35:fe:ee:96:31:c7:3d:91:eb:22:53:1f:bf:cc:20:cc:aa:f4: - 04:92:3c:8b:50:06:ea:a1:cc:b7:c2:4a:d6:02:af:53:a7:a4: - 71:81:78:bc:95:f3:2d:46:c4:83:4c:d5:92:11:7c:c7:67:d3: - 47:f6:06:9f:1c:46:da:d6:20:72:47:c2:57:d7:fb:66:d3:35: - 82:07:61:13:4e:4d:e6:0c:93:e6:f3:be:98:ff:e8:de:60:a7: - 06:94:cd:bb:f5:6e:b3:4e:0b:d6:e9:2b:72:bd:6e:ae:86:23: - 2d:44:33:c4:3b:a7:52:12:46:d2:76:95:06:3e:69:0f:72:60: - 16:d6 + 48:d5:9f:8d:90:bc:4a:59:38:1d:2b:83:2d:71:1c:74:9d:01: + 73:a0:b6:98:e7:1c:c2:22:66:23:33:0a:8f:64:ff:9c:6b:37: + 09:12:1c:15:12:cb:c3:61:d9:ab:cd:96:dd:95:fa:a6:02:67: + 3c:4c:ec:98:38:5c:fc:48:cc:85:a9:5b:49:2c:2b:06:66:07: + 9e:31:0f:93:10:ab:3e:9f:97:60:64:01:61:7e:86:15:bb:5e: + f1:90:31:a3:54:d0:86:0e:80:05:87:09:2e:65:b6:95:89:5c: + c1:e5:80:d9:b8:81:b6:ed:1a:20:b8:9b:22:ce:ef:d0:26:47: + 9d:57 -----BEGIN CA CERTIFICATE----- -MIIBnDCCAQWgAwIBAgIBADANBgkqhkiG9w0BAQUFADASMRAwDgYDVQQDEwdUZXN0IENBMCIYDzI -wMTcwMTAxMDAwMDAwWhgPMjAxODAxMDEwMDAwMDBaMBIxEDAOBgNVBAMTB1Rlc3QgQ0EwgZ8wDQ -YJKoZIhvcNAQEBBQADgY0AMIGJAoGBALglK+5Zmp28tEiuCc4NusWDVwOS/VIyVfXkLqbPnkvEE -K8k2tXdRKjWKDicpRHJC3ChtXHPpDXCahextcfPdIOsetU7EmZ08ksVsMJZrwx4LEI8P4uDsx2a -yLzOsMjyGqgKHLtubtTGEGY8qOzjxGNA9nnsixT/hZ4tGufoMVaBAgMBAAEwDQYJKoZIhvcNAQE -FBQADgYEANf7uljHHPZHrIlMfv8wgzKr0BJI8i1AG6qHMt8JK1gKvU6ekcYF4vJXzLUbEg0zVkh -F8x2fTR/YGnxxG2tYgckfCV9f7ZtM1ggdhE05N5gyT5vO+mP/o3mCnBpTNu/Vus04L1ukrcr1ur -oYjLUQzxDunUhJG0naVBj5pD3JgFtY= +MIIBqTCCARKgAwIBAgIBATANBgkqhkiG9w0BAQUFADASMRAwDgYDVQQDDAdUZXN0IENBMCIYDzI +wMTcwMTAxMDAwMDAwWhgPMjAxODAxMDEwMDAwMDBaMB8xHTAbBgNVBAMMFFRlc3QgSW50ZXJtZW +RpYXRlIENBMIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQC5MgneM0pP4gRzSdUuK4OSOpTkG +wwnG/hDgxe4dfWkr+NMhD5sSHl23031Oa+SS8Wghqs1zBlrk4LA+ERNGhRdSIdlAg6wqJbZBhk/ +qoUthMB4GaaWqyZW929aGpeiAYgAmRCKlznIIm7e5Vb0piPN6kgOZWekc6BQkd66z1QIjwIDAQA +BMA0GCSqGSIb3DQEBBQUAA4GBAEjVn42QvEpZOB0rgy1xHHSdAXOgtpjnHMIiZiMzCo9k/5xrNw +kSHBUSy8Nh2avNlt2V+qYCZzxM7Jg4XPxIzIWpW0ksKwZmB54xD5MQqz6fl2BkAWF+hhW7XvGQM +aNU0IYOgAWHCS5ltpWJXMHlgNm4gbbtGiC4myLO79AmR51X -----END CA CERTIFICATE----- $ openssl x509 -text < [CERTIFICATE] Certificate: Data: Version: 3 (0x2) - Serial Number: 3 (0x3) + Serial Number: 4 (0x4) Signature Algorithm: sha1WithRSAEncryption - Issuer: CN=Test CA + Issuer: CN = Test Intermediate CA Validity Not Before: Jan 1 00:00:00 2017 GMT Not After : Jan 1 00:00:00 2018 GMT - Subject: CN=Test Cert + Subject: CN = Test Cert Subject Public Key Info: Public Key Algorithm: rsaEncryption Public-Key: (1024 bit) Modulus: - 00:d5:12:3f:22:6f:b0:e1:43:c5:93:b3:c3:5b:70: - 52:b2:8b:10:ec:11:c4:c4:aa:aa:43:92:c8:d0:f3: - 35:23:e3:76:2d:b4:ea:93:26:6f:6a:79:1c:64:51: - d3:4d:21:4a:73:83:35:dc:a0:16:74:db:f0:b9:a5: - 46:35:8d:53:e8:7d:37:5b:4d:ad:a3:df:d6:ae:01: - 38:ad:16:09:6e:fd:65:ad:1c:4b:48:12:1e:48:a7: - ff:5b:47:c4:c9:3b:74:85:63:1a:0a:06:b2:9f:b9: - cb:ad:dc:3f:24:8b:a4:a7:8a:13:15:45:89:24:c1: - a7:3b:c2:a2:c8:74:f1:3f:6f + 00:bc:4c:d5:b3:8d:92:fa:66:ac:32:43:1a:9e:eb: + 17:e0:aa:76:35:1b:1d:10:48:4e:3e:22:8b:75:2e: + e8:6f:a4:55:1e:0a:5e:60:c0:61:f1:7d:29:58:7e: + 0b:ef:29:be:ad:f8:f7:43:c8:58:95:14:5b:1d:af: + 4a:b8:90:9e:4e:ec:4e:b3:86:7a:b9:96:c1:34:d3: + b9:a6:57:df:9b:bd:d9:dd:67:15:54:d4:9f:65:b8: + 33:29:59:ba:9a:c6:75:ea:a5:76:3d:a4:57:0f:e2: + e4:c3:91:35:1d:6e:ff:61:7d:c2:53:23:66:b2:a8: + 0b:e1:c7:55:48:c5:2b:4d:7d Exponent: 65537 (0x10001) Signature Algorithm: sha1WithRSAEncryption - 04:21:70:de:14:92:27:13:e8:d2:b0:51:f0:af:34:75:0b:a7: - ff:84:cb:c6:96:30:80:01:f5:c1:3a:c6:81:ee:ba:89:60:33: - c3:e5:0f:43:cc:ac:81:8d:09:fb:25:e1:67:40:64:a3:ca:fd: - bd:9c:c4:73:e4:bc:4d:8e:e2:70:f1:17:ce:b4:ab:a0:b2:63: - 72:25:27:ae:d5:8e:18:73:0d:dc:12:5a:32:1c:b7:da:cd:23: - 5b:c8:87:58:08:3e:95:0c:fd:c8:48:a2:75:6e:79:f2:00:82: - 6e:b5:cc:71:e3:79:ca:68:85:9b:1b:5c:52:bf:a2:5a:71:e3: - 05:b5 + 18:bb:93:d9:2a:e0:34:69:2f:96:57:ac:55:ac:a7:83:04:b4: + bc:22:7f:5f:f7:c0:dc:ac:af:13:9b:86:7e:ac:02:8c:44:83: + 2e:c0:fa:a1:77:1d:dd:86:31:7e:98:93:c0:4f:b2:3d:be:30: + 6f:a5:fc:c7:2e:b1:b8:08:d2:17:cb:60:55:bf:5a:e0:94:f3: + 1d:44:fa:b1:2f:1a:24:c5:33:e1:d4:f0:ac:d5:2c:67:da:a7: + 5d:ee:eb:d6:7a:a7:41:e8:94:7a:34:43:b2:1f:ab:e9:cf:5d: + 25:49:56:18:d2:a9:49:1a:37:34:43:c7:06:96:4a:29:38:cc: + f2:1c -----BEGIN CERTIFICATE----- -MIIBnjCCAQegAwIBAgIBAzANBgkqhkiG9w0BAQUFADASMRAwDgYDVQQDEwdUZXN0IENBMCIYDzI -wMTcwMTAxMDAwMDAwWhgPMjAxODAxMDEwMDAwMDBaMBQxEjAQBgNVBAMTCVRlc3QgQ2VydDCBnz -ANBgkqhkiG9w0BAQEFAAOBjQAwgYkCgYEA1RI/Im+w4UPFk7PDW3BSsosQ7BHExKqqQ5LI0PM1I -+N2LbTqkyZvankcZFHTTSFKc4M13KAWdNvwuaVGNY1T6H03W02to9/WrgE4rRYJbv1lrRxLSBIe -SKf/W0fEyTt0hWMaCgayn7nLrdw/JIukp4oTFUWJJMGnO8KiyHTxP28CAwEAATANBgkqhkiG9w0 -BAQUFAAOBgQAEIXDeFJInE+jSsFHwrzR1C6f/hMvGljCAAfXBOsaB7rqJYDPD5Q9DzKyBjQn7Je -FnQGSjyv29nMRz5LxNjuJw8RfOtKugsmNyJSeu1Y4Ycw3cEloyHLfazSNbyIdYCD6VDP3ISKJ1b -nnyAIJutcxx43nKaIWbG1xSv6JaceMFtQ== +MIIBqzCCARSgAwIBAgIBBDANBgkqhkiG9w0BAQUFADAfMR0wGwYDVQQDDBRUZXN0IEludGVybWV +kaWF0ZSBDQTAiGA8yMDE3MDEwMTAwMDAwMFoYDzIwMTgwMTAxMDAwMDAwWjAUMRIwEAYDVQQDDA +lUZXN0IENlcnQwgZ8wDQYJKoZIhvcNAQEBBQADgY0AMIGJAoGBALxM1bONkvpmrDJDGp7rF+Cqd +jUbHRBITj4ii3Uu6G+kVR4KXmDAYfF9KVh+C+8pvq3490PIWJUUWx2vSriQnk7sTrOGermWwTTT +uaZX35u92d1nFVTUn2W4MylZuprGdeqldj2kVw/i5MORNR1u/2F9wlMjZrKoC+HHVUjFK019AgM +BAAEwDQYJKoZIhvcNAQEFBQADgYEAGLuT2SrgNGkvllesVayngwS0vCJ/X/fA3KyvE5uGfqwCjE +SDLsD6oXcd3YYxfpiTwE+yPb4wb6X8xy6xuAjSF8tgVb9a4JTzHUT6sS8aJMUz4dTwrNUsZ9qnX +e7r1nqnQeiUejRDsh+r6c9dJUlWGNKpSRo3NEPHBpZKKTjM8hw= -----END CERTIFICATE----- $ openssl asn1parse -i < [OCSP REQUEST] @@ -133,10 +133,10 @@ 10:d=5 hl=2 l= 9 cons: SEQUENCE 12:d=6 hl=2 l= 5 prim: OBJECT :sha1 19:d=6 hl=2 l= 0 prim: NULL - 21:d=5 hl=2 l= 20 prim: OCTET STRING [HEX DUMP]:02FF75DA24DE8ADD150FAB689DCCE6E6636D0901 - 43:d=5 hl=2 l= 20 prim: OCTET STRING [HEX DUMP]:84E1BA52A25C543CA972491224BC8B1ECA8B9FF4 - 65:d=5 hl=2 l= 1 prim: INTEGER :03 + 21:d=5 hl=2 l= 20 prim: OCTET STRING [HEX DUMP]:449B1C5B31C6E9990966523E49C3F773C024190A + 43:d=5 hl=2 l= 20 prim: OCTET STRING [HEX DUMP]:FC6D3387CC3B39B049C755C46DF4395548930BCE + 65:d=5 hl=2 l= 1 prim: INTEGER :04 -----BEGIN OCSP REQUEST----- -MEIwQDA+MDwwOjAJBgUrDgMCGgUABBQC/3XaJN6K3RUPq2idzObmY20JAQQUhOG6UqJcVDypckk -SJLyLHsqLn/QCAQM= +MEIwQDA+MDwwOjAJBgUrDgMCGgUABBREmxxbMcbpmQlmUj5Jw/dzwCQZCgQU/G0zh8w7ObBJx1X +EbfQ5VUiTC84CAQQ= -----END OCSP REQUEST-----
diff --git a/net/data/ocsp_unittest/revoke_response.pem b/net/data/ocsp_unittest/revoke_response.pem index 1c516e91..4f4a52c 100644 --- a/net/data/ocsp_unittest/revoke_response.pem +++ b/net/data/ocsp_unittest/revoke_response.pem
@@ -5,124 +5,124 @@ OCSP Response Status: successful (0x0) Response Type: Basic OCSP Response Version: 1 (0x0) - Responder Id: CN = Test CA + Responder Id: CN = Test Intermediate CA Produced At: Mar 2 00:00:00 2017 GMT Responses: Certificate ID: Hash Algorithm: sha1 - Issuer Name Hash: 02FF75DA24DE8ADD150FAB689DCCE6E6636D0901 - Issuer Key Hash: 84E1BA52A25C543CA972491224BC8B1ECA8B9FF4 - Serial Number: 03 + Issuer Name Hash: 449B1C5B31C6E9990966523E49C3F773C024190A + Issuer Key Hash: FC6D3387CC3B39B049C755C46DF4395548930BCE + Serial Number: 04 Cert Status: revoked Revocation Time: Feb 1 00:00:00 2017 GMT This Update: Mar 1 00:00:00 2017 GMT Signature Algorithm: sha1WithRSAEncryption - 1d:ee:f6:9e:f8:1f:be:4a:3e:bd:7a:a7:22:19:c3:14:1c:77: - 07:b2:31:ce:b2:09:12:fc:e6:3c:81:9a:a2:18:5d:f2:f1:24: - 4f:15:3f:69:3b:d7:ca:29:8a:98:a8:90:77:c8:be:2f:7b:25: - d5:6c:e4:8f:3b:c6:5a:f4:73:be:01:08:b4:19:95:f7:9d:27: - ec:3c:c3:2c:1f:ee:c9:aa:d9:01:0a:e3:a8:15:56:c9:30:1f: - ba:7d:28:2f:60:67:be:4d:96:6d:0c:03:de:e1:34:03:3f:08: - a6:ea:18:d8:15:9c:80:27:85:0e:05:f1:b7:0f:10:57:4d:12: - 71:52 + 7f:1c:3d:59:76:22:2f:6b:f9:53:63:8b:b7:be:f4:50:30:60: + a6:41:fb:1e:2e:30:9d:cb:fa:1a:1a:55:7b:50:62:6e:0b:33: + 7f:7f:d2:3d:a2:23:87:57:f8:53:5e:ca:1c:ac:98:8e:a9:77: + 28:a2:6f:f9:e7:d4:9d:c6:ee:62:35:b2:3a:91:6e:8e:12:a1: + 97:06:46:42:e3:84:7e:f1:73:97:d4:03:2f:d6:3b:39:c0:ef: + 8d:15:ea:94:4e:1e:2e:6d:cf:a1:f9:35:b9:48:2f:26:17:79: + bd:7a:b4:83:4e:dc:43:e9:4b:c9:64:f0:4f:3d:fc:d9:3d:2a: + 16:7f -----BEGIN OCSP RESPONSE----- -MIIBPQoBAKCCATYwggEyBgkrBgEFBQcwAQEEggEjMIIBHzCBiaEUMBIxEDAOBgNVBAMTB1Rlc3Q -gQ0EYDzIwMTcwMzAyMDAwMDAwWjBgMF4wODAHBgUrDgMCGgQUAv912iTeit0VD6tonczm5mNtCQ -EEFIThulKiXFQ8qXJJEiS8ix7Ki5/0AgEDoREYDzIwMTcwMjAxMDAwMDAwWhgPMjAxNzAzMDEwM -DAwMDBaMA0GCSqGSIb3DQEBBQUAA4GBAB3u9p74H75KPr16pyIZwxQcdweyMc6yCRL85jyBmqIY -XfLxJE8VP2k718opipiokHfIvi97JdVs5I87xlr0c74BCLQZlfedJ+w8wywf7smq2QEK46gVVsk -wH7p9KC9gZ75Nlm0MA97hNAM/CKbqGNgVnIAnhQ4F8bcPEFdNEnFS +MIIBSgoBAKCCAUMwggE/BgkrBgEFBQcwAQEEggEwMIIBLDCBlqEhMB8xHTAbBgNVBAMMFFRlc3Q +gSW50ZXJtZWRpYXRlIENBGA8yMDE3MDMwMjAwMDAwMFowYDBeMDgwBwYFKw4DAhoEFESbHFsxxu +mZCWZSPknD93PAJBkKBBT8bTOHzDs5sEnHVcRt9DlVSJMLzgIBBKERGA8yMDE3MDIwMTAwMDAwM +FoYDzIwMTcwMzAxMDAwMDAwWjANBgkqhkiG9w0BAQUFAAOBgQB/HD1ZdiIva/lTY4u3vvRQMGCm +QfseLjCdy/oaGlV7UGJuCzN/f9I9oiOHV/hTXsocrJiOqXcoom/559Sdxu5iNbI6kW6OEqGXBkZ +C44R+8XOX1AMv1js5wO+NFeqUTh4ubc+h+TW5SC8mF3m9erSDTtxD6UvJZPBPPfzZPSoWfw== -----END OCSP RESPONSE----- $ openssl x509 -text < [CA CERTIFICATE] Certificate: Data: Version: 3 (0x2) - Serial Number: 0 (0x0) + Serial Number: 1 (0x1) Signature Algorithm: sha1WithRSAEncryption - Issuer: CN=Test CA + Issuer: CN = Test CA Validity Not Before: Jan 1 00:00:00 2017 GMT Not After : Jan 1 00:00:00 2018 GMT - Subject: CN=Test CA + Subject: CN = Test Intermediate CA Subject Public Key Info: Public Key Algorithm: rsaEncryption Public-Key: (1024 bit) Modulus: - 00:b8:25:2b:ee:59:9a:9d:bc:b4:48:ae:09:ce:0d: - ba:c5:83:57:03:92:fd:52:32:55:f5:e4:2e:a6:cf: - 9e:4b:c4:10:af:24:da:d5:dd:44:a8:d6:28:38:9c: - a5:11:c9:0b:70:a1:b5:71:cf:a4:35:c2:6a:17:b1: - b5:c7:cf:74:83:ac:7a:d5:3b:12:66:74:f2:4b:15: - b0:c2:59:af:0c:78:2c:42:3c:3f:8b:83:b3:1d:9a: - c8:bc:ce:b0:c8:f2:1a:a8:0a:1c:bb:6e:6e:d4:c6: - 10:66:3c:a8:ec:e3:c4:63:40:f6:79:ec:8b:14:ff: - 85:9e:2d:1a:e7:e8:31:56:81 + 00:b9:32:09:de:33:4a:4f:e2:04:73:49:d5:2e:2b: + 83:92:3a:94:e4:1b:0c:27:1b:f8:43:83:17:b8:75: + f5:a4:af:e3:4c:84:3e:6c:48:79:76:df:4d:f5:39: + af:92:4b:c5:a0:86:ab:35:cc:19:6b:93:82:c0:f8: + 44:4d:1a:14:5d:48:87:65:02:0e:b0:a8:96:d9:06: + 19:3f:aa:85:2d:84:c0:78:19:a6:96:ab:26:56:f7: + 6f:5a:1a:97:a2:01:88:00:99:10:8a:97:39:c8:22: + 6e:de:e5:56:f4:a6:23:cd:ea:48:0e:65:67:a4:73: + a0:50:91:de:ba:cf:54:08:8f Exponent: 65537 (0x10001) Signature Algorithm: sha1WithRSAEncryption - 35:fe:ee:96:31:c7:3d:91:eb:22:53:1f:bf:cc:20:cc:aa:f4: - 04:92:3c:8b:50:06:ea:a1:cc:b7:c2:4a:d6:02:af:53:a7:a4: - 71:81:78:bc:95:f3:2d:46:c4:83:4c:d5:92:11:7c:c7:67:d3: - 47:f6:06:9f:1c:46:da:d6:20:72:47:c2:57:d7:fb:66:d3:35: - 82:07:61:13:4e:4d:e6:0c:93:e6:f3:be:98:ff:e8:de:60:a7: - 06:94:cd:bb:f5:6e:b3:4e:0b:d6:e9:2b:72:bd:6e:ae:86:23: - 2d:44:33:c4:3b:a7:52:12:46:d2:76:95:06:3e:69:0f:72:60: - 16:d6 + 48:d5:9f:8d:90:bc:4a:59:38:1d:2b:83:2d:71:1c:74:9d:01: + 73:a0:b6:98:e7:1c:c2:22:66:23:33:0a:8f:64:ff:9c:6b:37: + 09:12:1c:15:12:cb:c3:61:d9:ab:cd:96:dd:95:fa:a6:02:67: + 3c:4c:ec:98:38:5c:fc:48:cc:85:a9:5b:49:2c:2b:06:66:07: + 9e:31:0f:93:10:ab:3e:9f:97:60:64:01:61:7e:86:15:bb:5e: + f1:90:31:a3:54:d0:86:0e:80:05:87:09:2e:65:b6:95:89:5c: + c1:e5:80:d9:b8:81:b6:ed:1a:20:b8:9b:22:ce:ef:d0:26:47: + 9d:57 -----BEGIN CA CERTIFICATE----- -MIIBnDCCAQWgAwIBAgIBADANBgkqhkiG9w0BAQUFADASMRAwDgYDVQQDEwdUZXN0IENBMCIYDzI -wMTcwMTAxMDAwMDAwWhgPMjAxODAxMDEwMDAwMDBaMBIxEDAOBgNVBAMTB1Rlc3QgQ0EwgZ8wDQ -YJKoZIhvcNAQEBBQADgY0AMIGJAoGBALglK+5Zmp28tEiuCc4NusWDVwOS/VIyVfXkLqbPnkvEE -K8k2tXdRKjWKDicpRHJC3ChtXHPpDXCahextcfPdIOsetU7EmZ08ksVsMJZrwx4LEI8P4uDsx2a -yLzOsMjyGqgKHLtubtTGEGY8qOzjxGNA9nnsixT/hZ4tGufoMVaBAgMBAAEwDQYJKoZIhvcNAQE -FBQADgYEANf7uljHHPZHrIlMfv8wgzKr0BJI8i1AG6qHMt8JK1gKvU6ekcYF4vJXzLUbEg0zVkh -F8x2fTR/YGnxxG2tYgckfCV9f7ZtM1ggdhE05N5gyT5vO+mP/o3mCnBpTNu/Vus04L1ukrcr1ur -oYjLUQzxDunUhJG0naVBj5pD3JgFtY= +MIIBqTCCARKgAwIBAgIBATANBgkqhkiG9w0BAQUFADASMRAwDgYDVQQDDAdUZXN0IENBMCIYDzI +wMTcwMTAxMDAwMDAwWhgPMjAxODAxMDEwMDAwMDBaMB8xHTAbBgNVBAMMFFRlc3QgSW50ZXJtZW +RpYXRlIENBMIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQC5MgneM0pP4gRzSdUuK4OSOpTkG +wwnG/hDgxe4dfWkr+NMhD5sSHl23031Oa+SS8Wghqs1zBlrk4LA+ERNGhRdSIdlAg6wqJbZBhk/ +qoUthMB4GaaWqyZW929aGpeiAYgAmRCKlznIIm7e5Vb0piPN6kgOZWekc6BQkd66z1QIjwIDAQA +BMA0GCSqGSIb3DQEBBQUAA4GBAEjVn42QvEpZOB0rgy1xHHSdAXOgtpjnHMIiZiMzCo9k/5xrNw +kSHBUSy8Nh2avNlt2V+qYCZzxM7Jg4XPxIzIWpW0ksKwZmB54xD5MQqz6fl2BkAWF+hhW7XvGQM +aNU0IYOgAWHCS5ltpWJXMHlgNm4gbbtGiC4myLO79AmR51X -----END CA CERTIFICATE----- $ openssl x509 -text < [CERTIFICATE] Certificate: Data: Version: 3 (0x2) - Serial Number: 3 (0x3) + Serial Number: 4 (0x4) Signature Algorithm: sha1WithRSAEncryption - Issuer: CN=Test CA + Issuer: CN = Test Intermediate CA Validity Not Before: Jan 1 00:00:00 2017 GMT Not After : Jan 1 00:00:00 2018 GMT - Subject: CN=Test Cert + Subject: CN = Test Cert Subject Public Key Info: Public Key Algorithm: rsaEncryption Public-Key: (1024 bit) Modulus: - 00:d5:12:3f:22:6f:b0:e1:43:c5:93:b3:c3:5b:70: - 52:b2:8b:10:ec:11:c4:c4:aa:aa:43:92:c8:d0:f3: - 35:23:e3:76:2d:b4:ea:93:26:6f:6a:79:1c:64:51: - d3:4d:21:4a:73:83:35:dc:a0:16:74:db:f0:b9:a5: - 46:35:8d:53:e8:7d:37:5b:4d:ad:a3:df:d6:ae:01: - 38:ad:16:09:6e:fd:65:ad:1c:4b:48:12:1e:48:a7: - ff:5b:47:c4:c9:3b:74:85:63:1a:0a:06:b2:9f:b9: - cb:ad:dc:3f:24:8b:a4:a7:8a:13:15:45:89:24:c1: - a7:3b:c2:a2:c8:74:f1:3f:6f + 00:bc:4c:d5:b3:8d:92:fa:66:ac:32:43:1a:9e:eb: + 17:e0:aa:76:35:1b:1d:10:48:4e:3e:22:8b:75:2e: + e8:6f:a4:55:1e:0a:5e:60:c0:61:f1:7d:29:58:7e: + 0b:ef:29:be:ad:f8:f7:43:c8:58:95:14:5b:1d:af: + 4a:b8:90:9e:4e:ec:4e:b3:86:7a:b9:96:c1:34:d3: + b9:a6:57:df:9b:bd:d9:dd:67:15:54:d4:9f:65:b8: + 33:29:59:ba:9a:c6:75:ea:a5:76:3d:a4:57:0f:e2: + e4:c3:91:35:1d:6e:ff:61:7d:c2:53:23:66:b2:a8: + 0b:e1:c7:55:48:c5:2b:4d:7d Exponent: 65537 (0x10001) Signature Algorithm: sha1WithRSAEncryption - 04:21:70:de:14:92:27:13:e8:d2:b0:51:f0:af:34:75:0b:a7: - ff:84:cb:c6:96:30:80:01:f5:c1:3a:c6:81:ee:ba:89:60:33: - c3:e5:0f:43:cc:ac:81:8d:09:fb:25:e1:67:40:64:a3:ca:fd: - bd:9c:c4:73:e4:bc:4d:8e:e2:70:f1:17:ce:b4:ab:a0:b2:63: - 72:25:27:ae:d5:8e:18:73:0d:dc:12:5a:32:1c:b7:da:cd:23: - 5b:c8:87:58:08:3e:95:0c:fd:c8:48:a2:75:6e:79:f2:00:82: - 6e:b5:cc:71:e3:79:ca:68:85:9b:1b:5c:52:bf:a2:5a:71:e3: - 05:b5 + 18:bb:93:d9:2a:e0:34:69:2f:96:57:ac:55:ac:a7:83:04:b4: + bc:22:7f:5f:f7:c0:dc:ac:af:13:9b:86:7e:ac:02:8c:44:83: + 2e:c0:fa:a1:77:1d:dd:86:31:7e:98:93:c0:4f:b2:3d:be:30: + 6f:a5:fc:c7:2e:b1:b8:08:d2:17:cb:60:55:bf:5a:e0:94:f3: + 1d:44:fa:b1:2f:1a:24:c5:33:e1:d4:f0:ac:d5:2c:67:da:a7: + 5d:ee:eb:d6:7a:a7:41:e8:94:7a:34:43:b2:1f:ab:e9:cf:5d: + 25:49:56:18:d2:a9:49:1a:37:34:43:c7:06:96:4a:29:38:cc: + f2:1c -----BEGIN CERTIFICATE----- -MIIBnjCCAQegAwIBAgIBAzANBgkqhkiG9w0BAQUFADASMRAwDgYDVQQDEwdUZXN0IENBMCIYDzI -wMTcwMTAxMDAwMDAwWhgPMjAxODAxMDEwMDAwMDBaMBQxEjAQBgNVBAMTCVRlc3QgQ2VydDCBnz -ANBgkqhkiG9w0BAQEFAAOBjQAwgYkCgYEA1RI/Im+w4UPFk7PDW3BSsosQ7BHExKqqQ5LI0PM1I -+N2LbTqkyZvankcZFHTTSFKc4M13KAWdNvwuaVGNY1T6H03W02to9/WrgE4rRYJbv1lrRxLSBIe -SKf/W0fEyTt0hWMaCgayn7nLrdw/JIukp4oTFUWJJMGnO8KiyHTxP28CAwEAATANBgkqhkiG9w0 -BAQUFAAOBgQAEIXDeFJInE+jSsFHwrzR1C6f/hMvGljCAAfXBOsaB7rqJYDPD5Q9DzKyBjQn7Je -FnQGSjyv29nMRz5LxNjuJw8RfOtKugsmNyJSeu1Y4Ycw3cEloyHLfazSNbyIdYCD6VDP3ISKJ1b -nnyAIJutcxx43nKaIWbG1xSv6JaceMFtQ== +MIIBqzCCARSgAwIBAgIBBDANBgkqhkiG9w0BAQUFADAfMR0wGwYDVQQDDBRUZXN0IEludGVybWV +kaWF0ZSBDQTAiGA8yMDE3MDEwMTAwMDAwMFoYDzIwMTgwMTAxMDAwMDAwWjAUMRIwEAYDVQQDDA +lUZXN0IENlcnQwgZ8wDQYJKoZIhvcNAQEBBQADgY0AMIGJAoGBALxM1bONkvpmrDJDGp7rF+Cqd +jUbHRBITj4ii3Uu6G+kVR4KXmDAYfF9KVh+C+8pvq3490PIWJUUWx2vSriQnk7sTrOGermWwTTT +uaZX35u92d1nFVTUn2W4MylZuprGdeqldj2kVw/i5MORNR1u/2F9wlMjZrKoC+HHVUjFK019AgM +BAAEwDQYJKoZIhvcNAQEFBQADgYEAGLuT2SrgNGkvllesVayngwS0vCJ/X/fA3KyvE5uGfqwCjE +SDLsD6oXcd3YYxfpiTwE+yPb4wb6X8xy6xuAjSF8tgVb9a4JTzHUT6sS8aJMUz4dTwrNUsZ9qnX +e7r1nqnQeiUejRDsh+r6c9dJUlWGNKpSRo3NEPHBpZKKTjM8hw= -----END CERTIFICATE----- $ openssl asn1parse -i < [OCSP REQUEST] @@ -134,10 +134,10 @@ 10:d=5 hl=2 l= 9 cons: SEQUENCE 12:d=6 hl=2 l= 5 prim: OBJECT :sha1 19:d=6 hl=2 l= 0 prim: NULL - 21:d=5 hl=2 l= 20 prim: OCTET STRING [HEX DUMP]:02FF75DA24DE8ADD150FAB689DCCE6E6636D0901 - 43:d=5 hl=2 l= 20 prim: OCTET STRING [HEX DUMP]:84E1BA52A25C543CA972491224BC8B1ECA8B9FF4 - 65:d=5 hl=2 l= 1 prim: INTEGER :03 + 21:d=5 hl=2 l= 20 prim: OCTET STRING [HEX DUMP]:449B1C5B31C6E9990966523E49C3F773C024190A + 43:d=5 hl=2 l= 20 prim: OCTET STRING [HEX DUMP]:FC6D3387CC3B39B049C755C46DF4395548930BCE + 65:d=5 hl=2 l= 1 prim: INTEGER :04 -----BEGIN OCSP REQUEST----- -MEIwQDA+MDwwOjAJBgUrDgMCGgUABBQC/3XaJN6K3RUPq2idzObmY20JAQQUhOG6UqJcVDypckk -SJLyLHsqLn/QCAQM= +MEIwQDA+MDwwOjAJBgUrDgMCGgUABBREmxxbMcbpmQlmUj5Jw/dzwCQZCgQU/G0zh8w7ObBJx1X +EbfQ5VUiTC84CAQQ= -----END OCSP REQUEST-----
diff --git a/net/data/ocsp_unittest/revoke_response_reason.pem b/net/data/ocsp_unittest/revoke_response_reason.pem index ad35fd4..457f63d 100644 --- a/net/data/ocsp_unittest/revoke_response_reason.pem +++ b/net/data/ocsp_unittest/revoke_response_reason.pem
@@ -5,125 +5,126 @@ OCSP Response Status: successful (0x0) Response Type: Basic OCSP Response Version: 1 (0x0) - Responder Id: CN = Test CA + Responder Id: CN = Test Intermediate CA Produced At: Mar 2 00:00:00 2017 GMT Responses: Certificate ID: Hash Algorithm: sha1 - Issuer Name Hash: 02FF75DA24DE8ADD150FAB689DCCE6E6636D0901 - Issuer Key Hash: 84E1BA52A25C543CA972491224BC8B1ECA8B9FF4 - Serial Number: 03 + Issuer Name Hash: 449B1C5B31C6E9990966523E49C3F773C024190A + Issuer Key Hash: FC6D3387CC3B39B049C755C46DF4395548930BCE + Serial Number: 04 Cert Status: revoked Revocation Time: Feb 1 00:00:00 2017 GMT Revocation Reason: keyCompromise (0x1) This Update: Mar 1 00:00:00 2017 GMT Signature Algorithm: sha1WithRSAEncryption - 46:0d:80:78:5a:e8:9d:e2:b8:86:5b:13:46:3a:cf:0a:8b:17: - e3:7e:0c:da:21:0e:5b:6d:53:fa:b0:11:26:6e:5a:f1:17:37: - 13:f4:7f:ee:04:44:e2:31:cd:0c:62:a2:a5:c8:6d:7f:54:c0: - f1:18:bf:5a:6e:04:c8:3b:76:63:05:42:49:a8:50:90:a0:0c: - c2:97:22:f4:ac:9e:54:eb:aa:5c:a3:56:43:70:ef:7b:70:5e: - a6:df:96:d8:0e:ca:d5:38:2d:cb:f1:70:c5:69:96:9c:3c:4c: - 07:a6:1a:1d:cd:36:53:dc:3b:b1:1c:55:f0:af:d8:b9:d3:8d: - 8e:45 + 31:a5:29:cb:33:73:d4:f3:ee:d5:ff:13:9c:a7:3b:1f:7d:bc: + 4e:08:34:e7:ca:39:94:a1:65:48:3f:73:da:06:a7:df:ff:23: + b5:ce:af:c9:8d:61:d5:d1:e4:e9:3e:7f:9a:a5:09:f7:78:7b: + 4a:80:31:c8:02:44:0a:62:57:34:21:a6:7a:7a:73:8e:8c:c5: + 3e:98:58:29:4b:74:1d:30:40:c4:b1:ce:ab:b9:3f:1f:d2:e4: + c3:81:9c:b3:ab:3e:e9:4a:36:4d:f3:ef:f8:9f:48:b1:58:2e: + ff:47:f7:1a:de:12:8d:63:55:17:b3:e7:9c:1f:39:05:6c:f5: + 95:dd -----BEGIN OCSP RESPONSE----- -MIIBQgoBAKCCATswggE3BgkrBgEFBQcwAQEEggEoMIIBJDCBjqEUMBIxEDAOBgNVBAMTB1Rlc3Q -gQ0EYDzIwMTcwMzAyMDAwMDAwWjBlMGMwODAHBgUrDgMCGgQUAv912iTeit0VD6tonczm5mNtCQ -EEFIThulKiXFQ8qXJJEiS8ix7Ki5/0AgEDoRYYDzIwMTcwMjAxMDAwMDAwWqADCgEBGA8yMDE3M -DMwMTAwMDAwMFowDQYJKoZIhvcNAQEFBQADgYEARg2AeFroneK4hlsTRjrPCosX434M2iEOW21T -+rARJm5a8Rc3E/R/7gRE4jHNDGKipchtf1TA8Ri/Wm4EyDt2YwVCSahQkKAMwpci9KyeVOuqXKN -WQ3Dve3Bept+W2A7K1Tgty/FwxWmWnDxMB6YaHc02U9w7sRxV8K/YudONjkU= +MIIBTwoBAKCCAUgwggFEBgkrBgEFBQcwAQEEggE1MIIBMTCBm6EhMB8xHTAbBgNVBAMMFFRlc3Q +gSW50ZXJtZWRpYXRlIENBGA8yMDE3MDMwMjAwMDAwMFowZTBjMDgwBwYFKw4DAhoEFESbHFsxxu +mZCWZSPknD93PAJBkKBBT8bTOHzDs5sEnHVcRt9DlVSJMLzgIBBKEWGA8yMDE3MDIwMTAwMDAwM +FqgAwoBARgPMjAxNzAzMDEwMDAwMDBaMA0GCSqGSIb3DQEBBQUAA4GBADGlKcszc9Tz7tX/E5yn +Ox99vE4INOfKOZShZUg/c9oGp9//I7XOr8mNYdXR5Ok+f5qlCfd4e0qAMcgCRApiVzQhpnp6c46 +MxT6YWClLdB0wQMSxzqu5Px/S5MOBnLOrPulKNk3z7/ifSLFYLv9H9xreEo1jVRez55wfOQVs9Z +Xd -----END OCSP RESPONSE----- $ openssl x509 -text < [CA CERTIFICATE] Certificate: Data: Version: 3 (0x2) - Serial Number: 0 (0x0) + Serial Number: 1 (0x1) Signature Algorithm: sha1WithRSAEncryption - Issuer: CN=Test CA + Issuer: CN = Test CA Validity Not Before: Jan 1 00:00:00 2017 GMT Not After : Jan 1 00:00:00 2018 GMT - Subject: CN=Test CA + Subject: CN = Test Intermediate CA Subject Public Key Info: Public Key Algorithm: rsaEncryption Public-Key: (1024 bit) Modulus: - 00:b8:25:2b:ee:59:9a:9d:bc:b4:48:ae:09:ce:0d: - ba:c5:83:57:03:92:fd:52:32:55:f5:e4:2e:a6:cf: - 9e:4b:c4:10:af:24:da:d5:dd:44:a8:d6:28:38:9c: - a5:11:c9:0b:70:a1:b5:71:cf:a4:35:c2:6a:17:b1: - b5:c7:cf:74:83:ac:7a:d5:3b:12:66:74:f2:4b:15: - b0:c2:59:af:0c:78:2c:42:3c:3f:8b:83:b3:1d:9a: - c8:bc:ce:b0:c8:f2:1a:a8:0a:1c:bb:6e:6e:d4:c6: - 10:66:3c:a8:ec:e3:c4:63:40:f6:79:ec:8b:14:ff: - 85:9e:2d:1a:e7:e8:31:56:81 + 00:b9:32:09:de:33:4a:4f:e2:04:73:49:d5:2e:2b: + 83:92:3a:94:e4:1b:0c:27:1b:f8:43:83:17:b8:75: + f5:a4:af:e3:4c:84:3e:6c:48:79:76:df:4d:f5:39: + af:92:4b:c5:a0:86:ab:35:cc:19:6b:93:82:c0:f8: + 44:4d:1a:14:5d:48:87:65:02:0e:b0:a8:96:d9:06: + 19:3f:aa:85:2d:84:c0:78:19:a6:96:ab:26:56:f7: + 6f:5a:1a:97:a2:01:88:00:99:10:8a:97:39:c8:22: + 6e:de:e5:56:f4:a6:23:cd:ea:48:0e:65:67:a4:73: + a0:50:91:de:ba:cf:54:08:8f Exponent: 65537 (0x10001) Signature Algorithm: sha1WithRSAEncryption - 35:fe:ee:96:31:c7:3d:91:eb:22:53:1f:bf:cc:20:cc:aa:f4: - 04:92:3c:8b:50:06:ea:a1:cc:b7:c2:4a:d6:02:af:53:a7:a4: - 71:81:78:bc:95:f3:2d:46:c4:83:4c:d5:92:11:7c:c7:67:d3: - 47:f6:06:9f:1c:46:da:d6:20:72:47:c2:57:d7:fb:66:d3:35: - 82:07:61:13:4e:4d:e6:0c:93:e6:f3:be:98:ff:e8:de:60:a7: - 06:94:cd:bb:f5:6e:b3:4e:0b:d6:e9:2b:72:bd:6e:ae:86:23: - 2d:44:33:c4:3b:a7:52:12:46:d2:76:95:06:3e:69:0f:72:60: - 16:d6 + 48:d5:9f:8d:90:bc:4a:59:38:1d:2b:83:2d:71:1c:74:9d:01: + 73:a0:b6:98:e7:1c:c2:22:66:23:33:0a:8f:64:ff:9c:6b:37: + 09:12:1c:15:12:cb:c3:61:d9:ab:cd:96:dd:95:fa:a6:02:67: + 3c:4c:ec:98:38:5c:fc:48:cc:85:a9:5b:49:2c:2b:06:66:07: + 9e:31:0f:93:10:ab:3e:9f:97:60:64:01:61:7e:86:15:bb:5e: + f1:90:31:a3:54:d0:86:0e:80:05:87:09:2e:65:b6:95:89:5c: + c1:e5:80:d9:b8:81:b6:ed:1a:20:b8:9b:22:ce:ef:d0:26:47: + 9d:57 -----BEGIN CA CERTIFICATE----- -MIIBnDCCAQWgAwIBAgIBADANBgkqhkiG9w0BAQUFADASMRAwDgYDVQQDEwdUZXN0IENBMCIYDzI -wMTcwMTAxMDAwMDAwWhgPMjAxODAxMDEwMDAwMDBaMBIxEDAOBgNVBAMTB1Rlc3QgQ0EwgZ8wDQ -YJKoZIhvcNAQEBBQADgY0AMIGJAoGBALglK+5Zmp28tEiuCc4NusWDVwOS/VIyVfXkLqbPnkvEE -K8k2tXdRKjWKDicpRHJC3ChtXHPpDXCahextcfPdIOsetU7EmZ08ksVsMJZrwx4LEI8P4uDsx2a -yLzOsMjyGqgKHLtubtTGEGY8qOzjxGNA9nnsixT/hZ4tGufoMVaBAgMBAAEwDQYJKoZIhvcNAQE -FBQADgYEANf7uljHHPZHrIlMfv8wgzKr0BJI8i1AG6qHMt8JK1gKvU6ekcYF4vJXzLUbEg0zVkh -F8x2fTR/YGnxxG2tYgckfCV9f7ZtM1ggdhE05N5gyT5vO+mP/o3mCnBpTNu/Vus04L1ukrcr1ur -oYjLUQzxDunUhJG0naVBj5pD3JgFtY= +MIIBqTCCARKgAwIBAgIBATANBgkqhkiG9w0BAQUFADASMRAwDgYDVQQDDAdUZXN0IENBMCIYDzI +wMTcwMTAxMDAwMDAwWhgPMjAxODAxMDEwMDAwMDBaMB8xHTAbBgNVBAMMFFRlc3QgSW50ZXJtZW +RpYXRlIENBMIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQC5MgneM0pP4gRzSdUuK4OSOpTkG +wwnG/hDgxe4dfWkr+NMhD5sSHl23031Oa+SS8Wghqs1zBlrk4LA+ERNGhRdSIdlAg6wqJbZBhk/ +qoUthMB4GaaWqyZW929aGpeiAYgAmRCKlznIIm7e5Vb0piPN6kgOZWekc6BQkd66z1QIjwIDAQA +BMA0GCSqGSIb3DQEBBQUAA4GBAEjVn42QvEpZOB0rgy1xHHSdAXOgtpjnHMIiZiMzCo9k/5xrNw +kSHBUSy8Nh2avNlt2V+qYCZzxM7Jg4XPxIzIWpW0ksKwZmB54xD5MQqz6fl2BkAWF+hhW7XvGQM +aNU0IYOgAWHCS5ltpWJXMHlgNm4gbbtGiC4myLO79AmR51X -----END CA CERTIFICATE----- $ openssl x509 -text < [CERTIFICATE] Certificate: Data: Version: 3 (0x2) - Serial Number: 3 (0x3) + Serial Number: 4 (0x4) Signature Algorithm: sha1WithRSAEncryption - Issuer: CN=Test CA + Issuer: CN = Test Intermediate CA Validity Not Before: Jan 1 00:00:00 2017 GMT Not After : Jan 1 00:00:00 2018 GMT - Subject: CN=Test Cert + Subject: CN = Test Cert Subject Public Key Info: Public Key Algorithm: rsaEncryption Public-Key: (1024 bit) Modulus: - 00:d5:12:3f:22:6f:b0:e1:43:c5:93:b3:c3:5b:70: - 52:b2:8b:10:ec:11:c4:c4:aa:aa:43:92:c8:d0:f3: - 35:23:e3:76:2d:b4:ea:93:26:6f:6a:79:1c:64:51: - d3:4d:21:4a:73:83:35:dc:a0:16:74:db:f0:b9:a5: - 46:35:8d:53:e8:7d:37:5b:4d:ad:a3:df:d6:ae:01: - 38:ad:16:09:6e:fd:65:ad:1c:4b:48:12:1e:48:a7: - ff:5b:47:c4:c9:3b:74:85:63:1a:0a:06:b2:9f:b9: - cb:ad:dc:3f:24:8b:a4:a7:8a:13:15:45:89:24:c1: - a7:3b:c2:a2:c8:74:f1:3f:6f + 00:bc:4c:d5:b3:8d:92:fa:66:ac:32:43:1a:9e:eb: + 17:e0:aa:76:35:1b:1d:10:48:4e:3e:22:8b:75:2e: + e8:6f:a4:55:1e:0a:5e:60:c0:61:f1:7d:29:58:7e: + 0b:ef:29:be:ad:f8:f7:43:c8:58:95:14:5b:1d:af: + 4a:b8:90:9e:4e:ec:4e:b3:86:7a:b9:96:c1:34:d3: + b9:a6:57:df:9b:bd:d9:dd:67:15:54:d4:9f:65:b8: + 33:29:59:ba:9a:c6:75:ea:a5:76:3d:a4:57:0f:e2: + e4:c3:91:35:1d:6e:ff:61:7d:c2:53:23:66:b2:a8: + 0b:e1:c7:55:48:c5:2b:4d:7d Exponent: 65537 (0x10001) Signature Algorithm: sha1WithRSAEncryption - 04:21:70:de:14:92:27:13:e8:d2:b0:51:f0:af:34:75:0b:a7: - ff:84:cb:c6:96:30:80:01:f5:c1:3a:c6:81:ee:ba:89:60:33: - c3:e5:0f:43:cc:ac:81:8d:09:fb:25:e1:67:40:64:a3:ca:fd: - bd:9c:c4:73:e4:bc:4d:8e:e2:70:f1:17:ce:b4:ab:a0:b2:63: - 72:25:27:ae:d5:8e:18:73:0d:dc:12:5a:32:1c:b7:da:cd:23: - 5b:c8:87:58:08:3e:95:0c:fd:c8:48:a2:75:6e:79:f2:00:82: - 6e:b5:cc:71:e3:79:ca:68:85:9b:1b:5c:52:bf:a2:5a:71:e3: - 05:b5 + 18:bb:93:d9:2a:e0:34:69:2f:96:57:ac:55:ac:a7:83:04:b4: + bc:22:7f:5f:f7:c0:dc:ac:af:13:9b:86:7e:ac:02:8c:44:83: + 2e:c0:fa:a1:77:1d:dd:86:31:7e:98:93:c0:4f:b2:3d:be:30: + 6f:a5:fc:c7:2e:b1:b8:08:d2:17:cb:60:55:bf:5a:e0:94:f3: + 1d:44:fa:b1:2f:1a:24:c5:33:e1:d4:f0:ac:d5:2c:67:da:a7: + 5d:ee:eb:d6:7a:a7:41:e8:94:7a:34:43:b2:1f:ab:e9:cf:5d: + 25:49:56:18:d2:a9:49:1a:37:34:43:c7:06:96:4a:29:38:cc: + f2:1c -----BEGIN CERTIFICATE----- -MIIBnjCCAQegAwIBAgIBAzANBgkqhkiG9w0BAQUFADASMRAwDgYDVQQDEwdUZXN0IENBMCIYDzI -wMTcwMTAxMDAwMDAwWhgPMjAxODAxMDEwMDAwMDBaMBQxEjAQBgNVBAMTCVRlc3QgQ2VydDCBnz -ANBgkqhkiG9w0BAQEFAAOBjQAwgYkCgYEA1RI/Im+w4UPFk7PDW3BSsosQ7BHExKqqQ5LI0PM1I -+N2LbTqkyZvankcZFHTTSFKc4M13KAWdNvwuaVGNY1T6H03W02to9/WrgE4rRYJbv1lrRxLSBIe -SKf/W0fEyTt0hWMaCgayn7nLrdw/JIukp4oTFUWJJMGnO8KiyHTxP28CAwEAATANBgkqhkiG9w0 -BAQUFAAOBgQAEIXDeFJInE+jSsFHwrzR1C6f/hMvGljCAAfXBOsaB7rqJYDPD5Q9DzKyBjQn7Je -FnQGSjyv29nMRz5LxNjuJw8RfOtKugsmNyJSeu1Y4Ycw3cEloyHLfazSNbyIdYCD6VDP3ISKJ1b -nnyAIJutcxx43nKaIWbG1xSv6JaceMFtQ== +MIIBqzCCARSgAwIBAgIBBDANBgkqhkiG9w0BAQUFADAfMR0wGwYDVQQDDBRUZXN0IEludGVybWV +kaWF0ZSBDQTAiGA8yMDE3MDEwMTAwMDAwMFoYDzIwMTgwMTAxMDAwMDAwWjAUMRIwEAYDVQQDDA +lUZXN0IENlcnQwgZ8wDQYJKoZIhvcNAQEBBQADgY0AMIGJAoGBALxM1bONkvpmrDJDGp7rF+Cqd +jUbHRBITj4ii3Uu6G+kVR4KXmDAYfF9KVh+C+8pvq3490PIWJUUWx2vSriQnk7sTrOGermWwTTT +uaZX35u92d1nFVTUn2W4MylZuprGdeqldj2kVw/i5MORNR1u/2F9wlMjZrKoC+HHVUjFK019AgM +BAAEwDQYJKoZIhvcNAQEFBQADgYEAGLuT2SrgNGkvllesVayngwS0vCJ/X/fA3KyvE5uGfqwCjE +SDLsD6oXcd3YYxfpiTwE+yPb4wb6X8xy6xuAjSF8tgVb9a4JTzHUT6sS8aJMUz4dTwrNUsZ9qnX +e7r1nqnQeiUejRDsh+r6c9dJUlWGNKpSRo3NEPHBpZKKTjM8hw= -----END CERTIFICATE----- $ openssl asn1parse -i < [OCSP REQUEST] @@ -135,10 +136,10 @@ 10:d=5 hl=2 l= 9 cons: SEQUENCE 12:d=6 hl=2 l= 5 prim: OBJECT :sha1 19:d=6 hl=2 l= 0 prim: NULL - 21:d=5 hl=2 l= 20 prim: OCTET STRING [HEX DUMP]:02FF75DA24DE8ADD150FAB689DCCE6E6636D0901 - 43:d=5 hl=2 l= 20 prim: OCTET STRING [HEX DUMP]:84E1BA52A25C543CA972491224BC8B1ECA8B9FF4 - 65:d=5 hl=2 l= 1 prim: INTEGER :03 + 21:d=5 hl=2 l= 20 prim: OCTET STRING [HEX DUMP]:449B1C5B31C6E9990966523E49C3F773C024190A + 43:d=5 hl=2 l= 20 prim: OCTET STRING [HEX DUMP]:FC6D3387CC3B39B049C755C46DF4395548930BCE + 65:d=5 hl=2 l= 1 prim: INTEGER :04 -----BEGIN OCSP REQUEST----- -MEIwQDA+MDwwOjAJBgUrDgMCGgUABBQC/3XaJN6K3RUPq2idzObmY20JAQQUhOG6UqJcVDypckk -SJLyLHsqLn/QCAQM= +MEIwQDA+MDwwOjAJBgUrDgMCGgUABBREmxxbMcbpmQlmUj5Jw/dzwCQZCgQU/G0zh8w7ObBJx1X +EbfQ5VUiTC84CAQQ= -----END OCSP REQUEST-----
diff --git a/net/data/ocsp_unittest/unknown_response.pem b/net/data/ocsp_unittest/unknown_response.pem index ca3bda92e..6c0cc7d3 100644 --- a/net/data/ocsp_unittest/unknown_response.pem +++ b/net/data/ocsp_unittest/unknown_response.pem
@@ -5,123 +5,123 @@ OCSP Response Status: successful (0x0) Response Type: Basic OCSP Response Version: 1 (0x0) - Responder Id: CN = Test CA + Responder Id: CN = Test Intermediate CA Produced At: Mar 2 00:00:00 2017 GMT Responses: Certificate ID: Hash Algorithm: sha1 - Issuer Name Hash: 02FF75DA24DE8ADD150FAB689DCCE6E6636D0901 - Issuer Key Hash: 84E1BA52A25C543CA972491224BC8B1ECA8B9FF4 - Serial Number: 03 + Issuer Name Hash: 449B1C5B31C6E9990966523E49C3F773C024190A + Issuer Key Hash: FC6D3387CC3B39B049C755C46DF4395548930BCE + Serial Number: 04 Cert Status: unknown This Update: Mar 1 00:00:00 2017 GMT Signature Algorithm: sha1WithRSAEncryption - 3f:a2:42:0a:3d:68:14:4a:38:f7:4f:c1:0e:15:38:a0:5a:96: - ff:08:b4:99:c7:81:41:6c:c3:95:04:33:4b:22:ec:f5:a8:c4: - 4d:6f:e0:35:39:31:82:15:90:e7:cf:f0:57:17:9c:70:d6:c8: - 21:08:93:ab:8c:d0:98:f2:8f:0b:00:65:c4:45:a7:bd:3f:c1: - 21:97:59:d1:be:a1:e8:26:4e:55:1c:3a:45:bf:b3:bc:7f:a2: - 93:f3:cd:a3:14:58:df:bf:a4:6d:aa:60:06:af:60:0b:d7:9c: - 7c:40:7a:74:74:f1:30:23:bc:ff:a7:43:d6:8e:70:9d:dc:ab: - cc:71 + 67:3a:7c:61:e2:6a:25:bb:d8:11:e1:d9:48:41:8a:69:ad:00: + f2:f8:b2:67:02:cd:a4:93:e7:66:35:3d:04:99:03:01:95:d0: + 6f:7b:67:35:77:a4:e7:19:62:a9:c7:c2:db:1b:29:9a:f3:f6: + 47:a4:91:8f:25:c8:31:1d:fb:4a:9f:50:29:af:66:f7:21:1f: + 65:97:e6:31:cb:70:38:46:b0:09:f0:43:29:4c:1b:e4:e2:36: + f5:34:07:a5:2f:63:17:f7:ec:e8:3e:70:98:74:1a:67:78:06: + a9:42:11:47:93:11:13:1f:d4:0d:96:f8:6c:81:80:a8:63:c8: + e3:b5 -----BEGIN OCSP RESPONSE----- -MIIBKwoBAKCCASQwggEgBgkrBgEFBQcwAQEEggERMIIBDTB4oRQwEjEQMA4GA1UEAxMHVGVzdCB -DQRgPMjAxNzAzMDIwMDAwMDBaME8wTTA4MAcGBSsOAwIaBBQC/3XaJN6K3RUPq2idzObmY20JAQ -QUhOG6UqJcVDypckkSJLyLHsqLn/QCAQOCABgPMjAxNzAzMDEwMDAwMDBaMA0GCSqGSIb3DQEBB -QUAA4GBAD+iQgo9aBRKOPdPwQ4VOKBalv8ItJnHgUFsw5UEM0si7PWoxE1v4DU5MYIVkOfP8FcX -nHDWyCEIk6uM0JjyjwsAZcRFp70/wSGXWdG+oegmTlUcOkW/s7x/opPzzaMUWN+/pG2qYAavYAv -XnHxAenR08TAjvP+nQ9aOcJ3cq8xx +MIIBOQoBAKCCATIwggEuBgkrBgEFBQcwAQEEggEfMIIBGzCBhaEhMB8xHTAbBgNVBAMMFFRlc3Q +gSW50ZXJtZWRpYXRlIENBGA8yMDE3MDMwMjAwMDAwMFowTzBNMDgwBwYFKw4DAhoEFESbHFsxxu +mZCWZSPknD93PAJBkKBBT8bTOHzDs5sEnHVcRt9DlVSJMLzgIBBIIAGA8yMDE3MDMwMTAwMDAwM +FowDQYJKoZIhvcNAQEFBQADgYEAZzp8YeJqJbvYEeHZSEGKaa0A8viyZwLNpJPnZjU9BJkDAZXQ +b3tnNXek5xliqcfC2xspmvP2R6SRjyXIMR37Sp9QKa9m9yEfZZfmMctwOEawCfBDKUwb5OI29TQ +HpS9jF/fs6D5wmHQaZ3gGqUIRR5MREx/UDZb4bIGAqGPI47U= -----END OCSP RESPONSE----- $ openssl x509 -text < [CA CERTIFICATE] Certificate: Data: Version: 3 (0x2) - Serial Number: 0 (0x0) + Serial Number: 1 (0x1) Signature Algorithm: sha1WithRSAEncryption - Issuer: CN=Test CA + Issuer: CN = Test CA Validity Not Before: Jan 1 00:00:00 2017 GMT Not After : Jan 1 00:00:00 2018 GMT - Subject: CN=Test CA + Subject: CN = Test Intermediate CA Subject Public Key Info: Public Key Algorithm: rsaEncryption Public-Key: (1024 bit) Modulus: - 00:b8:25:2b:ee:59:9a:9d:bc:b4:48:ae:09:ce:0d: - ba:c5:83:57:03:92:fd:52:32:55:f5:e4:2e:a6:cf: - 9e:4b:c4:10:af:24:da:d5:dd:44:a8:d6:28:38:9c: - a5:11:c9:0b:70:a1:b5:71:cf:a4:35:c2:6a:17:b1: - b5:c7:cf:74:83:ac:7a:d5:3b:12:66:74:f2:4b:15: - b0:c2:59:af:0c:78:2c:42:3c:3f:8b:83:b3:1d:9a: - c8:bc:ce:b0:c8:f2:1a:a8:0a:1c:bb:6e:6e:d4:c6: - 10:66:3c:a8:ec:e3:c4:63:40:f6:79:ec:8b:14:ff: - 85:9e:2d:1a:e7:e8:31:56:81 + 00:b9:32:09:de:33:4a:4f:e2:04:73:49:d5:2e:2b: + 83:92:3a:94:e4:1b:0c:27:1b:f8:43:83:17:b8:75: + f5:a4:af:e3:4c:84:3e:6c:48:79:76:df:4d:f5:39: + af:92:4b:c5:a0:86:ab:35:cc:19:6b:93:82:c0:f8: + 44:4d:1a:14:5d:48:87:65:02:0e:b0:a8:96:d9:06: + 19:3f:aa:85:2d:84:c0:78:19:a6:96:ab:26:56:f7: + 6f:5a:1a:97:a2:01:88:00:99:10:8a:97:39:c8:22: + 6e:de:e5:56:f4:a6:23:cd:ea:48:0e:65:67:a4:73: + a0:50:91:de:ba:cf:54:08:8f Exponent: 65537 (0x10001) Signature Algorithm: sha1WithRSAEncryption - 35:fe:ee:96:31:c7:3d:91:eb:22:53:1f:bf:cc:20:cc:aa:f4: - 04:92:3c:8b:50:06:ea:a1:cc:b7:c2:4a:d6:02:af:53:a7:a4: - 71:81:78:bc:95:f3:2d:46:c4:83:4c:d5:92:11:7c:c7:67:d3: - 47:f6:06:9f:1c:46:da:d6:20:72:47:c2:57:d7:fb:66:d3:35: - 82:07:61:13:4e:4d:e6:0c:93:e6:f3:be:98:ff:e8:de:60:a7: - 06:94:cd:bb:f5:6e:b3:4e:0b:d6:e9:2b:72:bd:6e:ae:86:23: - 2d:44:33:c4:3b:a7:52:12:46:d2:76:95:06:3e:69:0f:72:60: - 16:d6 + 48:d5:9f:8d:90:bc:4a:59:38:1d:2b:83:2d:71:1c:74:9d:01: + 73:a0:b6:98:e7:1c:c2:22:66:23:33:0a:8f:64:ff:9c:6b:37: + 09:12:1c:15:12:cb:c3:61:d9:ab:cd:96:dd:95:fa:a6:02:67: + 3c:4c:ec:98:38:5c:fc:48:cc:85:a9:5b:49:2c:2b:06:66:07: + 9e:31:0f:93:10:ab:3e:9f:97:60:64:01:61:7e:86:15:bb:5e: + f1:90:31:a3:54:d0:86:0e:80:05:87:09:2e:65:b6:95:89:5c: + c1:e5:80:d9:b8:81:b6:ed:1a:20:b8:9b:22:ce:ef:d0:26:47: + 9d:57 -----BEGIN CA CERTIFICATE----- -MIIBnDCCAQWgAwIBAgIBADANBgkqhkiG9w0BAQUFADASMRAwDgYDVQQDEwdUZXN0IENBMCIYDzI -wMTcwMTAxMDAwMDAwWhgPMjAxODAxMDEwMDAwMDBaMBIxEDAOBgNVBAMTB1Rlc3QgQ0EwgZ8wDQ -YJKoZIhvcNAQEBBQADgY0AMIGJAoGBALglK+5Zmp28tEiuCc4NusWDVwOS/VIyVfXkLqbPnkvEE -K8k2tXdRKjWKDicpRHJC3ChtXHPpDXCahextcfPdIOsetU7EmZ08ksVsMJZrwx4LEI8P4uDsx2a -yLzOsMjyGqgKHLtubtTGEGY8qOzjxGNA9nnsixT/hZ4tGufoMVaBAgMBAAEwDQYJKoZIhvcNAQE -FBQADgYEANf7uljHHPZHrIlMfv8wgzKr0BJI8i1AG6qHMt8JK1gKvU6ekcYF4vJXzLUbEg0zVkh -F8x2fTR/YGnxxG2tYgckfCV9f7ZtM1ggdhE05N5gyT5vO+mP/o3mCnBpTNu/Vus04L1ukrcr1ur -oYjLUQzxDunUhJG0naVBj5pD3JgFtY= +MIIBqTCCARKgAwIBAgIBATANBgkqhkiG9w0BAQUFADASMRAwDgYDVQQDDAdUZXN0IENBMCIYDzI +wMTcwMTAxMDAwMDAwWhgPMjAxODAxMDEwMDAwMDBaMB8xHTAbBgNVBAMMFFRlc3QgSW50ZXJtZW +RpYXRlIENBMIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQC5MgneM0pP4gRzSdUuK4OSOpTkG +wwnG/hDgxe4dfWkr+NMhD5sSHl23031Oa+SS8Wghqs1zBlrk4LA+ERNGhRdSIdlAg6wqJbZBhk/ +qoUthMB4GaaWqyZW929aGpeiAYgAmRCKlznIIm7e5Vb0piPN6kgOZWekc6BQkd66z1QIjwIDAQA +BMA0GCSqGSIb3DQEBBQUAA4GBAEjVn42QvEpZOB0rgy1xHHSdAXOgtpjnHMIiZiMzCo9k/5xrNw +kSHBUSy8Nh2avNlt2V+qYCZzxM7Jg4XPxIzIWpW0ksKwZmB54xD5MQqz6fl2BkAWF+hhW7XvGQM +aNU0IYOgAWHCS5ltpWJXMHlgNm4gbbtGiC4myLO79AmR51X -----END CA CERTIFICATE----- $ openssl x509 -text < [CERTIFICATE] Certificate: Data: Version: 3 (0x2) - Serial Number: 3 (0x3) + Serial Number: 4 (0x4) Signature Algorithm: sha1WithRSAEncryption - Issuer: CN=Test CA + Issuer: CN = Test Intermediate CA Validity Not Before: Jan 1 00:00:00 2017 GMT Not After : Jan 1 00:00:00 2018 GMT - Subject: CN=Test Cert + Subject: CN = Test Cert Subject Public Key Info: Public Key Algorithm: rsaEncryption Public-Key: (1024 bit) Modulus: - 00:d5:12:3f:22:6f:b0:e1:43:c5:93:b3:c3:5b:70: - 52:b2:8b:10:ec:11:c4:c4:aa:aa:43:92:c8:d0:f3: - 35:23:e3:76:2d:b4:ea:93:26:6f:6a:79:1c:64:51: - d3:4d:21:4a:73:83:35:dc:a0:16:74:db:f0:b9:a5: - 46:35:8d:53:e8:7d:37:5b:4d:ad:a3:df:d6:ae:01: - 38:ad:16:09:6e:fd:65:ad:1c:4b:48:12:1e:48:a7: - ff:5b:47:c4:c9:3b:74:85:63:1a:0a:06:b2:9f:b9: - cb:ad:dc:3f:24:8b:a4:a7:8a:13:15:45:89:24:c1: - a7:3b:c2:a2:c8:74:f1:3f:6f + 00:bc:4c:d5:b3:8d:92:fa:66:ac:32:43:1a:9e:eb: + 17:e0:aa:76:35:1b:1d:10:48:4e:3e:22:8b:75:2e: + e8:6f:a4:55:1e:0a:5e:60:c0:61:f1:7d:29:58:7e: + 0b:ef:29:be:ad:f8:f7:43:c8:58:95:14:5b:1d:af: + 4a:b8:90:9e:4e:ec:4e:b3:86:7a:b9:96:c1:34:d3: + b9:a6:57:df:9b:bd:d9:dd:67:15:54:d4:9f:65:b8: + 33:29:59:ba:9a:c6:75:ea:a5:76:3d:a4:57:0f:e2: + e4:c3:91:35:1d:6e:ff:61:7d:c2:53:23:66:b2:a8: + 0b:e1:c7:55:48:c5:2b:4d:7d Exponent: 65537 (0x10001) Signature Algorithm: sha1WithRSAEncryption - 04:21:70:de:14:92:27:13:e8:d2:b0:51:f0:af:34:75:0b:a7: - ff:84:cb:c6:96:30:80:01:f5:c1:3a:c6:81:ee:ba:89:60:33: - c3:e5:0f:43:cc:ac:81:8d:09:fb:25:e1:67:40:64:a3:ca:fd: - bd:9c:c4:73:e4:bc:4d:8e:e2:70:f1:17:ce:b4:ab:a0:b2:63: - 72:25:27:ae:d5:8e:18:73:0d:dc:12:5a:32:1c:b7:da:cd:23: - 5b:c8:87:58:08:3e:95:0c:fd:c8:48:a2:75:6e:79:f2:00:82: - 6e:b5:cc:71:e3:79:ca:68:85:9b:1b:5c:52:bf:a2:5a:71:e3: - 05:b5 + 18:bb:93:d9:2a:e0:34:69:2f:96:57:ac:55:ac:a7:83:04:b4: + bc:22:7f:5f:f7:c0:dc:ac:af:13:9b:86:7e:ac:02:8c:44:83: + 2e:c0:fa:a1:77:1d:dd:86:31:7e:98:93:c0:4f:b2:3d:be:30: + 6f:a5:fc:c7:2e:b1:b8:08:d2:17:cb:60:55:bf:5a:e0:94:f3: + 1d:44:fa:b1:2f:1a:24:c5:33:e1:d4:f0:ac:d5:2c:67:da:a7: + 5d:ee:eb:d6:7a:a7:41:e8:94:7a:34:43:b2:1f:ab:e9:cf:5d: + 25:49:56:18:d2:a9:49:1a:37:34:43:c7:06:96:4a:29:38:cc: + f2:1c -----BEGIN CERTIFICATE----- -MIIBnjCCAQegAwIBAgIBAzANBgkqhkiG9w0BAQUFADASMRAwDgYDVQQDEwdUZXN0IENBMCIYDzI -wMTcwMTAxMDAwMDAwWhgPMjAxODAxMDEwMDAwMDBaMBQxEjAQBgNVBAMTCVRlc3QgQ2VydDCBnz -ANBgkqhkiG9w0BAQEFAAOBjQAwgYkCgYEA1RI/Im+w4UPFk7PDW3BSsosQ7BHExKqqQ5LI0PM1I -+N2LbTqkyZvankcZFHTTSFKc4M13KAWdNvwuaVGNY1T6H03W02to9/WrgE4rRYJbv1lrRxLSBIe -SKf/W0fEyTt0hWMaCgayn7nLrdw/JIukp4oTFUWJJMGnO8KiyHTxP28CAwEAATANBgkqhkiG9w0 -BAQUFAAOBgQAEIXDeFJInE+jSsFHwrzR1C6f/hMvGljCAAfXBOsaB7rqJYDPD5Q9DzKyBjQn7Je -FnQGSjyv29nMRz5LxNjuJw8RfOtKugsmNyJSeu1Y4Ycw3cEloyHLfazSNbyIdYCD6VDP3ISKJ1b -nnyAIJutcxx43nKaIWbG1xSv6JaceMFtQ== +MIIBqzCCARSgAwIBAgIBBDANBgkqhkiG9w0BAQUFADAfMR0wGwYDVQQDDBRUZXN0IEludGVybWV +kaWF0ZSBDQTAiGA8yMDE3MDEwMTAwMDAwMFoYDzIwMTgwMTAxMDAwMDAwWjAUMRIwEAYDVQQDDA +lUZXN0IENlcnQwgZ8wDQYJKoZIhvcNAQEBBQADgY0AMIGJAoGBALxM1bONkvpmrDJDGp7rF+Cqd +jUbHRBITj4ii3Uu6G+kVR4KXmDAYfF9KVh+C+8pvq3490PIWJUUWx2vSriQnk7sTrOGermWwTTT +uaZX35u92d1nFVTUn2W4MylZuprGdeqldj2kVw/i5MORNR1u/2F9wlMjZrKoC+HHVUjFK019AgM +BAAEwDQYJKoZIhvcNAQEFBQADgYEAGLuT2SrgNGkvllesVayngwS0vCJ/X/fA3KyvE5uGfqwCjE +SDLsD6oXcd3YYxfpiTwE+yPb4wb6X8xy6xuAjSF8tgVb9a4JTzHUT6sS8aJMUz4dTwrNUsZ9qnX +e7r1nqnQeiUejRDsh+r6c9dJUlWGNKpSRo3NEPHBpZKKTjM8hw= -----END CERTIFICATE----- $ openssl asn1parse -i < [OCSP REQUEST] @@ -133,10 +133,10 @@ 10:d=5 hl=2 l= 9 cons: SEQUENCE 12:d=6 hl=2 l= 5 prim: OBJECT :sha1 19:d=6 hl=2 l= 0 prim: NULL - 21:d=5 hl=2 l= 20 prim: OCTET STRING [HEX DUMP]:02FF75DA24DE8ADD150FAB689DCCE6E6636D0901 - 43:d=5 hl=2 l= 20 prim: OCTET STRING [HEX DUMP]:84E1BA52A25C543CA972491224BC8B1ECA8B9FF4 - 65:d=5 hl=2 l= 1 prim: INTEGER :03 + 21:d=5 hl=2 l= 20 prim: OCTET STRING [HEX DUMP]:449B1C5B31C6E9990966523E49C3F773C024190A + 43:d=5 hl=2 l= 20 prim: OCTET STRING [HEX DUMP]:FC6D3387CC3B39B049C755C46DF4395548930BCE + 65:d=5 hl=2 l= 1 prim: INTEGER :04 -----BEGIN OCSP REQUEST----- -MEIwQDA+MDwwOjAJBgUrDgMCGgUABBQC/3XaJN6K3RUPq2idzObmY20JAQQUhOG6UqJcVDypckk -SJLyLHsqLn/QCAQM= +MEIwQDA+MDwwOjAJBgUrDgMCGgUABBREmxxbMcbpmQlmUj5Jw/dzwCQZCgQU/G0zh8w7ObBJx1X +EbfQ5VUiTC84CAQQ= -----END OCSP REQUEST-----
diff --git a/net/disk_cache/backend_unittest.cc b/net/disk_cache/backend_unittest.cc index 6bd72f9..f6682160 100644 --- a/net/disk_cache/backend_unittest.cc +++ b/net/disk_cache/backend_unittest.cc
@@ -13,6 +13,7 @@ #include "base/strings/string_split.h" #include "base/strings/string_util.h" #include "base/strings/stringprintf.h" +#include "base/test/histogram_tester.h" #include "base/test/mock_entropy_provider.h" #include "base/test/scoped_task_environment.h" #include "base/third_party/dynamic_annotations/dynamic_annotations.h" @@ -38,6 +39,7 @@ #include "net/disk_cache/memory/mem_backend_impl.h" #include "net/disk_cache/simple/simple_backend_impl.h" #include "net/disk_cache/simple/simple_entry_format.h" +#include "net/disk_cache/simple/simple_histogram_enums.h" #include "net/disk_cache/simple/simple_index.h" #include "net/disk_cache/simple/simple_synchronous_entry.h" #include "net/disk_cache/simple/simple_test_util.h" @@ -1041,22 +1043,24 @@ int seed = static_cast<int>(Time::Now().ToInternalValue()); srand(seed); - disk_cache::Entry* entries[100]; - for (int i = 0; i < 100; i++) { + const int kNumEntries = 512; + + disk_cache::Entry* entries[kNumEntries]; + for (int i = 0; i < kNumEntries; i++) { std::string key = GenerateKey(true); ASSERT_THAT(CreateEntry(key, &entries[i]), IsOk()); } - EXPECT_EQ(100, cache_->GetEntryCount()); + EXPECT_EQ(kNumEntries, cache_->GetEntryCount()); - for (int i = 0; i < 100; i++) { - int source1 = rand() % 100; - int source2 = rand() % 100; + for (int i = 0; i < kNumEntries; i++) { + int source1 = rand() % kNumEntries; + int source2 = rand() % kNumEntries; disk_cache::Entry* temp = entries[source1]; entries[source1] = entries[source2]; entries[source2] = temp; } - for (int i = 0; i < 100; i++) { + for (int i = 0; i < kNumEntries; i++) { disk_cache::Entry* entry; ASSERT_THAT(OpenEntry(entries[i]->GetKey(), &entry), IsOk()); EXPECT_TRUE(entry == entries[i]); @@ -3784,21 +3788,13 @@ BackendKeying(); } -// MacOS has a default open file limit of 256 files, which is incompatible with -// this simple cache test. -#if defined(OS_MACOSX) -#define SIMPLE_MAYBE_MACOS(TestName) DISABLED_ ## TestName -#else -#define SIMPLE_MAYBE_MACOS(TestName) TestName -#endif - -TEST_F(DiskCacheBackendTest, SIMPLE_MAYBE_MACOS(SimpleCacheLoad)) { +TEST_F(DiskCacheBackendTest, SimpleCacheLoad) { SetMaxSize(0x100000); SetSimpleCacheMode(); BackendLoad(); } -TEST_F(DiskCacheBackendTest, SIMPLE_MAYBE_MACOS(SimpleCacheAppCacheLoad)) { +TEST_F(DiskCacheBackendTest, SimpleCacheAppCacheLoad) { SetCacheType(net::APP_CACHE); SetSimpleCacheMode(); SetMaxSize(0x100000); @@ -4215,3 +4211,104 @@ EXPECT_LE(reopen_entry1->GetLastModified(), entry1_timestamp); reopen_entry1->Close(); } + +TEST_F(DiskCacheBackendTest, SimpleFdLimit) { + base::HistogramTester histogram_tester; + SetSimpleCacheMode(); + // Make things blocking so CreateEntry actually waits for file to be + // created. + SetCacheType(net::APP_CACHE); + InitCache(); + const int kNumEntries = 512; + + disk_cache::Entry* entries[kNumEntries]; + std::string keys[kNumEntries]; + for (int i = 0; i < kNumEntries; ++i) { + keys[i] = GenerateKey(true); + ASSERT_THAT(CreateEntry(keys[i], &entries[i]), IsOk()); + } + + // Note the fixture sets the file limit to 64. + histogram_tester.ExpectBucketCount("SimpleCache.FileDescriptorLimiterAction", + disk_cache::FD_LIMIT_CLOSE_FILE, 512 - 64); + histogram_tester.ExpectBucketCount("SimpleCache.FileDescriptorLimiterAction", + disk_cache::FD_LIMIT_REOPEN_FILE, 0); + histogram_tester.ExpectBucketCount("SimpleCache.FileDescriptorLimiterAction", + disk_cache::FD_LIMIT_FAIL_REOPEN_FILE, 0); + + const int kSize = 25000; + scoped_refptr<net::IOBuffer> buf1(new net::IOBuffer(kSize)); + CacheTestFillBuffer(buf1->data(), kSize, false); + + scoped_refptr<net::IOBuffer> buf2(new net::IOBuffer(kSize)); + CacheTestFillBuffer(buf2->data(), kSize, false); + + // Doom an entry and create a new one with same name, to test that both + // re-open properly. + EXPECT_EQ(net::OK, DoomEntry(keys[0])); + disk_cache::Entry* alt_entry; + ASSERT_THAT(CreateEntry(keys[0], &alt_entry), IsOk()); + + // One more file closure here to accomodate for alt_entry. + histogram_tester.ExpectBucketCount("SimpleCache.FileDescriptorLimiterAction", + disk_cache::FD_LIMIT_CLOSE_FILE, + 512 - 64 + 1); + histogram_tester.ExpectBucketCount("SimpleCache.FileDescriptorLimiterAction", + disk_cache::FD_LIMIT_REOPEN_FILE, 0); + histogram_tester.ExpectBucketCount("SimpleCache.FileDescriptorLimiterAction", + disk_cache::FD_LIMIT_FAIL_REOPEN_FILE, 0); + + // Do some writes in [1...511] range, both testing bring those in and kicking + // out [0] and [alt_entry]. These have to be to stream != 0 to actually need + // files. + for (int i = 1; i < kNumEntries; ++i) { + EXPECT_EQ(kSize, WriteData(entries[i], 1, 0, buf1.get(), kSize, true)); + scoped_refptr<net::IOBuffer> read_buf(new net::IOBuffer(kSize)); + ASSERT_EQ(kSize, ReadData(entries[i], 1, 0, read_buf.get(), kSize)); + EXPECT_EQ(0, memcmp(read_buf->data(), buf1->data(), kSize)); + } + + histogram_tester.ExpectBucketCount("SimpleCache.FileDescriptorLimiterAction", + disk_cache::FD_LIMIT_CLOSE_FILE, + 512 - 64 + 1 + 511); + histogram_tester.ExpectBucketCount("SimpleCache.FileDescriptorLimiterAction", + disk_cache::FD_LIMIT_REOPEN_FILE, 511); + histogram_tester.ExpectBucketCount("SimpleCache.FileDescriptorLimiterAction", + disk_cache::FD_LIMIT_FAIL_REOPEN_FILE, 0); + EXPECT_EQ(kSize, WriteData(entries[0], 1, 0, buf1.get(), kSize, true)); + EXPECT_EQ(kSize, WriteData(alt_entry, 1, 0, buf2.get(), kSize, true)); + + scoped_refptr<net::IOBuffer> read_buf(new net::IOBuffer(kSize)); + ASSERT_EQ(kSize, ReadData(entries[0], 1, 0, read_buf.get(), kSize)); + EXPECT_EQ(0, memcmp(read_buf->data(), buf1->data(), kSize)); + + scoped_refptr<net::IOBuffer> read_buf2(new net::IOBuffer(kSize)); + ASSERT_EQ(kSize, ReadData(alt_entry, 1, 0, read_buf2.get(), kSize)); + EXPECT_EQ(0, memcmp(read_buf2->data(), buf2->data(), kSize)); + + // Two more things than last time --- entries[0] and |alt_entry| + histogram_tester.ExpectBucketCount("SimpleCache.FileDescriptorLimiterAction", + disk_cache::FD_LIMIT_CLOSE_FILE, + 512 - 64 + 1 + 511 + 2); + histogram_tester.ExpectBucketCount("SimpleCache.FileDescriptorLimiterAction", + disk_cache::FD_LIMIT_REOPEN_FILE, 513); + histogram_tester.ExpectBucketCount("SimpleCache.FileDescriptorLimiterAction", + disk_cache::FD_LIMIT_FAIL_REOPEN_FILE, 0); + + for (int i = 0; i < kNumEntries; ++i) { + entries[i]->Close(); + } + alt_entry->Close(); + NetTestSuite::GetScopedTaskEnvironment()->RunUntilIdle(); + + // Closes have to pull things in to write out the footer, but they also + // free up FDs, so we will only need to kick one more thing out. + histogram_tester.ExpectBucketCount("SimpleCache.FileDescriptorLimiterAction", + disk_cache::FD_LIMIT_CLOSE_FILE, + 512 - 64 + 1 + 511 + 2 + 1); + histogram_tester.ExpectBucketCount("SimpleCache.FileDescriptorLimiterAction", + disk_cache::FD_LIMIT_REOPEN_FILE, + 512 - 64 + 1 + 511 + 2 + 1); + histogram_tester.ExpectBucketCount("SimpleCache.FileDescriptorLimiterAction", + disk_cache::FD_LIMIT_FAIL_REOPEN_FILE, 0); +}
diff --git a/net/disk_cache/disk_cache_test_base.cc b/net/disk_cache/disk_cache_test_base.cc index b5483cf..2410d47 100644 --- a/net/disk_cache/disk_cache_test_base.cc +++ b/net/disk_cache/disk_cache_test_base.cc
@@ -327,8 +327,11 @@ if (simple_cache_mode_) { net::TestCompletionCallback cb; + // We limit ourselves to 64 fds since OS X by default gives us 256. + // (Chrome raises the number on startup, but the test fixture doesn't). if (!simple_file_tracker_) - simple_file_tracker_ = std::make_unique<disk_cache::SimpleFileTracker>(); + simple_file_tracker_ = + std::make_unique<disk_cache::SimpleFileTracker>(64); std::unique_ptr<disk_cache::SimpleBackendImpl> simple_backend = std::make_unique<disk_cache::SimpleBackendImpl>( cache_path_, /* cleanup_tracker = */ nullptr,
diff --git a/net/disk_cache/simple/simple_file_tracker.cc b/net/disk_cache/simple/simple_file_tracker.cc index f8bcce0..dd342b8 100644 --- a/net/disk_cache/simple/simple_file_tracker.cc +++ b/net/disk_cache/simple/simple_file_tracker.cc
@@ -10,63 +10,99 @@ #include <utility> #include "base/files/file.h" +#include "base/metrics/histogram_macros.h" #include "base/synchronization/lock.h" +#include "net/disk_cache/simple/simple_histogram_enums.h" #include "net/disk_cache/simple/simple_synchronous_entry.h" namespace disk_cache { -SimpleFileTracker::SimpleFileTracker() = default; +SimpleFileTracker::SimpleFileTracker(int file_limit) + : file_limit_(file_limit), open_files_(0) {} SimpleFileTracker::~SimpleFileTracker() { + DCHECK(lru_.empty()); DCHECK(tracked_files_.empty()); } void SimpleFileTracker::Register(const SimpleSynchronousEntry* owner, SubFile subfile, std::unique_ptr<base::File> file) { - base::AutoLock hold_lock(lock_); + DCHECK(file->IsValid()); + std::vector<std::unique_ptr<base::File>> files_to_close; - // Make sure the list exists. - auto insert_status = tracked_files_.insert(std::make_pair( - owner->entry_file_key().entry_hash, std::vector<TrackedFiles>())); + { + base::AutoLock hold_lock(lock_); - std::vector<TrackedFiles>& candidates = insert_status.first->second; + // Make sure the list of everything with given hash exists. + auto insert_status = tracked_files_.insert( + std::make_pair(owner->entry_file_key().entry_hash, + std::vector<std::unique_ptr<TrackedFiles>>())); - // See if entry already exists, if not append. - TrackedFiles* owners_files = nullptr; - for (TrackedFiles& candidate : candidates) { - if (candidate.owner == owner) { - owners_files = &candidate; - break; + std::vector<std::unique_ptr<TrackedFiles>>& candidates = + insert_status.first->second; + + // See if entry for |owner| already exists, if not append. + TrackedFiles* owners_files = nullptr; + for (const std::unique_ptr<TrackedFiles>& candidate : candidates) { + if (candidate->owner == owner) { + owners_files = candidate.get(); + break; + } } - } - if (!owners_files) { - candidates.emplace_back(); - owners_files = &candidates.back(); - owners_files->owner = owner; - owners_files->key = owner->entry_file_key(); - } + if (!owners_files) { + candidates.emplace_back(new TrackedFiles()); + owners_files = candidates.back().get(); + owners_files->owner = owner; + owners_files->key = owner->entry_file_key(); + } - int file_index = static_cast<int>(subfile); - DCHECK_EQ(TrackedFiles::TF_NO_REGISTRATION, owners_files->state[file_index]); - owners_files->files[file_index] = std::move(file); - owners_files->state[file_index] = TrackedFiles::TF_REGISTERED; + EnsureInFrontOfLRU(owners_files); + + int file_index = static_cast<int>(subfile); + DCHECK_EQ(TrackedFiles::TF_NO_REGISTRATION, + owners_files->state[file_index]); + owners_files->files[file_index] = std::move(file); + owners_files->state[file_index] = TrackedFiles::TF_REGISTERED; + ++open_files_; + CloseFilesIfTooManyOpen(&files_to_close); + } } SimpleFileTracker::FileHandle SimpleFileTracker::Acquire( const SimpleSynchronousEntry* owner, SubFile subfile) { - base::AutoLock hold_lock(lock_); - std::vector<TrackedFiles>::iterator owners_files = Find(owner); - int file_index = static_cast<int>(subfile); + std::vector<std::unique_ptr<base::File>> files_to_close; - DCHECK_EQ(TrackedFiles::TF_REGISTERED, owners_files->state[file_index]); - owners_files->state[file_index] = TrackedFiles::TF_ACQUIRED; - return FileHandle(this, owner, subfile, - owners_files->files[file_index].get()); + { + base::AutoLock hold_lock(lock_); + TrackedFiles* owners_files = Find(owner); + int file_index = static_cast<int>(subfile); + + DCHECK_EQ(TrackedFiles::TF_REGISTERED, owners_files->state[file_index]); + owners_files->state[file_index] = TrackedFiles::TF_ACQUIRED; + EnsureInFrontOfLRU(owners_files); + + // Check to see if we have to reopen the file. That might push us over the + // fd limit. CloseFilesIfTooManyOpen will not close anything in + // |*owners_files| since it's already in the the TF_ACQUIRED state. + if (owners_files->files[file_index] == nullptr) { + ReopenFile(owners_files, subfile); + CloseFilesIfTooManyOpen(&files_to_close); + } + + return FileHandle(this, owner, subfile, + owners_files->files[file_index].get()); + } } +SimpleFileTracker::TrackedFiles::TrackedFiles() : in_lru(false) { + std::fill(state, state + kSimpleEntryTotalFileCount, TF_NO_REGISTRATION); +} + +SimpleFileTracker::TrackedFiles::~TrackedFiles() = default; + bool SimpleFileTracker::TrackedFiles::Empty() const { for (State s : state) if (s != TF_NO_REGISTRATION) @@ -74,13 +110,20 @@ return true; } +bool SimpleFileTracker::TrackedFiles::HasOpenFiles() const { + for (const std::unique_ptr<base::File>& file : files) + if (file != nullptr) + return true; + return false; +} + void SimpleFileTracker::Release(const SimpleSynchronousEntry* owner, SubFile subfile) { - std::unique_ptr<base::File> file_to_close; + std::vector<std::unique_ptr<base::File>> files_to_close; { base::AutoLock hold_lock(lock_); - std::vector<TrackedFiles>::iterator owners_files = Find(owner); + TrackedFiles* owners_files = Find(owner); int file_index = static_cast<int>(subfile); DCHECK(owners_files->state[file_index] == TrackedFiles::TF_ACQUIRED || @@ -90,13 +133,16 @@ // Prepare to executed deferred close, if any. if (owners_files->state[file_index] == TrackedFiles::TF_ACQUIRED_PENDING_CLOSE) { - file_to_close = PrepareClose(owners_files, file_index); + files_to_close.push_back(PrepareClose(owners_files, file_index)); } else { owners_files->state[file_index] = TrackedFiles::TF_REGISTERED; } - } - // The destructor of file_to_close will close it if needed. + // It's possible that we were over limit and couldn't do much about it + // since everything was lent out, so now may be the time to close extra + // stuff. + CloseFilesIfTooManyOpen(&files_to_close); + } } void SimpleFileTracker::Close(const SimpleSynchronousEntry* owner, @@ -105,7 +151,7 @@ { base::AutoLock hold_lock(lock_); - std::vector<TrackedFiles>::iterator owners_files = Find(owner); + TrackedFiles* owners_files = Find(owner); int file_index = static_cast<int>(subfile); DCHECK(owners_files->state[file_index] == TrackedFiles::TF_ACQUIRED || @@ -120,10 +166,6 @@ file_to_close = PrepareClose(owners_files, file_index); } } - - // The destructor of file_to_close will close it if needed. Thing to watch - // for impl with stealing: race between bookkeeping above and actual - // close --- the FD is still alive for it. } void SimpleFileTracker::Doom(const SimpleSynchronousEntry* owner, @@ -133,9 +175,10 @@ DCHECK(iter != tracked_files_.end()); uint64_t max_doom_gen = 0; - for (const TrackedFiles& file_with_same_hash : iter->second) { + for (const std::unique_ptr<TrackedFiles>& file_with_same_hash : + iter->second) { max_doom_gen = - std::max(max_doom_gen, file_with_same_hash.key.doom_generation); + std::max(max_doom_gen, file_with_same_hash->key.doom_generation); } // It would take >502 years to doom the same hash enough times (at 10^9 dooms @@ -148,46 +191,120 @@ key->doom_generation = new_doom_gen; // Update our own. - for (TrackedFiles& file_with_same_hash : iter->second) { - if (file_with_same_hash.owner == owner) - file_with_same_hash.key.doom_generation = new_doom_gen; + for (const std::unique_ptr<TrackedFiles>& file_with_same_hash : + iter->second) { + if (file_with_same_hash->owner == owner) + file_with_same_hash->key.doom_generation = new_doom_gen; } } bool SimpleFileTracker::IsEmptyForTesting() { base::AutoLock hold_lock(lock_); - return tracked_files_.empty(); + return tracked_files_.empty() && lru_.empty(); } -std::vector<SimpleFileTracker::TrackedFiles>::iterator SimpleFileTracker::Find( +SimpleFileTracker::TrackedFiles* SimpleFileTracker::Find( const SimpleSynchronousEntry* owner) { auto candidates = tracked_files_.find(owner->entry_file_key().entry_hash); DCHECK(candidates != tracked_files_.end()); - for (std::vector<TrackedFiles>::iterator i = candidates->second.begin(); - i != candidates->second.end(); ++i) { - if (i->owner == owner) { - return i; + for (const auto& candidate : candidates->second) { + if (candidate->owner == owner) { + return candidate.get(); } } LOG(DFATAL) << "SimpleFileTracker operation on non-found entry"; - return candidates->second.end(); + return nullptr; } std::unique_ptr<base::File> SimpleFileTracker::PrepareClose( - std::vector<TrackedFiles>::iterator owners_files, + TrackedFiles* owners_files, int file_index) { std::unique_ptr<base::File> file_out = std::move(owners_files->files[file_index]); owners_files->state[file_index] = TrackedFiles::TF_NO_REGISTRATION; if (owners_files->Empty()) { auto iter = tracked_files_.find(owners_files->key.entry_hash); - iter->second.erase(owners_files); + for (auto i = iter->second.begin(); i != iter->second.end(); ++i) { + if ((*i).get() == owners_files) { + if (owners_files->in_lru) + lru_.erase(owners_files->position_in_lru); + iter->second.erase(i); + break; + } + } if (iter->second.empty()) tracked_files_.erase(iter); } + if (file_out != nullptr) + --open_files_; return file_out; } +void SimpleFileTracker::CloseFilesIfTooManyOpen( + std::vector<std::unique_ptr<base::File>>* files_to_close) { + std::list<TrackedFiles*>::iterator i = lru_.end(); + while (open_files_ > file_limit_ && i != lru_.begin()) { + --i; // Point to the actual entry. + TrackedFiles* tracked_files = *i; + DCHECK(tracked_files->in_lru); + for (int j = 0; j < kSimpleEntryTotalFileCount; ++j) { + if (tracked_files->state[j] == TrackedFiles::TF_REGISTERED && + tracked_files->files[j] != nullptr) { + files_to_close->push_back(std::move(tracked_files->files[j])); + --open_files_; + UMA_HISTOGRAM_ENUMERATION("SimpleCache.FileDescriptorLimiterAction", + FD_LIMIT_CLOSE_FILE, FD_LIMIT_OP_MAX); + } + } + + if (!tracked_files->HasOpenFiles()) { + // If there is nothing here that can possibly be closed, remove this from + // LRU for now so we don't have to rescan it next time we are here. If the + // files get re-opened (in Acquire), it will get added back in. + DCHECK_EQ(*tracked_files->position_in_lru, tracked_files); + DCHECK(i == tracked_files->position_in_lru); + // Note that we're erasing at i, which would make it invalid, so go back + // one element ahead to we can decrement from that on next iteration. + ++i; + lru_.erase(tracked_files->position_in_lru); + tracked_files->in_lru = false; + } + } +} + +void SimpleFileTracker::ReopenFile(TrackedFiles* owners_files, + SubFile subfile) { + int file_index = static_cast<int>(subfile); + DCHECK(owners_files->files[file_index] == nullptr); + int flags = base::File::FLAG_OPEN | base::File::FLAG_READ | + base::File::FLAG_WRITE | base::File::FLAG_SHARE_DELETE; + base::FilePath file_path = + owners_files->owner->GetFilenameForSubfile(subfile); + owners_files->files[file_index] = + std::make_unique<base::File>(file_path, flags); + if (owners_files->files[file_index]->IsValid()) { + UMA_HISTOGRAM_ENUMERATION("SimpleCache.FileDescriptorLimiterAction", + FD_LIMIT_REOPEN_FILE, FD_LIMIT_OP_MAX); + + ++open_files_; + } else { + owners_files->files[file_index] = nullptr; + UMA_HISTOGRAM_ENUMERATION("SimpleCache.FileDescriptorLimiterAction", + FD_LIMIT_FAIL_REOPEN_FILE, FD_LIMIT_OP_MAX); + } +} + +void SimpleFileTracker::EnsureInFrontOfLRU(TrackedFiles* owners_files) { + if (!owners_files->in_lru) { + lru_.push_front(owners_files); + owners_files->position_in_lru = lru_.begin(); + owners_files->in_lru = true; + } else if (owners_files->position_in_lru != lru_.begin()) { + lru_.splice(lru_.begin(), lru_, owners_files->position_in_lru); + } + DCHECK_EQ(*owners_files->position_in_lru, owners_files); +} + SimpleFileTracker::FileHandle::FileHandle() : file_tracker_(nullptr), entry_(nullptr), file_(nullptr) {}
diff --git a/net/disk_cache/simple/simple_file_tracker.h b/net/disk_cache/simple/simple_file_tracker.h index edc646a..2f590a2 100644 --- a/net/disk_cache/simple/simple_file_tracker.h +++ b/net/disk_cache/simple/simple_file_tracker.h
@@ -7,6 +7,7 @@ #include <stdint.h> #include <algorithm> +#include <list> #include <memory> #include <unordered_map> #include <vector> @@ -84,14 +85,16 @@ uint64_t doom_generation; }; - SimpleFileTracker(); + // The default limit here is half of what's available on our target OS where + // Chrome has the lowest limit. + SimpleFileTracker(int file_limit = 512); ~SimpleFileTracker(); // Established |file| as what's backing |subfile| for |owner|. This is // intended to be called when SimpleSynchronousEntry first sets up the file to // transfer its ownership to SimpleFileTracker. Any Register() call must be // eventually followed by a corresponding Close() call before the |owner| is - // destroyed. + // destroyed. |file->IsValid()| must be true. void Register(const SimpleSynchronousEntry* owner, SubFile subfile, std::unique_ptr<base::File> file); @@ -139,12 +142,17 @@ TF_ACQUIRED_PENDING_CLOSE = 3, }; - TrackedFiles() { - std::fill(state, state + kSimpleEntryTotalFileCount, TF_NO_REGISTRATION); - } + NET_EXPORT_PRIVATE TrackedFiles(); + NET_EXPORT_PRIVATE ~TrackedFiles(); + // True if this isn't keeping track of anything any more. bool Empty() const; + // True if this has open files. Note that this is not the same as !Empty() + // as this may be false when an entry had its files temporarily closed, but + // is still relevant. + bool HasOpenFiles() const; + // We use pointers to SimpleSynchronousEntry two ways: // 1) As opaque keys. This is handy as it avoids having to compare paths in // case multiple backends use the same key. Since we access the @@ -156,30 +164,61 @@ const SimpleSynchronousEntry* owner; EntryFileKey key; - // Some of these may be !IsValid(), if they are not open. + // Some of these may be nullptr, if they are not open. Non-null pointers + // to files that are not valid will not be stored here. // Note that these are stored indirect since we hand out pointers to these, // and we don't want those to become invalid if some other thread appends // things here. std::unique_ptr<base::File> files[kSimpleEntryTotalFileCount]; State state[kSimpleEntryTotalFileCount]; + std::list<TrackedFiles*>::iterator position_in_lru; + + // true if position_in_lru is valid. For entries where we closed everything, + // we try not to keep them in the LRU so that we don't have to constantly + // rescan them. + bool in_lru; }; // Marks the file that was previously returned by Acquire as eligible for // closing again. Called by ~FileHandle. void Release(const SimpleSynchronousEntry* owner, SubFile subfile); - // |*found| will be set to whether the entry was found or not. - std::vector<TrackedFiles>::iterator Find(const SimpleSynchronousEntry* owner); + // Precondition: entry for given |owner| must already be in tracked_files_ + TrackedFiles* Find(const SimpleSynchronousEntry* owner); // Handles state transition of closing file (when we are not deferring it), - // and moves the file out. Note that this may invalidate |owners_files|. - std::unique_ptr<base::File> PrepareClose( - std::vector<TrackedFiles>::iterator owners_files, - int file_index); + // and moves the file out. Note that this may delete |*owners_files|. + std::unique_ptr<base::File> PrepareClose(TrackedFiles* owners_files, + int file_index); + + // If too many files are open, picks some to close, and moves them to + // |*files_to_close|, updating other state as appropriate. + void CloseFilesIfTooManyOpen( + std::vector<std::unique_ptr<base::File>>* files_to_close); + + // Tries to reopen given file, updating |*owners_files| if successful. + void ReopenFile(TrackedFiles* owners_files, SubFile subfile); + + // Makes sure the entry is marked as most recently used, adding it to LRU + // if needed. + void EnsureInFrontOfLRU(TrackedFiles* owners_files); base::Lock lock_; - std::unordered_map<uint64_t, std::vector<TrackedFiles>> tracked_files_; + std::unordered_map<uint64_t, std::vector<std::unique_ptr<TrackedFiles>>> + tracked_files_; + std::list<TrackedFiles*> lru_; + + int file_limit_; + + // How many actually open files we are using. + // Note that when a thread commits to closing a file, but hasn't actually + // executed the close yet, the file is no longer counted as open here, so this + // might be a little off. This should be OK as long as file_limit_ is set + // conservatively, considering SimpleCache's parallelism is bounded by a low + // number of threads, and getting it exact would require re-acquiring the + // lock after closing the file. + int open_files_; DISALLOW_COPY_AND_ASSIGN(SimpleFileTracker); };
diff --git a/net/disk_cache/simple/simple_file_tracker_unittest.cc b/net/disk_cache/simple/simple_file_tracker_unittest.cc index 87fb58b..82e0761 100644 --- a/net/disk_cache/simple/simple_file_tracker_unittest.cc +++ b/net/disk_cache/simple/simple_file_tracker_unittest.cc
@@ -11,9 +11,12 @@ #include "base/logging.h" #include "base/strings/string_number_conversions.h" #include "base/strings/string_piece.h" +#include "base/strings/string_util.h" +#include "base/test/histogram_tester.h" #include "net/base/cache_type.h" #include "net/disk_cache/disk_cache_test_base.h" #include "net/disk_cache/simple/simple_file_tracker.h" +#include "net/disk_cache/simple/simple_histogram_enums.h" #include "net/disk_cache/simple/simple_synchronous_entry.h" #include "testing/gtest/include/gtest/gtest.h" @@ -23,7 +26,14 @@ public: void DeleteSyncEntry(SimpleSynchronousEntry* entry) { delete entry; } + // We limit open files to 4 for the fixture, as this is large enough + // that simple tests don't have to worry about naming files normally, + // but small enough to test with easily. + static const int kFileLimit = 4; + protected: + SimpleFileTrackerTest() : file_tracker_(kFileLimit) {} + // A bit of messiness since we rely on friendship of the fixture to be able to // create/delete SimpleSynchronousEntry objects. class SyncEntryDeleter { @@ -47,6 +57,11 @@ SyncEntryDeleter(this)); } + void UpdateEntryFileKey(SimpleSynchronousEntry* sync_entry, + SimpleFileTracker::EntryFileKey file_key) { + sync_entry->entry_file_key_ = file_key; + } + SimpleFileTracker file_tracker_; }; @@ -166,10 +181,11 @@ std::move(file_1)); file_tracker_.Close(entry.get(), SimpleFileTracker::SubFile::FILE_1); - base::File file_1b(path_1, base::File::FLAG_OPEN | base::File::FLAG_WRITE); - ASSERT_TRUE(file_1b.IsValid()); + std::unique_ptr<base::File> file_1b = std::make_unique<base::File>( + path_1, base::File::FLAG_OPEN | base::File::FLAG_WRITE); + ASSERT_TRUE(file_1b->IsValid()); file_tracker_.Register(entry.get(), SimpleFileTracker::SubFile::FILE_1, - std::move(file_1)); + std::move(file_1b)); file_tracker_.Close(entry.get(), SimpleFileTracker::SubFile::FILE_0); file_tracker_.Close(entry.get(), SimpleFileTracker::SubFile::FILE_1); EXPECT_TRUE(file_tracker_.IsEmptyForTesting()); @@ -249,4 +265,116 @@ file_tracker_.Close(entry2.get(), SimpleFileTracker::SubFile::FILE_0); } +TEST_F(SimpleFileTrackerTest, OverLimit) { + base::HistogramTester histogram_tester; + + const int kEntries = 10; // want more than FD limit in fixture. + std::vector<SyncEntryPointer> entries; + std::vector<base::FilePath> names; + for (int i = 0; i < kEntries; ++i) { + SyncEntryPointer entry = MakeSyncEntry(i); + base::FilePath name = + entry->GetFilenameForSubfile(SimpleFileTracker::SubFile::FILE_0); + std::unique_ptr<base::File> file = std::make_unique<base::File>( + name, base::File::FLAG_CREATE | base::File::FLAG_WRITE | + base::File::FLAG_READ); + ASSERT_TRUE(file->IsValid()); + file_tracker_.Register(entry.get(), SimpleFileTracker::SubFile::FILE_0, + std::move(file)); + entries.push_back(std::move(entry)); + names.push_back(name); + } + + histogram_tester.ExpectBucketCount("SimpleCache.FileDescriptorLimiterAction", + disk_cache::FD_LIMIT_CLOSE_FILE, + kEntries - kFileLimit); + histogram_tester.ExpectBucketCount("SimpleCache.FileDescriptorLimiterAction", + disk_cache::FD_LIMIT_REOPEN_FILE, 0); + histogram_tester.ExpectBucketCount("SimpleCache.FileDescriptorLimiterAction", + disk_cache::FD_LIMIT_FAIL_REOPEN_FILE, 0); + + // Grab the last one; we will hold it open till the end of the test. It's + // still open, so no change in stats after. + SimpleFileTracker::FileHandle borrow_last = file_tracker_.Acquire( + entries[kEntries - 1].get(), SimpleFileTracker::SubFile::FILE_0); + EXPECT_EQ(1, borrow_last->Write(0, "L", 1)); + + histogram_tester.ExpectBucketCount("SimpleCache.FileDescriptorLimiterAction", + disk_cache::FD_LIMIT_CLOSE_FILE, + kEntries - kFileLimit); + histogram_tester.ExpectBucketCount("SimpleCache.FileDescriptorLimiterAction", + disk_cache::FD_LIMIT_REOPEN_FILE, 0); + histogram_tester.ExpectBucketCount("SimpleCache.FileDescriptorLimiterAction", + disk_cache::FD_LIMIT_FAIL_REOPEN_FILE, 0); + + // Delete file for [2], to cause error on its re-open. + EXPECT_TRUE(base::DeleteFile(names[2], false)) << names[2]; + + // Reacquire all the other files. + for (int i = 0; i < kEntries - 1; ++i) { + SimpleFileTracker::FileHandle borrow = file_tracker_.Acquire( + entries[i].get(), SimpleFileTracker::SubFile::FILE_0); + if (i != 2) { + EXPECT_TRUE(borrow.IsOK()); + char c = static_cast<char>(i); + EXPECT_EQ(1, borrow->Write(0, &c, 1)); + } else { + EXPECT_FALSE(borrow.IsOK()); + } + } + + histogram_tester.ExpectBucketCount("SimpleCache.FileDescriptorLimiterAction", + disk_cache::FD_LIMIT_CLOSE_FILE, + kEntries - kFileLimit + kEntries - 2); + histogram_tester.ExpectBucketCount("SimpleCache.FileDescriptorLimiterAction", + disk_cache::FD_LIMIT_REOPEN_FILE, + kEntries - 2); + histogram_tester.ExpectBucketCount("SimpleCache.FileDescriptorLimiterAction", + disk_cache::FD_LIMIT_FAIL_REOPEN_FILE, 1); + + // Doom file for [1]. + SimpleFileTracker::EntryFileKey key = entries[1]->entry_file_key(); + file_tracker_.Doom(entries[1].get(), &key); + base::FilePath old_path = names[1]; + UpdateEntryFileKey(entries[1].get(), key); + base::FilePath new_path = + entries[1]->GetFilenameForSubfile(SimpleFileTracker::SubFile::FILE_0); + EXPECT_TRUE(base::StartsWith(new_path.BaseName().MaybeAsASCII(), "todelete_", + base::CompareCase::SENSITIVE)); + EXPECT_TRUE(base::Move(old_path, new_path)); + + // Now re-acquire everything again; this time reading. + for (int i = 0; i < kEntries - 1; ++i) { + SimpleFileTracker::FileHandle borrow = file_tracker_.Acquire( + entries[i].get(), SimpleFileTracker::SubFile::FILE_0); + char read; + char expected = static_cast<char>(i); + if (i != 2) { + EXPECT_TRUE(borrow.IsOK()); + EXPECT_EQ(1, borrow->Read(0, &read, 1)); + EXPECT_EQ(expected, read); + } else { + EXPECT_FALSE(borrow.IsOK()); + } + } + + histogram_tester.ExpectBucketCount( + "SimpleCache.FileDescriptorLimiterAction", + disk_cache::FD_LIMIT_CLOSE_FILE, + kEntries - kFileLimit + 2 * (kEntries - 2)); + histogram_tester.ExpectBucketCount("SimpleCache.FileDescriptorLimiterAction", + disk_cache::FD_LIMIT_REOPEN_FILE, + 2 * (kEntries - 2)); + histogram_tester.ExpectBucketCount("SimpleCache.FileDescriptorLimiterAction", + disk_cache::FD_LIMIT_FAIL_REOPEN_FILE, 2); + + // Read from the last one, too. Should still be fine. + char read; + EXPECT_EQ(1, borrow_last->Read(0, &read, 1)); + EXPECT_EQ('L', read); + + for (const auto& entry : entries) + file_tracker_.Close(entry.get(), SimpleFileTracker::SubFile::FILE_0); +}; + } // namespace disk_cache
diff --git a/net/disk_cache/simple/simple_histogram_enums.h b/net/disk_cache/simple/simple_histogram_enums.h index 883753d2..8f6d40b 100644 --- a/net/disk_cache/simple/simple_histogram_enums.h +++ b/net/disk_cache/simple/simple_histogram_enums.h
@@ -71,6 +71,14 @@ MAX = 3 }; +// Used in histograms, please only add entries at the end. +enum FileDescriptorLimiterOp { + FD_LIMIT_CLOSE_FILE = 0, + FD_LIMIT_REOPEN_FILE = 1, + FD_LIMIT_FAIL_REOPEN_FILE = 2, + FD_LIMIT_OP_MAX = 3 +}; + } // namespace disk_cache #endif // NET_DISK_CACHE_SIMPLE_SIMPLE_HISTOGRAM_ENUMS_H_
diff --git a/net/disk_cache/simple/simple_synchronous_entry.cc b/net/disk_cache/simple/simple_synchronous_entry.cc index 70a4b12..1e4a63d 100644 --- a/net/disk_cache/simple/simple_synchronous_entry.cc +++ b/net/disk_cache/simple/simple_synchronous_entry.cc
@@ -114,6 +114,11 @@ : SimpleFileTracker::SubFile::FILE_1; } +int FileIndexForSubFile(SimpleFileTracker::SubFile sub_file) { + DCHECK_NE(SimpleFileTracker::SubFile::FILE_SPARSE, sub_file); + return sub_file == SimpleFileTracker::SubFile::FILE_0 ? 0 : 1; +} + } // namespace using simple_util::GetEntryHashKey; @@ -1564,11 +1569,21 @@ } } -FilePath SimpleSynchronousEntry::GetFilenameFromFileIndex(int file_index) { +FilePath SimpleSynchronousEntry::GetFilenameFromFileIndex( + int file_index) const { return path_.AppendASCII( GetFilenameFromEntryFileKeyAndFileIndex(entry_file_key_, file_index)); } +base::FilePath SimpleSynchronousEntry::GetFilenameForSubfile( + SimpleFileTracker::SubFile sub_file) const { + if (sub_file == SimpleFileTracker::SubFile::FILE_SPARSE) + return path_.AppendASCII( + GetSparseFilenameFromEntryFileKey(entry_file_key_)); + else + return GetFilenameFromFileIndex(FileIndexForSubFile(sub_file)); +} + bool SimpleSynchronousEntry::OpenSparseFileIfExists( int32_t* out_sparse_data_size) { DCHECK(!sparse_file_open());
diff --git a/net/disk_cache/simple/simple_synchronous_entry.h b/net/disk_cache/simple/simple_synchronous_entry.h index a46a61e..0539dd1 100644 --- a/net/disk_cache/simple/simple_synchronous_entry.h +++ b/net/disk_cache/simple/simple_synchronous_entry.h
@@ -248,6 +248,9 @@ return entry_file_key_; } + NET_EXPORT_PRIVATE base::FilePath GetFilenameForSubfile( + SimpleFileTracker::SubFile sub_file) const; + private: FRIEND_TEST_ALL_PREFIXES(::DiskCacheBackendTest, SimpleCacheEnumerationLongKeys); @@ -424,7 +427,7 @@ void RecordSyncCreateResult(CreateEntryResult result, bool had_index); - base::FilePath GetFilenameFromFileIndex(int file_index); + base::FilePath GetFilenameFromFileIndex(int file_index) const; bool sparse_file_open() const { return sparse_file_open_; }
diff --git a/net/dns/mojo_host_struct_traits.cc b/net/dns/mojo_host_struct_traits.cc index 4ba742d..94afcd6 100644 --- a/net/dns/mojo_host_struct_traits.cc +++ b/net/dns/mojo_host_struct_traits.cc
@@ -8,7 +8,7 @@ #include "base/memory/ptr_util.h" #include "net/base/address_list.h" -#include "net/interfaces/address_family_traits.h" +#include "net/interfaces/address_family_mojom_traits.h" #include "net/interfaces/ip_endpoint_struct_traits.h" namespace mojo {
diff --git a/net/extras/sqlite/sqlite_persistent_cookie_store.cc b/net/extras/sqlite/sqlite_persistent_cookie_store.cc index 7f94dda..59a1ac028 100644 --- a/net/extras/sqlite/sqlite_persistent_cookie_store.cc +++ b/net/extras/sqlite/sqlite_persistent_cookie_store.cc
@@ -457,15 +457,9 @@ if (!db->Execute("CREATE INDEX domain ON cookies(host_key)")) return false; -#if defined(OS_IOS) - // iOS 8.1 and older doesn't support partial indices. iOS 8.2 supports - // partial indices. - if (!db->Execute("CREATE INDEX is_transient ON cookies(persistent)")) { -#else if (!db->Execute( "CREATE INDEX is_transient ON cookies(persistent) " "where persistent != 1")) { -#endif return false; }
diff --git a/net/http/http_network_transaction_unittest.cc b/net/http/http_network_transaction_unittest.cc index 3eccb84..d9affe3 100644 --- a/net/http/http_network_transaction_unittest.cc +++ b/net/http/http_network_transaction_unittest.cc
@@ -52,7 +52,6 @@ #include "net/http/http_auth_handler_mock.h" #include "net/http/http_auth_handler_ntlm.h" #include "net/http/http_auth_scheme.h" -#include "net/http/http_basic_state.h" #include "net/http/http_basic_stream.h" #include "net/http/http_network_session.h" #include "net/http/http_network_session_peer.h" @@ -61,7 +60,6 @@ #include "net/http/http_server_properties_impl.h" #include "net/http/http_stream.h" #include "net/http/http_stream_factory.h" -#include "net/http/http_stream_parser.h" #include "net/http/http_transaction_test_util.h" #include "net/log/net_log.h" #include "net/log/net_log_event_type.h" @@ -100,6 +98,7 @@ #include "net/test/test_data_directory.h" #include "net/traffic_annotation/network_traffic_annotation_test_helper.h" #include "net/websockets/websocket_handshake_stream_base.h" +#include "net/websockets/websocket_test_util.h" #include "testing/gmock/include/gmock/gmock.h" #include "testing/gtest/include/gtest/gtest.h" #include "testing/platform_test.h" @@ -354,14 +353,6 @@ EXPECT_TRUE(load_timing_info.receive_headers_end.is_null()); } -void AddWebSocketHeaders(HttpRequestHeaders* headers) { - headers->SetHeader("Connection", "Upgrade"); - headers->SetHeader("Upgrade", "websocket"); - headers->SetHeader("Origin", "http://www.example.org"); - headers->SetHeader("Sec-WebSocket-Version", "13"); - headers->SetHeader("Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ=="); -} - std::unique_ptr<HttpNetworkSession> CreateSession( SpdySessionDependencies* session_deps) { return SpdySessionDependencies::SpdyCreateSession(session_deps); @@ -16004,147 +15995,6 @@ DISALLOW_COPY_AND_ASSIGN(FakeStreamFactory); }; -// TODO(ricea): Maybe unify this with the one in -// url_request_http_job_unittest.cc ? -class FakeWebSocketBasicHandshakeStream : public WebSocketHandshakeStreamBase { - public: - FakeWebSocketBasicHandshakeStream( - std::unique_ptr<ClientSocketHandle> connection, - bool using_proxy) - : state_(std::move(connection), using_proxy, false) {} - - // Fake implementation of HttpStreamBase methods. - // This ends up being quite "real" because this object has to really send data - // on the mock socket. It might be easier to use the real implementation, but - // the fact that the WebSocket code is not compiled on iOS makes that - // difficult. - int InitializeStream(const HttpRequestInfo* request_info, - bool can_send_early, - RequestPriority priority, - const NetLogWithSource& net_log, - const CompletionCallback& callback) override { - state_.Initialize(request_info, can_send_early, priority, net_log, - callback); - return OK; - } - - int SendRequest(const HttpRequestHeaders& request_headers, - HttpResponseInfo* response, - const CompletionCallback& callback) override { - return parser()->SendRequest(state_.GenerateRequestLine(), request_headers, - TRAFFIC_ANNOTATION_FOR_TESTS, response, - callback); - } - - int ReadResponseHeaders(const CompletionCallback& callback) override { - return parser()->ReadResponseHeaders(callback); - } - - int ReadResponseBody(IOBuffer* buf, - int buf_len, - const CompletionCallback& callback) override { - NOTREACHED(); - return ERR_IO_PENDING; - } - - void Close(bool not_reusable) override { - if (parser()) - parser()->Close(true); - } - - bool IsResponseBodyComplete() const override { - NOTREACHED(); - return false; - } - - bool IsConnectionReused() const override { - NOTREACHED(); - return false; - } - void SetConnectionReused() override { NOTREACHED(); } - - bool CanReuseConnection() const override { return false; } - - int64_t GetTotalReceivedBytes() const override { - NOTREACHED(); - return 0; - } - - int64_t GetTotalSentBytes() const override { - NOTREACHED(); - return 0; - } - - bool GetLoadTimingInfo(LoadTimingInfo* load_timing_info) const override { - NOTREACHED(); - return false; - } - - bool GetAlternativeService( - AlternativeService* alternative_service) const override { - ADD_FAILURE(); - return false; - } - - void GetSSLInfo(SSLInfo* ssl_info) override {} - - void GetSSLCertRequestInfo(SSLCertRequestInfo* cert_request_info) override { - NOTREACHED(); - } - - bool GetRemoteEndpoint(IPEndPoint* endpoint) override { return false; } - - Error GetTokenBindingSignature(crypto::ECPrivateKey* key, - TokenBindingType tb_type, - std::vector<uint8_t>* out) override { - ADD_FAILURE(); - return ERR_NOT_IMPLEMENTED; - } - - void Drain(HttpNetworkSession* session) override { NOTREACHED(); } - - void PopulateNetErrorDetails(NetErrorDetails* details) override { return; } - - void SetPriority(RequestPriority priority) override { NOTREACHED(); } - - HttpStream* RenewStreamForAuth() override { - NOTREACHED(); - return nullptr; - } - - // Fake implementation of WebSocketHandshakeStreamBase method(s) - std::unique_ptr<WebSocketStream> Upgrade() override { - NOTREACHED(); - return std::unique_ptr<WebSocketStream>(); - } - - private: - HttpStreamParser* parser() const { return state_.parser(); } - HttpBasicState state_; - - DISALLOW_COPY_AND_ASSIGN(FakeWebSocketBasicHandshakeStream); -}; - -// TODO(yhirano): Split this class out into a net/websockets file, if it is -// worth doing. -class FakeWebSocketStreamCreateHelper : - public WebSocketHandshakeStreamBase::CreateHelper { - public: - std::unique_ptr<WebSocketHandshakeStreamBase> CreateBasicStream( - std::unique_ptr<ClientSocketHandle> connection, - bool using_proxy) override { - return std::make_unique<FakeWebSocketBasicHandshakeStream>( - std::move(connection), using_proxy); - } - - ~FakeWebSocketStreamCreateHelper() override = default; - - virtual std::unique_ptr<WebSocketStream> Upgrade() { - NOTREACHED(); - return std::unique_ptr<WebSocketStream>(); - } -}; - } // namespace // Make sure that HttpNetworkTransaction passes on its priority to its @@ -16221,39 +16071,6 @@ EXPECT_EQ(LOWEST, fake_stream->priority()); } -TEST_F(HttpNetworkTransactionTest, CreateWebSocketHandshakeStream) { - // The same logic needs to be tested for both ws: and wss: schemes, but this - // test is already parameterised on NextProto, so it uses a loop to verify - // that the different schemes work. - std::string test_cases[] = {"ws://www.example.org/", - "wss://www.example.org/"}; - for (size_t i = 0; i < arraysize(test_cases); ++i) { - std::unique_ptr<HttpNetworkSession> session(CreateSession(&session_deps_)); - HttpNetworkSessionPeer peer(session.get()); - FakeStreamFactory* fake_factory = new FakeStreamFactory(); - FakeWebSocketStreamCreateHelper websocket_stream_create_helper; - peer.SetHttpStreamFactory(std::unique_ptr<HttpStreamFactory>(fake_factory)); - - HttpRequestInfo request; - HttpNetworkTransaction trans(LOW, session.get()); - trans.SetWebSocketHandshakeStreamCreateHelper( - &websocket_stream_create_helper); - - TestCompletionCallback callback; - request.method = "GET"; - request.url = GURL(test_cases[i]); - - EXPECT_EQ(ERR_IO_PENDING, - trans.Start(&request, callback.callback(), NetLogWithSource())); - - base::WeakPtr<FakeStreamRequest> fake_request = - fake_factory->last_stream_request(); - ASSERT_TRUE(fake_request); - EXPECT_EQ(&websocket_stream_create_helper, - fake_request->websocket_stream_create_helper()); - } -} - // Tests that when a used socket is returned to the SSL socket pool, it's closed // if the transport socket pool is stalled on the global socket limit. TEST_F(HttpNetworkTransactionTest, CloseSSLSocketOnIdleForHttpRequest) { @@ -16875,6 +16692,53 @@ EXPECT_THAT(rv, IsError(ERR_CONNECTION_RESET)); } +#if BUILDFLAG(ENABLE_WEBSOCKETS) + +namespace { + +void AddWebSocketHeaders(HttpRequestHeaders* headers) { + headers->SetHeader("Connection", "Upgrade"); + headers->SetHeader("Upgrade", "websocket"); + headers->SetHeader("Origin", "http://www.example.org"); + headers->SetHeader("Sec-WebSocket-Version", "13"); + headers->SetHeader("Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ=="); +} + +} // namespace + +TEST_F(HttpNetworkTransactionTest, CreateWebSocketHandshakeStream) { + // The same logic needs to be tested for both ws: and wss: schemes, but this + // test is already parameterised on NextProto, so it uses a loop to verify + // that the different schemes work. + std::string test_cases[] = {"ws://www.example.org/", + "wss://www.example.org/"}; + for (size_t i = 0; i < arraysize(test_cases); ++i) { + std::unique_ptr<HttpNetworkSession> session(CreateSession(&session_deps_)); + HttpNetworkSessionPeer peer(session.get()); + FakeStreamFactory* fake_factory = new FakeStreamFactory(); + peer.SetHttpStreamFactory(std::unique_ptr<HttpStreamFactory>(fake_factory)); + + HttpRequestInfo request; + request.method = "GET"; + request.url = GURL(test_cases[i]); + + FakeWebSocketStreamCreateHelper websocket_stream_create_helper; + HttpNetworkTransaction trans(LOW, session.get()); + trans.SetWebSocketHandshakeStreamCreateHelper( + &websocket_stream_create_helper); + + TestCompletionCallback callback; + EXPECT_EQ(ERR_IO_PENDING, + trans.Start(&request, callback.callback(), NetLogWithSource())); + + base::WeakPtr<FakeStreamRequest> fake_request = + fake_factory->last_stream_request(); + ASSERT_TRUE(fake_request); + EXPECT_EQ(&websocket_stream_create_helper, + fake_request->websocket_stream_create_helper()); + } +} + // Verify that proxy headers are not sent to the destination server when // establishing a tunnel for a secure WebSocket connection. TEST_F(HttpNetworkTransactionTest, ProxyHeadersNotSentOverWssTunnel) { @@ -17057,6 +16921,8 @@ session->CloseAllConnections(); } +#endif // BUILDFLAG(ENABLE_WEBSOCKETS) + TEST_F(HttpNetworkTransactionTest, TotalNetworkBytesPost) { std::vector<std::unique_ptr<UploadElementReader>> element_readers; element_readers.push_back(
diff --git a/net/interfaces/OWNERS b/net/interfaces/OWNERS index 2c44a46..b957a91 100644 --- a/net/interfaces/OWNERS +++ b/net/interfaces/OWNERS
@@ -4,3 +4,5 @@ per-file *_struct_traits*.*=file://ipc/SECURITY_OWNERS per-file *.typemap=set noparent per-file *.typemap=file://ipc/SECURITY_OWNERS +per-file *_mojom_traits*.*=set noparent +per-file *_mojom_traits*.*=file://ipc/SECURITY_OWNERS
diff --git a/net/interfaces/address_family.typemap b/net/interfaces/address_family.typemap index 89e9459..65bf219b 100644 --- a/net/interfaces/address_family.typemap +++ b/net/interfaces/address_family.typemap
@@ -4,9 +4,9 @@ mojom = "//net/interfaces/address_family.mojom" public_headers = [ "//net/base/address_family.h" ] -traits_headers = [ "//net/interfaces/address_family_traits.h" ] +traits_headers = [ "//net/interfaces/address_family_mojom_traits.h" ] sources = [ - "//net/interfaces/address_family_traits.cc", + "//net/interfaces/address_family_mojom_traits.cc", ] type_mappings = [ "net.interfaces.AddressFamily=net::AddressFamily" ] public_deps = [
diff --git a/net/interfaces/address_family_traits.cc b/net/interfaces/address_family_mojom_traits.cc similarity index 95% rename from net/interfaces/address_family_traits.cc rename to net/interfaces/address_family_mojom_traits.cc index efb947d..86695ae 100644 --- a/net/interfaces/address_family_traits.cc +++ b/net/interfaces/address_family_mojom_traits.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 "net/interfaces/address_family_traits.h" +#include "net/interfaces/address_family_mojom_traits.h" namespace mojo {
diff --git a/net/interfaces/address_family_traits.h b/net/interfaces/address_family_mojom_traits.h similarity index 78% rename from net/interfaces/address_family_traits.h rename to net/interfaces/address_family_mojom_traits.h index 875b779..32061c23 100644 --- a/net/interfaces/address_family_traits.h +++ b/net/interfaces/address_family_mojom_traits.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 NET_INTERFACES_ADDRESS_FAMILY_TRAITS_H_ -#define NET_INTERFACES_ADDRESS_FAMILY_TRAITS_H_ +#ifndef NET_INTERFACES_ADDRESS_FAMILY_MOJOM_TRAITS_H_ +#define NET_INTERFACES_ADDRESS_FAMILY_MOJOM_TRAITS_H_ #include "mojo/public/cpp/bindings/enum_traits.h" #include "net/interfaces/address_family.mojom.h" @@ -20,4 +20,4 @@ } // namespace mojo -#endif // NET_INTERFACES_ADDRESS_FAMILY_TRAITS_H_ +#endif // NET_INTERFACES_ADDRESS_FAMILY_MOJOM_TRAITS_H_
diff --git a/net/network_error_logging/network_error_logging_service.cc b/net/network_error_logging/network_error_logging_service.cc index c929fc5..b06a131 100644 --- a/net/network_error_logging/network_error_logging_service.cc +++ b/net/network_error_logging/network_error_logging_service.cc
@@ -11,6 +11,7 @@ #include "base/json/json_reader.h" #include "base/logging.h" #include "base/memory/ptr_util.h" +#include "base/rand_util.h" #include "base/time/default_tick_clock.h" #include "base/time/tick_clock.h" #include "base/time/time.h" @@ -30,6 +31,8 @@ const char kReportToKey[] = "report-to"; const char kMaxAgeKey[] = "max-age"; const char kIncludeSubdomainsKey[] = "includeSubdomains"; +const char kSuccessFractionKey[] = "success-fraction"; +const char kFailureFractionKey[] = "failure-fraction"; // Returns the superdomain of a given domain, or the empty string if the given // domain is just a single label. Note that this does not take into account @@ -110,6 +113,8 @@ const char NetworkErrorLoggingService::kReportType[] = "network-error"; const char NetworkErrorLoggingService::kUriKey[] = "uri"; const char NetworkErrorLoggingService::kReferrerKey[] = "referrer"; +const char NetworkErrorLoggingService::kSamplingFractionKey[] = + "sampling-fraction"; const char NetworkErrorLoggingService::kServerIpKey[] = "server-ip"; const char NetworkErrorLoggingService::kProtocolKey[] = "protocol"; const char NetworkErrorLoggingService::kStatusCodeKey[] = "status-code"; @@ -182,8 +187,14 @@ if (!GetTypeFromNetError(details.type, &type_string)) return; - reporting_service_->QueueReport(details.uri, policy->report_to, kReportType, - CreateReportBody(type_string, details)); + // TODO(dcreager): Report successful requests, too. + double sampling_fraction = policy->failure_fraction; + if (base::RandDouble() >= sampling_fraction) + return; + + reporting_service_->QueueReport( + details.uri, policy->report_to, kReportType, + CreateReportBody(type_string, sampling_fraction, details)); } void NetworkErrorLoggingService::RemoveBrowsingData( @@ -243,6 +254,16 @@ // GetBoolean fails. dict->GetBoolean(kIncludeSubdomainsKey, &include_subdomains); + double success_fraction = 0.0; + // success-fraction is optional and defaults to 0.0, so it's okay if + // GetDouble fails. + dict->GetDouble(kSuccessFractionKey, &success_fraction); + + double failure_fraction = 1.0; + // failure-fraction is optional and defaults to 1.0, so it's okay if + // GetDouble fails. + dict->GetDouble(kFailureFractionKey, &failure_fraction); + policy_out->report_to = report_to; if (max_age_sec > 0) { policy_out->expires = @@ -251,6 +272,8 @@ policy_out->expires = base::TimeTicks(); } policy_out->include_subdomains = include_subdomains; + policy_out->success_fraction = success_fraction; + policy_out->failure_fraction = failure_fraction; return true; } @@ -334,11 +357,13 @@ std::unique_ptr<const base::Value> NetworkErrorLoggingService::CreateReportBody( const std::string& type, + double sampling_fraction, const NetworkErrorLoggingDelegate::ErrorDetails& details) const { auto body = std::make_unique<base::DictionaryValue>(); body->SetString(kUriKey, details.uri.spec()); body->SetString(kReferrerKey, details.referrer.spec()); + body->SetDouble(kSamplingFractionKey, sampling_fraction); body->SetString(kServerIpKey, details.server_ip.ToString()); std::string protocol = NextProtoToString(details.protocol); if (protocol == "unknown")
diff --git a/net/network_error_logging/network_error_logging_service.h b/net/network_error_logging/network_error_logging_service.h index 5cefaddd8..ed74509b 100644 --- a/net/network_error_logging/network_error_logging_service.h +++ b/net/network_error_logging/network_error_logging_service.h
@@ -45,6 +45,7 @@ static const char kUriKey[]; static const char kReferrerKey[]; + static const char kSamplingFractionKey[]; static const char kServerIpKey[]; static const char kProtocolKey[]; static const char kStatusCodeKey[]; @@ -80,6 +81,8 @@ base::TimeTicks expires; + double success_fraction; + double failure_fraction; bool include_subdomains; }; @@ -114,6 +117,7 @@ const OriginPolicy* policy); std::unique_ptr<const base::Value> CreateReportBody( const std::string& type, + double sampling_fraction, const ErrorDetails& details) const; base::TickClock* tick_clock_;
diff --git a/net/network_error_logging/network_error_logging_service_unittest.cc b/net/network_error_logging/network_error_logging_service_unittest.cc index 140b614..07b06ba 100644 --- a/net/network_error_logging/network_error_logging_service_unittest.cc +++ b/net/network_error_logging/network_error_logging_service_unittest.cc
@@ -153,6 +153,10 @@ const std::string kHeader_ = "{\"report-to\":\"group\",\"max-age\":86400}"; const std::string kHeaderIncludeSubdomains_ = "{\"report-to\":\"group\",\"max-age\":86400,\"includeSubdomains\":true}"; + const std::string kHeaderFailureFraction0_ = + "{\"report-to\":\"group\",\"max-age\":86400,\"failure-fraction\":0.0}"; + const std::string kHeaderFailureFractionHalf_ = + "{\"report-to\":\"group\",\"max-age\":86400,\"failure-fraction\":0.5}"; const std::string kHeaderMaxAge0_ = "{\"max-age\":0}"; const std::string kGroup_ = "group"; @@ -166,6 +170,14 @@ std::unique_ptr<TestReportingService> reporting_service_; }; +void ExpectDictDoubleValue(double expected_value, + const base::DictionaryValue& value, + const std::string& key) { + double double_value = 0.0; + EXPECT_TRUE(value.GetDouble(key, &double_value)) << key; + EXPECT_DOUBLE_EQ(expected_value, double_value) << key; +} + TEST_F(NetworkErrorLoggingServiceTest, CreateService) { // Service is created by default in the test fixture.. EXPECT_TRUE(service()); @@ -214,6 +226,8 @@ base::ExpectDictStringValue(kReferrer_.spec(), *body, NetworkErrorLoggingService::kReferrerKey); // TODO(juliatuttle): Extract these constants. + ExpectDictDoubleValue(1.0, *body, + NetworkErrorLoggingService::kSamplingFractionKey); base::ExpectDictStringValue("0.0.0.0", *body, NetworkErrorLoggingService::kServerIpKey); base::ExpectDictStringValue("", *body, @@ -236,6 +250,45 @@ EXPECT_TRUE(reports().empty()); } +TEST_F(NetworkErrorLoggingServiceTest, FailureFraction0) { + service()->OnHeader(kOrigin_, kHeaderFailureFraction0_); + + // Each network error has a 0% chance of being reported. Fire off several and + // verify that no reports are produced. + constexpr size_t kReportCount = 100; + for (size_t i = 0; i < kReportCount; ++i) + service()->OnNetworkError(MakeErrorDetails(kUrl_, ERR_CONNECTION_REFUSED)); + + EXPECT_TRUE(reports().empty()); +} + +TEST_F(NetworkErrorLoggingServiceTest, FailureFractionHalf) { + service()->OnHeader(kOrigin_, kHeaderFailureFractionHalf_); + + // Each network error has a 50% chance of being reported. Fire off several + // and verify that some requests were reported and some weren't. (We can't + // verify exact counts because each decision is made randomly.) + constexpr size_t kReportCount = 100; + for (size_t i = 0; i < kReportCount; ++i) + service()->OnNetworkError(MakeErrorDetails(kUrl_, ERR_CONNECTION_REFUSED)); + + // If our random selection logic is correct, there is a 2^-100 chance that + // every single report above was skipped. If this check fails, it's much more + // likely that our code is wrong. + EXPECT_FALSE(reports().empty()); + + // There's also a 2^-100 chance that every single report was logged. Same as + // above, that's much more likely to be a code error. + EXPECT_GT(kReportCount, reports().size()); + + for (const auto& report : reports()) { + const base::DictionaryValue* body; + ASSERT_TRUE(report.body->GetAsDictionary(&body)); + ExpectDictDoubleValue(0.5, *body, + NetworkErrorLoggingService::kSamplingFractionKey); + } +} + TEST_F(NetworkErrorLoggingServiceTest, ExcludeSubdomainsDoesntMatchDifferentPort) { service()->OnHeader(kOrigin_, kHeader_);
diff --git a/net/quic/chromium/quic_network_transaction_unittest.cc b/net/quic/chromium/quic_network_transaction_unittest.cc index 545e405..b7e8ac9 100644 --- a/net/quic/chromium/quic_network_transaction_unittest.cc +++ b/net/quic/chromium/quic_network_transaction_unittest.cc
@@ -2058,14 +2058,8 @@ quic_data.AddWrite(client_maker_.MakeDataPacket( 10, kHeadersStreamId, true, false, settings_offset, settings_data)); - if (FLAGS_quic_reloadable_flag_quic_strict_ack_handling) { - quic_data.AddWrite(client_maker_.MakeConnectionClosePacket( - 11, true, QUIC_NETWORK_IDLE_TIMEOUT, "No recent network activity.")); - } else { - quic_data.AddWrite(client_maker_.MakeAckAndConnectionClosePacket( - 11, true, QuicTime::Delta::Infinite(), 0, 1, 1, - QUIC_NETWORK_IDLE_TIMEOUT, "No recent network activity.")); - } + quic_data.AddWrite(client_maker_.MakeConnectionClosePacket( + 11, true, QUIC_NETWORK_IDLE_TIMEOUT, "No recent network activity.")); quic_data.AddRead(ASYNC, ERR_IO_PENDING); quic_data.AddRead(ASYNC, OK); @@ -2162,14 +2156,8 @@ quic_data.AddWrite(client_maker_.MakeDataPacket( 12, kHeadersStreamId, true, false, settings_offset, settings_data)); // RTO 5 - if (FLAGS_quic_reloadable_flag_quic_strict_ack_handling) { - quic_data.AddWrite(client_maker_.MakeConnectionClosePacket( - 13, true, QUIC_TOO_MANY_RTOS, "5 consecutive retransmission timeouts")); - } else { - quic_data.AddWrite(client_maker_.MakeAckAndConnectionClosePacket( - 13, true, QuicTime::Delta::Infinite(), 0, 1, 1, QUIC_TOO_MANY_RTOS, - "5 consecutive retransmission timeouts")); - } + quic_data.AddWrite(client_maker_.MakeConnectionClosePacket( + 13, true, QUIC_TOO_MANY_RTOS, "5 consecutive retransmission timeouts")); quic_data.AddRead(ASYNC, OK); quic_data.AddSocketDataToFactory(&socket_factory_); @@ -2269,14 +2257,8 @@ quic_data.AddWrite(client_maker_.MakeDataPacket(13, kHeadersStreamId, true, false, 0, request_data)); // RTO 5 - if (FLAGS_quic_reloadable_flag_quic_strict_ack_handling) { - quic_data.AddWrite(client_maker_.MakeConnectionClosePacket( - 14, true, QUIC_TOO_MANY_RTOS, "5 consecutive retransmission timeouts")); - } else { - quic_data.AddWrite(client_maker_.MakeAckAndConnectionClosePacket( - 14, true, QuicTime::Delta::Infinite(), 0, 1, 1, QUIC_TOO_MANY_RTOS, - "5 consecutive retransmission timeouts")); - } + quic_data.AddWrite(client_maker_.MakeConnectionClosePacket( + 14, true, QUIC_TOO_MANY_RTOS, "5 consecutive retransmission timeouts")); quic_data.AddRead(ASYNC, OK); quic_data.AddSocketDataToFactory(&socket_factory_); @@ -2434,14 +2416,8 @@ quic_data.AddWrite(client_maker_.MakeDataPacket( 10, kHeadersStreamId, true, false, settings_offset, settings_data)); - if (FLAGS_quic_reloadable_flag_quic_strict_ack_handling) { - quic_data.AddWrite(client_maker_.MakeConnectionClosePacket( - 11, true, QUIC_NETWORK_IDLE_TIMEOUT, "No recent network activity.")); - } else { - quic_data.AddWrite(client_maker_.MakeAckAndConnectionClosePacket( - 11, true, QuicTime::Delta::Infinite(), 0, 1, 1, - QUIC_NETWORK_IDLE_TIMEOUT, "No recent network activity.")); - } + quic_data.AddWrite(client_maker_.MakeConnectionClosePacket( + 11, true, QUIC_NETWORK_IDLE_TIMEOUT, "No recent network activity.")); quic_data.AddRead(ASYNC, ERR_IO_PENDING); quic_data.AddRead(ASYNC, OK); @@ -2560,14 +2536,8 @@ quic_data.AddWrite(client_maker_.MakeDataPacket( 10, kHeadersStreamId, true, false, settings_offset, settings_data)); - if (FLAGS_quic_reloadable_flag_quic_strict_ack_handling) { - quic_data.AddWrite(client_maker_.MakeConnectionClosePacket( - 11, true, QUIC_NETWORK_IDLE_TIMEOUT, "No recent network activity.")); - } else { - quic_data.AddWrite(client_maker_.MakeAckAndConnectionClosePacket( - 11, true, QuicTime::Delta::Infinite(), 0, 1, 1, - QUIC_NETWORK_IDLE_TIMEOUT, "No recent network activity.")); - } + quic_data.AddWrite(client_maker_.MakeConnectionClosePacket( + 11, true, QUIC_NETWORK_IDLE_TIMEOUT, "No recent network activity.")); quic_data.AddRead(ASYNC, ERR_IO_PENDING); quic_data.AddRead(ASYNC, OK); @@ -2810,14 +2780,8 @@ quic_data.AddWrite(client_maker_.MakeDataPacket( 12, kHeadersStreamId, true, false, settings_offset, settings_data)); - if (FLAGS_quic_reloadable_flag_quic_strict_ack_handling) { - quic_data.AddWrite(client_maker_.MakeConnectionClosePacket( - 13, true, QUIC_TOO_MANY_RTOS, "5 consecutive retransmission timeouts")); - } else { - quic_data.AddWrite(client_maker_.MakeAckAndConnectionClosePacket( - 13, true, QuicTime::Delta::Infinite(), 0, 1, 1, QUIC_TOO_MANY_RTOS, - "5 consecutive retransmission timeouts")); - } + quic_data.AddWrite(client_maker_.MakeConnectionClosePacket( + 13, true, QUIC_TOO_MANY_RTOS, "5 consecutive retransmission timeouts")); quic_data.AddRead(ASYNC, OK); quic_data.AddSocketDataToFactory(&socket_factory_); @@ -2943,14 +2907,8 @@ quic_data.AddWrite(client_maker_.MakeDataPacket(13, kHeadersStreamId, true, false, 0, request_data)); // RTO 5 - if (FLAGS_quic_reloadable_flag_quic_strict_ack_handling) { - quic_data.AddWrite(client_maker_.MakeConnectionClosePacket( - 14, true, QUIC_TOO_MANY_RTOS, "5 consecutive retransmission timeouts")); - } else { - quic_data.AddWrite(client_maker_.MakeAckAndConnectionClosePacket( - 14, true, QuicTime::Delta::Infinite(), 0, 1, 1, QUIC_TOO_MANY_RTOS, - "5 consecutive retransmission timeouts")); - } + quic_data.AddWrite(client_maker_.MakeConnectionClosePacket( + 14, true, QUIC_TOO_MANY_RTOS, "5 consecutive retransmission timeouts")); quic_data.AddRead(ASYNC, OK); quic_data.AddSocketDataToFactory(&socket_factory_);
diff --git a/net/quic/core/crypto/transport_parameters.cc b/net/quic/core/crypto/transport_parameters.cc new file mode 100644 index 0000000..1b118b7 --- /dev/null +++ b/net/quic/core/crypto/transport_parameters.cc
@@ -0,0 +1,291 @@ +// Copyright (c) 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 "net/quic/core/crypto/transport_parameters.h" + +#include "third_party/boringssl/src/include/openssl/bytestring.h" + +namespace net { + +namespace { + +// Values of the TransportParameterId enum as defined in +// draft-ietf-quic-transport-08 section 7.4. When parameters are encoded, one of +// these enum values is used to indicate which parameter is encoded. +enum TransportParameterId : uint16_t { + kInitialMaxStreamData = 0, + kInitialMaxData = 1, + kInitialMaxStreamIdBidi = 2, + kIdleTimeout = 3, + kOmitConnectionId = 4, + kMaxPacketSize = 5, + kStatelessResetToken = 6, + kAckDelayExponent = 7, + kInitialMaxStreamIdUni = 8, + + kMaxKnownParameterId = 9, +}; + +// The following constants define minimum and maximum allowed values for some of +// the parameters. These come from draft-ietf-quic-transport-08 section 7.4.1. +const uint16_t kMaxAllowedIdleTimeout = 600; +const uint16_t kMinAllowedMaxPacketSize = 1200; +const uint16_t kMaxAllowedMaxPacketSize = 65527; +const uint8_t kMaxAllowedAckDelayExponent = 20; + +static_assert(kMaxKnownParameterId <= 32, "too many parameters to bit pack"); + +// The initial_max_stream_data, initial_max_data, and idle_timeout parameters +// are always required to be present. When parsing the extension, a bitmask is +// used to keep track of which parameter have been seen so far, and that bitmask +// will be compared to this mask to check that all of the required parameters +// were present. +static constexpr uint16_t kRequiredParamsMask = + (1 << kInitialMaxStreamData) | (1 << kInitialMaxData) | (1 << kIdleTimeout); + +} // namespace + +TransportParameters::TransportParameters() = default; + +TransportParameters::TransportParameters( + const TransportParameters& transport_params) = default; + +TransportParameters::~TransportParameters() = default; + +bool TransportParameters::is_valid() const { + if (perspective == Perspective::IS_CLIENT && !stateless_reset_token.empty()) { + return false; + } + if (perspective == Perspective::IS_SERVER && + stateless_reset_token.size() != 16) { + return false; + } + if (idle_timeout > kMaxAllowedIdleTimeout || + (max_packet_size.present && + (max_packet_size.value > kMaxAllowedMaxPacketSize || + max_packet_size.value < kMinAllowedMaxPacketSize)) || + (ack_delay_exponent.present && + ack_delay_exponent.value > kMaxAllowedAckDelayExponent)) { + return false; + } + return true; +} + +bool SerializeTransportParameters(const TransportParameters& in, + std::vector<uint8_t>* out) { + if (!in.is_valid()) { + return false; + } + bssl::ScopedCBB cbb; + // 28 is the minimum size that the serialized TransportParameters can be, + // which is when it is for a client and only the required parameters are + // present. The CBB will grow to fit larger serializations. + if (!CBB_init(cbb.get(), 28) || !CBB_add_u32(cbb.get(), in.version)) { + return false; + } + CBB versions; + if (in.perspective == Perspective::IS_SERVER) { + if (!CBB_add_u8_length_prefixed(cbb.get(), &versions)) { + return false; + } + for (QuicVersionLabel version : in.supported_versions) { + if (!CBB_add_u32(&versions, version)) { + return false; + } + } + } + + CBB params, initial_max_stream_data_param, initial_max_data_param, + idle_timeout_param; + // required parameters + if (!CBB_add_u16_length_prefixed(cbb.get(), ¶ms) || + // initial_max_stream_data + !CBB_add_u16(¶ms, kInitialMaxStreamData) || + !CBB_add_u16_length_prefixed(¶ms, &initial_max_stream_data_param) || + !CBB_add_u32(&initial_max_stream_data_param, + in.initial_max_stream_data) || + // initial_max_data + !CBB_add_u16(¶ms, kInitialMaxData) || + !CBB_add_u16_length_prefixed(¶ms, &initial_max_data_param) || + !CBB_add_u32(&initial_max_data_param, in.initial_max_data) || + // idle_timeout + !CBB_add_u16(¶ms, kIdleTimeout) || + !CBB_add_u16_length_prefixed(¶ms, &idle_timeout_param) || + !CBB_add_u16(&idle_timeout_param, in.idle_timeout)) { + return false; + } + + CBB stateless_reset_token_param; + if (!in.stateless_reset_token.empty()) { + if (!CBB_add_u16(¶ms, kStatelessResetToken) || + !CBB_add_u16_length_prefixed(¶ms, &stateless_reset_token_param) || + !CBB_add_bytes(&stateless_reset_token_param, + in.stateless_reset_token.data(), + in.stateless_reset_token.size())) { + return false; + } + } + + if (in.initial_max_stream_id_bidi.present) { + CBB initial_max_stream_id_param; + if (!CBB_add_u16(¶ms, kInitialMaxStreamIdBidi) || + !CBB_add_u16_length_prefixed(¶ms, &initial_max_stream_id_param) || + !CBB_add_u32(&initial_max_stream_id_param, + in.initial_max_stream_id_bidi.value)) { + return false; + } + } + if (in.initial_max_stream_id_uni.present) { + CBB initial_max_stream_id_param; + if (!CBB_add_u16(¶ms, kInitialMaxStreamIdUni) || + !CBB_add_u16_length_prefixed(¶ms, &initial_max_stream_id_param) || + !CBB_add_u32(&initial_max_stream_id_param, + in.initial_max_stream_id_uni.value)) { + return false; + } + } + if (in.omit_connection_id) { + if (!CBB_add_u16(¶ms, kOmitConnectionId) || !CBB_add_u16(¶ms, 0)) { + return false; + } + } + if (in.max_packet_size.present) { + CBB max_packet_size_param; + if (!CBB_add_u16(¶ms, kMaxPacketSize) || + !CBB_add_u16_length_prefixed(¶ms, &max_packet_size_param) || + !CBB_add_u16(&max_packet_size_param, in.max_packet_size.value)) { + return false; + } + } + if (in.ack_delay_exponent.present) { + CBB max_packet_size_param; + if (!CBB_add_u16(¶ms, kMaxPacketSize) || + !CBB_add_u16_length_prefixed(¶ms, &max_packet_size_param) || + !CBB_add_u8(&max_packet_size_param, in.ack_delay_exponent.value)) { + return false; + } + } + if (!CBB_flush(cbb.get())) { + return false; + } + out->resize(CBB_len(cbb.get())); + memcpy(out->data(), CBB_data(cbb.get()), CBB_len(cbb.get())); + return true; +} + +bool ParseTransportParameters(const uint8_t* in, + size_t in_len, + Perspective perspective, + TransportParameters* out) { + CBS cbs; + CBS_init(&cbs, in, in_len); + if (!CBS_get_u32(&cbs, &out->version)) { + return false; + } + if (perspective == Perspective::IS_SERVER) { + CBS versions; + if (!CBS_get_u8_length_prefixed(&cbs, &versions) || + CBS_len(&versions) % 4 != 0) { + return false; + } + while (CBS_len(&versions) > 0) { + QuicVersionLabel version; + if (!CBS_get_u32(&versions, &version)) { + return false; + } + out->supported_versions.push_back(version); + } + } + out->perspective = perspective; + + uint32_t present_params = 0; + CBS params; + if (!CBS_get_u16_length_prefixed(&cbs, ¶ms)) { + return false; + } + while (CBS_len(¶ms) > 0) { + uint16_t param_id; + CBS value; + if (!CBS_get_u16(¶ms, ¶m_id) || + !CBS_get_u16_length_prefixed(¶ms, &value)) { + return false; + } + if (param_id < kMaxKnownParameterId) { + uint16_t mask = 1 << param_id; + if (present_params & mask) { + return false; + } + present_params |= mask; + } + switch (param_id) { + case kInitialMaxStreamData: + if (!CBS_get_u32(&value, &out->initial_max_stream_data) || + CBS_len(&value) != 0) { + return false; + } + break; + case kInitialMaxData: + if (!CBS_get_u32(&value, &out->initial_max_data) || + CBS_len(&value) != 0) { + return false; + } + break; + case kInitialMaxStreamIdBidi: + if (!CBS_get_u32(&value, &out->initial_max_stream_id_bidi.value) || + CBS_len(&value) != 0) { + return false; + } + out->initial_max_stream_id_bidi.present = true; + break; + case kIdleTimeout: + if (!CBS_get_u16(&value, &out->idle_timeout) || CBS_len(&value) != 0) { + return false; + } + break; + case kOmitConnectionId: + if (CBS_len(&value) != 0) { + return false; + } + out->omit_connection_id = true; + break; + case kMaxPacketSize: + if (!CBS_get_u16(&value, &out->max_packet_size.value) || + CBS_len(&value) != 0) { + return false; + } + out->max_packet_size.present = true; + break; + case kStatelessResetToken: + if (CBS_len(&value) == 0) { + return false; + } + out->stateless_reset_token.resize(CBS_len(&value)); + if (!CBS_copy_bytes(&value, out->stateless_reset_token.data(), + CBS_len(&value)) || + CBS_len(&value) != 0) { + return false; + } + break; + case kAckDelayExponent: + if (!CBS_get_u8(&value, &out->ack_delay_exponent.value) || + CBS_len(&value) != 0) { + return false; + } + out->ack_delay_exponent.present = true; + break; + case kInitialMaxStreamIdUni: + if (!CBS_get_u32(&value, &out->initial_max_stream_id_uni.value) || + CBS_len(&value) != 0) { + return false; + } + out->initial_max_stream_id_uni.present = true; + } + } + if ((present_params & kRequiredParamsMask) != kRequiredParamsMask) { + return false; + } + return out->is_valid(); +} + +} // namespace net
diff --git a/net/quic/core/crypto/transport_parameters.h b/net/quic/core/crypto/transport_parameters.h new file mode 100644 index 0000000..c6497c0f --- /dev/null +++ b/net/quic/core/crypto/transport_parameters.h
@@ -0,0 +1,88 @@ +// Copyright (c) 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. + +#ifndef NET_QUIC_CORE_CRYPTO_TRANSPORT_PARAMETERS_H_ +#define NET_QUIC_CORE_CRYPTO_TRANSPORT_PARAMETERS_H_ + +#include <vector> + +#include "net/quic/core/quic_types.h" +#include "net/quic/core/quic_versions.h" + +namespace net { + +// TransportParameters contains parameters for QUIC's transport layer that are +// indicated during the TLS handshake. This struct is a mirror of the struct in +// section 7.4 of draft-ietf-quic-transport-08. +struct QUIC_EXPORT_PRIVATE TransportParameters { + TransportParameters(); + TransportParameters(const TransportParameters& transport_params); + ~TransportParameters(); + + // When |perspective| is Perspective::IS_CLIENT, this struct is being used in + // the client_hello handshake message; when it is Perspective::IS_SERVER, it + // is being used in the encrypted_extensions handshake message. + Perspective perspective; + + // When Perspective::IS_CLIENT, |version| is the initial version offered by + // the client (before any version negotiation packets) for this connection. + // When Perspective::IS_SERVER, |version| is the version that is in use. + QuicVersionLabel version; + + // Server-only parameters: + + // |supported_versions| contains a list of all versions that the server would + // send in a version negotiation packet. It is not used if |perspective == + // Perspective::IS_CLIENT|. + QuicVersionLabelVector supported_versions; + + // See section 7.4.1 of draft-ietf-quic-transport-08 for definition. + std::vector<uint8_t> stateless_reset_token; + + // Required parameters. See section 7.4.1 of draft-ietf-quic-transport-08 for + // definitions. + uint32_t initial_max_stream_data = 0; + uint32_t initial_max_data = 0; + uint16_t idle_timeout = 0; + + template <typename T> + struct OptionalParam { + bool present = false; + T value; + }; + + // Optional parameters. See section 7.4.1 of draft-ietf-quic-transport-08 for + // definitions. + OptionalParam<uint32_t> initial_max_stream_id_bidi; + OptionalParam<uint32_t> initial_max_stream_id_uni; + OptionalParam<uint16_t> max_packet_size; + OptionalParam<uint8_t> ack_delay_exponent; + bool omit_connection_id = false; + + // Returns true if the contents of this struct are valid. + bool is_valid() const; +}; + +// Serializes a TransportParameters struct into the format for sending it in a +// TLS extension. The serialized bytes are put in |*out|, and this function +// returns true on success or false if |TransportParameters::is_valid| returns +// false. +QUIC_EXPORT_PRIVATE bool SerializeTransportParameters( + const TransportParameters& in, + std::vector<uint8_t>* out); + +// Parses bytes from the quic_transport_parameters TLS extension and writes the +// parsed parameters into |*out|. Input is read from |in| for |in_len| bytes. +// |perspective| indicates whether the input came from a client or a server. +// This method returns true if the input was successfully parsed, and false if +// it could not be parsed. +// TODO(nharper): Write fuzz tests for this method. +QUIC_EXPORT_PRIVATE bool ParseTransportParameters(const uint8_t* in, + size_t in_len, + Perspective perspective, + TransportParameters* out); + +} // namespace net + +#endif // NET_QUIC_CORE_CRYPTO_TRANSPORT_PARAMETERS_H_
diff --git a/net/quic/core/crypto/transport_parameters_test.cc b/net/quic/core/crypto/transport_parameters_test.cc new file mode 100644 index 0000000..2e7e987 --- /dev/null +++ b/net/quic/core/crypto/transport_parameters_test.cc
@@ -0,0 +1,381 @@ +// Copyright (c) 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 "net/quic/core/crypto/transport_parameters.h" + +#include "net/quic/platform/api/quic_arraysize.h" +#include "net/quic/platform/api/quic_test.h" +#include "third_party/boringssl/src/include/openssl/mem.h" + +namespace net { +namespace test { + +class TransportParametersTest : public QuicTest {}; + +TEST_F(TransportParametersTest, RoundTripClient) { + TransportParameters orig_params; + orig_params.perspective = Perspective::IS_CLIENT; + orig_params.initial_max_stream_data = 12; + orig_params.initial_max_data = 34; + orig_params.idle_timeout = 56; + orig_params.version = 0xff000005; + + std::vector<uint8_t> serialized; + ASSERT_TRUE(SerializeTransportParameters(orig_params, &serialized)); + + TransportParameters new_params; + ASSERT_TRUE(ParseTransportParameters(serialized.data(), serialized.size(), + Perspective::IS_CLIENT, &new_params)); + + EXPECT_EQ(new_params.initial_max_stream_data, + orig_params.initial_max_stream_data); + EXPECT_EQ(new_params.initial_max_data, orig_params.initial_max_data); + EXPECT_EQ(new_params.idle_timeout, orig_params.idle_timeout); + EXPECT_EQ(new_params.version, orig_params.version); +} + +TEST_F(TransportParametersTest, RoundTripServer) { + TransportParameters orig_params; + orig_params.perspective = Perspective::IS_SERVER; + orig_params.initial_max_stream_data = 12; + orig_params.initial_max_data = 34; + orig_params.idle_timeout = 56; + orig_params.stateless_reset_token.resize(16); + orig_params.version = 0xff000005; + orig_params.supported_versions.push_back(0xff000005); + orig_params.supported_versions.push_back(0xff000004); + + std::vector<uint8_t> serialized; + ASSERT_TRUE(SerializeTransportParameters(orig_params, &serialized)); + + TransportParameters new_params; + ASSERT_TRUE(ParseTransportParameters(serialized.data(), serialized.size(), + Perspective::IS_SERVER, &new_params)); + + EXPECT_EQ(new_params.initial_max_stream_data, + orig_params.initial_max_stream_data); + EXPECT_EQ(new_params.initial_max_data, orig_params.initial_max_data); + EXPECT_EQ(new_params.idle_timeout, orig_params.idle_timeout); + EXPECT_EQ(new_params.stateless_reset_token, + orig_params.stateless_reset_token); + EXPECT_EQ(new_params.version, orig_params.version); + ASSERT_EQ(new_params.supported_versions, orig_params.supported_versions); +} + +TEST_F(TransportParametersTest, IsValid) { + TransportParameters empty_params; + empty_params.perspective = Perspective::IS_CLIENT; + EXPECT_TRUE(empty_params.is_valid()); + + { + TransportParameters params = empty_params; + params.idle_timeout = 600; + EXPECT_TRUE(params.is_valid()); + params.idle_timeout = 601; + EXPECT_FALSE(params.is_valid()); + } + { + TransportParameters params = empty_params; + params.max_packet_size.present = true; + params.max_packet_size.value = 0; + EXPECT_FALSE(params.is_valid()); + params.max_packet_size.value = 1200; + EXPECT_TRUE(params.is_valid()); + params.max_packet_size.value = 65527; + EXPECT_TRUE(params.is_valid()); + params.max_packet_size.value = 65535; + EXPECT_FALSE(params.is_valid()); + } + { + TransportParameters params = empty_params; + params.ack_delay_exponent.present = true; + params.ack_delay_exponent.value = 0; + EXPECT_TRUE(params.is_valid()); + params.ack_delay_exponent.value = 20; + EXPECT_TRUE(params.is_valid()); + params.ack_delay_exponent.value = 21; + EXPECT_FALSE(params.is_valid()); + } +} + +TEST_F(TransportParametersTest, NoServerParamsWithoutStatelessResetToken) { + TransportParameters orig_params; + orig_params.perspective = Perspective::IS_SERVER; + orig_params.initial_max_stream_data = 12; + orig_params.initial_max_data = 34; + orig_params.idle_timeout = 56; + orig_params.version = 0xff000005; + orig_params.supported_versions.push_back(0xff000005); + orig_params.supported_versions.push_back(0xff000004); + + std::vector<uint8_t> out; + ASSERT_FALSE(SerializeTransportParameters(orig_params, &out)); +} + +TEST_F(TransportParametersTest, NoClientParamsWithStatelessResetToken) { + TransportParameters orig_params; + orig_params.perspective = Perspective::IS_CLIENT; + orig_params.initial_max_stream_data = 12; + orig_params.initial_max_data = 34; + orig_params.idle_timeout = 56; + orig_params.stateless_reset_token.resize(16); + orig_params.version = 0xff000005; + + std::vector<uint8_t> out; + ASSERT_FALSE(SerializeTransportParameters(orig_params, &out)); +} + +TEST_F(TransportParametersTest, ParseClientParams) { + const uint8_t kClientParams[] = { + 0xff, 0x00, 0x00, 0x05, // initial version + 0x00, 0x16, // length parameters array that follows + // initial_max_stream_data + 0x00, 0x00, // parameter id + 0x00, 0x04, // length + 0x00, 0x00, 0x00, 0x0c, // value + // initial_max_data + 0x00, 0x01, // parameter id + 0x00, 0x04, // length + 0x00, 0x00, 0x00, 0x22, // value + // idle_timeout + 0x00, 0x03, // parameter id + 0x00, 0x02, // length + 0x00, 0x38, // value + }; + + TransportParameters out_params; + ASSERT_TRUE(ParseTransportParameters(kClientParams, + QUIC_ARRAYSIZE(kClientParams), + Perspective::IS_CLIENT, &out_params)); +} + +TEST_F(TransportParametersTest, ParseClientParamsFailsWithStatelessResetToken) { + TransportParameters out_params; + + // clang-format off + const uint8_t kClientParamsWithFullToken[] = { + 0xff, 0x00, 0x00, 0x05, // initial version + 0x00, 0x2a, // length parameters array that follows + // initial_max_stream_data + 0x00, 0x00, // parameter id + 0x00, 0x04, // length + 0x00, 0x00, 0x00, 0x0c, // value + // initial_max_data + 0x00, 0x01, // parameter id + 0x00, 0x04, // length + 0x00, 0x00, 0x00, 0x22, // value + // idle_timeout + 0x00, 0x03, // parameter id + 0x00, 0x02, // length + 0x00, 0x38, // value + // stateless_reset_token + 0x00, 0x06, // parameter id + 0x00, 0x10, // length + 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, + 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, + }; + // clang-format on + + ASSERT_FALSE(ParseTransportParameters( + kClientParamsWithFullToken, QUIC_ARRAYSIZE(kClientParamsWithFullToken), + Perspective::IS_CLIENT, &out_params)); + + const uint8_t kClientParamsWithEmptyToken[] = { + 0xff, 0x00, 0x00, 0x05, // initial version + 0x00, 0x1a, // length parameters array that follows + // initial_max_stream_data + 0x00, 0x00, // parameter id + 0x00, 0x04, // length + 0x00, 0x00, 0x00, 0x0c, // value + // initial_max_data + 0x00, 0x01, // parameter id + 0x00, 0x04, // length + 0x00, 0x00, 0x00, 0x22, // value + // idle_timeout + 0x00, 0x03, // parameter id + 0x00, 0x02, // length + 0x00, 0x38, // value + // stateless_reset_token + 0x00, 0x06, // parameter id + 0x00, 0x00, // length + }; + + ASSERT_FALSE(ParseTransportParameters( + kClientParamsWithEmptyToken, QUIC_ARRAYSIZE(kClientParamsWithEmptyToken), + Perspective::IS_CLIENT, &out_params)); +} + +TEST_F(TransportParametersTest, ParseClientParametersWithInvalidParams) { + TransportParameters out_params; + + const uint8_t kClientParamsRepeated[] = { + 0xff, 0x00, 0x00, 0x05, // initial version + 0x00, 0x1c, // length parameters array that follows + // initial_max_stream_data + 0x00, 0x00, // parameter id + 0x00, 0x04, // length + 0x00, 0x00, 0x00, 0x0c, // value + // initial_max_data + 0x00, 0x01, // parameter id + 0x00, 0x04, // length + 0x00, 0x00, 0x00, 0x22, // value + // idle_timeout + 0x00, 0x03, // parameter id + 0x00, 0x02, // length + 0x00, 0x38, // value + // idle_timeout (repeat) + 0x00, 0x03, // parameter id + 0x00, 0x02, // length + 0x00, 0x38, // value + }; + ASSERT_FALSE(ParseTransportParameters(kClientParamsRepeated, + QUIC_ARRAYSIZE(kClientParamsRepeated), + Perspective::IS_CLIENT, &out_params)); + + const uint8_t kClientParamsMissing[] = { + 0xff, 0x00, 0x00, 0x05, // initial version + 0x00, 0x10, // length parameters array that follows + // initial_max_stream_data + 0x00, 0x00, // parameter id + 0x00, 0x04, // length + 0x00, 0x00, 0x00, 0x0c, // value + // initial_max_data + 0x00, 0x01, // parameter id + 0x00, 0x04, // length + 0x00, 0x00, 0x00, 0x22, // value + }; + ASSERT_FALSE(ParseTransportParameters(kClientParamsMissing, + QUIC_ARRAYSIZE(kClientParamsMissing), + Perspective::IS_CLIENT, &out_params)); +} + +TEST_F(TransportParametersTest, ParseServerParams) { + // clang-format off + const uint8_t kServerParams[] = { + 0xff, 0x00, 0x00, 0x05, // negotiated_version + 0x08, // length of supported versions array + 0xff, 0x00, 0x00, 0x05, + 0xff, 0x00, 0x00, 0x04, + 0x00, 0x2a, // length of parameters array that follows + // initial_max_stream_data + 0x00, 0x00, + 0x00, 0x04, + 0x00, 0x00, 0x00, 0x0c, + // initial_max_data + 0x00, 0x01, + 0x00, 0x04, + 0x00, 0x00, 0x00, 0x22, + // idle_timeout + 0x00, 0x03, + 0x00, 0x02, + 0x00, 0x38, + // stateless_reset_token + 0x00, 0x06, + 0x00, 0x10, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + }; + // clang-format on + + TransportParameters out_params; + ASSERT_TRUE(ParseTransportParameters(kServerParams, + QUIC_ARRAYSIZE(kServerParams), + Perspective::IS_SERVER, &out_params)); +} + +TEST_F(TransportParametersTest, ParseServerParamsWithoutToken) { + // clang-format off + const uint8_t kServerParams[] = { + 0xff, 0x00, 0x00, 0x05, // negotiated_version + 0x08, // length of supported versions array + 0xff, 0x00, 0x00, 0x05, + 0xff, 0x00, 0x00, 0x04, + 0x00, 0x16, // length of parameters array that follows + // initial_max_stream_data + 0x00, 0x00, + 0x00, 0x04, + 0x00, 0x00, 0x00, 0x0c, + // initial_max_data + 0x00, 0x01, + 0x00, 0x04, + 0x00, 0x00, 0x00, 0x22, + // idle_timeout + 0x00, 0x03, + 0x00, 0x02, + 0x00, 0x38, + }; + // clang-format on + + TransportParameters out_params; + ASSERT_FALSE(ParseTransportParameters(kServerParams, + QUIC_ARRAYSIZE(kServerParams), + Perspective::IS_SERVER, &out_params)); +} + +TEST_F(TransportParametersTest, ParseServerParametersWithInvalidParams) { + TransportParameters out_params; + + // clang-format off + const uint8_t kServerParamsRepeated[] = { + 0xff, 0x00, 0x00, 0x05, // negotiated_version + 0x08, // length of supported versions array + 0xff, 0x00, 0x00, 0x05, + 0xff, 0x00, 0x00, 0x04, + 0x00, 0x30, // length of parameters array that follows + // initial_max_stream_data + 0x00, 0x00, + 0x00, 0x04, + 0x00, 0x00, 0x00, 0x0c, + // initial_max_data + 0x00, 0x01, + 0x00, 0x04, + 0x00, 0x00, 0x00, 0x22, + // idle_timeout + 0x00, 0x03, + 0x00, 0x02, + 0x00, 0x38, + // idle_timeout (repeat) + 0x00, 0x03, + 0x00, 0x02, + 0x00, 0x38, + // stateless_reset_token + 0x00, 0x06, + 0x00, 0x10, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + }; + // clang-format on + ASSERT_FALSE(ParseTransportParameters(kServerParamsRepeated, + QUIC_ARRAYSIZE(kServerParamsRepeated), + Perspective::IS_SERVER, &out_params)); + + // clang-format off + const uint8_t kServerParamsMissing[] = { + 0xff, 0x00, 0x00, 0x05, // negotiated_version + 0x08, // length of supported versions array + 0xff, 0x00, 0x00, 0x05, + 0xff, 0x00, 0x00, 0x04, + 0x00, 0x24, // length of parameters array that follows + // initial_max_stream_data + 0x00, 0x00, + 0x00, 0x04, + 0x00, 0x00, 0x00, 0x0c, + // initial_max_data + 0x00, 0x01, + 0x00, 0x04, + 0x00, 0x00, 0x00, 0x22, + // stateless_reset_token + 0x00, 0x06, + 0x00, 0x10, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + }; + // clang-format on + ASSERT_FALSE(ParseTransportParameters(kServerParamsMissing, + QUIC_ARRAYSIZE(kServerParamsMissing), + Perspective::IS_SERVER, &out_params)); +} + +} // namespace test +} // namespace net
diff --git a/net/quic/core/frames/quic_frame.cc b/net/quic/core/frames/quic_frame.cc index be96ff00..0a724ee 100644 --- a/net/quic/core/frames/quic_frame.cc +++ b/net/quic/core/frames/quic_frame.cc
@@ -219,7 +219,7 @@ break; } case PING_FRAME: { - os << "type { PING_FRAME } "; + os << "type { PING_FRAME } " << frame.ping_frame; break; } case MTU_DISCOVERY_FRAME: {
diff --git a/net/quic/core/quic_connection.cc b/net/quic/core/quic_connection.cc index 2cbb7239..5b05092 100644 --- a/net/quic/core/quic_connection.cc +++ b/net/quic/core/quic_connection.cc
@@ -207,6 +207,7 @@ largest_seen_packet_with_ack_(0), largest_seen_packet_with_stop_waiting_(0), max_undecryptable_packets_(0), + max_tracked_packets_(kMaxTrackedPackets), pending_version_negotiation_packet_(false), save_crypto_packets_as_termination_packets_(false), idle_timeout_connection_close_behavior_( @@ -278,7 +279,9 @@ use_control_frame_manager_( GetQuicReloadableFlag(quic_use_control_frame_manager)) { QUIC_DLOG(INFO) << ENDPOINT - << "Created connection with connection_id: " << connection_id; + << "Created connection with connection_id: " << connection_id + << " and version: " + << QuicVersionToString(transport_version()); framer_.set_visitor(this); stats_.connection_creation_time = clock_->ApproximateNow(); // TODO(ianswett): Supply the NetworkChangeVisitor as a constructor argument @@ -1054,6 +1057,7 @@ } ClearLastFrames(); + CloseIfTooManyOutstandingSentPackets(); } void QuicConnection::MaybeQueueAck(bool was_missing) { @@ -1127,6 +1131,23 @@ should_last_packet_instigate_acks_ = false; } +void QuicConnection::CloseIfTooManyOutstandingSentPackets() { + if (!GetQuicReloadableFlag( + quic_close_session_on_too_many_outstanding_sent_packets)) { + return; + } + + // This occurs if we don't discard old packets we've seen fast enough. It's + // possible largest observed is less than leaset unacked. + if (sent_packet_manager_.GetLargestObserved() > + sent_packet_manager_.GetLeastUnacked() + max_tracked_packets_) { + CloseConnection( + QUIC_TOO_MANY_OUTSTANDING_SENT_PACKETS, + QuicStrCat("More than ", max_tracked_packets_, " outstanding."), + ConnectionCloseBehavior::SEND_CONNECTION_CLOSE_PACKET); + } +} + const QuicFrame QuicConnection::GetUpdatedAckFrame() { return received_packet_manager_.GetUpdatedAckFrame(clock_->ApproximateNow()); } @@ -1207,7 +1228,7 @@ bool QuicConnection::SendControlFrame(const QuicFrame& frame) { DCHECK(use_control_frame_manager_); if (!CanWrite(HAS_RETRANSMITTABLE_DATA) && frame.type != PING_FRAME) { - QUIC_DVLOG(1) << "Failed to send control frame: " << frame; + QUIC_DVLOG(1) << ENDPOINT << "Failed to send control frame: " << frame; // Do not check congestion window for ping. return false; } @@ -2390,8 +2411,7 @@ // If caller wants us to include an ack, check the delayed-ack timer to see if // there's ack info to be sent. if (ShouldSendAck(ack_mode)) { - if (!GetQuicReloadableFlag(quic_strict_ack_handling) || - !connection_->GetUpdatedAckFrame().ack_frame->packets.Empty()) { + if (!connection_->GetUpdatedAckFrame().ack_frame->packets.Empty()) { QUIC_DVLOG(1) << "Bundling ack with outgoing packet."; connection_->SendAck(); }
diff --git a/net/quic/core/quic_connection.h b/net/quic/core/quic_connection.h index fa86285..8b3c35d 100644 --- a/net/quic/core/quic_connection.h +++ b/net/quic/core/quic_connection.h
@@ -835,6 +835,10 @@ // Deletes and clears any queued packets. void ClearQueuedPackets(); + // Closes the connection if the sent packet manager are tracking too many + // outstanding packets. + void CloseIfTooManyOutstandingSentPackets(); + // Writes as many queued packets as possible. The connection must not be // blocked when this is called. void WriteQueuedPackets(); @@ -970,6 +974,9 @@ // Maximum number of undecryptable packets the connection will store. size_t max_undecryptable_packets_; + // Maximum number of tracked packets. + QuicPacketCount max_tracked_packets_; + // When the version negotiation packet could not be sent because the socket // was not writable, this is set to true. bool pending_version_negotiation_packet_;
diff --git a/net/quic/core/quic_connection_test.cc b/net/quic/core/quic_connection_test.cc index 22843ee..cc841c3e 100644 --- a/net/quic/core/quic_connection_test.cc +++ b/net/quic/core/quic_connection_test.cc
@@ -1935,15 +1935,24 @@ } TEST_P(QuicConnectionTest, TooManySentPackets) { + SetQuicReloadableFlag(quic_close_session_on_too_many_outstanding_sent_packets, + true); EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_)); - const int num_packets = kMaxTrackedPackets + 100; + QuicPacketCount max_tracked_packets = 50; + QuicConnectionPeer::SetMaxTrackedPackets(&connection_, max_tracked_packets); + + const int num_packets = max_tracked_packets + 5; + for (int i = 0; i < num_packets; ++i) { SendStreamDataToPeer(1, "foo", 3 * i, NO_FIN, nullptr); } // Ack packet 1, which leaves more than the limit outstanding. EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _)); + EXPECT_CALL(visitor_, + OnConnectionClosed(QUIC_TOO_MANY_OUTSTANDING_SENT_PACKETS, _, + ConnectionCloseSource::FROM_SELF)); // Nack the first packet and ack the rest, leaving a huge gap. QuicAckFrame frame1 = ConstructAckFrame(num_packets, 1); @@ -2123,8 +2132,6 @@ TEST_P(QuicConnectionTest, FramePacking) { // Send two stream frames in 1 packet by queueing them. - // If quic_strict_ack_handling is false, the packet - // also bundles an empty ack frame and a stop_waiting frame. connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE); { QuicConnection::ScopedPacketFlusher flusher(&connection_, @@ -2139,25 +2146,15 @@ // Parse the last packet and ensure it's an ack and two stream frames from // two different streams. if (GetParam().no_stop_waiting) { - EXPECT_EQ(GetQuicReloadableFlag(quic_strict_ack_handling) ? 2u : 3u, - writer_->frame_count()); + EXPECT_EQ(2u, writer_->frame_count()); EXPECT_TRUE(writer_->stop_waiting_frames().empty()); } else { - EXPECT_EQ(GetQuicReloadableFlag(quic_strict_ack_handling) ? 2u : 4u, - writer_->frame_count()); - - if (GetQuicReloadableFlag(quic_strict_ack_handling)) { - EXPECT_TRUE(writer_->stop_waiting_frames().empty()); - } else { - EXPECT_FALSE(writer_->stop_waiting_frames().empty()); - } + EXPECT_EQ(2u, writer_->frame_count()); + EXPECT_TRUE(writer_->stop_waiting_frames().empty()); } - if (GetQuicReloadableFlag(quic_strict_ack_handling)) { - EXPECT_TRUE(writer_->ack_frames().empty()); - } else { - EXPECT_FALSE(writer_->ack_frames().empty()); - } + EXPECT_TRUE(writer_->ack_frames().empty()); + ASSERT_EQ(2u, writer_->stream_frames().size()); EXPECT_EQ(kClientDataStreamId1, writer_->stream_frames()[0]->stream_id); EXPECT_EQ(kClientDataStreamId2, writer_->stream_frames()[1]->stream_id);
diff --git a/net/quic/core/quic_crypto_stream_test.cc b/net/quic/core/quic_crypto_stream_test.cc index 59726408..cce2a56 100644 --- a/net/quic/core/quic_crypto_stream_test.cc +++ b/net/quic/core/quic_crypto_stream_test.cc
@@ -130,9 +130,6 @@ } TEST_F(QuicCryptoStreamTest, RetransmitCryptoData) { - if (!FLAGS_quic_reloadable_flag_quic_allow_multiple_acks_for_data2) { - return; - } InSequence s; // Send [0, 1350) in ENCRYPTION_NONE. EXPECT_EQ(ENCRYPTION_NONE, connection_->encryption_level()); @@ -169,9 +166,6 @@ } TEST_F(QuicCryptoStreamTest, NeuterUnencryptedStreamData) { - if (!FLAGS_quic_reloadable_flag_quic_allow_multiple_acks_for_data2) { - return; - } // Send [0, 1350) in ENCRYPTION_NONE. EXPECT_EQ(ENCRYPTION_NONE, connection_->encryption_level()); string data(1350, 'a');
diff --git a/net/quic/core/quic_flags_list.h b/net/quic/core/quic_flags_list.h index 6f7b86e..5311ff0b 100644 --- a/net/quic/core/quic_flags_list.h +++ b/net/quic/core/quic_flags_list.h
@@ -119,30 +119,17 @@ FLAGS_quic_reloadable_flag_quic_server_reply_to_connectivity_probing, true) -// If true, allow stream data and control frames to be acked multiple times. -QUIC_FLAG(bool, - FLAGS_quic_reloadable_flag_quic_allow_multiple_acks_for_data2, - true) - // If true, calculate stream sequencer buffer block count in a way that // guaranteed to be 2048. QUIC_FLAG(bool, FLAGS_quic_reloadable_flag_quic_fix_sequencer_buffer_block_count2, true) -// If true, use deframer from net/quic/http instead of net/http2. -QUIC_FLAG(bool, FLAGS_quic_reloadable_flag_quic_enable_hq_deframer, true) - -// If true, then 1) at sender, avoid sending empty acks, 2) at receiver, close -// connection when a ack frame\'s first block length is 0, unless the ack is -// completely empty. -QUIC_FLAG(bool, FLAGS_quic_reloadable_flag_quic_strict_ack_handling, true) - // If true, fixes for the two bugs described in crbug.com/723604 will be // enabled. QUIC_FLAG(bool, FLAGS_quic_reloadable_flag_quic_2rtt_drop_client_cached_certs, - false) + true) // If true, limit quic stream length to be below 2^62. QUIC_FLAG(bool, FLAGS_quic_reloadable_flag_quic_stream_too_long, false) @@ -179,7 +166,13 @@ QUIC_FLAG(bool, FLAGS_quic_reloadable_flag_quic_use_control_frame_manager, false) - // When true, allows two connection options to run experiments with using max // ack delay as described in QUIC IETF. QUIC_FLAG(bool, FLAGS_quic_reloadable_flag_quic_max_ack_delay, false) + +// If ture, sender will close connection when there are too many outstanding +// sent packets +QUIC_FLAG( + bool, + FLAGS_quic_reloadable_flag_quic_close_session_on_too_many_outstanding_sent_packets, + false)
diff --git a/net/quic/core/quic_framer.cc b/net/quic/core/quic_framer.cc index 96fa0c0d..9d69775 100644 --- a/net/quic/core/quic_framer.cc +++ b/net/quic/core/quic_framer.cc
@@ -1388,9 +1388,7 @@ return false; } - if (GetQuicReloadableFlag(quic_strict_ack_handling) && - first_block_length == 0) { - QUIC_FLAG_COUNT(quic_reloadable_flag_quic_strict_ack_handling); + if (first_block_length == 0) { // For non-empty ACKs, the first block length must be non-zero. if (largest_acked != 0 || num_ack_blocks != 0) { set_detailed_error(
diff --git a/net/quic/core/quic_framer_test.cc b/net/quic/core/quic_framer_test.cc index 055af341..3f11cdf 100644 --- a/net/quic/core/quic_framer_test.cc +++ b/net/quic/core/quic_framer_test.cc
@@ -2199,9 +2199,6 @@ } TEST_P(QuicFramerTest, AckFrameFirstAckBlockLengthZero) { - SetQuicReloadableFlag(quic_strict_ack_handling, - true); - // clang-format off PacketFragments packet = { // public flags (8 byte connection_id)
diff --git a/net/quic/core/quic_headers_stream.cc b/net/quic/core/quic_headers_stream.cc index f6b80ea05..5334b38c 100644 --- a/net/quic/core/quic_headers_stream.cc +++ b/net/quic/core/quic_headers_stream.cc
@@ -64,9 +64,7 @@ bool fin_acked, QuicTime::Delta ack_delay_time) { QuicIntervalSet<QuicStreamOffset> newly_acked(offset, offset + data_length); - if (session()->allow_multiple_acks_for_data()) { - newly_acked.Difference(bytes_acked()); - } + newly_acked.Difference(bytes_acked()); for (const auto& acked : newly_acked) { QuicStreamOffset acked_offset = acked.min(); QuicByteCount acked_length = acked.max() - acked.min();
diff --git a/net/quic/core/quic_headers_stream_test.cc b/net/quic/core/quic_headers_stream_test.cc index 0953229..ff163c28 100644 --- a/net/quic/core/quic_headers_stream_test.cc +++ b/net/quic/core/quic_headers_stream_test.cc
@@ -841,9 +841,6 @@ EXPECT_CALL(session_, WritevData(headers_stream_, kHeadersStreamId, _, _, NO_FIN)) .WillRepeatedly(Invoke(MockQuicSession::ConsumeData)); - if (!GetQuicReloadableFlag(quic_allow_multiple_acks_for_data2)) { - EXPECT_CALL(*connection_, CloseConnection(QUIC_INTERNAL_ERROR, _, _)); - } InSequence s; QuicReferenceCountedPointer<MockAckListener> ack_listener1( new MockAckListener()); @@ -890,14 +887,8 @@ QuicTime::Delta::Zero())); // Unsent data is acked. EXPECT_CALL(*ack_listener2, OnPacketAcked(7, _)); - if (GetQuicReloadableFlag(quic_allow_multiple_acks_for_data2)) { - EXPECT_TRUE(headers_stream_->OnStreamFrameAcked(14, 10, false, - QuicTime::Delta::Zero())); - } else { - EXPECT_QUIC_BUG(headers_stream_->OnStreamFrameAcked( - 14, 10, false, QuicTime::Delta::Zero()), - "Unsent stream data is acked."); - } + EXPECT_TRUE(headers_stream_->OnStreamFrameAcked(14, 10, false, + QuicTime::Delta::Zero())); } TEST_P(QuicHeadersStreamTest, FrameContainsMultipleHeaders) { @@ -944,9 +935,6 @@ } TEST_P(QuicHeadersStreamTest, HeadersGetAckedMultipleTimes) { - if (!GetQuicReloadableFlag(quic_allow_multiple_acks_for_data2)) { - return; - } EXPECT_CALL(session_, WritevData(headers_stream_, kHeadersStreamId, _, _, NO_FIN)) .WillRepeatedly(Invoke(MockQuicSession::ConsumeData));
diff --git a/net/quic/core/quic_sent_packet_manager.cc b/net/quic/core/quic_sent_packet_manager.cc index 57adbd6..fa7ca1f7 100644 --- a/net/quic/core/quic_sent_packet_manager.cc +++ b/net/quic/core/quic_sent_packet_manager.cc
@@ -14,6 +14,7 @@ #include "net/quic/core/proto/cached_network_parameters.pb.h" #include "net/quic/core/quic_connection_stats.h" #include "net/quic/core/quic_pending_retransmission.h" +#include "net/quic/core/quic_utils.h" #include "net/quic/platform/api/quic_bug_tracker.h" #include "net/quic/platform/api/quic_flag_utils.h" #include "net/quic/platform/api/quic_flags.h" @@ -297,7 +298,7 @@ // These packets are still in flight. break; } - if (it->is_unackable) { + if (!QuicUtils::IsAckable(it->state)) { continue; } if (!ack_frame.packets.Contains(packet_number)) { @@ -481,7 +482,7 @@ } unacked_packets_.RemoveFromInFlight(info); unacked_packets_.RemoveRetransmittability(info); - info->is_unackable = true; + info->state = ACKED; } bool QuicSentPacketManager::HasUnackedPackets() const {
diff --git a/net/quic/core/quic_session.cc b/net/quic/core/quic_session.cc index dfe4569f..bba5344 100644 --- a/net/quic/core/quic_session.cc +++ b/net/quic/core/quic_session.cc
@@ -59,13 +59,8 @@ goaway_received_(false), control_frame_manager_(this), can_use_slices_(GetQuicReloadableFlag(quic_use_mem_slices)), - allow_multiple_acks_for_data_( - GetQuicReloadableFlag(quic_allow_multiple_acks_for_data2)), session_unblocks_stream_( GetQuicReloadableFlag(quic_streams_unblocked_by_session)) { - if (allow_multiple_acks_for_data_) { - QUIC_FLAG_COUNT(quic_reloadable_flag_quic_allow_multiple_acks_for_data2); - } if (use_control_frame_manager()) { QUIC_FLAG_COUNT(quic_reloadable_flag_quic_use_control_frame_manager); }
diff --git a/net/quic/core/quic_session.h b/net/quic/core/quic_session.h index ddd8cfc..424a231 100644 --- a/net/quic/core/quic_session.h +++ b/net/quic/core/quic_session.h
@@ -295,10 +295,6 @@ bool can_use_slices() const { return can_use_slices_; } - bool allow_multiple_acks_for_data() const { - return allow_multiple_acks_for_data_; - } - bool session_unblocks_stream() const { return session_unblocks_stream_; } bool use_control_frame_manager() const; @@ -534,9 +530,6 @@ // counted memory to avoid data copy. const bool can_use_slices_; - // Latched value of quic_reloadable_flag_quic_allow_multiple_acks_for_data2. - const bool allow_multiple_acks_for_data_; - // TODO(fayang): switch to linked_hash_set when chromium supports it. The bool // is not used here. // List of streams with pending retransmissions.
diff --git a/net/quic/core/quic_spdy_session.cc b/net/quic/core/quic_spdy_session.cc index 2c9a2093..b3bdf4f7 100644 --- a/net/quic/core/quic_spdy_session.cc +++ b/net/quic/core/quic_spdy_session.cc
@@ -298,17 +298,10 @@ supports_push_promise_(perspective() == Perspective::IS_CLIENT), cur_max_timestamp_(QuicTime::Zero()), prev_max_timestamp_(QuicTime::Zero()), - use_hq_deframer_(GetQuicReloadableFlag(quic_enable_hq_deframer)), spdy_framer_(SpdyFramer::ENABLE_COMPRESSION), spdy_framer_visitor_(new SpdyFramerVisitor(this)) { - if (use_hq_deframer_) { - QUIC_FLAG_COUNT(quic_reloadable_flag_quic_enable_hq_deframer); - hq_deframer_.set_visitor(spdy_framer_visitor_.get()); - hq_deframer_.set_debug_visitor(spdy_framer_visitor_.get()); - } else { - h2_deframer_.set_visitor(spdy_framer_visitor_.get()); - h2_deframer_.set_debug_visitor(spdy_framer_visitor_.get()); - } + hq_deframer_.set_visitor(spdy_framer_visitor_.get()); + hq_deframer_.set_debug_visitor(spdy_framer_visitor_.get()); } QuicSpdySession::~QuicSpdySession() { @@ -391,10 +384,8 @@ QuicTime timestamp) { DCHECK(timestamp.IsInitialized()); UpdateCurMaxTimeStamp(timestamp); - return use_hq_deframer_ ? hq_deframer_.ProcessInput( - static_cast<char*>(iov.iov_base), iov.iov_len) - : h2_deframer_.ProcessInput( - static_cast<char*>(iov.iov_base), iov.iov_len); + return hq_deframer_.ProcessInput(static_cast<char*>(iov.iov_base), + iov.iov_len); } size_t QuicSpdySession::WriteHeaders( @@ -615,15 +606,9 @@ void QuicSpdySession::SetHpackDecoderDebugVisitor( std::unique_ptr<QuicHpackDebugVisitor> visitor) { - if (use_hq_deframer_) { - hq_deframer_.SetDecoderHeaderTableDebugVisitor( - std::unique_ptr<HeaderTableDebugVisitor>(new HeaderTableDebugVisitor( - connection()->helper()->GetClock(), std::move(visitor)))); - } else { - h2_deframer_.SetDecoderHeaderTableDebugVisitor( - std::unique_ptr<HeaderTableDebugVisitor>(new HeaderTableDebugVisitor( - connection()->helper()->GetClock(), std::move(visitor)))); - } + hq_deframer_.SetDecoderHeaderTableDebugVisitor( + std::unique_ptr<HeaderTableDebugVisitor>(new HeaderTableDebugVisitor( + connection()->helper()->GetClock(), std::move(visitor)))); } void QuicSpdySession::UpdateHeaderEncoderTableSize(uint32_t value) {
diff --git a/net/quic/core/quic_spdy_session.h b/net/quic/core/quic_spdy_session.h index f8a2d5c..0fcb50a 100644 --- a/net/quic/core/quic_spdy_session.h +++ b/net/quic/core/quic_spdy_session.h
@@ -78,7 +78,7 @@ size_t frame_len, const QuicHeaderList& header_list); - // Sends contents of |iov| to h2_deframer_, returns number of bytes processed. + // Sends contents of |iov| to hq_deframer_, returns number of bytes processed. size_t ProcessHeaderData(const struct iovec& iov, QuicTime timestamp); // Writes |headers| for the stream |id| to the dedicated headers stream. @@ -196,16 +196,11 @@ bool IsConnected() { return connection()->connected(); } - // Sets how much encoded data the hpack decoder of h2_deframer_ is willing to + // Sets how much encoded data the hpack decoder of hq_deframer_ is willing to // buffer. void set_max_decode_buffer_size_bytes(size_t max_decode_buffer_size_bytes) { - if (use_hq_deframer_) { - hq_deframer_.GetHpackDecoder()->set_max_decode_buffer_size_bytes( - max_decode_buffer_size_bytes); - } else { - h2_deframer_.GetHpackDecoder()->set_max_decode_buffer_size_bytes( - max_decode_buffer_size_bytes); - } + hq_deframer_.GetHpackDecoder()->set_max_decode_buffer_size_bytes( + max_decode_buffer_size_bytes); } void set_max_uncompressed_header_bytes( @@ -275,11 +270,7 @@ QuicTime cur_max_timestamp_; QuicTime prev_max_timestamp_; - // TODO(ckrasic): remove |use_hq_deframer_| and |h2_deframer_| when - // FLAGS_quic_reloadable_flag_quic_enable_hq_deframer is deprecated. - bool use_hq_deframer_; SpdyFramer spdy_framer_; - Http2DecoderAdapter h2_deframer_; QuicHttpDecoderAdapter hq_deframer_; std::unique_ptr<SpdyFramerVisitor> spdy_framer_visitor_;
diff --git a/net/quic/core/quic_stream.cc b/net/quic/core/quic_stream.cc index 0d3f38f..4204f4b 100644 --- a/net/quic/core/quic_stream.cc +++ b/net/quic/core/quic_stream.cc
@@ -72,8 +72,7 @@ add_random_padding_after_fin_(false), ack_listener_(nullptr), send_buffer_( - session->connection()->helper()->GetStreamSendBufferAllocator(), - session->allow_multiple_acks_for_data()), + session->connection()->helper()->GetStreamSendBufferAllocator()), buffered_data_threshold_( GetQuicFlag(FLAGS_quic_buffered_data_threshold)) { SetFromConfig(); @@ -590,9 +589,8 @@ return false; } // Indicates whether ack listener's OnPacketAcked should be called. - const bool new_data_acked = !session()->allow_multiple_acks_for_data() || - newly_acked_length > 0 || - (fin_acked && fin_outstanding_); + const bool new_data_acked = + newly_acked_length > 0 || (fin_acked && fin_outstanding_); if (fin_acked) { fin_outstanding_ = false; fin_lost_ = false;
diff --git a/net/quic/core/quic_stream_send_buffer.cc b/net/quic/core/quic_stream_send_buffer.cc index 7671245..d92205c4 100644 --- a/net/quic/core/quic_stream_send_buffer.cc +++ b/net/quic/core/quic_stream_send_buffer.cc
@@ -16,9 +16,7 @@ namespace net { BufferedSlice::BufferedSlice(QuicMemSlice mem_slice, QuicStreamOffset offset) - : slice(std::move(mem_slice)), - offset(offset), - outstanding_data_length(slice.length()) {} + : slice(std::move(mem_slice)), offset(offset) {} BufferedSlice::BufferedSlice(BufferedSlice&& other) = default; @@ -31,16 +29,13 @@ return offset == other.offset && length == other.length; } -QuicStreamSendBuffer::QuicStreamSendBuffer(QuicBufferAllocator* allocator, - bool allow_multiple_acks_for_data) +QuicStreamSendBuffer::QuicStreamSendBuffer(QuicBufferAllocator* allocator) : stream_offset_(0), allocator_(allocator), stream_bytes_written_(0), stream_bytes_outstanding_(0), - allow_multiple_acks_for_data_(allow_multiple_acks_for_data), write_index_(-1), - use_write_index_(allow_multiple_acks_for_data_ && - GetQuicReloadableFlag(quic_use_write_index)) {} + use_write_index_(GetQuicReloadableFlag(quic_use_write_index)) {} QuicStreamSendBuffer::~QuicStreamSendBuffer() {} @@ -178,9 +173,7 @@ return true; } QuicIntervalSet<QuicStreamOffset> newly_acked(offset, offset + data_length); - if (allow_multiple_acks_for_data_) { - newly_acked.Difference(bytes_acked_); - } + newly_acked.Difference(bytes_acked_); for (const auto& interval : newly_acked) { *newly_acked_length += (interval.max() - interval.min()); } @@ -188,54 +181,28 @@ return false; } stream_bytes_outstanding_ -= *newly_acked_length; - if (allow_multiple_acks_for_data_) { - bytes_acked_.Add(offset, offset + data_length); - pending_retransmissions_.Difference(offset, offset + data_length); - while (!buffered_slices_.empty() && - bytes_acked_.Contains(buffered_slices_.front().offset, - buffered_slices_.front().offset + - buffered_slices_.front().slice.length())) { - // Remove data which stops waiting for acks. Please note, data can be - // acked out of order, but send buffer is cleaned up in order. - if (use_write_index_) { - QUIC_FLAG_COUNT_N(quic_reloadable_flag_quic_use_write_index, 2, 2); - QUIC_BUG_IF(write_index_ == 0) - << "Fail to advance current_write_slice_. It points to the slice " - "whose data has all be written and ACK'ed or ignored. " - "current_write_slice_ offset " - << buffered_slices_[write_index_].offset << " length " - << buffered_slices_[write_index_].slice.length(); - if (write_index_ > 0) { - // If write index is pointing to any slice, reduce the index as the - // slices are all shifted to the left by one. - --write_index_; - } - } - buffered_slices_.pop_front(); - } - return true; - } - - for (BufferedSlice& slice : buffered_slices_) { - if (offset < slice.offset) { - break; - } - if (offset >= slice.offset + slice.slice.length()) { - continue; - } - QuicByteCount slice_offset = offset - slice.offset; - QuicByteCount removing_length = - std::min(data_length, slice.slice.length() - slice_offset); - slice.outstanding_data_length -= removing_length; - offset += removing_length; - data_length -= removing_length; - } - DCHECK_EQ(0u, data_length); - - // Remove data which stops waiting for acks. Please note, data can be - // acked out of order, but send buffer is cleaned up in order. + bytes_acked_.Add(offset, offset + data_length); + pending_retransmissions_.Difference(offset, offset + data_length); while (!buffered_slices_.empty() && - buffered_slices_.front().outstanding_data_length == 0) { + bytes_acked_.Contains(buffered_slices_.front().offset, + buffered_slices_.front().offset + + buffered_slices_.front().slice.length())) { + // Remove data which stops waiting for acks. Please note, data can be + // acked out of order, but send buffer is cleaned up in order. + if (use_write_index_) { + QUIC_FLAG_COUNT_N(quic_reloadable_flag_quic_use_write_index, 2, 2); + QUIC_BUG_IF(write_index_ == 0) + << "Fail to advance current_write_slice_. It points to the slice " + "whose data has all be written and ACK'ed or ignored. " + "current_write_slice_ offset " + << buffered_slices_[write_index_].offset << " length " + << buffered_slices_[write_index_].slice.length(); + if (write_index_ > 0) { + // If write index is pointing to any slice, reduce the index as the + // slices are all shifted to the left by one. + --write_index_; + } + } buffered_slices_.pop_front(); } return true;
diff --git a/net/quic/core/quic_stream_send_buffer.h b/net/quic/core/quic_stream_send_buffer.h index c9a7b4a..30a1270 100644 --- a/net/quic/core/quic_stream_send_buffer.h +++ b/net/quic/core/quic_stream_send_buffer.h
@@ -36,10 +36,6 @@ QuicMemSlice slice; // Location of this data slice in the stream. QuicStreamOffset offset; - // Length of payload which is outstanding and waiting for acks. - // TODO(fayang): remove this field when deprecating - // quic_reloadable_flag_quic_allow_multiple_acks_for_data2. - QuicByteCount outstanding_data_length; }; struct StreamPendingRetransmission { @@ -61,8 +57,7 @@ // across slice boundaries. class QUIC_EXPORT_PRIVATE QuicStreamSendBuffer { public: - explicit QuicStreamSendBuffer(QuicBufferAllocator* allocator, - bool allow_multiple_acks_for_data); + explicit QuicStreamSendBuffer(QuicBufferAllocator* allocator); QuicStreamSendBuffer(const QuicStreamSendBuffer& other) = delete; QuicStreamSendBuffer(QuicStreamSendBuffer&& other) = delete; ~QuicStreamSendBuffer(); @@ -153,9 +148,6 @@ // Offsets of data that has been acked. QuicIntervalSet<QuicStreamOffset> bytes_acked_; - // Latch value for quic_reloadable_flag_quic_allow_multiple_acks_for_data2. - const bool allow_multiple_acks_for_data_; - // Data considered as lost and needs to be retransmitted. QuicIntervalSet<QuicStreamOffset> pending_retransmissions_; @@ -163,8 +155,7 @@ // time. -1 if send buffer is empty or all data has been written. int32_t write_index_; - // True if quic_reloadable_flag_quic_stream_send_buffer_write_index and - // allow_multiple_acks_for_data_ are both true. + // Latched value of quic_reloadable_flag_quic_stream_send_buffer_write_index. const bool use_write_index_; };
diff --git a/net/quic/core/quic_stream_send_buffer_test.cc b/net/quic/core/quic_stream_send_buffer_test.cc index f4e092f..cc285e8 100644 --- a/net/quic/core/quic_stream_send_buffer_test.cc +++ b/net/quic/core/quic_stream_send_buffer_test.cc
@@ -26,10 +26,7 @@ class QuicStreamSendBufferTest : public QuicTest { public: - QuicStreamSendBufferTest() - : send_buffer_( - &allocator_, - GetQuicReloadableFlag(quic_allow_multiple_acks_for_data2)) { + QuicStreamSendBufferTest() : send_buffer_(&allocator_) { EXPECT_EQ(0u, send_buffer_.size()); EXPECT_EQ(0u, send_buffer_.stream_bytes_written()); EXPECT_EQ(0u, send_buffer_.stream_bytes_outstanding()); @@ -106,8 +103,7 @@ // Invalid data copy. QuicDataWriter writer3(4000, buf, HOST_BYTE_ORDER); EXPECT_FALSE(send_buffer_.WriteStreamData(3000, 1024, &writer3)); - if (GetQuicReloadableFlag(quic_use_write_index) && - GetQuicReloadableFlag(quic_allow_multiple_acks_for_data2)) { + if (GetQuicReloadableFlag(quic_use_write_index)) { EXPECT_DFATAL(send_buffer_.WriteStreamData(0, 4000, &writer3), "Writer fails to write."); } else { @@ -168,9 +164,6 @@ } TEST_F(QuicStreamSendBufferTest, AckStreamDataMultipleTimes) { - if (!GetQuicReloadableFlag(quic_allow_multiple_acks_for_data2)) { - return; - } WriteAllData(); QuicByteCount newly_acked_length; EXPECT_TRUE(send_buffer_.OnStreamDataAcked(100, 1500, &newly_acked_length)); @@ -194,9 +187,6 @@ } TEST_F(QuicStreamSendBufferTest, PendingRetransmission) { - if (!FLAGS_quic_reloadable_flag_quic_allow_multiple_acks_for_data2) { - return; - } WriteAllData(); EXPECT_TRUE(send_buffer_.IsStreamDataOutstanding(0, 3840)); EXPECT_FALSE(send_buffer_.HasPendingRetransmission()); @@ -238,8 +228,7 @@ } TEST_F(QuicStreamSendBufferTest, CurrentWriteIndex) { - if (!GetQuicReloadableFlag(quic_use_write_index) || - !GetQuicReloadableFlag(quic_allow_multiple_acks_for_data2)) { + if (!GetQuicReloadableFlag(quic_use_write_index)) { return; } char buf[4000];
diff --git a/net/quic/core/quic_stream_test.cc b/net/quic/core/quic_stream_test.cc index 55f15a7..ca6c6c0 100644 --- a/net/quic/core/quic_stream_test.cc +++ b/net/quic/core/quic_stream_test.cc
@@ -1045,7 +1045,6 @@ } TEST_F(QuicStreamTest, StreamDataGetAckedMultipleTimes) { - SetQuicReloadableFlag(quic_allow_multiple_acks_for_data2, true); Initialize(kShouldProcessData); QuicReferenceCountedPointer<MockAckListener> mock_ack_listener( new StrictMock<MockAckListener>); @@ -1102,9 +1101,6 @@ } TEST_F(QuicStreamTest, OnStreamFrameLost) { - if (!FLAGS_quic_reloadable_flag_quic_allow_multiple_acks_for_data2) { - return; - } Initialize(kShouldProcessData); // Send [0, 9).
diff --git a/net/quic/core/quic_transmission_info.cc b/net/quic/core/quic_transmission_info.cc index d5654328..9e937baa 100644 --- a/net/quic/core/quic_transmission_info.cc +++ b/net/quic/core/quic_transmission_info.cc
@@ -13,7 +13,7 @@ sent_time(QuicTime::Zero()), transmission_type(NOT_RETRANSMISSION), in_flight(false), - is_unackable(false), + state(OUTSTANDING), has_crypto_handshake(false), num_padding_bytes(0), retransmission(0), @@ -33,7 +33,7 @@ sent_time(sent_time), transmission_type(transmission_type), in_flight(false), - is_unackable(false), + state(OUTSTANDING), has_crypto_handshake(has_crypto_handshake), num_padding_bytes(num_padding_bytes), retransmission(0),
diff --git a/net/quic/core/quic_transmission_info.h b/net/quic/core/quic_transmission_info.h index 6cdae6e..05240e54 100644 --- a/net/quic/core/quic_transmission_info.h +++ b/net/quic/core/quic_transmission_info.h
@@ -42,10 +42,8 @@ TransmissionType transmission_type; // In flight packets have not been abandoned or lost. bool in_flight; - // True if the packet can never be acked, so it can be removed. Occurs when - // a packet is never sent, after it is acknowledged once, or if it's a crypto - // packet we never expect to receive an ack for. - bool is_unackable; + // State of this packet. + SentPacketState state; // True if the packet contains stream data from the crypto stream. bool has_crypto_handshake; // Non-zero if the packet needs padding if it's retransmitted.
diff --git a/net/quic/core/quic_types.h b/net/quic/core/quic_types.h index 7537e5a7..fef02ca 100644 --- a/net/quic/core/quic_types.h +++ b/net/quic/core/quic_types.h
@@ -258,6 +258,22 @@ FIN_AND_PADDING, }; +enum SentPacketState : uint8_t { + // The packet has been sent and waiting to be acked. + OUTSTANDING, + FIRST_PACKET_STATE = OUTSTANDING, + // The packet was never sent. + NEVER_SENT, + // The packet has been acked. + ACKED, + // This packet is not expected to be acked. + UNACKABLE, + + // TODO(fayang): Add more packet state corresponding to retransmission types + // in TransmissionType. + LAST_PACKET_STATE = UNACKABLE, +}; + // Information about a newly acknowledged packet. struct AckedPacket { AckedPacket(QuicPacketNumber packet_number,
diff --git a/net/quic/core/quic_unacked_packet_map.cc b/net/quic/core/quic_unacked_packet_map.cc index ac022ec..df2100d 100644 --- a/net/quic/core/quic_unacked_packet_map.cc +++ b/net/quic/core/quic_unacked_packet_map.cc
@@ -36,7 +36,7 @@ DCHECK_GE(packet_number, least_unacked_ + unacked_packets_.size()); while (least_unacked_ + unacked_packets_.size() < packet_number) { unacked_packets_.push_back(QuicTransmissionInfo()); - unacked_packets_.back().is_unackable = true; + unacked_packets_.back().state = NEVER_SENT; } const bool has_crypto_handshake = @@ -124,7 +124,7 @@ // encryption changes. if (transmission_type == ALL_INITIAL_RETRANSMISSION || transmission_type == ALL_UNACKED_RETRANSMISSION) { - transmission_info->is_unackable = true; + transmission_info->state = UNACKABLE; } else { transmission_info->retransmission = new_packet_number; } @@ -182,7 +182,7 @@ const QuicTransmissionInfo& info) const { // Packet can be used for RTT measurement if it may yet be acked as the // largest observed packet by the receiver. - return !info.is_unackable && packet_number > largest_observed_; + return QuicUtils::IsAckable(info.state) && packet_number > largest_observed_; } bool QuicUnackedPacketMap::IsPacketUsefulForCongestionControl(
diff --git a/net/quic/core/quic_utils.cc b/net/quic/core/quic_utils.cc index 109f376..39ccb665 100644 --- a/net/quic/core/quic_utils.cc +++ b/net/quic/core/quic_utils.cc
@@ -259,4 +259,9 @@ QUIC_BUG_IF(buffer_length > 0) << "Failed to copy entire length to buffer."; } +// static +bool QuicUtils::IsAckable(SentPacketState state) { + return state != NEVER_SENT && state != ACKED && state != UNACKABLE; +} + } // namespace net
diff --git a/net/quic/core/quic_utils.h b/net/quic/core/quic_utils.h index 9bc4386..de612dc 100644 --- a/net/quic/core/quic_utils.h +++ b/net/quic/core/quic_utils.h
@@ -69,6 +69,11 @@ size_t buffer_length, char* buffer); + // Returns true if a packet is ackable. A packet is unackable if it can never + // be acked. Occurs when a packet is never sent, after it is acknowledged + // once, or if it's a crypto packet we never expect to receive an ack for. + static bool IsAckable(SentPacketState state); + private: DISALLOW_COPY_AND_ASSIGN(QuicUtils); };
diff --git a/net/quic/core/quic_utils_test.cc b/net/quic/core/quic_utils_test.cc index 4f99397..7ac16810 100644 --- a/net/quic/core/quic_utils_test.cc +++ b/net/quic/core/quic_utils_test.cc
@@ -100,6 +100,16 @@ reinterpret_cast<const char*>(data.data()), data.size()))); } +TEST_F(QuicUtilsTest, IsUnackable) { + for (size_t i = FIRST_PACKET_STATE; i <= LAST_PACKET_STATE; ++i) { + if (i == NEVER_SENT || i == ACKED || i == UNACKABLE) { + EXPECT_FALSE(QuicUtils::IsAckable(static_cast<SentPacketState>(i))); + } else { + EXPECT_TRUE(QuicUtils::IsAckable(static_cast<SentPacketState>(i))); + } + } +} + } // namespace } // namespace test } // namespace net
diff --git a/net/quic/platform/api/quic_mem_slice_span_test.cc b/net/quic/platform/api/quic_mem_slice_span_test.cc index 6e37f08..abf976b 100644 --- a/net/quic/platform/api/quic_mem_slice_span_test.cc +++ b/net/quic/platform/api/quic_mem_slice_span_test.cc
@@ -28,8 +28,7 @@ TEST_F(QuicMemSliceSpanImplTest, SaveDataInSendBuffer) { SimpleBufferAllocator allocator; - QuicStreamSendBuffer send_buffer( - &allocator, GetQuicReloadableFlag(quic_allow_multiple_acks_for_data2)); + QuicStreamSendBuffer send_buffer(&allocator); QuicTestMemSliceVector vector(buffers_); EXPECT_EQ(10 * 1024u, vector.span().SaveMemSlicesInSendBuffer(&send_buffer)); @@ -38,8 +37,7 @@ TEST_F(QuicMemSliceSpanImplTest, SaveEmptyMemSliceInSendBuffer) { SimpleBufferAllocator allocator; - QuicStreamSendBuffer send_buffer( - &allocator, GetQuicReloadableFlag(quic_allow_multiple_acks_for_data2)); + QuicStreamSendBuffer send_buffer(&allocator); buffers_.push_back(std::make_pair(nullptr, 0)); QuicTestMemSliceVector vector(buffers_); EXPECT_EQ(10 * 1024u, vector.span().SaveMemSlicesInSendBuffer(&send_buffer));
diff --git a/net/quic/platform/impl/quic_url_utils_impl.cc b/net/quic/platform/impl/quic_url_utils_impl.cc index c7fde76b9..2aab048d 100644 --- a/net/quic/platform/impl/quic_url_utils_impl.cc +++ b/net/quic/platform/impl/quic_url_utils_impl.cc
@@ -127,7 +127,7 @@ // // Note: url::CanonicalizeScheme() will have added the ':' to // |canonical_scheme|. - GURL origin_url(canonical_scheme + "//" + authority.as_string()); + GURL origin_url(canonical_scheme + "//" + std::string(authority)); if (!origin_url.is_valid() || !origin_url.SchemeIsHTTPOrHTTPS() || // The following checks are merely defense in depth. origin_url.SchemeIsSuborigin() || origin_url.has_username() || @@ -140,7 +140,7 @@ // Attempt to parse the path. std::string spec = origin_url.GetWithEmptyPath().spec(); spec.pop_back(); // Remove the '/', as ":path" must contain it. - spec.append(path.as_string()); + spec.append(std::string(path)); // Attempt to parse the full URL, with the path as well. Ensure there is no // fragment to the query.
diff --git a/net/quic/test_tools/quic_connection_peer.cc b/net/quic/test_tools/quic_connection_peer.cc index 11da9495..b29ac885 100644 --- a/net/quic/test_tools/quic_connection_peer.cc +++ b/net/quic/test_tools/quic_connection_peer.cc
@@ -258,5 +258,12 @@ connection->no_stop_waiting_frames_ = no_stop_waiting_frames; } +// static +void QuicConnectionPeer::SetMaxTrackedPackets( + QuicConnection* connection, + QuicPacketCount max_tracked_packets) { + connection->max_tracked_packets_ = max_tracked_packets; +} + } // namespace test } // namespace net
diff --git a/net/quic/test_tools/quic_connection_peer.h b/net/quic/test_tools/quic_connection_peer.h index 5619a58..421217f 100644 --- a/net/quic/test_tools/quic_connection_peer.h +++ b/net/quic/test_tools/quic_connection_peer.h
@@ -112,6 +112,8 @@ QuicPacketNumber packet_number); static void SetNoStopWaitingFrames(QuicConnection* connection, bool no_stop_waiting_frames); + static void SetMaxTrackedPackets(QuicConnection* connection, + QuicPacketCount max_tracked_packets); private: DISALLOW_COPY_AND_ASSIGN(QuicConnectionPeer);
diff --git a/net/quic/test_tools/simple_data_producer.cc b/net/quic/test_tools/simple_data_producer.cc index e581357..2de5807c 100644 --- a/net/quic/test_tools/simple_data_producer.cc +++ b/net/quic/test_tools/simple_data_producer.cc
@@ -25,8 +25,7 @@ return; } if (!QuicContainsKey(send_buffer_map_, id)) { - send_buffer_map_[id] = QuicMakeUnique<QuicStreamSendBuffer>( - &allocator_, GetQuicReloadableFlag(quic_allow_multiple_acks_for_data2)); + send_buffer_map_[id] = QuicMakeUnique<QuicStreamSendBuffer>(&allocator_); } send_buffer_map_[id]->SaveStreamData(iov, iov_count, iov_offset, data_length); }
diff --git a/net/socket/socket_test_util.cc b/net/socket/socket_test_util.cc index daa5a898..6a6f7e7 100644 --- a/net/socket/socket_test_util.cc +++ b/net/socket/socket_test_util.cc
@@ -760,13 +760,13 @@ const SSLConfig& ssl_config, const SSLClientSocketContext& context) { SSLSocketDataProvider* next_ssl_data = mock_ssl_data_.GetNext(); - if (!next_ssl_data->next_protos_expected_in_ssl_config.empty()) { - EXPECT_EQ(next_ssl_data->next_protos_expected_in_ssl_config.size(), + if (next_ssl_data->next_protos_expected_in_ssl_config.has_value()) { + EXPECT_EQ(next_ssl_data->next_protos_expected_in_ssl_config.value().size(), ssl_config.alpn_protos.size()); - EXPECT_TRUE( - std::equal(next_ssl_data->next_protos_expected_in_ssl_config.begin(), - next_ssl_data->next_protos_expected_in_ssl_config.end(), - ssl_config.alpn_protos.begin())); + EXPECT_TRUE(std::equal( + next_ssl_data->next_protos_expected_in_ssl_config.value().begin(), + next_ssl_data->next_protos_expected_in_ssl_config.value().end(), + ssl_config.alpn_protos.begin())); } return std::unique_ptr<SSLClientSocket>(new MockSSLClientSocket( std::move(transport_socket), host_and_port, ssl_config, next_ssl_data));
diff --git a/net/socket/socket_test_util.h b/net/socket/socket_test_util.h index 1e8ea79..3a28951 100644 --- a/net/socket/socket_test_util.h +++ b/net/socket/socket_test_util.h
@@ -19,6 +19,7 @@ #include "base/memory/ptr_util.h" #include "base/memory/ref_counted.h" #include "base/memory/weak_ptr.h" +#include "base/optional.h" #include "base/strings/string16.h" #include "base/time/time.h" #include "build/build_config.h" @@ -374,7 +375,7 @@ SSLCertRequestInfo* cert_request_info; ChannelIDService* channel_id_service; - NextProtoVector next_protos_expected_in_ssl_config; + base::Optional<NextProtoVector> next_protos_expected_in_ssl_config; }; // Uses the sequence_number field in the mock reads and writes to
diff --git a/net/spdy/chromium/spdy_network_transaction_unittest.cc b/net/spdy/chromium/spdy_network_transaction_unittest.cc index 0ef486f8..5552aa08 100644 --- a/net/spdy/chromium/spdy_network_transaction_unittest.cc +++ b/net/spdy/chromium/spdy_network_transaction_unittest.cc
@@ -4468,8 +4468,8 @@ auto ssl_provider0 = std::make_unique<SSLSocketDataProvider>(ASYNC, OK); // Expect HTTP/2 protocols too in SSLConfig. - ssl_provider0->next_protos_expected_in_ssl_config.push_back(kProtoHTTP2); - ssl_provider0->next_protos_expected_in_ssl_config.push_back(kProtoHTTP11); + ssl_provider0->next_protos_expected_in_ssl_config = + NextProtoVector{kProtoHTTP2, kProtoHTTP11}; // Force SPDY. ssl_provider0->next_proto = kProtoHTTP2; helper.AddDataWithSSLSocketDataProvider(&data0, std::move(ssl_provider0)); @@ -4488,7 +4488,8 @@ auto ssl_provider1 = std::make_unique<SSLSocketDataProvider>(ASYNC, OK); // Expect only HTTP/1.1 protocol in SSLConfig. - ssl_provider1->next_protos_expected_in_ssl_config.push_back(kProtoHTTP11); + ssl_provider1->next_protos_expected_in_ssl_config = + NextProtoVector{kProtoHTTP11}; // Force HTTP/1.1. ssl_provider1->next_proto = kProtoHTTP11; helper.AddDataWithSSLSocketDataProvider(&data1, std::move(ssl_provider1)); @@ -4542,8 +4543,8 @@ auto ssl_provider0 = std::make_unique<SSLSocketDataProvider>(ASYNC, OK); // Expect HTTP/2 protocols too in SSLConfig. - ssl_provider0->next_protos_expected_in_ssl_config.push_back(kProtoHTTP2); - ssl_provider0->next_protos_expected_in_ssl_config.push_back(kProtoHTTP11); + ssl_provider0->next_protos_expected_in_ssl_config = + NextProtoVector{kProtoHTTP2, kProtoHTTP11}; // Force SPDY. ssl_provider0->next_proto = kProtoHTTP2; helper.AddDataWithSSLSocketDataProvider(&data0, std::move(ssl_provider0)); @@ -4572,7 +4573,8 @@ auto ssl_provider1 = std::make_unique<SSLSocketDataProvider>(ASYNC, OK); // Expect only HTTP/1.1 protocol in SSLConfig. - ssl_provider1->next_protos_expected_in_ssl_config.push_back(kProtoHTTP11); + ssl_provider1->next_protos_expected_in_ssl_config = + NextProtoVector{kProtoHTTP11}; // Force HTTP/1.1. ssl_provider1->next_proto = kProtoHTTP11; helper.AddDataWithSSLSocketDataProvider(&data1, std::move(ssl_provider1));
diff --git a/content/public/test/controllable_http_response.cc b/net/test/embedded_test_server/controllable_http_response.cc similarity index 84% rename from content/public/test/controllable_http_response.cc rename to net/test/embedded_test_server/controllable_http_response.cc index 586462e5..e19e95b4 100644 --- a/content/public/test/controllable_http_response.cc +++ b/net/test/embedded_test_server/controllable_http_response.cc
@@ -2,15 +2,16 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#include "content/public/test/controllable_http_response.h" +#include "net/test/embedded_test_server/controllable_http_response.h" #include "base/logging.h" #include "base/threading/thread_task_runner_handle.h" -namespace content { +namespace net { -class ControllableHttpResponse::Interceptor - : public net::test_server::HttpResponse { +namespace test_server { + +class ControllableHttpResponse::Interceptor : public HttpResponse { public: explicit Interceptor( base::WeakPtr<ControllableHttpResponse> controller, @@ -20,9 +21,8 @@ ~Interceptor() override {} private: - void SendResponse( - const net::test_server::SendBytesCallback& send, - const net::test_server::SendCompleteCallback& done) override { + void SendResponse(const SendBytesCallback& send, + const SendCompleteCallback& done) override { controller_task_runner_->PostTask( FROM_HERE, base::BindOnce(&ControllableHttpResponse::OnRequest, controller_, @@ -36,7 +36,7 @@ }; ControllableHttpResponse::ControllableHttpResponse( - net::test_server::EmbeddedTestServer* embedded_test_server, + EmbeddedTestServer* embedded_test_server, const std::string& relative_url) : weak_ptr_factory_(this) { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); @@ -85,8 +85,8 @@ void ControllableHttpResponse::OnRequest( scoped_refptr<base::SingleThreadTaskRunner> embedded_test_server_task_runner, - const net::test_server::SendBytesCallback& send, - const net::test_server::SendCompleteCallback& done) { + const SendBytesCallback& send, + const SendCompleteCallback& done) { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); DCHECK(!embedded_test_server_task_runner_) << "A ControllableHttpResponse can only handle one request at a time"; @@ -98,13 +98,12 @@ // Helper function used in the ControllableHttpResponse constructor. // static -std::unique_ptr<net::test_server::HttpResponse> -ControllableHttpResponse::RequestHandler( +std::unique_ptr<HttpResponse> ControllableHttpResponse::RequestHandler( base::WeakPtr<ControllableHttpResponse> controller, scoped_refptr<base::SingleThreadTaskRunner> controller_task_runner, bool* available, const std::string& relative_url, - const net::test_server::HttpRequest& request) { + const HttpRequest& request) { if (*available && request.relative_url == relative_url) { *available = false; return std::make_unique<ControllableHttpResponse::Interceptor>( @@ -113,4 +112,6 @@ return nullptr; } -} // namespace content +} // namespace test_server + +} // namespace net
diff --git a/content/public/test/controllable_http_response.h b/net/test/embedded_test_server/controllable_http_response.h similarity index 74% rename from content/public/test/controllable_http_response.h rename to net/test/embedded_test_server/controllable_http_response.h index 55e430c6..74f7965 100644 --- a/content/public/test/controllable_http_response.h +++ b/net/test/embedded_test_server/controllable_http_response.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 CONTENT_PUBLIC_TEST_CONTROLLABLE_HTTP_RESPONSE_H_ -#define CONTENT_PUBLIC_TEST_CONTROLLABLE_HTTP_RESPONSE_H_ +#ifndef NET_TEST_EMBEDDED_TEST_SERVER_CONTROLLABLE_HTTP_RESPONSE_H_ +#define NET_TEST_EMBEDDED_TEST_SERVER_CONTROLLABLE_HTTP_RESPONSE_H_ #include <memory> #include <string> @@ -18,7 +18,9 @@ #include "net/test/embedded_test_server/http_request.h" #include "net/test/embedded_test_server/http_response.h" -namespace content { +namespace net { + +namespace test_server { // A response that can be manually controlled on the current test thread. It is // used for waiting for a connection, sending data and closing it. It will @@ -27,9 +29,8 @@ // order they were created. class ControllableHttpResponse { public: - ControllableHttpResponse( - net::test_server::EmbeddedTestServer* embedded_test_server, - const std::string& relative_path); + ControllableHttpResponse(EmbeddedTestServer* embedded_test_server, + const std::string& relative_path); ~ControllableHttpResponse(); // These method are intented to be used in order. @@ -50,21 +51,21 @@ void OnRequest(scoped_refptr<base::SingleThreadTaskRunner> embedded_test_server_task_runner, - const net::test_server::SendBytesCallback& send, - const net::test_server::SendCompleteCallback& done); + const SendBytesCallback& send, + const SendCompleteCallback& done); - static std::unique_ptr<net::test_server::HttpResponse> RequestHandler( + static std::unique_ptr<HttpResponse> RequestHandler( base::WeakPtr<ControllableHttpResponse> controller, scoped_refptr<base::SingleThreadTaskRunner> controller_task_runner, bool* available, const std::string& relative_url, - const net::test_server::HttpRequest& request); + const HttpRequest& request); State state_ = State::WAITING_FOR_REQUEST; base::RunLoop loop_; scoped_refptr<base::SingleThreadTaskRunner> embedded_test_server_task_runner_; - net::test_server::SendBytesCallback send_; - net::test_server::SendCompleteCallback done_; + SendBytesCallback send_; + SendCompleteCallback done_; SEQUENCE_CHECKER(sequence_checker_); base::WeakPtrFactory<ControllableHttpResponse> weak_ptr_factory_; @@ -72,6 +73,8 @@ DISALLOW_COPY_AND_ASSIGN(ControllableHttpResponse); }; -} // namespace content +} // namespace test_server -#endif // CONTENT_PUBLIC_TEST_CONTROLLABLE_HTTP_RESPONSE_H_ +} // namespace net + +#endif // NET_TEST_EMBEDDED_TEST_SERVER_CONTROLLABLE_HTTP_RESPONSE_H_
diff --git a/net/test/embedded_test_server/default_handlers.cc b/net/test/embedded_test_server/default_handlers.cc index 05aa1037..0cc401d 100644 --- a/net/test/embedded_test_server/default_handlers.cc +++ b/net/test/embedded_test_server/default_handlers.cc
@@ -646,6 +646,43 @@ return std::make_unique<HungAfterHeadersHttpResponse>(); } +// /exabyte_response +// A HttpResponse that is almost never ending (with an Exabyte content-length). +class ExabyteResponse : public net::test_server::BasicHttpResponse { + public: + ExabyteResponse() {} + + void SendResponse( + const net::test_server::SendBytesCallback& send, + const net::test_server::SendCompleteCallback& done) override { + // Use 10^18 bytes (exabyte) as the content length so that the client will + // be expecting data. + send.Run("HTTP/1.1 200 OK\r\nContent-Length:1000000000000000000\r\n\r\n", + base::BindRepeating(&ExabyteResponse::SendExabyte, send)); + } + + private: + // Keeps sending the word "echo" over and over again. It can go further to + // limit the response to exactly an exabyte, but it shouldn't be necessary + // for the purpose of testing. + static void SendExabyte(const net::test_server::SendBytesCallback& send) { + base::ThreadTaskRunnerHandle::Get()->PostTask( + FROM_HERE, + base::BindRepeating( + send, "echo", + base::BindRepeating(&ExabyteResponse::SendExabyte, send))); + } + + DISALLOW_COPY_AND_ASSIGN(ExabyteResponse); +}; + +// /exabyte_response +// Almost never ending response. +std::unique_ptr<net::test_server::HttpResponse> HandleExabyteResponse( + const net::test_server::HttpRequest& request) { + return std::make_unique<ExabyteResponse>(); +} + // /gzip-body?<body> // Returns a response with a gzipped body of "<body>". Attempts to allocate // enough memory to contain the body, but DCHECKs if that fails. @@ -746,6 +783,8 @@ server->RegisterDefaultHandler( PREFIXED_HANDLER("/hung-after-headers", &HandleHungAfterHeadersResponse)); server->RegisterDefaultHandler( + PREFIXED_HANDLER("/exabyte_response", &HandleExabyteResponse)); + server->RegisterDefaultHandler( PREFIXED_HANDLER("/gzip-body", &HandleGzipBody)); server->RegisterDefaultHandler(PREFIXED_HANDLER("/self.pac", &HandleSelfPac));
diff --git a/net/test/spawned_test_server/remote_test_server.cc b/net/test/spawned_test_server/remote_test_server.cc index ce5b2db..210cb61 100644 --- a/net/test/spawned_test_server/remote_test_server.cc +++ b/net/test/spawned_test_server/remote_test_server.cc
@@ -88,14 +88,17 @@ // pass right server type to Python test server. arguments_dict.SetString("server-type", GetServerTypeString(type())); - // If the server is not on localhost and it's expected to start OCSP server - // then pass OCSP proxy port number, so the server can generate certificates - // for the OCSP server valid for the proxied port. + // If the server is expected to handle OCSP, it needs to know what port + // number to write into the AIA urls. Initialize the ocsp proxy to + // reserve a port, and pass it to the testserver so it can generate + // certificates for the OCSP server valid for the proxied port. Note that + // the test spawer may forward OCSP a second time, from the device to the + // host. bool ocsp_server_enabled = type() == TYPE_HTTPS && (ssl_options().server_certificate == SSLOptions::CERT_AUTO_AIA_INTERMEDIATE || !ssl_options().GetOCSPArgument().empty()); - if (config_.address() != IPAddress::IPv4Localhost() && ocsp_server_enabled) { + if (ocsp_server_enabled) { ocsp_proxy_ = std::make_unique<TcpSocketProxy>(io_thread_.task_runner()); bool initialized = ocsp_proxy_->Initialize(); CHECK(initialized); @@ -141,21 +144,21 @@ CHECK(initialized); test_server_proxy_->Start(IPEndPoint(config_.address(), remote_port_)); - if (ocsp_proxy_) { - const base::Value* ocsp_port_value = server_data().FindKey("ocsp_port"); - if (ocsp_port_value && ocsp_port_value->is_int()) { - ocsp_proxy_->Start( - IPEndPoint(config_.address(), ocsp_port_value->GetInt())); - } else { - LOG(WARNING) << "testserver.py didn't return ocsp_port."; - } - } - SetPort(test_server_proxy_->local_port()); } else { SetPort(remote_port_); } + if (ocsp_proxy_) { + const base::Value* ocsp_port_value = server_data().FindKey("ocsp_port"); + if (ocsp_port_value && ocsp_port_value->is_int()) { + ocsp_proxy_->Start( + IPEndPoint(config_.address(), ocsp_port_value->GetInt())); + } else { + LOG(WARNING) << "testserver.py didn't return ocsp_port."; + } + } + return SetupWhenServerStarted(); }
diff --git a/net/tools/quic/platform/impl/quic_socket_utils.cc b/net/tools/quic/platform/impl/quic_socket_utils.cc index e188da2e..434e96e 100644 --- a/net/tools/quic/platform/impl/quic_socket_utils.cc +++ b/net/tools/quic/platform/impl/quic_socket_utils.cc
@@ -274,6 +274,8 @@ // static int QuicSocketUtils::CreateUDPSocket(const QuicSocketAddress& address, + int32_t receive_buffer_size, + int32_t send_buffer_size, bool* overflow_supported) { int address_family = address.host().AddressFamilyToInt(); int fd = socket(address_family, SOCK_DGRAM | SOCK_NONBLOCK, IPPROTO_UDP); @@ -291,11 +293,11 @@ *overflow_supported = true; } - if (!SetReceiveBufferSize(fd, kDefaultSocketReceiveBuffer)) { + if (!SetReceiveBufferSize(fd, receive_buffer_size)) { return -1; } - if (!SetSendBufferSize(fd, kDefaultSocketReceiveBuffer)) { + if (!SetSendBufferSize(fd, send_buffer_size)) { return -1; }
diff --git a/net/tools/quic/platform/impl/quic_socket_utils.h b/net/tools/quic/platform/impl/quic_socket_utils.h index 3fb28f9..6db434f 100644 --- a/net/tools/quic/platform/impl/quic_socket_utils.h +++ b/net/tools/quic/platform/impl/quic_socket_utils.h
@@ -121,6 +121,8 @@ // Returns the created FD if successful, -1 otherwise. // |overflow_supported| is set to true if the socket supports it. static int CreateUDPSocket(const QuicSocketAddress& address, + int32_t receive_buffer_size, + int32_t send_buffer_size, bool* overflow_supported); private:
diff --git a/net/tools/quic/platform/impl/quic_socket_utils_test.cc b/net/tools/quic/platform/impl/quic_socket_utils_test.cc index 3b4e733..7d5d173b 100644 --- a/net/tools/quic/platform/impl/quic_socket_utils_test.cc +++ b/net/tools/quic/platform/impl/quic_socket_utils_test.cc
@@ -29,7 +29,9 @@ int CreateUDPSocket(const QuicSocketAddress& address) { bool overflow_supported = false; - int fd = QuicSocketUtils::CreateUDPSocket(address, &overflow_supported); + int fd = QuicSocketUtils::CreateUDPSocket( + address, /*receive_buffer_size =*/kDefaultSocketReceiveBuffer, + /*send_buffer_size =*/kDefaultSocketReceiveBuffer, &overflow_supported); if (fd != -1) { open_sockets_.push_back(fd); }
diff --git a/net/tools/quic/quic_client_epoll_network_helper.cc b/net/tools/quic/quic_client_epoll_network_helper.cc index fd8d0c7..fefaae4 100644 --- a/net/tools/quic/quic_client_epoll_network_helper.cc +++ b/net/tools/quic/quic_client_epoll_network_helper.cc
@@ -65,8 +65,7 @@ int bind_to_port) { epoll_server_->set_timeout_in_us(50 * 1000); - int fd = - QuicSocketUtils::CreateUDPSocket(server_address, &overflow_supported_); + int fd = CreateUDPSocket(server_address, &overflow_supported_); if (fd < 0) { return false; } @@ -144,6 +143,11 @@ overflow_supported_ ? &packets_dropped_ : nullptr); --times_to_read; } + if (packets_dropped_ > 100) { + QUIC_LOG_FIRST_N(ERROR, 50) + << packets_dropped_ + << " packets droped in the socket receive buffer."; + } if (client_->connected() && more_to_read) { event->out_ready_mask |= EPOLLIN; } @@ -189,4 +193,12 @@ client_->session()->ProcessUdpPacket(self_address, peer_address, packet); } +int QuicClientEpollNetworkHelper::CreateUDPSocket( + QuicSocketAddress server_address, + bool* overflow_supported) { + return QuicSocketUtils::CreateUDPSocket( + server_address, + /*receive_buffer_size =*/kDefaultSocketReceiveBuffer, + /*send_buffer_size =*/kDefaultSocketReceiveBuffer, overflow_supported); +} } // namespace net
diff --git a/net/tools/quic/quic_client_epoll_network_helper.h b/net/tools/quic/quic_client_epoll_network_helper.h index 4e83100..61fbaf0 100644 --- a/net/tools/quic/quic_client_epoll_network_helper.h +++ b/net/tools/quic/quic_client_epoll_network_helper.h
@@ -81,6 +81,12 @@ // Otherwise, return -1. int GetLatestFD() const; + // Create socket for connection to |server_address| with default socket + // options. + // Return fd index. + virtual int CreateUDPSocket(QuicSocketAddress server_address, + bool* overflow_supported); + QuicClientBase* client() { return client_; } void set_max_reads_per_epoll_loop(int num_reads) {
diff --git a/net/tools/quic/quic_dispatcher.cc b/net/tools/quic/quic_dispatcher.cc index 0eb953fa..a18d2ce 100644 --- a/net/tools/quic/quic_dispatcher.cc +++ b/net/tools/quic/quic_dispatcher.cc
@@ -54,9 +54,7 @@ public QuicStreamFrameDataProducer { public: explicit PacketCollector(QuicBufferAllocator* allocator) - : send_buffer_( - allocator, - GetQuicReloadableFlag(quic_allow_multiple_acks_for_data2)) {} + : send_buffer_(allocator) {} ~PacketCollector() override = default; // QuicPacketCreator::DelegateInterface methods:
diff --git a/net/tools/quic/quic_server.cc b/net/tools/quic/quic_server.cc index 42fb23737..45269bd 100644 --- a/net/tools/quic/quic_server.cc +++ b/net/tools/quic/quic_server.cc
@@ -114,7 +114,10 @@ QuicServer::~QuicServer() = default; bool QuicServer::CreateUDPSocketAndListen(const QuicSocketAddress& address) { - fd_ = QuicSocketUtils::CreateUDPSocket(address, &overflow_supported_); + fd_ = QuicSocketUtils::CreateUDPSocket( + address, + /*receive_buffer_size =*/kDefaultSocketReceiveBuffer, + /*send_buffer_size =*/kDefaultSocketReceiveBuffer, &overflow_supported_); if (fd_ < 0) { QUIC_LOG(ERROR) << "CreateSocket() failed: " << strerror(errno); return false;
diff --git a/net/url_request/url_request_http_job_unittest.cc b/net/url_request/url_request_http_job_unittest.cc index bef92b1..b07fa70 100644 --- a/net/url_request/url_request_http_job_unittest.cc +++ b/net/url_request/url_request_http_job_unittest.cc
@@ -40,6 +40,7 @@ #include "net/url_request/url_request_status.h" #include "net/url_request/url_request_test_util.h" #include "net/websockets/websocket_handshake_stream_base.h" +#include "net/websockets/websocket_test_util.h" #include "testing/gmock/include/gmock/gmock.h" #include "testing/gtest/include/gtest/gtest.h" #include "url/gurl.h" @@ -1515,6 +1516,8 @@ } #endif +#if BUILDFLAG(ENABLE_WEBSOCKETS) + // This base class just serves to set up some things before the TestURLRequest // constructor is called. class URLRequestHttpJobWebSocketTestBase : public ::testing::Test { @@ -1566,17 +1569,15 @@ WebSocketHandshakeStreamBase*()); }; -#if BUILDFLAG(ENABLE_WEBSOCKETS) - -class FakeWebSocketHandshakeStream : public WebSocketHandshakeStreamBase { +class AsyncFakeWebSocketHandshakeStream + : public FakeWebSocketHandshakeStreamBase { public: - FakeWebSocketHandshakeStream() : initialize_stream_was_called_(false) {} + AsyncFakeWebSocketHandshakeStream() : initialize_stream_was_called_(false) {} bool initialize_stream_was_called() const { return initialize_stream_was_called_; } - // Fake implementation of HttpStreamBase methods. int InitializeStream(const HttpRequestInfo* request_info, bool can_send_early, RequestPriority priority, @@ -1596,59 +1597,8 @@ return ERR_IO_PENDING; } - int ReadResponseBody(IOBuffer* buf, - int buf_len, - const CompletionCallback& callback) override { - return ERR_IO_PENDING; - } - void Close(bool not_reusable) override {} - bool IsResponseBodyComplete() const override { return false; } - - bool IsConnectionReused() const override { return false; } - void SetConnectionReused() override {} - - bool CanReuseConnection() const override { return false; } - - int64_t GetTotalReceivedBytes() const override { return 0; } - int64_t GetTotalSentBytes() const override { return 0; } - - bool GetLoadTimingInfo(LoadTimingInfo* load_timing_info) const override { - return false; - } - - bool GetAlternativeService( - AlternativeService* alternative_service) const override { - return false; - } - - void GetSSLInfo(SSLInfo* ssl_info) override {} - - void GetSSLCertRequestInfo(SSLCertRequestInfo* cert_request_info) override {} - - bool GetRemoteEndpoint(IPEndPoint* endpoint) override { return false; } - - Error GetTokenBindingSignature(crypto::ECPrivateKey* key, - TokenBindingType tb_type, - std::vector<uint8_t>* out) override { - ADD_FAILURE(); - return ERR_NOT_IMPLEMENTED; - } - - void Drain(HttpNetworkSession* session) override {} - - void PopulateNetErrorDetails(NetErrorDetails* details) override { return; } - - void SetPriority(RequestPriority priority) override {} - - HttpStream* RenewStreamForAuth() override { return nullptr; } - - // Fake implementation of WebSocketHandshakeStreamBase method(s) - std::unique_ptr<WebSocketStream> Upgrade() override { - return std::unique_ptr<WebSocketStream>(); - } - private: bool initialize_stream_was_called_; }; @@ -1662,8 +1612,7 @@ TEST_F(URLRequestHttpJobWebSocketTest, CreateHelperPassedThrough) { std::unique_ptr<MockCreateHelper> create_helper = std::make_unique<::testing::StrictMock<MockCreateHelper>>(); - FakeWebSocketHandshakeStream* fake_handshake_stream( - new FakeWebSocketHandshakeStream); + auto* fake_handshake_stream = new AsyncFakeWebSocketHandshakeStream; // Ownership of fake_handshake_stream is transferred when CreateBasicStream() // is called. EXPECT_CALL(*create_helper, CreateBasicStreamMock())
diff --git a/net/url_request/url_request_unittest.cc b/net/url_request/url_request_unittest.cc index dfc1a1a..4f1dfff 100644 --- a/net/url_request/url_request_unittest.cc +++ b/net/url_request/url_request_unittest.cc
@@ -149,7 +149,7 @@ #include "net/url_request/network_error_logging_delegate.h" #endif // BUILDFLAG(ENABLE_REPORTING) -#if defined(USE_BUILTIN_CERT_VERIFIER) +#if defined(OS_ANDROID) || defined(USE_BUILTIN_CERT_VERIFIER) #include "net/cert/cert_net_fetcher.h" #include "net/cert_net/cert_net_fetcher_impl.h" #endif @@ -10405,7 +10405,7 @@ CHECK_NE(static_cast<X509Certificate*>(NULL), root_cert.get()); test_root_.reset(new ScopedTestRoot(root_cert.get())); -#if defined(USE_BUILTIN_CERT_VERIFIER) +#if defined(OS_ANDROID) || defined(USE_BUILTIN_CERT_VERIFIER) SetGlobalCertNetFetcherForTesting(net::CreateCertNetFetcher(&context_)); #endif @@ -10454,7 +10454,7 @@ } ~HTTPSOCSPTest() override { -#if defined(USE_BUILTIN_CERT_VERIFIER) +#if defined(OS_ANDROID) || defined(USE_BUILTIN_CERT_VERIFIER) ShutdownGlobalCertNetFetcher(); #endif @@ -11200,14 +11200,6 @@ HTTPSOCSPVerifyTest, testing::ValuesIn(kOCSPVerifyData)); -static bool SystemSupportsAIA() { -#if defined(OS_ANDROID) - return false; -#else - return true; -#endif -} - class HTTPSAIATest : public HTTPSOCSPTest { public: void SetupContext() override { @@ -11240,15 +11232,10 @@ EXPECT_EQ(1, d.response_started_count()); CertStatus cert_status = r->ssl_info().cert_status; - if (SystemSupportsAIA()) { - EXPECT_EQ(OK, d.request_status()); - EXPECT_EQ(0u, cert_status & CERT_STATUS_ALL_ERRORS); - ASSERT_TRUE(r->ssl_info().cert); - EXPECT_EQ(2u, r->ssl_info().cert->intermediate_buffers().size()); - } else { - EXPECT_EQ(CERT_STATUS_AUTHORITY_INVALID, - cert_status & CERT_STATUS_ALL_ERRORS); - } + EXPECT_EQ(OK, d.request_status()); + EXPECT_EQ(0u, cert_status & CERT_STATUS_ALL_ERRORS); + ASSERT_TRUE(r->ssl_info().cert); + EXPECT_EQ(2u, r->ssl_info().cert->intermediate_buffers().size()); ASSERT_TRUE(r->ssl_info().unverified_cert); EXPECT_EQ(0u, r->ssl_info().unverified_cert->intermediate_buffers().size()); }
diff --git a/net/websockets/websocket_test_util.cc b/net/websockets/websocket_test_util.cc index bfdb376..6a2acdd9 100644 --- a/net/websockets/websocket_test_util.cc +++ b/net/websockets/websocket_test_util.cc
@@ -188,4 +188,128 @@ return &url_request_context_; } +int FakeWebSocketHandshakeStreamBase::ReadResponseBody( + IOBuffer* buf, + int buf_len, + const CompletionCallback& callback) { + NOTREACHED(); + return ERR_IO_PENDING; +} + +bool FakeWebSocketHandshakeStreamBase::IsResponseBodyComplete() const { + NOTREACHED(); + return false; +} + +bool FakeWebSocketHandshakeStreamBase::IsConnectionReused() const { + NOTREACHED(); + return false; +} +void FakeWebSocketHandshakeStreamBase::SetConnectionReused() { + NOTREACHED(); +} + +bool FakeWebSocketHandshakeStreamBase::CanReuseConnection() const { + return false; +} + +int64_t FakeWebSocketHandshakeStreamBase::GetTotalReceivedBytes() const { + return 0; +} + +int64_t FakeWebSocketHandshakeStreamBase::GetTotalSentBytes() const { + return 0; +} + +bool FakeWebSocketHandshakeStreamBase::GetLoadTimingInfo( + LoadTimingInfo* load_timing_info) const { + NOTREACHED(); + return false; +} + +bool FakeWebSocketHandshakeStreamBase::GetAlternativeService( + AlternativeService* alternative_service) const { + NOTREACHED(); + return false; +} + +void FakeWebSocketHandshakeStreamBase::GetSSLInfo(SSLInfo* ssl_info) {} + +void FakeWebSocketHandshakeStreamBase::GetSSLCertRequestInfo( + SSLCertRequestInfo* cert_request_info) { + NOTREACHED(); +} + +bool FakeWebSocketHandshakeStreamBase::GetRemoteEndpoint(IPEndPoint* endpoint) { + return false; +} + +Error FakeWebSocketHandshakeStreamBase::GetTokenBindingSignature( + crypto::ECPrivateKey* key, + TokenBindingType tb_type, + std::vector<uint8_t>* out) { + NOTREACHED(); + return ERR_NOT_IMPLEMENTED; +} + +void FakeWebSocketHandshakeStreamBase::Drain(HttpNetworkSession* session) { + NOTREACHED(); +} + +void FakeWebSocketHandshakeStreamBase::PopulateNetErrorDetails( + NetErrorDetails* details) { + NOTREACHED(); +} + +void FakeWebSocketHandshakeStreamBase::SetPriority(RequestPriority priority) { + NOTREACHED(); +} + +HttpStream* FakeWebSocketHandshakeStreamBase::RenewStreamForAuth() { + NOTREACHED(); + return nullptr; +} + +std::unique_ptr<WebSocketStream> FakeWebSocketHandshakeStreamBase::Upgrade() { + NOTREACHED(); + return std::unique_ptr<WebSocketStream>(); +} + +int FakeWebSocketHandshakeStream::InitializeStream( + const HttpRequestInfo* request_info, + bool can_send_early, + RequestPriority priority, + const NetLogWithSource& net_log, + const CompletionCallback& callback) { + state_.Initialize(request_info, can_send_early, priority, net_log, callback); + return OK; +} + +int FakeWebSocketHandshakeStream::SendRequest( + const HttpRequestHeaders& request_headers, + HttpResponseInfo* response, + const CompletionCallback& callback) { + return parser()->SendRequest(state_.GenerateRequestLine(), request_headers, + TRAFFIC_ANNOTATION_FOR_TESTS, response, + callback); +} + +int FakeWebSocketHandshakeStream::ReadResponseHeaders( + const CompletionCallback& callback) { + return parser()->ReadResponseHeaders(callback); +} + +void FakeWebSocketHandshakeStream::Close(bool not_reusable) { + if (parser()) + parser()->Close(true); +} + +std::unique_ptr<WebSocketHandshakeStreamBase> +FakeWebSocketStreamCreateHelper::CreateBasicStream( + std::unique_ptr<ClientSocketHandle> connection, + bool using_proxy) { + return std::make_unique<FakeWebSocketHandshakeStream>(std::move(connection), + using_proxy); +} + } // namespace net
diff --git a/net/websockets/websocket_test_util.h b/net/websockets/websocket_test_util.h index 945220632..cc490d9 100644 --- a/net/websockets/websocket_test_util.h +++ b/net/websockets/websocket_test_util.h
@@ -11,6 +11,10 @@ #include <string> #include "base/macros.h" +#include "net/http/http_basic_state.h" +#include "net/http/http_stream_parser.h" +#include "net/socket/client_socket_handle.h" +#include "net/traffic_annotation/network_traffic_annotation_test_helper.h" #include "net/url_request/url_request_test_util.h" #include "net/websockets/websocket_stream.h" @@ -140,6 +144,82 @@ DISALLOW_COPY_AND_ASSIGN(WebSocketTestURLRequestContextHost); }; +// Dummy WebSocketHandshakeStreamBase implementation to reduce boilerplate in +// tests. +class FakeWebSocketHandshakeStreamBase : public WebSocketHandshakeStreamBase { + public: + FakeWebSocketHandshakeStreamBase() = default; + + // HttpStreamBase methods. + int ReadResponseBody(IOBuffer* buf, + int buf_len, + const CompletionCallback& callback) override; + bool IsResponseBodyComplete() const override; + bool IsConnectionReused() const override; + void SetConnectionReused() override; + bool CanReuseConnection() const override; + int64_t GetTotalReceivedBytes() const override; + int64_t GetTotalSentBytes() const override; + bool GetLoadTimingInfo(LoadTimingInfo* load_timing_info) const override; + bool GetAlternativeService( + AlternativeService* alternative_service) const override; + void GetSSLInfo(SSLInfo* ssl_info) override; + void GetSSLCertRequestInfo(SSLCertRequestInfo* cert_request_info) override; + bool GetRemoteEndpoint(IPEndPoint* endpoint) override; + Error GetTokenBindingSignature(crypto::ECPrivateKey* key, + TokenBindingType tb_type, + std::vector<uint8_t>* out) override; + void Drain(HttpNetworkSession* session) override; + void PopulateNetErrorDetails(NetErrorDetails* details) override; + void SetPriority(RequestPriority priority) override; + HttpStream* RenewStreamForAuth() override; + + // WebSocketHandshakeStreamBase method. + std::unique_ptr<WebSocketStream> Upgrade() override; + + private: + DISALLOW_COPY_AND_ASSIGN(FakeWebSocketHandshakeStreamBase); +}; + +// Fake WebSocketHandshakeStreamBase implementation that implements SendRequest +// and ReadResponseHeaders to send data on the mock socket. +class FakeWebSocketHandshakeStream : public FakeWebSocketHandshakeStreamBase { + public: + FakeWebSocketHandshakeStream(std::unique_ptr<ClientSocketHandle> connection, + bool using_proxy) + : state_(std::move(connection), using_proxy, false) {} + + // HttpStreamBase methods. + int InitializeStream(const HttpRequestInfo* request_info, + bool can_send_early, + RequestPriority priority, + const NetLogWithSource& net_log, + const CompletionCallback& callback) override; + + int SendRequest(const HttpRequestHeaders& request_headers, + HttpResponseInfo* response, + const CompletionCallback& callback) override; + + int ReadResponseHeaders(const CompletionCallback& callback) override; + + void Close(bool not_reusable) override; + + private: + HttpStreamParser* parser() const { return state_.parser(); } + HttpBasicState state_; + + DISALLOW_COPY_AND_ASSIGN(FakeWebSocketHandshakeStream); +}; + +class FakeWebSocketStreamCreateHelper + : public WebSocketHandshakeStreamBase::CreateHelper { + public: + std::unique_ptr<WebSocketHandshakeStreamBase> CreateBasicStream( + std::unique_ptr<ClientSocketHandle> connection, + bool using_proxy) override; + ~FakeWebSocketStreamCreateHelper() override = default; +}; + } // namespace net #endif // NET_WEBSOCKETS_WEBSOCKET_TEST_UTIL_H_
diff --git a/remoting/host/policy_watcher.cc b/remoting/host/policy_watcher.cc index 297dcd7..c428bad 100644 --- a/remoting/host/policy_watcher.cc +++ b/remoting/host/policy_watcher.cc
@@ -376,8 +376,7 @@ policy::PolicyServiceImpl::Providers providers; providers.push_back(policy_provider.get()); std::unique_ptr<policy::PolicyServiceImpl> policy_service = - std::make_unique<policy::PolicyServiceImpl>(); - policy_service->SetProviders(providers); + std::make_unique<policy::PolicyServiceImpl>(std::move(providers)); policy::PolicyService* borrowed_policy_service = policy_service.get(); return base::WrapUnique(new PolicyWatcher(
diff --git a/services/BUILD.gn b/services/BUILD.gn index 861c27f8..a4167a9 100644 --- a/services/BUILD.gn +++ b/services/BUILD.gn
@@ -65,6 +65,9 @@ "//services/data_decoder/public/cpp/android:safe_json_java", "//services/device:java", + # Some tests make network requests. + "//net/android:net_java", + # Some tests need to initialize V8. "//v8:v8_external_startup_data_assets", ] @@ -91,7 +94,10 @@ # The division between "all platforms" and "!iOS" here needs to match that # for the main deps list in the services_unittests target above. - catalog_deps = [ "//services/identity:tests_catalog" ] + catalog_deps = [ + "//services/identity:tests_catalog", + "//services/network:tests_catalog", + ] if (!is_ios) { catalog_deps += [
diff --git a/services/identity/public/cpp/primary_account_access_token_fetcher_unittest.cc b/services/identity/public/cpp/primary_account_access_token_fetcher_unittest.cc index cc4fac0..4cb16f51 100644 --- a/services/identity/public/cpp/primary_account_access_token_fetcher_unittest.cc +++ b/services/identity/public/cpp/primary_account_access_token_fetcher_unittest.cc
@@ -16,7 +16,6 @@ #include "components/signin/core/browser/account_tracker_service.h" #include "components/signin/core/browser/fake_profile_oauth2_token_service.h" #include "components/signin/core/browser/fake_signin_manager.h" -#include "components/signin/core/browser/profile_management_switches.h" #include "components/signin/core/browser/test_signin_client.h" #include "components/sync_preferences/testing_pref_service_syncable.h" #include "testing/gmock/include/gmock/gmock.h" @@ -62,7 +61,6 @@ PrimaryAccountAccessTokenFetcherTest() : signin_client_(&pref_service_) { AccountTrackerService::RegisterPrefs(pref_service_.registry()); - signin::RegisterAccountConsistencyProfilePrefs(pref_service_.registry()); #if defined(OS_CHROMEOS) SigninManagerBase::RegisterProfilePrefs(pref_service_.registry()); SigninManagerBase::RegisterPrefs(pref_service_.registry()); @@ -71,9 +69,6 @@ SigninManager::RegisterPrefs(pref_service_.registry()); #endif // OS_CHROMEOS - signin::SetGaiaOriginIsolatedCallback( - base::BindRepeating([] { return true; })); - account_tracker_ = base::MakeUnique<AccountTrackerService>(); account_tracker_->Initialize(&signin_client_);
diff --git a/services/network/BUILD.gn b/services/network/BUILD.gn index 45c8a51f..1cadb5c 100644 --- a/services/network/BUILD.gn +++ b/services/network/BUILD.gn
@@ -3,7 +3,10 @@ # found in the LICENSE file. import("//mojo/public/tools/bindings/mojom.gni") +import("//services/catalog/public/tools/catalog.gni") +import("//services/service_manager/public/cpp/service.gni") import("//services/service_manager/public/service_manifest.gni") +import("//services/service_manager/public/tools/test/service_test.gni") static_library("network_service") { sources = [ @@ -63,7 +66,6 @@ "//net", "//net:extras", "//services/network/public/cpp", - "//services/network/public/cpp:network_features", "//services/network/public/interfaces", "//services/service_manager/public/cpp", "//services/service_manager/public/interfaces", @@ -107,7 +109,13 @@ ] if (!is_ios) { - sources += [ "proxy_resolver_factory_mojo_unittest.cc" ] + sources += [ + # TODO(sdefresne): get these working on iOS. They currently hang. + # http://crbug.com/803149 + "network_service_unittest.cc", + "proxy_resolver_factory_mojo_unittest.cc", + "url_loader_unittest.cc", + ] } deps = [ @@ -119,8 +127,10 @@ "//mojo/public/cpp/bindings", "//net", "//net:test_support", - "//services/network/public/cpp:network_features", + "//services/network/public/cpp", "//services/network/public/interfaces", + "//services/service_manager/public/cpp", + "//services/service_manager/public/cpp:service_test_support", "//testing/gtest", ] } @@ -152,3 +162,14 @@ name = "network" source = "manifest.json" } + +service_manifest("unittest_manifest") { + name = "network_unittests" + source = "test/service_unittest_manifest.json" + packaged_services = [ ":manifest" ] +} + +catalog("tests_catalog") { + testonly = true + embedded_services = [ ":unittest_manifest" ] +}
diff --git a/services/network/cookie_manager.cc b/services/network/cookie_manager.cc index 0012abb..aea0291 100644 --- a/services/network/cookie_manager.cc +++ b/services/network/cookie_manager.cc
@@ -126,10 +126,6 @@ case net::CookieStore::ChangeCause::INSERTED: return network::mojom::CookieChangeCause::INSERTED; case net::CookieStore::ChangeCause::EXPLICIT: - case net::CookieStore::ChangeCause::EXPLICIT_DELETE_BETWEEN: - case net::CookieStore::ChangeCause::EXPLICIT_DELETE_PREDICATE: - case net::CookieStore::ChangeCause::EXPLICIT_DELETE_SINGLE: - case net::CookieStore::ChangeCause::EXPLICIT_DELETE_CANONICAL: return network::mojom::CookieChangeCause::EXPLICIT; case net::CookieStore::ChangeCause::UNKNOWN_DELETION: return network::mojom::CookieChangeCause::UNKNOWN_DELETION;
diff --git a/content/network/network_service_unittest.cc b/services/network/network_service_unittest.cc similarity index 78% rename from content/network/network_service_unittest.cc rename to services/network/network_service_unittest.cc index bcaa413..32f082e 100644 --- a/content/network/network_service_unittest.cc +++ b/services/network/network_service_unittest.cc
@@ -9,7 +9,6 @@ #include "base/test/scoped_task_environment.h" #include "base/threading/thread_task_runner_handle.h" #include "build/build_config.h" -#include "content/public/common/service_names.mojom.h" #include "net/base/mock_network_change_notifier.h" #include "net/proxy_resolution/proxy_config.h" #include "net/test/embedded_test_server/embedded_test_server.h" @@ -24,15 +23,14 @@ #include "services/service_manager/public/interfaces/service_factory.mojom.h" #include "testing/gtest/include/gtest/gtest.h" -using network::NetworkService; - -namespace content { +namespace network { namespace { -network::mojom::NetworkContextParamsPtr CreateContextParams() { - network::mojom::NetworkContextParamsPtr params = - network::mojom::NetworkContextParams::New(); +const char kNetworkServiceName[] = "network"; + +mojom::NetworkContextParamsPtr CreateContextParams() { + mojom::NetworkContextParamsPtr params = mojom::NetworkContextParams::New(); // Use a fixed proxy config, to avoid dependencies on local network // configuration. params->initial_proxy_config = net::ProxyConfig::CreateDirect(); @@ -44,7 +42,7 @@ NetworkServiceTest() : scoped_task_environment_( base::test::ScopedTaskEnvironment::MainThreadType::IO), - service_(network::NetworkServiceImpl::CreateForTesting()) {} + service_(NetworkServiceImpl::CreateForTesting()) {} ~NetworkServiceTest() override {} NetworkService* service() const { return service_.get(); } @@ -59,7 +57,7 @@ // Test shutdown in the case a NetworkContext is destroyed before the // NetworkService. TEST_F(NetworkServiceTest, CreateAndDestroyContext) { - network::mojom::NetworkContextPtr network_context; + mojom::NetworkContextPtr network_context; service()->CreateNetworkContext(mojo::MakeRequest(&network_context), CreateContextParams()); network_context.reset(); @@ -71,7 +69,7 @@ // NetworkService is destroyed. The service should destroy the NetworkContext // itself. TEST_F(NetworkServiceTest, DestroyingServiceDestroysContext) { - network::mojom::NetworkContextPtr network_context; + mojom::NetworkContextPtr network_context; service()->CreateNetworkContext(mojo::MakeRequest(&network_context), CreateContextParams()); base::RunLoop run_loop; @@ -106,9 +104,9 @@ service_manager::mojom::ServiceRequest request, const std::string& name, service_manager::mojom::PIDReceiverPtr pid_receiver) override { - if (name == mojom::kNetworkServiceName) { + if (name == kNetworkServiceName) { service_context_.reset(new service_manager::ServiceContext( - network::NetworkServiceImpl::CreateForTesting(), std::move(request))); + NetworkServiceImpl::CreateForTesting(), std::move(request))); } } @@ -131,12 +129,12 @@ : public service_manager::test::ServiceTest { public: NetworkServiceTestWithService() - : ServiceTest("content_unittests", + : ServiceTest("network_unittests", base::test::ScopedTaskEnvironment::MainThreadType::IO) {} ~NetworkServiceTestWithService() override {} void LoadURL(const GURL& url) { - network::ResourceRequest request; + ResourceRequest request; request.url = url; request.method = "GET"; request.request_initiator = url::Origin(); @@ -144,24 +142,23 @@ client_->RunUntilComplete(); } - void StartLoadingURL(const network::ResourceRequest& request, - uint32_t process_id) { - client_.reset(new network::TestURLLoaderClient()); - network::mojom::URLLoaderFactoryPtr loader_factory; + void StartLoadingURL(const ResourceRequest& request, uint32_t process_id) { + client_.reset(new TestURLLoaderClient()); + mojom::URLLoaderFactoryPtr loader_factory; network_context_->CreateURLLoaderFactory(mojo::MakeRequest(&loader_factory), process_id); loader_factory->CreateLoaderAndStart( - mojo::MakeRequest(&loader_), 1, 1, network::mojom::kURLLoadOptionNone, - request, client_->CreateInterfacePtr(), + mojo::MakeRequest(&loader_), 1, 1, mojom::kURLLoadOptionNone, request, + client_->CreateInterfacePtr(), net::MutableNetworkTrafficAnnotationTag(TRAFFIC_ANNOTATION_FOR_TESTS)); } net::EmbeddedTestServer* test_server() { return &test_server_; } - network::TestURLLoaderClient* client() { return client_.get(); } - network::mojom::URLLoader* loader() { return loader_.get(); } - network::mojom::NetworkService* service() { return network_service_.get(); } - network::mojom::NetworkContext* context() { return network_context_.get(); } + TestURLLoaderClient* client() { return client_.get(); } + mojom::URLLoader* loader() { return loader_.get(); } + mojom::NetworkService* service() { return network_service_.get(); } + mojom::NetworkContext* context() { return network_context_.get(); } private: std::unique_ptr<service_manager::Service> CreateService() override { @@ -169,22 +166,22 @@ } void SetUp() override { - base::FilePath content_test_data(FILE_PATH_LITERAL("content/test/data")); - test_server_.AddDefaultHandlers(content_test_data); + base::FilePath services_test_data(FILE_PATH_LITERAL("services/test/data")); + test_server_.AddDefaultHandlers(services_test_data); ASSERT_TRUE(test_server_.Start()); service_manager::test::ServiceTest::SetUp(); - connector()->BindInterface(mojom::kNetworkServiceName, &network_service_); - network::mojom::NetworkContextParamsPtr context_params = - network::mojom::NetworkContextParams::New(); + connector()->BindInterface(kNetworkServiceName, &network_service_); + mojom::NetworkContextParamsPtr context_params = + mojom::NetworkContextParams::New(); network_service_->CreateNetworkContext(mojo::MakeRequest(&network_context_), std::move(context_params)); } net::EmbeddedTestServer test_server_; - std::unique_ptr<network::TestURLLoaderClient> client_; - network::mojom::NetworkServicePtr network_service_; - network::mojom::NetworkContextPtr network_context_; - network::mojom::URLLoaderPtr loader_; + std::unique_ptr<TestURLLoaderClient> client_; + mojom::NetworkServicePtr network_service_; + mojom::NetworkContextPtr network_context_; + mojom::URLLoaderPtr loader_; DISALLOW_COPY_AND_ASSIGN(NetworkServiceTestWithService); }; @@ -198,7 +195,7 @@ // Verifies that raw headers are only reported if requested. TEST_F(NetworkServiceTestWithService, RawRequestHeadersAbsent) { - network::ResourceRequest request; + ResourceRequest request; request.url = test_server()->GetURL("/server-redirect?/echo"); request.method = "GET"; request.request_initiator = url::Origin(); @@ -212,7 +209,7 @@ } TEST_F(NetworkServiceTestWithService, RawRequestHeadersPresent) { - network::ResourceRequest request; + ResourceRequest request; request.url = test_server()->GetURL("/server-redirect?/echo"); request.method = "GET"; request.report_raw_headers = true; @@ -221,7 +218,7 @@ client()->RunUntilRedirectReceived(); EXPECT_TRUE(client()->has_received_redirect()); { - scoped_refptr<network::HttpRawRequestResponseInfo> request_response_info = + scoped_refptr<HttpRawRequestResponseInfo> request_response_info = client()->response_head().raw_request_response_info; ASSERT_TRUE(request_response_info); EXPECT_EQ(301, request_response_info->http_status_code); @@ -238,7 +235,7 @@ loader()->FollowRedirect(); client()->RunUntilComplete(); { - scoped_refptr<network::HttpRawRequestResponseInfo> request_response_info = + scoped_refptr<HttpRawRequestResponseInfo> request_response_info = client()->response_head().raw_request_response_info; EXPECT_EQ(200, request_response_info->http_status_code); EXPECT_EQ("OK", request_response_info->http_status_text); @@ -255,7 +252,7 @@ TEST_F(NetworkServiceTestWithService, RawRequestAccessControl) { const uint32_t process_id = 42; - network::ResourceRequest request; + ResourceRequest request; request.url = test_server()->GetURL("/nocache.html"); request.method = "GET"; request.report_raw_headers = true; @@ -268,7 +265,7 @@ StartLoadingURL(request, process_id); client()->RunUntilComplete(); { - scoped_refptr<network::HttpRawRequestResponseInfo> request_response_info = + scoped_refptr<HttpRawRequestResponseInfo> request_response_info = client()->response_head().raw_request_response_info; ASSERT_TRUE(request_response_info); EXPECT_EQ(200, request_response_info->http_status_code); @@ -282,12 +279,12 @@ } TEST_F(NetworkServiceTestWithService, SetNetworkConditions) { - network::mojom::NetworkConditionsPtr network_conditions = - network::mojom::NetworkConditions::New(); + mojom::NetworkConditionsPtr network_conditions = + mojom::NetworkConditions::New(); network_conditions->offline = true; context()->SetNetworkConditions("42", std::move(network_conditions)); - network::ResourceRequest request; + ResourceRequest request; request.url = test_server()->GetURL("/nocache.html"); request.method = "GET"; @@ -302,14 +299,14 @@ EXPECT_EQ(net::ERR_INTERNET_DISCONNECTED, client()->completion_status().error_code); - network_conditions = network::mojom::NetworkConditions::New(); + network_conditions = mojom::NetworkConditions::New(); network_conditions->offline = false; context()->SetNetworkConditions("42", std::move(network_conditions)); StartLoadingURL(request, 0); client()->RunUntilComplete(); EXPECT_EQ(net::OK, client()->completion_status().error_code); - network_conditions = network::mojom::NetworkConditions::New(); + network_conditions = mojom::NetworkConditions::New(); network_conditions->offline = true; context()->SetNetworkConditions("42", std::move(network_conditions)); @@ -326,19 +323,18 @@ } class TestNetworkChangeManagerClient - : public network::mojom::NetworkChangeManagerClient { + : public mojom::NetworkChangeManagerClient { public: explicit TestNetworkChangeManagerClient( - network::mojom::NetworkService* network_service) - : connection_type_(network::mojom::ConnectionType::CONNECTION_UNKNOWN), + mojom::NetworkService* network_service) + : connection_type_(mojom::ConnectionType::CONNECTION_UNKNOWN), binding_(this) { - network::mojom::NetworkChangeManagerPtr manager_ptr; - network::mojom::NetworkChangeManagerRequest request( - mojo::MakeRequest(&manager_ptr)); + mojom::NetworkChangeManagerPtr manager_ptr; + mojom::NetworkChangeManagerRequest request(mojo::MakeRequest(&manager_ptr)); network_service->GetNetworkChangeManager(std::move(request)); - network::mojom::NetworkChangeManagerClientPtr client_ptr; - network::mojom::NetworkChangeManagerClientRequest client_request( + mojom::NetworkChangeManagerClientPtr client_ptr; + mojom::NetworkChangeManagerClientRequest client_request( mojo::MakeRequest(&client_ptr)); binding_.Bind(std::move(client_request)); manager_ptr->RequestNotifications(std::move(client_ptr)); @@ -347,26 +343,26 @@ ~TestNetworkChangeManagerClient() override {} // NetworkChangeManagerClient implementation: - void OnInitialConnectionType(network::mojom::ConnectionType type) override { + void OnInitialConnectionType(mojom::ConnectionType type) override { if (type == connection_type_) run_loop_.Quit(); } - void OnNetworkChanged(network::mojom::ConnectionType type) override { + void OnNetworkChanged(mojom::ConnectionType type) override { if (type == connection_type_) run_loop_.Quit(); } // Waits for the desired |connection_type| notification. - void WaitForNotification(network::mojom::ConnectionType type) { + void WaitForNotification(mojom::ConnectionType type) { connection_type_ = type; run_loop_.Run(); } private: base::RunLoop run_loop_; - network::mojom::ConnectionType connection_type_; - mojo::Binding<network::mojom::NetworkChangeManagerClient> binding_; + mojom::ConnectionType connection_type_; + mojo::Binding<mojom::NetworkChangeManagerClient> binding_; DISALLOW_COPY_AND_ASSIGN(TestNetworkChangeManagerClient); }; @@ -376,7 +372,7 @@ NetworkChangeTest() : scoped_task_environment_( base::test::ScopedTaskEnvironment::MainThreadType::IO) { - service_ = network::NetworkServiceImpl::CreateForTesting(); + service_ = NetworkServiceImpl::CreateForTesting(); } ~NetworkChangeTest() override {} @@ -394,7 +390,7 @@ std::unique_ptr<NetworkService> service_; }; -// network::mojom:NetworkChangeManager currently doesn't support ChromeOS, +// mojom:NetworkChangeManager currently doesn't support ChromeOS, // which has a different code path to set up net::NetworkChangeNotifier. #if defined(OS_CHROMEOS) || defined(OS_FUCHSIA) #define MAYBE_NetworkChangeManagerRequest DISABLED_NetworkChangeManagerRequest @@ -405,19 +401,18 @@ TestNetworkChangeManagerClient manager_client(service()); net::NetworkChangeNotifier::NotifyObserversOfNetworkChangeForTests( net::NetworkChangeNotifier::CONNECTION_3G); - manager_client.WaitForNotification( - network::mojom::ConnectionType::CONNECTION_3G); + manager_client.WaitForNotification(mojom::ConnectionType::CONNECTION_3G); } class NetworkServiceNetworkChangeTest : public service_manager::test::ServiceTest { public: NetworkServiceNetworkChangeTest() - : ServiceTest("content_unittests", + : ServiceTest("network_unittests", base::test::ScopedTaskEnvironment::MainThreadType::IO) {} ~NetworkServiceNetworkChangeTest() override {} - network::mojom::NetworkService* service() { return network_service_.get(); } + mojom::NetworkService* service() { return network_service_.get(); } private: // A ServiceTestClient that broadcasts a network change notification in the @@ -434,10 +429,9 @@ service_manager::mojom::ServiceRequest request, const std::string& name, service_manager::mojom::PIDReceiverPtr pid_receiver) override { - if (name == mojom::kNetworkServiceName) { + if (name == kNetworkServiceName) { service_context_.reset(new service_manager::ServiceContext( - network::NetworkServiceImpl::CreateForTesting(), - std::move(request))); + NetworkServiceImpl::CreateForTesting(), std::move(request))); // Send a broadcast after NetworkService is actually created. // Otherwise, this NotifyObservers is a no-op. net::NetworkChangeNotifier::NotifyObserversOfNetworkChangeForTests( @@ -451,10 +445,10 @@ void SetUp() override { service_manager::test::ServiceTest::SetUp(); - connector()->BindInterface(mojom::kNetworkServiceName, &network_service_); + connector()->BindInterface(kNetworkServiceName, &network_service_); } - network::mojom::NetworkServicePtr network_service_; + mojom::NetworkServicePtr network_service_; #if defined(OS_ANDROID) // On Android, NetworkChangeNotifier setup is more involved and needs // to be split between UI thread and network thread. Use a mock @@ -467,10 +461,9 @@ TEST_F(NetworkServiceNetworkChangeTest, MAYBE_NetworkChangeManagerRequest) { TestNetworkChangeManagerClient manager_client(service()); - manager_client.WaitForNotification( - network::mojom::ConnectionType::CONNECTION_3G); + manager_client.WaitForNotification(mojom::ConnectionType::CONNECTION_3G); } } // namespace -} // namespace content +} // namespace network
diff --git a/services/network/public/cpp/BUILD.gn b/services/network/public/cpp/BUILD.gn index b72e41f0..2a87004 100644 --- a/services/network/public/cpp/BUILD.gn +++ b/services/network/public/cpp/BUILD.gn
@@ -4,10 +4,14 @@ import("//mojo/public/tools/bindings/mojom.gni") -static_library("cpp") { +component("cpp") { + output_name = "network_cpp" + sources = [ "cors/cors.cc", "cors/cors.h", + "features.cc", + "features.h", "ignore_errors_cert_verifier.cc", "ignore_errors_cert_verifier.h", "loader_util.cc", @@ -29,8 +33,7 @@ ] public_deps = [ - ":network_features", - ":typemap_dependencies", + ":cpp_base", "//services/network/public/interfaces", "//url/ipc:url_ipc", ] @@ -43,9 +46,13 @@ "//net", "//services/proxy_resolver/public/interfaces", ] + + defines = [ "IS_NETWORK_CPP_IMPL" ] } -static_library("typemap_dependencies") { +component("cpp_base") { + output_name = "network_cpp_base" + sources = [ "cors/cors_error_status.cc", "cors/cors_error_status.h", @@ -81,23 +88,7 @@ "//net", "//services/network/public/interfaces:interfaces_shared", ] -} - -component("network_features") { - public = [ - "features.h", - ] - - sources = [ - "features.cc", - "features_export.h", - ] - - public_deps = [ - "//base", - ] - - defines = [ "NETWORK_FEATURES_IMPLEMENTATION" ] + defines = [ "IS_NETWORK_CPP_BASE_IMPL" ] } mojom("test_interfaces") {
diff --git a/services/network/public/cpp/cors/cors.h b/services/network/public/cpp/cors/cors.h index 4ce03e6..deb61a1 100644 --- a/services/network/public/cpp/cors/cors.h +++ b/services/network/public/cpp/cors/cors.h
@@ -7,6 +7,7 @@ #include <string> +#include "base/component_export.h" #include "base/optional.h" #include "services/network/public/interfaces/cors.mojom-shared.h" #include "services/network/public/interfaces/fetch_api.mojom-shared.h" @@ -22,13 +23,17 @@ namespace header_names { +COMPONENT_EXPORT(NETWORK_CPP) extern const char kAccessControlAllowCredentials[]; +COMPONENT_EXPORT(NETWORK_CPP) extern const char kAccessControlAllowOrigin[]; +COMPONENT_EXPORT(NETWORK_CPP) extern const char kAccessControlAllowSuborigin[]; } // namespace header_names // Performs a CORS access check on the response parameters. +COMPONENT_EXPORT(NETWORK_CPP) base::Optional<mojom::CORSError> CheckAccess( const GURL& response_url, const int response_status_code, @@ -45,19 +50,23 @@ // TODO(toyoshim): Remove |skip_scheme_check| that is used when customized // scheme check runs in Blink side in the legacy mode. // See https://crbug.com/800669. +COMPONENT_EXPORT(NETWORK_CPP) base::Optional<mojom::CORSError> CheckRedirectLocation(const GURL& redirect_url, bool skip_scheme_check); // Performs the required CORS checks on the response to a preflight request. // Returns |kPreflightSuccess| if preflight response was successful. +COMPONENT_EXPORT(NETWORK_CPP) base::Optional<mojom::CORSError> CheckPreflight(const int status_code); // Checks errors for the currently experimental "Access-Control-Allow-External:" // header. Shares error conditions with standard preflight checking. // See https://crbug.com/590714. +COMPONENT_EXPORT(NETWORK_CPP) base::Optional<mojom::CORSError> CheckExternalPreflight( const base::Optional<std::string>& allow_external); +COMPONENT_EXPORT(NETWORK_CPP) bool IsCORSEnabledRequestMode(mojom::FetchRequestMode mode); } // namespace cors
diff --git a/services/network/public/cpp/cors/cors_error_status.h b/services/network/public/cpp/cors/cors_error_status.h index a8e3551a..0a7fdcbc 100644 --- a/services/network/public/cpp/cors/cors_error_status.h +++ b/services/network/public/cpp/cors/cors_error_status.h
@@ -5,13 +5,14 @@ #ifndef SERVICES_NETWORK_PUBLIC_CPP_CORS_CORS_ERROR_STATUS_H_ #define SERVICES_NETWORK_PUBLIC_CPP_CORS_CORS_ERROR_STATUS_H_ +#include "base/component_export.h" #include "base/memory/scoped_refptr.h" #include "net/http/http_response_headers.h" #include "services/network/public/interfaces/cors.mojom-shared.h" namespace network { -struct CORSErrorStatus { +struct COMPONENT_EXPORT(NETWORK_CPP_BASE) CORSErrorStatus { // This constructor is used by generated IPC serialization code. // Should not use this explicitly. // TODO(toyoshim, yhirano): Exploring a way to make this private, and allows
diff --git a/services/network/public/cpp/cors_error_status.typemap b/services/network/public/cpp/cors_error_status.typemap index efda7cd..677ec1d 100644 --- a/services/network/public/cpp/cors_error_status.typemap +++ b/services/network/public/cpp/cors_error_status.typemap
@@ -9,6 +9,6 @@ "//net", ] public_deps = [ - "//services/network/public/cpp:typemap_dependencies", + "//services/network/public/cpp:cpp_base", ] type_mappings = [ "network.mojom.CORSErrorStatus=network::CORSErrorStatus" ]
diff --git a/services/network/public/cpp/data_element.h b/services/network/public/cpp/data_element.h index 6f534ae..54ce5f99 100644 --- a/services/network/public/cpp/data_element.h +++ b/services/network/public/cpp/data_element.h
@@ -14,6 +14,7 @@ #include <string> #include <vector> +#include "base/component_export.h" #include "base/files/file.h" #include "base/files/file_path.h" #include "base/gtest_prod_util.h" @@ -27,7 +28,7 @@ // Represents a base Web data element. This could be either one of // bytes, file or blob data. -class DataElement { +class COMPONENT_EXPORT(NETWORK_CPP_BASE) DataElement { public: static const uint64_t kUnknownSize = std::numeric_limits<uint64_t>::max(); @@ -175,7 +176,9 @@ base::Time expected_modification_time_; }; +COMPONENT_EXPORT(NETWORK_CPP_BASE) bool operator==(const DataElement& a, const DataElement& b); +COMPONENT_EXPORT(NETWORK_CPP_BASE) bool operator!=(const DataElement& a, const DataElement& b); } // namespace network
diff --git a/services/network/public/cpp/features.h b/services/network/public/cpp/features.h index b247a8c..718b6ea 100644 --- a/services/network/public/cpp/features.h +++ b/services/network/public/cpp/features.h
@@ -2,23 +2,27 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#ifndef SERVICES_NETWORK_PUBLIC_CPP_FEATURES_ -#define SERVICES_NETWORK_PUBLIC_CPP_FEATURES_ +#ifndef SERVICES_NETWORK_PUBLIC_CPP_FEATURES_H_ +#define SERVICES_NETWORK_PUBLIC_CPP_FEATURES_H_ +#include "base/component_export.h" #include "base/feature_list.h" -#include "services/network/public/cpp/features_export.h" namespace network { namespace features { -NETWORK_FEATURES_EXPORT extern const base::Feature kNetworkErrorLogging; -NETWORK_FEATURES_EXPORT extern const base::Feature kNetworkService; -NETWORK_FEATURES_EXPORT extern const base::Feature kOutOfBlinkCORS; -NETWORK_FEATURES_EXPORT extern const base::Feature - kRendererSideResourceScheduler; -NETWORK_FEATURES_EXPORT extern const base::Feature kReporting; +COMPONENT_EXPORT(NETWORK_CPP) +extern const base::Feature kNetworkErrorLogging; +COMPONENT_EXPORT(NETWORK_CPP) +extern const base::Feature kNetworkService; +COMPONENT_EXPORT(NETWORK_CPP) +extern const base::Feature kOutOfBlinkCORS; +COMPONENT_EXPORT(NETWORK_CPP) +extern const base::Feature kRendererSideResourceScheduler; +COMPONENT_EXPORT(NETWORK_CPP) +extern const base::Feature kReporting; } // namespace features } // namespace network -#endif // SERVICES_NETWORK_PUBLIC_CPP_FEATURES_ +#endif // SERVICES_NETWORK_PUBLIC_CPP_FEATURES_H_
diff --git a/services/network/public/cpp/features_export.h b/services/network/public/cpp/features_export.h deleted file mode 100644 index 821c526..0000000 --- a/services/network/public/cpp/features_export.h +++ /dev/null
@@ -1,34 +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. - -#ifndef SERVICES_NETWORK_PUBLIC_CPP_FEATURES_EXPORT_H_ -#define SERVICES_NETWORK_PUBLIC_CPP_FEATURES_EXPORT_H_ - -#if defined(COMPONENT_BUILD) - -#if defined(WIN32) - -#if defined(NETWORK_FEATURES_IMPLEMENTATION) -#define NETWORK_FEATURES_EXPORT __declspec(dllexport) -#else -#define NETWORK_FEATURES_EXPORT __declspec(dllimport) -#endif - -#else // !defined(WIN32) - -#if defined(NETWORK_FEATURES_IMPLEMENTATION) -#define NETWORK_FEATURES_EXPORT __attribute__((visibility("default"))) -#else -#define NETWORK_FEATURES_EXPORT -#endif - -#endif - -#else // !defined(COMPONENT_BUILD) - -#define NETWORK_FEATURES_EXPORT - -#endif - -#endif // SERVICES_NETWORK_PUBLIC_CPP_FEATURES_EXPORT_H_
diff --git a/services/network/public/cpp/http_raw_request_response_info.h b/services/network/public/cpp/http_raw_request_response_info.h index 7a78e2e..0a31347 100644 --- a/services/network/public/cpp/http_raw_request_response_info.h +++ b/services/network/public/cpp/http_raw_request_response_info.h
@@ -10,6 +10,7 @@ #include <string> #include <vector> +#include "base/component_export.h" #include "base/memory/ref_counted.h" #include "base/strings/string_split.h" @@ -17,9 +18,9 @@ // Note: when modifying this structure, also update DeepCopy in // http_raw_request_response_info.cc. -struct HttpRawRequestResponseInfo +struct COMPONENT_EXPORT(NETWORK_CPP_BASE) HttpRawRequestResponseInfo : base::RefCounted<HttpRawRequestResponseInfo> { - typedef base::StringPairs HeadersVector; + using HeadersVector = base::StringPairs; HttpRawRequestResponseInfo();
diff --git a/services/network/public/cpp/ignore_errors_cert_verifier.h b/services/network/public/cpp/ignore_errors_cert_verifier.h index 5e08240..a848715 100644 --- a/services/network/public/cpp/ignore_errors_cert_verifier.h +++ b/services/network/public/cpp/ignore_errors_cert_verifier.h
@@ -10,6 +10,7 @@ #include <vector> #include "base/command_line.h" +#include "base/component_export.h" #include "base/containers/flat_set.h" #include "net/cert/cert_verifier.h" @@ -22,7 +23,8 @@ // IgnoreErrorsCertVerifier wraps another CertVerifier in order to ignore // verification errors from certificate chains that match a whitelist of SPKI // fingerprints. -class IgnoreErrorsCertVerifier : public net::CertVerifier { +class COMPONENT_EXPORT(NETWORK_CPP) IgnoreErrorsCertVerifier + : public net::CertVerifier { public: // SPKIHashSet is a set of SHA-256 SPKI fingerprints (RFC 7469, Section 2.4). using SPKIHashSet = base::flat_set<net::SHA256HashValue>;
diff --git a/services/network/public/cpp/loader_util.h b/services/network/public/cpp/loader_util.h index 30bcb3d0..9c88377 100644 --- a/services/network/public/cpp/loader_util.h +++ b/services/network/public/cpp/loader_util.h
@@ -5,6 +5,7 @@ #ifndef SERVICES_NETWORK_PUBLIC_CPP_LOADER_UTIL_H_ #define SERVICES_NETWORK_PUBLIC_CPP_LOADER_UTIL_H_ +#include "base/component_export.h" #include "base/memory/ref_counted.h" class GURL; @@ -23,12 +24,14 @@ struct ResourceResponse; // The name of the "Accept" header. -extern const char kAcceptHeader[]; +COMPONENT_EXPORT(NETWORK_CPP) extern const char kAcceptHeader[]; // Accept header used for frame requests. +COMPONENT_EXPORT(NETWORK_CPP) extern const char kFrameAcceptHeader[]; // The default Accept header value to use if none were specified. +COMPONENT_EXPORT(NETWORK_CPP) extern const char kDefaultAcceptHeader[]; // Helper utilities shared between network service and ResourceDispatcherHost @@ -36,16 +39,19 @@ // Whether the response body should be sniffed in order to determine the MIME // type of the response. +COMPONENT_EXPORT(NETWORK_CPP) bool ShouldSniffContent(net::URLRequest* url_request, ResourceResponse* response); // Fill HttpRawRequestResponseInfo based on raw headers. +COMPONENT_EXPORT(NETWORK_CPP) scoped_refptr<HttpRawRequestResponseInfo> BuildRawRequestResponseInfo( const net::URLRequest& request, const net::HttpRawRequestHeaders& raw_request_headers, const net::HttpResponseHeaders* raw_response_headers); // Returns the referrer based on the validity of the URL and command line flags. +COMPONENT_EXPORT(NETWORK_CPP) std::string ComputeReferrer(const GURL& referrer); } // namespace network
diff --git a/services/network/public/cpp/net_adapters.h b/services/network/public/cpp/net_adapters.h index 1008a64..cb19f83 100644 --- a/services/network/public/cpp/net_adapters.h +++ b/services/network/public/cpp/net_adapters.h
@@ -2,11 +2,12 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#ifndef SERVICES_NETWORK_PUBLIC_CPP_NET_ADAPTERS_ -#define SERVICES_NETWORK_PUBLIC_CPP_NET_ADAPTERS_ +#ifndef SERVICES_NETWORK_PUBLIC_CPP_NET_ADAPTERS_H_ +#define SERVICES_NETWORK_PUBLIC_CPP_NET_ADAPTERS_H_ #include <stdint.h> +#include "base/component_export.h" #include "base/macros.h" #include "mojo/public/cpp/system/data_pipe.h" #include "net/base/io_buffer.h" @@ -25,7 +26,7 @@ // of the Mojo pipe, which in turn is kept alive by the IOBuffer. This allows // the request to potentially outlive the object managing the translation. // Mojo side of a Net -> Mojo copy. The buffer is allocated by Mojo. -class NetToMojoPendingBuffer +class COMPONENT_EXPORT(NETWORK_CPP) NetToMojoPendingBuffer : public base::RefCountedThreadSafe<NetToMojoPendingBuffer> { public: // Begins a two-phase write to the data pipe. @@ -58,7 +59,8 @@ // Net side of a Net -> Mojo copy. The data will be read from the network and // copied into the buffer associated with the pending mojo write. -class NetToMojoIOBuffer : public net::WrappedIOBuffer { +class COMPONENT_EXPORT(NETWORK_CPP) NetToMojoIOBuffer + : public net::WrappedIOBuffer { public: // If |offset| is specified then the memory buffer passed to the Net layer // will be offset by that many bytes. @@ -71,7 +73,7 @@ DISALLOW_COPY_AND_ASSIGN(NetToMojoIOBuffer); }; -class MojoToNetPendingBuffer +class COMPONENT_EXPORT(NETWORK_CPP) MojoToNetPendingBuffer : public base::RefCountedThreadSafe<MojoToNetPendingBuffer> { public: // Starts reading from Mojo. @@ -117,7 +119,8 @@ // Net side of a Mojo -> Net copy. The data will already be in the // MojoToNetPendingBuffer's buffer. -class MojoToNetIOBuffer : public net::WrappedIOBuffer { +class COMPONENT_EXPORT(NETWORK_CPP) MojoToNetIOBuffer + : public net::WrappedIOBuffer { public: // |bytes_to_be_read| contains the number of bytes expected to be read by // the consumer. @@ -133,4 +136,4 @@ } // namespace network -#endif // SERVICES_NETWORK_PUBLIC_CPP_NET_ADAPTERS_ +#endif // SERVICES_NETWORK_PUBLIC_CPP_NET_ADAPTERS_H_
diff --git a/services/network/public/cpp/network_param_ipc_traits.h b/services/network/public/cpp/network_param_ipc_traits.h index a3e938d6..b0739389 100644 --- a/services/network/public/cpp/network_param_ipc_traits.h +++ b/services/network/public/cpp/network_param_ipc_traits.h
@@ -7,6 +7,7 @@ #include <string> +#include "base/component_export.h" #include "base/pickle.h" #include "ipc/ipc_param_traits.h" #include "ipc/param_traits_macros.h" @@ -36,13 +37,8 @@ #ifndef INTERNAL_SERVICES_NETWORK_PUBLIC_CPP_NETWORK_PARAM_IPC_TRAITS_H_ #define INTERNAL_SERVICES_NETWORK_PUBLIC_CPP_NETWORK_PARAM_IPC_TRAITS_H_ -// services/network/public/cpp is currently packaged as a static library, -// so there's no need for export defines; it's linked directly into whatever -// other components need it. -// This redefinition is present for the IPC macros below, including in the -// included header files. #undef IPC_MESSAGE_EXPORT -#define IPC_MESSAGE_EXPORT +#define IPC_MESSAGE_EXPORT COMPONENT_EXPORT(NETWORK_CPP_BASE) namespace network { struct HttpRawRequestResponseInfo; @@ -51,7 +47,7 @@ namespace IPC { template <> -struct ParamTraits<net::CertVerifyResult> { +struct COMPONENT_EXPORT(NETWORK_CPP_BASE) ParamTraits<net::CertVerifyResult> { typedef net::CertVerifyResult param_type; static void Write(base::Pickle* m, const param_type& p); static bool Read(const base::Pickle* m, @@ -61,7 +57,7 @@ }; template <> -struct ParamTraits<net::HashValue> { +struct COMPONENT_EXPORT(NETWORK_CPP_BASE) ParamTraits<net::HashValue> { typedef net::HashValue param_type; static void Write(base::Pickle* m, const param_type& p); static bool Read(const base::Pickle* m, @@ -71,7 +67,7 @@ }; template <> -struct ParamTraits<net::HostPortPair> { +struct COMPONENT_EXPORT(NETWORK_CPP_BASE) ParamTraits<net::HostPortPair> { typedef net::HostPortPair param_type; static void Write(base::Pickle* m, const param_type& p); static bool Read(const base::Pickle* m, @@ -81,7 +77,7 @@ }; template <> -struct ParamTraits<net::HttpRequestHeaders> { +struct COMPONENT_EXPORT(NETWORK_CPP_BASE) ParamTraits<net::HttpRequestHeaders> { typedef net::HttpRequestHeaders param_type; static void Write(base::Pickle* m, const param_type& p); static bool Read(const base::Pickle* m, @@ -91,7 +87,7 @@ }; template <> -struct ParamTraits<net::OCSPVerifyResult> { +struct COMPONENT_EXPORT(NETWORK_CPP_BASE) ParamTraits<net::OCSPVerifyResult> { typedef net::OCSPVerifyResult param_type; static void Write(base::Pickle* m, const param_type& p); static bool Read(const base::Pickle* m, @@ -101,7 +97,8 @@ }; template <> -struct ParamTraits<scoped_refptr<net::SSLCertRequestInfo>> { +struct COMPONENT_EXPORT(NETWORK_CPP_BASE) + ParamTraits<scoped_refptr<net::SSLCertRequestInfo>> { typedef scoped_refptr<net::SSLCertRequestInfo> param_type; static void Write(base::Pickle* m, const param_type& p); static bool Read(const base::Pickle* m, @@ -111,7 +108,7 @@ }; template <> -struct ParamTraits<net::SSLInfo> { +struct COMPONENT_EXPORT(NETWORK_CPP_BASE) ParamTraits<net::SSLInfo> { typedef net::SSLInfo param_type; static void Write(base::Pickle* m, const param_type& p); static bool Read(const base::Pickle* m, @@ -121,7 +118,8 @@ }; template <> -struct ParamTraits<scoped_refptr<net::ct::SignedCertificateTimestamp>> { +struct COMPONENT_EXPORT(NETWORK_CPP_BASE) + ParamTraits<scoped_refptr<net::ct::SignedCertificateTimestamp>> { typedef scoped_refptr<net::ct::SignedCertificateTimestamp> param_type; static void Write(base::Pickle* m, const param_type& p); static bool Read(const base::Pickle* m, @@ -131,7 +129,8 @@ }; template <> -struct ParamTraits<scoped_refptr<network::HttpRawRequestResponseInfo>> { +struct COMPONENT_EXPORT(NETWORK_CPP_BASE) + ParamTraits<scoped_refptr<network::HttpRawRequestResponseInfo>> { typedef scoped_refptr<network::HttpRawRequestResponseInfo> param_type; static void Write(base::Pickle* m, const param_type& p); static bool Read(const base::Pickle* m, @@ -141,7 +140,8 @@ }; template <> -struct ParamTraits<scoped_refptr<net::HttpResponseHeaders>> { +struct COMPONENT_EXPORT(NETWORK_CPP_BASE) + ParamTraits<scoped_refptr<net::HttpResponseHeaders>> { typedef scoped_refptr<net::HttpResponseHeaders> param_type; static void Write(base::Pickle* m, const param_type& p); static bool Read(const base::Pickle* m, @@ -151,7 +151,8 @@ }; template <> -struct ParamTraits<scoped_refptr<net::X509Certificate>> { +struct COMPONENT_EXPORT(NETWORK_CPP_BASE) + ParamTraits<scoped_refptr<net::X509Certificate>> { typedef scoped_refptr<net::X509Certificate> param_type; static void Write(base::Pickle* m, const param_type& p); static bool Read(const base::Pickle* m, @@ -161,7 +162,7 @@ }; template <> -struct ParamTraits<net::LoadTimingInfo> { +struct COMPONENT_EXPORT(NETWORK_CPP_BASE) ParamTraits<net::LoadTimingInfo> { typedef net::LoadTimingInfo param_type; static void Write(base::Pickle* m, const param_type& p); static bool Read(const base::Pickle* m, @@ -171,7 +172,7 @@ }; template <> -struct ParamTraits<network::DataElement> { +struct COMPONENT_EXPORT(NETWORK_CPP_BASE) ParamTraits<network::DataElement> { typedef network::DataElement param_type; static void Write(base::Pickle* m, const param_type& p); static bool Read(const base::Pickle* m, @@ -181,7 +182,8 @@ }; template <> -struct ParamTraits<scoped_refptr<network::ResourceRequestBody>> { +struct COMPONENT_EXPORT(NETWORK_CPP_BASE) + ParamTraits<scoped_refptr<network::ResourceRequestBody>> { typedef scoped_refptr<network::ResourceRequestBody> param_type; static void Write(base::Pickle* m, const param_type& p); static bool Read(const base::Pickle* m, @@ -191,7 +193,7 @@ }; template <> -struct ParamTraits<url::Origin> { +struct COMPONENT_EXPORT(NETWORK_CPP_BASE) ParamTraits<url::Origin> { typedef url::Origin param_type; static void Write(base::Pickle* m, const param_type& p); static bool Read(const base::Pickle* m,
diff --git a/services/network/public/cpp/network_switches.h b/services/network/public/cpp/network_switches.h index 5fc8138..411e455b 100644 --- a/services/network/public/cpp/network_switches.h +++ b/services/network/public/cpp/network_switches.h
@@ -2,20 +2,24 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#ifndef SERVICES_NETWORK_PUBLIC_CPP_NETWORK_SWITCHES_ -#define SERVICES_NETWORK_PUBLIC_CPP_NETWORK_SWITCHES_ +#ifndef SERVICES_NETWORK_PUBLIC_CPP_NETWORK_SWITCHES_H_ +#define SERVICES_NETWORK_PUBLIC_CPP_NETWORK_SWITCHES_H_ + +#include "base/component_export.h" namespace network { namespace switches { +COMPONENT_EXPORT(NETWORK_CPP) extern const char kHostResolverRules[]; +COMPONENT_EXPORT(NETWORK_CPP) extern const char kIgnoreCertificateErrorsSPKIList[]; -extern const char kLogNetLog[]; -extern const char kNoReferrers[]; +COMPONENT_EXPORT(NETWORK_CPP) extern const char kLogNetLog[]; +COMPONENT_EXPORT(NETWORK_CPP) extern const char kNoReferrers[]; } // namespace switches } // namespace network -#endif // SERVICES_NETWORK_PUBLIC_CPP_NETWORK_SWITCHES_ +#endif // SERVICES_NETWORK_PUBLIC_CPP_NETWORK_SWITCHES_H_
diff --git a/services/network/public/cpp/network_types.typemap b/services/network/public/cpp/network_types.typemap index 22fdb53..6c36d91 100644 --- a/services/network/public/cpp/network_types.typemap +++ b/services/network/public/cpp/network_types.typemap
@@ -9,7 +9,7 @@ public_headers = [ "//net/nqe/effective_connection_type.h" ] traits_headers = [ "//services/network/public/cpp/network_param_ipc_traits.h" ] deps = [ - "//services/network/public/cpp:typemap_dependencies", + "//services/network/public/cpp:cpp_base", ] type_mappings = [ "network.mojom.EffectiveConnectionType=net::EffectiveConnectionType" ]
diff --git a/services/network/public/cpp/proxy_config_traits.h b/services/network/public/cpp/proxy_config_traits.h index e6232d2..c7d33aa3 100644 --- a/services/network/public/cpp/proxy_config_traits.h +++ b/services/network/public/cpp/proxy_config_traits.h
@@ -5,6 +5,7 @@ #ifndef SERVICES_NETWORK_PUBLIC_CPP_PROXY_CONFIG_TRAITS_H_ #define SERVICES_NETWORK_PUBLIC_CPP_PROXY_CONFIG_TRAITS_H_ +#include "base/component_export.h" #include "net/proxy_resolution/proxy_bypass_rules.h" #include "net/proxy_resolution/proxy_config.h" #include "net/proxy_resolution/proxy_config_source.h" @@ -17,8 +18,9 @@ namespace mojo { template <> -struct StructTraits<network::mojom::ProxyBypassRulesDataView, - net::ProxyBypassRules> { +struct COMPONENT_EXPORT(NETWORK_CPP_BASE) + StructTraits<network::mojom::ProxyBypassRulesDataView, + net::ProxyBypassRules> { public: static std::vector<std::string> rules(const net::ProxyBypassRules& r); static bool Read(network::mojom::ProxyBypassRulesDataView data, @@ -26,7 +28,8 @@ }; template <> -struct StructTraits<network::mojom::ProxyListDataView, net::ProxyList> { +struct COMPONENT_EXPORT(NETWORK_CPP_BASE) + StructTraits<network::mojom::ProxyListDataView, net::ProxyList> { public: static std::vector<std::string> proxies(const net::ProxyList& r); static bool Read(network::mojom::ProxyListDataView data, @@ -34,8 +37,9 @@ }; template <> -struct EnumTraits<network::mojom::ProxyRulesType, - net::ProxyConfig::ProxyRules::Type> { +struct COMPONENT_EXPORT(NETWORK_CPP_BASE) + EnumTraits<network::mojom::ProxyRulesType, + net::ProxyConfig::ProxyRules::Type> { public: static network::mojom::ProxyRulesType ToMojom( net::ProxyConfig::ProxyRules::Type net_proxy_rules_type); @@ -44,8 +48,9 @@ }; template <> -struct StructTraits<network::mojom::ProxyRulesDataView, - net::ProxyConfig::ProxyRules> { +struct COMPONENT_EXPORT(NETWORK_CPP_BASE) + StructTraits<network::mojom::ProxyRulesDataView, + net::ProxyConfig::ProxyRules> { public: static const net::ProxyBypassRules& bypass_rules( const net::ProxyConfig::ProxyRules& r) { @@ -84,7 +89,8 @@ }; template <> -struct EnumTraits<network::mojom::ProxyConfigSource, net::ProxyConfigSource> { +struct COMPONENT_EXPORT(NETWORK_CPP_BASE) + EnumTraits<network::mojom::ProxyConfigSource, net::ProxyConfigSource> { public: static network::mojom::ProxyConfigSource ToMojom( net::ProxyConfigSource net_proxy_config_source); @@ -94,7 +100,8 @@ }; template <> -struct StructTraits<network::mojom::ProxyConfigDataView, net::ProxyConfig> { +struct COMPONENT_EXPORT(NETWORK_CPP_BASE) + StructTraits<network::mojom::ProxyConfigDataView, net::ProxyConfig> { public: static bool auto_detect(const net::ProxyConfig& r) { return r.auto_detect(); } static const GURL& pac_url(const net::ProxyConfig& r) { return r.pac_url(); }
diff --git a/services/network/public/cpp/proxy_resolving_client_socket.h b/services/network/public/cpp/proxy_resolving_client_socket.h index 3ee36ae..b2ffb9e 100644 --- a/services/network/public/cpp/proxy_resolving_client_socket.h +++ b/services/network/public/cpp/proxy_resolving_client_socket.h
@@ -1,6 +1,7 @@ // Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. + #ifndef SERVICES_NETWORK_PUBLIC_CPP_PROXY_RESOLVING_CLIENT_SOCKET_H_ #define SERVICES_NETWORK_PUBLIC_CPP_PROXY_RESOLVING_CLIENT_SOCKET_H_ @@ -9,6 +10,7 @@ #include <memory> #include "base/compiler_specific.h" +#include "base/component_export.h" #include "base/gtest_prod_util.h" #include "base/macros.h" #include "base/memory/ref_counted.h" @@ -39,7 +41,8 @@ // TODO(xunjieli): https://crbug.com/721401. This class should be private (i.e. // moved out of services/network/public/cpp). The functionalities will be // exposed only through a mojo interface. -class ProxyResolvingClientSocket : public net::StreamSocket { +class COMPONENT_EXPORT(NETWORK_CPP) ProxyResolvingClientSocket + : public net::StreamSocket { public: // Constructs a new ProxyResolvingClientSocket. |url|'s host and port specify // where a connection will be established to. The full URL will be only used
diff --git a/services/network/public/cpp/proxy_resolving_client_socket_factory.h b/services/network/public/cpp/proxy_resolving_client_socket_factory.h index 58facf1..5d9d95a 100644 --- a/services/network/public/cpp/proxy_resolving_client_socket_factory.h +++ b/services/network/public/cpp/proxy_resolving_client_socket_factory.h
@@ -7,6 +7,7 @@ #include <memory> +#include "base/component_export.h" #include "base/macros.h" #include "base/memory/ref_counted.h" #include "net/ssl/ssl_config.h" @@ -22,7 +23,7 @@ class ProxyResolvingClientSocket; -class ProxyResolvingClientSocketFactory { +class COMPONENT_EXPORT(NETWORK_CPP) ProxyResolvingClientSocketFactory { public: // Constructs a new ProxyResolvingClientSocket. |socket_factory| is the // ClientSocketFactory that will be used by the underlying HttpNetworkSession.
diff --git a/services/network/public/cpp/resource_request.h b/services/network/public/cpp/resource_request.h index f0fd32b..4accc130 100644 --- a/services/network/public/cpp/resource_request.h +++ b/services/network/public/cpp/resource_request.h
@@ -8,6 +8,7 @@ #include <stdint.h> #include <string> +#include "base/component_export.h" #include "base/memory/ref_counted.h" #include "base/optional.h" #include "net/base/request_priority.h" @@ -22,7 +23,7 @@ namespace network { -struct ResourceRequest { +struct COMPONENT_EXPORT(NETWORK_CPP_BASE) ResourceRequest { ResourceRequest(); ResourceRequest(const ResourceRequest& request); ~ResourceRequest();
diff --git a/services/network/public/cpp/resource_request_body.h b/services/network/public/cpp/resource_request_body.h index 04b90d7..64b945a 100644 --- a/services/network/public/cpp/resource_request_body.h +++ b/services/network/public/cpp/resource_request_body.h
@@ -10,18 +10,18 @@ #include <string> #include <vector> +#include "base/component_export.h" #include "base/files/file.h" #include "base/files/file_path.h" #include "base/macros.h" #include "base/memory/ref_counted.h" -#include "build/build_config.h" #include "services/network/public/cpp/data_element.h" #include "url/gurl.h" namespace network { // ResourceRequestBody represents body (i.e. upload data) of a HTTP request. -class ResourceRequestBody +class COMPONENT_EXPORT(NETWORK_CPP_BASE) ResourceRequestBody : public base::RefCountedThreadSafe<ResourceRequestBody> { public: ResourceRequestBody();
diff --git a/services/network/public/cpp/resource_response.h b/services/network/public/cpp/resource_response.h index 011bffee..71cac5f4 100644 --- a/services/network/public/cpp/resource_response.h +++ b/services/network/public/cpp/resource_response.h
@@ -11,6 +11,7 @@ #include <string> #include "base/compiler_specific.h" +#include "base/component_export.h" #include "base/memory/ref_counted.h" #include "net/url_request/url_request_status.h" #include "services/network/public/cpp/resource_response_info.h" @@ -19,7 +20,8 @@ namespace network { // Parameters for a resource response header. -struct ResourceResponseHead : ResourceResponseInfo { +struct COMPONENT_EXPORT(NETWORK_CPP_BASE) ResourceResponseHead + : ResourceResponseInfo { // TimeTicks::Now() when the browser received the request from the renderer. base::TimeTicks request_start; // TimeTicks::Now() when the browser sent the response to the renderer. @@ -28,7 +30,8 @@ // Simple wrapper that refcounts ResourceResponseHead. // Inherited, rather than typedef'd, to allow forward declarations. -struct ResourceResponse : public base::RefCountedThreadSafe<ResourceResponse> { +struct COMPONENT_EXPORT(NETWORK_CPP_BASE) ResourceResponse + : public base::RefCountedThreadSafe<ResourceResponse> { public: ResourceResponseHead head;
diff --git a/services/network/public/cpp/resource_response_info.h b/services/network/public/cpp/resource_response_info.h index 64cdc9f..c1de45af 100644 --- a/services/network/public/cpp/resource_response_info.h +++ b/services/network/public/cpp/resource_response_info.h
@@ -9,6 +9,7 @@ #include <string> +#include "base/component_export.h" #include "base/files/file_path.h" #include "base/memory/ref_counted.h" #include "base/time/time.h" @@ -26,7 +27,7 @@ // NOTE: when modifying this structure, also update ResourceResponse::DeepCopy // in resource_response.cc. -struct ResourceResponseInfo { +struct COMPONENT_EXPORT(NETWORK_CPP_BASE) ResourceResponseInfo { ResourceResponseInfo(); ResourceResponseInfo(const ResourceResponseInfo& other); ~ResourceResponseInfo();
diff --git a/services/network/public/cpp/url_loader_completion_status.h b/services/network/public/cpp/url_loader_completion_status.h index 3f4a3037..799ceb83ac 100644 --- a/services/network/public/cpp/url_loader_completion_status.h +++ b/services/network/public/cpp/url_loader_completion_status.h
@@ -7,6 +7,7 @@ #include <stdint.h> +#include "base/component_export.h" #include "base/macros.h" #include "base/optional.h" #include "base/time/time.h" @@ -16,7 +17,7 @@ namespace network { -struct URLLoaderCompletionStatus { +struct COMPONENT_EXPORT(NETWORK_CPP_BASE) URLLoaderCompletionStatus { URLLoaderCompletionStatus(); URLLoaderCompletionStatus(const URLLoaderCompletionStatus& status);
diff --git a/services/network/public/cpp/url_loader_completion_status.typemap b/services/network/public/cpp/url_loader_completion_status.typemap index 65416e4..16ef28bf2 100644 --- a/services/network/public/cpp/url_loader_completion_status.typemap +++ b/services/network/public/cpp/url_loader_completion_status.typemap
@@ -10,7 +10,7 @@ "//net", ] public_deps = [ - "//services/network/public/cpp:typemap_dependencies", + "//services/network/public/cpp:cpp_base", ] type_mappings = [ "network.mojom.URLLoaderCompletionStatus=network::URLLoaderCompletionStatus",
diff --git a/services/network/public/cpp/url_request.typemap b/services/network/public/cpp/url_request.typemap index 92dac7e1..6dad4f1d 100644 --- a/services/network/public/cpp/url_request.typemap +++ b/services/network/public/cpp/url_request.typemap
@@ -9,7 +9,7 @@ "//services/network/public/cpp/url_request_struct_traits.h", ] public_deps = [ - "//services/network/public/cpp:typemap_dependencies", + "//services/network/public/cpp:cpp_base", ] type_mappings = [ "network.mojom.URLRequest=network::ResourceRequest",
diff --git a/services/network/public/cpp/url_request_context_owner.h b/services/network/public/cpp/url_request_context_owner.h index 981f91c..8790f16 100644 --- a/services/network/public/cpp/url_request_context_owner.h +++ b/services/network/public/cpp/url_request_context_owner.h
@@ -2,11 +2,13 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#ifndef SERVICES_NETWORK_PUBLIC_CPP_NETWORK_URL_REQUEST_CONTEXT_OWNER_H_ -#define SERVICES_NETWORK_PUBLIC_CPP_NETWORK_URL_REQUEST_CONTEXT_OWNER_H_ +#ifndef SERVICES_NETWORK_PUBLIC_CPP_URL_REQUEST_CONTEXT_OWNER_H_ +#define SERVICES_NETWORK_PUBLIC_CPP_URL_REQUEST_CONTEXT_OWNER_H_ #include <memory> +#include "base/component_export.h" + class PrefService; namespace net { @@ -16,7 +18,7 @@ namespace network { // This owns a net::URLRequestContext and other state that's used with it. -struct URLRequestContextOwner { +struct COMPONENT_EXPORT(NETWORK_CPP) URLRequestContextOwner { URLRequestContextOwner(); ~URLRequestContextOwner(); URLRequestContextOwner(URLRequestContextOwner&& other); @@ -30,4 +32,4 @@ } // namespace network -#endif // SERVICES_NETWORK_PUBLIC_CPP_NETWORK_URL_REQUEST_CONTEXT_OWNER_H_ +#endif // SERVICES_NETWORK_PUBLIC_CPP_URL_REQUEST_CONTEXT_OWNER_H_
diff --git a/services/network/public/cpp/url_request_struct_traits.h b/services/network/public/cpp/url_request_struct_traits.h index 30f4b7ab5..055091b7e 100644 --- a/services/network/public/cpp/url_request_struct_traits.h +++ b/services/network/public/cpp/url_request_struct_traits.h
@@ -5,6 +5,7 @@ #ifndef SERVICES_NETWORK_PUBLIC_CPP_URL_REQUEST_STRUCT_TRAITS_H_ #define SERVICES_NETWORK_PUBLIC_CPP_URL_REQUEST_STRUCT_TRAITS_H_ +#include "base/component_export.h" #include "mojo/public/cpp/bindings/enum_traits.h" #include "net/base/request_priority.h" #include "services/network/public/interfaces/url_loader.mojom-shared.h" @@ -12,7 +13,8 @@ namespace mojo { template <> -struct EnumTraits<network::mojom::RequestPriority, net::RequestPriority> { +struct COMPONENT_EXPORT(NETWORK_CPP_BASE) + EnumTraits<network::mojom::RequestPriority, net::RequestPriority> { static network::mojom::RequestPriority ToMojom(net::RequestPriority priority); static bool FromMojom(network::mojom::RequestPriority in, net::RequestPriority* out);
diff --git a/services/network/public/cpp/url_response_head.typemap b/services/network/public/cpp/url_response_head.typemap index 66e8663..b8d092b 100644 --- a/services/network/public/cpp/url_response_head.typemap +++ b/services/network/public/cpp/url_response_head.typemap
@@ -6,7 +6,7 @@ public_headers = [ "//services/network/public/cpp/resource_response.h" ] traits_headers = [ "//services/network/public/cpp/network_param_ipc_traits.h" ] public_deps = [ - "//services/network/public/cpp:typemap_dependencies", + "//services/network/public/cpp:cpp_base", ] type_mappings = [ "network.mojom.URLResponseHead=network::ResourceResponseHead" ]
diff --git a/services/network/test/OWNERS b/services/network/test/OWNERS new file mode 100644 index 0000000..5415e12 --- /dev/null +++ b/services/network/test/OWNERS
@@ -0,0 +1,2 @@ +per-file service_unittest_manifest.json=set noparent +per-file service_unittest_manifest.json=file://ipc/SECURITY_OWNERS
diff --git a/services/network/test/service_unittest_manifest.json b/services/network/test/service_unittest_manifest.json new file mode 100644 index 0000000..5ce5e98c --- /dev/null +++ b/services/network/test/service_unittest_manifest.json
@@ -0,0 +1,16 @@ +{ + "name": "network_unittests", + "display_name": "Network Unittests", + "interface_provider_specs": { + "service_manager:connector": { + "provides": { + "service_manager:service_factory": [ + "service_manager::mojom::ServiceFactory" + ] + }, + "requires": { + "network": [ "network_service" ] + } + } + } +}
diff --git a/content/network/url_loader_unittest.cc b/services/network/url_loader_unittest.cc similarity index 90% rename from content/network/url_loader_unittest.cc rename to services/network/url_loader_unittest.cc index 6cbd1ea..b8ffd9e1 100644 --- a/content/network/url_loader_unittest.cc +++ b/services/network/url_loader_unittest.cc
@@ -20,8 +20,6 @@ #include "base/threading/thread_task_runner_handle.h" #include "base/time/time.h" #include "build/build_config.h" -#include "content/public/common/content_paths.h" -#include "content/public/test/controllable_http_response.h" #include "mojo/common/data_pipe_utils.h" #include "mojo/public/c/system/data_pipe.h" #include "mojo/public/cpp/system/wait.h" @@ -30,6 +28,7 @@ #include "net/base/mime_sniffer.h" #include "net/base/net_errors.h" #include "net/test/cert_test_util.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_response.h" #include "net/test/test_data_directory.h" @@ -47,26 +46,21 @@ #include "services/network/test/test_url_loader_client.h" #include "services/network/url_loader.h" #include "testing/gtest/include/gtest/gtest.h" -#include "ui/base/page_transition_types.h" #include "url/gurl.h" -using network::NetworkContext; -using network::URLLoader; - -namespace content { +namespace network { namespace { -static network::ResourceRequest CreateResourceRequest(const char* method, - const GURL& url) { - network::ResourceRequest request; +static ResourceRequest CreateResourceRequest(const char* method, + const GURL& url) { + ResourceRequest request; request.method = std::string(method); request.url = url; request.site_for_cookies = url; // bypass third-party cookie blocking request.request_initiator = url::Origin::Create(url); // ensure initiator is set request.is_main_frame = true; - request.transition_type = ui::PAGE_TRANSITION_LINK; request.allow_download = true; return request; } @@ -185,7 +179,7 @@ URLLoaderTest() : scoped_task_environment_( base::test::ScopedTaskEnvironment::MainThreadType::IO), - context_(network::NetworkContext::CreateForTesting()) { + context_(NetworkContext::CreateForTesting()) { net::URLRequestFailedJob::AddUrlHandler(); } ~URLLoaderTest() override { @@ -194,7 +188,7 @@ void SetUp() override { test_server_.AddDefaultHandlers( - base::FilePath(FILE_PATH_LITERAL("content/test/data"))); + base::FilePath(FILE_PATH_LITERAL("services/test/data"))); // This Unretained is safe because test_server_ is owned by |this|. test_server_.RegisterRequestMonitor( base::Bind(&URLLoaderTest::Monitor, base::Unretained(this))); @@ -208,17 +202,17 @@ // block on trying to write the body buffer. int Load(const GURL& url, std::string* body = nullptr) WARN_UNUSED_RESULT { DCHECK(!ran_); - network::mojom::URLLoaderPtr loader; + mojom::URLLoaderPtr loader; - network::ResourceRequest request = + ResourceRequest request = CreateResourceRequest(!request_body_ ? "GET" : "POST", url); - uint32_t options = network::mojom::kURLLoadOptionNone; + uint32_t options = mojom::kURLLoadOptionNone; if (send_ssl_with_response_) - options |= network::mojom::kURLLoadOptionSendSSLInfoWithResponse; + options |= mojom::kURLLoadOptionSendSSLInfoWithResponse; if (sniff_) - options |= network::mojom::kURLLoadOptionSniffMimeType; + options |= mojom::kURLLoadOptionSniffMimeType; if (send_ssl_for_cert_error_) - options |= network::mojom::kURLLoadOptionSendSSLInfoForCertificateError; + options |= mojom::kURLLoadOptionSendSSLInfoForCertificateError; if (request_body_) request.request_body = request_body_; @@ -322,13 +316,16 @@ net::EmbeddedTestServer* test_server() { return &test_server_; } NetworkContext* context() { return context_.get(); } - network::TestURLLoaderClient* client() { return &client_; } + TestURLLoaderClient* client() { return &client_; } void DestroyContext() { context_.reset(); } // Returns the path of the requested file in the test data directory. base::FilePath GetTestFilePath(const std::string& file_name) { base::FilePath file_path; - PathService::Get(DIR_TEST_DATA, &file_path); + PathService::Get(base::DIR_SOURCE_ROOT, &file_path); + file_path = file_path.Append(FILE_PATH_LITERAL("services")); + file_path = file_path.Append(FILE_PATH_LITERAL("test")); + file_path = file_path.Append(FILE_PATH_LITERAL("data")); return file_path.AppendASCII(file_name); } @@ -359,8 +356,7 @@ DCHECK(!ran_); expect_redirect_ = true; } - void set_request_body( - scoped_refptr<network::ResourceRequestBody> request_body) { + void set_request_body(scoped_refptr<ResourceRequestBody> request_body) { request_body_ = request_body; } @@ -454,13 +450,13 @@ bool send_ssl_with_response_ = false; bool send_ssl_for_cert_error_ = false; bool expect_redirect_ = false; - scoped_refptr<network::ResourceRequestBody> request_body_; + scoped_refptr<ResourceRequestBody> request_body_; // Used to ensure that methods are called either before or after a request is // made, since the test fixture is meant to be used only once. bool ran_ = false; net::test_server::HttpRequest sent_request_; - network::TestURLLoaderClient client_; + TestURLLoaderClient client_; }; TEST_F(URLLoaderTest, Basic) { @@ -474,7 +470,7 @@ TEST_F(URLLoaderTest, BasicSSL) { net::EmbeddedTestServer https_server(net::EmbeddedTestServer::TYPE_HTTPS); https_server.ServeFilesFromSourceDirectory( - base::FilePath(FILE_PATH_LITERAL("content/test/data"))); + base::FilePath(FILE_PATH_LITERAL("services/test/data"))); ASSERT_TRUE(https_server.Start()); GURL url = https_server.GetURL("/simple_page.html"); @@ -489,7 +485,7 @@ TEST_F(URLLoaderTest, SSLSentOnlyWhenRequested) { net::EmbeddedTestServer https_server(net::EmbeddedTestServer::TYPE_HTTPS); https_server.ServeFilesFromSourceDirectory( - base::FilePath(FILE_PATH_LITERAL("content/test/data"))); + base::FilePath(FILE_PATH_LITERAL("services/test/data"))); ASSERT_TRUE(https_server.Start()); GURL url = https_server.GetURL("/simple_page.html"); @@ -563,9 +559,9 @@ TEST_F(URLLoaderTest, DestroyContextWithLiveRequest) { GURL url = test_server()->GetURL("/hung-after-headers"); - network::ResourceRequest request = CreateResourceRequest("GET", url); + ResourceRequest request = CreateResourceRequest("GET", url); - network::mojom::URLLoaderPtr loader; + mojom::URLLoaderPtr loader; // The loader is implicitly owned by the client and the NetworkContext, so // don't hold on to a pointer to it. base::WeakPtr<URLLoader> loader_impl = @@ -721,10 +717,10 @@ })); ASSERT_TRUE(server.Start()); - network::ResourceRequest request = + ResourceRequest request = CreateResourceRequest("GET", server.GetURL("/hello.html")); - network::mojom::URLLoaderPtr loader; + mojom::URLLoaderPtr loader; // The loader is implicitly owned by the client and the NetworkContext. new URLLoader(context(), mojo::MakeRequest(&loader), 0, request, false, client()->CreateInterfacePtr(), TRAFFIC_ANNOTATION_FOR_TESTS, @@ -759,13 +755,13 @@ const char* const kBodyContents = "This is the data as you requested."; net::EmbeddedTestServer server; - ControllableHttpResponse response_controller(&server, kPath); + net::test_server::ControllableHttpResponse response_controller(&server, + kPath); ASSERT_TRUE(server.Start()); - network::ResourceRequest request = - CreateResourceRequest("GET", server.GetURL(kPath)); + ResourceRequest request = CreateResourceRequest("GET", server.GetURL(kPath)); - network::mojom::URLLoaderPtr loader; + mojom::URLLoaderPtr loader; // The loader is implicitly owned by the client and the NetworkContext. new URLLoader(context(), mojo::MakeRequest(&loader), 0, request, false, client()->CreateInterfacePtr(), TRAFFIC_ANNOTATION_FOR_TESTS, @@ -816,13 +812,13 @@ const char* const kBodyContentsSecondHalf = "This is the second half."; net::EmbeddedTestServer server; - ControllableHttpResponse response_controller(&server, kPath); + net::test_server::ControllableHttpResponse response_controller(&server, + kPath); ASSERT_TRUE(server.Start()); - network::ResourceRequest request = - CreateResourceRequest("GET", server.GetURL(kPath)); + ResourceRequest request = CreateResourceRequest("GET", server.GetURL(kPath)); - network::mojom::URLLoaderPtr loader; + mojom::URLLoaderPtr loader; // The loader is implicitly owned by the client and the NetworkContext. new URLLoader(context(), mojo::MakeRequest(&loader), 0, request, false, client()->CreateInterfacePtr(), TRAFFIC_ANNOTATION_FOR_TESTS, @@ -862,13 +858,13 @@ const char* const kBodyContentsFirstHalf = "This is the first half."; net::EmbeddedTestServer server; - ControllableHttpResponse response_controller(&server, kPath); + net::test_server::ControllableHttpResponse response_controller(&server, + kPath); ASSERT_TRUE(server.Start()); - network::ResourceRequest request = - CreateResourceRequest("GET", server.GetURL(kPath)); + ResourceRequest request = CreateResourceRequest("GET", server.GetURL(kPath)); - network::mojom::URLLoaderPtr loader; + mojom::URLLoaderPtr loader; // The loader is implicitly owned by the client and the NetworkContext. new URLLoader(context(), mojo::MakeRequest(&loader), 0, request, false, client()->CreateInterfacePtr(), TRAFFIC_ANNOTATION_FOR_TESTS, @@ -902,13 +898,13 @@ const char* const kBodyContentsSecondHalf = "This is the second half."; net::EmbeddedTestServer server; - ControllableHttpResponse response_controller(&server, kPath); + net::test_server::ControllableHttpResponse response_controller(&server, + kPath); ASSERT_TRUE(server.Start()); - network::ResourceRequest request = - CreateResourceRequest("GET", server.GetURL(kPath)); + ResourceRequest request = CreateResourceRequest("GET", server.GetURL(kPath)); - network::mojom::URLLoaderPtr loader; + mojom::URLLoaderPtr loader; // The loader is implicitly owned by the client and the NetworkContext. new URLLoader(context(), mojo::MakeRequest(&loader), 0, request, false, client()->CreateInterfacePtr(), TRAFFIC_ANNOTATION_FOR_TESTS, @@ -952,8 +948,7 @@ TEST_F(URLLoaderTest, UploadBytes) { const std::string kRequestBody = "Request Body"; - scoped_refptr<network::ResourceRequestBody> request_body( - new network::ResourceRequestBody()); + scoped_refptr<ResourceRequestBody> request_body(new ResourceRequestBody()); request_body->AppendBytes(kRequestBody.c_str(), kRequestBody.length()); set_request_body(std::move(request_body)); @@ -969,8 +964,7 @@ ASSERT_TRUE(base::ReadFileToString(file_path, &expected_body)) << "File not found: " << file_path.value(); - scoped_refptr<network::ResourceRequestBody> request_body( - new network::ResourceRequestBody()); + scoped_refptr<ResourceRequestBody> request_body(new ResourceRequestBody()); request_body->AppendFileRange( file_path, 0, std::numeric_limits<uint64_t>::max(), base::Time()); set_request_body(std::move(request_body)); @@ -988,8 +982,7 @@ << "File not found: " << file_path.value(); expected_body = expected_body.substr(1, expected_body.size() - 2); - scoped_refptr<network::ResourceRequestBody> request_body( - new network::ResourceRequestBody()); + scoped_refptr<ResourceRequestBody> request_body(new ResourceRequestBody()); request_body->AppendFileRange(file_path, 1, expected_body.size(), base::Time()); set_request_body(std::move(request_body)); @@ -1006,8 +999,7 @@ ASSERT_TRUE(base::ReadFileToString(file_path, &expected_body)) << "File not found: " << file_path.value(); - scoped_refptr<network::ResourceRequestBody> request_body( - new network::ResourceRequestBody()); + scoped_refptr<ResourceRequestBody> request_body(new ResourceRequestBody()); request_body->AppendRawFileRange( OpenFileForUpload(file_path), GetTestFilePath("should_be_ignored"), 0, std::numeric_limits<uint64_t>::max(), base::Time()); @@ -1026,8 +1018,7 @@ << "File not found: " << file_path.value(); expected_body = expected_body.substr(1, expected_body.size() - 2); - scoped_refptr<network::ResourceRequestBody> request_body( - new network::ResourceRequestBody()); + scoped_refptr<ResourceRequestBody> request_body(new ResourceRequestBody()); request_body->AppendRawFileRange(OpenFileForUpload(file_path), GetTestFilePath("should_be_ignored"), 1, expected_body.size(), base::Time()); @@ -1042,12 +1033,11 @@ TEST_F(URLLoaderTest, UploadDataPipe) { const std::string kRequestBody = "Request Body"; - network::mojom::DataPipeGetterPtr data_pipe_getter_ptr; - auto data_pipe_getter = std::make_unique<network::TestDataPipeGetter>( + mojom::DataPipeGetterPtr data_pipe_getter_ptr; + auto data_pipe_getter = std::make_unique<TestDataPipeGetter>( kRequestBody, mojo::MakeRequest(&data_pipe_getter_ptr)); - auto resource_request_body = - base::MakeRefCounted<network::ResourceRequestBody>(); + auto resource_request_body = base::MakeRefCounted<ResourceRequestBody>(); resource_request_body->AppendDataPipe(std::move(data_pipe_getter_ptr)); set_request_body(std::move(resource_request_body)); @@ -1060,12 +1050,11 @@ TEST_F(URLLoaderTest, UploadDataPipe_Redirect307) { const std::string kRequestBody = "Request Body"; - network::mojom::DataPipeGetterPtr data_pipe_getter_ptr; - auto data_pipe_getter = std::make_unique<network::TestDataPipeGetter>( + mojom::DataPipeGetterPtr data_pipe_getter_ptr; + auto data_pipe_getter = std::make_unique<TestDataPipeGetter>( kRequestBody, mojo::MakeRequest(&data_pipe_getter_ptr)); - auto resource_request_body = - base::MakeRefCounted<network::ResourceRequestBody>(); + auto resource_request_body = base::MakeRefCounted<ResourceRequestBody>(); resource_request_body->AppendDataPipe(std::move(data_pipe_getter_ptr)); set_request_body(std::move(resource_request_body)); set_expect_redirect(); @@ -1086,12 +1075,11 @@ while (request_body.size() < 5 * 1024 * 1024) request_body.append("foppity"); - network::mojom::DataPipeGetterPtr data_pipe_getter_ptr; - auto data_pipe_getter = std::make_unique<network::TestDataPipeGetter>( + mojom::DataPipeGetterPtr data_pipe_getter_ptr; + auto data_pipe_getter = std::make_unique<TestDataPipeGetter>( request_body, mojo::MakeRequest(&data_pipe_getter_ptr)); - auto resource_request_body = - base::MakeRefCounted<network::ResourceRequestBody>(); + auto resource_request_body = base::MakeRefCounted<ResourceRequestBody>(); resource_request_body->AppendDataPipe(std::move(data_pipe_getter_ptr)); set_request_body(std::move(resource_request_body)); @@ -1103,13 +1091,12 @@ TEST_F(URLLoaderTest, UploadDataPipeError) { const std::string kRequestBody = "Request Body"; - network::mojom::DataPipeGetterPtr data_pipe_getter_ptr; - auto data_pipe_getter = std::make_unique<network::TestDataPipeGetter>( + mojom::DataPipeGetterPtr data_pipe_getter_ptr; + auto data_pipe_getter = std::make_unique<TestDataPipeGetter>( kRequestBody, mojo::MakeRequest(&data_pipe_getter_ptr)); data_pipe_getter->set_start_error(net::ERR_ACCESS_DENIED); - auto resource_request_body = - base::MakeRefCounted<network::ResourceRequestBody>(); + auto resource_request_body = base::MakeRefCounted<ResourceRequestBody>(); resource_request_body->AppendDataPipe(std::move(data_pipe_getter_ptr)); set_request_body(std::move(resource_request_body)); @@ -1119,13 +1106,12 @@ TEST_F(URLLoaderTest, UploadDataPipeClosedEarly) { const std::string kRequestBody = "Request Body"; - network::mojom::DataPipeGetterPtr data_pipe_getter_ptr; - auto data_pipe_getter = std::make_unique<network::TestDataPipeGetter>( + mojom::DataPipeGetterPtr data_pipe_getter_ptr; + auto data_pipe_getter = std::make_unique<TestDataPipeGetter>( kRequestBody, mojo::MakeRequest(&data_pipe_getter_ptr)); data_pipe_getter->set_pipe_closed_early(true); - auto resource_request_body = - base::MakeRefCounted<network::ResourceRequestBody>(); + auto resource_request_body = base::MakeRefCounted<ResourceRequestBody>(); resource_request_body->AppendDataPipe(std::move(data_pipe_getter_ptr)); set_request_body(std::move(resource_request_body)); @@ -1140,8 +1126,7 @@ ASSERT_TRUE(base::ReadFileToString(file_path, &expected_body)) << "File not found: " << file_path.value(); - scoped_refptr<network::ResourceRequestBody> request_body( - new network::ResourceRequestBody()); + scoped_refptr<ResourceRequestBody> request_body(new ResourceRequestBody()); request_body->AppendRawFileRange( OpenFileForUpload(file_path), GetTestFilePath("should_be_ignored"), 0, std::numeric_limits<uint64_t>::max(), base::Time()); @@ -1246,4 +1231,4 @@ client()->response_head().cert_status); } -} // namespace content +} // namespace network
diff --git a/services/shape_detection/BUILD.gn b/services/shape_detection/BUILD.gn index 36043e5..e102f2b 100644 --- a/services/shape_detection/BUILD.gn +++ b/services/shape_detection/BUILD.gn
@@ -9,7 +9,6 @@ source_set("lib") { sources = [ "barcode_detection_impl.h", - "face_detection_provider_impl.h", "shape_detection_service.cc", "shape_detection_service.h", "text_detection_impl.h", @@ -23,12 +22,13 @@ "detection_utils_mac.mm", "face_detection_impl_mac.h", "face_detection_impl_mac.mm", + "face_detection_provider_mac.h", + "face_detection_provider_mac.mm", "text_detection_impl_mac.h", "text_detection_impl_mac.mm", ] libs = [ "QuartzCore.framework" ] } else if (is_win) { - sources -= [ "face_detection_provider_impl.h" ] sources += [ "barcode_detection_impl.cc", "detection_utils_win.cc", @@ -44,6 +44,7 @@ sources += [ "barcode_detection_impl.cc", "face_detection_provider_impl.cc", + "face_detection_provider_impl.h", "text_detection_impl.cc", ] }
diff --git a/services/shape_detection/face_detection_impl_mac.mm b/services/shape_detection/face_detection_impl_mac.mm index 7228152d..58e5f20 100644 --- a/services/shape_detection/face_detection_impl_mac.mm +++ b/services/shape_detection/face_detection_impl_mac.mm
@@ -5,20 +5,10 @@ #include "services/shape_detection/face_detection_impl_mac.h" #include "base/mac/scoped_cftyperef.h" -#include "mojo/public/cpp/bindings/strong_binding.h" #include "services/shape_detection/detection_utils_mac.h" -#include "services/shape_detection/face_detection_provider_impl.h" namespace shape_detection { -void FaceDetectionProviderImpl::CreateFaceDetection( - shape_detection::mojom::FaceDetectionRequest request, - shape_detection::mojom::FaceDetectorOptionsPtr options) { - mojo::MakeStrongBinding( - std::make_unique<FaceDetectionImplMac>(std::move(options)), - std::move(request)); -} - FaceDetectionImplMac::FaceDetectionImplMac( shape_detection::mojom::FaceDetectorOptionsPtr options) { NSString* const accuracy =
diff --git a/services/shape_detection/face_detection_provider_mac.h b/services/shape_detection/face_detection_provider_mac.h new file mode 100644 index 0000000..1702b52 --- /dev/null +++ b/services/shape_detection/face_detection_provider_mac.h
@@ -0,0 +1,34 @@ +// 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. + +#ifndef SERVICES_SHAPE_DETECTION_FACE_DETECTION_PROVIDER_MAC_H_ +#define SERVICES_SHAPE_DETECTION_FACE_DETECTION_PROVIDER_MAC_H_ + +#include "base/macros.h" +#include "services/shape_detection/public/interfaces/facedetection_provider.mojom.h" + +namespace shape_detection { + +// The FaceDetectionProviderMac class is a provider that binds an implementation +// of mojom::FaceDetection with Core Image or Vision Framework. +class FaceDetectionProviderMac + : public shape_detection::mojom::FaceDetectionProvider { + public: + FaceDetectionProviderMac(); + ~FaceDetectionProviderMac() override; + + // Binds FaceDetection provider request to the implementation of + // mojom::FaceDetectionProvider. + static void Create(mojom::FaceDetectionProviderRequest request); + + void CreateFaceDetection(mojom::FaceDetectionRequest request, + mojom::FaceDetectorOptionsPtr options) override; + + private: + DISALLOW_COPY_AND_ASSIGN(FaceDetectionProviderMac); +}; + +} // namespace shape_detection + +#endif // SERVICES_SHAPE_DETECTION_FACE_DETECTION_PROVIDER_MAC_H_
diff --git a/services/shape_detection/face_detection_provider_mac.mm b/services/shape_detection/face_detection_provider_mac.mm new file mode 100644 index 0000000..8bd2f44c --- /dev/null +++ b/services/shape_detection/face_detection_provider_mac.mm
@@ -0,0 +1,34 @@ +// 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 "services/shape_detection/face_detection_provider_mac.h" + +#include <memory> +#include <utility> + +#include "mojo/public/cpp/bindings/strong_binding.h" +#include "services/shape_detection/face_detection_impl_mac.h" + +namespace shape_detection { + +FaceDetectionProviderMac::FaceDetectionProviderMac() = default; + +FaceDetectionProviderMac::~FaceDetectionProviderMac() = default; + +// static +void FaceDetectionProviderMac::Create( + mojom::FaceDetectionProviderRequest request) { + mojo::MakeStrongBinding(std::make_unique<FaceDetectionProviderMac>(), + std::move(request)); +} + +void FaceDetectionProviderMac::CreateFaceDetection( + mojom::FaceDetectionRequest request, + mojom::FaceDetectorOptionsPtr options) { + mojo::MakeStrongBinding( + std::make_unique<FaceDetectionImplMac>(std::move(options)), + std::move(request)); +} + +} // namespace shape_detection
diff --git a/services/shape_detection/shape_detection_service.cc b/services/shape_detection/shape_detection_service.cc index 492ad06..2b23a3e 100644 --- a/services/shape_detection/shape_detection_service.cc +++ b/services/shape_detection/shape_detection_service.cc
@@ -4,12 +4,18 @@ #include "services/shape_detection/shape_detection_service.h" +#include <string> +#include <utility> + +#include "base/bind.h" #include "base/macros.h" #include "build/build_config.h" #include "services/service_manager/public/cpp/service_context.h" #include "services/shape_detection/barcode_detection_impl.h" #if defined(OS_WIN) #include "services/shape_detection/face_detection_provider_win.h" +#elif defined(OS_MACOSX) +#include "services/shape_detection/face_detection_provider_mac.h" #else #include "services/shape_detection/face_detection_provider_impl.h" #endif @@ -47,6 +53,10 @@ registry_.AddInterface(base::Bind(&BarcodeDetectionImpl::Create)); registry_.AddInterface(base::Bind(&TextDetectionImpl::Create)); registry_.AddInterface(base::Bind(&FaceDetectionProviderWin::Create)); +#elif defined(OS_MACOSX) + registry_.AddInterface(base::Bind(&BarcodeDetectionImpl::Create)); + registry_.AddInterface(base::Bind(&TextDetectionImpl::Create)); + registry_.AddInterface(base::Bind(&FaceDetectionProviderMac::Create)); #else registry_.AddInterface(base::Bind(&BarcodeDetectionImpl::Create)); registry_.AddInterface(base::Bind(&TextDetectionImpl::Create));
diff --git a/services/test/BUILD.gn b/services/test/BUILD.gn index df1f2194..9372d36c 100644 --- a/services/test/BUILD.gn +++ b/services/test/BUILD.gn
@@ -22,6 +22,10 @@ "//ui/base", ] + data = [ + "data/", + ] + data_deps = [ "//ui/resources:ui_test_pak_data", ]
diff --git a/services/test/data/content-sniffer-test0.html b/services/test/data/content-sniffer-test0.html new file mode 100644 index 0000000..597a51b --- /dev/null +++ b/services/test/data/content-sniffer-test0.html
@@ -0,0 +1,4 @@ +<html> +<head><title>Content Sniffer Test 0</title></head> +<body>We should sniff this content as HTML.</body> +</html>
diff --git a/content/test/data/content-sniffer-test4.html.mock-http-headers b/services/test/data/content-sniffer-test0.html.mock-http-headers similarity index 100% copy from content/test/data/content-sniffer-test4.html.mock-http-headers copy to services/test/data/content-sniffer-test0.html.mock-http-headers
diff --git a/services/test/data/content-sniffer-test1.html b/services/test/data/content-sniffer-test1.html new file mode 100644 index 0000000..c3bfc9b4 --- /dev/null +++ b/services/test/data/content-sniffer-test1.html
@@ -0,0 +1,4 @@ +<html> +<head><title>Content Sniffer Test 1</title></head> +<body>We should not sniff this content as HTML.</body> +</html>
diff --git a/services/test/data/content-sniffer-test1.html.mock-http-headers b/services/test/data/content-sniffer-test1.html.mock-http-headers new file mode 100644 index 0000000..05079a91 --- /dev/null +++ b/services/test/data/content-sniffer-test1.html.mock-http-headers
@@ -0,0 +1,2 @@ +HTTP/1.1 200 OK +Content-Type: text/plain; charset=utf-8
diff --git a/services/test/data/content-sniffer-test2.html b/services/test/data/content-sniffer-test2.html new file mode 100644 index 0000000..c4b99f8 --- /dev/null +++ b/services/test/data/content-sniffer-test2.html
@@ -0,0 +1,4 @@ +<html> +<head><title>Content Sniffer Test 2</title></head> +<body>We should not sniff this as HTML as server says its a GIF.</body> +</html>
diff --git a/services/test/data/content-sniffer-test2.html.mock-http-headers b/services/test/data/content-sniffer-test2.html.mock-http-headers new file mode 100644 index 0000000..7b2176c --- /dev/null +++ b/services/test/data/content-sniffer-test2.html.mock-http-headers
@@ -0,0 +1,2 @@ +HTTP/1.1 200 OK +Content-Type: image/gif
diff --git a/content/test/data/content-sniffer-test4.html b/services/test/data/content-sniffer-test4.html similarity index 100% rename from content/test/data/content-sniffer-test4.html rename to services/test/data/content-sniffer-test4.html
diff --git a/content/test/data/content-sniffer-test4.html.mock-http-headers b/services/test/data/content-sniffer-test4.html.mock-http-headers similarity index 100% rename from content/test/data/content-sniffer-test4.html.mock-http-headers rename to services/test/data/content-sniffer-test4.html.mock-http-headers
diff --git a/content/test/data/content-sniffer-test4.html b/services/test/data/empty.html similarity index 100% copy from content/test/data/content-sniffer-test4.html copy to services/test/data/empty.html
diff --git a/services/test/data/hello.html b/services/test/data/hello.html new file mode 100644 index 0000000..be3b725 --- /dev/null +++ b/services/test/data/hello.html
@@ -0,0 +1,2 @@ +<!doctype html> +<p>hello</p>
diff --git a/services/test/data/hello.html.mock-http-headers b/services/test/data/hello.html.mock-http-headers new file mode 100644 index 0000000..5ad3ef0 --- /dev/null +++ b/services/test/data/hello.html.mock-http-headers
@@ -0,0 +1,2 @@ +HTTP/1.1 200 OK +content-type: text/html \ No newline at end of file
diff --git a/content/test/data/nocache.html b/services/test/data/nocache.html similarity index 100% rename from content/test/data/nocache.html rename to services/test/data/nocache.html
diff --git a/content/test/data/nocache.html.mock-http-headers b/services/test/data/nocache.html.mock-http-headers similarity index 100% rename from content/test/data/nocache.html.mock-http-headers rename to services/test/data/nocache.html.mock-http-headers
diff --git a/services/test/data/nosniff-test.html b/services/test/data/nosniff-test.html new file mode 100644 index 0000000..a7ab8ba --- /dev/null +++ b/services/test/data/nosniff-test.html
@@ -0,0 +1,4 @@ +<html> +<head><title>nosniff Test</title></head> +<body>We should NOT sniff this content as HTML.</body> +</html>
diff --git a/services/test/data/nosniff-test.html.mock-http-headers b/services/test/data/nosniff-test.html.mock-http-headers new file mode 100644 index 0000000..78ff33d --- /dev/null +++ b/services/test/data/nosniff-test.html.mock-http-headers
@@ -0,0 +1,3 @@ +HTTP/1.1 200 OK +Content-Length: 111 +X-Content-Type-Options: nosniff
diff --git a/services/test/data/redirect307-to-echo b/services/test/data/redirect307-to-echo new file mode 100644 index 0000000..7898192 --- /dev/null +++ b/services/test/data/redirect307-to-echo
@@ -0,0 +1 @@ +a
diff --git a/services/test/data/redirect307-to-echo.mock-http-headers b/services/test/data/redirect307-to-echo.mock-http-headers new file mode 100644 index 0000000..3d9f6a9 --- /dev/null +++ b/services/test/data/redirect307-to-echo.mock-http-headers
@@ -0,0 +1,2 @@ +HTTP/1.1 307 Yo +Location: /echo
diff --git a/services/test/data/simple_page.html b/services/test/data/simple_page.html new file mode 100644 index 0000000..6170792 --- /dev/null +++ b/services/test/data/simple_page.html
@@ -0,0 +1,6 @@ +<html> +<head><title>OK</title></head> +<body> +Basic html test. +</body> +</html>
diff --git a/sql/vfs_wrapper.cc b/sql/vfs_wrapper.cc index 954d488..e0e33b75 100644 --- a/sql/vfs_wrapper.cc +++ b/sql/vfs_wrapper.cc
@@ -498,7 +498,9 @@ wrapper_vfs->xDlClose = &DlClose; wrapper_vfs->xRandomness = &Randomness; wrapper_vfs->xSleep = &Sleep; - wrapper_vfs->xCurrentTime = &CurrentTime; + // |xCurrentTime| is null when SQLite is built with SQLITE_OMIT_DEPRECATED. + wrapper_vfs->xCurrentTime = + (wrapped_vfs->xCurrentTime ? &CurrentTime : nullptr); wrapper_vfs->xGetLastError = &GetLastError; // The methods above are in version 1 of sqlite_vfs. // There were VFS implementations with nullptr for |xCurrentTimeInt64|.
diff --git a/storage/browser/BUILD.gn b/storage/browser/BUILD.gn index 1e0f856..8e2a5e8 100644 --- a/storage/browser/BUILD.gn +++ b/storage/browser/BUILD.gn
@@ -213,6 +213,7 @@ "//mojo/public/cpp/bindings", "//net", "//services/network/public/cpp", + "//services/network/public/interfaces", "//sql", "//third_party/leveldatabase", "//third_party/sqlite",
diff --git a/testing/buildbot/chromium.clang.json b/testing/buildbot/chromium.clang.json index f614600f..1653981 100644 --- a/testing/buildbot/chromium.clang.json +++ b/testing/buildbot/chromium.clang.json
@@ -7553,6 +7553,16 @@ ], "isolated_scripts": [ { + "args": [ + "--filter=__main__.ChromeDriverTest.testLoadUrl" + ], + "isolate_name": "chromedriver_py_tests", + "name": "chromedriver_py_tests", + "swarming": { + "can_use_on_swarming_builders": true + } + }, + { "isolate_name": "telemetry_gpu_unittests", "name": "telemetry_gpu_unittests", "swarming": {
diff --git a/testing/buildbot/chromium.fyi.json b/testing/buildbot/chromium.fyi.json index c58f767..af3ee83 100644 --- a/testing/buildbot/chromium.fyi.json +++ b/testing/buildbot/chromium.fyi.json
@@ -1801,6 +1801,16 @@ ], "isolated_scripts": [ { + "args": [ + "--filter=__main__.ChromeDriverTest.testLoadUrl" + ], + "isolate_name": "chromedriver_py_tests", + "name": "chromedriver_py_tests", + "swarming": { + "can_use_on_swarming_builders": false + } + }, + { "isolate_name": "telemetry_gpu_unittests", "name": "telemetry_gpu_unittests", "swarming": { @@ -2543,6 +2553,16 @@ ], "isolated_scripts": [ { + "args": [ + "--filter=__main__.ChromeDriverTest.testLoadUrl" + ], + "isolate_name": "chromedriver_py_tests", + "name": "chromedriver_py_tests", + "swarming": { + "can_use_on_swarming_builders": true + } + }, + { "isolate_name": "telemetry_gpu_unittests", "name": "telemetry_gpu_unittests", "swarming": { @@ -4684,7 +4704,7 @@ "device_type": "bullhead" } ], - "hard_timeout": 960, + "hard_timeout": 1800, "output_links": [ { "link": [ @@ -6286,6 +6306,16 @@ ], "isolated_scripts": [ { + "args": [ + "--filter=__main__.ChromeDriverTest.testLoadUrl" + ], + "isolate_name": "chromedriver_py_tests", + "name": "chromedriver_py_tests", + "swarming": { + "can_use_on_swarming_builders": true + } + }, + { "isolate_name": "telemetry_gpu_unittests", "name": "telemetry_gpu_unittests", "swarming": {
diff --git a/testing/buildbot/chromium.gpu.fyi.json b/testing/buildbot/chromium.gpu.fyi.json index 9424d3b..9fe1c64 100644 --- a/testing/buildbot/chromium.gpu.fyi.json +++ b/testing/buildbot/chromium.gpu.fyi.json
@@ -10686,7 +10686,9 @@ "trigger_script": { "args": [ "--gpu-trigger-configs", - "[{\"gpu\": \"10de:1cb3-23.21.13.8792\", \"os\": \"Windows-2008ServerR2-SP1\", \"pool\": \"Chrome-GPU\"}, {\"gpu\": \"10de:1cb3-23.21.13.8816\", \"os\": \"Windows-10\", \"pool\": \"Chrome-GPU\"}]" + "[{\"gpu\": \"10de:1cb3-23.21.13.8792\", \"os\": \"Windows-2008ServerR2-SP1\", \"pool\": \"Chrome-GPU\"}, {\"gpu\": \"10de:1cb3-23.21.13.8816\", \"os\": \"Windows-10\", \"pool\": \"Chrome-GPU\"}]", + "--gpu-trigger-script-verbose", + "True" ], "script": "//content/test/gpu/trigger_gpu_test.py" }, @@ -10710,7 +10712,9 @@ "trigger_script": { "args": [ "--gpu-trigger-configs", - "[{\"gpu\": \"10de:1cb3-23.21.13.8792\", \"os\": \"Windows-2008ServerR2-SP1\", \"pool\": \"Chrome-GPU\"}, {\"gpu\": \"10de:1cb3-23.21.13.8816\", \"os\": \"Windows-10\", \"pool\": \"Chrome-GPU\"}]" + "[{\"gpu\": \"10de:1cb3-23.21.13.8792\", \"os\": \"Windows-2008ServerR2-SP1\", \"pool\": \"Chrome-GPU\"}, {\"gpu\": \"10de:1cb3-23.21.13.8816\", \"os\": \"Windows-10\", \"pool\": \"Chrome-GPU\"}]", + "--gpu-trigger-script-verbose", + "True" ], "script": "//content/test/gpu/trigger_gpu_test.py" }, @@ -10736,7 +10740,9 @@ "trigger_script": { "args": [ "--gpu-trigger-configs", - "[{\"gpu\": \"10de:1cb3-23.21.13.8792\", \"os\": \"Windows-2008ServerR2-SP1\", \"pool\": \"Chrome-GPU\"}, {\"gpu\": \"10de:1cb3-23.21.13.8816\", \"os\": \"Windows-10\", \"pool\": \"Chrome-GPU\"}]" + "[{\"gpu\": \"10de:1cb3-23.21.13.8792\", \"os\": \"Windows-2008ServerR2-SP1\", \"pool\": \"Chrome-GPU\"}, {\"gpu\": \"10de:1cb3-23.21.13.8816\", \"os\": \"Windows-10\", \"pool\": \"Chrome-GPU\"}]", + "--gpu-trigger-script-verbose", + "True" ], "script": "//content/test/gpu/trigger_gpu_test.py" }, @@ -10763,7 +10769,9 @@ "trigger_script": { "args": [ "--gpu-trigger-configs", - "[{\"gpu\": \"10de:1cb3-23.21.13.8792\", \"os\": \"Windows-2008ServerR2-SP1\", \"pool\": \"Chrome-GPU\"}, {\"gpu\": \"10de:1cb3-23.21.13.8816\", \"os\": \"Windows-10\", \"pool\": \"Chrome-GPU\"}]" + "[{\"gpu\": \"10de:1cb3-23.21.13.8792\", \"os\": \"Windows-2008ServerR2-SP1\", \"pool\": \"Chrome-GPU\"}, {\"gpu\": \"10de:1cb3-23.21.13.8816\", \"os\": \"Windows-10\", \"pool\": \"Chrome-GPU\"}]", + "--gpu-trigger-script-verbose", + "True" ], "script": "//content/test/gpu/trigger_gpu_test.py" }, @@ -10787,7 +10795,9 @@ "trigger_script": { "args": [ "--gpu-trigger-configs", - "[{\"gpu\": \"10de:1cb3-23.21.13.8792\", \"os\": \"Windows-2008ServerR2-SP1\", \"pool\": \"Chrome-GPU\"}, {\"gpu\": \"10de:1cb3-23.21.13.8816\", \"os\": \"Windows-10\", \"pool\": \"Chrome-GPU\"}]" + "[{\"gpu\": \"10de:1cb3-23.21.13.8792\", \"os\": \"Windows-2008ServerR2-SP1\", \"pool\": \"Chrome-GPU\"}, {\"gpu\": \"10de:1cb3-23.21.13.8816\", \"os\": \"Windows-10\", \"pool\": \"Chrome-GPU\"}]", + "--gpu-trigger-script-verbose", + "True" ], "script": "//content/test/gpu/trigger_gpu_test.py" }, @@ -10808,7 +10818,9 @@ "trigger_script": { "args": [ "--gpu-trigger-configs", - "[{\"gpu\": \"10de:1cb3-23.21.13.8792\", \"os\": \"Windows-2008ServerR2-SP1\", \"pool\": \"Chrome-GPU\"}, {\"gpu\": \"10de:1cb3-23.21.13.8816\", \"os\": \"Windows-10\", \"pool\": \"Chrome-GPU\"}]" + "[{\"gpu\": \"10de:1cb3-23.21.13.8792\", \"os\": \"Windows-2008ServerR2-SP1\", \"pool\": \"Chrome-GPU\"}, {\"gpu\": \"10de:1cb3-23.21.13.8816\", \"os\": \"Windows-10\", \"pool\": \"Chrome-GPU\"}]", + "--gpu-trigger-script-verbose", + "True" ], "script": "//content/test/gpu/trigger_gpu_test.py" }, @@ -10829,7 +10841,9 @@ "trigger_script": { "args": [ "--gpu-trigger-configs", - "[{\"gpu\": \"10de:1cb3-23.21.13.8792\", \"os\": \"Windows-2008ServerR2-SP1\", \"pool\": \"Chrome-GPU\"}, {\"gpu\": \"10de:1cb3-23.21.13.8816\", \"os\": \"Windows-10\", \"pool\": \"Chrome-GPU\"}]" + "[{\"gpu\": \"10de:1cb3-23.21.13.8792\", \"os\": \"Windows-2008ServerR2-SP1\", \"pool\": \"Chrome-GPU\"}, {\"gpu\": \"10de:1cb3-23.21.13.8816\", \"os\": \"Windows-10\", \"pool\": \"Chrome-GPU\"}]", + "--gpu-trigger-script-verbose", + "True" ], "script": "//content/test/gpu/trigger_gpu_test.py" }, @@ -10857,7 +10871,9 @@ "trigger_script": { "args": [ "--gpu-trigger-configs", - "[{\"gpu\": \"10de:1cb3-23.21.13.8792\", \"os\": \"Windows-2008ServerR2-SP1\", \"pool\": \"Chrome-GPU\"}, {\"gpu\": \"10de:1cb3-23.21.13.8816\", \"os\": \"Windows-10\", \"pool\": \"Chrome-GPU\"}]" + "[{\"gpu\": \"10de:1cb3-23.21.13.8792\", \"os\": \"Windows-2008ServerR2-SP1\", \"pool\": \"Chrome-GPU\"}, {\"gpu\": \"10de:1cb3-23.21.13.8816\", \"os\": \"Windows-10\", \"pool\": \"Chrome-GPU\"}]", + "--gpu-trigger-script-verbose", + "True" ], "script": "//content/test/gpu/trigger_gpu_test.py" } @@ -10893,7 +10909,9 @@ "trigger_script": { "args": [ "--gpu-trigger-configs", - "[{\"gpu\": \"10de:1cb3-23.21.13.8792\", \"os\": \"Windows-2008ServerR2-SP1\", \"pool\": \"Chrome-GPU\"}, {\"gpu\": \"10de:1cb3-23.21.13.8816\", \"os\": \"Windows-10\", \"pool\": \"Chrome-GPU\"}]" + "[{\"gpu\": \"10de:1cb3-23.21.13.8792\", \"os\": \"Windows-2008ServerR2-SP1\", \"pool\": \"Chrome-GPU\"}, {\"gpu\": \"10de:1cb3-23.21.13.8816\", \"os\": \"Windows-10\", \"pool\": \"Chrome-GPU\"}]", + "--gpu-trigger-script-verbose", + "True" ], "script": "//content/test/gpu/trigger_gpu_test.py" } @@ -10922,7 +10940,9 @@ "trigger_script": { "args": [ "--gpu-trigger-configs", - "[{\"gpu\": \"10de:1cb3-23.21.13.8792\", \"os\": \"Windows-2008ServerR2-SP1\", \"pool\": \"Chrome-GPU\"}, {\"gpu\": \"10de:1cb3-23.21.13.8816\", \"os\": \"Windows-10\", \"pool\": \"Chrome-GPU\"}]" + "[{\"gpu\": \"10de:1cb3-23.21.13.8792\", \"os\": \"Windows-2008ServerR2-SP1\", \"pool\": \"Chrome-GPU\"}, {\"gpu\": \"10de:1cb3-23.21.13.8816\", \"os\": \"Windows-10\", \"pool\": \"Chrome-GPU\"}]", + "--gpu-trigger-script-verbose", + "True" ], "script": "//content/test/gpu/trigger_gpu_test.py" } @@ -10951,7 +10971,9 @@ "trigger_script": { "args": [ "--gpu-trigger-configs", - "[{\"gpu\": \"10de:1cb3-23.21.13.8792\", \"os\": \"Windows-2008ServerR2-SP1\", \"pool\": \"Chrome-GPU\"}, {\"gpu\": \"10de:1cb3-23.21.13.8816\", \"os\": \"Windows-10\", \"pool\": \"Chrome-GPU\"}]" + "[{\"gpu\": \"10de:1cb3-23.21.13.8792\", \"os\": \"Windows-2008ServerR2-SP1\", \"pool\": \"Chrome-GPU\"}, {\"gpu\": \"10de:1cb3-23.21.13.8816\", \"os\": \"Windows-10\", \"pool\": \"Chrome-GPU\"}]", + "--gpu-trigger-script-verbose", + "True" ], "script": "//content/test/gpu/trigger_gpu_test.py" } @@ -10986,7 +11008,9 @@ "trigger_script": { "args": [ "--gpu-trigger-configs", - "[{\"gpu\": \"10de:1cb3-23.21.13.8792\", \"os\": \"Windows-2008ServerR2-SP1\", \"pool\": \"Chrome-GPU\"}, {\"gpu\": \"10de:1cb3-23.21.13.8816\", \"os\": \"Windows-10\", \"pool\": \"Chrome-GPU\"}]" + "[{\"gpu\": \"10de:1cb3-23.21.13.8792\", \"os\": \"Windows-2008ServerR2-SP1\", \"pool\": \"Chrome-GPU\"}, {\"gpu\": \"10de:1cb3-23.21.13.8816\", \"os\": \"Windows-10\", \"pool\": \"Chrome-GPU\"}]", + "--gpu-trigger-script-verbose", + "True" ], "script": "//content/test/gpu/trigger_gpu_test.py" } @@ -11019,7 +11043,9 @@ "trigger_script": { "args": [ "--gpu-trigger-configs", - "[{\"gpu\": \"10de:1cb3-23.21.13.8792\", \"os\": \"Windows-2008ServerR2-SP1\", \"pool\": \"Chrome-GPU\"}, {\"gpu\": \"10de:1cb3-23.21.13.8816\", \"os\": \"Windows-10\", \"pool\": \"Chrome-GPU\"}]" + "[{\"gpu\": \"10de:1cb3-23.21.13.8792\", \"os\": \"Windows-2008ServerR2-SP1\", \"pool\": \"Chrome-GPU\"}, {\"gpu\": \"10de:1cb3-23.21.13.8816\", \"os\": \"Windows-10\", \"pool\": \"Chrome-GPU\"}]", + "--gpu-trigger-script-verbose", + "True" ], "script": "//content/test/gpu/trigger_gpu_test.py" } @@ -11052,7 +11078,9 @@ "trigger_script": { "args": [ "--gpu-trigger-configs", - "[{\"gpu\": \"10de:1cb3-23.21.13.8792\", \"os\": \"Windows-2008ServerR2-SP1\", \"pool\": \"Chrome-GPU\"}, {\"gpu\": \"10de:1cb3-23.21.13.8816\", \"os\": \"Windows-10\", \"pool\": \"Chrome-GPU\"}]" + "[{\"gpu\": \"10de:1cb3-23.21.13.8792\", \"os\": \"Windows-2008ServerR2-SP1\", \"pool\": \"Chrome-GPU\"}, {\"gpu\": \"10de:1cb3-23.21.13.8816\", \"os\": \"Windows-10\", \"pool\": \"Chrome-GPU\"}]", + "--gpu-trigger-script-verbose", + "True" ], "script": "//content/test/gpu/trigger_gpu_test.py" } @@ -11085,7 +11113,9 @@ "trigger_script": { "args": [ "--gpu-trigger-configs", - "[{\"gpu\": \"10de:1cb3-23.21.13.8792\", \"os\": \"Windows-2008ServerR2-SP1\", \"pool\": \"Chrome-GPU\"}, {\"gpu\": \"10de:1cb3-23.21.13.8816\", \"os\": \"Windows-10\", \"pool\": \"Chrome-GPU\"}]" + "[{\"gpu\": \"10de:1cb3-23.21.13.8792\", \"os\": \"Windows-2008ServerR2-SP1\", \"pool\": \"Chrome-GPU\"}, {\"gpu\": \"10de:1cb3-23.21.13.8816\", \"os\": \"Windows-10\", \"pool\": \"Chrome-GPU\"}]", + "--gpu-trigger-script-verbose", + "True" ], "script": "//content/test/gpu/trigger_gpu_test.py" } @@ -11118,7 +11148,9 @@ "trigger_script": { "args": [ "--gpu-trigger-configs", - "[{\"gpu\": \"10de:1cb3-23.21.13.8792\", \"os\": \"Windows-2008ServerR2-SP1\", \"pool\": \"Chrome-GPU\"}, {\"gpu\": \"10de:1cb3-23.21.13.8816\", \"os\": \"Windows-10\", \"pool\": \"Chrome-GPU\"}]" + "[{\"gpu\": \"10de:1cb3-23.21.13.8792\", \"os\": \"Windows-2008ServerR2-SP1\", \"pool\": \"Chrome-GPU\"}, {\"gpu\": \"10de:1cb3-23.21.13.8816\", \"os\": \"Windows-10\", \"pool\": \"Chrome-GPU\"}]", + "--gpu-trigger-script-verbose", + "True" ], "script": "//content/test/gpu/trigger_gpu_test.py" } @@ -15228,7 +15260,9 @@ "trigger_script": { "args": [ "--gpu-trigger-configs", - "[{\"gpu\": \"10de:1cb3-23.21.13.8792\", \"os\": \"Windows-2008ServerR2-SP1\", \"pool\": \"Chrome-GPU\"}, {\"gpu\": \"10de:1cb3-23.21.13.8816\", \"os\": \"Windows-10\", \"pool\": \"Chrome-GPU\"}]" + "[{\"gpu\": \"10de:1cb3-23.21.13.8792\", \"os\": \"Windows-2008ServerR2-SP1\", \"pool\": \"Chrome-GPU\"}, {\"gpu\": \"10de:1cb3-23.21.13.8816\", \"os\": \"Windows-10\", \"pool\": \"Chrome-GPU\"}]", + "--gpu-trigger-script-verbose", + "True" ], "script": "//content/test/gpu/trigger_gpu_test.py" }, @@ -15253,7 +15287,9 @@ "trigger_script": { "args": [ "--gpu-trigger-configs", - "[{\"gpu\": \"10de:1cb3-23.21.13.8792\", \"os\": \"Windows-2008ServerR2-SP1\", \"pool\": \"Chrome-GPU\"}, {\"gpu\": \"10de:1cb3-23.21.13.8816\", \"os\": \"Windows-10\", \"pool\": \"Chrome-GPU\"}]" + "[{\"gpu\": \"10de:1cb3-23.21.13.8792\", \"os\": \"Windows-2008ServerR2-SP1\", \"pool\": \"Chrome-GPU\"}, {\"gpu\": \"10de:1cb3-23.21.13.8816\", \"os\": \"Windows-10\", \"pool\": \"Chrome-GPU\"}]", + "--gpu-trigger-script-verbose", + "True" ], "script": "//content/test/gpu/trigger_gpu_test.py" }, @@ -15277,7 +15313,9 @@ "trigger_script": { "args": [ "--gpu-trigger-configs", - "[{\"gpu\": \"10de:1cb3-23.21.13.8792\", \"os\": \"Windows-2008ServerR2-SP1\", \"pool\": \"Chrome-GPU\"}, {\"gpu\": \"10de:1cb3-23.21.13.8816\", \"os\": \"Windows-10\", \"pool\": \"Chrome-GPU\"}]" + "[{\"gpu\": \"10de:1cb3-23.21.13.8792\", \"os\": \"Windows-2008ServerR2-SP1\", \"pool\": \"Chrome-GPU\"}, {\"gpu\": \"10de:1cb3-23.21.13.8816\", \"os\": \"Windows-10\", \"pool\": \"Chrome-GPU\"}]", + "--gpu-trigger-script-verbose", + "True" ], "script": "//content/test/gpu/trigger_gpu_test.py" }, @@ -15305,7 +15343,9 @@ "trigger_script": { "args": [ "--gpu-trigger-configs", - "[{\"gpu\": \"10de:1cb3-23.21.13.8792\", \"os\": \"Windows-2008ServerR2-SP1\", \"pool\": \"Chrome-GPU\"}, {\"gpu\": \"10de:1cb3-23.21.13.8816\", \"os\": \"Windows-10\", \"pool\": \"Chrome-GPU\"}]" + "[{\"gpu\": \"10de:1cb3-23.21.13.8792\", \"os\": \"Windows-2008ServerR2-SP1\", \"pool\": \"Chrome-GPU\"}, {\"gpu\": \"10de:1cb3-23.21.13.8816\", \"os\": \"Windows-10\", \"pool\": \"Chrome-GPU\"}]", + "--gpu-trigger-script-verbose", + "True" ], "script": "//content/test/gpu/trigger_gpu_test.py" }, @@ -15330,7 +15370,9 @@ "trigger_script": { "args": [ "--gpu-trigger-configs", - "[{\"gpu\": \"10de:1cb3-23.21.13.8792\", \"os\": \"Windows-2008ServerR2-SP1\", \"pool\": \"Chrome-GPU\"}, {\"gpu\": \"10de:1cb3-23.21.13.8816\", \"os\": \"Windows-10\", \"pool\": \"Chrome-GPU\"}]" + "[{\"gpu\": \"10de:1cb3-23.21.13.8792\", \"os\": \"Windows-2008ServerR2-SP1\", \"pool\": \"Chrome-GPU\"}, {\"gpu\": \"10de:1cb3-23.21.13.8816\", \"os\": \"Windows-10\", \"pool\": \"Chrome-GPU\"}]", + "--gpu-trigger-script-verbose", + "True" ], "script": "//content/test/gpu/trigger_gpu_test.py" }, @@ -15356,7 +15398,9 @@ "trigger_script": { "args": [ "--gpu-trigger-configs", - "[{\"gpu\": \"10de:1cb3-23.21.13.8792\", \"os\": \"Windows-2008ServerR2-SP1\", \"pool\": \"Chrome-GPU\"}, {\"gpu\": \"10de:1cb3-23.21.13.8816\", \"os\": \"Windows-10\", \"pool\": \"Chrome-GPU\"}]" + "[{\"gpu\": \"10de:1cb3-23.21.13.8792\", \"os\": \"Windows-2008ServerR2-SP1\", \"pool\": \"Chrome-GPU\"}, {\"gpu\": \"10de:1cb3-23.21.13.8816\", \"os\": \"Windows-10\", \"pool\": \"Chrome-GPU\"}]", + "--gpu-trigger-script-verbose", + "True" ], "script": "//content/test/gpu/trigger_gpu_test.py" }, @@ -15380,7 +15424,9 @@ "trigger_script": { "args": [ "--gpu-trigger-configs", - "[{\"gpu\": \"10de:1cb3-23.21.13.8792\", \"os\": \"Windows-2008ServerR2-SP1\", \"pool\": \"Chrome-GPU\"}, {\"gpu\": \"10de:1cb3-23.21.13.8816\", \"os\": \"Windows-10\", \"pool\": \"Chrome-GPU\"}]" + "[{\"gpu\": \"10de:1cb3-23.21.13.8792\", \"os\": \"Windows-2008ServerR2-SP1\", \"pool\": \"Chrome-GPU\"}, {\"gpu\": \"10de:1cb3-23.21.13.8816\", \"os\": \"Windows-10\", \"pool\": \"Chrome-GPU\"}]", + "--gpu-trigger-script-verbose", + "True" ], "script": "//content/test/gpu/trigger_gpu_test.py" }, @@ -15406,7 +15452,9 @@ "trigger_script": { "args": [ "--gpu-trigger-configs", - "[{\"gpu\": \"10de:1cb3-23.21.13.8792\", \"os\": \"Windows-2008ServerR2-SP1\", \"pool\": \"Chrome-GPU\"}, {\"gpu\": \"10de:1cb3-23.21.13.8816\", \"os\": \"Windows-10\", \"pool\": \"Chrome-GPU\"}]" + "[{\"gpu\": \"10de:1cb3-23.21.13.8792\", \"os\": \"Windows-2008ServerR2-SP1\", \"pool\": \"Chrome-GPU\"}, {\"gpu\": \"10de:1cb3-23.21.13.8816\", \"os\": \"Windows-10\", \"pool\": \"Chrome-GPU\"}]", + "--gpu-trigger-script-verbose", + "True" ], "script": "//content/test/gpu/trigger_gpu_test.py" }, @@ -15433,7 +15481,9 @@ "trigger_script": { "args": [ "--gpu-trigger-configs", - "[{\"gpu\": \"10de:1cb3-23.21.13.8792\", \"os\": \"Windows-2008ServerR2-SP1\", \"pool\": \"Chrome-GPU\"}, {\"gpu\": \"10de:1cb3-23.21.13.8816\", \"os\": \"Windows-10\", \"pool\": \"Chrome-GPU\"}]" + "[{\"gpu\": \"10de:1cb3-23.21.13.8792\", \"os\": \"Windows-2008ServerR2-SP1\", \"pool\": \"Chrome-GPU\"}, {\"gpu\": \"10de:1cb3-23.21.13.8816\", \"os\": \"Windows-10\", \"pool\": \"Chrome-GPU\"}]", + "--gpu-trigger-script-verbose", + "True" ], "script": "//content/test/gpu/trigger_gpu_test.py" }, @@ -15457,7 +15507,9 @@ "trigger_script": { "args": [ "--gpu-trigger-configs", - "[{\"gpu\": \"10de:1cb3-23.21.13.8792\", \"os\": \"Windows-2008ServerR2-SP1\", \"pool\": \"Chrome-GPU\"}, {\"gpu\": \"10de:1cb3-23.21.13.8816\", \"os\": \"Windows-10\", \"pool\": \"Chrome-GPU\"}]" + "[{\"gpu\": \"10de:1cb3-23.21.13.8792\", \"os\": \"Windows-2008ServerR2-SP1\", \"pool\": \"Chrome-GPU\"}, {\"gpu\": \"10de:1cb3-23.21.13.8816\", \"os\": \"Windows-10\", \"pool\": \"Chrome-GPU\"}]", + "--gpu-trigger-script-verbose", + "True" ], "script": "//content/test/gpu/trigger_gpu_test.py" }, @@ -15478,7 +15530,9 @@ "trigger_script": { "args": [ "--gpu-trigger-configs", - "[{\"gpu\": \"10de:1cb3-23.21.13.8792\", \"os\": \"Windows-2008ServerR2-SP1\", \"pool\": \"Chrome-GPU\"}, {\"gpu\": \"10de:1cb3-23.21.13.8816\", \"os\": \"Windows-10\", \"pool\": \"Chrome-GPU\"}]" + "[{\"gpu\": \"10de:1cb3-23.21.13.8792\", \"os\": \"Windows-2008ServerR2-SP1\", \"pool\": \"Chrome-GPU\"}, {\"gpu\": \"10de:1cb3-23.21.13.8816\", \"os\": \"Windows-10\", \"pool\": \"Chrome-GPU\"}]", + "--gpu-trigger-script-verbose", + "True" ], "script": "//content/test/gpu/trigger_gpu_test.py" }, @@ -15499,7 +15553,9 @@ "trigger_script": { "args": [ "--gpu-trigger-configs", - "[{\"gpu\": \"10de:1cb3-23.21.13.8792\", \"os\": \"Windows-2008ServerR2-SP1\", \"pool\": \"Chrome-GPU\"}, {\"gpu\": \"10de:1cb3-23.21.13.8816\", \"os\": \"Windows-10\", \"pool\": \"Chrome-GPU\"}]" + "[{\"gpu\": \"10de:1cb3-23.21.13.8792\", \"os\": \"Windows-2008ServerR2-SP1\", \"pool\": \"Chrome-GPU\"}, {\"gpu\": \"10de:1cb3-23.21.13.8816\", \"os\": \"Windows-10\", \"pool\": \"Chrome-GPU\"}]", + "--gpu-trigger-script-verbose", + "True" ], "script": "//content/test/gpu/trigger_gpu_test.py" }, @@ -15526,7 +15582,9 @@ "trigger_script": { "args": [ "--gpu-trigger-configs", - "[{\"gpu\": \"10de:1cb3-23.21.13.8792\", \"os\": \"Windows-2008ServerR2-SP1\", \"pool\": \"Chrome-GPU\"}, {\"gpu\": \"10de:1cb3-23.21.13.8816\", \"os\": \"Windows-10\", \"pool\": \"Chrome-GPU\"}]" + "[{\"gpu\": \"10de:1cb3-23.21.13.8792\", \"os\": \"Windows-2008ServerR2-SP1\", \"pool\": \"Chrome-GPU\"}, {\"gpu\": \"10de:1cb3-23.21.13.8816\", \"os\": \"Windows-10\", \"pool\": \"Chrome-GPU\"}]", + "--gpu-trigger-script-verbose", + "True" ], "script": "//content/test/gpu/trigger_gpu_test.py" }, @@ -15553,7 +15611,9 @@ "trigger_script": { "args": [ "--gpu-trigger-configs", - "[{\"gpu\": \"10de:1cb3-23.21.13.8792\", \"os\": \"Windows-2008ServerR2-SP1\", \"pool\": \"Chrome-GPU\"}, {\"gpu\": \"10de:1cb3-23.21.13.8816\", \"os\": \"Windows-10\", \"pool\": \"Chrome-GPU\"}]" + "[{\"gpu\": \"10de:1cb3-23.21.13.8792\", \"os\": \"Windows-2008ServerR2-SP1\", \"pool\": \"Chrome-GPU\"}, {\"gpu\": \"10de:1cb3-23.21.13.8816\", \"os\": \"Windows-10\", \"pool\": \"Chrome-GPU\"}]", + "--gpu-trigger-script-verbose", + "True" ], "script": "//content/test/gpu/trigger_gpu_test.py" }, @@ -15580,7 +15640,9 @@ "trigger_script": { "args": [ "--gpu-trigger-configs", - "[{\"gpu\": \"10de:1cb3-23.21.13.8792\", \"os\": \"Windows-2008ServerR2-SP1\", \"pool\": \"Chrome-GPU\"}, {\"gpu\": \"10de:1cb3-23.21.13.8816\", \"os\": \"Windows-10\", \"pool\": \"Chrome-GPU\"}]" + "[{\"gpu\": \"10de:1cb3-23.21.13.8792\", \"os\": \"Windows-2008ServerR2-SP1\", \"pool\": \"Chrome-GPU\"}, {\"gpu\": \"10de:1cb3-23.21.13.8816\", \"os\": \"Windows-10\", \"pool\": \"Chrome-GPU\"}]", + "--gpu-trigger-script-verbose", + "True" ], "script": "//content/test/gpu/trigger_gpu_test.py" }, @@ -15608,7 +15670,9 @@ "trigger_script": { "args": [ "--gpu-trigger-configs", - "[{\"gpu\": \"10de:1cb3-23.21.13.8792\", \"os\": \"Windows-2008ServerR2-SP1\", \"pool\": \"Chrome-GPU\"}, {\"gpu\": \"10de:1cb3-23.21.13.8816\", \"os\": \"Windows-10\", \"pool\": \"Chrome-GPU\"}]" + "[{\"gpu\": \"10de:1cb3-23.21.13.8792\", \"os\": \"Windows-2008ServerR2-SP1\", \"pool\": \"Chrome-GPU\"}, {\"gpu\": \"10de:1cb3-23.21.13.8816\", \"os\": \"Windows-10\", \"pool\": \"Chrome-GPU\"}]", + "--gpu-trigger-script-verbose", + "True" ], "script": "//content/test/gpu/trigger_gpu_test.py" } @@ -15640,7 +15704,9 @@ "trigger_script": { "args": [ "--gpu-trigger-configs", - "[{\"gpu\": \"10de:1cb3-23.21.13.8792\", \"os\": \"Windows-2008ServerR2-SP1\", \"pool\": \"Chrome-GPU\"}, {\"gpu\": \"10de:1cb3-23.21.13.8816\", \"os\": \"Windows-10\", \"pool\": \"Chrome-GPU\"}]" + "[{\"gpu\": \"10de:1cb3-23.21.13.8792\", \"os\": \"Windows-2008ServerR2-SP1\", \"pool\": \"Chrome-GPU\"}, {\"gpu\": \"10de:1cb3-23.21.13.8816\", \"os\": \"Windows-10\", \"pool\": \"Chrome-GPU\"}]", + "--gpu-trigger-script-verbose", + "True" ], "script": "//content/test/gpu/trigger_gpu_test.py" } @@ -15672,7 +15738,9 @@ "trigger_script": { "args": [ "--gpu-trigger-configs", - "[{\"gpu\": \"10de:1cb3-23.21.13.8792\", \"os\": \"Windows-2008ServerR2-SP1\", \"pool\": \"Chrome-GPU\"}, {\"gpu\": \"10de:1cb3-23.21.13.8816\", \"os\": \"Windows-10\", \"pool\": \"Chrome-GPU\"}]" + "[{\"gpu\": \"10de:1cb3-23.21.13.8792\", \"os\": \"Windows-2008ServerR2-SP1\", \"pool\": \"Chrome-GPU\"}, {\"gpu\": \"10de:1cb3-23.21.13.8816\", \"os\": \"Windows-10\", \"pool\": \"Chrome-GPU\"}]", + "--gpu-trigger-script-verbose", + "True" ], "script": "//content/test/gpu/trigger_gpu_test.py" } @@ -15704,7 +15772,9 @@ "trigger_script": { "args": [ "--gpu-trigger-configs", - "[{\"gpu\": \"10de:1cb3-23.21.13.8792\", \"os\": \"Windows-2008ServerR2-SP1\", \"pool\": \"Chrome-GPU\"}, {\"gpu\": \"10de:1cb3-23.21.13.8816\", \"os\": \"Windows-10\", \"pool\": \"Chrome-GPU\"}]" + "[{\"gpu\": \"10de:1cb3-23.21.13.8792\", \"os\": \"Windows-2008ServerR2-SP1\", \"pool\": \"Chrome-GPU\"}, {\"gpu\": \"10de:1cb3-23.21.13.8816\", \"os\": \"Windows-10\", \"pool\": \"Chrome-GPU\"}]", + "--gpu-trigger-script-verbose", + "True" ], "script": "//content/test/gpu/trigger_gpu_test.py" } @@ -15736,7 +15806,9 @@ "trigger_script": { "args": [ "--gpu-trigger-configs", - "[{\"gpu\": \"10de:1cb3-23.21.13.8792\", \"os\": \"Windows-2008ServerR2-SP1\", \"pool\": \"Chrome-GPU\"}, {\"gpu\": \"10de:1cb3-23.21.13.8816\", \"os\": \"Windows-10\", \"pool\": \"Chrome-GPU\"}]" + "[{\"gpu\": \"10de:1cb3-23.21.13.8792\", \"os\": \"Windows-2008ServerR2-SP1\", \"pool\": \"Chrome-GPU\"}, {\"gpu\": \"10de:1cb3-23.21.13.8816\", \"os\": \"Windows-10\", \"pool\": \"Chrome-GPU\"}]", + "--gpu-trigger-script-verbose", + "True" ], "script": "//content/test/gpu/trigger_gpu_test.py" } @@ -15772,7 +15844,9 @@ "trigger_script": { "args": [ "--gpu-trigger-configs", - "[{\"gpu\": \"10de:1cb3-23.21.13.8792\", \"os\": \"Windows-2008ServerR2-SP1\", \"pool\": \"Chrome-GPU\"}, {\"gpu\": \"10de:1cb3-23.21.13.8816\", \"os\": \"Windows-10\", \"pool\": \"Chrome-GPU\"}]" + "[{\"gpu\": \"10de:1cb3-23.21.13.8792\", \"os\": \"Windows-2008ServerR2-SP1\", \"pool\": \"Chrome-GPU\"}, {\"gpu\": \"10de:1cb3-23.21.13.8816\", \"os\": \"Windows-10\", \"pool\": \"Chrome-GPU\"}]", + "--gpu-trigger-script-verbose", + "True" ], "script": "//content/test/gpu/trigger_gpu_test.py" } @@ -15811,7 +15885,9 @@ "trigger_script": { "args": [ "--gpu-trigger-configs", - "[{\"gpu\": \"10de:1cb3-23.21.13.8792\", \"os\": \"Windows-2008ServerR2-SP1\", \"pool\": \"Chrome-GPU\"}, {\"gpu\": \"10de:1cb3-23.21.13.8816\", \"os\": \"Windows-10\", \"pool\": \"Chrome-GPU\"}]" + "[{\"gpu\": \"10de:1cb3-23.21.13.8792\", \"os\": \"Windows-2008ServerR2-SP1\", \"pool\": \"Chrome-GPU\"}, {\"gpu\": \"10de:1cb3-23.21.13.8816\", \"os\": \"Windows-10\", \"pool\": \"Chrome-GPU\"}]", + "--gpu-trigger-script-verbose", + "True" ], "script": "//content/test/gpu/trigger_gpu_test.py" } @@ -15840,7 +15916,9 @@ "trigger_script": { "args": [ "--gpu-trigger-configs", - "[{\"gpu\": \"10de:1cb3-23.21.13.8792\", \"os\": \"Windows-2008ServerR2-SP1\", \"pool\": \"Chrome-GPU\"}, {\"gpu\": \"10de:1cb3-23.21.13.8816\", \"os\": \"Windows-10\", \"pool\": \"Chrome-GPU\"}]" + "[{\"gpu\": \"10de:1cb3-23.21.13.8792\", \"os\": \"Windows-2008ServerR2-SP1\", \"pool\": \"Chrome-GPU\"}, {\"gpu\": \"10de:1cb3-23.21.13.8816\", \"os\": \"Windows-10\", \"pool\": \"Chrome-GPU\"}]", + "--gpu-trigger-script-verbose", + "True" ], "script": "//content/test/gpu/trigger_gpu_test.py" } @@ -15887,7 +15965,9 @@ "trigger_script": { "args": [ "--gpu-trigger-configs", - "[{\"gpu\": \"10de:1cb3-23.21.13.8792\", \"os\": \"Windows-2008ServerR2-SP1\", \"pool\": \"Chrome-GPU\"}, {\"gpu\": \"10de:1cb3-23.21.13.8816\", \"os\": \"Windows-10\", \"pool\": \"Chrome-GPU\"}]" + "[{\"gpu\": \"10de:1cb3-23.21.13.8792\", \"os\": \"Windows-2008ServerR2-SP1\", \"pool\": \"Chrome-GPU\"}, {\"gpu\": \"10de:1cb3-23.21.13.8816\", \"os\": \"Windows-10\", \"pool\": \"Chrome-GPU\"}]", + "--gpu-trigger-script-verbose", + "True" ], "script": "//content/test/gpu/trigger_gpu_test.py" } @@ -15920,7 +16000,9 @@ "trigger_script": { "args": [ "--gpu-trigger-configs", - "[{\"gpu\": \"10de:1cb3-23.21.13.8792\", \"os\": \"Windows-2008ServerR2-SP1\", \"pool\": \"Chrome-GPU\"}, {\"gpu\": \"10de:1cb3-23.21.13.8816\", \"os\": \"Windows-10\", \"pool\": \"Chrome-GPU\"}]" + "[{\"gpu\": \"10de:1cb3-23.21.13.8792\", \"os\": \"Windows-2008ServerR2-SP1\", \"pool\": \"Chrome-GPU\"}, {\"gpu\": \"10de:1cb3-23.21.13.8816\", \"os\": \"Windows-10\", \"pool\": \"Chrome-GPU\"}]", + "--gpu-trigger-script-verbose", + "True" ], "script": "//content/test/gpu/trigger_gpu_test.py" } @@ -15952,7 +16034,9 @@ "trigger_script": { "args": [ "--gpu-trigger-configs", - "[{\"gpu\": \"10de:1cb3-23.21.13.8792\", \"os\": \"Windows-2008ServerR2-SP1\", \"pool\": \"Chrome-GPU\"}, {\"gpu\": \"10de:1cb3-23.21.13.8816\", \"os\": \"Windows-10\", \"pool\": \"Chrome-GPU\"}]" + "[{\"gpu\": \"10de:1cb3-23.21.13.8792\", \"os\": \"Windows-2008ServerR2-SP1\", \"pool\": \"Chrome-GPU\"}, {\"gpu\": \"10de:1cb3-23.21.13.8816\", \"os\": \"Windows-10\", \"pool\": \"Chrome-GPU\"}]", + "--gpu-trigger-script-verbose", + "True" ], "script": "//content/test/gpu/trigger_gpu_test.py" } @@ -15981,7 +16065,9 @@ "trigger_script": { "args": [ "--gpu-trigger-configs", - "[{\"gpu\": \"10de:1cb3-23.21.13.8792\", \"os\": \"Windows-2008ServerR2-SP1\", \"pool\": \"Chrome-GPU\"}, {\"gpu\": \"10de:1cb3-23.21.13.8816\", \"os\": \"Windows-10\", \"pool\": \"Chrome-GPU\"}]" + "[{\"gpu\": \"10de:1cb3-23.21.13.8792\", \"os\": \"Windows-2008ServerR2-SP1\", \"pool\": \"Chrome-GPU\"}, {\"gpu\": \"10de:1cb3-23.21.13.8816\", \"os\": \"Windows-10\", \"pool\": \"Chrome-GPU\"}]", + "--gpu-trigger-script-verbose", + "True" ], "script": "//content/test/gpu/trigger_gpu_test.py" } @@ -16016,7 +16102,9 @@ "trigger_script": { "args": [ "--gpu-trigger-configs", - "[{\"gpu\": \"10de:1cb3-23.21.13.8792\", \"os\": \"Windows-2008ServerR2-SP1\", \"pool\": \"Chrome-GPU\"}, {\"gpu\": \"10de:1cb3-23.21.13.8816\", \"os\": \"Windows-10\", \"pool\": \"Chrome-GPU\"}]" + "[{\"gpu\": \"10de:1cb3-23.21.13.8792\", \"os\": \"Windows-2008ServerR2-SP1\", \"pool\": \"Chrome-GPU\"}, {\"gpu\": \"10de:1cb3-23.21.13.8816\", \"os\": \"Windows-10\", \"pool\": \"Chrome-GPU\"}]", + "--gpu-trigger-script-verbose", + "True" ], "script": "//content/test/gpu/trigger_gpu_test.py" } @@ -16051,7 +16139,9 @@ "trigger_script": { "args": [ "--gpu-trigger-configs", - "[{\"gpu\": \"10de:1cb3-23.21.13.8792\", \"os\": \"Windows-2008ServerR2-SP1\", \"pool\": \"Chrome-GPU\"}, {\"gpu\": \"10de:1cb3-23.21.13.8816\", \"os\": \"Windows-10\", \"pool\": \"Chrome-GPU\"}]" + "[{\"gpu\": \"10de:1cb3-23.21.13.8792\", \"os\": \"Windows-2008ServerR2-SP1\", \"pool\": \"Chrome-GPU\"}, {\"gpu\": \"10de:1cb3-23.21.13.8816\", \"os\": \"Windows-10\", \"pool\": \"Chrome-GPU\"}]", + "--gpu-trigger-script-verbose", + "True" ], "script": "//content/test/gpu/trigger_gpu_test.py" } @@ -16086,7 +16176,9 @@ "trigger_script": { "args": [ "--gpu-trigger-configs", - "[{\"gpu\": \"10de:1cb3-23.21.13.8792\", \"os\": \"Windows-2008ServerR2-SP1\", \"pool\": \"Chrome-GPU\"}, {\"gpu\": \"10de:1cb3-23.21.13.8816\", \"os\": \"Windows-10\", \"pool\": \"Chrome-GPU\"}]" + "[{\"gpu\": \"10de:1cb3-23.21.13.8792\", \"os\": \"Windows-2008ServerR2-SP1\", \"pool\": \"Chrome-GPU\"}, {\"gpu\": \"10de:1cb3-23.21.13.8816\", \"os\": \"Windows-10\", \"pool\": \"Chrome-GPU\"}]", + "--gpu-trigger-script-verbose", + "True" ], "script": "//content/test/gpu/trigger_gpu_test.py" } @@ -16119,7 +16211,9 @@ "trigger_script": { "args": [ "--gpu-trigger-configs", - "[{\"gpu\": \"10de:1cb3-23.21.13.8792\", \"os\": \"Windows-2008ServerR2-SP1\", \"pool\": \"Chrome-GPU\"}, {\"gpu\": \"10de:1cb3-23.21.13.8816\", \"os\": \"Windows-10\", \"pool\": \"Chrome-GPU\"}]" + "[{\"gpu\": \"10de:1cb3-23.21.13.8792\", \"os\": \"Windows-2008ServerR2-SP1\", \"pool\": \"Chrome-GPU\"}, {\"gpu\": \"10de:1cb3-23.21.13.8816\", \"os\": \"Windows-10\", \"pool\": \"Chrome-GPU\"}]", + "--gpu-trigger-script-verbose", + "True" ], "script": "//content/test/gpu/trigger_gpu_test.py" } @@ -16152,7 +16246,9 @@ "trigger_script": { "args": [ "--gpu-trigger-configs", - "[{\"gpu\": \"10de:1cb3-23.21.13.8792\", \"os\": \"Windows-2008ServerR2-SP1\", \"pool\": \"Chrome-GPU\"}, {\"gpu\": \"10de:1cb3-23.21.13.8816\", \"os\": \"Windows-10\", \"pool\": \"Chrome-GPU\"}]" + "[{\"gpu\": \"10de:1cb3-23.21.13.8792\", \"os\": \"Windows-2008ServerR2-SP1\", \"pool\": \"Chrome-GPU\"}, {\"gpu\": \"10de:1cb3-23.21.13.8816\", \"os\": \"Windows-10\", \"pool\": \"Chrome-GPU\"}]", + "--gpu-trigger-script-verbose", + "True" ], "script": "//content/test/gpu/trigger_gpu_test.py" } @@ -16185,7 +16281,9 @@ "trigger_script": { "args": [ "--gpu-trigger-configs", - "[{\"gpu\": \"10de:1cb3-23.21.13.8792\", \"os\": \"Windows-2008ServerR2-SP1\", \"pool\": \"Chrome-GPU\"}, {\"gpu\": \"10de:1cb3-23.21.13.8816\", \"os\": \"Windows-10\", \"pool\": \"Chrome-GPU\"}]" + "[{\"gpu\": \"10de:1cb3-23.21.13.8792\", \"os\": \"Windows-2008ServerR2-SP1\", \"pool\": \"Chrome-GPU\"}, {\"gpu\": \"10de:1cb3-23.21.13.8816\", \"os\": \"Windows-10\", \"pool\": \"Chrome-GPU\"}]", + "--gpu-trigger-script-verbose", + "True" ], "script": "//content/test/gpu/trigger_gpu_test.py" } @@ -16218,7 +16316,9 @@ "trigger_script": { "args": [ "--gpu-trigger-configs", - "[{\"gpu\": \"10de:1cb3-23.21.13.8792\", \"os\": \"Windows-2008ServerR2-SP1\", \"pool\": \"Chrome-GPU\"}, {\"gpu\": \"10de:1cb3-23.21.13.8816\", \"os\": \"Windows-10\", \"pool\": \"Chrome-GPU\"}]" + "[{\"gpu\": \"10de:1cb3-23.21.13.8792\", \"os\": \"Windows-2008ServerR2-SP1\", \"pool\": \"Chrome-GPU\"}, {\"gpu\": \"10de:1cb3-23.21.13.8816\", \"os\": \"Windows-10\", \"pool\": \"Chrome-GPU\"}]", + "--gpu-trigger-script-verbose", + "True" ], "script": "//content/test/gpu/trigger_gpu_test.py" } @@ -16251,7 +16351,9 @@ "trigger_script": { "args": [ "--gpu-trigger-configs", - "[{\"gpu\": \"10de:1cb3-23.21.13.8792\", \"os\": \"Windows-2008ServerR2-SP1\", \"pool\": \"Chrome-GPU\"}, {\"gpu\": \"10de:1cb3-23.21.13.8816\", \"os\": \"Windows-10\", \"pool\": \"Chrome-GPU\"}]" + "[{\"gpu\": \"10de:1cb3-23.21.13.8792\", \"os\": \"Windows-2008ServerR2-SP1\", \"pool\": \"Chrome-GPU\"}, {\"gpu\": \"10de:1cb3-23.21.13.8816\", \"os\": \"Windows-10\", \"pool\": \"Chrome-GPU\"}]", + "--gpu-trigger-script-verbose", + "True" ], "script": "//content/test/gpu/trigger_gpu_test.py" } @@ -16304,7 +16406,9 @@ "trigger_script": { "args": [ "--gpu-trigger-configs", - "[{\"gpu\": \"10de:1cb3-23.21.13.8792\", \"os\": \"Windows-2008ServerR2-SP1\", \"pool\": \"Chrome-GPU\"}, {\"gpu\": \"10de:1cb3-23.21.13.8816\", \"os\": \"Windows-10\", \"pool\": \"Chrome-GPU\"}]" + "[{\"gpu\": \"10de:1cb3-23.21.13.8792\", \"os\": \"Windows-2008ServerR2-SP1\", \"pool\": \"Chrome-GPU\"}, {\"gpu\": \"10de:1cb3-23.21.13.8816\", \"os\": \"Windows-10\", \"pool\": \"Chrome-GPU\"}]", + "--gpu-trigger-script-verbose", + "True" ], "script": "//content/test/gpu/trigger_gpu_test.py" }, @@ -16331,7 +16435,9 @@ "trigger_script": { "args": [ "--gpu-trigger-configs", - "[{\"gpu\": \"10de:1cb3-23.21.13.8792\", \"os\": \"Windows-2008ServerR2-SP1\", \"pool\": \"Chrome-GPU\"}, {\"gpu\": \"10de:1cb3-23.21.13.8816\", \"os\": \"Windows-10\", \"pool\": \"Chrome-GPU\"}]" + "[{\"gpu\": \"10de:1cb3-23.21.13.8792\", \"os\": \"Windows-2008ServerR2-SP1\", \"pool\": \"Chrome-GPU\"}, {\"gpu\": \"10de:1cb3-23.21.13.8816\", \"os\": \"Windows-10\", \"pool\": \"Chrome-GPU\"}]", + "--gpu-trigger-script-verbose", + "True" ], "script": "//content/test/gpu/trigger_gpu_test.py" }, @@ -16358,7 +16464,9 @@ "trigger_script": { "args": [ "--gpu-trigger-configs", - "[{\"gpu\": \"10de:1cb3-23.21.13.8792\", \"os\": \"Windows-2008ServerR2-SP1\", \"pool\": \"Chrome-GPU\"}, {\"gpu\": \"10de:1cb3-23.21.13.8816\", \"os\": \"Windows-10\", \"pool\": \"Chrome-GPU\"}]" + "[{\"gpu\": \"10de:1cb3-23.21.13.8792\", \"os\": \"Windows-2008ServerR2-SP1\", \"pool\": \"Chrome-GPU\"}, {\"gpu\": \"10de:1cb3-23.21.13.8816\", \"os\": \"Windows-10\", \"pool\": \"Chrome-GPU\"}]", + "--gpu-trigger-script-verbose", + "True" ], "script": "//content/test/gpu/trigger_gpu_test.py" }, @@ -16385,7 +16493,9 @@ "trigger_script": { "args": [ "--gpu-trigger-configs", - "[{\"gpu\": \"10de:1cb3-23.21.13.8792\", \"os\": \"Windows-2008ServerR2-SP1\", \"pool\": \"Chrome-GPU\"}, {\"gpu\": \"10de:1cb3-23.21.13.8816\", \"os\": \"Windows-10\", \"pool\": \"Chrome-GPU\"}]" + "[{\"gpu\": \"10de:1cb3-23.21.13.8792\", \"os\": \"Windows-2008ServerR2-SP1\", \"pool\": \"Chrome-GPU\"}, {\"gpu\": \"10de:1cb3-23.21.13.8816\", \"os\": \"Windows-10\", \"pool\": \"Chrome-GPU\"}]", + "--gpu-trigger-script-verbose", + "True" ], "script": "//content/test/gpu/trigger_gpu_test.py" }, @@ -16412,7 +16522,9 @@ "trigger_script": { "args": [ "--gpu-trigger-configs", - "[{\"gpu\": \"10de:1cb3-23.21.13.8792\", \"os\": \"Windows-2008ServerR2-SP1\", \"pool\": \"Chrome-GPU\"}, {\"gpu\": \"10de:1cb3-23.21.13.8816\", \"os\": \"Windows-10\", \"pool\": \"Chrome-GPU\"}]" + "[{\"gpu\": \"10de:1cb3-23.21.13.8792\", \"os\": \"Windows-2008ServerR2-SP1\", \"pool\": \"Chrome-GPU\"}, {\"gpu\": \"10de:1cb3-23.21.13.8816\", \"os\": \"Windows-10\", \"pool\": \"Chrome-GPU\"}]", + "--gpu-trigger-script-verbose", + "True" ], "script": "//content/test/gpu/trigger_gpu_test.py" },
diff --git a/testing/buildbot/chromium.gpu.json b/testing/buildbot/chromium.gpu.json index 08451b7..5dd9969 100644 --- a/testing/buildbot/chromium.gpu.json +++ b/testing/buildbot/chromium.gpu.json
@@ -2810,7 +2810,9 @@ "trigger_script": { "args": [ "--gpu-trigger-configs", - "[{\"gpu\": \"10de:1cb3-23.21.13.8792\", \"os\": \"Windows-2008ServerR2-SP1\", \"pool\": \"Chrome-GPU\"}, {\"gpu\": \"10de:1cb3-23.21.13.8816\", \"os\": \"Windows-10\", \"pool\": \"Chrome-GPU\"}]" + "[{\"gpu\": \"10de:1cb3-23.21.13.8792\", \"os\": \"Windows-2008ServerR2-SP1\", \"pool\": \"Chrome-GPU\"}, {\"gpu\": \"10de:1cb3-23.21.13.8816\", \"os\": \"Windows-10\", \"pool\": \"Chrome-GPU\"}]", + "--gpu-trigger-script-verbose", + "True" ], "script": "//content/test/gpu/trigger_gpu_test.py" }, @@ -2838,7 +2840,9 @@ "trigger_script": { "args": [ "--gpu-trigger-configs", - "[{\"gpu\": \"10de:1cb3-23.21.13.8792\", \"os\": \"Windows-2008ServerR2-SP1\", \"pool\": \"Chrome-GPU\"}, {\"gpu\": \"10de:1cb3-23.21.13.8816\", \"os\": \"Windows-10\", \"pool\": \"Chrome-GPU\"}]" + "[{\"gpu\": \"10de:1cb3-23.21.13.8792\", \"os\": \"Windows-2008ServerR2-SP1\", \"pool\": \"Chrome-GPU\"}, {\"gpu\": \"10de:1cb3-23.21.13.8816\", \"os\": \"Windows-10\", \"pool\": \"Chrome-GPU\"}]", + "--gpu-trigger-script-verbose", + "True" ], "script": "//content/test/gpu/trigger_gpu_test.py" }, @@ -2863,7 +2867,9 @@ "trigger_script": { "args": [ "--gpu-trigger-configs", - "[{\"gpu\": \"10de:1cb3-23.21.13.8792\", \"os\": \"Windows-2008ServerR2-SP1\", \"pool\": \"Chrome-GPU\"}, {\"gpu\": \"10de:1cb3-23.21.13.8816\", \"os\": \"Windows-10\", \"pool\": \"Chrome-GPU\"}]" + "[{\"gpu\": \"10de:1cb3-23.21.13.8792\", \"os\": \"Windows-2008ServerR2-SP1\", \"pool\": \"Chrome-GPU\"}, {\"gpu\": \"10de:1cb3-23.21.13.8816\", \"os\": \"Windows-10\", \"pool\": \"Chrome-GPU\"}]", + "--gpu-trigger-script-verbose", + "True" ], "script": "//content/test/gpu/trigger_gpu_test.py" }, @@ -2889,7 +2895,9 @@ "trigger_script": { "args": [ "--gpu-trigger-configs", - "[{\"gpu\": \"10de:1cb3-23.21.13.8792\", \"os\": \"Windows-2008ServerR2-SP1\", \"pool\": \"Chrome-GPU\"}, {\"gpu\": \"10de:1cb3-23.21.13.8816\", \"os\": \"Windows-10\", \"pool\": \"Chrome-GPU\"}]" + "[{\"gpu\": \"10de:1cb3-23.21.13.8792\", \"os\": \"Windows-2008ServerR2-SP1\", \"pool\": \"Chrome-GPU\"}, {\"gpu\": \"10de:1cb3-23.21.13.8816\", \"os\": \"Windows-10\", \"pool\": \"Chrome-GPU\"}]", + "--gpu-trigger-script-verbose", + "True" ], "script": "//content/test/gpu/trigger_gpu_test.py" }, @@ -2913,7 +2921,9 @@ "trigger_script": { "args": [ "--gpu-trigger-configs", - "[{\"gpu\": \"10de:1cb3-23.21.13.8792\", \"os\": \"Windows-2008ServerR2-SP1\", \"pool\": \"Chrome-GPU\"}, {\"gpu\": \"10de:1cb3-23.21.13.8816\", \"os\": \"Windows-10\", \"pool\": \"Chrome-GPU\"}]" + "[{\"gpu\": \"10de:1cb3-23.21.13.8792\", \"os\": \"Windows-2008ServerR2-SP1\", \"pool\": \"Chrome-GPU\"}, {\"gpu\": \"10de:1cb3-23.21.13.8816\", \"os\": \"Windows-10\", \"pool\": \"Chrome-GPU\"}]", + "--gpu-trigger-script-verbose", + "True" ], "script": "//content/test/gpu/trigger_gpu_test.py" }, @@ -2940,7 +2950,9 @@ "trigger_script": { "args": [ "--gpu-trigger-configs", - "[{\"gpu\": \"10de:1cb3-23.21.13.8792\", \"os\": \"Windows-2008ServerR2-SP1\", \"pool\": \"Chrome-GPU\"}, {\"gpu\": \"10de:1cb3-23.21.13.8816\", \"os\": \"Windows-10\", \"pool\": \"Chrome-GPU\"}]" + "[{\"gpu\": \"10de:1cb3-23.21.13.8792\", \"os\": \"Windows-2008ServerR2-SP1\", \"pool\": \"Chrome-GPU\"}, {\"gpu\": \"10de:1cb3-23.21.13.8816\", \"os\": \"Windows-10\", \"pool\": \"Chrome-GPU\"}]", + "--gpu-trigger-script-verbose", + "True" ], "script": "//content/test/gpu/trigger_gpu_test.py" }, @@ -2975,7 +2987,9 @@ "trigger_script": { "args": [ "--gpu-trigger-configs", - "[{\"gpu\": \"10de:1cb3-23.21.13.8792\", \"os\": \"Windows-2008ServerR2-SP1\", \"pool\": \"Chrome-GPU\"}, {\"gpu\": \"10de:1cb3-23.21.13.8816\", \"os\": \"Windows-10\", \"pool\": \"Chrome-GPU\"}]" + "[{\"gpu\": \"10de:1cb3-23.21.13.8792\", \"os\": \"Windows-2008ServerR2-SP1\", \"pool\": \"Chrome-GPU\"}, {\"gpu\": \"10de:1cb3-23.21.13.8816\", \"os\": \"Windows-10\", \"pool\": \"Chrome-GPU\"}]", + "--gpu-trigger-script-verbose", + "True" ], "script": "//content/test/gpu/trigger_gpu_test.py" } @@ -3007,7 +3021,9 @@ "trigger_script": { "args": [ "--gpu-trigger-configs", - "[{\"gpu\": \"10de:1cb3-23.21.13.8792\", \"os\": \"Windows-2008ServerR2-SP1\", \"pool\": \"Chrome-GPU\"}, {\"gpu\": \"10de:1cb3-23.21.13.8816\", \"os\": \"Windows-10\", \"pool\": \"Chrome-GPU\"}]" + "[{\"gpu\": \"10de:1cb3-23.21.13.8792\", \"os\": \"Windows-2008ServerR2-SP1\", \"pool\": \"Chrome-GPU\"}, {\"gpu\": \"10de:1cb3-23.21.13.8816\", \"os\": \"Windows-10\", \"pool\": \"Chrome-GPU\"}]", + "--gpu-trigger-script-verbose", + "True" ], "script": "//content/test/gpu/trigger_gpu_test.py" } @@ -3039,7 +3055,9 @@ "trigger_script": { "args": [ "--gpu-trigger-configs", - "[{\"gpu\": \"10de:1cb3-23.21.13.8792\", \"os\": \"Windows-2008ServerR2-SP1\", \"pool\": \"Chrome-GPU\"}, {\"gpu\": \"10de:1cb3-23.21.13.8816\", \"os\": \"Windows-10\", \"pool\": \"Chrome-GPU\"}]" + "[{\"gpu\": \"10de:1cb3-23.21.13.8792\", \"os\": \"Windows-2008ServerR2-SP1\", \"pool\": \"Chrome-GPU\"}, {\"gpu\": \"10de:1cb3-23.21.13.8816\", \"os\": \"Windows-10\", \"pool\": \"Chrome-GPU\"}]", + "--gpu-trigger-script-verbose", + "True" ], "script": "//content/test/gpu/trigger_gpu_test.py" } @@ -3071,7 +3089,9 @@ "trigger_script": { "args": [ "--gpu-trigger-configs", - "[{\"gpu\": \"10de:1cb3-23.21.13.8792\", \"os\": \"Windows-2008ServerR2-SP1\", \"pool\": \"Chrome-GPU\"}, {\"gpu\": \"10de:1cb3-23.21.13.8816\", \"os\": \"Windows-10\", \"pool\": \"Chrome-GPU\"}]" + "[{\"gpu\": \"10de:1cb3-23.21.13.8792\", \"os\": \"Windows-2008ServerR2-SP1\", \"pool\": \"Chrome-GPU\"}, {\"gpu\": \"10de:1cb3-23.21.13.8816\", \"os\": \"Windows-10\", \"pool\": \"Chrome-GPU\"}]", + "--gpu-trigger-script-verbose", + "True" ], "script": "//content/test/gpu/trigger_gpu_test.py" } @@ -3107,7 +3127,9 @@ "trigger_script": { "args": [ "--gpu-trigger-configs", - "[{\"gpu\": \"10de:1cb3-23.21.13.8792\", \"os\": \"Windows-2008ServerR2-SP1\", \"pool\": \"Chrome-GPU\"}, {\"gpu\": \"10de:1cb3-23.21.13.8816\", \"os\": \"Windows-10\", \"pool\": \"Chrome-GPU\"}]" + "[{\"gpu\": \"10de:1cb3-23.21.13.8792\", \"os\": \"Windows-2008ServerR2-SP1\", \"pool\": \"Chrome-GPU\"}, {\"gpu\": \"10de:1cb3-23.21.13.8816\", \"os\": \"Windows-10\", \"pool\": \"Chrome-GPU\"}]", + "--gpu-trigger-script-verbose", + "True" ], "script": "//content/test/gpu/trigger_gpu_test.py" } @@ -3146,7 +3168,9 @@ "trigger_script": { "args": [ "--gpu-trigger-configs", - "[{\"gpu\": \"10de:1cb3-23.21.13.8792\", \"os\": \"Windows-2008ServerR2-SP1\", \"pool\": \"Chrome-GPU\"}, {\"gpu\": \"10de:1cb3-23.21.13.8816\", \"os\": \"Windows-10\", \"pool\": \"Chrome-GPU\"}]" + "[{\"gpu\": \"10de:1cb3-23.21.13.8792\", \"os\": \"Windows-2008ServerR2-SP1\", \"pool\": \"Chrome-GPU\"}, {\"gpu\": \"10de:1cb3-23.21.13.8816\", \"os\": \"Windows-10\", \"pool\": \"Chrome-GPU\"}]", + "--gpu-trigger-script-verbose", + "True" ], "script": "//content/test/gpu/trigger_gpu_test.py" } @@ -3193,7 +3217,9 @@ "trigger_script": { "args": [ "--gpu-trigger-configs", - "[{\"gpu\": \"10de:1cb3-23.21.13.8792\", \"os\": \"Windows-2008ServerR2-SP1\", \"pool\": \"Chrome-GPU\"}, {\"gpu\": \"10de:1cb3-23.21.13.8816\", \"os\": \"Windows-10\", \"pool\": \"Chrome-GPU\"}]" + "[{\"gpu\": \"10de:1cb3-23.21.13.8792\", \"os\": \"Windows-2008ServerR2-SP1\", \"pool\": \"Chrome-GPU\"}, {\"gpu\": \"10de:1cb3-23.21.13.8816\", \"os\": \"Windows-10\", \"pool\": \"Chrome-GPU\"}]", + "--gpu-trigger-script-verbose", + "True" ], "script": "//content/test/gpu/trigger_gpu_test.py" } @@ -3226,7 +3252,9 @@ "trigger_script": { "args": [ "--gpu-trigger-configs", - "[{\"gpu\": \"10de:1cb3-23.21.13.8792\", \"os\": \"Windows-2008ServerR2-SP1\", \"pool\": \"Chrome-GPU\"}, {\"gpu\": \"10de:1cb3-23.21.13.8816\", \"os\": \"Windows-10\", \"pool\": \"Chrome-GPU\"}]" + "[{\"gpu\": \"10de:1cb3-23.21.13.8792\", \"os\": \"Windows-2008ServerR2-SP1\", \"pool\": \"Chrome-GPU\"}, {\"gpu\": \"10de:1cb3-23.21.13.8816\", \"os\": \"Windows-10\", \"pool\": \"Chrome-GPU\"}]", + "--gpu-trigger-script-verbose", + "True" ], "script": "//content/test/gpu/trigger_gpu_test.py" } @@ -3258,7 +3286,9 @@ "trigger_script": { "args": [ "--gpu-trigger-configs", - "[{\"gpu\": \"10de:1cb3-23.21.13.8792\", \"os\": \"Windows-2008ServerR2-SP1\", \"pool\": \"Chrome-GPU\"}, {\"gpu\": \"10de:1cb3-23.21.13.8816\", \"os\": \"Windows-10\", \"pool\": \"Chrome-GPU\"}]" + "[{\"gpu\": \"10de:1cb3-23.21.13.8792\", \"os\": \"Windows-2008ServerR2-SP1\", \"pool\": \"Chrome-GPU\"}, {\"gpu\": \"10de:1cb3-23.21.13.8816\", \"os\": \"Windows-10\", \"pool\": \"Chrome-GPU\"}]", + "--gpu-trigger-script-verbose", + "True" ], "script": "//content/test/gpu/trigger_gpu_test.py" } @@ -3291,7 +3321,9 @@ "trigger_script": { "args": [ "--gpu-trigger-configs", - "[{\"gpu\": \"10de:1cb3-23.21.13.8792\", \"os\": \"Windows-2008ServerR2-SP1\", \"pool\": \"Chrome-GPU\"}, {\"gpu\": \"10de:1cb3-23.21.13.8816\", \"os\": \"Windows-10\", \"pool\": \"Chrome-GPU\"}]" + "[{\"gpu\": \"10de:1cb3-23.21.13.8792\", \"os\": \"Windows-2008ServerR2-SP1\", \"pool\": \"Chrome-GPU\"}, {\"gpu\": \"10de:1cb3-23.21.13.8816\", \"os\": \"Windows-10\", \"pool\": \"Chrome-GPU\"}]", + "--gpu-trigger-script-verbose", + "True" ], "script": "//content/test/gpu/trigger_gpu_test.py" }
diff --git a/testing/buildbot/chromium.mac.json b/testing/buildbot/chromium.mac.json index 38fbe63c..80461b91 100644 --- a/testing/buildbot/chromium.mac.json +++ b/testing/buildbot/chromium.mac.json
@@ -396,6 +396,16 @@ ], "isolated_scripts": [ { + "args": [ + "--filter=__main__.ChromeDriverTest.testLoadUrl" + ], + "isolate_name": "chromedriver_py_tests", + "name": "chromedriver_py_tests", + "swarming": { + "can_use_on_swarming_builders": true + } + }, + { "isolate_name": "telemetry_gpu_unittests", "name": "telemetry_gpu_unittests", "swarming": { @@ -840,6 +850,16 @@ ], "isolated_scripts": [ { + "args": [ + "--filter=__main__.ChromeDriverTest.testLoadUrl" + ], + "isolate_name": "chromedriver_py_tests", + "name": "chromedriver_py_tests", + "swarming": { + "can_use_on_swarming_builders": true + } + }, + { "isolate_name": "telemetry_gpu_unittests", "name": "telemetry_gpu_unittests", "swarming": { @@ -1284,6 +1304,16 @@ ], "isolated_scripts": [ { + "args": [ + "--filter=__main__.ChromeDriverTest.testLoadUrl" + ], + "isolate_name": "chromedriver_py_tests", + "name": "chromedriver_py_tests", + "swarming": { + "can_use_on_swarming_builders": true + } + }, + { "isolate_name": "telemetry_gpu_unittests", "name": "telemetry_gpu_unittests", "swarming": { @@ -1742,6 +1772,16 @@ ], "isolated_scripts": [ { + "args": [ + "--filter=__main__.ChromeDriverTest.testLoadUrl" + ], + "isolate_name": "chromedriver_py_tests", + "name": "chromedriver_py_tests", + "swarming": { + "can_use_on_swarming_builders": true + } + }, + { "isolate_name": "content_shell_crash_test", "name": "content_shell_crash_test", "swarming": {
diff --git a/testing/buildbot/chromium.sandbox.json b/testing/buildbot/chromium.sandbox.json index e8ed742..6c7867a3 100644 --- a/testing/buildbot/chromium.sandbox.json +++ b/testing/buildbot/chromium.sandbox.json
@@ -576,6 +576,16 @@ ], "isolated_scripts": [ { + "args": [ + "--filter=__main__.ChromeDriverTest.testLoadUrl" + ], + "isolate_name": "chromedriver_py_tests", + "name": "chromedriver_py_tests", + "swarming": { + "can_use_on_swarming_builders": true + } + }, + { "isolate_name": "content_shell_crash_test", "name": "content_shell_crash_test", "swarming": {
diff --git a/testing/buildbot/chromium.win.json b/testing/buildbot/chromium.win.json index b405f59..136b332 100644 --- a/testing/buildbot/chromium.win.json +++ b/testing/buildbot/chromium.win.json
@@ -538,6 +538,16 @@ ], "isolated_scripts": [ { + "args": [ + "--filter=__main__.ChromeDriverTest.testLoadUrl" + ], + "isolate_name": "chromedriver_py_tests", + "name": "chromedriver_py_tests", + "swarming": { + "can_use_on_swarming_builders": true + } + }, + { "isolate_name": "metrics_python_tests", "name": "metrics_python_tests", "swarming": { @@ -1714,6 +1724,16 @@ ], "isolated_scripts": [ { + "args": [ + "--filter=__main__.ChromeDriverTest.testLoadUrl" + ], + "isolate_name": "chromedriver_py_tests", + "name": "chromedriver_py_tests", + "swarming": { + "can_use_on_swarming_builders": true + } + }, + { "isolate_name": "content_shell_crash_test", "name": "content_shell_crash_test", "swarming": {
diff --git a/testing/buildbot/test_suites.pyl b/testing/buildbot/test_suites.pyl index c8a0d2e..2114cd6 100644 --- a/testing/buildbot/test_suites.pyl +++ b/testing/buildbot/test_suites.pyl
@@ -1788,7 +1788,13 @@ 'vr_platform_specific_non_clang_win_chromium_gtests', ], - 'chromium_isolated_scripts': [ + 'chromium_dbg_isolated_scripts': [ + 'desktop_chromium_isolated_scripts', + 'telemetry_perf_unittests_isolated_scripts', + ], + + 'chromium_rel_isolated_scripts': [ + 'chromedriver_py_tests_isolated_scripts', 'desktop_chromium_isolated_scripts', 'telemetry_perf_unittests_isolated_scripts', ], @@ -1953,7 +1959,7 @@ 'viz_gtests', ], - 'chromium_linux_isolated_scripts': [ + 'chromium_linux_dbg_isolated_scripts': [ 'desktop_chromium_isolated_scripts', 'linux_specific_chromium_isolated_scripts', 'telemetry_perf_unittests_isolated_scripts',
diff --git a/testing/buildbot/waterfalls.pyl b/testing/buildbot/waterfalls.pyl index 82130bc..5c91f28 100644 --- a/testing/buildbot/waterfalls.pyl +++ b/testing/buildbot/waterfalls.pyl
@@ -738,7 +738,7 @@ 'ToTMac': { 'test_suites': { 'gtest_tests': 'chromium_mac_clang_gtests', - 'isolated_scripts': 'chromium_isolated_scripts', + 'isolated_scripts': 'chromium_rel_isolated_scripts', }, }, 'ToTMacASan': { @@ -897,7 +897,7 @@ 'Chromium Mac 10.11': { 'test_suites': { 'gtest_tests': 'chromium_mac_fyi_gtests', - 'isolated_scripts': 'chromium_isolated_scripts', + 'isolated_scripts': 'chromium_rel_isolated_scripts', }, 'use_swarming': False, }, @@ -910,7 +910,7 @@ 'Chromium Mac 10.13': { 'test_suites': { 'gtest_tests': 'chromium_mac_fyi_gtests', - 'isolated_scripts': 'chromium_isolated_scripts', + 'isolated_scripts': 'chromium_rel_isolated_scripts', }, }, 'Chromium Win 10 GCE Tests': { @@ -1095,7 +1095,7 @@ 'device_type': 'bullhead', }, ], - 'hard_timeout': 960, + 'hard_timeout': 1800, }, 'os_type': 'android', 'test_suites': { @@ -1149,7 +1149,7 @@ 'Out of Process Profiling Mac': { 'test_suites': { 'gtest_tests': 'chromium_mac_fyi_gtests', - 'isolated_scripts': 'chromium_isolated_scripts', + 'isolated_scripts': 'chromium_rel_isolated_scripts', }, }, 'Out of Process Profiling Windows': { @@ -1401,13 +1401,13 @@ 'Linux Tests (dbg)(1)': { 'test_suites': { 'gtest_tests': 'chromium_linux_gtests', - 'isolated_scripts': 'chromium_linux_isolated_scripts', + 'isolated_scripts': 'chromium_linux_dbg_isolated_scripts', }, }, 'Linux Tests (dbg)(1)(32)': { 'test_suites': { 'gtest_tests': 'chromium_linux_gtests', - 'isolated_scripts': 'chromium_linux_isolated_scripts', + 'isolated_scripts': 'chromium_linux_dbg_isolated_scripts', }, }, 'Ozone Linux': { @@ -1531,32 +1531,32 @@ 'Mac10.10 Tests': { 'test_suites': { 'gtest_tests': 'chromium_mac_gtests', - 'isolated_scripts': 'chromium_isolated_scripts', + 'isolated_scripts': 'chromium_rel_isolated_scripts', }, }, 'Mac10.11 Tests': { 'test_suites': { 'gtest_tests': 'chromium_mac_gtests', - 'isolated_scripts': 'chromium_isolated_scripts', + 'isolated_scripts': 'chromium_rel_isolated_scripts', }, }, 'Mac10.12 Tests': { 'test_suites': { 'gtest_tests': 'chromium_mac_gtests', - 'isolated_scripts': 'chromium_isolated_scripts', + 'isolated_scripts': 'chromium_rel_isolated_scripts', }, }, 'Mac10.9 Tests': { 'test_suites': { 'gtest_tests': 'chromium_mac_gtests', - 'isolated_scripts': 'chromium_isolated_scripts', + 'isolated_scripts': 'chromium_rel_isolated_scripts', 'scripts': 'chromium_scripts', }, }, 'Mac10.9 Tests (dbg)': { 'test_suites': { 'gtest_tests': 'chromium_mac_gtests', - 'isolated_scripts': 'chromium_isolated_scripts', + 'isolated_scripts': 'chromium_dbg_isolated_scripts', }, }, }, @@ -1647,7 +1647,7 @@ # exceptions that Linux Tests doesn't also have. 'test_suites': { 'gtest_tests': 'chromium_linux_gtests', - 'isolated_scripts': 'chromium_linux_isolated_scripts', + 'isolated_scripts': 'chromium_linux_rel_isolated_scripts', 'scripts': 'chromium_linux_scripts', }, }, @@ -1981,7 +1981,7 @@ 'Win 7 Tests x64 (1)': { 'test_suites': { 'gtest_tests': 'chromium_win_gtests', - 'isolated_scripts': 'chromium_isolated_scripts', + 'isolated_scripts': 'chromium_rel_isolated_scripts', }, }, 'Win10 Tests x64': { @@ -1997,14 +1997,14 @@ 'Win7 Tests (1)': { 'test_suites': { 'gtest_tests': 'chromium_win_gtests', - 'isolated_scripts': 'chromium_isolated_scripts', + 'isolated_scripts': 'chromium_rel_isolated_scripts', 'scripts': 'chromium_scripts', }, }, 'Win7 Tests (dbg)(1)': { 'test_suites': { 'gtest_tests': 'chromium_win_gtests', - 'isolated_scripts': 'chromium_isolated_scripts', + 'isolated_scripts': 'chromium_dbg_isolated_scripts', }, }, },
diff --git a/testing/scripts/run_gpu_integration_test_as_googletest.py b/testing/scripts/run_gpu_integration_test_as_googletest.py index 3163bdf..174f1a6 100755 --- a/testing/scripts/run_gpu_integration_test_as_googletest.py +++ b/testing/scripts/run_gpu_integration_test_as_googletest.py
@@ -104,7 +104,10 @@ rc = 0 try: env['CHROME_HEADLESS'] = '1' - rc = common.run_command([sys.executable] + rest_args + sharding_args + [ + main_command = [sys.executable] + if not os.getenv('VIRTUAL_ENV'): + main_command = ['vpython'] + rc = common.run_command(main_command + rest_args + sharding_args + [ '--write-full-results-to', args.isolated_script_test_output ], env=env) except Exception:
diff --git a/testing/test.gni b/testing/test.gni index d3aa7a6f..f50f332c 100644 --- a/testing/test.gni +++ b/testing/test.gni
@@ -247,6 +247,7 @@ ] test_name = _output_name exe_path = "$root_out_dir/" + get_label_info(_exec_target, "name") + package_name = _output_name } executable(_exec_target) {
diff --git a/testing/variations/fieldtrial_testing_config.json b/testing/variations/fieldtrial_testing_config.json index 55f50fc..7a29818 100644 --- a/testing/variations/fieldtrial_testing_config.json +++ b/testing/variations/fieldtrial_testing_config.json
@@ -649,6 +649,26 @@ ] } ], + "BlinkSchedulerHighPriorityInput": [ + { + "platforms": [ + "android", + "chromeos", + "ios", + "linux", + "mac", + "win" + ], + "experiments": [ + { + "name": "BlinkSchedulerHighPriorityInput", + "enable_features": [ + "BlinkSchedulerHighPriorityInput" + ] + } + ] + } + ], "BookmarkInProductHelp": [ { "platforms": [ @@ -1490,6 +1510,16 @@ ], "experiments": [ { + "name": "SofterWarningWarnOnLowReputation", + "params": { + "softer_warning": "true", + "warn_on_low_reputation": "true" + }, + "enable_features": [ + "PasswordProtectionGoogleBrandedPhishingWarning" + ] + }, + { "name": "SofterWarning", "params": { "softer_warning": "true", @@ -2107,13 +2137,18 @@ "NetAdaptiveProxyConnectionTimeout": [ { "platforms": [ - "android" + "android", + "chromeos", + "linux", + "mac", + "win" ], "experiments": [ { - "name": "Enabled_1_m5", + "name": "Enabled_Forced", "params": { - "transport_rtt_multiplier": "5" + "non_ssl_http_rtt_multiplier": "6", + "ssl_http_rtt_multiplier": "8" } } ] @@ -2322,10 +2357,15 @@ ], "experiments": [ { - "name": "HideSuggestionUrlSchemeAndTrivialSubdomains", + "name": "UIExperiments", + "params": { + "UIVerticalMargin": "8" + }, "enable_features": [ "OmniboxUIExperimentHideSuggestionUrlScheme", - "OmniboxUIExperimentHideSuggestionUrlTrivialSubdomains" + "OmniboxUIExperimentHideSuggestionUrlTrivialSubdomains", + "OmniboxUIExperimentSwapTitleAndUrl", + "OmniboxUIExperimentVerticalMargin" ] } ] @@ -2816,7 +2856,7 @@ { "name": "Enabled", "enable_features": [ - "ReaderForAccessibility" + "AllowReaderForAccessibility" ] } ] @@ -2837,6 +2877,27 @@ ] } ], + "ReferrerChainDiagnose": [ + { + "platforms": [ + "chromeos", + "linux", + "mac", + "win" + ], + "experiments": [ + { + "name": "Append5RecentNavigations", + "params": { + "recent_navigation_count": "5" + }, + "enable_features": [ + "AppendRecentNavigationEvents" + ] + } + ] + } + ], "RefreshTokenDeviceId": [ { "platforms": [ @@ -3503,6 +3564,27 @@ ] } ], + "SpeculativePreconnectValidation": [ + { + "platforms": [ + "win", + "mac", + "linux", + "android" + ], + "experiments": [ + { + "name": "Preconnect2", + "params": { + "mode": "preconnect" + }, + "enable_features": [ + "SpeculativePreconnect" + ] + } + ] + } + ], "StabilityDebugging": [ { "platforms": [ @@ -3906,6 +3988,12 @@ "enable_features": [ "UseHeuristicLanguageModel" ] + }, + { + "name": "Stable_Experiment", + "enable_features": [ + "UseHeuristicLanguageModel" + ] } ] }
diff --git a/third_party/WebKit/LayoutTests/FlagExpectations/enable-blink-features=LayoutNG b/third_party/WebKit/LayoutTests/FlagExpectations/enable-blink-features=LayoutNG index 88dcafd..9af630b 100644 --- a/third_party/WebKit/LayoutTests/FlagExpectations/enable-blink-features=LayoutNG +++ b/third_party/WebKit/LayoutTests/FlagExpectations/enable-blink-features=LayoutNG
@@ -4,12 +4,6 @@ # Need support for getBoundingClientRect() with LayoutNG. crbug.com/755750 accessibility/selection-affinity.html [ Failure ] -# We currently write back whitespace-collapsed strings to LayoutText, causing -# the following failures. Once we can paint inlines directly from fragment tree, -# we can stop the writeback. - -# Editing does not completely work with LayoutNG yet. - ## Reverse hosting of editable block crbug.com/707656 editing/execCommand/format-block-crash.html [ Crash ] crbug.com/707656 editing/input/scroll-viewport-page-up-down.html [ Failure ] @@ -28,7 +22,6 @@ # Slow when run with LayoutNG crbug.com/591099 external/wpt/css/css-color/color-resolving-hsl.html [ Timeout ] - # New passes crbug.com/626703 external/wpt/css/css-ui/text-overflow-021.html [ Failure ] crbug.com/492664 external/wpt/css/css-writing-modes/inline-block-alignment-003.xht [ Pass ] @@ -109,16 +102,18 @@ crbug.com/591099 accessibility/readonly.html [ Failure ] crbug.com/591099 accessibility/removed-continuation-element-causes-crash.html [ Failure ] crbug.com/591099 accessibility/role-attribute.html [ Failure ] +crbug.com/591099 accessibility/role-change.html [ Failure ] crbug.com/591099 accessibility/scroll-div-horiz-sends-notification.html [ Failure ] crbug.com/714962 accessibility/selection-events.html [ Failure ] crbug.com/714962 accessibility/set-selection-link.html [ Failure ] crbug.com/591099 accessibility/spelling-markers.html [ Failure ] crbug.com/591099 accessibility/table-cells.html [ Failure ] -crbug.com/714962 accessibility/table-detection.html [ Failure ] +crbug.com/714962 accessibility/table-detection.html [ Failure Pass ] crbug.com/591099 accessibility/table-header-column-row.html [ Failure ] crbug.com/591099 accessibility/table-one-cell.html [ Failure ] crbug.com/714962 accessibility/table-with-empty-thead-causes-crash.html [ Failure ] -crbug.com/714962 accessibility/table-with-rules.html [ Failure ] +crbug.com/591099 accessibility/table-with-presentation-role.html [ Failure ] +crbug.com/714962 accessibility/table-with-rules.html [ Failure Pass ] crbug.com/591099 accessibility/textarea-caret-position.html [ Failure ] crbug.com/591099 accessibility/textarea-selection.html [ Failure ] crbug.com/591099 accessibility/whitespace-in-name-calc.html [ Failure ] @@ -1001,7 +996,7 @@ crbug.com/591099 editing/pasteboard/4806874.html [ Failure ] crbug.com/591099 editing/pasteboard/4947130.html [ Failure ] crbug.com/591099 editing/pasteboard/5006779.html [ Failure ] -crbug.com/591099 editing/pasteboard/5032095.html [ Failure ] +crbug.com/591099 editing/pasteboard/5032095.html [ Failure Pass ] crbug.com/591099 editing/pasteboard/5071074-2.html [ Failure ] crbug.com/591099 editing/pasteboard/5071074.html [ Failure ] crbug.com/591099 editing/pasteboard/5134759.html [ Failure ] @@ -1129,7 +1124,7 @@ crbug.com/591099 editing/selection/move-backwords-by-word-001.html [ Failure ] crbug.com/591099 editing/selection/move-by-line-002.html [ Failure ] crbug.com/591099 editing/selection/move-by-sentence-001.html [ Failure ] -crbug.com/591099 editing/selection/move-by-word-001.html [ Failure ] +crbug.com/591099 editing/selection/move-by-word-001.html [ Failure Pass ] crbug.com/591099 editing/selection/move-left-right.html [ Pass Timeout ] crbug.com/591099 editing/selection/move-past-trailing-space.html [ Failure ] crbug.com/714962 editing/selection/offset-from-point-complex-scripts.html [ Failure ] @@ -1210,7 +1205,7 @@ crbug.com/591099 external/wpt/WebCryptoAPI/generateKey/failures_ECDH.worker.html [ Timeout ] crbug.com/591099 external/wpt/WebCryptoAPI/generateKey/failures_ECDSA.worker.html [ Timeout ] crbug.com/591099 external/wpt/WebCryptoAPI/generateKey/failures_HMAC.worker.html [ Timeout ] -crbug.com/714962 external/wpt/WebCryptoAPI/generateKey/failures_RSA-OAEP.https.worker.html [ Timeout ] +crbug.com/714962 external/wpt/WebCryptoAPI/generateKey/failures_RSA-OAEP.https.worker.html [ Pass Timeout ] crbug.com/591099 external/wpt/WebCryptoAPI/generateKey/failures_RSA-OAEP.worker.html [ Timeout ] crbug.com/591099 external/wpt/WebCryptoAPI/generateKey/failures_RSA-PSS.worker.html [ Timeout ] crbug.com/591099 external/wpt/WebCryptoAPI/generateKey/failures_RSASSA-PKCS1-v1_5.worker.html [ Timeout ] @@ -1539,7 +1534,7 @@ crbug.com/591099 external/wpt/css/css-shapes/spec-examples/shape-outside-018.html [ Failure ] crbug.com/591099 external/wpt/css/css-shapes/spec-examples/shape-outside-019.html [ Failure ] crbug.com/591099 external/wpt/css/css-style-attr/style-attr-urls-001.xht [ Failure ] -crbug.com/591099 external/wpt/css/css-style-attr/style-attr-urls-002.xht [ Failure ] +crbug.com/591099 external/wpt/css/css-style-attr/style-attr-urls-002.xht [ Failure Pass ] crbug.com/591099 external/wpt/css/css-tables/height-distribution/percentage-sizing-of-table-cell-children.html [ Failure ] crbug.com/591099 external/wpt/css/css-tables/html5-table-formatting-fixed-layout-1.html [ Crash ] crbug.com/591099 external/wpt/css/css-tables/table-model-fixup-2.html [ Failure ] @@ -1635,7 +1630,7 @@ crbug.com/714962 external/wpt/css/css-writing-modes/abs-pos-non-replaced-vlr-055.xht [ Failure ] crbug.com/714962 external/wpt/css/css-writing-modes/abs-pos-non-replaced-vlr-057.xht [ Failure ] crbug.com/714962 external/wpt/css/css-writing-modes/abs-pos-non-replaced-vlr-059.xht [ Failure Pass ] -crbug.com/714962 external/wpt/css/css-writing-modes/abs-pos-non-replaced-vlr-061.xht [ Failure ] +crbug.com/714962 external/wpt/css/css-writing-modes/abs-pos-non-replaced-vlr-061.xht [ Failure Pass ] crbug.com/714962 external/wpt/css/css-writing-modes/abs-pos-non-replaced-vlr-063.xht [ Failure ] crbug.com/591099 external/wpt/css/css-writing-modes/abs-pos-non-replaced-vlr-065.xht [ Failure ] crbug.com/714962 external/wpt/css/css-writing-modes/abs-pos-non-replaced-vlr-067.xht [ Failure ] @@ -1651,7 +1646,7 @@ crbug.com/714962 external/wpt/css/css-writing-modes/abs-pos-non-replaced-vlr-087.xht [ Failure ] crbug.com/591099 external/wpt/css/css-writing-modes/abs-pos-non-replaced-vlr-089.xht [ Failure ] crbug.com/714962 external/wpt/css/css-writing-modes/abs-pos-non-replaced-vlr-091.xht [ Failure ] -crbug.com/714962 external/wpt/css/css-writing-modes/abs-pos-non-replaced-vlr-093.xht [ Failure ] +crbug.com/714962 external/wpt/css/css-writing-modes/abs-pos-non-replaced-vlr-093.xht [ Failure Pass ] crbug.com/591099 external/wpt/css/css-writing-modes/abs-pos-non-replaced-vlr-095.xht [ Failure Pass ] crbug.com/714962 external/wpt/css/css-writing-modes/abs-pos-non-replaced-vlr-097.xht [ Failure Pass ] crbug.com/714962 external/wpt/css/css-writing-modes/abs-pos-non-replaced-vlr-103.xht [ Failure ] @@ -1669,7 +1664,7 @@ crbug.com/714962 external/wpt/css/css-writing-modes/abs-pos-non-replaced-vlr-127.xht [ Failure ] crbug.com/714962 external/wpt/css/css-writing-modes/abs-pos-non-replaced-vlr-129.xht [ Failure ] crbug.com/714962 external/wpt/css/css-writing-modes/abs-pos-non-replaced-vlr-131.xht [ Failure ] -crbug.com/714962 external/wpt/css/css-writing-modes/abs-pos-non-replaced-vlr-133.xht [ Failure ] +crbug.com/714962 external/wpt/css/css-writing-modes/abs-pos-non-replaced-vlr-133.xht [ Failure Pass ] crbug.com/714962 external/wpt/css/css-writing-modes/abs-pos-non-replaced-vlr-135.xht [ Failure Pass ] crbug.com/591099 external/wpt/css/css-writing-modes/abs-pos-non-replaced-vlr-137.xht [ Failure Pass ] crbug.com/714962 external/wpt/css/css-writing-modes/abs-pos-non-replaced-vlr-139.xht [ Failure Pass ] @@ -1690,14 +1685,14 @@ crbug.com/591099 external/wpt/css/css-writing-modes/abs-pos-non-replaced-vlr-169.xht [ Failure ] crbug.com/714962 external/wpt/css/css-writing-modes/abs-pos-non-replaced-vlr-171.xht [ Failure ] crbug.com/591099 external/wpt/css/css-writing-modes/abs-pos-non-replaced-vlr-173.xht [ Failure ] -crbug.com/714962 external/wpt/css/css-writing-modes/abs-pos-non-replaced-vlr-175.xht [ Failure ] +crbug.com/714962 external/wpt/css/css-writing-modes/abs-pos-non-replaced-vlr-175.xht [ Failure Pass ] crbug.com/714962 external/wpt/css/css-writing-modes/abs-pos-non-replaced-vlr-177.xht [ Failure Pass ] crbug.com/714962 external/wpt/css/css-writing-modes/abs-pos-non-replaced-vlr-179.xht [ Failure ] crbug.com/591099 external/wpt/css/css-writing-modes/abs-pos-non-replaced-vlr-181.xht [ Failure ] crbug.com/714962 external/wpt/css/css-writing-modes/abs-pos-non-replaced-vlr-183.xht [ Failure ] crbug.com/591099 external/wpt/css/css-writing-modes/abs-pos-non-replaced-vlr-185.xht [ Failure ] crbug.com/714962 external/wpt/css/css-writing-modes/abs-pos-non-replaced-vlr-187.xht [ Failure Pass ] -crbug.com/591099 external/wpt/css/css-writing-modes/abs-pos-non-replaced-vlr-189.xht [ Failure ] +crbug.com/591099 external/wpt/css/css-writing-modes/abs-pos-non-replaced-vlr-189.xht [ Failure Pass ] crbug.com/714962 external/wpt/css/css-writing-modes/abs-pos-non-replaced-vlr-191.xht [ Failure Pass ] crbug.com/714962 external/wpt/css/css-writing-modes/abs-pos-non-replaced-vlr-193.xht [ Failure ] crbug.com/714962 external/wpt/css/css-writing-modes/abs-pos-non-replaced-vlr-195.xht [ Failure ] @@ -1707,7 +1702,7 @@ crbug.com/714962 external/wpt/css/css-writing-modes/abs-pos-non-replaced-vlr-203.xht [ Failure ] crbug.com/591099 external/wpt/css/css-writing-modes/abs-pos-non-replaced-vlr-205.xht [ Failure ] crbug.com/714962 external/wpt/css/css-writing-modes/abs-pos-non-replaced-vlr-207.xht [ Failure ] -crbug.com/714962 external/wpt/css/css-writing-modes/abs-pos-non-replaced-vlr-209.xht [ Failure ] +crbug.com/714962 external/wpt/css/css-writing-modes/abs-pos-non-replaced-vlr-209.xht [ Failure Pass ] crbug.com/714962 external/wpt/css/css-writing-modes/abs-pos-non-replaced-vlr-211.xht [ Failure Pass ] crbug.com/714962 external/wpt/css/css-writing-modes/abs-pos-non-replaced-vlr-213.xht [ Failure Pass ] crbug.com/714962 external/wpt/css/css-writing-modes/abs-pos-non-replaced-vlr-215.xht [ Failure ] @@ -1805,12 +1800,12 @@ crbug.com/714962 external/wpt/css/css-writing-modes/abs-pos-non-replaced-vrl-174.xht [ Failure ] crbug.com/591099 external/wpt/css/css-writing-modes/abs-pos-non-replaced-vrl-176.xht [ Failure Pass ] crbug.com/714962 external/wpt/css/css-writing-modes/abs-pos-non-replaced-vrl-178.xht [ Failure ] -crbug.com/714962 external/wpt/css/css-writing-modes/abs-pos-non-replaced-vrl-180.xht [ Failure ] +crbug.com/714962 external/wpt/css/css-writing-modes/abs-pos-non-replaced-vrl-180.xht [ Failure Pass ] crbug.com/714962 external/wpt/css/css-writing-modes/abs-pos-non-replaced-vrl-182.xht [ Failure ] crbug.com/714962 external/wpt/css/css-writing-modes/abs-pos-non-replaced-vrl-184.xht [ Failure ] crbug.com/714962 external/wpt/css/css-writing-modes/abs-pos-non-replaced-vrl-186.xht [ Failure ] crbug.com/591099 external/wpt/css/css-writing-modes/abs-pos-non-replaced-vrl-188.xht [ Failure ] -crbug.com/714962 external/wpt/css/css-writing-modes/abs-pos-non-replaced-vrl-190.xht [ Failure ] +crbug.com/714962 external/wpt/css/css-writing-modes/abs-pos-non-replaced-vrl-190.xht [ Failure Pass ] crbug.com/591099 external/wpt/css/css-writing-modes/abs-pos-non-replaced-vrl-192.xht [ Failure ] crbug.com/714962 external/wpt/css/css-writing-modes/abs-pos-non-replaced-vrl-194.xht [ Failure ] crbug.com/714962 external/wpt/css/css-writing-modes/abs-pos-non-replaced-vrl-196.xht [ Failure ] @@ -1856,10 +1851,10 @@ crbug.com/591099 external/wpt/css/css-writing-modes/float-contiguous-vrl-006.xht [ Failure ] crbug.com/591099 external/wpt/css/css-writing-modes/float-contiguous-vrl-008.xht [ Failure ] crbug.com/714962 external/wpt/css/css-writing-modes/float-shrink-to-fit-vrl-008.xht [ Failure ] -crbug.com/714962 external/wpt/css/css-writing-modes/float-vlr-005.xht [ Failure ] +crbug.com/714962 external/wpt/css/css-writing-modes/float-vlr-005.xht [ Failure Pass ] crbug.com/714962 external/wpt/css/css-writing-modes/float-vlr-007.xht [ Failure ] crbug.com/591099 external/wpt/css/css-writing-modes/float-vlr-013.xht [ Failure ] -crbug.com/591099 external/wpt/css/css-writing-modes/float-vrl-004.xht [ Failure ] +crbug.com/591099 external/wpt/css/css-writing-modes/float-vrl-004.xht [ Failure Pass ] crbug.com/591099 external/wpt/css/css-writing-modes/float-vrl-006.xht [ Failure Pass ] crbug.com/714962 external/wpt/css/css-writing-modes/float-vrl-008.xht [ Failure ] crbug.com/591099 external/wpt/css/css-writing-modes/float-vrl-012.xht [ Failure ] @@ -1930,12 +1925,12 @@ crbug.com/591099 external/wpt/css/css-writing-modes/text-align-vlr-011.xht [ Failure ] crbug.com/714962 external/wpt/css/css-writing-modes/text-align-vlr-013.xht [ Failure Pass ] crbug.com/714962 external/wpt/css/css-writing-modes/text-align-vlr-015.xht [ Failure Pass ] -crbug.com/714962 external/wpt/css/css-writing-modes/text-align-vlr-017.xht [ Failure ] +crbug.com/714962 external/wpt/css/css-writing-modes/text-align-vlr-017.xht [ Failure Pass ] crbug.com/714962 external/wpt/css/css-writing-modes/text-align-vlr-019.xht [ Failure Pass ] crbug.com/714962 external/wpt/css/css-writing-modes/text-align-vrl-002.xht [ Failure Pass ] crbug.com/714962 external/wpt/css/css-writing-modes/text-align-vrl-004.xht [ Failure Pass ] -crbug.com/714962 external/wpt/css/css-writing-modes/text-align-vrl-006.xht [ Failure ] -crbug.com/714962 external/wpt/css/css-writing-modes/text-align-vrl-008.xht [ Failure ] +crbug.com/714962 external/wpt/css/css-writing-modes/text-align-vrl-006.xht [ Failure Pass ] +crbug.com/714962 external/wpt/css/css-writing-modes/text-align-vrl-008.xht [ Failure Pass ] crbug.com/714962 external/wpt/css/css-writing-modes/text-align-vrl-010.xht [ Failure Pass ] crbug.com/714962 external/wpt/css/css-writing-modes/text-align-vrl-012.xht [ Failure ] crbug.com/714962 external/wpt/css/css-writing-modes/text-align-vrl-014.xht [ Failure ] @@ -1994,7 +1989,7 @@ crbug.com/591099 external/wpt/css/cssom-view/overscrollBehavior-manual.html [ Timeout ] crbug.com/714962 external/wpt/css/cssom/medialist-dynamic-001.html [ Failure ] crbug.com/626703 external/wpt/css/cssom/stylesheet-replacedata-dynamic.html [ Failure ] -crbug.com/591099 external/wpt/css/geometry/interfaces.html [ Timeout ] +crbug.com/591099 external/wpt/css/geometry/interfaces.html [ Pass Timeout ] crbug.com/591099 external/wpt/css/geometry/interfaces.worker.html [ Pass Timeout ] crbug.com/714962 external/wpt/css/selectors/focus-within-001.html [ Failure ] crbug.com/591099 external/wpt/css/selectors/focus-within-004.html [ Failure ] @@ -2269,7 +2264,7 @@ crbug.com/591099 external/wpt/svg/linking/reftests/href-filter-element.html [ Failure ] crbug.com/591099 external/wpt/uievents/order-of-events/focus-events/focus-manual.html [ Timeout ] crbug.com/714962 external/wpt/uievents/order-of-events/mouse-events/click-cancel.html [ Failure ] -crbug.com/591099 external/wpt/url/url-setters.html [ Timeout ] +crbug.com/591099 external/wpt/url/url-setters.html [ Pass Timeout ] crbug.com/591099 external/wpt/wasm/wasm_local_iframe_test.html [ Failure ] crbug.com/591099 external/wpt/webmessaging/broadcastchannel/sandbox.html [ Failure ] crbug.com/591099 external/wpt/webrtc/interfaces.html [ Pass Timeout ] @@ -3374,6 +3369,7 @@ crbug.com/714962 fast/forms/file/file-input-reset-validation.html [ Timeout ] crbug.com/714962 fast/forms/file/file-input-reset.html [ Failure ] crbug.com/591099 fast/forms/file/file-input-webkitdirectory-click.html [ Failure ] +crbug.com/591099 fast/forms/file/file-user-selection.html [ Timeout ] crbug.com/591099 fast/forms/file/get-file-upload.html [ Failure ] crbug.com/714962 fast/forms/file/input-file-entries.html [ Timeout ] crbug.com/714962 fast/forms/file/input-file-value-with-zoom.html [ Failure ] @@ -6641,7 +6637,7 @@ crbug.com/714962 svg/custom/width-full-percentage.svg [ Failure ] crbug.com/714962 svg/dom/SVGStringList-basics.xhtml [ Failure ] crbug.com/591099 svg/dom/svg-root-lengths.html [ Failure ] -crbug.com/591099 svg/dom/svgangle-units.html [ Timeout ] +crbug.com/591099 svg/dom/svgangle-units.html [ Pass Timeout ] crbug.com/591099 svg/dom/tooltip-title-inline-svg.html [ Failure ] crbug.com/714962 svg/dynamic-updates/SVG-dynamic-css-transform.html [ Failure ] crbug.com/714962 svg/dynamic-updates/SVGMaskElement-dom-height-attr.html [ Failure ]
diff --git a/third_party/WebKit/LayoutTests/FlagExpectations/enable-features=NetworkService b/third_party/WebKit/LayoutTests/FlagExpectations/enable-features=NetworkService index bf3d980..d4b65267 100644 --- a/third_party/WebKit/LayoutTests/FlagExpectations/enable-features=NetworkService +++ b/third_party/WebKit/LayoutTests/FlagExpectations/enable-features=NetworkService
@@ -25,6 +25,7 @@ Bug(none) external/wpt/service-workers/service-worker/client-navigate.https.html [ Pass Crash Failure ] Bug(none) external/wpt/service-workers/service-worker/clients-get-client-types.https.html [ Failure ] Bug(none) external/wpt/service-workers/service-worker/clients-get.https.html [ Failure ] +crbug.com/807271 external/wpt/service-workers/service-worker/fetch-canvas-tainting-video-cache.https.html [ Failure ] Bug(none) external/wpt/service-workers/service-worker/fetch-event-respond-with-response-body-with-invalid-chunk.https.html [ Failure ] Bug(none) external/wpt/service-workers/service-worker/fetch-frame-resource.https.html [ Pass Failure ] Bug(none) external/wpt/service-workers/service-worker/fetch-header-visibility.https.html [ Pass Failure Crash ]
diff --git a/third_party/WebKit/LayoutTests/FlagExpectations/root-layer-scrolls b/third_party/WebKit/LayoutTests/FlagExpectations/root-layer-scrolls index b5a93f6..40cf945f 100644 --- a/third_party/WebKit/LayoutTests/FlagExpectations/root-layer-scrolls +++ b/third_party/WebKit/LayoutTests/FlagExpectations/root-layer-scrolls
@@ -1,4 +1,5 @@ crbug.com/417782 compositing/iframes/become-composited-nested-iframes.html [ Failure ] +crbug.com/417782 [ Win ] compositing/masks/mask-layer-size.html [ Failure ] crbug.com/417782 compositing/overflow/border-radius-composited-subframe.html [ Failure ] crbug.com/417782 compositing/overflow/tiled-mask.html [ Failure ] crbug.com/417782 compositing/squashing/squash-above-fixed-1.html [ Failure ] @@ -26,6 +27,7 @@ crbug.com/417782 paint/invalidation/background/body-background-image.html [ Failure ] crbug.com/417782 paint/invalidation/background/viewport-gradient-background-html-move-overflow.html [ Failure ] crbug.com/417782 paint/invalidation/background/viewport-gradient-background-html-resize-overflow.html [ Failure ] +crbug.com/417782 [ Win ] paint/invalidation/clip/clip-path-constant-repaint.html [ Failure ] crbug.com/417782 paint/invalidation/compositing/iframe-inside-squashed-layer.html [ Failure ] crbug.com/417782 paint/invalidation/filters/filter-on-html-element-with-fixed-position-child.html [ Failure ] crbug.com/417782 [ Mac Win ] paint/invalidation/reflection/reflection-with-rotation.html [ Failure ]
diff --git a/third_party/WebKit/LayoutTests/TestExpectations b/third_party/WebKit/LayoutTests/TestExpectations index 8c6bbab..910c91c9 100644 --- a/third_party/WebKit/LayoutTests/TestExpectations +++ b/third_party/WebKit/LayoutTests/TestExpectations
@@ -1684,6 +1684,9 @@ # This test requires enabling the flag CustomUserTiming in a virtual test. crbug.com/758385 http/tests/performance-timing/custom-user-timing/po-customusertiming-mark.html [ Skip ] +# This test requires enabling the flag LongTaskV2 in a virtual test suite. +crbug.com/738493 http/tests/performance-timing/longtask-v2/longtask-v8compile.html [ Skip ] + # Expected failures during incremental implementation of mojo notification. crbug.com/595685 virtual/mojo-notifications/http/tests/notifications/close-dedicated-worker.html [ Skip ] crbug.com/595685 virtual/mojo-notifications/http/tests/notifications/close-dispatch-asynchronous.html [ Skip ] @@ -2528,7 +2531,7 @@ # Crashes crbug.com/709227 external/wpt/offscreen-canvas/fill-and-stroke-styles/2d.pattern.basic.nocontext.worker.html [ Crash ] -crbug.com/803943 [ Win ] external/wpt/html/syntax/parsing/html5lib_tests16.html?run_type=uri [ Pass Timeout ] +crbug.com/803943 [ Win Linux Mac ] external/wpt/html/syntax/parsing/html5lib_tests16.html?run_type=uri [ Pass Timeout ] # ====== Tests from enabling .any.js/.worker.js tests end here ======== @@ -3204,8 +3207,6 @@ crbug.com/774463 [ Win7 Debug ] virtual/mouseevent_fractional/fast/events/autoscroll-should-not-stop-on-keypress.html [ Failure Pass ] crbug.com/774688 [ Mac ] fast/spatial-navigation/snav-container-white-space.html [ Pass Failure ] -crbug.com/776201 [ Win7 Debug ] virtual/longtask-v2/http/tests/performance-timing/longtask-v2/longtask-v8compile.html [ Pass Failure ] - # Sheriff failures 2017-10-23 crbug.com/772411 http/tests/media/autoplay-crossorigin.html [ Timeout Failure Pass ] crbug.com/777222 http/tests/devtools/change-iframe-src.js [ Pass Failure Timeout ] @@ -3331,8 +3332,6 @@ crbug.com/802915 css3/blending/isolation-should-include-non-local-background.html [ Failure ] -crbug.com/807159 hittesting/inline-with-clip-path.html [ Pass Crash ] - # Sheriff faulures 2017-12-12 crbug.com/794180 http/tests/devtools/layers/layer-compositing-reasons.js [ Failure Pass ]
diff --git a/third_party/WebKit/LayoutTests/accessibility/name-calc-visibility.html b/third_party/WebKit/LayoutTests/accessibility/name-calc-visibility.html index feb59ed..f89f95a 100644 --- a/third_party/WebKit/LayoutTests/accessibility/name-calc-visibility.html +++ b/third_party/WebKit/LayoutTests/accessibility/name-calc-visibility.html
@@ -32,7 +32,7 @@ <div id="label2"> <p>1</p> - <table> + <table role="presentation"> <tr><td>2</td></tr> <tr><td style="visibility: hidden">3</td></tr> <tr><td style="display:none">4</td></tr>
diff --git a/third_party/WebKit/LayoutTests/accessibility/non-data-table-cell-title-ui-element.html b/third_party/WebKit/LayoutTests/accessibility/non-data-table-cell-title-ui-element.html index 8562ac8..a0924d2 100644 --- a/third_party/WebKit/LayoutTests/accessibility/non-data-table-cell-title-ui-element.html +++ b/third_party/WebKit/LayoutTests/accessibility/non-data-table-cell-title-ui-element.html
@@ -4,39 +4,39 @@ testRunner.dumpAsText(); </script> <body id="body"> - + <!-- This test makes sure that tables that are not exposed as tables do not have title ui elements incorrectly set --> <TABLE> <tbody><tr><td colspan="6"><h2>ATS</h2></td></tr> -<tr> -<th>pass</th> -<th>issue</th> -<th>fail</th> -<th>blocked</th> -<th>skip</th> -<th>test</th> +<tr tabindex="0" id="tr2"> +<td>pass</td> +<td>issue</td> +<td>fail</td> +<td>blocked</td> +<td>skip</td> +<td>test</td> </tr> </tbody> </tABLE> - + <div id="result"></div> - + <script> if (window.accessibilityController) { var result = document.getElementById("result"); - var pass = document.getElementById("body"); - body.focus(); - // get the <th>skip</th> element - var group = accessibilityController.focusedElement.childAtIndex(5); + var pass = document.getElementById("tr2"); + pass.focus(); + // get the <td>skip</td> element + var group = accessibilityController.focusedElement.childAtIndex(4); var titleUI = group.nameElementAtIndex(0); var allAttributes = ""; if (titleUI) allAttributes = titleUI.allAttributes(); - // verify it has no title ui element + // verify it has no title ui element if (!allAttributes) { result.innerText += "Test passed\n"; }
diff --git a/third_party/WebKit/LayoutTests/accessibility/presentation-owned-elements-expected.txt b/third_party/WebKit/LayoutTests/accessibility/presentation-owned-elements-expected.txt index 53a25a9c5..795abb78 100644 --- a/third_party/WebKit/LayoutTests/accessibility/presentation-owned-elements-expected.txt +++ b/third_party/WebKit/LayoutTests/accessibility/presentation-owned-elements-expected.txt
@@ -47,12 +47,15 @@ AXRole: AXGenericContainer AXRole: AXStaticText "These two tables have static text roles because they have presentation roles." AXRole: AXInlineTextBox "These two tables have static text roles because they have presentation roles." - AXRole: AXStaticText "Presentation th" - AXRole: AXInlineTextBox "Presentation th" - AXRole: AXStaticText "Presentation th" - AXRole: AXInlineTextBox "Presentation th" - AXRole: AXStaticText "Presentation th" - AXRole: AXInlineTextBox "Presentation th" + AXRole: AXGenericContainer + AXRole: AXStaticText "Presentation th" + AXRole: AXInlineTextBox "Presentation th" + AXRole: AXGenericContainer + AXRole: AXStaticText "Presentation th" + AXRole: AXInlineTextBox "Presentation th" + AXRole: AXGenericContainer + AXRole: AXStaticText "Presentation th" + AXRole: AXInlineTextBox "Presentation th" AXRole: AXGenericContainer AXRole: AXStaticText "The "Presentation th" has a static text role because it has a presentation role." AXRole: AXInlineTextBox "The "Presentation th" has a static text role because it has a presentation role." @@ -68,8 +71,9 @@ AXRole: AXGenericContainer AXRole: AXStaticText "Explicit th" AXRole: AXInlineTextBox "Explicit th" - AXRole: AXStaticText "Implicit td" - AXRole: AXInlineTextBox "Implicit td" + AXRole: AXGenericContainer + AXRole: AXStaticText "Implicit td" + AXRole: AXInlineTextBox "Implicit td" AXRole: AXGenericContainer AXRole: AXStaticText "The menu items except button have a static text role because it has a presentation role and is disabled." AXRole: AXInlineTextBox "The menu items except button have a static text role because it has a presentation role and is disabled."
diff --git a/third_party/WebKit/LayoutTests/accessibility/role-change.html b/third_party/WebKit/LayoutTests/accessibility/role-change.html index f8bc0d4..09738208 100644 --- a/third_party/WebKit/LayoutTests/accessibility/role-change.html +++ b/third_party/WebKit/LayoutTests/accessibility/role-change.html
@@ -46,7 +46,7 @@ test(function(t) { assert_equals(axElementById('table'), undefined); assert_equals(axElementById('tr1'), undefined); - assert_equals(axElementById('td1'), undefined); + assert_equals(axElementById('td1').role, "AXRole: AXGenericContainer"); // Change role="presentation" document.getElementById('table1').removeAttribute('role'); @@ -65,7 +65,7 @@ assert_equals(axElementById('table'), undefined); assert_equals(axElementById('tr1'), undefined); - assert_equals(axElementById('td1'), undefined); + assert_equals(axElementById('td1').role, "AXRole: AXGenericContainer"); }, "Role presentation toggled on table."); test(function(t) {
diff --git a/third_party/WebKit/LayoutTests/accessibility/table-detection-expected.txt b/third_party/WebKit/LayoutTests/accessibility/table-detection-expected.txt index a07eb84c..a4a252ff 100644 --- a/third_party/WebKit/LayoutTests/accessibility/table-detection-expected.txt +++ b/third_party/WebKit/LayoutTests/accessibility/table-detection-expected.txt
@@ -14,7 +14,7 @@ This should not be a table because its cells do not have borders. -AXRole: AXGenericContainer +AXRole: AXLayoutTable asdf asdf @@ -45,13 +45,13 @@ This should not be a table because cells have different but no spacing. -AXRole: AXGenericContainer +AXRole: AXLayoutTable asdf asdf This should not be a table because cells have the same colors even though there is spacing. -AXRole: AXGenericContainer +AXRole: AXLayoutTable asdf asdf @@ -63,13 +63,13 @@ This should not be a table because it only has one valid cell (need more than one). -AXRole: AXGenericContainer +AXRole: AXLayoutTable Contributions This should not be a table because it does not have enough cell borders or background colors -AXRole: AXGenericContainer +AXRole: AXLayoutTable Politics Decision '08 @@ -94,7 +94,7 @@ This should not be a table because cells have different borders. -AXRole: AXGenericContainer +AXRole: AXLayoutTable asdf asdf asdf asdf
diff --git a/third_party/WebKit/LayoutTests/accessibility/table-one-cell-expected.txt b/third_party/WebKit/LayoutTests/accessibility/table-one-cell-expected.txt index fb9f9f2c..120cd4f1 100644 --- a/third_party/WebKit/LayoutTests/accessibility/table-one-cell-expected.txt +++ b/third_party/WebKit/LayoutTests/accessibility/table-one-cell-expected.txt
@@ -2,4 +2,4 @@ Get specific content for your area. http://web.apple.com -AXRole: AXParagraph +AXRole: AXLayoutTable
diff --git a/third_party/WebKit/LayoutTests/accessibility/table-with-presentation-role.html b/third_party/WebKit/LayoutTests/accessibility/table-with-presentation-role.html index a8b59dd..43a1f80 100644 --- a/third_party/WebKit/LayoutTests/accessibility/table-with-presentation-role.html +++ b/third_party/WebKit/LayoutTests/accessibility/table-with-presentation-role.html
@@ -15,12 +15,16 @@ <script> test(() => { - var axContainer = accessibilityController.accessibleElementById('container'); - assert_equals(axContainer.childrenCount, 4); - var axText1 = axContainer.childAtIndex(0); + var axTableContainer = accessibilityController.accessibleElementById('container'); + assert_equals(axTableContainer.childrenCount, 4); + var axTextContainer1 = axTableContainer.childAtIndex(0); + assert_equals(axTextContainer1.role, "AXRole: AXGenericContainer"); + var axText1 = axTextContainer1.childAtIndex(0); assert_equals(axText1.role, "AXRole: AXStaticText"); assert_equals(axText1.name, "A"); - var axText2 = axContainer.childAtIndex(1); + var axTextContainer2 = axTableContainer.childAtIndex(1); + assert_equals(axTextContainer2.role, "AXRole: AXGenericContainer"); + var axText2 = axTextContainer2.childAtIndex(0); assert_equals(axText2.role, "AXRole: AXStaticText"); assert_equals(axText2.name, "B"); }, "ARIA presentation role on table element has no rows or cells.");
diff --git a/third_party/WebKit/LayoutTests/accessibility/table-with-rules-expected.txt b/third_party/WebKit/LayoutTests/accessibility/table-with-rules-expected.txt index b347946..36cca5c4 100644 --- a/third_party/WebKit/LayoutTests/accessibility/table-with-rules-expected.txt +++ b/third_party/WebKit/LayoutTests/accessibility/table-with-rules-expected.txt
@@ -15,9 +15,9 @@ AXRole: AXTable -AXRole: AXGenericContainer +AXRole: AXTable -AXRole: AXGenericContainer +AXRole: AXLayoutTable
diff --git a/third_party/WebKit/LayoutTests/accessibility/table-with-rules.html b/third_party/WebKit/LayoutTests/accessibility/table-with-rules.html index 4fd86c0c..2d89383b 100644 --- a/third_party/WebKit/LayoutTests/accessibility/table-with-rules.html +++ b/third_party/WebKit/LayoutTests/accessibility/table-with-rules.html
@@ -4,28 +4,28 @@ testRunner.dumpAsText(); </script> <body id="body"> - + <table id="testTable1" rules="rows"><tr><td>asdf</td><td>asdf</td></tr></table> <table id="testTable2" rules="all"><tr><td>asdf</td><td>asdf</td></tr></table> <table id="testTable3" rules="col"><tr><td>asdf</td><td>asdf</td></tr></table> <table id="testTable4" rules="groups"><tr><td>asdf</td><td>asdf</td></tr></table> <table id="testTable5"><tr><td>asdf</td><td>asdf</td></tr></table> - + <BR>------------------------------------<BR> - + <div id="result"></div> - + <script> if (window.accessibilityController) { var result = document.getElementById("result"); var body = document.getElementById("body"); body.focus(); - + // these should be the tables. in this order - // the last two tables should not show up as tables - for (var k = 1; k < 6; k++) { + // the last table should not show up as a table. + for (var k = 0; k < 5; k++) { var table = accessibilityController.focusedElement.childAtIndex(k); - result.innerText += table.allAttributes() + "\n\n"; + result.innerText += table.allAttributes() + "\n\n"; } } </script>
diff --git a/third_party/WebKit/LayoutTests/bluetooth/characteristic/service-same-from-2-characteristics.html b/third_party/WebKit/LayoutTests/bluetooth/characteristic/service-same-from-2-characteristics.html index db5dabc..36669dd 100644 --- a/third_party/WebKit/LayoutTests/bluetooth/characteristic/service-same-from-2-characteristics.html +++ b/third_party/WebKit/LayoutTests/bluetooth/characteristic/service-same-from-2-characteristics.html
@@ -3,7 +3,6 @@ <script src="../../resources/testharnessreport.js"></script> <script src="../../resources/testdriver.js"></script> <script src="../../resources/testdriver-vendor.js"></script> -<script src="../../resources/bluetooth/bluetooth-helpers.js"></script> <script src="../../external/wpt/bluetooth/resources/bluetooth-helpers.js"></script> <script> 'use strict';
diff --git a/third_party/WebKit/LayoutTests/bluetooth/characteristic/service-same-object.html b/third_party/WebKit/LayoutTests/bluetooth/characteristic/service-same-object.html index 13f6c24..bf87c87 100644 --- a/third_party/WebKit/LayoutTests/bluetooth/characteristic/service-same-object.html +++ b/third_party/WebKit/LayoutTests/bluetooth/characteristic/service-same-object.html
@@ -3,7 +3,6 @@ <script src="../../resources/testharnessreport.js"></script> <script src="../../resources/testdriver.js"></script> <script src="../../resources/testdriver-vendor.js"></script> -<script src="../../resources/bluetooth/bluetooth-helpers.js"></script> <script src="../../external/wpt/bluetooth/resources/bluetooth-helpers.js"></script> <script> 'use strict';
diff --git a/third_party/WebKit/LayoutTests/bluetooth/descriptor/readValue/read-succeeds.html b/third_party/WebKit/LayoutTests/bluetooth/descriptor/readValue/read-succeeds.html index 9c19271..0965c89 100644 --- a/third_party/WebKit/LayoutTests/bluetooth/descriptor/readValue/read-succeeds.html +++ b/third_party/WebKit/LayoutTests/bluetooth/descriptor/readValue/read-succeeds.html
@@ -6,16 +6,16 @@ <script src="../../../external/wpt/bluetooth/resources/bluetooth-helpers.js"></script> <script> 'use strict'; -bluetooth_test(() => { - const EXPECTED_VALUE = [0, 1, 2]; - return getUserDescriptionDescriptor() - .then(({descriptor, fake_descriptor}) => { - return fake_descriptor.setNextReadResponse(GATT_SUCCESS, EXPECTED_VALUE) - .then(() => descriptor.readValue()) - .then(value => { - assert_array_equals(Array.from(new Uint8Array( - value.buffer)), EXPECTED_VALUE); - }); - }); -}, 'A read request succeeds and returns the descriptor\'s value.'); +const test_desc = 'A read request succeeds and returns the descriptor\'s value.'; +const EXPECTED_VALUE = [0, 1, 2]; +let descriptor, fake_descriptor; + +bluetooth_test(() => getUserDescriptionDescriptor() + .then(_ => ({descriptor, fake_descriptor} = _)) + .then(() => + fake_descriptor.setNextReadResponse(GATT_SUCCESS, EXPECTED_VALUE)) + .then(() => descriptor.readValue()) + .then(value => assert_array_equals(Array.from(new Uint8Array( + value.buffer)), EXPECTED_VALUE)), + test_desc); </script>
diff --git a/third_party/WebKit/LayoutTests/bluetooth/device/gattserverdisconnected-event/disconnected.html b/third_party/WebKit/LayoutTests/bluetooth/device/gattserverdisconnected-event/disconnected.html index 802c458..bab7b67 100644 --- a/third_party/WebKit/LayoutTests/bluetooth/device/gattserverdisconnected-event/disconnected.html +++ b/third_party/WebKit/LayoutTests/bluetooth/device/gattserverdisconnected-event/disconnected.html
@@ -6,14 +6,14 @@ <script src="../../../external/wpt/bluetooth/resources/bluetooth-helpers.js"></script> <script> 'use strict'; -let test_desc = 'A device disconnecting while connected should fire the ' + +const test_desc = 'A device disconnecting while connected should fire the ' + 'gattserverdisconnected event.'; -let device, fake_peripheral; + bluetooth_test(() => getHealthThermometerDevice() - .then(_ => ({device, fake_peripheral} = _)) - .then(() => { + .then(({device, fake_peripheral}) => { fake_peripheral.simulateGATTDisconnection(); return eventPromise(device, 'gattserverdisconnected'); }) - .then(e => assert_true(e.bubbles)), test_desc); + .then(e => assert_true(e.bubbles)), + test_desc); </script>
diff --git a/third_party/WebKit/LayoutTests/bluetooth/device/gattserverdisconnected-event/disconnected_gc.html b/third_party/WebKit/LayoutTests/bluetooth/device/gattserverdisconnected-event/disconnected_gc.html index 97b30bd..846bb78 100644 --- a/third_party/WebKit/LayoutTests/bluetooth/device/gattserverdisconnected-event/disconnected_gc.html +++ b/third_party/WebKit/LayoutTests/bluetooth/device/gattserverdisconnected-event/disconnected_gc.html
@@ -6,12 +6,11 @@ <script src="../../../external/wpt/bluetooth/resources/bluetooth-helpers.js"></script> <script> 'use strict'; -let test_desc = 'A device disconnecting after the BluetoothDevice object has ' + - 'been gced should not access freed memory.'; -let fake_peripheral; +const test_desc = 'A device disconnecting after the BluetoothDevice object ' + + 'has been GC\'ed should not access freed memory.'; + bluetooth_test(() => getHealthThermometerDevice() - .then(_ => ({fake_peripheral} = _)) - .then(() => { + .then(({fake_peripheral}) => { // 1. Disconnect. fake_peripheral.simulateGATTDisconnection(); // 2. Run garbage collection. @@ -20,5 +19,6 @@ }) // 3. Wait 50ms after the GC runs for the disconnection event to come back. // There's nothing to assert other than that only valid memory is used. - .then(() => new Promise(resolve => step_timeout(resolve, 50))), test_desc); + .then(() => new Promise(resolve => step_timeout(resolve, 50))), + test_desc); </script>
diff --git a/third_party/WebKit/LayoutTests/bluetooth/device/gattserverdisconnected-event/one-event-per-disconnection.html b/third_party/WebKit/LayoutTests/bluetooth/device/gattserverdisconnected-event/one-event-per-disconnection.html index f6d6ad2d..4e310fe1 100644 --- a/third_party/WebKit/LayoutTests/bluetooth/device/gattserverdisconnected-event/one-event-per-disconnection.html +++ b/third_party/WebKit/LayoutTests/bluetooth/device/gattserverdisconnected-event/one-event-per-disconnection.html
@@ -6,16 +6,17 @@ <script src="../../../external/wpt/bluetooth/resources/bluetooth-helpers.js"></script> <script> 'use strict'; -let test_desc = 'If a site disconnects from a device while the platform is ' + +const test_desc = 'If a site disconnects from a device while the platform is ' + 'disconnecting that device, only one gattserverdisconnected event should ' + 'fire.'; let device, fake_peripheral; let num_events = 0; + bluetooth_test(() => getHealthThermometerDevice() .then(_ => ({device, fake_peripheral} = _)) // 1. Listen for disconnections. .then(() => - device.addEventListener('gattserverdisconnected', () => num_events++)) + device.addEventListener('gattserverdisconnected', () => num_events++)) // 2. Disconnect several times. .then(() => Promise.all([ eventPromise(device, 'gattserverdisconnected'), @@ -26,5 +27,6 @@ // 3. Wait to catch disconnect events. .then(() => new Promise(resolve => step_timeout(resolve, 50))) // 4. Ensure there is exactly 1 disconnection recorded. - .then(() => assert_equals(num_events, 1)), test_desc); + .then(() => assert_equals(num_events, 1)), + test_desc); </script>
diff --git a/third_party/WebKit/LayoutTests/bluetooth/idl/idl-BluetoothDevice.html b/third_party/WebKit/LayoutTests/bluetooth/idl/idl-BluetoothDevice.html index e8058a67..b1713dc 100644 --- a/third_party/WebKit/LayoutTests/bluetooth/idl/idl-BluetoothDevice.html +++ b/third_party/WebKit/LayoutTests/bluetooth/idl/idl-BluetoothDevice.html
@@ -3,11 +3,11 @@ <script src="../../resources/testharnessreport.js"></script> <script src="../../resources/testdriver.js"></script> <script src="../../resources/testdriver-vendor.js"></script> -<script src="../../resources/bluetooth/bluetooth-helpers.js"></script> <script src="../../external/wpt/bluetooth/resources/bluetooth-helpers.js"></script> <script> 'use strict'; const test_desc_idl = 'BluetoothDevice IDL test.'; + test(() => { assert_throws(new TypeError(), () => new BluetoothDevice(), 'the constructor should not be callable with "new"'); @@ -18,15 +18,14 @@ const test_desc_attr = 'BluetoothDevice attributes.'; let device; bluetooth_test(() => getHealthThermometerDevice() - .then(_ => ({device} = _)) - .then(() => { + .then(({device}) => { assert_equals(device.constructor.name, 'BluetoothDevice'); var old_device_id = device.id; assert_throws(new TypeError(), () => device.id = 'overwritten', - 'the device id should not be writable'); + 'the device id should not be writable'); assert_throws(new TypeError(), () => device.name = 'overwritten', - 'the device name should not be writable'); + 'the device name should not be writable'); assert_equals(device.id, old_device_id); assert_equals(device.name, 'Health Thermometer'); - }), test_desc_attr); + }), test_desc_attr); </script>
diff --git a/third_party/WebKit/LayoutTests/bluetooth/service/device-same-from-2-services.html b/third_party/WebKit/LayoutTests/bluetooth/service/device-same-from-2-services.html index ad5991b..bb024d8 100644 --- a/third_party/WebKit/LayoutTests/bluetooth/service/device-same-from-2-services.html +++ b/third_party/WebKit/LayoutTests/bluetooth/service/device-same-from-2-services.html
@@ -3,16 +3,16 @@ <script src="../../resources/testharnessreport.js"></script> <script src="../../resources/testdriver.js"></script> <script src="../../resources/testdriver-vendor.js"></script> -<script src="../../resources/bluetooth/bluetooth-helpers.js"></script> <script src="../../external/wpt/bluetooth/resources/bluetooth-helpers.js"></script> <script> 'use strict'; -bluetooth_test(() => { - return getTwoHealthThermometerServicesDevice({ - filters: [{services: ['health_thermometer']}]}) +const test_desc = 'Same parent device returned from multiple services.'; + +bluetooth_test(() => getTwoHealthThermometerServicesDevice({ + filters: [{services: ['health_thermometer']}] +}) .then(({device}) => device.gatt.getPrimaryServices('health_thermometer')) - .then(([service1, service2]) => { - assert_equals(service1.device, service2.device); - }); -}, "Same parent device returned from multiple services."); + .then(([service1, service2]) => + assert_equals(service1.device, service2.device)), + test_desc); </script>
diff --git a/third_party/WebKit/LayoutTests/bluetooth/service/device-same-object.html b/third_party/WebKit/LayoutTests/bluetooth/service/device-same-object.html index 62ebece..1f919c7 100644 --- a/third_party/WebKit/LayoutTests/bluetooth/service/device-same-object.html +++ b/third_party/WebKit/LayoutTests/bluetooth/service/device-same-object.html
@@ -3,16 +3,15 @@ <script src="../../resources/testharnessreport.js"></script> <script src="../../resources/testdriver.js"></script> <script src="../../resources/testdriver-vendor.js"></script> -<script src="../../resources/bluetooth/bluetooth-helpers.js"></script> <script src="../../external/wpt/bluetooth/resources/bluetooth-helpers.js"></script> <script> 'use strict'; -bluetooth_test(() => { - return getHealthThermometerDevice({ - filters: [{services: ['health_thermometer']}]}) +const test_desc = '[SameObject] test for BluetoothRemoteGATTService device.'; + +bluetooth_test(() => getHealthThermometerDevice({ + filters: [{services: ['health_thermometer']}] +}) .then(({device}) => device.gatt.getPrimaryService('health_thermometer')) - .then(service => { - assert_equals(service.device, service.device); - }); -}, "[SameObject] test for BluetoothRemoteGATTService's device."); + .then(service => assert_equals(service.device, service.device)), + test_desc); </script>
diff --git a/third_party/WebKit/LayoutTests/css3/flexbox/flexbox-width-with-overflow-auto.html b/third_party/WebKit/LayoutTests/css3/flexbox/flexbox-width-with-overflow-auto.html new file mode 100644 index 0000000..b607fdd --- /dev/null +++ b/third_party/WebKit/LayoutTests/css3/flexbox/flexbox-width-with-overflow-auto.html
@@ -0,0 +1,30 @@ +<!DOCTYPE html> +<html> +<link href="resources/flexbox.css" rel="stylesheet"> +<style> +.flexbox { + border: 5px solid green; + position: relative; + height: 50px; + display: inline-flex; +} + +.overflow { + border: 1px solid red; + overflow: auto; + min-width: 0; + min-height: 0; +} +</style> +<script src="../../resources/testharness.js"></script> +<script src="../../resources/testharnessreport.js"></script> +<script src="../../resources/check-layout-th.js"></script> +<body onload="checkLayout('.flexbox')"> +<div id=log></div> +<div id=target class="flexbox" data-expected-width="47"> + <div class="overflow"> + <div style="height: 100px; width: 20px"></div> + </div> +</div> +</body> +</html>
diff --git a/third_party/WebKit/LayoutTests/editing/deleting/smart-delete-across-editable-boundaries-expected.txt b/third_party/WebKit/LayoutTests/editing/deleting/smart-delete-across-editable-boundaries-expected.txt deleted file mode 100644 index 4354f6e4..0000000 --- a/third_party/WebKit/LayoutTests/editing/deleting/smart-delete-across-editable-boundaries-expected.txt +++ /dev/null
@@ -1,4 +0,0 @@ -This tests for a bug where expansion for smart delete would not consider editable boundaries. Only 'foo' should be deleted. You should see ' bar'. <radr://problem/5390681> -| <span> -| contenteditable="false" -| " bar"
diff --git a/third_party/WebKit/LayoutTests/editing/deleting/smart-delete-across-editable-boundaries.html b/third_party/WebKit/LayoutTests/editing/deleting/smart-delete-across-editable-boundaries.html index 949418a..9992f13 100644 --- a/third_party/WebKit/LayoutTests/editing/deleting/smart-delete-across-editable-boundaries.html +++ b/third_party/WebKit/LayoutTests/editing/deleting/smart-delete-across-editable-boundaries.html
@@ -1,18 +1,14 @@ -<!DOCTYPE html> -<html> -<body> -<script src="../../resources/dump-as-markup.js"></script> -<div contenteditable="true" id="div">foo<span contenteditable="false"> bar</span></div> +<!doctype html> +<script src="../../resources/testharness.js"></script> +<script src="../../resources/testharnessreport.js"></script> +<script src="../assert_selection.js"></script> <script> -if (window.internals) - internals.settings.setEditingBehavior('mac'); -var div = document.getElementById("div"); -var sel = window.getSelection(); -sel.collapse(div, 0); -sel.modify("extend", "forward", "word"); -document.execCommand("Delete"); -Markup.description("This tests for a bug where expansion for smart delete would not consider editable boundaries. Only 'foo' should be deleted. You should see ' bar'. <radr://problem/5390681>"); -Markup.dump(div); +// This tests for a bug where expansion for smart delete would not consider +// editable boundaries. Only 'foo' should be deleted. You should see ' bar'. +// <radr://problem/5390681> +selection_test( + '<div contenteditable>^foo|<span contenteditable="false"> bar</span></div>', + 'delete', + '<div contenteditable>|<span contenteditable="false"> bar</span></div>', + 'Delete should consider editable boundaries'); </script> -</body> -</html>
diff --git a/third_party/WebKit/LayoutTests/editing/pasteboard/5032095.html b/third_party/WebKit/LayoutTests/editing/pasteboard/5032095.html index ed215cf..5bb5827 100644 --- a/third_party/WebKit/LayoutTests/editing/pasteboard/5032095.html +++ b/third_party/WebKit/LayoutTests/editing/pasteboard/5032095.html
@@ -1,10 +1,13 @@ -<p>This tests for a bug where content pasted at the end of a paragraph would be inserted into the next paragraph. You should see 'helloworld' below.</p> -<div id="div" contenteditable="true">hello</div> - +<!doctype html> +<script src="../../resources/testharness.js"></script> +<script src="../../resources/testharnessreport.js"></script> +<script src="../assert_selection.js"></script> <script> -var div = document.getElementById("div"); -var sel = window.getSelection(); -sel.collapse(div, 0); -sel.modify("move", "forward", "word"); -document.execCommand("InsertHTML", false, "<span><div>world</div></span>"); +// This tests for a bug where content pasted at the end of a paragraph would be +// inserted into the next paragraph. You should see 'helloworld' below. +selection_test( + '<div contenteditable>hello|</div>', + 'InsertHTML <span><div>world</div></span>', + '<div contenteditable>helloworld|</div>', + 'InsertHTML at end of a paragraph'); </script>
diff --git a/third_party/WebKit/LayoutTests/editing/selection/modify_extend/extend-by-word-001.html b/third_party/WebKit/LayoutTests/editing/selection/modify_extend/extend-by-word-001.html index 305d30f..29d8cf9 100644 --- a/third_party/WebKit/LayoutTests/editing/selection/modify_extend/extend-by-word-001.html +++ b/third_party/WebKit/LayoutTests/editing/selection/modify_extend/extend-by-word-001.html
@@ -1,25 +1,19 @@ <!DOCTYPE html> <script src="../../../resources/testharness.js"></script> <script src="../../../resources/testharnessreport.js"></script> -<body> -<div contenteditable id="root" class="editing"> -<div id="span">foo<span style="white-space:pre"> </span>bar</div> -</div> -<div id="log"></div> - +<script src="../../assert_selection.js"></script> <script> -test(function () { - var selection = getSelection(); - selection.collapse(span.firstChild, 0); - for (i = 0; i < 4; i++) { - selection.modify("move", "forward", "character"); - } - selection.modify("extend", "forward", "word"); - assert_equals(selection.anchorNode, span.childNodes[2]); - assert_equals(selection.anchorOffset, 0); - assert_equals(selection.focusNode, span.childNodes[2]); - assert_equals(selection.focusOffset, 3); -}); +selection_test( + [ + '<div contenteditable>', + '<div>foo<span style="white-space:pre">\t|</span>bar</div>', + '</div>', + ], + selection => selection.modify('extend', 'forward', 'word'), + [ + '<div contenteditable>', + '<div>foo<span style="white-space:pre">\t</span>^bar|</div>', + '</div>', + ], + 'Extend word from after TAB character'); </script> - -</body>
diff --git a/third_party/WebKit/LayoutTests/editing/selection/move-by-word-001.html b/third_party/WebKit/LayoutTests/editing/selection/move-by-word-001.html index 49348fc..58fed66 100644 --- a/third_party/WebKit/LayoutTests/editing/selection/move-by-word-001.html +++ b/third_party/WebKit/LayoutTests/editing/selection/move-by-word-001.html
@@ -1,45 +1,26 @@ -<html> -<head> - -<style> -.editing { - border: 2px solid red; - padding: 12px; - font-size: 24px; -} -.cell { - padding: 12px; - font-size: 24px; - height: 48px; -} -</style> -<script src=../editing.js language="JavaScript" type="text/JavaScript" ></script> - +<!doctype html> +<script src="../../resources/testharness.js"></script> +<script src="../../resources/testharnessreport.js"></script> +<script src="../assert_selection.js"></script> <script> +// Specifically checks test case in bug: <rdar://problem/3917929> REGRESSION +// (Mail): Command-left-arrow leaves insertion point too high after specific +// steps +selection_test( + '<div contenteditable><div>|foo</div>bar</div>', + selection => selection.modify('move', 'forward', 'word'), + '<div contenteditable><div>foo|</div>bar</div>', + 'Move forward word 1'); -function editingTest() { - for (i = 0; i < 6; i++) - moveSelectionForwardByWordCommand(); - extendSelectionBackwardByWordCommand(); -} +selection_test( + '<div contenteditable><div>foo|</div>bar</div>', + selection => selection.modify('move', 'forward', 'word'), + '<div contenteditable><div>foo</div>bar|</div>', + 'Move forward word 2'); +selection_test( + '<div contenteditable><div>foo</div>bar|</div>', + selection => selection.modify('extend', 'backward', 'word'), + '<div contenteditable><div>foo</div>|bar^</div>', + 'Extend backward word'); </script> - -<title>Editing Test</title> -</head> -<body> -<div contenteditable id="root" class="editing"> -<div id="test">foo</div>bar -</div> - -<!-- - Specifically checks test case in bug: - <rdar://problem/3917929> REGRESSION (Mail): Command-left-arrow leaves insertion point too high after specific steps ---> - -<script> -runEditingTest(); -</script> - -</body> -</html>
diff --git a/third_party/WebKit/LayoutTests/editing/selection/thai-word-at-document-end.html b/third_party/WebKit/LayoutTests/editing/selection/thai-word-at-document-end.html index 42e1671..b70a084 100644 --- a/third_party/WebKit/LayoutTests/editing/selection/thai-word-at-document-end.html +++ b/third_party/WebKit/LayoutTests/editing/selection/thai-word-at-document-end.html Binary files differ
diff --git a/third_party/WebKit/LayoutTests/external/WPT_BASE_MANIFEST.json b/third_party/WebKit/LayoutTests/external/WPT_BASE_MANIFEST.json index ae8b41a..68d752c 100644 --- a/third_party/WebKit/LayoutTests/external/WPT_BASE_MANIFEST.json +++ b/third_party/WebKit/LayoutTests/external/WPT_BASE_MANIFEST.json
@@ -94116,6 +94116,11 @@ {} ] ], + "content-security-policy/reporting-api/reporting-api-works-on-frame-src.https.sub.html.sub.headers": [ + [ + {} + ] + ], "content-security-policy/reporting/multiple-report-policies.html.sub.headers": [ [ {} @@ -139271,11 +139276,6 @@ {} ] ], - "html/semantics/forms/the-input-element/radio-expected.txt": [ - [ - {} - ] - ], "html/semantics/forms/the-input-element/range-expected.txt": [ [ {} @@ -148871,6 +148871,16 @@ {} ] ], + "service-workers/service-worker/fetch-canvas-tainting-video-cache.https-expected.txt": [ + [ + {} + ] + ], + "service-workers/service-worker/fetch-canvas-tainting-video.https-expected.txt": [ + [ + {} + ] + ], "service-workers/service-worker/fetch-event-redirect.https-expected.txt": [ [ {} @@ -167303,6 +167313,12 @@ {} ] ], + "content-security-policy/reporting-api/reporting-api-works-on-frame-src.https.sub.html": [ + [ + "/content-security-policy/reporting-api/reporting-api-works-on-frame-src.https.sub.html", + {} + ] + ], "content-security-policy/reporting/multiple-report-policies.html": [ [ "/content-security-policy/reporting/multiple-report-policies.html", @@ -173447,9 +173463,9 @@ {} ] ], - "css/css-typed-om/stylevalue-subclasses/cssRotation.tentative.html": [ + "css/css-typed-om/stylevalue-subclasses/cssRotate.tentative.html": [ [ - "/css/css-typed-om/stylevalue-subclasses/cssRotation.tentative.html", + "/css/css-typed-om/stylevalue-subclasses/cssRotate.tentative.html", {} ] ], @@ -173471,9 +173487,9 @@ {} ] ], - "css/css-typed-om/stylevalue-subclasses/cssTranslation.tentative.html": [ + "css/css-typed-om/stylevalue-subclasses/cssTranslate.tentative.html": [ [ - "/css/css-typed-om/stylevalue-subclasses/cssTranslation.tentative.html", + "/css/css-typed-om/stylevalue-subclasses/cssTranslate.tentative.html", {} ] ], @@ -175715,6 +175731,12 @@ {} ] ], + "custom-elements/Document-createElementNS.html": [ + [ + "/custom-elements/Document-createElementNS.html", + {} + ] + ], "custom-elements/HTMLElement-constructor.html": [ [ "/custom-elements/HTMLElement-constructor.html", @@ -214925,15 +214947,27 @@ {} ] ], - "service-workers/service-worker/fetch-canvas-tainting-cache.https.html": [ + "service-workers/service-worker/fetch-canvas-tainting-image-cache.https.html": [ [ - "/service-workers/service-worker/fetch-canvas-tainting-cache.https.html", + "/service-workers/service-worker/fetch-canvas-tainting-image-cache.https.html", {} ] ], - "service-workers/service-worker/fetch-canvas-tainting.https.html": [ + "service-workers/service-worker/fetch-canvas-tainting-image.https.html": [ [ - "/service-workers/service-worker/fetch-canvas-tainting.https.html", + "/service-workers/service-worker/fetch-canvas-tainting-image.https.html", + {} + ] + ], + "service-workers/service-worker/fetch-canvas-tainting-video-cache.https.html": [ + [ + "/service-workers/service-worker/fetch-canvas-tainting-video-cache.https.html", + {} + ] + ], + "service-workers/service-worker/fetch-canvas-tainting-video.https.html": [ + [ + "/service-workers/service-worker/fetch-canvas-tainting-video.https.html", {} ] ], @@ -215919,12 +215953,6 @@ {} ] ], - "shadow-dom/untriaged/elements-and-dom-objects/extensions-to-event-interface/event-path-001.html": [ - [ - "/shadow-dom/untriaged/elements-and-dom-objects/extensions-to-event-interface/event-path-001.html", - {} - ] - ], "shadow-dom/untriaged/elements-and-dom-objects/shadowroot-object/shadowroot-attributes/activeElement-confirm-return-null.html": [ [ "/shadow-dom/untriaged/elements-and-dom-objects/shadowroot-object/shadowroot-attributes/activeElement-confirm-return-null.html", @@ -239689,7 +239717,7 @@ "testharness" ], "content-security-policy/embedded-enforcement/required_csp-header.html": [ - "9c06eea69babc70158e7bf25fad5d79a7367403e", + "b5c68072adf79a87b1371c34a9357a1507d6d981", "testharness" ], "content-security-policy/embedded-enforcement/subsumption_algorithm-general.html": [ @@ -240500,6 +240528,14 @@ "515b0d940eeb19ae13da605a95039442a5893239", "support" ], + "content-security-policy/reporting-api/reporting-api-works-on-frame-src.https.sub.html": [ + "1475964f0393ad3833c0024153236e5480ee33fd", + "testharness" + ], + "content-security-policy/reporting-api/reporting-api-works-on-frame-src.https.sub.html.sub.headers": [ + "f48e0c655e1dcc688c1f66309cdd61ba5aaefb74", + "support" + ], "content-security-policy/reporting/multiple-report-policies.html": [ "f639d91d9603d3f69e76e0e674502c3377feac1e", "testharness" @@ -287265,7 +287301,7 @@ "support" ], "css/css-typed-om/resources/testhelper.js": [ - "f06d685311e05da81ae332326863211c0230c519", + "275f59ac6a15d54a73293b17edd2c6363ec22ad0", "support" ], "css/css-typed-om/styleMap-update-function.html": [ @@ -287297,7 +287333,7 @@ "testharness" ], "css/css-typed-om/stylevalue-normalization/transformvalue-normalization.tentative.html": [ - "3a5ea9eef361accde1e0166d9defa186bae5c602", + "1b1af8a14ed0a1751ef3899e574e263c842440fd", "testharness" ], "css/css-typed-om/stylevalue-objects/interface.html": [ @@ -287337,7 +287373,7 @@ "testharness" ], "css/css-typed-om/stylevalue-serialization/cssTransformValue.tentative.html": [ - "d255d5d406d5620d4ed1cdd2979c7dc720475399", + "fdc7e5f43de941a0d79b0c4c13ae515038e028d1", "testharness" ], "css/css-typed-om/stylevalue-serialization/cssUnitValue.tentative.html": [ @@ -287380,8 +287416,8 @@ "445aa6e5e61d34add060b6870891309bf9e7f71f", "testharness" ], - "css/css-typed-om/stylevalue-subclasses/cssRotation.tentative.html": [ - "e96dd183a70beaae8ce9a24d35ac36362fff13b5", + "css/css-typed-om/stylevalue-subclasses/cssRotate.tentative.html": [ + "c4762f3f138145cbcc8af32d70c08088d0c0cfc2", "testharness" ], "css/css-typed-om/stylevalue-subclasses/cssScale.tentative.html": [ @@ -287393,11 +287429,11 @@ "testharness" ], "css/css-typed-om/stylevalue-subclasses/cssTransformValue.tentative.html": [ - "4dbec3e781758e19b3a7befb9cef8dfd396ae2fb", + "c1ee0153bd654f64b64f74bf00b6b0709c7cb9ed", "testharness" ], - "css/css-typed-om/stylevalue-subclasses/cssTranslation.tentative.html": [ - "87faf447cd03773e35eb52df213898d0ab765d01", + "css/css-typed-om/stylevalue-subclasses/cssTranslate.tentative.html": [ + "700fae462f258404f3d0b8fad290613fc1929e1d", "testharness" ], "css/css-typed-om/stylevalue-subclasses/cssUnparsedValue.tentative.html": [ @@ -287437,7 +287473,7 @@ "testharness" ], "css/css-typed-om/stylevalue-subclasses/numeric-objects/cssMathValue.tentative.html": [ - "e2779a78b3bdfd83911bede7cba2a88bb589b80d", + "e19ec7ede86d52ecf29a142607de481facabcfb2", "testharness" ], "css/css-typed-om/stylevalue-subclasses/numeric-objects/cssUnitValue.tentative-expected.txt": [ @@ -297277,7 +297313,7 @@ "testharness" ], "css/cssom/MediaList.html": [ - "f44ce7ec837ace7d4a2184b9ef73b462f7999aad", + "784bc428e8e65a0784dcf89c6e3e27305781cc72", "testharness" ], "css/cssom/MediaList2.xhtml": [ @@ -302708,6 +302744,10 @@ "14960ee9498f6ff23c1c94d3351a8ef383e60067", "testharness" ], + "custom-elements/Document-createElementNS.html": [ + "04cd97839e98c6082f67740dbcfc7588e2b251b9", + "testharness" + ], "custom-elements/HTMLElement-constructor.html": [ "64522527ef425b90c704b20b000c8feef0d1ca25", "testharness" @@ -309289,7 +309329,7 @@ "support" ], "graphics-aam/graphics-document_on_html_element-manual.html": [ - "199638ab8b60fd4c795adfb1ef6eae22a36e6fc6", + "933fcb47c29bb5e119326147266457231dabf810", "manual" ], "graphics-aam/graphics-document_on_svg_element-manual-expected.txt": [ @@ -309305,7 +309345,7 @@ "support" ], "graphics-aam/graphics-object_on_html_element-manual.html": [ - "7529fffa48b2f0ef3cad4860ce6c3cbf8d05602a", + "5fef647bd9e1cfed38467ca790b8796ef9d58bbe", "manual" ], "graphics-aam/graphics-object_on_svg_element-manual-expected.txt": [ @@ -309321,7 +309361,7 @@ "support" ], "graphics-aam/graphics-symbol_on_html_element-manual.html": [ - "1139a213f51ace79293632e5bd928c961c863711", + "be301a3a71514708c547fa033eab0271367a3fb9", "manual" ], "graphics-aam/graphics-symbol_on_svg_element-manual-expected.txt": [ @@ -323568,10 +323608,6 @@ "b8c2314d0883a385de40e5655a72a8f1953f2308", "testharness" ], - "html/semantics/forms/the-input-element/radio-expected.txt": [ - "9d3d38653e440fc6a65c8a88e89426dfbfe2fc39", - "support" - ], "html/semantics/forms/the-input-element/radio-groupname-case.html": [ "98985c9572d61e4a22a5dcf927e7cc20288c1d88", "testharness" @@ -347505,7 +347541,7 @@ "support" ], "screen-orientation/resources/sandboxed-iframe-locking.html": [ - "a900654e798241fb52ea214e90d25c272494e058", + "27c3eb23f9931697d65c64a2c7a46be77f8961ee", "support" ], "secure-contexts/OWNERS": [ @@ -348976,12 +349012,28 @@ "401235c18e1594c7248b22eb6881d54801de9809", "testharness" ], - "service-workers/service-worker/fetch-canvas-tainting-cache.https.html": [ - "1405d91626bd1c04fb80d4faf876a76b009f9e92", + "service-workers/service-worker/fetch-canvas-tainting-image-cache.https.html": [ + "a9a3c252cb40c38f3e53f577d35486f597c3f73c", "testharness" ], - "service-workers/service-worker/fetch-canvas-tainting.https.html": [ - "3a7eda70a92b343be65712ae9edf8aaf006cb5da", + "service-workers/service-worker/fetch-canvas-tainting-image.https.html": [ + "189e24f1aa5768d2bb75453900826843e0ab306b", + "testharness" + ], + "service-workers/service-worker/fetch-canvas-tainting-video-cache.https-expected.txt": [ + "d95c1de2759b4eab61835e65d610837cdc0b02c7", + "support" + ], + "service-workers/service-worker/fetch-canvas-tainting-video-cache.https.html": [ + "68deaada4bc6996777980c0b0b69bf9da4689eb4", + "testharness" + ], + "service-workers/service-worker/fetch-canvas-tainting-video.https-expected.txt": [ + "8cfb4d4aafa58cc8067ae482571a9f16331ec81c", + "support" + ], + "service-workers/service-worker/fetch-canvas-tainting-video.https.html": [ + "54838009a0f9d724f0088adab56173526597385b", "testharness" ], "service-workers/service-worker/fetch-cors-exposed-header-names.https.html": [ @@ -349741,15 +349793,15 @@ "support" ], "service-workers/service-worker/resources/fetch-access-control.py": [ - "e612c0f7457c8d15ff7d0e2515d8e967a8bb81b5", + "be1cb7ce3d6346a98d35a6c19d7a3bf656f9373b", "support" ], "service-workers/service-worker/resources/fetch-canvas-tainting-iframe.html": [ - "ebcfb2aaadbef90672503f7fd13261db7afb1af5", + "9fc63a38bee0e0368bec3c7c6d1185d72c3bc752", "support" ], "service-workers/service-worker/resources/fetch-canvas-tainting-tests.js": [ - "fc95bf5e9365861c332cde08b2c82c1f5fddaf0b", + "2119442a255d9544a2642be58f16a1b404c41c40", "support" ], "service-workers/service-worker/resources/fetch-cors-exposed-header-names-worker.js": [ @@ -350960,10 +351012,6 @@ "4b18b29129666d399abcf949f2e977cbad5a5eeb", "testharness" ], - "shadow-dom/untriaged/elements-and-dom-objects/extensions-to-event-interface/event-path-001.html": [ - "32840cb9d6e7809d31113d8ec4b6acd929cb5b58", - "testharness" - ], "shadow-dom/untriaged/elements-and-dom-objects/shadowroot-object/shadowroot-attributes/activeElement-confirm-return-null.html": [ "1b42c7c55978b8f6c2afc39e9ede4e9caee22c2c", "testharness" @@ -360749,7 +360797,7 @@ "support" ], "webxr/interfaces.https-expected.txt": [ - "d5a7d26ce187c7e5ef553edc67af2f64f24d3356", + "1bba0cdba31d6d3319e39559f1e4fecb0b3da765", "support" ], "webxr/interfaces.https.html": [ @@ -360761,7 +360809,7 @@ "support" ], "webxr/resources/webxr_util.js": [ - "2e92835bb77e028fffc597767528a4a3548f27e8", + "df6490ff3370ea580015f6b02ef5ec7ef2bb1e2b", "support" ], "webxr/webxr_availability.http.sub.html": [
diff --git a/third_party/WebKit/LayoutTests/external/wpt/content-security-policy/embedded-enforcement/required_csp-header.html b/third_party/WebKit/LayoutTests/external/wpt/content-security-policy/embedded-enforcement/required_csp-header.html index 3d8e337f2..9e7894b6 100644 --- a/third_party/WebKit/LayoutTests/external/wpt/content-security-policy/embedded-enforcement/required_csp-header.html +++ b/third_party/WebKit/LayoutTests/external/wpt/content-security-policy/embedded-enforcement/required_csp-header.html
@@ -50,7 +50,9 @@ { "name": "Wrong value of `csp` should not trigger sending Sec-Required-CSP Header - report-uri present", "csp": "script-src 'unsafe-inline'; report-uri resources/dummy-report.php", "expected": null }, - // TODO(andypaicu): when `report-to` is implemented, add tests here. + { "name": "Wrong value of `csp` should not trigger sending Sec-Required-CSP Header - report-to present", + "csp": "script-src 'unsafe-inline'; report-to resources/dummy-report.php", + "expected": null }, ]; tests.forEach(test => {
diff --git a/third_party/WebKit/LayoutTests/external/wpt/content-security-policy/reporting-api/reporting-api-works-on-frame-src.https.sub.html b/third_party/WebKit/LayoutTests/external/wpt/content-security-policy/reporting-api/reporting-api-works-on-frame-src.https.sub.html new file mode 100644 index 0000000..d633e3b --- /dev/null +++ b/third_party/WebKit/LayoutTests/external/wpt/content-security-policy/reporting-api/reporting-api-works-on-frame-src.https.sub.html
@@ -0,0 +1,22 @@ +<!DOCTYPE HTML> +<html> +<head> + <title>Test that reports using the report-api service are sent when there's a violation</title> + <script src='/resources/testharness.js'></script> + <script src='/resources/testharnessreport.js'></script> +</head> +<body> + <script> + async_test(function(t2) { + window.addEventListener("securitypolicyviolation", t2.step_func(function(e) { + assert_equals(e.blockedURI, "{{location[scheme]}}://{{location[host]}}/content-security-policy/support/fail.html"); + assert_equals(e.violatedDirective, "frame-src"); + t2.done(); + })); + }, "Event is fired"); + </script> + <iframe src="../support/fail.html"></iframe> + + <script async defer src='../support/checkReport.sub.js?reportField=violated-directive&reportValue=frame-src%20%27none%27'></script> +</body> +</html>
diff --git a/third_party/WebKit/LayoutTests/external/wpt/content-security-policy/reporting-api/reporting-api-works-on-frame-src.https.sub.html.sub.headers b/third_party/WebKit/LayoutTests/external/wpt/content-security-policy/reporting-api/reporting-api-works-on-frame-src.https.sub.html.sub.headers new file mode 100644 index 0000000..8da5216 --- /dev/null +++ b/third_party/WebKit/LayoutTests/external/wpt/content-security-policy/reporting-api/reporting-api-works-on-frame-src.https.sub.html.sub.headers
@@ -0,0 +1,6 @@ +Expires: Mon, 26 Jul 1997 05:00:00 GMT +Cache-Control: no-store, no-cache, must-revalidate +Pragma: no-cache +Set-Cookie: reporting-api-works-on-frame-src={{$id:uuid()}}; Path=/content-security-policy/reporting-api +Report-To: { "url": "https://{{host}}:{{ports[https][0]}}/content-security-policy/support/report.py?op=put&reportID={{$id}}", "group": "csp-group", "max-age": 10886400 } +Content-Security-Policy: script-src 'self' 'unsafe-inline'; frame-src 'none'; report-to csp-group
diff --git a/third_party/WebKit/LayoutTests/external/wpt/css/css-typed-om/resources/testhelper.js b/third_party/WebKit/LayoutTests/external/wpt/css/css-typed-om/resources/testhelper.js index cca80f2..f7c7e03 100644 --- a/third_party/WebKit/LayoutTests/external/wpt/css/css-typed-om/resources/testhelper.js +++ b/third_party/WebKit/LayoutTests/external/wpt/css/css-typed-om/resources/testhelper.js
@@ -137,7 +137,7 @@ test.add_cleanup(() => { style.remove(); }); - return [rule, rule.attributeStyleMap]; + return [rule, rule.styleMap]; } // Creates a new element with background image set to |imageValue|
diff --git a/third_party/WebKit/LayoutTests/external/wpt/css/css-typed-om/stylevalue-subclasses/cssPositionValue-invalid.html b/third_party/WebKit/LayoutTests/external/wpt/css/css-typed-om/stylevalue-subclasses/cssPositionValue-invalid.html new file mode 100644 index 0000000..d63c0c78 --- /dev/null +++ b/third_party/WebKit/LayoutTests/external/wpt/css/css-typed-om/stylevalue-subclasses/cssPositionValue-invalid.html
@@ -0,0 +1,67 @@ +<!doctype html> +<meta charset="utf-8"> +<title>CSSPositionValue Error Handling</title> +<link rel="help" href="https://drafts.css-houdini.org/css-typed-om-1/#positionvalue-objects"> +<meta name="assert" content="Test CSSPositionValue constructor and attributes error handling" /> +<script src="/resources/testharness.js"></script> +<script src="/resources/testharnessreport.js"></script> +<body> +<div id="log"> +<script> +'use strict'; + +const gTestArguments = [ + { + description: 'a keyword', + value: 'auto', + }, + { + description: 'a double', + value: 3.14, + }, + { + description: 'a unitless zero', + value: 0, + }, + { + description: 'a string length', + value: '10px', + }, + { + description: 'a number CSSUnitValue', + value: CSS.number(10), + }, + { + description: 'a time CSSUnitValue', + value: CSS.s(10), + }, + { + description: 'a CSSMathValue of angle type', + value: new CSSMathSum(CSS.deg(1)), + }, +]; + +for (const {value, description} of gTestArguments) { + test(() => { + assert_throws(new TypeError(), () => new CSSPositionValue(value, CSS.px(0))); + assert_throws(new TypeError(), () => new CSSPositionValue(CSS.px(0), value)); + }, `Constructing a CSSPositionValue with ${description} throws a TypeError`); + + test(() => { + let position = new CSSPositionValue(CSS.px(0), CSS.px(0)); + assert_throws(new TypeError(), () => position.x = value); + + assert_equals(position.x.value, 0, + 'X member should not have changed'); + }, `Updating CSSPositionValue.x with ${description} throws a TypeError`); + + test(() => { + let position = new CSSPositionValue(CSS.px(0), CSS.px(0)); + assert_throws(new TypeError(), () => position.y = value); + + assert_equals(position.y.value, 0, + 'Y member should not have changed'); + }, `Updating CSSPositionValue.y with ${description} throws a TypeError`); +} + +</script>
diff --git a/third_party/WebKit/LayoutTests/external/wpt/css/css-typed-om/stylevalue-subclasses/cssPositionValue.html b/third_party/WebKit/LayoutTests/external/wpt/css/css-typed-om/stylevalue-subclasses/cssPositionValue.html new file mode 100644 index 0000000..a780a86 --- /dev/null +++ b/third_party/WebKit/LayoutTests/external/wpt/css/css-typed-om/stylevalue-subclasses/cssPositionValue.html
@@ -0,0 +1,61 @@ +<!doctype html> +<meta charset="utf-8"> +<title>CSSPositionValue</title> +<link rel="help" href="https://drafts.css-houdini.org/css-typed-om-1/#positionvalue-objects"> +<meta name="assert" content="Test CSSPositionValue constructor and attributes" /> +<script src="/resources/testharness.js"></script> +<script src="/resources/testharnessreport.js"></script> +<script src="../resources/testhelper.js"></script> +<body> +<div id="log"> +<script> +'use strict'; + +const gTestArguments = [ + { + description: 'a length CSSUnitValue' , + value: CSS.px(1), + }, + { + description: 'a percent CSSUnitValue' , + value: CSS.percent(10), + }, + { + description: 'a CSSMathValue of length type' , + value: new CSSMathSum(CSS.px(1)), + }, + { + description: 'a CSSMathValue of percent type' , + value: new CSSMathSum(CSS.percent(1)), + }, +]; + +for (const {value, description} of gTestArguments) { + test(() => { + const position = new CSSPositionValue(value, value); + assert_style_value_equals(position.x, value, + 'X member should be same as passed in constructor'); + assert_style_value_equals(position.y, value, + 'Y member should be same as passed in constructor'); + }, 'CSSPositionValue can be constructed from ' + description); +} + +for (const {value, description} of gTestArguments) { + test(() => { + let position = new CSSPositionValue(CSS.px(0), CSS.px(0)); + position.x = value; + + assert_style_value_equals(position.x, value, + 'X member should be updated to new value'); + }, 'CSSPositionValue.x can be updated to ' + description); + + test(() => { + let position = new CSSPositionValue(CSS.px(0), CSS.px(0)); + position.y = value; + + assert_style_value_equals(position.y, value, + 'Y member should be updated to new value'); + }, 'CSSPositionValue.y can be updated to ' + description); +} + +</script>
diff --git a/third_party/WebKit/LayoutTests/external/wpt/css/css-typed-om/stylevalue-subclasses/cssPositionValue.tentative.html b/third_party/WebKit/LayoutTests/external/wpt/css/css-typed-om/stylevalue-subclasses/cssPositionValue.tentative.html deleted file mode 100644 index db07c91..0000000 --- a/third_party/WebKit/LayoutTests/external/wpt/css/css-typed-om/stylevalue-subclasses/cssPositionValue.tentative.html +++ /dev/null
@@ -1,65 +0,0 @@ -<!doctype html> -<meta charset="utf-8"> -<title>CSSPositionValue tests</title> -<link rel="help" href="https://drafts.css-houdini.org/css-typed-om-1/#positionvalue-objects"> -<script src="/resources/testharness.js"></script> -<script src="/resources/testharnessreport.js"></script> -<script src="../resources/testhelper.js"></script> -<script> -'use strict'; - -const gInvalidTestCases = [ - { value: 'auto', desc: 'a keyword'}, - { value: 10, desc: 'a double'}, - { value: 0, desc: 'a unitless zero'}, - { value: '10px', desc: 'a string length'}, - { value: CSS.number(10), desc: 'a number CSSUnitValue'}, - { value: CSS.s(10), desc: 'a time dimension CSSUnitValue'}, - { value: new CSSMathSum(CSS.deg(1)), desc: 'a CSSMathValue of angle type' }, -]; - -for (const {value, desc} of gInvalidTestCases) { - test(() => { - assert_throws(new TypeError(), () => new CSSPositionValue(value, CSS.px(0))); - assert_throws(new TypeError(), () => new CSSPositionValue(CSS.px(0), value)); - }, 'Constructing a CSSPositionValue with ' + desc + ' throws a TypeError'); -} - -for (const attr of ['x', 'y']) { - for (const {value, desc} of gInvalidTestCases) { - test(() => { - const position = new CSSPositionValue(CSS.px(0), CSS.px(0)); - assert_throws(new TypeError(), () => position[attr] = value); - assert_style_value_equals(position[attr], CSS.px(0)); - }, 'Updating CSSPositionValue.' + attr + ' with ' + desc + ' throws a TypeError'); - } -} - -const gValidTestCases = [ - { value: CSS.px(1), desc: 'a length CSSUnitValue' }, - { value: CSS.percent(10), desc: 'a percent CSSUnitValue' }, - { value: new CSSMathSum(CSS.px(1)), desc: 'a CSSMathValue of length type' }, - { value: new CSSMathSum(CSS.percent(1)), desc: 'a CSSMathValue of percent type' }, -]; - -for (const {value: x, desc: xDesc} of gValidTestCases) { - for (const {value: y, desc: yDesc} of gValidTestCases) { - test(() => { - const position = new CSSPositionValue(x, y); - assert_equals(position.x, x); - assert_equals(position.y, y); - }, 'CSSPositionValue can be constructed from ' + xDesc + ' and ' + yDesc); - } -} - -for (const attr of ['x', 'y']) { - for (const {value, desc} of gValidTestCases) { - test(() => { - const position = new CSSPositionValue(CSS.px(0), CSS.px(0)); - position[attr] = value; - assert_style_value_equals(position[attr], value); - }, 'CSSPositionValue.' + attr + ' can be updated to ' + desc); - } -} - -</script>
diff --git a/third_party/WebKit/LayoutTests/external/wpt/css/css-typed-om/stylevalue-subclasses/cssUnparsedValue-interface-expected.txt b/third_party/WebKit/LayoutTests/external/wpt/css/css-typed-om/stylevalue-subclasses/cssUnparsedValue-interface-expected.txt new file mode 100644 index 0000000..22270a6 --- /dev/null +++ b/third_party/WebKit/LayoutTests/external/wpt/css/css-typed-om/stylevalue-subclasses/cssUnparsedValue-interface-expected.txt
@@ -0,0 +1,37 @@ +This is a testharness.js-based test. +PASS CSSUnparsedValue interface: existence and properties of interface object +PASS CSSUnparsedValue interface object length +PASS CSSUnparsedValue interface object name +PASS CSSUnparsedValue interface: existence and properties of interface prototype object +PASS CSSUnparsedValue interface: existence and properties of interface prototype object's "constructor" property +PASS Testing Symbol.iterator property of iterable interface CSSUnparsedValue +FAIL Testing value iterable interface CSSUnparsedValue assert_equals: values function is not the same as Array one expected (undefined) undefined but got (function) function "function values() { [native code] }" +PASS CSSUnparsedValue interface: attribute length +FAIL CSSUnparsedValue interface: operation entries() assert_throws: calling operation with this = {} didn't throw TypeError function "function() { + fn.apply(obj, args); + }" did not throw +FAIL CSSUnparsedValue interface: operation keys() assert_throws: calling operation with this = {} didn't throw TypeError function "function() { + fn.apply(obj, args); + }" did not throw +FAIL CSSUnparsedValue interface: operation values() assert_throws: calling operation with this = {} didn't throw TypeError function "function() { + fn.apply(obj, args); + }" did not throw +PASS CSSUnparsedValue interface: operation forEach(function, any) +PASS CSSUnparsedValue must be primary interface of new CSSUnparsedValue() +PASS Stringification of new CSSUnparsedValue() +PASS CSSUnparsedValue interface: new CSSUnparsedValue() must inherit property "length" with the proper type +PASS CSSUnparsedValue interface: new CSSUnparsedValue() must inherit property "entries()" with the proper type +PASS CSSUnparsedValue interface: new CSSUnparsedValue() must inherit property "keys()" with the proper type +PASS CSSUnparsedValue interface: new CSSUnparsedValue() must inherit property "values()" with the proper type +PASS CSSUnparsedValue interface: new CSSUnparsedValue() must inherit property "forEach(function, any)" with the proper type +PASS CSSUnparsedValue interface: calling forEach(function, any) on new CSSUnparsedValue() with too few arguments must throw TypeError +PASS CSSUnparsedValue must be primary interface of new CSSUnparsedValue("foo") +PASS Stringification of new CSSUnparsedValue("foo") +PASS CSSUnparsedValue interface: new CSSUnparsedValue("foo") must inherit property "length" with the proper type +PASS CSSUnparsedValue interface: new CSSUnparsedValue("foo") must inherit property "entries()" with the proper type +PASS CSSUnparsedValue interface: new CSSUnparsedValue("foo") must inherit property "keys()" with the proper type +PASS CSSUnparsedValue interface: new CSSUnparsedValue("foo") must inherit property "values()" with the proper type +PASS CSSUnparsedValue interface: new CSSUnparsedValue("foo") must inherit property "forEach(function, any)" with the proper type +PASS CSSUnparsedValue interface: calling forEach(function, any) on new CSSUnparsedValue("foo") with too few arguments must throw TypeError +Harness: the test ran to completion. +
diff --git a/third_party/WebKit/LayoutTests/external/wpt/css/css-typed-om/stylevalue-subclasses/cssUnparsedValue-interface.html b/third_party/WebKit/LayoutTests/external/wpt/css/css-typed-om/stylevalue-subclasses/cssUnparsedValue-interface.html new file mode 100644 index 0000000..b20d054 --- /dev/null +++ b/third_party/WebKit/LayoutTests/external/wpt/css/css-typed-om/stylevalue-subclasses/cssUnparsedValue-interface.html
@@ -0,0 +1,30 @@ +<!doctype html> +<meta charset=utf-8> +<title>CSSUnparsedValue IDL</title> +<link rel="help" href="https://drafts.css-houdini.org/css-typed-om-1/#cssunparsedvalue"> +<script src="/resources/testharness.js"></script> +<script src="/resources/testharnessreport.js"></script> +<script src="/resources/WebIDLParser.js"></script> +<script src="/resources/idlharness.js"></script> +<script type="text/plain" id="idl"> +[Constructor((DOMString or CSSVariableReferenceValue)... members)] +interface CSSUnparsedValue : CSSStyleValue { + iterable<(DOMString or CSSVariableReferenceValue)>; + readonly attribute unsigned long length; + getter (DOMString or CSSVariableReferenceValue) (unsigned long index); +}; +</script> +<script> +'use strict'; +const idlArray = new IdlArray(); +idlArray.add_untested_idls('interface CSSStyleValue { stringifier; };'); +idlArray.add_untested_idls('interface CSSVariableReferenceValue : CSSStyleValue { };'); +idlArray.add_idls(document.getElementById('idl').textContent); +idlArray.add_objects({ + CSSUnparsedValue: [ + 'new CSSUnparsedValue()', + 'new CSSUnparsedValue("foo")', + ] +}); +idlArray.test(); +</script>
diff --git a/third_party/WebKit/LayoutTests/external/wpt/css/css-typed-om/stylevalue-subclasses/cssUnparsedValue.html b/third_party/WebKit/LayoutTests/external/wpt/css/css-typed-om/stylevalue-subclasses/cssUnparsedValue.html new file mode 100644 index 0000000..3a994dd --- /dev/null +++ b/third_party/WebKit/LayoutTests/external/wpt/css/css-typed-om/stylevalue-subclasses/cssUnparsedValue.html
@@ -0,0 +1,50 @@ +<!doctype html> +<meta charset="utf-8"> +<title>CSSUnparsedValue</title> +<link rel="help" href="https://drafts.css-houdini.org/css-typed-om-1/#unparsedvalue-objects"> +<meta name="assert" content="Test CSSUnparsedValue constructor and members"> +<script src="/resources/testharness.js"></script> +<script src="/resources/testharnessreport.js"></script> +<body> +<div id="log"> +<script> +'use strict'; + +const gTestArguments = [ + { + description: 'no arguments', + args: [], + }, + { + description: 'an empty string', + args: [''], + }, + { + description: 'a CSSVariableReferenceValue', + args: [new CSSVariableReferenceValue('--foo')], + }, + { + description: 'mix of strings and CSSVariableReferenceValues', + args: [ + 'foo', + 'bar', + new CSSVariableReferenceValue('--A'), + 'baz', + new CSSVariableReferenceValue('--B') + ], + }, +]; + +for (const {args, description} of gTestArguments) { + test(() => { + const result = new CSSUnparsedValue(...args); + + assert_not_equals(result, null, + 'A CSSUnparsedValue should be created'); + assert_array_equals(result, args, + 'Content of CSSUnparsedValue should be same as the arguments ' + + 'passed in the constructor'); + }, 'CSSUnparsedValue can be constructed from ' + description); +} + +</script>
diff --git a/third_party/WebKit/LayoutTests/external/wpt/css/css-typed-om/stylevalue-subclasses/cssUnparsedValue.tentative.html b/third_party/WebKit/LayoutTests/external/wpt/css/css-typed-om/stylevalue-subclasses/cssUnparsedValue.tentative.html deleted file mode 100644 index ea65a9b3..0000000 --- a/third_party/WebKit/LayoutTests/external/wpt/css/css-typed-om/stylevalue-subclasses/cssUnparsedValue.tentative.html +++ /dev/null
@@ -1,28 +0,0 @@ -<!doctype html> -<meta charset="utf-8"> -<title>CSSUnparsedValue tests</title> -<link rel="help" href="https://drafts.css-houdini.org/css-typed-om-1/#unparsedvalue-objects"> -<script src="/resources/testharness.js"></script> -<script src="/resources/testharnessreport.js"></script> -<script src="../resources/testhelper.js"></script> -<script> -'use strict'; - -const gValidTestArgs = [ - { args: [], desc: 'no arguments' }, - { args: [''], desc: 'an empty string' }, - { args: [new CSSVariableReferenceValue('--foo')], desc: 'a CSSVariableReferenceValue' }, - { - args: ['foo', 'bar', new CSSVariableReferenceValue('--A'), 'baz', new CSSVariableReferenceValue('--B')], - desc: 'mix of strings and CSSVariableReferenceValues' - }, -]; - -for (const {args, desc} of gValidTestArgs) { - test(() => { - const result = new CSSUnparsedValue(...args); - assert_array_equals(result, args); - }, 'CSSUnparsedValue can be constructed from ' + desc); -} - -</script>
diff --git a/third_party/WebKit/LayoutTests/external/wpt/css/css-typed-om/stylevalue-subclasses/cssVariableReferenceValue-interface.html b/third_party/WebKit/LayoutTests/external/wpt/css/css-typed-om/stylevalue-subclasses/cssVariableReferenceValue-interface.html new file mode 100644 index 0000000..15db3276 --- /dev/null +++ b/third_party/WebKit/LayoutTests/external/wpt/css/css-typed-om/stylevalue-subclasses/cssVariableReferenceValue-interface.html
@@ -0,0 +1,26 @@ +<!doctype html> +<meta charset=utf-8> +<title>CSSVariableReferenceValue IDL</title> +<link rel="help" href="https://drafts.css-houdini.org/css-typed-om-1/#cssvariablereferencevalue"> +<script src="/resources/testharness.js"></script> +<script src="/resources/testharnessreport.js"></script> +<script src="/resources/WebIDLParser.js"></script> +<script src="/resources/idlharness.js"></script> +<script type="text/plain" id="idl"> +[Constructor(DOMString variable, optional CSSUnparsedValue fallback)] +interface CSSVariableReferenceValue { + attribute DOMString variable; + readonly attribute CSSUnparsedValue? fallback; +}; +</script> +<script> +'use strict'; +const idlArray = new IdlArray(); +idlArray.add_idls(document.getElementById('idl').textContent); +idlArray.add_objects({ + CSSVariableReferenceValue: [ + 'new CSSVariableReferenceValue("--foo")', + ] +}); +idlArray.test(); +</script>
diff --git a/third_party/WebKit/LayoutTests/external/wpt/css/css-typed-om/stylevalue-subclasses/cssVariableReferenceValue-invalid.html b/third_party/WebKit/LayoutTests/external/wpt/css/css-typed-om/stylevalue-subclasses/cssVariableReferenceValue-invalid.html new file mode 100644 index 0000000..c58bf76 --- /dev/null +++ b/third_party/WebKit/LayoutTests/external/wpt/css/css-typed-om/stylevalue-subclasses/cssVariableReferenceValue-invalid.html
@@ -0,0 +1,41 @@ +<!doctype html> +<meta charset="utf-8"> +<title>CSSVariableReferenceValue Error Handling</title> +<link rel="help" href="https://drafts.css-houdini.org/css-typed-om-1/#cssvariablereferencevalue"> +<meta name="assert" content="Test CSSVariableReferenceValue constructor and attributes error handling" /> +<script src="/resources/testharness.js"></script> +<script src="/resources/testharnessreport.js"></script> +<body> +<div id="log"> +<script> +'use strict'; + +test(() => { + assert_throws(new TypeError(), () => new CSSVariableReferenceValue('')); +}, 'Constructing a CSSVariableReferenceValue with an empty variable name ' + + 'throws a TypeError'); + +test(() => { + assert_throws(new TypeError(), () => new CSSVariableReferenceValue('bar')); +}, 'Constructing a CSSVariableReferenceValue with an invalid variable name ' + + 'throws SyntaxError'); + +test(() => { + let result = new CSSVariableReferenceValue('--foo'); + assert_throws(new TypeError(), () => result.variable = ''); + + assert_equals(result.variable, '--foo', + 'Variable member should not have changed'); +}, 'Updating CSSVariableReferenceValue.variable to an empty variable name ' + + 'throws TypeError'); + +test(() => { + let result = new CSSVariableReferenceValue('--foo'); + assert_throws(new TypeError(), () => result.variable = 'bar'); + + assert_equals(result.variable, '--foo', + 'Variable member should not have changed'); +}, 'Updating CSSVariableReferenceValue.variable to an invalid variable name ' + + 'throws TypeError'); + +</script>
diff --git a/third_party/WebKit/LayoutTests/external/wpt/css/css-typed-om/stylevalue-subclasses/cssVariableReferenceValue.html b/third_party/WebKit/LayoutTests/external/wpt/css/css-typed-om/stylevalue-subclasses/cssVariableReferenceValue.html new file mode 100644 index 0000000..24082eb --- /dev/null +++ b/third_party/WebKit/LayoutTests/external/wpt/css/css-typed-om/stylevalue-subclasses/cssVariableReferenceValue.html
@@ -0,0 +1,45 @@ +<!doctype html> +<meta charset="utf-8"> +<title>CSSVariableReferenceValue tests</title> +<link rel="help" href="https://drafts.css-houdini.org/css-typed-om-1/#cssvariablereferencevalue"> +<meta name="assert" content="Test CSSVariableReferenceValue constructor and attributes" /> +<script src="/resources/testharness.js"></script> +<script src="/resources/testharnessreport.js"></script> +<script src="../resources/testhelper.js"></script> +<script> +'use strict'; + +test(() => { + const result = new CSSVariableReferenceValue('--foo'); + + assert_not_equals(result, null, + 'A CSSVariableReferenceValue should be created'); + assert_equals(result.variable, '--foo', + 'Variable member should be same as passed in the constructor'); + assert_equals(result.fallback, null, + 'Fallback member should be null'); +}, 'CSSVariableReferenceValue can be constructed with no fallback'); + +test(() => { + const result = new CSSVariableReferenceValue('--foo', + new CSSUnparsedValue('lemon')); + + assert_not_equals(result, null, + 'A CSSVariableReferenceValue should be created'); + assert_equals(result.variable, '--foo', + 'Variable member should be same as passed in the constructor'); + assert_not_equals(result.fallback, null, + 'Fallback member should not be null'); + assert_style_value_equals(result.fallback, new CSSUnparsedValue('lemon'), + 'Fallback member should be as same as passed in the constructor'); +}, 'CSSVariableReferenceValue can be constructed with fallback'); + +test(() => { + let result = new CSSVariableReferenceValue('--foo'); + result.variable = '--bar'; + + assert_equals(result.variable, '--bar', + 'Variable member should be updated to new value'); +}, 'CSSVariableReferenceValue.variable can updated to a valid variable name'); + +</script>
diff --git a/third_party/WebKit/LayoutTests/external/wpt/css/css-typed-om/stylevalue-subclasses/cssVariableReferenceValue.tentative-expected.txt b/third_party/WebKit/LayoutTests/external/wpt/css/css-typed-om/stylevalue-subclasses/cssVariableReferenceValue.tentative-expected.txt deleted file mode 100644 index d3cee65..0000000 --- a/third_party/WebKit/LayoutTests/external/wpt/css/css-typed-om/stylevalue-subclasses/cssVariableReferenceValue.tentative-expected.txt +++ /dev/null
@@ -1,8 +0,0 @@ -This is a testharness.js-based test. -FAIL Constructing a CSSVariableReferenceValue with an invalid variable name throws SyntaxError assert_throws: function "() => new CSSVariableReferenceValue('bar')" did not throw -FAIL Updating CSSVariableReferenceValue.variable to an invalid variable name throws SyntaxError assert_throws: function "() => result.variable = 'bar'" did not throw -PASS CSSVariableReferenceValue can be constructed with no fallback -PASS CSSVariableReferenceValue can be constructed with fallback -PASS CSSVariableReferenceValue.variable can updated to a valid variable name -Harness: the test ran to completion. -
diff --git a/third_party/WebKit/LayoutTests/external/wpt/css/css-typed-om/stylevalue-subclasses/cssVariableReferenceValue.tentative.html b/third_party/WebKit/LayoutTests/external/wpt/css/css-typed-om/stylevalue-subclasses/cssVariableReferenceValue.tentative.html deleted file mode 100644 index 38a350e4..0000000 --- a/third_party/WebKit/LayoutTests/external/wpt/css/css-typed-om/stylevalue-subclasses/cssVariableReferenceValue.tentative.html +++ /dev/null
@@ -1,42 +0,0 @@ -<!doctype html> -<meta charset="utf-8"> -<title>CSSVariableReferenceValue tests</title> -<link rel="help" href="https://drafts.css-houdini.org/css-typed-om-1/#cssvariablereferencevalue"> -<script src="/resources/testharness.js"></script> -<script src="/resources/testharnessreport.js"></script> -<script src="../resources/testhelper.js"></script> -<script> -'use strict'; - -test(() => { - assert_throws(new SyntaxError(), () => new CSSVariableReferenceValue('bar')); - assert_throws(new SyntaxError(), () => new CSSVariableReferenceValue('')); -}, 'Constructing a CSSVariableReferenceValue with an invalid variable name throws SyntaxError'); - -test(() => { - let result = new CSSVariableReferenceValue('--foo'); - assert_throws(new SyntaxError(), () => result.variable = 'bar'); - assert_equals(result.variable, '--foo'); - assert_throws(new SyntaxError(), () => result.variable = ''); - assert_equals(result.variable, '--foo'); -}, 'Updating CSSVariableReferenceValue.variable to an invalid variable name throws SyntaxError'); - -test(() => { - const result = new CSSVariableReferenceValue('--foo'); - assert_equals(result.variable, '--foo'); - assert_equals(result.fallback, null); -}, 'CSSVariableReferenceValue can be constructed with no fallback'); - -test(() => { - const result = new CSSVariableReferenceValue('--foo', new CSSUnparsedValue('lemon')); - assert_equals(result.variable, '--foo'); - assert_style_value_equals(result.fallback, new CSSUnparsedValue('lemon')); -}, 'CSSVariableReferenceValue can be constructed with fallback'); - -test(() => { - let result = new CSSVariableReferenceValue('--foo'); - result.variable = '--bar'; - assert_equals(result.variable, '--bar'); -}, 'CSSVariableReferenceValue.variable can updated to a valid variable name'); - -</script>
diff --git a/third_party/WebKit/LayoutTests/external/wpt/css/css-typed-om/the-stylepropertymap/declared/declared.tentative.html b/third_party/WebKit/LayoutTests/external/wpt/css/css-typed-om/the-stylepropertymap/declared/declared.tentative.html index 96c1e3e8..355a509 100644 --- a/third_party/WebKit/LayoutTests/external/wpt/css/css-typed-om/the-stylepropertymap/declared/declared.tentative.html +++ b/third_party/WebKit/LayoutTests/external/wpt/css/css-typed-om/the-stylepropertymap/declared/declared.tentative.html
@@ -28,7 +28,7 @@ 'use strict'; const target = document.getElementById('target'); -const styleMap = document.styleSheets[0].rules[0].attributeStyleMap; +const styleMap = document.styleSheets[0].rules[0].styleMap; test(() => { const properties = styleMap.getProperties(); @@ -63,7 +63,7 @@ style.sheet.insertRule('.test { width: 10px; }'); let rule = style.sheet.rules[0]; - let styleMap = rule.attributeStyleMap; + let styleMap = rule.styleMap; assert_style_value_equals(styleMap.get('width'), CSS.px(10)); rule.style.width = '20px';
diff --git a/third_party/WebKit/LayoutTests/external/wpt/css/css-typed-om/the-stylepropertymap/declared/test.tentative.html b/third_party/WebKit/LayoutTests/external/wpt/css/css-typed-om/the-stylepropertymap/declared/test.tentative.html deleted file mode 100644 index c171769d..0000000 --- a/third_party/WebKit/LayoutTests/external/wpt/css/css-typed-om/the-stylepropertymap/declared/test.tentative.html +++ /dev/null
@@ -1,24 +0,0 @@ -<!doctype html> -<meta charset="utf-8"> -<title>Declared StylePropertyMap tests</title> -<link rel="help" href="https://drafts.css-houdini.org/css-typed-om-1/#declared-stylepropertymap-objects"> -<script src="/resources/testharness.js"></script> -<script src="/resources/testharnessreport.js"></script> -<script src="../../resources/testhelper.js"></script> -<style> -#target { width: 100px; height: 100px; background: red; } -</style> -<body> -<div id="target"> -<script> -'use strict'; - -test(() => { - let rule = document.styleSheets[0].rules[0]; - rule.attributeStyleMap.set('width', CSS.px(200)); - assert_equals(getComputedStyle(target).width, '200px') - rule.attributeStyleMap.set('width', CSS.px(150)); - assert_equals(getComputedStyle(target).width, '150px') -}); -</script> -</body>
diff --git a/third_party/WebKit/LayoutTests/external/wpt/css/css-typed-om/the-stylepropertymap/interface-expected.txt b/third_party/WebKit/LayoutTests/external/wpt/css/css-typed-om/the-stylepropertymap/interface-expected.txt index 51ea83cb..2aea84c 100644 --- a/third_party/WebKit/LayoutTests/external/wpt/css/css-typed-om/the-stylepropertymap/interface-expected.txt +++ b/third_party/WebKit/LayoutTests/external/wpt/css/css-typed-om/the-stylepropertymap/interface-expected.txt
@@ -26,6 +26,6 @@ PASS StylePropertyMap interface: operation update(DOMString, UpdateFunction) PASS Element interface: operation computedStyleMap() PASS Element interface: attribute attributeStyleMap -PASS CSSStyleRule interface: attribute attributeStyleMap +PASS CSSStyleRule interface: attribute styleMap Harness: the test ran to completion.
diff --git a/third_party/WebKit/LayoutTests/external/wpt/css/css-typed-om/the-stylepropertymap/interface.html b/third_party/WebKit/LayoutTests/external/wpt/css/css-typed-om/the-stylepropertymap/interface.html index 3e884909..6e03010 100644 --- a/third_party/WebKit/LayoutTests/external/wpt/css/css-typed-om/the-stylepropertymap/interface.html +++ b/third_party/WebKit/LayoutTests/external/wpt/css/css-typed-om/the-stylepropertymap/interface.html
@@ -30,7 +30,7 @@ }; partial interface CSSStyleRule { - [SameObject] readonly attribute StylePropertyMap attributeStyleMap; + [SameObject] readonly attribute StylePropertyMap styleMap; }; partial interface Element {
diff --git a/third_party/WebKit/LayoutTests/external/wpt/custom-elements/Document-createElement-svg.svg b/third_party/WebKit/LayoutTests/external/wpt/custom-elements/Document-createElement-svg.svg new file mode 100644 index 0000000..0b53bd8 --- /dev/null +++ b/third_party/WebKit/LayoutTests/external/wpt/custom-elements/Document-createElement-svg.svg
@@ -0,0 +1,24 @@ +<?xml version="1.0" encoding="utf-8"?> +<svg:svg xmlns:svg="http://www.w3.org/2000/svg" + xmlns="http://www.w3.org/1999/xhtml" + width="100%" height="100%" viewBox="0 0 800 600"> +<svg:title>document.createElement in SVG for custom elements</svg:title> +<script src="/resources/testharness.js"></script> +<script src="/resources/testharnessreport.js"></script> +<script><![CDATA[ +test(() => { + class MyElement1 extends HTMLElement {} + customElements.define('my-element', MyElement1); + let element = document.createElement('my-element', {}); + assert_false(element instanceof MyElement1, 'Autonomous custom element should not be created.'); +}, 'document.createElement() in SVG documents should not create autonomous custom elements.') + +test(() => { + class MyElement2 extends HTMLDivElement {} + customElements.define('my-div', MyElement2, { extends: 'div' }); + + let element = document.createElement('div', { is: 'my-div' }); + assert_false(element instanceof MyElement2, 'Custom built-in element should not be created.'); +}, 'document.createElement() in SVG documents should not create custom built-in elements.') +]]></script> +</svg:svg>
diff --git a/third_party/WebKit/LayoutTests/external/wpt/custom-elements/builtin-coverage-expected.txt b/third_party/WebKit/LayoutTests/external/wpt/custom-elements/builtin-coverage-expected.txt index b2dd528..de65063 100644 --- a/third_party/WebKit/LayoutTests/external/wpt/custom-elements/builtin-coverage-expected.txt +++ b/third_party/WebKit/LayoutTests/external/wpt/custom-elements/builtin-coverage-expected.txt
@@ -1,6 +1,6 @@ This is a testharness.js-based test. Harness Error. harness_status.status = 1 , harness_status.message = Uncaught TypeError: Illegal constructor: localName does not match the HTML element interface -Found 442 tests; 414 PASS, 28 FAIL, 0 TIMEOUT, 0 NOTRUN. +Found 442 tests; 423 PASS, 19 FAIL, 0 TIMEOUT, 0 NOTRUN. PASS a: Define a customized built-in element PASS a: Operator 'new' should instantiate a customized built-in element PASS a: document.createElement() should instantiate a customized built-in element @@ -129,17 +129,9 @@ PASS em: document.createElement() should instantiate a customized built-in element PASS em: innerHTML should instantiate a customized built-in element PASS embed: Define a customized built-in element -FAIL embed: Operator 'new' should instantiate a customized built-in element Illegal constructor -FAIL embed: document.createElement() should instantiate a customized built-in element assert_equals: expected function "class MyEmbed extends HTMLEmbedElement { - constructor() { - super(); - } -}" but got function "function HTMLEmbedElement() { [native code] }" -FAIL embed: innerHTML should instantiate a customized built-in element assert_equals: expected function "class MyEmbed extends HTMLEmbedElement { - constructor() { - super(); - } -}" but got function "function HTMLEmbedElement() { [native code] }" +PASS embed: Operator 'new' should instantiate a customized built-in element +PASS embed: document.createElement() should instantiate a customized built-in element +PASS embed: innerHTML should instantiate a customized built-in element PASS fieldset: Define a customized built-in element PASS fieldset: Operator 'new' should instantiate a customized built-in element PASS fieldset: document.createElement() should instantiate a customized built-in element @@ -157,17 +149,9 @@ PASS footer: document.createElement() should instantiate a customized built-in element PASS footer: innerHTML should instantiate a customized built-in element PASS form: Define a customized built-in element -FAIL form: Operator 'new' should instantiate a customized built-in element Illegal constructor -FAIL form: document.createElement() should instantiate a customized built-in element assert_equals: expected function "class MyForm extends HTMLFormElement { - constructor() { - super(); - } -}" but got function "function HTMLFormElement() { [native code] }" -FAIL form: innerHTML should instantiate a customized built-in element assert_equals: expected function "class MyForm extends HTMLFormElement { - constructor() { - super(); - } -}" but got function "function HTMLFormElement() { [native code] }" +PASS form: Operator 'new' should instantiate a customized built-in element +PASS form: document.createElement() should instantiate a customized built-in element +PASS form: innerHTML should instantiate a customized built-in element PASS h1: Define a customized built-in element PASS h1: Operator 'new' should instantiate a customized built-in element PASS h1: document.createElement() should instantiate a customized built-in element @@ -288,17 +272,9 @@ } }" but got function "function HTMLElement() { [native code] }" PASS object: Define a customized built-in element -FAIL object: Operator 'new' should instantiate a customized built-in element Illegal constructor -FAIL object: document.createElement() should instantiate a customized built-in element assert_equals: expected function "class MyObject extends HTMLObjectElement { - constructor() { - super(); - } -}" but got function "function HTMLObjectElement() { [native code] }" -FAIL object: innerHTML should instantiate a customized built-in element assert_equals: expected function "class MyObject extends HTMLObjectElement { - constructor() { - super(); - } -}" but got function "function HTMLObjectElement() { [native code] }" +PASS object: Operator 'new' should instantiate a customized built-in element +PASS object: document.createElement() should instantiate a customized built-in element +PASS object: innerHTML should instantiate a customized built-in element PASS ol: Define a customized built-in element PASS ol: Operator 'new' should instantiate a customized built-in element PASS ol: document.createElement() should instantiate a customized built-in element
diff --git a/third_party/WebKit/LayoutTests/external/wpt/graphics-aam/graphics-document_on_html_element-manual.html b/third_party/WebKit/LayoutTests/external/wpt/graphics-aam/graphics-document_on_html_element-manual.html index 9e386d55..293ad2ea 100644 --- a/third_party/WebKit/LayoutTests/external/wpt/graphics-aam/graphics-document_on_html_element-manual.html +++ b/third_party/WebKit/LayoutTests/external/wpt/graphics-aam/graphics-document_on_html_element-manual.html
@@ -93,7 +93,7 @@ <body> <p>This test examines the ARIA properties for graphics-document on HTML element.</p> <div id="test" role="graphics-document" aria-label="house"> - <div role="graphics-object" aria-label="door"> + <div role="graphics-object" aria-label="door"></div> </div> <div id="manualMode"></div>
diff --git a/third_party/WebKit/LayoutTests/external/wpt/graphics-aam/graphics-object_on_html_element-manual.html b/third_party/WebKit/LayoutTests/external/wpt/graphics-aam/graphics-object_on_html_element-manual.html index ea47792..19979b2 100644 --- a/third_party/WebKit/LayoutTests/external/wpt/graphics-aam/graphics-object_on_html_element-manual.html +++ b/third_party/WebKit/LayoutTests/external/wpt/graphics-aam/graphics-object_on_html_element-manual.html
@@ -87,7 +87,7 @@ <body> <p>This test examines the ARIA properties for graphics-object on HTML element.</p> <div role="graphics-document" aria-label="house"> - <div id="test" role="graphics-object" aria-label="door"> + <div id="test" role="graphics-object" aria-label="door"></div> </div> <div id="manualMode"></div>
diff --git a/third_party/WebKit/LayoutTests/external/wpt/graphics-aam/graphics-symbol_on_html_element-manual.html b/third_party/WebKit/LayoutTests/external/wpt/graphics-aam/graphics-symbol_on_html_element-manual.html index 59d2d905..3b9c77f 100644 --- a/third_party/WebKit/LayoutTests/external/wpt/graphics-aam/graphics-symbol_on_html_element-manual.html +++ b/third_party/WebKit/LayoutTests/external/wpt/graphics-aam/graphics-symbol_on_html_element-manual.html
@@ -86,7 +86,7 @@ </head> <body> <p>This test examines the ARIA properties for graphics-symbol on HTML element.</p> - <div>Spinach Salad with Strawberry & Almonds + <div>Spinach Salad with Strawberry & Almonds <span id="test" aria-label="vegetarian" role="graphics-symbol">🌿</span> <span aria-label="contains nuts" role="graphics-symbol">🌰</span> </div>
diff --git a/third_party/WebKit/LayoutTests/external/wpt/webxr/OWNERS b/third_party/WebKit/LayoutTests/external/wpt/webxr/OWNERS index dffd2c95..576f2265c 100644 --- a/third_party/WebKit/LayoutTests/external/wpt/webxr/OWNERS +++ b/third_party/WebKit/LayoutTests/external/wpt/webxr/OWNERS
@@ -1 +1,4 @@ +# TEAM: xr-dev@chromium.org +# COMPONENT: Blink>WebVR +# WPT-NOTIFY: true file://third_party/WebKit/Source/modules/xr/OWNERS \ No newline at end of file
diff --git a/third_party/WebKit/LayoutTests/fast/css-grid-layout/grid-item-display.html b/third_party/WebKit/LayoutTests/fast/css-grid-layout/grid-item-display.html index eff8467db9..154d2a9 100644 --- a/third_party/WebKit/LayoutTests/fast/css-grid-layout/grid-item-display.html +++ b/third_party/WebKit/LayoutTests/fast/css-grid-layout/grid-item-display.html
@@ -43,8 +43,8 @@ <!-- Elements with custom renderers. --> <button data-expected-display="block" data-offset-x="50" data-offset-y="150"></button> <canvas data-expected-display="block" data-offset-x="50" data-offset-y="150">canvas</canvas> - <iframe data-expected-display="block" data-offset-x="50" data-offset-y="150" src="data:text/html,<body bgcolor=#fff>iframe</body>"></iframe> - <iframe seamless data-expected-display="block" data-offset-x="50" data-offset-y="150" src="data:text/html,<body bgcolor=#fff>iframe</body>"></iframe> + <iframe data-expected-display="block" data-offset-x="50" data-offset-y="150" src="data:text/html,<body bgcolor=%23fff>iframe</body>"></iframe> + <iframe seamless data-expected-display="block" data-offset-x="50" data-offset-y="150" src="data:text/html,<body bgcolor=%23fff>iframe</body>"></iframe> <object data-expected-display="block" data-offset-x="50" data-offset-y="150">object</object> <select data-expected-display="block" data-offset-x="50" data-offset-y="150"> <option>select</option>
diff --git a/third_party/WebKit/LayoutTests/fast/css/deprecated-three-value-position-expected.txt b/third_party/WebKit/LayoutTests/fast/css/deprecated-three-value-position-expected.txt new file mode 100644 index 0000000..8aff0a79 --- /dev/null +++ b/third_party/WebKit/LayoutTests/fast/css/deprecated-three-value-position-expected.txt
@@ -0,0 +1,5 @@ +CONSOLE WARNING: Expressing a position using 3 parts is deprecated and will be removed in M68, around July 2018. Please use <position> syntax instead. See https://www.chromestatus.com/features/5116559680864256 for more details. +CONSOLE WARNING: Expressing a position using 3 parts is deprecated and will be removed in M68, around July 2018. Please use <position> syntax instead. See https://www.chromestatus.com/features/5116559680864256 for more details. +CONSOLE WARNING: Expressing a position using 3 parts is deprecated and will be removed in M68, around July 2018. Please use <position> syntax instead. See https://www.chromestatus.com/features/5116559680864256 for more details. +CONSOLE WARNING: Expressing a position using 3 parts is deprecated and will be removed in M68, around July 2018. Please use <position> syntax instead. See https://www.chromestatus.com/features/5116559680864256 for more details. +
diff --git a/third_party/WebKit/LayoutTests/fast/css/deprecated-three-value-position.html b/third_party/WebKit/LayoutTests/fast/css/deprecated-three-value-position.html new file mode 100644 index 0000000..a4f174c --- /dev/null +++ b/third_party/WebKit/LayoutTests/fast/css/deprecated-three-value-position.html
@@ -0,0 +1,29 @@ +<!DOCTYPE html> +<style> + #a { + /* Each of the four <position> contexts generates a warning. */ + object-position: center left 1px; + perspective-origin: center top 2px; + background-image: conic-gradient(at right 3% center, black, red); + clip-path: circle(at left 4px top); + } + + #b { + /* These <position> contexts have already been counted. + No additional warnings are generated.*/ + object-position: right top 5px; + perspective-origin: bottom 6% center; + background-image: conic-gradient(at bottom 7% left, black, red); + clip-path: circle(at bottom right 8%); + } + + #c { + /* Valid <bg-position>, so no warning generated. */ + background-position: center left 1px; + } +</style> +<script> + if (window.testRunner) { + testRunner.dumpAsText(); + } +</script>
diff --git a/third_party/WebKit/LayoutTests/fast/css/import-style-update.html b/third_party/WebKit/LayoutTests/fast/css/import-style-update.html index 681e670f..f49d31a 100644 --- a/third_party/WebKit/LayoutTests/fast/css/import-style-update.html +++ b/third_party/WebKit/LayoutTests/fast/css/import-style-update.html
@@ -1,6 +1,6 @@ <head> <style> -@import url("data:text/css,#test{display:none;}"); +@import url("data:text/css,%23test{display:none;}"); </style> <script> if (window.testRunner)
diff --git a/third_party/WebKit/LayoutTests/fast/css/link-disabled-attr.html b/third_party/WebKit/LayoutTests/fast/css/link-disabled-attr.html index 115fac2..3e24be2 100644 --- a/third_party/WebKit/LayoutTests/fast/css/link-disabled-attr.html +++ b/third_party/WebKit/LayoutTests/fast/css/link-disabled-attr.html
@@ -1,7 +1,7 @@ <!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML//EN"> <html> <head> -<link id="sheet" rel="stylesheet" href="data:tex/css,#test-element{text-decoration:line-through}"> +<link id="sheet" rel="stylesheet" href="data:tex/css,%23test-element{text-decoration:line-through}"> <link id="notsheet" rel="author" href="mailto:nosuch@webkit.org"> <link id="alt" rel="alternate stylesheet" title="altset" href="resources/green.css"> <script src="../../resources/js-test.js"></script>
diff --git a/third_party/WebKit/LayoutTests/fast/css/parsing-object-position-expected.txt b/third_party/WebKit/LayoutTests/fast/css/parsing-object-position-expected.txt index 97c6918..27bcae9e 100644 --- a/third_party/WebKit/LayoutTests/fast/css/parsing-object-position-expected.txt +++ b/third_party/WebKit/LayoutTests/fast/css/parsing-object-position-expected.txt
@@ -1,3 +1,4 @@ +CONSOLE WARNING: line 24: Expressing a position using 3 parts is deprecated and will be removed in M68, around July 2018. Please use <position> syntax instead. See https://www.chromestatus.com/features/5116559680864256 for more details. This tests checks that all of the input values for object-position parse correctly. On success, you will see a series of "PASS" messages, followed by "TEST COMPLETE".
diff --git a/third_party/WebKit/LayoutTests/fast/css/parsing-object-position.html b/third_party/WebKit/LayoutTests/fast/css/parsing-object-position.html index 41c72c1..e8570d7 100644 --- a/third_party/WebKit/LayoutTests/fast/css/parsing-object-position.html +++ b/third_party/WebKit/LayoutTests/fast/css/parsing-object-position.html
@@ -34,7 +34,7 @@ shouldBeEqualToString('testComputedStyle("object-position: 10px 10px;")', '10px 10px'); shouldBeEqualToString('testComputedStyle("object-position: right top;")', '100% 0%'); shouldBeEqualToString('testComputedStyle("object-position: top right;")', '100% 0%'); - shouldBeEqualToString('testComputedStyle("object-position: left 20px center;")', '20px 50%'); + shouldBeEqualToString('testComputedStyle("object-position: left 20px center;")', '20px 50%'); // Deprecated shouldBeEqualToString('testComputedStyle("object-position: center bottom 25%;")', '50% 75%'); shouldBeEqualToString('testComputedStyle("object-position: bottom 20px right 12px;")', 'calc(-12px + 100%) calc(-20px + 100%)');
diff --git a/third_party/WebKit/LayoutTests/fast/css/stylesheet-parentStyleSheet.html b/third_party/WebKit/LayoutTests/fast/css/stylesheet-parentStyleSheet.html index c37f3b7..09027bc 100644 --- a/third_party/WebKit/LayoutTests/fast/css/stylesheet-parentStyleSheet.html +++ b/third_party/WebKit/LayoutTests/fast/css/stylesheet-parentStyleSheet.html
@@ -1,6 +1,6 @@ <head> <style> -@import url("data:text/css,#test{}"); +@import url("data:text/css,%23test{}"); </style> <script> if (window.testRunner)
diff --git a/third_party/WebKit/LayoutTests/fast/dom/domListEnumeration.html b/third_party/WebKit/LayoutTests/fast/dom/domListEnumeration.html index 97d90d01..65d2ea4 100644 --- a/third_party/WebKit/LayoutTests/fast/dom/domListEnumeration.html +++ b/third_party/WebKit/LayoutTests/fast/dom/domListEnumeration.html
@@ -1,7 +1,7 @@ <!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML//EN"> <html> <head> -<link rel="stylesheet" href="data:text/css,#test-element{text-decoration:line-through}"> +<link rel="stylesheet" href="data:text/css,%23test-element{text-decoration:line-through}"> <script src="../../resources/js-test.js"></script> </head> <body>
diff --git a/third_party/WebKit/LayoutTests/fast/dom/shadow/alternate-stylesheets.html b/third_party/WebKit/LayoutTests/fast/dom/shadow/alternate-stylesheets.html index c18b603..e8bdc73 100644 --- a/third_party/WebKit/LayoutTests/fast/dom/shadow/alternate-stylesheets.html +++ b/third_party/WebKit/LayoutTests/fast/dom/shadow/alternate-stylesheets.html
@@ -6,7 +6,7 @@ root.innerHTML = '<style title="not-preferred">div { color: red }</style><style title="ignored">div { color: green }</style><div>Should be green</div>'; </script> <style>#alternate { color: green }</style> -<link rel="alternate stylesheet" title="not-preferred" href="data:text/css,#alternate { color: red }"> +<link rel="alternate stylesheet" title="not-preferred" href="data:text/css,%23alternate { color: red }"> </style> <div id="alternate">Should be green</div> <script>
diff --git a/third_party/WebKit/LayoutTests/fast/events/hit-test-counts-expected.txt b/third_party/WebKit/LayoutTests/fast/events/hit-test-counts-expected.txt index 7b8a411..8230f1fd 100644 --- a/third_party/WebKit/LayoutTests/fast/events/hit-test-counts-expected.txt +++ b/third_party/WebKit/LayoutTests/fast/events/hit-test-counts-expected.txt
@@ -19,9 +19,9 @@ TouchStart: 1+1 TouchMove: 0+0 TouchEnd: 0+0 -GestureTapDown: 0+1 -GestureShowPress: 0+1 -GestureTap: 0+3 +GestureTapDown: 1+2 +GestureShowPress: 1+2 +GestureTap: 1+4 GestureScrollBegin: 0+1 GestureTapCancel: 0+1 GestureScrollUpdate: 0+0 @@ -38,9 +38,9 @@ TouchStart: 2+0 2+0 1+1 TouchMove: 0+0 0+0 0+0 TouchEnd: 0+0 0+0 0+0 -GestureTapDown: 1+0 1+0 0+1 -GestureShowPress: 1+0 1+0 0+1 -GestureTap: 1+0 1+0 0+3 +GestureTapDown: 2+0 2+0 1+2 +GestureShowPress: 2+0 2+0 1+2 +GestureTap: 2+0 2+0 1+4 GestureScrollBegin: 0+1 0+1 0+1 GestureTapCancel: 1+0 1+0 0+1 GestureScrollUpdate: 0+0 0+0 0+0 @@ -57,9 +57,9 @@ TouchStart: 2+0 1+1 1+0 TouchMove: 0+0 0+0 0+0 TouchEnd: 0+0 0+0 0+0 -GestureTapDown: 1+0 0+1 0+0 -GestureShowPress: 1+0 0+1 0+0 -GestureTap: 1+0 0+3 0+0 +GestureTapDown: 2+0 1+1 1+0 +GestureShowPress: 2+0 1+1 1+0 +GestureTap: 2+0 1+3 1+0 GestureScrollBegin: 0+1 0+1 0+0 GestureTapCancel: 1+0 0+1 0+0 GestureScrollUpdate: 0+0 0+0 0+0 @@ -76,9 +76,9 @@ TouchStart: 1+1 TouchMove: 0+0 TouchEnd: 0+0 -GestureTapDown: 0+1 -GestureShowPress: 0+1 -GestureTap: 0+3 [with multiTargetTapNotification: 1+3] +GestureTapDown: 1+2 +GestureShowPress: 1+2 +GestureTap: 1+4 [with multiTargetTapNotification: 2+4] GestureScrollBegin: 0+1 GestureTapCancel: 0+1 GestureScrollUpdate: 0+0
diff --git a/third_party/WebKit/LayoutTests/fast/events/scale-and-scroll-iframe-window-expected.png b/third_party/WebKit/LayoutTests/fast/events/scale-and-scroll-iframe-window-expected.png deleted file mode 100644 index a0abe1f..0000000 --- a/third_party/WebKit/LayoutTests/fast/events/scale-and-scroll-iframe-window-expected.png +++ /dev/null Binary files differ
diff --git a/third_party/WebKit/LayoutTests/fast/events/scale-and-scroll-iframe-window-expected.txt b/third_party/WebKit/LayoutTests/fast/events/scale-and-scroll-iframe-window-expected.txt deleted file mode 100644 index 3b338be..0000000 --- a/third_party/WebKit/LayoutTests/fast/events/scale-and-scroll-iframe-window-expected.txt +++ /dev/null
@@ -1,8 +0,0 @@ -PASS successfullyParsed is true - -TEST COMPLETE -PASS frame.contentDocument.scrollingElement.scrollTop is 100 -PASS frame.contentDocument.scrollingElement.scrollLeft is 100 -PASS frame.contentWindow.scrollX is 100 -PASS frame.contentWindow.scrollY is 100 -
diff --git a/third_party/WebKit/LayoutTests/fast/events/scale-and-scroll-iframe-window.html b/third_party/WebKit/LayoutTests/fast/events/scale-and-scroll-iframe-window.html index 3d10cc2f..2173f5a 100644 --- a/third_party/WebKit/LayoutTests/fast/events/scale-and-scroll-iframe-window.html +++ b/third_party/WebKit/LayoutTests/fast/events/scale-and-scroll-iframe-window.html
@@ -1,56 +1,76 @@ -<html> -<head> - <script> - window.enablePixelTesting = true; +<script src="../../resources/testharness.js"></script> +<script src="../../resources/testharnessreport.js"></script> +<script> + const mainTest = async_test( + 'window.scrollTo while zoomed causes correct amount of scroll', {}); + const frameTest = async_test( + 'window.scrollTo while zoomed causes correct amount of scroll in ' + + 'iframe', {}); - function scroll() { - window.scrollTo(0, 100); - var frame = document.getElementById('frame'); - frame.contentWindow.scrollTo(100,100); + function runTest() { + var scaleFactor = 2; + if (window.internals) + internals.setPageScaleFactor(scaleFactor); - shouldBe("frame.contentDocument.scrollingElement.scrollTop", "100"); - shouldBe("frame.contentDocument.scrollingElement.scrollLeft", "100"); - shouldBe("frame.contentWindow.scrollX", "100"); - shouldBe("frame.contentWindow.scrollY", "100"); - } + window.scrollTo(0, 100); - function scaleWithEventSender() { - var scaleFactor = 0.5; - if (window.internals) { - internals.setPageScaleFactorLimits(scaleFactor, scaleFactor); - internals.setPageScaleFactor(scaleFactor); - } - } + mainTest.step(function() { + assert_equals(document.scrollingElement.scrollLeft, 0, + "scrollingElement has correct scrollLeft"); + assert_equals(document.scrollingElement.scrollTop, 100, + "scrollingElement has correct scrollTop"); + assert_equals(window.scrollX, 0, + "window has correct scrollX"); + assert_equals(window.scrollY, 100, + "window has correct scrollY"); + }); + mainTest.done(); - function test() { - scaleWithEventSender(); - scroll(); - } - </script> - <script src="../../resources/js-test.js"></script> -</head> -<body onload="test();" style="width: 4000px; height: 4000px"> - <div id="console"></div> - <iframe id="frame" style="width:400px; height: 400px; position: absolute; top: 100px;"></iframe> - - <script> var frame = document.getElementById('frame'); - var doc = frame.contentDocument.open(); - doc.write("<html><style>::-webkit-scrollbar {width: 0px;height: 0px;}</style></html>"); - doc.write("<div style='left:0; top:0; width:100px; height:100px; position:absolute; background:yellow;'></div>"); - doc.write("<div style='left:100px; top:0; width:100px; height:100px; position:absolute; background:green;'></div>"); - doc.write("<div style='left:200px; top:0; width:100px; height:100px; position:absolute; background:blue;'></div>"); - doc.write("<div style='left:300px; top:0; width:100px; height:100px; position:absolute; background:green;'></div>"); - doc.write("<div style='left:400px; top:0; width:100px; height:100px; position:absolute; background:blue;'></div>"); + frame.contentWindow.scrollTo(100,100); - doc.write("<div style='left:0; top:100px; width:100px; height:100px; position:absolute; background: green;'></div>"); - doc.write("<div style='left:100px; top:100px; width:100px; height:100px; position:absolute; background:blue;'></div>"); - doc.write("<div style='left:200px; top:100px; width:100px; height:100px; position:absolute; background:green;'></div>"); - doc.write("<div style='left:300px; top:100px; width:100px; height:100px; position:absolute; background:blue;'></div>"); - doc.write("<div style='left:400px; top:100px; width:100px; height:100px; position:absolute; background:green;'></div>"); - doc.close(); - frame.contentDocument.body.style.width = "2000px"; - frame.contentDocument.body.style.height = "2000px"; - </script> -</body> -</html> + frameTest.step(function() { + assert_equals(frame.contentDocument.scrollingElement.scrollLeft, + 100, + "IFrame ScrollingElement has correct scrollLeft"); + assert_equals(frame.contentDocument.scrollingElement.scrollTop, + 100, + "IFrame ScrollingElement has correct scrollTop"); + assert_equals(frame.contentWindow.scrollX, 100, + "IFrame window has correct scrollX"); + assert_equals(frame.contentWindow.scrollY, 100, + "IFrame window has correct scrollY"); + }); + frameTest.done(); + } + + addEventListener('load', runTest); +</script> +<style> + body { + width: 4000px; + height: 4000px; + } +</style> + +<div id="console"></div> +<iframe id="frame" style="width:400px; height: 400px; position: absolute; top: 100px;"></iframe> +<script> + var frame = document.getElementById('frame'); + var doc = frame.contentDocument.open(); + doc.write("<html><style>::-webkit-scrollbar {width: 0px;height: 0px;}</style></html>"); + doc.write("<div style='left:0; top:0; width:100px; height:100px; position:absolute; background:yellow;'></div>"); + doc.write("<div style='left:100px; top:0; width:100px; height:100px; position:absolute; background:green;'></div>"); + doc.write("<div style='left:200px; top:0; width:100px; height:100px; position:absolute; background:blue;'></div>"); + doc.write("<div style='left:300px; top:0; width:100px; height:100px; position:absolute; background:green;'></div>"); + doc.write("<div style='left:400px; top:0; width:100px; height:100px; position:absolute; background:blue;'></div>"); + + doc.write("<div style='left:0; top:100px; width:100px; height:100px; position:absolute; background: green;'></div>"); + doc.write("<div style='left:100px; top:100px; width:100px; height:100px; position:absolute; background:blue;'></div>"); + doc.write("<div style='left:200px; top:100px; width:100px; height:100px; position:absolute; background:green;'></div>"); + doc.write("<div style='left:300px; top:100px; width:100px; height:100px; position:absolute; background:blue;'></div>"); + doc.write("<div style='left:400px; top:100px; width:100px; height:100px; position:absolute; background:green;'></div>"); + doc.close(); + frame.contentDocument.body.style.width = "2000px"; + frame.contentDocument.body.style.height = "2000px"; +</script>
diff --git a/third_party/WebKit/LayoutTests/fast/innerHTML/806705-crash.html b/third_party/WebKit/LayoutTests/fast/innerHTML/806705-crash.html new file mode 100644 index 0000000..3cf0b22 --- /dev/null +++ b/third_party/WebKit/LayoutTests/fast/innerHTML/806705-crash.html
@@ -0,0 +1,9 @@ +<script src="../../resources/testharness.js"></script> +<script src="../../resources/testharnessreport.js"></script> +<script> +test(function() { +var d = document.implementation.createHTMLDocument(); +var e = d.body.innerHTML = '<noscript>noscript</noscript>'; +assert_equals(d.querySelector('noscript').innerHTML, 'noscript'); +}); +</script>
diff --git a/third_party/WebKit/LayoutTests/fast/loader/data-url-encoding-html.html b/third_party/WebKit/LayoutTests/fast/loader/data-url-encoding-html.html index dc4d14e..2760419 100644 --- a/third_party/WebKit/LayoutTests/fast/loader/data-url-encoding-html.html +++ b/third_party/WebKit/LayoutTests/fast/loader/data-url-encoding-html.html
@@ -13,6 +13,6 @@ } </script> <iframe src="data:text/html;charset=utf-8,<body>ðÒÏ×ÅÒËÁ</body>"></iframe> -<iframe src="data:text/html;charset=utf-8,<body foo='#'>ðÒÏ×ÅÒËÁ</body>"></iframe> +<iframe src="data:text/html;charset=utf-8,<body foo='%23'>ðÒÏ×ÅÒËÁ</body>"></iframe> <iframe src="data:text/html;charset=utf-8,<body>%D0%9F%D1%80%D0%BE%D0%B2%D0%B5%D1%80%D0%BA%D0%B0</body>"></iframe> </body>
diff --git a/third_party/WebKit/LayoutTests/fast/loader/data-url-encoding-svg.html b/third_party/WebKit/LayoutTests/fast/loader/data-url-encoding-svg.html index 25282191..0ae31d8 100644 --- a/third_party/WebKit/LayoutTests/fast/loader/data-url-encoding-svg.html +++ b/third_party/WebKit/LayoutTests/fast/loader/data-url-encoding-svg.html
@@ -17,6 +17,6 @@ <p>Test that non-ASCII data: URLs are handled correctly.</p> <pre id=result></pre> <iframe src="data:image/svg+xml;charset=utf-8,<svg xmlns=%22http://www.w3.org/2000/svg%22 test='ðÒÏ×ÅÒËÁ'></svg>"></iframe> -<iframe src="data:image/svg+xml;charset=utf-8,<svg xmlns=%22http://www.w3.org/2000/svg%22 foo='#' test='ðÒÏ×ÅÒËÁ'></svg>"></iframe> -<iframe src="data:image/svg+xml;charset=utf-8,<svg xmlns=%22http://www.w3.org/2000/svg%22 foo='#' test='%D0%9F%D1%80%D0%BE%D0%B2%D0%B5%D1%80%D0%BA%D0%B0'></svg>"></iframe> +<iframe src="data:image/svg+xml;charset=utf-8,<svg xmlns=%22http://www.w3.org/2000/svg%22 foo='%23' test='ðÒÏ×ÅÒËÁ'></svg>"></iframe> +<iframe src="data:image/svg+xml;charset=utf-8,<svg xmlns=%22http://www.w3.org/2000/svg%22 foo='%23' test='%D0%9F%D1%80%D0%BE%D0%B2%D0%B5%D1%80%D0%BA%D0%B0'></svg>"></iframe> </body>
diff --git a/third_party/WebKit/LayoutTests/fast/loader/document-open-iframe-then-detach-expected.txt b/third_party/WebKit/LayoutTests/fast/loader/document-open-iframe-then-detach-expected.txt new file mode 100644 index 0000000..ef3dbcd --- /dev/null +++ b/third_party/WebKit/LayoutTests/fast/loader/document-open-iframe-then-detach-expected.txt
@@ -0,0 +1 @@ +PASS if no timeout.
diff --git a/third_party/WebKit/LayoutTests/fast/loader/document-open-iframe-then-detach.html b/third_party/WebKit/LayoutTests/fast/loader/document-open-iframe-then-detach.html new file mode 100644 index 0000000..13d8531 --- /dev/null +++ b/third_party/WebKit/LayoutTests/fast/loader/document-open-iframe-then-detach.html
@@ -0,0 +1,11 @@ +PASS if no timeout. +<iframe id="i"></iframe> +<script> +if (window.testRunner) + testRunner.dumpAsText(); + +i.contentDocument.open(); +setTimeout(function() { + i.remove(); +}, 0); +</script>
diff --git a/third_party/WebKit/LayoutTests/fast/shapes/parsing/parsing-shape-outside-expected.txt b/third_party/WebKit/LayoutTests/fast/shapes/parsing/parsing-shape-outside-expected.txt index 3bc17ea..a991742 100644 --- a/third_party/WebKit/LayoutTests/fast/shapes/parsing/parsing-shape-outside-expected.txt +++ b/third_party/WebKit/LayoutTests/fast/shapes/parsing/parsing-shape-outside-expected.txt
@@ -1,3 +1,4 @@ +CONSOLE WARNING: line 199: Expressing a position using 3 parts is deprecated and will be removed in M68, around July 2018. Please use <position> syntax instead. See https://www.chromestatus.com/features/5116559680864256 for more details. Testing parsing of the shape-outside property. On success, you will see a series of "PASS" messages, followed by "TEST COMPLETE".
diff --git a/third_party/WebKit/LayoutTests/fast/spatial-navigation/resources/iframe.html b/third_party/WebKit/LayoutTests/fast/spatial-navigation/resources/iframe.html index 30388d5..09e1e6f 100644 --- a/third_party/WebKit/LayoutTests/fast/spatial-navigation/resources/iframe.html +++ b/third_party/WebKit/LayoutTests/fast/spatial-navigation/resources/iframe.html
@@ -2,14 +2,14 @@ <body> <iframe width='80%' height="70px" frameborder="0" src="data:text/html, <body> - <a id='1' href='#'>b</a> - <a id='2' href='#'>c</a> - <a id='3' href='#'>d</a> - <a id='4' href='#'>e</a> - <a id='5' href='#'>f</a> - <a id='6' href='#'>g</a> - <a id='7' href='#'>h</a> - <a id='8' href='#'>i</a> + <a id='1' href='%23'>b</a> + <a id='2' href='%23'>c</a> + <a id='3' href='%23'>d</a> + <a id='4' href='%23'>e</a> + <a id='5' href='%23'>f</a> + <a id='6' href='%23'>g</a> + <a id='7' href='%23'>h</a> + <a id='8' href='%23'>i</a> </body> "></iframe> </body>
diff --git a/third_party/WebKit/LayoutTests/fast/spatial-navigation/snav-iframe-with-outside-focusable-element.html b/third_party/WebKit/LayoutTests/fast/spatial-navigation/snav-iframe-with-outside-focusable-element.html index 668a682..be7a38d 100644 --- a/third_party/WebKit/LayoutTests/fast/spatial-navigation/snav-iframe-with-outside-focusable-element.html +++ b/third_party/WebKit/LayoutTests/fast/spatial-navigation/snav-iframe-with-outside-focusable-element.html
@@ -34,7 +34,7 @@ <a id="start" href="#">Start</a><br> <iframe src="data:text/html, - <a id='1' href='#' style='margin-left: 125px'>a</a>" + <a id='1' href='%23' style='margin-left: 125px'>a</a>" ></iframe><br> <a id="2" href="#">b</a> <a id="end" href="#" style="margin-left: 125px;">End</a>
diff --git a/third_party/WebKit/LayoutTests/html/document_metadata/link-rel-stylesheet.html b/third_party/WebKit/LayoutTests/html/document_metadata/link-rel-stylesheet.html index 8e631ee..0653a4ca 100644 --- a/third_party/WebKit/LayoutTests/html/document_metadata/link-rel-stylesheet.html +++ b/third_party/WebKit/LayoutTests/html/document_metadata/link-rel-stylesheet.html
@@ -2,10 +2,10 @@ <html> <head> <title>Test for importing styles via incorrect link element</title> -<link type="text/css" href="data:text/css;charset=utf-8,p#one%20%7Bbackground-color%3A%20red%3B%7D%0D%0A"/> -<link rel="stylesheet" href="data:text/css;charset=utf-8,p#two%20%7Bbackground-color%3A%20lime%3B%7D%0D%0A"/> -<link href="data:text/css;charset=utf-8,p#three%20%7Bbackground-color%3A%20red%3B%7D%0D%0A"/> -<link type="text/css" rel="stylesheet" href="data:text/css;charset=utf-8,p#four%20%7Bbackground-color%3A%20lime%3B%7D%0D%0A"/> +<link type="text/css" href="data:text/css;charset=utf-8,p%23one%20%7Bbackground-color%3A%20red%3B%7D%0D%0A"/> +<link rel="stylesheet" href="data:text/css;charset=utf-8,p%23two%20%7Bbackground-color%3A%20lime%3B%7D%0D%0A"/> +<link href="data:text/css;charset=utf-8,p%23three%20%7Bbackground-color%3A%20red%3B%7D%0D%0A"/> +<link type="text/css" rel="stylesheet" href="data:text/css;charset=utf-8,p%23four%20%7Bbackground-color%3A%20lime%3B%7D%0D%0A"/> </head> <body> <p id="one">This line should not have red background</p>
diff --git a/third_party/WebKit/LayoutTests/http/tests/devtools/console/console-correct-suggestions-expected.txt b/third_party/WebKit/LayoutTests/http/tests/devtools/console/console-correct-suggestions-expected.txt index 56a21c7..6cfaf4b 100644 --- a/third_party/WebKit/LayoutTests/http/tests/devtools/console/console-correct-suggestions-expected.txt +++ b/third_party/WebKit/LayoutTests/http/tests/devtools/console/console-correct-suggestions-expected.txt
@@ -155,4 +155,10 @@ Checking 'complicatedObject["notDangerous();' Found: "notDangerous();"], displayed as "notDangerous();" +Checking 'queryOb' +Found: queryObjects + +Checking 'fun' +Found: function +
diff --git a/third_party/WebKit/LayoutTests/http/tests/devtools/console/console-correct-suggestions.js b/third_party/WebKit/LayoutTests/http/tests/devtools/console/console-correct-suggestions.js index f68a830..1da6a99a 100644 --- a/third_party/WebKit/LayoutTests/http/tests/devtools/console/console-correct-suggestions.js +++ b/third_party/WebKit/LayoutTests/http/tests/devtools/console/console-correct-suggestions.js
@@ -30,6 +30,11 @@ var consoleEditor; + /** + * @param {string} text + * @param {!Array<string>} expected + * @param {boolean=} force + */ function testCompletions(text, expected, force) { var cursorPosition = text.indexOf('|'); @@ -41,8 +46,11 @@ consoleEditor._autocompleteController.autocomplete(force); return TestRunner.addSnifferPromise(consoleEditor._autocompleteController, '_onSuggestionsShownForTest').then(checkExpected); + /** + * @param {!Array<{text: string, title: string}>} suggestions + */ function checkExpected(suggestions) { - var completions = new Map(suggestions.map(suggestion => [suggestion.text, suggestion])); + var completions = new Map(suggestions.map(suggestion => [suggestion, suggestion.text])).inverse(); var message = 'Checking \'' + text.replace('\n', '\\n').replace('\r', '\\r') + '\''; if (force) @@ -52,10 +60,12 @@ for (var i = 0; i < expected.length; i++) { if (completions.has(expected[i])) { - if (completions.get(expected[i]).title) - TestRunner.addResult('Found: ' + expected[i] + ', displayed as ' + completions.get(expected[i]).title); - else - TestRunner.addResult('Found: ' + expected[i]); + for (var completion of completions.get(expected[i])) { + if (completion.title) + TestRunner.addResult('Found: ' + expected[i] + ', displayed as ' + completion.title); + else + TestRunner.addResult('Found: ' + expected[i]); + } } else { TestRunner.addResult('Not Found: ' + expected[i]); } @@ -122,6 +132,8 @@ () => testCompletions('complicatedObject[\'\\\'sing', ['\'\\\'single-qouted\\\'\']']), () => testCompletions('complicatedObject["\'single-qou', ['"\'single-qouted\'"]']), () => testCompletions('complicatedObject["\\"double-qouted\\"', ['"\\"double-qouted\\""]']), - () => testCompletions('complicatedObject["notDangerous();', ['"notDangerous();"]']) + () => testCompletions('complicatedObject["notDangerous();', ['"notDangerous();"]']), + () => testCompletions('queryOb', ["queryObjects"]), + () => testCompletions('fun', ['function']) ]).then(TestRunner.completeTest); })();
diff --git a/third_party/WebKit/LayoutTests/http/tests/devtools/extensions/resources/extensions-network.html b/third_party/WebKit/LayoutTests/http/tests/devtools/extensions/resources/extensions-network.html index 92b74dc0..d9d82da 100644 --- a/third_party/WebKit/LayoutTests/http/tests/devtools/extensions/resources/extensions-network.html +++ b/third_party/WebKit/LayoutTests/http/tests/devtools/extensions/resources/extensions-network.html
@@ -10,8 +10,7 @@ <img src="missing-image.png"> <script> function doXHR() { - return fetch('extensions-network.html') - .then(response => response.arrayBuffer()); + return fetch('extensions-network.html'); } </script> <p>some text.</p>
diff --git a/third_party/WebKit/LayoutTests/http/tests/inspector-protocol/audits/get-encoded-response.js b/third_party/WebKit/LayoutTests/http/tests/inspector-protocol/audits/get-encoded-response.js index 87c2cde..e90d7cc 100644 --- a/third_party/WebKit/LayoutTests/http/tests/inspector-protocol/audits/get-encoded-response.js +++ b/third_party/WebKit/LayoutTests/http/tests/inspector-protocol/audits/get-encoded-response.js
@@ -11,8 +11,7 @@ async function logResponse(url, encoding, quality, sizeOnly) { testRunner.log(`\nResults for ${url} encoding=${encoding} q=${quality} sizeOnly=${sizeOnly}`); - session.evaluate(`fetch(${JSON.stringify(url)}) - .then(response => response.arrayBuffer())`); + session.evaluate(`fetch(${JSON.stringify(url)})`); const requestId = (await dp.Network.onceResponseReceived()).params.requestId; const result = (await dp.Audits.getEncodedResponse({requestId, encoding, quality, sizeOnly})).result;
diff --git a/third_party/WebKit/LayoutTests/http/tests/inspector-protocol/network-data-length.js b/third_party/WebKit/LayoutTests/http/tests/inspector-protocol/network-data-length.js index 85fced0..7a74640 100644 --- a/third_party/WebKit/LayoutTests/http/tests/inspector-protocol/network-data-length.js +++ b/third_party/WebKit/LayoutTests/http/tests/inspector-protocol/network-data-length.js
@@ -10,9 +10,7 @@ var pendingRequests = 0; function sendRequest(url) { - dp.Runtime.evaluate({expression: ` - fetch('${url}') - .then(response => response.arrayBuffer())`}); + dp.Runtime.evaluate({expression: `fetch('${url}')`}); pendingRequests++; }
diff --git a/third_party/WebKit/LayoutTests/http/tests/inspector-protocol/network/get-response-body.js b/third_party/WebKit/LayoutTests/http/tests/inspector-protocol/network/get-response-body.js index 32292fd..7090d712 100644 --- a/third_party/WebKit/LayoutTests/http/tests/inspector-protocol/network/get-response-body.js +++ b/third_party/WebKit/LayoutTests/http/tests/inspector-protocol/network/get-response-body.js
@@ -5,8 +5,7 @@ await dp.Network.enable(); async function logResponseBody(url) { - session.evaluate(`fetch(${JSON.stringify(url)}) - .then(response => response.arrayBuffer())`); + session.evaluate(`fetch(${JSON.stringify(url)});`); var requestWillBeSent = (await dp.Network.onceRequestWillBeSent()).params; testRunner.log(`Request for ${requestWillBeSent.request.url}`);
diff --git a/third_party/WebKit/LayoutTests/http/tests/inspector-protocol/network/override-referer-with-downgrade.js b/third_party/WebKit/LayoutTests/http/tests/inspector-protocol/network/override-referer-with-downgrade.js index b7a38d9..c60fd99 100644 --- a/third_party/WebKit/LayoutTests/http/tests/inspector-protocol/network/override-referer-with-downgrade.js +++ b/third_party/WebKit/LayoutTests/http/tests/inspector-protocol/network/override-referer-with-downgrade.js
@@ -5,8 +5,7 @@ dp.Network.enable(); await dp.Network.setExtraHTTPHeaders({headers: {'ReFeReR': 'https://127.0.0.1:8000/'}}); - session.evaluate(`fetch('${testRunner.url('./resources/echo-headers.php?headers=HTTP_REFERER')}') - .then(response => response.arrayBuffer())`); + session.evaluate(`fetch('${testRunner.url('./resources/echo-headers.php?headers=HTTP_REFERER')}')`); var response = (await dp.Network.onceLoadingFinished()).params; var content = await dp.Network.getResponseBody({requestId: response.requestId});
diff --git a/third_party/WebKit/LayoutTests/http/tests/inspector-protocol/network/request-interception-on-both-redirect-rewrite.js b/third_party/WebKit/LayoutTests/http/tests/inspector-protocol/network/request-interception-on-both-redirect-rewrite.js index 0c8604dc..1e31efa1 100644 --- a/third_party/WebKit/LayoutTests/http/tests/inspector-protocol/network/request-interception-on-both-redirect-rewrite.js +++ b/third_party/WebKit/LayoutTests/http/tests/inspector-protocol/network/request-interception-on-both-redirect-rewrite.js
@@ -18,8 +18,7 @@ ]}); testRunner.log('Request interception patterns sent.'); - session.evaluate(`fetch('${testRunner.url('../resources/redirect1.php')}') - .then(response => response.arrayBuffer())`); + session.evaluate(`fetch('${testRunner.url('../resources/redirect1.php')}')`); // Should be redirect1.php as request. var interceptionEvent = await waitForInterceptionEvent();
diff --git a/third_party/WebKit/LayoutTests/http/tests/inspector-protocol/network/request-interception-on-response-redirect.js b/third_party/WebKit/LayoutTests/http/tests/inspector-protocol/network/request-interception-on-response-redirect.js index 32e7233..8cab1976 100644 --- a/third_party/WebKit/LayoutTests/http/tests/inspector-protocol/network/request-interception-on-response-redirect.js +++ b/third_party/WebKit/LayoutTests/http/tests/inspector-protocol/network/request-interception-on-response-redirect.js
@@ -65,8 +65,7 @@ await new Promise(resolve => { session.protocol.Network.onResponseReceived(resolve); session.evaluate(` - fetch('${testRunner.url('../resources/ping-redirect.php')}') - .then(response => response.arrayBuffer()); + fetch('${testRunner.url('../resources/ping-redirect.php')}'); `); });
diff --git a/third_party/WebKit/LayoutTests/http/tests/inspector-protocol/network/request-interception-patterns.js b/third_party/WebKit/LayoutTests/http/tests/inspector-protocol/network/request-interception-patterns.js index 0a9c3dc..7b8b587 100644 --- a/third_party/WebKit/LayoutTests/http/tests/inspector-protocol/network/request-interception-patterns.js +++ b/third_party/WebKit/LayoutTests/http/tests/inspector-protocol/network/request-interception-patterns.js
@@ -71,14 +71,11 @@ * @return {!Promise} */ async function testUrls() { - session.evaluate(`fetch('../network/resources/small-test-1.txt') - .then(response => response.arrayBuffer())`); + session.evaluate(`fetch('../network/resources/small-test-1.txt')`); await new Promise(resolve => responseWasReceivedCallback = resolve); - session.evaluate(`fetch('../network/resources/small-test-2.txt') - .then(response => response.arrayBuffer())`); + session.evaluate(`fetch('../network/resources/small-test-2.txt')`); await new Promise(resolve => responseWasReceivedCallback = resolve); - session.evaluate(`fetch('../resources/test-page.html') - .then(response => response.arrayBuffer())`); + session.evaluate(`fetch('../resources/test-page.html')`); await new Promise(resolve => responseWasReceivedCallback = resolve); testRunner.log(''); }
diff --git a/third_party/WebKit/LayoutTests/http/tests/inspector-protocol/network/search-in-response.js b/third_party/WebKit/LayoutTests/http/tests/inspector-protocol/network/search-in-response.js index ba2f4c6..02b6c470 100644 --- a/third_party/WebKit/LayoutTests/http/tests/inspector-protocol/network/search-in-response.js +++ b/third_party/WebKit/LayoutTests/http/tests/inspector-protocol/network/search-in-response.js
@@ -4,8 +4,7 @@ await dp.Network.enable(); var url = testRunner.url('./resources/final.js'); - session.evaluate(`fetch("${url}") - .then(response => response.arrayBuffer());`); + session.evaluate(`fetch("${url}");`); var requestWillBeSent = (await dp.Network.onceRequestWillBeSent()).params; testRunner.log(`Request for ${requestWillBeSent.request.url}`);
diff --git a/third_party/WebKit/LayoutTests/http/tests/inspector-protocol/target/oopif-no-discovery.js b/third_party/WebKit/LayoutTests/http/tests/inspector-protocol/target/oopif-no-discovery.js index fd024c5..8aab24b 100644 --- a/third_party/WebKit/LayoutTests/http/tests/inspector-protocol/target/oopif-no-discovery.js +++ b/third_party/WebKit/LayoutTests/http/tests/inspector-protocol/target/oopif-no-discovery.js
@@ -6,8 +6,7 @@ await dp.Page.onceLoadEventFired(); testRunner.log('Enabling auto-discovery...'); - await dp.Target.setAutoAttach({autoAttach: true, waitForDebuggerOnStart: false}); - dp.Target.setAttachToFrames({value: true}); + dp.Target.setAutoAttach({autoAttach: true, waitForDebuggerOnStart: false}); let attachedEvent = (await dp.Target.onceAttachedToTarget()).params; testRunner.log('Got auto-attached.');
diff --git a/third_party/WebKit/LayoutTests/http/tests/inspector-protocol/target/wait-for-debugger.js b/third_party/WebKit/LayoutTests/http/tests/inspector-protocol/target/wait-for-debugger.js index 267cf81..0c943ea7 100644 --- a/third_party/WebKit/LayoutTests/http/tests/inspector-protocol/target/wait-for-debugger.js +++ b/third_party/WebKit/LayoutTests/http/tests/inspector-protocol/target/wait-for-debugger.js
@@ -3,7 +3,6 @@ `Tests that waitForDebuggerOnStart works with out-of-process iframes.`); await dp.Target.setAutoAttach({autoAttach: true, waitForDebuggerOnStart: true}); - await dp.Target.setAttachToFrames({value: true}); await dp.Page.enable(); dp.Network.enable();
diff --git a/third_party/WebKit/LayoutTests/http/tests/locks/query-empty.html b/third_party/WebKit/LayoutTests/http/tests/locks/query-empty.html new file mode 100644 index 0000000..a6133218 --- /dev/null +++ b/third_party/WebKit/LayoutTests/http/tests/locks/query-empty.html
@@ -0,0 +1,24 @@ +<!DOCTYPE html> +<meta charset=utf-8> +<title>Web Locks API: navigator.locks.query method - no locks held</title> +<link rel=help href="https://github.com/inexorabletash/web-locks"> +<script src="/resources/testharness.js"></script> +<script src="/resources/testharnessreport.js"></script> +<script src="resources/helpers.js"></script> +<script> +'use strict'; + +promise_test(async t => { + const state = await navigator.locks.query(); + + assert_own_property(state, 'pending', 'State has `pending` property'); + assert_true(Array.isArray(state.pending), + 'State `pending` property is an array'); + assert_array_equals(state.pending, [], 'Pending array is empty'); + + assert_own_property(state, 'held', 'State has `held` property'); + assert_true(Array.isArray(state.held), 'State `held` property is an array'); + assert_array_equals(state.held, [], 'Held array is empty'); +}, 'query() returns dictionary with empty arrays when no locks are held'); + +</script>
diff --git a/third_party/WebKit/LayoutTests/http/tests/performance-timing/longtask-v2/longtask-v8compile-expected.txt b/third_party/WebKit/LayoutTests/http/tests/performance-timing/longtask-v2/longtask-v8compile-expected.txt deleted file mode 100644 index ed3010d..0000000 --- a/third_party/WebKit/LayoutTests/http/tests/performance-timing/longtask-v2/longtask-v8compile-expected.txt +++ /dev/null
@@ -1,4 +0,0 @@ -This is a testharness.js-based test. -FAIL Performance longtask entries with script-compile attribute are observable. assert_false: script-compile is not captured. expected false got true -Harness: the test ran to completion. -
diff --git a/third_party/WebKit/LayoutTests/http/tests/performance-timing/longtask-v2/longtask-v8compile.html b/third_party/WebKit/LayoutTests/http/tests/performance-timing/longtask-v2/longtask-v8compile.html index 59a120e0..a8c2c15f 100644 --- a/third_party/WebKit/LayoutTests/http/tests/performance-timing/longtask-v2/longtask-v8compile.html +++ b/third_party/WebKit/LayoutTests/http/tests/performance-timing/longtask-v2/longtask-v8compile.html
@@ -10,12 +10,20 @@ <div id="log"></div> <script> async_test(function (t) { + const scriptURL = 'resources/makelongtask.js'; + const lineColumn = '(0, 0)'; const observer = new PerformanceObserver( - t.step_func(function (entryList) { - const entries = entryList.getEntries(); - assert_equals(entries.length, 1, - 'Exactly one entry is expected.'); - const longtask = entries[0]; + t.step_func(function(entryList) { + const longtaskEntries = entryList.getEntries().filter((e) => { + return e.attribution.find((a) => { + return a.scriptURL.includes(scriptURL); + }); + }); + if (longtaskEntries.length === 0) { + return; + } + assert_equals(longtaskEntries.length, 1); + const longtask = longtaskEntries[0]; assert_equals(longtask.entryType, 'longtask'); assert_equals(longtask.name, 'self'); assert_greater_than(longtask.duration, 50); @@ -23,17 +31,19 @@ const currentTime = performance.now(); assert_less_than_equal(longtask.startTime, currentTime); - const it = longtask.attribution.find(function(it) { - return it.name === 'script-compile'; + const compileAttribution = longtask.attribution.filter((it) => { + return it.name === 'script-compile' && + it.scriptURL.includes(scriptURL); }); - assert_false(!it, 'script-compile is not captured.'); + assert_equals(compileAttribution.length, 1); + const it = compileAttribution[0]; assert_greater_than(it.startTime, 0); assert_equals(it.entryType, 'taskattribution'); assert_equals(it.containerType, 'iframe'); assert_equals(it.containerId, ''); assert_equals(it.containerName, ''); assert_equals(it.containerSrc, ''); - assert_true(it.scriptURL.includes('resources/makelongtask.js(0, 0)')); + assert_true(it.scriptURL.includes(scriptURL + lineColumn)); observer.disconnect(); t.done(); })
diff --git a/third_party/WebKit/LayoutTests/inspector-protocol/accessibility/accessibility-nameSources-visiblity.js b/third_party/WebKit/LayoutTests/inspector-protocol/accessibility/accessibility-nameSources-visiblity.js index b84e9d7..e76a73ed 100644 --- a/third_party/WebKit/LayoutTests/inspector-protocol/accessibility/accessibility-nameSources-visiblity.js +++ b/third_party/WebKit/LayoutTests/inspector-protocol/accessibility/accessibility-nameSources-visiblity.js
@@ -14,7 +14,7 @@ <div class='tests'> <div data-dump id='link1' tabIndex=0 role='link'> <p>1</p> - <table> + <table role="presentation"> <tr><td>2</td></tr> <tr><td style='visibility: hidden'>3</td></tr> <tr><td style='display:none'>4</td></tr> @@ -27,7 +27,7 @@ <input data-dump id='input2' aria-labelledby='label2'> <div id='label2'> <p>1</p> - <table> + <table role="presentation"> <tr><td>2</td></tr> <tr><td style='visibility: hidden'>3</td></tr> <tr><td style='display:none'>4</td></tr> @@ -39,7 +39,7 @@ <input data-dump id='input3' aria-labelledby='3a 3b 3c 3d 3e 3f 3g'> <p id='3a'>1</p> - <table> + <table role="presentation"> <tr><td id='3b'>2</td></tr> <tr><td id='3c' style='visibility: hidden'>3</td></tr> <tr><td id='3d' style='display:none'>4</td></tr>
diff --git a/third_party/WebKit/LayoutTests/media/content/counting.mp4 b/third_party/WebKit/LayoutTests/media/content/counting.mp4 index 5fbd6d9..aaa3363 100644 --- a/third_party/WebKit/LayoutTests/media/content/counting.mp4 +++ b/third_party/WebKit/LayoutTests/media/content/counting.mp4 Binary files differ
diff --git a/third_party/WebKit/LayoutTests/media/media-controls.js b/third_party/WebKit/LayoutTests/media/media-controls.js index 380f8283..89837b9 100644 --- a/third_party/WebKit/LayoutTests/media/media-controls.js +++ b/third_party/WebKit/LayoutTests/media/media-controls.js
@@ -331,7 +331,7 @@ } function pictureInPictureInterstitial(videoElement) { - var controlID = '-internal-picture-in-picture-interstitial'; + var controlID = '-internal-picture-in-picture-message'; var interstitial = getElementByPseudoId(window.internals.shadowRoot(videoElement).firstChild, controlID); if (!interstitial) @@ -340,7 +340,7 @@ } function checkPictureInPictureInterstitialDoesNotExist(videoElement) { - var controlID = '-internal-picture-in-picture-interstitial'; + var controlID = '-internal-picture-in-picture-message'; var interstitial = getElementByPseudoId(internals.oldestShadowRoot(videoElement), controlID); if (interstitial)
diff --git a/third_party/WebKit/LayoutTests/platform/linux/editing/pasteboard/5032095-expected.png b/third_party/WebKit/LayoutTests/platform/linux/editing/pasteboard/5032095-expected.png deleted file mode 100644 index f5cc2b51..0000000 --- a/third_party/WebKit/LayoutTests/platform/linux/editing/pasteboard/5032095-expected.png +++ /dev/null Binary files differ
diff --git a/third_party/WebKit/LayoutTests/platform/linux/editing/pasteboard/5032095-expected.txt b/third_party/WebKit/LayoutTests/platform/linux/editing/pasteboard/5032095-expected.txt deleted file mode 100644 index 97dea279..0000000 --- a/third_party/WebKit/LayoutTests/platform/linux/editing/pasteboard/5032095-expected.txt +++ /dev/null
@@ -1,14 +0,0 @@ -layer at (0,0) size 800x600 - LayoutView at (0,0) size 800x600 -layer at (0,0) size 800x600 - LayoutBlockFlow {HTML} at (0,0) size 800x600 - LayoutBlockFlow {BODY} at (8,8) size 784x584 - LayoutBlockFlow {P} at (0,0) size 784x40 - LayoutText {#text} at (0,0) size 763x39 - text run at (0,0) width 690: "This tests for a bug where content pasted at the end of a paragraph would be inserted into the next paragraph. " - text run at (690,0) width 73: "You should" - text run at (0,20) width 144: "see 'helloworld' below." - LayoutBlockFlow {DIV} at (0,56) size 784x20 - LayoutText {#text} at (0,0) size 68x19 - text run at (0,0) width 68: "helloworld" -caret: position 10 of child 0 {#text} of child 2 {DIV} of body
diff --git a/third_party/WebKit/LayoutTests/platform/linux/editing/selection/move-by-word-001-expected.png b/third_party/WebKit/LayoutTests/platform/linux/editing/selection/move-by-word-001-expected.png deleted file mode 100644 index 4fdee79..0000000 --- a/third_party/WebKit/LayoutTests/platform/linux/editing/selection/move-by-word-001-expected.png +++ /dev/null Binary files differ
diff --git a/third_party/WebKit/LayoutTests/platform/mac/editing/pasteboard/5032095-expected.png b/third_party/WebKit/LayoutTests/platform/mac/editing/pasteboard/5032095-expected.png deleted file mode 100644 index 2d61df0..0000000 --- a/third_party/WebKit/LayoutTests/platform/mac/editing/pasteboard/5032095-expected.png +++ /dev/null Binary files differ
diff --git a/third_party/WebKit/LayoutTests/platform/mac/editing/pasteboard/5032095-expected.txt b/third_party/WebKit/LayoutTests/platform/mac/editing/pasteboard/5032095-expected.txt deleted file mode 100644 index 73e47bfb..0000000 --- a/third_party/WebKit/LayoutTests/platform/mac/editing/pasteboard/5032095-expected.txt +++ /dev/null
@@ -1,14 +0,0 @@ -layer at (0,0) size 800x600 - LayoutView at (0,0) size 800x600 -layer at (0,0) size 800x600 - LayoutBlockFlow {HTML} at (0,0) size 800x600 - LayoutBlockFlow {BODY} at (8,8) size 784x584 - LayoutBlockFlow {P} at (0,0) size 784x36 - LayoutText {#text} at (0,0) size 775x36 - text run at (0,0) width 702: "This tests for a bug where content pasted at the end of a paragraph would be inserted into the next paragraph. " - text run at (701,0) width 74: "You should" - text run at (0,18) width 146: "see 'helloworld' below." - LayoutBlockFlow {DIV} at (0,52) size 784x18 - LayoutText {#text} at (0,0) size 70x18 - text run at (0,0) width 70: "helloworld" -caret: position 10 of child 0 {#text} of child 2 {DIV} of body
diff --git a/third_party/WebKit/LayoutTests/platform/mac/editing/selection/move-by-word-001-expected.png b/third_party/WebKit/LayoutTests/platform/mac/editing/selection/move-by-word-001-expected.png deleted file mode 100644 index 17d63651..0000000 --- a/third_party/WebKit/LayoutTests/platform/mac/editing/selection/move-by-word-001-expected.png +++ /dev/null Binary files differ
diff --git a/third_party/WebKit/LayoutTests/platform/mac/editing/selection/move-by-word-001-expected.txt b/third_party/WebKit/LayoutTests/platform/mac/editing/selection/move-by-word-001-expected.txt deleted file mode 100644 index a2c265c..0000000 --- a/third_party/WebKit/LayoutTests/platform/mac/editing/selection/move-by-word-001-expected.txt +++ /dev/null
@@ -1,18 +0,0 @@ -EDITING DELEGATE: webViewDidChangeSelection:WebViewDidChangeSelectionNotification -EDITING DELEGATE: webViewDidChangeSelection:WebViewDidChangeSelectionNotification -EDITING DELEGATE: webViewDidChangeSelection:WebViewDidChangeSelectionNotification -EDITING DELEGATE: webViewDidChangeSelection:WebViewDidChangeSelectionNotification -layer at (0,0) size 800x600 - LayoutView at (0,0) size 800x600 -layer at (0,0) size 800x600 - LayoutBlockFlow {HTML} at (0,0) size 800x600 - LayoutBlockFlow {BODY} at (8,8) size 784x584 - LayoutBlockFlow {DIV} at (0,0) size 784x84 [border: (2px solid #FF0000)] - LayoutBlockFlow {DIV} at (14,14) size 756x28 - LayoutText {#text} at (0,0) size 32x28 - text run at (0,0) width 32: "foo" - LayoutBlockFlow (anonymous) at (14,42) size 756x28 - LayoutText {#text} at (0,0) size 31x28 - text run at (0,0) width 31: "bar" -selection start: position 0 of child 2 {#text} of child 1 {DIV} of body -selection end: position 3 of child 2 {#text} of child 1 {DIV} of body
diff --git a/third_party/WebKit/LayoutTests/platform/mac/virtual/pointerevent/fast/events/scale-and-scroll-iframe-window-expected.png b/third_party/WebKit/LayoutTests/platform/mac/virtual/pointerevent/fast/events/scale-and-scroll-iframe-window-expected.png deleted file mode 100644 index f0dc220..0000000 --- a/third_party/WebKit/LayoutTests/platform/mac/virtual/pointerevent/fast/events/scale-and-scroll-iframe-window-expected.png +++ /dev/null Binary files differ
diff --git a/third_party/WebKit/LayoutTests/platform/win/editing/pasteboard/5032095-expected.png b/third_party/WebKit/LayoutTests/platform/win/editing/pasteboard/5032095-expected.png deleted file mode 100644 index 98806cc..0000000 --- a/third_party/WebKit/LayoutTests/platform/win/editing/pasteboard/5032095-expected.png +++ /dev/null Binary files differ
diff --git a/third_party/WebKit/LayoutTests/platform/win/editing/pasteboard/5032095-expected.txt b/third_party/WebKit/LayoutTests/platform/win/editing/pasteboard/5032095-expected.txt deleted file mode 100644 index 01e103d..0000000 --- a/third_party/WebKit/LayoutTests/platform/win/editing/pasteboard/5032095-expected.txt +++ /dev/null
@@ -1,14 +0,0 @@ -layer at (0,0) size 800x600 - LayoutView at (0,0) size 800x600 -layer at (0,0) size 800x600 - LayoutBlockFlow {HTML} at (0,0) size 800x600 - LayoutBlockFlow {BODY} at (8,8) size 784x584 - LayoutBlockFlow {P} at (0,0) size 784x40 - LayoutText {#text} at (0,0) size 755x39 - text run at (0,0) width 663: "This tests for a bug where content pasted at the end of a paragraph would be inserted into the next paragraph. " - text run at (663,0) width 92: "You should see" - text run at (0,20) width 113: "'helloworld' below." - LayoutBlockFlow {DIV} at (0,56) size 784x20 - LayoutText {#text} at (0,0) size 63x19 - text run at (0,0) width 63: "helloworld" -caret: position 10 of child 0 {#text} of child 2 {DIV} of body
diff --git a/third_party/WebKit/LayoutTests/platform/win/editing/selection/move-by-word-001-expected.png b/third_party/WebKit/LayoutTests/platform/win/editing/selection/move-by-word-001-expected.png deleted file mode 100644 index d7c4312..0000000 --- a/third_party/WebKit/LayoutTests/platform/win/editing/selection/move-by-word-001-expected.png +++ /dev/null Binary files differ
diff --git a/third_party/WebKit/LayoutTests/platform/win/editing/selection/move-by-word-001-expected.txt b/third_party/WebKit/LayoutTests/platform/win/editing/selection/move-by-word-001-expected.txt deleted file mode 100644 index 82eb9c0e..0000000 --- a/third_party/WebKit/LayoutTests/platform/win/editing/selection/move-by-word-001-expected.txt +++ /dev/null
@@ -1,18 +0,0 @@ -EDITING DELEGATE: webViewDidChangeSelection:WebViewDidChangeSelectionNotification -EDITING DELEGATE: webViewDidChangeSelection:WebViewDidChangeSelectionNotification -EDITING DELEGATE: webViewDidChangeSelection:WebViewDidChangeSelectionNotification -EDITING DELEGATE: webViewDidChangeSelection:WebViewDidChangeSelectionNotification -layer at (0,0) size 800x600 - LayoutView at (0,0) size 800x600 -layer at (0,0) size 800x600 - LayoutBlockFlow {HTML} at (0,0) size 800x600 - LayoutBlockFlow {BODY} at (8,8) size 784x584 - LayoutBlockFlow {DIV} at (0,0) size 784x84 [border: (2px solid #FF0000)] - LayoutBlockFlow {DIV} at (14,14) size 756x28 - LayoutText {#text} at (0,0) size 32x27 - text run at (0,0) width 32: "foo" - LayoutBlockFlow (anonymous) at (14,42) size 756x28 - LayoutText {#text} at (0,0) size 31x27 - text run at (0,0) width 31: "bar" -selection start: position 0 of child 2 {#text} of child 1 {DIV} of body -selection end: position 3 of child 2 {#text} of child 1 {DIV} of body
diff --git a/third_party/WebKit/LayoutTests/platform/win/virtual/pointerevent/fast/events/scale-and-scroll-iframe-window-expected.png b/third_party/WebKit/LayoutTests/platform/win/virtual/pointerevent/fast/events/scale-and-scroll-iframe-window-expected.png deleted file mode 100644 index 1c932ef5..0000000 --- a/third_party/WebKit/LayoutTests/platform/win/virtual/pointerevent/fast/events/scale-and-scroll-iframe-window-expected.png +++ /dev/null Binary files differ
diff --git a/third_party/WebKit/LayoutTests/svg/canvas/canvas-draw-image-globalalpha.html b/third_party/WebKit/LayoutTests/svg/canvas/canvas-draw-image-globalalpha.html index 24ba5cd..dbd247d6 100644 --- a/third_party/WebKit/LayoutTests/svg/canvas/canvas-draw-image-globalalpha.html +++ b/third_party/WebKit/LayoutTests/svg/canvas/canvas-draw-image-globalalpha.html
@@ -2,7 +2,7 @@ <canvas width=100 height=100></canvas> <script> var img = new Image(); -img.src = 'data:image/svg+xml,<svg xmlns="http://www.w3.org/2000/svg"><rect width="100" height="100" fill="#008000"/></svg>'; +img.src = 'data:image/svg+xml,<svg xmlns="http://www.w3.org/2000/svg"><rect width="100" height="100" fill="%23008000"/></svg>'; img.onload = function() { var c = document.querySelector('canvas').getContext('2d'); c.globalAlpha = 0.5;
diff --git a/third_party/WebKit/LayoutTests/typedcssom/resources/testhelper.js b/third_party/WebKit/LayoutTests/typedcssom/resources/testhelper.js index 9e5bfd1..67a3227 100644 --- a/third_party/WebKit/LayoutTests/typedcssom/resources/testhelper.js +++ b/third_party/WebKit/LayoutTests/typedcssom/resources/testhelper.js
@@ -123,7 +123,7 @@ test.add_cleanup(() => { style.remove(); }); - return rule.attributeStyleMap; + return rule.styleMap; } // Creates a new element with background image set to |imageValue|
diff --git a/third_party/WebKit/LayoutTests/typedcssom/the-stylepropertymap/declared/delete-rule-crash.html b/third_party/WebKit/LayoutTests/typedcssom/the-stylepropertymap/declared/delete-rule-crash.html index 87c86d7..8f9ade7 100644 --- a/third_party/WebKit/LayoutTests/typedcssom/the-stylepropertymap/declared/delete-rule-crash.html +++ b/third_party/WebKit/LayoutTests/typedcssom/the-stylepropertymap/declared/delete-rule-crash.html
@@ -12,7 +12,7 @@ <script> test(() => { var sheet = document.styleSheets[0]; - var styleMap = sheet.cssRules[0].attributeStyleMap; + var styleMap = sheet.cssRules[0].styleMap; sheet.deleteRule(0); gc();
diff --git a/third_party/WebKit/LayoutTests/virtual/reporting-api/external/wpt/content-security-policy/reporting-api/README.txt b/third_party/WebKit/LayoutTests/virtual/reporting-api/external/wpt/content-security-policy/reporting-api/README.txt index 52d9ec4..40491ade 100644 --- a/third_party/WebKit/LayoutTests/virtual/reporting-api/external/wpt/content-security-policy/reporting-api/README.txt +++ b/third_party/WebKit/LayoutTests/virtual/reporting-api/external/wpt/content-security-policy/reporting-api/README.txt
@@ -1,2 +1,2 @@ -# This suite runs the tests in external/wpt/content-security-policy/reporting +# This suite runs the tests in external/wpt/content-security-policy/reporting-api # with the flag --enable-feature=Reporting
diff --git a/third_party/WebKit/LayoutTests/webexposed/global-interface-listing-expected.txt b/third_party/WebKit/LayoutTests/webexposed/global-interface-listing-expected.txt index 42c3b74..d3bfbc9 100644 --- a/third_party/WebKit/LayoutTests/webexposed/global-interface-listing-expected.txt +++ b/third_party/WebKit/LayoutTests/webexposed/global-interface-listing-expected.txt
@@ -793,9 +793,9 @@ setter cssText interface CSSStyleRule : CSSRule attribute @@toStringTag - getter attributeStyleMap getter selectorText getter style + getter styleMap method constructor setter selectorText setter style
diff --git a/third_party/WebKit/LayoutTests/xr/events_deviceconnect.html b/third_party/WebKit/LayoutTests/xr/events_deviceconnect.html index 4aa162e2..c3e1ba6 100644 --- a/third_party/WebKit/LayoutTests/xr/events_deviceconnect.html +++ b/third_party/WebKit/LayoutTests/xr/events_deviceconnect.html
@@ -1,33 +1,29 @@ <!DOCTYPE html> <script src="../resources/testharness.js"></script> <script src="../resources/testharnessreport.js"></script> -<script src="../vr/resources/fake-vr-displays.js"></script> <script src="file:///gen/layout_test_data/mojo/public/js/mojo_bindings.js"></script> <script src="file:///gen/device/vr/vr_service.mojom.js"></script> -<script src="../vr/resources/mock-vr-service.js"></script> +<script src="../xr/resources/xr-device-mocking.js"></script> +<script src="../xr/resources/xr-test-utils.js"></script> <canvas id="webgl-canvas"></canvas> <script> -let fakeDisplays = fakeVRDisplays(); +promise_test((t) => { + setFakeDevices([fakeXRDevices()["FakeGooglePixelPhone"]]); -vr_test((t, mockService) => { let watcherDone = new Event("watcherdone"); let eventWatcher = new EventWatcher(t, navigator.xr, ["devicechange", "watcherdone"]); - eventWatcher.wait_for(["devicechange", "watcherdone"]) - .then( () => { - t.done(); - }); // The event should fire when a listener is added even if the devices are not // explicity queried with navigator.xr.requestDevice(). function onDeviceChange() { - t.step( () => { - navigator.xr.dispatchEvent(watcherDone); - }); - } + navigator.xr.dispatchEvent(watcherDone); + }; + navigator.xr.addEventListener("devicechange", onDeviceChange, false); -}, [fakeDisplays["Pixel"]], -"Test devicechange fires when devices are connected."); + return eventWatcher.wait_for(["devicechange", "watcherdone"]); + +}, "Test devicechange fires when devices are connected."); </script>
diff --git a/third_party/WebKit/LayoutTests/xr/events_session_end.html b/third_party/WebKit/LayoutTests/xr/events_session_end.html index 0003e36..5491d09 100644 --- a/third_party/WebKit/LayoutTests/xr/events_session_end.html +++ b/third_party/WebKit/LayoutTests/xr/events_session_end.html
@@ -1,48 +1,32 @@ <!DOCTYPE html> <script src="../resources/testharness.js"></script> <script src="../resources/testharnessreport.js"></script> -<script src="../vr/resources/fake-vr-displays.js"></script> <script src="file:///gen/layout_test_data/mojo/public/js/mojo_bindings.js"></script> <script src="file:///gen/device/vr/vr_service.mojom.js"></script> -<script src="../vr/resources/mock-vr-service.js"></script> +<script src="../xr/resources/xr-device-mocking.js"></script> +<script src="../xr/resources/xr-test-utils.js"></script> <canvas id="webgl-canvas"></canvas> -<script src="../vr/resources/presentation-setup.js"></script> + <script> -let fakeDisplays = fakeVRDisplays(); -vr_test((t, mockService) => { - let watcherDone = new Event("watcherdone"); +let fakeDevices = fakeXRDevices(); +let watcherDone = new Event("watcherdone"); - navigator.xr.requestDevice().then( (device) => { - runWithUserGesture( () => { - device.requestSession({ exclusive: true }).then( (session) => { - let eventWatcher = new EventWatcher(t, session, ["end", "watcherdone"]); - let eventPromise = eventWatcher.wait_for(["end", "watcherdone"]); +xr_session_promise_test( (session, t) => { + let eventWatcher = new EventWatcher(t, session, ["end", "watcherdone"]); + let eventPromise = eventWatcher.wait_for(["end", "watcherdone"]); - function onSessionEnd(event) { - t.step( () => { - assert_equals(event.session, session); - session.dispatchEvent(watcherDone); - }); - } - session.addEventListener("end", onSessionEnd, false); - session.end(); - - return eventPromise; - }, (err) => { - t.step( () => { - assert_unreached("requestSession rejected"); - }); - }).then( () => { - t.done(); - }); - }); - }, (err) => { + function onSessionEnd(event) { t.step( () => { - assert_unreached("requestDevice rejected"); + assert_equals(event.session, session); + session.dispatchEvent(watcherDone); }); - }); -}, [fakeDisplays["Pixel"]], -"Test deviceconnect fires when devices are connected."); + } + session.addEventListener("end", onSessionEnd, false); + session.end(); + + return eventPromise; +}, fakeDevices["FakeGooglePixelPhone"], { exclusive: true }, +"Test end fires when session ends"); </script>
diff --git a/third_party/WebKit/LayoutTests/xr/exclusive_requestFrame_called.html b/third_party/WebKit/LayoutTests/xr/exclusive_requestFrame_called.html index df0247dc..4150d936 100644 --- a/third_party/WebKit/LayoutTests/xr/exclusive_requestFrame_called.html +++ b/third_party/WebKit/LayoutTests/xr/exclusive_requestFrame_called.html
@@ -1,28 +1,27 @@ <!DOCTYPE html> <script src="../resources/testharness.js"></script> <script src="../resources/testharnessreport.js"></script> -<script src="../vr/resources/fake-vr-displays.js"></script> <script src="file:///gen/layout_test_data/mojo/public/js/mojo_bindings.js"></script> <script src="file:///gen/device/vr/vr_service.mojom.js"></script> -<script src="../vr/resources/mock-vr-service.js"></script> +<script src="../xr/resources/xr-device-mocking.js"></script> +<script src="../xr/resources/xr-test-utils.js"></script> <canvas id="webgl-canvas"></canvas> -<script src="../vr/resources/presentation-setup.js"></script> + <script> -let fakeDisplays = fakeVRDisplays(); +let fakeDevices = fakeXRDevices(); -xr_session_test( (t, session) => { - // Session must have a baseLayer or frame requests will be ignored. - session.baseLayer = new XRWebGLLayer(session, gl); +xr_session_promise_test( (session) => new Promise((resolve) => { + // Session must have a baseLayer or frame requests will be ignored. + session.baseLayer = new XRWebGLLayer(session, gl); - function onFrame(time, xrFrame) { - t.step( () => { + function onFrame(time, xrFrame) { assert_true(xrFrame instanceof XRPresentationFrame); - }); - t.done(); - } + // Test does not complete until the returned promise resolves. + resolve(); + } - session.requestAnimationFrame(onFrame); -}, fakeDisplays["Pixel"], { exclusive: true }, + session.requestAnimationFrame(onFrame); + }), fakeDevices["FakeGooglePixelPhone"], { exclusive: true }, "XRSession requestAnimationFrame properly calls the provided callback"); </script>
diff --git a/third_party/WebKit/LayoutTests/xr/exclusive_requestFrame_invalidhandle.html b/third_party/WebKit/LayoutTests/xr/exclusive_requestFrame_invalidhandle.html index c9c124f..c468168 100644 --- a/third_party/WebKit/LayoutTests/xr/exclusive_requestFrame_invalidhandle.html +++ b/third_party/WebKit/LayoutTests/xr/exclusive_requestFrame_invalidhandle.html
@@ -1,16 +1,17 @@ <!DOCTYPE html> <script src="../resources/testharness.js"></script> <script src="../resources/testharnessreport.js"></script> -<script src="../vr/resources/fake-vr-displays.js"></script> + <script src="file:///gen/layout_test_data/mojo/public/js/mojo_bindings.js"></script> <script src="file:///gen/device/vr/vr_service.mojom.js"></script> -<script src="../vr/resources/mock-vr-service.js"></script> +<script src="../xr/resources/xr-device-mocking.js"></script> +<script src="../xr/resources/xr-test-utils.js"></script> <canvas id="webgl-canvas"></canvas> -<script src="../vr/resources/presentation-setup.js"></script> -<script> -let fakeDisplays = fakeVRDisplays(); -xr_session_test( (t, session) => { +<script> +let fakeDevices = fakeXRDevices(); + +xr_session_promise_test( (session) => new Promise((resolve) => { // Session must have a baseLayer or frame requests will be ignored. session.baseLayer = new XRWebGLLayer(session, gl); @@ -18,12 +19,12 @@ function onFrame(time, vrFrame) { // Intentionally session.requestAnimationFrame at the beginning, ensuring that - // there's an outstanding callback when t.done() is called. This is to make + // there's an outstanding callback when the test completes. This is to make // sure it doesn't cause any unexpected behavior like it did with // crbug.com/679401 session.requestAnimationFrame(onFrame); if (counter > 10) { - t.done(); + resolve(); } counter++; } @@ -35,7 +36,7 @@ session.cancelAnimationFrame(handle - 1); session.cancelAnimationFrame(0.5); session.cancelAnimationFrame(null); -}, fakeDisplays["Pixel"], { exclusive: true }, +}), fakeDevices["FakeGooglePixelPhone"], { exclusive: true }, "XRSession cancelAnimationFrame does not have unexpected behavior when given invalid handles"); </script>
diff --git a/third_party/WebKit/LayoutTests/xr/exclusive_requestFrame_nolayer.html b/third_party/WebKit/LayoutTests/xr/exclusive_requestFrame_nolayer.html index cf789e9..44e1289 100644 --- a/third_party/WebKit/LayoutTests/xr/exclusive_requestFrame_nolayer.html +++ b/third_party/WebKit/LayoutTests/xr/exclusive_requestFrame_nolayer.html
@@ -1,47 +1,39 @@ <!DOCTYPE html> <script src="../resources/testharness.js"></script> <script src="../resources/testharnessreport.js"></script> -<script src="../vr/resources/fake-vr-displays.js"></script> <script src="file:///gen/layout_test_data/mojo/public/js/mojo_bindings.js"></script> <script src="file:///gen/device/vr/vr_service.mojom.js"></script> -<script src="../vr/resources/mock-vr-service.js"></script> +<script src="../xr/resources/xr-device-mocking.js"></script> +<script src="../xr/resources/xr-test-utils.js"></script> <canvas id="webgl-canvas"></canvas> -<script src="../vr/resources/presentation-setup.js"></script> -<script> -let fakeDisplays = fakeVRDisplays(); -xr_session_test( (t, session) => { +<script> +let fakeDevices = fakeXRDevices(); + +xr_session_promise_test( (session) => new Promise((resolve, reject) => { // Session must have a baseLayer or frame requests will be ignored. let webglLayer = new XRWebGLLayer(session, gl); function onBadFrame(time, vrFrame) { - t.step( () => { - assert_unreached("Callback registered without layer was called"); - }); - t.done(); + reject("Callback registered without layer was called"); } function onGoodFrame(time, vrFrame) { - t.done(); + resolve(); } // This callback shouldn't be allowed to register, since the session doesn't // have a baseLayer when this call is made. let badHandle = session.requestAnimationFrame(onBadFrame); - - t.step( () => { - assert_equals(badHandle, 0); - }); + assert_equals(badHandle, 0); // Once the base layer is set the callback should be allowed. session.baseLayer = webglLayer; let goodHandle = session.requestAnimationFrame(onGoodFrame); + assert_not_equals(goodHandle, 0); - t.step( () => { - assert_not_equals(goodHandle, 0); - }); -}, fakeDisplays["Pixel"], { exclusive: true }, +}), fakeDevices["FakeGooglePixelPhone"], { exclusive: true }, "XRSession requestAnimationFrame must fail if the session has no baseLayer"); </script>
diff --git a/third_party/WebKit/LayoutTests/xr/exclusive_requestFrame_unregister.html b/third_party/WebKit/LayoutTests/xr/exclusive_requestFrame_unregister.html index a1b7eee..2abe0c5 100644 --- a/third_party/WebKit/LayoutTests/xr/exclusive_requestFrame_unregister.html +++ b/third_party/WebKit/LayoutTests/xr/exclusive_requestFrame_unregister.html
@@ -1,24 +1,21 @@ <!DOCTYPE html> <script src="../resources/testharness.js"></script> <script src="../resources/testharnessreport.js"></script> -<script src="../vr/resources/fake-vr-displays.js"></script> <script src="file:///gen/layout_test_data/mojo/public/js/mojo_bindings.js"></script> <script src="file:///gen/device/vr/vr_service.mojom.js"></script> -<script src="../vr/resources/mock-vr-service.js"></script> +<script src="../xr/resources/xr-device-mocking.js"></script> +<script src="../xr/resources/xr-test-utils.js"></script> <canvas id="webgl-canvas"></canvas> -<script src="../vr/resources/presentation-setup.js"></script> -<script> -let fakeDisplays = fakeVRDisplays(); -xr_session_test( (t, session) => { +<script> +let fakeDevices = fakeXRDevices(); + +xr_session_promise_test( (session) => new Promise((resolve, reject) => { // Session must have a baseLayer or frame requests will be ignored. session.baseLayer = new XRWebGLLayer(session, gl); function onFrameBad(time, vrFrame) { - t.step( () => { - assert_unreached("Unregistered callback was called"); - }); - t.done(); + reject("Unregistered callback was called"); } let counter = 0; @@ -26,7 +23,7 @@ function onFrameGood(time, vrFrame) { counter++; if (counter >= 4) { - t.done(); + resolve(); // Intentionally don't return immediately so that session.requestAnimationFrame // gets called again to make sure it doesn't cause unexpected behavior // like in crbug.com/679401 @@ -47,7 +44,7 @@ session.cancelAnimationFrame(handle); session.requestAnimationFrame(onFrameGood); handle2 = session.requestAnimationFrame(onFrameBad); -}, fakeDisplays["Pixel"], { exclusive: true }, +}), fakeDevices["FakeGooglePixelPhone"], { exclusive: true }, "XRSession requestAnimationFrame callbacks can be unregistered with cancelAnimationFrame"); </script>
diff --git a/third_party/WebKit/LayoutTests/xr/getDevicePose_oneframeupdate.html b/third_party/WebKit/LayoutTests/xr/getDevicePose_oneframeupdate.html index 180b16b..96eb821 100644 --- a/third_party/WebKit/LayoutTests/xr/getDevicePose_oneframeupdate.html +++ b/third_party/WebKit/LayoutTests/xr/getDevicePose_oneframeupdate.html
@@ -1,36 +1,36 @@ <!DOCTYPE html> <script src="../resources/testharness.js"></script> <script src="../resources/testharnessreport.js"></script> -<script src="../vr/resources/fake-vr-displays.js"></script> <script src="file:///gen/layout_test_data/mojo/public/js/mojo_bindings.js"></script> <script src="file:///gen/device/vr/vr_service.mojom.js"></script> -<script src="../vr/resources/mock-vr-service.js"></script> -<script src="../vr/resources/test-constants.js"></script> +<script src="../xr/resources/xr-device-mocking.js"></script> +<script src="../xr/resources/xr-test-utils.js"></script> +<script src="../xr/resources/test-constants.js"></script> <canvas id="webgl-canvas"></canvas> -<script src="../vr/resources/presentation-setup.js"></script> -<script> -let fakeDisplays = fakeVRDisplays(); -xr_session_test( (t, session, mockService) => { +<script> +let fakeDevices = fakeXRDevices(); + +xr_session_promise_test( (session) => { // Session must have a baseLayer or else frame requests will be ignored. session.baseLayer = new XRWebGLLayer(session, gl); - session.requestFrameOfReference("eyeLevel").then((frameOfRef) => { - let expected_pose = VALID_POSE; - let counter = 0; + return session.requestFrameOfReference("eyeLevel") + .then((frameOfRef) => new Promise((resolve, reject) => { + let expected_pose = VALID_POSE; + let counter = 0; + function onFrame(time, vrFrame) { + session.requestAnimationFrame(onFrame); + if (counter == 0) { + // Expecting to not get a pose since none has been supplied + assert_equals(vrFrame.getDevicePose(frameOfRef), null); - function onFrame(time, vrFrame) { - session.requestAnimationFrame(onFrame); - if (counter == 0) { - t.step( () => { + setPose(expected_pose); + + // Check that pose does not update pose within the same frame. assert_equals(vrFrame.getDevicePose(frameOfRef), null); - }, "Expecting to not get a pose since none has been supplied"); - mockService.mockVRDisplays_[0].setPose(expected_pose); - t.step( () => { - assert_equals(vrFrame.getDevicePose(frameOfRef), null); - }, "Does not update pose within the same frame"); - } else { - t.step( () => { + } else { + // Check that pose was updated. let pose = vrFrame.getDevicePose(frameOfRef); assert_not_equals(pose, null); @@ -39,15 +39,16 @@ let expectedMatrix = matrixFrom11Pose(expected_pose); assert_matrices_approx_equal(poseMatrix, expectedMatrix); - }, "Pose was updated in the next frame"); - t.done(); - } - counter++; - } - session.requestAnimationFrame(onFrame); - }); -}, fakeDisplays["Pixel"], { exclusive: true }, + // Finished. + resolve(); + } + counter++; + } + + session.requestAnimationFrame(onFrame); + })); +}, fakeDevices["FakeGooglePixelPhone"], { exclusive: true }, "XRPresentationFrame getDevicePose updates on the next frame"); </script>
diff --git a/third_party/WebKit/LayoutTests/xr/navigator_xr_blocked_by_getVRDisplays.html b/third_party/WebKit/LayoutTests/xr/navigator_xr_blocked_by_getVRDisplays.html index 7a84f4855..c7ddbc4 100644 --- a/third_party/WebKit/LayoutTests/xr/navigator_xr_blocked_by_getVRDisplays.html +++ b/third_party/WebKit/LayoutTests/xr/navigator_xr_blocked_by_getVRDisplays.html
@@ -3,7 +3,7 @@ <script src="../resources/testharnessreport.js"></script> <script> -promise_test(t => navigator.getVRDisplays().then(() => { +promise_test((t) => navigator.getVRDisplays().then(() => { assert_true(navigator.xr == null); }), "Test that access to navigator.xr is blocked once navigator.getVRDisplays has been called.");
diff --git a/third_party/WebKit/LayoutTests/xr/navigator_xr_blocks_getVRDisplays.html b/third_party/WebKit/LayoutTests/xr/navigator_xr_blocks_getVRDisplays.html index 6994bed8..b945238 100644 --- a/third_party/WebKit/LayoutTests/xr/navigator_xr_blocks_getVRDisplays.html +++ b/third_party/WebKit/LayoutTests/xr/navigator_xr_blocks_getVRDisplays.html
@@ -3,7 +3,7 @@ <script src="../resources/testharnessreport.js"></script> <script> -promise_test(t => navigator.xr.requestDevice().catch(() => { +promise_test((t) => navigator.xr.requestDevice().catch(() => { return promise_rejects(t, "InvalidStateError", navigator.getVRDisplays()); }), "Test that calls to navigator.getVRDisplays are blocked once navigator.xr has been accessed.");
diff --git a/third_party/WebKit/LayoutTests/xr/navigator_xr_detached.html b/third_party/WebKit/LayoutTests/xr/navigator_xr_detached.html index 4a657d8..b360f448 100644 --- a/third_party/WebKit/LayoutTests/xr/navigator_xr_detached.html +++ b/third_party/WebKit/LayoutTests/xr/navigator_xr_detached.html
@@ -9,7 +9,7 @@ <iframe sandbox="allow-same-origin" id="subframe"></iframe> <script> -promise_test(t => { +promise_test((t) => { var nav_xr = window.frames[0].navigator.xr; document.getElementById("subframe").remove(); return promise_rejects(t, "InvalidStateError", nav_xr.requestDevice());
diff --git a/third_party/WebKit/LayoutTests/xr/requestDevice_one_device.html b/third_party/WebKit/LayoutTests/xr/requestDevice_one_device.html index 61f6b86..e8428839 100644 --- a/third_party/WebKit/LayoutTests/xr/requestDevice_one_device.html +++ b/third_party/WebKit/LayoutTests/xr/requestDevice_one_device.html
@@ -1,28 +1,20 @@ <!DOCTYPE html> <script src="../resources/testharness.js"></script> <script src="../resources/testharnessreport.js"></script> -<script src="../vr/resources/fake-vr-displays.js"></script> <script src="file:///gen/layout_test_data/mojo/public/js/mojo_bindings.js"></script> <script src="file:///gen/device/vr/vr_service.mojom.js"></script> -<script src="../vr/resources/mock-vr-service.js"></script> -<script src="../vr/resources/test-constants.js"></script> +<script src="../xr/resources/xr-device-mocking.js"></script> +<script src="../xr/resources/xr-test-utils.js"></script> +<script src="../xr/resources/test-constants.js"></script> <script> -let fakeDisplays = fakeVRDisplays(); +let fakeDevices = fakeXRDevices(); -vr_test( (t) => { +promise_test((t) => { + setFakeDevices([fakeDevices["FakeGooglePixelPhone"]]); return navigator.xr.requestDevice().then( (device) => { - t.step( () => { - assert_true(device != null); - assert_false(device.external); - }, "requestDevice returned correct results"); - }, (err) => { - t.step( () => { - assert_unreached("requestDevice rejected"); - }); - }).then( () => { - t.done(); + assert_true(device != null); + assert_false(device.external); }); -}, [fakeDisplays["Pixel"]], -"navigator.xr.requestDevice properly returns a single device"); +}, "navigator.xr.requestDevice properly returns a single device"); </script>
diff --git a/third_party/WebKit/LayoutTests/xr/requestDevice_two_devices.html b/third_party/WebKit/LayoutTests/xr/requestDevice_two_devices.html index 279a9ef..a17db4c 100644 --- a/third_party/WebKit/LayoutTests/xr/requestDevice_two_devices.html +++ b/third_party/WebKit/LayoutTests/xr/requestDevice_two_devices.html
@@ -1,33 +1,21 @@ <!DOCTYPE html> <script src="../resources/testharness.js"></script> <script src="../resources/testharnessreport.js"></script> -<script src="../vr/resources/fake-vr-displays.js"></script> <script src="file:///gen/layout_test_data/mojo/public/js/mojo_bindings.js"></script> <script src="file:///gen/device/vr/vr_service.mojom.js"></script> -<script src="../vr/resources/mock-vr-service.js"></script> -<script src="../vr/resources/test-constants.js"></script> +<script src="../xr/resources/xr-device-mocking.js"></script> +<script src="../xr/resources/xr-test-utils.js"></script> +<script src="../xr/resources/test-constants.js"></script> <script> -let fakeDisplays = fakeVRDisplays(); -vr_test( (t) => { +let fakeDevices = fakeXRDevices(); +promise_test( (t) => { // TODO(offenwanger) When we know how to we want to select which device to // return, update this test. - + setFakeDevices([fakeDevices["FakeGooglePixelPhone"], fakeDevices["FakeMagicWindowOnly"]]); return navigator.xr.requestDevice().then( (device) => { - t.step( () => { - assert_true(device != null); - }, "requestDevice returned result"); - - t.step( () => { - assert_false(device.external); - }, "Attribute for device is correct"); - }, (err) => { - t.step( () => { - assert_unreached("requestDevice rejected"); - }); - }).then( () => { - t.done(); + assert_true(device != null); + assert_false(device.external); }); -}, [fakeDisplays["Pixel"], fakeDisplays["FakeMagicWindowOnly"]], -"navigator.xr.requestDevice properly returns one device when there are two"); +}, "navigator.xr.requestDevice properly returns one device when there are two"); </script>
diff --git a/third_party/WebKit/LayoutTests/xr/requestDevice_zero_devices.html b/third_party/WebKit/LayoutTests/xr/requestDevice_zero_devices.html index 9d361c4..af46da89 100644 --- a/third_party/WebKit/LayoutTests/xr/requestDevice_zero_devices.html +++ b/third_party/WebKit/LayoutTests/xr/requestDevice_zero_devices.html
@@ -1,26 +1,16 @@ <!DOCTYPE html> <script src="../resources/testharness.js"></script> <script src="../resources/testharnessreport.js"></script> -<script src="../vr/resources/fake-vr-displays.js"></script> <script src="file:///gen/layout_test_data/mojo/public/js/mojo_bindings.js"></script> <script src="file:///gen/device/vr/vr_service.mojom.js"></script> -<script src="../vr/resources/mock-vr-service.js"></script> -<script src="../vr/resources/test-constants.js"></script> +<script src="../xr/resources/xr-device-mocking.js"></script> +<script src="../xr/resources/xr-test-utils.js"></script> +<script src="../xr/resources/test-constants.js"></script> <script> -let fakeDisplays = fakeVRDisplays(); +let fakeDevices = fakeXRDevices(); -vr_test( (t) => { - return navigator.xr.requestDevice().then( (device) => { - t.step( () => { - assert_unreached("requestDevice resolved"); - }, "requestDevice resolved when it shouldn't have"); - }, (err) => { - t.step( () => { - assert_equals(err.name, "NotFoundError") - t.done(); - }); - }); -}, [], -"navigator.xr.requestDevice properly returns zero devices"); +promise_test( (t) => { + return promise_rejects(t, 'NotFoundError', navigator.xr.requestDevice()); +}, "navigator.xr.requestDevice properly rejects when there are 0 devices"); </script> \ No newline at end of file
diff --git a/third_party/WebKit/LayoutTests/xr/resources/test-constants.js b/third_party/WebKit/LayoutTests/xr/resources/test-constants.js new file mode 100644 index 0000000..56612113 --- /dev/null +++ b/third_party/WebKit/LayoutTests/xr/resources/test-constants.js
@@ -0,0 +1,13 @@ +// assert_equals can fail when comparing floats due to precision errors, so +// use assert_approx_equals with this constant instead +var FLOAT_EPSILON = 0.000001; + +// A valid VRPose for when we don't care about specific values +var VALID_POSE = { + position: [1.1, 2.2, 3.3], + linearVelocity: [0.1, 0.2, 0.3], + linearAcceleration: [0.0, 0.1, 0.2], + orientation: [0.1, 0.2, 0.3, 0.4], + angularVelocity: [1.1, 2.1, 3.1], + angularAcceleration: [1.0, 2.0, 3.0] +}
diff --git a/third_party/WebKit/LayoutTests/xr/resources/xr-device-mocking.js b/third_party/WebKit/LayoutTests/xr/resources/xr-device-mocking.js new file mode 100644 index 0000000..ab56df9 --- /dev/null +++ b/third_party/WebKit/LayoutTests/xr/resources/xr-device-mocking.js
@@ -0,0 +1,395 @@ +'use strict'; + +/* This class contains everything required to trick the system into thinking it + * has a fully functional XRDevices. When moving test to WPT, this file will + * need to be modified to be consistent with what is decided for the cross- + * platform APIs. */ + +let mockVRService; +function addFakeDevice(device) { + // TODO(offenwanger): Switch out this code with test API code when it's + // available. + if (!mockVRService) { + mockVRService = new MockVRService(mojo.frameInterfaces); + } + + mockVRService.addVRDisplay(device); +} + +function setFakeDevices(devices) { + // TODO(offenwanger): Switch out this code with test API code when it's + // available. + if (!mockVRService) { + mockVRService = new MockVRService(mojo.frameInterfaces); + } + + mockVRService.setVRDisplays(devices); +} + +// Sets the pose for the first device +function setPose(pose) { + mockVRService.mockVRDisplays_[0].setPose(pose); +} + +// Returns the submitted frame count for the first display +function getSubmitFrameCount() { + return mockVRService.mockVRDisplays_[0].getSubmitFrameCount(); +} + +function fakeXRDevices() { + let generic_left_fov = { + upDegrees: 45, + downDegrees: 45, + leftDegrees: 50, + rightDegrees: 40, + }; + + let generic_right_fov = { + upDegrees: 45, + downDegrees: 45, + leftDegrees: 40, + rightDegrees: 50, + }; + + let generic_left_eye = { + fieldOfView: generic_left_fov, + offset: [-0.03, 0, 0], + renderWidth: 1024, + renderHeight: 1024 + }; + + let generic_right_eye = { + fieldOfView: generic_right_fov, + offset: [0.03, 0, 0], + renderWidth: 1024, + renderHeight: 1024 + }; + + return { + FakeMagicWindowOnly: { + displayName: 'FakeVRDisplay', + capabilities: + {hasPosition: false, hasExternalDisplay: false, canPresent: false}, + stageParameters: null, + leftEye: null, + rightEye: null, + }, + + FakeRoomScale: { + displayName: 'FakeVRDisplayRoom', + capabilities: { + hasPosition: true, + hasExternalDisplay: true, + canPresent: true, + maxLayers: 1 + }, + stageParameters: { + standingTransform: [ + 0.0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1.0, 0.1, 0.2, 0.3, + 0.4, 0.5 + ], + sizeX: 5.0, + sizeZ: 3.0, + }, + leftEye: generic_left_eye, + rightEye: generic_right_eye, + }, + + FakeGooglePixelPhone: { + // Pixel info as of Dec. 22 2016 + displayName: 'Google, Inc. Daydream View', + capabilities: { + hasPosition: false, + hasExternalDisplay: false, + canPresent: true, + maxLayers: 1 + }, + stageParameters: null, + leftEye: { + fieldOfView: { + upDegrees: 48.316, + downDegrees: 50.099, + leftDegrees: 35.197, + rightDegrees: 50.899, + }, + offset: [-0.032, 0, 0], + renderWidth: 960, + renderHeight: 1080 + }, + rightEye: { + fieldOfView: { + upDegrees: 48.316, + downDegrees: 50.099, + leftDegrees: 50.899, + rightDegrees: 35.197 + }, + offset: [0.032, 0, 0], + renderWidth: 960, + renderHeight: 1080 + } + } + }; +} + +// TODO(offenwanger): Update this to remove references to 1.1 +// Gets the corresponding transform matrix for a WebVR 1.1 pose +function matrixFrom11Pose(pose) { + let x = pose.orientation[0]; + let y = pose.orientation[1]; + let z = pose.orientation[2]; + let w = pose.orientation[3]; + let x2 = x + x; + let y2 = y + y; + let z2 = z + z; + let xx = x * x2; + let xy = x * y2; + let xz = x * z2; + let yy = y * y2; + let yz = y * z2; + let zz = z * z2; + let wx = w * x2; + let wy = w * y2; + let wz = w * z2; + + let out = new Float32Array(16); + out[0] = 1 - (yy + zz); + out[1] = xy + wz; + out[2] = xz - wy; + out[3] = 0; + out[4] = xy - wz; + out[5] = 1 - (xx + zz); + out[6] = yz + wx; + out[7] = 0; + out[8] = xz + wy; + out[9] = yz - wx; + out[10] = 1 - (xx + yy); + out[11] = 0; + out[12] = pose.position[0]; + out[13] = pose.position[1]; + out[14] = pose.position[2]; + out[15] = 1; + + return out; +} + +function perspectiveFromFieldOfView(fov, near, far) { + let upTan = Math.tan(fov.upDegrees * Math.PI / 180.0); + let downTan = Math.tan(fov.downDegrees * Math.PI / 180.0); + let leftTan = Math.tan(fov.leftDegrees * Math.PI / 180.0); + let rightTan = Math.tan(fov.rightDegrees * Math.PI / 180.0); + let xScale = 2.0 / (leftTan + rightTan); + let yScale = 2.0 / (upTan + downTan); + let nf = 1.0 / (near - far); + + let out = new Float32Array(16); + out[0] = xScale; + out[1] = 0.0; + out[2] = 0.0; + out[3] = 0.0; + out[4] = 0.0; + out[5] = yScale; + out[6] = 0.0; + out[7] = 0.0; + out[8] = -((leftTan - rightTan) * xScale * 0.5); + out[9] = ((upTan - downTan) * yScale * 0.5); + out[10] = (near + far) * nf; + out[11] = -1.0; + out[12] = 0.0; + out[13] = 0.0; + out[14] = (2.0 * far * near) * nf; + out[15] = 0.0; + + return out; +} + +function assert_matrices_approx_equal(matA, matB, epsilon = FLOAT_EPSILON) { + if (matA == null && matB == null) { + return; + } + + assert_not_equals(matA, null); + assert_not_equals(matB, null); + + assert_equals(matA.length, 16); + assert_equals(matB.length, 16); + for (let i = 0; i < 16; ++i) { + assert_approx_equals(matA[i], matB[i], epsilon); + } +} + +// TODO(offenwanger): Delete everything below when test API code is available. +class MockDevice { + constructor(displayInfo, service) { + this.displayClient_ = new device.mojom.VRDisplayClientPtr(); + this.displayInfo_ = displayInfo; + this.service_ = service; + this.presentation_provider_ = new MockVRPresentationProvider(); + + if (service.client_) { + this.notifyClientOfDisplay(); + } + } + + requestPresent(submitFrameClient, request, presentOptions) { + this.presentation_provider_.bind( + submitFrameClient, request, presentOptions); + // The JavaScript bindings convert c_style_names to camelCase names. + var options = new device.mojom.VRDisplayFrameTransportOptions(); + options.transportMethod = + device.mojom.VRDisplayFrameTransportMethod.SUBMIT_AS_MAILBOX_HOLDER; + options.waitForTransferNotification = true; + options.waitForRenderNotification = true; + return Promise.resolve({success: true, transportOptions: options}); + } + + setPose(pose) { + if (pose == null) { + this.presentation_provider_.pose_ = null; + } else { + this.presentation_provider_.initPose(); + this.presentation_provider_.fillPose(pose); + } + } + + getPose() { + return Promise.resolve({ + pose: this.presentation_provider_.pose_, + }); + } + + getSubmitFrameCount() { + return this.presentation_provider_.submit_frame_count_; + } + + forceActivate(reason) { + this.displayClient_.onActivate(reason); + } + + // This function calls to the backend to add this device to the list. + notifyClientOfDisplay() { + let displayPtr = new device.mojom.VRDisplayHostPtr(); + let displayRequest = mojo.makeRequest(displayPtr); + let displayBinding = + new mojo.Binding(device.mojom.VRDisplayHost, this, displayRequest); + + let magicWindowPtr = new device.mojom.VRMagicWindowProviderPtr(); + let magicWindowRequest = mojo.makeRequest(magicWindowPtr); + let magicWindowBinding = new mojo.Binding( + device.mojom.VRMagicWindowProvider, this, magicWindowRequest); + + let clientRequest = mojo.makeRequest(this.displayClient_); + this.service_.client_.onDisplayConnected( + magicWindowPtr, displayPtr, clientRequest, this.displayInfo_); + } +} + +class MockVRPresentationProvider { + constructor() { + this.binding_ = new mojo.Binding(device.mojom.VRPresentationProvider, this); + this.pose_ = null; + this.submit_frame_count_ = 0; + } + + bind(client, request) { + this.submitFrameClient_ = client; + this.binding_.close(); + this.binding_.bind(request); + } + + submitFrame(frameId, mailboxHolder, timeWaited) { + this.submit_frame_count_++; + + // Trigger the submit completion callbacks here. WARNING: The + // Javascript-based mojo mocks are *not* re-entrant. It's OK to + // wait for these notifications on the next frame, but waiting + // within the current frame would never finish since the incoming + // calls would be queued until the current execution context finishes. + this.submitFrameClient_.onSubmitFrameTransferred(true); + this.submitFrameClient_.onSubmitFrameRendered(); + } + + getVSync() { + if (this.pose_) { + this.pose_.poseIndex++; + } + + // Convert current document time to monotonic time. + var now = window.performance.now() / 1000.0; + var diff = now - window.internals.monotonicTimeToZeroBasedDocumentTime(now); + now += diff; + now *= 1000000; + + let retval = Promise.resolve({ + pose: this.pose_, + time: { + microseconds: now, + }, + frameId: 0, + status: device.mojom.VRPresentationProvider.VSyncStatus.SUCCESS, + }); + + return retval; + } + + initPose() { + this.pose_ = { + orientation: null, + position: null, + angularVelocity: null, + linearVelocity: null, + angularAcceleration: null, + linearAcceleration: null, + poseIndex: 0 + }; + } + + fillPose(pose) { + for (var field in pose) { + if (this.pose_.hasOwnProperty(field)) { + this.pose_[field] = pose[field]; + } + } + } +} + +class MockVRService { + constructor() { + this.bindingSet_ = new mojo.BindingSet(device.mojom.VRService); + this.mockVRDisplays_ = []; + + this.interceptor_ = + new MojoInterfaceInterceptor(device.mojom.VRService.name); + this.interceptor_.oninterfacerequest = e => + this.bindingSet_.addBinding(this, e.handle); + this.interceptor_.start(); + } + + setVRDisplays(displays) { + this.mockVRDisplays_ = []; + for (let i = 0; i < displays.length; i++) { + displays[i].index = i; + this.mockVRDisplays_.push(new MockDevice(displays[i], this)); + } + } + + addVRDisplay(display) { + if (this.mockVRDisplays_.length) { + display.index = this.mockVRDisplays_[this.mockVRDisplays_.length - 1] + 1; + } else { + display.index = 0; + } + this.mockVRDisplays_.push(new MockDevice(display, this)); + } + + // This function gets called from mojo, and is what triggers all displays to + // be added. + setClient(client) { + this.client_ = client; + for (let i = 0; i < this.mockVRDisplays_.length; i++) { + this.mockVRDisplays_[i].notifyClientOfDisplay(); + } + + let device_number = this.mockVRDisplays_.length; + return Promise.resolve({numberOfConnectedDevices: device_number}); + } +} \ No newline at end of file
diff --git a/third_party/WebKit/LayoutTests/xr/resources/xr-test-utils.js b/third_party/WebKit/LayoutTests/xr/resources/xr-test-utils.js new file mode 100644 index 0000000..dbeca772 --- /dev/null +++ b/third_party/WebKit/LayoutTests/xr/resources/xr-test-utils.js
@@ -0,0 +1,50 @@ +// func: A function that takes a session and optionally a test object and +// performs tests. If func returns a promise, test will only pass if the promise +// resolves. +function xr_session_promise_test( + func, device, sessionOptions, name, properties) { + if (document.getElementById('webgl-canvas') || + document.getElementById('webgl2-canvas')) { + webglCanvasSetup(); + } + + addFakeDevice(device); + + promise_test((t) => { + return navigator.xr.requestDevice().then( + (device) => new Promise((resolve, reject) => { + // Perform the session request in a user gesture. + runWithUserGesture(() => { + resolve(device.requestSession(sessionOptions) + .then((session) => func(session, t))); + }); + })); + }, name, properties); +} + +let webglCanvas, gl; +function webglCanvasSetup() { + let webgl2 = false; + webglCanvas = document.getElementById('webgl-canvas'); + if (!webglCanvas) { + webglCanvas = document.getElementById('webgl2-canvas'); + webgl2 = true; + } + let glAttributes = { + alpha: false, + antialias: false, + }; + gl = webglCanvas.getContext(webgl2 ? 'webgl2' : 'webgl', glAttributes); +} + +// TODO(offenwanger): eventSender cannot be used with WPTs. Find another way to +// fake use gestures. +// https://chromium.googlesource.com/chromium/src/+/lkgr/docs/testing/web_platform_tests.md#tests-that-require-testing-apis +function runWithUserGesture(fn) { + function thunk() { + document.removeEventListener('keypress', thunk, false); + fn() + } + document.addEventListener('keypress', thunk, false); + eventSender.keyDown(' ', []); +} \ No newline at end of file
diff --git a/third_party/WebKit/LayoutTests/xr/xrDevice_requestSession_exclusive_no_gesture.html b/third_party/WebKit/LayoutTests/xr/xrDevice_requestSession_exclusive_no_gesture.html index 9e48a21d..94d6b8f 100644 --- a/third_party/WebKit/LayoutTests/xr/xrDevice_requestSession_exclusive_no_gesture.html +++ b/third_party/WebKit/LayoutTests/xr/xrDevice_requestSession_exclusive_no_gesture.html
@@ -1,33 +1,18 @@ <!DOCTYPE html> <script src="../resources/testharness.js"></script> <script src="../resources/testharnessreport.js"></script> -<script src="../vr/resources/fake-vr-displays.js"></script> <script src="file:///gen/layout_test_data/mojo/public/js/mojo_bindings.js"></script> <script src="file:///gen/device/vr/vr_service.mojom.js"></script> -<script src="../vr/resources/mock-vr-service.js"></script> -<script src="../vr/resources/test-constants.js"></script> +<script src="../xr/resources/xr-device-mocking.js"></script> +<script src="../xr/resources/xr-test-utils.js"></script> +<script src="../xr/resources/test-constants.js"></script> <canvas id="webgl-canvas"></canvas> -<script src="../vr/resources/presentation-setup.js"></script> + <script> -let fakeDisplays = fakeVRDisplays(); - -vr_test( (t) => { - return navigator.xr.requestDevice().then( (device) => { - - device.requestSession({ exclusive: true }).then(() => { - assert_unreached("requestSession resolved unexpectedly"); - }).catch((e) => { - assert_equals(e.name, "InvalidStateError"); - t.done(); - }); - - }, (err) => { - t.step( () => { - assert_unreached("getDevices rejected"); - }); - }); -}, [fakeDisplays["Pixel"]], -"requestSession with an exclusive session outside of a user gesture rejects"); - - -</script> +let fakeDevices = fakeXRDevices(); +promise_test( (t) => { + setFakeDevices([fakeDevices["FakeGooglePixelPhone"]]); + return navigator.xr.requestDevice().then( (device) => + promise_rejects(t, 'InvalidStateError', device.requestSession({ exclusive: true }))); +}, "requestSession with an exclusive session outside of a user gesture rejects"); +</script> \ No newline at end of file
diff --git a/third_party/WebKit/LayoutTests/xr/xrDevice_requestSession_exclusive_supported.html b/third_party/WebKit/LayoutTests/xr/xrDevice_requestSession_exclusive_supported.html index 84bfc45..639c06c 100644 --- a/third_party/WebKit/LayoutTests/xr/xrDevice_requestSession_exclusive_supported.html +++ b/third_party/WebKit/LayoutTests/xr/xrDevice_requestSession_exclusive_supported.html
@@ -1,40 +1,18 @@ <!DOCTYPE html> <script src="../resources/testharness.js"></script> <script src="../resources/testharnessreport.js"></script> -<script src="../vr/resources/fake-vr-displays.js"></script> <script src="file:///gen/layout_test_data/mojo/public/js/mojo_bindings.js"></script> <script src="file:///gen/device/vr/vr_service.mojom.js"></script> -<script src="../vr/resources/mock-vr-service.js"></script> -<script src="../vr/resources/test-constants.js"></script> +<script src="../xr/resources/xr-device-mocking.js"></script> +<script src="../xr/resources/xr-test-utils.js"></script> +<script src="../xr/resources/test-constants.js"></script> <canvas id="webgl-canvas"></canvas> -<script src="../vr/resources/presentation-setup.js"></script> + <script> -let fakeDisplays = fakeVRDisplays(); +let fakeDevices = fakeXRDevices(); -vr_test( (t) => { - return navigator.xr.requestDevice().then( (device) => { - - runWithUserGesture( () => { - device.requestSession({ exclusive: true }).then( (session) => { - t.step( () => { - assert_true(session.exclusive); - }, "requestSession resolved as expected"); - }, (err) => { - t.step( () => { - assert_unreached("requestSession rejected unexpectedly"); - }); - }).then( () => { - t.done(); - }); - }); - - }, (err) => { - t.step( () => { - assert_unreached("getDevices rejected"); - }); - }); -}, [fakeDisplays["Pixel"]], +xr_session_promise_test( (session) => { + assert_not_equals(session, null); +}, fakeDevices["FakeGooglePixelPhone"], { exclusive: true }, "requestSession for an exclusive session with a user gesture resolves"); - - </script>
diff --git a/third_party/WebKit/LayoutTests/xr/xrDevice_requestSession_exclusive_unsupported.html b/third_party/WebKit/LayoutTests/xr/xrDevice_requestSession_exclusive_unsupported.html index faee322..9969f83 100644 --- a/third_party/WebKit/LayoutTests/xr/xrDevice_requestSession_exclusive_unsupported.html +++ b/third_party/WebKit/LayoutTests/xr/xrDevice_requestSession_exclusive_unsupported.html
@@ -1,33 +1,28 @@ <!DOCTYPE html> <script src="../resources/testharness.js"></script> <script src="../resources/testharnessreport.js"></script> -<script src="../vr/resources/fake-vr-displays.js"></script> <script src="file:///gen/layout_test_data/mojo/public/js/mojo_bindings.js"></script> <script src="file:///gen/device/vr/vr_service.mojom.js"></script> -<script src="../vr/resources/mock-vr-service.js"></script> -<script src="../vr/resources/test-constants.js"></script> +<script src="../xr/resources/xr-device-mocking.js"></script> +<script src="../xr/resources/xr-test-utils.js"></script> +<script src="../xr/resources/test-constants.js"></script> <canvas id="webgl-canvas"></canvas> -<script src="../vr/resources/presentation-setup.js"></script> + <script> -let fakeDisplays = fakeVRDisplays(); -vr_test( (t) => { - return navigator.xr.requestDevice().then( (magicWindowOnlyDevice) => { - runWithUserGesture( () => { +let fakeDevices = fakeXRDevices(); +promise_test( (t) => { + setFakeDevices([fakeDevices["FakeMagicWindowOnly"]]); - magicWindowOnlyDevice.requestSession({ exclusive: true }).then(() => { - assert_unreached("requestSession resolved unexpectedly"); - }, (e) => { - assert_equals(e.name, "NotSupportedError"); - t.done(); + return navigator.xr.requestDevice() + .then( (magicWindowOnlyDevice) => new Promise((resolve) => { + runWithUserGesture( () => { + resolve(promise_rejects( + t, + "NotSupportedError", + magicWindowOnlyDevice.requestSession({ exclusive: true }) + )) }); - - }); - }, (err) => { - t.step( () => { - assert_unreached("requestDevice rejected"); - }); - }); -}, [fakeDisplays["FakeMagicWindowOnly"]], -"requesting an exclusive session on an unsupported device rejects"); + })); +}, "requesting an exclusive session on an unsupported device rejects"); </script>
diff --git a/third_party/WebKit/LayoutTests/xr/xrDevice_supportsSession_exclusive_rejects.html b/third_party/WebKit/LayoutTests/xr/xrDevice_supportsSession_exclusive_rejects.html index 186b85f..8a46c4a 100644 --- a/third_party/WebKit/LayoutTests/xr/xrDevice_supportsSession_exclusive_rejects.html +++ b/third_party/WebKit/LayoutTests/xr/xrDevice_supportsSession_exclusive_rejects.html
@@ -1,32 +1,23 @@ <!DOCTYPE html> <script src="../resources/testharness.js"></script> <script src="../resources/testharnessreport.js"></script> -<script src="../vr/resources/fake-vr-displays.js"></script> <script src="file:///gen/layout_test_data/mojo/public/js/mojo_bindings.js"></script> <script src="file:///gen/device/vr/vr_service.mojom.js"></script> -<script src="../vr/resources/mock-vr-service.js"></script> -<script src="../vr/resources/test-constants.js"></script> +<script src="../xr/resources/xr-device-mocking.js"></script> +<script src="../xr/resources/xr-test-utils.js"></script> +<script src="../xr/resources/test-constants.js"></script> <script> -let fakeDisplays = fakeVRDisplays(); +let fakeDevices = fakeXRDevices(); -vr_test( (t) => { +promise_test( (t) => { + setFakeDevices([fakeDevices["FakeMagicWindowOnly"]]); return navigator.xr.requestDevice().then( (magicWindowOnlyDevice) => { - - magicWindowOnlyDevice.supportsSession({ exclusive: true }).then( () => { - t.step( () => { - assert_unreached("supportsSession unexpectedly allowed exclusive"); - }); - }, () => { - // Expected result. Test complete. - t.done(); - }); - - }, (err) => { - t.step( () => { - assert_unreached("requestDevice rejected"); - }); + return promise_rejects( + t, + "NotSupportedError", + magicWindowOnlyDevice.supportsSession({ exclusive: true }) + ); }); -}, [fakeDisplays["FakeMagicWindowOnly"]], -"supportsSession rejects when exclusive session is not supported on device"); +}, "supportsSession rejects when exclusive session is not supported on device"); </script>
diff --git a/third_party/WebKit/LayoutTests/xr/xrDevice_supportsSession_exclusive_resolves.html b/third_party/WebKit/LayoutTests/xr/xrDevice_supportsSession_exclusive_resolves.html index 53ad8939..71f9ef54 100644 --- a/third_party/WebKit/LayoutTests/xr/xrDevice_supportsSession_exclusive_resolves.html +++ b/third_party/WebKit/LayoutTests/xr/xrDevice_supportsSession_exclusive_resolves.html
@@ -1,31 +1,18 @@ <!DOCTYPE html> <script src="../resources/testharness.js"></script> <script src="../resources/testharnessreport.js"></script> -<script src="../vr/resources/fake-vr-displays.js"></script> <script src="file:///gen/layout_test_data/mojo/public/js/mojo_bindings.js"></script> <script src="file:///gen/device/vr/vr_service.mojom.js"></script> -<script src="../vr/resources/mock-vr-service.js"></script> -<script src="../vr/resources/test-constants.js"></script> +<script src="../xr/resources/xr-device-mocking.js"></script> +<script src="../xr/resources/xr-test-utils.js"></script> +<script src="../xr/resources/test-constants.js"></script> <script> -let fakeDisplays = fakeVRDisplays(); +let fakeDevices = fakeXRDevices(); -vr_test( (t) => { - return navigator.xr.requestDevice().then( (device) => { - - device.supportsSession({ exclusive: true }).then( () => { - // Expected result - t.done(); - }, () => { - t.step( () => { - assert_unreached("supportsSession unexpectedly rejected exclusive"); - }); - }); - }, (err) => { - t.step( () => { - assert_unreached("requestDevice rejected"); - }); - }); -}, [fakeDisplays["Pixel"]], -"supportsSession resolves when support exclusive session is supported on device"); +promise_test( () => { + setFakeDevices([fakeDevices["FakeGooglePixelPhone"]]); + return navigator.xr.requestDevice().then( (device) => + device.supportsSession({ exclusive: true })); +}, "supportsSession resolves when support exclusive session is supported on device"); </script>
diff --git a/third_party/WebKit/LayoutTests/xr/xrDevice_supportsSession_non_exclusive.html b/third_party/WebKit/LayoutTests/xr/xrDevice_supportsSession_non_exclusive.html index 493dd7a..d37b2141 100644 --- a/third_party/WebKit/LayoutTests/xr/xrDevice_supportsSession_non_exclusive.html +++ b/third_party/WebKit/LayoutTests/xr/xrDevice_supportsSession_non_exclusive.html
@@ -1,32 +1,19 @@ <!DOCTYPE html> <script src="../resources/testharness.js"></script> <script src="../resources/testharnessreport.js"></script> -<script src="../vr/resources/fake-vr-displays.js"></script> <script src="file:///gen/layout_test_data/mojo/public/js/mojo_bindings.js"></script> <script src="file:///gen/device/vr/vr_service.mojom.js"></script> -<script src="../vr/resources/mock-vr-service.js"></script> -<script src="../vr/resources/test-constants.js"></script> +<script src="../xr/resources/xr-device-mocking.js"></script> +<script src="../xr/resources/xr-test-utils.js"></script> +<script src="../xr/resources/test-constants.js"></script> <script> -let fakeDisplays = fakeVRDisplays(); +let fakeDevices = fakeXRDevices(); -vr_test( (t) => { - return navigator.xr.requestDevice().then( (device) => { - - device.supportsSession().then( () => { - t.step( () => { - assert_unreached("supportsSession unexpectedly allowed non-exclusive session without an output context"); - }); - }).catch( () => { - // Expected result, test is finished. - t.done(); - }); - - }, (err) => { - t.step( () => { - assert_unreached("requestDevice rejected"); - }); - }); -}, [fakeDisplays["Pixel"]], -"supportsSession properly identifies supported non-exclusive sessions"); +promise_test( (t) => { + setFakeDevices([fakeDevices["FakeGooglePixelPhone"]]); + return navigator.xr.requestDevice().then( (device) => + promise_rejects(t, 'NotSupportedError', device.supportsSession()) + ); +}, "supportsSession properly identifies supported non-exclusive sessions"); </script>
diff --git a/third_party/WebKit/LayoutTests/xr/xrSession_exclusive.html b/third_party/WebKit/LayoutTests/xr/xrSession_exclusive.html index 7faf007..f0c0408 100644 --- a/third_party/WebKit/LayoutTests/xr/xrSession_exclusive.html +++ b/third_party/WebKit/LayoutTests/xr/xrSession_exclusive.html
@@ -1,40 +1,28 @@ <!DOCTYPE html> <script src="../resources/testharness.js"></script> <script src="../resources/testharnessreport.js"></script> -<script src="../vr/resources/fake-vr-displays.js"></script> <script src="file:///gen/layout_test_data/mojo/public/js/mojo_bindings.js"></script> <script src="file:///gen/device/vr/vr_service.mojom.js"></script> -<script src="../vr/resources/mock-vr-service.js"></script> -<script src="../vr/resources/test-constants.js"></script> +<script src="../xr/resources/xr-device-mocking.js"></script> +<script src="../xr/resources/xr-test-utils.js"></script> +<script src="../xr/resources/test-constants.js"></script> <canvas id="webgl-canvas"></canvas> -<script src="../vr/resources/presentation-setup.js"></script> -<script> -let fakeDisplays = fakeVRDisplays(); -vr_test( (t) => { - return navigator.xr.requestDevice().then( (device) => { +<script> +let fakeDevices = fakeXRDevices(); + +promise_test( (t) => { + setFakeDevices([fakeDevices["FakeGooglePixelPhone"]]); + return navigator.xr.requestDevice().then( (device) => new Promise((resolve) => { runWithUserGesture( () => { - device.requestSession({ exclusive: true }).then( (session) => { - t.step( () => { - assert_true(session.exclusive); - assert_equals(session.device, device); - assert_approx_equals(session.depthNear, 0.1, FLOAT_EPSILON); - assert_approx_equals(session.depthFar, 1000.0, FLOAT_EPSILON); - }, "requestSession returned correct results"); - }, (err) => { - t.step( () => { - assert_unreached("requestSession rejected"); - }); - }).then( () => { - t.done(); - }); + resolve(device.requestSession({ exclusive: true }).then( (session) => { + assert_true(session.exclusive); + assert_equals(session.device, device); + assert_approx_equals(session.depthNear, 0.1, FLOAT_EPSILON); + assert_approx_equals(session.depthFar, 1000.0, FLOAT_EPSILON); + })); }); - }, (err) => { - t.step( () => { - assert_unreached("requestDevice rejected"); - }); - }); -}, [fakeDisplays["Pixel"]], -"supportsSession returns expected exclusive session"); + })); +}, "supportsSession returns expected exclusive session"); </script>
diff --git a/third_party/WebKit/LayoutTests/xr/xrSession_prevent_multiple_exclusive.html b/third_party/WebKit/LayoutTests/xr/xrSession_prevent_multiple_exclusive.html index a318235..8777488 100644 --- a/third_party/WebKit/LayoutTests/xr/xrSession_prevent_multiple_exclusive.html +++ b/third_party/WebKit/LayoutTests/xr/xrSession_prevent_multiple_exclusive.html
@@ -1,57 +1,43 @@ <!DOCTYPE html> <script src="../resources/testharness.js"></script> <script src="../resources/testharnessreport.js"></script> -<script src="../vr/resources/fake-vr-displays.js"></script> <script src="file:///gen/layout_test_data/mojo/public/js/mojo_bindings.js"></script> <script src="file:///gen/device/vr/vr_service.mojom.js"></script> -<script src="../vr/resources/mock-vr-service.js"></script> -<script src="../vr/resources/test-constants.js"></script> +<script src="../xr/resources/xr-device-mocking.js"></script> +<script src="../xr/resources/xr-test-utils.js"></script> +<script src="../xr/resources/test-constants.js"></script> <canvas id="webgl-canvas"></canvas> -<script src="../vr/resources/presentation-setup.js"></script> + <script> -let fakeDisplays = fakeVRDisplays(); +let fakeDevices = fakeXRDevices(); -vr_test( (t) => { - return navigator.xr.requestDevice().then( (device) => { +promise_test( (t) => { + setFakeDevices([fakeDevices["FakeGooglePixelPhone"]]); + return navigator.xr.requestDevice().then( (device) => new Promise((resolve) => { runWithUserGesture( () => { - device.requestSession({ exclusive: true }).then( (session) => { - runWithUserGesture( () => { - // Requesting a second exclusive session from a device that already - // has an active exclusive session should fail. Exclusive sessions - // are, well... exclusive! - promise_rejects(t, "InvalidStateError", device.requestSession({ exclusive: true })).then( () => { - // End the exclusive session and try again. Now the exclusive - // session creation should succeed. - session.end().then( () => { - runWithUserGesture( () => { - device.requestSession({ exclusive: true }).then( (session) => { - }, (err) => { - t.step( () => { - assert_unreached("requestSession rejected second exclusive session"); + resolve(device.requestSession({ exclusive: true }) + .then( (session) => new Promise((resolve) => { + runWithUserGesture( () => { + // Requesting a second exclusive session from a device that already + // has an active exclusive session should fail. Exclusive sessions + // are, well... exclusive! + resolve(promise_rejects( + t, + "InvalidStateError", + device.requestSession({ exclusive: true }) + ).then( () => { + // End the exclusive session and try again. Now the exclusive + // session creation should succeed. + return session.end().then( () => new Promise((resolve) => { + runWithUserGesture( () => { + resolve(device.requestSession({ exclusive: true })); }); - }).then( () => { - t.done(); - }); - }); - }); + })); + })); }); - }); - }, (err) => { - t.step( () => { - assert_unreached("requestSession rejected first exclusive session"); - }); - }).then( () => { - t.done(); - }); - - return; + }))); }); - }, (err) => { - t.step( () => { - assert_unreached("getDevices rejected"); - }); - }); -}, [fakeDisplays["Pixel"]], -"requestSession prevents creation of multiple simultaneous exclusive sessions"); + })); +}, "requestSession prevents creation of multiple simultaneous exclusive sessions"); </script>
diff --git a/third_party/WebKit/LayoutTests/xr/xrSession_requestFrameOfReference.html b/third_party/WebKit/LayoutTests/xr/xrSession_requestFrameOfReference.html index 16a298a6..670fbfa 100644 --- a/third_party/WebKit/LayoutTests/xr/xrSession_requestFrameOfReference.html +++ b/third_party/WebKit/LayoutTests/xr/xrSession_requestFrameOfReference.html
@@ -1,75 +1,39 @@ <!DOCTYPE html> <script src="../resources/testharness.js"></script> <script src="../resources/testharnessreport.js"></script> -<script src="../vr/resources/fake-vr-displays.js"></script> <script src="file:///gen/layout_test_data/mojo/public/js/mojo_bindings.js"></script> <script src="file:///gen/device/vr/vr_service.mojom.js"></script> -<script src="../vr/resources/mock-vr-service.js"></script> -<script src="../vr/resources/test-constants.js"></script> +<script src="../xr/resources/xr-device-mocking.js"></script> +<script src="../xr/resources/xr-test-utils.js"></script> +<script src="../xr/resources/test-constants.js"></script> <canvas id="webgl-canvas"></canvas> -<script src="../vr/resources/presentation-setup.js"></script> + <script> -let fakeDisplays = fakeVRDisplays(); +let fakeDevices = fakeXRDevices(); -vr_test( (t) => { - return navigator.xr.requestDevice().then( (device) => { - runWithUserGesture( () => { - device.requestSession({ exclusive: true }).then( (session) => { - - promise_test( function() { - return promise_rejects(this, new TypeError(), - session.requestFrameOfReference("foo")); - }, "requestFrameOfReference rejected for unknown requested type."); - - return Promise.all([ - session.requestFrameOfReference("headModel").then( (frameOfRef) => { - t.step( () => { - assert_true(frameOfRef instanceof XRCoordinateSystem); - assert_true(frameOfRef instanceof XRFrameOfReference); - }, "'headModel' Frame of Reference is the correct type."); - }, (err) => { - t.step( () => { - assert_unreached("requestFrameOfReference 'headModel' rejected"); - }); - }), - - session.requestFrameOfReference("eyeLevel").then( (frameOfRef) => { - t.step( () => { - assert_true(frameOfRef instanceof XRCoordinateSystem); - assert_true(frameOfRef instanceof XRFrameOfReference); - }, "'eyeLevel' Frame of Reference is the correct type."); - }, (err) => { - t.step( () => { - assert_unreached("requestFrameOfReference 'eyeLevel' rejected"); - }); - }), - - session.requestFrameOfReference("stage").then( (frameOfRef) => { - t.step( () => { - assert_true(frameOfRef instanceof XRCoordinateSystem); - assert_true(frameOfRef instanceof XRFrameOfReference); - }, "'stage' Frame of Reference is the correct type."); - }, (err) => { - t.step( () => { - assert_unreached("requestFrameOfReference 'stage' rejected"); - }); - }) - ]); - - }, (err) => { - t.step( () => { - assert_unreached("requestSession rejected"); - }); - }).then( () => { - t.done(); - }); - }); - }, (err) => { - t.step( () => { - assert_unreached("requestDevice rejected"); - }); - }); -}, [fakeDisplays["Pixel"]], +xr_session_promise_test( (session, t) => { + return promise_rejects(t, new TypeError(), session.requestFrameOfReference("foo")) + .then(() => Promise.all([ + session.requestFrameOfReference("headModel").then( (frameOfRef) => { + assert_true(frameOfRef instanceof XRCoordinateSystem, + "headModel frameOfRef is not correct type."); + assert_true(frameOfRef instanceof XRFrameOfReference, + "headModel frameOfRef is not correct type."); + }), + session.requestFrameOfReference("eyeLevel").then( (frameOfRef) => { + assert_true(frameOfRef instanceof XRCoordinateSystem, + "eyeLevel frameOfRef is not correct type."); + assert_true(frameOfRef instanceof XRFrameOfReference, + "eyeLevel frameOfRef is not correct type."); + }), + session.requestFrameOfReference("stage").then( (frameOfRef) => { + assert_true(frameOfRef instanceof XRCoordinateSystem, + "stage frameOfRef is not correct type."); + assert_true(frameOfRef instanceof XRFrameOfReference, + "stage frameOfRef is not correct type."); + }) + ])); +}, fakeDevices["FakeGooglePixelPhone"], { exclusive: true }, "requestFrameOfReference returns the expected objects"); </script>
diff --git a/third_party/WebKit/LayoutTests/xr/xrView_match.html b/third_party/WebKit/LayoutTests/xr/xrView_match.html index 2da49d13..218cbe8 100644 --- a/third_party/WebKit/LayoutTests/xr/xrView_match.html +++ b/third_party/WebKit/LayoutTests/xr/xrView_match.html
@@ -1,60 +1,60 @@ <!DOCTYPE html> <script src="../resources/testharness.js"></script> <script src="../resources/testharnessreport.js"></script> -<script src="../vr/resources/fake-vr-displays.js"></script> <script src="file:///gen/layout_test_data/mojo/public/js/mojo_bindings.js"></script> <script src="file:///gen/device/vr/vr_service.mojom.js"></script> -<script src="../vr/resources/mock-vr-service.js"></script> -<script src="../vr/resources/test-constants.js"></script> +<script src="../xr/resources/xr-device-mocking.js"></script> +<script src="../xr/resources/xr-test-utils.js"></script> +<script src="../xr/resources/test-constants.js"></script> <canvas id="webgl-canvas"></canvas> -<script src="../vr/resources/presentation-setup.js"></script> -<script> -let fakeDisplays = fakeVRDisplays(); -xr_session_test( (t, session, mockService) => { +<script> +let fakeDevices = fakeXRDevices(); + +xr_session_promise_test( (session) => { // Session must have a baseLayer or frame requests will be ignored. let webglLayer = new XRWebGLLayer(session, gl); session.baseLayer = webglLayer; - session.requestFrameOfReference("eyeLevel").then((frameOfRef) => { + return session.requestFrameOfReference("eyeLevel").then((frameOfRef) => new Promise((resolve) =>{ function onFrame(time, xrFrame) { - t.step( () => { - // Ensure that two views are provided. - assert_not_equals(xrFrame.views, null); - assert_equals(xrFrame.views.length, 2); + // Ensure that two views are provided. + assert_not_equals(xrFrame.views, null); + assert_equals(xrFrame.views.length, 2); - let leftView = xrFrame.views[0]; - let rightView = xrFrame.views[1]; + let leftView = xrFrame.views[0]; + let rightView = xrFrame.views[1]; - // Ensure that the views are the right type. - assert_true(leftView instanceof XRView); - assert_true(rightView instanceof XRView); + // Ensure that the views are the right type. + assert_true(leftView instanceof XRView); + assert_true(rightView instanceof XRView); - // Ensure that they have the expected eye enums. - assert_equals(leftView.eye, "left"); - assert_equals(rightView.eye, "right"); + // Ensure that they have the expected eye enums. + assert_equals(leftView.eye, "left"); + assert_equals(rightView.eye, "right"); - // Ensure they have the expected projection matrices. - assert_not_equals(leftView.projectionMatrix, null); - assert_not_equals(rightView.projectionMatrix, null); + // Ensure they have the expected projection matrices. + assert_not_equals(leftView.projectionMatrix, null); + assert_not_equals(rightView.projectionMatrix, null); - let displayLeftEye = fakeDisplays["Pixel"].leftEye; - let displayRightEye = fakeDisplays["Pixel"].rightEye; + let displayLeftEye = fakeDevices["FakeGooglePixelPhone"].leftEye; + let displayRightEye = fakeDevices["FakeGooglePixelPhone"].rightEye; - let expectedLeftProjection = perspectiveFromFieldOfView( - displayLeftEye.fieldOfView, session.depthNear, session.depthFar); - let expectedRightProjection = perspectiveFromFieldOfView( - displayRightEye.fieldOfView, session.depthNear, session.depthFar); + let expectedLeftProjection = perspectiveFromFieldOfView( + displayLeftEye.fieldOfView, session.depthNear, session.depthFar); + let expectedRightProjection = perspectiveFromFieldOfView( + displayRightEye.fieldOfView, session.depthNear, session.depthFar); - assert_matrices_approx_equal(leftView.projectionMatrix, expectedLeftProjection); - assert_matrices_approx_equal(rightView.projectionMatrix, expectedRightProjection); - }, "XRView attributes match the expected values"); - t.done(); + assert_matrices_approx_equal(leftView.projectionMatrix, expectedLeftProjection); + assert_matrices_approx_equal(rightView.projectionMatrix, expectedRightProjection); + + // Finished test. + resolve(); } session.requestAnimationFrame(onFrame); - }); -}, fakeDisplays["Pixel"], { exclusive: true }, + })); +}, fakeDevices["FakeGooglePixelPhone"], { exclusive: true }, "XRPresentationFrame contains the expected views"); </script>
diff --git a/third_party/WebKit/LayoutTests/xr/xrView_oneframeupdate.html b/third_party/WebKit/LayoutTests/xr/xrView_oneframeupdate.html index 2dc48a6..115b75283 100644 --- a/third_party/WebKit/LayoutTests/xr/xrView_oneframeupdate.html +++ b/third_party/WebKit/LayoutTests/xr/xrView_oneframeupdate.html
@@ -1,34 +1,34 @@ <!DOCTYPE html> <script src="../resources/testharness.js"></script> <script src="../resources/testharnessreport.js"></script> -<script src="../vr/resources/fake-vr-displays.js"></script> <script src="file:///gen/layout_test_data/mojo/public/js/mojo_bindings.js"></script> <script src="file:///gen/device/vr/vr_service.mojom.js"></script> -<script src="../vr/resources/mock-vr-service.js"></script> -<script src="../vr/resources/test-constants.js"></script> +<script src="../xr/resources/xr-device-mocking.js"></script> +<script src="../xr/resources/xr-test-utils.js"></script> +<script src="../xr/resources/test-constants.js"></script> <canvas id="webgl-canvas"></canvas> -<script src="../vr/resources/presentation-setup.js"></script> + <script> -let fakeDisplays = fakeVRDisplays(); +let fakeDevices = fakeXRDevices(); -let displayLeftEye = fakeDisplays["Pixel"].leftEye; -let displayRightEye = fakeDisplays["Pixel"].rightEye; +let displayLeftEye = fakeDevices["FakeGooglePixelPhone"].leftEye; +let displayRightEye = fakeDevices["FakeGooglePixelPhone"].rightEye; -xr_session_test( (t, session, mockService) => { +xr_session_promise_test( (session) => { // Session must have a baseLayer or frame requests will be ignored. session.baseLayer = new XRWebGLLayer(session, gl); - session.requestFrameOfReference("eyeLevel").then((frameOfRef) => { - let counter = 0; + return session.requestFrameOfReference("eyeLevel") + .then((frameOfRef) => new Promise((resolve) =>{ + let counter = 0; - function onFrame(time, xrFrame) { - let leftView = xrFrame.views[0]; - let rightView = xrFrame.views[1]; + function onFrame(time, xrFrame) { + let leftView = xrFrame.views[0]; + let rightView = xrFrame.views[1]; - if (counter == 0) { - session.requestAnimationFrame(onFrame); + if (counter == 0) { + session.requestAnimationFrame(onFrame); - t.step( () => { let expectedLeftProjection = perspectiveFromFieldOfView( displayLeftEye.fieldOfView, session.depthNear, session.depthFar); let expectedRightProjection = perspectiveFromFieldOfView( @@ -45,9 +45,7 @@ // account the new session depth values this frame. assert_matrices_approx_equal(leftView.projectionMatrix, expectedLeftProjection); assert_matrices_approx_equal(rightView.projectionMatrix, expectedRightProjection); - }, "Projection matrices do not update within the same frame"); - } else { - t.step( () => { + } else { // New depth values should be retained between frames. assert_equals(session.depthNear, 1.0); assert_equals(session.depthFar, 100.0); @@ -60,15 +58,14 @@ // Projection matricies should now reflect the new depth values assert_matrices_approx_equal(leftView.projectionMatrix, expectedLeftProjection); assert_matrices_approx_equal(rightView.projectionMatrix, expectedRightProjection); - }, "Projection matrices do update on subsequent frames"); - t.done(); + resolve(); + } + counter++; } - counter++; - } - session.requestAnimationFrame(onFrame); - }); -}, fakeDisplays["Pixel"], { exclusive: true }, + session.requestAnimationFrame(onFrame); + })); +}, fakeDevices["FakeGooglePixelPhone"], { exclusive: true }, "XRView projection matrices update near and far depths on the next frame"); </script>
diff --git a/third_party/WebKit/LayoutTests/xr/xrViewport_valid.html b/third_party/WebKit/LayoutTests/xr/xrViewport_valid.html index ae20bdf..20f643c 100644 --- a/third_party/WebKit/LayoutTests/xr/xrViewport_valid.html +++ b/third_party/WebKit/LayoutTests/xr/xrViewport_valid.html
@@ -1,70 +1,69 @@ <!DOCTYPE html> <script src="../resources/testharness.js"></script> <script src="../resources/testharnessreport.js"></script> -<script src="../vr/resources/fake-vr-displays.js"></script> <script src="file:///gen/layout_test_data/mojo/public/js/mojo_bindings.js"></script> <script src="file:///gen/device/vr/vr_service.mojom.js"></script> -<script src="../vr/resources/mock-vr-service.js"></script> -<script src="../vr/resources/test-constants.js"></script> +<script src="../xr/resources/xr-device-mocking.js"></script> +<script src="../xr/resources/xr-test-utils.js"></script> +<script src="../xr/resources/test-constants.js"></script> <canvas id="webgl-canvas"></canvas> -<script src="../vr/resources/presentation-setup.js"></script> -<script> -let fakeDisplays = fakeVRDisplays(); -xr_session_test( (t, session, mockService) => { +<script> +let fakeDevices = fakeXRDevices(); + +xr_session_promise_test( (session) => { // Session must have a baseLayer or frame requests will be ignored. let webglLayer = new XRWebGLLayer(session, gl); session.baseLayer = webglLayer; - session.requestFrameOfReference("eyeLevel").then((frameOfRef) => { - function onFrame(time, xrFrame) { - let leftView = xrFrame.views[0]; - let rightView = xrFrame.views[1]; + return session.requestFrameOfReference("eyeLevel") + .then((frameOfRef) => new Promise((resolve) =>{ + function onFrame(time, xrFrame) { + let leftView = xrFrame.views[0]; + let rightView = xrFrame.views[1]; - let leftViewport = leftView.getViewport(webglLayer); - let rightViewport = rightView.getViewport(webglLayer); + let leftViewport = leftView.getViewport(webglLayer); + let rightViewport = rightView.getViewport(webglLayer); - // Ensure the views report the expected viewports into the WebGL layer. - t.step( () => { + // Ensure the views report the expected viewports into the WebGL layer. assert_true(leftViewport instanceof XRViewport); assert_true(rightViewport instanceof XRViewport); assert_not_equals(leftViewport, null); assert_not_equals(rightViewport, null); - }, "Viewports are of the right type and not null"); - // Exact viewport values don't matter, but they must pass several tests: + // Exact viewport values don't matter, but they must pass several tests: - t.step( () => { + // Viewports have non-zero widths and heights. assert_greater_than(leftViewport.width, 0); assert_greater_than(leftViewport.height, 0); assert_greater_than(rightViewport.width, 0); assert_greater_than(rightViewport.height, 0); - }, "Viewports have non-zero widths and heights"); - t.step( () => { + // Viewports are located within the framebuffer. assert_greater_than_equal(leftViewport.x, 0); assert_greater_than_equal(leftViewport.y, 0); assert_greater_than_equal(leftViewport.x, 0); assert_greater_than_equal(leftViewport.y, 0); - assert_less_than_equal(leftViewport.x + leftViewport.width, webglLayer.framebufferWidth); - assert_less_than_equal(leftViewport.y + leftViewport.height, webglLayer.framebufferHeight); - assert_less_than_equal(rightViewport.x + rightViewport.width, webglLayer.framebufferWidth); - assert_less_than_equal(rightViewport.y + rightViewport.height, webglLayer.framebufferHeight); - }, "Viewports are located within the framebuffer"); + assert_less_than_equal( + leftViewport.x + leftViewport.width, webglLayer.framebufferWidth); + assert_less_than_equal( + leftViewport.y + leftViewport.height, webglLayer.framebufferHeight); + assert_less_than_equal( + rightViewport.x + rightViewport.width, webglLayer.framebufferWidth); + assert_less_than_equal( + rightViewport.y + rightViewport.height, webglLayer.framebufferHeight); - t.step( () => { // Assumes that the left viewport will always be physically to the left // of the right viewport. assert_less_than_equal(leftViewport.x + leftViewport.width, rightViewport.x); - }, "XRViewports do not overlap"); - t.done(); - } - session.requestAnimationFrame(onFrame); - }); -}, fakeDisplays["Pixel"], { exclusive: true }, + resolve(); + } + session.requestAnimationFrame(onFrame); + })); +}, fakeDevices["FakeGooglePixelPhone"], { exclusive: true }, "XRViewport attributes are valid"); </script>
diff --git a/third_party/WebKit/LayoutTests/xr/xrWebGLLayer_constructor.html b/third_party/WebKit/LayoutTests/xr/xrWebGLLayer_constructor.html index ceaca9c..0b99252 100644 --- a/third_party/WebKit/LayoutTests/xr/xrWebGLLayer_constructor.html +++ b/third_party/WebKit/LayoutTests/xr/xrWebGLLayer_constructor.html
@@ -1,60 +1,51 @@ <!DOCTYPE html> <script src="../resources/testharness.js"></script> <script src="../resources/testharnessreport.js"></script> -<script src="../vr/resources/fake-vr-displays.js"></script> <script src="file:///gen/layout_test_data/mojo/public/js/mojo_bindings.js"></script> <script src="file:///gen/device/vr/vr_service.mojom.js"></script> -<script src="../vr/resources/mock-vr-service.js"></script> -<script src="../vr/resources/test-constants.js"></script> +<script src="../xr/resources/xr-device-mocking.js"></script> +<script src="../xr/resources/xr-test-utils.js"></script> +<script src="../xr/resources/test-constants.js"></script> <canvas id="webgl-canvas"></canvas> -<script src="../vr/resources/presentation-setup.js"></script> -<script> -let fakeDisplays = fakeVRDisplays(); -xr_session_test( (t, session, mockService) => { - t.step( () => { - try { - let webglLayerGood = new XRWebGLLayer(session, gl); - } catch (err) { - assert_unreached("XRWebGLLayer should not fail with valid arguments"); - } - }); +<script> +let fakeDevices = fakeXRDevices(); + +xr_session_promise_test( (session) => new Promise((resolve, reject) => { + try { + let webglLayerGood = new XRWebGLLayer(session, gl); + } catch (err) { + reject("XRWebGLLayer should not fail with valid arguments"); + } let lose_context_ext = gl.getExtension('WEBGL_lose_context'); webglCanvas.addEventListener('webglcontextlost', (ev) => { ev.preventDefault(); - t.step( () => { - try { - let webglLayerBadContext = new XRWebGLLayer(session, gl); - assert_unreached("XRWebGLLayer should fail when created with a lost context"); - t.done(); - } catch (err) { - assert_equals(err.name, 'InvalidStateError'); - setTimeout(() => { lose_context_ext.restoreContext(); }, 100); - } - }); + try { + let webglLayerBadContext = new XRWebGLLayer(session, gl); + reject("XRWebGLLayer should fail when created with a lost context"); + } catch (err) { + assert_equals(err.name, 'InvalidStateError'); + setTimeout(() => { lose_context_ext.restoreContext(); }, 100); + } }); webglCanvas.addEventListener('webglcontextrestored', (ev) => { - session.end().then(() => { - t.step( () => { - try { - let webglLayerBadSession = new XRWebGLLayer(session, gl); - assert_unreached("XRWebGLLayer should fail when created with an ended session"); - } catch (err) { - assert_equals(err.name, 'InvalidStateError'); - } - - t.done(); - }); - }); + resolve(session.end().then(() => { + try { + let webglLayerBadSession = new XRWebGLLayer(session, gl); + assert_unreached("XRWebGLLayer should fail when created with an ended session"); + } catch (err) { + assert_equals(err.name, 'InvalidStateError'); + } + })); }); lose_context_ext.loseContext(); -}, fakeDisplays["Pixel"], { exclusive: true }, +}), fakeDevices["FakeGooglePixelPhone"], { exclusive: true }, "Ensure a WebGL layer's framebuffer can only be drawn to inside a XR frame"); </script>
diff --git a/third_party/WebKit/LayoutTests/xr/xrWebGLLayer_dirty_framebuffer.html b/third_party/WebKit/LayoutTests/xr/xrWebGLLayer_dirty_framebuffer.html index ccb231b1..f632694d 100644 --- a/third_party/WebKit/LayoutTests/xr/xrWebGLLayer_dirty_framebuffer.html +++ b/third_party/WebKit/LayoutTests/xr/xrWebGLLayer_dirty_framebuffer.html
@@ -1,51 +1,52 @@ <!DOCTYPE html> <script src="../resources/testharness.js"></script> <script src="../resources/testharnessreport.js"></script> -<script src="../vr/resources/fake-vr-displays.js"></script> <script src="file:///gen/layout_test_data/mojo/public/js/mojo_bindings.js"></script> <script src="file:///gen/device/vr/vr_service.mojom.js"></script> -<script src="../vr/resources/mock-vr-service.js"></script> -<script src="../vr/resources/test-constants.js"></script> +<script src="../xr/resources/xr-device-mocking.js"></script> +<script src="../xr/resources/xr-test-utils.js"></script> +<script src="../xr/resources/test-constants.js"></script> <canvas id="webgl-canvas"></canvas> -<script src="../vr/resources/presentation-setup.js"></script> -<script> -let fakeDisplays = fakeVRDisplays(); -xr_session_test( (t, session, mockService) => { +<script> +let fakeDevices = fakeXRDevices(); + +xr_session_promise_test( (session) => new Promise((resolve, reject) => { // Session must have a baseLayer or else frame requests will be ignored. let webglLayer = new XRWebGLLayer(session, gl); session.baseLayer = webglLayer; - let mockDisplay = mockService.mockVRDisplays_[0]; + function onSkipFrame(time, xrFrame) { - // No GL commands issued + // No GL commands issued. session.requestAnimationFrame(onDrawToCanvas); } + function onDrawToCanvas(time, xrFrame) { - // Ensure the previous step did not submit a frame - t.step( () => { - assert_equals(mockDisplay.getSubmitFrameCount(), 0); - }, "Expecting no frame was submitted during onSkipFrame"); - // Clear the canvas + // Ensure the previous step did not submit a frame. + assert_equals(getSubmitFrameCount(), 0); + + // Clear the canvas. gl.clear(gl.COLOR_BUFFER_BIT); session.requestAnimationFrame(onDrawToFramebuffer); } + function onDrawToFramebuffer(time, xrFrame) { - // Ensure the previous step did not submit a frame - t.step( () => { - assert_equals(mockDisplay.getSubmitFrameCount(), 0); - }, "Expecting no frame was submitted during onDrawToCanvas"); - // Clear the VRWebGLLayer framebuffer + // Ensure the previous step did not submit a frame. + assert_equals(getSubmitFrameCount(), 0); + + // Clear the VRWebGLLayer framebuffer. gl.bindFramebuffer(gl.FRAMEBUFFER, webglLayer.framebuffer); gl.clear(gl.COLOR_BUFFER_BIT); + // After the function returns ensure the frame was submitted. window.setTimeout(() => { - t.step( () => { - assert_equals(mockDisplay.getSubmitFrameCount(), 1); - }, "Expecting one frame was submitted during onDrawToFramebuffer"); - t.done(); + assert_equals(getSubmitFrameCount(), 1); + // Finished test. + resolve(); }, 100); } + session.requestAnimationFrame(onSkipFrame); -}, fakeDisplays["Pixel"], { exclusive: true }, +}), fakeDevices["FakeGooglePixelPhone"], { exclusive: true }, "A frame should be submitted if the base layer was written to during requestAnimationFrame"); </script>
diff --git a/third_party/WebKit/LayoutTests/xr/xrWebGLLayer_framebuffer_draw.html b/third_party/WebKit/LayoutTests/xr/xrWebGLLayer_framebuffer_draw.html index 3a67bedf..0bf94c4 100644 --- a/third_party/WebKit/LayoutTests/xr/xrWebGLLayer_framebuffer_draw.html +++ b/third_party/WebKit/LayoutTests/xr/xrWebGLLayer_framebuffer_draw.html
@@ -1,15 +1,15 @@ <!DOCTYPE html> <script src="../resources/testharness.js"></script> <script src="../resources/testharnessreport.js"></script> -<script src="../vr/resources/fake-vr-displays.js"></script> <script src="file:///gen/layout_test_data/mojo/public/js/mojo_bindings.js"></script> <script src="file:///gen/device/vr/vr_service.mojom.js"></script> -<script src="../vr/resources/mock-vr-service.js"></script> -<script src="../vr/resources/test-constants.js"></script> +<script src="../xr/resources/xr-device-mocking.js"></script> +<script src="../xr/resources/xr-test-utils.js"></script> +<script src="../xr/resources/test-constants.js"></script> <canvas id="webgl-canvas"></canvas> -<script src="../vr/resources/presentation-setup.js"></script> + <script> -let fakeDisplays = fakeVRDisplays(); +let fakeDevices = fakeXRDevices(); // Very simple program setup with no error checking. function setupProgram(gl, vertexSrc, fragmentSrc) { @@ -31,7 +31,7 @@ return program; } -xr_session_test( (t, session, mockService) => { +xr_session_promise_test( (session) => new Promise((resolve, reject) => { // Setup simple WebGL geometry to draw with. let program = setupProgram(gl, "attribute vec4 vPosition; void main() { gl_Position = vPosition; }", @@ -40,7 +40,10 @@ let vertexObject = gl.createBuffer(); gl.bindBuffer(gl.ARRAY_BUFFER, vertexObject); - gl.bufferData(gl.ARRAY_BUFFER, new Float32Array([ 0,0.5,0, -0.5,-0.5,0, 0.5,-0.5,0 ]), gl.STATIC_DRAW); + gl.bufferData( + gl.ARRAY_BUFFER, + new Float32Array([ 0,0.5,0, -0.5,-0.5,0, 0.5,-0.5,0 ]), + gl.STATIC_DRAW); gl.enableVertexAttribArray(0); gl.vertexAttribPointer(0, 3, gl.FLOAT, false, 0, 0); @@ -54,44 +57,36 @@ let xrFramebuffer = webglLayer.framebuffer; - function runDrawTests(t, expectedError) { - t.step( () => { - // Make sure we're starting with a clean error slate. - assert_equals(gl.getError(), gl.NO_ERROR); + function runDrawTests(expectedError) { + // Make sure we're starting with a clean error slate. + assert_equals(gl.getError(), gl.NO_ERROR); - gl.bindFramebuffer(gl.FRAMEBUFFER, xrFramebuffer); - assert_equals(gl.getError(), gl.NO_ERROR); - }, "Framebuffer must be bindable"); + gl.bindFramebuffer(gl.FRAMEBUFFER, xrFramebuffer); + assert_equals(gl.getError(), gl.NO_ERROR); - t.step( () => { - gl.clear(gl.COLOR_BUFFER_BIT); - assert_equals(gl.getError(), gl[expectedError]); + gl.clear(gl.COLOR_BUFFER_BIT); + assert_equals(gl.getError(), gl[expectedError]); - gl.clear(gl.DEPTH_BUFFER_BIT); - assert_equals(gl.getError(), gl[expectedError]); - }, `Test clearing the framebuffer, expect ${expectedError}`); + gl.clear(gl.DEPTH_BUFFER_BIT); + assert_equals(gl.getError(), gl[expectedError]); - t.step( () => { - gl.drawArrays(gl.TRIANGLES, 0, 3); - assert_equals(gl.getError(), gl[expectedError]); - }, `Test drawArrays, expect ${expectedError}`); + gl.drawArrays(gl.TRIANGLES, 0, 3); + assert_equals(gl.getError(), gl[expectedError]); - t.step( () => { - gl.drawElements(gl.TRIANGLES, 3, gl.UNSIGNED_BYTE, 0); - assert_equals(gl.getError(), gl[expectedError]); - }, `Test drawElements, expect ${expectedError}`); + gl.drawElements(gl.TRIANGLES, 3, gl.UNSIGNED_BYTE, 0); + assert_equals(gl.getError(), gl[expectedError]); } // Drawing operations outside of a XR frame should fail. - runDrawTests(t, "INVALID_FRAMEBUFFER_OPERATION"); + runDrawTests("INVALID_FRAMEBUFFER_OPERATION"); // Drawing operations within a XR frame should succeed. session.requestAnimationFrame((time, xrFrame) => { - runDrawTests(t, "NO_ERROR"); - t.done(); + runDrawTests("NO_ERROR"); + resolve(); }); -}, fakeDisplays["Pixel"], { exclusive: true }, +}), fakeDevices["FakeGooglePixelPhone"], { exclusive: true }, "Ensure a WebGL layer's framebuffer can only be drawn to inside a XR frame"); </script>
diff --git a/third_party/WebKit/LayoutTests/xr/xrWebGLLayer_opaque_framebuffer.html b/third_party/WebKit/LayoutTests/xr/xrWebGLLayer_opaque_framebuffer.html index 723738d..bffd554c 100644 --- a/third_party/WebKit/LayoutTests/xr/xrWebGLLayer_opaque_framebuffer.html +++ b/third_party/WebKit/LayoutTests/xr/xrWebGLLayer_opaque_framebuffer.html
@@ -1,109 +1,104 @@ <!DOCTYPE html> <script src="../resources/testharness.js"></script> <script src="../resources/testharnessreport.js"></script> -<script src="../vr/resources/fake-vr-displays.js"></script> <script src="file:///gen/layout_test_data/mojo/public/js/mojo_bindings.js"></script> <script src="file:///gen/device/vr/vr_service.mojom.js"></script> -<script src="../vr/resources/mock-vr-service.js"></script> -<script src="../vr/resources/test-constants.js"></script> +<script src="../xr/resources/xr-device-mocking.js"></script> +<script src="../xr/resources/xr-test-utils.js"></script> +<script src="../xr/resources/test-constants.js"></script> <canvas id="webgl-canvas"></canvas> -<script src="../vr/resources/presentation-setup.js"></script> -<script> -let fakeDisplays = fakeVRDisplays(); -xr_session_test( (t, session, mockService) => { +<script> +let fakeDevices = fakeXRDevices(); + +xr_session_promise_test( (session) => new Promise((resolve, reject) => { // Session must have a baseLayer or frame requests will be ignored. let webglLayer = new XRWebGLLayer(session, gl); session.baseLayer = webglLayer; let xrFramebuffer = webglLayer.framebuffer; - t.step( () => { - // Make sure we're starting with a clean error slate. - assert_equals(gl.getError(), gl.NO_ERROR); + // Make sure we're starting with a clean error slate. + assert_equals(gl.getError(), gl.NO_ERROR); - assert_not_equals(xrFramebuffer, null); - assert_greater_than(webglLayer.framebufferWidth, 0); - assert_greater_than(webglLayer.framebufferHeight, 0); + assert_not_equals(xrFramebuffer, null); + assert_greater_than(webglLayer.framebufferWidth, 0); + assert_greater_than(webglLayer.framebufferHeight, 0); - gl.bindFramebuffer(gl.FRAMEBUFFER, xrFramebuffer); - assert_equals(gl.getError(), gl.NO_ERROR); - }, "Framebuffer must be non-null, non-zero size, bindable."); + gl.bindFramebuffer(gl.FRAMEBUFFER, xrFramebuffer); + assert_equals(gl.getError(), gl.NO_ERROR); - t.step( () => { - gl.deleteFramebuffer(xrFramebuffer); - assert_equals(gl.getError(), gl.INVALID_OPERATION); + gl.deleteFramebuffer(xrFramebuffer); + assert_equals(gl.getError(), gl.INVALID_OPERATION); - // Make sure the framebuffer is still bound after failed attempt to delete. - let boundFramebuffer = gl.getParameter(gl.FRAMEBUFFER_BINDING); - assert_equals(xrFramebuffer, boundFramebuffer); - assert_equals(gl.getError(), gl.NO_ERROR); - }, "Ensure the framebuffer cannot be deleted"); + // Make sure the framebuffer is still bound after failed attempt to delete. + let boundFramebuffer = gl.getParameter(gl.FRAMEBUFFER_BINDING); + assert_equals(xrFramebuffer, boundFramebuffer); + assert_equals(gl.getError(), gl.NO_ERROR); - t.step( () => { - let attachments = [ - gl.COLOR_ATTACHMENT0, - gl.DEPTH_ATTACHMENT, - gl.STENCIL_ATTACHMENT, - ]; + // Ensure the framebuffer attachment properties cannot be inspected. + let attachments = [ + gl.COLOR_ATTACHMENT0, + gl.DEPTH_ATTACHMENT, + gl.STENCIL_ATTACHMENT, + ]; - let parameters = [ - gl.FRAMEBUFFER_ATTACHMENT_OBJECT_TYPE, - gl.FRAMEBUFFER_ATTACHMENT_OBJECT_NAME, - gl.FRAMEBUFFER_ATTACHMENT_TEXTURE_LEVEL, - gl.FRAMEBUFFER_ATTACHMENT_TEXTURE_CUBE_MAP_FACE, - ]; + let parameters = [ + gl.FRAMEBUFFER_ATTACHMENT_OBJECT_TYPE, + gl.FRAMEBUFFER_ATTACHMENT_OBJECT_NAME, + gl.FRAMEBUFFER_ATTACHMENT_TEXTURE_LEVEL, + gl.FRAMEBUFFER_ATTACHMENT_TEXTURE_CUBE_MAP_FACE, + ]; - for (let attachment of attachments) { - for (let parameter of parameters) { - let value = gl.getFramebufferAttachmentParameter(gl.FRAMEBUFFER, attachment, parameter); - assert_equals(value, null); - assert_equals(gl.getError(), gl.INVALID_OPERATION); - } + for (let attachment of attachments) { + for (let parameter of parameters) { + let value = gl.getFramebufferAttachmentParameter(gl.FRAMEBUFFER, attachment, parameter); + assert_equals(value, null); + assert_equals(gl.getError(), gl.INVALID_OPERATION); } - }, "Ensure the framebuffer attachment properties cannot be inspected"); + } let width = 64; let height = 64; - t.step( () => { - var texture = gl.createTexture(); - gl.bindTexture(gl.TEXTURE_2D, texture); - gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST); - gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST); - gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE); - gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE); - gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, width, height, 0, gl.RGBA, gl.UNSIGNED_BYTE, null); + // Ensure the framebuffer texture 2D attachmentments cannot be changed. + var texture = gl.createTexture(); + gl.bindTexture(gl.TEXTURE_2D, texture); + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST); + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST); + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE); + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE); + gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, width, height, 0, gl.RGBA, gl.UNSIGNED_BYTE, null); - gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0); - assert_equals(gl.getError(), gl.INVALID_OPERATION); - }, "Ensure the framebuffer texture 2D attachmentments cannot be changed"); + gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0); + assert_equals(gl.getError(), gl.INVALID_OPERATION); - t.step( () => { - let renderbuffer = gl.createRenderbuffer(); - gl.bindRenderbuffer(gl.RENDERBUFFER, renderbuffer); - gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, width, height); - gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, renderbuffer); - assert_equals(gl.getError(), gl.INVALID_OPERATION); + // Ensure the framebuffer renderbuffer attachmentments cannot be changed. + let renderbuffer = gl.createRenderbuffer(); + gl.bindRenderbuffer(gl.RENDERBUFFER, renderbuffer); + gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, width, height); + gl.framebufferRenderbuffer( + gl.FRAMEBUFFER, + gl.DEPTH_ATTACHMENT, + gl.RENDERBUFFER, + renderbuffer); + assert_equals(gl.getError(), gl.INVALID_OPERATION); - gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, width, height); - gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, renderbuffer); - assert_equals(gl.getError(), gl.INVALID_OPERATION); - }, "Ensure the framebuffer renderbuffer attachmentments cannot be changed"); + gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, width, height); + gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, renderbuffer); + assert_equals(gl.getError(), gl.INVALID_OPERATION); - t.step( () => { - assert_equals(gl.checkFramebufferStatus(gl.FRAMEBUFFER), gl.FRAMEBUFFER_UNSUPPORTED); - }, "Framebuffer status must be unsupported outside of a XR frame callback"); + // Framebuffer status must be unsupported outside of a XR frame callback. + assert_equals(gl.checkFramebufferStatus(gl.FRAMEBUFFER), gl.FRAMEBUFFER_UNSUPPORTED); session.requestAnimationFrame((time, xrFrame) => { - t.step( () => { - assert_equals(gl.checkFramebufferStatus(gl.FRAMEBUFFER), gl.FRAMEBUFFER_COMPLETE); - }, "Framebuffer status must be complete inside of a XR frame callback"); - - t.done(); + // Framebuffer status must be complete inside of a XR frame callback. + assert_equals(gl.checkFramebufferStatus(gl.FRAMEBUFFER), gl.FRAMEBUFFER_COMPLETE); + // Finished. + resolve(); }); -}, fakeDisplays["Pixel"], { exclusive: true }, +}), fakeDevices["FakeGooglePixelPhone"], { exclusive: true }, "Ensure that the framebuffer given by the WebGL layer is opaque"); </script>
diff --git a/third_party/WebKit/Source/bindings/core/v8/DOMWrapperWorldTest.cpp b/third_party/WebKit/Source/bindings/core/v8/DOMWrapperWorldTest.cpp index 2ed15cbf..2739157 100644 --- a/third_party/WebKit/Source/bindings/core/v8/DOMWrapperWorldTest.cpp +++ b/third_party/WebKit/Source/bindings/core/v8/DOMWrapperWorldTest.cpp
@@ -118,7 +118,8 @@ // Start a worker thread and create worlds on that. std::unique_ptr<WorkerBackingThread> thread = WorkerBackingThread::Create( - WebThreadCreationParams("DOMWrapperWorld test thread")); + WebThreadCreationParams(WebThreadType::kTestThread) + .SetThreadName("DOMWrapperWorld test thread")); scoped_refptr<base::SingleThreadTaskRunner> main_thread_task_runner = Platform::Current()->CurrentThread()->GetWebTaskRunner(); thread->BackingThread().PostTask(
diff --git a/third_party/WebKit/Source/bindings/core/v8/ScriptController.cpp b/third_party/WebKit/Source/bindings/core/v8/ScriptController.cpp index b2dd852..3b920e6 100644 --- a/third_party/WebKit/Source/bindings/core/v8/ScriptController.cpp +++ b/third_party/WebKit/Source/bindings/core/v8/ScriptController.cpp
@@ -145,13 +145,22 @@ .ToLocal(&script)) return result; - V8ScriptRunner::ProduceCache(GetIsolate(), script, source, - produce_cache_options, compile_options); + v8::MaybeLocal<v8::Value> maybe_result; + if (RuntimeEnabledFeatures::CodeCacheAfterExecuteEnabled()) { + maybe_result = V8ScriptRunner::RunCompiledScript( + GetIsolate(), script, GetFrame()->GetDocument()); + V8ScriptRunner::ProduceCache(GetIsolate(), script, source, + produce_cache_options, compile_options); + } else { + V8ScriptRunner::ProduceCache(GetIsolate(), script, source, + produce_cache_options, compile_options); + maybe_result = V8ScriptRunner::RunCompiledScript( + GetIsolate(), script, GetFrame()->GetDocument()); + } - if (!V8ScriptRunner::RunCompiledScript(GetIsolate(), script, - GetFrame()->GetDocument()) - .ToLocal(&result)) + if (!maybe_result.ToLocal(&result)) { return result; + } } return result;
diff --git a/third_party/WebKit/Source/bindings/core/v8/ScriptStreamerThread.cpp b/third_party/WebKit/Source/bindings/core/v8/ScriptStreamerThread.cpp index 5b8f5c50..19b34b5 100644 --- a/third_party/WebKit/Source/bindings/core/v8/ScriptStreamerThread.cpp +++ b/third_party/WebKit/Source/bindings/core/v8/ScriptStreamerThread.cpp
@@ -51,7 +51,7 @@ WebThread& ScriptStreamerThread::PlatformThread() { if (!IsRunning()) { thread_ = Platform::Current()->CreateThread( - WebThreadCreationParams("ScriptStreamerThread")); + WebThreadCreationParams(WebThreadType::kScriptStreamerThread)); } return *thread_; }
diff --git a/third_party/WebKit/Source/bindings/core/v8/WorkerOrWorkletScriptController.cpp b/third_party/WebKit/Source/bindings/core/v8/WorkerOrWorkletScriptController.cpp index af33a7b..030dc6e4 100644 --- a/third_party/WebKit/Source/bindings/core/v8/WorkerOrWorkletScriptController.cpp +++ b/third_party/WebKit/Source/bindings/core/v8/WorkerOrWorkletScriptController.cpp
@@ -280,10 +280,17 @@ kSharableCrossOrigin, compile_options, no_cache_reason, referrer_info) .ToLocal(&compiled_script)) { - V8ScriptRunner::ProduceCache(isolate_, compiled_script, source_code, - produce_cache_options, compile_options); - maybe_result = V8ScriptRunner::RunCompiledScript(isolate_, compiled_script, - global_scope_); + if (RuntimeEnabledFeatures::CodeCacheAfterExecuteEnabled()) { + maybe_result = V8ScriptRunner::RunCompiledScript( + isolate_, compiled_script, global_scope_); + V8ScriptRunner::ProduceCache(isolate_, compiled_script, source_code, + produce_cache_options, compile_options); + } else { + V8ScriptRunner::ProduceCache(isolate_, compiled_script, source_code, + produce_cache_options, compile_options); + maybe_result = V8ScriptRunner::RunCompiledScript( + isolate_, compiled_script, global_scope_); + } } if (!block.CanContinue()) {
diff --git a/third_party/WebKit/Source/core/BUILD.gn b/third_party/WebKit/Source/core/BUILD.gn index 78dc7eb..5c53aad2 100644 --- a/third_party/WebKit/Source/core/BUILD.gn +++ b/third_party/WebKit/Source/core/BUILD.gn
@@ -1698,7 +1698,6 @@ "css/cssom/CSSResourceValueTest.cpp", "css/cssom/CSSStyleImageValueTest.cpp", "css/cssom/CSSUnitValueTest.cpp", - "css/cssom/CSSVariableReferenceValueTest.cpp", "css/cssom/FilteredComputedStylePropertyMapTest.cpp", "css/invalidation/InvalidationSetTest.cpp", "css/invalidation/StyleInvalidatorTest.cpp", @@ -1712,6 +1711,7 @@ "css/parser/MediaConditionTest.cpp", "css/parser/SizesAttributeParserTest.cpp", "css/parser/SizesCalcParserTest.cpp", + "css/properties/CSSParsingUtilsTest.cpp", "css/resolver/FontBuilderTest.cpp", "css/resolver/FontStyleResolverTest.cpp", "css/resolver/MatchResultTest.cpp",
diff --git a/third_party/WebKit/Source/core/animation/Animation.cpp b/third_party/WebKit/Source/core/animation/Animation.cpp index 3c5a2a9..1eb8477 100644 --- a/third_party/WebKit/Source/core/animation/Animation.cpp +++ b/third_party/WebKit/Source/core/animation/Animation.cpp
@@ -45,7 +45,6 @@ #include "core/inspector/InspectorTraceEvents.h" #include "core/paint/PaintLayer.h" #include "core/probe/CoreProbes.h" -#include "platform/WebTaskRunner.h" #include "platform/animation/CompositorAnimationPlayer.h" #include "platform/bindings/ScriptForbiddenScope.h" #include "platform/heap/Persistent.h"
diff --git a/third_party/WebKit/Source/core/animation/BasicShapeInterpolationFunctions.cpp b/third_party/WebKit/Source/core/animation/BasicShapeInterpolationFunctions.cpp index faa1a14e..56b5074 100644 --- a/third_party/WebKit/Source/core/animation/BasicShapeInterpolationFunctions.cpp +++ b/third_party/WebKit/Source/core/animation/BasicShapeInterpolationFunctions.cpp
@@ -173,7 +173,8 @@ kCircleComponentIndexCount, }; -InterpolationValue ConvertCSSValue(const CSSBasicShapeCircleValue& circle) { +InterpolationValue ConvertCSSValue( + const cssvalue::CSSBasicShapeCircleValue& circle) { std::unique_ptr<InterpolableList> list = InterpolableList::Create(kCircleComponentIndexCount); list->Set(kCircleCenterXIndex, ConvertCSSCoordinate(circle.CenterX())); @@ -241,7 +242,8 @@ kEllipseComponentIndexCount, }; -InterpolationValue ConvertCSSValue(const CSSBasicShapeEllipseValue& ellipse) { +InterpolationValue ConvertCSSValue( + const cssvalue::CSSBasicShapeEllipseValue& ellipse) { std::unique_ptr<InterpolableList> list = InterpolableList::Create(kEllipseComponentIndexCount); list->Set(kEllipseCenterXIndex, ConvertCSSCoordinate(ellipse.CenterX())); @@ -326,7 +328,8 @@ kInsetComponentIndexCount, }; -InterpolationValue ConvertCSSValue(const CSSBasicShapeInsetValue& inset) { +InterpolationValue ConvertCSSValue( + const cssvalue::CSSBasicShapeInsetValue& inset) { std::unique_ptr<InterpolableList> list = InterpolableList::Create(kInsetComponentIndexCount); list->Set(kInsetTopIndex, ConvertCSSLength(inset.Top())); @@ -449,7 +452,8 @@ namespace PolygonFunctions { -InterpolationValue ConvertCSSValue(const CSSBasicShapePolygonValue& polygon) { +InterpolationValue ConvertCSSValue( + const cssvalue::CSSBasicShapePolygonValue& polygon) { size_t size = polygon.Values().size(); std::unique_ptr<InterpolableList> list = InterpolableList::Create(size); for (size_t i = 0; i < size; i++) @@ -506,16 +510,22 @@ InterpolationValue BasicShapeInterpolationFunctions::MaybeConvertCSSValue( const CSSValue& value) { - if (value.IsBasicShapeCircleValue()) - return CircleFunctions::ConvertCSSValue(ToCSSBasicShapeCircleValue(value)); - if (value.IsBasicShapeEllipseValue()) + if (value.IsBasicShapeCircleValue()) { + return CircleFunctions::ConvertCSSValue( + cssvalue::ToCSSBasicShapeCircleValue(value)); + } + if (value.IsBasicShapeEllipseValue()) { return EllipseFunctions::ConvertCSSValue( - ToCSSBasicShapeEllipseValue(value)); - if (value.IsBasicShapeInsetValue()) - return InsetFunctions::ConvertCSSValue(ToCSSBasicShapeInsetValue(value)); - if (value.IsBasicShapePolygonValue()) + cssvalue::ToCSSBasicShapeEllipseValue(value)); + } + if (value.IsBasicShapeInsetValue()) { + return InsetFunctions::ConvertCSSValue( + cssvalue::ToCSSBasicShapeInsetValue(value)); + } + if (value.IsBasicShapePolygonValue()) { return PolygonFunctions::ConvertCSSValue( - ToCSSBasicShapePolygonValue(value)); + cssvalue::ToCSSBasicShapePolygonValue(value)); + } return nullptr; }
diff --git a/third_party/WebKit/Source/core/css/BUILD.gn b/third_party/WebKit/Source/core/css/BUILD.gn index 018c1fd4..e69e2d6 100644 --- a/third_party/WebKit/Source/core/css/BUILD.gn +++ b/third_party/WebKit/Source/core/css/BUILD.gn
@@ -350,6 +350,7 @@ "cssom/CSSStyleImageValue.h", "cssom/CSSStyleValue.cpp", "cssom/CSSStyleValue.h", + "cssom/CSSStyleVariableReferenceValue.cpp", "cssom/CSSStyleVariableReferenceValue.h", "cssom/CSSTransformComponent.cpp", "cssom/CSSTransformComponent.h",
diff --git a/third_party/WebKit/Source/core/css/BasicShapeFunctions.cpp b/third_party/WebKit/Source/core/css/BasicShapeFunctions.cpp index 608f94f..04ab9f0 100644 --- a/third_party/WebKit/Source/core/css/BasicShapeFunctions.cpp +++ b/third_party/WebKit/Source/core/css/BasicShapeFunctions.cpp
@@ -133,8 +133,8 @@ case BasicShape::kBasicShapeCircleType: { const BasicShapeCircle* circle = ToBasicShapeCircle(basic_shape); - CSSBasicShapeCircleValue* circle_value = - CSSBasicShapeCircleValue::Create(); + cssvalue::CSSBasicShapeCircleValue* circle_value = + cssvalue::CSSBasicShapeCircleValue::Create(); circle_value->SetCenterX(ValueForCenterCoordinate( style, circle->CenterX(), EBoxOrient::kHorizontal)); @@ -146,8 +146,8 @@ } case BasicShape::kBasicShapeEllipseType: { const BasicShapeEllipse* ellipse = ToBasicShapeEllipse(basic_shape); - CSSBasicShapeEllipseValue* ellipse_value = - CSSBasicShapeEllipseValue::Create(); + cssvalue::CSSBasicShapeEllipseValue* ellipse_value = + cssvalue::CSSBasicShapeEllipseValue::Create(); ellipse_value->SetCenterX(ValueForCenterCoordinate( style, ellipse->CenterX(), EBoxOrient::kHorizontal)); @@ -161,8 +161,8 @@ } case BasicShape::kBasicShapePolygonType: { const BasicShapePolygon* polygon = ToBasicShapePolygon(basic_shape); - CSSBasicShapePolygonValue* polygon_value = - CSSBasicShapePolygonValue::Create(); + cssvalue::CSSBasicShapePolygonValue* polygon_value = + cssvalue::CSSBasicShapePolygonValue::Create(); polygon_value->SetWindRule(polygon->GetWindRule()); const Vector<Length>& values = polygon->Values(); @@ -175,7 +175,8 @@ } case BasicShape::kBasicShapeInsetType: { const BasicShapeInset* inset = ToBasicShapeInset(basic_shape); - CSSBasicShapeInsetValue* inset_value = CSSBasicShapeInsetValue::Create(); + cssvalue::CSSBasicShapeInsetValue* inset_value = + cssvalue::CSSBasicShapeInsetValue::Create(); inset_value->SetTop( CSSPrimitiveValue::Create(inset->Top(), style.EffectiveZoom())); @@ -287,8 +288,8 @@ scoped_refptr<BasicShape> basic_shape; if (basic_shape_value.IsBasicShapeCircleValue()) { - const CSSBasicShapeCircleValue& circle_value = - ToCSSBasicShapeCircleValue(basic_shape_value); + const cssvalue::CSSBasicShapeCircleValue& circle_value = + cssvalue::ToCSSBasicShapeCircleValue(basic_shape_value); scoped_refptr<BasicShapeCircle> circle = BasicShapeCircle::Create(); circle->SetCenterX( @@ -299,8 +300,8 @@ basic_shape = std::move(circle); } else if (basic_shape_value.IsBasicShapeEllipseValue()) { - const CSSBasicShapeEllipseValue& ellipse_value = - ToCSSBasicShapeEllipseValue(basic_shape_value); + const cssvalue::CSSBasicShapeEllipseValue& ellipse_value = + cssvalue::ToCSSBasicShapeEllipseValue(basic_shape_value); scoped_refptr<BasicShapeEllipse> ellipse = BasicShapeEllipse::Create(); ellipse->SetCenterX( @@ -314,8 +315,8 @@ basic_shape = std::move(ellipse); } else if (basic_shape_value.IsBasicShapePolygonValue()) { - const CSSBasicShapePolygonValue& polygon_value = - ToCSSBasicShapePolygonValue(basic_shape_value); + const cssvalue::CSSBasicShapePolygonValue& polygon_value = + cssvalue::ToCSSBasicShapePolygonValue(basic_shape_value); scoped_refptr<BasicShapePolygon> polygon = BasicShapePolygon::Create(); polygon->SetWindRule(polygon_value.GetWindRule()); @@ -327,8 +328,8 @@ basic_shape = std::move(polygon); } else if (basic_shape_value.IsBasicShapeInsetValue()) { - const CSSBasicShapeInsetValue& rect_value = - ToCSSBasicShapeInsetValue(basic_shape_value); + const cssvalue::CSSBasicShapeInsetValue& rect_value = + cssvalue::ToCSSBasicShapeInsetValue(basic_shape_value); scoped_refptr<BasicShapeInset> rect = BasicShapeInset::Create(); rect->SetTop(ConvertToLength(state, rect_value.Top()));
diff --git a/third_party/WebKit/Source/core/css/CSSBasicShapeValues.cpp b/third_party/WebKit/Source/core/css/CSSBasicShapeValues.cpp index cf7648562..f7122a5 100644 --- a/third_party/WebKit/Source/core/css/CSSBasicShapeValues.cpp +++ b/third_party/WebKit/Source/core/css/CSSBasicShapeValues.cpp
@@ -36,6 +36,7 @@ #include "platform/wtf/text/StringBuilder.h" namespace blink { +namespace cssvalue { static String BuildCircleString(const String& radius, const String& center_x, @@ -436,4 +437,5 @@ CSSValue::TraceAfterDispatch(visitor); } +} // namespace cssvalue } // namespace blink
diff --git a/third_party/WebKit/Source/core/css/CSSBasicShapeValues.h b/third_party/WebKit/Source/core/css/CSSBasicShapeValues.h index 534e43c..a508ec44 100644 --- a/third_party/WebKit/Source/core/css/CSSBasicShapeValues.h +++ b/third_party/WebKit/Source/core/css/CSSBasicShapeValues.h
@@ -39,6 +39,7 @@ #include "platform/wtf/text/WTFString.h" namespace blink { +namespace cssvalue { class CSSBasicShapeCircleValue final : public CSSValue { public: @@ -216,6 +217,7 @@ IsBasicShapePolygonValue()); DEFINE_CSS_VALUE_TYPE_CASTS(CSSBasicShapeInsetValue, IsBasicShapeInsetValue()); +} // namespace cssvalue } // namespace blink #endif // CSSBasicShapeValues_h
diff --git a/third_party/WebKit/Source/core/css/CSSFontFaceSrcValue.h b/third_party/WebKit/Source/core/css/CSSFontFaceSrcValue.h index f74db17..1fb96f16 100644 --- a/third_party/WebKit/Source/core/css/CSSFontFaceSrcValue.h +++ b/third_party/WebKit/Source/core/css/CSSFontFaceSrcValue.h
@@ -106,8 +106,9 @@ USING_GARBAGE_COLLECTED_MIXIN(FontResourceHelper); public: - static FontResourceHelper* Create(FontResource* resource, - WebTaskRunner* task_runner) { + static FontResourceHelper* Create( + FontResource* resource, + base::SingleThreadTaskRunner* task_runner) { return new FontResourceHelper(resource, task_runner); } @@ -116,7 +117,8 @@ } private: - FontResourceHelper(FontResource* resource, WebTaskRunner* task_runner) { + FontResourceHelper(FontResource* resource, + base::SingleThreadTaskRunner* task_runner) { SetResource(resource, task_runner); }
diff --git a/third_party/WebKit/Source/core/css/CSSProperties.json5 b/third_party/WebKit/Source/core/css/CSSProperties.json5 index fa0a1680..f2af8a4c 100644 --- a/third_party/WebKit/Source/core/css/CSSProperties.json5 +++ b/third_party/WebKit/Source/core/css/CSSProperties.json5
@@ -577,7 +577,6 @@ property_methods: ["ParseSingleValue", "CSSValueFromComputedStyleInternal"], interpolable: true, inherited: true, - runtime_flag: "CSSVariableFonts", font: true, name_for_methods: "VariationSettings", converter: "ConvertFontVariationSettings",
diff --git a/third_party/WebKit/Source/core/css/CSSStyleRule.cpp b/third_party/WebKit/Source/core/css/CSSStyleRule.cpp index beea086..1069a118 100644 --- a/third_party/WebKit/Source/core/css/CSSStyleRule.cpp +++ b/third_party/WebKit/Source/core/css/CSSStyleRule.cpp
@@ -44,7 +44,7 @@ CSSStyleRule::CSSStyleRule(StyleRule* style_rule, CSSStyleSheet* parent) : CSSRule(parent), style_rule_(style_rule), - attribute_style_map_(new DeclaredStylePropertyMap(this)) {} + style_map_(new DeclaredStylePropertyMap(this)) {} CSSStyleRule::~CSSStyleRule() = default; @@ -111,7 +111,7 @@ void CSSStyleRule::Trace(blink::Visitor* visitor) { visitor->Trace(style_rule_); visitor->Trace(properties_cssom_wrapper_); - visitor->Trace(attribute_style_map_); + visitor->Trace(style_map_); CSSRule::Trace(visitor); }
diff --git a/third_party/WebKit/Source/core/css/CSSStyleRule.h b/third_party/WebKit/Source/core/css/CSSStyleRule.h index 99cc937..87ab08d 100644 --- a/third_party/WebKit/Source/core/css/CSSStyleRule.h +++ b/third_party/WebKit/Source/core/css/CSSStyleRule.h
@@ -51,9 +51,7 @@ CSSStyleDeclaration* style() const; - StylePropertyMap* attributeStyleMap() const { - return attribute_style_map_.Get(); - } + StylePropertyMap* styleMap() const { return style_map_.Get(); } // FIXME: Not CSSOM. Remove. StyleRule* GetStyleRule() const { return style_rule_.Get(); } @@ -67,7 +65,7 @@ Member<StyleRule> style_rule_; mutable Member<StyleRuleCSSStyleDeclaration> properties_cssom_wrapper_; - Member<StylePropertyMap> attribute_style_map_; + Member<StylePropertyMap> style_map_; }; DEFINE_CSS_RULE_TYPE_CASTS(CSSStyleRule, kStyleRule);
diff --git a/third_party/WebKit/Source/core/css/CSSStyleRule.idl b/third_party/WebKit/Source/core/css/CSSStyleRule.idl index af11906..2bfabec 100644 --- a/third_party/WebKit/Source/core/css/CSSStyleRule.idl +++ b/third_party/WebKit/Source/core/css/CSSStyleRule.idl
@@ -25,5 +25,5 @@ ] interface CSSStyleRule : CSSRule { [SetterCallWith=ExecutionContext] attribute DOMString selectorText; [SameObject, PutForwards=cssText] readonly attribute CSSStyleDeclaration style; - [SameObject, RuntimeEnabled=CSSTypedOM, MeasureAs=CSSTypedOMStylePropertyMap] readonly attribute StylePropertyMap attributeStyleMap; + [SameObject, RuntimeEnabled=CSSTypedOM, MeasureAs=CSSTypedOMStylePropertyMap] readonly attribute StylePropertyMap styleMap; };
diff --git a/third_party/WebKit/Source/core/css/FontFace.cpp b/third_party/WebKit/Source/core/css/FontFace.cpp index e6cbcc4..d6f1a87 100644 --- a/third_party/WebKit/Source/core/css/FontFace.cpp +++ b/third_party/WebKit/Source/core/css/FontFace.cpp
@@ -63,7 +63,6 @@ #include "core/workers/WorkerGlobalScope.h" #include "platform/Histogram.h" #include "platform/SharedBuffer.h" -#include "platform/WebTaskRunner.h" #include "platform/bindings/ScriptState.h" #include "platform/font_family_names.h" #include "platform/runtime_enabled_features.h"
diff --git a/third_party/WebKit/Source/core/css/cssom/CSSStyleVariableReferenceValue.cpp b/third_party/WebKit/Source/core/css/cssom/CSSStyleVariableReferenceValue.cpp new file mode 100644 index 0000000..aed830a --- /dev/null +++ b/third_party/WebKit/Source/core/css/cssom/CSSStyleVariableReferenceValue.cpp
@@ -0,0 +1,46 @@ +// 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 "core/css/cssom/CSSStyleVariableReferenceValue.h" + +namespace blink { + +CSSStyleVariableReferenceValue* CSSStyleVariableReferenceValue::Create( + const String& variable, + ExceptionState& exception_state) { + return Create(variable, nullptr, exception_state); +} + +CSSStyleVariableReferenceValue* CSSStyleVariableReferenceValue::Create( + const String& variable, + CSSUnparsedValue* fallback, + ExceptionState& exception_state) { + CSSStyleVariableReferenceValue* result = Create(variable, fallback); + if (!result) { + exception_state.ThrowTypeError("Invalid custom property name"); + return nullptr; + } + + return result; +} + +CSSStyleVariableReferenceValue* CSSStyleVariableReferenceValue::Create( + const String& variable, + CSSUnparsedValue* fallback) { + if (!variable.StartsWith("--")) + return nullptr; + return new CSSStyleVariableReferenceValue(variable, fallback); +} + +void CSSStyleVariableReferenceValue::setVariable( + const String& value, + ExceptionState& exception_state) { + if (!value.StartsWith("--")) { + exception_state.ThrowTypeError("Invalid custom property name"); + return; + } + variable_ = value; +} + +} // namespace blink
diff --git a/third_party/WebKit/Source/core/css/cssom/CSSStyleVariableReferenceValue.h b/third_party/WebKit/Source/core/css/cssom/CSSStyleVariableReferenceValue.h index 9754408..82decfeb 100644 --- a/third_party/WebKit/Source/core/css/cssom/CSSStyleVariableReferenceValue.h +++ b/third_party/WebKit/Source/core/css/cssom/CSSStyleVariableReferenceValue.h
@@ -12,6 +12,8 @@ namespace blink { +class ExceptionState; + // CSSStyleVariableReferenceValue represents a CSS var() value for CSS Typed OM. // The corresponding idl file is CSSVariableReferenceValue.idl. class CORE_EXPORT CSSStyleVariableReferenceValue final @@ -19,16 +21,19 @@ DEFINE_WRAPPERTYPEINFO(); public: - virtual ~CSSStyleVariableReferenceValue() = default; + static CSSStyleVariableReferenceValue* Create(const String& variable, + ExceptionState&); + + static CSSStyleVariableReferenceValue* Create(const String& variable, + CSSUnparsedValue* fallback, + ExceptionState&); static CSSStyleVariableReferenceValue* Create( const String& variable, - CSSUnparsedValue* fallback = nullptr) { - return new CSSStyleVariableReferenceValue(variable, fallback); - } + CSSUnparsedValue* fallback = nullptr); const String& variable() const { return variable_; } - void setVariable(const String& value) { variable_ = value; } + void setVariable(const String&, ExceptionState&); CSSUnparsedValue* fallback() { return fallback_.Get(); } const CSSUnparsedValue* fallback() const { return fallback_.Get(); }
diff --git a/third_party/WebKit/Source/core/css/cssom/CSSVariableReferenceValue.idl b/third_party/WebKit/Source/core/css/cssom/CSSVariableReferenceValue.idl index c26c3ec1..dbf53a6 100644 --- a/third_party/WebKit/Source/core/css/cssom/CSSVariableReferenceValue.idl +++ b/third_party/WebKit/Source/core/css/cssom/CSSVariableReferenceValue.idl
@@ -8,8 +8,9 @@ Constructor(DOMString variable, optional CSSUnparsedValue fallback), Exposed=(Window,PaintWorklet), RuntimeEnabled=CSSTypedOM, + RaisesException=Constructor, ImplementedAs=CSSStyleVariableReferenceValue ] interface CSSVariableReferenceValue { - attribute DOMString variable; + [RaisesException=Setter] attribute DOMString variable; readonly attribute CSSUnparsedValue? fallback; };
diff --git a/third_party/WebKit/Source/core/css/cssom/CSSVariableReferenceValueTest.cpp b/third_party/WebKit/Source/core/css/cssom/CSSVariableReferenceValueTest.cpp deleted file mode 100644 index 7bc7cb22..0000000 --- a/third_party/WebKit/Source/core/css/cssom/CSSVariableReferenceValueTest.cpp +++ /dev/null
@@ -1,41 +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. - -#include "core/css/cssom/CSSStyleVariableReferenceValue.h" - -#include "core/css/cssom/CSSUnparsedValue.h" -#include "testing/gtest/include/gtest/gtest.h" - -namespace blink { - -TEST(CSSVariableReferenceValueTest, EmptyList) { - HeapVector<StringOrCSSVariableReferenceValue> fragments; - CSSUnparsedValue* unparsed_value = CSSUnparsedValue::Create(fragments); - - CSSStyleVariableReferenceValue* variable_reference_value = - CSSStyleVariableReferenceValue::Create("test", unparsed_value); - - EXPECT_EQ(variable_reference_value->variable(), "test"); - EXPECT_EQ(variable_reference_value->fallback(), unparsed_value); -} - -TEST(CSSVariableReferenceValueTest, MixedList) { - HeapVector<StringOrCSSVariableReferenceValue> fragments; - fragments.push_back(StringOrCSSVariableReferenceValue::FromString("string")); - fragments.push_back( - StringOrCSSVariableReferenceValue::FromCSSVariableReferenceValue( - CSSStyleVariableReferenceValue::Create( - "Variable", CSSUnparsedValue::FromString("Fallback")))); - fragments.push_back(StringOrCSSVariableReferenceValue()); - - CSSUnparsedValue* unparsed_value = CSSUnparsedValue::Create(fragments); - - CSSStyleVariableReferenceValue* variable_reference_value = - CSSStyleVariableReferenceValue::Create("test", unparsed_value); - - EXPECT_EQ(variable_reference_value->variable(), "test"); - EXPECT_EQ(variable_reference_value->fallback(), unparsed_value); -} - -} // namespace blink
diff --git a/third_party/WebKit/Source/core/css/cssom/DeclaredStylePropertyMap.h b/third_party/WebKit/Source/core/css/cssom/DeclaredStylePropertyMap.h index 4e3ddf9..22e120b 100644 --- a/third_party/WebKit/Source/core/css/cssom/DeclaredStylePropertyMap.h +++ b/third_party/WebKit/Source/core/css/cssom/DeclaredStylePropertyMap.h
@@ -19,7 +19,7 @@ // The declared StylePropertyMap retrieves styles specified by a CSS style rule // and returns them as CSSStyleValues. The IDL for this class is in // StylePropertyMap.idl. The declared StylePropertyMap for an element is -// accessed via CSSStyleRule.attributeStyleMap (see CSSStyleRule.idl) +// accessed via CSSStyleRule.styleMap (see CSSStyleRule.idl) class CORE_EXPORT DeclaredStylePropertyMap final : public StylePropertyMap { WTF_MAKE_NONCOPYABLE(DeclaredStylePropertyMap);
diff --git a/third_party/WebKit/Source/core/css/parser/CSSParserTokenStream.h b/third_party/WebKit/Source/core/css/parser/CSSParserTokenStream.h index da0fd24..7e373d0 100644 --- a/third_party/WebKit/Source/core/css/parser/CSSParserTokenStream.h +++ b/third_party/WebKit/Source/core/css/parser/CSSParserTokenStream.h
@@ -65,7 +65,9 @@ static constexpr size_t InitialBufferSize() { return 128; } explicit CSSParserTokenStream(CSSTokenizer& tokenizer) - : buffer_(InitialBufferSize()), tokenizer_(tokenizer), next_(kEOFToken) {} + : tokenizer_(tokenizer), next_(kEOFToken) { + buffer_.ReserveInitialCapacity(InitialBufferSize()); + } CSSParserTokenStream(CSSParserTokenStream&&) = default; @@ -141,7 +143,7 @@ CSSParserTokenRange ConsumeUntilPeekedTypeIs() { EnsureLookAhead(); - buffer_.clear(); + buffer_.Shrink(0); while (!UncheckedAtEnd() && !detail::IsTokenTypeOneOf<Types...>(UncheckedPeek().GetType())) { // Have to use internal consume/peek in here because they can read past @@ -158,35 +160,10 @@ } while (!PeekInternal().IsEOF() && nesting_level); } - return buffer_.Range(); + return CSSParserTokenRange(buffer_); } private: - // Used to store tokens for CSSParserTokenRanges. - // FIXME: Determine if this improves speed at all compared to allocating a - // fresh vector each time. - class TokenBuffer { - public: - TokenBuffer(size_t capacity) { tokens_.ReserveInitialCapacity(capacity); } - - void clear() { size_ = 0; } - void push_back(const CSSParserToken& token) { - if (size_ < tokens_.size()) - tokens_[size_] = token; - else - tokens_.push_back(token); - ++size_; - } - CSSParserTokenRange Range() const { - return CSSParserTokenRange(tokens_).MakeSubRange(tokens_.begin(), - tokens_.begin() + size_); - } - - private: - Vector<CSSParserToken, 32> tokens_; - size_t size_ = 0; - }; - const CSSParserToken& PeekInternal() { EnsureLookAhead(); return UncheckedPeekInternal(); @@ -211,7 +188,7 @@ void UncheckedSkipToEndOfBlock(); - TokenBuffer buffer_; + Vector<CSSParserToken, 32> buffer_; CSSTokenizer& tokenizer_; CSSParserToken next_; size_t offset_ = 0;
diff --git a/third_party/WebKit/Source/core/css/parser/CSSPropertyParserHelpers.cpp b/third_party/WebKit/Source/core/css/parser/CSSPropertyParserHelpers.cpp index 87470ab..f0c89ec 100644 --- a/third_party/WebKit/Source/core/css/parser/CSSPropertyParserHelpers.cpp +++ b/third_party/WebKit/Source/core/css/parser/CSSPropertyParserHelpers.cpp
@@ -900,7 +900,10 @@ PositionFromTwoValues(value1, value2, result_x, result_y); return true; } - context.Count(*threeValuePosition); + if (*threeValuePosition == WebFeature::kThreeValuedPositionBackground) + context.Count(*threeValuePosition); + else + context.CountDeprecation(*threeValuePosition); } CSSValue* values[5]; @@ -1479,6 +1482,16 @@ } if (!result || !args.AtEnd()) return nullptr; + + WebFeature feature; + if (id == CSSValueWebkitCrossFade) + feature = WebFeature::kWebkitCrossFade; + else if (id == CSSValuePaint) + feature = WebFeature::kCSSPaintFunction; + else + feature = WebFeature::kCSSGradient; + context->Count(feature); + range = range_copy; return result; }
diff --git a/third_party/WebKit/Source/core/css/parser/CSSPropertyParserTest.cpp b/third_party/WebKit/Source/core/css/parser/CSSPropertyParserTest.cpp index 05df892..bd2f28b 100644 --- a/third_party/WebKit/Source/core/css/parser/CSSPropertyParserTest.cpp +++ b/third_party/WebKit/Source/core/css/parser/CSSPropertyParserTest.cpp
@@ -9,6 +9,7 @@ #include "core/css/CSSValueList.h" #include "core/css/StyleSheetContents.h" #include "core/css/parser/CSSParser.h" +#include "core/html/HTMLHtmlElement.h" #include "core/testing/DummyPageHolder.h" #include "platform/testing/RuntimeEnabledFeaturesTestHelpers.h" #include "testing/gtest/include/gtest/gtest.h" @@ -388,4 +389,39 @@ EXPECT_FALSE(value); } +TEST(CSSPropertyParserTest, GradientUseCount) { + std::unique_ptr<DummyPageHolder> dummy_page_holder = + DummyPageHolder::Create(IntSize(800, 600)); + Document& document = dummy_page_holder->GetDocument(); + WebFeature feature = WebFeature::kCSSGradient; + EXPECT_FALSE(UseCounter::IsCounted(document, feature)); + document.documentElement()->SetInnerHTMLFromString( + "<style>* { background-image: linear-gradient(red, blue); }</style>"); + EXPECT_TRUE(UseCounter::IsCounted(document, feature)); +} + +TEST(CSSPropertyParserTest, PaintUseCount) { + std::unique_ptr<DummyPageHolder> dummy_page_holder = + DummyPageHolder::Create(IntSize(800, 600)); + Document& document = dummy_page_holder->GetDocument(); + document.SetSecureContextStateForTesting(SecureContextState::kSecure); + WebFeature feature = WebFeature::kCSSPaintFunction; + EXPECT_FALSE(UseCounter::IsCounted(document, feature)); + document.documentElement()->SetInnerHTMLFromString( + "<style>span { background-image: paint(geometry); }</style>"); + EXPECT_TRUE(UseCounter::IsCounted(document, feature)); +} + +TEST(CSSPropertyParserTest, CrossFadeUseCount) { + std::unique_ptr<DummyPageHolder> dummy_page_holder = + DummyPageHolder::Create(IntSize(800, 600)); + Document& document = dummy_page_holder->GetDocument(); + WebFeature feature = WebFeature::kWebkitCrossFade; + EXPECT_FALSE(UseCounter::IsCounted(document, feature)); + document.documentElement()->SetInnerHTMLFromString( + "<style>div { background-image: -webkit-cross-fade(url('from.png'), " + "url('to.png'), 0.2); }</style>"); + EXPECT_TRUE(UseCounter::IsCounted(document, feature)); +} + } // namespace blink
diff --git a/third_party/WebKit/Source/core/css/properties/CSSParsingUtils.cpp b/third_party/WebKit/Source/core/css/properties/CSSParsingUtils.cpp index ea99b07f2..84f84e6 100644 --- a/third_party/WebKit/Source/core/css/properties/CSSParsingUtils.cpp +++ b/third_party/WebKit/Source/core/css/properties/CSSParsingUtils.cpp
@@ -46,6 +46,9 @@ #include "platform/wtf/text/StringBuilder.h" namespace blink { + +using namespace cssvalue; + namespace CSSParsingUtils { namespace { @@ -144,8 +147,7 @@ return nullptr; range = range_copy; - return cssvalue::CSSStepsTimingFunctionValue::Create(steps->GetIntValue(), - position); + return CSSStepsTimingFunctionValue::Create(steps->GetIntValue(), position); } CSSValue* ConsumeFrames(CSSParserTokenRange& range) { @@ -167,7 +169,7 @@ return nullptr; range = range_copy; - return cssvalue::CSSFramesTimingFunctionValue::Create(frames_int); + return CSSFramesTimingFunctionValue::Create(frames_int); } CSSValue* ConsumeCubicBezier(CSSParserTokenRange& range) { @@ -187,7 +189,7 @@ CSSPropertyParserHelpers::ConsumeCommaIncludingWhitespace(args) && CSSPropertyParserHelpers::ConsumeNumberRaw(args, y2) && args.AtEnd()) { range = range_copy; - return cssvalue::CSSCubicBezierTimingFunctionValue::Create(x1, y1, x2, y2); + return CSSCubicBezierTimingFunctionValue::Create(x1, y1, x2, y2); } return nullptr; @@ -1168,7 +1170,7 @@ CSSPropertyParserHelpers::Complete4Sides(slices); if (default_fill == DefaultFill::kFill) fill = true; - return cssvalue::CSSBorderImageSliceValue::Create( + return CSSBorderImageSliceValue::Create( CSSQuadValue::Create(slices[0], slices[1], slices[2], slices[3], CSSQuadValue::kSerializeAsQuad), fill); @@ -1573,8 +1575,7 @@ return CSSPropertyParserHelpers::ConsumeIdent(range); CSSValueList* settings = CSSValueList::CreateCommaSeparated(); do { - cssvalue::CSSFontFeatureValue* font_feature_value = - ConsumeFontFeatureTag(range); + CSSFontFeatureValue* font_feature_value = ConsumeFontFeatureTag(range); if (!font_feature_value) return nullptr; settings->Append(*font_feature_value); @@ -1582,8 +1583,7 @@ return settings; } -cssvalue::CSSFontFeatureValue* ConsumeFontFeatureTag( - CSSParserTokenRange& range) { +CSSFontFeatureValue* ConsumeFontFeatureTag(CSSParserTokenRange& range) { // Feature tag name consists of 4-letter characters. const unsigned kTagNameLength = 4; @@ -1611,7 +1611,7 @@ range.Peek().Id() == CSSValueOff) { tag_value = range.ConsumeIncludingWhitespace().Id() == CSSValueOn; } - return cssvalue::CSSFontFeatureValue::Create(tag, tag_value); + return CSSFontFeatureValue::Create(tag, tag_value); } CSSIdentifierValue* ConsumeFontVariantCSS21(CSSParserTokenRange& range) { @@ -2249,7 +2249,7 @@ range = function_range; if (byte_stream->IsEmpty()) return CSSIdentifierValue::Create(CSSValueNone); - return cssvalue::CSSPathValue::Create(std::move(byte_stream)); + return CSSPathValue::Create(std::move(byte_stream)); } CSSValue* ConsumeRay(CSSParserTokenRange& range, @@ -2460,6 +2460,8 @@ shape = ConsumeBasicShapeInset(args, context); if (!shape || !args.AtEnd()) return nullptr; + + context.Count(WebFeature::kCSSBasicShape); range = range_copy; return shape; }
diff --git a/third_party/WebKit/Source/core/css/properties/CSSParsingUtilsTest.cpp b/third_party/WebKit/Source/core/css/properties/CSSParsingUtilsTest.cpp new file mode 100644 index 0000000..8f1d074 --- /dev/null +++ b/third_party/WebKit/Source/core/css/properties/CSSParsingUtilsTest.cpp
@@ -0,0 +1,24 @@ +// 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 "core/css/properties/CSSParsingUtils.h" +#include "core/frame/UseCounter.h" +#include "core/html/HTMLHtmlElement.h" +#include "core/testing/DummyPageHolder.h" +#include "testing/gtest/include/gtest/gtest.h" + +namespace blink { + +TEST(CSSParsingUtilsTest, BasicShapeUseCount) { + std::unique_ptr<DummyPageHolder> dummy_page_holder = + DummyPageHolder::Create(IntSize(800, 600)); + Document& document = dummy_page_holder->GetDocument(); + WebFeature feature = WebFeature::kCSSBasicShape; + EXPECT_FALSE(UseCounter::IsCounted(document, feature)); + document.documentElement()->SetInnerHTMLFromString( + "<style>span { shape-outside: circle(); }</style>"); + EXPECT_TRUE(UseCounter::IsCounted(document, feature)); +} + +} // namespace blink
diff --git a/third_party/WebKit/Source/core/css/properties/longhands/FontVariationSettingsCustom.cpp b/third_party/WebKit/Source/core/css/properties/longhands/FontVariationSettingsCustom.cpp index cb074de..e34a77d5 100644 --- a/third_party/WebKit/Source/core/css/properties/longhands/FontVariationSettingsCustom.cpp +++ b/third_party/WebKit/Source/core/css/properties/longhands/FontVariationSettingsCustom.cpp
@@ -46,7 +46,6 @@ CSSParserTokenRange& range, const CSSParserContext& context, const CSSParserLocalContext&) const { - DCHECK(RuntimeEnabledFeatures::CSSVariableFontsEnabled()); if (range.Peek().Id() == CSSValueNormal) return CSSPropertyParserHelpers::ConsumeIdent(range); CSSValueList* variation_settings = CSSValueList::CreateCommaSeparated(); @@ -66,7 +65,6 @@ const LayoutObject*, Node* styled_node, bool allow_visited_style) const { - DCHECK(RuntimeEnabledFeatures::CSSVariableFontsEnabled()); const blink::FontVariationSettings* variation_settings = style.GetFontDescription().VariationSettings(); if (!variation_settings || !variation_settings->size())
diff --git a/third_party/WebKit/Source/core/css/resolver/StyleResolver.cpp b/third_party/WebKit/Source/core/css/resolver/StyleResolver.cpp index c3d3f308..14cfbd1 100644 --- a/third_party/WebKit/Source/core/css/resolver/StyleResolver.cpp +++ b/third_party/WebKit/Source/core/css/resolver/StyleResolver.cpp
@@ -1294,7 +1294,6 @@ case CSSPropertyTextDecorationSkipInk: return true; case CSSPropertyFontVariationSettings: - DCHECK(RuntimeEnabledFeatures::CSSVariableFontsEnabled()); return true; default: break; @@ -1398,7 +1397,6 @@ case CSSPropertyWordSpacing: return true; case CSSPropertyFontVariationSettings: - DCHECK(RuntimeEnabledFeatures::CSSVariableFontsEnabled()); return true; case CSSPropertyTextDecorationColor: case CSSPropertyTextDecorationLine:
diff --git a/third_party/WebKit/Source/core/css/threaded/MultiThreadedTestUtil.h b/third_party/WebKit/Source/core/css/threaded/MultiThreadedTestUtil.h index 78c9657..c116711a 100644 --- a/third_party/WebKit/Source/core/css/threaded/MultiThreadedTestUtil.h +++ b/third_party/WebKit/Source/core/css/threaded/MultiThreadedTestUtil.h
@@ -9,6 +9,7 @@ #include <memory> +#include "base/single_thread_task_runner.h" #include "platform/CrossThreadFunctional.h" #include "platform/WaitableEvent.h" #include "platform/WebTaskRunner.h" @@ -57,13 +58,13 @@ Vector<std::unique_ptr<WaitableEvent>> waits; for (int i = 0; i < num_threads_; ++i) { - threads.push_back( - WebThreadSupportingGC::Create(WebThreadCreationParams(""))); + threads.push_back(WebThreadSupportingGC::Create( + WebThreadCreationParams(WebThreadType::kTestThread))); waits.push_back(std::make_unique<WaitableEvent>()); } for (int i = 0; i < num_threads_; ++i) { - WebTaskRunner* task_runner = + base::SingleThreadTaskRunner* task_runner = threads[i]->PlatformThread().GetWebTaskRunner(); PostCrossThreadTask(*task_runner, FROM_HERE,
diff --git a/third_party/WebKit/Source/core/dom/Document.cpp b/third_party/WebKit/Source/core/dom/Document.cpp index 7f15a508..c274aac 100644 --- a/third_party/WebKit/Source/core/dom/Document.cpp +++ b/third_party/WebKit/Source/core/dom/Document.cpp
@@ -953,7 +953,13 @@ // 2. localName converted to ASCII lowercase const AtomicString& converted_local_name = ConvertLocalName(local_name); + QualifiedName q_name(g_null_atom, converted_local_name, + IsXHTMLDocument() || IsHTMLDocument() + ? HTMLNames::xhtmlNamespaceURI + : g_null_atom); + // TODO(tkent): Share the code with createElementNS(namespace_uri, + // qualified_name, string_or_options, exception_state). bool is_v1 = string_or_options.IsDictionary() || !RegistrationContext(); bool create_v1_builtin = string_or_options.IsDictionary() && @@ -968,7 +974,7 @@ // 4. Let definition be result of lookup up custom element definition CustomElementDefinition* definition = nullptr; - if (is_v1) { + if (is_v1 && q_name.NamespaceURI() == HTMLNames::xhtmlNamespaceURI) { // Is the runtime flag enabled for customized builtin elements? const CustomElementDescriptor desc = RuntimeEnabledFeatures::CustomElementsBuiltinEnabled() @@ -992,20 +998,12 @@ Element* element; if (definition) { - element = CustomElement::CreateCustomElementSync( - *this, converted_local_name, definition); + element = CustomElement::CreateCustomElementSync(*this, q_name, definition); } else if (V0CustomElement::IsValidName(local_name) && RegistrationContext()) { - element = RegistrationContext()->CreateCustomTagElement( - *this, - QualifiedName(g_null_atom, converted_local_name, xhtmlNamespaceURI)); + element = RegistrationContext()->CreateCustomTagElement(*this, q_name); } else { - element = - CreateRawElement(QualifiedName(g_null_atom, converted_local_name, - IsXHTMLDocument() || IsHTMLDocument() - ? HTMLNames::xhtmlNamespaceURI - : g_null_atom), - kCreatedByCreateElement); + element = CreateRawElement(q_name, kCreatedByCreateElement); } // 8. If 'is' is non-null, set 'is' attribute @@ -7259,7 +7257,8 @@ return &GetFrame()->GetInterfaceProvider(); } -scoped_refptr<WebTaskRunner> Document::GetTaskRunner(TaskType type) { +scoped_refptr<base::SingleThreadTaskRunner> Document::GetTaskRunner( + TaskType type) { DCHECK(IsMainThread()); if (ContextDocument() && ContextDocument()->GetFrame())
diff --git a/third_party/WebKit/Source/core/dom/Document.h b/third_party/WebKit/Source/core/dom/Document.h index ac79dbb..2c878c7 100644 --- a/third_party/WebKit/Source/core/dom/Document.h +++ b/third_party/WebKit/Source/core/dom/Document.h
@@ -34,6 +34,7 @@ #include <utility> #include "base/memory/scoped_refptr.h" +#include "base/single_thread_task_runner.h" #include "bindings/core/v8/ExceptionState.h" #include "bindings/core/v8/ScriptValue.h" #include "core/CoreExport.h" @@ -66,7 +67,6 @@ #include "core/page/PageVisibilityState.h" #include "platform/Length.h" #include "platform/Timer.h" -#include "platform/WebTaskRunner.h" #include "platform/bindings/TraceWrapperMember.h" #include "platform/loader/fetch/ClientHintsPreferences.h" #include "platform/scroll/ScrollTypes.h" @@ -1408,7 +1408,7 @@ ukm::UkmRecorder* UkmRecorder(); int64_t UkmSourceID() const; - scoped_refptr<WebTaskRunner> GetTaskRunner(TaskType) override; + scoped_refptr<base::SingleThreadTaskRunner> GetTaskRunner(TaskType) override; void RecordUkmOutliveTimeAfterShutdown(int outlive_time_count);
diff --git a/third_party/WebKit/Source/core/dom/ExecutionContext.h b/third_party/WebKit/Source/core/dom/ExecutionContext.h index bac31c8..236d525d 100644 --- a/third_party/WebKit/Source/core/dom/ExecutionContext.h +++ b/third_party/WebKit/Source/core/dom/ExecutionContext.h
@@ -32,12 +32,12 @@ #include "base/location.h" #include "base/macros.h" +#include "base/single_thread_task_runner.h" #include "core/CoreExport.h" #include "core/dom/ContextLifecycleNotifier.h" #include "core/dom/ContextLifecycleObserver.h" #include "core/dom/SecurityContext.h" #include "platform/Supplementable.h" -#include "platform/WebTaskRunner.h" #include "platform/heap/Handle.h" #include "platform/loader/fetch/AccessControlStatus.h" #include "platform/weborigin/KURL.h" @@ -205,7 +205,8 @@ return nullptr; } - virtual scoped_refptr<WebTaskRunner> GetTaskRunner(TaskType) = 0; + virtual scoped_refptr<base::SingleThreadTaskRunner> GetTaskRunner( + TaskType) = 0; InterfaceInvalidator* GetInterfaceInvalidator() { return invalidator_.get(); }
diff --git a/third_party/WebKit/Source/core/dom/IdleDeadlineTest.cpp b/third_party/WebKit/Source/core/dom/IdleDeadlineTest.cpp index 2c27aef..2f22ee2 100644 --- a/third_party/WebKit/Source/core/dom/IdleDeadlineTest.cpp +++ b/third_party/WebKit/Source/core/dom/IdleDeadlineTest.cpp
@@ -4,7 +4,7 @@ #include "core/dom/IdleDeadline.h" -#include "platform/WebTaskRunner.h" +#include "base/single_thread_task_runner.h" #include "platform/scheduler/child/web_scheduler.h" #include "platform/testing/TestingPlatformSupportWithMockScheduler.h" #include "platform/wtf/Time.h" @@ -20,8 +20,8 @@ ~MockIdleDeadlineScheduler() override = default; // WebScheduler implementation: - WebTaskRunner* TimerTaskRunner() override { return nullptr; } - WebTaskRunner* V8TaskRunner() override { return nullptr; } + base::SingleThreadTaskRunner* TimerTaskRunner() override { return nullptr; } + base::SingleThreadTaskRunner* V8TaskRunner() override { return nullptr; } void Shutdown() override {} bool ShouldYieldForHighPriorityWork() override { return true; } bool CanExceedIdleDeadlineIfRequired() override { return false; } @@ -33,7 +33,9 @@ WebViewScheduler::WebViewSchedulerDelegate*) override { return nullptr; } - WebTaskRunner* CompositorTaskRunner() override { return nullptr; } + base::SingleThreadTaskRunner* CompositorTaskRunner() override { + return nullptr; + } std::unique_ptr<RendererPauseHandle> PauseScheduler() override { return nullptr; }
diff --git a/third_party/WebKit/Source/core/dom/ScriptedIdleTaskControllerTest.cpp b/third_party/WebKit/Source/core/dom/ScriptedIdleTaskControllerTest.cpp index 016122b..05fe341 100644 --- a/third_party/WebKit/Source/core/dom/ScriptedIdleTaskControllerTest.cpp +++ b/third_party/WebKit/Source/core/dom/ScriptedIdleTaskControllerTest.cpp
@@ -24,9 +24,11 @@ ~MockScriptedIdleTaskControllerScheduler() override = default; // WebScheduler implementation: - WebTaskRunner* TimerTaskRunner() override { return nullptr; } - WebTaskRunner* CompositorTaskRunner() override { return nullptr; } - WebTaskRunner* V8TaskRunner() override { return nullptr; } + base::SingleThreadTaskRunner* TimerTaskRunner() override { return nullptr; } + base::SingleThreadTaskRunner* CompositorTaskRunner() override { + return nullptr; + } + base::SingleThreadTaskRunner* V8TaskRunner() override { return nullptr; } void Shutdown() override {} bool ShouldYieldForHighPriorityWork() override { return should_yield_; } bool CanExceedIdleDeadlineIfRequired() override { return false; }
diff --git a/third_party/WebKit/Source/core/editing/Editor.cpp b/third_party/WebKit/Source/core/editing/Editor.cpp index d072311..875d932 100644 --- a/third_party/WebKit/Source/core/editing/Editor.cpp +++ b/third_party/WebKit/Source/core/editing/Editor.cpp
@@ -45,7 +45,6 @@ #include "core/editing/EditingUtilities.h" #include "core/editing/EphemeralRange.h" #include "core/editing/FrameSelection.h" -#include "core/editing/RenderedPosition.h" #include "core/editing/SelectionTemplate.h" #include "core/editing/SetSelectionOptions.h" #include "core/editing/VisiblePosition.h" @@ -1476,15 +1475,15 @@ const PositionWithAffinity start_position( CreateVisiblePosition(range.StartPosition()).DeepEquivalent(), TextAffinity::kDownstream); - const IntRect start_caret_rect = RenderedPosition::AbsoluteRect( - start_position, &extra_width_to_end_of_line); + const IntRect start_caret_rect = + AbsoluteCaretRectOfPosition(start_position, &extra_width_to_end_of_line); if (start_caret_rect.IsEmpty()) return IntRect(); const PositionWithAffinity end_position( CreateVisiblePosition(range.EndPosition()).DeepEquivalent(), TextAffinity::kUpstream); - const IntRect end_caret_rect = RenderedPosition::AbsoluteRect(end_position); + const IntRect end_caret_rect = AbsoluteCaretRectOfPosition(end_position); if (end_caret_rect.IsEmpty()) return IntRect();
diff --git a/third_party/WebKit/Source/core/editing/FrameCaret.cpp b/third_party/WebKit/Source/core/editing/FrameCaret.cpp index cc37b76..c5067f7e 100644 --- a/third_party/WebKit/Source/core/editing/FrameCaret.cpp +++ b/third_party/WebKit/Source/core/editing/FrameCaret.cpp
@@ -238,7 +238,7 @@ } void FrameCaret::RecreateCaretBlinkTimerForTesting( - scoped_refptr<WebTaskRunner> task_runner) { + scoped_refptr<base::SingleThreadTaskRunner> task_runner) { caret_blink_timer_.reset(new TaskRunnerTimer<FrameCaret>( std::move(task_runner), this, &FrameCaret::CaretBlinkTimerFired)); }
diff --git a/third_party/WebKit/Source/core/editing/FrameCaret.h b/third_party/WebKit/Source/core/editing/FrameCaret.h index 9bd15ba..fcc98f8 100644 --- a/third_party/WebKit/Source/core/editing/FrameCaret.h +++ b/third_party/WebKit/Source/core/editing/FrameCaret.h
@@ -86,7 +86,8 @@ const DisplayItemClient& CaretDisplayItemClientForTesting() const; const LayoutBlock* CaretLayoutBlockForTesting() const; bool ShouldPaintCaretForTesting() const { return should_paint_caret_; } - void RecreateCaretBlinkTimerForTesting(scoped_refptr<WebTaskRunner>); + void RecreateCaretBlinkTimerForTesting( + scoped_refptr<base::SingleThreadTaskRunner>); void Trace(blink::Visitor*);
diff --git a/third_party/WebKit/Source/core/editing/FrameSelection.cpp b/third_party/WebKit/Source/core/editing/FrameSelection.cpp index 5b0db3b..0cdbe90 100644 --- a/third_party/WebKit/Source/core/editing/FrameSelection.cpp +++ b/third_party/WebKit/Source/core/editing/FrameSelection.cpp
@@ -1255,7 +1255,7 @@ } std::pair<unsigned, unsigned> FrameSelection::LayoutSelectionStartEndForNG( - const NGPhysicalTextFragment& text_fragment) { + const NGPhysicalTextFragment& text_fragment) const { return layout_selection_->SelectionStartEndForNG(text_fragment); }
diff --git a/third_party/WebKit/Source/core/editing/FrameSelection.h b/third_party/WebKit/Source/core/editing/FrameSelection.h index 0e6d421..a8e0aa3 100644 --- a/third_party/WebKit/Source/core/editing/FrameSelection.h +++ b/third_party/WebKit/Source/core/editing/FrameSelection.h
@@ -225,7 +225,7 @@ WTF::Optional<unsigned> LayoutSelectionEnd() const; void ClearLayoutSelection(); std::pair<unsigned, unsigned> LayoutSelectionStartEndForNG( - const NGPhysicalTextFragment&); + const NGPhysicalTextFragment&) const; void Trace(blink::Visitor*);
diff --git a/third_party/WebKit/Source/core/editing/LayoutSelection.cpp b/third_party/WebKit/Source/core/editing/LayoutSelection.cpp index 3bd23002..63d564d 100644 --- a/third_party/WebKit/Source/core/editing/LayoutSelection.cpp +++ b/third_party/WebKit/Source/core/editing/LayoutSelection.cpp
@@ -662,7 +662,7 @@ } std::pair<unsigned, unsigned> LayoutSelection::SelectionStartEndForNG( - const NGPhysicalTextFragment& text_fragment) { + const NGPhysicalTextFragment& text_fragment) const { // FrameSelection holds selection offsets in layout block flow at // LayoutSelection::Commit() if selection starts/ends within Text that // each LayoutObject::SelectionState indicates.
diff --git a/third_party/WebKit/Source/core/editing/LayoutSelection.h b/third_party/WebKit/Source/core/editing/LayoutSelection.h index 94a3bf98..dafc9c6 100644 --- a/third_party/WebKit/Source/core/editing/LayoutSelection.h +++ b/third_party/WebKit/Source/core/editing/LayoutSelection.h
@@ -110,7 +110,7 @@ // (text_fragment.StartOffset(), text_fragment.EndOffset()). // If first equals second, it indicates "no selection in fragment". std::pair<unsigned, unsigned> SelectionStartEndForNG( - const NGPhysicalTextFragment&); + const NGPhysicalTextFragment&) const; void OnDocumentShutdown();
diff --git a/third_party/WebKit/Source/core/editing/RenderedPosition.cpp b/third_party/WebKit/Source/core/editing/RenderedPosition.cpp index 27cb4a9d..68805074 100644 --- a/third_party/WebKit/Source/core/editing/RenderedPosition.cpp +++ b/third_party/WebKit/Source/core/editing/RenderedPosition.cpp
@@ -248,22 +248,6 @@ PrevLeafChild()->CaretRightmostOffset()); } -// static -IntRect RenderedPosition::AbsoluteRect(const PositionWithAffinity& position, - LayoutUnit* extra_width_to_end_of_line) { - const LocalCaretRect local_caret_rect = - LocalCaretRectOfPosition(position, extra_width_to_end_of_line); - if (!local_caret_rect.layout_object) - return IntRect(); - - IntRect local_rect = PixelSnappedIntRect(local_caret_rect.rect); - return local_rect == IntRect() - ? IntRect() - : local_caret_rect.layout_object - ->LocalToAbsoluteQuad(FloatRect(local_rect)) - .EnclosingBoundingBox(); -} - // Convert a local point into the coordinate system of backing coordinates. // Also returns the backing layer if needed. static FloatPoint LocalToInvalidationBackingPoint(
diff --git a/third_party/WebKit/Source/core/editing/RenderedPosition.h b/third_party/WebKit/Source/core/editing/RenderedPosition.h index e14a1041..0a71406d 100644 --- a/third_party/WebKit/Source/core/editing/RenderedPosition.h +++ b/third_party/WebKit/Source/core/editing/RenderedPosition.h
@@ -40,7 +40,6 @@ namespace blink { class FrameSelection; -class LayoutUnit; class LayoutObject; struct CompositedSelection; @@ -86,11 +85,6 @@ // TODO(editing-dev): This function doesn't use RenderedPosition // instance anymore. Consider moving. - static IntRect AbsoluteRect(const PositionWithAffinity&, - LayoutUnit* extra_width_to_end_of_line = nullptr); - - // TODO(editing-dev): This function doesn't use RenderedPosition - // instance anymore. Consider moving. static CompositedSelection ComputeCompositedSelection(const FrameSelection&); private:
diff --git a/third_party/WebKit/Source/core/editing/VisibleSelectionTest.cpp b/third_party/WebKit/Source/core/editing/VisibleSelectionTest.cpp index 121ea99..04d27a0a0 100644 --- a/third_party/WebKit/Source/core/editing/VisibleSelectionTest.cpp +++ b/third_party/WebKit/Source/core/editing/VisibleSelectionTest.cpp
@@ -213,20 +213,21 @@ // For http://wkb.ug/32622 TEST_F(VisibleSelectionTest, ExpandUsingGranularityWithEmptyCell) { - SetBodyContent( + const SelectionInDOMTree& selection_in_dom_tree = SetSelectionTextToBody( "<div contentEditable><table cellspacing=0><tr>" - "<td id='first' width='50' height='25pt'></td>" + "<td id='first' width='50' height='25pt'>|</td>" "<td id='second' width='50' height='25pt'></td>" "</tr></table></div>"); - Element* const first = GetDocument().getElementById("first"); const VisibleSelectionInFlatTree& selection = CreateVisibleSelectionWithGranularity( - SelectionInFlatTree::Builder() - .Collapse(PositionInFlatTree(first, 0)) - .Build(), + ConvertToSelectionInFlatTree(selection_in_dom_tree), TextGranularity::kWord); - EXPECT_EQ(PositionInFlatTree(first, 0), selection.Start()); - EXPECT_EQ(PositionInFlatTree(first, 0), selection.End()); + EXPECT_EQ( + "<div contenteditable><table cellspacing=\"0\"><tbody><tr>" + "<td height=\"25pt\" id=\"first\" width=\"50\">|</td>" + "<td height=\"25pt\" id=\"second\" width=\"50\"></td>" + "</tr></tbody></table></div>", + GetSelectionTextInFlatTreeFromBody(selection.AsSelection())); } TEST_F(VisibleSelectionTest, Initialisation) {
diff --git a/third_party/WebKit/Source/core/editing/VisibleUnits.cpp b/third_party/WebKit/Source/core/editing/VisibleUnits.cpp index 2e4c695b..a51aa9a 100644 --- a/third_party/WebKit/Source/core/editing/VisibleUnits.cpp +++ b/third_party/WebKit/Source/core/editing/VisibleUnits.cpp
@@ -1183,6 +1183,23 @@ return AbsoluteCaretBoundsOfAlgorithm<EditingStrategy>(visible_position); } +// TODO(editing-dev): This function does pretty much the same thing as +// |AbsoluteCaretBoundsOf()|. Consider merging them. +IntRect AbsoluteCaretRectOfPosition(const PositionWithAffinity& position, + LayoutUnit* extra_width_to_end_of_line) { + const LocalCaretRect local_caret_rect = + LocalCaretRectOfPosition(position, extra_width_to_end_of_line); + if (!local_caret_rect.layout_object) + return IntRect(); + + const IntRect local_rect = PixelSnappedIntRect(local_caret_rect.rect); + return local_rect == IntRect() + ? IntRect() + : local_caret_rect.layout_object + ->LocalToAbsoluteQuad(FloatRect(local_rect)) + .EnclosingBoundingBox(); +} + template <typename Strategy> static IntRect AbsoluteSelectionBoundsOfAlgorithm( const VisiblePositionTemplate<Strategy>& visible_position) {
diff --git a/third_party/WebKit/Source/core/editing/VisibleUnits.h b/third_party/WebKit/Source/core/editing/VisibleUnits.h index 9ccd44e5..c1eb1c6 100644 --- a/third_party/WebKit/Source/core/editing/VisibleUnits.h +++ b/third_party/WebKit/Source/core/editing/VisibleUnits.h
@@ -98,6 +98,10 @@ CORE_EXPORT IntRect AbsoluteCaretBoundsOf(const VisiblePosition&); CORE_EXPORT IntRect AbsoluteCaretBoundsOf(const VisiblePositionInFlatTree&); +IntRect AbsoluteCaretRectOfPosition( + const PositionWithAffinity&, + LayoutUnit* extra_width_to_end_of_line = nullptr); + CORE_EXPORT IntRect AbsoluteSelectionBoundsOf(const VisiblePosition&); CORE_EXPORT IntRect AbsoluteSelectionBoundsOf(const VisiblePositionInFlatTree&);
diff --git a/third_party/WebKit/Source/core/editing/VisibleUnitsWordTest.cpp b/third_party/WebKit/Source/core/editing/VisibleUnitsWordTest.cpp index c7d56bb..9144f5f9 100644 --- a/third_party/WebKit/Source/core/editing/VisibleUnitsWordTest.cpp +++ b/third_party/WebKit/Source/core/editing/VisibleUnitsWordTest.cpp
@@ -86,6 +86,23 @@ EXPECT_EQ("|abc<s>foo bar</s>baz", DoStartOfWord("abc<s>foo bar</s>b|az")); } +TEST_F(VisibleUnitsWordTest, EndOfWordBasic) { + EXPECT_EQ("<p> (|1) abc def</p>", DoEndOfWord("<p>| (1) abc def</p>")); + EXPECT_EQ("<p> (|1) abc def</p>", DoEndOfWord("<p> |(1) abc def</p>")); + EXPECT_EQ("<p> (1|) abc def</p>", DoEndOfWord("<p> (|1) abc def</p>")); + EXPECT_EQ("<p> (1)| abc def</p>", DoEndOfWord("<p> (1|) abc def</p>")); + EXPECT_EQ("<p> (1) |abc def</p>", DoEndOfWord("<p> (1)| abc def</p>")); + EXPECT_EQ("<p> (1) abc| def</p>", DoEndOfWord("<p> (1) |abc def</p>")); + EXPECT_EQ("<p> (1) abc| def</p>", DoEndOfWord("<p> (1) a|bc def</p>")); + EXPECT_EQ("<p> (1) abc| def</p>", DoEndOfWord("<p> (1) ab|c def</p>")); + EXPECT_EQ("<p> (1) abc |def</p>", DoEndOfWord("<p> (1) abc| def</p>")); + EXPECT_EQ("<p> (1) abc def|</p>", DoEndOfWord("<p> (1) abc |def</p>")); + EXPECT_EQ("<p> (1) abc def|</p>", DoEndOfWord("<p> (1) abc d|ef</p>")); + EXPECT_EQ("<p> (1) abc def|</p>", DoEndOfWord("<p> (1) abc de|f</p>")); + EXPECT_EQ("<p> (1) abc def|</p>", DoEndOfWord("<p> (1) abc def|</p>")); + EXPECT_EQ("<p> (1) abc def|</p>", DoEndOfWord("<p> (1) abc def</p>|")); +} + TEST_F(VisibleUnitsWordTest, EndOfWordTextSecurity) { // Note: |EndOfWord()| considers security characters as a sequence "x". InsertStyleElement("s {-webkit-text-security:disc;}");
diff --git a/third_party/WebKit/Source/core/editing/commands/CompositeEditCommand.cpp b/third_party/WebKit/Source/core/editing/commands/CompositeEditCommand.cpp index 6b6ea8c7..b1cd2d4 100644 --- a/third_party/WebKit/Source/core/editing/commands/CompositeEditCommand.cpp +++ b/third_party/WebKit/Source/core/editing/commands/CompositeEditCommand.cpp
@@ -288,6 +288,7 @@ ShouldAssumeContentIsAlwaysEditable should_assume_content_is_always_editable) { DCHECK_NE(GetDocument().body(), ref_child); + ABORT_EDITING_COMMAND_IF(!ref_child->parentNode()); // TODO(editing-dev): Use of updateStyleAndLayoutIgnorePendingStylesheets // needs to be audited. See http://crbug.com/590369 for more details. GetDocument().UpdateStyleAndLayoutIgnorePendingStylesheets();
diff --git a/third_party/WebKit/Source/core/editing/commands/CompositeEditCommandTest.cpp b/third_party/WebKit/Source/core/editing/commands/CompositeEditCommandTest.cpp index 6b48de8..a397bc88 100644 --- a/third_party/WebKit/Source/core/editing/commands/CompositeEditCommandTest.cpp +++ b/third_party/WebKit/Source/core/editing/commands/CompositeEditCommandTest.cpp
@@ -134,4 +134,16 @@ body->InnerHTMLAsString()); } +TEST_F(CompositeEditCommandTest, InsertNodeOnDisconnectedParent) { + SetBodyContent("<p><b></b></p>"); + SampleCommand& sample = *new SampleCommand(GetDocument()); + Node* insert_child = GetDocument().QuerySelector("b"); + Element* ref_child = GetDocument().QuerySelector("p"); + ref_child->remove(); + EditingState editing_state; + // editing state should abort here. + sample.InsertNodeBefore(insert_child, ref_child, &editing_state); + EXPECT_TRUE(editing_state.IsAborted()); +} + } // namespace blink
diff --git a/third_party/WebKit/Source/core/editing/commands/EditingCommandsUtilities.cpp b/third_party/WebKit/Source/core/editing/commands/EditingCommandsUtilities.cpp index 77bf610..6d11b33 100644 --- a/third_party/WebKit/Source/core/editing/commands/EditingCommandsUtilities.cpp +++ b/third_party/WebKit/Source/core/editing/commands/EditingCommandsUtilities.cpp
@@ -33,7 +33,6 @@ #include "core/editing/SelectionTemplate.h" #include "core/editing/VisiblePosition.h" #include "core/editing/VisibleSelection.h" -#include "core/html_element_factory.h" #include "core/layout/LayoutObject.h" namespace blink { @@ -332,8 +331,9 @@ } HTMLElement* CreateHTMLElement(Document& document, const QualifiedName& name) { - return HTMLElementFactory::createHTMLElement(name.LocalName(), document, - kCreatedByCloneNode); + DCHECK_EQ(name.NamespaceURI(), HTMLNames::xhtmlNamespaceURI) + << "Unexpected namespace: " << name; + return ToHTMLElement(document.createElement(name, kCreatedByCloneNode)); } HTMLElement* EnclosingList(const Node* node) {
diff --git a/third_party/WebKit/Source/core/editing/serializers/MarkupFormatter.cpp b/third_party/WebKit/Source/core/editing/serializers/MarkupFormatter.cpp index 721e4be3..8cd72de 100644 --- a/third_party/WebKit/Source/core/editing/serializers/MarkupFormatter.cpp +++ b/third_party/WebKit/Source/core/editing/serializers/MarkupFormatter.cpp
@@ -479,7 +479,7 @@ *parent_name == xmpTag || *parent_name == iframeTag || *parent_name == plaintextTag || *parent_name == noembedTag || *parent_name == noframesTag || - (*parent_name == noscriptTag && + (*parent_name == noscriptTag && text.GetDocument().GetFrame() && text.GetDocument().CanExecuteScripts(kNotAboutToExecuteScript)))) return kEntityMaskInCDATA; return kEntityMaskInHTMLPCDATA;
diff --git a/third_party/WebKit/Source/core/events/PromiseRejectionEvent.cpp b/third_party/WebKit/Source/core/events/PromiseRejectionEvent.cpp index 33b4911..02e7276 100644 --- a/third_party/WebKit/Source/core/events/PromiseRejectionEvent.cpp +++ b/third_party/WebKit/Source/core/events/PromiseRejectionEvent.cpp
@@ -42,8 +42,8 @@ } ScriptValue PromiseRejectionEvent::reason(ScriptState* script_state) const { - // Return null when the value is accessed by a different world than the world - // that created the value. + // Return undefined when the value is accessed by a different world than the + // world that created the value. if (reason_.IsEmpty() || !CanBeDispatchedInWorld(script_state->World())) return ScriptValue(script_state, v8::Undefined(script_state->GetIsolate())); return ScriptValue(script_state,
diff --git a/third_party/WebKit/Source/core/exported/WebAssociatedURLLoaderImpl.cpp b/third_party/WebKit/Source/core/exported/WebAssociatedURLLoaderImpl.cpp index 50d432ff..bd4dfd0 100644 --- a/third_party/WebKit/Source/core/exported/WebAssociatedURLLoaderImpl.cpp +++ b/third_party/WebKit/Source/core/exported/WebAssociatedURLLoaderImpl.cpp
@@ -100,7 +100,7 @@ const WebAssociatedURLLoaderOptions&, network::mojom::FetchRequestMode, network::mojom::FetchCredentialsMode, - scoped_refptr<WebTaskRunner>); + scoped_refptr<base::SingleThreadTaskRunner>); // ThreadableLoaderClient void DidSendData(unsigned long long /*bytesSent*/, @@ -144,7 +144,7 @@ const WebAssociatedURLLoaderOptions&, network::mojom::FetchRequestMode, network::mojom::FetchCredentialsMode, - scoped_refptr<WebTaskRunner>); + scoped_refptr<base::SingleThreadTaskRunner>); void NotifyError(TimerBase*); @@ -169,7 +169,7 @@ const WebAssociatedURLLoaderOptions& options, network::mojom::FetchRequestMode fetch_request_mode, network::mojom::FetchCredentialsMode credentials_mode, - scoped_refptr<WebTaskRunner> task_runner) { + scoped_refptr<base::SingleThreadTaskRunner> task_runner) { return WTF::WrapUnique(new ClientAdapter(loader, client, options, fetch_request_mode, credentials_mode, task_runner)); @@ -181,7 +181,7 @@ const WebAssociatedURLLoaderOptions& options, network::mojom::FetchRequestMode fetch_request_mode, network::mojom::FetchCredentialsMode credentials_mode, - scoped_refptr<WebTaskRunner> task_runner) + scoped_refptr<base::SingleThreadTaskRunner> task_runner) : loader_(loader), client_(client), options_(options), @@ -395,7 +395,7 @@ new_request.ToMutableResourceRequest().SetCORSPreflightPolicy( options_.preflight_policy); - scoped_refptr<WebTaskRunner> task_runner; + scoped_refptr<base::SingleThreadTaskRunner> task_runner; if (observer_) { task_runner = ToDocument(observer_->LifecycleContext()) ->GetTaskRunner(TaskType::kUnspecedLoading); @@ -467,7 +467,8 @@ loader_->SetDefersLoading(defers_loading); } -void WebAssociatedURLLoaderImpl::SetLoadingTaskRunner(blink::WebTaskRunner*) { +void WebAssociatedURLLoaderImpl::SetLoadingTaskRunner( + base::SingleThreadTaskRunner*) { // TODO(alexclarke): Maybe support this one day if it proves worthwhile. }
diff --git a/third_party/WebKit/Source/core/exported/WebAssociatedURLLoaderImpl.h b/third_party/WebKit/Source/core/exported/WebAssociatedURLLoaderImpl.h index bc6fe57..b085a0d 100644 --- a/third_party/WebKit/Source/core/exported/WebAssociatedURLLoaderImpl.h +++ b/third_party/WebKit/Source/core/exported/WebAssociatedURLLoaderImpl.h
@@ -9,8 +9,8 @@ #include "base/macros.h" #include "base/memory/scoped_refptr.h" +#include "base/single_thread_task_runner.h" #include "core/CoreExport.h" -#include "platform/WebTaskRunner.h" #include "platform/heap/Handle.h" #include "public/web/WebAssociatedURLLoader.h" #include "public/web/WebAssociatedURLLoaderOptions.h" @@ -32,7 +32,7 @@ WebAssociatedURLLoaderClient*) override; void Cancel() override; void SetDefersLoading(bool) override; - void SetLoadingTaskRunner(blink::WebTaskRunner*) override; + void SetLoadingTaskRunner(base::SingleThreadTaskRunner*) override; // Called by |m_observer| to handle destruction of the Document associated // with the frame given to the constructor.
diff --git a/third_party/WebKit/Source/core/exported/WebDevToolsAgentImpl.cpp b/third_party/WebKit/Source/core/exported/WebDevToolsAgentImpl.cpp index 3cc0495a..a495655 100644 --- a/third_party/WebKit/Source/core/exported/WebDevToolsAgentImpl.cpp +++ b/third_party/WebKit/Source/core/exported/WebDevToolsAgentImpl.cpp
@@ -34,6 +34,7 @@ #include <memory> #include <utility> +#include "base/single_thread_task_runner.h" #include "bindings/core/v8/ScriptController.h" #include "bindings/core/v8/V8BindingForCore.h" #include "core/CoreInitializer.h" @@ -259,7 +260,7 @@ : public mojom::blink::DevToolsSession { public: IOSession(scoped_refptr<base::SingleThreadTaskRunner> session_task_runner, - scoped_refptr<WebTaskRunner> agent_task_runner, + scoped_refptr<base::SingleThreadTaskRunner> agent_task_runner, CrossThreadWeakPersistent<WebDevToolsAgentImpl::Session> session, mojom::blink::DevToolsSessionRequest request) : session_task_runner_(session_task_runner), @@ -300,7 +301,7 @@ private: scoped_refptr<base::SingleThreadTaskRunner> session_task_runner_; - scoped_refptr<WebTaskRunner> agent_task_runner_; + scoped_refptr<base::SingleThreadTaskRunner> agent_task_runner_; CrossThreadWeakPersistent<WebDevToolsAgentImpl::Session> session_; mojo::Binding<mojom::blink::DevToolsSession> binding_;
diff --git a/third_party/WebKit/Source/core/exported/WebDocumentLoaderImpl.cpp b/third_party/WebKit/Source/core/exported/WebDocumentLoaderImpl.cpp index 5d93517..3246a56f0e 100644 --- a/third_party/WebKit/Source/core/exported/WebDocumentLoaderImpl.cpp +++ b/third_party/WebKit/Source/core/exported/WebDocumentLoaderImpl.cpp
@@ -34,7 +34,6 @@ #include "core/dom/Document.h" #include "core/frame/LocalFrame.h" #include "core/loader/SubresourceFilter.h" -#include "platform/network/NetworkUtils.h" #include "platform/wtf/PtrUtil.h" #include "public/platform/WebDocumentSubresourceFilter.h" #include "public/platform/WebURL.h" @@ -44,35 +43,6 @@ namespace blink { -namespace { - -bool IsHttpOrHttpsOrigin(const WebSecurityOrigin& origin) { - return origin.Protocol() == "http" || origin.Protocol() == "https"; -} - -} // anonymous namespace - -// static -bool WebDocumentLoader::ShouldPersistUserActivation( - const WebSecurityOrigin& previous_origin, - const WebSecurityOrigin& new_origin) { - if (previous_origin.IsNull() || new_origin.IsNull()) - return false; - - if (!IsHttpOrHttpsOrigin(previous_origin) || !IsHttpOrHttpsOrigin(new_origin)) - return false; - - if (previous_origin.Host() == new_origin.Host()) - return true; - - String previous_domain = NetworkUtils::GetDomainAndRegistry( - previous_origin.Host(), NetworkUtils::kIncludePrivateRegistries); - String new_domain = NetworkUtils::GetDomainAndRegistry( - new_origin.Host(), NetworkUtils::kIncludePrivateRegistries); - - return !previous_domain.IsEmpty() && previous_domain == new_domain; -} - WebDocumentLoaderImpl* WebDocumentLoaderImpl::Create( LocalFrame* frame, const ResourceRequest& request,
diff --git a/third_party/WebKit/Source/core/exported/WebFrameContentDumper.cpp b/third_party/WebKit/Source/core/exported/WebFrameContentDumper.cpp index ac26584..d717be19 100644 --- a/third_party/WebKit/Source/core/exported/WebFrameContentDumper.cpp +++ b/third_party/WebKit/Source/core/exported/WebFrameContentDumper.cpp
@@ -228,9 +228,16 @@ WebString WebFrameContentDumper::DumpWebViewAsText(WebView* web_view, size_t max_chars) { DCHECK(web_view); + WebLocalFrame* frame = web_view->MainFrame()->ToWebLocalFrame(); + if (!frame) + return WebString(); + web_view->UpdateAllLifecyclePhases(); - return WebFrameContentDumper::DeprecatedDumpFrameTreeAsText( - web_view->MainFrame()->ToWebLocalFrame(), max_chars); + + StringBuilder text; + FrameContentAsPlainText(max_chars, ToWebLocalFrameImpl(frame)->GetFrame(), + text); + return text.ToString(); } WebString WebFrameContentDumper::DumpAsMarkup(WebLocalFrame* frame) {
diff --git a/third_party/WebKit/Source/core/exported/WebRemoteFrameImpl.cpp b/third_party/WebKit/Source/core/exported/WebRemoteFrameImpl.cpp index 27e21b5..19725d3 100644 --- a/third_party/WebKit/Source/core/exported/WebRemoteFrameImpl.cpp +++ b/third_party/WebKit/Source/core/exported/WebRemoteFrameImpl.cpp
@@ -333,7 +333,7 @@ } void WebRemoteFrameImpl::SetHasReceivedUserGesture() { - GetFrame()->UpdateUserActivationInFrameTree(); + Frame::NotifyUserActivation(GetFrame(), UserGestureToken::kNewGesture); } void WebRemoteFrameImpl::ScrollRectToVisible(
diff --git a/third_party/WebKit/Source/core/exported/WebSharedWorkerImpl.cpp b/third_party/WebKit/Source/core/exported/WebSharedWorkerImpl.cpp index 3c094f0..bb2a8214 100644 --- a/third_party/WebKit/Source/core/exported/WebSharedWorkerImpl.cpp +++ b/third_party/WebKit/Source/core/exported/WebSharedWorkerImpl.cpp
@@ -265,6 +265,7 @@ // via WebPreference by embedders. (crbug.com/254993) Document* document = shadow_page_->GetDocument(); const SecurityOrigin* starter_origin = document->GetSecurityOrigin(); + bool starter_secure_context = document->IsSecureContext(); WorkerClients* worker_clients = WorkerClients::Create(); CoreInitializer::GetInstance().ProvideLocalFileSystemToWorker( @@ -303,8 +304,8 @@ url_, document->UserAgent(), content_security_policy ? content_security_policy->Headers().get() : nullptr, - referrer_policy, starter_origin, worker_clients, - main_script_loader_->ResponseAddressSpace(), + referrer_policy, starter_origin, starter_secure_context, + worker_clients, main_script_loader_->ResponseAddressSpace(), main_script_loader_->OriginTrialTokens(), std::move(worker_settings), kV8CacheOptionsDefault, std::move(pending_interface_provider_)); String source_code = main_script_loader_->SourceText();
diff --git a/third_party/WebKit/Source/core/exported/WebSharedWorkerImpl.h b/third_party/WebKit/Source/core/exported/WebSharedWorkerImpl.h index b67035c..8e31f06 100644 --- a/third_party/WebKit/Source/core/exported/WebSharedWorkerImpl.h +++ b/third_party/WebKit/Source/core/exported/WebSharedWorkerImpl.h
@@ -41,7 +41,6 @@ #include "core/workers/SharedWorkerReportingProxy.h" #include "core/workers/WorkerClients.h" #include "core/workers/WorkerThread.h" -#include "platform/WebTaskRunner.h" #include "public/platform/WebContentSecurityPolicy.h" #include "public/web/WebSharedWorkerClient.h" #include "public/web/worker_content_settings_proxy.mojom-blink.h"
diff --git a/third_party/WebKit/Source/core/fetch/BytesConsumer.cpp b/third_party/WebKit/Source/core/fetch/BytesConsumer.cpp index e5bd65136..c5ffb0b 100644 --- a/third_party/WebKit/Source/core/fetch/BytesConsumer.cpp +++ b/third_party/WebKit/Source/core/fetch/BytesConsumer.cpp
@@ -9,7 +9,6 @@ #include "base/memory/scoped_refptr.h" #include "core/dom/ExecutionContext.h" #include "core/fetch/BlobBytesConsumer.h" -#include "platform/WebTaskRunner.h" #include "platform/blob/BlobData.h" #include "platform/wtf/Functional.h" #include "public/platform/TaskType.h"
diff --git a/third_party/WebKit/Source/core/fetch/BytesConsumerForDataConsumerHandle.cpp b/third_party/WebKit/Source/core/fetch/BytesConsumerForDataConsumerHandle.cpp index 87821341..cf943c6 100644 --- a/third_party/WebKit/Source/core/fetch/BytesConsumerForDataConsumerHandle.cpp +++ b/third_party/WebKit/Source/core/fetch/BytesConsumerForDataConsumerHandle.cpp
@@ -9,7 +9,6 @@ #include "base/location.h" #include "core/dom/ExecutionContext.h" -#include "platform/WebTaskRunner.h" #include "platform/wtf/Functional.h" #include "public/platform/TaskType.h"
diff --git a/third_party/WebKit/Source/core/fetch/BytesConsumerTestUtil.cpp b/third_party/WebKit/Source/core/fetch/BytesConsumerTestUtil.cpp index 17576f33..a8586fca 100644 --- a/third_party/WebKit/Source/core/fetch/BytesConsumerTestUtil.cpp +++ b/third_party/WebKit/Source/core/fetch/BytesConsumerTestUtil.cpp
@@ -5,7 +5,6 @@ #include "core/fetch/BytesConsumerTestUtil.h" #include "core/dom/ExecutionContext.h" -#include "platform/WebTaskRunner.h" #include "platform/testing/UnitTestHelpers.h" #include "platform/wtf/Assertions.h" #include "platform/wtf/Functional.h"
diff --git a/third_party/WebKit/Source/core/fetch/BytesConsumerTestUtil.h b/third_party/WebKit/Source/core/fetch/BytesConsumerTestUtil.h index f03e20a..6fc50b2 100644 --- a/third_party/WebKit/Source/core/fetch/BytesConsumerTestUtil.h +++ b/third_party/WebKit/Source/core/fetch/BytesConsumerTestUtil.h
@@ -108,7 +108,7 @@ // commends when read. class ReplayingBytesConsumer final : public BytesConsumer { public: - // The ExecutionContext is needed to get a WebTaskRunner. + // The ExecutionContext is needed to get a base::SingleThreadTaskRunner. explicit ReplayingBytesConsumer(ExecutionContext*); ~ReplayingBytesConsumer() override;
diff --git a/third_party/WebKit/Source/core/fetch/DataConsumerHandleTestUtil.cpp b/third_party/WebKit/Source/core/fetch/DataConsumerHandleTestUtil.cpp index 38c6a66..840aabe 100644 --- a/third_party/WebKit/Source/core/fetch/DataConsumerHandleTestUtil.cpp +++ b/third_party/WebKit/Source/core/fetch/DataConsumerHandleTestUtil.cpp
@@ -38,9 +38,9 @@ } // namespace DataConsumerHandleTestUtil::Thread::Thread( - const char* name, + const WebThreadCreationParams& params, InitializationPolicy initialization_policy) - : thread_(WebThreadSupportingGC::Create(WebThreadCreationParams(name))), + : thread_(WebThreadSupportingGC::Create(params)), initialization_policy_(initialization_policy), waitable_event_(std::make_unique<WaitableEvent>()) { thread_->PostTask(FROM_HERE, CrossThreadBind(&Thread::Initialize,
diff --git a/third_party/WebKit/Source/core/fetch/DataConsumerHandleTestUtil.h b/third_party/WebKit/Source/core/fetch/DataConsumerHandleTestUtil.h index 9dd8d45..63aa76c 100644 --- a/third_party/WebKit/Source/core/fetch/DataConsumerHandleTestUtil.h +++ b/third_party/WebKit/Source/core/fetch/DataConsumerHandleTestUtil.h
@@ -57,7 +57,8 @@ kWithExecutionContext, }; - Thread(const char* name, InitializationPolicy = kGarbageCollection); + Thread(const WebThreadCreationParams&, + InitializationPolicy = kGarbageCollection); ~Thread(); WebThreadSupportingGC* GetThread() { return thread_.get(); } @@ -164,8 +165,12 @@ public: ThreadHolder(ThreadingTestBase* test) : context_(test->context_), - reading_thread_(std::make_unique<Thread>("reading thread")), - updating_thread_(std::make_unique<Thread>("updating thread")) { + reading_thread_(std::make_unique<Thread>( + WebThreadCreationParams(WebThreadType::kTestThread) + .SetThreadName("reading thread"))), + updating_thread_(std::make_unique<Thread>( + WebThreadCreationParams(WebThreadType::kTestThread) + .SetThreadName("updating thread"))) { context_->RegisterThreadHolder(this); } ~ThreadHolder() { context_->UnregisterThreadHolder(); }
diff --git a/third_party/WebKit/Source/core/frame/DOMTimer.cpp b/third_party/WebKit/Source/core/frame/DOMTimer.cpp index ddf83da..be7d96a8 100644 --- a/third_party/WebKit/Source/core/frame/DOMTimer.cpp +++ b/third_party/WebKit/Source/core/frame/DOMTimer.cpp
@@ -186,7 +186,7 @@ action->Dispose(); } -scoped_refptr<WebTaskRunner> DOMTimer::TimerTaskRunner() const { +scoped_refptr<base::SingleThreadTaskRunner> DOMTimer::TimerTaskRunner() const { return GetExecutionContext()->Timers()->TimerTaskRunner(); }
diff --git a/third_party/WebKit/Source/core/frame/DOMTimer.h b/third_party/WebKit/Source/core/frame/DOMTimer.h index 5325c1e9..02ab00f5 100644 --- a/third_party/WebKit/Source/core/frame/DOMTimer.h +++ b/third_party/WebKit/Source/core/frame/DOMTimer.h
@@ -83,7 +83,7 @@ int timeout_id); void Fired() override; - scoped_refptr<WebTaskRunner> TimerTaskRunner() const override; + scoped_refptr<base::SingleThreadTaskRunner> TimerTaskRunner() const override; int timeout_id_; int nesting_level_;
diff --git a/third_party/WebKit/Source/core/frame/DOMTimerCoordinator.cpp b/third_party/WebKit/Source/core/frame/DOMTimerCoordinator.cpp index b270faf..6259ec9 100644 --- a/third_party/WebKit/Source/core/frame/DOMTimerCoordinator.cpp +++ b/third_party/WebKit/Source/core/frame/DOMTimerCoordinator.cpp
@@ -12,7 +12,7 @@ namespace blink { DOMTimerCoordinator::DOMTimerCoordinator( - scoped_refptr<WebTaskRunner> timer_task_runner) + scoped_refptr<base::SingleThreadTaskRunner> timer_task_runner) : circular_sequential_id_(0), timer_nesting_level_(0), timer_task_runner_(std::move(timer_task_runner)) {}
diff --git a/third_party/WebKit/Source/core/frame/DOMTimerCoordinator.h b/third_party/WebKit/Source/core/frame/DOMTimerCoordinator.h index d38d744..1c15688 100644 --- a/third_party/WebKit/Source/core/frame/DOMTimerCoordinator.h +++ b/third_party/WebKit/Source/core/frame/DOMTimerCoordinator.h
@@ -8,7 +8,7 @@ #include <memory> #include "base/macros.h" -#include "platform/WebTaskRunner.h" +#include "base/single_thread_task_runner.h" #include "platform/heap/Handle.h" #include "platform/wtf/Time.h" @@ -27,7 +27,7 @@ DISALLOW_NEW(); public: - explicit DOMTimerCoordinator(scoped_refptr<WebTaskRunner>); + explicit DOMTimerCoordinator(scoped_refptr<base::SingleThreadTaskRunner>); // Creates and installs a new timer. Returns the assigned ID. int InstallNewTimeout(ExecutionContext*, @@ -50,7 +50,7 @@ // deeper timer nesting level, see DOMTimer::DOMTimer. void SetTimerNestingLevel(int level) { timer_nesting_level_ = level; } - scoped_refptr<WebTaskRunner> TimerTaskRunner() const { + scoped_refptr<base::SingleThreadTaskRunner> TimerTaskRunner() const { return timer_task_runner_; } @@ -64,7 +64,7 @@ int circular_sequential_id_; int timer_nesting_level_; - scoped_refptr<WebTaskRunner> timer_task_runner_; + scoped_refptr<base::SingleThreadTaskRunner> timer_task_runner_; DISALLOW_COPY_AND_ASSIGN(DOMTimerCoordinator); };
diff --git a/third_party/WebKit/Source/core/frame/Deprecation.cpp b/third_party/WebKit/Source/core/frame/Deprecation.cpp index 23da9fd6..2ad541f 100644 --- a/third_party/WebKit/Source/core/frame/Deprecation.cpp +++ b/third_party/WebKit/Source/core/frame/Deprecation.cpp
@@ -608,6 +608,15 @@ return {"ChromeLoadTimesWasAlternateProtocolAvailable", Unknown, chromeLoadTimesNextHopProtocol}; + case WebFeature::kThreeValuedPositionBasicShape: + case WebFeature::kThreeValuedPositionGradient: + case WebFeature::kThreeValuedPositionObjectPosition: + case WebFeature::kThreeValuedPositionPerspectiveOrigin: + return { + "ThreeValuedPosition", M68, + replacedWillBeRemoved("Expressing a position using 3 parts", + "<position> syntax", M68, "5116559680864256")}; + // Features that aren't deprecated don't have a deprecation message. default: return {"NotDeprecated", Unknown, ""};
diff --git a/third_party/WebKit/Source/core/frame/FrameTest.cpp b/third_party/WebKit/Source/core/frame/FrameTest.cpp index 07f3263a..7a89a55 100644 --- a/third_party/WebKit/Source/core/frame/FrameTest.cpp +++ b/third_party/WebKit/Source/core/frame/FrameTest.cpp
@@ -5,6 +5,7 @@ #include "core/frame/Frame.h" #include "core/dom/UserGestureIndicator.h" +#include "core/loader/DocumentLoader.h" #include "core/testing/PageTestBase.h" #include "platform/testing/UnitTestHelpers.h" #include "testing/gtest/include/gtest/gtest.h" @@ -15,27 +16,38 @@ public: void SetUp() override { PageTestBase::SetUp(); - Navigate("https://example.com/"); + Navigate("https://example.com/", false); ASSERT_FALSE(GetDocument().GetFrame()->HasBeenActivated()); ASSERT_FALSE( GetDocument().GetFrame()->HasReceivedUserGestureBeforeNavigation()); } - void Navigate(const String& destinationUrl) { + void Navigate(const String& destinationUrl, bool user_activated) { const KURL& url = KURL(NullURL(), destinationUrl); FrameLoadRequest request(nullptr, ResourceRequest(url), SubstituteData(SharedBuffer::Create())); GetDocument().GetFrame()->Loader().Load(request); + if (user_activated) { + GetDocument() + .GetFrame() + ->Loader() + .GetProvisionalDocumentLoader() + ->SetUserActivated(); + } blink::testing::RunPendingTasks(); ASSERT_EQ(url.GetString(), GetDocument().Url().GetString()); } void NavigateSameDomain(const String& page) { - Navigate("https://test.example.com/" + page); + NavigateSameDomain(page, true); } - void NavigateDifferentDomain() { Navigate("https://example.org/"); } + void NavigateSameDomain(const String& page, bool user_activated) { + Navigate("https://test.example.com/" + page, user_activated); + } + + void NavigateDifferentDomain() { Navigate("https://example.org/", false); } }; TEST_F(FrameTest, NoGesture) { @@ -145,7 +157,7 @@ EXPECT_FALSE( GetDocument().GetFrame()->HasReceivedUserGestureBeforeNavigation()); - NavigateSameDomain("page1"); + NavigateSameDomain("page1", false); EXPECT_FALSE(GetDocument().GetFrame()->HasBeenActivated()); EXPECT_FALSE( GetDocument().GetFrame()->HasReceivedUserGestureBeforeNavigation());
diff --git a/third_party/WebKit/Source/core/frame/FrameTestHelpers.h b/third_party/WebKit/Source/core/frame/FrameTestHelpers.h index 9a0fee7..d3497b5e 100644 --- a/third_party/WebKit/Source/core/frame/FrameTestHelpers.h +++ b/third_party/WebKit/Source/core/frame/FrameTestHelpers.h
@@ -39,7 +39,6 @@ #include "base/macros.h" #include "core/exported/WebViewImpl.h" #include "core/frame/Settings.h" -#include "platform/WebTaskRunner.h" #include "platform/runtime_enabled_features.h" #include "platform/scroll/ScrollbarTheme.h" #include "platform/testing/UseMockScrollbarSettings.h"
diff --git a/third_party/WebKit/Source/core/frame/LocalFrame.cpp b/third_party/WebKit/Source/core/frame/LocalFrame.cpp index 8c3a3fbc..c16922e 100644 --- a/third_party/WebKit/Source/core/frame/LocalFrame.cpp +++ b/third_party/WebKit/Source/core/frame/LocalFrame.cpp
@@ -818,7 +818,8 @@ return frame_scheduler_.get(); } -scoped_refptr<WebTaskRunner> LocalFrame::GetTaskRunner(TaskType type) { +scoped_refptr<base::SingleThreadTaskRunner> LocalFrame::GetTaskRunner( + TaskType type) { DCHECK(IsMainThread()); return frame_scheduler_->GetTaskRunner(type); }
diff --git a/third_party/WebKit/Source/core/frame/LocalFrame.h b/third_party/WebKit/Source/core/frame/LocalFrame.h index 1d5f68c..156ad6aa 100644 --- a/third_party/WebKit/Source/core/frame/LocalFrame.h +++ b/third_party/WebKit/Source/core/frame/LocalFrame.h
@@ -219,7 +219,7 @@ // Returns the frame scheduler, creating one if needed. WebFrameScheduler* FrameScheduler(); - scoped_refptr<WebTaskRunner> GetTaskRunner(TaskType); + scoped_refptr<base::SingleThreadTaskRunner> GetTaskRunner(TaskType); void ScheduleVisualUpdateUnlessThrottled(); bool IsNavigationAllowed() const { return navigation_disable_count_ == 0; }
diff --git a/third_party/WebKit/Source/core/frame/LocalFrameView.cpp b/third_party/WebKit/Source/core/frame/LocalFrameView.cpp index 761268d..7b4c7af 100644 --- a/third_party/WebKit/Source/core/frame/LocalFrameView.cpp +++ b/third_party/WebKit/Source/core/frame/LocalFrameView.cpp
@@ -650,7 +650,8 @@ return result; } -scoped_refptr<WebTaskRunner> LocalFrameView::GetTimerTaskRunner() const { +scoped_refptr<base::SingleThreadTaskRunner> LocalFrameView::GetTimerTaskRunner() + const { return frame_->GetTaskRunner(TaskType::kUnspecedTimer); } @@ -3656,13 +3657,19 @@ LayoutPoint LocalFrameView::ConvertToLayoutObject( const LayoutObject& layout_object, const LayoutPoint& frame_point) const { - LayoutPoint point = frame_point; + return LayoutPoint( + ConvertToLayoutObject(layout_object, FloatPoint(frame_point))); +} + +FloatPoint LocalFrameView::ConvertToLayoutObject( + const LayoutObject& layout_object, + const FloatPoint& frame_point) const { + FloatPoint point = frame_point; // Convert from LocalFrameView coords into page ("absolute") coordinates. - point += LayoutSize(ScrollX(), ScrollY()); + point += FloatSize(ScrollX(), ScrollY()); - return LayoutPoint( - layout_object.AbsoluteToLocal(FloatPoint(point), kUseTransforms)); + return layout_object.AbsoluteToLocal(point, kUseTransforms); } IntPoint LocalFrameView::ConvertSelfToChild(const EmbeddedContentView& child, @@ -3785,17 +3792,31 @@ LayoutPoint LocalFrameView::ConvertFromContainingEmbeddedContentView( const LayoutPoint& parent_point) const { + return LayoutPoint( + ConvertFromContainingEmbeddedContentView(DoublePoint(parent_point))); +} + +FloatPoint LocalFrameView::ConvertFromContainingEmbeddedContentView( + const FloatPoint& parent_point) const { + return FloatPoint( + ConvertFromContainingEmbeddedContentView(DoublePoint(parent_point))); +} + +DoublePoint LocalFrameView::ConvertFromContainingEmbeddedContentView( + const DoublePoint& parent_point) const { if (LocalFrameView* parent = ParentFrameView()) { // Get our layoutObject in the parent view auto* layout_object = frame_->OwnerLayoutObject(); if (!layout_object) return parent_point; - LayoutPoint point = - parent->ConvertToLayoutObject(*layout_object, parent_point); + DoublePoint point = DoublePoint(parent->ConvertToLayoutObject( + *layout_object, FloatPoint(parent_point))); // Subtract borders and padding - point.Move((-layout_object->BorderLeft() - layout_object->PaddingLeft()), - (-layout_object->BorderTop() - layout_object->PaddingTop())); + point.Move( + (-layout_object->BorderLeft() - layout_object->PaddingLeft()) + .ToDouble(), + (-layout_object->BorderTop() - layout_object->PaddingTop()).ToDouble()); return point; } @@ -3811,7 +3832,7 @@ IntPoint LocalFrameView::ConvertFromContainingEmbeddedContentView( const IntPoint& parent_point) const { return RoundedIntPoint( - ConvertFromContainingEmbeddedContentView(LayoutPoint(parent_point))); + ConvertFromContainingEmbeddedContentView(DoublePoint(parent_point))); } void LocalFrameView::SetInitialTracksPaintInvalidationsForTesting( @@ -5085,24 +5106,11 @@ FloatPoint LocalFrameView::ConvertFromRootFrame( const FloatPoint& point_in_root_frame) const { - // FrameViews / windows are required to be IntPoint aligned, but we may - // need to convert FloatPoint values within them (eg. for event - // co-ordinates). - IntPoint floored_point = FlooredIntPoint(point_in_root_frame); - FloatPoint parent_point = ConvertFromRootFrame(floored_point); - FloatSize window_fraction = point_in_root_frame - floored_point; - // Use linear interpolation handle any fractional value (eg. for iframes - // subject to a transform beyond just a simple translation). - // FIXME: Add FloatPoint variants of all co-ordinate space conversion APIs. - if (!window_fraction.IsEmpty()) { - const int kFactor = 1000; - IntPoint parent_line_end = ConvertFromRootFrame( - floored_point + RoundedIntSize(window_fraction.ScaledBy(kFactor))); - FloatSize parent_fraction = - (parent_line_end - parent_point).ScaledBy(1.0f / kFactor); - parent_point.Move(parent_fraction); + if (LocalFrameView* parent = ParentFrameView()) { + FloatPoint parent_point = parent->ConvertFromRootFrame(point_in_root_frame); + return ConvertFromContainingEmbeddedContentView(parent_point); } - return parent_point; + return point_in_root_frame; } IntPoint LocalFrameView::ConvertFromContainingEmbeddedContentViewToScrollbar(
diff --git a/third_party/WebKit/Source/core/frame/LocalFrameView.h b/third_party/WebKit/Source/core/frame/LocalFrameView.h index c466228..7e0afb1 100644 --- a/third_party/WebKit/Source/core/frame/LocalFrameView.h +++ b/third_party/WebKit/Source/core/frame/LocalFrameView.h
@@ -373,6 +373,8 @@ const LayoutPoint&) const; LayoutPoint ConvertToLayoutObject(const LayoutObject&, const LayoutPoint&) const; + FloatPoint ConvertToLayoutObject(const LayoutObject&, + const FloatPoint&) const; bool IsFrameViewScrollCorner(LayoutScrollbarPart* scroll_corner) const { return scroll_corner_ == scroll_corner; @@ -485,7 +487,7 @@ FloatQuad LocalToVisibleContentQuad(const FloatQuad&, const LayoutObject*, unsigned = 0) const final; - scoped_refptr<WebTaskRunner> GetTimerTaskRunner() const final; + scoped_refptr<base::SingleThreadTaskRunner> GetTimerTaskRunner() const final; LayoutRect ScrollIntoView(const LayoutRect& rect_in_content, const WebScrollIntoViewParams& params) override; @@ -1084,6 +1086,9 @@ IntPoint ConvertFromContainingEmbeddedContentView(const IntPoint&) const; LayoutPoint ConvertFromContainingEmbeddedContentView( const LayoutPoint&) const; + FloatPoint ConvertFromContainingEmbeddedContentView(const FloatPoint&) const; + DoublePoint ConvertFromContainingEmbeddedContentView( + const DoublePoint&) const; void DidChangeGlobalRootScroller() override;
diff --git a/third_party/WebKit/Source/core/frame/ReportingContext.cpp b/third_party/WebKit/Source/core/frame/ReportingContext.cpp index 07166ddf..8d6e7ed62 100644 --- a/third_party/WebKit/Source/core/frame/ReportingContext.cpp +++ b/third_party/WebKit/Source/core/frame/ReportingContext.cpp
@@ -7,7 +7,6 @@ #include "core/dom/ExecutionContext.h" #include "core/frame/Report.h" #include "core/frame/ReportingObserver.h" -#include "platform/WebTaskRunner.h" #include "platform/bindings/ScriptState.h" #include "public/platform/TaskType.h"
diff --git a/third_party/WebKit/Source/core/frame/RootFrameViewport.cpp b/third_party/WebKit/Source/core/frame/RootFrameViewport.cpp index 34ed72b..1bb3234f 100644 --- a/third_party/WebKit/Source/core/frame/RootFrameViewport.cpp +++ b/third_party/WebKit/Source/core/frame/RootFrameViewport.cpp
@@ -118,7 +118,8 @@ return viewport_quad; } -scoped_refptr<WebTaskRunner> RootFrameViewport::GetTimerTaskRunner() const { +scoped_refptr<base::SingleThreadTaskRunner> +RootFrameViewport::GetTimerTaskRunner() const { return LayoutViewport().GetTimerTaskRunner(); }
diff --git a/third_party/WebKit/Source/core/frame/RootFrameViewport.h b/third_party/WebKit/Source/core/frame/RootFrameViewport.h index b10a555..c7c1986 100644 --- a/third_party/WebKit/Source/core/frame/RootFrameViewport.h +++ b/third_party/WebKit/Source/core/frame/RootFrameViewport.h
@@ -106,7 +106,7 @@ FloatQuad LocalToVisibleContentQuad(const FloatQuad&, const LayoutObject*, unsigned = 0) const final; - scoped_refptr<WebTaskRunner> GetTimerTaskRunner() const final; + scoped_refptr<base::SingleThreadTaskRunner> GetTimerTaskRunner() const final; ScrollbarTheme& GetPageScrollbarTheme() const override; private:
diff --git a/third_party/WebKit/Source/core/frame/RootFrameViewportTest.cpp b/third_party/WebKit/Source/core/frame/RootFrameViewportTest.cpp index 1c7bfac..b106f71 100644 --- a/third_party/WebKit/Source/core/frame/RootFrameViewportTest.cpp +++ b/third_party/WebKit/Source/core/frame/RootFrameViewportTest.cpp
@@ -73,7 +73,7 @@ contents_size_ = contents_size; } - scoped_refptr<WebTaskRunner> GetTimerTaskRunner() const final { + scoped_refptr<base::SingleThreadTaskRunner> GetTimerTaskRunner() const final { return timer_task_runner_; } @@ -133,7 +133,7 @@ ScrollOffset scroll_offset_; IntSize viewport_size_; IntSize contents_size_; - scoped_refptr<WebTaskRunner> timer_task_runner_; + scoped_refptr<base::SingleThreadTaskRunner> timer_task_runner_; }; class RootFrameViewStub : public ScrollableAreaStub {
diff --git a/third_party/WebKit/Source/core/frame/VisualViewport.cpp b/third_party/WebKit/Source/core/frame/VisualViewport.cpp index 42fe36f8..0dd07306 100644 --- a/third_party/WebKit/Source/core/frame/VisualViewport.cpp +++ b/third_party/WebKit/Source/core/frame/VisualViewport.cpp
@@ -667,7 +667,8 @@ return rect; } -scoped_refptr<WebTaskRunner> VisualViewport::GetTimerTaskRunner() const { +scoped_refptr<base::SingleThreadTaskRunner> VisualViewport::GetTimerTaskRunner() + const { return MainFrame()->GetTaskRunner(TaskType::kUnspecedTimer); }
diff --git a/third_party/WebKit/Source/core/frame/VisualViewport.h b/third_party/WebKit/Source/core/frame/VisualViewport.h index 4555f934..64f4eb0 100644 --- a/third_party/WebKit/Source/core/frame/VisualViewport.h +++ b/third_party/WebKit/Source/core/frame/VisualViewport.h
@@ -216,7 +216,7 @@ CompositorAnimationTimeline* GetCompositorAnimationTimeline() const override; IntRect VisibleContentRect( IncludeScrollbarsInRect = kExcludeScrollbars) const override; - scoped_refptr<WebTaskRunner> GetTimerTaskRunner() const final; + scoped_refptr<base::SingleThreadTaskRunner> GetTimerTaskRunner() const final; // VisualViewport scrolling may involve pinch zoom and gets routed through // WebViewImpl explicitly rather than via ScrollingCoordinator::DidScroll
diff --git a/third_party/WebKit/Source/core/frame/WebLocalFrameImpl.cpp b/third_party/WebKit/Source/core/frame/WebLocalFrameImpl.cpp index dce98e89..761162fe 100644 --- a/third_party/WebKit/Source/core/frame/WebLocalFrameImpl.cpp +++ b/third_party/WebKit/Source/core/frame/WebLocalFrameImpl.cpp
@@ -2137,20 +2137,16 @@ for (const WebString& end_point : violation.report_endpoints) report_endpoints.push_back(end_point); document->GetContentSecurityPolicy()->ReportViolation( - violation.directive, /* directiveText */ - ContentSecurityPolicy::GetDirectiveType( - violation.effective_directive), /* effectiveType */ - violation.console_message, /* consoleMessage */ - violation.blocked_url, /* blockedUrl */ - report_endpoints, /* reportEndpoints */ - false, /* don't use the reporting api yet*/ - violation.header, /* header */ + violation.directive, + ContentSecurityPolicy::GetDirectiveType(violation.effective_directive), + violation.console_message, violation.blocked_url, report_endpoints, + violation.use_reporting_api, violation.header, static_cast<ContentSecurityPolicyHeaderType>(violation.disposition), - ContentSecurityPolicy::ViolationType::kURLViolation, /* ViolationType */ - std::move(source_location), nullptr, /* LocalFrame */ + ContentSecurityPolicy::ViolationType::kURLViolation, + std::move(source_location), nullptr /* LocalFrame */, violation.after_redirect ? RedirectStatus::kFollowedRedirect : RedirectStatus::kNoRedirect, - nullptr); /* Element */ + nullptr /* Element */); } bool WebLocalFrameImpl::IsLoading() const { @@ -2179,8 +2175,7 @@ } void WebLocalFrameImpl::SetHasReceivedUserGesture() { - if (GetFrame()) - GetFrame()->UpdateUserActivationInFrameTree(); + Frame::NotifyUserActivation(GetFrame(), UserGestureToken::kNewGesture); } void WebLocalFrameImpl::BlinkFeatureUsageReport(const std::set<int>& features) {
diff --git a/third_party/WebKit/Source/core/frame/WebLocalFrameImpl.h b/third_party/WebKit/Source/core/frame/WebLocalFrameImpl.h index 850fc0d..9eff6a7 100644 --- a/third_party/WebKit/Source/core/frame/WebLocalFrameImpl.h +++ b/third_party/WebKit/Source/core/frame/WebLocalFrameImpl.h
@@ -31,13 +31,13 @@ #ifndef WebLocalFrameImpl_h #define WebLocalFrameImpl_h +#include "base/single_thread_task_runner.h" #include "core/CoreExport.h" #include "core/editing/Forward.h" #include "core/exported/WebInputMethodControllerImpl.h" #include "core/frame/ContentSettingsClient.h" #include "core/frame/LocalFrame.h" #include "core/frame/WebFrameWidgetBase.h" -#include "platform/WebTaskRunner.h" #include "platform/geometry/FloatRect.h" #include "platform/heap/SelfKeepAlive.h" #include "platform/wtf/Compiler.h"
diff --git a/third_party/WebKit/Source/core/frame/csp/CSPDirectiveList.cpp b/third_party/WebKit/Source/core/frame/csp/CSPDirectiveList.cpp index 2d6071f..21e2c86 100644 --- a/third_party/WebKit/Source/core/frame/csp/CSPDirectiveList.cpp +++ b/third_party/WebKit/Source/core/frame/csp/CSPDirectiveList.cpp
@@ -1532,15 +1532,13 @@ } policy.directives = directives; - // TODO(andypaicu): for now the content csp will not know about report-to - // endpoints, make it work. std::vector<WebString> report_endpoints; - if (!use_reporting_api_) { - for (const auto& report_endpoint : ReportEndpoints()) { - report_endpoints.push_back(report_endpoint); - } + for (const auto& report_endpoint : ReportEndpoints()) { + report_endpoints.push_back(report_endpoint); } + policy.use_reporting_api = use_reporting_api_; + policy.report_endpoints = report_endpoints; policy.header = Header();
diff --git a/third_party/WebKit/Source/core/frame/csp/ContentSecurityPolicy.cpp b/third_party/WebKit/Source/core/frame/csp/ContentSecurityPolicy.cpp index 7af69e0..c1b7aad 100644 --- a/third_party/WebKit/Source/core/frame/csp/ContentSecurityPolicy.cpp +++ b/third_party/WebKit/Source/core/frame/csp/ContentSecurityPolicy.cpp
@@ -1850,8 +1850,6 @@ // Don't allow any report endpoints in "csp" attributes. for (auto& directiveList : policy->policies_) { - // TODO(andypaicu): when `report-to` is implemented, make sure this still - // works. if (directiveList->ReportEndpoints().size() != 0) return false; }
diff --git a/third_party/WebKit/Source/core/frame/csp/ContentSecurityPolicyTest.cpp b/third_party/WebKit/Source/core/frame/csp/ContentSecurityPolicyTest.cpp index 80daa1bf..091021b 100644 --- a/third_party/WebKit/Source/core/frame/csp/ContentSecurityPolicyTest.cpp +++ b/third_party/WebKit/Source/core/frame/csp/ContentSecurityPolicyTest.cpp
@@ -1335,7 +1335,12 @@ EXPECT_FALSE(ContentSecurityPolicy::IsValidCSPAttr( "report-uri relative-path/reporting;" "base-uri http://example.com 'self'")); - // TODO(andypaicu): when `report-to` is implemented, add tests here. + + EXPECT_FALSE(ContentSecurityPolicy::IsValidCSPAttr( + "script-src 'none'; report-to http://example.com/reporting")); + EXPECT_FALSE(ContentSecurityPolicy::IsValidCSPAttr( + "report-to relative-path/reporting;" + "base-uri http://example.com 'self'")); } } // namespace blink
diff --git a/third_party/WebKit/Source/core/html/HTMLEmbedElement.idl b/third_party/WebKit/Source/core/html/HTMLEmbedElement.idl index f9df7f03..020794f 100644 --- a/third_party/WebKit/Source/core/html/HTMLEmbedElement.idl +++ b/third_party/WebKit/Source/core/html/HTMLEmbedElement.idl
@@ -23,7 +23,8 @@ // TODO(yukishiino): HTMLEmbedElement should not have [OverrideBuiltins]. [ OverrideBuiltins, - ActiveScriptWrappable + ActiveScriptWrappable, + HTMLConstructor ] interface HTMLEmbedElement : HTMLElement { [CEReactions, Reflect, URL] attribute DOMString src; [CEReactions, Reflect] attribute DOMString type;
diff --git a/third_party/WebKit/Source/core/html/HTMLLinkElement.cpp b/third_party/WebKit/Source/core/html/HTMLLinkElement.cpp index 0bf4860..ff85f9d3 100644 --- a/third_party/WebKit/Source/core/html/HTMLLinkElement.cpp +++ b/third_party/WebKit/Source/core/html/HTMLLinkElement.cpp
@@ -271,7 +271,8 @@ DispatchEvent(Event::Create(EventTypeNames::webkitprerenderdomcontentloaded)); } -scoped_refptr<WebTaskRunner> HTMLLinkElement::GetLoadingTaskRunner() { +scoped_refptr<base::SingleThreadTaskRunner> +HTMLLinkElement::GetLoadingTaskRunner() { return GetDocument().GetTaskRunner(TaskType::kNetworking); }
diff --git a/third_party/WebKit/Source/core/html/HTMLLinkElement.h b/third_party/WebKit/Source/core/html/HTMLLinkElement.h index 30c3ced..403e837 100644 --- a/third_party/WebKit/Source/core/html/HTMLLinkElement.h +++ b/third_party/WebKit/Source/core/html/HTMLLinkElement.h
@@ -25,6 +25,7 @@ #define HTMLLinkElement_h #include <memory> +#include "base/single_thread_task_runner.h" #include "core/CoreExport.h" #include "core/dom/DOMTokenList.h" #include "core/dom/IncrementLoadEventDelayCount.h" @@ -35,7 +36,6 @@ #include "core/html/RelList.h" #include "core/loader/LinkLoader.h" #include "core/loader/LinkLoaderClient.h" -#include "platform/WebTaskRunner.h" #include "platform/bindings/TraceWrapperMember.h" namespace blink { @@ -151,7 +151,7 @@ void DidStopLinkPrerender() override; void DidSendLoadForLinkPrerender() override; void DidSendDOMContentLoadedForLinkPrerender() override; - scoped_refptr<WebTaskRunner> GetLoadingTaskRunner() override; + scoped_refptr<base::SingleThreadTaskRunner> GetLoadingTaskRunner() override; Member<LinkResource> link_; Member<LinkLoader> link_loader_;
diff --git a/third_party/WebKit/Source/core/html/HTMLObjectElement.idl b/third_party/WebKit/Source/core/html/HTMLObjectElement.idl index f160057..8284067 100644 --- a/third_party/WebKit/Source/core/html/HTMLObjectElement.idl +++ b/third_party/WebKit/Source/core/html/HTMLObjectElement.idl
@@ -23,7 +23,8 @@ // TODO(yukishiino): HTMLObjectElement should not have [OverrideBuiltins]. [ OverrideBuiltins, - ActiveScriptWrappable + ActiveScriptWrappable, + HTMLConstructor ] interface HTMLObjectElement : HTMLElement { [CEReactions, Reflect, URL] attribute DOMString data; [CEReactions, Reflect] attribute DOMString type;
diff --git a/third_party/WebKit/Source/core/html/canvas/CanvasFontCache.cpp b/third_party/WebKit/Source/core/html/canvas/CanvasFontCache.cpp index a5637dc..d2f03ff 100644 --- a/third_party/WebKit/Source/core/html/canvas/CanvasFontCache.cpp +++ b/third_party/WebKit/Source/core/html/canvas/CanvasFontCache.cpp
@@ -40,10 +40,6 @@ } CanvasFontCache::~CanvasFontCache() { - main_cache_purge_preventer_.reset(); - if (pruning_scheduled_) { - Platform::Current()->CurrentThread()->RemoveTaskObserver(this); - } } unsigned CanvasFontCache::MaxFonts() { @@ -160,4 +156,11 @@ visitor->Trace(document_); } +void CanvasFontCache::Dispose() { + main_cache_purge_preventer_.reset(); + if (pruning_scheduled_) { + Platform::Current()->CurrentThread()->RemoveTaskObserver(this); + } +} + } // namespace blink
diff --git a/third_party/WebKit/Source/core/html/canvas/CanvasFontCache.h b/third_party/WebKit/Source/core/html/canvas/CanvasFontCache.h index e823d0d..71552ac 100644 --- a/third_party/WebKit/Source/core/html/canvas/CanvasFontCache.h +++ b/third_party/WebKit/Source/core/html/canvas/CanvasFontCache.h
@@ -24,6 +24,8 @@ class CORE_EXPORT CanvasFontCache final : public GarbageCollectedFinalized<CanvasFontCache>, public WebThread::TaskObserver { + USING_PRE_FINALIZER(CanvasFontCache, Dispose); + public: static CanvasFontCache* Create(Document& document) { return new CanvasFontCache(document); @@ -52,6 +54,7 @@ private: explicit CanvasFontCache(Document&); + void Dispose(); void SchedulePruningIfNeeded(); typedef HeapHashMap<String, Member<MutableCSSPropertyValueSet>> MutableStylePropertyMap;
diff --git a/third_party/WebKit/Source/core/html/canvas/HTMLCanvasElement.cpp b/third_party/WebKit/Source/core/html/canvas/HTMLCanvasElement.cpp index 4dc97093..15138ce 100644 --- a/third_party/WebKit/Source/core/html/canvas/HTMLCanvasElement.cpp +++ b/third_party/WebKit/Source/core/html/canvas/HTMLCanvasElement.cpp
@@ -436,9 +436,16 @@ did_notify_listeners_for_current_frame_ = false; } -void HTMLCanvasElement::DisableAcceleration() { +void HTMLCanvasElement::DisableAcceleration( + std::unique_ptr<Canvas2DLayerBridge> + unaccelerated_bridge_used_for_testing) { // Create and configure an unaccelerated Canvas2DLayerBridge. - std::unique_ptr<Canvas2DLayerBridge> bridge = CreateUnaccelerated2dBuffer(); + std::unique_ptr<Canvas2DLayerBridge> bridge; + if (unaccelerated_bridge_used_for_testing) { + bridge = std::move(unaccelerated_bridge_used_for_testing); + } else { + bridge = CreateUnaccelerated2dBuffer(); + } if (bridge && canvas2d_bridge_) { ReplaceExistingCanvas2DBuffer(std::move(bridge)); @@ -1342,7 +1349,7 @@ void HTMLCanvasElement::SetPlaceholderFrame( scoped_refptr<StaticBitmapImage> image, base::WeakPtr<OffscreenCanvasFrameDispatcher> dispatcher, - scoped_refptr<WebTaskRunner> task_runner, + scoped_refptr<base::SingleThreadTaskRunner> task_runner, unsigned resource_id) { OffscreenCanvasPlaceholder::SetPlaceholderFrame( std::move(image), std::move(dispatcher), std::move(task_runner), @@ -1542,10 +1549,11 @@ // functional. if (!image) return; - new_buffer->Canvas()->drawImage(image->PaintImageForCurrentFrame(), 0, 0); + new_buffer->DrawFullImage(image->PaintImageForCurrentFrame()); } RestoreCanvasMatrixClipStack(new_buffer->Canvas()); + new_buffer->DidRestoreCanvasMatrixClipStack(new_buffer->Canvas()); canvas2d_bridge_ = std::move(new_buffer); }
diff --git a/third_party/WebKit/Source/core/html/canvas/HTMLCanvasElement.h b/third_party/WebKit/Source/core/html/canvas/HTMLCanvasElement.h index 1099619..c7c0a3b 100644 --- a/third_party/WebKit/Source/core/html/canvas/HTMLCanvasElement.h +++ b/third_party/WebKit/Source/core/html/canvas/HTMLCanvasElement.h
@@ -205,7 +205,8 @@ void SetNeedsCompositingUpdate() override; void UpdateMemoryUsage() override; - void DisableAcceleration(); + void DisableAcceleration(std::unique_ptr<Canvas2DLayerBridge> + unaccelerated_bridge_used_for_testing = nullptr); // ImageBitmapSource implementation IntSize BitmapSourceSize() const override; @@ -217,7 +218,7 @@ // OffscreenCanvasPlaceholder implementation. void SetPlaceholderFrame(scoped_refptr<StaticBitmapImage>, base::WeakPtr<OffscreenCanvasFrameDispatcher>, - scoped_refptr<WebTaskRunner>, + scoped_refptr<base::SingleThreadTaskRunner>, unsigned resource_id) override; virtual void Trace(blink::Visitor*);
diff --git a/third_party/WebKit/Source/core/html/custom/CustomElement.cpp b/third_party/WebKit/Source/core/html/custom/CustomElement.cpp index 2b6930f..e51a0f6c0 100644 --- a/third_party/WebKit/Source/core/html/custom/CustomElement.cpp +++ b/third_party/WebKit/Source/core/html/custom/CustomElement.cpp
@@ -103,16 +103,6 @@ return CreateCustomElementSync(document, tag_name, definition); } -HTMLElement* CustomElement::CreateCustomElementSync( - Document& document, - const AtomicString& local_name, - CustomElementDefinition* definition) { - return CreateCustomElementSync( - document, - QualifiedName(g_null_atom, local_name, HTMLNames::xhtmlNamespaceURI), - definition); -} - // https://dom.spec.whatwg.org/#concept-create-element HTMLElement* CustomElement::CreateCustomElementSync( Document& document,
diff --git a/third_party/WebKit/Source/core/html/custom/CustomElement.h b/third_party/WebKit/Source/core/html/custom/CustomElement.h index c8f1b92..2d8b12f 100644 --- a/third_party/WebKit/Source/core/html/custom/CustomElement.h +++ b/third_party/WebKit/Source/core/html/custom/CustomElement.h
@@ -70,9 +70,6 @@ static HTMLElement* CreateCustomElementSync(Document&, const QualifiedName&); static HTMLElement* CreateCustomElementSync(Document&, - const AtomicString& local_name, - CustomElementDefinition*); - static HTMLElement* CreateCustomElementSync(Document&, const QualifiedName&, CustomElementDefinition*); static HTMLElement* CreateCustomElementAsync(Document&,
diff --git a/third_party/WebKit/Source/core/html/custom/CustomElementDefinition.cpp b/third_party/WebKit/Source/core/html/custom/CustomElementDefinition.cpp index 4a3704a..5f096718 100644 --- a/third_party/WebKit/Source/core/html/custom/CustomElementDefinition.cpp +++ b/third_party/WebKit/Source/core/html/custom/CustomElementDefinition.cpp
@@ -92,13 +92,14 @@ HTMLElement* CustomElementDefinition::CreateElementForConstructor( Document& document) { - // TODO(kojii): When HTMLElementFactory has an option not to queue - // upgrade, call that instead of HTMLElement. HTMLElement is enough - // for now, but type extension will require HTMLElementFactory. - HTMLElement* element = - HTMLElement::Create(QualifiedName(g_null_atom, Descriptor().LocalName(), - HTMLNames::xhtmlNamespaceURI), - document); + HTMLElement* element = HTMLElementFactory::CreateRawHTMLElement( + Descriptor().LocalName(), document, kCreatedByCreateElement); + if (!element) { + element = + HTMLElement::Create(QualifiedName(g_null_atom, Descriptor().LocalName(), + HTMLNames::xhtmlNamespaceURI), + document); + } // TODO(davaajav): write this as one call to setCustomElementState instead of // two element->SetCustomElementState(CustomElementState::kUndefined);
diff --git a/third_party/WebKit/Source/core/html/forms/HTMLFormElement.idl b/third_party/WebKit/Source/core/html/forms/HTMLFormElement.idl index 342d19b..c4e37caf 100644 --- a/third_party/WebKit/Source/core/html/forms/HTMLFormElement.idl +++ b/third_party/WebKit/Source/core/html/forms/HTMLFormElement.idl
@@ -21,6 +21,7 @@ // https://html.spec.whatwg.org/#the-form-element [ + HTMLConstructor, OverrideBuiltins ] interface HTMLFormElement : HTMLElement { [CEReactions, Reflect=accept_charset] attribute DOMString acceptCharset;
diff --git a/third_party/WebKit/Source/core/html/media/MediaRemotingInterstitial.cpp b/third_party/WebKit/Source/core/html/media/MediaRemotingInterstitial.cpp index a1db032..2d3b02f 100644 --- a/third_party/WebKit/Source/core/html/media/MediaRemotingInterstitial.cpp +++ b/third_party/WebKit/Source/core/html/media/MediaRemotingInterstitial.cpp
@@ -29,10 +29,10 @@ this, &MediaRemotingInterstitial::ToggleInterstitialTimerFired), video_element_(&videoElement) { - SetShadowPseudoId(AtomicString("-internal-media-remoting-interstitial")); + SetShadowPseudoId(AtomicString("-internal-media-interstitial")); background_image_ = HTMLImageElement::Create(GetDocument()); background_image_->SetShadowPseudoId( - AtomicString("-internal-media-remoting-background-image")); + AtomicString("-internal-media-interstitial-background-image")); background_image_->SetSrc(videoElement.getAttribute(HTMLNames::posterAttr)); AppendChild(background_image_);
diff --git a/third_party/WebKit/Source/core/html/media/MediaRemotingInterstitial.h b/third_party/WebKit/Source/core/html/media/MediaRemotingInterstitial.h index 0df621b..19430a179 100644 --- a/third_party/WebKit/Source/core/html/media/MediaRemotingInterstitial.h +++ b/third_party/WebKit/Source/core/html/media/MediaRemotingInterstitial.h
@@ -7,7 +7,6 @@ #include "core/html/HTMLDivElement.h" #include "platform/Timer.h" -#include "platform/WebTaskRunner.h" #include "public/platform/WebLocalizedString.h" namespace blink {
diff --git a/third_party/WebKit/Source/core/html/media/PictureInPictureInterstitial.cpp b/third_party/WebKit/Source/core/html/media/PictureInPictureInterstitial.cpp index c4909f4..128ae6b 100644 --- a/third_party/WebKit/Source/core/html/media/PictureInPictureInterstitial.cpp +++ b/third_party/WebKit/Source/core/html/media/PictureInPictureInterstitial.cpp
@@ -27,10 +27,10 @@ this, &PictureInPictureInterstitial::ToggleInterstitialTimerFired), video_element_(&videoElement) { - SetShadowPseudoId(AtomicString("-internal-picture-in-picture-interstitial")); + SetShadowPseudoId(AtomicString("-internal-media-interstitial")); background_image_ = HTMLImageElement::Create(GetDocument()); background_image_->SetShadowPseudoId( - AtomicString("-internal-picture-in-picture-background-image")); + AtomicString("-internal-media-interstitial-background-image")); background_image_->SetSrc(videoElement.getAttribute(HTMLNames::posterAttr)); AppendChild(background_image_);
diff --git a/third_party/WebKit/Source/core/html/media/PictureInPictureInterstitial.h b/third_party/WebKit/Source/core/html/media/PictureInPictureInterstitial.h index bbafdf4..1ae92e2 100644 --- a/third_party/WebKit/Source/core/html/media/PictureInPictureInterstitial.h +++ b/third_party/WebKit/Source/core/html/media/PictureInPictureInterstitial.h
@@ -7,7 +7,6 @@ #include "core/html/HTMLDivElement.h" #include "platform/Timer.h" -#include "platform/WebTaskRunner.h" namespace blink {
diff --git a/third_party/WebKit/Source/core/html/parser/BackgroundHTMLParser.cpp b/third_party/WebKit/Source/core/html/parser/BackgroundHTMLParser.cpp index f090fe3..2188de39 100644 --- a/third_party/WebKit/Source/core/html/parser/BackgroundHTMLParser.cpp +++ b/third_party/WebKit/Source/core/html/parser/BackgroundHTMLParser.cpp
@@ -26,6 +26,7 @@ #include "core/html/parser/BackgroundHTMLParser.h" #include <memory> +#include "base/single_thread_task_runner.h" #include "core/html/parser/HTMLDocumentParser.h" #include "core/html/parser/TextResourceDecoder.h" #include "core/html/parser/XSSAuditor.h" @@ -88,7 +89,7 @@ base::WeakPtr<BackgroundHTMLParser> BackgroundHTMLParser::Create( std::unique_ptr<Configuration> config, - scoped_refptr<WebTaskRunner> loading_task_runner) { + scoped_refptr<base::SingleThreadTaskRunner> loading_task_runner) { auto* background_parser = new BackgroundHTMLParser( std::move(config), std::move(loading_task_runner)); return background_parser->weak_factory_.GetWeakPtr(); @@ -111,7 +112,7 @@ BackgroundHTMLParser::BackgroundHTMLParser( std::unique_ptr<Configuration> config, - scoped_refptr<WebTaskRunner> loading_task_runner) + scoped_refptr<base::SingleThreadTaskRunner> loading_task_runner) : weak_factory_(this), token_(WTF::WrapUnique(new HTMLToken)), tokenizer_(HTMLTokenizer::Create(config->options)),
diff --git a/third_party/WebKit/Source/core/html/parser/BackgroundHTMLParser.h b/third_party/WebKit/Source/core/html/parser/BackgroundHTMLParser.h index dbbf904..d4a0f12 100644 --- a/third_party/WebKit/Source/core/html/parser/BackgroundHTMLParser.h +++ b/third_party/WebKit/Source/core/html/parser/BackgroundHTMLParser.h
@@ -30,6 +30,7 @@ #include "base/macros.h" #include "base/memory/weak_ptr.h" +#include "base/single_thread_task_runner.h" #include "core/dom/DocumentEncodingData.h" #include "core/html/parser/BackgroundHTMLInputStream.h" #include "core/html/parser/CompactHTMLToken.h" @@ -40,7 +41,6 @@ #include "core/html/parser/TextResourceDecoder.h" #include "core/html/parser/TokenizedChunkQueue.h" #include "core/html/parser/XSSAuditorDelegate.h" -#include "platform/WebTaskRunner.h" namespace blink { @@ -73,7 +73,7 @@ // calling stop(). static base::WeakPtr<BackgroundHTMLParser> Create( std::unique_ptr<Configuration>, - scoped_refptr<WebTaskRunner>); + scoped_refptr<base::SingleThreadTaskRunner>); void Init(const KURL& document_url, std::unique_ptr<CachedDocumentParameters>, const MediaValuesCached::MediaValuesCachedData&); @@ -103,7 +103,7 @@ private: BackgroundHTMLParser(std::unique_ptr<Configuration>, - scoped_refptr<WebTaskRunner>); + scoped_refptr<base::SingleThreadTaskRunner>); ~BackgroundHTMLParser(); void AppendDecodedBytes(const String&); @@ -139,7 +139,7 @@ std::unique_ptr<TokenPreloadScanner> preload_scanner_; std::unique_ptr<TextResourceDecoder> decoder_; DocumentEncodingData last_seen_encoding_data_; - scoped_refptr<WebTaskRunner> loading_task_runner_; + scoped_refptr<base::SingleThreadTaskRunner> loading_task_runner_; scoped_refptr<TokenizedChunkQueue> tokenized_chunk_queue_; // Index into |m_pendingTokens| of the last <meta> csp token found. Will be
diff --git a/third_party/WebKit/Source/core/html/parser/HTMLDocumentParser.h b/third_party/WebKit/Source/core/html/parser/HTMLDocumentParser.h index 6995b97c..95065d8 100644 --- a/third_party/WebKit/Source/core/html/parser/HTMLDocumentParser.h +++ b/third_party/WebKit/Source/core/html/parser/HTMLDocumentParser.h
@@ -244,7 +244,7 @@ // A scanner used only for input provided to the insert() method. std::unique_ptr<HTMLPreloadScanner> insertion_preload_scanner_; - scoped_refptr<WebTaskRunner> loading_task_runner_; + scoped_refptr<base::SingleThreadTaskRunner> loading_task_runner_; Member<HTMLParserScheduler> parser_scheduler_; HTMLSourceTracker source_tracker_; TextPosition text_position_;
diff --git a/third_party/WebKit/Source/core/html/parser/HTMLParserScheduler.cpp b/third_party/WebKit/Source/core/html/parser/HTMLParserScheduler.cpp index 2c727bf..925cec0 100644 --- a/third_party/WebKit/Source/core/html/parser/HTMLParserScheduler.cpp +++ b/third_party/WebKit/Source/core/html/parser/HTMLParserScheduler.cpp
@@ -58,7 +58,7 @@ HTMLParserScheduler::HTMLParserScheduler( HTMLDocumentParser* parser, - scoped_refptr<WebTaskRunner> loading_task_runner) + scoped_refptr<base::SingleThreadTaskRunner> loading_task_runner) : parser_(parser), loading_task_runner_(std::move(loading_task_runner)), is_paused_with_active_timer_(false) {}
diff --git a/third_party/WebKit/Source/core/html/parser/HTMLParserScheduler.h b/third_party/WebKit/Source/core/html/parser/HTMLParserScheduler.h index 4dd8975..46184ac8 100644 --- a/third_party/WebKit/Source/core/html/parser/HTMLParserScheduler.h +++ b/third_party/WebKit/Source/core/html/parser/HTMLParserScheduler.h
@@ -30,6 +30,7 @@ #include "base/macros.h" #include "base/memory/scoped_refptr.h" +#include "base/single_thread_task_runner.h" #include "core/html/parser/NestingLevelIncrementer.h" #include "platform/WebTaskRunner.h" #include "platform/wtf/Allocator.h" @@ -67,7 +68,7 @@ public: static HTMLParserScheduler* Create( HTMLDocumentParser* parser, - scoped_refptr<WebTaskRunner> loading_task_runner) { + scoped_refptr<base::SingleThreadTaskRunner> loading_task_runner) { return new HTMLParserScheduler(parser, std::move(loading_task_runner)); } ~HTMLParserScheduler(); @@ -93,13 +94,14 @@ void Trace(blink::Visitor*); private: - HTMLParserScheduler(HTMLDocumentParser*, scoped_refptr<WebTaskRunner>); + HTMLParserScheduler(HTMLDocumentParser*, + scoped_refptr<base::SingleThreadTaskRunner>); bool ShouldYield(const SpeculationsPumpSession&, bool starting_script) const; void ContinueParsing(); Member<HTMLDocumentParser> parser_; - scoped_refptr<WebTaskRunner> loading_task_runner_; + scoped_refptr<base::SingleThreadTaskRunner> loading_task_runner_; TaskHandle cancellable_continue_parse_task_handle_; bool is_paused_with_active_timer_;
diff --git a/third_party/WebKit/Source/core/html/parser/HTMLPreloadScanner.cpp b/third_party/WebKit/Source/core/html/parser/HTMLPreloadScanner.cpp index ada8b6a7..d87a922 100644 --- a/third_party/WebKit/Source/core/html/parser/HTMLPreloadScanner.cpp +++ b/third_party/WebKit/Source/core/html/parser/HTMLPreloadScanner.cpp
@@ -789,9 +789,10 @@ "accept-ch")) { const typename Token::Attribute* content_attribute = token.GetAttributeItem(contentAttr); - if (content_attribute) + if (content_attribute) { client_hints_preferences_.UpdateFromAcceptClientHintsHeader( - content_attribute->Value(), nullptr); + content_attribute->Value(), document_url_, nullptr); + } } return; }
diff --git a/third_party/WebKit/Source/core/html/parser/HTMLPreloadScannerTest.cpp b/third_party/WebKit/Source/core/html/parser/HTMLPreloadScannerTest.cpp index f50b666..234be39 100644 --- a/third_party/WebKit/Source/core/html/parser/HTMLPreloadScannerTest.cpp +++ b/third_party/WebKit/Source/core/html/parser/HTMLPreloadScannerTest.cpp
@@ -20,6 +20,7 @@ #include "public/platform/WebClientHintsType.h" #include "public/platform/WebURLLoaderMockFactory.h" #include "testing/gtest/include/gtest/gtest.h" +#include "third_party/WebKit/public/platform/WebRuntimeFeatures.h" namespace blink { @@ -208,9 +209,12 @@ void RunSetUp( ViewportState viewport_state, PreloadState preload_state = kPreloadEnabled, - ReferrerPolicy document_referrer_policy = kReferrerPolicyDefault) { + ReferrerPolicy document_referrer_policy = kReferrerPolicyDefault, + bool use_secure_document_url = false) { HTMLParserOptions options(&GetDocument()); - KURL document_url("http://whatever.test/"); + KURL document_url = KURL("http://whatever.test/"); + if (use_secure_document_url) + document_url = KURL("https://whatever.test/"); GetDocument().SetURL(document_url); GetDocument().SetSecurityOrigin(SecurityOrigin::Create(document_url)); GetDocument().GetSettings()->SetViewportEnabled(viewport_state == @@ -594,11 +598,58 @@ }; for (const auto& test_case : test_cases) { - RunSetUp(kViewportDisabled); + RunSetUp(kViewportDisabled, kPreloadEnabled, kReferrerPolicyDefault, + true /* use_secure_document_url */); Test(test_case); } } +TEST_F(HTMLPreloadScannerTest, testMetaAcceptCHInsecureDocument) { + ClientHintsPreferences all; + all.SetShouldSendForTesting(mojom::WebClientHintsType::kDpr); + all.SetShouldSendForTesting(mojom::WebClientHintsType::kResourceWidth); + all.SetShouldSendForTesting(mojom::WebClientHintsType::kViewportWidth); + + const PreloadScannerTestCase expect_no_client_hint = { + "http://example.test", + "<meta http-equiv='accept-ch' content=' viewport-width ,width, " + "wutever, dpr \t'><img sizes='90vw' srcset='bla.gif 320w, blabla.gif " + "640w'>", + "blabla.gif", + "http://example.test/", + Resource::kImage, + 450}; + + const PreloadScannerTestCase expect_client_hint = { + "http://example.test", + "<meta http-equiv='accept-ch' content=' viewport-width ,width, " + "wutever, dpr \t'><img sizes='90vw' srcset='bla.gif 320w, blabla.gif " + "640w'>", + "blabla.gif", + "http://example.test/", + Resource::kImage, + 450, + all}; + + // For an insecure document, client hint should not be attached. + WebRuntimeFeatures::EnableClientHintsPersistent(true); + RunSetUp(kViewportDisabled, kPreloadEnabled, kReferrerPolicyDefault, + false /* use_secure_document_url */); + Test(expect_no_client_hint); + + // For a secure document, client hint should be attached. + RunSetUp(kViewportDisabled, kPreloadEnabled, kReferrerPolicyDefault, + true /* use_secure_document_url */); + Test(expect_client_hint); + + // For an insecure document, client hint should be attached if the persistent + // client hints are not enabled. + WebRuntimeFeatures::EnableClientHintsPersistent(false); + RunSetUp(kViewportDisabled, kPreloadEnabled, kReferrerPolicyDefault, + false /* use_secure_document_url */); + Test(expect_client_hint); +} + TEST_F(HTMLPreloadScannerTest, testPreconnect) { HTMLPreconnectTestCase test_cases[] = { {"http://example.test", "<link rel=preconnect href=http://example2.test>",
diff --git a/third_party/WebKit/Source/core/html/track/vtt/VTTElement.cpp b/third_party/WebKit/Source/core/html/track/vtt/VTTElement.cpp index 8b9437ae..80a72c9b 100644 --- a/third_party/WebKit/Source/core/html/track/vtt/VTTElement.cpp +++ b/third_party/WebKit/Source/core/html/track/vtt/VTTElement.cpp
@@ -26,7 +26,7 @@ #include "core/html/track/vtt/VTTElement.h" #include "core/css/StyleChangeReason.h" -#include "core/html_element_factory.h" +#include "core/dom/Document.h" namespace blink { @@ -82,37 +82,37 @@ } HTMLElement* VTTElement::CreateEquivalentHTMLElement(Document& document) { - HTMLElement* html_element = nullptr; + Element* html_element = nullptr; switch (web_vtt_node_type_) { case kVTTNodeTypeClass: case kVTTNodeTypeLanguage: case kVTTNodeTypeVoice: - html_element = HTMLElementFactory::createHTMLElement( - HTMLNames::spanTag.LocalName(), document); + html_element = + document.CreateRawElement(HTMLNames::spanTag, kCreatedByParser); html_element->setAttribute(HTMLNames::titleAttr, getAttribute(VoiceAttributeName())); html_element->setAttribute(HTMLNames::langAttr, getAttribute(LangAttributeName())); break; case kVTTNodeTypeItalic: - html_element = HTMLElementFactory::createHTMLElement( - HTMLNames::iTag.LocalName(), document); + html_element = + document.CreateRawElement(HTMLNames::iTag, kCreatedByParser); break; case kVTTNodeTypeBold: - html_element = HTMLElementFactory::createHTMLElement( - HTMLNames::bTag.LocalName(), document); + html_element = + document.CreateRawElement(HTMLNames::bTag, kCreatedByParser); break; case kVTTNodeTypeUnderline: - html_element = HTMLElementFactory::createHTMLElement( - HTMLNames::uTag.LocalName(), document); + html_element = + document.CreateRawElement(HTMLNames::uTag, kCreatedByParser); break; case kVTTNodeTypeRuby: - html_element = HTMLElementFactory::createHTMLElement( - HTMLNames::rubyTag.LocalName(), document); + html_element = + document.CreateRawElement(HTMLNames::rubyTag, kCreatedByParser); break; case kVTTNodeTypeRubyText: - html_element = HTMLElementFactory::createHTMLElement( - HTMLNames::rtTag.LocalName(), document); + html_element = + document.CreateRawElement(HTMLNames::rtTag, kCreatedByParser); break; default: NOTREACHED(); @@ -120,7 +120,7 @@ html_element->setAttribute(HTMLNames::classAttr, getAttribute(HTMLNames::classAttr)); - return html_element; + return ToHTMLElement(html_element); } void VTTElement::SetIsPastNode(bool is_past_node) {
diff --git a/third_party/WebKit/Source/core/imagebitmap/ImageBitmap.cpp b/third_party/WebKit/Source/core/imagebitmap/ImageBitmap.cpp index 060c7cf..55fbcfc 100644 --- a/third_party/WebKit/Source/core/imagebitmap/ImageBitmap.cpp +++ b/third_party/WebKit/Source/core/imagebitmap/ImageBitmap.cpp
@@ -595,7 +595,10 @@ : kUnpremul_SkAlphaType, color_params.GetSkColorSpaceForSkSurfaces()); SkPixmap pixmap(info, pixel_data, info.bytesPerPixel() * width); - image_ = StaticBitmapImage::Create(SkImage::MakeRasterCopy(pixmap)); + sk_sp<SkImage> raster_copy = SkImage::MakeRasterCopy(pixmap); + if (!raster_copy) + return; + image_ = StaticBitmapImage::Create(std::move(raster_copy)); if (!image_) return; image_->SetOriginClean(is_image_bitmap_origin_clean); @@ -845,7 +848,7 @@ paint_record->Playback(surface->getCanvas()); skia_image = surface->makeImageSnapshot(); } - scoped_refptr<WebTaskRunner> task_runner = + scoped_refptr<base::SingleThreadTaskRunner> task_runner = Platform::Current()->MainThread()->GetWebTaskRunner(); PostCrossThreadTask(*task_runner, FROM_HERE, CrossThreadBind(&ResolvePromiseOnOriginalThread,
diff --git a/third_party/WebKit/Source/core/imagebitmap/ImageBitmapFactories.cpp b/third_party/WebKit/Source/core/imagebitmap/ImageBitmapFactories.cpp index cf27d3fd..bc33d29 100644 --- a/third_party/WebKit/Source/core/imagebitmap/ImageBitmapFactories.cpp +++ b/third_party/WebKit/Source/core/imagebitmap/ImageBitmapFactories.cpp
@@ -302,7 +302,7 @@ void ImageBitmapFactories::ImageBitmapLoader::ScheduleAsyncImageBitmapDecoding( DOMArrayBuffer* array_buffer) { - scoped_refptr<WebTaskRunner> task_runner = + scoped_refptr<base::SingleThreadTaskRunner> task_runner = Platform::Current()->CurrentThread()->GetWebTaskRunner(); BackgroundTaskRunner::PostOnBackgroundThread( FROM_HERE, @@ -314,7 +314,7 @@ } void ImageBitmapFactories::ImageBitmapLoader::DecodeImageOnDecoderThread( - scoped_refptr<WebTaskRunner> task_runner, + scoped_refptr<base::SingleThreadTaskRunner> task_runner, DOMArrayBuffer* array_buffer, const String& premultiply_alpha_option, const String& color_space_conversion_option) {
diff --git a/third_party/WebKit/Source/core/imagebitmap/ImageBitmapFactories.h b/third_party/WebKit/Source/core/imagebitmap/ImageBitmapFactories.h index ec52647..4d4ba0c 100644 --- a/third_party/WebKit/Source/core/imagebitmap/ImageBitmapFactories.h +++ b/third_party/WebKit/Source/core/imagebitmap/ImageBitmapFactories.h
@@ -32,6 +32,7 @@ #define ImageBitmapFactories_h #include <memory> +#include "base/single_thread_task_runner.h" #include "bindings/core/v8/ScriptPromise.h" #include "bindings/core/v8/ScriptPromiseResolver.h" #include "bindings/core/v8/image_bitmap_source.h" @@ -41,7 +42,6 @@ #include "core/imagebitmap/ImageBitmapOptions.h" #include "core/workers/WorkerGlobalScope.h" #include "platform/Supplementable.h" -#include "platform/WebTaskRunner.h" #include "platform/bindings/ScriptState.h" #include "platform/geometry/IntRect.h" #include "third_party/skia/include/core/SkRefCnt.h" @@ -132,7 +132,7 @@ void ScheduleAsyncImageBitmapDecoding(DOMArrayBuffer*); void DecodeImageOnDecoderThread( - scoped_refptr<WebTaskRunner>, + scoped_refptr<base::SingleThreadTaskRunner>, DOMArrayBuffer*, const String& premultiply_alpha_option, const String& color_space_conversion_option);
diff --git a/third_party/WebKit/Source/core/input/EventHandler.cpp b/third_party/WebKit/Source/core/input/EventHandler.cpp index fcee50f2..ea4820067 100644 --- a/third_party/WebKit/Source/core/input/EventHandler.cpp +++ b/third_party/WebKit/Source/core/input/EventHandler.cpp
@@ -1678,17 +1678,10 @@ LayoutSize padding; if (ShouldApplyTouchAdjustment(gesture_event)) { - // If gesture_event unique id matches the stored touch event result, do - // point-base hit test. Otherwise add padding to do rect-based hit test. - if (GestureCorrespondsToAdjustedTouch(gesture_event)) { - adjusted_event.ApplyTouchAdjustment( - touch_adjustment_result_.adjusted_point); - } else { - padding = LayoutSize(adjusted_event.TapAreaInRootFrame()); - if (!padding.IsEmpty()) { - padding.Scale(1.f / 2); - hit_type |= HitTestRequest::kListBased; - } + padding = LayoutSize(adjusted_event.TapAreaInRootFrame()); + if (!padding.IsEmpty()) { + padding.Scale(1.f / 2); + hit_type |= HitTestRequest::kListBased; } } LayoutPoint hit_test_point(frame_->View()->RootFrameToContents( @@ -1720,6 +1713,7 @@ // by now to ensure consumers don't accidentally use one of the other // candidates. DCHECK(!hit_test_result.IsRectBasedTest()); + if (ShouldApplyTouchAdjustment(gesture_event) && (gesture_event.GetType() == WebInputEvent::kGestureTap || gesture_event.GetType() == WebInputEvent::kGestureLongPress)) { @@ -1729,6 +1723,22 @@ UMA_HISTOGRAM_COUNTS_100("Event.Touch.TouchAdjustment.AdjustDistance", static_cast<int>(adjusted_distance)); } + if (GestureCorrespondsToAdjustedTouch(gesture_event)) { + LayoutPoint stored_adjusted_point(frame_->View()->RootFrameToContents( + touch_adjustment_result_.adjusted_point)); + HitTestResult point_base_result = HitTestResultAtPoint( + stored_adjusted_point, + (hit_type | HitTestRequest::kReadOnly) & ~HitTestRequest::kListBased); + if (gesture_event.GetType() == WebInputEvent::kGestureTap) { + UMA_HISTOGRAM_BOOLEAN( + "Event.Touch.TouchAdjustment.AdjustToSameNode", + point_base_result.InnerNode() == hit_test_result.InnerNode()); + } + adjusted_event.ApplyTouchAdjustment( + touch_adjustment_result_.adjusted_point); + return GestureEventWithHitTestResults(adjusted_event, point_base_result); + } + return GestureEventWithHitTestResults(adjusted_event, hit_test_result); }
diff --git a/third_party/WebKit/Source/core/inspector/InspectorMemoryAgent.cpp b/third_party/WebKit/Source/core/inspector/InspectorMemoryAgent.cpp index 987645a..39bf3fae 100644 --- a/third_party/WebKit/Source/core/inspector/InspectorMemoryAgent.cpp +++ b/third_party/WebKit/Source/core/inspector/InspectorMemoryAgent.cpp
@@ -161,20 +161,32 @@ std::vector<std::string> InspectorMemoryAgent::Symbolize( const std::vector<void*>& addresses) { // TODO(alph): Move symbolization to the client. - std::vector<std::string> result; - base::debug::StackTrace trace(addresses.data(), addresses.size()); - std::string text = trace.ToString(); + std::vector<void*> addresses_to_symbolize; + for (void* address : addresses) { + if (!symbols_cache_.Contains(address)) + addresses_to_symbolize.push_back(address); + } + std::string text = base::debug::StackTrace(addresses_to_symbolize.data(), + addresses_to_symbolize.size()) + .ToString(); + // Populate cache with new entries. size_t next_pos; - for (size_t pos = 0;; pos = next_pos + 1) { + for (size_t pos = 0, i = 0;; pos = next_pos + 1, ++i) { next_pos = text.find('\n', pos); if (next_pos == std::string::npos) break; std::string line = text.substr(pos, next_pos - pos); size_t space_pos = line.rfind(' '); - result.push_back( - line.substr(space_pos == std::string::npos ? 0 : space_pos + 1)); + std::string name = + line.substr(space_pos == std::string::npos ? 0 : space_pos + 1); + symbols_cache_.insert(addresses_to_symbolize[i], name); } + + std::vector<std::string> result; + for (void* address : addresses) + result.push_back(symbols_cache_.at(address)); + return result; }
diff --git a/third_party/WebKit/Source/core/inspector/InspectorMemoryAgent.h b/third_party/WebKit/Source/core/inspector/InspectorMemoryAgent.h index beaeabd1..c040bf5 100644 --- a/third_party/WebKit/Source/core/inspector/InspectorMemoryAgent.h +++ b/third_party/WebKit/Source/core/inspector/InspectorMemoryAgent.h
@@ -84,6 +84,7 @@ std::unique_ptr<PrepareForLeakDetectionCallback> callback_; Member<InspectedFrames> frames_; uint32_t profile_id_ = 0; + HashMap<void*, std::string> symbols_cache_; DISALLOW_COPY_AND_ASSIGN(InspectorMemoryAgent); };
diff --git a/third_party/WebKit/Source/core/inspector/InspectorWorkerAgent.cpp b/third_party/WebKit/Source/core/inspector/InspectorWorkerAgent.cpp index 2ae0894..905519b 100644 --- a/third_party/WebKit/Source/core/inspector/InspectorWorkerAgent.cpp +++ b/third_party/WebKit/Source/core/inspector/InspectorWorkerAgent.cpp
@@ -94,10 +94,6 @@ return Response::OK(); } -Response InspectorWorkerAgent::setAttachToFrames(bool attach) { - return Response::OK(); -} - bool InspectorWorkerAgent::AutoAttachEnabled() { return state_->booleanProperty(WorkerAgentState::kAutoAttach, false); }
diff --git a/third_party/WebKit/Source/core/inspector/InspectorWorkerAgent.h b/third_party/WebKit/Source/core/inspector/InspectorWorkerAgent.h index d8b9c0a..70a70ceb 100644 --- a/third_party/WebKit/Source/core/inspector/InspectorWorkerAgent.h +++ b/third_party/WebKit/Source/core/inspector/InspectorWorkerAgent.h
@@ -63,7 +63,6 @@ // Called from Dispatcher protocol::Response setAutoAttach(bool auto_attach, bool wait_for_debugger_on_start) override; - protocol::Response setAttachToFrames(bool attach) override; protocol::Response sendMessageToTarget( const String& message, protocol::Maybe<String> session_id,
diff --git a/third_party/WebKit/Source/core/inspector/browser_protocol.json b/third_party/WebKit/Source/core/inspector/browser_protocol.json index a4cfce43..0e107ab43 100644 --- a/third_party/WebKit/Source/core/inspector/browser_protocol.json +++ b/third_party/WebKit/Source/core/inspector/browser_protocol.json
@@ -10128,6 +10128,12 @@ "description": "HTML template for the print footer. Should use the same format as the `headerTemplate`.", "optional": true, "type": "string" + }, + { + "name": "preferCSSPageSize", + "description": "Whether or not to prefer page size as defined by css. Defaults to false,\nin which case the content will be scaled to fit the paper size.", + "optional": true, + "type": "boolean" } ], "returns": [ @@ -11914,17 +11920,6 @@ ] }, { - "name": "setAttachToFrames", - "experimental": true, - "parameters": [ - { - "name": "value", - "description": "Whether to attach to frames.", - "type": "boolean" - } - ] - }, - { "name": "setAutoAttach", "description": "Controls whether to automatically attach to new targets which are considered to be related to\nthis one. When turned on, attaches to all existing related targets as well. When turned off,\nautomatically detaches from all currently attached targets.", "experimental": true,
diff --git a/third_party/WebKit/Source/core/inspector/browser_protocol.pdl b/third_party/WebKit/Source/core/inspector/browser_protocol.pdl index f5bfa88..b38ad1a 100644 --- a/third_party/WebKit/Source/core/inspector/browser_protocol.pdl +++ b/third_party/WebKit/Source/core/inspector/browser_protocol.pdl
@@ -4633,6 +4633,9 @@ optional string headerTemplate # HTML template for the print footer. Should use the same format as the `headerTemplate`. optional string footerTemplate + # Whether or not to prefer page size as defined by css. Defaults to false, + # in which case the content will be scaled to fit the paper size. + optional boolean preferCSSPageSize returns # Base64-encoded pdf data. string data @@ -5456,11 +5459,6 @@ # Deprecated. deprecated optional TargetID targetId - experimental command setAttachToFrames - parameters - # Whether to attach to frames. - boolean value - # Controls whether to automatically attach to new targets which are considered to be related to # this one. When turned on, attaches to all existing related targets as well. When turned off, # automatically detaches from all currently attached targets.
diff --git a/third_party/WebKit/Source/core/inspector/inspector_protocol_config.json b/third_party/WebKit/Source/core/inspector/inspector_protocol_config.json index 29e49586..99b781d 100644 --- a/third_party/WebKit/Source/core/inspector/inspector_protocol_config.json +++ b/third_party/WebKit/Source/core/inspector/inspector_protocol_config.json
@@ -101,7 +101,7 @@ }, { "domain": "Target", - "include": ["setAutoAttach", "sendMessageToTarget", "setAttachToFrames"], + "include": ["setAutoAttach", "sendMessageToTarget"], "include_events": ["attachedToTarget", "detachedFromTarget", "receivedMessageFromTarget"] } ]
diff --git a/third_party/WebKit/Source/core/layout/LayoutFlexibleBox.cpp b/third_party/WebKit/Source/core/layout/LayoutFlexibleBox.cpp index 5a7f59c0b..ddbd099 100644 --- a/third_party/WebKit/Source/core/layout/LayoutFlexibleBox.cpp +++ b/third_party/WebKit/Source/core/layout/LayoutFlexibleBox.cpp
@@ -382,6 +382,9 @@ LayoutFlexItems(relayout_children, layout_scope); if (PaintLayerScrollableArea::PreventRelayoutScope::RelayoutNeeded()) { + // Recompute the logical width, because children may have added or removed + // scrollbars. + UpdateLogicalWidthAndColumnWidth(); PaintLayerScrollableArea::FreezeScrollbarsScope freeze_scrollbars_scope; PrepareOrderIteratorAndMargins(); LayoutFlexItems(true, layout_scope);
diff --git a/third_party/WebKit/Source/core/layout/custom/LayoutWorkletGlobalScopeProxy.cpp b/third_party/WebKit/Source/core/layout/custom/LayoutWorkletGlobalScopeProxy.cpp index 1123d25..c0618f0 100644 --- a/third_party/WebKit/Source/core/layout/custom/LayoutWorkletGlobalScopeProxy.cpp +++ b/third_party/WebKit/Source/core/layout/custom/LayoutWorkletGlobalScopeProxy.cpp
@@ -32,8 +32,8 @@ document->Url(), document->UserAgent(), document->GetContentSecurityPolicy()->Headers().get(), document->GetReferrerPolicy(), document->GetSecurityOrigin(), - nullptr /* worker_clients */, document->AddressSpace(), - OriginTrialContext::GetTokens(document).get(), + document->IsSecureContext(), nullptr /* worker_clients */, + document->AddressSpace(), OriginTrialContext::GetTokens(document).get(), nullptr /* worker_settings */, kV8CacheOptionsDefault); global_scope_ = LayoutWorkletGlobalScope::Create(frame, std::move(creation_params), @@ -44,7 +44,7 @@ const KURL& module_url_record, WorkletModuleResponsesMap* module_responses_map, network::mojom::FetchCredentialsMode credentials_mode, - scoped_refptr<WebTaskRunner> outside_settings_task_runner, + scoped_refptr<base::SingleThreadTaskRunner> outside_settings_task_runner, WorkletPendingTasks* pending_tasks) { DCHECK(IsMainThread()); global_scope_->FetchAndInvokeScript(
diff --git a/third_party/WebKit/Source/core/layout/custom/LayoutWorkletGlobalScopeProxy.h b/third_party/WebKit/Source/core/layout/custom/LayoutWorkletGlobalScopeProxy.h index 4727d18..893d52e 100644 --- a/third_party/WebKit/Source/core/layout/custom/LayoutWorkletGlobalScopeProxy.h +++ b/third_party/WebKit/Source/core/layout/custom/LayoutWorkletGlobalScopeProxy.h
@@ -31,7 +31,7 @@ const KURL& module_url_record, WorkletModuleResponsesMap*, network::mojom::FetchCredentialsMode, - scoped_refptr<WebTaskRunner> outside_settings_task_runner, + scoped_refptr<base::SingleThreadTaskRunner> outside_settings_task_runner, WorkletPendingTasks*) override; void WorkletObjectDestroyed() override; void TerminateWorkletGlobalScope() override;
diff --git a/third_party/WebKit/Source/core/loader/BaseFetchContext.cpp b/third_party/WebKit/Source/core/loader/BaseFetchContext.cpp index 6907098..49c63cc 100644 --- a/third_party/WebKit/Source/core/loader/BaseFetchContext.cpp +++ b/third_party/WebKit/Source/core/loader/BaseFetchContext.cpp
@@ -206,6 +206,7 @@ break; case Resource::kXSLStyleSheet: DCHECK(RuntimeEnabledFeatures::XSLTEnabled()); + FALLTHROUGH; case Resource::kSVGDocument: if (!security_origin->CanRequest(url)) { PrintAccessDeniedMessage(url);
diff --git a/third_party/WebKit/Source/core/loader/DocumentLoader.cpp b/third_party/WebKit/Source/core/loader/DocumentLoader.cpp index 4717f7f..bd28e1be 100644 --- a/third_party/WebKit/Source/core/loader/DocumentLoader.cpp +++ b/third_party/WebKit/Source/core/loader/DocumentLoader.cpp
@@ -91,7 +91,6 @@ #include "platform/wtf/text/WTFString.h" #include "public/platform/Platform.h" #include "public/platform/modules/serviceworker/WebServiceWorkerNetworkProvider.h" -#include "public/web/WebDocumentLoader.h" #include "public/web/WebHistoryCommitType.h" namespace blink { @@ -417,7 +416,7 @@ switch (state_) { case kNotStarted: probe::frameClearedScheduledClientNavigation(frame_); - // Fall-through + FALLTHROUGH; case kProvisional: state_ = kSentDidFinishLoad; GetLocalFrameClient().DispatchDidFailProvisionalLoad(error, @@ -774,14 +773,15 @@ redirect_chain_.push_back(url); } -void DocumentLoader::DetachFromFrame() { - DCHECK(frame_); - - // It never makes sense to have a document loader that is detached from its - // frame have any loads active, so go ahead and kill all the loads. +void DocumentLoader::StopLoading() { fetcher_->StopFetching(); if (frame_ && !SentDidFinishLoad()) LoadFailed(ResourceError::CancelledError(Url())); +} + +void DocumentLoader::DetachFromFrame() { + DCHECK(frame_); + StopLoading(); fetcher_->ClearContext(); // If that load cancellation triggered another detach, leave. @@ -1040,9 +1040,6 @@ if (global_object_reuse_policy != WebGlobalObjectReusePolicy::kUseExisting) frame_->SetDOMWindow(LocalDOMWindow::Create(*frame_)); - bool user_gesture_bit_set = frame_->HasBeenActivated() || - frame_->HasReceivedUserGestureBeforeNavigation(); - if (reason == InstallNewDocumentReason::kNavigation) WillCommitNavigation(); @@ -1055,32 +1052,18 @@ .WithNewRegistrationContext(), false); - // Persist the user gesture state between frames. - bool user_gesture_before_value = false; - if (user_gesture_bit_set) { - user_gesture_before_value = WebDocumentLoader::ShouldPersistUserActivation( - WebSecurityOrigin(previous_security_origin), - WebSecurityOrigin(document->GetSecurityOrigin())); + // Clear the user activation state. + // TODO(crbug.com/736415): Clear this bit unconditionally for all frames. + if (frame_->IsMainFrame()) + frame_->ClearActivation(); - // Clear the user gesture bit that is not persisted. - // TODO(crbug.com/736415): Clear this bit unconditionally for all frames. - if (frame_->IsMainFrame()) - frame_->ClearActivation(); - } - - // If the load request was user activated, pretend that there was a gesture - // to carry over. - if (user_activated_) - user_gesture_before_value = true; - - // If the user gesture before navigation bit has changed then update it on the - // frame. - if (frame_->HasReceivedUserGestureBeforeNavigation() != - user_gesture_before_value) { - frame_->SetDocumentHasReceivedUserGestureBeforeNavigation( - user_gesture_before_value); + // The DocumentLoader was flagged as activated if it needs to notify the frame + // that it was activated before navigation. Update the frame state based on + // the new value. + if (frame_->HasReceivedUserGestureBeforeNavigation() != user_activated_) { + frame_->SetDocumentHasReceivedUserGestureBeforeNavigation(user_activated_); GetLocalFrameClient().SetHasReceivedUserGestureBeforeNavigation( - user_gesture_before_value); + user_activated_); } if (ShouldClearWindowName(*frame_, previous_security_origin, *document)) {
diff --git a/third_party/WebKit/Source/core/loader/DocumentLoader.h b/third_party/WebKit/Source/core/loader/DocumentLoader.h index 958d067..260c5ca 100644 --- a/third_party/WebKit/Source/core/loader/DocumentLoader.h +++ b/third_party/WebKit/Source/core/loader/DocumentLoader.h
@@ -172,6 +172,7 @@ HistoryItem* GetHistoryItem() const { return history_item_; } void StartLoading(); + void StopLoading(); DocumentLoadTiming& GetTiming() { return document_load_timing_; } const DocumentLoadTiming& GetTiming() const { return document_load_timing_; }
diff --git a/third_party/WebKit/Source/core/loader/EmptyClients.cpp b/third_party/WebKit/Source/core/loader/EmptyClients.cpp index 3ceaa1e..af47b1b 100644 --- a/third_party/WebKit/Source/core/loader/EmptyClients.cpp +++ b/third_party/WebKit/Source/core/loader/EmptyClients.cpp
@@ -63,7 +63,8 @@ public: EmptyFrameScheduler() { DCHECK(IsMainThread()); } - scoped_refptr<WebTaskRunner> GetTaskRunner(TaskType type) override { + scoped_refptr<base::SingleThreadTaskRunner> GetTaskRunner( + TaskType type) override { return Platform::Current()->MainThread()->GetWebTaskRunner(); }
diff --git a/third_party/WebKit/Source/core/loader/FrameFetchContext.cpp b/third_party/WebKit/Source/core/loader/FrameFetchContext.cpp index 54fc2e3..024b467f 100644 --- a/third_party/WebKit/Source/core/loader/FrameFetchContext.cpp +++ b/third_party/WebKit/Source/core/loader/FrameFetchContext.cpp
@@ -178,12 +178,6 @@ ResourceType::kIsNotMainResource, load_type); } -bool IsClientHintsAllowed(const KURL& url) { - return (url.ProtocolIs("http") || url.ProtocolIs("https")) && - (SecurityOrigin::IsSecure(url) || - SecurityOrigin::Create(url)->IsLocalhost()); -} - } // namespace struct FrameFetchContext::FrozenState final @@ -300,7 +294,8 @@ return frame; } -scoped_refptr<WebTaskRunner> FrameFetchContext::GetLoadingTaskRunner() { +scoped_refptr<base::SingleThreadTaskRunner> +FrameFetchContext::GetLoadingTaskRunner() { if (IsDetached()) return FetchContext::GetLoadingTaskRunner(); return GetFrame()->GetTaskRunner(TaskType::kNetworking); @@ -528,14 +523,11 @@ ->Loader() .GetProvisionalDocumentLoader()) { FrameClientHintsPreferencesContext hints_context(GetFrame()); - if (!blink::RuntimeEnabledFeatures::ClientHintsPersistentEnabled() || - IsClientHintsAllowed(response.Url())) { - // If the persistent client hint feature is enabled, then client hints - // should be allowed only on secure URLs. - document_loader_->GetClientHintsPreferences() - .UpdateFromAcceptClientHintsHeader( - response.HttpHeaderField(HTTPNames::Accept_CH), &hints_context); - } + document_loader_->GetClientHintsPreferences() + .UpdateFromAcceptClientHintsHeader( + response.HttpHeaderField(HTTPNames::Accept_CH), response.Url(), + &hints_context); + // When response is received with a provisional docloader, the resource // haven't committed yet, and we cannot load resources, only preconnect. resource_loading_policy = LinkLoader::kDoNotLoadResources; @@ -807,11 +799,6 @@ return document_ && document_->LoadEventFinished(); } -bool FrameFetchContext::PageDismissalEventBeingDispatched() const { - return document_ && document_->PageDismissalEventBeingDispatched() != - Document::kNoDismissal; -} - bool FrameFetchContext::UpdateTimingInfoForIFrameNavigation( ResourceTimingInfo* info) { if (IsDetached()) @@ -832,12 +819,6 @@ return true; } -void FrameFetchContext::SendImagePing(const KURL& url) { - if (IsDetached()) - return; - PingLoader::LoadImage(GetFrame(), url); -} - const SecurityOrigin* FrameFetchContext::GetSecurityOrigin() const { if (IsDetached()) return frozen_state_->security_origin.get(); @@ -862,7 +843,7 @@ if (blink::RuntimeEnabledFeatures::ClientHintsPersistentEnabled()) { // If the feature is enabled, then client hints are allowed only on secure // URLs. - if (!IsClientHintsAllowed(request.Url())) + if (!ClientHintsPreferences::IsClientHintsAllowed(request.Url())) return; // Check if |url| is allowed to run JavaScript. If not, client hints are not @@ -1195,9 +1176,6 @@ void FrameFetchContext::ParseAndPersistClientHints( const ResourceResponse& response) { - if (!IsClientHintsAllowed(response.Url())) - return; - ClientHintsPreferences hints_preferences; WebEnabledClientHints enabled_client_hints; TimeDelta persist_duration; @@ -1219,7 +1197,7 @@ std::unique_ptr<WebURLLoader> FrameFetchContext::CreateURLLoader( const ResourceRequest& request, - scoped_refptr<WebTaskRunner> task_runner) { + scoped_refptr<base::SingleThreadTaskRunner> task_runner) { DCHECK(!IsDetached()); WrappedResourceRequest webreq(request); if (MasterDocumentLoader()->GetServiceWorkerNetworkProvider()) {
diff --git a/third_party/WebKit/Source/core/loader/FrameFetchContext.h b/third_party/WebKit/Source/core/loader/FrameFetchContext.h index 50eaae87..45323efb 100644 --- a/third_party/WebKit/Source/core/loader/FrameFetchContext.h +++ b/third_party/WebKit/Source/core/loader/FrameFetchContext.h
@@ -31,10 +31,10 @@ #ifndef FrameFetchContext_h #define FrameFetchContext_h +#include "base/single_thread_task_runner.h" #include "core/CoreExport.h" #include "core/frame/csp/ContentSecurityPolicy.h" #include "core/loader/BaseFetchContext.h" -#include "platform/WebTaskRunner.h" #include "platform/heap/Handle.h" #include "platform/loader/fetch/ClientHintsPreferences.h" #include "platform/loader/fetch/FetchParameters.h" @@ -134,9 +134,7 @@ bool IsMainFrame() const override; bool DefersLoading() const override; bool IsLoadComplete() const override; - bool PageDismissalEventBeingDispatched() const override; bool UpdateTimingInfoForIFrameNavigation(ResourceTimingInfo*) override; - void SendImagePing(const KURL&) override; const SecurityOrigin* GetSecurityOrigin() const override; @@ -156,7 +154,7 @@ std::unique_ptr<WebURLLoader> CreateURLLoader( const ResourceRequest&, - scoped_refptr<WebTaskRunner>) override; + scoped_refptr<base::SingleThreadTaskRunner>) override; ResourceLoadScheduler::ThrottlingPolicy InitialLoadThrottlingPolicy() const override { @@ -192,7 +190,7 @@ // FetchContext overrides: WebFrameScheduler* GetFrameScheduler() const override; - scoped_refptr<WebTaskRunner> GetLoadingTaskRunner() override; + scoped_refptr<base::SingleThreadTaskRunner> GetLoadingTaskRunner() override; // BaseFetchContext overrides: KURL GetSiteForCookies() const override;
diff --git a/third_party/WebKit/Source/core/loader/FrameFetchContextTest.cpp b/third_party/WebKit/Source/core/loader/FrameFetchContextTest.cpp index b5fb9fa..547fa1c 100644 --- a/third_party/WebKit/Source/core/loader/FrameFetchContextTest.cpp +++ b/third_party/WebKit/Source/core/loader/FrameFetchContextTest.cpp
@@ -1383,12 +1383,6 @@ EXPECT_TRUE(fetch_context->IsLoadComplete()); } -TEST_F(FrameFetchContextTest, PageDismissalEventBeingDispatchedWhenDetached) { - dummy_page_holder = nullptr; - - EXPECT_FALSE(fetch_context->PageDismissalEventBeingDispatched()); -} - TEST_F(FrameFetchContextTest, UpdateTimingInfoForIFrameNavigationWhenDetached) { scoped_refptr<ResourceTimingInfo> info = ResourceTimingInfo::Create("type", 0.3, false); @@ -1399,15 +1393,6 @@ // Should not crash. } -TEST_F(FrameFetchContextTest, SendImagePingWhenDetached) { - const KURL url("https://www.example.com/"); - - dummy_page_holder = nullptr; - - fetch_context->SendImagePing(url); - // Should not crash. Nothing should be sent. -} - TEST_F(FrameFetchContextTest, AddConsoleMessageWhenDetached) { dummy_page_holder = nullptr;
diff --git a/third_party/WebKit/Source/core/loader/FrameLoader.cpp b/third_party/WebKit/Source/core/loader/FrameLoader.cpp index 03f1bbc..7746324 100644 --- a/third_party/WebKit/Source/core/loader/FrameLoader.cpp +++ b/third_party/WebKit/Source/core/loader/FrameLoader.cpp
@@ -988,7 +988,7 @@ if (in_stop_all_loaders_) return; - in_stop_all_loaders_ = true; + AutoReset<bool> in_stop_all_loaders(&in_stop_all_loaders_, true); for (Frame* child = frame_->Tree().FirstChild(); child; child = child->Tree().NextSibling()) { @@ -998,21 +998,11 @@ frame_->GetDocument()->CancelParsing(); if (document_loader_) - document_loader_->Fetcher()->StopFetching(); + document_loader_->StopLoading(); if (!protect_provisional_loader_) DetachDocumentLoader(provisional_document_loader_); - frame_->GetNavigationScheduler().Cancel(); - - // It's possible that the above actions won't have stopped loading if load - // completion had been blocked on parsing or if we were in the middle of - // committing an empty document. In that case, emulate a failed navigation. - if (document_loader_ && !document_loader_->SentDidFinishLoad()) { - document_loader_->LoadFailed( - ResourceError::CancelledError(document_loader_->Url())); - } - - in_stop_all_loaders_ = false; + DidFinishNavigation(); TakeObjectSnapshot(); }
diff --git a/third_party/WebKit/Source/core/loader/HttpEquiv.cpp b/third_party/WebKit/Source/core/loader/HttpEquiv.cpp index 089795ea..93eb51c 100644 --- a/third_party/WebKit/Source/core/loader/HttpEquiv.cpp +++ b/third_party/WebKit/Source/core/loader/HttpEquiv.cpp
@@ -95,7 +95,7 @@ UseCounter::Count(document, WebFeature::kClientHintsMetaAcceptCH); FrameClientHintsPreferencesContext hints_context(document.GetFrame()); document.GetClientHintsPreferences().UpdateFromAcceptClientHintsHeader( - content, &hints_context); + content, document.Url(), &hints_context); } void HttpEquiv::ProcessHttpEquivDefaultStyle(Document& document,
diff --git a/third_party/WebKit/Source/core/loader/IdlenessDetector.cpp b/third_party/WebKit/Source/core/loader/IdlenessDetector.cpp index 54544ed3..32cadd38 100644 --- a/third_party/WebKit/Source/core/loader/IdlenessDetector.cpp +++ b/third_party/WebKit/Source/core/loader/IdlenessDetector.cpp
@@ -15,14 +15,19 @@ namespace blink { +const TimeDelta IdlenessDetector::kNetworkQuietWindow; +const TimeDelta IdlenessDetector::kNetworkQuietWatchdog; + void IdlenessDetector::Shutdown() { Stop(); local_frame_ = nullptr; } void IdlenessDetector::WillCommitLoad() { - network_2_quiet_ = -1; - network_0_quiet_ = -1; + in_network_2_quiet_period_ = false; + in_network_0_quiet_period_ = false; + network_2_quiet_ = TimeTicks(); + network_0_quiet_ = TimeTicks(); network_2_quiet_start_time_ = TimeTicks(); network_0_quiet_start_time_ = TimeTicks(); } @@ -36,8 +41,10 @@ task_observer_added_ = true; } - network_2_quiet_ = 0; - network_0_quiet_ = 0; + in_network_2_quiet_period_ = true; + in_network_0_quiet_period_ = true; + network_2_quiet_ = TimeTicks(); + network_0_quiet_ = TimeTicks(); if (::resource_coordinator::IsPageAlmostIdleSignalEnabled()) { if (auto* frame_resource_coordinator = @@ -59,10 +66,10 @@ // fetcher, thus we need to add 1 as the total request count. int request_count = fetcher->ActiveRequestCount() + 1; // If we are above the allowed number of active requests, reset timers. - if (network_2_quiet_ >= 0 && request_count > 2) - network_2_quiet_ = 0; - if (network_0_quiet_ >= 0 && request_count > 0) - network_0_quiet_ = 0; + if (in_network_2_quiet_period_ && request_count > 2) + network_2_quiet_ = TimeTicks(); + if (in_network_0_quiet_period_ && request_count > 0) + network_0_quiet_ = TimeTicks(); } // This function is called when the number of active connections is decreased. @@ -77,7 +84,7 @@ return; // If we already reported quiet time, bail out. - if (network_0_quiet_ < 0 && network_2_quiet_ < 0) + if (!in_network_0_quiet_period_ && !in_network_2_quiet_period_) return; int request_count = @@ -87,25 +94,25 @@ return; TimeTicks timestamp = CurrentTimeTicks(); - double timestamp_seconds = TimeTicksInSeconds(timestamp); // Arriving at =2 updates the quiet_2 base timestamp. // Arriving at <2 sets the quiet_2 base timestamp only if // it was not already set. - if (request_count == 2 && network_2_quiet_ >= 0) { - network_2_quiet_ = timestamp_seconds; + if (request_count == 2 && in_network_2_quiet_period_) { + network_2_quiet_ = timestamp; network_2_quiet_start_time_ = timestamp; - } else if (request_count < 2 && network_2_quiet_ == 0) { - network_2_quiet_ = timestamp_seconds; + } else if (request_count < 2 && in_network_2_quiet_period_ && + network_2_quiet_.is_null()) { + network_2_quiet_ = timestamp; network_2_quiet_start_time_ = timestamp; } - if (request_count == 0 && network_0_quiet_ >= 0) { - network_0_quiet_ = timestamp_seconds; + if (request_count == 0 && in_network_0_quiet_period_) { + network_0_quiet_ = timestamp; network_0_quiet_start_time_ = timestamp; } if (!network_quiet_timer_.IsActive()) { - network_quiet_timer_.StartOneShot(kNetworkQuietWatchdogSeconds, FROM_HERE); + network_quiet_timer_.StartOneShot(kNetworkQuietWatchdog, FROM_HERE); } } @@ -117,12 +124,13 @@ return network_0_quiet_start_time_; } -void IdlenessDetector::WillProcessTask(double start_time) { - // If we have idle time and we are kNetworkQuietWindowSeconds seconds past it, - // emit idle signals. +void IdlenessDetector::WillProcessTask(double start_time_seconds) { + // If we have idle time and we are kNetworkQuietWindow seconds past it, emit + // idle signals. + TimeTicks start_time = TimeTicksFromSeconds(start_time_seconds); DocumentLoader* loader = local_frame_->Loader().GetDocumentLoader(); - if (network_2_quiet_ > 0 && - start_time - network_2_quiet_ > kNetworkQuietWindowSeconds) { + if (in_network_2_quiet_period_ && !network_2_quiet_.is_null() && + start_time - network_2_quiet_ > kNetworkQuietWindow) { probe::lifecycleEvent(local_frame_, loader, "networkAlmostIdle", TimeTicksInSeconds(network_2_quiet_start_time_)); if (::resource_coordinator::IsPageAlmostIdleSignalEnabled()) { @@ -132,25 +140,31 @@ } } local_frame_->GetDocument()->Fetcher()->OnNetworkQuiet(); - network_2_quiet_ = -1; + in_network_2_quiet_period_ = false; + network_2_quiet_ = TimeTicks(); } - if (network_0_quiet_ > 0 && - start_time - network_0_quiet_ > kNetworkQuietWindowSeconds) { + if (in_network_0_quiet_period_ && !network_0_quiet_.is_null() && + start_time - network_0_quiet_ > kNetworkQuietWindow) { probe::lifecycleEvent(local_frame_, loader, "networkIdle", TimeTicksInSeconds(network_0_quiet_start_time_)); - network_0_quiet_ = -1; + in_network_0_quiet_period_ = false; + network_0_quiet_ = TimeTicks(); } - if (network_0_quiet_ < 0 && network_2_quiet_ < 0) + if (!in_network_0_quiet_period_ && !in_network_2_quiet_period_) Stop(); } -void IdlenessDetector::DidProcessTask(double start_time, double end_time) { +void IdlenessDetector::DidProcessTask(double start_time_seconds, + double end_time_seconds) { + TimeTicks start_time = TimeTicksFromSeconds(start_time_seconds); + TimeTicks end_time = TimeTicksFromSeconds(end_time_seconds); + // Shift idle timestamps with the duration of the task, we were not idle. - if (network_2_quiet_ > 0) + if (in_network_2_quiet_period_ && !network_2_quiet_.is_null()) network_2_quiet_ += end_time - start_time; - if (network_0_quiet_ > 0) + if (in_network_0_quiet_period_ && !network_0_quiet_.is_null()) network_0_quiet_ += end_time - start_time; } @@ -171,8 +185,9 @@ void IdlenessDetector::NetworkQuietTimerFired(TimerBase*) { // TODO(lpy) Reduce the number of timers. - if (network_0_quiet_ > 0 || network_2_quiet_ > 0) { - network_quiet_timer_.StartOneShot(kNetworkQuietWatchdogSeconds, FROM_HERE); + if ((in_network_0_quiet_period_ && !network_0_quiet_.is_null()) || + (in_network_2_quiet_period_ && !network_2_quiet_.is_null())) { + network_quiet_timer_.StartOneShot(kNetworkQuietWatchdog, FROM_HERE); } }
diff --git a/third_party/WebKit/Source/core/loader/IdlenessDetector.h b/third_party/WebKit/Source/core/loader/IdlenessDetector.h index 73d1637..054576ee 100644 --- a/third_party/WebKit/Source/core/loader/IdlenessDetector.h +++ b/third_party/WebKit/Source/core/loader/IdlenessDetector.h
@@ -45,8 +45,9 @@ // The page is quiet if there are no more than 2 active network requests for // this duration of time. - static constexpr double kNetworkQuietWindowSeconds = 0.5; - static constexpr double kNetworkQuietWatchdogSeconds = 2; + static constexpr TimeDelta kNetworkQuietWindow = + TimeDelta::FromMilliseconds(500); + static constexpr TimeDelta kNetworkQuietWatchdog = TimeDelta::FromSeconds(2); static constexpr int kNetworkQuietMaximumConnections = 2; // scheduler::TaskTimeObserver implementation @@ -58,9 +59,13 @@ Member<LocalFrame> local_frame_; bool task_observer_added_; + + bool in_network_0_quiet_period_ = true; + bool in_network_2_quiet_period_ = true; + // Store the accumulated time of network quiet. - double network_0_quiet_ = 0; - double network_2_quiet_ = 0; + TimeTicks network_0_quiet_; + TimeTicks network_2_quiet_; // Record the actual start time of network quiet. TimeTicks network_0_quiet_start_time_; TimeTicks network_2_quiet_start_time_;
diff --git a/third_party/WebKit/Source/core/loader/IdlenessDetectorTest.cpp b/third_party/WebKit/Source/core/loader/IdlenessDetectorTest.cpp index 8d75760b..c1c14227 100644 --- a/third_party/WebKit/Source/core/loader/IdlenessDetectorTest.cpp +++ b/third_party/WebKit/Source/core/loader/IdlenessDetectorTest.cpp
@@ -25,12 +25,8 @@ } bool HadNetworkQuiet() { - return Detector()->network_2_quiet_ == -1 && - Detector()->network_0_quiet_ == -1; - } - - double NetworkQuietStartTime() { - return TimeTicksInSeconds(Detector()->network_2_quiet_start_time_); + return !Detector()->in_network_2_quiet_period_ && + !Detector()->in_network_0_quiet_period_; } void WillProcessTask(double start_time) {
diff --git a/third_party/WebKit/Source/core/loader/ImageLoader.cpp b/third_party/WebKit/Source/core/loader/ImageLoader.cpp index b259fd52..3edd3212 100644 --- a/third_party/WebKit/Source/core/loader/ImageLoader.cpp +++ b/third_party/WebKit/Source/core/loader/ImageLoader.cpp
@@ -395,6 +395,16 @@ !GetElement()->FastGetAttribute(HTMLNames::srcsetAttr).IsNull()) resource_request.SetRequestContext( WebURLRequest::kRequestContextImageSet); + + bool page_is_being_dismissed = + document.PageDismissalEventBeingDispatched() != Document::kNoDismissal; + if (page_is_being_dismissed) { + resource_request.SetHTTPHeaderField(HTTPNames::Cache_Control, + "max-age=0"); + resource_request.SetKeepalive(true); + resource_request.SetRequestContext(WebURLRequest::kRequestContextPing); + } + FetchParameters params(resource_request, resource_loader_options); ConfigureRequest(params, bypass_behavior, *element_, document.GetClientHintsPreferences()); @@ -403,6 +413,12 @@ document.GetFrame()->MaybeAllowImagePlaceholder(params); new_image_content = ImageResourceContent::Fetch(params, document.Fetcher()); + + // If this load is starting while navigating away, treat it as an auditing + // keepalive request, and don't report its results back to the element. + if (page_is_being_dismissed) + new_image_content = nullptr; + ClearFailedLoadURL(); } else { if (!image_source_url.IsNull()) {
diff --git a/third_party/WebKit/Source/core/loader/LinkLoader.cpp b/third_party/WebKit/Source/core/loader/LinkLoader.cpp index dddf96b..1b4c8b8 100644 --- a/third_party/WebKit/Source/core/loader/LinkLoader.cpp +++ b/third_party/WebKit/Source/core/loader/LinkLoader.cpp
@@ -125,7 +125,7 @@ }; LinkLoader::LinkLoader(LinkLoaderClient* client, - scoped_refptr<WebTaskRunner> task_runner) + scoped_refptr<base::SingleThreadTaskRunner> task_runner) : client_(client) { DCHECK(client_); }
diff --git a/third_party/WebKit/Source/core/loader/LinkLoader.h b/third_party/WebKit/Source/core/loader/LinkLoader.h index 71842aa..4b30ce3 100644 --- a/third_party/WebKit/Source/core/loader/LinkLoader.h +++ b/third_party/WebKit/Source/core/loader/LinkLoader.h
@@ -106,7 +106,7 @@ private: class FinishObserver; - LinkLoader(LinkLoaderClient*, scoped_refptr<WebTaskRunner>); + LinkLoader(LinkLoaderClient*, scoped_refptr<base::SingleThreadTaskRunner>); void NotifyFinished(); // SingleModuleClient implementation
diff --git a/third_party/WebKit/Source/core/loader/LinkLoaderClient.h b/third_party/WebKit/Source/core/loader/LinkLoaderClient.h index 7e9489e..321fdee 100644 --- a/third_party/WebKit/Source/core/loader/LinkLoaderClient.h +++ b/third_party/WebKit/Source/core/loader/LinkLoaderClient.h
@@ -31,8 +31,8 @@ #ifndef LinkLoaderClient_h #define LinkLoaderClient_h +#include "base/single_thread_task_runner.h" #include "core/CoreExport.h" -#include "platform/WebTaskRunner.h" #include "platform/heap/Handle.h" @@ -54,7 +54,8 @@ virtual void DidSendLoadForLinkPrerender() = 0; virtual void DidSendDOMContentLoadedForLinkPrerender() = 0; - virtual scoped_refptr<WebTaskRunner> GetLoadingTaskRunner() = 0; + virtual scoped_refptr<base::SingleThreadTaskRunner> + GetLoadingTaskRunner() = 0; }; } // namespace blink
diff --git a/third_party/WebKit/Source/core/loader/LinkLoaderTest.cpp b/third_party/WebKit/Source/core/loader/LinkLoaderTest.cpp index a1332921..024655e 100644 --- a/third_party/WebKit/Source/core/loader/LinkLoaderTest.cpp +++ b/third_party/WebKit/Source/core/loader/LinkLoaderTest.cpp
@@ -50,7 +50,7 @@ void DidSendLoadForLinkPrerender() override {} void DidSendDOMContentLoadedForLinkPrerender() override {} - scoped_refptr<WebTaskRunner> GetLoadingTaskRunner() override { + scoped_refptr<base::SingleThreadTaskRunner> GetLoadingTaskRunner() override { return Platform::Current()->CurrentThread()->GetWebTaskRunner(); }
diff --git a/third_party/WebKit/Source/core/loader/PingLoader.cpp b/third_party/WebKit/Source/core/loader/PingLoader.cpp index 064dca99..0979b32 100644 --- a/third_party/WebKit/Source/core/loader/PingLoader.cpp +++ b/third_party/WebKit/Source/core/loader/PingLoader.cpp
@@ -208,20 +208,6 @@ } // namespace -void PingLoader::LoadImage(LocalFrame* frame, const KURL& url) { - ResourceRequest request(url); - request.SetHTTPHeaderField(HTTPNames::Cache_Control, "max-age=0"); - request.SetKeepalive(true); - request.SetRequestContext(WebURLRequest::kRequestContextPing); - FetchParameters params(request); - params.MutableOptions().initiator_info.name = FetchInitiatorTypeNames::ping; - // TODO(mkwst): Reevaluate this. - params.SetContentSecurityCheck(kDoNotCheckContentSecurityPolicy); - - frame->Client()->DidDispatchPingLoader(request.Url()); - RawResource::Fetch(params, frame->GetDocument()->Fetcher(), nullptr); -} - // http://www.whatwg.org/specs/web-apps/current-work/multipage/links.html#hyperlink-auditing void PingLoader::SendLinkAuditPing(LocalFrame* frame, const KURL& ping_url,
diff --git a/third_party/WebKit/Source/core/loader/PingLoader.h b/third_party/WebKit/Source/core/loader/PingLoader.h index af96198..6be5d08 100644 --- a/third_party/WebKit/Source/core/loader/PingLoader.h +++ b/third_party/WebKit/Source/core/loader/PingLoader.h
@@ -65,7 +65,6 @@ kXSSAuditorViolationReport }; - static void LoadImage(LocalFrame*, const KURL&); static void SendLinkAuditPing(LocalFrame*, const KURL& ping_url, const KURL& destination_url);
diff --git a/third_party/WebKit/Source/core/loader/PingLoaderTest.cpp b/third_party/WebKit/Source/core/loader/PingLoaderTest.cpp index 6448d1a..6d7ee0f 100644 --- a/third_party/WebKit/Source/core/loader/PingLoaderTest.cpp +++ b/third_party/WebKit/Source/core/loader/PingLoaderTest.cpp
@@ -103,20 +103,6 @@ ASSERT_TRUE(ping_request.IsNull()); } -TEST_F(PingLoaderTest, LoadImagePriority) { - SetDocumentURL(KURL("http://localhost/foo.html")); - - KURL ping_url("https://localhost/bar.html"); - URLTestHelpers::RegisterMockedURLLoad( - ping_url, testing::CoreTestDataPath("bar.html"), "text/html"); - PingLoader::LoadImage(&page_holder_->GetFrame(), ping_url); - Platform::Current()->GetURLLoaderMockFactory()->ServeAsynchronousRequests(); - const ResourceRequest& request = client_->PingRequest(); - ASSERT_FALSE(request.IsNull()); - ASSERT_EQ(request.Url(), ping_url); - EXPECT_EQ(ResourceLoadPriority::kVeryLow, request.Priority()); -} - TEST_F(PingLoaderTest, LinkAuditPingPriority) { KURL destination_url("http://navigation.destination"); SetDocumentURL(KURL("http://localhost/foo.html"));
diff --git a/third_party/WebKit/Source/core/loader/SubresourceFilter.cpp b/third_party/WebKit/Source/core/loader/SubresourceFilter.cpp index 9fc5171..bf9e1e98 100644 --- a/third_party/WebKit/Source/core/loader/SubresourceFilter.cpp +++ b/third_party/WebKit/Source/core/loader/SubresourceFilter.cpp
@@ -7,12 +7,12 @@ #include <utility> #include "base/location.h" +#include "base/single_thread_task_runner.h" #include "core/dom/Document.h" #include "core/frame/LocalFrame.h" #include "core/inspector/ConsoleMessage.h" #include "core/loader/DocumentLoader.h" #include "core/workers/WorkerOrWorkletGlobalScope.h" -#include "platform/WebTaskRunner.h" #include "platform/weborigin/KURL.h" #include "platform/wtf/text/StringBuilder.h" #include "public/platform/TaskType.h" @@ -74,7 +74,7 @@ // thread. Note that this unconditionally calls reportLoad unlike allowLoad, // because there aren't developer-invisible connections (like speculative // preloads) happening here. - scoped_refptr<WebTaskRunner> task_runner = + scoped_refptr<base::SingleThreadTaskRunner> task_runner = execution_context_->GetTaskRunner(TaskType::kNetworking); DCHECK(task_runner->RunsTasksInCurrentSequence()); task_runner->PostTask( @@ -102,7 +102,7 @@ kOtherMessageSource, kErrorMessageLevel, GetErrorStringForDisallowedLoad(resource_url))); } - // fall through + FALLTHROUGH; case WebDocumentSubresourceFilter::kWouldDisallow: // TODO(csharrison): Consider posting a task to the main thread from // worker thread, or adding support for DidObserveLoadingBehavior to
diff --git a/third_party/WebKit/Source/core/loader/ThreadableLoaderTest.cpp b/third_party/WebKit/Source/core/loader/ThreadableLoaderTest.cpp index 9db8df0..21e26430 100644 --- a/third_party/WebKit/Source/core/loader/ThreadableLoaderTest.cpp +++ b/third_party/WebKit/Source/core/loader/ThreadableLoaderTest.cpp
@@ -423,7 +423,7 @@ std::unique_ptr<DummyPageHolder> dummy_page_holder_; // Accessed cross-thread when worker thread posts tasks to the parent. CrossThreadPersistent<ParentFrameTaskRunners> parent_frame_task_runners_; - scoped_refptr<WebTaskRunner> worker_loading_task_runner_; + scoped_refptr<base::SingleThreadTaskRunner> worker_loading_task_runner_; Checkpoint checkpoint_; // |m_loader| must be touched only from the worker thread only. CrossThreadPersistent<ThreadableLoader> loader_;
diff --git a/third_party/WebKit/Source/core/loader/WorkerFetchContext.cpp b/third_party/WebKit/Source/core/loader/WorkerFetchContext.cpp index 5d607fa2..3e04453 100644 --- a/third_party/WebKit/Source/core/loader/WorkerFetchContext.cpp +++ b/third_party/WebKit/Source/core/loader/WorkerFetchContext.cpp
@@ -4,6 +4,7 @@ #include "core/loader/WorkerFetchContext.h" +#include "base/single_thread_task_runner.h" #include "core/frame/Deprecation.h" #include "core/frame/UseCounter.h" #include "core/loader/MixedContentChecker.h" @@ -13,7 +14,6 @@ #include "core/workers/WorkerClients.h" #include "core/workers/WorkerGlobalScope.h" #include "platform/Supplementable.h" -#include "platform/WebTaskRunner.h" #include "platform/exported/WrappedResourceRequest.h" #include "platform/loader/fetch/ResourceFetcher.h" #include "platform/network/NetworkStateNotifier.h" @@ -222,7 +222,7 @@ std::unique_ptr<WebURLLoader> WorkerFetchContext::CreateURLLoader( const ResourceRequest& request, - scoped_refptr<WebTaskRunner> task_runner) { + scoped_refptr<base::SingleThreadTaskRunner> task_runner) { CountUsage(WebFeature::kOffMainThreadFetch); if (!url_loader_factory_) url_loader_factory_ = web_context_->CreateURLLoaderFactory(); @@ -351,7 +351,8 @@ out_request.SetRequestorOrigin(GetSecurityOrigin()); } -scoped_refptr<WebTaskRunner> WorkerFetchContext::GetLoadingTaskRunner() { +scoped_refptr<base::SingleThreadTaskRunner> +WorkerFetchContext::GetLoadingTaskRunner() { return loading_task_runner_; }
diff --git a/third_party/WebKit/Source/core/loader/WorkerFetchContext.h b/third_party/WebKit/Source/core/loader/WorkerFetchContext.h index 1ae62d5..5cf3b53 100644 --- a/third_party/WebKit/Source/core/loader/WorkerFetchContext.h +++ b/third_party/WebKit/Source/core/loader/WorkerFetchContext.h
@@ -6,9 +6,9 @@ #define WorkerFetchContext_h #include <memory> +#include "base/single_thread_task_runner.h" #include "core/CoreExport.h" #include "core/loader/BaseFetchContext.h" -#include "platform/WebTaskRunner.h" #include "platform/wtf/Forward.h" #include "services/network/public/interfaces/request_context_frame_type.mojom-blink.h" @@ -67,7 +67,7 @@ const SecurityOrigin* GetSecurityOrigin() const override; std::unique_ptr<WebURLLoader> CreateURLLoader( const ResourceRequest&, - scoped_refptr<WebTaskRunner>) override; + scoped_refptr<base::SingleThreadTaskRunner>) override; void PrepareRequest(ResourceRequest&, RedirectType) override; bool IsControlledByServiceWorker() const override; int ApplicationCacheHostID() const override; @@ -104,7 +104,7 @@ const FetchParameters::ResourceWidth&, ResourceRequest&) override; void SetFirstPartyCookieAndRequestorOrigin(ResourceRequest&) override; - scoped_refptr<WebTaskRunner> GetLoadingTaskRunner() override; + scoped_refptr<base::SingleThreadTaskRunner> GetLoadingTaskRunner() override; void Trace(blink::Visitor*) override; @@ -117,7 +117,7 @@ std::unique_ptr<WebURLLoaderFactory> url_loader_factory_; Member<SubresourceFilter> subresource_filter_; Member<ResourceFetcher> resource_fetcher_; - scoped_refptr<WebTaskRunner> loading_task_runner_; + scoped_refptr<base::SingleThreadTaskRunner> loading_task_runner_; // The value of |save_data_enabled_| is read once per frame from // NetworkStateNotifier, which is guarded by a mutex lock, and cached locally
diff --git a/third_party/WebKit/Source/core/loader/WorkerThreadableLoader.cpp b/third_party/WebKit/Source/core/loader/WorkerThreadableLoader.cpp index bffef07..822b181e 100644 --- a/third_party/WebKit/Source/core/loader/WorkerThreadableLoader.cpp +++ b/third_party/WebKit/Source/core/loader/WorkerThreadableLoader.cpp
@@ -69,7 +69,7 @@ : public WorkerThreadableLoader::TaskForwarder { public: explicit AsyncTaskForwarder( - scoped_refptr<WebTaskRunner> worker_loading_task_runner) + scoped_refptr<base::SingleThreadTaskRunner> worker_loading_task_runner) : worker_loading_task_runner_(std::move(worker_loading_task_runner)) { DCHECK(IsMainThread()); } @@ -90,7 +90,7 @@ void Abort() override { DCHECK(IsMainThread()); } private: - scoped_refptr<WebTaskRunner> worker_loading_task_runner_; + scoped_refptr<base::SingleThreadTaskRunner> worker_loading_task_runner_; }; struct WorkerThreadableLoader::TaskWithLocation final { @@ -236,7 +236,7 @@ event_with_tasks = WaitableEventWithTasks::Create(); WorkerThread* worker_thread = worker_global_scope_->GetThread(); - scoped_refptr<WebTaskRunner> worker_loading_task_runner = + scoped_refptr<base::SingleThreadTaskRunner> worker_loading_task_runner = worker_global_scope_->GetTaskRunner(TaskType::kUnspecedLoading); PostCrossThreadTask( *parent_frame_task_runners_->Get(TaskType::kUnspecedLoading), FROM_HERE, @@ -427,7 +427,7 @@ void WorkerThreadableLoader::MainThreadLoaderHolder::CreateAndStart( WorkerThreadableLoader* worker_loader, ThreadableLoadingContext* loading_context, - scoped_refptr<WebTaskRunner> worker_loading_task_runner, + scoped_refptr<base::SingleThreadTaskRunner> worker_loading_task_runner, WorkerThreadLifecycleContext* worker_thread_lifecycle_context, std::unique_ptr<CrossThreadResourceRequestData> request, const ThreadableLoaderOptions& options,
diff --git a/third_party/WebKit/Source/core/loader/WorkerThreadableLoader.h b/third_party/WebKit/Source/core/loader/WorkerThreadableLoader.h index c8e45c8..624b06c 100644 --- a/third_party/WebKit/Source/core/loader/WorkerThreadableLoader.h +++ b/third_party/WebKit/Source/core/loader/WorkerThreadableLoader.h
@@ -128,7 +128,7 @@ public: static void CreateAndStart(WorkerThreadableLoader*, ThreadableLoadingContext*, - scoped_refptr<WebTaskRunner>, + scoped_refptr<base::SingleThreadTaskRunner>, WorkerThreadLifecycleContext*, std::unique_ptr<CrossThreadResourceRequestData>, const ThreadableLoaderOptions&,
diff --git a/third_party/WebKit/Source/core/loader/modulescript/ModuleScriptLoaderTest.cpp b/third_party/WebKit/Source/core/loader/modulescript/ModuleScriptLoaderTest.cpp index a453659..63d9d5986 100644 --- a/third_party/WebKit/Source/core/loader/modulescript/ModuleScriptLoaderTest.cpp +++ b/third_party/WebKit/Source/core/loader/modulescript/ModuleScriptLoaderTest.cpp
@@ -178,7 +178,8 @@ GetDocument().Url(), GetDocument().UserAgent(), nullptr /* content_security_policy_parsed_headers */, GetDocument().GetReferrerPolicy(), GetDocument().GetSecurityOrigin(), - nullptr /* worker_clients */, GetDocument().AddressSpace(), + GetDocument().IsSecureContext(), nullptr /* worker_clients */, + GetDocument().AddressSpace(), OriginTrialContext::GetTokens(&GetDocument()).get(), nullptr /* worker_settings */, kV8CacheOptionsDefault); global_scope_ = new MainThreadWorkletGlobalScope(
diff --git a/third_party/WebKit/Source/core/loader/modulescript/ModuleTreeLinker.cpp b/third_party/WebKit/Source/core/loader/modulescript/ModuleTreeLinker.cpp index b6034d8b..feed9a8 100644 --- a/third_party/WebKit/Source/core/loader/modulescript/ModuleTreeLinker.cpp +++ b/third_party/WebKit/Source/core/loader/modulescript/ModuleTreeLinker.cpp
@@ -8,7 +8,6 @@ #include "core/loader/modulescript/ModuleScriptFetchRequest.h" #include "core/loader/modulescript/ModuleTreeLinkerRegistry.h" #include "core/script/ModuleScript.h" -#include "platform/WebTaskRunner.h" #include "platform/bindings/V8ThrowException.h" #include "platform/loader/fetch/ResourceLoadingLog.h" #include "platform/wtf/Vector.h"
diff --git a/third_party/WebKit/Source/core/loader/resource/FontResource.cpp b/third_party/WebKit/Source/core/loader/resource/FontResource.cpp index 0339bbc..aa13b93 100644 --- a/third_party/WebKit/Source/core/loader/resource/FontResource.cpp +++ b/third_party/WebKit/Source/core/loader/resource/FontResource.cpp
@@ -119,7 +119,8 @@ Resource::SetRevalidatingRequest(request); } -void FontResource::StartLoadLimitTimers(WebTaskRunner* task_runner) { +void FontResource::StartLoadLimitTimers( + base::SingleThreadTaskRunner* task_runner) { DCHECK(IsLoading()); DCHECK_EQ(load_limit_state_, kLoadNotStarted); load_limit_state_ = kUnderLimit;
diff --git a/third_party/WebKit/Source/core/loader/resource/FontResource.h b/third_party/WebKit/Source/core/loader/resource/FontResource.h index 6bdb6522..40fdd696 100644 --- a/third_party/WebKit/Source/core/loader/resource/FontResource.h +++ b/third_party/WebKit/Source/core/loader/resource/FontResource.h
@@ -28,6 +28,7 @@ #include "base/gtest_prod_util.h" #include "base/memory/scoped_refptr.h" +#include "base/single_thread_task_runner.h" #include "core/CoreExport.h" #include "platform/WebTaskRunner.h" #include "platform/heap/Handle.h" @@ -53,7 +54,7 @@ void SetRevalidatingRequest(const ResourceRequest&) override; void AllClientsAndObserversRemoved() override; - void StartLoadLimitTimers(WebTaskRunner*); + void StartLoadLimitTimers(base::SingleThreadTaskRunner*); String OtsParsingMessage() const { return ots_parsing_message_; }
diff --git a/third_party/WebKit/Source/core/loader/resource/ImageResource.cpp b/third_party/WebKit/Source/core/loader/resource/ImageResource.cpp index eaa2c91..0ac1b12 100644 --- a/third_party/WebKit/Source/core/loader/resource/ImageResource.cpp +++ b/third_party/WebKit/Source/core/loader/resource/ImageResource.cpp
@@ -169,23 +169,6 @@ WebURLRequest::kRequestContextUnspecified) { params.SetRequestContext(WebURLRequest::kRequestContextImage); } - if (fetcher->Context().PageDismissalEventBeingDispatched()) { - KURL request_url = params.GetResourceRequest().Url(); - if (request_url.IsValid()) { - ResourceRequestBlockedReason block_reason = fetcher->Context().CanRequest( - Resource::kImage, params.GetResourceRequest(), request_url, - params.Options(), - /* Don't send security violation reports for speculative preloads */ - params.IsSpeculativePreload() - ? SecurityViolationReportingPolicy::kSuppressReporting - : SecurityViolationReportingPolicy::kReport, - params.GetOriginRestriction(), - params.GetResourceRequest().GetRedirectStatus()); - if (block_reason == ResourceRequestBlockedReason::kNone) - fetcher->Context().SendImagePing(request_url); - } - return nullptr; - } ImageResource* resource = ToImageResource( fetcher->RequestResource(params, ImageResourceFactory(params), nullptr)); @@ -420,7 +403,7 @@ } void ImageResource::Finish(double load_finish_time, - WebTaskRunner* task_runner) { + base::SingleThreadTaskRunner* task_runner) { if (multipart_parser_) { multipart_parser_->Finish(); if (Data()) @@ -438,7 +421,7 @@ } void ImageResource::FinishAsError(const ResourceError& error, - WebTaskRunner* task_runner) { + base::SingleThreadTaskRunner* task_runner) { if (multipart_parser_) multipart_parser_->Cancel(); // TODO(hiroshige): Move setEncodedSize() call to Resource::error() if it
diff --git a/third_party/WebKit/Source/core/loader/resource/ImageResource.h b/third_party/WebKit/Source/core/loader/resource/ImageResource.h index 183deca..23454c8 100644 --- a/third_party/WebKit/Source/core/loader/resource/ImageResource.h +++ b/third_party/WebKit/Source/core/loader/resource/ImageResource.h
@@ -86,8 +86,9 @@ void ResponseReceived(const ResourceResponse&, std::unique_ptr<WebDataConsumerHandle>) override; void AppendData(const char*, size_t) override; - void Finish(double finish_time, WebTaskRunner*) override; - void FinishAsError(const ResourceError&, WebTaskRunner*) override; + void Finish(double finish_time, base::SingleThreadTaskRunner*) override; + void FinishAsError(const ResourceError&, + base::SingleThreadTaskRunner*) override; // For compatibility, images keep loading even if there are HTTP errors. bool ShouldIgnoreHTTPStatusCodeErrors() const override { return true; }
diff --git a/third_party/WebKit/Source/core/messaging/BlinkCloneableMessageStructTraits.cpp b/third_party/WebKit/Source/core/messaging/BlinkCloneableMessageStructTraits.cpp index a2e66e3..ec45131e 100644 --- a/third_party/WebKit/Source/core/messaging/BlinkCloneableMessageStructTraits.cpp +++ b/third_party/WebKit/Source/core/messaging/BlinkCloneableMessageStructTraits.cpp
@@ -8,16 +8,13 @@ namespace mojo { -Vector<blink::mojom::blink::SerializedBlobPtr> StructTraits< +Vector<scoped_refptr<blink::BlobDataHandle>> StructTraits< blink::mojom::blink::CloneableMessage::DataView, blink::BlinkCloneableMessage>::blobs(blink::BlinkCloneableMessage& input) { - Vector<blink::mojom::blink::SerializedBlobPtr> result; + Vector<scoped_refptr<blink::BlobDataHandle>> result; result.ReserveInitialCapacity(input.message->BlobDataHandles().size()); - for (const auto& blob : input.message->BlobDataHandles()) { - result.push_back(blink::mojom::blink::SerializedBlob::New( - blob.value->Uuid(), blob.value->GetType(), blob.value->size(), - blob.value->CloneBlobPtr().PassInterface())); - } + for (const auto& blob : input.message->BlobDataHandles()) + result.push_back(blob.value); return result; } @@ -30,14 +27,11 @@ out->message = blink::SerializedScriptValue::Create( reinterpret_cast<const char*>(message_data.data()), message_data.size()); - Vector<blink::mojom::blink::SerializedBlobPtr> blobs; + Vector<scoped_refptr<blink::BlobDataHandle>> blobs; if (!data.ReadBlobs(&blobs)) return false; for (auto& blob : blobs) { - out->message->BlobDataHandles().Set( - blob->uuid, - blink::BlobDataHandle::Create(blob->uuid, blob->content_type, - blob->size, std::move(blob->blob))); + out->message->BlobDataHandles().Set(blob->Uuid(), blob); } out->sender_stack_trace_id = v8_inspector::V8StackTraceId( static_cast<uintptr_t>(data.stack_trace_id()),
diff --git a/third_party/WebKit/Source/core/messaging/BlinkCloneableMessageStructTraits.h b/third_party/WebKit/Source/core/messaging/BlinkCloneableMessageStructTraits.h index 056fb4d..30ef4af3 100644 --- a/third_party/WebKit/Source/core/messaging/BlinkCloneableMessageStructTraits.h +++ b/third_party/WebKit/Source/core/messaging/BlinkCloneableMessageStructTraits.h
@@ -9,6 +9,7 @@ #include "core/messaging/BlinkCloneableMessage.h" #include "mojo/public/cpp/bindings/array_traits_wtf_vector.h" #include "mojo/public/cpp/bindings/string_traits_wtf.h" +#include "platform/blob/SerializedBlobStructTraits.h" #include "third_party/WebKit/common/message_port/message_port.mojom-blink.h" namespace mojo { @@ -21,7 +22,7 @@ return input.message->GetWireData(); } - static Vector<blink::mojom::blink::SerializedBlobPtr> blobs( + static Vector<scoped_refptr<blink::BlobDataHandle>> blobs( blink::BlinkCloneableMessage& input); static uint64_t stack_trace_id(blink::BlinkCloneableMessage& input) {
diff --git a/third_party/WebKit/Source/core/messaging/MessagePort.h b/third_party/WebKit/Source/core/messaging/MessagePort.h index 3049be4..88b0496 100644 --- a/third_party/WebKit/Source/core/messaging/MessagePort.h +++ b/third_party/WebKit/Source/core/messaging/MessagePort.h
@@ -29,13 +29,13 @@ #include <memory> #include "base/memory/scoped_refptr.h" +#include "base/single_thread_task_runner.h" #include "bindings/core/v8/ActiveScriptWrappable.h" #include "bindings/core/v8/serialization/SerializedScriptValue.h" #include "core/CoreExport.h" #include "core/dom/ContextLifecycleObserver.h" #include "core/dom/events/EventListener.h" #include "core/dom/events/EventTarget.h" -#include "platform/WebTaskRunner.h" #include "platform/wtf/Vector.h" #include "public/platform/WebVector.h" #include "third_party/WebKit/common/message_port/message_port_channel.h" @@ -140,7 +140,7 @@ bool started_ = false; bool closed_ = false; - scoped_refptr<WebTaskRunner> task_runner_; + scoped_refptr<base::SingleThreadTaskRunner> task_runner_; }; } // namespace blink
diff --git a/third_party/WebKit/Source/core/mojo/MojoWatcher.h b/third_party/WebKit/Source/core/mojo/MojoWatcher.h index 1b300ed..dbbbab7 100644 --- a/third_party/WebKit/Source/core/mojo/MojoWatcher.h +++ b/third_party/WebKit/Source/core/mojo/MojoWatcher.h
@@ -55,7 +55,7 @@ MojoWatcherNotificationFlags); void RunReadyCallback(MojoResult); - scoped_refptr<WebTaskRunner> task_runner_; + scoped_refptr<base::SingleThreadTaskRunner> task_runner_; TraceWrapperMember<V8MojoWatchCallback> callback_; mojo::ScopedWatcherHandle watcher_handle_; mojo::Handle handle_;
diff --git a/third_party/WebKit/Source/core/mojo/test/MojoInterfaceInterceptor.cpp b/third_party/WebKit/Source/core/mojo/test/MojoInterfaceInterceptor.cpp index 6e68b38..55418044 100644 --- a/third_party/WebKit/Source/core/mojo/test/MojoInterfaceInterceptor.cpp +++ b/third_party/WebKit/Source/core/mojo/test/MojoInterfaceInterceptor.cpp
@@ -14,7 +14,6 @@ #include "core/mojo/test/MojoInterfaceRequestEvent.h" #include "core/workers/WorkerGlobalScope.h" #include "core/workers/WorkerThread.h" -#include "platform/WebTaskRunner.h" #include "platform/bindings/ScriptState.h" #include "platform/wtf/text/StringUTF8Adaptor.h" #include "public/platform/Platform.h"
diff --git a/third_party/WebKit/Source/core/origin_trials/OriginTrialContext.cpp b/third_party/WebKit/Source/core/origin_trials/OriginTrialContext.cpp index 9ca0fb4..5ca33d6 100644 --- a/third_party/WebKit/Source/core/origin_trials/OriginTrialContext.cpp +++ b/third_party/WebKit/Source/core/origin_trials/OriginTrialContext.cpp
@@ -13,7 +13,7 @@ #include "core/dom/Document.h" #include "core/dom/ExecutionContext.h" #include "core/frame/LocalFrame.h" -#include "core/workers/WorkerGlobalScope.h" +#include "core/workers/WorkletGlobalScope.h" #include "platform/Histogram.h" #include "platform/bindings/OriginTrialFeatures.h" #include "platform/runtime_enabled_features.h" @@ -229,7 +229,20 @@ DCHECK(!token.IsEmpty()); // Origin trials are only enabled for secure origins - if (!GetSupplementable()->IsSecureContext()) { + // - For worklets, they are currently spec'd to not be secure, given their + // scope has unique origin: + // https://drafts.css-houdini.org/worklets/#script-settings-for-worklets + // - For the purpose of origin trials, we consider worklets as running in the + // same context as the originating document. Thus, the special logic here + // to validate the token against the document context. + bool is_secure = false; + ExecutionContext* context = GetSupplementable(); + if (context->IsWorkletGlobalScope()) { + is_secure = ToWorkletGlobalScope(context)->DocumentSecureContext(); + } else { + is_secure = context->IsSecureContext(); + } + if (!is_secure) { TokenValidationResultHistogram().Count( static_cast<int>(OriginTrialTokenStatus::kInsecure)); return false; @@ -241,7 +254,14 @@ return false; } - WebSecurityOrigin origin(GetSupplementable()->GetSecurityOrigin()); + WebSecurityOrigin origin; + if (context->IsWorkletGlobalScope()) { + origin = WebSecurityOrigin( + ToWorkletGlobalScope(context)->DocumentSecurityOrigin()); + } else { + origin = WebSecurityOrigin(context->GetSecurityOrigin()); + } + WebString trial_name; bool valid = false; OriginTrialTokenStatus token_result =
diff --git a/third_party/WebKit/Source/core/page/scrolling/RootScrollerController.cpp b/third_party/WebKit/Source/core/page/scrolling/RootScrollerController.cpp index 18e3045..152c7e2 100644 --- a/third_party/WebKit/Source/core/page/scrolling/RootScrollerController.cpp +++ b/third_party/WebKit/Source/core/page/scrolling/RootScrollerController.cpp
@@ -221,26 +221,32 @@ if (!node.IsInTreeScope()) return; - if (node.IsFrameOwnerElement()) { - HTMLFrameOwnerElement* frame_owner = ToHTMLFrameOwnerElement(&node); - DCHECK(frame_owner->ContentFrame()); + if (!node.IsFrameOwnerElement()) + return; - if (frame_owner->ContentFrame()->IsLocalFrame()) { - LocalFrameView* frame_view = - ToLocalFrameView(frame_owner->OwnedEmbeddedContentView()); + HTMLFrameOwnerElement* frame_owner = ToHTMLFrameOwnerElement(&node); - bool is_root_scroller = &EffectiveRootScroller() == &node; + // The current effective root scroller may have lost its ContentFrame. If + // that's the case, there's nothing to be done. https://crbug.com/805317 for + // an example of how we get here. + if (!frame_owner->ContentFrame()) + return; - // If we're making the Frame the root scroller, it must have a FrameView - // by now. - DCHECK(frame_view || !is_root_scroller); - if (frame_view) { - frame_view->SetLayoutSizeFixedToFrameSize(!is_root_scroller); - UpdateIFrameGeometryAndLayoutSize(*frame_owner); - } - } else { - // TODO(bokan): Make work with OOPIF. crbug.com/642378. + if (frame_owner->ContentFrame()->IsLocalFrame()) { + LocalFrameView* frame_view = + ToLocalFrameView(frame_owner->OwnedEmbeddedContentView()); + + bool is_root_scroller = &EffectiveRootScroller() == &node; + + // If we're making the Frame the root scroller, it must have a FrameView + // by now. + DCHECK(frame_view || !is_root_scroller); + if (frame_view) { + frame_view->SetLayoutSizeFixedToFrameSize(!is_root_scroller); + UpdateIFrameGeometryAndLayoutSize(*frame_owner); } + } else { + // TODO(bokan): Make work with OOPIF. crbug.com/642378. } }
diff --git a/third_party/WebKit/Source/core/page/scrolling/RootScrollerTest.cpp b/third_party/WebKit/Source/core/page/scrolling/RootScrollerTest.cpp index 480f8d8..227f0d2c 100644 --- a/third_party/WebKit/Source/core/page/scrolling/RootScrollerTest.cpp +++ b/third_party/WebKit/Source/core/page/scrolling/RootScrollerTest.cpp
@@ -1449,6 +1449,79 @@ GetDocument().GetRootScrollerController().EffectiveRootScroller()); } +// Tests that we don't explode when a layout occurs and the effective +// rootScroller no longer has a ContentFrame(). We setup the frame tree such +// that the first iframe is the effective root scroller. The second iframe has +// an unload handler that reaches back to the common parent and causes a +// layout. This will cause us to recalculate the effective root scroller while +// the current one is valid in all ways except that it no longer has a content +// frame. This test passes if it doesn't crash. https://crbug.com/805317. +TEST_P(RootScrollerSimTest, RecomputeEffectiveWithNoContentFrame) { + WebView().Resize(WebSize(800, 600)); + SimRequest request("https://example.com/test.html", "text/html"); + SimRequest first_request("https://example.com/first.html", "text/html"); + SimRequest second_request("https://example.com/second.html", "text/html"); + SimRequest final_request("https://newdomain.com/test.html", "text/html"); + LoadURL("https://example.com/test.html"); + request.Complete(R"HTML( + <!DOCTYPE html> + <style> + ::-webkit-scrollbar { + width: 0px; + height: 0px; + } + body, html { + width: 100%; + height: 100%; + margin: 0px; + } + iframe { + width: 100%; + height: 100%; + border: 0; + } + </style> + <iframe id="first" src="https://example.com/first.html"> + </iframe> + <iframe id="second" src="https://example.com/second.html"> + </iframe> + <script> + // Dirty layout on unload + window.addEventListener('unload', function() { + document.getElementById("first").style.width="0"; + }); + </script> + )HTML"); + + first_request.Complete(R"HTML( + <!DOCTYPE html> + )HTML"); + + second_request.Complete(R"HTML( + <!DOCTYPE html> + <body></body> + <script> + window.addEventListener('unload', function() { + // This will do a layout. + window.top.document.getElementById("first").clientWidth; + }); + </script> + )HTML"); + + Compositor().BeginFrame(); + + Element* container = GetDocument().getElementById("first"); + GetDocument().GetRootScrollerController().Set(container); + ASSERT_EQ(container, + GetDocument().GetRootScrollerController().EffectiveRootScroller()); + + // This will unload first the root, then the first frame, then the second. + LoadURL("https://newdomain.com/test.html"); + final_request.Complete(R"HTML( + <!DOCTYPE html> + )HTML"); +} + class RootScrollerHitTest : public RootScrollerTest { public: void CheckHitTestAtBottomOfScreen() {
diff --git a/third_party/WebKit/Source/core/paint/AppliedDecorationPainter.cpp b/third_party/WebKit/Source/core/paint/AppliedDecorationPainter.cpp index 27796c26..63615ec1 100644 --- a/third_party/WebKit/Source/core/paint/AppliedDecorationPainter.cpp +++ b/third_party/WebKit/Source/core/paint/AppliedDecorationPainter.cpp
@@ -117,7 +117,7 @@ case ETextDecorationStyle::kDotted: case ETextDecorationStyle::kDashed: context_.SetShouldAntialias(decoration_info_.antialias); - // Fall through + FALLTHROUGH; default: context_.DrawLineForText(start_point_, decoration_info_.width);
diff --git a/third_party/WebKit/Source/core/paint/BackgroundImageGeometry.cpp b/third_party/WebKit/Source/core/paint/BackgroundImageGeometry.cpp index beb50c36..69afefc 100644 --- a/third_party/WebKit/Source/core/paint/BackgroundImageGeometry.cpp +++ b/third_party/WebKit/Source/core/paint/BackgroundImageGeometry.cpp
@@ -121,6 +121,7 @@ // If the image has neither an intrinsic width nor an intrinsic height, // its size is determined as for 'contain'. type = EFillSizeType::kContain; + FALLTHROUGH; } case EFillSizeType::kContain: case EFillSizeType::kCover: { @@ -527,7 +528,7 @@ switch (fill_layer.Clip()) { case EFillBox::kContent: dest_adjust += positioning_box_.PaddingOutsets(); - // fall through + FALLTHROUGH; case EFillBox::kPadding: dest_adjust += positioning_box_.BorderBoxOutsets(); break;
diff --git a/third_party/WebKit/Source/core/paint/BoxBorderPainter.cpp b/third_party/WebKit/Source/core/paint/BoxBorderPainter.cpp index 9dc2372..106844a 100644 --- a/third_party/WebKit/Source/core/paint/BoxBorderPainter.cpp +++ b/third_party/WebKit/Source/core/paint/BoxBorderPainter.cpp
@@ -345,7 +345,7 @@ context.FillDRRect(adjusted_outer, inner, color); break; } - // fall through + FALLTHROUGH; default: context.FillDRRect(outer, inner, color); break;
diff --git a/third_party/WebKit/Source/core/paint/ObjectPainterBase.cpp b/third_party/WebKit/Source/core/paint/ObjectPainterBase.cpp index 91bf990..7fbd15b 100644 --- a/third_party/WebKit/Source/core/paint/ObjectPainterBase.cpp +++ b/third_party/WebKit/Source/core/paint/ObjectPainterBase.cpp
@@ -572,12 +572,12 @@ // https://bugs.webkit.org/show_bug.cgi?id=58608 if (side == BoxSide::kTop || side == BoxSide::kLeft) color = color.Dark(); - // fall through + FALLTHROUGH; case EBorderStyle::kOutset: if (style == EBorderStyle::kOutset && (side == BoxSide::kBottom || side == BoxSide::kRight)) color = color.Dark(); - // fall through + FALLTHROUGH; case EBorderStyle::kSolid: DrawSolidBoxSide(graphics_context, x1, y1, x2, y2, side, color, adjacent_width1, adjacent_width2, antialias);
diff --git a/third_party/WebKit/Source/core/paint/PaintLayerPainter.cpp b/third_party/WebKit/Source/core/paint/PaintLayerPainter.cpp index 90d13a1..3f43dbe 100644 --- a/third_party/WebKit/Source/core/paint/PaintLayerPainter.cpp +++ b/third_party/WebKit/Source/core/paint/PaintLayerPainter.cpp
@@ -1097,6 +1097,7 @@ ->AncestorClippingMaskLayer(); break; } + FALLTHROUGH; default: clipping_rule = LayerClipRecorder::kIncludeSelfForBorderRadius; break;
diff --git a/third_party/WebKit/Source/core/paint/PaintLayerScrollableArea.cpp b/third_party/WebKit/Source/core/paint/PaintLayerScrollableArea.cpp index da7f05b..1b3e4f7 100644 --- a/third_party/WebKit/Source/core/paint/PaintLayerScrollableArea.cpp +++ b/third_party/WebKit/Source/core/paint/PaintLayerScrollableArea.cpp
@@ -1042,8 +1042,8 @@ return local_object->LocalToAncestorQuad(quad, box, flags); } -scoped_refptr<WebTaskRunner> PaintLayerScrollableArea::GetTimerTaskRunner() - const { +scoped_refptr<base::SingleThreadTaskRunner> +PaintLayerScrollableArea::GetTimerTaskRunner() const { return GetLayoutBox()->GetFrame()->GetTaskRunner(TaskType::kUnspecedTimer); }
diff --git a/third_party/WebKit/Source/core/paint/PaintLayerScrollableArea.h b/third_party/WebKit/Source/core/paint/PaintLayerScrollableArea.h index 7c29849..8acb37f 100644 --- a/third_party/WebKit/Source/core/paint/PaintLayerScrollableArea.h +++ b/third_party/WebKit/Source/core/paint/PaintLayerScrollableArea.h
@@ -434,7 +434,7 @@ const LayoutObject*, unsigned = 0) const final; - scoped_refptr<WebTaskRunner> GetTimerTaskRunner() const final; + scoped_refptr<base::SingleThreadTaskRunner> GetTimerTaskRunner() const final; bool ShouldRebuildHorizontalScrollbarLayer() const { return rebuild_horizontal_scrollbar_layer_;
diff --git a/third_party/WebKit/Source/core/paint/SVGFilterPainter.cpp b/third_party/WebKit/Source/core/paint/SVGFilterPainter.cpp index 650eec8..5ec45cba 100644 --- a/third_party/WebKit/Source/core/paint/SVGFilterPainter.cpp +++ b/third_party/WebKit/Source/core/paint/SVGFilterPainter.cpp
@@ -42,7 +42,7 @@ paint_controller_->GetPaintArtifact().Replay( *context_, initial_context_.GetPaintController() .CurrentPaintChunkProperties() - .property_tree_state); + .property_tree_state.GetPropertyTreeState()); sk_sp<PaintRecord> content = context_->EndRecording(); // Content is cached by the source graphic so temporaries can be freed.
diff --git a/third_party/WebKit/Source/core/paint/SVGPaintContext.cpp b/third_party/WebKit/Source/core/paint/SVGPaintContext.cpp index 40040b73..8a48ab0 100644 --- a/third_party/WebKit/Source/core/paint/SVGPaintContext.cpp +++ b/third_party/WebKit/Source/core/paint/SVGPaintContext.cpp
@@ -127,8 +127,8 @@ if (const auto* properties = object_.FirstFragment().PaintProperties()) { if (const auto* effect = properties->Effect()) { auto& paint_controller = GetPaintInfo().context.GetPaintController(); - PropertyTreeState state( - paint_controller.CurrentPaintChunkProperties().property_tree_state); + PropertyTreeState state(paint_controller.CurrentPaintChunkProperties() + .property_tree_state.GetPropertyTreeState()); state.SetEffect(effect); if (const auto* mask_clip = properties->MaskClip()) state.SetClip(mask_clip);
diff --git a/third_party/WebKit/Source/core/paint/compositing/CompositedLayerMapping.cpp b/third_party/WebKit/Source/core/paint/compositing/CompositedLayerMapping.cpp index d5bdbd75..75eb742c 100644 --- a/third_party/WebKit/Source/core/paint/compositing/CompositedLayerMapping.cpp +++ b/third_party/WebKit/Source/core/paint/compositing/CompositedLayerMapping.cpp
@@ -806,10 +806,7 @@ ScrollingLayer()->SetMaskLayer(first_come_first_served); first_come_first_served = nullptr; } - if (is_accelerated_contents) { - graphics_layer_->SetContentsClippingMaskLayer(first_come_first_served); - first_come_first_served = nullptr; - } + graphics_layer_->SetContentsClippingMaskLayer(first_come_first_served); } UpdateBackgroundColor(); @@ -1654,8 +1651,13 @@ bool overflow_clip_rect_offset_changed = old_scrolling_layer_offset != scrolling_layer_->OffsetFromLayoutObject(); - IntSize scroll_size(layout_box.PixelSnappedScrollWidth(), - layout_box.PixelSnappedScrollHeight()); + IntSize scroll_size = + PixelSnappedIntRect( + LayoutRect( + LayoutPoint(owning_layer_.SubpixelAccumulation()), + LayoutSize(layout_box.ScrollWidth(), layout_box.ScrollHeight()))) + .Size(); + if (overflow_clip_rect_offset_changed) scrolling_contents_layer_->SetNeedsDisplay();
diff --git a/third_party/WebKit/Source/core/paint/compositing/CompositedLayerMappingTest.cpp b/third_party/WebKit/Source/core/paint/compositing/CompositedLayerMappingTest.cpp index 3f9fa34..3ff16d6 100644 --- a/third_party/WebKit/Source/core/paint/compositing/CompositedLayerMappingTest.cpp +++ b/third_party/WebKit/Source/core/paint/compositing/CompositedLayerMappingTest.cpp
@@ -2475,4 +2475,47 @@ EXPECT_EQ(FloatSize(100, 100), mapping->ForegroundLayer()->Size()); } +TEST_P(CompositedLayerMappingTest, ScrollLayerSizingSubpixelAccumulation) { + // This test verifies that when subpixel accumulation causes snapping it + // applies to both the scrolling and scrolling contents layers. Verify that + // the mapping doesn't have any vertical scrolling introduced as a result of + // the snapping behavior. https://crbug.com/801381. + GetDocument().GetFrame()->GetSettings()->SetPreferCompositingToLCDTextEnabled( + true); + + // The values below are chosen so that the subpixel accumulation causes the + // pixel snapped height to be increased relative to snapping without it. + SetBodyInnerHTML(R"HTML( + <!DOCTYPE html> + <style> + body { + margin: 0; + } + #scroller { + position: relative; + top: 0.5625px; + width: 200px; + height: 200.8125px; + overflow: auto; + } + #space { + width: 1000px; + height: 200.8125px; + } + </style> + <div id="scroller"> + <div id="space"></div> + </div> + )HTML"); + GetDocument().View()->UpdateAllLifecyclePhases(); + auto* mapping = ToLayoutBoxModelObject(GetLayoutObjectByElementId("scroller")) + ->Layer() + ->GetCompositedLayerMapping(); + ASSERT_TRUE(mapping); + ASSERT_TRUE(mapping->ScrollingLayer()); + ASSERT_TRUE(mapping->ScrollingContentsLayer()); + EXPECT_EQ(mapping->ScrollingLayer()->Size().Height(), + mapping->ScrollingContentsLayer()->Size().Height()); +} + } // namespace blink
diff --git a/third_party/WebKit/Source/core/scheduler/FrameThrottlingTest.cpp b/third_party/WebKit/Source/core/scheduler/FrameThrottlingTest.cpp index 84c471f..20db066 100644 --- a/third_party/WebKit/Source/core/scheduler/FrameThrottlingTest.cpp +++ b/third_party/WebKit/Source/core/scheduler/FrameThrottlingTest.cpp
@@ -891,8 +891,7 @@ // The dumped contents should not include the throttled frame. DocumentLifecycle::AllowThrottlingScope throttling_scope( GetDocument().Lifecycle()); - WebString result = WebFrameContentDumper::DeprecatedDumpFrameTreeAsText( - WebView().MainFrameImpl(), 1024); + WebString result = WebFrameContentDumper::DumpWebViewAsText(&WebView(), 1024); EXPECT_NE(std::string::npos, result.Utf8().find("main")); EXPECT_EQ(std::string::npos, result.Utf8().find("throttled")); }
diff --git a/third_party/WebKit/Source/core/script/Modulator.h b/third_party/WebKit/Source/core/script/Modulator.h index 8b312b4f..610dda1 100644 --- a/third_party/WebKit/Source/core/script/Modulator.h +++ b/third_party/WebKit/Source/core/script/Modulator.h
@@ -5,10 +5,10 @@ #ifndef Modulator_h #define Modulator_h +#include "base/single_thread_task_runner.h" #include "bindings/core/v8/ScriptModule.h" #include "core/CoreExport.h" #include "core/script/ModuleImportMeta.h" -#include "platform/WebTaskRunner.h" #include "platform/bindings/ScriptWrappable.h" #include "platform/bindings/V8PerContextData.h" #include "platform/heap/Handle.h" @@ -85,7 +85,7 @@ void TraceWrappers(const ScriptWrappableVisitor*) const override {} virtual ScriptModuleResolver* GetScriptModuleResolver() = 0; - virtual WebTaskRunner* TaskRunner() = 0; + virtual base::SingleThreadTaskRunner* TaskRunner() = 0; virtual ReferrerPolicy GetReferrerPolicy() = 0; // Returns the security origin of the "fetch client settings object".
diff --git a/third_party/WebKit/Source/core/script/ModulatorImplBase.cpp b/third_party/WebKit/Source/core/script/ModulatorImplBase.cpp index e3b60a7..81b4ec8 100644 --- a/third_party/WebKit/Source/core/script/ModulatorImplBase.cpp +++ b/third_party/WebKit/Source/core/script/ModulatorImplBase.cpp
@@ -12,7 +12,6 @@ #include "core/script/ModuleMap.h" #include "core/script/ModuleScript.h" #include "core/script/ScriptModuleResolverImpl.h" -#include "platform/WebTaskRunner.h" #include "public/platform/TaskType.h" namespace blink {
diff --git a/third_party/WebKit/Source/core/script/ModulatorImplBase.h b/third_party/WebKit/Source/core/script/ModulatorImplBase.h index 0eb87e4..76698af 100644 --- a/third_party/WebKit/Source/core/script/ModulatorImplBase.h +++ b/third_party/WebKit/Source/core/script/ModulatorImplBase.h
@@ -5,9 +5,9 @@ #ifndef ModulatorImplBase_h #define ModulatorImplBase_h +#include "base/single_thread_task_runner.h" #include "bindings/core/v8/ScriptModule.h" #include "core/script/Modulator.h" -#include "platform/WebTaskRunner.h" #include "platform/bindings/ScriptWrappable.h" #include "platform/bindings/TraceWrapperMember.h" #include "platform/bindings/V8PerIsolateData.h" @@ -45,7 +45,9 @@ ScriptModuleResolver* GetScriptModuleResolver() override { return script_module_resolver_.Get(); } - WebTaskRunner* TaskRunner() override { return task_runner_.get(); } + base::SingleThreadTaskRunner* TaskRunner() override { + return task_runner_.get(); + } ReferrerPolicy GetReferrerPolicy() override; const SecurityOrigin* GetSecurityOriginForFetch() override; @@ -77,7 +79,7 @@ ScriptValue ExecuteModule(const ModuleScript*, CaptureEvalErrorFlag) override; scoped_refptr<ScriptState> script_state_; - scoped_refptr<WebTaskRunner> task_runner_; + scoped_refptr<base::SingleThreadTaskRunner> task_runner_; TraceWrapperMember<ModuleMap> map_; Member<ModuleScriptLoaderRegistry> loader_registry_; TraceWrapperMember<ModuleTreeLinkerRegistry> tree_linker_registry_;
diff --git a/third_party/WebKit/Source/core/script/ModuleMap.cpp b/third_party/WebKit/Source/core/script/ModuleMap.cpp index 10f4f17..538f6b9 100644 --- a/third_party/WebKit/Source/core/script/ModuleMap.cpp +++ b/third_party/WebKit/Source/core/script/ModuleMap.cpp
@@ -8,7 +8,6 @@ #include "core/loader/modulescript/ModuleScriptLoaderClient.h" #include "core/script/Modulator.h" #include "core/script/ModuleScript.h" -#include "platform/WebTaskRunner.h" namespace blink {
diff --git a/third_party/WebKit/Source/core/script/ModuleMapTest.cpp b/third_party/WebKit/Source/core/script/ModuleMapTest.cpp index 129f80d6..2d7dfe2 100644 --- a/third_party/WebKit/Source/core/script/ModuleMapTest.cpp +++ b/third_party/WebKit/Source/core/script/ModuleMapTest.cpp
@@ -97,7 +97,7 @@ return resolver_.Get(); } - WebTaskRunner* TaskRunner() override { + base::SingleThreadTaskRunner* TaskRunner() override { return Platform::Current()->CurrentThread()->GetWebTaskRunner(); };
diff --git a/third_party/WebKit/Source/core/script/ScriptRunner.h b/third_party/WebKit/Source/core/script/ScriptRunner.h index a234720..d1b9c3f 100644 --- a/third_party/WebKit/Source/core/script/ScriptRunner.h +++ b/third_party/WebKit/Source/core/script/ScriptRunner.h
@@ -28,8 +28,8 @@ #include "base/location.h" #include "base/macros.h" +#include "base/single_thread_task_runner.h" #include "core/CoreExport.h" -#include "platform/WebTaskRunner.h" #include "platform/bindings/ScriptWrappable.h" #include "platform/bindings/TraceWrapperMember.h" #include "platform/heap/Handle.h" @@ -103,7 +103,7 @@ HeapDeque<TraceWrapperMember<ScriptLoader>> async_scripts_to_execute_soon_; HeapDeque<TraceWrapperMember<ScriptLoader>> in_order_scripts_to_execute_soon_; - scoped_refptr<WebTaskRunner> task_runner_; + scoped_refptr<base::SingleThreadTaskRunner> task_runner_; int number_of_in_order_scripts_with_pending_notification_;
diff --git a/third_party/WebKit/Source/core/style/ClipPathOperation.cpp b/third_party/WebKit/Source/core/style/ClipPathOperation.cpp index a0a3be3a..02699d24 100644 --- a/third_party/WebKit/Source/core/style/ClipPathOperation.cpp +++ b/third_party/WebKit/Source/core/style/ClipPathOperation.cpp
@@ -6,8 +6,9 @@ namespace blink { -void ReferenceClipPathOperation::AddClient(SVGResourceClient* client, - WebTaskRunner* task_runner) { +void ReferenceClipPathOperation::AddClient( + SVGResourceClient* client, + base::SingleThreadTaskRunner* task_runner) { element_proxy_->AddClient(client, task_runner); }
diff --git a/third_party/WebKit/Source/core/style/ClipPathOperation.h b/third_party/WebKit/Source/core/style/ClipPathOperation.h index 86755e7..99fc555 100644 --- a/third_party/WebKit/Source/core/style/ClipPathOperation.h +++ b/third_party/WebKit/Source/core/style/ClipPathOperation.h
@@ -70,7 +70,7 @@ return base::AdoptRef(new ReferenceClipPathOperation(url, element_proxy)); } - void AddClient(SVGResourceClient*, WebTaskRunner*); + void AddClient(SVGResourceClient*, base::SingleThreadTaskRunner*); void RemoveClient(SVGResourceClient*); SVGElement* FindElement(TreeScope&) const;
diff --git a/third_party/WebKit/Source/core/style/FilterOperation.cpp b/third_party/WebKit/Source/core/style/FilterOperation.cpp index 44eec27c..02cec41 100644 --- a/third_party/WebKit/Source/core/style/FilterOperation.cpp +++ b/third_party/WebKit/Source/core/style/FilterOperation.cpp
@@ -62,8 +62,9 @@ SVGElementProxy& element_proxy) : FilterOperation(REFERENCE), url_(url), element_proxy_(&element_proxy) {} -void ReferenceFilterOperation::AddClient(SVGResourceClient* client, - WebTaskRunner* task_runner) { +void ReferenceFilterOperation::AddClient( + SVGResourceClient* client, + base::SingleThreadTaskRunner* task_runner) { element_proxy_->AddClient(client, task_runner); }
diff --git a/third_party/WebKit/Source/core/style/FilterOperation.h b/third_party/WebKit/Source/core/style/FilterOperation.h index b86f2af..35c53a8 100644 --- a/third_party/WebKit/Source/core/style/FilterOperation.h +++ b/third_party/WebKit/Source/core/style/FilterOperation.h
@@ -27,10 +27,10 @@ #define FilterOperation_h #include "base/macros.h" +#include "base/single_thread_task_runner.h" #include "core/CoreExport.h" #include "core/style/ShadowData.h" #include "platform/Length.h" -#include "platform/WebTaskRunner.h" #include "platform/geometry/FloatRect.h" #include "platform/graphics/BoxReflection.h" #include "platform/graphics/Color.h" @@ -147,7 +147,7 @@ SVGElementProxy& ElementProxy() const { return *element_proxy_; } - void AddClient(SVGResourceClient*, WebTaskRunner*); + void AddClient(SVGResourceClient*, base::SingleThreadTaskRunner*); void RemoveClient(SVGResourceClient*); virtual void Trace(blink::Visitor*);
diff --git a/third_party/WebKit/Source/core/style/FilterOperations.cpp b/third_party/WebKit/Source/core/style/FilterOperations.cpp index 1823401b..32d137f 100644 --- a/third_party/WebKit/Source/core/style/FilterOperations.cpp +++ b/third_party/WebKit/Source/core/style/FilterOperations.cpp
@@ -104,8 +104,9 @@ return false; } -void FilterOperations::AddClient(SVGResourceClient* client, - WebTaskRunner* task_runner) const { +void FilterOperations::AddClient( + SVGResourceClient* client, + base::SingleThreadTaskRunner* task_runner) const { for (FilterOperation* operation : operations_) { if (operation->GetType() == FilterOperation::REFERENCE) ToReferenceFilterOperation(*operation).AddClient(client, task_runner);
diff --git a/third_party/WebKit/Source/core/style/FilterOperations.h b/third_party/WebKit/Source/core/style/FilterOperations.h index 117835ba..fdf0ca6 100644 --- a/third_party/WebKit/Source/core/style/FilterOperations.h +++ b/third_party/WebKit/Source/core/style/FilterOperations.h
@@ -71,7 +71,7 @@ bool HasReferenceFilter() const; - void AddClient(SVGResourceClient*, WebTaskRunner*) const; + void AddClient(SVGResourceClient*, base::SingleThreadTaskRunner*) const; void RemoveClient(SVGResourceClient*) const; void Trace(blink::Visitor*);
diff --git a/third_party/WebKit/Source/core/svg/SVGElement.h b/third_party/WebKit/Source/core/svg/SVGElement.h index cd52c1d..8273619 100644 --- a/third_party/WebKit/Source/core/svg/SVGElement.h +++ b/third_party/WebKit/Source/core/svg/SVGElement.h
@@ -317,7 +317,7 @@ return IsSVGElement() && ToSVGElement(*this).HasTagName(name); } -// This requires isSVG*Element(const SVGElement&). +// This requires IsSVG*Element(const SVGElement&). #define DEFINE_SVGELEMENT_TYPE_CASTS_WITH_FUNCTION(thisType) \ inline bool Is##thisType(const thisType* element); \ inline bool Is##thisType(const thisType& element); \ @@ -325,16 +325,12 @@ return element && Is##thisType(*element); \ } \ inline bool Is##thisType(const Node& node) { \ - return node.IsSVGElement() ? Is##thisType(ToSVGElement(node)) : false; \ + return node.IsSVGElement() && Is##thisType(ToSVGElement(node)); \ } \ inline bool Is##thisType(const Node* node) { \ return node && Is##thisType(*node); \ } \ template <typename T> \ - inline bool Is##thisType(const T* node) { \ - return Is##thisType(node); \ - } \ - template <typename T> \ inline bool Is##thisType(const Member<T>& node) { \ return Is##thisType(node.Get()); \ } \
diff --git a/third_party/WebKit/Source/core/svg/SVGElementProxy.cpp b/third_party/WebKit/Source/core/svg/SVGElementProxy.cpp index db248d3..14b8488 100644 --- a/third_party/WebKit/Source/core/svg/SVGElementProxy.cpp +++ b/third_party/WebKit/Source/core/svg/SVGElementProxy.cpp
@@ -41,8 +41,8 @@ } void ContentChanged() { - DCHECK(Lifecycle().GetState() <= DocumentLifecycle::kCompositingClean || - Lifecycle().GetState() >= DocumentLifecycle::kPaintClean); + DCHECK(Lifecycle().GetState() != DocumentLifecycle::kInPrePaint && + Lifecycle().GetState() != DocumentLifecycle::kInPaint); HeapVector<Member<SVGResourceClient>> clients; CopyToVector(clients_, clients); for (SVGResourceClient* client : clients) @@ -73,7 +73,7 @@ SVGElementProxy::~SVGElementProxy() = default; void SVGElementProxy::AddClient(SVGResourceClient* client, - WebTaskRunner* task_runner) { + base::SingleThreadTaskRunner* task_runner) { // An empty id will never be a valid element reference. if (id_.IsEmpty()) return;
diff --git a/third_party/WebKit/Source/core/svg/SVGElementProxy.h b/third_party/WebKit/Source/core/svg/SVGElementProxy.h index cb04a38..0e286a58 100644 --- a/third_party/WebKit/Source/core/svg/SVGElementProxy.h +++ b/third_party/WebKit/Source/core/svg/SVGElementProxy.h
@@ -78,7 +78,7 @@ } virtual ~SVGElementProxy(); - void AddClient(SVGResourceClient*, WebTaskRunner*); + void AddClient(SVGResourceClient*, base::SingleThreadTaskRunner*); void RemoveClient(SVGResourceClient*); // Resolve a potentially external document reference.
diff --git a/third_party/WebKit/Source/core/svg/SVGGeometryElement.cpp b/third_party/WebKit/Source/core/svg/SVGGeometryElement.cpp index aea74fc..3ab04fa3 100644 --- a/third_party/WebKit/Source/core/svg/SVGGeometryElement.cpp +++ b/third_party/WebKit/Source/core/svg/SVGGeometryElement.cpp
@@ -142,15 +142,25 @@ if (!pathLength()->IsSpecified()) return 1; float author_path_length = pathLength()->CurrentValue()->Value(); + // https://svgwg.org/svg2-draft/paths.html#PathLengthAttribute + // "A negative value is an error" if (author_path_length < 0) return 1; - if (!author_path_length) - return 0; DCHECK(GetLayoutObject()); + // If the computed path length is zero, then the scale factor will + // always be zero except if the author path length is also zero - in + // which case performing the division would yield a NaN. Avoid the + // division in this case and always return zero. float computed_path_length = ComputePathLength(); if (!computed_path_length) - return 1; - return computed_path_length / author_path_length; + return 0; + // "A value of zero is valid and must be treated as a scaling factor + // of infinity. A value of zero scaled infinitely must remain zero, + // while any value greater than zero must become +Infinity." + // However, since 0 * Infinity is not zero (but rather NaN) per + // IEEE, we need to make sure to clamp the result below - avoiding + // the actual Infinity (and using max()) instead. + return clampTo<float>(computed_path_length / author_path_length); } LayoutObject* SVGGeometryElement::CreateLayoutObject(const ComputedStyle&) {
diff --git a/third_party/WebKit/Source/core/svg/SVGPathStringSource.cpp b/third_party/WebKit/Source/core/svg/SVGPathStringSource.cpp index bdea20a..1200cfca 100644 --- a/third_party/WebKit/Source/core/svg/SVGPathStringSource.cpp +++ b/third_party/WebKit/Source/core/svg/SVGPathStringSource.cpp
@@ -196,12 +196,12 @@ case kPathSegCurveToCubicAbs: segment.point1.SetX(ParseNumberWithError()); segment.point1.SetY(ParseNumberWithError()); - /* fall through */ + FALLTHROUGH; case kPathSegCurveToCubicSmoothRel: case kPathSegCurveToCubicSmoothAbs: segment.point2.SetX(ParseNumberWithError()); segment.point2.SetY(ParseNumberWithError()); - /* fall through */ + FALLTHROUGH; case kPathSegMoveToRel: case kPathSegMoveToAbs: case kPathSegLineToRel:
diff --git a/third_party/WebKit/Source/core/svg/SVGTransformDistance.cpp b/third_party/WebKit/Source/core/svg/SVGTransformDistance.cpp index ab27361..7688eda 100644 --- a/third_party/WebKit/Source/core/svg/SVGTransformDistance.cpp +++ b/third_party/WebKit/Source/core/svg/SVGTransformDistance.cpp
@@ -19,9 +19,9 @@ #include "core/svg/SVGTransformDistance.h" +#include <math.h> #include "platform/geometry/FloatPoint.h" #include "platform/geometry/FloatSize.h" -#include <math.h> namespace blink { @@ -48,6 +48,7 @@ switch (transform_type_) { case kSvgTransformMatrix: NOTREACHED(); + FALLTHROUGH; case kSvgTransformUnknown: break; case kSvgTransformRotate: { @@ -85,6 +86,7 @@ switch (transform_type_) { case kSvgTransformMatrix: NOTREACHED(); + FALLTHROUGH; case kSvgTransformUnknown: return SVGTransformDistance(); case kSvgTransformRotate: @@ -122,6 +124,7 @@ switch (first->TransformType()) { case kSvgTransformMatrix: NOTREACHED(); + FALLTHROUGH; case kSvgTransformUnknown: return transform; case kSvgTransformRotate: { @@ -168,6 +171,7 @@ switch (transform_type_) { case kSvgTransformMatrix: NOTREACHED(); + FALLTHROUGH; case kSvgTransformUnknown: return SVGTransform::Create(); case kSvgTransformTranslate: { @@ -204,6 +208,7 @@ switch (transform_type_) { case kSvgTransformMatrix: NOTREACHED(); + FALLTHROUGH; case kSvgTransformUnknown: return 0; case kSvgTransformRotate:
diff --git a/third_party/WebKit/Source/core/testing/DummyModulator.cpp b/third_party/WebKit/Source/core/testing/DummyModulator.cpp index 6732368..30c2bf0 100644 --- a/third_party/WebKit/Source/core/testing/DummyModulator.cpp +++ b/third_party/WebKit/Source/core/testing/DummyModulator.cpp
@@ -63,7 +63,7 @@ return resolver_.Get(); } -WebTaskRunner* DummyModulator::TaskRunner() { +base::SingleThreadTaskRunner* DummyModulator::TaskRunner() { NOTREACHED(); return nullptr; };
diff --git a/third_party/WebKit/Source/core/testing/DummyModulator.h b/third_party/WebKit/Source/core/testing/DummyModulator.h index b6242d2..88f58cc 100644 --- a/third_party/WebKit/Source/core/testing/DummyModulator.h +++ b/third_party/WebKit/Source/core/testing/DummyModulator.h
@@ -5,9 +5,9 @@ #ifndef DummyModulator_h #define DummyModulator_h +#include "base/single_thread_task_runner.h" #include "bindings/core/v8/ScriptModule.h" #include "core/script/Modulator.h" -#include "platform/WebTaskRunner.h" #include "platform/heap/Handle.h" namespace blink { @@ -32,7 +32,7 @@ void Trace(blink::Visitor*); ScriptModuleResolver* GetScriptModuleResolver() override; - WebTaskRunner* TaskRunner() override; + base::SingleThreadTaskRunner* TaskRunner() override; ReferrerPolicy GetReferrerPolicy() override; const SecurityOrigin* GetSecurityOriginForFetch() override; ScriptState* GetScriptState() override;
diff --git a/third_party/WebKit/Source/core/testing/NullExecutionContext.cpp b/third_party/WebKit/Source/core/testing/NullExecutionContext.cpp index 2b43363..4227d8b 100644 --- a/third_party/WebKit/Source/core/testing/NullExecutionContext.cpp +++ b/third_party/WebKit/Source/core/testing/NullExecutionContext.cpp
@@ -46,7 +46,8 @@ SecurityContext::SetContentSecurityPolicy(policy); } -scoped_refptr<WebTaskRunner> NullExecutionContext::GetTaskRunner(TaskType) { +scoped_refptr<base::SingleThreadTaskRunner> NullExecutionContext::GetTaskRunner( + TaskType) { return Platform::Current()->CurrentThread()->GetWebTaskRunner(); }
diff --git a/third_party/WebKit/Source/core/testing/NullExecutionContext.h b/third_party/WebKit/Source/core/testing/NullExecutionContext.h index e88a395..51a1b595 100644 --- a/third_party/WebKit/Source/core/testing/NullExecutionContext.h +++ b/third_party/WebKit/Source/core/testing/NullExecutionContext.h
@@ -54,7 +54,7 @@ ResourceFetcher* Fetcher() const override { return nullptr; } - scoped_refptr<WebTaskRunner> GetTaskRunner(TaskType) override; + scoped_refptr<base::SingleThreadTaskRunner> GetTaskRunner(TaskType) override; using SecurityContext::GetSecurityOrigin; using SecurityContext::GetContentSecurityPolicy;
diff --git a/third_party/WebKit/Source/core/timing/PerformanceBase.cpp b/third_party/WebKit/Source/core/timing/PerformanceBase.cpp index 24eeb97..672fe1c 100644 --- a/third_party/WebKit/Source/core/timing/PerformanceBase.cpp +++ b/third_party/WebKit/Source/core/timing/PerformanceBase.cpp
@@ -89,8 +89,9 @@ static const size_t kDefaultResourceTimingBufferSize = 150; static const size_t kDefaultFrameTimingBufferSize = 150; -PerformanceBase::PerformanceBase(TimeTicks time_origin, - scoped_refptr<WebTaskRunner> task_runner) +PerformanceBase::PerformanceBase( + TimeTicks time_origin, + scoped_refptr<base::SingleThreadTaskRunner> task_runner) : frame_timing_buffer_size_(kDefaultFrameTimingBufferSize), resource_timing_buffer_size_(kDefaultResourceTimingBufferSize), user_timing_(nullptr),
diff --git a/third_party/WebKit/Source/core/timing/PerformanceBase.h b/third_party/WebKit/Source/core/timing/PerformanceBase.h index 0a3960e1..b1d7bfa 100644 --- a/third_party/WebKit/Source/core/timing/PerformanceBase.h +++ b/third_party/WebKit/Source/core/timing/PerformanceBase.h
@@ -226,7 +226,8 @@ void AddPaintTiming(PerformancePaintTiming::PaintType, TimeTicks start_time); protected: - PerformanceBase(TimeTicks time_origin, scoped_refptr<WebTaskRunner>); + PerformanceBase(TimeTicks time_origin, + scoped_refptr<base::SingleThreadTaskRunner>); // Expect Performance to override this method, // WorkerPerformance doesn't have to override this.
diff --git a/third_party/WebKit/Source/core/workers/DedicatedWorker.cpp b/third_party/WebKit/Source/core/workers/DedicatedWorker.cpp index e0c915e..98eb57e 100644 --- a/third_party/WebKit/Source/core/workers/DedicatedWorker.cpp +++ b/third_party/WebKit/Source/core/workers/DedicatedWorker.cpp
@@ -219,8 +219,9 @@ return std::make_unique<GlobalScopeCreationParams>( script_url_, GetExecutionContext()->UserAgent(), document->GetContentSecurityPolicy()->Headers().get(), - kReferrerPolicyDefault, starter_origin, CreateWorkerClients(), - document->AddressSpace(), OriginTrialContext::GetTokens(document).get(), + kReferrerPolicyDefault, starter_origin, document->IsSecureContext(), + CreateWorkerClients(), document->AddressSpace(), + OriginTrialContext::GetTokens(document).get(), std::make_unique<WorkerSettings>(document->GetSettings()), kV8CacheOptionsDefault, ConnectToWorkerInterfaceProvider(document,
diff --git a/third_party/WebKit/Source/core/workers/DedicatedWorkerTest.cpp b/third_party/WebKit/Source/core/workers/DedicatedWorkerTest.cpp index 9bea88a1..1f955c0b 100644 --- a/third_party/WebKit/Source/core/workers/DedicatedWorkerTest.cpp +++ b/third_party/WebKit/Source/core/workers/DedicatedWorkerTest.cpp
@@ -31,7 +31,7 @@ : DedicatedWorkerThread(nullptr /* ThreadableLoadingContext */, worker_object_proxy) { worker_backing_thread_ = WorkerBackingThread::CreateForTest( - WebThreadCreationParams("Test thread")); + WebThreadCreationParams(WebThreadType::kTestThread)); } WorkerOrWorkletGlobalScope* CreateWorkerGlobalScope( @@ -71,7 +71,7 @@ void TestTaskRunner() { EXPECT_TRUE(IsCurrentThread()); - scoped_refptr<WebTaskRunner> task_runner = + scoped_refptr<base::SingleThreadTaskRunner> task_runner = GlobalScope()->GetTaskRunner(TaskType::kInternalTest); EXPECT_TRUE(task_runner->RunsTasksInCurrentSequence()); PostCrossThreadTask( @@ -132,9 +132,9 @@ std::make_unique<GlobalScopeCreationParams>( script_url, "fake user agent", headers.get(), kReferrerPolicyDefault, security_origin_.get(), - nullptr /* worker_clients */, mojom::IPAddressSpace::kLocal, - nullptr /* origin_trial_tokens */, std::move(worker_settings), - kV8CacheOptionsDefault), + false /* starter_secure_context */, nullptr /* worker_clients */, + mojom::IPAddressSpace::kLocal, nullptr /* origin_trial_tokens */, + std::move(worker_settings), kV8CacheOptionsDefault), WorkerBackingThreadStartupData( WorkerBackingThreadStartupData::HeapLimitMode::kDefault, WorkerBackingThreadStartupData::AtomicsWaitMode::kAllow));
diff --git a/third_party/WebKit/Source/core/workers/DedicatedWorkerThread.cpp b/third_party/WebKit/Source/core/workers/DedicatedWorkerThread.cpp index ecd5eda..f692ee8 100644 --- a/third_party/WebKit/Source/core/workers/DedicatedWorkerThread.cpp +++ b/third_party/WebKit/Source/core/workers/DedicatedWorkerThread.cpp
@@ -52,7 +52,7 @@ DedicatedWorkerObjectProxy& worker_object_proxy) : WorkerThread(loading_context, worker_object_proxy), worker_backing_thread_(WorkerBackingThread::Create( - WebThreadCreationParams("DedicatedWorker Thread"))), + WebThreadCreationParams(GetThreadType()))), worker_object_proxy_(worker_object_proxy) {} DedicatedWorkerThread::~DedicatedWorkerThread() = default;
diff --git a/third_party/WebKit/Source/core/workers/DedicatedWorkerThread.h b/third_party/WebKit/Source/core/workers/DedicatedWorkerThread.h index db8e776..47472165 100644 --- a/third_party/WebKit/Source/core/workers/DedicatedWorkerThread.h +++ b/third_party/WebKit/Source/core/workers/DedicatedWorkerThread.h
@@ -60,8 +60,8 @@ WorkerOrWorkletGlobalScope* CreateWorkerGlobalScope( std::unique_ptr<GlobalScopeCreationParams>) override; - scheduler::ThreadType GetThreadType() const override { - return scheduler::ThreadType::kDedicatedWorkerThread; + WebThreadType GetThreadType() const override { + return WebThreadType::kDedicatedWorkerThread; } std::unique_ptr<WorkerBackingThread> worker_backing_thread_;
diff --git a/third_party/WebKit/Source/core/workers/GlobalScopeCreationParams.cpp b/third_party/WebKit/Source/core/workers/GlobalScopeCreationParams.cpp index 4b5ab2a..9e11647 100644 --- a/third_party/WebKit/Source/core/workers/GlobalScopeCreationParams.cpp +++ b/third_party/WebKit/Source/core/workers/GlobalScopeCreationParams.cpp
@@ -16,6 +16,7 @@ const Vector<CSPHeaderAndType>* content_security_policy_parsed_headers, ReferrerPolicy referrer_policy, const SecurityOrigin* starter_origin, + bool starter_secure_context, WorkerClients* worker_clients, mojom::IPAddressSpace address_space, const Vector<String>* origin_trial_tokens, @@ -27,6 +28,7 @@ user_agent(user_agent.IsolatedCopy()), referrer_policy(referrer_policy), starter_origin(starter_origin ? starter_origin->IsolatedCopy() : nullptr), + starter_secure_context(starter_secure_context), worker_clients(worker_clients), address_space(address_space), worker_settings(std::move(worker_settings)),
diff --git a/third_party/WebKit/Source/core/workers/GlobalScopeCreationParams.h b/third_party/WebKit/Source/core/workers/GlobalScopeCreationParams.h index 3a1c32e..af8f129 100644 --- a/third_party/WebKit/Source/core/workers/GlobalScopeCreationParams.h +++ b/third_party/WebKit/Source/core/workers/GlobalScopeCreationParams.h
@@ -38,6 +38,7 @@ const Vector<CSPHeaderAndType>* content_security_policy_parsed_headers, ReferrerPolicy referrer_policy, const SecurityOrigin*, + bool starter_secure_context, WorkerClients*, mojom::IPAddressSpace, const Vector<String>* origin_trial_tokens, @@ -76,6 +77,15 @@ // script loader uses Document's SecurityOrigin for security checks. scoped_refptr<const SecurityOrigin> starter_origin; + // Indicates if the Document creating a Worker/Worklet is a secure context. + // + // Worklets are defined to have a unique, opaque origin, so are not secure: + // https://drafts.css-houdini.org/worklets/#script-settings-for-worklets + // Origin trials are only enabled in secure contexts, and the trial tokens are + // inherited from the document, so also consider the context of the document. + // The value should be supplied as the result of Document.IsSecureContext(). + bool starter_secure_context; + // This object is created and initialized on the thread creating // a new worker context, but ownership of it and this // GlobalScopeCreationParams structure is passed along to the new worker
diff --git a/third_party/WebKit/Source/core/workers/MainThreadWorkletGlobalScope.cpp b/third_party/WebKit/Source/core/workers/MainThreadWorkletGlobalScope.cpp index 81361d6..5e8812f 100644 --- a/third_party/WebKit/Source/core/workers/MainThreadWorkletGlobalScope.cpp +++ b/third_party/WebKit/Source/core/workers/MainThreadWorkletGlobalScope.cpp
@@ -32,8 +32,8 @@ return nullptr; } -scoped_refptr<WebTaskRunner> MainThreadWorkletGlobalScope::GetTaskRunner( - TaskType type) { +scoped_refptr<base::SingleThreadTaskRunner> +MainThreadWorkletGlobalScope::GetTaskRunner(TaskType type) { DCHECK(IsContextThread()); // MainThreadWorkletGlobalScope lives on the main thread and its GetThread() // doesn't return a valid worker thread. Instead, retrieve a task runner
diff --git a/third_party/WebKit/Source/core/workers/MainThreadWorkletGlobalScope.h b/third_party/WebKit/Source/core/workers/MainThreadWorkletGlobalScope.h index 4a23f7a..74cadb85b 100644 --- a/third_party/WebKit/Source/core/workers/MainThreadWorkletGlobalScope.h +++ b/third_party/WebKit/Source/core/workers/MainThreadWorkletGlobalScope.h
@@ -31,7 +31,7 @@ // WorkerOrWorkletGlobalScope WorkerThread* GetThread() const final; - scoped_refptr<WebTaskRunner> GetTaskRunner(TaskType) override; + scoped_refptr<base::SingleThreadTaskRunner> GetTaskRunner(TaskType) override; void Terminate();
diff --git a/third_party/WebKit/Source/core/workers/MainThreadWorkletTest.cpp b/third_party/WebKit/Source/core/workers/MainThreadWorkletTest.cpp index fc3ed0d..2c69a061b 100644 --- a/third_party/WebKit/Source/core/workers/MainThreadWorkletTest.cpp +++ b/third_party/WebKit/Source/core/workers/MainThreadWorkletTest.cpp
@@ -62,8 +62,8 @@ document->Url(), document->UserAgent(), document->GetContentSecurityPolicy()->Headers().get(), document->GetReferrerPolicy(), document->GetSecurityOrigin(), - nullptr /* worker_clients */, document->AddressSpace(), - OriginTrialContext::GetTokens(document).get(), + document->IsSecureContext(), nullptr /* worker_clients */, + document->AddressSpace(), OriginTrialContext::GetTokens(document).get(), nullptr /* worker_settings */, kV8CacheOptionsDefault); global_scope_ = new MainThreadWorkletGlobalScope( &page_->GetFrame(), std::move(creation_params), *reporting_proxy_); @@ -133,7 +133,7 @@ } TEST_F(MainThreadWorkletTest, TaskRunner) { - scoped_refptr<WebTaskRunner> task_runner = + scoped_refptr<base::SingleThreadTaskRunner> task_runner = global_scope_->GetTaskRunner(TaskType::kInternalTest); EXPECT_TRUE(task_runner->RunsTasksInCurrentSequence()); }
diff --git a/third_party/WebKit/Source/core/workers/ParentFrameTaskRunners.cpp b/third_party/WebKit/Source/core/workers/ParentFrameTaskRunners.cpp index 048712f..028afb51 100644 --- a/third_party/WebKit/Source/core/workers/ParentFrameTaskRunners.cpp +++ b/third_party/WebKit/Source/core/workers/ParentFrameTaskRunners.cpp
@@ -38,7 +38,8 @@ } } -scoped_refptr<WebTaskRunner> ParentFrameTaskRunners::Get(TaskType type) { +scoped_refptr<base::SingleThreadTaskRunner> ParentFrameTaskRunners::Get( + TaskType type) { MutexLocker lock(task_runners_mutex_); return task_runners_.at(type); }
diff --git a/third_party/WebKit/Source/core/workers/ParentFrameTaskRunners.h b/third_party/WebKit/Source/core/workers/ParentFrameTaskRunners.h index 7d219fd..838930e 100644 --- a/third_party/WebKit/Source/core/workers/ParentFrameTaskRunners.h +++ b/third_party/WebKit/Source/core/workers/ParentFrameTaskRunners.h
@@ -7,10 +7,10 @@ #include <memory> #include "base/macros.h" +#include "base/single_thread_task_runner.h" #include "core/CoreExport.h" #include "core/dom/ContextLifecycleObserver.h" #include "core/dom/TaskTypeTraits.h" -#include "platform/WebTaskRunner.h" #include "platform/heap/Handle.h" #include "platform/wtf/Allocator.h" #include "platform/wtf/PtrUtil.h" @@ -41,13 +41,13 @@ // Might return nullptr for unsupported task types. This can be called from // any threads. - scoped_refptr<WebTaskRunner> Get(TaskType); + scoped_refptr<base::SingleThreadTaskRunner> Get(TaskType); void Trace(blink::Visitor*) override; private: using TaskRunnerHashMap = HashMap<TaskType, - scoped_refptr<WebTaskRunner>, + scoped_refptr<base::SingleThreadTaskRunner>, WTF::IntHash<TaskType>, TaskTypeTraits>;
diff --git a/third_party/WebKit/Source/core/workers/SharedWorkerThread.cpp b/third_party/WebKit/Source/core/workers/SharedWorkerThread.cpp index 7635fb1..84f42d9 100644 --- a/third_party/WebKit/Source/core/workers/SharedWorkerThread.cpp +++ b/third_party/WebKit/Source/core/workers/SharedWorkerThread.cpp
@@ -44,7 +44,7 @@ WorkerReportingProxy& worker_reporting_proxy) : WorkerThread(loading_context, worker_reporting_proxy), worker_backing_thread_(WorkerBackingThread::Create( - WebThreadCreationParams("SharedWorker Thread"))), + WebThreadCreationParams(GetThreadType()))), name_(name.IsolatedCopy()) {} SharedWorkerThread::~SharedWorkerThread() = default;
diff --git a/third_party/WebKit/Source/core/workers/SharedWorkerThread.h b/third_party/WebKit/Source/core/workers/SharedWorkerThread.h index e3bd99c..e2d17ea 100644 --- a/third_party/WebKit/Source/core/workers/SharedWorkerThread.h +++ b/third_party/WebKit/Source/core/workers/SharedWorkerThread.h
@@ -55,8 +55,8 @@ WorkerOrWorkletGlobalScope* CreateWorkerGlobalScope( std::unique_ptr<GlobalScopeCreationParams>) override; - scheduler::ThreadType GetThreadType() const override { - return scheduler::ThreadType::kSharedWorkerThread; + WebThreadType GetThreadType() const override { + return WebThreadType::kSharedWorkerThread; } std::unique_ptr<WorkerBackingThread> worker_backing_thread_;
diff --git a/third_party/WebKit/Source/core/workers/ThreadedWorkletMessagingProxy.cpp b/third_party/WebKit/Source/core/workers/ThreadedWorkletMessagingProxy.cpp index 8b15d200..b64cc15cf 100644 --- a/third_party/WebKit/Source/core/workers/ThreadedWorkletMessagingProxy.cpp +++ b/third_party/WebKit/Source/core/workers/ThreadedWorkletMessagingProxy.cpp
@@ -4,6 +4,7 @@ #include "core/workers/ThreadedWorkletMessagingProxy.h" +#include "base/single_thread_task_runner.h" #include "bindings/core/v8/V8CacheOptions.h" #include "core/dom/Document.h" #include "core/dom/SecurityContext.h" @@ -41,7 +42,7 @@ std::make_unique<GlobalScopeCreationParams>( document->Url(), document->UserAgent(), csp->Headers().get(), document->GetReferrerPolicy(), document->GetSecurityOrigin(), - worker_clients, document->AddressSpace(), + document->IsSecureContext(), worker_clients, document->AddressSpace(), OriginTrialContext::GetTokens(document).get(), std::make_unique<WorkerSettings>(document->GetSettings()), kV8CacheOptionsDefault); @@ -59,7 +60,7 @@ const KURL& module_url_record, WorkletModuleResponsesMap* module_responses_map, network::mojom::FetchCredentialsMode credentials_mode, - scoped_refptr<WebTaskRunner> outside_settings_task_runner, + scoped_refptr<base::SingleThreadTaskRunner> outside_settings_task_runner, WorkletPendingTasks* pending_tasks) { DCHECK(IsMainThread()); PostCrossThreadTask(
diff --git a/third_party/WebKit/Source/core/workers/ThreadedWorkletMessagingProxy.h b/third_party/WebKit/Source/core/workers/ThreadedWorkletMessagingProxy.h index 6dbd2e1c..06053b4 100644 --- a/third_party/WebKit/Source/core/workers/ThreadedWorkletMessagingProxy.h +++ b/third_party/WebKit/Source/core/workers/ThreadedWorkletMessagingProxy.h
@@ -25,7 +25,7 @@ const KURL& module_url_record, WorkletModuleResponsesMap*, network::mojom::FetchCredentialsMode, - scoped_refptr<WebTaskRunner> outside_settings_task_runner, + scoped_refptr<base::SingleThreadTaskRunner> outside_settings_task_runner, WorkletPendingTasks*) final; void WorkletObjectDestroyed() final; void TerminateWorkletGlobalScope() final;
diff --git a/third_party/WebKit/Source/core/workers/ThreadedWorkletObjectProxy.cpp b/third_party/WebKit/Source/core/workers/ThreadedWorkletObjectProxy.cpp index 177bbb51..f947b7a 100644 --- a/third_party/WebKit/Source/core/workers/ThreadedWorkletObjectProxy.cpp +++ b/third_party/WebKit/Source/core/workers/ThreadedWorkletObjectProxy.cpp
@@ -26,7 +26,7 @@ const KURL& module_url_record, WorkletModuleResponsesMap* module_responses_map, network::mojom::FetchCredentialsMode credentials_mode, - scoped_refptr<WebTaskRunner> outside_settings_task_runner, + scoped_refptr<base::SingleThreadTaskRunner> outside_settings_task_runner, WorkletPendingTasks* pending_tasks, WorkerThread* worker_thread) { ThreadedWorkletGlobalScope* global_scope =
diff --git a/third_party/WebKit/Source/core/workers/ThreadedWorkletObjectProxy.h b/third_party/WebKit/Source/core/workers/ThreadedWorkletObjectProxy.h index e54808a..b4529fd 100644 --- a/third_party/WebKit/Source/core/workers/ThreadedWorkletObjectProxy.h +++ b/third_party/WebKit/Source/core/workers/ThreadedWorkletObjectProxy.h
@@ -6,10 +6,10 @@ #define ThreadedWorkletObjectProxy_h #include "base/macros.h" +#include "base/single_thread_task_runner.h" #include "core/CoreExport.h" #include "core/workers/ThreadedObjectProxyBase.h" #include "core/workers/WorkerReportingProxy.h" -#include "platform/WebTaskRunner.h" #include "public/platform/WebURLRequest.h" namespace blink { @@ -37,7 +37,7 @@ const KURL& module_url_record, WorkletModuleResponsesMap*, network::mojom::FetchCredentialsMode, - scoped_refptr<WebTaskRunner> outside_settings_task_runner, + scoped_refptr<base::SingleThreadTaskRunner> outside_settings_task_runner, WorkletPendingTasks*, WorkerThread*);
diff --git a/third_party/WebKit/Source/core/workers/ThreadedWorkletTest.cpp b/third_party/WebKit/Source/core/workers/ThreadedWorkletTest.cpp index b782298..ccf4aae 100644 --- a/third_party/WebKit/Source/core/workers/ThreadedWorkletTest.cpp +++ b/third_party/WebKit/Source/core/workers/ThreadedWorkletTest.cpp
@@ -69,7 +69,8 @@ static void EnsureSharedBackingThread() { DCHECK(IsMainThread()); WorkletThreadHolder<ThreadedWorkletThreadForTest>::CreateForTest( - WebThreadCreationParams("ThreadedWorkletThreadForTest")); + WebThreadCreationParams(WebThreadType::kTestThread) + .SetThreadName("ThreadedWorkletThreadForTest")); } static void ClearSharedBackingThread() { @@ -138,7 +139,7 @@ void TestTaskRunner() { EXPECT_TRUE(IsCurrentThread()); - scoped_refptr<WebTaskRunner> task_runner = + scoped_refptr<base::SingleThreadTaskRunner> task_runner = GlobalScope()->GetTaskRunner(TaskType::kInternalTest); EXPECT_TRUE(task_runner->RunsTasksInCurrentSequence()); PostCrossThreadTask( @@ -155,8 +156,8 @@ bool IsOwningBackingThread() const final { return false; } - scheduler::ThreadType GetThreadType() const override { - return scheduler::ThreadType::kUnspecifiedWorkerThread; + WebThreadType GetThreadType() const override { + return WebThreadType::kUnspecifiedWorkerThread; } }; @@ -182,7 +183,8 @@ document->Url(), document->UserAgent(), document->GetContentSecurityPolicy()->Headers().get(), document->GetReferrerPolicy(), document->GetSecurityOrigin(), - worker_clients, document->AddressSpace(), + document->IsSecureContext(), worker_clients, + document->AddressSpace(), OriginTrialContext::GetTokens(document).get(), std::move(worker_settings), kV8CacheOptionsDefault), WTF::nullopt);
diff --git a/third_party/WebKit/Source/core/workers/WorkerInspectorProxy.cpp b/third_party/WebKit/Source/core/workers/WorkerInspectorProxy.cpp index d02bd173..bb827d8 100644 --- a/third_party/WebKit/Source/core/workers/WorkerInspectorProxy.cpp +++ b/third_party/WebKit/Source/core/workers/WorkerInspectorProxy.cpp
@@ -14,7 +14,6 @@ #include "core/workers/WorkerGlobalScope.h" #include "core/workers/WorkerThread.h" #include "platform/CrossThreadFunctional.h" -#include "platform/WebTaskRunner.h" #include "platform/instrumentation/tracing/TraceEvent.h" #include "platform/weborigin/KURL.h"
diff --git a/third_party/WebKit/Source/core/workers/WorkerOrWorkletGlobalScope.cpp b/third_party/WebKit/Source/core/workers/WorkerOrWorkletGlobalScope.cpp index d6f05b22..6a95a61 100644 --- a/third_party/WebKit/Source/core/workers/WorkerOrWorkletGlobalScope.cpp +++ b/third_party/WebKit/Source/core/workers/WorkerOrWorkletGlobalScope.cpp
@@ -176,8 +176,8 @@ modulator_ = modulator; } -scoped_refptr<WebTaskRunner> WorkerOrWorkletGlobalScope::GetTaskRunner( - TaskType type) { +scoped_refptr<base::SingleThreadTaskRunner> +WorkerOrWorkletGlobalScope::GetTaskRunner(TaskType type) { DCHECK(IsContextThread()); return GetThread()->GetTaskRunner(type); }
diff --git a/third_party/WebKit/Source/core/workers/WorkerOrWorkletGlobalScope.h b/third_party/WebKit/Source/core/workers/WorkerOrWorkletGlobalScope.h index fcce23f..37999029 100644 --- a/third_party/WebKit/Source/core/workers/WorkerOrWorkletGlobalScope.h +++ b/third_party/WebKit/Source/core/workers/WorkerOrWorkletGlobalScope.h
@@ -100,7 +100,7 @@ void Trace(blink::Visitor*) override; void TraceWrappers(const ScriptWrappableVisitor*) const override; - scoped_refptr<WebTaskRunner> GetTaskRunner(TaskType) override; + scoped_refptr<base::SingleThreadTaskRunner> GetTaskRunner(TaskType) override; protected: void ApplyContentSecurityPolicyFromVector(
diff --git a/third_party/WebKit/Source/core/workers/WorkerThread.h b/third_party/WebKit/Source/core/workers/WorkerThread.h index 557e0f6..3243eee5 100644 --- a/third_party/WebKit/Source/core/workers/WorkerThread.h +++ b/third_party/WebKit/Source/core/workers/WorkerThread.h
@@ -30,6 +30,7 @@ #include <memory> #include "base/memory/scoped_refptr.h" +#include "base/single_thread_task_runner.h" #include "core/CoreExport.h" #include "core/frame/csp/ContentSecurityPolicy.h" #include "core/loader/ThreadableLoadingContext.h" @@ -41,11 +42,11 @@ #include "platform/WaitableEvent.h" #include "platform/WebTaskRunner.h" #include "platform/scheduler/child/worker_global_scope_scheduler.h" -#include "platform/scheduler/util/thread_type.h" #include "platform/wtf/Forward.h" #include "platform/wtf/Functional.h" #include "platform/wtf/Optional.h" #include "public/platform/WebThread.h" +#include "public/platform/WebThreadType.h" #include "services/network/public/interfaces/fetch_api.mojom-shared.h" #include "v8/include/v8.h" @@ -194,14 +195,14 @@ } // Can be called on both the main thread and the worker thread. - scoped_refptr<WebTaskRunner> GetTaskRunner(TaskType type) { + scoped_refptr<base::SingleThreadTaskRunner> GetTaskRunner(TaskType type) { return global_scope_scheduler_->GetTaskRunner(type); } protected: WorkerThread(ThreadableLoadingContext*, WorkerReportingProxy&); - virtual scheduler::ThreadType GetThreadType() const = 0; + virtual WebThreadType GetThreadType() const = 0; // Official moment of creation of worker: when the worker thread is created. // (https://w3c.github.io/hr-time/#time-origin)
diff --git a/third_party/WebKit/Source/core/workers/WorkerThreadTest.cpp b/third_party/WebKit/Source/core/workers/WorkerThreadTest.cpp index 1f24f389..2c8021e 100644 --- a/third_party/WebKit/Source/core/workers/WorkerThreadTest.cpp +++ b/third_party/WebKit/Source/core/workers/WorkerThreadTest.cpp
@@ -300,8 +300,8 @@ std::make_unique<GlobalScopeCreationParams>( KURL("http://fake.url/"), "fake user agent", headers.get(), kReferrerPolicyDefault, security_origin_.get(), - nullptr /* workerClients */, mojom::IPAddressSpace::kLocal, - nullptr /* originTrialToken */, + false /* starter_secure_context */, nullptr /* workerClients */, + mojom::IPAddressSpace::kLocal, nullptr /* originTrialToken */, std::make_unique<WorkerSettings>(Settings::Create().get()), kV8CacheOptionsDefault);
diff --git a/third_party/WebKit/Source/core/workers/WorkerThreadTestHelper.h b/third_party/WebKit/Source/core/workers/WorkerThreadTestHelper.h index c232522..b372b56 100644 --- a/third_party/WebKit/Source/core/workers/WorkerThreadTestHelper.h +++ b/third_party/WebKit/Source/core/workers/WorkerThreadTestHelper.h
@@ -81,7 +81,7 @@ WorkerReportingProxy& mock_worker_reporting_proxy) : WorkerThread(loading_context, mock_worker_reporting_proxy), worker_backing_thread_(WorkerBackingThread::CreateForTest( - WebThreadCreationParams("Test thread"))) {} + WebThreadCreationParams(WebThreadType::kTestThread))) {} ~WorkerThreadForTest() override = default; @@ -102,7 +102,8 @@ auto creation_params = std::make_unique<GlobalScopeCreationParams>( script_url, "fake user agent", headers.get(), kReferrerPolicyDefault, - security_origin, worker_clients, mojom::IPAddressSpace::kLocal, nullptr, + security_origin, false /* starter_secure_context */, worker_clients, + mojom::IPAddressSpace::kLocal, nullptr, std::make_unique<WorkerSettings>(Settings::Create().get()), kV8CacheOptionsDefault); @@ -129,8 +130,8 @@ } private: - scheduler::ThreadType GetThreadType() const override { - return scheduler::ThreadType::kUnspecifiedWorkerThread; + WebThreadType GetThreadType() const override { + return WebThreadType::kUnspecifiedWorkerThread; } std::unique_ptr<WorkerBackingThread> worker_backing_thread_;
diff --git a/third_party/WebKit/Source/core/workers/Worklet.cpp b/third_party/WebKit/Source/core/workers/Worklet.cpp index b3a1274..e5b1d295 100644 --- a/third_party/WebKit/Source/core/workers/Worklet.cpp +++ b/third_party/WebKit/Source/core/workers/Worklet.cpp
@@ -4,12 +4,12 @@ #include "core/workers/Worklet.h" +#include "base/single_thread_task_runner.h" #include "bindings/core/v8/ScriptPromiseResolver.h" #include "core/dom/DOMException.h" #include "core/dom/Document.h" #include "core/fetch/Request.h" #include "core/workers/WorkletPendingTasks.h" -#include "platform/WebTaskRunner.h" #include "platform/wtf/WTF.h" #include "public/platform/TaskType.h" #include "public/platform/WebURLRequest.h" @@ -106,7 +106,7 @@ // document's responsible event loop. In our implementation, we use the // document's UnspecedLoading task runner as that is what we commonly use for // module loading. - scoped_refptr<WebTaskRunner> outside_settings_task_runner = + scoped_refptr<base::SingleThreadTaskRunner> outside_settings_task_runner = GetExecutionContext()->GetTaskRunner(TaskType::kUnspecedLoading); // Step 8: "Let moduleResponsesMap be worklet's module responses map."
diff --git a/third_party/WebKit/Source/core/workers/WorkletGlobalScope.cpp b/third_party/WebKit/Source/core/workers/WorkletGlobalScope.cpp index 617a09dd..35b83b4d 100644 --- a/third_party/WebKit/Source/core/workers/WorkletGlobalScope.cpp +++ b/third_party/WebKit/Source/core/workers/WorkletGlobalScope.cpp
@@ -9,6 +9,7 @@ #include "bindings/core/v8/SourceLocation.h" #include "bindings/core/v8/WorkerOrWorkletScriptController.h" #include "core/inspector/MainThreadDebugger.h" +#include "core/origin_trials/OriginTrialContext.h" #include "core/probe/CoreProbes.h" #include "core/script/Modulator.h" #include "core/workers/GlobalScopeCreationParams.h" @@ -33,7 +34,8 @@ reporting_proxy), url_(creation_params->script_url), user_agent_(creation_params->user_agent), - document_security_origin_(creation_params->starter_origin) { + document_security_origin_(creation_params->starter_origin), + document_secure_context_(creation_params->starter_secure_context) { // Step 2: "Let inheritedAPIBaseURL be outsideSettings's API base URL." // |url_| is the inheritedAPIBaseURL passed from the parent Document. @@ -48,6 +50,9 @@ // workletGlobalScope." ApplyContentSecurityPolicyFromVector( *creation_params->content_security_policy_parsed_headers); + + OriginTrialContext::AddTokens(this, + creation_params->origin_trial_tokens.get()); } WorkletGlobalScope::~WorkletGlobalScope() = default; @@ -73,7 +78,7 @@ const KURL& module_url_record, WorkletModuleResponsesMap* module_responses_map, network::mojom::FetchCredentialsMode credentials_mode, - scoped_refptr<WebTaskRunner> outside_settings_task_runner, + scoped_refptr<base::SingleThreadTaskRunner> outside_settings_task_runner, WorkletPendingTasks* pending_tasks) { DCHECK(IsContextThread()); if (!module_responses_map_proxy_) {
diff --git a/third_party/WebKit/Source/core/workers/WorkletGlobalScope.h b/third_party/WebKit/Source/core/workers/WorkletGlobalScope.h index 813b55d..c27368c4 100644 --- a/third_party/WebKit/Source/core/workers/WorkletGlobalScope.h +++ b/third_party/WebKit/Source/core/workers/WorkletGlobalScope.h
@@ -6,13 +6,13 @@ #define WorkletGlobalScope_h #include <memory> +#include "base/single_thread_task_runner.h" #include "bindings/core/v8/ActiveScriptWrappable.h" #include "core/CoreExport.h" #include "core/dom/ExecutionContext.h" #include "core/inspector/ConsoleMessage.h" #include "core/workers/WorkerOrWorkletGlobalScope.h" #include "core/workers/WorkletModuleResponsesMapProxy.h" -#include "platform/WebTaskRunner.h" #include "platform/bindings/ScriptWrappable.h" #include "platform/bindings/TraceWrapperMember.h" #include "platform/heap/Handle.h" @@ -66,7 +66,7 @@ const KURL& module_url_record, WorkletModuleResponsesMap*, network::mojom::FetchCredentialsMode, - scoped_refptr<WebTaskRunner> outside_settings_task_runner, + scoped_refptr<base::SingleThreadTaskRunner> outside_settings_task_runner, WorkletPendingTasks*); WorkletModuleResponsesMapProxy* ModuleResponsesMapProxy() const; @@ -76,6 +76,15 @@ return document_security_origin_.get(); } + // Customize the security context used for origin trials. + // Origin trials are only enabled in secure contexts, but WorkletGlobalScopes + // are defined to have a unique, opaque origin, so are not secure: + // https://drafts.css-houdini.org/worklets/#script-settings-for-worklets + // For origin trials, instead consider the context of the document which + // created the worklet, since the origin trial tokens are inherited from the + // document. + bool DocumentSecureContext() const { return document_secure_context_; } + void Trace(blink::Visitor*) override; void TraceWrappers(const ScriptWrappableVisitor*) const override; @@ -94,9 +103,13 @@ const KURL url_; const String user_agent_; - // Used for module fetch. + // Used for module fetch and origin trials, inherited from the parent + // Document. const scoped_refptr<const SecurityOrigin> document_security_origin_; + // Used for origin trials, inherited from the parent Document. + const bool document_secure_context_; + Member<WorkletModuleResponsesMapProxy> module_responses_map_proxy_; };
diff --git a/third_party/WebKit/Source/core/workers/WorkletGlobalScopeProxy.h b/third_party/WebKit/Source/core/workers/WorkletGlobalScopeProxy.h index f4cb535..6a9d76e 100644 --- a/third_party/WebKit/Source/core/workers/WorkletGlobalScopeProxy.h +++ b/third_party/WebKit/Source/core/workers/WorkletGlobalScopeProxy.h
@@ -5,8 +5,8 @@ #ifndef WorkletGlobalScopeProxy_h #define WorkletGlobalScopeProxy_h +#include "base/single_thread_task_runner.h" #include "core/CoreExport.h" -#include "platform/WebTaskRunner.h" #include "platform/heap/GarbageCollected.h" #include "platform/weborigin/KURL.h" #include "public/platform/WebURLRequest.h" @@ -29,7 +29,7 @@ const KURL& module_url_record, WorkletModuleResponsesMap*, network::mojom::FetchCredentialsMode, - scoped_refptr<WebTaskRunner> outside_settings_task_runner, + scoped_refptr<base::SingleThreadTaskRunner> outside_settings_task_runner, WorkletPendingTasks*) = 0; // Notifies that the Worklet object is destroyed. This should be called in the
diff --git a/third_party/WebKit/Source/core/workers/WorkletModuleResponsesMapProxy.cpp b/third_party/WebKit/Source/core/workers/WorkletModuleResponsesMapProxy.cpp index c13fb18..1a5374b 100644 --- a/third_party/WebKit/Source/core/workers/WorkletModuleResponsesMapProxy.cpp +++ b/third_party/WebKit/Source/core/workers/WorkletModuleResponsesMapProxy.cpp
@@ -26,7 +26,7 @@ public: static ClientAdapter* Create( WorkletModuleResponsesMap::Client* client, - scoped_refptr<WebTaskRunner> inside_settings_task_runner) { + scoped_refptr<base::SingleThreadTaskRunner> inside_settings_task_runner) { return new ClientAdapter(client, std::move(inside_settings_task_runner)); } @@ -50,21 +50,22 @@ void Trace(blink::Visitor* visitor) override {} private: - ClientAdapter(WorkletModuleResponsesMap::Client* client, - scoped_refptr<WebTaskRunner> inside_settings_task_runner) + ClientAdapter( + WorkletModuleResponsesMap::Client* client, + scoped_refptr<base::SingleThreadTaskRunner> inside_settings_task_runner) : client_(client), inside_settings_task_runner_(std::move(inside_settings_task_runner)) {} CrossThreadPersistent<WorkletModuleResponsesMap::Client> client_; - scoped_refptr<WebTaskRunner> inside_settings_task_runner_; + scoped_refptr<base::SingleThreadTaskRunner> inside_settings_task_runner_; }; } // namespace WorkletModuleResponsesMapProxy* WorkletModuleResponsesMapProxy::Create( WorkletModuleResponsesMap* module_responses_map, - scoped_refptr<WebTaskRunner> outside_settings_task_runner, - scoped_refptr<WebTaskRunner> inside_settings_task_runner) { + scoped_refptr<base::SingleThreadTaskRunner> outside_settings_task_runner, + scoped_refptr<base::SingleThreadTaskRunner> inside_settings_task_runner) { return new WorkletModuleResponsesMapProxy( module_responses_map, std::move(outside_settings_task_runner), std::move(inside_settings_task_runner)); @@ -85,8 +86,8 @@ WorkletModuleResponsesMapProxy::WorkletModuleResponsesMapProxy( WorkletModuleResponsesMap* module_responses_map, - scoped_refptr<WebTaskRunner> outside_settings_task_runner, - scoped_refptr<WebTaskRunner> inside_settings_task_runner) + scoped_refptr<base::SingleThreadTaskRunner> outside_settings_task_runner, + scoped_refptr<base::SingleThreadTaskRunner> inside_settings_task_runner) : module_responses_map_(module_responses_map), outside_settings_task_runner_(outside_settings_task_runner), inside_settings_task_runner_(inside_settings_task_runner) {
diff --git a/third_party/WebKit/Source/core/workers/WorkletModuleResponsesMapProxy.h b/third_party/WebKit/Source/core/workers/WorkletModuleResponsesMapProxy.h index dc6498b..292e3f6e 100644 --- a/third_party/WebKit/Source/core/workers/WorkletModuleResponsesMapProxy.h +++ b/third_party/WebKit/Source/core/workers/WorkletModuleResponsesMapProxy.h
@@ -5,9 +5,9 @@ #ifndef WorkletModuleResponsesMapProxy_h #define WorkletModuleResponsesMapProxy_h +#include "base/single_thread_task_runner.h" #include "core/CoreExport.h" #include "core/workers/WorkletModuleResponsesMap.h" -#include "platform/WebTaskRunner.h" #include "platform/heap/Heap.h" namespace blink { @@ -24,8 +24,8 @@ static WorkletModuleResponsesMapProxy* Create( WorkletModuleResponsesMap*, - scoped_refptr<WebTaskRunner> outside_settings_task_runner, - scoped_refptr<WebTaskRunner> inside_settings_task_runner); + scoped_refptr<base::SingleThreadTaskRunner> outside_settings_task_runner, + scoped_refptr<base::SingleThreadTaskRunner> inside_settings_task_runner); void ReadEntry(const FetchParameters&, Client*); @@ -34,15 +34,15 @@ private: WorkletModuleResponsesMapProxy( WorkletModuleResponsesMap*, - scoped_refptr<WebTaskRunner> outside_settings_task_runner, - scoped_refptr<WebTaskRunner> inside_settings_task_runner); + scoped_refptr<base::SingleThreadTaskRunner> outside_settings_task_runner, + scoped_refptr<base::SingleThreadTaskRunner> inside_settings_task_runner); void ReadEntryOnMainThread(std::unique_ptr<CrossThreadFetchParametersData>, Client*); CrossThreadPersistent<WorkletModuleResponsesMap> module_responses_map_; - scoped_refptr<WebTaskRunner> outside_settings_task_runner_; - scoped_refptr<WebTaskRunner> inside_settings_task_runner_; + scoped_refptr<base::SingleThreadTaskRunner> outside_settings_task_runner_; + scoped_refptr<base::SingleThreadTaskRunner> inside_settings_task_runner_; }; } // namespace blink
diff --git a/third_party/WebKit/Source/core/workers/WorkletModuleTreeClient.cpp b/third_party/WebKit/Source/core/workers/WorkletModuleTreeClient.cpp index 75363d145..0f815ba9 100644 --- a/third_party/WebKit/Source/core/workers/WorkletModuleTreeClient.cpp +++ b/third_party/WebKit/Source/core/workers/WorkletModuleTreeClient.cpp
@@ -14,7 +14,7 @@ WorkletModuleTreeClient::WorkletModuleTreeClient( Modulator* modulator, - scoped_refptr<WebTaskRunner> outside_settings_task_runner, + scoped_refptr<base::SingleThreadTaskRunner> outside_settings_task_runner, WorkletPendingTasks* pending_tasks) : modulator_(modulator), outside_settings_task_runner_(std::move(outside_settings_task_runner)),
diff --git a/third_party/WebKit/Source/core/workers/WorkletModuleTreeClient.h b/third_party/WebKit/Source/core/workers/WorkletModuleTreeClient.h index 08f4b1f..f410c0e 100644 --- a/third_party/WebKit/Source/core/workers/WorkletModuleTreeClient.h +++ b/third_party/WebKit/Source/core/workers/WorkletModuleTreeClient.h
@@ -5,9 +5,9 @@ #ifndef WorkletModuleTreeClient_h #define WorkletModuleTreeClient_h +#include "base/single_thread_task_runner.h" #include "core/script/Modulator.h" #include "core/workers/WorkletPendingTasks.h" -#include "platform/WebTaskRunner.h" #include "platform/heap/GarbageCollected.h" namespace blink { @@ -19,7 +19,7 @@ public: WorkletModuleTreeClient( Modulator*, - scoped_refptr<WebTaskRunner> outside_settings_task_runner, + scoped_refptr<base::SingleThreadTaskRunner> outside_settings_task_runner, WorkletPendingTasks*); // Implements ModuleTreeClient. @@ -29,7 +29,7 @@ private: Member<Modulator> modulator_; - scoped_refptr<WebTaskRunner> outside_settings_task_runner_; + scoped_refptr<base::SingleThreadTaskRunner> outside_settings_task_runner_; CrossThreadPersistent<WorkletPendingTasks> pending_tasks_; };
diff --git a/third_party/WebKit/Source/core/workers/WorkletThreadHolder.h b/third_party/WebKit/Source/core/workers/WorkletThreadHolder.h index 2833f079..d2484d5 100644 --- a/third_party/WebKit/Source/core/workers/WorkletThreadHolder.h +++ b/third_party/WebKit/Source/core/workers/WorkletThreadHolder.h
@@ -25,16 +25,6 @@ return thread_holder_instance_; } - static void EnsureInstance(const char* thread_name) { - DCHECK(IsMainThread()); - MutexLocker locker(HolderInstanceMutex()); - if (thread_holder_instance_) - return; - thread_holder_instance_ = new WorkletThreadHolder<DerivedWorkletThread>; - thread_holder_instance_->Initialize( - WorkerBackingThread::Create(WebThreadCreationParams(thread_name))); - } - static void EnsureInstance(WebThread* thread) { DCHECK(IsMainThread()); MutexLocker locker(HolderInstanceMutex());
diff --git a/third_party/WebKit/Source/core/xml/DocumentXMLTreeViewer.css b/third_party/WebKit/Source/core/xml/DocumentXMLTreeViewer.css index 192e5f3..6e0a0d9f 100644 --- a/third_party/WebKit/Source/core/xml/DocumentXMLTreeViewer.css +++ b/third_party/WebKit/Source/core/xml/DocumentXMLTreeViewer.css
@@ -43,11 +43,11 @@ } .collapse-button { - background: url("data:image/svg+xml,<svg xmlns='http://www.w3.org/2000/svg' fill='#909090' width='10' height='10'><path d='M0 0 L8 0 L4 7 Z'/></svg>"); + background: url("data:image/svg+xml,<svg xmlns='http://www.w3.org/2000/svg' fill='%23909090' width='10' height='10'><path d='M0 0 L8 0 L4 7 Z'/></svg>"); height: 10px; } .expand-button { - background: url("data:image/svg+xml,<svg xmlns='http://www.w3.org/2000/svg' fill='#909090' width='10' height='10'><path d='M0 0 L0 8 L7 4 Z'/></svg>"); + background: url("data:image/svg+xml,<svg xmlns='http://www.w3.org/2000/svg' fill='%23909090' width='10' height='10'><path d='M0 0 L0 8 L7 4 Z'/></svg>"); height: 10px; }
diff --git a/third_party/WebKit/Source/devtools/front_end/accessibility/module.json b/third_party/WebKit/Source/devtools/front_end/accessibility/module.json index 9ec17112..f0e42b34 100644 --- a/third_party/WebKit/Source/devtools/front_end/accessibility/module.json +++ b/third_party/WebKit/Source/devtools/front_end/accessibility/module.json
@@ -11,7 +11,6 @@ } ], "dependencies": ["elements"], - "experiment": "accessibilityInspection", "scripts": [ "AccessibilityModel.js", "AccessibilitySidebarView.js",
diff --git a/third_party/WebKit/Source/devtools/front_end/audits2/lighthouse/report-styles.css b/third_party/WebKit/Source/devtools/front_end/audits2/lighthouse/report-styles.css index b112fca..c5db5a2 100644 --- a/third_party/WebKit/Source/devtools/front_end/audits2/lighthouse/report-styles.css +++ b/third_party/WebKit/Source/devtools/front_end/audits2/lighthouse/report-styles.css
@@ -55,8 +55,8 @@ --lh-audit-hgap: 12px; --lh-audit-group-vpadding: 12px; --lh-section-vpadding: 12px; - --pass-icon-url: url('data:image/svg+xml;utf8,<svg width="12" height="12" viewBox="0 0 12 12" xmlns="http://www.w3.org/2000/svg"><path stroke="#007F04" stroke-width="1.5" d="M1 5.75l3.5 3.5 6.5-6.5" fill="none" fill-rule="evenodd"/></svg>'); - --fail-icon-url: url('data:image/svg+xml;utf8,<svg width="12" height="12" viewBox="0 0 12 12" xmlns="http://www.w3.org/2000/svg"><g stroke="#EE1D0A" stroke-width="1.5" fill="none" fill-rule="evenodd"><path d="M2 10l8-8M10 10L2 2"/></g></svg>'); + --pass-icon-url: url('data:image/svg+xml;utf8,<svg width="12" height="12" viewBox="0 0 12 12" xmlns="http://www.w3.org/2000/svg"><path stroke="%23007F04" stroke-width="1.5" d="M1 5.75l3.5 3.5 6.5-6.5" fill="none" fill-rule="evenodd"/></svg>'); + --fail-icon-url: url('data:image/svg+xml;utf8,<svg width="12" height="12" viewBox="0 0 12 12" xmlns="http://www.w3.org/2000/svg"><g stroke="%23EE1D0A" stroke-width="1.5" fill="none" fill-rule="evenodd"><path d="M2 10l8-8M10 10L2 2"/></g></svg>'); --collapsed-icon-url: url('data:image/svg+xml;utf8,<svg width="12" height="12" viewBox="0 0 12 12" xmlns="http://www.w3.org/2000/svg"><g fill="none" fill-rule="evenodd"><path fill="none" d="M0 0h12v12H0z"/><path fill="hsl(0, 0%, 60%)" d="M3 2l6 4-6 4z"/></g></svg>'); --expanded-icon-url: url('data:image/svg+xml;utf8,<svg width="12" height="12" viewBox="0 0 12 12" xmlns="http://www.w3.org/2000/svg"><g fill="none" fill-rule="evenodd"><path fill="none" d="M0 0h12v12H0z"/><path fill="hsl(0, 0%, 60%)" d="M10 3L6 9 2 3z"/></g></svg>'); }
diff --git a/third_party/WebKit/Source/devtools/front_end/audits2/lighthouse/templates.html b/third_party/WebKit/Source/devtools/front_end/audits2/lighthouse/templates.html index 4ca308ad..3a2bc90 100644 --- a/third_party/WebKit/Source/devtools/front_end/audits2/lighthouse/templates.html +++ b/third_party/WebKit/Source/devtools/front_end/audits2/lighthouse/templates.html
@@ -494,19 +494,19 @@ background-position: top left; } .lh-crc .horiz-down { - background: url('data:image/svg+xml;utf8,<svg width="16" height="26" viewBox="0 0 16 26" xmlns="http://www.w3.org/2000/svg"><g fill="#D8D8D8" fill-rule="evenodd"><path d="M16 12v2H-2v-2z"/><path d="M9 12v14H7V12z"/></g></svg>'); + background: url('data:image/svg+xml;utf8,<svg width="16" height="26" viewBox="0 0 16 26" xmlns="http://www.w3.org/2000/svg"><g fill="%23D8D8D8" fill-rule="evenodd"><path d="M16 12v2H-2v-2z"/><path d="M9 12v14H7V12z"/></g></svg>'); } .lh-crc .right { - background: url('data:image/svg+xml;utf8,<svg width="16" height="26" viewBox="0 0 16 26" xmlns="http://www.w3.org/2000/svg"><path d="M16 12v2H0v-2z" fill="#D8D8D8" fill-rule="evenodd"/></svg>'); + background: url('data:image/svg+xml;utf8,<svg width="16" height="26" viewBox="0 0 16 26" xmlns="http://www.w3.org/2000/svg"><path d="M16 12v2H0v-2z" fill="%23D8D8D8" fill-rule="evenodd"/></svg>'); } .lh-crc .up-right { - background: url('data:image/svg+xml;utf8,<svg width="16" height="26" viewBox="0 0 16 26" xmlns="http://www.w3.org/2000/svg"><path d="M7 0h2v14H7zm2 12h7v2H9z" fill="#D8D8D8" fill-rule="evenodd"/></svg>'); + background: url('data:image/svg+xml;utf8,<svg width="16" height="26" viewBox="0 0 16 26" xmlns="http://www.w3.org/2000/svg"><path d="M7 0h2v14H7zm2 12h7v2H9z" fill="%23D8D8D8" fill-rule="evenodd"/></svg>'); } .lh-crc .vert-right { - background: url('data:image/svg+xml;utf8,<svg width="16" height="26" viewBox="0 0 16 26" xmlns="http://www.w3.org/2000/svg"><path d="M7 0h2v27H7zm2 12h7v2H9z" fill="#D8D8D8" fill-rule="evenodd"/></svg>'); + background: url('data:image/svg+xml;utf8,<svg width="16" height="26" viewBox="0 0 16 26" xmlns="http://www.w3.org/2000/svg"><path d="M7 0h2v27H7zm2 12h7v2H9z" fill="%23D8D8D8" fill-rule="evenodd"/></svg>'); } .lh-crc .vert { - background: url('data:image/svg+xml;utf8,<svg width="16" height="26" viewBox="0 0 16 26" xmlns="http://www.w3.org/2000/svg"><path d="M7 0h2v26H7z" fill="#D8D8D8" fill-rule="evenodd"/></svg>'); + background: url('data:image/svg+xml;utf8,<svg width="16" height="26" viewBox="0 0 16 26" xmlns="http://www.w3.org/2000/svg"><path d="M7 0h2v26H7z" fill="%23D8D8D8" fill-rule="evenodd"/></svg>'); } .lh-crc .crc-tree { font-size: 14px;
diff --git a/third_party/WebKit/Source/devtools/front_end/bindings_test_runner/PersistenceTestRunner.js b/third_party/WebKit/Source/devtools/front_end/bindings_test_runner/PersistenceTestRunner.js index fd757c65..177d1cb 100644 --- a/third_party/WebKit/Source/devtools/front_end/bindings_test_runner/PersistenceTestRunner.js +++ b/third_party/WebKit/Source/devtools/front_end/bindings_test_runner/PersistenceTestRunner.js
@@ -49,20 +49,13 @@ }; BindingsTestRunner.initializeTestMapping = function() { - var testMapping; - - Persistence.persistence._setMappingForTest((bindingCreated, bindingRemoved) => { - testMapping = new TestMapping(bindingCreated, bindingRemoved); - return testMapping; - }); - - return testMapping; + return new TestMapping(Persistence.persistence); }; class TestMapping { - constructor(onBindingAdded, onBindingRemoved) { - this._onBindingAdded = onBindingAdded; - this._onBindingRemoved = onBindingRemoved; + constructor(persistence) { + this._persistence = persistence; + persistence.setAutomappingEnabled(false); this._bindings = new Set(); } @@ -75,9 +68,9 @@ var networkUISourceCode = await TestRunner.waitForUISourceCode(urlSuffix, Workspace.projectTypes.Network); var fileSystemUISourceCode = await TestRunner.waitForUISourceCode(urlSuffix, Workspace.projectTypes.FileSystem); - var binding = new Persistence.AutomappingBinding(networkUISourceCode, fileSystemUISourceCode, false); + var binding = new Persistence.PersistenceBinding(networkUISourceCode, fileSystemUISourceCode); this._bindings.add(binding); - this._onBindingAdded.call(null, binding); + this._persistence.addBindingForTest(binding); } _findBinding(urlSuffix) { @@ -99,12 +92,12 @@ } this._bindings.delete(binding); - this._onBindingRemoved.call(null, binding); + this._persistence.removeBindingForTest(binding); } dispose() { for (var binding of this._bindings) - this._onBindingRemoved.call(null, binding); + this._persistence.removeBindingForTest(binding); this._bindings.clear(); }
diff --git a/third_party/WebKit/Source/devtools/front_end/console/ConsoleSidebar.js b/third_party/WebKit/Source/devtools/front_end/console/ConsoleSidebar.js index 67f1748..c84529f 100644 --- a/third_party/WebKit/Source/devtools/front_end/console/ConsoleSidebar.js +++ b/third_party/WebKit/Source/devtools/front_end/console/ConsoleSidebar.js
@@ -9,7 +9,6 @@ constructor(badgePool) { super(true); this.setMinimumSize(125, 0); - this._enabled = Runtime.experiments.isEnabled('logManagement'); this._tree = new UI.TreeOutlineInShadow(); this._tree.registerRequiredCSS('console/consoleSidebar.css'); @@ -68,8 +67,6 @@ } clear() { - if (!this._enabled) - return; for (var treeElement of this._treeElements) treeElement.clear(); } @@ -78,8 +75,6 @@ * @param {!Console.ConsoleViewMessage} viewMessage */ onMessageAdded(viewMessage) { - if (!this._enabled) - return; for (var treeElement of this._treeElements) treeElement.onMessageAdded(viewMessage); } @@ -89,7 +84,7 @@ * @return {boolean} */ shouldBeVisible(viewMessage) { - if (!this._enabled || !this._selectedTreeElement) + if (!this._selectedTreeElement) return true; return this._selectedTreeElement._filter.shouldBeVisible(viewMessage); }
diff --git a/third_party/WebKit/Source/devtools/front_end/console/ConsoleView.js b/third_party/WebKit/Source/devtools/front_end/console/ConsoleView.js index e20c7b8..6563f21 100644 --- a/third_party/WebKit/Source/devtools/front_end/console/ConsoleView.js +++ b/third_party/WebKit/Source/devtools/front_end/console/ConsoleView.js
@@ -48,27 +48,22 @@ this._filter = new Console.ConsoleViewFilter(this._onFilterChanged.bind(this)); var toolbar = new UI.Toolbar('', this.element); - var isLogManagementEnabled = Runtime.experiments.isEnabled('logManagement'); - if (isLogManagementEnabled) { - this._splitWidget = - new UI.SplitWidget(true /* isVertical */, false /* secondIsSidebar */, 'console.sidebar.width', 100); - this._splitWidget.setMainWidget(this._searchableView); - this._splitWidget.setSidebarWidget(this._sidebar); - this._splitWidget.show(this.element); - this._splitWidget.hideSidebar(); - this._splitWidget.enableShowModeSaving(); - this._isSidebarOpen = this._splitWidget.showMode() === UI.SplitWidget.ShowMode.Both; - if (this._isSidebarOpen) - this._filter._levelMenuButton.setEnabled(false); - toolbar.appendToolbarItem(this._splitWidget.createShowHideSidebarButton('console sidebar')); - this._splitWidget.addEventListener(UI.SplitWidget.Events.ShowModeChanged, event => { - this._isSidebarOpen = event.data === UI.SplitWidget.ShowMode.Both; - this._filter._levelMenuButton.setEnabled(!this._isSidebarOpen); - this._onFilterChanged(); - }); - } else { - this._searchableView.show(this.element); - } + this._splitWidget = + new UI.SplitWidget(true /* isVertical */, false /* secondIsSidebar */, 'console.sidebar.width', 100); + this._splitWidget.setMainWidget(this._searchableView); + this._splitWidget.setSidebarWidget(this._sidebar); + this._splitWidget.show(this.element); + this._splitWidget.hideSidebar(); + this._splitWidget.enableShowModeSaving(); + this._isSidebarOpen = this._splitWidget.showMode() === UI.SplitWidget.ShowMode.Both; + if (this._isSidebarOpen) + this._filter._levelMenuButton.setEnabled(false); + toolbar.appendToolbarItem(this._splitWidget.createShowHideSidebarButton('console sidebar')); + this._splitWidget.addEventListener(UI.SplitWidget.Events.ShowModeChanged, event => { + this._isSidebarOpen = event.data === UI.SplitWidget.ShowMode.Both; + this._filter._levelMenuButton.setEnabled(!this._isSidebarOpen); + this._onFilterChanged(); + }); this._contentsElement = this._searchableView.element; this.element.classList.add('console-view'); @@ -125,9 +120,6 @@ this._filter._filterByExecutionContextSetting, Common.UIString('Only show messages from the current context (top, iframe, worker, extension)'), Common.UIString('Selected context only')); - var filterConsoleAPICheckbox = new UI.ToolbarSettingCheckbox( - Common.moduleSetting('consoleAPIFilterEnabled'), Common.UIString('Only show messages from console API methods'), - Common.UIString('User messages only')); var monitoringXHREnabledSetting = Common.moduleSetting('monitoringXHREnabled'); this._timestampsSetting = Common.moduleSetting('consoleTimestampsEnabled'); this._consoleHistoryAutocompleteSetting = Common.moduleSetting('consoleHistoryAutocomplete'); @@ -141,8 +133,6 @@ settingsToolbarLeft.appendToolbarItem(this._hideNetworkMessagesCheckbox); settingsToolbarLeft.appendToolbarItem(this._preserveLogCheckbox); settingsToolbarLeft.appendToolbarItem(filterByExecutionContextCheckbox); - if (!isLogManagementEnabled) - settingsToolbarLeft.appendToolbarItem(filterConsoleAPICheckbox); var settingsToolbarRight = new UI.Toolbar('', settingsPane.element); settingsToolbarRight.makeVertical(); @@ -1193,13 +1183,11 @@ this._messageLevelFiltersSetting = Console.ConsoleViewFilter.levelFilterSetting(); this._hideNetworkMessagesSetting = Common.moduleSetting('hideNetworkMessages'); this._filterByExecutionContextSetting = Common.moduleSetting('selectedContextFilterEnabled'); - this._filterByConsoleAPISetting = Common.moduleSetting('consoleAPIFilterEnabled'); this._messageURLFiltersSetting.addChangeListener(this._onFilterChanged.bind(this)); this._messageLevelFiltersSetting.addChangeListener(this._onFilterChanged.bind(this)); this._hideNetworkMessagesSetting.addChangeListener(this._onFilterChanged.bind(this)); this._filterByExecutionContextSetting.addChangeListener(this._onFilterChanged.bind(this)); - this._filterByConsoleAPISetting.addChangeListener(this._onFilterChanged.bind(this)); UI.context.addFlavorChangeListener(SDK.ExecutionContext, this._onFilterChanged, this); var filterKeys = Object.values(Console.ConsoleFilter.FilterType); @@ -1265,14 +1253,6 @@ }); } - if (this._filterByConsoleAPISetting.get()) { - parsedFilters.push({ - key: Console.ConsoleFilter.FilterType.Source, - text: ConsoleModel.ConsoleMessage.MessageSource.ConsoleAPI, - negative: false - }); - } - var blockedURLs = Object.keys(this._messageURLFiltersSetting.get()); var urlFilters = blockedURLs.map(url => ({key: Console.ConsoleFilter.FilterType.Url, text: url, negative: true})); parsedFilters = parsedFilters.concat(urlFilters); @@ -1385,7 +1365,6 @@ this._messageURLFiltersSetting.set({}); this._messageLevelFiltersSetting.set(Console.ConsoleFilter.defaultLevelsFilterValue()); this._filterByExecutionContextSetting.set(false); - this._filterByConsoleAPISetting.set(false); this._hideNetworkMessagesSetting.set(false); this._textFilterUI.setValue(''); this._onFilterChanged();
diff --git a/third_party/WebKit/Source/devtools/front_end/console/module.json b/third_party/WebKit/Source/devtools/front_end/console/module.json index 9a12bde..467344a9 100644 --- a/third_party/WebKit/Source/devtools/front_end/console/module.json +++ b/third_party/WebKit/Source/devtools/front_end/console/module.json
@@ -99,25 +99,6 @@ { "type": "setting", "category": "Console", - "title": "User messages only", - "settingName": "consoleAPIFilterEnabled", - "settingType": "boolean", - "storageType": "session", - "defaultValue": false, - "options": [ - { - "value": true, - "title": "Only show messages from console API methods" - }, - { - "value": false, - "title": "Show messages from all sources" - } - ] - }, - { - "type": "setting", - "category": "Console", "title": "Log XMLHttpRequests", "settingName": "monitoringXHREnabled", "settingType": "boolean",
diff --git a/third_party/WebKit/Source/devtools/front_end/main/Main.js b/third_party/WebKit/Source/devtools/front_end/main/Main.js index ec1d2c98..2703ea3 100644 --- a/third_party/WebKit/Source/devtools/front_end/main/Main.js +++ b/third_party/WebKit/Source/devtools/front_end/main/Main.js
@@ -111,16 +111,13 @@ _initializeExperiments() { // Keep this sorted alphabetically: both keys and values. - Runtime.experiments.register('accessibilityInspection', 'Accessibility Inspection'); Runtime.experiments.register('applyCustomStylesheet', 'Allow custom UI themes'); Runtime.experiments.register('blackboxJSFramesOnTimeline', 'Blackbox JavaScript frames on Timeline', true); Runtime.experiments.register('colorContrastRatio', 'Color contrast ratio line in color picker', true); Runtime.experiments.register('emptySourceMapAutoStepping', 'Empty sourcemap auto-stepping'); Runtime.experiments.register('inputEventsOnTimelineOverview', 'Input events on Timeline overview', true); Runtime.experiments.register('oopifInlineDOM', 'OOPIF: inline DOM ', true); - Runtime.experiments.register('logManagement', 'Log management', true); Runtime.experiments.register('nativeHeapProfiler', 'Native memory sampling heap profiler', true); - Runtime.experiments.register('performanceMonitor', 'Performance Monitor', true); Runtime.experiments.register('sourceDiff', 'Source diff'); Runtime.experiments.register( 'stepIntoAsync', 'Introduce separate step action, stepInto becomes powerful enough to go inside async call'); @@ -143,18 +140,12 @@ if (Host.isUnderTest()) { var testPath = Runtime.queryParam('test'); // Enable experiments for testing. - if (testPath.indexOf('accessibility/') !== -1) - Runtime.experiments.enableForTest('accessibilityInspection'); - if (testPath.indexOf('console-sidebar/') !== -1) - Runtime.experiments.enableForTest('logManagement'); if (testPath.indexOf('oopif/') !== -1) Runtime.experiments.enableForTest('oopifInlineDOM'); } - Runtime.experiments.setDefaultExperiments([ - 'accessibilityInspection', 'colorContrastRatio', 'logManagement', 'performanceMonitor', 'stepIntoAsync', - 'timelineKeepHistory', 'oopifInlineDOM' - ]); + Runtime.experiments.setDefaultExperiments( + ['colorContrastRatio', 'stepIntoAsync', 'timelineKeepHistory', 'oopifInlineDOM']); } /**
diff --git a/third_party/WebKit/Source/devtools/front_end/object_ui/JavaScriptAutocomplete.js b/third_party/WebKit/Source/devtools/front_end/object_ui/JavaScriptAutocomplete.js index 355a312..e570614 100644 --- a/third_party/WebKit/Source/devtools/front_end/object_ui/JavaScriptAutocomplete.js +++ b/third_party/WebKit/Source/devtools/front_end/object_ui/JavaScriptAutocomplete.js
@@ -211,7 +211,8 @@ this._expressionCache.set(expressionString, cache); completionGroups = await cache.value; } - return this._receivedPropertyNames(completionGroups, dotNotation, bracketNotation, expressionString, query); + return this._receivedPropertyNames( + completionGroups.slice(0), dotNotation, bracketNotation, expressionString, query); /** * @this {ObjectUI.JavaScriptAutocomplete}
diff --git a/third_party/WebKit/Source/devtools/front_end/object_ui/ObjectPropertiesSection.js b/third_party/WebKit/Source/devtools/front_end/object_ui/ObjectPropertiesSection.js index 3da66a6..48d55a7 100644 --- a/third_party/WebKit/Source/devtools/front_end/object_ui/ObjectPropertiesSection.js +++ b/third_party/WebKit/Source/devtools/front_end/object_ui/ObjectPropertiesSection.js
@@ -1278,7 +1278,8 @@ ObjectUI.ObjectPropertyPrompt = class extends UI.TextPrompt { constructor() { super(); - this.initialize(ObjectUI.javaScriptAutocomplete.completionsForTextInCurrentContext); + this.initialize( + ObjectUI.javaScriptAutocomplete.completionsForTextInCurrentContext.bind(ObjectUI.javaScriptAutocomplete)); } };
diff --git a/third_party/WebKit/Source/devtools/front_end/persistence/Automapping.js b/third_party/WebKit/Source/devtools/front_end/persistence/Automapping.js index 0806e829..16f210a 100644 --- a/third_party/WebKit/Source/devtools/front_end/persistence/Automapping.js +++ b/third_party/WebKit/Source/devtools/front_end/persistence/Automapping.js
@@ -20,7 +20,6 @@ /** @type {!Set<!Persistence.AutomappingBinding>} */ this._bindings = new Set(); - this._enabled = true; /** @type {!Map<string, !Workspace.UISourceCode>} */ this._fileSystemUISourceCodes = new Map(); this._sweepThrottler = new Common.Throttler(100); @@ -53,16 +52,6 @@ this._onUISourceCodeAdded(uiSourceCode); } - /** - * @param {boolean} enabled - */ - setEnabled(enabled) { - if (this._enabled === enabled) - return; - this._enabled = enabled; - this._scheduleRemap(); - } - _scheduleRemap() { for (var binding of this._bindings.valuesArray()) this._unbindNetwork(binding.network); @@ -176,7 +165,7 @@ */ _bindNetwork(networkSourceCode) { if (networkSourceCode[Persistence.Automapping._processingPromise] || - networkSourceCode[Persistence.Automapping._binding] || !this._enabled) + networkSourceCode[Persistence.Automapping._binding]) return; var createBindingPromise = this._createBinding(networkSourceCode).then(validateBinding.bind(this)).then(onBinding.bind(this));
diff --git a/third_party/WebKit/Source/devtools/front_end/persistence/Persistence.js b/third_party/WebKit/Source/devtools/front_end/persistence/Persistence.js index 69819ac6..83fa3e7 100644 --- a/third_party/WebKit/Source/devtools/front_end/persistence/Persistence.js +++ b/third_party/WebKit/Source/devtools/front_end/persistence/Persistence.js
@@ -22,15 +22,23 @@ var linkDecorator = new Persistence.PersistenceUtils.LinkDecorator(this); Components.Linkifier.setLinkDecorator(linkDecorator); - this._mapping = - new Persistence.Automapping(workspace, this._onBindingAdded.bind(this), this._onBindingRemoved.bind(this)); + this._mapping = null; + this.setAutomappingEnabled(true); } /** * @param {boolean} enabled */ setAutomappingEnabled(enabled) { - this._mapping.setEnabled(enabled); + if (enabled === !!this._mapping) + return; + if (!enabled) { + this._mapping.dispose(); + this._mapping = null; + } else { + this._mapping = new Persistence.Automapping( + this._workspace, this._onBindingAdded.bind(this), this._onBindingRemoved.bind(this)); + } } /** @@ -43,16 +51,22 @@ /** * @param {!Persistence.PersistenceBinding} binding */ + addBindingForTest(binding) { + this._innerAddBinding(binding); + } + + /** + * @param {!Persistence.PersistenceBinding} binding + */ removeBinding(binding) { this._innerRemoveBinding(binding); } /** - * @param {function(function(!Persistence.AutomappingBinding), function(!Persistence.AutomappingBinding)):!Persistence.MappingSystem} mappingFactory + * @param {!Persistence.PersistenceBinding} binding */ - _setMappingForTest(mappingFactory) { - this._mapping.dispose(); - this._mapping = mappingFactory(this._onBindingAdded.bind(this), this._onBindingRemoved.bind(this)); + removeBindingForTest(binding) { + this._innerRemoveBinding(binding); } /** @@ -347,7 +361,10 @@ } dispose() { - this._mapping.dispose(); + if (this._mapping) { + this._mapping.dispose(); + this._mapping = null; + } } };
diff --git a/third_party/WebKit/Source/devtools/front_end/sdk/TargetManager.js b/third_party/WebKit/Source/devtools/front_end/sdk/TargetManager.js index c8ae57f..cb7d343 100644 --- a/third_party/WebKit/Source/devtools/front_end/sdk/TargetManager.js +++ b/third_party/WebKit/Source/devtools/front_end/sdk/TargetManager.js
@@ -405,8 +405,6 @@ parentTarget.registerTargetDispatcher(this); this._targetAgent.invoke_setAutoAttach({autoAttach: true, waitForDebuggerOnStart: true}); - // TODO(dgozman): remove the protocol method and make it default. - this._targetAgent.setAttachToFrames(true); if (!parentTarget.parentTarget()) { this._targetAgent.setDiscoverTargets(true);
diff --git a/third_party/WebKit/Source/devtools/front_end/timeline/module.json b/third_party/WebKit/Source/devtools/front_end/timeline/module.json index 900657e0..7426be2e 100644 --- a/third_party/WebKit/Source/devtools/front_end/timeline/module.json +++ b/third_party/WebKit/Source/devtools/front_end/timeline/module.json
@@ -16,7 +16,6 @@ "persistence": "closeable", "order": 100, "className": "Timeline.PerformanceMonitor", - "experiment": "performanceMonitor", "tags": "performance, system monitor, monitor, activity, metrics" }, {
diff --git a/third_party/WebKit/Source/devtools/front_end/ui/TextPrompt.js b/third_party/WebKit/Source/devtools/front_end/ui/TextPrompt.js index c773e83..32ff43c0 100644 --- a/third_party/WebKit/Source/devtools/front_end/ui/TextPrompt.js +++ b/third_party/WebKit/Source/devtools/front_end/ui/TextPrompt.js
@@ -49,7 +49,7 @@ } /** - * @param {(function(string, string, boolean=):!Promise<!UI.SuggestBox.Suggestions>)} completions + * @param {(function(this:null, string, string, boolean=):!Promise<!UI.SuggestBox.Suggestions>)} completions * @param {string=} stopCharacters */ initialize(completions, stopCharacters) {
diff --git a/third_party/WebKit/Source/modules/ModulesInitializer.cpp b/third_party/WebKit/Source/modules/ModulesInitializer.cpp index ed94529..084ebbd 100644 --- a/third_party/WebKit/Source/modules/ModulesInitializer.cpp +++ b/third_party/WebKit/Source/modules/ModulesInitializer.cpp
@@ -222,8 +222,7 @@ NavigatorGamepad::From(document); NavigatorServiceWorker::From(document); DOMWindowStorageController::From(document); - if (RuntimeEnabledFeatures::WebVREnabled() || - OriginTrials::webVREnabled(document.GetExecutionContext())) + if (OriginTrials::webVREnabled(document.GetExecutionContext())) NavigatorVR::From(document); if (RuntimeEnabledFeatures::PresentationEnabled() && settings.GetPresentationReceiver()) {
diff --git a/third_party/WebKit/Source/modules/accessibility/AXARIAGrid.h b/third_party/WebKit/Source/modules/accessibility/AXARIAGrid.h index 8d8a801..30b7a0a 100644 --- a/third_party/WebKit/Source/modules/accessibility/AXARIAGrid.h +++ b/third_party/WebKit/Source/modules/accessibility/AXARIAGrid.h
@@ -56,6 +56,7 @@ // ARIA treegrids and grids support selected rows. bool SupportsSelectedRows() override { return true; } bool IsTableExposableThroughAccessibility() const override { return true; } + bool ComputeIsDataTable() const override { return true; } void ComputeRows(AXObjectVector from_child_list); bool AddRow(AXObject*);
diff --git a/third_party/WebKit/Source/modules/accessibility/AXEnums.cpp b/third_party/WebKit/Source/modules/accessibility/AXEnums.cpp index 05b1f11..7cdbcea9 100644 --- a/third_party/WebKit/Source/modules/accessibility/AXEnums.cpp +++ b/third_party/WebKit/Source/modules/accessibility/AXEnums.cpp
@@ -63,6 +63,10 @@ STATIC_ASSERT_ENUM(kWebAXRoleInlineTextBox, kInlineTextBoxRole); STATIC_ASSERT_ENUM(kWebAXRoleInputTime, kInputTimeRole); STATIC_ASSERT_ENUM(kWebAXRoleLabel, kLabelRole); +STATIC_ASSERT_ENUM(kWebAXRoleLayoutTable, kLayoutTableRole); +STATIC_ASSERT_ENUM(kWebAXRoleLayoutTableCell, kLayoutTableCellRole); +STATIC_ASSERT_ENUM(kWebAXRoleLayoutTableColumn, kLayoutTableColumnRole); +STATIC_ASSERT_ENUM(kWebAXRoleLayoutTableRow, kLayoutTableRowRole); STATIC_ASSERT_ENUM(kWebAXRoleLegend, kLegendRole); STATIC_ASSERT_ENUM(kWebAXRoleLineBreak, kLineBreakRole); STATIC_ASSERT_ENUM(kWebAXRoleLink, kLinkRole);
diff --git a/third_party/WebKit/Source/modules/accessibility/AXEnums.h b/third_party/WebKit/Source/modules/accessibility/AXEnums.h index 11e4a45..5a59172 100644 --- a/third_party/WebKit/Source/modules/accessibility/AXEnums.h +++ b/third_party/WebKit/Source/modules/accessibility/AXEnums.h
@@ -62,6 +62,10 @@ kInlineTextBoxRole, // No mapping to ARIA role. kInputTimeRole, // No mapping to ARIA role. kLabelRole, + kLayoutTableRole, + kLayoutTableCellRole, + kLayoutTableColumnRole, + kLayoutTableRowRole, kLegendRole, // No mapping to ARIA role. kLineBreakRole, // No mapping to ARIA role. kLinkRole,
diff --git a/third_party/WebKit/Source/modules/accessibility/AXLayoutObject.cpp b/third_party/WebKit/Source/modules/accessibility/AXLayoutObject.cpp index 0fe4a03..238f35e 100644 --- a/third_party/WebKit/Source/modules/accessibility/AXLayoutObject.cpp +++ b/third_party/WebKit/Source/modules/accessibility/AXLayoutObject.cpp
@@ -719,8 +719,12 @@ if (IsGenericFocusableElement() && node->hasChildren()) return false; + // Positioned elements and scrollable containers are important for + // determining bounding boxes. if (IsScrollableContainer()) return false; + if (layout_object_->IsPositioned()) + return false; // Ignore layout objects that are block flows with inline children. These // are usually dummy layout objects that pad out the tree, but there are @@ -2150,6 +2154,7 @@ bool found_parent = false; switch (container_parent->RoleValue()) { + case kLayoutTableRole: case kTreeRole: case kTreeGridRole: case kGridRole:
diff --git a/third_party/WebKit/Source/modules/accessibility/AXNodeObject.cpp b/third_party/WebKit/Source/modules/accessibility/AXNodeObject.cpp index e7c6a32..596f4f2 100644 --- a/third_party/WebKit/Source/modules/accessibility/AXNodeObject.cpp +++ b/third_party/WebKit/Source/modules/accessibility/AXNodeObject.cpp
@@ -183,41 +183,6 @@ IsHTMLDListElement(*node); } -static bool IsPresentationalInTable(AXObject* parent, - HTMLElement* current_element) { - if (!current_element) - return false; - - Node* parent_node = parent->GetNode(); - if (!parent_node || !parent_node->IsHTMLElement()) - return false; - - // AXTable determines the role as checking isTableXXX. - // If Table has explicit role including presentation, AXTable doesn't assign - // implicit Role to a whole Table. That's why we should check it based on - // node. - // Normal Table Tree is that - // cell(its role)-> tr(tr role)-> tfoot, tbody, thead(ignored role) -> - // table(table role). - // If table has presentation role, it will be like - // cell(group)-> tr(unknown) -> tfoot, tbody, thead(ignored) -> - // table(presentation). - if (IsHTMLTableCellElement(*current_element) && - IsHTMLTableRowElement(*parent_node)) - return parent->HasInheritedPresentationalRole(); - - if (IsHTMLTableRowElement(*current_element) && - IsHTMLTableSectionElement(ToHTMLElement(*parent_node))) { - // Because TableSections have ignored role, presentation should be checked - // with its parent node. - AXObject* table_object = parent->ParentObject(); - Node* table_node = table_object ? table_object->GetNode() : nullptr; - return IsHTMLTableElement(table_node) && - table_object->HasInheritedPresentationalRole(); - } - return false; -} - static bool IsRequiredOwnedElement(AXObject* parent, AccessibilityRole current_role, HTMLElement* current_element) { @@ -270,17 +235,9 @@ HTMLElement* element = nullptr; if (GetNode() && GetNode()->IsHTMLElement()) element = ToHTMLElement(GetNode()); - if (!parent->HasInheritedPresentationalRole()) { - if (!GetLayoutObject() || !GetLayoutObject()->IsBoxModelObject()) - return nullptr; + if (!parent->HasInheritedPresentationalRole()) + return nullptr; - LayoutBoxModelObject* css_box = ToLayoutBoxModelObject(GetLayoutObject()); - if (!css_box->IsTableCell() && !css_box->IsTableRow()) - return nullptr; - - if (!IsPresentationalInTable(parent, element)) - return nullptr; - } // ARIA spec says that when a parent object is presentational and this object // is a required owned element of that parent, then this object is also // presentational. @@ -1583,6 +1540,7 @@ *out_value = (min_value + max_value) / 2.0f; return true; } + FALLTHROUGH; } case kSplitterRole: { *out_value = 50.0f;
diff --git a/third_party/WebKit/Source/modules/accessibility/AXObject.cpp b/third_party/WebKit/Source/modules/accessibility/AXObject.cpp index 7e61c98..c3501f0 100644 --- a/third_party/WebKit/Source/modules/accessibility/AXObject.cpp +++ b/third_party/WebKit/Source/modules/accessibility/AXObject.cpp
@@ -213,6 +213,10 @@ {kInlineTextBoxRole, "InlineTextBox"}, {kInputTimeRole, "InputTime"}, {kLabelRole, "Label"}, + {kLayoutTableRole, "LayoutTable"}, + {kLayoutTableCellRole, "LayoutCellTable"}, + {kLayoutTableColumnRole, "LayoutColumnTable"}, + {kLayoutTableRowRole, "LayoutRowTable"}, {kLegendRole, "Legend"}, {kLinkRole, "Link"}, {kLineBreakRole, "LineBreak"}, @@ -1525,6 +1529,7 @@ case kGroupRole: case kHeadingRole: case kImageRole: + case kLayoutTableRole: case kListRole: case kListBoxRole: case kListBoxOptionRole: @@ -2412,6 +2417,7 @@ case kComboBoxMenuButtonRole: case kDisclosureTriangleRole: case kHeadingRole: + case kLayoutTableCellRole: case kLineBreakRole: case kLinkRole: case kListBoxOptionRole: @@ -2463,6 +2469,9 @@ case kIframeRole: case kImageRole: case kInputTimeRole: + case kLayoutTableRole: + case kLayoutTableColumnRole: + case kLayoutTableRowRole: case kListBoxRole: case kLogRole: case kMainRole:
diff --git a/third_party/WebKit/Source/modules/accessibility/AXTable.cpp b/third_party/WebKit/Source/modules/accessibility/AXTable.cpp index 0bd4135..3d958c3f 100644 --- a/third_party/WebKit/Source/modules/accessibility/AXTable.cpp +++ b/third_party/WebKit/Source/modules/accessibility/AXTable.cpp
@@ -59,7 +59,10 @@ void AXTable::Init() { AXLayoutObject::Init(); + // Can it be exposed with any kind of table structure / interface? is_ax_table_ = IsTableExposableThroughAccessibility(); + // Data tables are a subset of AX Tables. The rest are layout tables. + is_data_table_ = is_ax_table_ && ComputeIsDataTable(); } AXTable* AXTable::Create(LayoutObject* layout_object, @@ -67,38 +70,37 @@ return new AXTable(layout_object, ax_object_cache); } -bool AXTable::HasARIARole() const { - if (!layout_object_) - return false; - - AccessibilityRole aria_role = AriaRoleAttribute(); - if (aria_role != kUnknownRole) - return true; - - return false; -} - bool AXTable::IsAXTable() const { - if (!layout_object_) - return false; - - return is_ax_table_; + return layout_object_ && is_ax_table_; } -static bool ElementHasAriaRole(const Element* element) { +static AccessibilityRole AriaRole(const Element* element) { + if (!element) + return kUnknownRole; + + const AtomicString& aria_role = element->FastGetAttribute(roleAttr); + if (aria_role.IsEmpty()) + return kUnknownRole; + return AXObject::AriaRoleToWebCoreRole(aria_role); +} + +static bool ElementHasSignificantAriaRole(const Element* element) { if (!element) return false; - const AtomicString& aria_role = element->FastGetAttribute(roleAttr); - return (!aria_role.IsNull() && !aria_role.IsEmpty()); + AccessibilityRole role = AriaRole(element); + return role != kUnknownRole && role != kNoneRole && + role != kPresentationalRole; } bool AXTable::IsDataTable() const { - if (!layout_object_ || !GetNode()) - return false; + return layout_object_ && is_data_table_; +} - // Do not consider it a data table if it has an ARIA role. - if (HasARIARole()) +// The following is a heuristic used to determine if a +// <table> should be with kTableRole or kLayoutTableRole. +bool AXTable::ComputeIsDataTable() const { + if (!layout_object_ || !GetNode()) return false; // When a section of the document is contentEditable, all tables should be @@ -114,36 +116,8 @@ LayoutTable* table = ToLayoutTable(layout_object_); Node* table_node = table->GetNode(); - if (!IsHTMLTableElement(table_node)) - return false; - - // Do not consider it a data table if any of its descendants have an ARIA - // role. + DCHECK(IsHTMLTableElement(table_node)); HTMLTableElement* table_element = ToHTMLTableElement(table_node); - if (ElementHasAriaRole(table_element->tHead())) - return false; - if (ElementHasAriaRole(table_element->tFoot())) - return false; - - HTMLCollection* bodies = table_element->tBodies(); - for (unsigned body_index = 0; body_index < bodies->length(); ++body_index) { - Element* body_element = bodies->item(body_index); - if (ElementHasAriaRole(body_element)) - return false; - } - - HTMLTableRowsCollection* rows = table_element->rows(); - unsigned row_count = rows->length(); - for (unsigned row_index = 0; row_index < row_count; ++row_index) { - HTMLTableRowElement* row_element = rows->Item(row_index); - if (ElementHasAriaRole(row_element)) - return false; - HTMLCollection* cells = row_element->cells(); - for (unsigned cell_index = 0; cell_index < cells->length(); ++cell_index) { - if (ElementHasAriaRole(cells->item(cell_index))) - return false; - } - } // If there is a caption element, summary, THEAD, or TFOOT section, it's most // certainly a data table @@ -202,9 +176,7 @@ Color alternating_row_colors[5]; int alternating_row_color_count = 0; - int headers_in_first_column_count = 0; for (int row = 0; row < num_rows; ++row) { - int headers_in_first_row_count = 0; int n_cols = first_body->NumCols(row); for (int col = 0; col < n_cols; ++col) { LayoutTableCell* cell = first_body->PrimaryCellAt(row, col); @@ -219,16 +191,9 @@ valid_cell_count++; - bool is_th_cell = cell_node->HasTagName(thTag); - // If the first row is comprised of all <th> tags, assume it is a data - // table. - if (!row && is_th_cell) - headers_in_first_row_count++; - - // If the first column is comprised of all <th> tags, assume it is a data - // table. - if (!col && is_th_cell) - headers_in_first_column_count++; + // Any <th> tag -> treat as data table. + if (cell_node->HasTagName(thTag)) + return true; // In this case, the developer explicitly assigned a "data" table // attribute. @@ -293,15 +258,8 @@ alternating_row_color_count++; } } - - if (!row && headers_in_first_row_count == num_cols_in_first_body && - num_cols_in_first_body > 1) - return true; } - if (headers_in_first_column_count == num_rows && num_rows > 1) - return true; - // if there is less than two valid cells, it's not a data table if (valid_cell_count <= 1) return false; @@ -337,21 +295,47 @@ return false; } +// If this returns false, the table will be exposed as a generic object +// instead of a kTableRole object with kRowRole children and kCellRole +// grandchildren. bool AXTable::IsTableExposableThroughAccessibility() const { - // The following is a heuristic used to determine if a - // <table> should be exposed as an AXTable. The goal - // is to only show "data" tables. - if (!layout_object_) return false; // If the developer assigned an aria role to this, then we // shouldn't expose it as a table, unless, of course, the aria // role is a table. - if (HasARIARole()) + if (AriaRole(GetElement()) != kUnknownRole) return false; - return IsDataTable(); + LayoutTable* table = ToLayoutTable(layout_object_); + Node* table_node = table->GetNode(); + if (!IsHTMLTableElement(table_node)) + return false; + + // Do not expose as table if any of its child sections or rows has an ARIA + // role. + HTMLTableElement* table_element = ToHTMLTableElement(table_node); + if (ElementHasSignificantAriaRole(table_element->tHead())) + return false; + if (ElementHasSignificantAriaRole(table_element->tFoot())) + return false; + + HTMLCollection* bodies = table_element->tBodies(); + for (unsigned body_index = 0; body_index < bodies->length(); ++body_index) { + Element* body_element = bodies->item(body_index); + if (ElementHasSignificantAriaRole(body_element)) + return false; + } + + HTMLTableRowsCollection* rows = table_element->rows(); + for (unsigned row_index = 0; row_index < rows->length(); ++row_index) { + Element* row_element = rows->item(row_index); + if (AriaRole(row_element) != kUnknownRole) + return false; + } + + return true; } void AXTable::ClearChildren() { @@ -588,7 +572,7 @@ if (!IsAXTable()) return AXLayoutObject::RoleValue(); - return kTableRole; + return IsDataTable() ? kTableRole : kLayoutTableRole; } bool AXTable::ComputeAccessibilityIsIgnored(
diff --git a/third_party/WebKit/Source/modules/accessibility/AXTable.h b/third_party/WebKit/Source/modules/accessibility/AXTable.h index b0380cb..fc09206 100644 --- a/third_party/WebKit/Source/modules/accessibility/AXTable.h +++ b/third_party/WebKit/Source/modules/accessibility/AXTable.h
@@ -82,12 +82,17 @@ AXObjectVector columns_; Member<AXObject> header_container_; - bool is_ax_table_; bool HasARIARole() const; - virtual bool IsTableExposableThroughAccessibility() const; bool ComputeAccessibilityIsIgnored(IgnoredReasons* = nullptr) const final; + virtual bool ComputeIsDataTable() const; + virtual bool IsTableExposableThroughAccessibility() const; + + private: + bool is_ax_table_; + bool is_data_table_; + DISALLOW_COPY_AND_ASSIGN(AXTable); };
diff --git a/third_party/WebKit/Source/modules/accessibility/AXTableCell.cpp b/third_party/WebKit/Source/modules/accessibility/AXTableCell.cpp index 013623b..4c025637 100644 --- a/third_party/WebKit/Source/modules/accessibility/AXTableCell.cpp +++ b/third_party/WebKit/Source/modules/accessibility/AXTableCell.cpp
@@ -182,6 +182,9 @@ if (!IsTableCell()) return AXLayoutObject::DetermineAccessibilityRole(); + if (!ParentTable()->IsDataTable()) + return kLayoutTableCellRole; + aria_role_ = DetermineAriaRoleAttribute(); return ScanToDecideHeaderRole(); }
diff --git a/third_party/WebKit/Source/modules/accessibility/AXTableColumn.cpp b/third_party/WebKit/Source/modules/accessibility/AXTableColumn.cpp index 7cf34ba..79d771f3 100644 --- a/third_party/WebKit/Source/modules/accessibility/AXTableColumn.cpp +++ b/third_party/WebKit/Source/modules/accessibility/AXTableColumn.cpp
@@ -120,6 +120,12 @@ return true; } +AccessibilityRole AXTableColumn::RoleValue() const { + return parent_ && parent_->IsAXTable() && ToAXTable(parent_)->IsDataTable() + ? kColumnRole + : kLayoutTableColumnRole; +} + void AXTableColumn::AddChildren() { DCHECK(!IsDetached()); DCHECK(!have_children_);
diff --git a/third_party/WebKit/Source/modules/accessibility/AXTableColumn.h b/third_party/WebKit/Source/modules/accessibility/AXTableColumn.h index 85e4750d..f3563b92 100644 --- a/third_party/WebKit/Source/modules/accessibility/AXTableColumn.h +++ b/third_party/WebKit/Source/modules/accessibility/AXTableColumn.h
@@ -51,8 +51,6 @@ // retrieves the "column" headers (th, scope) from top to bottom void HeaderObjectsForColumn(AXObjectVector&); - AccessibilityRole RoleValue() const override { return kColumnRole; } - void SetColumnIndex(int column_index) { column_index_ = column_index; } int ColumnIndex() const { return column_index_; } @@ -62,6 +60,11 @@ protected: virtual bool CanSetSelectedAttribute() const { return false; } + // Set the role via RoleValue() instead of DetermineAccessibilityRole(), + // because the role depends on the parent, and DetermineAccessibilityRole() + // is called before SetParent(). + AccessibilityRole RoleValue() const final; + private: unsigned column_index_;
diff --git a/third_party/WebKit/Source/modules/accessibility/AXTableRow.cpp b/third_party/WebKit/Source/modules/accessibility/AXTableRow.cpp index 7106fddc..1777147 100644 --- a/third_party/WebKit/Source/modules/accessibility/AXTableRow.cpp +++ b/third_party/WebKit/Source/modules/accessibility/AXTableRow.cpp
@@ -72,7 +72,7 @@ if ((aria_role_ = DetermineAriaRoleAttribute()) != kUnknownRole) return aria_role_; - return kRowRole; + return ParentTable()->IsDataTable() ? kRowRole : kLayoutTableRowRole; } bool AXTableRow::IsTableRow() const {
diff --git a/third_party/WebKit/Source/modules/animationworklet/AnimationWorkletGlobalScopeTest.cpp b/third_party/WebKit/Source/modules/animationworklet/AnimationWorkletGlobalScopeTest.cpp index 7c5b182..c59cc5b 100644 --- a/third_party/WebKit/Source/modules/animationworklet/AnimationWorkletGlobalScopeTest.cpp +++ b/third_party/WebKit/Source/modules/animationworklet/AnimationWorkletGlobalScopeTest.cpp
@@ -61,7 +61,7 @@ document->Url(), document->UserAgent(), nullptr /* content_security_policy_parsed_headers */, document->GetReferrerPolicy(), document->GetSecurityOrigin(), - clients, document->AddressSpace(), + document->IsSecureContext(), clients, document->AddressSpace(), OriginTrialContext::GetTokens(document).get(), nullptr /* worker_settings */, kV8CacheOptionsDefault), WTF::nullopt, WorkerInspectorProxy::PauseOnWorkerStart::kDontPause,
diff --git a/third_party/WebKit/Source/modules/animationworklet/AnimationWorkletThread.h b/third_party/WebKit/Source/modules/animationworklet/AnimationWorkletThread.h index a28ed6f..65055eb3 100644 --- a/third_party/WebKit/Source/modules/animationworklet/AnimationWorkletThread.h +++ b/third_party/WebKit/Source/modules/animationworklet/AnimationWorkletThread.h
@@ -47,8 +47,8 @@ bool IsOwningBackingThread() const override { return false; } - scheduler::ThreadType GetThreadType() const override { - return scheduler::ThreadType::kAnimationWorkletThread; + WebThreadType GetThreadType() const override { + return WebThreadType::kAnimationWorkletThread; } };
diff --git a/third_party/WebKit/Source/modules/animationworklet/AnimationWorkletThreadTest.cpp b/third_party/WebKit/Source/modules/animationworklet/AnimationWorkletThreadTest.cpp index 725f0811..7d600a1 100644 --- a/third_party/WebKit/Source/modules/animationworklet/AnimationWorkletThreadTest.cpp +++ b/third_party/WebKit/Source/modules/animationworklet/AnimationWorkletThreadTest.cpp
@@ -40,7 +40,8 @@ public: AnimationWorkletTestPlatform() : thread_(old_platform_->CreateThread( - WebThreadCreationParams("Compositor"))) {} + WebThreadCreationParams(WebThreadType::kTestThread) + .SetThreadName("Compositor"))) {} WebThread* CompositorThread() const override { return thread_.get(); } @@ -94,7 +95,7 @@ document->Url(), document->UserAgent(), nullptr /* content_security_policy_parsed_headers */, document->GetReferrerPolicy(), document->GetSecurityOrigin(), - clients, document->AddressSpace(), + document->IsSecureContext(), clients, document->AddressSpace(), OriginTrialContext::GetTokens(document).get(), nullptr /* worker_settings */, kV8CacheOptionsDefault), WTF::nullopt, WorkerInspectorProxy::PauseOnWorkerStart::kDontPause,
diff --git a/third_party/WebKit/Source/modules/canvas/canvas2d/CanvasRenderingContext2DState.cpp b/third_party/WebKit/Source/modules/canvas/canvas2d/CanvasRenderingContext2DState.cpp index e3fac475b..3b6fdfd1 100644 --- a/third_party/WebKit/Source/modules/canvas/canvas2d/CanvasRenderingContext2DState.cpp +++ b/third_party/WebKit/Source/modules/canvas/canvas2d/CanvasRenderingContext2DState.cpp
@@ -560,8 +560,9 @@ break; default: NOTREACHED(); - // no break on purpose: flags needs to be assigned to avoid compiler warning - // about uninitialized variable. + // no break on purpose: flags needs to be assigned to avoid compiler warning + // about uninitialized variable. + FALLTHROUGH; case kFillPaintType: UpdateFillStyle(); flags = &fill_flags_;
diff --git a/third_party/WebKit/Source/modules/canvas/canvas2d/CanvasRenderingContext2DTest.cpp b/third_party/WebKit/Source/modules/canvas/canvas2d/CanvasRenderingContext2DTest.cpp index 860774d..be35f00 100644 --- a/third_party/WebKit/Source/modules/canvas/canvas2d/CanvasRenderingContext2DTest.cpp +++ b/third_party/WebKit/Source/modules/canvas/canvas2d/CanvasRenderingContext2DTest.cpp
@@ -25,6 +25,7 @@ #include "platform/graphics/Canvas2DLayerBridge.h" #include "platform/graphics/CanvasHeuristicParameters.h" #include "platform/graphics/ColorCorrectionTestUtils.h" +#include "platform/graphics/GraphicsTypes.h" #include "platform/graphics/StaticBitmapImage.h" #include "platform/graphics/gpu/SharedGpuContext.h" #include "platform/graphics/test/FakeGLES2Interface.h" @@ -42,6 +43,8 @@ #include "third_party/skia/include/core/SkSurface.h" #include "third_party/skia/include/core/SkSwizzle.h" +using ::testing::_; +using ::testing::InSequence; using ::testing::Mock; namespace blink { @@ -259,18 +262,21 @@ //============================================================================ -class FakeAcceleratedImageBufferSurface : public Canvas2DLayerBridge { +class FakeCanvas2DLayerBridge : public Canvas2DLayerBridge { public: - FakeAcceleratedImageBufferSurface(const IntSize& size, - CanvasColorParams color_params) + FakeCanvas2DLayerBridge(const IntSize& size, + CanvasColorParams color_params, + AccelerationHint hint) : Canvas2DLayerBridge(size, 0, kDisableAcceleration, color_params), - is_accelerated_(true) {} - ~FakeAcceleratedImageBufferSurface() override = default; + is_accelerated_(hint != kPreferNoAcceleration) {} + ~FakeCanvas2DLayerBridge() override = default; bool IsAccelerated() const override { return is_accelerated_; } void SetIsAccelerated(bool is_accelerated) { if (is_accelerated != is_accelerated_) is_accelerated_ = is_accelerated; } + MOCK_METHOD1(DrawFullImage, void(const PaintImage& image)); + MOCK_METHOD1(DidRestoreCanvasMatrixClipStack, void(PaintCanvas*)); private: bool is_accelerated_; @@ -547,10 +553,10 @@ CreateContext(kNonOpaque); IntSize size(10, 10); - std::unique_ptr<FakeAcceleratedImageBufferSurface> fake_accelerate_surface = - std::make_unique<FakeAcceleratedImageBufferSurface>(size, - CanvasColorParams()); - FakeAcceleratedImageBufferSurface* fake_accelerate_surface_ptr = + std::unique_ptr<FakeCanvas2DLayerBridge> fake_accelerate_surface = + std::make_unique<FakeCanvas2DLayerBridge>(size, CanvasColorParams(), + kPreferAcceleration); + FakeCanvas2DLayerBridge* fake_accelerate_surface_ptr = fake_accelerate_surface.get(); CanvasElement().CreateImageBufferUsingSurfaceForTesting( std::move(fake_accelerate_surface), size); @@ -580,9 +586,8 @@ CanvasContextCreationAttributes attributes; anotherCanvas->GetCanvasRenderingContext("2d", attributes); IntSize size2(10, 5); - auto fake_accelerate_surface2 = - std::make_unique<FakeAcceleratedImageBufferSurface>(size2, - CanvasColorParams()); + auto fake_accelerate_surface2 = std::make_unique<FakeCanvas2DLayerBridge>( + size2, CanvasColorParams(), kPreferAcceleration); anotherCanvas->CreateImageBufferUsingSurfaceForTesting( std::move(fake_accelerate_surface2), size2); EXPECT_EQ(800, GetCurrentGPUMemoryUsage()); @@ -733,13 +738,12 @@ } } -TEST_F(CanvasRenderingContext2DTest, DisableAcceleration) { +TEST_F(CanvasRenderingContext2DTest, DisableAcceleration_UpdateGPUMemoryUsage) { CreateContext(kNonOpaque); IntSize size(10, 10); - auto fake_accelerate_surface = - std::make_unique<FakeAcceleratedImageBufferSurface>(size, - CanvasColorParams()); + auto fake_accelerate_surface = std::make_unique<FakeCanvas2DLayerBridge>( + size, CanvasColorParams(), kPreferAcceleration); CanvasElement().CreateImageBufferUsingSurfaceForTesting( std::move(fake_accelerate_surface), size); CanvasRenderingContext2D* context = Context2d(); @@ -763,6 +767,36 @@ EXPECT_EQ(0u, GetGlobalAcceleratedContextCount()); } +TEST_F(CanvasRenderingContext2DTest, + DisableAcceleration_RestoreCanvasMatrixClipStack) { + // This tests verifies whether the RestoreCanvasMatrixClipStack happens after + // PaintCanvas is drawn from old 2d bridge to new 2d bridge. + InSequence s; + + CreateContext(kNonOpaque); + IntSize size(10, 10); + auto fake_accelerate_surface = std::make_unique<FakeCanvas2DLayerBridge>( + size, CanvasColorParams(), kPreferAcceleration); + CanvasElement().CreateImageBufferUsingSurfaceForTesting( + std::move(fake_accelerate_surface), size); + + auto fake_deaccelerate_surface = std::make_unique<FakeCanvas2DLayerBridge>( + size, CanvasColorParams(), kPreferNoAcceleration); + PaintCanvas* paint_canvas_ptr = fake_deaccelerate_surface->Canvas(); + FakeCanvas2DLayerBridge* surface_ptr = fake_deaccelerate_surface.get(); + + EXPECT_CALL(*fake_deaccelerate_surface, DrawFullImage(_)).Times(1); + EXPECT_CALL(*fake_deaccelerate_surface, + DidRestoreCanvasMatrixClipStack(paint_canvas_ptr)) + .Times(1); + + EXPECT_TRUE(CanvasElement().Canvas2DBuffer()->IsAccelerated()); + CanvasElement().DisableAcceleration(std::move(fake_deaccelerate_surface)); + EXPECT_FALSE(CanvasElement().Canvas2DBuffer()->IsAccelerated()); + + Mock::VerifyAndClearExpectations(surface_ptr); +} + enum class ColorSpaceConversion : uint8_t { NONE = 0, DEFAULT_COLOR_CORRECTED = 1,
diff --git a/third_party/WebKit/Source/modules/clipboard/ClipboardPromise.cpp b/third_party/WebKit/Source/modules/clipboard/ClipboardPromise.cpp index f1ea1d9..3da363d 100644 --- a/third_party/WebKit/Source/modules/clipboard/ClipboardPromise.cpp +++ b/third_party/WebKit/Source/modules/clipboard/ClipboardPromise.cpp
@@ -78,7 +78,7 @@ buffer_(mojom::ClipboardBuffer::kStandard), write_data_() {} -scoped_refptr<WebTaskRunner> ClipboardPromise::GetTaskRunner() { +scoped_refptr<base::SingleThreadTaskRunner> ClipboardPromise::GetTaskRunner() { // TODO(garykac): Replace MiscPlatformAPI with TaskType specific to clipboard. return GetExecutionContext()->GetTaskRunner(TaskType::kMiscPlatformAPI); }
diff --git a/third_party/WebKit/Source/modules/clipboard/ClipboardPromise.h b/third_party/WebKit/Source/modules/clipboard/ClipboardPromise.h index 03dcb3930..cb82833 100644 --- a/third_party/WebKit/Source/modules/clipboard/ClipboardPromise.h +++ b/third_party/WebKit/Source/modules/clipboard/ClipboardPromise.h
@@ -36,7 +36,7 @@ private: ClipboardPromise(ScriptState*); - scoped_refptr<WebTaskRunner> GetTaskRunner(); + scoped_refptr<base::SingleThreadTaskRunner> GetTaskRunner(); mojom::blink::PermissionService* GetPermissionService(); bool IsFocusedDocument(ExecutionContext*);
diff --git a/third_party/WebKit/Source/modules/crypto/SubtleCrypto.cpp b/third_party/WebKit/Source/modules/crypto/SubtleCrypto.cpp index d4e95cc..0de9c03 100644 --- a/third_party/WebKit/Source/modules/crypto/SubtleCrypto.cpp +++ b/third_party/WebKit/Source/modules/crypto/SubtleCrypto.cpp
@@ -30,6 +30,7 @@ #include "modules/crypto/SubtleCrypto.h" +#include "base/single_thread_task_runner.h" #include "bindings/core/v8/Dictionary.h" #include "core/dom/ExecutionContext.h" #include "core/frame/Deprecation.h" @@ -41,7 +42,6 @@ #include "modules/crypto/CryptoResultImpl.h" #include "modules/crypto/CryptoUtilities.h" #include "modules/crypto/NormalizeAlgorithm.h" -#include "platform/WebTaskRunner.h" #include "platform/json/JSONValues.h" #include "public/platform/Platform.h" #include "public/platform/TaskType.h" @@ -192,7 +192,7 @@ HistogramAlgorithmAndKey(ExecutionContext::From(script_state), normalized_algorithm, key->Key()); - scoped_refptr<blink::WebTaskRunner> task_runner = + scoped_refptr<base::SingleThreadTaskRunner> task_runner = ExecutionContext::From(script_state) ->GetTaskRunner(blink::TaskType::kInternalWebCrypto); Platform::Current()->Crypto()->Encrypt(normalized_algorithm, key->Key(), @@ -234,7 +234,7 @@ HistogramAlgorithmAndKey(ExecutionContext::From(script_state), normalized_algorithm, key->Key()); - scoped_refptr<blink::WebTaskRunner> task_runner = + scoped_refptr<base::SingleThreadTaskRunner> task_runner = ExecutionContext::From(script_state) ->GetTaskRunner(blink::TaskType::kInternalWebCrypto); Platform::Current()->Crypto()->Decrypt(normalized_algorithm, key->Key(), @@ -276,7 +276,7 @@ HistogramAlgorithmAndKey(ExecutionContext::From(script_state), normalized_algorithm, key->Key()); - scoped_refptr<blink::WebTaskRunner> task_runner = + scoped_refptr<base::SingleThreadTaskRunner> task_runner = ExecutionContext::From(script_state) ->GetTaskRunner(blink::TaskType::kInternalWebCrypto); Platform::Current()->Crypto()->Sign(normalized_algorithm, key->Key(), @@ -324,7 +324,7 @@ HistogramAlgorithmAndKey(ExecutionContext::From(script_state), normalized_algorithm, key->Key()); - scoped_refptr<blink::WebTaskRunner> task_runner = + scoped_refptr<base::SingleThreadTaskRunner> task_runner = ExecutionContext::From(script_state) ->GetTaskRunner(blink::TaskType::kInternalWebCrypto); Platform::Current()->Crypto()->VerifySignature( @@ -355,7 +355,7 @@ HistogramAlgorithm(ExecutionContext::From(script_state), normalized_algorithm); - scoped_refptr<blink::WebTaskRunner> task_runner = + scoped_refptr<base::SingleThreadTaskRunner> task_runner = ExecutionContext::From(script_state) ->GetTaskRunner(blink::TaskType::kInternalWebCrypto); Platform::Current()->Crypto()->Digest(normalized_algorithm, std::move(data), @@ -393,7 +393,7 @@ HistogramAlgorithm(ExecutionContext::From(script_state), normalized_algorithm); - scoped_refptr<blink::WebTaskRunner> task_runner = + scoped_refptr<base::SingleThreadTaskRunner> task_runner = ExecutionContext::From(script_state) ->GetTaskRunner(blink::TaskType::kInternalWebCrypto); Platform::Current()->Crypto()->GenerateKey(normalized_algorithm, extractable, @@ -481,7 +481,7 @@ HistogramAlgorithm(ExecutionContext::From(script_state), normalized_algorithm); - scoped_refptr<blink::WebTaskRunner> task_runner = + scoped_refptr<base::SingleThreadTaskRunner> task_runner = ExecutionContext::From(script_state) ->GetTaskRunner(blink::TaskType::kInternalWebCrypto); Platform::Current()->Crypto()->ImportKey( @@ -512,7 +512,7 @@ } HistogramKey(ExecutionContext::From(script_state), key->Key()); - scoped_refptr<blink::WebTaskRunner> task_runner = + scoped_refptr<base::SingleThreadTaskRunner> task_runner = ExecutionContext::From(script_state) ->GetTaskRunner(blink::TaskType::kInternalWebCrypto); Platform::Current()->Crypto()->ExportKey(format, key->Key(), result->Result(), @@ -573,7 +573,7 @@ HistogramAlgorithmAndKey(ExecutionContext::From(script_state), normalized_algorithm, wrapping_key->Key()); HistogramKey(ExecutionContext::From(script_state), key->Key()); - scoped_refptr<blink::WebTaskRunner> task_runner = + scoped_refptr<base::SingleThreadTaskRunner> task_runner = ExecutionContext::From(script_state) ->GetTaskRunner(blink::TaskType::kInternalWebCrypto); Platform::Current()->Crypto()->WrapKey( @@ -649,7 +649,7 @@ normalized_algorithm, unwrapping_key->Key()); HistogramAlgorithm(ExecutionContext::From(script_state), normalized_key_algorithm); - scoped_refptr<blink::WebTaskRunner> task_runner = + scoped_refptr<base::SingleThreadTaskRunner> task_runner = ExecutionContext::From(script_state) ->GetTaskRunner(blink::TaskType::kInternalWebCrypto); Platform::Current()->Crypto()->UnwrapKey( @@ -689,7 +689,7 @@ HistogramAlgorithmAndKey(ExecutionContext::From(script_state), normalized_algorithm, base_key->Key()); - scoped_refptr<blink::WebTaskRunner> task_runner = + scoped_refptr<base::SingleThreadTaskRunner> task_runner = ExecutionContext::From(script_state) ->GetTaskRunner(blink::TaskType::kInternalWebCrypto); Platform::Current()->Crypto()->DeriveBits( @@ -762,7 +762,7 @@ normalized_algorithm, base_key->Key()); HistogramAlgorithm(ExecutionContext::From(script_state), normalized_derived_key_algorithm); - scoped_refptr<blink::WebTaskRunner> task_runner = + scoped_refptr<base::SingleThreadTaskRunner> task_runner = ExecutionContext::From(script_state) ->GetTaskRunner(blink::TaskType::kInternalWebCrypto); Platform::Current()->Crypto()->DeriveKey(
diff --git a/third_party/WebKit/Source/modules/csspaint/PaintWorklet.cpp b/third_party/WebKit/Source/modules/csspaint/PaintWorklet.cpp index cc4bcb4b..b803fbb 100644 --- a/third_party/WebKit/Source/modules/csspaint/PaintWorklet.cpp +++ b/third_party/WebKit/Source/modules/csspaint/PaintWorklet.cpp
@@ -102,6 +102,8 @@ PaintWorkletGlobalScopeProxy* proxy = PaintWorkletGlobalScopeProxy::From(FindAvailableGlobalScope()); CSSPaintDefinition* paint_definition = proxy->FindDefinition(name); + if (!paint_definition) + return nullptr; return paint_definition->Paint(observer, container_size, data); }
diff --git a/third_party/WebKit/Source/modules/csspaint/PaintWorkletGlobalScopeProxy.cpp b/third_party/WebKit/Source/modules/csspaint/PaintWorkletGlobalScopeProxy.cpp index b4ebea3..de68f1f 100644 --- a/third_party/WebKit/Source/modules/csspaint/PaintWorkletGlobalScopeProxy.cpp +++ b/third_party/WebKit/Source/modules/csspaint/PaintWorkletGlobalScopeProxy.cpp
@@ -33,8 +33,8 @@ document->Url(), document->UserAgent(), document->GetContentSecurityPolicy()->Headers().get(), document->GetReferrerPolicy(), document->GetSecurityOrigin(), - nullptr /* worker_clients */, document->AddressSpace(), - OriginTrialContext::GetTokens(document).get(), + document->IsSecureContext(), nullptr /* worker_clients */, + document->AddressSpace(), OriginTrialContext::GetTokens(document).get(), nullptr /* worker_settings */, kV8CacheOptionsDefault); global_scope_ = PaintWorkletGlobalScope::Create( frame, std::move(creation_params), *reporting_proxy_, @@ -45,7 +45,7 @@ const KURL& module_url_record, WorkletModuleResponsesMap* module_responses_map, network::mojom::FetchCredentialsMode credentials_mode, - scoped_refptr<WebTaskRunner> outside_settings_task_runner, + scoped_refptr<base::SingleThreadTaskRunner> outside_settings_task_runner, WorkletPendingTasks* pending_tasks) { DCHECK(IsMainThread()); global_scope_->FetchAndInvokeScript(
diff --git a/third_party/WebKit/Source/modules/csspaint/PaintWorkletGlobalScopeProxy.h b/third_party/WebKit/Source/modules/csspaint/PaintWorkletGlobalScopeProxy.h index 80a92d7e..19db8017 100644 --- a/third_party/WebKit/Source/modules/csspaint/PaintWorkletGlobalScopeProxy.h +++ b/third_party/WebKit/Source/modules/csspaint/PaintWorkletGlobalScopeProxy.h
@@ -35,7 +35,7 @@ const KURL& module_url_record, WorkletModuleResponsesMap*, network::mojom::FetchCredentialsMode, - scoped_refptr<WebTaskRunner> outside_settings_task_runner, + scoped_refptr<base::SingleThreadTaskRunner> outside_settings_task_runner, WorkletPendingTasks*) override; void WorkletObjectDestroyed() override; void TerminateWorkletGlobalScope() override;
diff --git a/third_party/WebKit/Source/modules/exported/WebEmbeddedWorkerImpl.cpp b/third_party/WebKit/Source/modules/exported/WebEmbeddedWorkerImpl.cpp index c2489a01..77a5a3a 100644 --- a/third_party/WebKit/Source/modules/exported/WebEmbeddedWorkerImpl.cpp +++ b/third_party/WebKit/Source/modules/exported/WebEmbeddedWorkerImpl.cpp
@@ -319,6 +319,7 @@ // FIXME: this document's origin is pristine and without any extra privileges. // (crbug.com/254993) const SecurityOrigin* starter_origin = document->GetSecurityOrigin(); + bool starter_secure_context = document->IsSecureContext(); WorkerClients* worker_clients = WorkerClients::Create(); ProvideIndexedDBClientToWorker(worker_clients, @@ -358,8 +359,8 @@ global_scope_creation_params = std::make_unique<GlobalScopeCreationParams>( worker_start_data_.script_url, worker_start_data_.user_agent, document->GetContentSecurityPolicy()->Headers().get(), - document->GetReferrerPolicy(), starter_origin, worker_clients, - main_script_loader_->ResponseAddressSpace(), + document->GetReferrerPolicy(), starter_origin, starter_secure_context, + worker_clients, main_script_loader_->ResponseAddressSpace(), main_script_loader_->OriginTrialTokens(), std::move(worker_settings), static_cast<V8CacheOptions>(worker_start_data_.v8_cache_options), std::move(interface_provider_info_)); @@ -373,8 +374,9 @@ global_scope_creation_params = std::make_unique<GlobalScopeCreationParams>( worker_start_data_.script_url, worker_start_data_.user_agent, nullptr /* ContentSecurityPolicy */, kReferrerPolicyDefault, - starter_origin, worker_clients, worker_start_data_.address_space, - nullptr /* OriginTrialTokens */, std::move(worker_settings), + starter_origin, starter_secure_context, worker_clients, + worker_start_data_.address_space, nullptr /* OriginTrialTokens */, + std::move(worker_settings), static_cast<V8CacheOptions>(worker_start_data_.v8_cache_options), std::move(interface_provider_info_)); }
diff --git a/third_party/WebKit/Source/modules/exported/WebEmbeddedWorkerImpl.h b/third_party/WebKit/Source/modules/exported/WebEmbeddedWorkerImpl.h index c14c3c7..5d6b1a9 100644 --- a/third_party/WebKit/Source/modules/exported/WebEmbeddedWorkerImpl.h +++ b/third_party/WebKit/Source/modules/exported/WebEmbeddedWorkerImpl.h
@@ -37,7 +37,6 @@ #include "core/workers/WorkerClients.h" #include "modules/ModulesExport.h" #include "modules/serviceworkers/ServiceWorkerContentSettingsProxy.h" -#include "platform/WebTaskRunner.h" #include "platform/heap/Handle.h" #include "public/web/WebEmbeddedWorker.h" #include "public/web/WebEmbeddedWorkerStartData.h"
diff --git a/third_party/WebKit/Source/modules/filesystem/DOMFileSystem.cpp b/third_party/WebKit/Source/modules/filesystem/DOMFileSystem.cpp index 9d9a09c..7347cc1 100644 --- a/third_party/WebKit/Source/modules/filesystem/DOMFileSystem.cpp +++ b/third_party/WebKit/Source/modules/filesystem/DOMFileSystem.cpp
@@ -38,7 +38,6 @@ #include "modules/filesystem/FileEntry.h" #include "modules/filesystem/FileSystemCallbacks.h" #include "modules/filesystem/FileWriter.h" -#include "platform/WebTaskRunner.h" #include "platform/weborigin/SecurityOrigin.h" #include "platform/wtf/text/StringBuilder.h" #include "platform/wtf/text/WTFString.h"
diff --git a/third_party/WebKit/Source/modules/geolocation/GeoNotifier.cpp b/third_party/WebKit/Source/modules/geolocation/GeoNotifier.cpp index 0d88713..0fbf4da1 100644 --- a/third_party/WebKit/Source/modules/geolocation/GeoNotifier.cpp +++ b/third_party/WebKit/Source/modules/geolocation/GeoNotifier.cpp
@@ -93,6 +93,12 @@ // TODO(yukishiino): Remove this check once we understand the cause. // https://crbug.com/792604 CHECK(!geolocation_->GetExecutionContext()->IsContextDestroyed()); + // As the timer fires asynchronously, it's possible that |geolocation_| + // no longer owns this notifier, i.e. |geolocation_| is no longer performing + // wrapper-tracing. In that case, the underlying V8 function may not be alive. + if (!geolocation_->DoesOwnNotifier(this)) { + return; // Do not invoke anything because of no owner geolocation. + } // Test for fatal error first. This is required for the case where the // LocalFrame is disconnected and requests are cancelled.
diff --git a/third_party/WebKit/Source/modules/geolocation/Geolocation.cpp b/third_party/WebKit/Source/modules/geolocation/Geolocation.cpp index 9dc71a9..4be41cc 100644 --- a/third_party/WebKit/Source/modules/geolocation/Geolocation.cpp +++ b/third_party/WebKit/Source/modules/geolocation/Geolocation.cpp
@@ -296,6 +296,10 @@ StopUpdating(); } +bool Geolocation::DoesOwnNotifier(GeoNotifier* notifier) const { + return one_shots_.Contains(notifier) || watchers_.Contains(notifier); +} + bool Geolocation::HaveSuitableCachedPosition(const PositionOptions& options) { if (!last_position_) return false; @@ -522,7 +526,8 @@ } bool Geolocation::HasPendingActivity() const { - return !one_shots_.IsEmpty() || !one_shots_being_invoked_.IsEmpty(); + return !one_shots_.IsEmpty() || !one_shots_being_invoked_.IsEmpty() || + !watchers_.IsEmpty() || !watchers_being_invoked_.IsEmpty(); } void Geolocation::OnGeolocationConnectionError() {
diff --git a/third_party/WebKit/Source/modules/geolocation/Geolocation.h b/third_party/WebKit/Source/modules/geolocation/Geolocation.h index a6fd82df..8b25a8e 100644 --- a/third_party/WebKit/Source/modules/geolocation/Geolocation.h +++ b/third_party/WebKit/Source/modules/geolocation/Geolocation.h
@@ -99,6 +99,9 @@ // Discards the notifier if it is a oneshot because it timed it. void RequestTimedOut(GeoNotifier*); + // Returns true if this geolocation still owns the given notifier. + bool DoesOwnNotifier(GeoNotifier*) const; + // Inherited from PageVisibilityObserver. void PageVisibilityChanged() override;
diff --git a/third_party/WebKit/Source/modules/media_controls/MediaControlsImpl.cpp b/third_party/WebKit/Source/modules/media_controls/MediaControlsImpl.cpp index ec2c5c4..ff91002 100644 --- a/third_party/WebKit/Source/modules/media_controls/MediaControlsImpl.cpp +++ b/third_party/WebKit/Source/modules/media_controls/MediaControlsImpl.cpp
@@ -610,23 +610,27 @@ } MediaControlsImpl::ControlsState MediaControlsImpl::State() const { - if (is_scrubbing_) + HTMLMediaElement::NetworkState network_state = + MediaElement().getNetworkState(); + HTMLMediaElement::ReadyState ready_state = MediaElement().getReadyState(); + + if (is_scrubbing_ && ready_state != HTMLMediaElement::kHaveNothing) return ControlsState::kScrubbing; - switch (MediaElement().getNetworkState()) { + switch (network_state) { case HTMLMediaElement::kNetworkEmpty: case HTMLMediaElement::kNetworkNoSource: return ControlsState::kNoSource; case HTMLMediaElement::kNetworkLoading: - if (MediaElement().getReadyState() == HTMLMediaElement::kHaveNothing) + if (ready_state == HTMLMediaElement::kHaveNothing) return ControlsState::kLoadingMetadata; if (!MediaElement().paused() && - MediaElement().getReadyState() != HTMLMediaElement::kHaveEnoughData) { + ready_state != HTMLMediaElement::kHaveEnoughData) { return ControlsState::kBuffering; } break; case HTMLMediaElement::kNetworkIdle: - if (MediaElement().getReadyState() == HTMLMediaElement::kHaveNothing) + if (ready_state == HTMLMediaElement::kHaveNothing) return ControlsState::kNotLoaded; break; } @@ -976,9 +980,8 @@ std::make_pair(toggle_closed_captions_button_.Get(), false), }; - // Get the size of the media controls. - WebSize controls_size = - MediaControlElementsHelper::GetSizeOrDefault(*this, WebSize(0, 0)); + // Current size of the media controls. + WebSize controls_size = size_; // The video controls are more than one row so we need to allocate vertical // room and hide the overlay play button if there is not enough room.
diff --git a/third_party/WebKit/Source/modules/media_controls/MediaControlsOrientationLockDelegate.h b/third_party/WebKit/Source/modules/media_controls/MediaControlsOrientationLockDelegate.h index 13f3bce..fe13bfa 100644 --- a/third_party/WebKit/Source/modules/media_controls/MediaControlsOrientationLockDelegate.h +++ b/third_party/WebKit/Source/modules/media_controls/MediaControlsOrientationLockDelegate.h
@@ -10,6 +10,7 @@ #include "modules/ModulesExport.h" #include "platform/WebTaskRunner.h" #include "platform/wtf/Optional.h" +#include "platform/wtf/Time.h" #include "public/platform/modules/screen_orientation/WebScreenOrientationLockType.h" namespace blink {
diff --git a/third_party/WebKit/Source/modules/media_controls/MediaControlsResourceLoader.cpp b/third_party/WebKit/Source/modules/media_controls/MediaControlsResourceLoader.cpp index 532cfedc..1dfff58 100644 --- a/third_party/WebKit/Source/modules/media_controls/MediaControlsResourceLoader.cpp +++ b/third_party/WebKit/Source/modules/media_controls/MediaControlsResourceLoader.cpp
@@ -77,6 +77,13 @@ return ResourceBundleHelper::UncompressResourceAsString( IDR_SHADOWSTYLE_MODERN_MEDIA_CONTROLS_OVERLAY_PLAY_CSS); }; + +// static +String MediaControlsResourceLoader::GetMediaInterstitialsStyleSheet() { + return ResourceBundleHelper::UncompressResourceAsString( + IDR_UASTYLE_MEDIA_INTERSTITIALS_CSS); +}; + // Re-enable the warnings. #if defined(OS_WIN) #pragma warning(default : 4068) @@ -85,9 +92,11 @@ #endif String MediaControlsResourceLoader::GetUAStyleSheet() { - if (ShouldLoadAndroidCSS()) - return GetMediaControlsCSS() + GetMediaControlsAndroidCSS(); - return GetMediaControlsCSS(); + if (ShouldLoadAndroidCSS()) { + return GetMediaControlsCSS() + GetMediaControlsAndroidCSS() + + GetMediaInterstitialsStyleSheet(); + } + return GetMediaControlsCSS() + GetMediaInterstitialsStyleSheet(); } void MediaControlsResourceLoader::InjectMediaControlsUAStyleSheet() {
diff --git a/third_party/WebKit/Source/modules/media_controls/MediaControlsResourceLoader.h b/third_party/WebKit/Source/modules/media_controls/MediaControlsResourceLoader.h index 4cb5a87..8392380 100644 --- a/third_party/WebKit/Source/modules/media_controls/MediaControlsResourceLoader.h +++ b/third_party/WebKit/Source/modules/media_controls/MediaControlsResourceLoader.h
@@ -31,6 +31,9 @@ // Returns the overlay play button stylesheet content as a string. static String GetOverlayPlayStyleSheet(); + // Returns the specific stylesheet used for media related interstitials. + static String GetMediaInterstitialsStyleSheet(); + String GetUAStyleSheet() override; MediaControlsResourceLoader();
diff --git a/third_party/WebKit/Source/modules/media_controls/resources/legacyMediaControls.css b/third_party/WebKit/Source/modules/media_controls/resources/legacyMediaControls.css index 6642bfab..9c98aaf 100644 --- a/third_party/WebKit/Source/modules/media_controls/resources/legacyMediaControls.css +++ b/third_party/WebKit/Source/modules/media_controls/resources/legacyMediaControls.css
@@ -170,101 +170,6 @@ padding: 0; } -/* TODO(xjz): Move media remoting elements to a separate css file. */ -video::-internal-media-remoting-interstitial, -video::-internal-picture-in-picture-interstitial { - width: inherit; - height: inherit; - position: relative; - direction: ltr; - display: flex; - flex-direction: column; - justify-content: flex-end; - align-items: center; - /* The font size is set to be proportional to the viewport width. - * Specifically, it is 15px for 400px width, and 36px for 1920px width. The - * full math expression is: - * 15px + (36 - 15) * ((100vw - 400px) / (1920 - 400)). */ - font-size: calc(9.5px + 1.38vw); - background-color: transparent; - opacity: 0; - transition: opacity .3s ease-in-out; -} - -video::-internal-media-remoting-background-image, -video::-internal-picture-in-picture-background-image { - display: flex; - position: absolute; - margin: 0; - top: 0px; - left: 0px; - width: 100%; - height: 100%; - border: none; - border-width: 0px; - background-color: transparent; - padding: 0; - filter: grayscale(100%) blur(5px) opacity(40%); -} - -video::-internal-media-remoting-cast-icon { - -webkit-appearance: none; - background-image: -webkit-image-set( - url(default_100_percent/legacy/mediaremoting_cast.png) 1x, - url(default_200_percent/legacy/mediaremoting_cast.png) 2x); - background-size: 100% 100%; - background-repeat: no-repeat; - background-position: center center; - display: flex; - position: absolute; - margin: 0px; - border-width: 0px; - background-color: transparent; - height: 2.5vw; - width: 3vw; - padding: 0px; - left: calc(50% - 1.5vw); - top: calc(50% - 3vw); -} - -video::-internal-media-remoting-cast-text-message, -video::-internal-picture-in-picture-message { - display: inline; - position: absolute; - top: calc(50% + 1vw); - border: none; - color: rgba(255,255,255,.54); - width: 100%; - text-wrap: none; - text-align: center; - background-color: transparent; - font-size: 90%; - font-family: Roboto-Regular, Sans-serif, Segoe, Serif, Helvetica; - padding: 0px; - margin: 0px; -} - -video::-internal-picture-in-picture-message { - top: calc(50%); -} - -video::-internal-media-remoting-toast-message { - display: inline; - position: absolute; - top: 16pt; - border: none; - border-radius: 2pt; - color: rgba(255,255,255, 1); - width: auto; - text-wrap: none; - text-align: center; - background-color: rgba(40, 44, 50, 0.7); - font-size: 90%; - font-family: Roboto-Regular, Sans-serif, Segoe, Serif, Helvetica; - padding: 10pt 24pt 10pt 24pt; - margin: 0px; -} - video::-internal-media-controls-overlay-cast-button { -webkit-appearance: none; background-image: -webkit-image-set(
diff --git a/third_party/WebKit/Source/modules/media_controls/resources/mediaInterstitials.css b/third_party/WebKit/Source/modules/media_controls/resources/mediaInterstitials.css new file mode 100644 index 0000000..d6eb09e1 --- /dev/null +++ b/third_party/WebKit/Source/modules/media_controls/resources/mediaInterstitials.css
@@ -0,0 +1,96 @@ +/* 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. */ + +video::-internal-media-interstitial { + width: inherit; + height: inherit; + position: relative; + direction: ltr; + display: flex; + flex-direction: column; + justify-content: flex-end; + align-items: center; + /* The font size is set to be proportional to the viewport width. + * Specifically, it is 15px for 400px width, and 36px for 1920px width. + * The full math expression is: + * 15px + (36 - 15) * ((100vw - 400px) / (1920 - 400)). + */ + font-size: calc(9.5px + 1.38vw); + background-color: transparent; + opacity: 0; + transition: opacity .3s ease-in-out; +} + +video::-internal-media-interstitial-background-image { + display: flex; + position: absolute; + margin: 0; + top: 0px; + left: 0px; + width: 100%; + height: 100%; + border: none; + border-width: 0px; + background-color: transparent; + padding: 0; + filter: grayscale(100%) blur(5px) opacity(40%); +} + +video::-internal-media-remoting-cast-icon { + -webkit-appearance: none; + background-image: -webkit-image-set( + url(default_100_percent/legacy/mediaremoting_cast.png) 1x, + url(default_200_percent/legacy/mediaremoting_cast.png) 2x); + background-size: 100% 100%; + background-repeat: no-repeat; + background-position: center center; + display: flex; + position: absolute; + margin: 0px; + border-width: 0px; + background-color: transparent; + height: 2.5vw; + width: 3vw; + padding: 0px; + left: calc(50% - 1.5vw); + top: calc(50% - 3vw); +} + +video::-internal-media-remoting-cast-text-message, +video::-internal-picture-in-picture-message { + display: inline; + position: absolute; + top: calc(50% + 1vw); + border: none; + color: rgba(255,255,255,.54); + width: 100%; + text-wrap: none; + text-align: center; + background-color: transparent; + font-size: 90%; + font-family: Roboto-Regular, Sans-serif, Segoe, Serif, Helvetica; + padding: 0px; + margin: 0px; +} + +video::-internal-picture-in-picture-message { + top: calc(50%); +} + +video::-internal-media-remoting-toast-message { + display: inline; + position: absolute; + top: 16pt; + border: none; + border-radius: 2pt; + color: rgba(255,255,255, 1); + width: auto; + text-wrap: none; + text-align: center; + background-color: rgba(40, 44, 50, 0.7); + font-size: 90%; + font-family: Roboto-Regular, Sans-serif, Segoe, Serif, Helvetica; + padding: 10pt 24pt 10pt 24pt; + margin: 0px; +}
diff --git a/third_party/WebKit/Source/modules/media_controls/resources/media_controls_resources.grd b/third_party/WebKit/Source/modules/media_controls/resources/media_controls_resources.grd index 536b8b93..909534b 100644 --- a/third_party/WebKit/Source/modules/media_controls/resources/media_controls_resources.grd +++ b/third_party/WebKit/Source/modules/media_controls/resources/media_controls_resources.grd
@@ -11,6 +11,7 @@ <structures fallback_to_low_resolution="true"> <structure type="chrome_html" name="IDR_UASTYLE_LEGACY_MEDIA_CONTROLS_CSS" file="legacyMediaControls.css" flattenhtml="true" compress="gzip" /> <structure type="chrome_html" name="IDR_UASTYLE_MODERN_MEDIA_CONTROLS_CSS" file="modernMediaControls.css" flattenhtml="true" compress="gzip" /> + <structure type="chrome_html" name="IDR_UASTYLE_MEDIA_INTERSTITIALS_CSS" file="mediaInterstitials.css" flattenhtml="true" compress="gzip" /> <structure type="chrome_html" name="IDR_SHADOWSTYLE_MODERN_MEDIA_CONTROLS_LOADING_CSS" file="modernMediaControls_loading.css" flattenhtml="true" compress="gzip" /> </structures> <includes>
diff --git a/third_party/WebKit/Source/modules/media_controls/resources/modernMediaControls.css b/third_party/WebKit/Source/modules/media_controls/resources/modernMediaControls.css index d69840d..f9c3228 100644 --- a/third_party/WebKit/Source/modules/media_controls/resources/modernMediaControls.css +++ b/third_party/WebKit/Source/modules/media_controls/resources/modernMediaControls.css
@@ -473,11 +473,17 @@ * Audio Controls */ +audio:not([controls]) { + display: none !important; +} + +audio { + width: 300px; + height: 54px; +} + audio::-webkit-media-controls { min-width: 240px; - display: flex; - align-items: center; - justify-content: center; } audio::-webkit-media-controls-overlay-enclosure { @@ -485,6 +491,7 @@ } audio::-webkit-media-controls-enclosure { + min-height: 54px; max-height: 54px; flex-direction: row; background: #F1F3F4;
diff --git a/third_party/WebKit/Source/modules/peerconnection/RTCPeerConnection.cpp b/third_party/WebKit/Source/modules/peerconnection/RTCPeerConnection.cpp index 151fef2..1699b90 100644 --- a/third_party/WebKit/Source/modules/peerconnection/RTCPeerConnection.cpp +++ b/third_party/WebKit/Source/modules/peerconnection/RTCPeerConnection.cpp
@@ -997,7 +997,7 @@ // Generate certificate. The |certificateObserver| will resolve the promise // asynchronously upon completion. The observer will manage its own // destruction as well as the resolver's destruction. - scoped_refptr<WebTaskRunner> task_runner = + scoped_refptr<base::SingleThreadTaskRunner> task_runner = ExecutionContext::From(script_state) ->GetTaskRunner(blink::TaskType::kUnthrottled); if (!expires) {
diff --git a/third_party/WebKit/Source/modules/presentation/PresentationAvailabilityState.cpp b/third_party/WebKit/Source/modules/presentation/PresentationAvailabilityState.cpp index e930233..b49b891 100644 --- a/third_party/WebKit/Source/modules/presentation/PresentationAvailabilityState.cpp +++ b/third_party/WebKit/Source/modules/presentation/PresentationAvailabilityState.cpp
@@ -6,7 +6,6 @@ #include "modules/presentation/PresentationAvailabilityObserver.h" #include "modules/presentation/PresentationController.h" -#include "platform/WebTaskRunner.h" #include "platform/wtf/Functional.h" #include "public/platform/Platform.h" #include "public/platform/modules/presentation/WebPresentationError.h"
diff --git a/third_party/WebKit/Source/modules/quota/DeprecatedStorageInfo.cpp b/third_party/WebKit/Source/modules/quota/DeprecatedStorageInfo.cpp index 0b78cc3..6cbfccf 100644 --- a/third_party/WebKit/Source/modules/quota/DeprecatedStorageInfo.cpp +++ b/third_party/WebKit/Source/modules/quota/DeprecatedStorageInfo.cpp
@@ -34,7 +34,6 @@ #include "core/dom/ExceptionCode.h" #include "core/dom/ExecutionContext.h" #include "modules/quota/DeprecatedStorageQuota.h" -#include "platform/WebTaskRunner.h" #include "platform/bindings/ScriptState.h" #include "public/platform/TaskType.h"
diff --git a/third_party/WebKit/Source/modules/quota/DeprecatedStorageQuota.cpp b/third_party/WebKit/Source/modules/quota/DeprecatedStorageQuota.cpp index 2d5b5c8..eb1575d2 100644 --- a/third_party/WebKit/Source/modules/quota/DeprecatedStorageQuota.cpp +++ b/third_party/WebKit/Source/modules/quota/DeprecatedStorageQuota.cpp
@@ -40,7 +40,6 @@ #include "modules/quota/DOMError.h" #include "modules/quota/QuotaUtils.h" #include "mojo/public/cpp/bindings/callback_helpers.h" -#include "platform/WebTaskRunner.h" #include "platform/bindings/ScriptState.h" #include "platform/weborigin/KURL.h" #include "platform/weborigin/SecurityOrigin.h"
diff --git a/third_party/WebKit/Source/modules/serviceworkers/ServiceWorkerThread.cpp b/third_party/WebKit/Source/modules/serviceworkers/ServiceWorkerThread.cpp index 4b4cc98..0da2b1bb 100644 --- a/third_party/WebKit/Source/modules/serviceworkers/ServiceWorkerThread.cpp +++ b/third_party/WebKit/Source/modules/serviceworkers/ServiceWorkerThread.cpp
@@ -48,7 +48,7 @@ : WorkerThread(loading_context, *global_scope_proxy), global_scope_proxy_(global_scope_proxy), worker_backing_thread_(WorkerBackingThread::Create( - WebThreadCreationParams("ServiceWorker Thread"))), + WebThreadCreationParams(GetThreadType()))), installed_scripts_manager_(std::move(installed_scripts_manager)) {} ServiceWorkerThread::~ServiceWorkerThread() {
diff --git a/third_party/WebKit/Source/modules/serviceworkers/ServiceWorkerThread.h b/third_party/WebKit/Source/modules/serviceworkers/ServiceWorkerThread.h index 23a68f9..7672ddd0 100644 --- a/third_party/WebKit/Source/modules/serviceworkers/ServiceWorkerThread.h +++ b/third_party/WebKit/Source/modules/serviceworkers/ServiceWorkerThread.h
@@ -63,8 +63,8 @@ WorkerOrWorkletGlobalScope* CreateWorkerGlobalScope( std::unique_ptr<GlobalScopeCreationParams>) override; - scheduler::ThreadType GetThreadType() const override { - return scheduler::ThreadType::kServiceWorkerThread; + WebThreadType GetThreadType() const override { + return WebThreadType::kServiceWorkerThread; } Persistent<ServiceWorkerGlobalScopeProxy> global_scope_proxy_;
diff --git a/third_party/WebKit/Source/modules/serviceworkers/WebEmbeddedWorkerImplTest.cpp b/third_party/WebKit/Source/modules/serviceworkers/WebEmbeddedWorkerImplTest.cpp index 65f6452..f3e82a6 100644 --- a/third_party/WebKit/Source/modules/serviceworkers/WebEmbeddedWorkerImplTest.cpp +++ b/third_party/WebKit/Source/modules/serviceworkers/WebEmbeddedWorkerImplTest.cpp
@@ -6,7 +6,6 @@ #include <memory> #include "platform/WaitableEvent.h" -#include "platform/WebTaskRunner.h" #include "platform/loader/fetch/ResourceError.h" #include "platform/runtime_enabled_features.h" #include "platform/testing/URLTestHelpers.h"
diff --git a/third_party/WebKit/Source/modules/webaudio/AsyncAudioDecoder.cpp b/third_party/WebKit/Source/modules/webaudio/AsyncAudioDecoder.cpp index 4f0ca5d..32096ed6 100644 --- a/third_party/WebKit/Source/modules/webaudio/AsyncAudioDecoder.cpp +++ b/third_party/WebKit/Source/modules/webaudio/AsyncAudioDecoder.cpp
@@ -32,6 +32,7 @@ #include "modules/webaudio/AudioBuffer.h" #include "modules/webaudio/BaseAudioContext.h" #include "platform/CrossThreadFunctional.h" +#include "platform/WebTaskRunner.h" #include "platform/audio/AudioBus.h" #include "platform/audio/AudioFileReader.h" #include "platform/threading/BackgroundTaskRunner.h"
diff --git a/third_party/WebKit/Source/modules/webaudio/AudioScheduledSourceNode.h b/third_party/WebKit/Source/modules/webaudio/AudioScheduledSourceNode.h index 1e2b377..9cd52e7 100644 --- a/third_party/WebKit/Source/modules/webaudio/AudioScheduledSourceNode.h +++ b/third_party/WebKit/Source/modules/webaudio/AudioScheduledSourceNode.h
@@ -132,7 +132,7 @@ // and getter to protect the access to this. int playback_state_; - scoped_refptr<WebTaskRunner> task_runner_; + scoped_refptr<base::SingleThreadTaskRunner> task_runner_; }; class AudioScheduledSourceNode
diff --git a/third_party/WebKit/Source/modules/webaudio/AudioWorkletGlobalScopeTest.cpp b/third_party/WebKit/Source/modules/webaudio/AudioWorkletGlobalScopeTest.cpp index 4e6c432..a4ed3e0 100644 --- a/third_party/WebKit/Source/modules/webaudio/AudioWorkletGlobalScopeTest.cpp +++ b/third_party/WebKit/Source/modules/webaudio/AudioWorkletGlobalScopeTest.cpp
@@ -72,7 +72,8 @@ document->Url(), document->UserAgent(), nullptr /* content_security_policy_parsed_headers */, document->GetReferrerPolicy(), document->GetSecurityOrigin(), - nullptr /* worker_clients */, document->AddressSpace(), + document->IsSecureContext(), nullptr /* worker_clients */, + document->AddressSpace(), OriginTrialContext::GetTokens(document).get(), nullptr /* worker_settings */, kV8CacheOptionsDefault), WTF::nullopt, WorkerInspectorProxy::PauseOnWorkerStart::kDontPause,
diff --git a/third_party/WebKit/Source/modules/webaudio/AudioWorkletNode.h b/third_party/WebKit/Source/modules/webaudio/AudioWorkletNode.h index 4cfdaa6..37ae995 100644 --- a/third_party/WebKit/Source/modules/webaudio/AudioWorkletNode.h +++ b/third_party/WebKit/Source/modules/webaudio/AudioWorkletNode.h
@@ -86,7 +86,7 @@ HashMap<String, std::unique_ptr<AudioFloatArray>> param_value_map_; // A reference to the main thread task runner. - scoped_refptr<WebTaskRunner> task_runner_; + scoped_refptr<base::SingleThreadTaskRunner> task_runner_; }; class AudioWorkletNode final : public AudioNode,
diff --git a/third_party/WebKit/Source/modules/webaudio/AudioWorkletProcessor.idl b/third_party/WebKit/Source/modules/webaudio/AudioWorkletProcessor.idl index d6702bc..1566021 100644 --- a/third_party/WebKit/Source/modules/webaudio/AudioWorkletProcessor.idl +++ b/third_party/WebKit/Source/modules/webaudio/AudioWorkletProcessor.idl
@@ -8,7 +8,8 @@ Constructor, ConstructorCallWith=ExecutionContext, Exposed=AudioWorklet, - Global=(Worklet,AudioWorklet) + Global=(Worklet,AudioWorklet), + OriginTrialEnabled=AudioWorklet ] interface AudioWorkletProcessor { readonly attribute MessagePort port; };
diff --git a/third_party/WebKit/Source/modules/webaudio/AudioWorkletThread.h b/third_party/WebKit/Source/modules/webaudio/AudioWorkletThread.h index 471a30b..8f2a5d97 100644 --- a/third_party/WebKit/Source/modules/webaudio/AudioWorkletThread.h +++ b/third_party/WebKit/Source/modules/webaudio/AudioWorkletThread.h
@@ -52,8 +52,8 @@ bool IsOwningBackingThread() const override { return false; } - scheduler::ThreadType GetThreadType() const override { - return scheduler::ThreadType::kAudioWorkletThread; + WebThreadType GetThreadType() const override { + return WebThreadType::kAudioWorkletThread; } // This raw pointer gets assigned in EnsureSharedBackingThread() and manually
diff --git a/third_party/WebKit/Source/modules/webaudio/AudioWorkletThreadTest.cpp b/third_party/WebKit/Source/modules/webaudio/AudioWorkletThreadTest.cpp index db871d2..000c89c 100644 --- a/third_party/WebKit/Source/modules/webaudio/AudioWorkletThreadTest.cpp +++ b/third_party/WebKit/Source/modules/webaudio/AudioWorkletThreadTest.cpp
@@ -54,7 +54,8 @@ document->Url(), document->UserAgent(), nullptr /* content_security_policy_parsed_headers */, document->GetReferrerPolicy(), document->GetSecurityOrigin(), - nullptr /* worker_clients */, document->AddressSpace(), + document->IsSecureContext(), nullptr /* worker_clients */, + document->AddressSpace(), OriginTrialContext::GetTokens(document).get(), nullptr /* worker_settings */, kV8CacheOptionsDefault), WTF::nullopt, WorkerInspectorProxy::PauseOnWorkerStart::kDontPause,
diff --git a/third_party/WebKit/Source/modules/webaudio/DeferredTaskHandler.cpp b/third_party/WebKit/Source/modules/webaudio/DeferredTaskHandler.cpp index 9a67fb4..716d8638 100644 --- a/third_party/WebKit/Source/modules/webaudio/DeferredTaskHandler.cpp +++ b/third_party/WebKit/Source/modules/webaudio/DeferredTaskHandler.cpp
@@ -28,6 +28,7 @@ #include "modules/webaudio/AudioNodeOutput.h" #include "modules/webaudio/OfflineAudioContext.h" #include "platform/CrossThreadFunctional.h" +#include "platform/WebTaskRunner.h" #include "public/platform/Platform.h" namespace blink {
diff --git a/third_party/WebKit/Source/modules/webaudio/MediaElementAudioSourceNode.h b/third_party/WebKit/Source/modules/webaudio/MediaElementAudioSourceNode.h index a1ffa9a0..1cf8a8c 100644 --- a/third_party/WebKit/Source/modules/webaudio/MediaElementAudioSourceNode.h +++ b/third_party/WebKit/Source/modules/webaudio/MediaElementAudioSourceNode.h
@@ -28,8 +28,8 @@ #include <memory> #include "base/memory/scoped_refptr.h" +#include "base/single_thread_task_runner.h" #include "modules/webaudio/AudioNode.h" -#include "platform/WebTaskRunner.h" #include "platform/audio/AudioSourceProviderClient.h" #include "platform/audio/MultiChannelResampler.h" #include "platform/wtf/ThreadingPrimitives.h" @@ -109,7 +109,7 @@ // onCurrentSrcChanged(). Protected by |m_processLock|. String current_src_string_; - scoped_refptr<WebTaskRunner> task_runner_; + scoped_refptr<base::SingleThreadTaskRunner> task_runner_; }; class MediaElementAudioSourceNode final : public AudioNode,
diff --git a/third_party/WebKit/Source/modules/webaudio/OfflineAudioDestinationNode.cpp b/third_party/WebKit/Source/modules/webaudio/OfflineAudioDestinationNode.cpp index d833e8a..cd02c94 100644 --- a/third_party/WebKit/Source/modules/webaudio/OfflineAudioDestinationNode.cpp +++ b/third_party/WebKit/Source/modules/webaudio/OfflineAudioDestinationNode.cpp
@@ -150,7 +150,7 @@ worklet_backing_thread_ = Context()->audioWorklet()->GetBackingThread(); } else { render_thread_ = Platform::Current()->CreateThread( - WebThreadCreationParams("offline audio renderer")); + WebThreadCreationParams(WebThreadType::kOfflineAudioRenderThread)); } render_target_ = render_target;
diff --git a/third_party/WebKit/Source/modules/webaudio/OfflineAudioDestinationNode.h b/third_party/WebKit/Source/modules/webaudio/OfflineAudioDestinationNode.h index 54e8b4d..9c98465 100644 --- a/third_party/WebKit/Source/modules/webaudio/OfflineAudioDestinationNode.h +++ b/third_party/WebKit/Source/modules/webaudio/OfflineAudioDestinationNode.h
@@ -154,7 +154,7 @@ unsigned number_of_channels_; float sample_rate_; - scoped_refptr<WebTaskRunner> task_runner_; + scoped_refptr<base::SingleThreadTaskRunner> task_runner_; }; class OfflineAudioDestinationNode final : public AudioDestinationNode {
diff --git a/third_party/WebKit/Source/modules/webaudio/ScriptProcessorNode.h b/third_party/WebKit/Source/modules/webaudio/ScriptProcessorNode.h index fec4613..099bfc94 100644 --- a/third_party/WebKit/Source/modules/webaudio/ScriptProcessorNode.h +++ b/third_party/WebKit/Source/modules/webaudio/ScriptProcessorNode.h
@@ -103,7 +103,7 @@ // Synchronize process() with fireProcessEvent(). mutable Mutex process_event_lock_; - scoped_refptr<WebTaskRunner> task_runner_; + scoped_refptr<base::SingleThreadTaskRunner> task_runner_; FRIEND_TEST_ALL_PREFIXES(ScriptProcessorNodeTest, BufferLifetime); };
diff --git a/third_party/WebKit/Source/modules/webdatabase/Database.cpp b/third_party/WebKit/Source/modules/webdatabase/Database.cpp index f0f115a..4538a54 100644 --- a/third_party/WebKit/Source/modules/webdatabase/Database.cpp +++ b/third_party/WebKit/Source/modules/webdatabase/Database.cpp
@@ -52,6 +52,7 @@ #include "modules/webdatabase/sqlite/SQLiteTransaction.h" #include "platform/CrossThreadFunctional.h" #include "platform/WaitableEvent.h" +#include "platform/WebTaskRunner.h" #include "platform/heap/SafePoint.h" #include "platform/wtf/Atomics.h" #include "platform/wtf/Time.h" @@ -990,7 +991,7 @@ return static_cast<bool>(AcquireLoad(&opened_)); } -WebTaskRunner* Database::GetDatabaseTaskRunner() const { +base::SingleThreadTaskRunner* Database::GetDatabaseTaskRunner() const { return database_task_runner_.get(); }
diff --git a/third_party/WebKit/Source/modules/webdatabase/Database.h b/third_party/WebKit/Source/modules/webdatabase/Database.h index fb4726df..40ad8db 100644 --- a/third_party/WebKit/Source/modules/webdatabase/Database.h +++ b/third_party/WebKit/Source/modules/webdatabase/Database.h
@@ -26,11 +26,11 @@ #ifndef Database_h #define Database_h +#include "base/single_thread_task_runner.h" #include "modules/webdatabase/DatabaseBasicTypes.h" #include "modules/webdatabase/DatabaseError.h" #include "modules/webdatabase/SQLTransactionBackend.h" #include "modules/webdatabase/sqlite/SQLiteDatabase.h" -#include "platform/WebTaskRunner.h" #include "platform/bindings/ScriptWrappable.h" #include "platform/bindings/TraceWrapperMember.h" #include "platform/weborigin/SecurityOrigin.h" @@ -118,7 +118,7 @@ return database_context_.Get(); } ExecutionContext* GetExecutionContext() const; - WebTaskRunner* GetDatabaseTaskRunner() const; + base::SingleThreadTaskRunner* GetDatabaseTaskRunner() const; private: class DatabaseOpenTask; @@ -182,10 +182,10 @@ scoped_refptr<const SecurityOrigin> database_thread_security_origin_; Member<DatabaseContext> database_context_; // Associated with m_executionContext. - // TaskRunnerHelper::get is not thread-safe, so we save WebTaskRunner for - // TaskType::DatabaseAccess for later use as the constructor runs in the main - // thread. - scoped_refptr<WebTaskRunner> database_task_runner_; + // TaskRunnerHelper::get is not thread-safe, so we save SingleThreadTaskRunner + // for TaskType::DatabaseAccess for later use as the constructor runs in the + // main thread. + scoped_refptr<base::SingleThreadTaskRunner> database_task_runner_; String name_; String expected_version_;
diff --git a/third_party/WebKit/Source/modules/webdatabase/DatabaseThread.cpp b/third_party/WebKit/Source/modules/webdatabase/DatabaseThread.cpp index fbf4df14..ad5fe2c 100644 --- a/third_party/WebKit/Source/modules/webdatabase/DatabaseThread.cpp +++ b/third_party/WebKit/Source/modules/webdatabase/DatabaseThread.cpp
@@ -60,7 +60,7 @@ if (thread_) return; thread_ = WebThreadSupportingGC::Create( - WebThreadCreationParams("WebCore: Database")); + WebThreadCreationParams(WebThreadType::kDatabaseThread)); thread_->PostTask(FROM_HERE, CrossThreadBind(&DatabaseThread::SetupDatabaseThread, WrapCrossThreadPersistent(this)));
diff --git a/third_party/WebKit/Source/modules/webdatabase/SQLTransactionClient.cpp b/third_party/WebKit/Source/modules/webdatabase/SQLTransactionClient.cpp index 3cf66840..157c291b 100644 --- a/third_party/WebKit/Source/modules/webdatabase/SQLTransactionClient.cpp +++ b/third_party/WebKit/Source/modules/webdatabase/SQLTransactionClient.cpp
@@ -35,7 +35,6 @@ #include "modules/webdatabase/Database.h" #include "modules/webdatabase/DatabaseContext.h" #include "platform/CrossThreadFunctional.h" -#include "platform/WebTaskRunner.h" #include "platform/weborigin/SecurityOrigin.h" #include "platform/wtf/Functional.h" #include "public/platform/Platform.h"
diff --git a/third_party/WebKit/Source/modules/webgl/WebGL2RenderingContextBase.cpp b/third_party/WebKit/Source/modules/webgl/WebGL2RenderingContextBase.cpp index 8879e51..964615b 100644 --- a/third_party/WebKit/Source/modules/webgl/WebGL2RenderingContextBase.cpp +++ b/third_party/WebKit/Source/modules/webgl/WebGL2RenderingContextBase.cpp
@@ -873,6 +873,7 @@ "for integer formats, samples > 0"); return; } + FALLTHROUGH; case GL_R8: case GL_RG8: case GL_RGB8: @@ -5521,6 +5522,7 @@ case GL_FRAMEBUFFER_ATTACHMENT_TEXTURE_LEVEL: if (!attachment_object->IsTexture()) break; + FALLTHROUGH; case GL_FRAMEBUFFER_ATTACHMENT_RED_SIZE: case GL_FRAMEBUFFER_ATTACHMENT_GREEN_SIZE: case GL_FRAMEBUFFER_ATTACHMENT_BLUE_SIZE: @@ -5539,6 +5541,7 @@ "COMPONENT_TYPE can't be queried for DEPTH_STENCIL_ATTACHMENT"); return ScriptValue::CreateNull(script_state); } + FALLTHROUGH; case GL_FRAMEBUFFER_ATTACHMENT_COLOR_ENCODING: { GLint value = 0; ContextGL()->GetFramebufferAttachmentParameteriv(target, attachment,
diff --git a/third_party/WebKit/Source/modules/webgl/WebGLQuery.h b/third_party/WebKit/Source/modules/webgl/WebGLQuery.h index 784eee2..c3c89c5 100644 --- a/third_party/WebKit/Source/modules/webgl/WebGLQuery.h +++ b/third_party/WebKit/Source/modules/webgl/WebGLQuery.h
@@ -5,6 +5,7 @@ #ifndef WebGLQuery_h #define WebGLQuery_h +#include "base/single_thread_task_runner.h" #include "modules/webgl/WebGLSharedPlatform3DObject.h" #include "platform/WebTaskRunner.h" @@ -53,7 +54,7 @@ bool query_result_available_; GLuint query_result_; - scoped_refptr<WebTaskRunner> task_runner_; + scoped_refptr<base::SingleThreadTaskRunner> task_runner_; TaskHandle task_handle_; };
diff --git a/third_party/WebKit/Source/modules/webgl/WebGLRenderingContextBase.cpp b/third_party/WebKit/Source/modules/webgl/WebGLRenderingContextBase.cpp index 6188c17..51ddfa1 100644 --- a/third_party/WebKit/Source/modules/webgl/WebGLRenderingContextBase.cpp +++ b/third_party/WebKit/Source/modules/webgl/WebGLRenderingContextBase.cpp
@@ -613,7 +613,7 @@ creation_info.gl_info = gl_info; creation_info.url = url.Copy(); creation_info.using_gpu_compositing = using_gpu_compositing; - scoped_refptr<WebTaskRunner> task_runner = + scoped_refptr<base::SingleThreadTaskRunner> task_runner = Platform::Current()->MainThread()->GetWebTaskRunner(); PostCrossThreadTask(*task_runner, FROM_HERE, CrossThreadBind(&CreateContextProviderOnMainThread, @@ -974,7 +974,7 @@ WebGLRenderingContextBase::WebGLRenderingContextBase( CanvasRenderingContextHost* host, - scoped_refptr<WebTaskRunner> task_runner, + scoped_refptr<base::SingleThreadTaskRunner> task_runner, std::unique_ptr<WebGraphicsContext3DProvider> context_provider, bool using_gpu_compositing, const CanvasContextCreationAttributes& requested_attributes, @@ -3244,6 +3244,7 @@ "invalid parameter name"); return ScriptValue::CreateNull(script_state); } + FALLTHROUGH; case GL_ATTACHED_SHADERS: case GL_ACTIVE_ATTRIBUTES: case GL_ACTIVE_UNIFORMS: @@ -3254,6 +3255,7 @@ ContextGL()->GetProgramiv(ObjectOrZero(program), pname, &value); return WebGLAny(script_state, static_cast<unsigned>(value)); } + FALLTHROUGH; default: SynthesizeGLError(GL_INVALID_ENUM, "getProgramParameter", "invalid parameter name"); @@ -3293,6 +3295,7 @@ "invalid parameter name"); return ScriptValue::CreateNull(script_state); } + FALLTHROUGH; case GL_RENDERBUFFER_WIDTH: case GL_RENDERBUFFER_HEIGHT: case GL_RENDERBUFFER_RED_SIZE: @@ -3783,7 +3786,7 @@ ContextGL()->GetVertexAttribiv(index, pname, &value); return WebGLAny(script_state, static_cast<bool>(value)); } - // fall through to default error case + FALLTHROUGH; default: SynthesizeGLError(GL_INVALID_ENUM, "getVertexAttrib", "invalid parameter name"); @@ -5541,12 +5544,12 @@ case GL_TEXTURE_MAG_FILTER: break; case GL_TEXTURE_WRAP_R: - // fall through to WRAP_S and WRAP_T for WebGL 2 or higher if (!IsWebGL2OrHigher()) { SynthesizeGLError(GL_INVALID_ENUM, "texParameter", "invalid parameter name"); return; } + FALLTHROUGH; case GL_TEXTURE_WRAP_S: case GL_TEXTURE_WRAP_T: if ((is_float && paramf != GL_CLAMP_TO_EDGE && @@ -6924,6 +6927,7 @@ } break; } + FALLTHROUGH; case GL_TEXTURE_2D_ARRAY: if (IsWebGL2OrHigher()) { if (width > (max_texture_size_ >> level) || @@ -6935,6 +6939,7 @@ } break; } + FALLTHROUGH; default: SynthesizeGLError(GL_INVALID_ENUM, function_name, "invalid target"); return false;
diff --git a/third_party/WebKit/Source/modules/webgl/WebGLRenderingContextBase.h b/third_party/WebKit/Source/modules/webgl/WebGLRenderingContextBase.h index 924d02c51..2580e63 100644 --- a/third_party/WebKit/Source/modules/webgl/WebGLRenderingContextBase.h +++ b/third_party/WebKit/Source/modules/webgl/WebGLRenderingContextBase.h
@@ -710,7 +710,7 @@ TaskRunnerTimer<WebGLRenderingContextBase> dispatch_context_lost_event_timer_; bool restore_allowed_; TaskRunnerTimer<WebGLRenderingContextBase> restore_timer_; - scoped_refptr<WebTaskRunner> task_runner_; + scoped_refptr<base::SingleThreadTaskRunner> task_runner_; bool marked_canvas_dirty_; bool animation_frame_in_progress_; @@ -1665,7 +1665,7 @@ private: WebGLRenderingContextBase(CanvasRenderingContextHost*, - scoped_refptr<WebTaskRunner>, + scoped_refptr<base::SingleThreadTaskRunner>, std::unique_ptr<WebGraphicsContext3DProvider>, bool using_gpu_compositing, const CanvasContextCreationAttributes&,
diff --git a/third_party/WebKit/Source/modules/webgl/WebGLTimerQueryEXT.h b/third_party/WebKit/Source/modules/webgl/WebGLTimerQueryEXT.h index 1a52496..d20c7aa 100644 --- a/third_party/WebKit/Source/modules/webgl/WebGLTimerQueryEXT.h +++ b/third_party/WebKit/Source/modules/webgl/WebGLTimerQueryEXT.h
@@ -5,6 +5,7 @@ #ifndef WebGLTimerQueryEXT_h #define WebGLTimerQueryEXT_h +#include "base/single_thread_task_runner.h" #include "modules/webgl/WebGLContextObject.h" #include "platform/WebTaskRunner.h" @@ -52,7 +53,7 @@ bool query_result_available_; GLuint64 query_result_; - scoped_refptr<WebTaskRunner> task_runner_; + scoped_refptr<base::SingleThreadTaskRunner> task_runner_; TaskHandle task_handle_; };
diff --git a/third_party/WebKit/Source/modules/websockets/DocumentWebSocketChannel.cpp b/third_party/WebKit/Source/modules/websockets/DocumentWebSocketChannel.cpp index 5d96a5c..813de3d 100644 --- a/third_party/WebKit/Source/modules/websockets/DocumentWebSocketChannel.cpp +++ b/third_party/WebKit/Source/modules/websockets/DocumentWebSocketChannel.cpp
@@ -55,7 +55,6 @@ #include "modules/websockets/WebSocketHandleImpl.h" #include "mojo/public/cpp/bindings/interface_request.h" #include "platform/WebFrameScheduler.h" -#include "platform/WebTaskRunner.h" #include "platform/loader/fetch/UniqueIdentifier.h" #include "platform/network/NetworkLog.h" #include "platform/network/WebSocketHandshakeRequest.h"
diff --git a/third_party/WebKit/Source/modules/websockets/DocumentWebSocketChannelTest.cpp b/third_party/WebKit/Source/modules/websockets/DocumentWebSocketChannelTest.cpp index cd5b64c..840fdc1 100644 --- a/third_party/WebKit/Source/modules/websockets/DocumentWebSocketChannelTest.cpp +++ b/third_party/WebKit/Source/modules/websockets/DocumentWebSocketChannelTest.cpp
@@ -94,7 +94,7 @@ const KURL&, const String&, WebSocketHandleClient*, - WebTaskRunner*)); + base::SingleThreadTaskRunner*)); MOCK_METHOD4(Send, void(bool, WebSocketHandle::MessageType, const char*, size_t)); MOCK_METHOD1(FlowControl, void(int64_t));
diff --git a/third_party/WebKit/Source/modules/websockets/WebSocketHandle.h b/third_party/WebKit/Source/modules/websockets/WebSocketHandle.h index 9cd6e799..7451b396 100644 --- a/third_party/WebKit/Source/modules/websockets/WebSocketHandle.h +++ b/third_party/WebKit/Source/modules/websockets/WebSocketHandle.h
@@ -32,7 +32,7 @@ #define WebSocketHandle_h #include <stdint.h> -#include "platform/WebTaskRunner.h" +#include "base/single_thread_task_runner.h" #include "platform/wtf/Forward.h" #include "platform/wtf/Vector.h" #include "public/platform/modules/websockets/websocket.mojom-blink.h" @@ -68,7 +68,7 @@ const KURL& site_for_cookies, const String& user_agent_override, WebSocketHandleClient*, - WebTaskRunner*) = 0; + base::SingleThreadTaskRunner*) = 0; virtual void Send(bool fin, MessageType, const char* data, size_t) = 0; virtual void FlowControl(int64_t quota) = 0; virtual void Close(unsigned short code, const String& reason) = 0;
diff --git a/third_party/WebKit/Source/modules/websockets/WebSocketHandleImpl.cpp b/third_party/WebKit/Source/modules/websockets/WebSocketHandleImpl.cpp index 646cb97..34c24b7 100644 --- a/third_party/WebKit/Source/modules/websockets/WebSocketHandleImpl.cpp +++ b/third_party/WebKit/Source/modules/websockets/WebSocketHandleImpl.cpp
@@ -4,8 +4,8 @@ #include "modules/websockets/WebSocketHandleImpl.h" +#include "base/single_thread_task_runner.h" #include "modules/websockets/WebSocketHandleClient.h" -#include "platform/WebTaskRunner.h" #include "platform/network/NetworkLog.h" #include "platform/network/WebSocketHandshakeRequest.h" #include "platform/network/WebSocketHandshakeResponse.h" @@ -50,7 +50,7 @@ const KURL& site_for_cookies, const String& user_agent_override, WebSocketHandleClient* client, - WebTaskRunner* task_runner) { + base::SingleThreadTaskRunner* task_runner) { DCHECK(websocket_); NETWORK_DVLOG(1) << this << " connect(" << url.GetString() << ", "
diff --git a/third_party/WebKit/Source/modules/websockets/WebSocketHandleImpl.h b/third_party/WebKit/Source/modules/websockets/WebSocketHandleImpl.h index 0f1175d..41d966b 100644 --- a/third_party/WebKit/Source/modules/websockets/WebSocketHandleImpl.h +++ b/third_party/WebKit/Source/modules/websockets/WebSocketHandleImpl.h
@@ -50,7 +50,7 @@ const KURL& site_for_cookies, const String& user_agent_override, WebSocketHandleClient*, - WebTaskRunner*) override; + base::SingleThreadTaskRunner*) override; void Send(bool fin, MessageType, const char* data, size_t) override; void FlowControl(int64_t quota) override; void Close(unsigned short code, const String& reason) override;
diff --git a/third_party/WebKit/Source/modules/websockets/WorkerWebSocketChannel.cpp b/third_party/WebKit/Source/modules/websockets/WorkerWebSocketChannel.cpp index 110de93..ad09763 100644 --- a/third_party/WebKit/Source/modules/websockets/WorkerWebSocketChannel.cpp +++ b/third_party/WebKit/Source/modules/websockets/WorkerWebSocketChannel.cpp
@@ -40,6 +40,7 @@ #include "core/workers/WorkerThreadLifecycleContext.h" #include "platform/CrossThreadFunctional.h" #include "platform/WaitableEvent.h" +#include "platform/WebTaskRunner.h" #include "platform/heap/SafePoint.h" #include "platform/wtf/Assertions.h" #include "platform/wtf/Functional.h" @@ -160,7 +161,7 @@ MainChannelClient::MainChannelClient( Bridge* bridge, - scoped_refptr<WebTaskRunner> worker_networking_task_runner, + scoped_refptr<base::SingleThreadTaskRunner> worker_networking_task_runner, WorkerThreadLifecycleContext* worker_thread_lifecycle_context) : WorkerThreadLifecycleObserver(worker_thread_lifecycle_context), bridge_(bridge), @@ -377,7 +378,7 @@ void Bridge::ConnectOnMainThread( std::unique_ptr<SourceLocation> location, ThreadableLoadingContext* loading_context, - scoped_refptr<WebTaskRunner> worker_networking_task_runner, + scoped_refptr<base::SingleThreadTaskRunner> worker_networking_task_runner, WorkerThreadLifecycleContext* worker_thread_lifecycle_context, const KURL& url, const String& protocol, @@ -403,7 +404,7 @@ // Wait for completion of the task on the main thread because the mixed // content check must synchronously be conducted. WebSocketChannelSyncHelper sync_helper; - scoped_refptr<WebTaskRunner> worker_networking_task_runner = + scoped_refptr<base::SingleThreadTaskRunner> worker_networking_task_runner = worker_global_scope_->GetTaskRunner(TaskType::kNetworking); WorkerThread* worker_thread = worker_global_scope_->GetThread();
diff --git a/third_party/WebKit/Source/modules/websockets/WorkerWebSocketChannel.h b/third_party/WebKit/Source/modules/websockets/WorkerWebSocketChannel.h index 97b2a9a1..c38f99b 100644 --- a/third_party/WebKit/Source/modules/websockets/WorkerWebSocketChannel.h +++ b/third_party/WebKit/Source/modules/websockets/WorkerWebSocketChannel.h
@@ -106,7 +106,7 @@ public: MainChannelClient(Bridge*, - scoped_refptr<WebTaskRunner>, + scoped_refptr<base::SingleThreadTaskRunner>, WorkerThreadLifecycleContext*); ~MainChannelClient() override; @@ -148,7 +148,7 @@ void ReleaseMainChannel(); CrossThreadWeakPersistent<Bridge> bridge_; - scoped_refptr<WebTaskRunner> worker_networking_task_runner_; + scoped_refptr<base::SingleThreadTaskRunner> worker_networking_task_runner_; Member<DocumentWebSocketChannel> main_channel_; }; @@ -178,7 +178,7 @@ void ConnectOnMainThread(std::unique_ptr<SourceLocation>, ThreadableLoadingContext*, - scoped_refptr<WebTaskRunner>, + scoped_refptr<base::SingleThreadTaskRunner>, WorkerThreadLifecycleContext*, const KURL&, const String& protocol,
diff --git a/third_party/WebKit/Source/modules/xr/XRFrameProvider.cpp b/third_party/WebKit/Source/modules/xr/XRFrameProvider.cpp index 116b5e01..b8b4901 100644 --- a/third_party/WebKit/Source/modules/xr/XRFrameProvider.cpp +++ b/third_party/WebKit/Source/modules/xr/XRFrameProvider.cpp
@@ -16,7 +16,6 @@ #include "modules/xr/XRSession.h" #include "modules/xr/XRViewport.h" #include "modules/xr/XRWebGLLayer.h" -#include "platform/WebTaskRunner.h" #include "platform/graphics/gpu/XRFrameTransport.h" #include "platform/instrumentation/tracing/TraceEvent.h" #include "platform/transforms/TransformationMatrix.h"
diff --git a/third_party/WebKit/Source/platform/BUILD.gn b/third_party/WebKit/Source/platform/BUILD.gn index b7485f2..5f04fd3 100644 --- a/third_party/WebKit/Source/platform/BUILD.gn +++ b/third_party/WebKit/Source/platform/BUILD.gn
@@ -408,6 +408,7 @@ "WebThread.cpp", "WebThreadSupportingGC.cpp", "WebThreadSupportingGC.h", + "WebThreadType.cpp", "WebTouchEvent.cpp", "WindowsKeyboardCodes.h", "animation/AnimationTranslationUtil.cpp", @@ -1218,6 +1219,8 @@ "graphics/paint/PropertyTreeState.h", "graphics/paint/RasterInvalidationTracking.cpp", "graphics/paint/RasterInvalidationTracking.h", + "graphics/paint/RefCountedPropertyTreeState.cpp", + "graphics/paint/RefCountedPropertyTreeState.h", "graphics/paint/ScopedDisplayItemFragment.h", "graphics/paint/ScopedPaintChunkProperties.h", "graphics/paint/ScrollDisplayItem.cpp", @@ -1309,6 +1312,8 @@ "mhtml/MHTMLArchive.h", "mhtml/MHTMLParser.cpp", "mhtml/MHTMLParser.h", + "mojo/BigStringMojomTraits.cpp", + "mojo/BigStringMojomTraits.h", "mojo/BluetoothStructTraits.cpp", "mojo/BluetoothStructTraits.h", "mojo/CommonCustomTypesStructTraits.cpp", @@ -1906,6 +1911,7 @@ "json/JSONValuesTest.cpp", "mac/GraphicsContextCanvasTest.mm", "mac/VersionUtilMacTest.mm", + "mojo/BigStringMojomTraitsTest.cpp", "mojo/CommonCustomTypesStructTraitsTest.cpp", "mojo/GeometryStructTraitsTest.cpp", "mojo/InterfaceInvalidatorTest.cpp",
diff --git a/third_party/WebKit/Source/platform/DEPS b/third_party/WebKit/Source/platform/DEPS index 3acf468..cbb3bd8 100644 --- a/third_party/WebKit/Source/platform/DEPS +++ b/third_party/WebKit/Source/platform/DEPS
@@ -10,6 +10,7 @@ "+base/guid.h", "+base/json", "+base/location.h", + "+base/logging.h", "+base/memory", "+base/message_loop/message_loop.h", "+base/metrics/histogram.h",
diff --git a/third_party/WebKit/Source/platform/OWNERS b/third_party/WebKit/Source/platform/OWNERS index f752305c..513ee139 100644 --- a/third_party/WebKit/Source/platform/OWNERS +++ b/third_party/WebKit/Source/platform/OWNERS
@@ -1,3 +1,4 @@ +dgozman@chromium.org drott@chromium.org eae@chromium.org fmalita@chromium.org
diff --git a/third_party/WebKit/Source/platform/WebThread.cpp b/third_party/WebKit/Source/platform/WebThread.cpp index ae73508..d3d188b 100644 --- a/third_party/WebKit/Source/platform/WebThread.cpp +++ b/third_party/WebKit/Source/platform/WebThread.cpp
@@ -16,8 +16,14 @@ namespace blink { -WebThreadCreationParams::WebThreadCreationParams(const char* name) - : name(name) {} +WebThreadCreationParams::WebThreadCreationParams(WebThreadType thread_type) + : thread_type(thread_type), name(GetNameForThreadType(thread_type)) {} + +WebThreadCreationParams& WebThreadCreationParams::SetThreadName( + const char* thread_name) { + name = thread_name; + return *this; +} #if defined(OS_WIN) static_assert(sizeof(blink::PlatformThreadId) >= sizeof(DWORD),
diff --git a/third_party/WebKit/Source/platform/WebThreadSupportingGC.cpp b/third_party/WebKit/Source/platform/WebThreadSupportingGC.cpp index f5ad0f1..f69cd1d 100644 --- a/third_party/WebKit/Source/platform/WebThreadSupportingGC.cpp +++ b/third_party/WebKit/Source/platform/WebThreadSupportingGC.cpp
@@ -15,21 +15,20 @@ std::unique_ptr<WebThreadSupportingGC> WebThreadSupportingGC::Create( const WebThreadCreationParams& params) { - return WTF::WrapUnique(new WebThreadSupportingGC(params, nullptr)); + return WTF::WrapUnique(new WebThreadSupportingGC(¶ms, nullptr)); } std::unique_ptr<WebThreadSupportingGC> WebThreadSupportingGC::CreateForThread( WebThread* thread) { - return WTF::WrapUnique( - new WebThreadSupportingGC(WebThreadCreationParams(nullptr), thread)); + return WTF::WrapUnique(new WebThreadSupportingGC(nullptr, thread)); } WebThreadSupportingGC::WebThreadSupportingGC( - const WebThreadCreationParams& params, + const WebThreadCreationParams* params, WebThread* thread) : thread_(thread) { DCHECK(IsMainThread()); - DCHECK(!params.name || !thread); + DCHECK(!params || !thread); #if DCHECK_IS_ON() // We call this regardless of whether an existing thread is given or not, // as it means that blink is going to run with more than one thread. @@ -37,7 +36,10 @@ #endif if (!thread_) { // If |thread| is not given, create a new one and own it. - owning_thread_ = Platform::Current()->CreateThread(params); + // TODO(scheduler-dev): AnimationWorklet can pass nullptr as WebThread* + // reference when a test doesn't have a compositor thread. + owning_thread_ = Platform::Current()->CreateThread( + params ? *params : WebThreadCreationParams(WebThreadType::kTestThread)); thread_ = owning_thread_.get(); } MemoryCoordinator::RegisterThread(thread_);
diff --git a/third_party/WebKit/Source/platform/WebThreadSupportingGC.h b/third_party/WebKit/Source/platform/WebThreadSupportingGC.h index a4af7ce..dadb634 100644 --- a/third_party/WebKit/Source/platform/WebThreadSupportingGC.h +++ b/third_party/WebKit/Source/platform/WebThreadSupportingGC.h
@@ -77,7 +77,7 @@ } private: - WebThreadSupportingGC(const WebThreadCreationParams&, WebThread*); + WebThreadSupportingGC(const WebThreadCreationParams*, WebThread*); std::unique_ptr<GCTaskRunner> gc_task_runner_;
diff --git a/third_party/WebKit/Source/platform/WebThreadType.cpp b/third_party/WebKit/Source/platform/WebThreadType.cpp new file mode 100644 index 0000000..183c326 --- /dev/null +++ b/third_party/WebKit/Source/platform/WebThreadType.cpp
@@ -0,0 +1,52 @@ +// 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 "public/platform/WebThreadType.h" + +#include "base/logging.h" + +namespace blink { + +const char* GetNameForThreadType(WebThreadType thread_type) { + switch (thread_type) { + case WebThreadType::kMainThread: + return "Main thread"; + case WebThreadType::kUnspecifiedWorkerThread: + return "unspecified worker thread"; + case WebThreadType::kCompositorThread: + return "Compositor thread"; + case WebThreadType::kDedicatedWorkerThread: + return "DedicatedWorker thread"; + case WebThreadType::kSharedWorkerThread: + return "SharedWorker thread"; + case WebThreadType::kAnimationWorkletThread: + return "AnimationWorklet thread"; + case WebThreadType::kServiceWorkerThread: + return "ServiceWorker thread"; + case WebThreadType::kAudioWorkletThread: + return "AudioWorklet thread"; + case WebThreadType::kFileThread: + return "File thread"; + case WebThreadType::kDatabaseThread: + return "Database thread"; + case WebThreadType::kWebAudioThread: + return "WebAudio thread"; + case WebThreadType::kScriptStreamerThread: + return "ScriptStreamer thread"; + case WebThreadType::kOfflineAudioRenderThread: + return "OfflineAudioRender thread"; + case WebThreadType::kReverbConvolutionBackgroundThread: + return "Reverb convolution background thread"; + case WebThreadType::kHRTFDatabaseLoaderThread: + return "HRTF database loader thread"; + case WebThreadType::kTestThread: + return "test thread"; + case WebThreadType::kCount: + NOTREACHED(); + return nullptr; + } + return nullptr; +} + +} // namespace blink
diff --git a/third_party/WebKit/Source/platform/animation/CompositorAnimationPlayer.cpp b/third_party/WebKit/Source/platform/animation/CompositorAnimationPlayer.cpp index 280cdb54..8e445935 100644 --- a/third_party/WebKit/Source/platform/animation/CompositorAnimationPlayer.cpp +++ b/third_party/WebKit/Source/platform/animation/CompositorAnimationPlayer.cpp
@@ -14,7 +14,8 @@ std::unique_ptr<CompositorAnimationPlayer> CompositorAnimationPlayer::Create() { return std::make_unique<CompositorAnimationPlayer>( - cc::AnimationPlayer::Create(cc::AnimationIdProvider::NextPlayerId())); + cc::SingleTickerAnimationPlayer::Create( + cc::AnimationIdProvider::NextPlayerId())); } std::unique_ptr<CompositorAnimationPlayer> @@ -29,7 +30,7 @@ } CompositorAnimationPlayer::CompositorAnimationPlayer( - scoped_refptr<cc::AnimationPlayer> player) + scoped_refptr<cc::SingleTickerAnimationPlayer> player) : animation_player_(player), delegate_() {} CompositorAnimationPlayer::~CompositorAnimationPlayer() { @@ -40,7 +41,8 @@ animation_player_->animation_timeline()->DetachPlayer(animation_player_); } -cc::AnimationPlayer* CompositorAnimationPlayer::CcAnimationPlayer() const { +cc::SingleTickerAnimationPlayer* CompositorAnimationPlayer::CcAnimationPlayer() + const { return animation_player_.get(); }
diff --git a/third_party/WebKit/Source/platform/animation/CompositorAnimationPlayer.h b/third_party/WebKit/Source/platform/animation/CompositorAnimationPlayer.h index e18ae1a2..47ceda8 100644 --- a/third_party/WebKit/Source/platform/animation/CompositorAnimationPlayer.h +++ b/third_party/WebKit/Source/platform/animation/CompositorAnimationPlayer.h
@@ -8,8 +8,8 @@ #include <memory> #include "base/memory/scoped_refptr.h" #include "cc/animation/animation_delegate.h" -#include "cc/animation/animation_player.h" #include "cc/animation/scroll_timeline.h" +#include "cc/animation/single_ticker_animation_player.h" #include "cc/animation/worklet_animation_player.h" #include "platform/PlatformExport.h" #include "platform/graphics/CompositorElementId.h" @@ -37,10 +37,11 @@ const String& name, std::unique_ptr<CompositorScrollTimeline>); - explicit CompositorAnimationPlayer(scoped_refptr<cc::AnimationPlayer>); + explicit CompositorAnimationPlayer( + scoped_refptr<cc::SingleTickerAnimationPlayer>); ~CompositorAnimationPlayer(); - cc::AnimationPlayer* CcAnimationPlayer() const; + cc::SingleTickerAnimationPlayer* CcAnimationPlayer() const; // An animation delegate is notified when animations are started and stopped. // The CompositorAnimationPlayer does not take ownership of the delegate, and @@ -73,7 +74,7 @@ base::TimeTicks animation_start_time, std::unique_ptr<cc::AnimationCurve>) override; - scoped_refptr<cc::AnimationPlayer> animation_player_; + scoped_refptr<cc::SingleTickerAnimationPlayer> animation_player_; CompositorAnimationDelegate* delegate_; };
diff --git a/third_party/WebKit/Source/platform/animation/CompositorAnimationPlayerTest.cpp b/third_party/WebKit/Source/platform/animation/CompositorAnimationPlayerTest.cpp index 6ad8e7c..a85658b0 100644 --- a/third_party/WebKit/Source/platform/animation/CompositorAnimationPlayerTest.cpp +++ b/third_party/WebKit/Source/platform/animation/CompositorAnimationPlayerTest.cpp
@@ -60,7 +60,7 @@ std::unique_ptr<CompositorAnimationPlayer> player = CompositorAnimationPlayer::Create(); - cc::AnimationPlayer* cc_player = player->CcAnimationPlayer(); + cc::SingleTickerAnimationPlayer* cc_player = player->CcAnimationPlayer(); std::unique_ptr<CompositorAnimationCurve> curve = CompositorFloatAnimationCurve::Create(); @@ -90,7 +90,8 @@ std::unique_ptr<CompositorAnimationPlayer> player = CompositorAnimationPlayer::Create(); - scoped_refptr<cc::AnimationPlayer> cc_player = player->CcAnimationPlayer(); + scoped_refptr<cc::SingleTickerAnimationPlayer> cc_player = + player->CcAnimationPlayer(); std::unique_ptr<CompositorAnimationCurve> curve = CompositorFloatAnimationCurve::Create(); @@ -124,7 +125,7 @@ scoped_refptr<cc::AnimationTimeline> cc_timeline = timeline->GetAnimationTimeline(); - scoped_refptr<cc::AnimationPlayer> cc_player = + scoped_refptr<cc::SingleTickerAnimationPlayer> cc_player = client->player_->CcAnimationPlayer(); EXPECT_FALSE(cc_player->animation_timeline());
diff --git a/third_party/WebKit/Source/platform/audio/HRTFDatabaseLoader.cpp b/third_party/WebKit/Source/platform/audio/HRTFDatabaseLoader.cpp index cbd61f5..4ca8b2b 100644 --- a/third_party/WebKit/Source/platform/audio/HRTFDatabaseLoader.cpp +++ b/third_party/WebKit/Source/platform/audio/HRTFDatabaseLoader.cpp
@@ -96,7 +96,7 @@ // Start the asynchronous database loading process. thread_ = Platform::Current()->CreateThread( - WebThreadCreationParams("HRTF database loader")); + WebThreadCreationParams(WebThreadType::kHRTFDatabaseLoaderThread)); // TODO(alexclarke): Should this be posted as a loading task? PostCrossThreadTask(*thread_->GetWebTaskRunner(), FROM_HERE, CrossThreadBind(&HRTFDatabaseLoader::LoadTask,
diff --git a/third_party/WebKit/Source/platform/audio/PushPullFIFOMultithreadTest.cpp b/third_party/WebKit/Source/platform/audio/PushPullFIFOMultithreadTest.cpp index 21f576f..74920e10 100644 --- a/third_party/WebKit/Source/platform/audio/PushPullFIFOMultithreadTest.cpp +++ b/third_party/WebKit/Source/platform/audio/PushPullFIFOMultithreadTest.cpp
@@ -30,7 +30,8 @@ : fifo_(fifo), bus_(AudioBus::Create(fifo->NumberOfChannels(), bus_length)), client_thread_(Platform::Current()->CreateThread( - WebThreadCreationParams("client thread"))), + WebThreadCreationParams(WebThreadType::kTestThread) + .SetThreadName("FIFOClientThread"))), done_event_(std::make_unique<WaitableEvent>()), jitter_range_ms_(jitter_range_ms) {}
diff --git a/third_party/WebKit/Source/platform/audio/ReverbConvolver.cpp b/third_party/WebKit/Source/platform/audio/ReverbConvolver.cpp index b170391..a7c8f56 100644 --- a/third_party/WebKit/Source/platform/audio/ReverbConvolver.cpp +++ b/third_party/WebKit/Source/platform/audio/ReverbConvolver.cpp
@@ -138,8 +138,9 @@ // FIXME: would be better to up the thread priority here. It doesn't need to // be real-time, but higher than the default... if (use_background_threads && background_stages_.size() > 0) { - background_thread_ = Platform::Current()->CreateThread( - WebThreadCreationParams("Reverb convolution background thread")); + background_thread_ = + Platform::Current()->CreateThread(WebThreadCreationParams( + WebThreadType::kReverbConvolutionBackgroundThread)); } }
diff --git a/third_party/WebKit/Source/platform/blob/BUILD.gn b/third_party/WebKit/Source/platform/blob/BUILD.gn index 3416778f..b412650 100644 --- a/third_party/WebKit/Source/platform/blob/BUILD.gn +++ b/third_party/WebKit/Source/platform/blob/BUILD.gn
@@ -31,6 +31,8 @@ "BlobRegistry.h", "BlobURL.cpp", "BlobURL.h", + "SerializedBlobStructTraits.cpp", + "SerializedBlobStructTraits.h", ] }
diff --git a/third_party/WebKit/Source/platform/blob/OWNERS b/third_party/WebKit/Source/platform/blob/OWNERS index e77e62a..e8cd7eaf 100644 --- a/third_party/WebKit/Source/platform/blob/OWNERS +++ b/third_party/WebKit/Source/platform/blob/OWNERS
@@ -1,5 +1,10 @@ dmurph@chromium.org mek@chromium.org +per-file *StructTraits*.*=set noparent +per-file *StructTraits*.*=file://ipc/SECURITY_OWNERS +per-file *.typemap=set noparent +per-file *.typemap=file://ipc/SECURITY_OWNERS + # TEAM: storage-dev@chromium.org # COMPONENT: Blink>FileAPI
diff --git a/third_party/WebKit/Source/platform/blob/SerializedBlob.typemap b/third_party/WebKit/Source/platform/blob/SerializedBlob.typemap new file mode 100644 index 0000000..fe70fef --- /dev/null +++ b/third_party/WebKit/Source/platform/blob/SerializedBlob.typemap
@@ -0,0 +1,13 @@ +# 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. + +mojom = "//third_party/WebKit/common/blob/serialized_blob.mojom" +public_headers = [ "//third_party/WebKit/Source/platform/blob/BlobData.h" ] +traits_headers = + [ "//third_party/WebKit/Source/platform/blob/SerializedBlobStructTraits.h" ] + +deps = [ + "//mojo/public/cpp/bindings", +] +type_mappings = [ "blink.mojom.SerializedBlob=scoped_refptr<::blink::BlobDataHandle>[nullable_is_same_type]" ]
diff --git a/third_party/WebKit/Source/platform/blob/SerializedBlobStructTraits.cpp b/third_party/WebKit/Source/platform/blob/SerializedBlobStructTraits.cpp new file mode 100644 index 0000000..f1574131 --- /dev/null +++ b/third_party/WebKit/Source/platform/blob/SerializedBlobStructTraits.cpp
@@ -0,0 +1,23 @@ +// 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 "platform/blob/SerializedBlobStructTraits.h" + +namespace mojo { + +bool StructTraits<blink::mojom::blink::SerializedBlob::DataView, + scoped_refptr<blink::BlobDataHandle>>:: + Read(blink::mojom::blink::SerializedBlob::DataView data, + scoped_refptr<blink::BlobDataHandle>* out) { + WTF::String uuid; + WTF::String type; + if (!data.ReadUuid(&uuid) || !data.ReadContentType(&type)) + return false; + *out = blink::BlobDataHandle::Create( + uuid, type, data.size(), + data.TakeBlob<blink::mojom::blink::BlobPtrInfo>()); + return true; +} + +} // namespace mojo
diff --git a/third_party/WebKit/Source/platform/blob/SerializedBlobStructTraits.h b/third_party/WebKit/Source/platform/blob/SerializedBlobStructTraits.h new file mode 100644 index 0000000..0b65373 --- /dev/null +++ b/third_party/WebKit/Source/platform/blob/SerializedBlobStructTraits.h
@@ -0,0 +1,44 @@ +// 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. + +#ifndef SerializedBlobStructTraits_h +#define SerializedBlobStructTraits_h + +#include "base/memory/ref_counted.h" +#include "mojo/public/cpp/bindings/string_traits_wtf.h" +#include "platform/PlatformExport.h" +#include "platform/blob/BlobData.h" +#include "third_party/WebKit/common/blob/serialized_blob.mojom-blink.h" + +namespace mojo { + +template <> +struct PLATFORM_EXPORT + StructTraits<blink::mojom::blink::SerializedBlob::DataView, + scoped_refptr<blink::BlobDataHandle>> { + static WTF::String uuid(const scoped_refptr<blink::BlobDataHandle>& input) { + return input->Uuid(); + } + + static WTF::String content_type( + const scoped_refptr<blink::BlobDataHandle>& input) { + return input->GetType(); + } + + static uint64_t size(const scoped_refptr<blink::BlobDataHandle>& input) { + return input->size(); + } + + static blink::mojom::blink::BlobPtr blob( + const scoped_refptr<blink::BlobDataHandle>& input) { + return input->CloneBlobPtr(); + } + + static bool Read(blink::mojom::blink::SerializedBlob::DataView, + scoped_refptr<blink::BlobDataHandle>* out); +}; + +} // namespace mojo + +#endif // SerializedBlobStructTraits_h
diff --git a/third_party/WebKit/Source/platform/exported/Platform.cpp b/third_party/WebKit/Source/platform/exported/Platform.cpp index 5ff71d1..ff49b78cb 100644 --- a/third_party/WebKit/Source/platform/exported/Platform.cpp +++ b/third_party/WebKit/Source/platform/exported/Platform.cpp
@@ -163,8 +163,8 @@ // Pre-create the File thread so multiple threads can call FileTaskRunner() in // a non racy way later. - g_platform->file_thread_ = - g_platform->CreateThread(WebThreadCreationParams("File")); + g_platform->file_thread_ = g_platform->CreateThread( + WebThreadCreationParams(WebThreadType::kFileThread)); if (BlinkResourceCoordinatorBase::IsEnabled()) RendererResourceCoordinator::Initialize();
diff --git a/third_party/WebKit/Source/platform/exported/WebClipboardImpl.cpp b/third_party/WebKit/Source/platform/exported/WebClipboardImpl.cpp index f46f0c2..70d7b2d 100644 --- a/third_party/WebKit/Source/platform/exported/WebClipboardImpl.cpp +++ b/third_party/WebKit/Source/platform/exported/WebClipboardImpl.cpp
@@ -8,6 +8,7 @@ #include "mojo/public/cpp/system/platform_handle.h" #include "public/platform/Platform.h" #include "services/service_manager/public/cpp/connector.h" +#include "third_party/WebKit/Source/platform/blob/BlobData.h" #include "third_party/WebKit/Source/platform/clipboard/ClipboardMimeTypes.h" #include "third_party/WebKit/public/platform/WebDragData.h" #include "third_party/WebKit/public/platform/WebImage.h" @@ -153,12 +154,11 @@ if (!IsValidBufferType(buffer)) return WebBlobInfo(); - mojom::blink::SerializedBlobPtr blob; + scoped_refptr<BlobDataHandle> blob; clipboard_->ReadImage(buffer, &blob); if (!blob) return WebBlobInfo(); - return WebBlobInfo(blob->uuid, blob->content_type, blob->size, - blob->blob.PassHandle()); + return blob; } WebString WebClipboardImpl::ReadCustomData(mojom::ClipboardBuffer buffer,
diff --git a/third_party/WebKit/Source/platform/exported/WebRuntimeFeatures.cpp b/third_party/WebKit/Source/platform/exported/WebRuntimeFeatures.cpp index 2f9c7a7..ec7f217 100644 --- a/third_party/WebKit/Source/platform/exported/WebRuntimeFeatures.cpp +++ b/third_party/WebKit/Source/platform/exported/WebRuntimeFeatures.cpp
@@ -502,4 +502,12 @@ RuntimeEnabledFeatures::SetDoubleTapToJumpOnVideoEnabled(enable); } +void WebRuntimeFeatures::EnableCodeCacheAfterExecute(bool enable) { + RuntimeEnabledFeatures::SetCodeCacheAfterExecuteEnabled(enable); +} + +void WebRuntimeFeatures::EnableUnifiedTouchAdjustment(bool enable) { + RuntimeEnabledFeatures::SetUnifiedTouchAdjustmentEnabled(enable); +} + } // namespace blink
diff --git a/third_party/WebKit/Source/platform/graphics/Canvas2DLayerBridge.cpp b/third_party/WebKit/Source/platform/graphics/Canvas2DLayerBridge.cpp index 0338d42..0b5e37b 100644 --- a/third_party/WebKit/Source/platform/graphics/Canvas2DLayerBridge.cpp +++ b/third_party/WebKit/Source/platform/graphics/Canvas2DLayerBridge.cpp
@@ -472,6 +472,10 @@ } } +void Canvas2DLayerBridge::DrawFullImage(const cc::PaintImage& image) { + Canvas()->drawImage(image, 0, 0); +} + bool Canvas2DLayerBridge::WritePixels(const SkImageInfo& orig_info, const void* pixels, size_t row_bytes,
diff --git a/third_party/WebKit/Source/platform/graphics/Canvas2DLayerBridge.h b/third_party/WebKit/Source/platform/graphics/Canvas2DLayerBridge.h index 94015f6..cef7d835 100644 --- a/third_party/WebKit/Source/platform/graphics/Canvas2DLayerBridge.h +++ b/third_party/WebKit/Source/platform/graphics/Canvas2DLayerBridge.h
@@ -96,13 +96,17 @@ void DoPaintInvalidation(const FloatRect& dirty_rect); WebLayer* Layer(); bool Restore(); - virtual void WillOverwriteCanvas(); // virtual for unit testing void DisableDeferral(DisableDeferralReason); void SetFilterQuality(SkFilterQuality); + // virtual for unit testing + virtual void WillOverwriteCanvas(); + virtual void DrawFullImage(const cc::PaintImage&); + virtual void DidRestoreCanvasMatrixClipStack(cc::PaintCanvas*) {} + virtual bool IsAccelerated() const; + PaintCanvas* Canvas(); bool IsValid() const; - virtual bool IsAccelerated() const; // virtual for unit testing bool WritePixels(const SkImageInfo&, const void* pixels, size_t row_bytes,
diff --git a/third_party/WebKit/Source/platform/graphics/DeferredImageDecoderTest.cpp b/third_party/WebKit/Source/platform/graphics/DeferredImageDecoderTest.cpp index 4a17a56..9a102a0e 100644 --- a/third_party/WebKit/Source/platform/graphics/DeferredImageDecoderTest.cpp +++ b/third_party/WebKit/Source/platform/graphics/DeferredImageDecoderTest.cpp
@@ -226,7 +226,8 @@ // Create a thread to rasterize PaintRecord. std::unique_ptr<WebThread> thread = Platform::Current()->CreateThread( - WebThreadCreationParams("RasterThread")); + WebThreadCreationParams(WebThreadType::kTestThread) + .SetThreadName("RasterThread")); PostCrossThreadTask( *thread->GetWebTaskRunner(), FROM_HERE, CrossThreadBind(&RasterizeMain, CrossThreadUnretained(canvas_.get()),
diff --git a/third_party/WebKit/Source/platform/graphics/GpuMemoryBufferImageCopy.cpp b/third_party/WebKit/Source/platform/graphics/GpuMemoryBufferImageCopy.cpp index c1ac5011..9515a50 100644 --- a/third_party/WebKit/Source/platform/graphics/GpuMemoryBufferImageCopy.cpp +++ b/third_party/WebKit/Source/platform/graphics/GpuMemoryBufferImageCopy.cpp
@@ -17,11 +17,9 @@ GpuMemoryBufferImageCopy::GpuMemoryBufferImageCopy( gpu::gles2::GLES2Interface* gl) : gl_(gl) { - gl_->GenFramebuffers(1, &draw_frame_buffer_); } GpuMemoryBufferImageCopy::~GpuMemoryBufferImageCopy() { - gl_->DeleteFramebuffers(1, &draw_frame_buffer_); } bool GpuMemoryBufferImageCopy::EnsureMemoryBuffer(int width, int height) { @@ -72,9 +70,6 @@ gl_->BindTexImage2DCHROMIUM(target, image_id); } gl_->BindTexture(GL_TEXTURE_2D, 0); - gl_->BindFramebuffer(GL_DRAW_FRAMEBUFFER, draw_frame_buffer_); - gl_->FramebufferTexture2D(GL_DRAW_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, target, - dest_texture_id, 0); // Bind the read framebuffer to our image. StaticBitmapImage* static_image = static_cast<StaticBitmapImage*>(image); @@ -86,19 +81,12 @@ gl_->WaitSyncTokenCHROMIUM(sync_token.GetData()); GLuint source_texture_id = gl_->CreateAndConsumeTextureCHROMIUM(mailbox.name); gl_->BindTexture(GL_TEXTURE_2D, 0); - GLuint read_frame_buffer; - gl_->GenFramebuffers(1, &read_frame_buffer); - gl_->BindFramebuffer(GL_READ_FRAMEBUFFER, read_frame_buffer); - gl_->FramebufferTexture2D(GL_READ_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, target, - source_texture_id, 0); - // Copy the read framebuffer to the draw framebuffer. - gl_->BlitFramebufferCHROMIUM(0, 0, width, height, 0, 0, width, height, - GL_COLOR_BUFFER_BIT, GL_NEAREST); + gl_->CopySubTextureCHROMIUM(source_texture_id, 0, GL_TEXTURE_2D, + dest_texture_id, 0, 0, 0, 0, 0, width, height, + false, false, false); // Cleanup the read framebuffer, associated image and texture. - gl_->BindFramebuffer(GL_FRAMEBUFFER, 0); - gl_->DeleteFramebuffers(1, &read_frame_buffer); gl_->BindTexture(GL_TEXTURE_2D, 0); gl_->DeleteTextures(1, &source_texture_id);
diff --git a/third_party/WebKit/Source/platform/graphics/GpuMemoryBufferImageCopy.h b/third_party/WebKit/Source/platform/graphics/GpuMemoryBufferImageCopy.h index b12e7768..f2db7e0f 100644 --- a/third_party/WebKit/Source/platform/graphics/GpuMemoryBufferImageCopy.h +++ b/third_party/WebKit/Source/platform/graphics/GpuMemoryBufferImageCopy.h
@@ -26,7 +26,6 @@ int last_width_ = 0; int last_height_ = 0; - GLuint draw_frame_buffer_; gpu::gles2::GLES2Interface* gl_; std::unique_ptr<gfx::GpuMemoryBuffer> gpu_memory_buffer_;
diff --git a/third_party/WebKit/Source/platform/graphics/ImageFrameGeneratorTest.cpp b/third_party/WebKit/Source/platform/graphics/ImageFrameGeneratorTest.cpp index cfba57067..74cb01f 100644 --- a/third_party/WebKit/Source/platform/graphics/ImageFrameGeneratorTest.cpp +++ b/third_party/WebKit/Source/platform/graphics/ImageFrameGeneratorTest.cpp
@@ -257,7 +257,8 @@ SetFrameStatus(ImageFrame::kFrameComplete); AddNewData(); std::unique_ptr<WebThread> thread = Platform::Current()->CreateThread( - WebThreadCreationParams("DecodeThread")); + WebThreadCreationParams(WebThreadType::kTestThread) + .SetThreadName("DecodeThread")); PostCrossThreadTask( *thread->GetWebTaskRunner(), FROM_HERE, CrossThreadBind(&DecodeThreadMain, WTF::RetainedRef(generator_),
diff --git a/third_party/WebKit/Source/platform/graphics/compositing/CompositedLayerRasterInvalidator.cpp b/third_party/WebKit/Source/platform/graphics/compositing/CompositedLayerRasterInvalidator.cpp index 4adcfb8e..8ba4f23c 100644 --- a/third_party/WebKit/Source/platform/graphics/compositing/CompositedLayerRasterInvalidator.cpp +++ b/third_party/WebKit/Source/platform/graphics/compositing/CompositedLayerRasterInvalidator.cpp
@@ -57,7 +57,8 @@ clip_rect.ClearIsTight(); } else { clip_rect = GeometryMapper::LocalToAncestorClipRect( - chunk.properties.property_tree_state, layer_state_); + chunk.properties.property_tree_state.GetPropertyTreeState(), + layer_state_); if (clip_rect.IsTight()) clip_rect.MoveBy(FloatPoint(-layer_bounds_.x(), -layer_bounds_.y())); }
diff --git a/third_party/WebKit/Source/platform/graphics/compositing/PaintArtifactCompositor.cpp b/third_party/WebKit/Source/platform/graphics/compositing/PaintArtifactCompositor.cpp index 161516a..21fda3ba 100644 --- a/third_party/WebKit/Source/platform/graphics/compositing/PaintArtifactCompositor.cpp +++ b/third_party/WebKit/Source/platform/graphics/compositing/PaintArtifactCompositor.cpp
@@ -265,7 +265,8 @@ rect_known_to_be_opaque( first_paint_chunk.known_to_be_opaque ? bounds : FloatRect()), backface_hidden(first_paint_chunk.properties.backface_hidden), - property_tree_state(first_paint_chunk.properties.property_tree_state), + property_tree_state(first_paint_chunk.properties.property_tree_state + .GetPropertyTreeState()), requires_own_layer(chunk_requires_own_layer) { paint_chunks.push_back(&first_paint_chunk); }
diff --git a/third_party/WebKit/Source/platform/graphics/compositing/PaintChunksToCcLayer.cpp b/third_party/WebKit/Source/platform/graphics/compositing/PaintChunksToCcLayer.cpp index 40922e7..8c4103f 100644 --- a/third_party/WebKit/Source/platform/graphics/compositing/PaintChunksToCcLayer.cpp +++ b/third_party/WebKit/Source/platform/graphics/compositing/PaintChunksToCcLayer.cpp
@@ -355,7 +355,8 @@ for (auto chunk_it = paint_chunks.begin(); chunk_it != paint_chunks.end(); chunk_it++) { const PaintChunk& chunk = **chunk_it; - const PropertyTreeState& chunk_state = chunk.properties.property_tree_state; + const PropertyTreeState& chunk_state = + chunk.properties.property_tree_state.GetPropertyTreeState(); SwitchToEffect(chunk_state.Effect()); SwitchToClip(chunk_state.Clip()); bool transformed = chunk_state.Transform() != current_transform_; @@ -445,7 +446,8 @@ const gfx::Vector2dF& layer_offset) { FloatClipRect rect(r); GeometryMapper::LocalToAncestorVisualRect( - chunk.properties.property_tree_state, layer_state, rect); + chunk.properties.property_tree_state.GetPropertyTreeState(), layer_state, + rect); if (rect.Rect().IsEmpty()) return IntRect();
diff --git a/third_party/WebKit/Source/platform/graphics/gpu/DrawingBuffer.cpp b/third_party/WebKit/Source/platform/graphics/gpu/DrawingBuffer.cpp index bc3c34db..2c51a9a 100644 --- a/third_party/WebKit/Source/platform/graphics/gpu/DrawingBuffer.cpp +++ b/third_party/WebKit/Source/platform/graphics/gpu/DrawingBuffer.cpp
@@ -848,10 +848,17 @@ layer_->SetOpaque(!want_alpha_channel_); layer_->SetBlendBackgroundColor(want_alpha_channel_); // If premultiplied_alpha_false_texture_ exists, then premultiplied_alpha_ - // has already been handled via CopySubTextureCHROMIUM, and does not need - // to be handled by the compositor. - layer_->SetPremultipliedAlpha(premultiplied_alpha_ && - !premultiplied_alpha_false_texture_); + // has already been handled via CopySubTextureCHROMIUM -- the alpha channel + // has been multiplied into the color channels. In this case, or if + // premultiplied_alpha_ is true, then the layer should consider its contents + // to be premultiplied. + // + // The only situation where the layer should consider its contents + // un-premultiplied is when premultiplied_alpha_ is false, and + // premultiplied_alpha_false_texture_ does not exist. + DCHECK(!(premultiplied_alpha_ && premultiplied_alpha_false_texture_)); + layer_->SetPremultipliedAlpha(premultiplied_alpha_ || + premultiplied_alpha_false_texture_); layer_->SetNearestNeighbor(filter_quality_ == kNone_SkFilterQuality); GraphicsLayer::RegisterContentsLayer(layer_->Layer()); }
diff --git a/third_party/WebKit/Source/platform/graphics/paint/GeometryMapperTest.cpp b/third_party/WebKit/Source/platform/graphics/paint/GeometryMapperTest.cpp index e92e4f8..d9c39ba 100644 --- a/third_party/WebKit/Source/platform/graphics/paint/GeometryMapperTest.cpp +++ b/third_party/WebKit/Source/platform/graphics/paint/GeometryMapperTest.cpp
@@ -663,7 +663,7 @@ ClipPaintPropertyNode::Root(), kColorFilterNone, filters, 1.0, SkBlendMode::kSrcOver, CompositingReason::kNone, CompositorElementId(), FloatPoint(100, 100)); - local_state.SetEffect(effect); + local_state.SetEffect(effect.get()); input_rect = FloatRect(100, 100, 50, 50); expected_transformed_rect = input_rect;
diff --git a/third_party/WebKit/Source/platform/graphics/paint/PaintChunkProperties.h b/third_party/WebKit/Source/platform/graphics/paint/PaintChunkProperties.h index 5a92b7a..b250659 100644 --- a/third_party/WebKit/Source/platform/graphics/paint/PaintChunkProperties.h +++ b/third_party/WebKit/Source/platform/graphics/paint/PaintChunkProperties.h
@@ -7,7 +7,7 @@ #include <iosfwd> #include "platform/PlatformExport.h" -#include "platform/graphics/paint/PropertyTreeState.h" +#include "platform/graphics/paint/RefCountedPropertyTreeState.h" #include "platform/wtf/Allocator.h" #include "platform/wtf/Forward.h" #include "platform/wtf/Noncopyable.h" @@ -33,7 +33,7 @@ : property_tree_state(nullptr, nullptr, nullptr), backface_hidden(false) {} - PropertyTreeState property_tree_state; + RefCountedPropertyTreeState property_tree_state; bool backface_hidden; String ToString() const;
diff --git a/third_party/WebKit/Source/platform/graphics/paint/PropertyTreeState.h b/third_party/WebKit/Source/platform/graphics/paint/PropertyTreeState.h index 4ae1476b..600f522 100644 --- a/third_party/WebKit/Source/platform/graphics/paint/PropertyTreeState.h +++ b/third_party/WebKit/Source/platform/graphics/paint/PropertyTreeState.h
@@ -15,7 +15,7 @@ namespace blink { // A complete set of paint properties including those that are inherited from -// other objects. RefPtrs are used to guard against use-after-free bugs. +// other objects. class PLATFORM_EXPORT PropertyTreeState { USING_FAST_MALLOC(PropertyTreeState); @@ -27,22 +27,16 @@ bool HasDirectCompositingReasons() const; - const TransformPaintPropertyNode* Transform() const { - return transform_.get(); - } - void SetTransform(scoped_refptr<const TransformPaintPropertyNode> node) { - transform_ = std::move(node); + const TransformPaintPropertyNode* Transform() const { return transform_; } + void SetTransform(const TransformPaintPropertyNode* node) { + transform_ = node; } - const ClipPaintPropertyNode* Clip() const { return clip_.get(); } - void SetClip(scoped_refptr<const ClipPaintPropertyNode> node) { - clip_ = std::move(node); - } + const ClipPaintPropertyNode* Clip() const { return clip_; } + void SetClip(const ClipPaintPropertyNode* node) { clip_ = node; } - const EffectPaintPropertyNode* Effect() const { return effect_.get(); } - void SetEffect(scoped_refptr<const EffectPaintPropertyNode> node) { - effect_ = std::move(node); - } + const EffectPaintPropertyNode* Effect() const { return effect_; } + void SetEffect(const EffectPaintPropertyNode* node) { effect_ = node; } static const PropertyTreeState& Root(); @@ -64,9 +58,9 @@ #endif private: - scoped_refptr<const TransformPaintPropertyNode> transform_; - scoped_refptr<const ClipPaintPropertyNode> clip_; - scoped_refptr<const EffectPaintPropertyNode> effect_; + const TransformPaintPropertyNode* transform_; + const ClipPaintPropertyNode* clip_; + const EffectPaintPropertyNode* effect_; }; inline bool operator==(const PropertyTreeState& a, const PropertyTreeState& b) {
diff --git a/third_party/WebKit/Source/platform/graphics/paint/RefCountedPropertyTreeState.cpp b/third_party/WebKit/Source/platform/graphics/paint/RefCountedPropertyTreeState.cpp new file mode 100644 index 0000000..60bd0c7 --- /dev/null +++ b/third_party/WebKit/Source/platform/graphics/paint/RefCountedPropertyTreeState.cpp
@@ -0,0 +1,51 @@ +// 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. + +#include "platform/graphics/paint/RefCountedPropertyTreeState.h" + +namespace blink { + +const RefCountedPropertyTreeState& RefCountedPropertyTreeState::Root() { + DEFINE_STATIC_LOCAL( + std::unique_ptr<RefCountedPropertyTreeState>, root, + (WTF::WrapUnique(new RefCountedPropertyTreeState( + TransformPaintPropertyNode::Root(), ClipPaintPropertyNode::Root(), + EffectPaintPropertyNode::Root())))); + return *root; +} + +const CompositorElementId RefCountedPropertyTreeState::GetCompositorElementId( + const CompositorElementIdSet& element_ids) const { + // The effect or transform nodes could have a compositor element id. The order + // doesn't matter as the element id should be the same on all that have a + // non-default CompositorElementId. + // + // Note that RefCountedPropertyTreeState acts as a context that accumulates + // state as we traverse the tree building layers. This means that we could see + // a compositor element id 'A' for a parent layer in conjunction with a + // compositor element id 'B' for a child layer. To preserve uniqueness of + // element ids, then, we check for presence in the |element_ids| set (which + // represents element ids already previously attached to a layer). This is an + // interim step while we pursue broader rework of animation subsystem noted in + // http://crbug.com/709137. + if (Effect()->GetCompositorElementId() && + !element_ids.Contains(Effect()->GetCompositorElementId())) + return Effect()->GetCompositorElementId(); + if (Transform()->GetCompositorElementId() && + !element_ids.Contains(Transform()->GetCompositorElementId())) + return Transform()->GetCompositorElementId(); + return CompositorElementId(); +} + +#if DCHECK_IS_ON() + +String RefCountedPropertyTreeState::ToTreeString() const { + return "transform:\n" + (Transform() ? Transform()->ToTreeString() : "null") + + "\nclip:\n" + (Clip() ? Clip()->ToTreeString() : "null") + + "\neffect:\n" + (Effect() ? Effect()->ToTreeString() : "null"); +} + +#endif + +} // namespace blink
diff --git a/third_party/WebKit/Source/platform/graphics/paint/RefCountedPropertyTreeState.h b/third_party/WebKit/Source/platform/graphics/paint/RefCountedPropertyTreeState.h new file mode 100644 index 0000000..fe38bf6 --- /dev/null +++ b/third_party/WebKit/Source/platform/graphics/paint/RefCountedPropertyTreeState.h
@@ -0,0 +1,87 @@ +// 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. + +#ifndef RefCountedPropertyTreeState_h +#define RefCountedPropertyTreeState_h + +#include "platform/graphics/paint/PropertyTreeState.h" +#include "platform/wtf/HashFunctions.h" +#include "platform/wtf/HashTraits.h" +#include "platform/wtf/text/StringBuilder.h" + +namespace blink { + +// A complete set of paint properties including those that are inherited from +// other objects. RefPtrs are used to guard against use-after-free bugs. +class PLATFORM_EXPORT RefCountedPropertyTreeState { + USING_FAST_MALLOC(RefCountedPropertyTreeState); + + public: + RefCountedPropertyTreeState(const TransformPaintPropertyNode* transform, + const ClipPaintPropertyNode* clip, + const EffectPaintPropertyNode* effect) + : transform_(transform), clip_(clip), effect_(effect) {} + + RefCountedPropertyTreeState(const PropertyTreeState& property_tree_state) + : transform_(property_tree_state.Transform()), + clip_(property_tree_state.Clip()), + effect_(property_tree_state.Effect()) {} + + bool HasDirectCompositingReasons() const; + + const TransformPaintPropertyNode* Transform() const { + return transform_.get(); + } + void SetTransform(scoped_refptr<const TransformPaintPropertyNode> node) { + transform_ = std::move(node); + } + + const ClipPaintPropertyNode* Clip() const { return clip_.get(); } + void SetClip(scoped_refptr<const ClipPaintPropertyNode> node) { + clip_ = std::move(node); + } + + const EffectPaintPropertyNode* Effect() const { return effect_.get(); } + void SetEffect(scoped_refptr<const EffectPaintPropertyNode> node) { + effect_ = std::move(node); + } + + static const RefCountedPropertyTreeState& Root(); + + PropertyTreeState GetPropertyTreeState() const { + return PropertyTreeState(transform_.get(), clip_.get(), effect_.get()); + } + + // Returns the compositor element id, if any, for this property state. If + // neither the effect nor transform nodes have a compositor element id then a + // default instance is returned. + const CompositorElementId GetCompositorElementId( + const CompositorElementIdSet& element_ids) const; + + void ClearChangedToRoot() const { + Transform()->ClearChangedToRoot(); + Clip()->ClearChangedToRoot(); + Effect()->ClearChangedToRoot(); + } + +#if DCHECK_IS_ON() + // Dumps the tree from this state up to the root as a string. + String ToTreeString() const; +#endif + + private: + scoped_refptr<const TransformPaintPropertyNode> transform_; + scoped_refptr<const ClipPaintPropertyNode> clip_; + scoped_refptr<const EffectPaintPropertyNode> effect_; +}; + +inline bool operator==(const RefCountedPropertyTreeState& a, + const RefCountedPropertyTreeState& b) { + return a.Transform() == b.Transform() && a.Clip() == b.Clip() && + a.Effect() == b.Effect(); +} + +} // namespace blink + +#endif // RefCountedPropertyTreeState_h
diff --git a/third_party/WebKit/Source/platform/heap/HeapPage.cpp b/third_party/WebKit/Source/platform/heap/HeapPage.cpp index 1ccdbdac..63e72a8 100644 --- a/third_party/WebKit/Source/platform/heap/HeapPage.cpp +++ b/third_party/WebKit/Source/platform/heap/HeapPage.cpp
@@ -440,6 +440,7 @@ void NormalPageArena::ClearFreeLists() { SetAllocationPoint(nullptr, 0); free_list_.Clear(); + promptly_freed_size_ = 0; } size_t NormalPageArena::ArenaSize() { @@ -719,7 +720,7 @@ // Rebuild free lists. free_list_.Clear(); - size_t freed_size = 0; + for (NormalPage* page = static_cast<NormalPage*>(first_page_); page; page = static_cast<NormalPage*>(page->Next())) { page->object_start_bit_map()->Clear(); @@ -732,18 +733,6 @@ DCHECK_GT(size, 0u); DCHECK_LT(size, BlinkPagePayloadSize()); - if (header->IsPromptlyFreed()) { - DCHECK_GE(size, sizeof(HeapObjectHeader)); - // Zero the memory in the free list header to maintain the - // invariant that memory on the free list is zero filled. - // The rest of the memory is already on the free list and is - // therefore already zero filled. - SET_MEMORY_INACCESSIBLE(header_address, sizeof(HeapObjectHeader)); - CHECK_MEMORY_INACCESSIBLE(header_address, size); - freed_size += size; - header_address += size; - continue; - } if (header->IsFree()) { // Zero the memory in the free list header to maintain the // invariant that memory on the free list is zero filled. @@ -769,8 +758,8 @@ page->VerifyObjectStartBitmapIsConsistentWithPayload(); } - GetThreadState()->Heap().HeapStats().DecreaseAllocatedObjectSize(freed_size); - DCHECK_EQ(promptly_freed_size_, freed_size); + + // After coalescing we do not have promptly freed objects. promptly_freed_size_ = 0; double coalesce_time = @@ -808,11 +797,31 @@ ->ClearBit(address); return; } - SET_MEMORY_INACCESSIBLE(payload, payload_size); - header->MarkPromptlyFreed(); + PromptlyFreeObjectInFreeList(header, size); } +} - promptly_freed_size_ += size; +void NormalPageArena::PromptlyFreeObjectInFreeList(HeapObjectHeader* header, + size_t size) { + Address address = reinterpret_cast<Address>(header); + NormalPage* page = reinterpret_cast<NormalPage*>(PageFromObject(header)); + if (page->HasBeenSwept()) { + Address payload = header->Payload(); + size_t payload_size = header->PayloadSize(); + // If the page has been swept a promptly freed object may be adjacent + // to other free list entries. We make the object available for future + // allocation right away by adding it to the free list and increase the + // promptly_freed_size_ counter which may result in coalescing later. + SET_MEMORY_INACCESSIBLE(payload, payload_size); + CHECK_MEMORY_INACCESSIBLE(payload, payload_size); + AddToFreeList(address, size); + promptly_freed_size_ += size; + } else { + // If we do not have free list entries the sweeper will take care of + // coalescing. + header->Unmark(); + } + GetThreadState()->Heap().HeapStats().DecreaseAllocatedObjectSize(size); } bool NormalPageArena::ExpandObject(HeapObjectHeader* header, size_t new_size) { @@ -858,15 +867,13 @@ HeapObjectHeader* freed_header = new (NotNull, shrink_address) HeapObjectHeader( shrink_size, header->GcInfoIndex(), HeapObjectHeader::kNormalPage); - freed_header->MarkPromptlyFreed(); + PromptlyFreeObjectInFreeList(freed_header, shrink_size); #if DCHECK_IS_ON() DCHECK_EQ(PageFromObject(reinterpret_cast<Address>(header)), FindPageFromAddress(reinterpret_cast<Address>(header))); #endif - promptly_freed_size_ += shrink_size; header->SetSize(allocation_size); - SET_MEMORY_INACCESSIBLE(shrink_address + sizeof(HeapObjectHeader), - shrink_size - sizeof(HeapObjectHeader)); + return false; } @@ -1392,8 +1399,6 @@ DCHECK_GT(size, 0u); DCHECK_LT(size, BlinkPagePayloadSize()); - if (header->IsPromptlyFreed()) - page_arena->DecreasePromptlyFreedSize(size); if (header->IsFree()) { // Zero the memory in the free list header to maintain the // invariant that memory on the free list is zero filled. @@ -1473,8 +1478,6 @@ DCHECK_GT(size, 0u); DCHECK_LT(size, BlinkPagePayloadSize()); - if (header->IsPromptlyFreed()) - page_arena->DecreasePromptlyFreedSize(size); if (header->IsFree()) { // Unpoison the freelist entry so that we // can compact into it as wanted. @@ -1576,8 +1579,6 @@ reinterpret_cast<HeapObjectHeader*>(header_address); size_t size = header->size(); DCHECK_LT(size, BlinkPagePayloadSize()); - if (header->IsPromptlyFreed()) - ArenaForNormalPage()->DecreasePromptlyFreedSize(size); if (header->IsFree()) { // Zero the memory in the free list header to maintain the // invariant that memory on the free list is zero filled.
diff --git a/third_party/WebKit/Source/platform/heap/HeapPage.h b/third_party/WebKit/Source/platform/heap/HeapPage.h index 0ac558a7..5e23003 100644 --- a/third_party/WebKit/Source/platform/heap/HeapPage.h +++ b/third_party/WebKit/Source/platform/heap/HeapPage.h
@@ -165,13 +165,6 @@ constexpr size_t kHeaderSizeMask = (static_cast<size_t>((1 << 14) - 1)) << 3; constexpr size_t kHeaderMarkBitMask = 1; constexpr size_t kHeaderFreedBitMask = 2; -// TODO(haraken): Remove the dead bit. It is used only by a header of -// a promptly freed object. -constexpr size_t kHeaderDeadBitMask = 4; -// On free-list entries we reuse the dead bit to distinguish a normal free-list -// entry from one that has been promptly freed. -constexpr size_t kHeaderPromptlyFreedBitMask = - kHeaderFreedBitMask | kHeaderDeadBitMask; constexpr size_t kLargeObjectSizeInHeader = 0; constexpr size_t kGcInfoIndexForFreeListHeader = 0; constexpr size_t kNonLargeObjectPageSizeMax = 1 << kBlinkPageSizeLog2; @@ -194,15 +187,6 @@ return encoded_ & kHeaderFreedBitMask; } - NO_SANITIZE_ADDRESS bool IsPromptlyFreed() const { - return (encoded_ & kHeaderPromptlyFreedBitMask) == - kHeaderPromptlyFreedBitMask; - } - - NO_SANITIZE_ADDRESS void MarkPromptlyFreed() { - encoded_ |= kHeaderPromptlyFreedBitMask; - } - size_t size() const; NO_SANITIZE_ADDRESS size_t GcInfoIndex() const { @@ -867,9 +851,9 @@ bool Coalesce(); void PromptlyFreeObject(HeapObjectHeader*); + void PromptlyFreeObjectInFreeList(HeapObjectHeader*, size_t); bool ExpandObject(HeapObjectHeader*, size_t); bool ShrinkObject(HeapObjectHeader*, size_t); - void DecreasePromptlyFreedSize(size_t size) { promptly_freed_size_ -= size; } size_t promptly_freed_size() const { return promptly_freed_size_; } bool IsObjectAllocatedAtAllocationPoint(HeapObjectHeader* header) { @@ -916,7 +900,9 @@ size_t remaining_allocation_size_; size_t last_remaining_allocation_size_; - // The size of promptly freed objects in the heap. + // The size of promptly freed objects in the heap. This counter is set to + // zero before sweeping when clearing the free list and after coalescing. + // It will increase for promptly freed objects on already swept pages. size_t promptly_freed_size_; bool is_lazy_sweeping_;
diff --git a/third_party/WebKit/Source/platform/heap/HeapTest.cpp b/third_party/WebKit/Source/platform/heap/HeapTest.cpp index 5fad312..c94f4aa6 100644 --- a/third_party/WebKit/Source/platform/heap/HeapTest.cpp +++ b/third_party/WebKit/Source/platform/heap/HeapTest.cpp
@@ -484,7 +484,8 @@ Vector<std::unique_ptr<WebThread>, kNumberOfThreads> threads; for (int i = 0; i < kNumberOfThreads; i++) { threads.push_back(Platform::Current()->CreateThread( - WebThreadCreationParams("blink gc testing thread"))); + WebThreadCreationParams(WebThreadType::kTestThread) + .SetThreadName("blink gc testing thread"))); PostCrossThreadTask( *threads.back()->GetWebTaskRunner(), FROM_HERE, CrossThreadBind(ThreadFunc, CrossThreadUnretained(tester))); @@ -5472,7 +5473,8 @@ MutexLocker locker(MainThreadMutex()); std::unique_ptr<WebThread> worker_thread = Platform::Current()->CreateThread( - WebThreadCreationParams("Test Worker Thread")); + WebThreadCreationParams(WebThreadType::kTestThread) + .SetThreadName("Test Worker Thread")); PostCrossThreadTask(*worker_thread->GetWebTaskRunner(), FROM_HERE, CrossThreadBind(WorkerThreadMain)); @@ -5572,7 +5574,8 @@ MutexLocker locker(MainThreadMutex()); std::unique_ptr<WebThread> worker_thread = Platform::Current()->CreateThread( - WebThreadCreationParams("Test Worker Thread")); + WebThreadCreationParams(WebThreadType::kTestThread) + .SetThreadName("Test Worker Thread")); PostCrossThreadTask( *worker_thread->GetWebTaskRunner(), FROM_HERE, CrossThreadBind(&MemberSameThreadCheckTester::WorkerThreadMain, @@ -5616,7 +5619,8 @@ MutexLocker locker(MainThreadMutex()); std::unique_ptr<WebThread> worker_thread = Platform::Current()->CreateThread( - WebThreadCreationParams("Test Worker Thread")); + WebThreadCreationParams(WebThreadType::kTestThread) + .SetThreadName("Test Worker Thread")); PostCrossThreadTask( *worker_thread->GetWebTaskRunner(), FROM_HERE, CrossThreadBind(&PersistentSameThreadCheckTester::WorkerThreadMain, @@ -5660,7 +5664,8 @@ MutexLocker locker(MainThreadMutex()); std::unique_ptr<WebThread> worker_thread = Platform::Current()->CreateThread( - WebThreadCreationParams("Test Worker Thread")); + WebThreadCreationParams(WebThreadType::kTestThread) + .SetThreadName("Test Worker Thread")); Persistent<MainThreadObject> main_thread_object = new MainThreadObject(); PostCrossThreadTask( *worker_thread->GetWebTaskRunner(), FROM_HERE, @@ -6459,7 +6464,8 @@ // the worker thread. MutexLocker main_thread_mutex_locker(MainThreadMutex()); std::unique_ptr<WebThread> worker_thread = Platform::Current()->CreateThread( - WebThreadCreationParams("Test Worker Thread")); + WebThreadCreationParams(WebThreadType::kTestThread) + .SetThreadName("Test Worker Thread")); DestructorLockingObject* object = nullptr; PostCrossThreadTask( *worker_thread->GetWebTaskRunner(), FROM_HERE,
diff --git a/third_party/WebKit/Source/platform/loader/fetch/ClientHintsPreferences.cpp b/third_party/WebKit/Source/platform/loader/fetch/ClientHintsPreferences.cpp index d7fffec2..7adb1ac 100644 --- a/third_party/WebKit/Source/platform/loader/fetch/ClientHintsPreferences.cpp +++ b/third_party/WebKit/Source/platform/loader/fetch/ClientHintsPreferences.cpp
@@ -52,10 +52,18 @@ void ClientHintsPreferences::UpdateFromAcceptClientHintsHeader( const String& header_value, + const KURL& url, Context* context) { if (header_value.IsEmpty()) return; + // If the persistent client hint feature is enabled, then client hints + // should be allowed only on secure URLs. + if (blink::RuntimeEnabledFeatures::ClientHintsPersistentEnabled() && + !IsClientHintsAllowed(url)) { + return; + } + WebEnabledClientHints new_enabled_types; ParseAcceptChHeader(header_value, new_enabled_types); @@ -101,6 +109,8 @@ } const KURL url = response.Url(); + if (!IsClientHintsAllowed(url)) + return; bool conversion_ok = false; int64_t persist_duration_seconds = @@ -115,4 +125,11 @@ ParseAcceptChHeader(accept_ch_header_value, enabled_hints); } +// static +bool ClientHintsPreferences::IsClientHintsAllowed(const KURL& url) { + return (url.ProtocolIs("http") || url.ProtocolIs("https")) && + (SecurityOrigin::IsSecure(url) || + SecurityOrigin::Create(url)->IsLocalhost()); +} + } // namespace blink
diff --git a/third_party/WebKit/Source/platform/loader/fetch/ClientHintsPreferences.h b/third_party/WebKit/Source/platform/loader/fetch/ClientHintsPreferences.h index d2100f2..ba6fb2540 100644 --- a/third_party/WebKit/Source/platform/loader/fetch/ClientHintsPreferences.h +++ b/third_party/WebKit/Source/platform/loader/fetch/ClientHintsPreferences.h
@@ -13,6 +13,7 @@ namespace blink { +class KURL; class ResourceResponse; // TODO (tbansal): Remove PLATFORM_EXPORT, and pass WebClientHintsType @@ -35,8 +36,12 @@ void UpdateFrom(const ClientHintsPreferences&); // Parses the client hints headers, and populates |this| with the client hint - // preferences. |context| may be null. - void UpdateFromAcceptClientHintsHeader(const String& header_value, Context*); + // preferences. |url| is the URL of the resource whose response included the + // |header_value|. |context| may be null. If client hints are not allowed for + // |url|, then |this| would not be updated. + void UpdateFromAcceptClientHintsHeader(const String& header_value, + const KURL&, + Context*); bool ShouldSend(mojom::WebClientHintsType type) const { return enabled_hints_.IsEnabled(type); @@ -59,6 +64,10 @@ WebEnabledClientHints& enabled_hints, TimeDelta* persist_duration); + // Returns true if client hints are allowed for the provided KURL. Client + // hints are allowed only on HTTP URLs that belong to secure contexts. + static bool IsClientHintsAllowed(const KURL&); + private: WebEnabledClientHints enabled_hints_; };
diff --git a/third_party/WebKit/Source/platform/loader/fetch/ClientHintsPreferencesTest.cpp b/third_party/WebKit/Source/platform/loader/fetch/ClientHintsPreferencesTest.cpp index 13ccbc0d..7086451 100644 --- a/third_party/WebKit/Source/platform/loader/fetch/ClientHintsPreferencesTest.cpp +++ b/third_party/WebKit/Source/platform/loader/fetch/ClientHintsPreferencesTest.cpp
@@ -15,7 +15,7 @@ class ClientHintsPreferencesTest : public ::testing::Test {}; -TEST_F(ClientHintsPreferencesTest, Basic) { +TEST_F(ClientHintsPreferencesTest, BasicSecure) { struct TestCase { const char* header_value; bool expectation_resource_width; @@ -32,7 +32,8 @@ for (const auto& test_case : cases) { ClientHintsPreferences preferences; - preferences.UpdateFromAcceptClientHintsHeader(test_case.header_value, + const KURL kurl(String::FromUTF8("https://www.google.com/")); + preferences.UpdateFromAcceptClientHintsHeader(test_case.header_value, kurl, nullptr); EXPECT_EQ( test_case.expectation_resource_width, @@ -45,7 +46,7 @@ // Calling UpdateFromAcceptClientHintsHeader with empty header should have // no impact on client hint preferences. - preferences.UpdateFromAcceptClientHintsHeader("", nullptr); + preferences.UpdateFromAcceptClientHintsHeader("", kurl, nullptr); EXPECT_EQ( test_case.expectation_resource_width, preferences.ShouldSend(mojom::WebClientHintsType::kResourceWidth)); @@ -57,7 +58,7 @@ // Calling UpdateFromAcceptClientHintsHeader with an invalid header should // have no impact on client hint preferences. - preferences.UpdateFromAcceptClientHintsHeader("foobar", nullptr); + preferences.UpdateFromAcceptClientHintsHeader("foobar", kurl, nullptr); EXPECT_EQ( test_case.expectation_resource_width, preferences.ShouldSend(mojom::WebClientHintsType::kResourceWidth)); @@ -69,6 +70,18 @@ } } +TEST_F(ClientHintsPreferencesTest, Insecure) { + for (const auto& use_secure_url : {false, true}) { + ClientHintsPreferences preferences; + const KURL kurl = use_secure_url + ? KURL(String::FromUTF8("https://www.google.com/")) + : KURL(String::FromUTF8("http://www.google.com/")); + preferences.UpdateFromAcceptClientHintsHeader("dpr", kurl, nullptr); + EXPECT_EQ(use_secure_url, + preferences.ShouldSend(mojom::WebClientHintsType::kDpr)); + } +} + TEST_F(ClientHintsPreferencesTest, PersistentHints) { struct TestCase { bool enable_persistent_runtime_feature;
diff --git a/third_party/WebKit/Source/platform/loader/fetch/FetchContext.cpp b/third_party/WebKit/Source/platform/loader/fetch/FetchContext.cpp index 6b02f0a..602064aa 100644 --- a/third_party/WebKit/Source/platform/loader/fetch/FetchContext.cpp +++ b/third_party/WebKit/Source/platform/loader/fetch/FetchContext.cpp
@@ -109,8 +109,6 @@ void FetchContext::AddResourceTiming(const ResourceTimingInfo&) {} -void FetchContext::SendImagePing(const KURL&) {} - void FetchContext::AddWarningConsoleMessage(const String&, LogSource) const {} void FetchContext::AddErrorConsoleMessage(const String&, LogSource) const {}
diff --git a/third_party/WebKit/Source/platform/loader/fetch/FetchContext.h b/third_party/WebKit/Source/platform/loader/fetch/FetchContext.h index e8900971..213ab28c 100644 --- a/third_party/WebKit/Source/platform/loader/fetch/FetchContext.h +++ b/third_party/WebKit/Source/platform/loader/fetch/FetchContext.h
@@ -203,11 +203,9 @@ virtual bool IsMainFrame() const { return true; } virtual bool DefersLoading() const { return false; } virtual bool IsLoadComplete() const { return false; } - virtual bool PageDismissalEventBeingDispatched() const { return false; } virtual bool UpdateTimingInfoForIFrameNavigation(ResourceTimingInfo*) { return false; } - virtual void SendImagePing(const KURL&); virtual void AddWarningConsoleMessage(const String&, LogSource) const; virtual void AddErrorConsoleMessage(const String&, LogSource) const;
diff --git a/third_party/WebKit/Source/platform/loader/fetch/ResourceFetcher.cpp b/third_party/WebKit/Source/platform/loader/fetch/ResourceFetcher.cpp index c53a4e87..e50a831 100644 --- a/third_party/WebKit/Source/platform/loader/fetch/ResourceFetcher.cpp +++ b/third_party/WebKit/Source/platform/loader/fetch/ResourceFetcher.cpp
@@ -120,6 +120,7 @@ return ResourceLoadPriority::kVeryHigh; case Resource::kXSLStyleSheet: DCHECK(RuntimeEnabledFeatures::XSLTEnabled()); + FALLTHROUGH; case Resource::kRaw: case Resource::kImportResource: case Resource::kScript: @@ -244,6 +245,7 @@ return WebURLRequest::kRequestContextHyperlink; case Resource::kXSLStyleSheet: DCHECK(RuntimeEnabledFeatures::XSLTEnabled()); + FALLTHROUGH; case Resource::kCSSStyleSheet: return WebURLRequest::kRequestContextStyle; case Resource::kScript: @@ -757,7 +759,7 @@ switch (policy) { case kReload: GetMemoryCache()->Remove(resource); - // Fall through + FALLTHROUGH; case kLoad: resource = CreateResourceForLoading(params, factory); break;
diff --git a/third_party/WebKit/Source/platform/loader/fetch/ResourceFetcherTest.cpp b/third_party/WebKit/Source/platform/loader/fetch/ResourceFetcherTest.cpp index a93e48fd..f4fc1b94 100644 --- a/third_party/WebKit/Source/platform/loader/fetch/ResourceFetcherTest.cpp +++ b/third_party/WebKit/Source/platform/loader/fetch/ResourceFetcherTest.cpp
@@ -469,6 +469,19 @@ resource->GetResourceRequest().Priority()); } +TEST_F(ResourceFetcherTest, PingPriority) { + KURL url("http://127.0.0.1:8000/foo.png"); + RegisterMockedURLLoad(url); + + ResourceFetcher* fetcher = ResourceFetcher::Create(Context()); + ResourceRequest resource_request(url); + resource_request.SetRequestContext(WebURLRequest::kRequestContextPing); + FetchParameters fetch_params(resource_request); + Resource* resource = RawResource::Fetch(fetch_params, fetcher, nullptr); + EXPECT_EQ(ResourceLoadPriority::kVeryLow, + resource->GetResourceRequest().Priority()); +} + TEST_F(ResourceFetcherTest, PreloadResourceTwice) { ResourceFetcher* fetcher = ResourceFetcher::Create(Context());
diff --git a/third_party/WebKit/Source/platform/loader/fetch/ResourceResponseTest.cpp b/third_party/WebKit/Source/platform/loader/fetch/ResourceResponseTest.cpp index 12eace9..813f85e 100644 --- a/third_party/WebKit/Source/platform/loader/fetch/ResourceResponseTest.cpp +++ b/third_party/WebKit/Source/platform/loader/fetch/ResourceResponseTest.cpp
@@ -77,7 +77,8 @@ ResourceResponse response(CreateTestResponse()); RunHeaderRelatedTest(response); std::unique_ptr<WebThread> thread = Platform::Current()->CreateThread( - WebThreadCreationParams("WorkerThread")); + WebThreadCreationParams(WebThreadType::kTestThread) + .SetThreadName("WorkerThread")); PostCrossThreadTask(*thread->GetWebTaskRunner(), FROM_HERE, CrossThreadBind(&RunInThread)); thread.reset();
diff --git a/third_party/WebKit/Source/platform/mojo/BigString.typemap b/third_party/WebKit/Source/platform/mojo/BigString.typemap new file mode 100644 index 0000000..c3aeb4b0 --- /dev/null +++ b/third_party/WebKit/Source/platform/mojo/BigString.typemap
@@ -0,0 +1,10 @@ +# 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. + +mojom = "//mojo/public/mojom/base/big_string.mojom" +public_headers = [ "//third_party/WebKit/Source/platform/wtf/text/WTFString.h" ] +traits_headers = + [ "//third_party/WebKit/Source/platform/mojo/BigStringMojomTraits.h" ] +type_mappings = + [ "mojo_base.mojom.BigString=WTF::String[nullable_is_same_type]" ]
diff --git a/third_party/WebKit/Source/platform/mojo/BigStringMojomTraits.cpp b/third_party/WebKit/Source/platform/mojo/BigStringMojomTraits.cpp new file mode 100644 index 0000000..c930936 --- /dev/null +++ b/third_party/WebKit/Source/platform/mojo/BigStringMojomTraits.cpp
@@ -0,0 +1,45 @@ +// 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. + +#include "platform/mojo/BigStringMojomTraits.h" + +#include <cstring> + +#include "base/containers/span.h" +#include "mojo/public/cpp/base/big_buffer.h" +#include "mojo/public/cpp/base/big_buffer_struct_traits.h" +#include "platform/wtf/text/StringUTF8Adaptor.h" + +namespace mojo { + +// static +mojo_base::BigBuffer StructTraits<mojo_base::mojom::BigStringDataView, + WTF::String>::data(const WTF::String& input) { + WTF::StringUTF8Adaptor adaptor(input); + return mojo_base::BigBuffer( + base::make_span(reinterpret_cast<const uint8_t*>(adaptor.Data()), + adaptor.length() * sizeof(char))); +} + +// static +bool StructTraits<mojo_base::mojom::BigStringDataView, WTF::String>::Read( + mojo_base::mojom::BigStringDataView data, + WTF::String* out) { + mojo_base::BigBuffer buffer; + if (!data.ReadData(&buffer)) + return false; + size_t size = buffer.size(); + if (size % sizeof(char)) + return false; + // An empty |mojo_base::BigBuffer| may have a null |data()| if empty. + if (!size) { + *out = g_empty_string; + } else { + *out = WTF::String::FromUTF8(reinterpret_cast<const char*>(buffer.data()), + size / sizeof(char)); + } + return true; +} + +} // namespace mojo
diff --git a/third_party/WebKit/Source/platform/mojo/BigStringMojomTraits.h b/third_party/WebKit/Source/platform/mojo/BigStringMojomTraits.h new file mode 100644 index 0000000..2c5eb013 --- /dev/null +++ b/third_party/WebKit/Source/platform/mojo/BigStringMojomTraits.h
@@ -0,0 +1,30 @@ +// 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. + +#ifndef BigStringMojomTraits_h +#define BigStringMojomTraits_h + +#include "mojo/public/cpp/bindings/struct_traits.h" +#include "mojo/public/mojom/base/big_string.mojom-blink.h" +#include "platform/PlatformExport.h" + +namespace mojo_base { +class BigBuffer; +} + +namespace mojo { + +template <> +struct PLATFORM_EXPORT + StructTraits<mojo_base::mojom::BigStringDataView, WTF::String> { + static bool IsNull(const WTF::String& input) { return input.IsNull(); } + static void SetToNull(WTF::String* output) { *output = WTF::String(); } + + static mojo_base::BigBuffer data(const WTF::String& input); + static bool Read(mojo_base::mojom::BigStringDataView, WTF::String* out); +}; + +} // namespace mojo + +#endif // BigStringMojomTraits_h
diff --git a/third_party/WebKit/Source/platform/mojo/BigStringMojomTraitsTest.cpp b/third_party/WebKit/Source/platform/mojo/BigStringMojomTraitsTest.cpp new file mode 100644 index 0000000..3745e44 --- /dev/null +++ b/third_party/WebKit/Source/platform/mojo/BigStringMojomTraitsTest.cpp
@@ -0,0 +1,71 @@ +// 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 "base/rand_util.h" +#include "mojo/common/test_common_custom_types.mojom-blink.h" +#include "mojo/public/cpp/base/big_buffer_struct_traits.h" +#include "mojo/public/cpp/test_support/test_utils.h" +#include "mojo/public/mojom/base/big_string.mojom-blink.h" +#include "platform/wtf/text/WTFString.h" +#include "testing/gtest/include/gtest/gtest.h" +#include "third_party/WebKit/Source/platform/mojo/BigStringMojomTraits.h" +#include "third_party/WebKit/Source/platform/wtf/text/WTFString.h" + +namespace blink { + +TEST(BigStringMojomTraitsTest, BigString_Null) { + String str; + String output; + + ASSERT_TRUE( + mojo::test::SerializeAndDeserialize<mojo_base::mojom::blink::BigString>( + &str, &output)); + ASSERT_EQ(str, output); +} + +TEST(BigStringMojomTraitsTest, BigString_Empty) { + String str = String::FromUTF8(""); + String output; + + ASSERT_TRUE( + mojo::test::SerializeAndDeserialize<mojo_base::mojom::blink::BigString>( + &str, &output)); + ASSERT_EQ(str, output); +} + +TEST(BigStringMojomTraitsTest, BigString_Short) { + String str = String::FromUTF8("hello world"); + ASSERT_TRUE(str.Is8Bit()); + String output; + + ASSERT_TRUE( + mojo::test::SerializeAndDeserialize<mojo_base::mojom::blink::BigString>( + &str, &output)); + ASSERT_EQ(str, output); + + // Replace the "o"s in "hello world" with "o"s with acute, so that |str| is + // 16-bit. + str = String::FromUTF8("hell\xC3\xB3 w\xC3\xB3rld"); + ASSERT_FALSE(str.Is8Bit()); + + ASSERT_TRUE( + mojo::test::SerializeAndDeserialize<mojo_base::mojom::blink::BigString>( + &str, &output)); + ASSERT_EQ(str, output); +} + +TEST(BigStringMojomTraitsTest, BigString_Long) { + WTF::Vector<char> random_latin1_string(1024 * 1024); + base::RandBytes(random_latin1_string.data(), random_latin1_string.size()); + + String str(random_latin1_string.data(), random_latin1_string.size()); + String output; + + ASSERT_TRUE( + mojo::test::SerializeAndDeserialize<mojo_base::mojom::blink::BigString>( + &str, &output)); + ASSERT_EQ(str, output); +} + +} // namespace blink
diff --git a/third_party/WebKit/Source/platform/mojo/DEPS b/third_party/WebKit/Source/platform/mojo/DEPS index c48934f..25ea4bf1 100644 --- a/third_party/WebKit/Source/platform/mojo/DEPS +++ b/third_party/WebKit/Source/platform/mojo/DEPS
@@ -7,6 +7,7 @@ "+base/observer_list.h", "+base/strings/string16.h", "+mojo/public/cpp/bindings/binding.h", + "+mojo/common/big_string.mojom-blink.h", "+mojo/common/string16.mojom-blink.h", "+mojo/common/test_common_custom_types.mojom-blink.h", "+services/network/public/interfaces/fetch_api.mojom-blink.h",
diff --git a/third_party/WebKit/Source/platform/mojo/OWNERS b/third_party/WebKit/Source/platform/mojo/OWNERS index e482ac73..3e025c8 100644 --- a/third_party/WebKit/Source/platform/mojo/OWNERS +++ b/third_party/WebKit/Source/platform/mojo/OWNERS
@@ -1,3 +1,5 @@ +per-file *MojomTraits*.*=set noparent +per-file *MojomTraits*.*=file://ipc/SECURITY_OWNERS per-file *StructTraits*.*=set noparent per-file *StructTraits*.*=file://ipc/SECURITY_OWNERS per-file *.typemap=set noparent
diff --git a/third_party/WebKit/Source/platform/mojo/blink_typemaps.gni b/third_party/WebKit/Source/platform/mojo/blink_typemaps.gni index eacb98e..05728df4 100644 --- a/third_party/WebKit/Source/platform/mojo/blink_typemaps.gni +++ b/third_party/WebKit/Source/platform/mojo/blink_typemaps.gni
@@ -7,7 +7,9 @@ "//mojo/common/values.typemap", "//third_party/WebKit/Source/core/messaging/BlinkCloneableMessage.typemap", "//third_party/WebKit/Source/core/messaging/BlinkTransferableMessage.typemap", + "//third_party/WebKit/Source/platform/blob/SerializedBlob.typemap", "//third_party/WebKit/Source/platform/mojo/BigBuffer.typemap", + "//third_party/WebKit/Source/platform/mojo/BigString.typemap", "//third_party/WebKit/Source/platform/mojo/File.typemap", "//third_party/WebKit/Source/platform/mojo/Geometry.typemap", "//third_party/WebKit/Source/platform/mojo/KURL.typemap",
diff --git a/third_party/WebKit/Source/platform/runtime_enabled_features.json5 b/third_party/WebKit/Source/platform/runtime_enabled_features.json5 index 8fb215c..268397b 100644 --- a/third_party/WebKit/Source/platform/runtime_enabled_features.json5 +++ b/third_party/WebKit/Source/platform/runtime_enabled_features.json5
@@ -169,6 +169,9 @@ name: "ClientPlaceholdersForServerLoFi", }, { + name: "CodeCacheAfterExecute" + }, + { name: "CompositedSelectionUpdate", }, { @@ -300,10 +303,6 @@ status: "experimental", }, { - name: "CSSVariableFonts", - status: "stable", - }, - { name: "CSSVariables2", status: "experimental", }, @@ -313,7 +312,7 @@ }, { name: "CustomElementsBuiltin", - status: "test", + status: "experimental", }, { name: "CustomUserTiming", @@ -397,18 +396,21 @@ }, { name: "FeaturePolicyAutoplayFeature", - status: "stable" + status: "stable", + depends_on: ["FeaturePolicy"] }, { name: "FeaturePolicyExperimentalFeatures", }, { name: "FeaturePolicyForPermissions", - status: "stable" + status: "stable", + depends_on: ["FeaturePolicy"] }, { name: "FeaturePolicyJavaScriptInterface", - status: "experimental" + status: "experimental", + depends_on: ["FeaturePolicy"] }, { name: "FetchRequestCache",
diff --git a/third_party/WebKit/Source/platform/scheduler/BUILD.gn b/third_party/WebKit/Source/platform/scheduler/BUILD.gn index eac970ce..9912e3b 100644 --- a/third_party/WebKit/Source/platform/scheduler/BUILD.gn +++ b/third_party/WebKit/Source/platform/scheduler/BUILD.gn
@@ -44,6 +44,7 @@ "child/compositor_metrics_helper.h", "child/compositor_worker_scheduler.cc", "child/compositor_worker_scheduler.h", + "child/features.h", "child/idle_canceled_delayed_task_sweeper.cc", "child/idle_canceled_delayed_task_sweeper.h", "child/idle_helper.cc",
diff --git a/third_party/WebKit/Source/platform/scheduler/child/compositor_metrics_helper.cc b/third_party/WebKit/Source/platform/scheduler/child/compositor_metrics_helper.cc index 19ab3b1..d3b3a64 100644 --- a/third_party/WebKit/Source/platform/scheduler/child/compositor_metrics_helper.cc +++ b/third_party/WebKit/Source/platform/scheduler/child/compositor_metrics_helper.cc
@@ -8,7 +8,7 @@ namespace scheduler { CompositorMetricsHelper::CompositorMetricsHelper() - : MetricsHelper(ThreadType::kCompositorThread) {} + : MetricsHelper(WebThreadType::kCompositorThread) {} CompositorMetricsHelper::~CompositorMetricsHelper() {}
diff --git a/third_party/WebKit/Source/platform/scheduler/child/compositor_worker_scheduler.cc b/third_party/WebKit/Source/platform/scheduler/child/compositor_worker_scheduler.cc index 3e89efa..a8fc595 100644 --- a/third_party/WebKit/Source/platform/scheduler/child/compositor_worker_scheduler.cc +++ b/third_party/WebKit/Source/platform/scheduler/child/compositor_worker_scheduler.cc
@@ -98,7 +98,7 @@ return base::TimeTicks::Now(); } -void CompositorWorkerScheduler::SetThreadType(ThreadType thread_type) {} +void CompositorWorkerScheduler::SetThreadType(WebThreadType thread_type) {} } // namespace scheduler } // namespace blink
diff --git a/third_party/WebKit/Source/platform/scheduler/child/compositor_worker_scheduler.h b/third_party/WebKit/Source/platform/scheduler/child/compositor_worker_scheduler.h index e069846f..5290b92 100644 --- a/third_party/WebKit/Source/platform/scheduler/child/compositor_worker_scheduler.h +++ b/third_party/WebKit/Source/platform/scheduler/child/compositor_worker_scheduler.h
@@ -12,7 +12,7 @@ #include "platform/scheduler/child/compositor_metrics_helper.h" #include "platform/scheduler/child/worker_scheduler.h" #include "platform/scheduler/util/task_duration_metric_reporter.h" -#include "platform/scheduler/util/thread_type.h" +#include "public/platform/WebThreadType.h" #include "public/platform/scheduler/child/single_thread_idle_task_runner.h" namespace base { @@ -40,7 +40,7 @@ base::TimeTicks start, base::TimeTicks end, base::Optional<base::TimeDelta> thread_time) override; - void SetThreadType(ThreadType thread_type) override; + void SetThreadType(WebThreadType thread_type) override; // ChildScheduler: scoped_refptr<base::SingleThreadTaskRunner> DefaultTaskRunner() override;
diff --git a/third_party/WebKit/Source/platform/scheduler/child/features.h b/third_party/WebKit/Source/platform/scheduler/child/features.h new file mode 100644 index 0000000..f3a49d2f --- /dev/null +++ b/third_party/WebKit/Source/platform/scheduler/child/features.h
@@ -0,0 +1,19 @@ +// 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. + +#ifndef THIRD_PARTY_WEBKIT_SOURCE_PLATFORM_SCHEDULER_CHILD_FEATURES_H_ +#define THIRD_PARTY_WEBKIT_SOURCE_PLATFORM_SCHEDULER_CHILD_FEATURES_H_ + +#include "base/feature_list.h" + +namespace blink { +namespace scheduler { + +const base::Feature kHighPriorityInput{"BlinkSchedulerHighPriorityInput", + base::FEATURE_DISABLED_BY_DEFAULT}; + +} // namespace scheduler +} // namespace blink + +#endif // THIRD_PARTY_WEBKIT_SOURCE_PLATFORM_SCHEDULER_CHILD_FEATURES_H_
diff --git a/third_party/WebKit/Source/platform/scheduler/child/metrics_helper.cc b/third_party/WebKit/Source/platform/scheduler/child/metrics_helper.cc index ce59e62..67143ab 100644 --- a/third_party/WebKit/Source/platform/scheduler/child/metrics_helper.cc +++ b/third_party/WebKit/Source/platform/scheduler/child/metrics_helper.cc
@@ -19,7 +19,7 @@ } // namespace -MetricsHelper::MetricsHelper(ThreadType thread_type) +MetricsHelper::MetricsHelper(WebThreadType thread_type) : thread_type_(thread_type), thread_task_duration_reporter_( "RendererScheduler.TaskDurationPerThreadType"), @@ -80,7 +80,7 @@ } } -void MetricsHelper::SetThreadType(ThreadType thread_type) { +void MetricsHelper::SetThreadType(WebThreadType thread_type) { thread_type_ = thread_type; }
diff --git a/third_party/WebKit/Source/platform/scheduler/child/metrics_helper.h b/third_party/WebKit/Source/platform/scheduler/child/metrics_helper.h index 937a0ea..c2586dd 100644 --- a/third_party/WebKit/Source/platform/scheduler/child/metrics_helper.h +++ b/third_party/WebKit/Source/platform/scheduler/child/metrics_helper.h
@@ -9,7 +9,7 @@ #include "base/time/time.h" #include "platform/scheduler/base/task_queue.h" #include "platform/scheduler/util/task_duration_metric_reporter.h" -#include "platform/scheduler/util/thread_type.h" +#include "public/platform/WebThreadType.h" namespace blink { namespace scheduler { @@ -27,7 +27,7 @@ // own instantiation of this class. class PLATFORM_EXPORT MetricsHelper { public: - explicit MetricsHelper(ThreadType thread_type); + explicit MetricsHelper(WebThreadType thread_type); ~MetricsHelper(); protected: @@ -44,21 +44,21 @@ base::TimeTicks end_time, base::Optional<base::TimeDelta> thread_time); - void SetThreadType(ThreadType thread_type); + void SetThreadType(WebThreadType thread_type); protected: - ThreadType thread_type_; + WebThreadType thread_type_; private: - TaskDurationMetricReporter<ThreadType> thread_task_duration_reporter_; - TaskDurationMetricReporter<ThreadType> thread_task_cpu_duration_reporter_; - TaskDurationMetricReporter<ThreadType> + TaskDurationMetricReporter<WebThreadType> thread_task_duration_reporter_; + TaskDurationMetricReporter<WebThreadType> thread_task_cpu_duration_reporter_; + TaskDurationMetricReporter<WebThreadType> foreground_thread_task_duration_reporter_; - TaskDurationMetricReporter<ThreadType> + TaskDurationMetricReporter<WebThreadType> foreground_thread_task_cpu_duration_reporter_; - TaskDurationMetricReporter<ThreadType> + TaskDurationMetricReporter<WebThreadType> background_thread_task_duration_reporter_; - TaskDurationMetricReporter<ThreadType> + TaskDurationMetricReporter<WebThreadType> background_thread_task_cpu_duration_reporter_; DISALLOW_COPY_AND_ASSIGN(MetricsHelper);
diff --git a/third_party/WebKit/Source/platform/scheduler/child/metrics_helper_unittest.cc b/third_party/WebKit/Source/platform/scheduler/child/metrics_helper_unittest.cc index 12006486..96874736 100644 --- a/third_party/WebKit/Source/platform/scheduler/child/metrics_helper_unittest.cc +++ b/third_party/WebKit/Source/platform/scheduler/child/metrics_helper_unittest.cc
@@ -14,7 +14,8 @@ class MetricsHelperForTest : public MetricsHelper { public: - MetricsHelperForTest(ThreadType thread_type) : MetricsHelper(thread_type) {} + MetricsHelperForTest(WebThreadType thread_type) + : MetricsHelper(thread_type) {} ~MetricsHelperForTest() = default; using MetricsHelper::RecordCommonTaskMetrics; @@ -25,9 +26,9 @@ TEST(MetricsHelperTest, TaskDurationPerThreadType) { base::HistogramTester histogram_tester; - MetricsHelperForTest main_thread_metrics(ThreadType::kMainThread); - MetricsHelperForTest compositor_metrics(ThreadType::kCompositorThread); - MetricsHelperForTest worker_metrics(ThreadType::kUnspecifiedWorkerThread); + MetricsHelperForTest main_thread_metrics(WebThreadType::kMainThread); + MetricsHelperForTest compositor_metrics(WebThreadType::kCompositorThread); + MetricsHelperForTest worker_metrics(WebThreadType::kUnspecifiedWorkerThread); TaskQueue::Task fake_task( (TaskQueue::PostedTask(base::OnceClosure(), base::Location())), @@ -58,19 +59,19 @@ histogram_tester.GetAllSamples( "RendererScheduler.TaskDurationPerThreadType"), testing::UnorderedElementsAre( - base::Bucket(static_cast<int>(ThreadType::kMainThread), 40), - base::Bucket(static_cast<int>(ThreadType::kCompositorThread), 170), - base::Bucket(static_cast<int>(ThreadType::kUnspecifiedWorkerThread), - 115))); + base::Bucket(static_cast<int>(WebThreadType::kMainThread), 40), + base::Bucket(static_cast<int>(WebThreadType::kCompositorThread), 170), + base::Bucket( + static_cast<int>(WebThreadType::kUnspecifiedWorkerThread), 115))); EXPECT_THAT( histogram_tester.GetAllSamples( "RendererScheduler.TaskCPUDurationPerThreadType"), testing::UnorderedElementsAre( - base::Bucket(static_cast<int>(ThreadType::kMainThread), 15), - base::Bucket(static_cast<int>(ThreadType::kCompositorThread), 5), - base::Bucket(static_cast<int>(ThreadType::kUnspecifiedWorkerThread), - 25))); + base::Bucket(static_cast<int>(WebThreadType::kMainThread), 15), + base::Bucket(static_cast<int>(WebThreadType::kCompositorThread), 5), + base::Bucket( + static_cast<int>(WebThreadType::kUnspecifiedWorkerThread), 25))); } } // namespace scheduler
diff --git a/third_party/WebKit/Source/platform/scheduler/child/worker_metrics_helper.cc b/third_party/WebKit/Source/platform/scheduler/child/worker_metrics_helper.cc index 625f604..e043175 100644 --- a/third_party/WebKit/Source/platform/scheduler/child/worker_metrics_helper.cc +++ b/third_party/WebKit/Source/platform/scheduler/child/worker_metrics_helper.cc
@@ -8,7 +8,7 @@ namespace scheduler { WorkerMetricsHelper::WorkerMetricsHelper() - : MetricsHelper(ThreadType::kUnspecifiedWorkerThread), + : MetricsHelper(WebThreadType::kUnspecifiedWorkerThread), dedicated_worker_per_task_type_duration_reporter_( "RendererScheduler.TaskDurationPerTaskType.DedicatedWorker"), dedicated_worker_per_task_type_cpu_duration_reporter_( @@ -28,7 +28,7 @@ MetricsHelper::RecordCommonTaskMetrics(queue, task, start_time, end_time, thread_time); - if (thread_type_ == ThreadType::kDedicatedWorkerThread) { + if (thread_type_ == WebThreadType::kDedicatedWorkerThread) { base::Optional<TaskType> task_type = task.task_type(); dedicated_worker_per_task_type_duration_reporter_.RecordTask( task_type ? task_type.value() : static_cast<TaskType>(0),
diff --git a/third_party/WebKit/Source/platform/scheduler/child/worker_scheduler.h b/third_party/WebKit/Source/platform/scheduler/child/worker_scheduler.h index 974ad57..c4e3796 100644 --- a/third_party/WebKit/Source/platform/scheduler/child/worker_scheduler.h +++ b/third_party/WebKit/Source/platform/scheduler/child/worker_scheduler.h
@@ -13,7 +13,7 @@ #include "platform/scheduler/base/task_queue.h" #include "platform/scheduler/child/worker_scheduler_helper.h" #include "platform/scheduler/child/worker_task_queue.h" -#include "platform/scheduler/util/thread_type.h" +#include "public/platform/WebThreadType.h" #include "public/platform/scheduler/child/child_scheduler.h" #include "public/platform/scheduler/child/single_thread_idle_task_runner.h" @@ -34,7 +34,7 @@ // initialization needed such as initializing idle period detection. virtual void Init() = 0; - virtual void SetThreadType(ThreadType thread_type) = 0; + virtual void SetThreadType(WebThreadType thread_type) = 0; virtual void OnTaskCompleted(WorkerTaskQueue* worker_task_queue, const TaskQueue::Task& task,
diff --git a/third_party/WebKit/Source/platform/scheduler/child/worker_scheduler_impl.cc b/third_party/WebKit/Source/platform/scheduler/child/worker_scheduler_impl.cc index 9f7905c..43dd670 100644 --- a/third_party/WebKit/Source/platform/scheduler/child/worker_scheduler_impl.cc +++ b/third_party/WebKit/Source/platform/scheduler/child/worker_scheduler_impl.cc
@@ -174,8 +174,8 @@ load_tracker_.RecordTaskTime(start_time_ticks, end_time_ticks); } -void WorkerSchedulerImpl::SetThreadType(ThreadType thread_type) { - DCHECK_NE(thread_type, ThreadType::kMainThread); +void WorkerSchedulerImpl::SetThreadType(WebThreadType thread_type) { + DCHECK_NE(thread_type, WebThreadType::kMainThread); worker_metrics_helper_.SetThreadType(thread_type); }
diff --git a/third_party/WebKit/Source/platform/scheduler/child/worker_scheduler_impl.h b/third_party/WebKit/Source/platform/scheduler/child/worker_scheduler_impl.h index 1001f81..23b486c 100644 --- a/third_party/WebKit/Source/platform/scheduler/child/worker_scheduler_impl.h +++ b/third_party/WebKit/Source/platform/scheduler/child/worker_scheduler_impl.h
@@ -15,7 +15,7 @@ #include "platform/scheduler/child/worker_scheduler.h" #include "platform/scheduler/util/task_duration_metric_reporter.h" #include "platform/scheduler/util/thread_load_tracker.h" -#include "platform/scheduler/util/thread_type.h" +#include "public/platform/WebThreadType.h" namespace blink { namespace scheduler { @@ -57,7 +57,7 @@ SchedulerHelper* GetSchedulerHelperForTesting(); base::TimeTicks CurrentIdleTaskDeadlineForTesting() const; - void SetThreadType(ThreadType thread_type) override; + void SetThreadType(WebThreadType thread_type) override; protected: // IdleHelper::Delegate implementation:
diff --git a/third_party/WebKit/Source/platform/scheduler/renderer/main_thread_scheduler_helper.cc b/third_party/WebKit/Source/platform/scheduler/renderer/main_thread_scheduler_helper.cc index 68e90fc..cd22631 100644 --- a/third_party/WebKit/Source/platform/scheduler/renderer/main_thread_scheduler_helper.cc +++ b/third_party/WebKit/Source/platform/scheduler/renderer/main_thread_scheduler_helper.cc
@@ -52,8 +52,12 @@ scoped_refptr<MainThreadTaskQueue> MainThreadSchedulerHelper::NewTaskQueue( const MainThreadTaskQueue::QueueCreationParams& params) { - return task_queue_manager_->CreateTaskQueue<MainThreadTaskQueue>( - params.spec, params, renderer_scheduler_); + scoped_refptr<MainThreadTaskQueue> task_queue = + task_queue_manager_->CreateTaskQueue<MainThreadTaskQueue>( + params.spec, params, renderer_scheduler_); + if (params.used_for_important_tasks) + task_queue->SetQueuePriority(TaskQueue::QueuePriority::kHighPriority); + return task_queue; } } // namespace scheduler
diff --git a/third_party/WebKit/Source/platform/scheduler/renderer/main_thread_task_queue.cc b/third_party/WebKit/Source/platform/scheduler/renderer/main_thread_task_queue.cc index 9e78007..54f1efec6 100644 --- a/third_party/WebKit/Source/platform/scheduler/renderer/main_thread_task_queue.cc +++ b/third_party/WebKit/Source/platform/scheduler/renderer/main_thread_task_queue.cc
@@ -100,7 +100,7 @@ can_be_throttled_(params.can_be_throttled), can_be_paused_(params.can_be_paused), can_be_stopped_(params.can_be_stopped), - used_for_control_tasks_(params.used_for_control_tasks), + used_for_important_tasks_(params.used_for_important_tasks), renderer_scheduler_(renderer_scheduler), web_frame_scheduler_(nullptr) { if (GetTaskQueueImpl()) {
diff --git a/third_party/WebKit/Source/platform/scheduler/renderer/main_thread_task_queue.h b/third_party/WebKit/Source/platform/scheduler/renderer/main_thread_task_queue.h index 010f091..c773bd82 100644 --- a/third_party/WebKit/Source/platform/scheduler/renderer/main_thread_task_queue.h +++ b/third_party/WebKit/Source/platform/scheduler/renderer/main_thread_task_queue.h
@@ -76,7 +76,7 @@ can_be_throttled(false), can_be_paused(false), can_be_stopped(false), - used_for_control_tasks(false) {} + used_for_important_tasks(false) {} QueueCreationParams SetCanBeDeferred(bool value) { can_be_blocked = value; @@ -98,8 +98,8 @@ return *this; } - QueueCreationParams SetUsedForControlTasks(bool value) { - used_for_control_tasks = value; + QueueCreationParams SetUsedForImportantTasks(bool value) { + used_for_important_tasks = value; return *this; } @@ -133,7 +133,7 @@ bool can_be_throttled; bool can_be_paused; bool can_be_stopped; - bool used_for_control_tasks; + bool used_for_important_tasks; }; ~MainThreadTaskQueue() override; @@ -150,7 +150,7 @@ bool CanBeStopped() const { return can_be_stopped_; } - bool UsedForControlTasks() const { return used_for_control_tasks_; } + bool UsedForImportantTasks() const { return used_for_important_tasks_; } void OnTaskStarted(const TaskQueue::Task& task, base::TimeTicks start); @@ -182,7 +182,7 @@ const bool can_be_throttled_; const bool can_be_paused_; const bool can_be_stopped_; - const bool used_for_control_tasks_; + const bool used_for_important_tasks_; // Needed to notify renderer scheduler about completed tasks. RendererSchedulerImpl* renderer_scheduler_; // NOT OWNED
diff --git a/third_party/WebKit/Source/platform/scheduler/renderer/queueing_time_estimator.cc b/third_party/WebKit/Source/platform/scheduler/renderer/queueing_time_estimator.cc index 84d0029..8bd8bf0a 100644 --- a/third_party/WebKit/Source/platform/scheduler/renderer/queueing_time_estimator.cc +++ b/third_party/WebKit/Source/platform/scheduler/renderer/queueing_time_estimator.cc
@@ -16,8 +16,8 @@ namespace { #define FRAME_STATUS_PREFIX \ - "RendererScheduler.ExpectedQueueingTimeByFrameStatus." -#define TASK_QUEUE_PREFIX "RendererScheduler.ExpectedQueueingTimeByTaskQueue." + "RendererScheduler.ExpectedQueueingTimeByFrameStatus2." +#define TASK_QUEUE_PREFIX "RendererScheduler.ExpectedQueueingTimeByTaskQueue2." // On Windows, when a computer sleeps, we may end up getting extremely long // tasks or idling. We'll ignore tasks longer than |kInvalidPeriodThreshold|.
diff --git a/third_party/WebKit/Source/platform/scheduler/renderer/queueing_time_estimator_unittest.cc b/third_party/WebKit/Source/platform/scheduler/renderer/queueing_time_estimator_unittest.cc index 0765de6..9759d9d7 100644 --- a/third_party/WebKit/Source/platform/scheduler/renderer/queueing_time_estimator_unittest.cc +++ b/third_party/WebKit/Source/platform/scheduler/renderer/queueing_time_estimator_unittest.cc
@@ -33,7 +33,7 @@ UMA_HISTOGRAM_TIMES("RendererScheduler.ExpectedTaskQueueingDuration", queueing_time); UMA_HISTOGRAM_CUSTOM_COUNTS( - "RendererScheduler.ExpectedTaskQueueingDuration2", + "RendererScheduler.ExpectedTaskQueueingDuration3", queueing_time.InMicroseconds(), RendererSchedulerImpl::kMinExpectedQueueingTimeBucket, RendererSchedulerImpl::kMaxExpectedQueueingTimeBucket, @@ -162,7 +162,7 @@ std::vector<BucketExpectation> expected = {{300, 1}}; TestHistogram("RendererScheduler.ExpectedTaskQueueingDuration", 1, expected); std::vector<BucketExpectation> fine_grained = GetFineGrained(expected); - TestHistogram("RendererScheduler.ExpectedTaskQueueingDuration2", 1, + TestHistogram("RendererScheduler.ExpectedTaskQueueingDuration3", 1, fine_grained); } @@ -201,10 +201,10 @@ std::vector<BucketExpectation> expected = { {900, 1}, {5500, 1}, {7600, 1}, {10500, 2}}; TestHistogram("RendererScheduler.ExpectedTaskQueueingDuration", 5, expected); - // Split here is different: 4 values go into the highest bucket. - std::vector<BucketExpectation> fine_grained = {{900 * 1000, 1}, - {5500 * 1000, 4}}; - TestHistogram("RendererScheduler.ExpectedTaskQueueingDuration2", 5, + // Split here is different: only 7600 and 10500 get grouped up. + std::vector<BucketExpectation> fine_grained = { + {900 * 1000, 1}, {5500 * 1000, 1}, {7600 * 1000, 2}, {15500 * 1000, 1}}; + TestHistogram("RendererScheduler.ExpectedTaskQueueingDuration3", 5, fine_grained); } @@ -298,7 +298,7 @@ histogram_tester.ExpectTotalCount( "RendererScheduler.ExpectedTaskQueueingDuration", 0); histogram_tester.ExpectTotalCount( - "RendererScheduler.ExpectedTaskQueueingDuration2", 0); + "RendererScheduler.ExpectedTaskQueueingDuration3", 0); } // Estimate @@ -337,7 +337,7 @@ EXPECT_EQ(base::TimeDelta::FromMilliseconds(25), estimated_queueing_time); std::vector<BucketExpectation> expected = {{0, 1}}; TestHistogram("RendererScheduler.ExpectedTaskQueueingDuration", 1, expected); - TestHistogram("RendererScheduler.ExpectedTaskQueueingDuration2", 1, expected); + TestHistogram("RendererScheduler.ExpectedTaskQueueingDuration3", 1, expected); } // Tasks containing nested run loops may be extremely long without @@ -374,7 +374,7 @@ std::vector<BucketExpectation> expected = {{0, 1}, {100, 1}}; TestHistogram("RendererScheduler.ExpectedTaskQueueingDuration", 2, expected); std::vector<BucketExpectation> fine_grained = GetFineGrained(expected); - TestHistogram("RendererScheduler.ExpectedTaskQueueingDuration2", 2, + TestHistogram("RendererScheduler.ExpectedTaskQueueingDuration3", 2, fine_grained); } @@ -425,7 +425,7 @@ std::vector<BucketExpectation> expected = {{100, 2}}; TestHistogram("RendererScheduler.ExpectedTaskQueueingDuration", 2, expected); std::vector<BucketExpectation> fine_grained = GetFineGrained(expected); - TestHistogram("RendererScheduler.ExpectedTaskQueueingDuration2", 2, + TestHistogram("RendererScheduler.ExpectedTaskQueueingDuration3", 2, fine_grained); } @@ -474,7 +474,7 @@ std::vector<BucketExpectation> expected = {{100, 2}}; TestHistogram("RendererScheduler.ExpectedTaskQueueingDuration", 2, expected); std::vector<BucketExpectation> fine_grained = GetFineGrained(expected); - TestHistogram("RendererScheduler.ExpectedTaskQueueingDuration2", 2, + TestHistogram("RendererScheduler.ExpectedTaskQueueingDuration3", 2, fine_grained); } @@ -573,7 +573,7 @@ std::vector<BucketExpectation> expected = {{0, 1}, {725, 1}}; TestHistogram("RendererScheduler.ExpectedTaskQueueingDuration", 2, expected); std::vector<BucketExpectation> fine_grained = GetFineGrained(expected); - TestHistogram("RendererScheduler.ExpectedTaskQueueingDuration2", 2, + TestHistogram("RendererScheduler.ExpectedTaskQueueingDuration3", 2, fine_grained); } @@ -632,9 +632,10 @@ ::testing::ElementsAreArray(expected_durations)); std::vector<BucketExpectation> expected = {{325, 1}, {400, 1}}; TestHistogram("RendererScheduler.ExpectedTaskQueueingDuration", 2, expected); - std::vector<BucketExpectation> fine_grained = GetFineGrained(expected); - TestHistogram("RendererScheduler.ExpectedTaskQueueingDuration2", 2, - fine_grained); + // The two values get grouped under the same bucket in the microsecond + // version. + expected = {{325 * 1000, 2}}; + TestHistogram("RendererScheduler.ExpectedTaskQueueingDuration3", 2, expected); } // There are multiple windows, but some of the EQTs are not reported due to @@ -690,7 +691,7 @@ {0, 1}, {20, 1}, {125, 1}, {1000, 1}}; TestHistogram("RendererScheduler.ExpectedTaskQueueingDuration", 4, expected); std::vector<BucketExpectation> fine_grained = GetFineGrained(expected); - TestHistogram("RendererScheduler.ExpectedTaskQueueingDuration2", 4, + TestHistogram("RendererScheduler.ExpectedTaskQueueingDuration3", 4, fine_grained); } @@ -873,9 +874,9 @@ base::TimeDelta::FromMilliseconds(800), base::TimeDelta::FromMilliseconds(100), base::TimeDelta::FromMilliseconds(36))); - std::vector<BucketExpectation> expected = { - {36, 1}, {100, 1}, {800, 1}, {900, 1}}; - TestHistogram("RendererScheduler.ExpectedQueueingTimeByTaskQueue.Default", 4, + // The 800 and 900 values get grouped into a single bucket. + std::vector<BucketExpectation> expected = {{36, 1}, {100, 1}, {800, 2}}; + TestHistogram("RendererScheduler.ExpectedQueueingTimeByTaskQueue2.Default", 4, GetFineGrained(expected)); EXPECT_THAT(client.QueueTypeValues(QueueType::kFrameLoading), @@ -885,7 +886,7 @@ base::TimeDelta::FromMilliseconds(36))); expected = {{0, 2}, {36, 1}, {100, 1}}; TestHistogram( - "RendererScheduler.ExpectedQueueingTimeByTaskQueue.FrameLoading", 4, + "RendererScheduler.ExpectedQueueingTimeByTaskQueue2.FrameLoading", 4, GetFineGrained(expected)); EXPECT_THAT(client.QueueTypeValues(QueueType::kFrameThrottleable), @@ -895,7 +896,7 @@ base::TimeDelta::FromMilliseconds(36))); expected = {{0, 2}, {36, 1}, {100, 1}}; TestHistogram( - "RendererScheduler.ExpectedQueueingTimeByTaskQueue.FrameThrottleable", 4, + "RendererScheduler.ExpectedQueueingTimeByTaskQueue2.FrameThrottleable", 4, GetFineGrained(expected)); EXPECT_THAT(client.QueueTypeValues(QueueType::kFramePausable), @@ -905,7 +906,7 @@ base::TimeDelta::FromMilliseconds(36))); expected = {{0, 3}, {36, 1}}; TestHistogram( - "RendererScheduler.ExpectedQueueingTimeByTaskQueue.FramePausable", 4, + "RendererScheduler.ExpectedQueueingTimeByTaskQueue2.FramePausable", 4, GetFineGrained(expected)); EXPECT_THAT(client.QueueTypeValues(QueueType::kUnthrottled), @@ -914,8 +915,9 @@ base::TimeDelta::FromMilliseconds(100), base::TimeDelta::FromMilliseconds(36))); expected = {{0, 2}, {36, 1}, {100, 1}}; - TestHistogram("RendererScheduler.ExpectedQueueingTimeByTaskQueue.Unthrottled", - 4, GetFineGrained(expected)); + TestHistogram( + "RendererScheduler.ExpectedQueueingTimeByTaskQueue2.Unthrottled", 4, + GetFineGrained(expected)); EXPECT_THAT(client.QueueTypeValues(QueueType::kCompositor), ::testing::ElementsAre(base::TimeDelta::FromMilliseconds(0), @@ -923,7 +925,7 @@ base::TimeDelta::FromMilliseconds(0), base::TimeDelta::FromMilliseconds(36))); expected = {{0, 3}, {36, 1}}; - TestHistogram("RendererScheduler.ExpectedQueueingTimeByTaskQueue.Compositor", + TestHistogram("RendererScheduler.ExpectedQueueingTimeByTaskQueue2.Compositor", 4, GetFineGrained(expected)); EXPECT_THAT(client.QueueTypeValues(QueueType::kOther), @@ -932,7 +934,7 @@ base::TimeDelta::FromMilliseconds(0), base::TimeDelta::FromMilliseconds(22))); expected = {{0, 3}, {22, 1}}; - TestHistogram("RendererScheduler.ExpectedQueueingTimeByTaskQueue.Other", 4, + TestHistogram("RendererScheduler.ExpectedQueueingTimeByTaskQueue2.Other", 4, GetFineGrained(expected)); // Check that the sum of split EQT equals the total EQT for each window. @@ -943,11 +945,13 @@ EXPECT_THAT(client.FrameStatusValues(FrameStatus::kNone), ::testing::ElementsAreArray(expected_sums)); expected = {{238, 1}, {400, 1}, {800, 1}, {900, 1}}; - std::vector<BucketExpectation> fine_grained = GetFineGrained(expected); - TestHistogram("RendererScheduler.ExpectedQueueingTimeByFrameStatus.Other", 4, + // The 800 and 900 values end up grouped up in the fine-grained version. + std::vector<BucketExpectation> fine_grained = { + {238 * 1000, 1}, {400 * 1000, 1}, {800 * 1000, 2}}; + TestHistogram("RendererScheduler.ExpectedQueueingTimeByFrameStatus2.Other", 4, fine_grained); TestHistogram("RendererScheduler.ExpectedTaskQueueingDuration", 4, expected); - TestHistogram("RendererScheduler.ExpectedTaskQueueingDuration2", 4, + TestHistogram("RendererScheduler.ExpectedTaskQueueingDuration3", 4, fine_grained); TestSplitSumsTotal(expected_sums, 5); } @@ -1127,9 +1131,10 @@ base::TimeDelta::FromMilliseconds(100), base::TimeDelta::FromMilliseconds(16))); std::vector<BucketExpectation> expected = { - {0, 1}, {16, 1}, {100, 1}, {800, 1}, {900, 1}}; + {0, 1}, {16, 1}, {100, 1}, {800, 2}}; TestHistogram( - "RendererScheduler.ExpectedQueueingTimeByFrameStatus.MainFrameBackground", + "RendererScheduler.ExpectedQueueingTimeByFrameStatus2." + "MainFrameBackground", 5, GetFineGrained(expected)); EXPECT_THAT(client.FrameStatusValues(FrameStatus::kMainFrameVisible), @@ -1138,10 +1143,10 @@ base::TimeDelta::FromMilliseconds(900), base::TimeDelta::FromMilliseconds(0), base::TimeDelta::FromMilliseconds(16))); - expected = {{0, 2}, {16, 1}, {800, 1}, {900, 1}}; + expected = {{0, 2}, {16, 1}, {800, 2}}; TestHistogram( - "RendererScheduler.ExpectedQueueingTimeByFrameStatus.MainFrameVisible", 5, - GetFineGrained(expected)); + "RendererScheduler.ExpectedQueueingTimeByFrameStatus2.MainFrameVisible", + 5, GetFineGrained(expected)); struct FrameExpectation { FrameStatus frame_status; @@ -1149,11 +1154,12 @@ }; FrameExpectation three_expected[] = { {FrameStatus::kSameOriginVisible, - "RendererScheduler.ExpectedQueueingTimeByFrameStatus.SameOriginVisible"}, + "RendererScheduler.ExpectedQueueingTimeByFrameStatus2." + "SameOriginVisible"}, {FrameStatus::kSameOriginHidden, - "RendererScheduler.ExpectedQueueingTimeByFrameStatus.SameOriginHidden"}, + "RendererScheduler.ExpectedQueueingTimeByFrameStatus2.SameOriginHidden"}, {FrameStatus::kCrossOriginVisible, - "RendererScheduler.ExpectedQueueingTimeByFrameStatus." + "RendererScheduler.ExpectedQueueingTimeByFrameStatus2." "CrossOriginVisible"}, }; for (const auto& frame_expectation : three_expected) { @@ -1169,15 +1175,16 @@ FrameExpectation more_expected[] = { {FrameStatus::kMainFrameHidden, - "RendererScheduler.ExpectedQueueingTimeByFrameStatus." + "RendererScheduler.ExpectedQueueingTimeByFrameStatus2." "MainFrameHidden"}, {FrameStatus::kSameOriginBackground, - "RendererScheduler.ExpectedQueueingTimeByFrameStatus." + "RendererScheduler.ExpectedQueueingTimeByFrameStatus2." "SameOriginBackground"}, {FrameStatus::kCrossOriginHidden, - "RendererScheduler.ExpectedQueueingTimeByFrameStatus.CrossOriginHidden"}, + "RendererScheduler.ExpectedQueueingTimeByFrameStatus2." + "CrossOriginHidden"}, {FrameStatus::kCrossOriginBackground, - "RendererScheduler.ExpectedQueueingTimeByFrameStatus." + "RendererScheduler.ExpectedQueueingTimeByFrameStatus2." "CrossOriginBackground"}}; for (const auto& frame_expectation : more_expected) { EXPECT_THAT(client.FrameStatusValues(frame_expectation.frame_status), @@ -1197,7 +1204,7 @@ base::TimeDelta::FromMilliseconds(0), base::TimeDelta::FromMilliseconds(82))); expected = {{0, 4}, {82, 1}}; - TestHistogram("RendererScheduler.ExpectedQueueingTimeByFrameStatus.Other", 5, + TestHistogram("RendererScheduler.ExpectedQueueingTimeByFrameStatus2.Other", 5, GetFineGrained(expected)); // Check that the sum of split EQT equals the total EQT for each window. @@ -1209,11 +1216,12 @@ EXPECT_THAT(client.QueueTypeValues(QueueType::kOther), ::testing::ElementsAreArray(expected_sums)); expected = {{226, 1}, {400, 1}, {800, 1}, {900, 1}, {1700, 1}}; - std::vector<BucketExpectation> fine_grained = GetFineGrained(expected); - TestHistogram("RendererScheduler.ExpectedQueueingTimeByTaskQueue.Other", 5, + std::vector<BucketExpectation> fine_grained = { + {226 * 1000, 1}, {400 * 1000, 1}, {800 * 1000, 2}, {1700 * 1000, 1}}; + TestHistogram("RendererScheduler.ExpectedQueueingTimeByTaskQueue2.Other", 5, fine_grained); TestHistogram("RendererScheduler.ExpectedTaskQueueingDuration", 5, expected); - TestHistogram("RendererScheduler.ExpectedTaskQueueingDuration2", 5, + TestHistogram("RendererScheduler.ExpectedTaskQueueingDuration3", 5, fine_grained); TestSplitSumsTotal(expected_sums, 6); }
diff --git a/third_party/WebKit/Source/platform/scheduler/renderer/renderer_metrics_helper.cc b/third_party/WebKit/Source/platform/scheduler/renderer/renderer_metrics_helper.cc index ad2257b..1861e24 100644 --- a/third_party/WebKit/Source/platform/scheduler/renderer/renderer_metrics_helper.cc +++ b/third_party/WebKit/Source/platform/scheduler/renderer/renderer_metrics_helper.cc
@@ -43,7 +43,7 @@ RendererSchedulerImpl* renderer_scheduler, base::TimeTicks now, bool renderer_backgrounded) - : MetricsHelper(ThreadType::kMainThread), + : MetricsHelper(WebThreadType::kMainThread), renderer_scheduler_(renderer_scheduler), main_thread_load_tracker( now,
diff --git a/third_party/WebKit/Source/platform/scheduler/renderer/renderer_metrics_helper.h b/third_party/WebKit/Source/platform/scheduler/renderer/renderer_metrics_helper.h index aec1917..3d56294 100644 --- a/third_party/WebKit/Source/platform/scheduler/renderer/renderer_metrics_helper.h +++ b/third_party/WebKit/Source/platform/scheduler/renderer/renderer_metrics_helper.h
@@ -14,7 +14,7 @@ #include "platform/scheduler/renderer/main_thread_task_queue.h" #include "platform/scheduler/util/task_duration_metric_reporter.h" #include "platform/scheduler/util/thread_load_tracker.h" -#include "platform/scheduler/util/thread_type.h" +#include "public/platform/WebThreadType.h" namespace blink { namespace scheduler {
diff --git a/third_party/WebKit/Source/platform/scheduler/renderer/renderer_scheduler_impl.cc b/third_party/WebKit/Source/platform/scheduler/renderer/renderer_scheduler_impl.cc index fb0e7bd..ba6f035 100644 --- a/third_party/WebKit/Source/platform/scheduler/renderer/renderer_scheduler_impl.cc +++ b/third_party/WebKit/Source/platform/scheduler/renderer/renderer_scheduler_impl.cc
@@ -7,6 +7,7 @@ #include <memory> #include "base/bind.h" #include "base/debug/stack_trace.h" +#include "base/feature_list.h" #include "base/logging.h" #include "base/metrics/field_trial_params.h" #include "base/metrics/histogram.h" @@ -25,6 +26,7 @@ #include "platform/scheduler/base/task_queue_impl.h" #include "platform/scheduler/base/task_queue_selector.h" #include "platform/scheduler/base/virtual_time_domain.h" +#include "platform/scheduler/child/features.h" #include "platform/scheduler/child/process_state.h" #include "platform/scheduler/renderer/auto_advancing_virtual_time_domain.h" #include "platform/scheduler/renderer/task_queue_throttler.h" @@ -194,6 +196,10 @@ return MainThreadTaskQueue::NameForQueueType(opt_desc->queue_type); } +bool IsUnconditionalHighPriorityInputEnabled() { + return base::FeatureList::IsEnabled(kHighPriorityInput); +} + } // namespace RendererSchedulerImpl::RendererSchedulerImpl( @@ -214,10 +220,12 @@ helper_.NewTaskQueue(MainThreadTaskQueue::QueueCreationParams( MainThreadTaskQueue::QueueType::kCompositor) .SetShouldMonitorQuiescence(true))), - input_task_queue_( - helper_.NewTaskQueue(MainThreadTaskQueue::QueueCreationParams( - MainThreadTaskQueue::QueueType::kInput) - .SetShouldMonitorQuiescence(true))), + input_task_queue_(helper_.NewTaskQueue( + MainThreadTaskQueue::QueueCreationParams( + MainThreadTaskQueue::QueueType::kInput) + .SetShouldMonitorQuiescence(true) + .SetUsedForImportantTasks( + IsUnconditionalHighPriorityInputEnabled()))), compositor_task_queue_enabled_voter_( compositor_task_queue_->CreateQueueEnabledVoter()), input_task_queue_enabled_voter_( @@ -696,7 +704,7 @@ .SetCanBePaused(true) .SetCanBeStopped(StopLoadingInBackgroundEnabled()) .SetCanBeDeferred(true) - .SetUsedForControlTasks( + .SetUsedForImportantTasks( queue_type == MainThreadTaskQueue::QueueType::kFrameLoadingControl)); } @@ -2118,8 +2126,8 @@ TaskQueue::QueuePriority RendererSchedulerImpl::TaskQueuePolicy::GetPriority( MainThreadTaskQueue* task_queue) const { - return task_queue->UsedForControlTasks() ? TaskQueue::kHighPriority - : priority; + return task_queue->UsedForImportantTasks() ? TaskQueue::kHighPriority + : priority; } RendererSchedulerImpl::TimeDomainType @@ -2508,7 +2516,7 @@ UMA_HISTOGRAM_TIMES("RendererScheduler.ExpectedTaskQueueingDuration", queueing_time); UMA_HISTOGRAM_CUSTOM_COUNTS( - "RendererScheduler.ExpectedTaskQueueingDuration2", + "RendererScheduler.ExpectedTaskQueueingDuration3", queueing_time.InMicroseconds(), kMinExpectedQueueingTimeBucket, kMaxExpectedQueueingTimeBucket, kNumberExpectedQueueingTimeBuckets); TRACE_COUNTER1(TRACE_DISABLED_BY_DEFAULT("renderer.scheduler"),
diff --git a/third_party/WebKit/Source/platform/scheduler/renderer/renderer_scheduler_impl.h b/third_party/WebKit/Source/platform/scheduler/renderer/renderer_scheduler_impl.h index 750b4d4..7e7dd24 100644 --- a/third_party/WebKit/Source/platform/scheduler/renderer/renderer_scheduler_impl.h +++ b/third_party/WebKit/Source/platform/scheduler/renderer/renderer_scheduler_impl.h
@@ -110,7 +110,7 @@ static const int kMinExpectedQueueingTimeBucket = 1; // The highest bucket for fine-grained Expected Queueing Time reporting, in // microseconds. - static const int kMaxExpectedQueueingTimeBucket = 4 * 1000 * 1000; + static const int kMaxExpectedQueueingTimeBucket = 30 * 1000 * 1000; // The number of buckets for fine-grained Expected Queueing Time reporting. static const int kNumberExpectedQueueingTimeBuckets = 50;
diff --git a/third_party/WebKit/Source/platform/scheduler/renderer/renderer_scheduler_impl_unittest.cc b/third_party/WebKit/Source/platform/scheduler/renderer/renderer_scheduler_impl_unittest.cc index 0520efd..78397f48 100644 --- a/third_party/WebKit/Source/platform/scheduler/renderer/renderer_scheduler_impl_unittest.cc +++ b/third_party/WebKit/Source/platform/scheduler/renderer/renderer_scheduler_impl_unittest.cc
@@ -13,11 +13,13 @@ #include "base/run_loop.h" #include "base/single_thread_task_runner.h" #include "base/test/histogram_tester.h" +#include "base/test/scoped_feature_list.h" #include "base/test/simple_test_tick_clock.h" #include "build/build_config.h" #include "components/viz/common/frame_sinks/begin_frame_args.h" #include "components/viz/test/ordered_simple_task_runner.h" #include "platform/scheduler/base/real_time_domain.h" +#include "platform/scheduler/child/features.h" #include "platform/scheduler/renderer/auto_advancing_virtual_time_domain.h" #include "platform/scheduler/renderer/budget_pool.h" #include "platform/scheduler/renderer/web_frame_scheduler_impl.h" @@ -262,6 +264,7 @@ RendererSchedulerImplTest() : fake_task_(TaskQueue::PostedTask(base::Bind([] {}), FROM_HERE), base::TimeTicks()) { + feature_list_.InitAndEnableFeature(kHighPriorityInput); clock_.Advance(base::TimeDelta::FromMicroseconds(5000)); } @@ -715,6 +718,7 @@ return scheduler->ThrottleableTaskQueue(); } + base::test::ScopedFeatureList feature_list_; base::SimpleTestTickClock clock_; TaskQueue::Task fake_task_; scoped_refptr<MainThreadTaskQueue> fake_queue_; @@ -893,10 +897,11 @@ EnableIdleTasks(); RunUntilIdle(); + // High-priority input is enabled and input tasks are processed first. EXPECT_THAT(run_order, - ::testing::ElementsAre(std::string("L1"), std::string("D1"), - std::string("P1"), std::string("C1"), - std::string("D2"), std::string("P2"), + ::testing::ElementsAre(std::string("P1"), std::string("P2"), + std::string("L1"), std::string("D1"), + std::string("C1"), std::string("D2"), std::string("C2"), std::string("I1"))); EXPECT_EQ(RendererSchedulerImpl::UseCase::kNone, CurrentUseCase()); } @@ -905,14 +910,16 @@ RunSlowCompositorTask(); std::vector<std::string> run_order; - PostTestTasks(&run_order, "L1 I1 D1 C1 D2 C2"); + PostTestTasks(&run_order, "L1 I1 D1 C1 P1 D2 C2"); EnableIdleTasks(); RunUntilIdle(); + // Even with slow compositor input tasks are handled first. EXPECT_THAT(run_order, - ::testing::ElementsAre(std::string("L1"), std::string("D1"), - std::string("C1"), std::string("D2"), - std::string("C2"), std::string("I1"))); + ::testing::ElementsAre(std::string("P1"), std::string("L1"), + std::string("D1"), std::string("C1"), + std::string("D2"), std::string("C2"), + std::string("I1"))); EXPECT_EQ(RendererSchedulerImpl::UseCase::kNone, CurrentUseCase()); }
diff --git a/third_party/WebKit/Source/platform/scheduler/util/thread_type.h b/third_party/WebKit/Source/platform/scheduler/util/thread_type.h deleted file mode 100644 index f47010c..0000000 --- a/third_party/WebKit/Source/platform/scheduler/util/thread_type.h +++ /dev/null
@@ -1,26 +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. - -#ifndef THIRD_PARTY_WEBKIT_SOURCE_PLATFORM_SCHEDULER_UTIL_THREAD_TYPE_H_ -#define THIRD_PARTY_WEBKIT_SOURCE_PLATFORM_SCHEDULER_UTIL_THREAD_TYPE_H_ - -namespace blink { -namespace scheduler { - -enum class ThreadType { - kMainThread = 0, - kUnspecifiedWorkerThread = 1, - kCompositorThread = 2, - kDedicatedWorkerThread = 3, - kSharedWorkerThread = 4, - kAnimationWorkletThread = 5, - kServiceWorkerThread = 6, - kAudioWorkletThread = 7, - kCount = 8 -}; - -} // namespace scheduler -} // namespace blink - -#endif // THIRD_PARTY_WEBKIT_SOURCE_PLATFORM_SCHEDULER_UTIL_THREAD_TYPE_H_
diff --git a/third_party/WebKit/Source/platform/text/BidiResolver.h b/third_party/WebKit/Source/platform/text/BidiResolver.h index a391f8c0..136e7069 100644 --- a/third_party/WebKit/Source/platform/text/BidiResolver.h +++ b/third_party/WebKit/Source/platform/text/BidiResolver.h
@@ -1002,8 +1002,9 @@ // weak types: case WTF::Unicode::kEuropeanNumber: + // If last_strong is kRightToLeftArabic, change kEuropeanNumber to + // kArabicNumber by falling through after this if. if (status_.last_strong != WTF::Unicode::kRightToLeftArabic) { - // if last strong was AL change EN to AN switch (status_.last) { case WTF::Unicode::kEuropeanNumber: case WTF::Unicode::kLeftToRight: @@ -1074,6 +1075,7 @@ direction_ = WTF::Unicode::kLeftToRight; break; } + FALLTHROUGH; case WTF::Unicode::kArabicNumber: dir_current = WTF::Unicode::kArabicNumber; switch (status_.last) {
diff --git a/third_party/WebKit/Tools/Scripts/webkitpy/layout_tests/controllers/manager.py b/third_party/WebKit/Tools/Scripts/webkitpy/layout_tests/controllers/manager.py index c7c4387..d1e7dae5 100644 --- a/third_party/WebKit/Tools/Scripts/webkitpy/layout_tests/controllers/manager.py +++ b/third_party/WebKit/Tools/Scripts/webkitpy/layout_tests/controllers/manager.py
@@ -367,7 +367,10 @@ # Create the output directory if it doesn't already exist. self._port.host.filesystem.maybe_make_directory(self._results_directory) - self._port.setup_test_run() + exit_code = self._port.setup_test_run() + if exit_code: + _log.error('Build setup failed') + return exit_code # Check that the system dependencies (themes, fonts, ...) are correct. if not self._options.nocheck_sys_deps:
diff --git a/third_party/WebKit/Tools/Scripts/webkitpy/layout_tests/port/android.py b/third_party/WebKit/Tools/Scripts/webkitpy/layout_tests/port/android.py index c228acf..83111f54 100644 --- a/third_party/WebKit/Tools/Scripts/webkitpy/layout_tests/port/android.py +++ b/third_party/WebKit/Tools/Scripts/webkitpy/layout_tests/port/android.py
@@ -116,13 +116,6 @@ PERF_TEST_PATH_PREFIX = '/all-perf-tests' LAYOUT_TEST_PATH_PREFIX = '/all-tests' -# All ports the Android forwarder to forward. -# 8000, 8080 and 8443 are for http/https tests; -# 8880 is for websocket tests (see apache_http.py and pywebsocket.py). -# 8001, 8081 and 8444 are for http/https WPT; -# 9001 and 9444 are for websocket WPT (see wptserve.py). -FORWARD_PORTS = '8000 8001 8080 8081 8443 8444 8880 9001 9444' - # We start netcat processes for each of the three stdio streams. In doing so, # we attempt to use ports starting from 10201. This starting value is # completely arbitrary. @@ -950,7 +943,7 @@ self._log_debug('Starting forwarder') forwarder.Forwarder.Map( - [(p, p) for p in FORWARD_PORTS.split()], + [(p, p) for p in base.Port.SERVER_PORTS], self._device) forwarder.Forwarder.Map( [(forwarder.DYNAMIC_DEVICE_PORT, p) @@ -1106,10 +1099,8 @@ def _command_from_driver_input(self, driver_input): command = super(ChromiumAndroidDriver, self)._command_from_driver_input(driver_input) if command.startswith('/'): - fs = self._port.host.filesystem - # FIXME: what happens if command lies outside of the layout_tests_dir on the host? - relative_test_filename = fs.relpath(command, fs.dirname(self._port.layout_tests_dir())) - command = DEVICE_WEBKIT_BASE_DIR + relative_test_filename + command = 'http://127.0.0.1:8000/all-tests/' + \ + self._port.relative_test_filename(command) return command def _read_prompt(self, deadline):
diff --git a/third_party/WebKit/Tools/Scripts/webkitpy/layout_tests/port/base.py b/third_party/WebKit/Tools/Scripts/webkitpy/layout_tests/port/base.py index 067f584..fba36d4 100644 --- a/third_party/WebKit/Tools/Scripts/webkitpy/layout_tests/port/base.py +++ b/third_party/WebKit/Tools/Scripts/webkitpy/layout_tests/port/base.py
@@ -107,6 +107,15 @@ 'android': ['kitkat'], } + # List of ports open on the host that the tests will connect to. When tests + # run on a separate machine (Android and Fuchsia) these ports need to be + # forwarded back to the host. + # 8000, 8080 and 8443 are for http/https tests; + # 8880 is for websocket tests (see apache_http.py and pywebsocket.py). + # 8001, 8081 and 8444 are for http/https WPT; + # 9001 and 9444 are for websocket WPT (see wptserve.py). + SERVER_PORTS = [8000, 8001, 8080, 8081, 8443, 8444, 8880, 9001, 9444] + FALLBACK_PATHS = {} SUPPORTED_VERSIONS = []
diff --git a/third_party/WebKit/Tools/Scripts/webkitpy/layout_tests/port/driver.py b/third_party/WebKit/Tools/Scripts/webkitpy/layout_tests/port/driver.py index 29d7f9e..584ad61 100644 --- a/third_party/WebKit/Tools/Scripts/webkitpy/layout_tests/port/driver.py +++ b/third_party/WebKit/Tools/Scripts/webkitpy/layout_tests/port/driver.py
@@ -371,9 +371,12 @@ self._current_cmd_line = None + def _base_cmd_line(self): + return [self._port._path_to_driver()] # pylint: disable=protected-access + def cmd_line(self, pixel_tests, per_test_args): cmd = self._command_wrapper(self._port.get_option('wrapper')) - cmd.append(self._port._path_to_driver()) + cmd += self._base_cmd_line() if self._no_timeout: cmd.append('--no-timeout') primary_driver_flag = self._port.primary_driver_flag()
diff --git a/third_party/WebKit/Tools/Scripts/webkitpy/layout_tests/port/factory.py b/third_party/WebKit/Tools/Scripts/webkitpy/layout_tests/port/factory.py index 82a7f5e..50006dd 100644 --- a/third_party/WebKit/Tools/Scripts/webkitpy/layout_tests/port/factory.py +++ b/third_party/WebKit/Tools/Scripts/webkitpy/layout_tests/port/factory.py
@@ -38,11 +38,12 @@ class PortFactory(object): PORT_CLASSES = ( 'android.AndroidPort', + 'fuchsia.FuchsiaPort', 'linux.LinuxPort', 'mac.MacPort', - 'win.WinPort', 'mock_drt.MockDRTPort', 'test.TestPort', + 'win.WinPort', ) def __init__(self, host):
diff --git a/third_party/WebKit/Tools/Scripts/webkitpy/layout_tests/port/fuchsia.py b/third_party/WebKit/Tools/Scripts/webkitpy/layout_tests/port/fuchsia.py new file mode 100644 index 0000000..e03ed77 --- /dev/null +++ b/third_party/WebKit/Tools/Scripts/webkitpy/layout_tests/port/fuchsia.py
@@ -0,0 +1,321 @@ +# Copyright (C) 2018 Google Inc. All rights reserved. +# +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions are +# met: +# +# * Redistributions of source code must retain the above copyright +# notice, this list of conditions and the following disclaimer. +# * Redistributions in binary form must reproduce the above +# copyright notice, this list of conditions and the following disclaimer +# in the documentation and/or other materials provided with the +# distribution. +# * Neither the name of Google Inc. nor the names of its +# contributors may be used to endorse or promote products derived from +# this software without specific prior written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +import logging +import os +import select +import socket +import subprocess +import sys +import threading + +from webkitpy.common import exit_codes +from webkitpy.layout_tests.port import base +from webkitpy.layout_tests.port import driver +from webkitpy.layout_tests.port import factory +from webkitpy.layout_tests.port import server_process + + +# Modules loaded dynamically in _import_fuchsia_runner(). +# pylint: disable=invalid-name +fuchsia_target = None +qemu_target = None +# pylint: enable=invalid-name + + +# Imports Fuchsia runner modules. This is done dynamically only when FuchsiaPort +# is instantiated to avoid dependency on Fuchsia runner on other platforms. +def _import_fuchsia_runner(): + sys.path.append(os.path.abspath(os.path.join( + os.path.dirname(__file__), *(['..'] * 7 + ['build/fuchsia'])))) + + # pylint: disable=import-error + # pylint: disable=invalid-name + # pylint: disable=redefined-outer-name + global fuchsia_target + import runner_v2.target as fuchsia_target + global qemu_target + import runner_v2.qemu_target as qemu_target + # pylint: enable=import-error + # pylint: enable=invalid-name + # pylint: disable=redefined-outer-name + + +# HTTP path prefix for the HTTP server. +PERF_TEST_PATH_PREFIX = '/all-perf-tests' +LAYOUT_TEST_PATH_PREFIX = '/all-tests' + +# Number of content_shell instances to run in parallel. +MAX_WORKERS = 8 + +PROCESS_START_TIMEOUT = 20 + + +_log = logging.getLogger(__name__) + + +def _subprocess_log_thread(pipe, prefix): + try: + while True: + line = pipe.readline() + if not line: + return + _log.error('%s: %s', prefix, line) + finally: + pipe.close() + + +class SubprocessOutputLogger(object): + def __init__(self, process, prefix): + self._process = process + self._thread = threading.Thread( + target=_subprocess_log_thread, + args=(process.stdout, prefix)) + self._thread.daemon = True + self._thread.start() + + def __del__(self): + self.close() + + def close(self): + self._process.kill() + + +class _TargetHost(object): + def __init__(self, build_path, ports_to_forward): + try: + self._target = None + self._target = qemu_target.QemuTarget( + build_path, 'x64', ram_size_mb=8192) + self._target.Start() + self._setup_target(build_path, ports_to_forward) + except: + self.cleanup() + raise + + def _setup_target(self, build_path, ports_to_forward): + # Run a proxy to forward all server ports from the Fuchsia device to + # the host. + # TODO(sergeyu): Potentially this can be implemented using port + # forwarding in SSH, but that feature is currently broken on Fuchsia, + # see ZX-1555. Remove layout_test_proxy once that SSH bug is fixed. + self._target.PutFile( + os.path.join( + build_path, + 'gen/build/fuchsia/layout_test_proxy/layout_test_proxy/layout_test_proxy.far'), + '/tmp') + command = ['run', '/tmp/layout_test_proxy.far', + '--remote-address=' + qemu_target.HOST_IP_ADDRESS, + '--ports=' + ','.join([str(p) for p in ports_to_forward])] + self._proxy = self._target.RunCommandPiped(command, + stdin=subprocess.PIPE, + stdout=subprocess.PIPE) + + # Copy content_shell package to the device. + self._target.PutFile( + os.path.join(build_path, 'gen/content/shell/content_shell.far'), '/tmp') + + # Currently dynamic library loading is not implemented for packaged + # apps. Copy libosmesa.so to /system/lib as a workaround. + self._target.PutFile( + os.path.join(build_path, 'libosmesa.so'), '/system/lib') + + def run_command(self, *args, **kvargs): + return self._target.RunCommandPiped(*args, + stdin=subprocess.PIPE, + stdout=subprocess.PIPE, + stderr=subprocess.PIPE, + **kvargs) + def cleanup(self): + if self._target: + # TODO(sergeyu): Currently __init__() always starts Qemu, so we can + # just shutdown it. Update this logic when reusing target devices + # for multiple test runs. + self._target.Shutdown() + self._target = None + + +class FuchsiaPort(base.Port): + port_name = 'fuchsia' + + SUPPORTED_VERSIONS = ('sdk',) + + FALLBACK_PATHS = {'sdk': ['fuchsia']} + + def __init__(self, host, port_name, **kwargs): + _import_fuchsia_runner() + super(FuchsiaPort, self).__init__(host, port_name, **kwargs) + + self._operating_system = 'fuchsia' + self._version = 'sdk' + + # TODO(sergeyu): Add support for arm64. + self._architecture = 'x86_64' + + self.server_process_constructor = FuchsiaServerProcess + + # Used to implement methods that depend on the host platform. + self._host_port = factory.PortFactory(host).get(**kwargs) + + self._target_host = self.get_option('fuchsia_target') + self._zircon_logger = None + + def _driver_class(self): + return ChromiumFuchsiaDriver + + def _path_to_driver(self, target=None): + return self._build_path_with_target(target, + 'gen/content/shell/content_shell.far') + + def __del__(self): + if self._zircon_logger: + self._zircon_logger.close() + + def setup_test_run(self): + super(FuchsiaPort, self).setup_test_run() + try: + self._target_host = \ + _TargetHost(self._build_path(), self.SERVER_PORTS) + + if self.get_option('zircon_logging'): + self._zircon_logger = SubprocessOutputLogger( + self._target_host.run_command(['dlog', '-f']), + 'Zircon') + + # Save fuchsia_target in _options, so it can be shared with other + # workers. + self._options.fuchsia_target = self._target_host + + except fuchsia_target.FuchsiaTargetException as e: + _log.error('Failed to start qemu: %s.', str(e)) + return exit_codes.NO_DEVICES_EXIT_STATUS + + def cleanup_test_run(self): + if self._target_host: + self._target_host.cleanup() + self._target_host = None + + def num_workers(self, requested_num_workers): + # Run a single qemu instance. + return min(MAX_WORKERS, requested_num_workers) + + def check_sys_deps(self, needs_http): + # TODO(sergeyu): Implement this. + return exit_codes.OK_EXIT_STATUS + + def requires_http_server(self): + """HTTP server is always required to avoid copying the tests to the VM. + """ + return True + + def start_http_server(self, additional_dirs, number_of_drivers): + additional_dirs[PERF_TEST_PATH_PREFIX] = self._perf_tests_dir() + additional_dirs[LAYOUT_TEST_PATH_PREFIX] = self.layout_tests_dir() + super(FuchsiaPort, self).start_http_server( + additional_dirs, number_of_drivers) + + def path_to_apache(self): + return self._host_port.path_to_apache() + + def path_to_apache_config_file(self): + return self._host_port.path_to_apache_config_file() + + def default_smoke_test_only(self): + return True + + def get_target_host(self): + return self._target_host + + +class ChromiumFuchsiaDriver(driver.Driver): + def __init__(self, port, worker_number, pixel_tests, no_timeout=False): + super(ChromiumFuchsiaDriver, self).__init__( + port, worker_number, pixel_tests, no_timeout) + + def _base_cmd_line(self): + return ['run', '/tmp/content_shell.far'] + + def _command_from_driver_input(self, driver_input): + command = super(ChromiumFuchsiaDriver, self)._command_from_driver_input( + driver_input) + if command.startswith('/'): + relative_test_filename = \ + os.path.relpath(command, self._port.layout_tests_dir()) + command = 'http://127.0.0.1:8000/all-tests/' + \ + relative_test_filename + return command + + +# Custom version of ServerProcess that runs processes on a remote device. +class FuchsiaServerProcess(server_process.ServerProcess): + def __init__(self, port_obj, name, cmd, env=None, + treat_no_data_as_crash=False, more_logging=False): + super(FuchsiaServerProcess, self).__init__( + port_obj, name, cmd, env, treat_no_data_as_crash, more_logging) + + def _start(self): + if self._proc: + raise ValueError('%s already running' % self._name) + self._reset() + + # Fuchsia doesn't support stdin stream for packaged applications, so the + # stdin stream for content_shell is routed through a separate TCP + # socket. Open a local socket and then pass the address with the port as + # --stdin-redirect parameter. content_shell will connect to this address + # and will use that connection as its stdin stream. + listen_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) + listen_socket.bind(('127.0.0.1', 0)) + listen_socket.listen(1) + stdin_port = listen_socket.getsockname()[1] + + command = ['%s=%s' % (k, v) for k, v in self._env.items()] + \ + self._cmd + \ + ['--stdin-redirect=%s:%s' % + (qemu_target.HOST_IP_ADDRESS, stdin_port)] + proc = self._port.get_target_host().run_command(command) + # Wait for incoming connection from content_shell. + fd = listen_socket.fileno() + read_fds, _, _ = select.select([fd], [], [], PROCESS_START_TIMEOUT) + if fd not in read_fds: + listen_socket.close() + proc.kill() + raise driver.DeviceFailure( + 'Timed out waiting connection from content_shell.') + + # Python's interfaces for sockets and pipes are different. To masquerade + # the socket as a pipe dup() the file descriptor and pass it to + # os.fdopen(). + stdin_socket, _ = listen_socket.accept() + fd = stdin_socket.fileno() # pylint: disable=no-member + stdin_pipe = os.fdopen(os.dup(fd), "w", 0) + stdin_socket.close() + + proc.stdin.close() + proc.stdin = stdin_pipe + + self._set_proc(proc)
diff --git a/third_party/WebKit/Tools/Scripts/webkitpy/layout_tests/port/server_process.py b/third_party/WebKit/Tools/Scripts/webkitpy/layout_tests/port/server_process.py index 125b785f..b565c1c 100644 --- a/third_party/WebKit/Tools/Scripts/webkitpy/layout_tests/port/server_process.py +++ b/third_party/WebKit/Tools/Scripts/webkitpy/layout_tests/port/server_process.py
@@ -88,6 +88,7 @@ self._treat_no_data_as_crash = treat_no_data_as_crash self._logging = more_logging self._host = self._port.host + self._proc = None self._pid = None self._reset() @@ -132,14 +133,19 @@ if self._env: env_str += '\n'.join('%s=%s' % (k, v) for k, v in self._env.items()) + '\n' _log.info('CMD: \n%s%s\n', env_str, _quote_cmd(self._cmd)) - self._proc = self._host.executive.popen(self._cmd, stdin=self._host.executive.PIPE, - stdout=self._host.executive.PIPE, - stderr=self._host.executive.PIPE, - close_fds=close_fds, - env=self._env) + proc = self._host.executive.popen(self._cmd, stdin=self._host.executive.PIPE, + stdout=self._host.executive.PIPE, + stderr=self._host.executive.PIPE, + close_fds=close_fds, + env=self._env) + self._set_proc(proc) + + def _set_proc(self, proc): + assert not self._proc + self._proc = proc self._pid = self._proc.pid - fd = self._proc.stdout.fileno() if not self._use_win32_apis: + fd = self._proc.stdout.fileno() fl = fcntl.fcntl(fd, fcntl.F_GETFL) fcntl.fcntl(fd, fcntl.F_SETFL, fl | os.O_NONBLOCK) fd = self._proc.stderr.fileno()
diff --git a/third_party/WebKit/Tools/Scripts/webkitpy/layout_tests/run_webkit_tests.py b/third_party/WebKit/Tools/Scripts/webkitpy/layout_tests/run_webkit_tests.py index 2ac0ee28..bed047e 100644 --- a/third_party/WebKit/Tools/Scripts/webkitpy/layout_tests/run_webkit_tests.py +++ b/third_party/WebKit/Tools/Scripts/webkitpy/layout_tests/run_webkit_tests.py
@@ -114,6 +114,22 @@ ])) option_group_definitions.append( + ('Fuchsia-specific Options', [ + optparse.make_option( + '--zircon-logging', + dest='zircon_logging', + action='store_true', + default=True, + help=('Log Zircon debug messages (enabled by default).')), + optparse.make_option( + '--no-zircon-logging', + dest='zircon_logging', + action='store_false', + default=True, + help=('Do not log Zircon debug messages.')), + ])) + + option_group_definitions.append( ('Results Options', [ optparse.make_option( '--add-platform-exceptions',
diff --git a/third_party/WebKit/Tools/lldb/lldb_webkit.py b/third_party/WebKit/Tools/lldb/lldb_webkit.py index 2347291..3b9c398 100644 --- a/third_party/WebKit/Tools/lldb/lldb_webkit.py +++ b/third_party/WebKit/Tools/lldb/lldb_webkit.py
@@ -182,7 +182,7 @@ self.valobj = valobj def to_string(self): - return "%gpx" % (self.valobj.GetChildMemberWithName('value_').GetValueAsUnsigned(0) / 64.0) + return "%.14gpx" % (self.valobj.GetChildMemberWithName('value_').GetValueAsSigned(0) / 64.0) class WebCoreLayoutSizeProvider:
diff --git a/third_party/WebKit/common/BUILD.gn b/third_party/WebKit/common/BUILD.gn index 6f1afde..362df21d 100644 --- a/third_party/WebKit/common/BUILD.gn +++ b/third_party/WebKit/common/BUILD.gn
@@ -113,6 +113,7 @@ "blob/blob.mojom", "blob/blob_registry.mojom", "blob/blob_url_store.mojom", + "blob/serialized_blob.mojom", "clipboard/clipboard.mojom", "color_chooser/color_chooser.mojom", "feature_policy/feature_policy.mojom",
diff --git a/third_party/WebKit/common/blob/blob.mojom b/third_party/WebKit/common/blob/blob.mojom index d94e18b7..91335669 100644 --- a/third_party/WebKit/common/blob/blob.mojom +++ b/third_party/WebKit/common/blob/blob.mojom
@@ -55,14 +55,3 @@ // identify the blob. GetInternalUUID() => (string uuid); }; - -// Struct wrapping a Blob interface pointer. -// TODO(mek): Once https://crbug.com/696107 is implemented all usage of this -// struct can be replaced with a simple Blob interface pointer with handle -// properties for the other attributes. -struct SerializedBlob { - string uuid; - string content_type; - uint64 size; - Blob blob; -};
diff --git a/third_party/WebKit/common/blob/serialized_blob.mojom b/third_party/WebKit/common/blob/serialized_blob.mojom new file mode 100644 index 0000000..703dc56ed --- /dev/null +++ b/third_party/WebKit/common/blob/serialized_blob.mojom
@@ -0,0 +1,18 @@ +// 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. + +module blink.mojom; + +import "third_party/WebKit/common/blob/blob.mojom"; + +// Struct wrapping a Blob interface pointer. +// TODO(mek): Once https://crbug.com/696107 is implemented all usage of this +// struct can be replaced with a simple Blob interface pointer with handle +// properties for the other attributes. +struct SerializedBlob { + string uuid; + string content_type; + uint64 size; + Blob blob; +};
diff --git a/third_party/WebKit/common/clipboard/clipboard.mojom b/third_party/WebKit/common/clipboard/clipboard.mojom index f85a68fc..bd679b2f 100644 --- a/third_party/WebKit/common/clipboard/clipboard.mojom +++ b/third_party/WebKit/common/clipboard/clipboard.mojom
@@ -5,7 +5,7 @@ module blink.mojom; import "mojo/common/string16.mojom"; -import "third_party/WebKit/common/blob/blob.mojom"; +import "third_party/WebKit/common/blob/serialized_blob.mojom"; import "ui/gfx/geometry/mojo/geometry.mojom"; import "url/mojo/url.mojom";
diff --git a/third_party/WebKit/common/message_port/message_port.mojom b/third_party/WebKit/common/message_port/message_port.mojom index 98858c4..b569ea7ce 100644 --- a/third_party/WebKit/common/message_port/message_port.mojom +++ b/third_party/WebKit/common/message_port/message_port.mojom
@@ -4,7 +4,7 @@ module blink.mojom; -import "third_party/WebKit/common/blob/blob.mojom"; +import "third_party/WebKit/common/blob/serialized_blob.mojom"; // A MessagePort is represented as a raw mojo message pipe, as such no interface // definition exists for it here. Messages on this pipe are serialized versions
diff --git a/third_party/WebKit/public/platform/WebContentSecurityPolicyStruct.h b/third_party/WebKit/public/platform/WebContentSecurityPolicyStruct.h index feb44c8..ce47966 100644 --- a/third_party/WebKit/public/platform/WebContentSecurityPolicyStruct.h +++ b/third_party/WebKit/public/platform/WebContentSecurityPolicyStruct.h
@@ -70,6 +70,7 @@ WebVector<WebContentSecurityPolicyDirective> directives; WebVector<WebString> report_endpoints; WebString header; + bool use_reporting_api; }; struct WebContentSecurityPolicyViolation { @@ -86,10 +87,15 @@ // The URL that was blocked by the policy. WebURL blocked_url; - // The set of URI where a JSON-formatted report of the violation should be - // sent. + // The set of endpoints where a report of the violation should be sent. + // Based on 'use_reporting_api' it can be either a set of group_names (when + // 'use_reporting_api' = true) or a set of URLs. This means that it's not + // possible to use both methods of reporting. This is by design. WebVector<WebString> report_endpoints; + // Whether to use the reporting api or not. + bool use_reporting_api; + // The raw content security policy header that was infringed. WebString header;
diff --git a/third_party/WebKit/public/platform/WebRuntimeFeatures.h b/third_party/WebKit/public/platform/WebRuntimeFeatures.h index 1e36ac6..1a7c4b6 100644 --- a/third_party/WebKit/public/platform/WebRuntimeFeatures.h +++ b/third_party/WebKit/public/platform/WebRuntimeFeatures.h
@@ -187,6 +187,8 @@ BLINK_PLATFORM_EXPORT static void EnableStopNonTimersInBackground(bool); BLINK_PLATFORM_EXPORT static void EnablePWAFullCodeCache(bool); BLINK_PLATFORM_EXPORT static void EnableDoubleTapToJumpOnVideo(bool); + BLINK_PLATFORM_EXPORT static void EnableCodeCacheAfterExecute(bool); + BLINK_PLATFORM_EXPORT static void EnableUnifiedTouchAdjustment(bool); private: WebRuntimeFeatures();
diff --git a/third_party/WebKit/public/platform/WebThread.h b/third_party/WebKit/public/platform/WebThread.h index e1baf6fc..e1289b94 100644 --- a/third_party/WebKit/public/platform/WebThread.h +++ b/third_party/WebKit/public/platform/WebThread.h
@@ -26,6 +26,7 @@ #define WebThread_h #include "WebCommon.h" +#include "WebThreadType.h" #include "base/callback_forward.h" #include "base/memory/scoped_refptr.h" @@ -46,8 +47,11 @@ typedef uintptr_t PlatformThreadId; struct BLINK_PLATFORM_EXPORT WebThreadCreationParams { - explicit WebThreadCreationParams(const char* name); + explicit WebThreadCreationParams(WebThreadType); + WebThreadCreationParams& SetThreadName(const char* name); + + WebThreadType thread_type; const char* name; };
diff --git a/third_party/WebKit/public/platform/WebThreadType.h b/third_party/WebKit/public/platform/WebThreadType.h new file mode 100644 index 0000000..348f144 --- /dev/null +++ b/third_party/WebKit/public/platform/WebThreadType.h
@@ -0,0 +1,37 @@ +// 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. + +#ifndef WebThreadType_h +#define WebThreadType_h + +#include "public/platform/WebCommon.h" + +namespace blink { + +enum class WebThreadType { + kMainThread = 0, + kUnspecifiedWorkerThread = 1, + kCompositorThread = 2, + kDedicatedWorkerThread = 3, + kSharedWorkerThread = 4, + kAnimationWorkletThread = 5, + kServiceWorkerThread = 6, + kAudioWorkletThread = 7, + kFileThread = 8, + kDatabaseThread = 9, + kWebAudioThread = 10, + kScriptStreamerThread = 11, + kOfflineAudioRenderThread = 12, + kReverbConvolutionBackgroundThread = 13, + kHRTFDatabaseLoaderThread = 14, + kTestThread = 15, + + kCount = 16 +}; + +BLINK_PLATFORM_EXPORT const char* GetNameForThreadType(WebThreadType); + +} // namespace blink + +#endif // ThreadType_h
diff --git a/third_party/WebKit/public/platform/web_feature.mojom b/third_party/WebKit/public/platform/web_feature.mojom index 287c713..93637b3 100644 --- a/third_party/WebKit/public/platform/web_feature.mojom +++ b/third_party/WebKit/public/platform/web_feature.mojom
@@ -1864,6 +1864,10 @@ kCSSLegacyAlignment = 2351, kSRISignatureCheck = 2352, kSRISignatureSuccess = 2353, + kCSSBasicShape = 2354, + kCSSGradient = 2355, + kCSSPaintFunction = 2356, + kWebkitCrossFade = 2357, // Add new features immediately above this line. Don't change assigned // numbers of any item, and don't reuse removed slots.
diff --git a/third_party/WebKit/public/web/WebAXEnums.h b/third_party/WebKit/public/web/WebAXEnums.h index 9f6a9443..80c7ec8 100644 --- a/third_party/WebKit/public/web/WebAXEnums.h +++ b/third_party/WebKit/public/web/WebAXEnums.h
@@ -125,6 +125,10 @@ kWebAXRoleInlineTextBox, kWebAXRoleInputTime, kWebAXRoleLabel, + kWebAXRoleLayoutTable, + kWebAXRoleLayoutTableCell, + kWebAXRoleLayoutTableColumn, + kWebAXRoleLayoutTableRow, kWebAXRoleLegend, kWebAXRoleLineBreak, kWebAXRoleLink,
diff --git a/third_party/WebKit/public/web/WebDocumentLoader.h b/third_party/WebKit/public/web/WebDocumentLoader.h index f3f4727..cff9cbd9 100644 --- a/third_party/WebKit/public/web/WebDocumentLoader.h +++ b/third_party/WebKit/public/web/WebDocumentLoader.h
@@ -41,7 +41,6 @@ namespace blink { class WebDocumentSubresourceFilter; -class WebSecurityOrigin; class WebServiceWorkerNetworkProvider; class WebURL; class WebURLRequest; @@ -59,12 +58,6 @@ virtual ~ExtraData() = default; }; - // Returns whether a user activation state should be persisted across - // navigation. - static bool ShouldPersistUserActivation( - const WebSecurityOrigin& previous_origin, - const WebSecurityOrigin& new_origin); - // Returns the original request that resulted in this datasource. virtual const WebURLRequest& OriginalRequest() const = 0;
diff --git a/third_party/WebKit/public/web/WebFrame.h b/third_party/WebKit/public/web/WebFrame.h index 0273387..6b69594 100644 --- a/third_party/WebKit/public/web/WebFrame.h +++ b/third_party/WebKit/public/web/WebFrame.h
@@ -204,6 +204,9 @@ void DetachFromParent(); #endif + // Mark this frame's document as having received a user gesture. + virtual void SetHasReceivedUserGesture() = 0; + protected: explicit WebFrame(WebTreeScopeType); virtual ~WebFrame();
diff --git a/third_party/WebKit/public/web/WebLocalFrame.h b/third_party/WebKit/public/web/WebLocalFrame.h index ff0e6e8..f4d2e74 100644 --- a/third_party/WebKit/public/web/WebLocalFrame.h +++ b/third_party/WebKit/public/web/WebLocalFrame.h
@@ -278,10 +278,6 @@ // cross process. virtual void SetCommittedFirstRealLoad() = 0; - // Mark this frame's document as having received a user gesture, based on - // one of its descendants having processed a user gesture. - virtual void SetHasReceivedUserGesture() = 0; - // Reports a list of unique blink::WebFeature values representing // Blink features used, performed or encountered by the browser during the // current page load happening on the frame.
diff --git a/third_party/WebKit/public/web/WebRemoteFrame.h b/third_party/WebKit/public/web/WebRemoteFrame.h index 215eefc7..5ce29144 100644 --- a/third_party/WebKit/public/web/WebRemoteFrame.h +++ b/third_party/WebKit/public/web/WebRemoteFrame.h
@@ -110,7 +110,6 @@ // owner. virtual void WillEnterFullscreen() = 0; - virtual void SetHasReceivedUserGesture() = 0; virtual void SetHasReceivedUserGestureBeforeNavigation(bool value) = 0; // Scrolls the given rectangle into view. This kicks off the recursive scroll
diff --git a/third_party/WebKit/public/web/remote_objects.mojom b/third_party/WebKit/public/web/remote_objects.mojom index edfe571c8..37d644e 100644 --- a/third_party/WebKit/public/web/remote_objects.mojom +++ b/third_party/WebKit/public/web/remote_objects.mojom
@@ -25,6 +25,7 @@ OK = 0, METHOD_NOT_FOUND, OBJECT_GET_CLASS_BLOCKED, + EXCEPTION_THROWN, }; struct RemoteInvocationResult {
diff --git a/third_party/android_crazy_linker/src/src/crazy_linker_api.cpp b/third_party/android_crazy_linker/src/src/crazy_linker_api.cpp index d0ac3a55..0852699 100644 --- a/third_party/android_crazy_linker/src/src/crazy_linker_api.cpp +++ b/third_party/android_crazy_linker/src/src/crazy_linker_api.cpp
@@ -21,8 +21,9 @@ using crazy::Globals; using crazy::Error; +using crazy::RDebug; using crazy::SearchPathList; -using crazy::ScopedGlobalLock; +using crazy::ScopedLockedGlobals; using crazy::LibraryView; // @@ -66,7 +67,9 @@ extern "C" { void crazy_set_sdk_build_version(int sdk_build_version) { - *Globals::GetSDKBuildVersion() = sdk_build_version; + // NOTE: This must be called before creating the Globals instance, + // so do not use Globals::Get() or a ScopedLockedGlobals instance here. + Globals::sdk_build_version = sdk_build_version; } crazy_context_t* crazy_context_create() { @@ -167,19 +170,16 @@ // if callback is NULL. class ScopedDelayedCallbackPoster { public: - ScopedDelayedCallbackPoster(crazy_context_t* context) { + ScopedDelayedCallbackPoster(crazy_context_t* context, RDebug* rdebug) { if (context && context->callback_poster) { - crazy::Globals::GetRDebug()->SetDelayedCallbackPoster(&PostFromContext, - context); - set_delayed_callback_poster_ = true; - } else { - set_delayed_callback_poster_ = false; + rdebug->SetDelayedCallbackPoster(&PostFromContext, context); + rdebug_ = rdebug; } } ~ScopedDelayedCallbackPoster() { - if (set_delayed_callback_poster_) - crazy::Globals::GetRDebug()->SetDelayedCallbackPoster(NULL, NULL); + if (rdebug_) + rdebug_->SetDelayedCallbackPoster(nullptr, nullptr); } private: @@ -187,32 +187,26 @@ static bool PostFromContext(void* crazy_context, crazy_callback_handler_t handler, void* opaque) { - crazy_context_t* context = static_cast<crazy_context_t*>(crazy_context); + auto* context = static_cast<crazy_context_t*>(crazy_context); crazy_callback_t callback; callback.handler = handler; callback.opaque = opaque; - return context->callback_poster(&callback, - context->callback_poster_opaque); + return context->callback_poster(&callback, context->callback_poster_opaque); } - // True if the context offered a callback_poster, otherwise false. - bool set_delayed_callback_poster_; + // Non-null iff the context offered a callback_poster. + RDebug* rdebug_ = nullptr; }; crazy_status_t crazy_library_open(crazy_library_t** library, const char* lib_name, crazy_context_t* context) { - ScopedDelayedCallbackPoster poster(context); - ScopedGlobalLock lock; + ScopedLockedGlobals globals; + ScopedDelayedCallbackPoster poster(context, globals->rdebug()); - LibraryView* wrap = - crazy::Globals::GetLibraries()->LoadLibrary(lib_name, - RTLD_NOW, - context->load_address, - context->file_offset, - &context->search_paths, - false, - &context->error); + LibraryView* wrap = globals->libraries()->LoadLibrary( + lib_name, RTLD_NOW, context->load_address, context->file_offset, + &context->search_paths, false, &context->error); if (!wrap) return CRAZY_STATUS_FAILURE; @@ -221,7 +215,7 @@ crazy::SharedLibrary* lib = wrap->GetCrazy(); if (!lib->SetJavaVM( context->java_vm, context->minimum_jni_version, &context->error)) { - crazy::Globals::GetLibraries()->UnloadLibrary(wrap); + globals->libraries()->UnloadLibrary(wrap); return CRAZY_STATUS_FAILURE; } } @@ -234,18 +228,12 @@ const char* zipfile_name, const char* lib_name, crazy_context_t* context) { - ScopedDelayedCallbackPoster poster(context); - ScopedGlobalLock lock; + ScopedLockedGlobals globals; + ScopedDelayedCallbackPoster poster(context, globals->rdebug()); - LibraryView* wrap = - crazy::Globals::GetLibraries()->LoadLibraryInZipFile( - zipfile_name, - lib_name, - RTLD_NOW, - context->load_address, - &context->search_paths, - false, - &context->error); + LibraryView* wrap = globals->libraries()->LoadLibraryInZipFile( + zipfile_name, lib_name, RTLD_NOW, context->load_address, + &context->search_paths, false, &context->error); if (!wrap) return CRAZY_STATUS_FAILURE; @@ -254,7 +242,7 @@ crazy::SharedLibrary* lib = wrap->GetCrazy(); if (!lib->SetJavaVM( context->java_vm, context->minimum_jni_version, &context->error)) { - crazy::Globals::GetLibraries()->UnloadLibrary(wrap); + globals->libraries()->UnloadLibrary(wrap); return CRAZY_STATUS_FAILURE; } } @@ -326,9 +314,8 @@ crazy_status_t crazy_library_find_by_name(const char* library_name, crazy_library_t** library) { { - ScopedGlobalLock lock; - LibraryView* wrap = - Globals::GetLibraries()->FindLibraryByName(library_name); + ScopedLockedGlobals globals; + LibraryView* wrap = globals->libraries()->FindLibraryByName(library_name); if (!wrap) return CRAZY_STATUS_FAILURE; @@ -358,8 +345,8 @@ crazy_status_t crazy_library_find_from_address(void* address, crazy_library_t** library) { { - ScopedGlobalLock lock; - LibraryView* wrap = Globals::GetLibraries()->FindLibraryForAddress(address); + ScopedLockedGlobals globals; + LibraryView* wrap = globals->libraries()->FindLibraryForAddress(address); if (!wrap) return CRAZY_STATUS_FAILURE; @@ -377,11 +364,11 @@ void crazy_library_close_with_context(crazy_library_t* library, crazy_context_t* context) { if (library) { - ScopedDelayedCallbackPoster poster(context); - ScopedGlobalLock lock; + ScopedLockedGlobals globals; + ScopedDelayedCallbackPoster poster(context, globals->rdebug()); LibraryView* wrap = reinterpret_cast<LibraryView*>(library); - Globals::GetLibraries()->UnloadLibrary(wrap); + globals->libraries()->UnloadLibrary(wrap); } }
diff --git a/third_party/android_crazy_linker/src/src/crazy_linker_globals.cpp b/third_party/android_crazy_linker/src/src/crazy_linker_globals.cpp index 156c194..5d6e4a3 100644 --- a/third_party/android_crazy_linker/src/src/crazy_linker_globals.cpp +++ b/third_party/android_crazy_linker/src/src/crazy_linker_globals.cpp
@@ -4,22 +4,39 @@ #include "crazy_linker_globals.h" -#include <pthread.h> +#include <new> -#include "crazy_linker_system.h" +#include <pthread.h> namespace crazy { namespace { -Globals* g_globals = NULL; -pthread_once_t g_globals_once = PTHREAD_ONCE_INIT; +// Implement lazy-initialized static variable without a C++ constructor. +// Note that this is leaky, i.e. the instance is never destroyed, but +// this was also the case with the previous heap-based implementation. +pthread_once_t s_once = PTHREAD_ONCE_INIT; -void CreateGlobalsInstance() { g_globals = new Globals(); } +union Storage { + char dummy; + Globals globals; + + Storage() {} + ~Storage() {} +}; + +Storage s_storage; + +void InitGlobals() { + new (&s_storage.globals) Globals(); +} } // namespace -Globals::Globals() : search_paths_(), rdebug_() { +Globals::Globals() { + // TODO(digit): Remove the need for a recursive mutex (which is often the + // symptom of something wrong in threaded code). This needs refactoring + // the deferred task management though. pthread_mutexattr_t attr; pthread_mutexattr_init(&attr); pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_RECURSIVE); @@ -27,14 +44,25 @@ search_paths_.ResetFromEnv("LD_LIBRARY_PATH"); } -Globals::~Globals() { pthread_mutex_destroy(&lock_); } +Globals::~Globals() { + pthread_mutex_destroy(&lock_); +} -Globals* Globals::Get() { - pthread_once(&g_globals_once, CreateGlobalsInstance); - return g_globals; +void Globals::Lock() { + pthread_mutex_lock(&lock_); +} + +void Globals::Unlock() { + pthread_mutex_unlock(&lock_); } // static -int Globals::sdk_build_version_ = 0; +Globals* Globals::Get() { + pthread_once(&s_once, InitGlobals); + return &s_storage.globals; +} + +// static +int Globals::sdk_build_version = 0; } // namespace crazy
diff --git a/third_party/android_crazy_linker/src/src/crazy_linker_globals.h b/third_party/android_crazy_linker/src/src/crazy_linker_globals.h index 716c8cd..68d02e3 100644 --- a/third_party/android_crazy_linker/src/src/crazy_linker_globals.h +++ b/third_party/android_crazy_linker/src/src/crazy_linker_globals.h
@@ -18,27 +18,41 @@ class Globals { public: - Globals(); - ~Globals(); - - void Lock() { pthread_mutex_lock(&lock_); } - - void Unlock() { pthread_mutex_unlock(&lock_); } - + // Get the single Globals instance for this process. static Globals* Get(); - static LibraryList* GetLibraries() { return &Get()->libraries_; } + // Default constructor. + Globals(); - static SearchPathList* GetSearchPaths() { return &Get()->search_paths_; } + // Destructor. + ~Globals(); - static RDebug* GetRDebug() { return &Get()->rdebug_; } + // Acquire and release the mutex that protects all other non-static members. + // ScopedLockedGlobals is recommended, to avoid using these directly. + void Lock(); + void Unlock(); - static int* GetSDKBuildVersion() { return &sdk_build_version_; } + // The list of libraries known to the crazy linker. + LibraryList* libraries() { return &libraries_; } + + // The RDebug instance for this process. + RDebug* rdebug() { return &rdebug_; } // Set of valid handles returned by the dlopen() wrapper. This is // required to deal with rare cases where the wrapper is passed // a handle that was opened with the system linker by mistake. - static PointerSet* GetValidHandles() { return &Get()->valid_handles_; } + PointerSet* valid_handles() { return &valid_handles_; } + + // The current library search path list used by the dlopen() wrapper. + // Initialized from LD_LIBRARY_PATH when ::Get() creates the instance. + SearchPathList* search_path_list() { return &search_paths_; } + + // Android API level for the current device (if known). + // This is static because it must be set before the first call to Get(). + static int sdk_build_version; + + // Convenience function to get the global RDebug instance. + static RDebug* GetRDebug() { return Get()->rdebug(); } private: pthread_mutex_t lock_; @@ -46,15 +60,28 @@ SearchPathList search_paths_; RDebug rdebug_; PointerSet valid_handles_; - static int sdk_build_version_; }; -// Helper class to access the globals with scoped locking. -class ScopedGlobalLock { +// Convenience class to retrieve the Globals instance and lock it at the same +// time on construction, then release it on destruction. Also dereference can +// be used to access global methods and members. +class ScopedLockedGlobals { public: - ScopedGlobalLock() { Globals::Get()->Lock(); } + // Default constructor acquires the lock on the global instance. + ScopedLockedGlobals() : globals_(Globals::Get()) { globals_->Lock(); } - ~ScopedGlobalLock() { Globals::Get()->Unlock(); } + // Destructor releases the lock. + ~ScopedLockedGlobals() { globals_->Unlock(); } + + // Disallow copy operations. + ScopedLockedGlobals(const ScopedLockedGlobals&) = delete; + ScopedLockedGlobals& operator=(const ScopedLockedGlobals&) = delete; + + // Dereference operator. + Globals* operator->() { return globals_; } + + private: + Globals* globals_; }; } // namespace crazy
diff --git a/third_party/android_crazy_linker/src/src/crazy_linker_globals_unittest.cpp b/third_party/android_crazy_linker/src/src/crazy_linker_globals_unittest.cpp index 9f8f99ed..32b459c 100644 --- a/third_party/android_crazy_linker/src/src/crazy_linker_globals_unittest.cpp +++ b/third_party/android_crazy_linker/src/src/crazy_linker_globals_unittest.cpp
@@ -12,10 +12,11 @@ TEST(Globals, Get) { SystemMock sys; - ASSERT_TRUE(Globals::Get()); - ASSERT_TRUE(Globals::GetLibraries()); - ASSERT_TRUE(Globals::GetSearchPaths()); - ASSERT_TRUE(Globals::GetRDebug()); + Globals* globals = Globals::Get(); + ASSERT_TRUE(globals); + ASSERT_TRUE(globals->libraries()); + ASSERT_TRUE(globals->search_path_list()); + ASSERT_TRUE(globals->rdebug()); } } // namespace crazy
diff --git a/third_party/android_crazy_linker/src/src/crazy_linker_library_list.cpp b/third_party/android_crazy_linker/src/src/crazy_linker_library_list.cpp index 0ced9c5..87e19bb 100644 --- a/third_party/android_crazy_linker/src/src/crazy_linker_library_list.cpp +++ b/third_party/android_crazy_linker/src/src/crazy_linker_library_list.cpp
@@ -63,7 +63,10 @@ } // namespace LibraryList::LibraryList() : head_(0), has_error_(false) { - const int sdk_build_version = *Globals::GetSDKBuildVersion(); + // NOTE: This constructor is called from the Globals::Globals() constructor, + // hence it is important that Globals::sdk_build_version is a static member + // that can be set before Globals::Get() is called for the first time. + const int sdk_build_version = Globals::sdk_build_version; // If SDK version is Lollipop or earlier, we need to load anything // listed in LD_PRELOAD explicitly, because dlsym() on the main executable
diff --git a/third_party/android_crazy_linker/src/src/crazy_linker_library_view.cpp b/third_party/android_crazy_linker/src/src/crazy_linker_library_view.cpp index ae7cdb6..3e68127 100644 --- a/third_party/android_crazy_linker/src/src/crazy_linker_library_view.cpp +++ b/third_party/android_crazy_linker/src/src/crazy_linker_library_view.cpp
@@ -29,7 +29,7 @@ return ::dlsym(system_, symbol_name); if (type_ == TYPE_CRAZY) { - LibraryList* lib_list = Globals::GetLibraries(); + LibraryList* lib_list = Globals::Get()->libraries(); return lib_list->FindSymbolFrom(symbol_name, this); }
diff --git a/third_party/android_crazy_linker/src/src/crazy_linker_rdebug.cpp b/third_party/android_crazy_linker/src/src/crazy_linker_rdebug.cpp index 693fc8b..a3c0672d 100644 --- a/third_party/android_crazy_linker/src/src/crazy_linker_rdebug.cpp +++ b/third_party/android_crazy_linker/src/src/crazy_linker_rdebug.cpp
@@ -411,7 +411,7 @@ } void RDebug::AddEntryImpl(link_map_t* entry) { - ScopedGlobalLock lock; + ScopedLockedGlobals globals; // TODO(digit): Remove this lock. LOG("Adding: %s", entry->l_name); if (!init_) Init(); @@ -469,7 +469,7 @@ } void RDebug::DelEntryImpl(link_map_t* entry) { - ScopedGlobalLock lock; + ScopedLockedGlobals globals; // TODO(digit): Remove this lock. LOG("Deleting: %s", entry->l_name); if (!r_debug_) return;
diff --git a/third_party/android_crazy_linker/src/src/crazy_linker_shared_library.cpp b/third_party/android_crazy_linker/src/src/crazy_linker_shared_library.cpp index 81ac507..391098f 100644 --- a/third_party/android_crazy_linker/src/src/crazy_linker_shared_library.cpp +++ b/third_party/android_crazy_linker/src/src/crazy_linker_shared_library.cpp
@@ -258,6 +258,7 @@ LOG("Parsing dynamic table for %s", base_name_); ElfView::DynamicIterator dyn(&view_); + RDebug* rdebug = Globals::GetRDebug(); for (; dyn.HasNext(); dyn.GetNext()) { ELF::Addr dyn_value = dyn.GetValue(); uintptr_t dyn_addr = dyn.GetAddress(load_bias()); @@ -265,7 +266,7 @@ case DT_DEBUG: if (view_.dynamic_flags() & PF_W) { *dyn.GetValuePointer() = - reinterpret_cast<uintptr_t>(Globals::GetRDebug()->GetAddress()); + reinterpret_cast<uintptr_t>(rdebug->GetAddress()); } break; case DT_INIT: @@ -314,7 +315,7 @@ #if defined(__mips__) case DT_MIPS_RLD_MAP: *dyn.GetValuePointer() = - reinterpret_cast<ELF::Addr>(Globals::GetRDebug()->GetAddress()); + reinterpret_cast<ELF::Addr>(rdebug->GetAddress()); break; #endif default:
diff --git a/third_party/android_crazy_linker/src/src/crazy_linker_wrappers.cpp b/third_party/android_crazy_linker/src/src/crazy_linker_wrappers.cpp index f1495ee..3a48f61 100644 --- a/third_party/android_crazy_linker/src/src/crazy_linker_wrappers.cpp +++ b/third_party/android_crazy_linker/src/src/crazy_linker_wrappers.cpp
@@ -88,23 +88,18 @@ } void* WrapDlopen(const char* path, int mode) { - ScopedGlobalLock lock; + ScopedLockedGlobals globals; // NOTE: If |path| is NULL, the wrapper should return a handle // corresponding to the current executable. This can't be a crazy // library, so don't try to handle it with the crazy linker. if (path) { - LibraryList* lib_list = Globals::GetLibraries(); Error error; - LibraryView* wrap = lib_list->LoadLibrary(path, - mode, - 0U /* load_address */, - 0U /* file_offset */, - Globals::GetSearchPaths(), - false, - &error); + LibraryView* wrap = globals->libraries()->LoadLibrary( + path, mode, 0U /* load_address */, 0U /* file_offset */, + globals->search_path_list(), false, &error); if (wrap) { - Globals::GetValidHandles()->Add(wrap); + globals->valid_handles()->Add(wrap); return wrap; } } @@ -119,8 +114,8 @@ LibraryView* wrap_lib = new LibraryView(); wrap_lib->SetSystem(system_lib, path ? path : "<executable>"); - Globals::GetLibraries()->AddLibrary(wrap_lib); - Globals::GetValidHandles()->Add(wrap_lib); + globals->libraries()->AddLibrary(wrap_lib); + globals->valid_handles()->Add(wrap_lib); return wrap_lib; } @@ -149,8 +144,8 @@ // when |lib_handle| corresponds to a crazy library, except that // it stops at system libraries that it depends on. - ScopedGlobalLock lock; - if (!Globals::GetValidHandles()->Has(lib_handle)) { + ScopedLockedGlobals globals; + if (!globals->valid_handles()->Has(lib_handle)) { // Note: the handle was not opened with the crazy linker, so fall back // to the system linker. That can happen in rare cases. void* result = ::dlsym(lib_handle, symbol_name); @@ -178,8 +173,7 @@ } if (wrap_lib->IsCrazy()) { - LibraryList* lib_list = Globals::GetLibraries(); - void* addr = lib_list->FindSymbolFrom(symbol_name, wrap_lib); + void* addr = globals->libraries()->FindSymbolFrom(symbol_name, wrap_lib); if (addr) return addr; @@ -198,9 +192,8 @@ int WrapDladdr(void* address, Dl_info* info) { // First, perform search in crazy libraries. { - ScopedGlobalLock lock; - LibraryList* lib_list = Globals::GetLibraries(); - LibraryView* wrap = lib_list->FindLibraryForAddress(address); + ScopedLockedGlobals globals; + LibraryView* wrap = globals->libraries()->FindLibraryForAddress(address); if (wrap && wrap->IsCrazy()) { size_t sym_size = 0; @@ -229,8 +222,8 @@ return -1; } - ScopedGlobalLock lock; - if (!Globals::GetValidHandles()->Remove(lib_handle)) { + ScopedLockedGlobals globals; + if (!globals->valid_handles()->Remove(lib_handle)) { // This is a foreign handle that was not created by the crazy linker. // Fall-back to the system in this case. if (::dlclose(lib_handle) != 0) { @@ -244,8 +237,7 @@ LibraryView* wrap_lib = reinterpret_cast<LibraryView*>(lib_handle); if (wrap_lib->IsSystem() || wrap_lib->IsCrazy()) { - LibraryList* lib_list = Globals::GetLibraries(); - lib_list->UnloadLibrary(wrap_lib); + globals->libraries()->UnloadLibrary(wrap_lib); return 0; } @@ -258,10 +250,9 @@ _Unwind_Ptr WrapDl_unwind_find_exidx(_Unwind_Ptr pc, int* pcount) { // First lookup in crazy libraries. { - ScopedGlobalLock lock; - LibraryList* list = Globals::GetLibraries(); + ScopedLockedGlobals globals; _Unwind_Ptr result = - list->FindArmExIdx(reinterpret_cast<void*>(pc), pcount); + globals->libraries()->FindArmExIdx(reinterpret_cast<void*>(pc), pcount); if (result) return result; } @@ -272,9 +263,8 @@ int WrapDl_iterate_phdr(int (*cb)(dl_phdr_info*, size_t, void*), void* data) { // First, iterate over crazy libraries. { - ScopedGlobalLock lock; - LibraryList* list = Globals::GetLibraries(); - int result = list->IteratePhdr(cb, data); + ScopedLockedGlobals globals; + int result = globals->libraries()->IteratePhdr(cb, data); if (result) return result; } @@ -298,9 +288,9 @@ // free()-ed by the caller. This returns nullptr is the array is empty. // On exit, sets |*p_count| to the number of items in the array. void** GetValidDlopenHandlesForTesting(size_t* p_count) { - ScopedGlobalLock lock; + ScopedLockedGlobals globals; const Vector<void*>& handles = - Globals::GetValidHandles()->GetValuesForTesting(); + globals->valid_handles()->GetValuesForTesting(); *p_count = handles.GetCount(); if (handles.IsEmpty()) return nullptr;
diff --git a/third_party/closure_compiler/externs/automation.js b/third_party/closure_compiler/externs/automation.js index c9a7f966..de4ac75 100644 --- a/third_party/closure_compiler/externs/automation.js +++ b/third_party/closure_compiler/externs/automation.js
@@ -130,6 +130,10 @@ INLINE_TEXT_BOX: 'inlineTextBox', INPUT_TIME: 'inputTime', LABEL_TEXT: 'labelText', + LAYOUT_TABLE: 'layoutTable', + LAYOUT_TABLE_CELL: 'layoutTableCell', + LAYOUT_TABLE_COLUMN: 'layoutTableColumn', + LAYOUT_TABLE_ROW: 'layoutTableRow', LEGEND: 'legend', LINE_BREAK: 'lineBreak', LINK: 'link', @@ -838,6 +842,20 @@ chrome.automation.AutomationNode.prototype.tableRowHeader; /** + * The column index of this column node. + * @type {(number|undefined)} + * @see https://developer.chrome.com/extensions/automation#type-tableColumnIndex + */ +chrome.automation.AutomationNode.prototype.tableColumnIndex; + +/** + * The row index of this row node. + * @type {(number|undefined)} + * @see https://developer.chrome.com/extensions/automation#type-tableRowIndex + */ +chrome.automation.AutomationNode.prototype.tableRowIndex; + +/** * The type of region if this is the root of a live region. Possible values are 'polite' and 'assertive'. * @type {(string|undefined)} * @see https://developer.chrome.com/extensions/automation#type-liveStatus @@ -964,7 +982,7 @@ chrome.automation.AutomationNode.prototype.language; /** - * Input restriction, if any, such as readonly or disabled: undefined - enabled control or other object that is not disabled Restriction.DISABLED - disallows input in itself + any descendants Restriction.READONLY - allow focus/selection but not input + * Input restriction, if any, such as readonly or disabled: undefined - enabled control or other object that is not disabled Restriction.DISABLED - disallows input in itself + any descendants Restriction.READONLY - allow focus/selection but not input * @type {(string|undefined)} * @see https://developer.chrome.com/extensions/automation#type-restriction */
diff --git a/third_party/metrics_proto/OWNERS b/third_party/metrics_proto/OWNERS index c929027..d8dcbe96 100644 --- a/third_party/metrics_proto/OWNERS +++ b/third_party/metrics_proto/OWNERS
@@ -1,3 +1,7 @@ file://base/metrics/OWNERS +per-file sampled_profile.proto=wittman@chromium.org +per-file call_stack_profile.proto=wittman@chromium.org +per-file execution_context.proto=wittman@chromium.org + # COMPONENT: Internals>Metrics
diff --git a/third_party/tcmalloc/README.chromium b/third_party/tcmalloc/README.chromium index 486b6d3..2e4fb29 100644 --- a/third_party/tcmalloc/README.chromium +++ b/third_party/tcmalloc/README.chromium
@@ -111,3 +111,4 @@ - Fix potential missing nul character in symbol names produced by addr2line-pdb. - Remove superfluous size_t value >= 0 check. - Make kFooType in tcmalloc.cc truly const. +- Added support for mips64el.
diff --git a/third_party/tcmalloc/chromium/src/base/atomicops-internals-mips.h b/third_party/tcmalloc/chromium/src/base/atomicops-internals-mips.h new file mode 100644 index 0000000..4bfd7f6 --- /dev/null +++ b/third_party/tcmalloc/chromium/src/base/atomicops-internals-mips.h
@@ -0,0 +1,323 @@ +// -*- Mode: C++; c-basic-offset: 2; indent-tabs-mode: nil -*- +/* Copyright (c) 2013, Google Inc. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are + * met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above + * copyright notice, this list of conditions and the following disclaimer + * in the documentation and/or other materials provided with the + * distribution. + * * Neither the name of Google Inc. nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR + * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT + * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +// Author: Jovan Zelincevic <jovan.zelincevic@imgtec.com> +// based on atomicops-internals by Sanjay Ghemawat + +// This file is an internal atomic implementation, use base/atomicops.h instead. +// +// This code implements MIPS atomics. + +#ifndef BASE_ATOMICOPS_INTERNALS_MIPS_H_ +#define BASE_ATOMICOPS_INTERNALS_MIPS_H_ + +#if (_MIPS_ISA == _MIPS_ISA_MIPS64) +#define BASE_HAS_ATOMIC64 1 +#endif + +typedef int32_t Atomic32; + +namespace base { +namespace subtle { + +// Atomically execute: +// result = *ptr; +// if (*ptr == old_value) +// *ptr = new_value; +// return result; +// +// I.e., replace "*ptr" with "new_value" if "*ptr" used to be "old_value". +// Always return the old value of "*ptr" +// +// This routine implies no memory barriers. +inline Atomic32 NoBarrier_CompareAndSwap(volatile Atomic32* ptr, + Atomic32 old_value, + Atomic32 new_value) +{ + Atomic32 prev, tmp; + __asm__ volatile( + ".set push \n" + ".set noreorder \n" + + "1: \n" + "ll %0, %5 \n" // prev = *ptr + "bne %0, %3, 2f \n" // if (prev != old_value) goto 2 + " move %2, %4 \n" // tmp = new_value + "sc %2, %1 \n" // *ptr = tmp (with atomic check) + "beqz %2, 1b \n" // start again on atomic error + " nop \n" // delay slot nop + "2: \n" + + ".set pop \n" + : "=&r" (prev), "=m" (*ptr), + "=&r" (tmp) + : "Ir" (old_value), "r" (new_value), + "m" (*ptr) + : "memory" + ); + return prev; +} + +// Atomically store new_value into *ptr, returning the previous value held in +// *ptr. This routine implies no memory barriers. +inline Atomic32 NoBarrier_AtomicExchange(volatile Atomic32* ptr, + Atomic32 new_value) +{ + Atomic32 temp, old; + __asm__ volatile( + ".set push \n" + ".set noreorder \n" + + "1: \n" + "ll %1, %2 \n" // old = *ptr + "move %0, %3 \n" // temp = new_value + "sc %0, %2 \n" // *ptr = temp (with atomic check) + "beqz %0, 1b \n" // start again on atomic error + " nop \n" // delay slot nop + + ".set pop \n" + : "=&r" (temp), "=&r" (old), + "=m" (*ptr) + : "r" (new_value), "m" (*ptr) + : "memory" + ); + return old; +} + +inline void MemoryBarrier() +{ + __asm__ volatile("sync" : : : "memory"); +} + +// "Acquire" operations +// ensure that no later memory access can be reordered ahead of the operation. +// "Release" operations ensure that no previous memory access can be reordered +// after the operation. "Barrier" operations have both "Acquire" and "Release" +// semantics. A MemoryBarrier() has "Barrier" semantics, but does no memory +// access. +inline Atomic32 Acquire_CompareAndSwap(volatile Atomic32* ptr, + Atomic32 old_value, + Atomic32 new_value) +{ + Atomic32 res = NoBarrier_CompareAndSwap(ptr, old_value, new_value); + MemoryBarrier(); + return res; +} + +inline Atomic32 Release_CompareAndSwap(volatile Atomic32* ptr, + Atomic32 old_value, + Atomic32 new_value) +{ + MemoryBarrier(); + Atomic32 res = NoBarrier_CompareAndSwap(ptr, old_value, new_value); + return res; +} + +inline void NoBarrier_Store(volatile Atomic32* ptr, Atomic32 value) +{ + *ptr = value; +} + +inline Atomic32 Acquire_AtomicExchange(volatile Atomic32* ptr, + Atomic32 new_value) +{ + Atomic32 old_value = NoBarrier_AtomicExchange(ptr, new_value); + MemoryBarrier(); + return old_value; +} + +inline Atomic32 Release_AtomicExchange(volatile Atomic32* ptr, + Atomic32 new_value) +{ + MemoryBarrier(); + return NoBarrier_AtomicExchange(ptr, new_value); +} + +inline void Acquire_Store(volatile Atomic32* ptr, Atomic32 value) +{ + *ptr = value; + MemoryBarrier(); +} + +inline void Release_Store(volatile Atomic32* ptr, Atomic32 value) +{ + MemoryBarrier(); + *ptr = value; +} + +inline Atomic32 NoBarrier_Load(volatile const Atomic32* ptr) +{ + return *ptr; +} + +inline Atomic32 Acquire_Load(volatile const Atomic32* ptr) +{ + Atomic32 value = *ptr; + MemoryBarrier(); + return value; +} + +inline Atomic32 Release_Load(volatile const Atomic32* ptr) +{ + MemoryBarrier(); + return *ptr; +} + +#if (_MIPS_ISA == _MIPS_ISA_MIPS64) || (_MIPS_SIM == _MIPS_SIM_ABI64) + +typedef int64_t Atomic64; + +inline Atomic64 NoBarrier_CompareAndSwap(volatile Atomic64* ptr, + Atomic64 old_value, + Atomic64 new_value) +{ + Atomic64 prev, tmp; + __asm__ volatile( + ".set push \n" + ".set noreorder \n" + + "1: \n" + "lld %0, %5 \n" // prev = *ptr + "bne %0, %3, 2f \n" // if (prev != old_value) goto 2 + " move %2, %4 \n" // tmp = new_value + "scd %2, %1 \n" // *ptr = tmp (with atomic check) + "beqz %2, 1b \n" // start again on atomic error + " nop \n" // delay slot nop + "2: \n" + + ".set pop \n" + : "=&r" (prev), "=m" (*ptr), + "=&r" (tmp) + : "Ir" (old_value), "r" (new_value), + "m" (*ptr) + : "memory" + ); + return prev; +} + +inline Atomic64 NoBarrier_AtomicExchange(volatile Atomic64* ptr, + Atomic64 new_value) +{ + Atomic64 temp, old; + __asm__ volatile( + ".set push \n" + ".set noreorder \n" + + "1: \n" + "lld %1, %2 \n" // old = *ptr + "move %0, %3 \n" // temp = new_value + "scd %0, %2 \n" // *ptr = temp (with atomic check) + "beqz %0, 1b \n" // start again on atomic error + " nop \n" // delay slot nop + + ".set pop \n" + : "=&r" (temp), "=&r" (old), + "=m" (*ptr) + : "r" (new_value), "m" (*ptr) + : "memory" + ); + return old; +} + +inline Atomic64 Acquire_AtomicExchange(volatile Atomic64* ptr, + Atomic64 new_value) +{ + Atomic64 old_value = NoBarrier_AtomicExchange(ptr, new_value); + MemoryBarrier(); + return old_value; +} + +inline Atomic64 Acquire_CompareAndSwap(volatile Atomic64* ptr, + Atomic64 old_value, + Atomic64 new_value) +{ + Atomic64 res = NoBarrier_CompareAndSwap(ptr, old_value, new_value); + MemoryBarrier(); + return res; +} + +inline Atomic64 Release_CompareAndSwap(volatile Atomic64* ptr, + Atomic64 old_value, + Atomic64 new_value) +{ + MemoryBarrier(); + Atomic64 res = NoBarrier_CompareAndSwap(ptr, old_value, new_value); + return res; +} + +inline void NoBarrier_Store(volatile Atomic64* ptr, Atomic64 value) +{ + *ptr = value; +} + +inline Atomic64 Release_AtomicExchange(volatile Atomic64* ptr, + Atomic64 new_value) +{ + MemoryBarrier(); + return NoBarrier_AtomicExchange(ptr, new_value); +} + +inline void Acquire_Store(volatile Atomic64* ptr, Atomic64 value) +{ + *ptr = value; + MemoryBarrier(); +} + +inline void Release_Store(volatile Atomic64* ptr, Atomic64 value) +{ + MemoryBarrier(); + *ptr = value; +} + +inline Atomic64 NoBarrier_Load(volatile const Atomic64* ptr) +{ + return *ptr; +} + +inline Atomic64 Acquire_Load(volatile const Atomic64* ptr) +{ + Atomic64 value = *ptr; + MemoryBarrier(); + return value; +} + +inline Atomic64 Release_Load(volatile const Atomic64* ptr) +{ + MemoryBarrier(); + return *ptr; +} + +#endif + +} // namespace base::subtle +} // namespace base + +#endif // BASE_ATOMICOPS_INTERNALS_MIPS_H_
diff --git a/third_party/tcmalloc/chromium/src/base/atomicops.h b/third_party/tcmalloc/chromium/src/base/atomicops.h index 17e8a27..9f7af79 100644 --- a/third_party/tcmalloc/chromium/src/base/atomicops.h +++ b/third_party/tcmalloc/chromium/src/base/atomicops.h
@@ -101,6 +101,8 @@ #include "base/atomicops-internals-x86.h" #elif defined(__linux__) && defined(__PPC__) #include "base/atomicops-internals-linuxppc.h" +#elif defined(__GNUC__) && defined(__mips__) +#include "base/atomicops-internals-mips.h" #else // Assume x86 for now. If you need to support a new architecture and // don't know how to implement atomic ops, you can probably get away
diff --git a/third_party/tcmalloc/chromium/src/common.h b/third_party/tcmalloc/chromium/src/common.h index c8ceb61..11f4c87 100644 --- a/third_party/tcmalloc/chromium/src/common.h +++ b/third_party/tcmalloc/chromium/src/common.h
@@ -81,9 +81,14 @@ #else // Original TCMalloc code used kPageShift == 13. In Chromium, we changed // this to 12 (as was done in prior versions of TCMalloc). +#if defined(_MIPS_ARCH_LOONGSON) +static const size_t kPageShift = 14; +static const size_t kNumClasses = 70 - kSkippedClasses; +#else static const size_t kPageShift = 12; static const size_t kNumClasses = 54 - kSkippedClasses; #endif +#endif static const size_t kMaxThreadCacheSize = 4 << 20; static const size_t kPageSize = 1 << kPageShift;
diff --git a/third_party/tcmalloc/chromium/src/stacktrace_config.h b/third_party/tcmalloc/chromium/src/stacktrace_config.h index a462ceb0..c356734 100644 --- a/third_party/tcmalloc/chromium/src/stacktrace_config.h +++ b/third_party/tcmalloc/chromium/src/stacktrace_config.h
@@ -80,6 +80,14 @@ # error stacktrace without frame pointer is not supported on ARM # endif +// The Mips case +#elif defined(__GNUC__) && defined(__mips__) +# if !defined(NO_FRAME_POINTER) +# define STACKTRACE_INL_HEADER "stacktrace_mips-inl.h" +# else +# define STACKTRACE_INL_HEADER "stacktrace_generic-inl.h" +# endif + // The Windows case -- probably cygwin and mingw will use one of the // x86-includes above, but if not, we can fall back to windows intrinsics. #elif defined(_WIN32) || defined(__CYGWIN__) || defined(__CYGWIN32__) || defined(__MINGW32__)
diff --git a/third_party/tcmalloc/chromium/src/stacktrace_mips-inl.h b/third_party/tcmalloc/chromium/src/stacktrace_mips-inl.h new file mode 100644 index 0000000..971abac --- /dev/null +++ b/third_party/tcmalloc/chromium/src/stacktrace_mips-inl.h
@@ -0,0 +1,397 @@ +// Copyright (c) 2005, Google Inc. +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above +// copyright notice, this list of conditions and the following disclaimer +// in the documentation and/or other materials provided with the +// distribution. +// * Neither the name of Google Inc. nor the names of its +// contributors may be used to endorse or promote products derived from +// this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +// --- +// Author: Sanjay Ghemawat +// +// Produce stack trace + +#ifndef BASE_STACKTRACE_MIPS_INL_H_ +#define BASE_STACKTRACE_MIPS_INL_H_ +// Note: this file is included into stacktrace.cc more than once. +// Anything that should only be defined once should be here: + +#include "config.h" +#include <stdlib.h> // for NULL +#include <assert.h> +#if defined(HAVE_SYS_UCONTEXT_H) +#include <sys/ucontext.h> +#elif defined(HAVE_UCONTEXT_H) +#include <ucontext.h> // for ucontext_t +#elif defined(HAVE_CYGWIN_SIGNAL_H) +// cygwin/signal.h has a buglet where it uses pthread_attr_t without +// #including <pthread.h> itself. So we have to do it. +# ifdef HAVE_PTHREAD +# include <pthread.h> +# endif +#include <cygwin/signal.h> +typedef ucontext ucontext_t; +#endif +#ifdef HAVE_STDINT_H +#include <stdint.h> // for uintptr_t +#endif +#ifdef HAVE_UNISTD_H +#include <unistd.h> +#endif +#ifdef HAVE_MMAP +#include <sys/mman.h> // for msync +#include "base/vdso_support.h" +#endif + +#include "gperftools/stacktrace.h" +#if defined(KEEP_SHADOW_STACKS) +#include "linux_shadow_stacks.h" +#endif // KEEP_SHADOW_STACKS + +#if defined(__linux__) && defined(__mips32) && defined(__ELF__) && defined(HAVE_MMAP) +// Count "push %reg" instructions in VDSO __kernel_vsyscall(), +// preceeding "syscall" or "sysenter". +// If __kernel_vsyscall uses frame pointer, answer 0. +// +// kMaxBytes tells how many instruction bytes of __kernel_vsyscall +// to analyze before giving up. Up to kMaxBytes+1 bytes of +// instructions could be accessed. +// +// Here are known __kernel_vsyscall instruction sequences: +// +// SYSENTER (linux-2.6.26/arch/x86/vdso/vdso32/sysenter.S). +// Used on Intel. +// 0xffffe400 <__kernel_vsyscall+0>: push %ecx +// 0xffffe401 <__kernel_vsyscall+1>: push %edx +// 0xffffe402 <__kernel_vsyscall+2>: push %ebp +// 0xffffe403 <__kernel_vsyscall+3>: mov %esp,%ebp +// 0xffffe405 <__kernel_vsyscall+5>: sysenter +// +// SYSCALL (see linux-2.6.26/arch/x86/vdso/vdso32/syscall.S). +// Used on AMD. +// 0xffffe400 <__kernel_vsyscall+0>: push %ebp +// 0xffffe401 <__kernel_vsyscall+1>: mov %ecx,%ebp +// 0xffffe403 <__kernel_vsyscall+3>: syscall +// +// i386 (see linux-2.6.26/arch/x86/vdso/vdso32/int80.S) +// 0xffffe400 <__kernel_vsyscall+0>: int $0x80 +// 0xffffe401 <__kernel_vsyscall+1>: ret +// +static const int kMaxBytes = 10; + +// We use assert()s instead of DCHECK()s -- this is too low level +// for DCHECK(). + +static int CountPushInstructions(const unsigned char *const addr) { + int result = 0; + for (int i = 0; i < kMaxBytes; ++i) { + if (addr[i] == 0x89) { + // "mov reg,reg" + if (addr[i + 1] == 0xE5) { + // Found "mov %esp,%ebp". + return 0; + } + ++i; // Skip register encoding byte. + } else if (addr[i] == 0x0F && + (addr[i + 1] == 0x34 || addr[i + 1] == 0x05)) { + // Found "sysenter" or "syscall". + return result; + } else if ((addr[i] & 0xF0) == 0x50) { + // Found "push %reg". + ++result; + } else if (addr[i] == 0xCD && addr[i + 1] == 0x80) { + // Found "int $0x80" + assert(result == 0); + return 0; + } else { + // Unexpected instruction. + assert(0 == "unexpected instruction in __kernel_vsyscall"); + return 0; + } + } + // Unexpected: didn't find SYSENTER or SYSCALL in + // [__kernel_vsyscall, __kernel_vsyscall + kMaxBytes) interval. + assert(0 == "did not find SYSENTER or SYSCALL in __kernel_vsyscall"); + return 0; +} +#endif + +// Given a pointer to a stack frame, locate and return the calling +// stackframe, or return NULL if no stackframe can be found. Perform sanity +// checks (the strictness of which is controlled by the boolean parameter +// "STRICT_UNWINDING") to reduce the chance that a bad pointer is returned. +template<bool STRICT_UNWINDING, bool WITH_CONTEXT> +static void **NextStackFrame(void **old_sp, const void *uc) { + void **new_sp = (void **) *old_sp; + +#if defined(__linux__) && defined(__mips32) && defined(HAVE_VDSO_SUPPORT) + if (WITH_CONTEXT && uc != NULL) { + // How many "push %reg" instructions are there at __kernel_vsyscall? + // This is constant for a given kernel and processor, so compute + // it only once. + static int num_push_instructions = -1; // Sentinel: not computed yet. + // Initialize with sentinel value: __kernel_rt_sigreturn can not possibly + // be there. + static const unsigned char *kernel_rt_sigreturn_address = NULL; + static const unsigned char *kernel_vsyscall_address = NULL; + if (num_push_instructions == -1) { + base::VDSOSupport vdso; + if (vdso.IsPresent()) { + base::VDSOSupport::SymbolInfo rt_sigreturn_symbol_info; + base::VDSOSupport::SymbolInfo vsyscall_symbol_info; + if (!vdso.LookupSymbol("__kernel_rt_sigreturn", "LINUX_2.5", + STT_FUNC, &rt_sigreturn_symbol_info) || + !vdso.LookupSymbol("__kernel_vsyscall", "LINUX_2.5", + STT_FUNC, &vsyscall_symbol_info) || + rt_sigreturn_symbol_info.address == NULL || + vsyscall_symbol_info.address == NULL) { + // Unexpected: 32-bit VDSO is present, yet one of the expected + // symbols is missing or NULL. + assert(0 == "VDSO is present, but doesn't have expected symbols"); + num_push_instructions = 0; + } else { + kernel_rt_sigreturn_address = + reinterpret_cast<const unsigned char *>( + rt_sigreturn_symbol_info.address); + kernel_vsyscall_address = + reinterpret_cast<const unsigned char *>( + vsyscall_symbol_info.address); + num_push_instructions = + CountPushInstructions(kernel_vsyscall_address); + } + } else { + num_push_instructions = 0; + } + } + if (num_push_instructions != 0 && kernel_rt_sigreturn_address != NULL && + old_sp[1] == kernel_rt_sigreturn_address) { + const ucontext_t *ucv = static_cast<const ucontext_t *>(uc); + // This kernel does not use frame pointer in its VDSO code, + // and so %ebp is not suitable for unwinding. + void **const reg_ebp = + reinterpret_cast<void **>(ucv->uc_mcontext.gregs[REG_EBP]); + const unsigned char *const reg_eip = + reinterpret_cast<unsigned char *>(ucv->uc_mcontext.gregs[REG_EIP]); + if (new_sp == reg_ebp && + kernel_vsyscall_address <= reg_eip && + reg_eip - kernel_vsyscall_address < kMaxBytes) { + // We "stepped up" to __kernel_vsyscall, but %ebp is not usable. + // Restore from 'ucv' instead. + void **const reg_esp = + reinterpret_cast<void **>(ucv->uc_mcontext.gregs[REG_ESP]); + // Check that alleged %esp is not NULL and is reasonably aligned. + if (reg_esp && + ((uintptr_t)reg_esp & (sizeof(reg_esp) - 1)) == 0) { + // Check that alleged %esp is actually readable. This is to prevent + // "double fault" in case we hit the first fault due to e.g. stack + // corruption. + // + // page_size is linker-initalized to avoid async-unsafe locking + // that GCC would otherwise insert (__cxa_guard_acquire etc). + static int page_size; + if (page_size == 0) { + // First time through. + page_size = getpagesize(); + } + void *const reg_esp_aligned = + reinterpret_cast<void *>( + (uintptr_t)(reg_esp + num_push_instructions - 1) & + ~(page_size - 1)); + if (msync(reg_esp_aligned, page_size, MS_ASYNC) == 0) { + // Alleged %esp is readable, use it for further unwinding. + new_sp = reinterpret_cast<void **>( + reg_esp[num_push_instructions - 1]); + } + } + } + } + } +#endif + + // Check that the transition from frame pointer old_sp to frame + // pointer new_sp isn't clearly bogus + if (STRICT_UNWINDING) { + // With the stack growing downwards, older stack frame must be + // at a greater address that the current one. + if (new_sp <= old_sp) return NULL; + // Assume stack frames larger than 100,000 bytes are bogus. + if ((uintptr_t)new_sp - (uintptr_t)old_sp > 100000) return NULL; + } else { + // In the non-strict mode, allow discontiguous stack frames. + // (alternate-signal-stacks for example). + if (new_sp == old_sp) return NULL; + if (new_sp > old_sp) { + // And allow frames upto about 1MB. + const uintptr_t delta = (uintptr_t)new_sp - (uintptr_t)old_sp; + const uintptr_t acceptable_delta = 1000000; + if (delta > acceptable_delta) { + return NULL; + } + } + } + if ((uintptr_t)new_sp & (sizeof(void *) - 1)) return NULL; +#ifdef __mips32 + // On 64-bit machines, the stack pointer can be very close to + // 0xffffffff, so we explicitly check for a pointer into the + // last two pages in the address space + if ((uintptr_t)new_sp >= 0xffffe000) return NULL; +#endif +#ifdef HAVE_MMAP + if (!STRICT_UNWINDING) { + // Lax sanity checks cause a crash on AMD-based machines with + // VDSO-enabled kernels. + // Make an extra sanity check to insure new_sp is readable. + // Note: NextStackFrame<false>() is only called while the program + // is already on its last leg, so it's ok to be slow here. + static int page_size = getpagesize(); + void *new_sp_aligned = (void *)((uintptr_t)new_sp & ~(page_size - 1)); + if (msync(new_sp_aligned, page_size, MS_ASYNC) == -1) + return NULL; + } +#endif + return new_sp; +} + +#endif // BASE_STACKTRACE_MIPS_INL_H_ + +// Note: this part of the file is included several times. +// Do not put globals below. + +// The following 4 functions are generated from the code below: +// GetStack{Trace,Frames}() +// GetStack{Trace,Frames}WithContext() +// +// These functions take the following args: +// void** result: the stack-trace, as an array +// int* sizes: the size of each stack frame, as an array +// (GetStackFrames* only) +// int max_depth: the size of the result (and sizes) array(s) +// int skip_count: how many stack pointers to skip before storing in result +// void* ucp: a ucontext_t* (GetStack{Trace,Frames}WithContext only) + +int GET_STACK_TRACE_OR_FRAMES { + void **sp; +#if (__GNUC__ > 4) || (__GNUC__ == 4 && __GNUC_MINOR__ >= 2) || __llvm__ + // __builtin_frame_address(0) can return the wrong address on gcc-4.1.0-k8. + // It's always correct on llvm, and the techniques below aren't (in + // particular, llvm-gcc will make a copy of pcs, so it's not in sp[2]), + // so we also prefer __builtin_frame_address when running under llvm. + sp = reinterpret_cast<void**>(__builtin_frame_address(0)); +#elif defined(__mips32) + // Stack frame format: + // sp[0] pointer to previous frame + // sp[1] caller address + // sp[2] first argument + // ... + // NOTE: This will break under llvm, since result is a copy and not in sp[2] + sp = (void **)&result - 2; +#elif defined(__mips64) + unsigned long t8; + // Move the value of the register %a6 into the local variable a6. + // We need 'volatile' to prevent this instruction from getting moved + // around during optimization to before function prologue is done. + // An alternative way to achieve this + // would be (before this __asm__ instruction) to call Noop() defined as + // static void Noop() __attribute__ ((noinline)); // prevent inlining + // static void Noop() { asm(""); } // prevent optimizing-away + __asm__ volatile ("mov %%t8, %0" : "=r" (t8)); + // Arguments are passed in registers on mips64, so we can't just + // offset from &result + sp = (void **) t8; +#else +# error Using stacktrace_mips-inl.h on a non mips architecture! +#endif + + int n = 0; +#if defined(KEEP_SHADOW_STACKS) + void **shadow_ip_stack; + void **shadow_sp_stack; + int stack_size; + shadow_ip_stack = (void**) get_shadow_ip_stack(&stack_size); + shadow_sp_stack = (void**) get_shadow_sp_stack(&stack_size); + int shadow_index = stack_size - 1; + for (int i = stack_size - 1; i >= 0; i--) { + if (sp == shadow_sp_stack[i]) { + shadow_index = i; + break; + } + } + void **prev_sp = NULL; +#endif // KEEP_SHADOW_STACKS + while (sp && n < max_depth) { + if (*(sp+1) == reinterpret_cast<void *>(0)) { + // In 64-bit code, we often see a frame that + // points to itself and has a return address of 0. + break; + } +#if !IS_WITH_CONTEXT + const void *const ucp = NULL; +#endif + void **next_sp = NextStackFrame<!IS_STACK_FRAMES, IS_WITH_CONTEXT>(sp, ucp); + if (skip_count > 0) { + skip_count--; +#if defined(KEEP_SHADOW_STACKS) + shadow_index--; +#endif // KEEP_SHADOW_STACKS + } else { + result[n] = *(sp+1); +#if defined(KEEP_SHADOW_STACKS) + if ((shadow_index > 0) && (sp == shadow_sp_stack[shadow_index])) { + shadow_index--; + } +#endif // KEEP_SHADOW_STACKS + +#if IS_STACK_FRAMES + if (next_sp > sp) { + sizes[n] = (uintptr_t)next_sp - (uintptr_t)sp; + } else { + // A frame-size of 0 is used to indicate unknown frame size. + sizes[n] = 0; + } +#endif + n++; + } +#if defined(KEEP_SHADOW_STACKS) + prev_sp = sp; +#endif // KEEP_SHADOW_STACKS + sp = next_sp; + } + +#if defined(KEEP_SHADOW_STACKS) + if (shadow_index >= 0) { + for (int i = shadow_index; i >= 0; i--) { + if (shadow_sp_stack[i] > prev_sp) { + result[n] = shadow_ip_stack[i]; + if (n + 1 < max_depth) { + n++; + continue; + } + } + break; + } + } +#endif // KEEP_SHADOW_STACKS + return n; +} +
diff --git a/third_party/webrtc_overrides/rtc_base/event.h b/third_party/webrtc_overrides/rtc_base/event.h index c474bcda..256b353 100644 --- a/third_party/webrtc_overrides/rtc_base/event.h +++ b/third_party/webrtc_overrides/rtc_base/event.h
@@ -7,6 +7,7 @@ #include "base/macros.h" #include "base/synchronization/waitable_event.h" +#include "base/threading/thread_restrictions.h" namespace rtc { @@ -30,6 +31,11 @@ DISALLOW_IMPLICIT_CONSTRUCTORS(Event); }; +// Pull ScopedAllowBaseSyncPrimitives into the rtc namespace. +// Managing what types in WebRTC are allowed to use +// ScopedAllowBaseSyncPrimitives, is done via thread_restrictions.h. +using base::ScopedAllowBaseSyncPrimitives; + } // namespace rtc #endif // THIRD_PARTY_WEBRTC_OVERRIDES_RTC_BASE_EVENT_H_
diff --git a/tools/battor_agent/battor_agent.cc b/tools/battor_agent/battor_agent.cc index af628cb8..231581b 100644 --- a/tools/battor_agent/battor_agent.cc +++ b/tools/battor_agent/battor_agent.cc
@@ -435,6 +435,7 @@ // Clear stored samples from prior attempts to read sample frames. samples_.clear(); calibration_frame_.clear(); + FALLTHROUGH; case Action::READ_DATA_FRAME: // The first frame sent back from the BattOr contains voltage and current // data that excludes whatever device is being measured from the
diff --git a/tools/chrome_proxy/webdriver/video.py b/tools/chrome_proxy/webdriver/video.py index aeea8eb..cb3b4840 100644 --- a/tools/chrome_proxy/webdriver/video.py +++ b/tools/chrome_proxy/webdriver/video.py
@@ -123,7 +123,7 @@ @Slow def testVideoMetrics(self): expected = { - 'duration': 3.128, + 'duration': 3.068, 'webkitDecodedFrameCount': 54.0, 'videoWidth': 1280.0, 'videoHeight': 720.0
diff --git a/tools/clang/pylib/clang/compile_db.py b/tools/clang/pylib/clang/compile_db.py index 1f1bc81..c4eecb60 100755 --- a/tools/clang/pylib/clang/compile_db.py +++ b/tools/clang/pylib/clang/compile_db.py
@@ -73,8 +73,8 @@ def GetNinjaPath(): return os.path.join( - os.path.dirname(os.realpath(__file__)), '..', '..', '..', 'third_party', - 'depot_tools', 'ninja') + os.path.dirname(os.path.realpath(__file__)), + '..', '..', '..', '..', 'third_party', 'depot_tools', 'ninja') # FIXME: This really should be a build target, rather than generated at runtime.
diff --git a/tools/cygprofile/patch_orderfile.py b/tools/cygprofile/patch_orderfile.py index 6d765ef..da30365 100755 --- a/tools/cygprofile/patch_orderfile.py +++ b/tools/cygprofile/patch_orderfile.py
@@ -385,10 +385,15 @@ # See the comment in //base/android/library_loader/anchor_functions.cc. for prefix in _PREFIXES: f.write(prefix + 'dummy_function_to_anchor_text\n') + for prefix in _PREFIXES: + f.write(prefix + 'dummy_function_start_of_ordered_text\n') for section in expanded_sections: f.write(section + '\n') + for prefix in _PREFIXES: + f.write(prefix + 'dummy_function_end_of_ordered_text\n') + # The following is needed otherwise Gold only applies a partial sort. f.write('.text\n') # gets methods not in a section, such as assembly f.write('.text.*\n') # gets everything else
diff --git a/tools/cygprofile/phased_orderfile.py b/tools/cygprofile/phased_orderfile.py new file mode 100755 index 0000000..49469de --- /dev/null +++ b/tools/cygprofile/phased_orderfile.py
@@ -0,0 +1,199 @@ +#!/usr/bin/python +# 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. + +"""Utilities for creating a phased orderfile. + +This kind of orderfile is based on cygprofile lightweight instrumentation. The +profile dump format is described in process_profiles.py. These tools assume +profiling has been done with two phases. + +The first phase, labeled 0 in the filename, is called "startup" and the second, +labeled 1, is called "interaction". These two phases are used to create an +orderfile with three parts: the code touched only in startup, the code +touched only during interaction, and code common to the two phases. We refer to +these parts as the orderfile phases. +""" + +import argparse +import collections +import glob +import itertools +import logging +import os.path + +import process_profiles + + +# Files matched when using this script to analyze directly (see main()). +PROFILE_GLOB = 'cygprofile-*.txt_*' + + +OrderfilePhaseOffsets = collections.namedtuple( + 'OrderfilePhaseOffsets', ('startup', 'common', 'interaction')) + + +class PhasedAnalyzer(object): + """A class which collects analysis around phased orderfiles. + + It maintains common data such as symbol table information to make analysis + more convenient. + """ + # These figures are taken from running memory and speedometer telemetry + # benchmarks, and are still subject to change as of 2018-01-24. + STARTUP_STABILITY_THRESHOLD = 1.5 + COMMON_STABILITY_THRESHOLD = 1.75 + INTERACTION_STABILITY_THRESHOLD = 2.5 + + def __init__(self, profiles, processor): + """Intialize. + + Args: + profiles (ProfileManager) Manager of the profile dump files. + processor (SymbolOffsetProcessor) Symbol table processor for the dumps. + """ + self._profiles = profiles + self._processor = processor + self._phase_offsets = None + + def IsStableProfile(self): + """Verify that the profiling has been stable. + + See ComputeStability for details. + + Returns: + True if the profile was stable as described above. + """ + (startup_stability, common_stability, + interaction_stability) = self.ComputeStability() + + stable = True + if startup_stability > self.STARTUP_STABILITY_THRESHOLD: + logging.error('Startup unstable: %.3f', startup_stability) + stable = False + if common_stability > self.COMMON_STABILITY_THRESHOLD: + logging.error('Common unstable: %.3f', common_stability) + stable = False + if interaction_stability > self.INTERACTION_STABILITY_THRESHOLD: + logging.error('Interaction unstable: %.3f', interaction_stability) + stable = False + + return stable + + def ComputeStability(self): + """Compute heuristic phase stability metrics. + + This computes the ratio in size of symbols between the union and + intersection of all orderfile phases. Intuitively if this ratio is not too + large it means that the profiling phases are stable with respect to the code + they cover. + + Returns: + (float, float, float) A heuristic stability metric for startup, common and + interaction orderfile phases, respectively. + """ + phase_offsets = self._GetOrderfilePhaseOffsets() + assert len(phase_offsets) > 1 # Otherwise the analysis is silly. + + startup_union = set(phase_offsets[0].startup) + startup_intersection = set(phase_offsets[0].startup) + common_union = set(phase_offsets[0].common) + common_intersection = set(phase_offsets[0].common) + interaction_union = set(phase_offsets[0].interaction) + interaction_intersection = set(phase_offsets[0].interaction) + for offsets in phase_offsets[1:]: + startup_union |= set(offsets.startup) + startup_intersection &= set(offsets.startup) + common_union |= set(offsets.common) + common_intersection &= set(offsets.common) + interaction_union |= set(offsets.interaction) + interaction_intersection &= set(offsets.interaction) + startup_stability = self._SafeDiv( + self._processor.OffsetsPrimarySize(startup_union), + self._processor.OffsetsPrimarySize(startup_intersection)) + common_stability = self._SafeDiv( + self._processor.OffsetsPrimarySize(common_union), + self._processor.OffsetsPrimarySize(common_intersection)) + interaction_stability = self._SafeDiv( + self._processor.OffsetsPrimarySize(interaction_union), + self._processor.OffsetsPrimarySize(interaction_intersection)) + return (startup_stability, common_stability, interaction_stability) + + def _GetOrderfilePhaseOffsets(self): + """Compute the phase offsets for each run. + + Returns: + [OrderfilePhaseOffsets] Each run corresponds to an OrderfilePhaseOffsets, + which groups the symbol offsets discovered in the runs. + """ + if self._phase_offsets is not None: + return self._phase_offsets + + assert self._profiles.GetPhases() == set([0, 1]), 'Unexpected phases' + self._phase_offsets = [] + for first, second in zip(self._profiles.GetRunGroupOffsets(phase=0), + self._profiles.GetRunGroupOffsets(phase=1)): + all_first_offsets = self._processor.GetReachedOffsetsFromDump(first) + all_second_offsets = self._processor.GetReachedOffsetsFromDump(second) + first_offsets_set = set(all_first_offsets) + second_offsets_set = set(all_second_offsets) + common_offsets_set = first_offsets_set & second_offsets_set + first_offsets_set -= common_offsets_set + second_offsets_set -= common_offsets_set + + startup = [x for x in all_first_offsets + if x in first_offsets_set] + + interaction = [x for x in all_second_offsets + if x in second_offsets_set] + + common_seen = set() + common = [] + for x in itertools.chain(all_first_offsets, all_second_offsets): + if x in common_offsets_set and x not in common_seen: + common_seen.add(x) + common.append(x) + + self._phase_offsets.append(OrderfilePhaseOffsets( + startup=startup, + interaction=interaction, + common=common)) + + return self._phase_offsets + + @classmethod + def _SafeDiv(cls, a, b): + if not b: + return None + return float(a) / b + + +def _CreateArgumentParser(): + parser = argparse.ArgumentParser( + description='Compute statistics on phased orderfiles') + parser.add_argument('--profile-directory', type=str, required=True, + help=('Directory containing profile runs. Files ' + 'matching {} are used.'.format(PROFILE_GLOB))) + parser.add_argument('--instrumented-build-dir', type=str, + help='Path to the instrumented build', required=True) + parser.add_argument('--library-name', default='libchrome.so', + help=('Chrome shared library name (usually libchrome.so ' + 'or libmonochrome.so')) + return parser + + +def main(): + logging.basicConfig(level=logging.INFO) + parser = _CreateArgumentParser() + args = parser.parse_args() + profiles = process_profiles.ProfileManager( + glob.glob(os.path.join(args.profile_directory, PROFILE_GLOB))) + processor = process_profiles.SymbolOffsetProcessor(os.path.join( + args.instrumented_build_dir, 'lib.unstripped', args.library_name)) + phaser = PhasedAnalyzer(profiles, processor) + print 'Stability: {:.2f} {:.2f} {:.2f}'.format(*phaser.ComputeStability()) + + +if __name__ == '__main__': + main()
diff --git a/tools/cygprofile/phased_orderfile_unittest.py b/tools/cygprofile/phased_orderfile_unittest.py new file mode 100644 index 0000000..24ca356 --- /dev/null +++ b/tools/cygprofile/phased_orderfile_unittest.py
@@ -0,0 +1,92 @@ +# 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. + +"""Tests for phased_orderfile.py.""" + +import collections +import unittest + +import phased_orderfile +import process_profiles + +SymbolInfo = collections.namedtuple('SymbolInfo', ['name', 'offset', 'size']) + + +class TestProfileManager(process_profiles.ProfileManager): + def __init__(self, filecontents_mapping): + super(TestProfileManager, self).__init__(filecontents_mapping.keys()) + self._filecontents_mapping = filecontents_mapping + + def _ReadOffsets(self, filename): + return self._filecontents_mapping[filename] + + +class TestSymbolOffsetProcessor(process_profiles.SymbolOffsetProcessor): + def __init__(self, symbol_infos): + super(TestSymbolOffsetProcessor, self).__init__(None) + self._symbol_infos = symbol_infos + + +class Mod10Processor(object): + """A restricted mock for a SymbolOffsetProcessor. + + This only implements GetReachedOffsetsFromDump, and works by mapping a dump + offset to offset - (offset % 10). If the dump offset is negative, it is marked + as not found. + """ + def GetReachedOffsetsFromDump(self, dump): + return [x - (x % 10) for x in dump if x >= 0] + + +class PhasedOrderfileTestCase(unittest.TestCase): + + def setUp(self): + self._file_counter = 0 + + def File(self, timestamp_sec, phase): + self._file_counter += 1 + return 'file-{}-{}.txt_{}'.format( + self._file_counter, timestamp_sec * 1000 * 1000 * 1000, phase) + + def testProfileStability(self): + symbols = [SymbolInfo(str(i), i, 10) + for i in xrange(20)] + phaser = phased_orderfile.PhasedAnalyzer( + None, TestSymbolOffsetProcessor(symbols)) + opo = lambda s, c, i: phased_orderfile.OrderfilePhaseOffsets( + startup=s, common=c, interaction=i) + phaser._phase_offsets = [opo(range(5), range(6, 10), range(11,15)), + opo(range(4), range(6, 10), range(18, 20))] + self.assertEquals((1.25, 1, None), phaser.ComputeStability()) + + def testIsStable(self): + symbols = [SymbolInfo(str(i), i, 10) + for i in xrange(20)] + phaser = phased_orderfile.PhasedAnalyzer( + None, TestSymbolOffsetProcessor(symbols)) + opo = lambda s, c, i: phased_orderfile.OrderfilePhaseOffsets( + startup=s, common=c, interaction=i) + phaser._phase_offsets = [opo(range(5), range(6, 10), range(11,15)), + opo(range(4), range(6, 10), range(18, 20))] + phaser.STARTUP_STABILITY_THRESHOLD = 1.1 + self.assertFalse(phaser.IsStableProfile()) + phaser.STARTUP_STABILITY_THRESHOLD = 1.5 + self.assertTrue(phaser.IsStableProfile()) + + def testGetOrderfilePhaseOffsets(self): + mgr = TestProfileManager({ + self.File(0, 0): [12, 21, -1, 33], + self.File(0, 1): [31, 49, 52], + self.File(100, 0): [113, 128], + self.File(200, 1): [132, 146], + self.File(300, 0): [19, 20, 32], + self.File(300, 1): [24, 39]}) + phaser = phased_orderfile.PhasedAnalyzer(mgr, Mod10Processor()) + opo = lambda s, c, i: phased_orderfile.OrderfilePhaseOffsets( + startup=s, common=c, interaction=i) + self.assertListEqual([opo([10, 20], [30], [40, 50]), + opo([110, 120], [], []), + opo([], [], [130, 140]), + opo([10], [20, 30], [])], + phaser._GetOrderfilePhaseOffsets())
diff --git a/tools/cygprofile/process_profiles.py b/tools/cygprofile/process_profiles.py index 6d89eafa..1466a624 100755 --- a/tools/cygprofile/process_profiles.py +++ b/tools/cygprofile/process_profiles.py
@@ -111,6 +111,17 @@ return self._offset_to_primary + def OffsetsPrimarySize(self, offsets): + """Computes the total primary size of a set of offsets. + + Args: + offsets (int iterable) a set of offsets. + + Returns + int The sum of the primary size of the offsets. + """ + return sum(self.OffsetToPrimaryMap()[x].size for x in offsets) + def GetReachedOffsetsFromDump(self, dump): """Find the symbol offsets from a list of binary offsets. @@ -220,7 +231,6 @@ time. This files can be grouped into run sets that are within 30 seconds of each other. Each run set is then grouped into phases as before. """ - class _RunGroup(object): RUN_GROUP_THRESHOLD_NS = 30e9 @@ -251,6 +261,14 @@ self._filenames = sorted(filenames, key=self._Timestamp) self._run_groups = None + def GetPhases(self): + """Return the set of phases of all orderfiles. + + Returns: + set(int) + """ + return set(self._Phase(f) for f in self._filenames) + def GetMergedOffsets(self, phase=None): """Merges files, as if from a single dump.
diff --git a/tools/cygprofile/process_profiles_unittest.py b/tools/cygprofile/process_profiles_unittest.py index 33cf934..258005a6 100644 --- a/tools/cygprofile/process_profiles_unittest.py +++ b/tools/cygprofile/process_profiles_unittest.py
@@ -83,14 +83,21 @@ processor = TestSymbolOffsetProcessor(symbol_infos) self.assertDictEqual({8: symbol_infos[1]}, processor.OffsetToPrimaryMap()) - def testMatchSymbols(self): - symbols_b = [SymbolInfo('W', 30, 10), + symbols = [SymbolInfo('W', 30, 10), SymbolInfo('Y', 60, 5), SymbolInfo('X', 100, 10)] - processor_b = TestSymbolOffsetProcessor(symbols_b) - self.assertListEqual(symbols_b[1:3], - processor_b.MatchSymbolNames(['Y', 'X'])) + processor = TestSymbolOffsetProcessor(symbols) + self.assertListEqual(symbols[1:3], + processor.MatchSymbolNames(['Y', 'X'])) + + def testOffsetsPrimarySize(self): + symbols = [SymbolInfo('W', 10, 1), + SymbolInfo('X', 20, 2), + SymbolInfo('Y', 30, 4), + SymbolInfo('Z', 40, 8)] + processor = TestSymbolOffsetProcessor(symbols) + self.assertEqual(13, processor.OffsetsPrimarySize([10, 30, 40])) def testMedian(self): self.assertEquals(None, process_profiles._Median([])) @@ -155,6 +162,15 @@ self.assertEquals(2, len(offsets_list)) self.assertListEqual([5, 6, 7, 1, 2, 3, 4], offsets_list[0]) + def testPhases(self): + mgr = TestProfileManager({ + self.File(40, 0): [], + self.File(150, 0): [], + self.File(30, 1): [], + self.File(30, 2): [], + self.File(30, 0): []}) + self.assertEquals(set([0,1,2]), mgr.GetPhases()) + if __name__ == '__main__': unittest.main()
diff --git a/tools/metrics/actions/actions.xml b/tools/metrics/actions/actions.xml index 6c102457..fe684eb7 100644 --- a/tools/metrics/actions/actions.xml +++ b/tools/metrics/actions/actions.xml
@@ -12032,6 +12032,13 @@ <description>Please enter the description of the metric.</description> </action> +<action name="MobileOmniboxDeleteUrl"> + <owner>thildebr@chromium.org</owner> + <description> + The user cleared the contents of the omnibox via the delete button. + </description> +</action> + <action name="MobileOmniboxRefineSuggestion"> <obsolete> Deprecated 07/2017. Replaced by MobileOmniboxRefineSuggestion.Query and @@ -12424,6 +12431,13 @@ <description>Please enter the description of this user action.</description> </action> +<action name="MobileToolbarOmniboxShortcut"> + <owner>gambard@chromium.org</owner> + <description> + User pressed the omnibox shortcut on the toolbar. iOS only. + </description> +</action> + <action name="MobileToolbarReload"> <owner>tedchoc@chromium.org</owner> <description> @@ -12433,6 +12447,13 @@ </description> </action> +<action name="MobileToolbarShareMenu"> + <owner>gambard@chromium.org</owner> + <description> + User pressed the toolbar's button to open the share menu. iOS only. + </description> +</action> + <action name="MobileToolbarShowMenu"> <owner>Please list the metric's owners. Add more owner tags as needed.</owner> <description>Please enter the description of this user action.</description>
diff --git a/tools/metrics/histograms/enums.xml b/tools/metrics/histograms/enums.xml index 3d5ff0e..7803fdef 100644 --- a/tools/metrics/histograms/enums.xml +++ b/tools/metrics/histograms/enums.xml
@@ -15069,6 +15069,7 @@ <int value="4" label="HOSTED_APP"/> <int value="5" label="LEGACY_PACKAGED_APP"/> <int value="6" label="PLATFORM_APP"/> + <int value="7" label="SHARED_MODULE"/> </enum> <enum name="ExtensionUninstallDialogAction"> @@ -15132,6 +15133,24 @@ <int value="35" label="CRX_EXPECTED_HASH_INVALID"/> </enum> +<enum name="ExtensionViewType"> + <int value="0" label="INVALID"/> + <int value="1" label="APP_WINDOW"/> + <int value="2" label="BACKGROUND_CONTENTS"/> + <int value="3" label="COMPONENT"/> + <int value="4" label="EXTENSION_BACKGROUND_PAGE"/> + <int value="5" label="EXTENSION_DIALOG"/> + <int value="6" label="EXTENSION_GUEST"/> + <int value="7" label="EXTENSION_POPUP"/> + <int value="8" label="PANEL"/> + <int value="9" label="TAB_CONTENTS"/> +</enum> + +<enum name="ExtensionViewTypeIsBackground"> + <int value="0" label="Not background"/> + <int value="1" label="Background"/> +</enum> + <enum name="ExternalDeviceAction"> <int value="0" label="Import to Drive"/> <int value="1" label="View files"/> @@ -17706,6 +17725,10 @@ <int value="2351" label="CSSLegacyAlignment"/> <int value="2352" label="SRISignatureCheck"/> <int value="2353" label="SRISignatureSuccess"/> + <int value="2354" label="CSSBasicShape"/> + <int value="2355" label="CSSGradient"/> + <int value="2356" label="CSSPaintFunction"/> + <int value="2357" label="WebkitCrossFade"/> </enum> <enum name="FeedbackSource"> @@ -25548,6 +25571,7 @@ <int value="-1349532167" label="enable-wifi-credential-sync"/> <int value="-1346722635" label="gesture-selection"/> <int value="-1344375439" label="ServiceWorkerPaymentApps:disabled"/> + <int value="-1343259222" label="RegionalLocalesAsDisplayUI:disabled"/> <int value="-1341092934" label="enable-accelerated-overflow-scroll"/> <int value="-1340055960" label="enable-streamlined-hosted-apps"/> <int value="-1338306372" label="BrowserTouchBar:enabled"/> @@ -26090,6 +26114,7 @@ <int value="67639499" label="stop-loading-in-background:disabled"/> <int value="70878462" label="WebAssembly:disabled"/> <int value="73929836" label="VrBrowsingInCustomTab:enabled"/> + <int value="75237697" label="ash-enable-new-overview-ui"/> <int value="75747474" label="disable-webview-signin-flow"/> <int value="78998551" label="disable-hosted-app-shim-creation"/> <int value="79094339" label="VrLaunchIntents:enabled"/> @@ -26348,6 +26373,7 @@ <int value="779086132" label="enable-data-reduction-proxy-alt"/> <int value="782167080" label="enable-new-qp-input-view"/> <int value="783270752" label="AndroidHistoryManager:enabled"/> + <int value="787385958" label="RegionalLocalesAsDisplayUI:enabled"/> <int value="803282885" label="PreferHtmlOverPlugins:disabled"/> <int value="806334184" label="AndroidSpellChecker:enabled"/> <int value="807447752" label="ChromeMemex:disabled"/> @@ -34085,6 +34111,11 @@ <int value="3" label="IPv6 BestConnection."/> </enum> +<enum name="PeerConnectionKeyProtocol"> + <int value="0" label="DTLS"/> + <int value="1" label="SDES"/> +</enum> + <enum name="PeerConnectionRtcpMux"> <int value="0" label="Disabled"/> <int value="1" label="Enabled"/> @@ -39586,6 +39617,12 @@ <int value="1" label="Empty stream 2 file removed"/> </enum> +<enum name="SimpleCache.FileDescriptorLimiterOp"> + <int value="0" label="Close file"/> + <int value="1" label="Reopen file successfully"/> + <int value="2" label="Fail to reopen file"/> +</enum> + <enum name="SimpleCache.FileDescriptorLimitStatus"> <int value="0" label="Unsupported"/> <int value="1" label="Supported but failed"/>
diff --git a/tools/metrics/histograms/histograms.xml b/tools/metrics/histograms/histograms.xml index fa4a936..5b92c3e 100644 --- a/tools/metrics/histograms/histograms.xml +++ b/tools/metrics/histograms/histograms.xml
@@ -21928,6 +21928,17 @@ </summary> </histogram> +<histogram name="Event.Touch.TouchAdjustment.AdjustToSameNode" enum="Boolean"> + <owner>eirage@chromium.org</owner> + <summary> + Records if doing touch adjustment on touchstart have same hit test node as + doing touch adjustment on GestureTap. True for same node, false for + different node. This only records GestureTap events. + + Team: input-dev@chromium.org. + </summary> +</histogram> + <histogram name="Event.Touch.TouchDispositionsAfterPageLoad" enum="TouchEventDispatchResultType"> <obsolete> @@ -23094,6 +23105,60 @@ </summary> </histogram> +<histogram name="Extensions.BrowsingInstanceViolation.ExtensionType" + enum="ExtensionType"> + <owner>lukasza@chromium.org</owner> + <summary> + When an extension violates browsing instance boundaries, this metric records + the extension type. + + This is a temporary metric - probably okay to remove it in M66, after we've + gathered sufficient UMA data in M65. See also http://crbug.com/718489. + </summary> +</histogram> + +<histogram + name="Extensions.BrowsingInstanceViolation.IsBackgroundSourceOrTarget" + enum="ExtensionViewTypeIsBackground"> + <owner>lukasza@chromium.org</owner> + <summary> + When an extension violates browsing instance boundaries, this metric records + whether either the source or the target frame was of the extension view type + of VIEW_TYPE_BACKGROUND_CONTENTS. + + This is a temporary metric - probably okay to remove it in M66, after we've + gathered sufficient UMA data in M65. See also http://crbug.com/718489. + </summary> +</histogram> + +<histogram name="Extensions.BrowsingInstanceViolation.SourceExtensionViewType" + enum="ExtensionViewType"> + <owner>lukasza@chromium.org</owner> + <summary> + When an extension violates browsing instance boundaries, this metric records + the extension view type of the source frame. + + This is a temporary metric - probably okay to remove it in M66, after we've + gathered sufficient UMA data in M65. See also http://crbug.com/718489. + </summary> +</histogram> + +<histogram name="Extensions.BrowsingInstanceViolation.TargetExtensionViewType" + enum="ExtensionViewType"> + <owner>lukasza@chromium.org</owner> + <summary> + When an extension violates browsing instance boundaries, this metric records + the extension view type of the found frame. + + This metric should help confirm or deny the theory that violating browsing + instance boundaries is only needed for looking up background contents / + pages (of VIEW_TYPE_BACKGROUND_CONTENTS type). + + This is a temporary metric - probably okay to remove it in M66, after we've + gathered sufficient UMA data in M65. See also http://crbug.com/718489. + </summary> +</histogram> + <histogram name="Extensions.CheckForExternalUpdatesTime" units="ms"> <owner>rkaplow@chromium.org</owner> <summary> @@ -58395,6 +58460,15 @@ </summary> </histogram> +<histogram name="PageLoad.Clients.ServiceWorker.PageTransition" + enum="CorePageTransition"> + <owner>falken@chromium.org</owner> + <summary> + The core transition type for main frame page loads controlled by a service + worker. + </summary> +</histogram> + <histogram name="PageLoad.Clients.SubresourceFilter.ActivationDecision" enum="SubresourceFilterActivationDecision"> <owner>bmcquade@chromium.org</owner> @@ -71196,6 +71270,10 @@ <histogram base="true" name="RendererScheduler.ExpectedQueueingTimeByFrameStatus" units="microseconds"> + <obsolete> + Replaced with RendererScheduler.ExpectedQueueingTimeByFrameStatus2 as of Feb + 2018. Buckets were changed. + </obsolete> <owner>npm@chromium.org</owner> <owner>tdresser@chromium.org</owner> <summary> @@ -71206,6 +71284,19 @@ </summary> </histogram> +<histogram base="true" + name="RendererScheduler.ExpectedQueueingTimeByFrameStatus2" + units="microseconds"> + <owner>npm@chromium.org</owner> + <owner>tdresser@chromium.org</owner> + <summary> + Expected queueing time split by tasks according to their frame status, in + microseconds. The sum of the split values will be equal to the total, + reported on RendererScheduler.ExpectedTaskQueueingDuration3. Recorded for + each 1000 ms window. + </summary> +</histogram> + <histogram base="true" name="RendererScheduler.ExpectedQueueingTimeByFrameType" units="ms"> <obsolete> @@ -71223,6 +71314,10 @@ <histogram base="true" name="RendererScheduler.ExpectedQueueingTimeByTaskQueue" units="microseconds"> + <obsolete> + Replaced with RendererScheduler.ExpectedQueueingTimeByTaskQueue2 as of Feb + 2018. Buckets were changed. + </obsolete> <owner>npm@chromium.org</owner> <owner>tdresser@chromium.org</owner> <summary> @@ -71234,6 +71329,19 @@ </histogram> <histogram base="true" + name="RendererScheduler.ExpectedQueueingTimeByTaskQueue2" + units="microseconds"> + <owner>npm@chromium.org</owner> + <owner>tdresser@chromium.org</owner> + <summary> + Expected queueing time split by tasks according to the type of their task + queue, in microseconds. The sum of the split values should be equal to the + total, reported on RendererScheduler.ExpectedTaskQueueingDuration3. Recorded + for each 1000 ms window. + </summary> +</histogram> + +<histogram base="true" name="RendererScheduler.ExpectedQueueingTimeByTaskQueueType" units="ms"> <obsolete> Replaced with RendererScheduler.ExpectedQueueingTimeByTaskQueue as of @@ -71271,6 +71379,21 @@ <histogram name="RendererScheduler.ExpectedTaskQueueingDuration2" units="microseconds"> + <obsolete> + Replaced with RendererScheduler.ExpectedTaskQueueingDuration3 as of Feb + 2018. Buckets were changed. + </obsolete> + <owner>tdresser@chromium.org</owner> + <owner>npm@chromium.org</owner> + <summary> + The estimated queueing duration which would be observed for additional high + priority tasks posted to the RendererScheduler, in microseconds. Recorded + for each 1000 ms window. + </summary> +</histogram> + +<histogram name="RendererScheduler.ExpectedTaskQueueingDuration3" + units="microseconds"> <owner>tdresser@chromium.org</owner> <owner>npm@chromium.org</owner> <summary> @@ -79556,6 +79679,10 @@ <histogram name="ServiceWorker.MainFramePageLoad.CoreTransition" enum="CorePageTransition"> + <obsolete> + Deprecated 2018-01 in favor of + PageLoad.Clients.ServiceWorker.PageTransition. + </obsolete> <owner>horo@chromium.org</owner> <summary> The transition type for main frame page loads controlled by a service @@ -79565,6 +79692,9 @@ <histogram name="ServiceWorker.MainFramePageLoad.RedirectChainLength" units="urls"> + <obsolete> + Deprecated 2018-01. + </obsolete> <owner>horo@chromium.org</owner> <summary> Total length of the server redirects during main frame page loads controlled @@ -82405,6 +82535,16 @@ <summary>Time spent selecting entries for eviction.</summary> </histogram> +<histogram name="SimpleCache.FileDescriptorLimiterAction" + enum="SimpleCache.FileDescriptorLimiterOp"> + <owner>morlovich@chromium.org</owner> + <summary> + This even is emitted when SimpleCache is forced to either close some files + due to being over FD limit, or reopen files it had to close due to such + limit earlier. + </summary> +</histogram> + <histogram name="SimpleCache.FileDescriptorLimitHard" units="file descriptors"> <owner>morlovich@chromium.org</owner> <summary> @@ -95351,10 +95491,8 @@ <owner>asvitkine@chromium.org</owner> <summary> The time interval between when the variations seed was downloaded and when - it was loaded for use. Not recorded for expired seeds. - - TODO(isherman): Implement this metric for safe seeds as well. (It's - currently not implemented; but also, safe mode is not triggerable.) + it was loaded for use. Not recorded for expired seeds, nor when the download + time is unknown (typically, for seeds imported via first run). </summary> </histogram> @@ -99379,6 +99517,15 @@ </summary> </histogram> +<histogram name="WebRTC.PeerConnection.KeyProtocol" + enum="PeerConnectionKeyProtocol"> + <owner>hta@chromium.org</owner> + <summary> + What key exchange protocol (DTLS or SDES) is used to establish the crypto + keys for a PeerConnection's RTP transport. + </summary> +</histogram> + <histogram name="WebRTC.PeerConnection.RtcpMux" enum="PeerConnectionRtcpMux"> <owner>pthatcher@chromium.org</owner> <summary> @@ -110450,6 +110597,8 @@ frames."/> <affected-histogram name="RendererScheduler.ExpectedQueueingTimeByFrameStatus"/> + <affected-histogram + name="RendererScheduler.ExpectedQueueingTimeByFrameStatus2"/> </histogram_suffixes> <histogram_suffixes @@ -110471,6 +110620,8 @@ <suffix name="Other" label="Expected Queueing Time from events in any other task queue."/> <affected-histogram name="RendererScheduler.ExpectedQueueingTimeByTaskQueue"/> + <affected-histogram + name="RendererScheduler.ExpectedQueueingTimeByTaskQueue2"/> </histogram_suffixes> <histogram_suffixes name="RendererScheduler.MainThreadLoadSplit" separator=".">
diff --git a/tools/perf/BUILD.gn b/tools/perf/BUILD.gn index 91798f6..39e01e25 100644 --- a/tools/perf/BUILD.gn +++ b/tools/perf/BUILD.gn
@@ -60,5 +60,8 @@ # Field trial dependencies "//tools/json_comment_eater/", "//tools/json_to_struct/", + + # For Pylib used by benchmarks + "//build/android/pylib/", ] }
diff --git a/tools/perf/expectations.config b/tools/perf/expectations.config index ffafd7d..cbc2ac13 100644 --- a/tools/perf/expectations.config +++ b/tools/perf/expectations.config
@@ -324,6 +324,7 @@ [ Android_Webview ] v8.browsing_mobile/browse:chrome:newtab [ Skip ] crbug.com/803465 [ Nexus_5 ] v8.browsing_mobile/browse:chrome:newtab [ Skip ] crbug.com/803870 [ Cherry_Mobile_Android_One ] v8.browsing_mobile/browse:social:tumblr_infinite_scroll [ Skip ] +crbug.com/803870 [ Cherry_Mobile_Android_One ] v8.browsing_mobile/browse:media:youtube [ Skip ] crbug.com/799080 [ Nexus_7 ] v8.browsing_mobile-future/browse:news:cnn [ Skip ] # Benchmark: v8.browsing_mobile-future @@ -336,6 +337,7 @@ [ Android_Webview ] v8.browsing_mobile-future/browse:chrome:omnibox [ Skip ] crbug.com/728081 [ Android ] v8.browsing_mobile-future/browse:news:toi [ Skip ] crbug.com/767970 [ Cherry_Mobile_Android_One ] v8.browsing_mobile-future/browse:news:cnn [ Skip ] +crbug.com/803870 [ Cherry_Mobile_Android_One ] v8.browsing_mobile-future/browse:media:youtube [ Skip ] crbug.com/767970 [ Mobile ] v8.browsing_mobile-future/browse:shopping:flipkart [ Skip ] crbug.com/708300 [ Mobile ] v8.browsing_mobile-future/browse:shopping:flipkart [ Skip ] [ Android_Webview ] v8.browsing_mobile-future/browse:chrome:newtab [ Skip ]
diff --git a/tools/perf/page_sets/key_mobile_sites_pages.py b/tools/perf/page_sets/key_mobile_sites_pages.py index 9589bd4..59e2324 100644 --- a/tools/perf/page_sets/key_mobile_sites_pages.py +++ b/tools/perf/page_sets/key_mobile_sites_pages.py
@@ -7,25 +7,30 @@ class KeyMobileSitesPage(page_module.Page): - def __init__(self, url, page_set, name='', tags=None): + def __init__(self, url, page_set, name='', tags=None, + extra_browser_args=None): if name == '': name = url super(KeyMobileSitesPage, self).__init__( - url=url, page_set=page_set, name=name, + url=url, + page_set=page_set, + name=name, shared_page_state_class=shared_page_state.SharedMobilePageState, - tags=tags) + tags=tags, + extra_browser_args=extra_browser_args) class CapitolVolkswagenPage(KeyMobileSitesPage): - """ Why: Typical mobile business site """ - def __init__(self, page_set, name=''): + def __init__(self, page_set, name='', extra_browser_args=None): super(CapitolVolkswagenPage, self).__init__( - url=('http://iphone.capitolvolkswagen.com/index.htm' - '#new-inventory_p_2Fsb-new_p_2Ehtm_p_3Freset_p_3DInventoryListing'), - page_set=page_set, - name=name) + url=( + 'http://iphone.capitolvolkswagen.com/index.htm' + '#new-inventory_p_2Fsb-new_p_2Ehtm_p_3Freset_p_3DInventoryListing'), + page_set=page_set, + name=name, + extra_browser_args=extra_browser_args) def RunNavigateSteps(self, action_runner): super(CapitolVolkswagenPage, self).RunNavigateSteps(action_runner) @@ -34,17 +39,17 @@ 'document.body.scrollHeight > 2560') - class TheVergeArticlePage(KeyMobileSitesPage): - """ Why: Top tech blog """ - def __init__(self, page_set, name=''): + def __init__(self, page_set, name='', extra_browser_args=None): super(TheVergeArticlePage, self).__init__( - # pylint: disable=line-too-long - url='http://www.theverge.com/2012/10/28/3568746/amazon-7-inch-fire-hd-ipad-mini-ad-ballsy', - page_set=page_set, - name=name) + # pylint: disable=line-too-long + url= + 'http://www.theverge.com/2012/10/28/3568746/amazon-7-inch-fire-hd-ipad-mini-ad-ballsy', + page_set=page_set, + name=name, + extra_browser_args=extra_browser_args) def RunNavigateSteps(self, action_runner): super(TheVergeArticlePage, self).RunNavigateSteps(action_runner) @@ -57,31 +62,31 @@ class CnnArticlePage(KeyMobileSitesPage): - """ Why: Top news site """ - def __init__(self, page_set, name=''): + def __init__(self, page_set, name='', extra_browser_args=None): super(CnnArticlePage, self).__init__( - # pylint: disable=line-too-long - url='http://www.cnn.com/2012/10/03/politics/michelle-obama-debate/index.html', - page_set=page_set, - name=name) + # pylint: disable=line-too-long + url= + 'http://www.cnn.com/2012/10/03/politics/michelle-obama-debate/index.html', + page_set=page_set, + name=name, + extra_browser_args=extra_browser_args) def RunNavigateSteps(self, action_runner): super(CnnArticlePage, self).RunNavigateSteps(action_runner) action_runner.Wait(8) - class FacebookPage(KeyMobileSitesPage): - """ Why: #1 (Alexa global) """ - def __init__(self, page_set, name=''): + def __init__(self, page_set, name='', extra_browser_args=None): super(FacebookPage, self).__init__( - url='https://facebook.com/barackobama', - page_set=page_set, - name=name) + url='https://facebook.com/barackobama', + page_set=page_set, + name=name, + extra_browser_args=extra_browser_args) def RunNavigateSteps(self, action_runner): super(FacebookPage, self).RunNavigateSteps(action_runner) @@ -91,14 +96,14 @@ class YoutubeMobilePage(KeyMobileSitesPage): - """ Why: #3 (Alexa global) """ - def __init__(self, page_set, name=''): + def __init__(self, page_set, name='', extra_browser_args=None): super(YoutubeMobilePage, self).__init__( - url='http://m.youtube.com/watch?v=9hBpF_Zj4OA', - page_set=page_set, - name=name) + url='http://m.youtube.com/watch?v=9hBpF_Zj4OA', + page_set=page_set, + name=name, + extra_browser_args=extra_browser_args) def RunNavigateSteps(self, action_runner): super(YoutubeMobilePage, self).RunNavigateSteps(action_runner) @@ -107,14 +112,14 @@ class LinkedInPage(KeyMobileSitesPage): - """ Why: #12 (Alexa global),Public profile """ - def __init__(self, page_set, name='LinkedIn'): + def __init__(self, page_set, name='LinkedIn', extra_browser_args=None): super(LinkedInPage, self).__init__( - url='https://www.linkedin.com/in/linustorvalds', - page_set=page_set, - name=name) + url='https://www.linkedin.com/in/linustorvalds', + page_set=page_set, + name=name, + extra_browser_args=extra_browser_args) def RunNavigateSteps(self, action_runner): super(LinkedInPage, self).RunNavigateSteps(action_runner) @@ -122,17 +127,16 @@ 'document.getElementById("profile-view-scroller") !== null') - class YahooAnswersPage(KeyMobileSitesPage): - """ Why: #1 Alexa reference """ - def __init__(self, page_set, name=''): + def __init__(self, page_set, name='', extra_browser_args=None): super(YahooAnswersPage, self).__init__( - # pylint: disable=line-too-long - url='http://answers.yahoo.com/question/index?qid=20110117024343AAopj8f', - page_set=page_set, - name=name) + # pylint: disable=line-too-long + url='http://answers.yahoo.com/question/index?qid=20110117024343AAopj8f', + page_set=page_set, + name=name, + extra_browser_args=extra_browser_args) def RunNavigateSteps(self, action_runner): super(YahooAnswersPage, self).RunNavigateSteps(action_runner) @@ -141,37 +145,36 @@ class GroupClonedPage(KeyMobileSitesPage): - """ Why: crbug.com/172906 """ - def __init__(self, page_set, name=''): + def __init__(self, page_set, name='', extra_browser_args=None): super(GroupClonedPage, self).__init__( - url='http://groupcloned.com', - page_set=page_set, - name=name) - + url='http://groupcloned.com', + page_set=page_set, + name=name, + extra_browser_args=extra_browser_args) def RunNavigateSteps(self, action_runner): super(GroupClonedPage, self).RunNavigateSteps(action_runner) action_runner.Wait(5) - action_runner.WaitForJavaScriptCondition(''' + action_runner.WaitForJavaScriptCondition(""" document.getElementById("element-19") !== null && document.getElementById("element-19").contentDocument .getElementById("element-22") !== null && document.getElementById("element-19").contentDocument .getElementsByClassName( - "container list-item gc-list-item stretched").length !== 0''') + "container list-item gc-list-item stretched").length !== 0""") class GroupClonedListImagesPage(KeyMobileSitesPage): - """ Why: crbug.com/172906 """ - def __init__(self, page_set, name=''): + def __init__(self, page_set, name='', extra_browser_args=None): super(GroupClonedListImagesPage, self).__init__( - url='http://groupcloned.com/test/list-images-variable/index.html', - page_set=page_set, - name=name) + url='http://groupcloned.com/test/list-images-variable/index.html', + page_set=page_set, + name=name, + extra_browser_args=extra_browser_args) def RunNavigateSteps(self, action_runner): super(GroupClonedListImagesPage, self).RunNavigateSteps(action_runner) @@ -180,14 +183,14 @@ class GoogleNewsMobilePage(KeyMobileSitesPage): - """ Why: Google News: accelerated scrolling version """ - def __init__(self, page_set, name=''): + def __init__(self, page_set, name='', extra_browser_args=None): super(GoogleNewsMobilePage, self).__init__( - url='http://mobile-news.sandbox.google.com/news/pt1', - page_set=page_set, - name=name) + url='http://mobile-news.sandbox.google.com/news/pt1', + page_set=page_set, + name=name, + extra_browser_args=extra_browser_args) def RunNavigateSteps(self, action_runner): super(GoogleNewsMobilePage, self).RunNavigateSteps(action_runner) @@ -197,16 +200,16 @@ class GoogleNewsMobile2Page(KeyMobileSitesPage): - """ Why: Google News: this iOS version is slower than accelerated scrolling """ - def __init__(self, page_set, name=''): + def __init__(self, page_set, name='', extra_browser_args=None): super(GoogleNewsMobile2Page, self).__init__( - url='http://mobile-news.sandbox.google.com/news/pt0', - page_set=page_set, - name=name) + url='http://mobile-news.sandbox.google.com/news/pt0', + page_set=page_set, + name=name, + extra_browser_args=extra_browser_args) def RunNavigateSteps(self, action_runner): super(GoogleNewsMobile2Page, self).RunNavigateSteps(action_runner) @@ -216,13 +219,13 @@ class AmazonNicolasCagePage(KeyMobileSitesPage): - """ Why: #1 world commerce website by visits; #3 commerce in the US by time spent """ - def __init__(self, page_set, name=''): + def __init__(self, page_set, name='', extra_browser_args=None): super(AmazonNicolasCagePage, self).__init__( - url='http://www.amazon.com/gp/aw/s/ref=is_box_?k=nicolas+cage', - page_set=page_set, - name=name) + url='http://www.amazon.com/gp/aw/s/ref=is_box_?k=nicolas+cage', + page_set=page_set, + name=name, + extra_browser_args=extra_browser_args)
diff --git a/tools/perf/page_sets/key_mobile_sites_smooth.py b/tools/perf/page_sets/key_mobile_sites_smooth.py index b5f6077..294d76e 100644 --- a/tools/perf/page_sets/key_mobile_sites_smooth.py +++ b/tools/perf/page_sets/key_mobile_sites_smooth.py
@@ -14,35 +14,47 @@ def _CreatePageClassWithSmoothInteractions(page_cls): + class DerivedSmoothPage(page_cls): # pylint: disable=no-init def RunPageInteractions(self, action_runner): _IssueMarkerAndScroll(action_runner) + return DerivedSmoothPage class KeyMobileSitesSmoothPage(page_module.Page): - def __init__(self, url, page_set, name='', tags=None, - action_on_load_complete=False): + def __init__(self, + url, + page_set, + name='', + tags=None, + action_on_load_complete=False, + extra_browser_args=None): if name == '': name = url super(KeyMobileSitesSmoothPage, self).__init__( - url=url, page_set=page_set, name=name, tags=tags, - shared_page_state_class=shared_page_state.SharedMobilePageState) + url=url, + page_set=page_set, + name=name, + tags=tags, + shared_page_state_class=shared_page_state.SharedMobilePageState, + extra_browser_args=extra_browser_args) self.action_on_load_complete = action_on_load_complete def RunPageInteractions(self, action_runner): if self.action_on_load_complete: - action_runner.WaitForJavaScriptCondition( - 'document.readyState == "complete"', timeout=30) + action_runner.WaitForJavaScriptCondition( + 'document.readyState == "complete"', timeout=30) _IssueMarkerAndScroll(action_runner) class LinkedInSmoothPage(key_mobile_sites_pages.LinkedInPage): - def __init__(self, page_set, name=''): - super(LinkedInSmoothPage, self).__init__(page_set=page_set, name=name) + def __init__(self, page_set, name='', extra_browser_args=None): + super(LinkedInSmoothPage, self).__init__( + page_set=page_set, name=name, extra_browser_args=extra_browser_args) # Linkedin has expensive shader compilation so it can benefit from shader # cache from reload. @@ -54,11 +66,13 @@ class WowwikiSmoothPage(KeyMobileSitesSmoothPage): """Why: Mobile wiki.""" - def __init__(self, page_set, name=''): + + def __init__(self, page_set, name='', extra_browser_args=None): super(WowwikiSmoothPage, self).__init__( - url='http://www.wowwiki.com/World_of_Warcraft:_Mists_of_Pandaria', - page_set=page_set, - name=name) + url='http://www.wowwiki.com/World_of_Warcraft:_Mists_of_Pandaria', + page_set=page_set, + name=name, + extra_browser_args=extra_browser_args) # Wowwiki has expensive shader compilation so it can benefit from shader # cache from reload. @@ -73,41 +87,40 @@ def RunPageInteractions(self, action_runner): with action_runner.CreateGestureInteraction('ScrollAction'): action_runner.ScrollPage( - distance_expr=''' + distance_expr=""" Math.max(0, 1250 + document.getElementById("element-19") .contentDocument .getElementById("element-22") - .getBoundingClientRect().top);''', + .getBoundingClientRect().top);""", use_touch=True) class GroupClonedListImagesPage( - key_mobile_sites_pages.GroupClonedListImagesPage): + key_mobile_sites_pages.GroupClonedListImagesPage): def RunPageInteractions(self, action_runner): with action_runner.CreateGestureInteraction('ScrollAction'): action_runner.ScrollPage( - distance_expr=''' + distance_expr=""" Math.max(0, 1250 + document.getElementById("element-5") - .getBoundingClientRect().top);''', + .getBoundingClientRect().top);""", use_touch=True) -class GoogleNewsMobile2SmoothPage( - key_mobile_sites_pages.GoogleNewsMobile2Page): + +class GoogleNewsMobile2SmoothPage(key_mobile_sites_pages.GoogleNewsMobile2Page): def RunPageInteractions(self, action_runner): with action_runner.CreateGestureInteraction('ScrollAction'): action_runner.ScrollElement( element_function='document.getElementById(":5")', - distance_expr=''' + distance_expr=""" Math.max(0, 2500 + - document.getElementById(':h').getBoundingClientRect().top)''', + document.getElementById(':h').getBoundingClientRect().top)""", use_touch=True) -class AmazonNicolasCageSmoothPage( - key_mobile_sites_pages.AmazonNicolasCagePage): +class AmazonNicolasCageSmoothPage(key_mobile_sites_pages.AmazonNicolasCagePage): def RunPageInteractions(self, action_runner): with action_runner.CreateGestureInteraction('ScrollAction'): @@ -115,8 +128,8 @@ selector='#search', distance_expr='document.body.scrollHeight - window.innerHeight') -class CNNArticleSmoothPage( - key_mobile_sites_pages.CnnArticlePage): + +class CNNArticleSmoothPage(key_mobile_sites_pages.CnnArticlePage): def RunPageInteractions(self, action_runner): with action_runner.CreateGestureInteraction('ScrollAction'): @@ -124,31 +137,29 @@ # will not be in the root scroller. action_runner.ScrollPage(top_start_ratio=0.01) -class KeyMobileSitesSmoothPageSet(story.StorySet): +class KeyMobileSitesSmoothPageSet(story.StorySet): """ Key mobile sites with smooth interactions. """ def __init__(self): super(KeyMobileSitesSmoothPageSet, self).__init__( - archive_data_file='data/key_mobile_sites_smooth.json', - cloud_storage_bucket=story.PARTNER_BUCKET) - + archive_data_file='data/key_mobile_sites_smooth.json', + cloud_storage_bucket=story.PARTNER_BUCKET) # Add pages with predefined classes that contain custom navigation logic. predefined_page_classes = [ - key_mobile_sites_pages.CapitolVolkswagenPage, - key_mobile_sites_pages.TheVergeArticlePage, - key_mobile_sites_pages.FacebookPage, - key_mobile_sites_pages.YoutubeMobilePage, - key_mobile_sites_pages.YahooAnswersPage, - key_mobile_sites_pages.GoogleNewsMobilePage, + key_mobile_sites_pages.CapitolVolkswagenPage, + key_mobile_sites_pages.TheVergeArticlePage, + key_mobile_sites_pages.FacebookPage, + key_mobile_sites_pages.YoutubeMobilePage, + key_mobile_sites_pages.YahooAnswersPage, + key_mobile_sites_pages.GoogleNewsMobilePage, ] for page_class in predefined_page_classes: - self.AddStory( - _CreatePageClassWithSmoothInteractions(page_class)(self)) + self.AddStory(_CreatePageClassWithSmoothInteractions(page_class)(self)) self.AddStory( - _CreatePageClassWithSmoothInteractions(LinkedInSmoothPage)(self)) + _CreatePageClassWithSmoothInteractions(LinkedInSmoothPage)(self)) self.AddStory(WowwikiSmoothPage(self)) # Add pages with custom page interaction logic. @@ -169,37 +180,45 @@ # Add pages with custom tags. # Why: Top news site. - self.AddStory(KeyMobileSitesSmoothPage( - url='http://nytimes.com/', page_set=self, tags=['fastpath'])) + self.AddStory( + KeyMobileSitesSmoothPage( + url='http://nytimes.com/', page_set=self, tags=['fastpath'])) # Why: Image-heavy site. - self.AddStory(KeyMobileSitesSmoothPage( - url='http://cuteoverload.com', page_set=self, tags=['fastpath'])) + self.AddStory( + KeyMobileSitesSmoothPage( + url='http://cuteoverload.com', page_set=self, tags=['fastpath'])) # Why: #11 (Alexa global), google property; some blogger layouts # have infinite scroll but more interesting. - self.AddStory(KeyMobileSitesSmoothPage( - url='http://googlewebmastercentral.blogspot.com/', - page_set=self, name='Blogger')) + self.AddStory( + KeyMobileSitesSmoothPage( + url='http://googlewebmastercentral.blogspot.com/', + page_set=self, + name='Blogger')) # Why: #18 (Alexa global), Picked an interesting post """ - self.AddStory(KeyMobileSitesSmoothPage( - url='http://en.blog.wordpress.com/2012/09/04/freshly-pressed-editors-picks-for-august-2012/', - page_set=self, - name='Wordpress')) + self.AddStory( + KeyMobileSitesSmoothPage( + url= + 'http://en.blog.wordpress.com/2012/09/04/freshly-pressed-editors-picks-for-august-2012/', + page_set=self, + name='Wordpress')) # Why: #6 (Alexa) most visited worldwide, picked an interesting page - self.AddStory(KeyMobileSitesSmoothPage( - url='http://en.wikipedia.org/wiki/Wikipedia', - page_set=self, - name='Wikipedia_(1_tab)')) + self.AddStory( + KeyMobileSitesSmoothPage( + url='http://en.wikipedia.org/wiki/Wikipedia', + page_set=self, + name='Wikipedia_(1_tab)')) # Why: Wikipedia page with a delayed scroll start - self.AddStory(KeyMobileSitesSmoothPage( - url='http://en.wikipedia.org/wiki/Wikipedia', - page_set=self, - name='Wikipedia_(1_tab)-delayed_scroll_start', - action_on_load_complete=True)) + self.AddStory( + KeyMobileSitesSmoothPage( + url='http://en.wikipedia.org/wiki/Wikipedia', + page_set=self, + name='Wikipedia_(1_tab)-delayed_scroll_start', + action_on_load_complete=True)) # Why: #8 (Alexa global), picked an interesting page # Forbidden (Rate Limit Exceeded) @@ -207,10 +226,9 @@ # url='http://twitter.com/katyperry', page_set=self, name='Twitter')) # Why: #37 (Alexa global) """ - self.AddStory(KeyMobileSitesSmoothPage( - url='http://pinterest.com', - page_set=self, - name='Pinterest')) + self.AddStory( + KeyMobileSitesSmoothPage( + url='http://pinterest.com', page_set=self, name='Pinterest')) # Why: #1 sports. # Fails often; crbug.com/249722' @@ -221,62 +239,66 @@ # self.AddStory(KeyMobileSitesSmoothPage( # url='http://forecast.io', page_set=self)) # Why: crbug.com/169827 - self.AddStory(KeyMobileSitesSmoothPage( - url='http://slashdot.org/', page_set=self, tags=['fastpath'])) + self.AddStory( + KeyMobileSitesSmoothPage( + url='http://slashdot.org/', page_set=self, tags=['fastpath'])) # Why: #5 Alexa news """ - self.AddStory(KeyMobileSitesSmoothPage( - url='http://www.reddit.com/r/programming/comments/1g96ve', - page_set=self, tags=['fastpath'])) + self.AddStory( + KeyMobileSitesSmoothPage( + url='http://www.reddit.com/r/programming/comments/1g96ve', + page_set=self, + tags=['fastpath'])) # Why: Problematic use of fixed position elements """ - self.AddStory(KeyMobileSitesSmoothPage( - url='http://www.boingboing.net', page_set=self, tags=['fastpath'])) + self.AddStory( + KeyMobileSitesSmoothPage( + url='http://www.boingboing.net', page_set=self, tags=['fastpath'])) # Add simple pages with no custom navigation logic or tags. urls_list = [ - # Why: Social; top Google property; Public profile; infinite scrolls. - 'https://plus.google.com/app/basic/110031535020051778989/posts?source=apppromo', - # Why: crbug.com/242544 - ('http://www.androidpolice.com/2012/10/03/rumor-evidence-mounts-that-an-' - 'lg-optimus-g-nexus-is-coming-along-with-a-nexus-phone-certification-' - 'program/'), - # Why: crbug.com/149958 - 'http://gsp.ro', - # Why: Top tech blog - 'http://theverge.com', - # Why: Top tech site - 'http://digg.com', - # Why: Top Google property; a Google tab is often open - 'https://www.google.co.uk/search?hl=en&q=barack+obama&cad=h', - # Why: #1 news worldwide (Alexa global) - 'http://news.yahoo.com', - # Why: #2 news worldwide - 'http://www.cnn.com', - # Why: #1 commerce website by time spent by users in US - 'http://shop.mobileweb.ebay.com/searchresults?kw=viking+helmet', - # Why: #1 Alexa recreation - 'http://www.booking.com/searchresults.html?src=searchresults&latitude=65.0500&longitude=25.4667', - # Why: Top tech blog - 'http://techcrunch.com', - # Why: #6 Alexa sports - 'http://mlb.com/', - # Why: #14 Alexa California - 'http://www.sfgate.com/', - # Why: Non-latin character set - 'http://worldjournal.com/', - # Why: #15 Alexa news - 'http://online.wsj.com/home-page', - # Why: Image-heavy mobile site - 'http://www.deviantart.com/', - # Why: Top search engine - ('http://www.baidu.com/s?wd=barack+obama&rsv_bp=0&rsv_spt=3&rsv_sug3=9&' - 'rsv_sug=0&rsv_sug4=3824&rsv_sug1=3&inputT=4920'), - # Why: Top search engine - 'http://www.bing.com/search?q=sloths', - # Why: Good example of poor initial scrolling - 'http://ftw.usatoday.com/2014/05/spelling-bee-rules-shenanigans' + # Why: Social; top Google property; Public profile; infinite scrolls. + 'https://plus.google.com/app/basic/110031535020051778989/posts?source=apppromo', + # Why: crbug.com/242544 + ('http://www.androidpolice.com/2012/10/03/rumor-evidence-mounts-that-an-' + 'lg-optimus-g-nexus-is-coming-along-with-a-nexus-phone-certification-' + 'program/'), + # Why: crbug.com/149958 + 'http://gsp.ro', + # Why: Top tech blog + 'http://theverge.com', + # Why: Top tech site + 'http://digg.com', + # Why: Top Google property; a Google tab is often open + 'https://www.google.co.uk/search?hl=en&q=barack+obama&cad=h', + # Why: #1 news worldwide (Alexa global) + 'http://news.yahoo.com', + # Why: #2 news worldwide + 'http://www.cnn.com', + # Why: #1 commerce website by time spent by users in US + 'http://shop.mobileweb.ebay.com/searchresults?kw=viking+helmet', + # Why: #1 Alexa recreation + 'http://www.booking.com/searchresults.html?src=searchresults&latitude=65.0500&longitude=25.4667', + # Why: Top tech blog + 'http://techcrunch.com', + # Why: #6 Alexa sports + 'http://mlb.com/', + # Why: #14 Alexa California + 'http://www.sfgate.com/', + # Why: Non-latin character set + 'http://worldjournal.com/', + # Why: #15 Alexa news + 'http://online.wsj.com/home-page', + # Why: Image-heavy mobile site + 'http://www.deviantart.com/', + # Why: Top search engine + ('http://www.baidu.com/s?wd=barack+obama&rsv_bp=0&rsv_spt=3&rsv_sug3=9&' + 'rsv_sug=0&rsv_sug4=3824&rsv_sug1=3&inputT=4920'), + # Why: Top search engine + 'http://www.bing.com/search?q=sloths', + # Why: Good example of poor initial scrolling + 'http://ftw.usatoday.com/2014/05/spelling-bee-rules-shenanigans' ] for url in urls_list:
diff --git a/tools/perf/page_sets/system_health/browsing_stories.py b/tools/perf/page_sets/system_health/browsing_stories.py index 4339fc21..52c9377 100644 --- a/tools/perf/page_sets/system_health/browsing_stories.py +++ b/tools/perf/page_sets/system_health/browsing_stories.py
@@ -706,7 +706,7 @@ action_runner.ClickElement(selector=self._MAPS_ZOOM_IN_SELECTOR) action_runner.WaitForJavaScriptCondition( self._CHECK_RESTAURANTS_UPDATED, - old_restaurant=prev_restaurant_hash) + old_restaurant=prev_restaurant_hash, timeout=90) # This wait is required to fetch the data for all the tiles in the map. action_runner.Wait(1) @@ -715,7 +715,7 @@ action_runner.ClickElement(selector=self._MAPS_ZOOM_IN_SELECTOR) action_runner.WaitForJavaScriptCondition( self._CHECK_RESTAURANTS_UPDATED, - old_restaurant=prev_restaurant_hash) + old_restaurant=prev_restaurant_hash, timeout=90) # This wait is required to fetch the data for all the tiles in the map. action_runner.Wait(1) @@ -730,7 +730,7 @@ repeat_count=2, speed=500, timeout=120, repeat_delay_ms=2000) action_runner.WaitForJavaScriptCondition( self._CHECK_RESTAURANTS_UPDATED, - old_restaurant=prev_restaurant_hash) + old_restaurant=prev_restaurant_hash, timeout=90) prev_restaurant_hash = action_runner.EvaluateJavaScript( self._GET_RESTAURANT_RESPONSE_HASH) @@ -739,7 +739,7 @@ repeat_count=2, speed=500, timeout=120, repeat_delay_ms=2000) action_runner.WaitForJavaScriptCondition( self._CHECK_RESTAURANTS_UPDATED, - old_restaurant=prev_restaurant_hash) + old_restaurant=prev_restaurant_hash, timeout=90) # To make the recording more realistic. action_runner.Wait(1)
diff --git a/tools/perf/page_sets/top_25_smooth.py b/tools/perf/page_sets/top_25_smooth.py index 270c7b1..6ae9e27 100644 --- a/tools/perf/page_sets/top_25_smooth.py +++ b/tools/perf/page_sets/top_25_smooth.py
@@ -30,14 +30,15 @@ class TopSmoothPage(page_module.Page): - def __init__(self, url, page_set, name=''): + def __init__(self, url, page_set, name='', extra_browser_args=None): if name == '': name = url super(TopSmoothPage, self).__init__( url=url, page_set=page_set, name=name, - shared_page_state_class=shared_page_state.SharedDesktopPageState) + shared_page_state_class=shared_page_state.SharedDesktopPageState, + extra_browser_args=extra_browser_args) def RunPageInteractions(self, action_runner): action_runner.Wait(1)
diff --git a/tools/perf/page_sets/top_pages.py b/tools/perf/page_sets/top_pages.py index 5f36c92..04c296b1 100644 --- a/tools/perf/page_sets/top_pages.py +++ b/tools/perf/page_sets/top_pages.py
@@ -9,14 +9,20 @@ class TopPages(page_module.Page): - def __init__(self, url, page_set, shared_page_state_class, name=''): + def __init__(self, + url, + page_set, + shared_page_state_class, + name='', + extra_browser_args=None): if name == '': name = url super(TopPages, self).__init__( url=url, page_set=page_set, + shared_page_state_class=shared_page_state_class, name=name, - shared_page_state_class=shared_page_state_class) + extra_browser_args=extra_browser_args) class GoogleWebSearchPage(TopPages): @@ -25,12 +31,14 @@ def __init__(self, page_set, shared_page_state_class=shared_page_state.SharedPageState, - name=''): + name='', + extra_browser_args=None): super(GoogleWebSearchPage, self).__init__( url='https://www.google.com/#hl=en&q=barack+obama', page_set=page_set, shared_page_state_class=shared_page_state_class, - name=name) + name=name, + extra_browser_args=extra_browser_args) def RunNavigateSteps(self, action_runner): super(GoogleWebSearchPage, self).RunNavigateSteps(action_runner) @@ -43,12 +51,14 @@ def __init__(self, page_set, shared_page_state_class=shared_page_state.SharedPageState, - name=''): + name='', + extra_browser_args=None): super(GoogleImageSearchPage, self).__init__( 'https://www.google.com/search?q=cats&tbm=isch', page_set=page_set, shared_page_state_class=shared_page_state_class, - name=name) + name=name, + extra_browser_args=extra_browser_args) def RunNavigateSteps(self, action_runner): google_login.LoginGoogleAccount(action_runner, 'googletest') @@ -61,12 +71,14 @@ def __init__(self, page_set, shared_page_state_class=shared_page_state.SharedPageState, - name=''): + name='', + extra_browser_args=None): super(GmailPage, self).__init__( url='https://mail.google.com/mail/', page_set=page_set, shared_page_state_class=shared_page_state_class, - name=name) + name=name, + extra_browser_args=extra_browser_args) def RunNavigateSteps(self, action_runner): google_login.LoginGoogleAccount(action_runner, 'googletest') @@ -82,12 +94,14 @@ def __init__(self, page_set, shared_page_state_class=shared_page_state.SharedPageState, - name=''): + name='', + extra_browser_args=None): super(GoogleCalendarPage, self).__init__( url='https://www.google.com/calendar/', page_set=page_set, shared_page_state_class=shared_page_state_class, - name=name) + name=name, + extra_browser_args=extra_browser_args) def RunNavigateSteps(self, action_runner): google_login.LoginGoogleAccount(action_runner, 'googletest') @@ -110,14 +124,16 @@ def __init__(self, page_set, shared_page_state_class=shared_page_state.SharedPageState, - name='Docs_(1_open_document_tab)'): + name='Docs_(1_open_document_tab)', + extra_browser_args=None): super(GoogleDocPage, self).__init__( # pylint: disable=line-too-long url= 'https://docs.google.com/document/d/1X-IKNjtEnx-WW5JIKRLsyhz5sbsat3mfTpAPUSX3_s4/view', page_set=page_set, shared_page_state_class=shared_page_state_class, - name=name) + name=name, + extra_browser_args=extra_browser_args) def RunNavigateSteps(self, action_runner): google_login.LoginGoogleAccount(action_runner, 'googletest') @@ -133,12 +149,14 @@ def __init__(self, page_set, shared_page_state_class=shared_page_state.SharedPageState, - name=''): + name='', + extra_browser_args=None): super(GooglePlusPage, self).__init__( url='https://plus.google.com/110031535020051778989/posts', page_set=page_set, shared_page_state_class=shared_page_state_class, - name=name) + name=name, + extra_browser_args=extra_browser_args) def RunNavigateSteps(self, action_runner): google_login.LoginGoogleAccount(action_runner, 'googletest') @@ -152,12 +170,14 @@ def __init__(self, page_set, shared_page_state_class=shared_page_state.SharedPageState, - name=''): + name='', + extra_browser_args=None): super(YoutubePage, self).__init__( url='http://www.youtube.com', page_set=page_set, shared_page_state_class=shared_page_state_class, - name=name) + name=name, + extra_browser_args=extra_browser_args) def RunNavigateSteps(self, action_runner): google_login.LoginGoogleAccount(action_runner, 'googletest') @@ -172,12 +192,14 @@ def __init__(self, page_set, shared_page_state_class=shared_page_state.SharedPageState, - name='Blogger'): + name='Blogger', + extra_browser_args=None): super(BlogspotPage, self).__init__( url='http://googlewebmastercentral.blogspot.com/', page_set=page_set, shared_page_state_class=shared_page_state_class, - name=name) + name=name, + extra_browser_args=extra_browser_args) def RunNavigateSteps(self, action_runner): super(BlogspotPage, self).RunNavigateSteps(action_runner) @@ -190,14 +212,16 @@ def __init__(self, page_set, shared_page_state_class=shared_page_state.SharedPageState, - name='Wordpress'): + name='Wordpress', + extra_browser_args=None): super(WordpressPage, self).__init__( # pylint: disable=line-too-long url= 'http://en.blog.wordpress.com/2012/09/04/freshly-pressed-editors-picks-for-august-2012/', page_set=page_set, shared_page_state_class=shared_page_state_class, - name=name) + name=name, + extra_browser_args=extra_browser_args) def RunNavigateSteps(self, action_runner): super(WordpressPage, self).RunNavigateSteps(action_runner) @@ -213,12 +237,14 @@ def __init__(self, page_set, shared_page_state_class=shared_page_state.SharedPageState, - name='Facebook'): + name='Facebook', + extra_browser_args=None): super(FacebookPage, self).__init__( url='https://www.facebook.com/barackobama', page_set=page_set, shared_page_state_class=shared_page_state_class, - name=name) + name=name, + extra_browser_args=extra_browser_args) def RunNavigateSteps(self, action_runner): super(FacebookPage, self).RunNavigateSteps(action_runner) @@ -231,12 +257,14 @@ def __init__(self, page_set, shared_page_state_class=shared_page_state.SharedPageState, - name='LinkedIn'): + name='LinkedIn', + extra_browser_args=None): super(LinkedinPage, self).__init__( url='http://www.linkedin.com/in/linustorvalds', page_set=page_set, shared_page_state_class=shared_page_state_class, - name=name) + name=name, + extra_browser_args=extra_browser_args) class WikipediaPage(TopPages): @@ -245,12 +273,14 @@ def __init__(self, page_set, shared_page_state_class=shared_page_state.SharedPageState, - name='Wikipedia_(1_tab)'): + name='Wikipedia_(1_tab)', + extra_browser_args=None): super(WikipediaPage, self).__init__( url='http://en.wikipedia.org/wiki/Wikipedia', page_set=page_set, shared_page_state_class=shared_page_state_class, - name=name) + name=name, + extra_browser_args=extra_browser_args) class TwitterPage(TopPages): @@ -259,12 +289,14 @@ def __init__(self, page_set, shared_page_state_class=shared_page_state.SharedPageState, - name='Twitter'): + name='Twitter', + extra_browser_args=None): super(TwitterPage, self).__init__( url='https://twitter.com/katyperry', page_set=page_set, shared_page_state_class=shared_page_state_class, - name=name) + name=name, + extra_browser_args=extra_browser_args) def RunNavigateSteps(self, action_runner): super(TwitterPage, self).RunNavigateSteps(action_runner) @@ -277,12 +309,14 @@ def __init__(self, page_set, shared_page_state_class=shared_page_state.SharedPageState, - name='Pinterest'): + name='Pinterest', + extra_browser_args=None): super(PinterestPage, self).__init__( url='http://pinterest.com', page_set=page_set, shared_page_state_class=shared_page_state_class, - name=name) + name=name, + extra_browser_args=extra_browser_args) class ESPNPage(TopPages): @@ -291,12 +325,14 @@ def __init__(self, page_set, shared_page_state_class=shared_page_state.SharedPageState, - name='ESPN'): + name='ESPN', + extra_browser_args=None): super(ESPNPage, self).__init__( url='http://espn.go.com', page_set=page_set, shared_page_state_class=shared_page_state_class, - name=name) + name=name, + extra_browser_args=extra_browser_args) class WeatherPage(TopPages): @@ -305,12 +341,14 @@ def __init__(self, page_set, shared_page_state_class=shared_page_state.SharedPageState, - name='Weather.com'): + name='Weather.com', + extra_browser_args=None): super(WeatherPage, self).__init__( url='http://www.weather.com/weather/right-now/Mountain+View+CA+94043', page_set=page_set, shared_page_state_class=shared_page_state_class, - name=name) + name=name, + extra_browser_args=extra_browser_args) class YahooGamesPage(TopPages): @@ -319,12 +357,14 @@ def __init__(self, page_set, shared_page_state_class=shared_page_state.SharedPageState, - name=''): + name='', + extra_browser_args=None): super(YahooGamesPage, self).__init__( url='http://games.yahoo.com', page_set=page_set, shared_page_state_class=shared_page_state_class, - name=name) + name=name, + extra_browser_args=extra_browser_args) def RunNavigateSteps(self, action_runner): super(YahooGamesPage, self).RunNavigateSteps(action_runner)
diff --git a/tools/traffic_annotation/README.md b/tools/traffic_annotation/README.md index 99b1947..724df46e 100644 --- a/tools/traffic_annotation/README.md +++ b/tools/traffic_annotation/README.md
@@ -99,4 +99,4 @@ re-enable the test. CLANG_REVISION = '321529' -LASTCHANGE=671628d8a99b8420f4dadcdb82751c0d3ea2117a-refs/heads/master@{#530817} +LASTCHANGE=c67646fb6096ac1d87b516b2eaf2eb9968d2da73-refs/heads/master@{#531988}
diff --git a/tools/traffic_annotation/auditor/instance.cc b/tools/traffic_annotation/auditor/instance.cc index 37affc6..cd680fc 100644 --- a/tools/traffic_annotation/auditor/instance.cc +++ b/tools/traffic_annotation/auditor/instance.cc
@@ -452,7 +452,6 @@ traffic_annotation::NetworkTrafficAnnotation_TrafficPolicy* dst_policy = combination->proto.mutable_policy(); - MERGE_STRING_FIELDS(src_policy, dst_policy, empty_policy_justification); MERGE_STRING_FIELDS(src_policy, dst_policy, cookies_store); MERGE_STRING_FIELDS(src_policy, dst_policy, setting);
diff --git a/tools/traffic_annotation/auditor/traffic_annotation_auditor_ui.cc b/tools/traffic_annotation/auditor/traffic_annotation_auditor_ui.cc index 1bd3c53..ccb15f4 100644 --- a/tools/traffic_annotation/auditor/traffic_annotation_auditor_ui.cc +++ b/tools/traffic_annotation/auditor/traffic_annotation_auditor_ui.cc
@@ -197,9 +197,8 @@ std::vector<std::string> lines; std::string title = "Unique ID\tLast Update\tSender\tDescription\tTrigger\tData\t" - "Destination\tEmpty Policy Justification\tCookies Allowed\t" - "Cookies Store\tSetting\tChrome Policy\tComments\tSource File\t" - "ID Hash Code\tContent Hash Code"; + "Destination\tCookies Allowed\tCookies Store\tSetting\tChrome Policy\t" + "Comments\tSource File\tID Hash Code\tContent Hash Code"; for (auto& instance : annotations) { if (instance.type != AnnotationInstance::Type::ANNOTATION_COMPLETE) @@ -251,8 +250,6 @@ // Policy. const auto policy = instance.proto.policy(); line += - base::StringPrintf("\t%s", policy.empty_policy_justification().c_str()); - line += policy.cookies_allowed() == traffic_annotation:: NetworkTrafficAnnotation_TrafficPolicy_CookiesAllowed_YES
diff --git a/tools/traffic_annotation/bin/linux64/traffic_annotation_auditor.sha1 b/tools/traffic_annotation/bin/linux64/traffic_annotation_auditor.sha1 index d93eae7..6ad544c 100644 --- a/tools/traffic_annotation/bin/linux64/traffic_annotation_auditor.sha1 +++ b/tools/traffic_annotation/bin/linux64/traffic_annotation_auditor.sha1
@@ -1 +1 @@ -15452c1f82231c0d5a73ebd9468d36af6735b3f8 \ No newline at end of file +4114b4ddfc462968ff5a4f487c96981cdc1a1eb3 \ No newline at end of file
diff --git a/tools/traffic_annotation/scripts/check_annotations.py b/tools/traffic_annotation/scripts/check_annotations.py index 0089d07..1068b29 100755 --- a/tools/traffic_annotation/scripts/check_annotations.py +++ b/tools/traffic_annotation/scripts/check_annotations.py
@@ -17,7 +17,7 @@ # If this test starts failing, please set TEST_IS_ENABLED to "False" and file a # bug to get this reenabled, and cc the people listed in # //tools/traffic_annotation/OWNERS. -TEST_IS_ENABLED = False +TEST_IS_ENABLED = sys.platform != 'win32' class NetworkTrafficAnnotationChecker():
diff --git a/tools/traffic_annotation/traffic_annotation.proto b/tools/traffic_annotation/traffic_annotation.proto index c74705d..d00be7e 100644 --- a/tools/traffic_annotation/traffic_annotation.proto +++ b/tools/traffic_annotation/traffic_annotation.proto
@@ -129,11 +129,6 @@ TrafficSemantics semantics = 3; message TrafficPolicy { - // Justification for an empty traffic policy. - // This can be used for network requests that do not have any traffic - // control policy, such as those inside the network stack. - string empty_policy_justification = 1; - enum CookiesAllowed { // Do not use this value. It's just a placeholder for default value. UNSPECIFIED = 0; @@ -143,7 +138,7 @@ // correct). YES = 2; } - CookiesAllowed cookies_allowed = 2; + CookiesAllowed cookies_allowed = 1; // If a request sends or stores cookies/channel IDs/... (i.e. if // cookies_allowed is true), we want to know which cookie store is being @@ -158,20 +153,20 @@ // io_thread()->system_url_request_context_getter()), put "system" here. // Otherwise, please explain (e.g. SafeBrowsing uses a separate cookie // store). - string cookies_store = 3; + string cookies_store = 2; // Human readable description of how to enable/disable a feature that // triggers this network request by a user (e.g. “Disable ‘Use a web service // to help resolve spelling errors.’ in settings under Advanced”). - string setting = 4; + string setting = 3; // Policy configuration(s) that disable or limit this network request. // This would be a text serialized protobuf of any enterprise policy. // see out/Debug/gen/components/policy/proto/chrome_settings.proto - repeated enterprise_management.ChromeSettingsProto chrome_policy = 5; + repeated enterprise_management.ChromeSettingsProto chrome_policy = 4; // Justification for not having a policy that disables this feature. - string policy_exception_justification = 6; + string policy_exception_justification = 5; } TrafficPolicy policy = 4;
diff --git a/tools/v8_context_snapshot/v8_context_snapshot.gni b/tools/v8_context_snapshot/v8_context_snapshot.gni index 04d498018..f8ce9764 100644 --- a/tools/v8_context_snapshot/v8_context_snapshot.gni +++ b/tools/v8_context_snapshot/v8_context_snapshot.gni
@@ -13,9 +13,10 @@ declare_args() { # TODO(crbug.com/764576): Enable the feature on more environments. - use_v8_context_snapshot = !is_chromeos && !is_android && !is_chromecast && - !(host_os == "mac" && current_cpu == "x86") && - (v8_target_cpu == target_cpu || is_msan) + use_v8_context_snapshot = + !is_chromeos && !is_android && !is_chromecast && !is_fuchsia && + !(host_os == "mac" && current_cpu == "x86") && + (v8_target_cpu == target_cpu || is_msan) } # We cannot use V8 context snapshot, if V8 doesn't use snapshot files.
diff --git a/ui/accelerated_widget_mac/accelerated_widget_mac.mm b/ui/accelerated_widget_mac/accelerated_widget_mac.mm index 7ff59be..98e1236 100644 --- a/ui/accelerated_widget_mac/accelerated_widget_mac.mm +++ b/ui/accelerated_widget_mac/accelerated_widget_mac.mm
@@ -148,7 +148,7 @@ GotCALayerFrame(base::scoped_nsobject<CALayer>(remote_layer_.get(), base::scoped_policy::RETAIN), ca_layer_params.pixel_size, ca_layer_params.scale_factor); - } else { + } else if (ca_layer_params.io_surface_mach_port) { base::ScopedCFTypeRef<IOSurfaceRef> io_surface( IOSurfaceLookupFromMachPort(ca_layer_params.io_surface_mach_port)); if (!io_surface) { @@ -156,6 +156,11 @@ } GotIOSurfaceFrame(io_surface, ca_layer_params.pixel_size, ca_layer_params.scale_factor); + } else { + LOG(ERROR) << "Frame had neither valid CAContext nor valid IOSurface."; + base::ScopedCFTypeRef<IOSurfaceRef> io_surface; + GotIOSurfaceFrame(io_surface, ca_layer_params.pixel_size, + ca_layer_params.scale_factor); } if (view_) view_->AcceleratedWidgetSwapCompleted();
diff --git a/ui/accessibility/ax_enum_util.cc b/ui/accessibility/ax_enum_util.cc index 78118b5..d9bedb8 100644 --- a/ui/accessibility/ax_enum_util.cc +++ b/ui/accessibility/ax_enum_util.cc
@@ -325,6 +325,14 @@ return "inputTime"; case ax::mojom::Role::kLabelText: return "labelText"; + case ax::mojom::Role::kLayoutTable: + return "layoutTable"; + case ax::mojom::Role::kLayoutTableCell: + return "layoutTableCell"; + case ax::mojom::Role::kLayoutTableColumn: + return "layoutTableColumn"; + case ax::mojom::Role::kLayoutTableRow: + return "layoutTableRow"; case ax::mojom::Role::kLegend: return "legend"; case ax::mojom::Role::kLineBreak: @@ -585,6 +593,14 @@ return ax::mojom::Role::kInputTime; if (0 == strcmp(role, "labelText")) return ax::mojom::Role::kLabelText; + if (0 == strcmp(role, "layoutTable")) + return ax::mojom::Role::kLayoutTable; + if (0 == strcmp(role, "layoutTableCell")) + return ax::mojom::Role::kLayoutTableCell; + if (0 == strcmp(role, "layoutTableColumn")) + return ax::mojom::Role::kLayoutTableColumn; + if (0 == strcmp(role, "layoutTableRow")) + return ax::mojom::Role::kLayoutTableRow; if (0 == strcmp(role, "legend")) return ax::mojom::Role::kLegend; if (0 == strcmp(role, "lineBreak"))
diff --git a/ui/accessibility/ax_enums.mojom b/ui/accessibility/ax_enums.mojom index 8cc5569f..4596ae9 100644 --- a/ui/accessibility/ax_enums.mojom +++ b/ui/accessibility/ax_enums.mojom
@@ -134,6 +134,10 @@ kInlineTextBox, kInputTime, kLabelText, + kLayoutTable, + kLayoutTableCell, + kLayoutTableColumn, + kLayoutTableRow, kLegend, kLineBreak, kLink,
diff --git a/ui/accessibility/ax_role_properties.cc b/ui/accessibility/ax_role_properties.cc index 7dac852..8c78792 100644 --- a/ui/accessibility/ax_role_properties.cc +++ b/ui/accessibility/ax_role_properties.cc
@@ -3,9 +3,18 @@ // found in the LICENSE file. #include "ui/accessibility/ax_role_properties.h" +#include "build/build_config.h" namespace ui { +namespace { +#if defined(OS_WIN) +static bool kExposeLayoutTableAsDataTable = true; +#else +static bool kExposeLayoutTableAsDataTable = false; +#endif +} // namespace + bool IsRoleClickable(ax::mojom::Role role) { switch (role) { case ax::mojom::Role::kButton: @@ -47,6 +56,8 @@ case ax::mojom::Role::kColumnHeader: case ax::mojom::Role::kRowHeader: return true; + case ax::mojom::Role::kLayoutTableCell: + return kExposeLayoutTableAsDataTable; default: return false; } @@ -58,6 +69,8 @@ case ax::mojom::Role::kGrid: case ax::mojom::Role::kTreeGrid: return true; + case ax::mojom::Role::kLayoutTable: + return kExposeLayoutTableAsDataTable; default: return false; }
diff --git a/ui/accessibility/platform/ax_platform_node_auralinux.cc b/ui/accessibility/platform/ax_platform_node_auralinux.cc index 775db1b..69a41c36 100644 --- a/ui/accessibility/platform/ax_platform_node_auralinux.cc +++ b/ui/accessibility/platform/ax_platform_node_auralinux.cc
@@ -870,6 +870,15 @@ return ATK_ROLE_IMAGE_MAP; case ax::mojom::Role::kLabelText: return ATK_ROLE_LABEL; + // Layout table objects are treated the same as Role::kGenericContainer. + case ax::mojom::Role::kLayoutTable: + return ATK_ROLE_PANEL; + case ax::mojom::Role::kLayoutTableCell: + return ATK_ROLE_PANEL; + case ax::mojom::Role::kLayoutTableColumn: + return ATK_ROLE_PANEL; + case ax::mojom::Role::kLayoutTableRow: + return ATK_ROLE_PANEL; case ax::mojom::Role::kLink: return ATK_ROLE_LINK; case ax::mojom::Role::kList:
diff --git a/ui/accessibility/platform/ax_platform_node_mac.mm b/ui/accessibility/platform/ax_platform_node_mac.mm index 45c9e5e..f3c84136 100644 --- a/ui/accessibility/platform/ax_platform_node_mac.mm +++ b/ui/accessibility/platform/ax_platform_node_mac.mm
@@ -81,6 +81,10 @@ {ax::mojom::Role::kImageMap, NSAccessibilityGroupRole}, {ax::mojom::Role::kInputTime, @"AXTimeField"}, {ax::mojom::Role::kLabelText, NSAccessibilityGroupRole}, + {ax::mojom::Role::kLayoutTable, NSAccessibilityGroupRole}, + {ax::mojom::Role::kLayoutTableCell, NSAccessibilityGroupRole}, + {ax::mojom::Role::kLayoutTableColumn, NSAccessibilityGroupRole}, + {ax::mojom::Role::kLayoutTableRow, NSAccessibilityGroupRole}, {ax::mojom::Role::kLegend, NSAccessibilityGroupRole}, {ax::mojom::Role::kLineBreak, NSAccessibilityGroupRole}, {ax::mojom::Role::kLink, NSAccessibilityLinkRole},
diff --git a/ui/accessibility/platform/ax_platform_node_win.cc b/ui/accessibility/platform/ax_platform_node_win.cc index b4054831..54652be0 100644 --- a/ui/accessibility/platform/ax_platform_node_win.cc +++ b/ui/accessibility/platform/ax_platform_node_win.cc
@@ -2529,6 +2529,18 @@ case ax::mojom::Role::kLegend: return ROLE_SYSTEM_TEXT; + case ax::mojom::Role::kLayoutTable: + return ROLE_SYSTEM_TABLE; + + case ax::mojom::Role::kLayoutTableCell: + return ROLE_SYSTEM_CELL; + + case ax::mojom::Role::kLayoutTableColumn: + return ROLE_SYSTEM_COLUMN; + + case ax::mojom::Role::kLayoutTableRow: + return ROLE_SYSTEM_ROW; + case ax::mojom::Role::kLink: return ROLE_SYSTEM_LINK; @@ -3100,6 +3112,8 @@ } } } + if (GetData().role == ax::mojom::Role::kLayoutTable) + result.push_back(base::string16(L"layout-guess:true")); // Expose aria-colcount and aria-rowcount in a table, grid or treegrid. if (IsTableLikeRole(GetData().role)) {
diff --git a/ui/android/java/src/org/chromium/ui/UiUtils.java b/ui/android/java/src/org/chromium/ui/UiUtils.java index 3d9b98e..fdaabaa 100644 --- a/ui/android/java/src/org/chromium/ui/UiUtils.java +++ b/ui/android/java/src/org/chromium/ui/UiUtils.java
@@ -4,6 +4,7 @@ package org.chromium.ui; +import android.annotation.SuppressLint; import android.content.Context; import android.graphics.Bitmap; import android.graphics.Canvas; @@ -201,6 +202,7 @@ * @param view A {@link View}. * @return Whether or not the software keyboard is visible and taking up screen space. */ + @SuppressLint("NewApi") public static boolean isKeyboardShowing(Context context, View view) { if (sKeyboardShowingDelegate != null && sKeyboardShowingDelegate.disableKeyboardCheck(context, view)) { @@ -212,9 +214,37 @@ Rect appRect = new Rect(); rootView.getWindowVisibleDisplayFrame(appRect); - final float density = context.getResources().getDisplayMetrics().density; - final float bottomMarginDp = Math.abs(rootView.getHeight() - appRect.height()) / density; - return bottomMarginDp > KEYBOARD_DETECT_BOTTOM_THRESHOLD_DP; + // Assume status bar is always at the top of the screen. + final int statusBarHeight = appRect.top; + + int bottomMargin = rootView.getHeight() - (appRect.height() + statusBarHeight); + + // If there is no bottom margin, the keyboard is not showing. + if (bottomMargin <= 0) return false; + + // If the display frame width is < root view width, controls are on the side of the screen. + // The inverse is not necessarily true; i.e. if navControlsOnSide is false, it doesn't mean + // the controls are not on the side or that they _are_ at the bottom. It might just mean the + // app is not responsible for drawing their background. + boolean navControlsOnSide = appRect.width() != rootView.getWidth(); + + // If the Android nav controls are on the sides instead of at the bottom, its height is not + // needed. + if (!navControlsOnSide) { + // When available, get the root view insets. + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { + bottomMargin -= rootView.getRootWindowInsets().getStableInsetBottom(); + } else { + // In the event we couldn't get the bottom nav height, use a best guess of the + // keyboard height. In certain cases this also means including the height of the + // Android navigation. + final float density = context.getResources().getDisplayMetrics().density; + bottomMargin -= KEYBOARD_DETECT_BOTTOM_THRESHOLD_DP * density; + } + } + + // After subtracting the bottom navigation, the remaining margin represents the keyboard. + return bottomMargin > 0; } /**
diff --git a/ui/chromeos/run_all_unittests.cc b/ui/chromeos/run_all_unittests.cc index df44659f..cde6889 100644 --- a/ui/chromeos/run_all_unittests.cc +++ b/ui/chromeos/run_all_unittests.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 <memory> + #include "base/bind.h" #include "base/compiler_specific.h" #include "base/macros.h" @@ -10,6 +12,7 @@ #include "base/test/test_suite.h" #include "mojo/edk/embedder/embedder.h" #include "testing/gtest/include/gtest/gtest.h" +#include "ui/aura/env.h" #include "ui/base/resource/resource_bundle.h" #include "ui/base/ui_base_paths.h" #include "ui/gl/test/gl_surface_test_support.h" @@ -30,14 +33,18 @@ base::FilePath ui_test_pak_path; ASSERT_TRUE(PathService::Get(ui::UI_TEST_PAK, &ui_test_pak_path)); ui::ResourceBundle::InitSharedInstanceWithPakPath(ui_test_pak_path); + env_ = aura::Env::CreateInstance(); } void Shutdown() override { + env_.reset(); ui::ResourceBundle::CleanupSharedInstance(); base::TestSuite::Shutdown(); } private: + std::unique_ptr<aura::Env> env_; + DISALLOW_COPY_AND_ASSIGN(UIChromeOSTestSuite); };
diff --git a/ui/compositor/layer_animator.cc b/ui/compositor/layer_animator.cc index 01b17ca7..7fe34df2 100644 --- a/ui/compositor/layer_animator.cc +++ b/ui/compositor/layer_animator.cc
@@ -12,9 +12,9 @@ #include "base/trace_event/trace_event.h" #include "cc/animation/animation_host.h" #include "cc/animation/animation_id_provider.h" -#include "cc/animation/animation_player.h" #include "cc/animation/animation_timeline.h" #include "cc/animation/element_animations.h" +#include "cc/animation/single_ticker_animation_player.h" #include "components/viz/common/frame_sinks/begin_frame_args.h" #include "ui/compositor/compositor.h" #include "ui/compositor/layer.h" @@ -55,8 +55,8 @@ disable_timer_for_test_(false), adding_animations_(false), animation_metrics_reporter_(nullptr) { - animation_player_ = - cc::AnimationPlayer::Create(cc::AnimationIdProvider::NextPlayerId()); + animation_player_ = cc::SingleTickerAnimationPlayer::Create( + cc::AnimationIdProvider::NextPlayerId()); } LayerAnimator::~LayerAnimator() { @@ -191,7 +191,8 @@ animation_player_->RemoveAnimation(animation_id); } -cc::AnimationPlayer* LayerAnimator::GetAnimationPlayerForTesting() const { +cc::SingleTickerAnimationPlayer* LayerAnimator::GetAnimationPlayerForTesting() + const { return animation_player_.get(); }
diff --git a/ui/compositor/layer_animator.h b/ui/compositor/layer_animator.h index 9ad8f5b..bd055ac 100644 --- a/ui/compositor/layer_animator.h +++ b/ui/compositor/layer_animator.h
@@ -24,9 +24,9 @@ namespace cc { class Animation; -class AnimationPlayer; class AnimationTimeline; class Layer; +class SingleTickerAnimationPlayer; } namespace gfx { @@ -119,7 +119,7 @@ // Detach AnimationPlayer from Layer and AnimationTimeline void DetachLayerAndTimeline(Compositor* compositor); - cc::AnimationPlayer* GetAnimationPlayerForTesting() const; + cc::SingleTickerAnimationPlayer* GetAnimationPlayerForTesting() const; // Sets the animation preemption strategy. This determines the behaviour if // a property is set during an animation. The default is @@ -388,7 +388,7 @@ LayerAnimationDelegate* delegate_; // Plays CC animations. - scoped_refptr<cc::AnimationPlayer> animation_player_; + scoped_refptr<cc::SingleTickerAnimationPlayer> animation_player_; // The currently running animations. RunningAnimations running_animations_;
diff --git a/ui/compositor/layer_owner_unittest.cc b/ui/compositor/layer_owner_unittest.cc index c848ee0d..cc6f4fa 100644 --- a/ui/compositor/layer_owner_unittest.cc +++ b/ui/compositor/layer_owner_unittest.cc
@@ -9,7 +9,7 @@ #include "base/macros.h" #include "base/memory/ptr_util.h" #include "base/test/null_task_runner.h" -#include "cc/animation/animation_player.h" +#include "cc/animation/single_ticker_animation_player.h" #include "testing/gtest/include/gtest/gtest.h" #include "ui/compositor/compositor.h" #include "ui/compositor/layer.h" @@ -186,7 +186,7 @@ layer->SetOpacity(0.5f); root_layer->Add(layer); - scoped_refptr<cc::AnimationPlayer> player = + scoped_refptr<cc::SingleTickerAnimationPlayer> player = layer->GetAnimator()->GetAnimationPlayerForTesting(); EXPECT_TRUE(player); EXPECT_TRUE(player->animation_timeline()); @@ -209,7 +209,7 @@ layer->SetOpacity(0.5f); - scoped_refptr<cc::AnimationPlayer> player = + scoped_refptr<cc::SingleTickerAnimationPlayer> player = layer->GetAnimator()->GetAnimationPlayerForTesting(); EXPECT_TRUE(player); EXPECT_TRUE(player->animation_timeline());
diff --git a/ui/compositor/layer_unittest.cc b/ui/compositor/layer_unittest.cc index fc5ac814..f7aa00a4 100644 --- a/ui/compositor/layer_unittest.cc +++ b/ui/compositor/layer_unittest.cc
@@ -26,8 +26,8 @@ #include "build/build_config.h" #include "cc/animation/animation_events.h" #include "cc/animation/animation_host.h" -#include "cc/animation/animation_player.h" #include "cc/animation/animation_ticker.h" +#include "cc/animation/single_ticker_animation_player.h" #include "cc/layers/layer.h" #include "cc/test/pixel_test_utils.h" #include "components/viz/common/frame_sinks/copy_output_request.h" @@ -1936,40 +1936,40 @@ auto* player1 = l1->GetAnimator()->GetAnimationPlayerForTesting(); auto* player2 = l2->GetAnimator()->GetAnimationPlayerForTesting(); - EXPECT_FALSE(player1->has_any_animation()); + EXPECT_FALSE(player1->animation_ticker()->has_any_animation()); // Trigger a threaded animation. l1->SetOpacity(0.5f); - EXPECT_TRUE(player1->has_any_animation()); + EXPECT_TRUE(player1->animation_ticker()->has_any_animation()); // Ensure we can remove a pending threaded animation. l1->GetAnimator()->StopAnimating(); - EXPECT_FALSE(player1->has_any_animation()); + EXPECT_FALSE(player1->animation_ticker()->has_any_animation()); // Trigger another threaded animation. l1->SetOpacity(0.2f); - EXPECT_TRUE(player1->has_any_animation()); + EXPECT_TRUE(player1->animation_ticker()->has_any_animation()); root->Add(l1.get()); GetCompositor()->SetRootLayer(root.get()); // Now l1 is part of a tree. - EXPECT_TRUE(player1->has_any_animation()); + EXPECT_TRUE(player1->animation_ticker()->has_any_animation()); l1->SetOpacity(0.1f); // IMMEDIATELY_SET_NEW_TARGET is a default preemption strategy for conflicting // animations. - EXPECT_FALSE(player1->has_any_animation()); + EXPECT_FALSE(player1->animation_ticker()->has_any_animation()); // Adding a layer to an existing tree. l2->SetOpacity(0.5f); - EXPECT_TRUE(player2->has_any_animation()); + EXPECT_TRUE(player2->animation_ticker()->has_any_animation()); l1->Add(l2.get()); - EXPECT_TRUE(player2->has_any_animation()); + EXPECT_TRUE(player2->animation_ticker()->has_any_animation()); } // Tests that in-progress threaded animations complete when a Layer's
diff --git a/ui/events/event.cc b/ui/events/event.cc index 3b38945..77a9307 100644 --- a/ui/events/event.cc +++ b/ui/events/event.cc
@@ -1178,6 +1178,7 @@ // Only Windows has native character events. if (is_char_) { key_ = DomKey::FromCharacter(native_event.wParam); + set_flags(PlatformKeyMap::ReplaceControlAndAltWithAltGraph(flags())); } else { int adjusted_flags = flags(); key_ = PlatformKeyMap::DomKeyFromKeyboardCode(key_code(), &adjusted_flags);
diff --git a/ui/events/event_unittest.cc b/ui/events/event_unittest.cc index be300ce3..3702b5b 100644 --- a/ui/events/event_unittest.cc +++ b/ui/events/event_unittest.cc
@@ -11,12 +11,15 @@ #include "base/macros.h" #include "base/test/histogram_tester.h" +#include "base/test/scoped_feature_list.h" #include "build/build_config.h" #include "testing/gtest/include/gtest/gtest.h" #include "ui/events/event_utils.h" #include "ui/events/keycodes/dom/dom_code.h" #include "ui/events/keycodes/dom/keycode_converter.h" +#include "ui/events/keycodes/keyboard_code_conversion.h" #include "ui/events/test/events_test_utils.h" +#include "ui/events/test/keyboard_layout.h" #include "ui/events/test/test_event_target.h" #include "ui/gfx/transform.h" @@ -1123,4 +1126,122 @@ } } +#if defined(OS_WIN) +namespace { + +const struct AltGraphEventTestCase { + KeyboardCode key_code; + KeyboardLayout layout; + std::vector<KeyboardCode> modifier_key_codes; + int expected_flags; +} kAltGraphEventTestCases[] = { + // US English -> AltRight never behaves as AltGraph. + {VKEY_C, + KEYBOARD_LAYOUT_ENGLISH_US, + {VKEY_RMENU, VKEY_LCONTROL, VKEY_MENU, VKEY_CONTROL}, + EF_ALT_DOWN | EF_CONTROL_DOWN}, + {VKEY_E, + KEYBOARD_LAYOUT_ENGLISH_US, + {VKEY_RMENU, VKEY_LCONTROL, VKEY_MENU, VKEY_CONTROL}, + EF_ALT_DOWN | EF_CONTROL_DOWN}, + + // French -> Always expect AltGraph if VKEY_RMENU is pressed. + {VKEY_C, + KEYBOARD_LAYOUT_FRENCH, + {VKEY_RMENU, VKEY_LCONTROL, VKEY_MENU, VKEY_CONTROL}, + EF_ALTGR_DOWN}, + {VKEY_E, + KEYBOARD_LAYOUT_FRENCH, + {VKEY_RMENU, VKEY_LCONTROL, VKEY_MENU, VKEY_CONTROL}, + EF_ALTGR_DOWN}, + + // French -> Expect Control+Alt is AltGraph on AltGraph-shifted keys. + {VKEY_C, + KEYBOARD_LAYOUT_FRENCH, + {VKEY_LMENU, VKEY_LCONTROL, VKEY_MENU, VKEY_CONTROL}, + EF_ALT_DOWN | EF_CONTROL_DOWN}, + {VKEY_E, + KEYBOARD_LAYOUT_FRENCH, + {VKEY_LMENU, VKEY_LCONTROL, VKEY_MENU, VKEY_CONTROL}, + EF_ALTGR_DOWN}, +}; + +class AltGraphEventTest : public testing::TestWithParam< + std::tr1::tuple<UINT, AltGraphEventTestCase>> { + public: + AltGraphEventTest() + : msg_({nullptr, message_type(), + static_cast<WPARAM>(test_case().key_code)}) { + // Save the current keyboard layout and state, to restore later. + CHECK(GetKeyboardState(original_keyboard_state_)); + original_keyboard_layout_ = GetKeyboardLayout(0); + + // Configure specified layout, and update keyboard state for specified + // modifier keys. + CHECK(ActivateKeyboardLayout(GetPlatformKeyboardLayout(test_case().layout), + 0)); + BYTE test_keyboard_state[256] = {}; + for (const auto& key_code : test_case().modifier_key_codes) + test_keyboard_state[key_code] = 0x80; + CHECK(SetKeyboardState(test_keyboard_state)); + } + + ~AltGraphEventTest() { + // Restore the original keyboard layout & key states. + CHECK(ActivateKeyboardLayout(original_keyboard_layout_, 0)); + CHECK(SetKeyboardState(original_keyboard_state_)); + } + + protected: + UINT message_type() const { return std::tr1::get<0>(GetParam()); } + const AltGraphEventTestCase& test_case() const { + return std::tr1::get<1>(GetParam()); + } + + const MSG msg_; + base::test::ScopedFeatureList feature_list_; + BYTE original_keyboard_state_[256] = {}; + HKL original_keyboard_layout_ = nullptr; +}; + +} // namespace + +TEST_P(AltGraphEventTest, OldKeyEventAltGraphModifier) { + feature_list_.InitFromCommandLine("", "FixAltGraph"); + + // Old behaviour always sets AltGraph modifier whenever both Control and Alt + // are pressed. + KeyEvent event(msg_); + EXPECT_EQ(event.flags() & (EF_CONTROL_DOWN | EF_ALT_DOWN | EF_ALTGR_DOWN), + EF_CONTROL_DOWN | EF_ALT_DOWN | EF_ALTGR_DOWN); +} + +TEST_P(AltGraphEventTest, KeyEventAltGraphModifer) { + feature_list_.InitFromCommandLine("FixAltGraph", ""); + + KeyEvent event(msg_); + if (message_type() == WM_CHAR) { + // By definition, if we receive a WM_CHAR message when Control and Alt are + // pressed, it indicates AltGraph. + EXPECT_EQ(event.flags() & (EF_CONTROL_DOWN | EF_ALT_DOWN | EF_ALTGR_DOWN), + EF_ALTGR_DOWN); + } else { + EXPECT_EQ(event.flags() & (EF_CONTROL_DOWN | EF_ALT_DOWN | EF_ALTGR_DOWN), + test_case().expected_flags); + } +} + +INSTANTIATE_TEST_CASE_P( + WM_KEY, + AltGraphEventTest, + ::testing::Combine(::testing::Values(WM_KEYDOWN, WM_KEYUP), + ::testing::ValuesIn(kAltGraphEventTestCases))); +INSTANTIATE_TEST_CASE_P( + WM_CHAR, + AltGraphEventTest, + ::testing::Combine(::testing::Values(WM_CHAR), + ::testing::ValuesIn(kAltGraphEventTestCases))); + +#endif // defined(OS_WIN) + } // namespace ui
diff --git a/ui/events/keycodes/platform_key_map_win.cc b/ui/events/keycodes/platform_key_map_win.cc index bd1dfcc7..d7ecacc 100644 --- a/ui/events/keycodes/platform_key_map_win.cc +++ b/ui/events/keycodes/platform_key_map_win.cc
@@ -65,10 +65,6 @@ return (flags & kControlAndAltFlags) == kControlAndAltFlags; } -int SetControlAndAltToAltGraph(int flags) { - return (flags & ~kControlAndAltFlags) | EF_ALTGR_DOWN; -} - int ReplaceAltGraphWithControlAndAlt(int flags) { return (flags & EF_ALTGR_DOWN) ? ((flags & ~EF_ALTGR_DOWN) | kControlAndAltFlags) @@ -322,12 +318,10 @@ if (it != printable_keycode_to_key_.end()) { key = it->second; if (key != DomKey::NONE) { - // TODO(25503): Map Ctrl+Alt to AltGraph if new behaviour is enabled. - if (HasControlAndAlt(try_flags) && - base::FeatureList::IsEnabled(kFixAltGraphModifier)) { - // Printable character generated via Control+Alt means AltGraph. - *flags = SetControlAndAltToAltGraph(*flags); - } + // If we find a character with |try_flags| including Control and Alt + // then this is an AltGraph-shifted event. + if (HasControlAndAlt(try_flags)) + *flags = ReplaceControlAndAltWithAltGraph(*flags); return key; } } @@ -362,6 +356,15 @@ } // static +int PlatformKeyMap::ReplaceControlAndAltWithAltGraph(int flags) { + if (!HasControlAndAlt(flags)) + return flags; + if (!IsFixAltGraphEnabled()) + return flags; + return (flags & ~kControlAndAltFlags) | EF_ALTGR_DOWN; +} + +// static bool PlatformKeyMap::UsesAltGraph() { base::ThreadLocalStorage::Slot* platform_key_map_tls = g_platform_key_map_tls_lazy.Pointer();
diff --git a/ui/events/keycodes/platform_key_map_win.h b/ui/events/keycodes/platform_key_map_win.h index 7b9871f..53e13ba 100644 --- a/ui/events/keycodes/platform_key_map_win.h +++ b/ui/events/keycodes/platform_key_map_win.h
@@ -11,6 +11,7 @@ #include "base/event_types.h" #include "base/hash.h" +#include "ui/events/event.h" #include "ui/events/events_export.h" #include "ui/events/keycodes/dom/dom_key.h" #include "ui/events/keycodes/keyboard_codes_win.h" @@ -25,15 +26,20 @@ ~PlatformKeyMap(); // Returns the DOM KeyboardEvent key from |KeyboardCode|+|EventFlags| and - // the keyboard layout of current thread. + // the keyboard layout of current thread. If this is an AltGraph modified + // key then |flags| will have Control+Alt removed, and AltGraph set. // Updates a per-thread key map cache whenever the layout changes. - // If |flags| includes both Control and Alt modifiers, they will be replaced - // by AltGraph if the key generates a printable character with them. static DomKey DomKeyFromKeyboardCode(KeyboardCode key_code, int* flags); // Returns true if the currently-active keymap uses AltGraph shift. static bool UsesAltGraph(); + // If the supplied event has both Control and Alt modifiers set, then they + // are replaced by AltGraph. This should only ever be applied to the flags + // for printable-character events. + // TODO(crbug.com/25503): Has no effect if FixAltGraph is not enabled. + static int ReplaceControlAndAltWithAltGraph(int flags); + // TODO(crbug.com/25503): Returns true if we disambiguate AltGraph. static bool IsFixAltGraphEnabled();
diff --git a/ui/events/keycodes/platform_key_map_win_unittest.cc b/ui/events/keycodes/platform_key_map_win_unittest.cc index 814d5a3..7424bfe8 100644 --- a/ui/events/keycodes/platform_key_map_win_unittest.cc +++ b/ui/events/keycodes/platform_key_map_win_unittest.cc
@@ -6,6 +6,7 @@ #include "base/macros.h" #include "base/strings/string16.h" +#include "base/test/scoped_feature_list.h" #include "testing/gtest/include/gtest/gtest.h" #include "ui/events/event_constants.h" #include "ui/events/keycodes/dom/dom_code.h" @@ -29,6 +30,11 @@ const char* altgr_capslock; }; +struct DomKeyAndFlags { + DomKey key; + int flags; +}; + } // anonymous namespace class PlatformKeyMapTest : public testing::Test { @@ -87,6 +93,16 @@ return keymap.DomKeyFromKeyboardCodeImpl(key_code, &flags); } + // Returns the DomKey and |flags| in a struct, for use in tests verifying + // that the API correctly modifies the |flags| in/out parameter. + DomKeyAndFlags DomKeyAndFlagsFromKeyboardCode(const PlatformKeyMap& keymap, + KeyboardCode key_code, + int flags) { + DomKeyAndFlags result = {DomKey(), flags}; + result.key = keymap.DomKeyFromKeyboardCodeImpl(key_code, &result.flags); + return result; + } + private: DISALLOW_COPY_AND_ASSIGN(PlatformKeyMapTest); }; @@ -326,7 +342,7 @@ } } -TEST_F(PlatformKeyMapTest, AltGraph) { +TEST_F(PlatformKeyMapTest, AltGraphDomKey) { PlatformKeyMap us_keymap( GetPlatformKeyboardLayout(KEYBOARD_LAYOUT_ENGLISH_US)); EXPECT_EQ(DomKey::ALT, @@ -343,4 +359,75 @@ EF_ALTGR_DOWN | EF_IS_EXTENDED_KEY)); } +namespace { + +const struct AltGraphModifierTestCase { + // Test-case Virtual Keycode and modifier flags. + KeyboardCode key_code; + int flags; + + // Whether or not this case generates an AltGraph-shifted key under FR-fr + // layout. + bool expect_alt_graph; +} kAltGraphModifierTestCases[] = { + {VKEY_C, EF_NONE, false}, + {VKEY_C, EF_ALTGR_DOWN, false}, + {VKEY_C, EF_CONTROL_DOWN | EF_ALT_DOWN, false}, + {VKEY_C, EF_CONTROL_DOWN | EF_ALT_DOWN | EF_ALTGR_DOWN, false}, + {VKEY_E, EF_NONE, false}, + {VKEY_E, EF_ALTGR_DOWN, true}, + {VKEY_E, EF_CONTROL_DOWN | EF_ALT_DOWN, true}, + {VKEY_E, EF_CONTROL_DOWN | EF_ALT_DOWN | EF_ALTGR_DOWN, true}, +}; + +class AltGraphModifierTest + : public PlatformKeyMapTest, + public testing::WithParamInterface<KeyboardLayout> { + public: + AltGraphModifierTest() : keymap_(GetPlatformKeyboardLayout(GetParam())) {} + + protected: + base::test::ScopedFeatureList feature_list_; + PlatformKeyMap keymap_; +}; + +TEST_P(AltGraphModifierTest, OldAltGraphModifierBehaviour) { + feature_list_.InitFromCommandLine("", "FixAltGraph"); + + // Regardless of the keyboard layout, modifier flags should be unchanged. + for (const auto& test_case : kAltGraphModifierTestCases) { + DomKeyAndFlags result = DomKeyAndFlagsFromKeyboardCode( + keymap_, test_case.key_code, test_case.flags); + EXPECT_EQ(test_case.flags, result.flags) + << " for key_code=" << test_case.key_code; + } +} + +TEST_P(AltGraphModifierTest, AltGraphModifierBehaviour) { + feature_list_.InitFromCommandLine("FixAltGraph", ""); + + // If the key generates a character under AltGraph then |result| should + // report AltGraph, but not Control or Alt. + for (const auto& test_case : kAltGraphModifierTestCases) { + DomKeyAndFlags result = DomKeyAndFlagsFromKeyboardCode( + keymap_, test_case.key_code, test_case.flags); + if (GetParam() == KEYBOARD_LAYOUT_FRENCH && test_case.expect_alt_graph) { + EXPECT_EQ(EF_ALTGR_DOWN, result.flags) + << " for key_code=" << test_case.key_code + << " flags=" << test_case.flags; + } else { + EXPECT_EQ(test_case.flags, result.flags) + << " for key_code=" << test_case.key_code + << " flags=" << test_case.flags; + } + } +} + +INSTANTIATE_TEST_CASE_P(VerifyAltGraph, + AltGraphModifierTest, + ::testing::Values(KEYBOARD_LAYOUT_ENGLISH_US, + KEYBOARD_LAYOUT_FRENCH)); + +} // namespace + } // namespace ui
diff --git a/ui/file_manager/file_manager/background/js/background.js b/ui/file_manager/file_manager/background/js/background.js index aad29e8..aefdbde 100644 --- a/ui/file_manager/file_manager/background/js/background.js +++ b/ui/file_manager/file_manager/background/js/background.js
@@ -146,8 +146,18 @@ * devicePath. * @private */ -FileBrowserBackgroundImpl.prototype.handleViewEvent_ = - function(event) { +FileBrowserBackgroundImpl.prototype.handleViewEvent_ = function(event) { + util.doIfPrimaryContext(() => { + this.handleViewEventInternal_(event); + }); +}; + +/** + * @param {!Event} event An event with the volumeId or + * devicePath. + * @private + */ +FileBrowserBackgroundImpl.prototype.handleViewEventInternal_ = function(event) { volumeManagerFactory.getInstance() .then( (/** @@ -468,6 +478,17 @@ * @private */ FileBrowserBackgroundImpl.prototype.onMountCompleted_ = function(event) { + util.doIfPrimaryContext(() => { + this.onMountCompletedInternal_(event); + }); +}; + +/** + * @param {!Object} event Event details. + * @private + */ +FileBrowserBackgroundImpl.prototype.onMountCompletedInternal_ = function( + event) { // If there is no focused window, then create a new one opened on the // mounted FSP volume. this.findFocusedWindow_().then(function(key) {
diff --git a/ui/gl/gl_image_io_surface.mm b/ui/gl/gl_image_io_surface.mm index 5c7b79ae..9b1054e 100644 --- a/ui/gl/gl_image_io_surface.mm +++ b/ui/gl/gl_image_io_surface.mm
@@ -220,6 +220,10 @@ gfx::BufferFormat format) { DCHECK(thread_checker_.CalledOnValidThread()); DCHECK(!io_surface_); + if (!io_surface) { + LOG(ERROR) << "Invalid IOSurface"; + return false; + } if (!ValidInternalFormat(internalformat_)) { LOG(ERROR) << "Invalid internalformat: "
diff --git a/ui/gl/gl_image_memory.cc b/ui/gl/gl_image_memory.cc index 87a5c1d..5944445 100644 --- a/ui/gl/gl_image_memory.cc +++ b/ui/gl/gl_image_memory.cc
@@ -12,6 +12,7 @@ #include "ui/gfx/buffer_format_util.h" #include "ui/gl/gl_bindings.h" #include "ui/gl/gl_context.h" +#include "ui/gl/gl_enums.h" #include "ui/gl/gl_version_info.h" using gfx::BufferFormat; @@ -30,6 +31,7 @@ case GL_RG: case GL_RGB: case GL_RGBA: + case GL_RGB10_A2_EXT: case GL_BGRA_EXT: return true; default: @@ -52,10 +54,10 @@ case gfx::BufferFormat::RGBX_8888: case gfx::BufferFormat::RGBA_8888: case gfx::BufferFormat::BGRX_8888: + case gfx::BufferFormat::BGRX_1010102: case gfx::BufferFormat::BGRA_8888: case gfx::BufferFormat::RGBA_F16: return true; - case gfx::BufferFormat::BGRX_1010102: case gfx::BufferFormat::YVU_420: case gfx::BufferFormat::YUV_420_BIPLANAR: case gfx::BufferFormat::UYVY_422: @@ -82,10 +84,10 @@ case gfx::BufferFormat::RGBX_8888: case gfx::BufferFormat::RGBA_8888: case gfx::BufferFormat::BGRX_8888: + case gfx::BufferFormat::BGRX_1010102: case gfx::BufferFormat::BGRA_8888: case gfx::BufferFormat::RGBA_F16: return false; - case gfx::BufferFormat::BGRX_1010102: case gfx::BufferFormat::YVU_420: case gfx::BufferFormat::YUV_420_BIPLANAR: case gfx::BufferFormat::UYVY_422: @@ -126,6 +128,9 @@ case gfx::BufferFormat::BGRX_8888: return GL_RGB; case gfx::BufferFormat::BGRX_1010102: + // Technically speaking we should use an opaque format, but neither + // OpenGLES nor OpenGL supports the hypothetical GL_RGB10_EXT. + return GL_RGB10_A2_EXT; case gfx::BufferFormat::YVU_420: case gfx::BufferFormat::YUV_420_BIPLANAR: case gfx::BufferFormat::UYVY_422: @@ -142,6 +147,7 @@ case gfx::BufferFormat::RGBX_8888: return GL_RGBA; case gfx::BufferFormat::BGRX_8888: + case gfx::BufferFormat::BGRX_1010102: return GL_BGRA_EXT; case gfx::BufferFormat::BGR_565: case gfx::BufferFormat::RGBA_4444: @@ -157,7 +163,6 @@ case gfx::BufferFormat::DXT5: case gfx::BufferFormat::ETC1: return TextureFormat(format); - case gfx::BufferFormat::BGRX_1010102: case gfx::BufferFormat::YVU_420: case gfx::BufferFormat::YUV_420_BIPLANAR: case gfx::BufferFormat::UYVY_422: @@ -186,12 +191,13 @@ return GL_UNSIGNED_SHORT; case gfx::BufferFormat::RGBA_F16: return GL_HALF_FLOAT_OES; + case gfx::BufferFormat::BGRX_1010102: + return GL_UNSIGNED_INT_2_10_10_10_REV; case gfx::BufferFormat::ATC: case gfx::BufferFormat::ATCIA: case gfx::BufferFormat::DXT1: case gfx::BufferFormat::DXT5: case gfx::BufferFormat::ETC1: - case gfx::BufferFormat::BGRX_1010102: case gfx::BufferFormat::YVU_420: case gfx::BufferFormat::YUV_420_BIPLANAR: case gfx::BufferFormat::UYVY_422: @@ -213,6 +219,7 @@ case gfx::BufferFormat::RGBX_8888: case gfx::BufferFormat::RGBA_8888: case gfx::BufferFormat::BGRX_8888: + case gfx::BufferFormat::BGRX_1010102: case gfx::BufferFormat::BGRA_8888: return base::checked_cast<GLint>(stride) / 4; case gfx::BufferFormat::RGBA_F16: @@ -224,7 +231,6 @@ case gfx::BufferFormat::DXT1: case gfx::BufferFormat::DXT5: case gfx::BufferFormat::ETC1: - case gfx::BufferFormat::BGRX_1010102: case gfx::BufferFormat::YVU_420: case gfx::BufferFormat::YUV_420_BIPLANAR: case gfx::BufferFormat::UYVY_422: @@ -330,6 +336,7 @@ data_format, data_type, data_row_length); case gfx::BufferFormat::RGBA_4444: case gfx::BufferFormat::RGBA_8888: + case gfx::BufferFormat::BGRX_1010102: case gfx::BufferFormat::BGRA_8888: case gfx::BufferFormat::RGBA_F16: case gfx::BufferFormat::R_8: @@ -356,11 +363,10 @@ case gfx::BufferFormat::DXT5: case gfx::BufferFormat::ETC1: return nullptr; // No data conversion needed - case gfx::BufferFormat::BGRX_1010102: case gfx::BufferFormat::YVU_420: case gfx::BufferFormat::YUV_420_BIPLANAR: case gfx::BufferFormat::UYVY_422: - NOTREACHED(); + NOTREACHED() << gfx::BufferFormatToString(format); return nullptr; } @@ -390,12 +396,13 @@ gfx::BufferFormat format, size_t stride) { if (!ValidInternalFormat(internalformat_)) { - LOG(ERROR) << "Invalid internalformat: " << internalformat_; + LOG(ERROR) << "Invalid internalformat: " + << GLEnums::GetStringEnum(internalformat_); return false; } if (!ValidFormat(format)) { - LOG(ERROR) << "Invalid format: " << static_cast<int>(format); + LOG(ERROR) << "Invalid format: " << gfx::BufferFormatToString(format); return false; }
diff --git a/ui/gl/gl_image_shared_memory_unittest.cc b/ui/gl/gl_image_shared_memory_unittest.cc index fdef8d9..990e4d28 100644 --- a/ui/gl/gl_image_shared_memory_unittest.cc +++ b/ui/gl/gl_image_shared_memory_unittest.cc
@@ -7,6 +7,7 @@ #include "base/memory/shared_memory.h" #include "base/sys_info.h" +#include "build/build_config.h" #include "testing/gtest/include/gtest/gtest.h" #include "ui/gl/gl_image_shared_memory.h" #include "ui/gl/test/gl_image_test_template.h" @@ -50,6 +51,12 @@ GLImageSharedMemoryTestDelegate<gfx::BufferFormat::RGBX_8888>, GLImageSharedMemoryTestDelegate<gfx::BufferFormat::RGBA_8888>, GLImageSharedMemoryTestDelegate<gfx::BufferFormat::BGRX_8888>, +#if defined(OS_LINUX) + // Fails on Win nVidia and linux android: the test writes nothing (we read + // back the color used to clear the buffer). + // TODO(mcasas): enable those paltforms https://crbug.com/803451. + GLImageSharedMemoryTestDelegate<gfx::BufferFormat::BGRX_1010102>, +#endif GLImageSharedMemoryTestDelegate<gfx::BufferFormat::BGRA_8888>>; INSTANTIATE_TYPED_TEST_CASE_P(GLImageSharedMemory,
diff --git a/ui/gl/gl_surface_glx.cc b/ui/gl/gl_surface_glx.cc index 7579c74..c9a66950 100644 --- a/ui/gl/gl_surface_glx.cc +++ b/ui/gl/gl_surface_glx.cc
@@ -673,10 +673,10 @@ const PresentationCallback& callback) { TRACE_EVENT2("gpu", "NativeViewGLSurfaceGLX:RealSwapBuffers", "width", GetSize().width(), "height", GetSize().height()); - presentation_helper_->PreSwapBuffers(callback); + GLSurfacePresentationHelper::ScopedSwapBuffers scoped_swap_buffers( + presentation_helper_.get(), callback); glXSwapBuffers(g_display, GetDrawableHandle()); - presentation_helper_->PostSwapBuffers(); - return gfx::SwapResult::SWAP_ACK; + return scoped_swap_buffers.result(); } gfx::Size NativeViewGLSurfaceGLX::GetSize() { @@ -716,10 +716,11 @@ int height, const PresentationCallback& callback) { DCHECK(g_driver_glx.ext.b_GLX_MESA_copy_sub_buffer); - presentation_helper_->PreSwapBuffers(callback); + + GLSurfacePresentationHelper::ScopedSwapBuffers scoped_swap_buffers( + presentation_helper_.get(), callback); glXCopySubBufferMESA(g_display, GetDrawableHandle(), x, y, width, height); - presentation_helper_->PostSwapBuffers(); - return gfx::SwapResult::SWAP_ACK; + return scoped_swap_buffers.result(); } bool NativeViewGLSurfaceGLX::OnMakeCurrent(GLContext* context) {
diff --git a/ui/gl/gl_surface_presentation_helper.cc b/ui/gl/gl_surface_presentation_helper.cc index 5391d73..6825fda 100644 --- a/ui/gl/gl_surface_presentation_helper.cc +++ b/ui/gl/gl_surface_presentation_helper.cc
@@ -11,6 +11,19 @@ namespace gl { +GLSurfacePresentationHelper::ScopedSwapBuffers::ScopedSwapBuffers( + GLSurfacePresentationHelper* helper, + const GLSurface::PresentationCallback& callback) + : helper_(helper) { + if (helper_) + helper_->PreSwapBuffers(callback); +} + +GLSurfacePresentationHelper::ScopedSwapBuffers::~ScopedSwapBuffers() { + if (helper_) + helper_->PostSwapBuffers(result_); +} + GLSurfacePresentationHelper::Frame::Frame(Frame&& other) = default; GLSurfacePresentationHelper::Frame::Frame( @@ -25,9 +38,7 @@ GLSurfacePresentationHelper::GLSurfacePresentationHelper( gfx::VSyncProvider* vsync_provider) - : vsync_provider_(vsync_provider), weak_ptr_factory_(this) { - DCHECK(vsync_provider_); -} + : vsync_provider_(vsync_provider), weak_ptr_factory_(this) {} GLSurfacePresentationHelper::GLSurfacePresentationHelper( base::TimeTicks timebase, @@ -84,9 +95,21 @@ pending_frames_.push_back(Frame(std::move(timer), callback)); } -void GLSurfacePresentationHelper::PostSwapBuffers() { - if (!waiting_for_vsync_parameters_) - CheckPendingFrames(); +void GLSurfacePresentationHelper::PostSwapBuffers(gfx::SwapResult result) { + DCHECK(!pending_frames_.empty()); + if (result == gfx::SwapResult::SWAP_ACK && gpu_timing_client_) { + if (!waiting_for_vsync_parameters_) + CheckPendingFrames(); + return; + } + + auto frame = std::move(pending_frames_.back()); + pending_frames_.pop_back(); + if (frame.timer) { + bool has_context = gl_context_ && gl_context_->IsCurrent(surface_); + frame.timer->Destroy(has_context); + } + frame.callback.Run(gfx::PresentationFeedback()); } void GLSurfacePresentationHelper::CheckPendingFrames() { @@ -109,7 +132,8 @@ if (gl_context_ && !gl_context_->IsCurrent(surface_)) { gpu_timing_client_ = nullptr; for (auto& frame : pending_frames_) { - frame.timer->Destroy(false /* has_context */); + if (frame.timer) + frame.timer->Destroy(false /* has_context */); frame.callback.Run(gfx::PresentationFeedback()); } pending_frames_.clear();
diff --git a/ui/gl/gl_surface_presentation_helper.h b/ui/gl/gl_surface_presentation_helper.h index e0e8b693..6baf88f 100644 --- a/ui/gl/gl_surface_presentation_helper.h +++ b/ui/gl/gl_surface_presentation_helper.h
@@ -9,6 +9,7 @@ #include "base/macros.h" #include "base/memory/weak_ptr.h" #include "base/time/time.h" +#include "ui/gfx/swap_result.h" #include "ui/gl/gl_export.h" #include "ui/gl/gl_surface.h" @@ -26,6 +27,22 @@ // implementations. class GL_EXPORT GLSurfacePresentationHelper { public: + class GL_EXPORT ScopedSwapBuffers { + public: + ScopedSwapBuffers(GLSurfacePresentationHelper* helper, + const GLSurface::PresentationCallback& callback); + ~ScopedSwapBuffers(); + + void set_result(gfx::SwapResult result) { result_ = result; } + gfx::SwapResult result() const { return result_; } + + private: + GLSurfacePresentationHelper* const helper_; + gfx::SwapResult result_ = gfx::SwapResult::SWAP_ACK; + + DISALLOW_COPY_AND_ASSIGN(ScopedSwapBuffers); + }; + explicit GLSurfacePresentationHelper(gfx::VSyncProvider* vsync_provider); // For using fixed VSync provider. @@ -35,7 +52,7 @@ void OnMakeCurrent(GLContext* context, GLSurface* surface); void PreSwapBuffers(const GLSurface::PresentationCallback& callback); - void PostSwapBuffers(); + void PostSwapBuffers(gfx::SwapResult result); private: struct Frame {
diff --git a/ui/keyboard/BUILD.gn b/ui/keyboard/BUILD.gn index 3b28161..ccf79d4 100644 --- a/ui/keyboard/BUILD.gn +++ b/ui/keyboard/BUILD.gn
@@ -35,6 +35,8 @@ "keyboard_util.h", "notification_manager.cc", "notification_manager.h", + "queued_container_type.cc", + "queued_container_type.h", ] defines = [ "KEYBOARD_IMPLEMENTATION" ]
diff --git a/ui/keyboard/keyboard_controller.cc b/ui/keyboard/keyboard_controller.cc index 67263cbc..ceca8f2a 100644 --- a/ui/keyboard/keyboard_controller.cc +++ b/ui/keyboard/keyboard_controller.cc
@@ -36,6 +36,7 @@ #include "ui/keyboard/keyboard_ui.h" #include "ui/keyboard/keyboard_util.h" #include "ui/keyboard/notification_manager.h" +#include "ui/keyboard/queued_container_type.h" #include "ui/wm/core/window_animations.h" #if defined(OS_CHROMEOS) @@ -202,12 +203,11 @@ show_on_content_update_(false), keyboard_locked_(false), state_(KeyboardControllerState::UNKNOWN), - enqueued_container_type_(ContainerType::FULL_WIDTH), weak_factory_report_lingering_state_(this), weak_factory_will_hide_(this) { ui_->GetInputMethod()->AddObserver(this); ui_->SetController(this); - SetContainerBehaviorInternal(enqueued_container_type_); + SetContainerBehaviorInternal(ContainerType::FULL_WIDTH); ChangeState(KeyboardControllerState::INITIAL); } @@ -385,11 +385,8 @@ } void KeyboardController::HideAnimationFinished() { - if (state_ != KeyboardControllerState::HIDDEN) - return; - - if (enqueued_container_type_ != container_behavior_->GetType()) { - SetContainerBehaviorInternal(enqueued_container_type_); + if (state_ == KeyboardControllerState::HIDDEN && queued_container_type_) { + SetContainerBehaviorInternal(queued_container_type_->container_type()); ShowKeyboard(false /* lock */); } } @@ -624,6 +621,10 @@ container_behavior_->DoShowingAnimation(container_.get(), &settings); + // the queued container behavior will notify JS to change layout when it + // gets destroyed. + queued_container_type_ = nullptr; + ChangeState(KeyboardControllerState::SHOWN); NotifyKeyboardBoundsChangingAndEnsureCaretInWorkArea(); } @@ -742,10 +743,20 @@ } void KeyboardController::SetContainerType(const ContainerType type) { - if (container_behavior_->GetType() == type) - return; + SetContainerType(type, base::BindOnce([](bool ignored) { /* noop */ })); +} - enqueued_container_type_ = type; +void KeyboardController::SetContainerType( + const ContainerType type, + base::OnceCallback<void(bool)> callback) { + if (container_behavior_->GetType() == type) { + std::move(callback).Run(false); + return; + } + + queued_container_type_ = + std::make_unique<QueuedContainerType>(this, type, std::move(callback)); + if (state_ == KeyboardControllerState::SHOWN) { HideKeyboard(HIDE_REASON_AUTOMATIC); } else {
diff --git a/ui/keyboard/keyboard_controller.h b/ui/keyboard/keyboard_controller.h index c702b72..76e15f7 100644 --- a/ui/keyboard/keyboard_controller.h +++ b/ui/keyboard/keyboard_controller.h
@@ -22,6 +22,7 @@ #include "ui/keyboard/keyboard_layout_delegate.h" #include "ui/keyboard/keyboard_util.h" #include "ui/keyboard/notification_manager.h" +#include "ui/keyboard/queued_container_type.h" namespace aura { class Window; @@ -152,6 +153,10 @@ KeyboardControllerState GetStateForTest() const { return state_; } + ContainerType GetActiveContainerType() const { + return container_behavior_->GetType(); + } + const gfx::Rect AdjustSetBoundsRequest( const gfx::Rect& display_bounds, const gfx::Rect& requested_bounds) const; @@ -171,6 +176,8 @@ // will trigger a hide animation and a subsequent show animation. Otherwise // the ContainerBehavior change is synchronous. void SetContainerType(const ContainerType type); + void SetContainerType(const ContainerType type, + base::OnceCallback<void(bool)> callback); // Sets floating keyboard drggable rect. bool SetDraggableArea(const gfx::Rect& rect); @@ -252,6 +259,8 @@ // Current active visual behavior for the keyboard container. std::unique_ptr<ContainerBehavior> container_behavior_; + std::unique_ptr<QueuedContainerType> queued_container_type_; + // If true, show the keyboard window when keyboard UI content updates. bool show_on_content_update_; @@ -268,8 +277,6 @@ KeyboardControllerState state_; - ContainerType enqueued_container_type_; - NotificationManager notification_manager_; static KeyboardController* instance_;
diff --git a/ui/keyboard/keyboard_controller_unittest.cc b/ui/keyboard/keyboard_controller_unittest.cc index fad8f1e..cb67733 100644 --- a/ui/keyboard/keyboard_controller_unittest.cc +++ b/ui/keyboard/keyboard_controller_unittest.cc
@@ -176,6 +176,32 @@ DISALLOW_COPY_AND_ASSIGN(TestKeyboardLayoutDelegate); }; +class SetModeCallbackInvocationCounter { + public: + SetModeCallbackInvocationCounter() : weak_factory_invoke_(this) {} + + void Invoke(bool status) { + if (status) + invocation_count_success_++; + else + invocation_count_failure_++; + } + + base::OnceCallback<void(bool)> GetInvocationCallback() { + return base::BindOnce(&SetModeCallbackInvocationCounter::Invoke, + weak_factory_invoke_.GetWeakPtr()); + } + + int invocation_count_for_status(bool status) { + return status ? invocation_count_success_ : invocation_count_failure_; + } + + private: + int invocation_count_success_ = 0; + int invocation_count_failure_ = 0; + base::WeakPtrFactory<SetModeCallbackInvocationCounter> weak_factory_invoke_; +}; + } // namespace class KeyboardControllerTest : public testing::Test, @@ -655,13 +681,27 @@ EXPECT_EQ(gfx::Rect(), notified_occluding_bounds()); EXPECT_FALSE(notified_is_available()); - controller()->SetContainerType(ContainerType::FLOATING); + SetModeCallbackInvocationCounter invocation_counter; + controller()->SetContainerType(ContainerType::FLOATING, + invocation_counter.GetInvocationCallback()); + EXPECT_EQ(0, invocation_counter.invocation_count_for_status(true)); + EXPECT_EQ(0, invocation_counter.invocation_count_for_status(false)); ShowKeyboard(); RunAnimationForLayer(layer); + EXPECT_EQ(1, invocation_counter.invocation_count_for_status(true)); + EXPECT_EQ(0, invocation_counter.invocation_count_for_status(false)); // Visible bounds and occluding bounds are now different. EXPECT_EQ(keyboard_container()->bounds(), notified_visible_bounds()); EXPECT_EQ(gfx::Rect(), notified_occluding_bounds()); EXPECT_TRUE(notified_is_available()); + + // callback should do nothing when container mode is set to the current active + // container type. An unnecessary call gets registered synchronously as a + // failure status to the callback. + controller()->SetContainerType(ContainerType::FLOATING, + invocation_counter.GetInvocationCallback()); + EXPECT_EQ(1, invocation_counter.invocation_count_for_status(true)); + EXPECT_EQ(1, invocation_counter.invocation_count_for_status(false)); } // Show keyboard during keyboard hide animation should abort the hide animation
diff --git a/ui/keyboard/keyboard_util.cc b/ui/keyboard/keyboard_util.cc index 356253966..b511c7a 100644 --- a/ui/keyboard/keyboard_util.cc +++ b/ui/keyboard/keyboard_util.cc
@@ -245,12 +245,14 @@ if (!input_method) return false; + // This can be null if no text input field is not focused. ui::TextInputClient* tic = input_method->GetTextInputClient(); SendProcessKeyEvent(ui::ET_KEY_PRESSED, host); ui::KeyEvent char_event(key_value, code, ui::EF_NONE); - tic->InsertChar(char_event); + if (tic) + tic->InsertChar(char_event); SendProcessKeyEvent(ui::ET_KEY_RELEASED, host); } } else {
diff --git a/ui/keyboard/queued_container_type.cc b/ui/keyboard/queued_container_type.cc new file mode 100644 index 0000000..2cf7b88 --- /dev/null +++ b/ui/keyboard/queued_container_type.cc
@@ -0,0 +1,24 @@ +// 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 "base/bind.h" +#include "ui/keyboard/keyboard_controller.h" + +namespace keyboard { + +QueuedContainerType::QueuedContainerType( + KeyboardController* controller, + ContainerType container_type, + base::OnceCallback<void(bool success)> callback) + : controller_(controller), + container_type_(container_type), + callback_(std::move(callback)){}; + +QueuedContainerType::~QueuedContainerType() { + bool change_successful = + controller_->GetActiveContainerType() == container_type_; + std::move(callback_).Run(change_successful); +}; + +} // namespace keyboard
diff --git a/ui/keyboard/queued_container_type.h b/ui/keyboard/queued_container_type.h new file mode 100644 index 0000000..ce58d930 --- /dev/null +++ b/ui/keyboard/queued_container_type.h
@@ -0,0 +1,37 @@ +// 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. + +#ifndef UI_KEYBOARD_QUEUED_CONTAINER_TYPE_H_ +#define UI_KEYBOARD_QUEUED_CONTAINER_TYPE_H_ + +#include "base/bind.h" +#include "ui/keyboard/container_type.h" + +namespace keyboard { + +class KeyboardController; + +// Tracks a queued ContainerType change request. Couples a container type with a +// callback to invoke once the necessary animation and container changes are +// complete. +// The callback will be invoked once this object goes out of scope. Success +// is defined as the KeyboardController's current container behavior matching +// the same container type as the queued container type. +class QueuedContainerType { + public: + QueuedContainerType(KeyboardController* controller, + ContainerType container_type, + base::OnceCallback<void(bool success)> callback); + ~QueuedContainerType(); + ContainerType container_type() { return container_type_; } + + private: + KeyboardController* controller_; + ContainerType container_type_; + base::OnceCallback<void(bool success)> callback_; +}; + +} // namespace keyboard + +#endif // UI_KEYBOARD_QUEUED_CONTAINER_TYPE_H_
diff --git a/ui/message_center/fake_message_center.cc b/ui/message_center/fake_message_center.cc index 6bb96cc9..7bc0491 100644 --- a/ui/message_center/fake_message_center.cc +++ b/ui/message_center/fake_message_center.cc
@@ -39,7 +39,7 @@ return false; } -message_center::Notification* FakeMessageCenter::FindVisibleNotificationById( +Notification* FakeMessageCenter::FindVisibleNotificationById( const std::string& id) { for (auto* notification : GetVisibleNotifications()) { if (id == notification->id())
diff --git a/ui/message_center/fake_message_center.h b/ui/message_center/fake_message_center.h index b10be1b..0c4ad72 100644 --- a/ui/message_center/fake_message_center.h +++ b/ui/message_center/fake_message_center.h
@@ -27,8 +27,7 @@ size_t NotificationCount() const override; bool HasPopupNotifications() const override; bool IsQuietMode() const override; - message_center::Notification* FindVisibleNotificationById( - const std::string& id) override; + Notification* FindVisibleNotificationById(const std::string& id) override; const NotificationList::Notifications& GetVisibleNotifications() override; NotificationList::PopupNotifications GetPopupNotifications() override; void AddNotification(std::unique_ptr<Notification> notification) override;
diff --git a/ui/message_center/message_center.h b/ui/message_center/message_center.h index c0666c34..493c1454 100644 --- a/ui/message_center/message_center.h +++ b/ui/message_center/message_center.h
@@ -24,7 +24,7 @@ // is shown, closed, or clicked on. // // MessageCenter is agnostic of profiles; it uses the string returned by -// message_center::Notification::id() to uniquely identify a notification. It is +// Notification::id() to uniquely identify a notification. It is // the caller's responsibility to formulate the id so that 2 different // notification should have different ids. For example, if the caller supports // multiple profiles, then caller should encode both profile characteristics and @@ -73,8 +73,7 @@ // Find the notification with the corresponding id. Returns null if not // found. The returned instance is owned by the message center. - virtual message_center::Notification* FindVisibleNotificationById( - const std::string& id) = 0; + virtual Notification* FindVisibleNotificationById(const std::string& id) = 0; // Gets all notifications to be shown to the user in the message center. Note // that queued changes due to the message center being open are not reflected
diff --git a/ui/message_center/message_center_impl.cc b/ui/message_center/message_center_impl.cc index 62f7c49..71df5756 100644 --- a/ui/message_center/message_center_impl.cc +++ b/ui/message_center/message_center_impl.cc
@@ -178,7 +178,7 @@ return notification_list_->quiet_mode(); } -message_center::Notification* MessageCenterImpl::FindVisibleNotificationById( +Notification* MessageCenterImpl::FindVisibleNotificationById( const std::string& id) { DCHECK_CALLED_ON_VALID_THREAD(thread_checker_); return notification_list_->GetNotificationById(id);
diff --git a/ui/message_center/message_center_impl.h b/ui/message_center/message_center_impl.h index 4fff2b3..6bc4b22 100644 --- a/ui/message_center/message_center_impl.h +++ b/ui/message_center/message_center_impl.h
@@ -48,8 +48,7 @@ size_t NotificationCount() const override; bool HasPopupNotifications() const override; bool IsQuietMode() const override; - message_center::Notification* FindVisibleNotificationById( - const std::string& id) override; + Notification* FindVisibleNotificationById(const std::string& id) override; const NotificationList::Notifications& GetVisibleNotifications() override; NotificationList::PopupNotifications GetPopupNotifications() override; void AddNotification(std::unique_ptr<Notification> notification) override;
diff --git a/ui/message_center/message_center_impl_unittest.cc b/ui/message_center/message_center_impl_unittest.cc index 02c2c98b..0f46b19 100644 --- a/ui/message_center/message_center_impl_unittest.cc +++ b/ui/message_center/message_center_impl_unittest.cc
@@ -117,14 +117,13 @@ } Notification* CreateNotification(const std::string& id, - message_center::NotificationType type) { + NotificationType type) { return CreateNotificationWithNotifierId(id, "app1", type); } - Notification* CreateNotificationWithNotifierId( - const std::string& id, - const std::string& notifier_id, - message_center::NotificationType type) { + Notification* CreateNotificationWithNotifierId(const std::string& id, + const std::string& notifier_id, + NotificationType type) { RichNotificationData optional_fields; optional_fields.buttons.push_back(ButtonInfo(UTF8ToUTF16("foo"))); optional_fields.buttons.push_back(ButtonInfo(UTF8ToUTF16("foo"))); @@ -162,7 +161,7 @@ // NotificationBlocker overrides: bool ShouldShowNotificationAsPopup( - const message_center::Notification& notification) const override { + const Notification& notification) const override { return notifications_enabled_; } @@ -402,8 +401,7 @@ EXPECT_EQ(2u, message_center()->GetVisibleNotifications().size()); // "id1" is displayed as a pop-up so that it will be closed when blocked. - message_center()->DisplayedNotification("id1", - message_center::DISPLAY_SOURCE_POPUP); + message_center()->DisplayedNotification("id1", DISPLAY_SOURCE_POPUP); // Block all notifications. All popups are gone and message center should be // hidden. @@ -451,8 +449,7 @@ EXPECT_EQ(1u, message_center()->GetVisibleNotifications().size()); // "id1" is displayed as a pop-up so that it will be closed when blocked. - message_center()->DisplayedNotification("id1", - message_center::DISPLAY_SOURCE_POPUP); + message_center()->DisplayedNotification("id1", DISPLAY_SOURCE_POPUP); // Create a notification during blocked. Still no popups. blocker.SetNotificationsEnabled(false); @@ -492,8 +489,7 @@ notifier_id2, RichNotificationData(), NULL))); // "id1" is displayed as a pop-up so that it will be closed when blocked. - message_center()->DisplayedNotification("id1", - message_center::DISPLAY_SOURCE_POPUP); + message_center()->DisplayedNotification("id1", DISPLAY_SOURCE_POPUP); // "id1" is closed but "id2" is still visible as a popup. blocker.SetNotificationsEnabled(false);
diff --git a/ui/message_center/notification_list_unittest.cc b/ui/message_center/notification_list_unittest.cc index 2e7fb3d..9953586 100644 --- a/ui/message_center/notification_list_unittest.cc +++ b/ui/message_center/notification_list_unittest.cc
@@ -39,8 +39,7 @@ // Currently NotificationListTest doesn't care about some fields like title or // message, so put a simple template on it. Returns the id of the new // notification. - std::string AddNotification( - const message_center::RichNotificationData& optional_fields) { + std::string AddNotification(const RichNotificationData& optional_fields) { std::string new_id; std::unique_ptr<Notification> notification( MakeNotification(optional_fields, &new_id)); @@ -50,16 +49,16 @@ } std::string AddNotification() { - return AddNotification(message_center::RichNotificationData()); + return AddNotification(RichNotificationData()); } // Construct a new notification for testing, but don't add it to the list yet. std::unique_ptr<Notification> MakeNotification( - const message_center::RichNotificationData& optional_fields, + const RichNotificationData& optional_fields, std::string* id_out) { *id_out = base::StringPrintf(kIdFormat, counter_); std::unique_ptr<Notification> notification(new Notification( - message_center::NOTIFICATION_TYPE_SIMPLE, *id_out, + NOTIFICATION_TYPE_SIMPLE, *id_out, UTF8ToUTF16(base::StringPrintf(kTitleFormat, counter_)), UTF8ToUTF16(base::StringPrintf(kMessageFormat, counter_)), gfx::Image(), UTF8ToUTF16(kDisplaySource), GURL(), @@ -69,12 +68,12 @@ } std::unique_ptr<Notification> MakeNotification(std::string* id_out) { - return MakeNotification(message_center::RichNotificationData(), id_out); + return MakeNotification(RichNotificationData(), id_out); } // Utility methods of AddNotification. std::string AddPriorityNotification(NotificationPriority priority) { - message_center::RichNotificationData optional; + RichNotificationData optional; optional.priority = priority; return AddNotification(optional); } @@ -169,12 +168,11 @@ std::string id0 = AddNotification(); std::string replaced = id0 + "_replaced"; EXPECT_EQ(1u, notification_list()->NotificationCount(blockers())); - std::unique_ptr<Notification> notification( - new Notification(message_center::NOTIFICATION_TYPE_SIMPLE, replaced, - UTF8ToUTF16("newtitle"), UTF8ToUTF16("newbody"), - gfx::Image(), UTF8ToUTF16(kDisplaySource), GURL(), - NotifierId(NotifierId::APPLICATION, kExtensionId), - message_center::RichNotificationData(), NULL)); + std::unique_ptr<Notification> notification(new Notification( + NOTIFICATION_TYPE_SIMPLE, replaced, UTF8ToUTF16("newtitle"), + UTF8ToUTF16("newbody"), gfx::Image(), UTF8ToUTF16(kDisplaySource), GURL(), + NotifierId(NotifierId::APPLICATION, kExtensionId), RichNotificationData(), + NULL)); notification_list()->UpdateNotificationMessage(id0, std::move(notification)); EXPECT_EQ(1u, notification_list()->NotificationCount(blockers())); const NotificationList::Notifications notifications = @@ -223,34 +221,34 @@ NotifierId id2(GURL("http://example.com")); NotifierId id3(NotifierId::SYSTEM_COMPONENT, "system-notifier"); std::unique_ptr<Notification> notification(new Notification( - message_center::NOTIFICATION_TYPE_SIMPLE, "id0", UTF8ToUTF16("title0"), + NOTIFICATION_TYPE_SIMPLE, "id0", UTF8ToUTF16("title0"), UTF8ToUTF16("message0"), gfx::Image(), UTF8ToUTF16("source0"), GURL(), - id0, message_center::RichNotificationData(), NULL)); + id0, RichNotificationData(), NULL)); notification_list()->AddNotification(std::move(notification)); notification.reset(new Notification( - message_center::NOTIFICATION_TYPE_SIMPLE, "id1", UTF8ToUTF16("title1"), + NOTIFICATION_TYPE_SIMPLE, "id1", UTF8ToUTF16("title1"), UTF8ToUTF16("message1"), gfx::Image(), UTF8ToUTF16("source0"), GURL(), - id0, message_center::RichNotificationData(), NULL)); + id0, RichNotificationData(), NULL)); notification_list()->AddNotification(std::move(notification)); notification.reset(new Notification( - message_center::NOTIFICATION_TYPE_SIMPLE, "id2", UTF8ToUTF16("title1"), + NOTIFICATION_TYPE_SIMPLE, "id2", UTF8ToUTF16("title1"), UTF8ToUTF16("message1"), gfx::Image(), UTF8ToUTF16("source1"), GURL(), - id0, message_center::RichNotificationData(), NULL)); + id0, RichNotificationData(), NULL)); notification_list()->AddNotification(std::move(notification)); notification.reset(new Notification( - message_center::NOTIFICATION_TYPE_SIMPLE, "id3", UTF8ToUTF16("title1"), + NOTIFICATION_TYPE_SIMPLE, "id3", UTF8ToUTF16("title1"), UTF8ToUTF16("message1"), gfx::Image(), UTF8ToUTF16("source2"), GURL(), - id1, message_center::RichNotificationData(), NULL)); + id1, RichNotificationData(), NULL)); notification_list()->AddNotification(std::move(notification)); notification.reset(new Notification( - message_center::NOTIFICATION_TYPE_SIMPLE, "id4", UTF8ToUTF16("title1"), + NOTIFICATION_TYPE_SIMPLE, "id4", UTF8ToUTF16("title1"), UTF8ToUTF16("message1"), gfx::Image(), UTF8ToUTF16("source2"), GURL(), - id2, message_center::RichNotificationData(), NULL)); + id2, RichNotificationData(), NULL)); notification_list()->AddNotification(std::move(notification)); notification.reset(new Notification( - message_center::NOTIFICATION_TYPE_SIMPLE, "id5", UTF8ToUTF16("title1"), + NOTIFICATION_TYPE_SIMPLE, "id5", UTF8ToUTF16("title1"), UTF8ToUTF16("message1"), gfx::Image(), UTF8ToUTF16("source2"), GURL(), - id3, message_center::RichNotificationData(), NULL)); + id3, RichNotificationData(), NULL)); notification_list()->AddNotification(std::move(notification)); NotificationList::Notifications by_notifier_id = @@ -390,12 +388,11 @@ std::string replaced = id0 + "_replaced"; EXPECT_EQ(1u, notification_list()->NotificationCount(blockers())); EXPECT_EQ(0u, GetPopupCounts()); - message_center::RichNotificationData optional; + RichNotificationData optional; optional.priority = 1; std::unique_ptr<Notification> notification(new Notification( - message_center::NOTIFICATION_TYPE_SIMPLE, replaced, - UTF8ToUTF16("newtitle"), UTF8ToUTF16("newbody"), gfx::Image(), - UTF8ToUTF16(kDisplaySource), GURL(), + NOTIFICATION_TYPE_SIMPLE, replaced, UTF8ToUTF16("newtitle"), + UTF8ToUTF16("newbody"), gfx::Image(), UTF8ToUTF16(kDisplaySource), GURL(), NotifierId(NotifierId::APPLICATION, kExtensionId), optional, NULL)); notification_list()->UpdateNotificationMessage(id0, std::move(notification)); EXPECT_EQ(1u, notification_list()->NotificationCount(blockers())); @@ -416,10 +413,10 @@ EXPECT_EQ(0u, GetPopupCounts()); // id0 promoted to LOW->DEFAULT, it'll appear as toast (popup). - message_center::RichNotificationData priority; + RichNotificationData priority; priority.priority = DEFAULT_PRIORITY; std::unique_ptr<Notification> notification(new Notification( - message_center::NOTIFICATION_TYPE_SIMPLE, id0, UTF8ToUTF16("newtitle"), + NOTIFICATION_TYPE_SIMPLE, id0, UTF8ToUTF16("newtitle"), UTF8ToUTF16("newbody"), gfx::Image(), UTF8ToUTF16(kDisplaySource), GURL(), NotifierId(NotifierId::APPLICATION, kExtensionId), priority, NULL)); notification_list()->UpdateNotificationMessage(id0, std::move(notification)); @@ -429,7 +426,7 @@ // update with no promotion change for id0, it won't appear as a toast. notification.reset(new Notification( - message_center::NOTIFICATION_TYPE_SIMPLE, id0, UTF8ToUTF16("newtitle2"), + NOTIFICATION_TYPE_SIMPLE, id0, UTF8ToUTF16("newtitle2"), UTF8ToUTF16("newbody2"), gfx::Image(), UTF8ToUTF16(kDisplaySource), GURL(), NotifierId(NotifierId::APPLICATION, kExtensionId), priority, NULL)); @@ -439,7 +436,7 @@ // id1 promoted to DEFAULT->HIGH, it'll appear as toast (popup). priority.priority = HIGH_PRIORITY; notification.reset(new Notification( - message_center::NOTIFICATION_TYPE_SIMPLE, id1, UTF8ToUTF16("newtitle"), + NOTIFICATION_TYPE_SIMPLE, id1, UTF8ToUTF16("newtitle"), UTF8ToUTF16("newbody"), gfx::Image(), UTF8ToUTF16(kDisplaySource), GURL(), NotifierId(NotifierId::APPLICATION, kExtensionId), priority, NULL)); notification_list()->UpdateNotificationMessage(id1, std::move(notification)); @@ -450,7 +447,7 @@ // id1 promoted to HIGH->MAX, it'll appear as toast again. priority.priority = MAX_PRIORITY; notification.reset(new Notification( - message_center::NOTIFICATION_TYPE_SIMPLE, id1, UTF8ToUTF16("newtitle2"), + NOTIFICATION_TYPE_SIMPLE, id1, UTF8ToUTF16("newtitle2"), UTF8ToUTF16("newbody2"), gfx::Image(), UTF8ToUTF16(kDisplaySource), GURL(), NotifierId(NotifierId::APPLICATION, kExtensionId), priority, NULL)); @@ -462,7 +459,7 @@ // id1 demoted to MAX->DEFAULT, no appearing as toast. priority.priority = DEFAULT_PRIORITY; notification.reset(new Notification( - message_center::NOTIFICATION_TYPE_SIMPLE, id1, UTF8ToUTF16("newtitle3"), + NOTIFICATION_TYPE_SIMPLE, id1, UTF8ToUTF16("newtitle3"), UTF8ToUTF16("newbody3"), gfx::Image(), UTF8ToUTF16(kDisplaySource), GURL(), NotifierId(NotifierId::APPLICATION, kExtensionId), priority, NULL)); @@ -473,11 +470,10 @@ TEST_F(NotificationListTest, WebNotificationUpdatePromotion) { std::string notification_id = "replaced-web-notification"; std::unique_ptr<Notification> original_notification(new Notification( - message_center::NOTIFICATION_TYPE_SIMPLE, notification_id, + NOTIFICATION_TYPE_SIMPLE, notification_id, UTF8ToUTF16("Web Notification"), UTF8ToUTF16("Notification contents"), gfx::Image(), UTF8ToUTF16(kDisplaySource), GURL(), - NotifierId(GURL("https://example.com/")), - message_center::RichNotificationData(), NULL)); + NotifierId(GURL("https://example.com/")), RichNotificationData(), NULL)); EXPECT_EQ(0u, GetPopupCounts()); notification_list()->AddNotification(std::move(original_notification)); @@ -487,12 +483,11 @@ EXPECT_EQ(0u, GetPopupCounts()); std::unique_ptr<Notification> replaced_notification(new Notification( - message_center::NOTIFICATION_TYPE_SIMPLE, notification_id, + NOTIFICATION_TYPE_SIMPLE, notification_id, UTF8ToUTF16("Web Notification Replacement"), UTF8ToUTF16("New notification contents"), gfx::Image(), UTF8ToUTF16(kDisplaySource), GURL(), - NotifierId(GURL("https://example.com/")), - message_center::RichNotificationData(), NULL)); + NotifierId(GURL("https://example.com/")), RichNotificationData(), NULL)); // Web Notifications will be re-shown as popups even if their priority didn't // change, to match the behavior of the Web Notification API. @@ -503,7 +498,7 @@ TEST_F(NotificationListTest, NotificationOrderAndPriority) { base::Time now = base::Time::Now(); - message_center::RichNotificationData optional; + RichNotificationData optional; optional.timestamp = now; optional.priority = 2; std::string max_id = AddNotification(optional); @@ -592,12 +587,11 @@ EXPECT_TRUE(n1->IsRead()); const std::string replaced("test-replaced-id"); - std::unique_ptr<Notification> notification( - new Notification(message_center::NOTIFICATION_TYPE_SIMPLE, replaced, - UTF8ToUTF16("newtitle"), UTF8ToUTF16("newbody"), - gfx::Image(), UTF8ToUTF16(kDisplaySource), GURL(), - NotifierId(NotifierId::APPLICATION, kExtensionId), - message_center::RichNotificationData(), NULL)); + std::unique_ptr<Notification> notification(new Notification( + NOTIFICATION_TYPE_SIMPLE, replaced, UTF8ToUTF16("newtitle"), + UTF8ToUTF16("newbody"), gfx::Image(), UTF8ToUTF16(kDisplaySource), GURL(), + NotifierId(NotifierId::APPLICATION, kExtensionId), RichNotificationData(), + NULL)); notification_list()->UpdateNotificationMessage(id1, std::move(notification)); n1 = GetNotification(id1); EXPECT_TRUE(n1 == NULL); @@ -638,21 +632,21 @@ TEST_F(NotificationListTest, TestHasNotificationOfType) { std::string id = AddNotification(); - EXPECT_TRUE(notification_list()->HasNotificationOfType( - id, message_center::NOTIFICATION_TYPE_SIMPLE)); + EXPECT_TRUE( + notification_list()->HasNotificationOfType(id, NOTIFICATION_TYPE_SIMPLE)); EXPECT_FALSE(notification_list()->HasNotificationOfType( - id, message_center::NOTIFICATION_TYPE_PROGRESS)); + id, NOTIFICATION_TYPE_PROGRESS)); - std::unique_ptr<Notification> updated_notification(new Notification( - message_center::NOTIFICATION_TYPE_PROGRESS, id, UTF8ToUTF16("updated"), - UTF8ToUTF16("updated"), gfx::Image(), base::string16(), GURL(), - NotifierId(), RichNotificationData(), NULL)); + std::unique_ptr<Notification> updated_notification( + new Notification(NOTIFICATION_TYPE_PROGRESS, id, UTF8ToUTF16("updated"), + UTF8ToUTF16("updated"), gfx::Image(), base::string16(), + GURL(), NotifierId(), RichNotificationData(), NULL)); notification_list()->AddNotification(std::move(updated_notification)); - EXPECT_FALSE(notification_list()->HasNotificationOfType( - id, message_center::NOTIFICATION_TYPE_SIMPLE)); + EXPECT_FALSE( + notification_list()->HasNotificationOfType(id, NOTIFICATION_TYPE_SIMPLE)); EXPECT_TRUE(notification_list()->HasNotificationOfType( - id, message_center::NOTIFICATION_TYPE_PROGRESS)); + id, NOTIFICATION_TYPE_PROGRESS)); } } // namespace message_center
diff --git a/ui/message_center/public/cpp/BUILD.gn b/ui/message_center/public/cpp/BUILD.gn index cbaa79f6..20d2a0b 100644 --- a/ui/message_center/public/cpp/BUILD.gn +++ b/ui/message_center/public/cpp/BUILD.gn
@@ -6,6 +6,8 @@ # C++ headers and sources that can be used outside message_center. jumbo_component("cpp") { + output_name = "ui_message_center_cpp" + sources = [ "message_center_constants.h", "message_center_public_export.h",
diff --git a/ui/message_center/public/cpp/notification.cc b/ui/message_center/public/cpp/notification.cc index c30ed3e7..da0ef47 100644 --- a/ui/message_center/public/cpp/notification.cc +++ b/ui/message_center/public/cpp/notification.cc
@@ -265,16 +265,16 @@ const gfx::VectorIcon& small_image, SystemNotificationWarningLevel color_type) { DCHECK_EQ(NotifierId::SYSTEM_COMPONENT, notifier_id.type); - SkColor color = message_center::kSystemNotificationColorNormal; + SkColor color = kSystemNotificationColorNormal; switch (color_type) { case SystemNotificationWarningLevel::NORMAL: - color = message_center::kSystemNotificationColorNormal; + color = kSystemNotificationColorNormal; break; case SystemNotificationWarningLevel::WARNING: - color = message_center::kSystemNotificationColorWarning; + color = kSystemNotificationColorWarning; break; case SystemNotificationWarningLevel::CRITICAL_WARNING: - color = message_center::kSystemNotificationColorCriticalWarning; + color = kSystemNotificationColorCriticalWarning; break; } std::unique_ptr<Notification> notification = std::make_unique<Notification>(
diff --git a/ui/message_center/public/cpp/notification_delegate.h b/ui/message_center/public/cpp/notification_delegate.h index e64e76d..0b700ee7 100644 --- a/ui/message_center/public/cpp/notification_delegate.h +++ b/ui/message_center/public/cpp/notification_delegate.h
@@ -71,7 +71,7 @@ explicit HandleNotificationClickDelegate( const base::RepeatingClosure& closure); - // message_center::NotificationDelegate overrides: + // NotificationDelegate overrides: void Click() override; void ButtonClick(int button_index) override;
diff --git a/ui/message_center/ui_controller.cc b/ui/message_center/ui_controller.cc index 3fd67d1..6743010 100644 --- a/ui/message_center/ui_controller.cc +++ b/ui/message_center/ui_controller.cc
@@ -42,7 +42,7 @@ message_center_visible_ = delegate_->ShowMessageCenter(show_by_click); if (message_center_visible_) { - message_center_->SetVisibility(message_center::VISIBILITY_MESSAGE_CENTER); + message_center_->SetVisibility(VISIBILITY_MESSAGE_CENTER); NotifyUiControllerChanged(); } return message_center_visible_; @@ -66,7 +66,7 @@ if (!message_center_visible_) return; message_center_visible_ = false; - message_center_->SetVisibility(message_center::VISIBILITY_TRANSIENT); + message_center_->SetVisibility(VISIBILITY_TRANSIENT); // Some notifications (like system ones) should appear as popups again // after the message center is closed. @@ -117,7 +117,7 @@ HidePopupBubbleInternal(); message_center_visible_ = delegate_->ShowNotifierSettings(); - message_center_->SetVisibility(message_center::VISIBILITY_SETTINGS); + message_center_->SetVisibility(VISIBILITY_SETTINGS); NotifyUiControllerChanged(); }
diff --git a/ui/message_center/ui_controller.h b/ui/message_center/ui_controller.h index a281fd2..c777344b 100644 --- a/ui/message_center/ui_controller.h +++ b/ui/message_center/ui_controller.h
@@ -53,10 +53,8 @@ bool message_center_visible() { return message_center_visible_; } bool popups_visible() { return popups_visible_; } UiDelegate* delegate() { return delegate_; } - const message_center::MessageCenter* message_center() const { - return message_center_; - } - message_center::MessageCenter* message_center() { return message_center_; } + const MessageCenter* message_center() const { return message_center_; } + MessageCenter* message_center() { return message_center_; } // Overridden from MessageCenterObserver: void OnNotificationAdded(const std::string& notification_id) override; @@ -77,7 +75,7 @@ void NotifyUiControllerChanged(); void HidePopupBubbleInternal(); - message_center::MessageCenter* message_center_; + MessageCenter* message_center_; bool message_center_visible_ = false; bool popups_visible_ = false; UiDelegate* delegate_;
diff --git a/ui/message_center/ui_controller_unittest.cc b/ui/message_center/ui_controller_unittest.cc index 1112f8d..a7163fe6 100644 --- a/ui/message_center/ui_controller_unittest.cc +++ b/ui/message_center/ui_controller_unittest.cc
@@ -19,7 +19,7 @@ namespace message_center { namespace { -class TestNotificationDelegate : public message_center::NotificationDelegate { +class TestNotificationDelegate : public NotificationDelegate { public: TestNotificationDelegate() = default; @@ -78,13 +78,11 @@ } Notification* AddNotification(const std::string& id, NotifierId notifier_id) { - std::unique_ptr<Notification> notification( - new Notification(message_center::NOTIFICATION_TYPE_SIMPLE, id, - ASCIIToUTF16("Test Web Notification"), - ASCIIToUTF16("Notification message body."), - gfx::Image(), ASCIIToUTF16("www.test.org"), GURL(), - notifier_id, message_center::RichNotificationData(), - new TestNotificationDelegate())); + std::unique_ptr<Notification> notification(new Notification( + NOTIFICATION_TYPE_SIMPLE, id, ASCIIToUTF16("Test Web Notification"), + ASCIIToUTF16("Notification message body."), gfx::Image(), + ASCIIToUTF16("www.test.org"), GURL(), notifier_id, + RichNotificationData(), new TestNotificationDelegate())); Notification* notification_ptr = notification.get(); message_center_->AddNotification(std::move(notification)); return notification_ptr; @@ -185,12 +183,11 @@ ASSERT_FALSE(ui_controller_->message_center_visible()); std::unique_ptr<Notification> notification(new Notification( - message_center::NOTIFICATION_TYPE_SIMPLE, - "MessageCenterReopnPopupsForSystemPriority", + NOTIFICATION_TYPE_SIMPLE, "MessageCenterReopnPopupsForSystemPriority", ASCIIToUTF16("Test Web Notification"), ASCIIToUTF16("Notification message body."), gfx::Image(), ASCIIToUTF16("www.test.org"), GURL(), DummyNotifierId(), - message_center::RichNotificationData(), NULL /* delegate */)); + RichNotificationData(), NULL /* delegate */)); notification->SetSystemPriority(); message_center_->AddNotification(std::move(notification));
diff --git a/ui/message_center/views/constants.h b/ui/message_center/views/constants.h index 5ef550d..7fed808 100644 --- a/ui/message_center/views/constants.h +++ b/ui/message_center/views/constants.h
@@ -31,11 +31,9 @@ // Character limit = pixels per line * line limit / min. pixels per character. const int kMinPixelsPerTitleCharacter = 4; const size_t kMessageCharacterLimit = - message_center::kNotificationWidth * - message_center::kMessageExpandedLineLimit / 3; + kNotificationWidth * kMessageExpandedLineLimit / 3; const size_t kContextMessageCharacterLimit = - message_center::kNotificationWidth * - message_center::kContextMessageLineLimit / 3; + kNotificationWidth * kContextMessageLineLimit / 3; } // namespace message_center
diff --git a/ui/message_center/views/message_popup_collection.cc b/ui/message_center/views/message_popup_collection.cc index bfad9985..629b1eb 100644 --- a/ui/message_center/views/message_popup_collection.cc +++ b/ui/message_center/views/message_popup_collection.cc
@@ -222,8 +222,8 @@ toast, ax::mojom::Event::kAlert); } - message_center_->DisplayedNotification( - notification.id(), message_center::DISPLAY_SOURCE_POPUP); + message_center_->DisplayedNotification(notification.id(), + DISPLAY_SOURCE_POPUP); } }
diff --git a/ui/message_center/views/message_popup_collection_unittest.cc b/ui/message_center/views/message_popup_collection_unittest.cc index dad8c8b..eec5c73 100644 --- a/ui/message_center/views/message_popup_collection_unittest.cc +++ b/ui/message_center/views/message_popup_collection_unittest.cc
@@ -33,23 +33,22 @@ #include "ui/views/widget/widget.h" #include "ui/views/widget/widget_delegate.h" +namespace message_center { + namespace { -std::unique_ptr<message_center::Notification> CreateTestNotification( - std::string id, - std::string text) { - return std::make_unique<message_center::Notification>( - message_center::NOTIFICATION_TYPE_BASE_FORMAT, id, - base::UTF8ToUTF16("test title"), base::ASCIIToUTF16(text), gfx::Image(), +std::unique_ptr<Notification> CreateTestNotification(std::string id, + std::string text) { + return std::make_unique<Notification>( + NOTIFICATION_TYPE_BASE_FORMAT, id, base::UTF8ToUTF16("test title"), + base::ASCIIToUTF16(text), gfx::Image(), base::string16() /* display_source */, GURL(), - message_center::NotifierId(message_center::NotifierId::APPLICATION, id), - message_center::RichNotificationData(), - new message_center::NotificationDelegate()); + NotifierId(NotifierId::APPLICATION, id), RichNotificationData(), + new NotificationDelegate()); } // Provides an aura window context for widget creation. -class TestPopupAlignmentDelegate - : public message_center::DesktopPopupAlignmentDelegate { +class TestPopupAlignmentDelegate : public DesktopPopupAlignmentDelegate { public: explicit TestPopupAlignmentDelegate(gfx::NativeWindow context) : context_(context) {} @@ -70,7 +69,6 @@ } // namespace -namespace message_center { namespace test { class MessagePopupCollectionTest : public views::ViewsTestBase { @@ -146,7 +144,7 @@ NOTIFICATION_TYPE_BASE_FORMAT, id, base::UTF8ToUTF16("test title"), base::UTF8ToUTF16("test message"), gfx::Image(), base::string16() /* display_source */, GURL(), NotifierId(), - message_center::RichNotificationData(), new NotificationDelegate())); + RichNotificationData(), new NotificationDelegate())); MessageCenter::Get()->AddNotification(std::move(notification)); return id; } @@ -667,7 +665,7 @@ base::UTF8ToUTF16("test title"), base::UTF8ToUTF16("test message"), gfx::Image(), base::string16() /* display_source */, GURL(), NotifierId(NotifierId::APPLICATION, kNotificationId), - message_center::RichNotificationData(), new NotificationDelegate())); + RichNotificationData(), new NotificationDelegate())); notification->set_pinned(true); // Add a pinned notification.
diff --git a/ui/message_center/views/message_view.cc b/ui/message_center/views/message_view.cc index 0981083..7ea0fd0 100644 --- a/ui/message_center/views/message_view.cc +++ b/ui/message_center/views/message_view.cc
@@ -26,6 +26,8 @@ #include "ui/views/painter.h" #include "ui/views/widget/widget.h" +namespace message_center { + namespace { const SkColor kBorderColor = SkColorSetARGB(0x1F, 0x0, 0x0, 0x0); @@ -37,8 +39,7 @@ // Creates a text for spoken feedback from the data contained in the // notification. -base::string16 CreateAccessibleName( - const message_center::Notification& notification) { +base::string16 CreateAccessibleName(const Notification& notification) { if (!notification.accessible_name().empty()) return notification.accessible_name(); @@ -46,10 +47,8 @@ std::vector<base::string16> accessible_lines = { notification.title(), notification.message(), notification.context_message()}; - std::vector<message_center::NotificationItem> items = notification.items(); - for (size_t i = 0; - i < items.size() && i < message_center::kNotificationMaximumItems; - ++i) { + std::vector<NotificationItem> items = notification.items(); + for (size_t i = 0; i < items.size() && i < kNotificationMaximumItems; ++i) { accessible_lines.push_back(items[i].title + base::ASCIIToUTF16(" ") + items[i].message); } @@ -60,14 +59,12 @@ #if defined(OS_CHROMEOS) return true; #else - return message_center::IsNewStyleNotificationEnabled(); + return IsNewStyleNotificationEnabled(); #endif } } // namespace -namespace message_center { - // static const char MessageView::kViewClassName[] = "MessageView";
diff --git a/ui/message_center/views/message_view_factory.h b/ui/message_center/views/message_view_factory.h index acb39f0..883257e 100644 --- a/ui/message_center/views/message_view_factory.h +++ b/ui/message_center/views/message_view_factory.h
@@ -24,8 +24,7 @@ public: // A function that creates MessageView for a NOTIFICATION_TYPE_CUSTOM // notification. - typedef base::Callback<std::unique_ptr<message_center::MessageView>( - const message_center::Notification&)> + typedef base::Callback<std::unique_ptr<MessageView>(const Notification&)> CustomMessageViewFactoryFunction; static MessageView* Create(const Notification& notification, bool top_level);
diff --git a/ui/message_center/views/notification_button.cc b/ui/message_center/views/notification_button.cc index f4110cc..86759f5d 100644 --- a/ui/message_center/views/notification_button.cc +++ b/ui/message_center/views/notification_button.cc
@@ -26,11 +26,10 @@ set_notify_enter_exit_on_child(true); SetLayoutManager(std::make_unique<views::BoxLayout>( views::BoxLayout::kHorizontal, - gfx::Insets(kButtonVerticalPadding, - message_center::kButtonHorizontalPadding), - message_center::kButtonIconToTitlePadding)); + gfx::Insets(kButtonVerticalPadding, kButtonHorizontalPadding), + kButtonIconToTitlePadding)); SetFocusPainter(views::Painter::CreateSolidFocusPainter( - message_center::kFocusBorderColor, gfx::Insets(1, 2, 2, 2))); + kFocusBorderColor, gfx::Insets(1, 2, 2, 2))); } NotificationButton::~NotificationButton() { @@ -43,13 +42,12 @@ icon_ = NULL; } else { icon_ = new views::ImageView(); - icon_->SetImageSize(gfx::Size(message_center::kNotificationButtonIconSize, - message_center::kNotificationButtonIconSize)); + icon_->SetImageSize( + gfx::Size(kNotificationButtonIconSize, kNotificationButtonIconSize)); icon_->SetImage(image); icon_->SetHorizontalAlignment(views::ImageView::LEADING); icon_->SetVerticalAlignment(views::ImageView::LEADING); - icon_->SetBorder(views::CreateEmptyBorder( - message_center::kButtonIconTopPadding, 0, 0, 0)); + icon_->SetBorder(views::CreateEmptyBorder(kButtonIconTopPadding, 0, 0, 0)); AddChildViewAt(icon_, 0); } } @@ -62,7 +60,7 @@ } else { title_ = new views::Label(title); title_->SetHorizontalAlignment(gfx::ALIGN_LEFT); - title_->SetEnabledColor(message_center::kRegularTextColor); + title_->SetEnabledColor(kRegularTextColor); title_->SetBackgroundColor(kRegularTextBackgroundColor); title_->SetBorder( views::CreateEmptyBorder(kButtonTitleTopPadding, 0, 0, 0)); @@ -72,12 +70,11 @@ } gfx::Size NotificationButton::CalculatePreferredSize() const { - return gfx::Size(message_center::kNotificationWidth, - message_center::kButtonHeight); + return gfx::Size(kNotificationWidth, kButtonHeight); } int NotificationButton::GetHeightForWidth(int width) const { - return message_center::kButtonHeight; + return kButtonHeight; } void NotificationButton::OnFocus() { @@ -95,8 +92,7 @@ void NotificationButton::StateChanged(ButtonState old_state) { if (state() == STATE_HOVERED || state() == STATE_PRESSED) { - SetBackground(views::CreateSolidBackground( - message_center::kHoveredButtonBackgroundColor)); + SetBackground(views::CreateSolidBackground(kHoveredButtonBackgroundColor)); } else { SetBackground(views::CreateSolidBackground(kNotificationBackgroundColor)); }
diff --git a/ui/message_center/views/notification_control_buttons_view.cc b/ui/message_center/views/notification_control_buttons_view.cc index b4fb713..a850ddb 100644 --- a/ui/message_center/views/notification_control_buttons_view.cc +++ b/ui/message_center/views/notification_control_buttons_view.cc
@@ -20,6 +20,8 @@ #include "ui/views/background.h" #include "ui/views/layout/box_layout.h" +namespace message_center { + namespace { // This value should be the same as the duration of reveal animation of @@ -28,13 +30,10 @@ base::TimeDelta::FromMilliseconds(360); // The initial background color of the view. -constexpr SkColor kInitialBackgroundColor = - message_center::kControlButtonBackgroundColor; +constexpr SkColor kInitialBackgroundColor = kControlButtonBackgroundColor; } // anonymous namespace -namespace message_center { - const char NotificationControlButtonsView::kViewClassName[] = "NotificationControlButtonsView"; @@ -58,7 +57,7 @@ void NotificationControlButtonsView::ShowCloseButton(bool show) { if (show && !close_button_) { - close_button_ = std::make_unique<message_center::PaddedButton>(this); + close_button_ = std::make_unique<PaddedButton>(this); close_button_->set_owned_by_client(); close_button_->SetImage(views::Button::STATE_NORMAL, gfx::CreateVectorIcon(kNotificationCloseButtonIcon, @@ -81,7 +80,7 @@ void NotificationControlButtonsView::ShowSettingsButton(bool show) { if (show && !settings_button_) { - settings_button_ = std::make_unique<message_center::PaddedButton>(this); + settings_button_ = std::make_unique<PaddedButton>(this); settings_button_->set_owned_by_client(); settings_button_->SetImage( views::Button::STATE_NORMAL,
diff --git a/ui/message_center/views/notification_control_buttons_view.h b/ui/message_center/views/notification_control_buttons_view.h index 31441a9..176221e 100644 --- a/ui/message_center/views/notification_control_buttons_view.h +++ b/ui/message_center/views/notification_control_buttons_view.h
@@ -77,8 +77,8 @@ private: MessageView* message_view_; - std::unique_ptr<message_center::PaddedButton> close_button_; - std::unique_ptr<message_center::PaddedButton> settings_button_; + std::unique_ptr<PaddedButton> close_button_; + std::unique_ptr<PaddedButton> settings_button_; std::unique_ptr<gfx::LinearAnimation> bgcolor_animation_; SkColor bgcolor_origin_;
diff --git a/ui/message_center/views/notification_header_view.h b/ui/message_center/views/notification_header_view.h index 7a316d38..1b775b6 100644 --- a/ui/message_center/views/notification_header_view.h +++ b/ui/message_center/views/notification_header_view.h
@@ -52,7 +52,7 @@ // Update visibility for both |summary_text_view_| and |timestamp_view_|. void UpdateSummaryTextVisibility(); - SkColor accent_color_ = message_center::kNotificationDefaultAccentColor; + SkColor accent_color_ = kNotificationDefaultAccentColor; views::Label* app_name_view_ = nullptr; views::Label* summary_text_divider_ = nullptr;
diff --git a/ui/message_center/views/notification_menu_model_unittest.cc b/ui/message_center/views/notification_menu_model_unittest.cc index 71cd701..ab0ca492 100644 --- a/ui/message_center/views/notification_menu_model_unittest.cc +++ b/ui/message_center/views/notification_menu_model_unittest.cc
@@ -18,7 +18,7 @@ namespace message_center { namespace { -class TestNotificationDelegate : public message_center::NotificationDelegate { +class TestNotificationDelegate : public NotificationDelegate { public: TestNotificationDelegate() = default; @@ -54,12 +54,11 @@ Notification* AddNotification(const std::string& id, NotifierId notifier_id) { std::unique_ptr<Notification> notification(new Notification( - message_center::NOTIFICATION_TYPE_SIMPLE, id, + NOTIFICATION_TYPE_SIMPLE, id, base::ASCIIToUTF16("Test Web Notification"), base::ASCIIToUTF16("Notification message body."), gfx::Image(), base::ASCIIToUTF16("www.test.org"), GURL(), notifier_id, - message_center::RichNotificationData(), - new TestNotificationDelegate())); + RichNotificationData(), new TestNotificationDelegate())); Notification* notification_ptr = notification.get(); message_center_->AddNotification(std::move(notification)); return notification_ptr; @@ -81,11 +80,11 @@ NotifierId notifier_id2(NotifierId::APPLICATION, "sample-app"); std::unique_ptr<Notification> notification = std::make_unique<Notification>( - message_center::NOTIFICATION_TYPE_SIMPLE, id2, + NOTIFICATION_TYPE_SIMPLE, id2, base::ASCIIToUTF16("Test Web Notification"), base::ASCIIToUTF16("Notification message body."), gfx::Image(), - display_source, GURL(), notifier_id2, - message_center::RichNotificationData(), new TestNotificationDelegate()); + display_source, GURL(), notifier_id2, RichNotificationData(), + new TestNotificationDelegate()); std::unique_ptr<ui::MenuModel> model( std::make_unique<NotificationMenuModel>(*notification));
diff --git a/ui/message_center/views/notification_view.h b/ui/message_center/views/notification_view.h index c1da6928..f1f0e2fb 100644 --- a/ui/message_center/views/notification_view.h +++ b/ui/message_center/views/notification_view.h
@@ -85,7 +85,7 @@ void CreateOrUpdateSmallIconView(const Notification& notification); void CreateOrUpdateImageView(const Notification& notification); void CreateOrUpdateActionButtonViews(const Notification& notification); - // TODO(yoshiki): Move this to message_center::MessageView + // TODO(yoshiki): Move this to MessageView void UpdateControlButtonsVisibilityWithNotification( const Notification& notification);
diff --git a/ui/message_center/views/notification_view_md.cc b/ui/message_center/views/notification_view_md.cc index dda12341..f715b38 100644 --- a/ui/message_center/views/notification_view_md.cc +++ b/ui/message_center/views/notification_view_md.cc
@@ -111,12 +111,12 @@ constexpr int kProgressBarHeight = 4; constexpr int kMessageViewWidthWithIcon = - message_center::kNotificationWidth - kIconViewSize.width() - + kNotificationWidth - kIconViewSize.width() - kLeftContentPaddingWithIcon.left() - kLeftContentPaddingWithIcon.right() - kContentRowPadding.left() - kContentRowPadding.right(); constexpr int kMessageViewWidth = - message_center::kNotificationWidth - kLeftContentPadding.left() - + kNotificationWidth - kLeftContentPadding.left() - kLeftContentPadding.right() - kContentRowPadding.left() - kContentRowPadding.right(); @@ -162,7 +162,7 @@ // ItemView //////////////////////////////////////////////////////////////////// -ItemView::ItemView(const message_center::NotificationItem& item) { +ItemView::ItemView(const NotificationItem& item) { SetLayoutManager(std::make_unique<views::BoxLayout>( views::BoxLayout::kHorizontal, gfx::Insets(), 0)); @@ -172,8 +172,8 @@ title->SetFontList(font_list); title->set_collapse_when_hidden(true); title->SetHorizontalAlignment(gfx::ALIGN_LEFT); - title->SetEnabledColor(message_center::kRegularTextColorMD); - title->SetBackgroundColor(message_center::kDimTextBackgroundColor); + title->SetEnabledColor(kRegularTextColorMD); + title->SetBackgroundColor(kDimTextBackgroundColor); AddChildView(title); views::Label* message = new views::Label(l10n_util::GetStringFUTF16( @@ -182,7 +182,7 @@ message->set_collapse_when_hidden(true); message->SetHorizontalAlignment(gfx::ALIGN_LEFT); message->SetEnabledColor(kDimTextColorMD); - message->SetBackgroundColor(message_center::kDimTextBackgroundColor); + message->SetBackgroundColor(kDimTextBackgroundColor); AddChildView(message); } @@ -313,8 +313,7 @@ : image_view_(new LargeImageView()) { SetLayoutManager(std::make_unique<views::FillLayout>()); SetBorder(views::CreateEmptyBorder(kLargeImageContainerPadding)); - SetBackground( - views::CreateSolidBackground(message_center::kImageBackgroundColor)); + SetBackground(views::CreateSolidBackground(kImageBackgroundColor)); AddChildView(image_view_); } @@ -371,9 +370,9 @@ // NotificationInputTextfieldMD //////////////////////////////////////////////// NotificationInputTextfieldMD::NotificationInputTextfieldMD( - NotificationInputDelegate* delegate) - : delegate_(delegate), index_(0) { - set_controller(this); + views::TextfieldController* controller) + : index_(0) { + set_controller(controller); SetTextColor(kInputTextColor); SetBackgroundColor(SK_ColorTRANSPARENT); set_placeholder_text_color(kInputPlaceholderColor); @@ -382,41 +381,6 @@ NotificationInputTextfieldMD::~NotificationInputTextfieldMD() = default; -void NotificationInputTextfieldMD::CheckUpdateImage() { - if (is_empty_ && !text().empty()) { - is_empty_ = false; - delegate_->SetNormalImageToReplyButton(); - } else if (!is_empty_ && text().empty()) { - is_empty_ = true; - delegate_->SetPlaceholderImageToReplyButton(); - } -} - -bool NotificationInputTextfieldMD::HandleKeyEvent(views::Textfield* sender, - const ui::KeyEvent& event) { - CheckUpdateImage(); - if (event.type() == ui::ET_KEY_PRESSED && - event.key_code() == ui::VKEY_RETURN) { - delegate_->OnNotificationInputSubmit(index_, text()); - return true; - } - return event.type() == ui::ET_KEY_RELEASED; -} - -bool NotificationInputTextfieldMD::HandleMouseEvent( - views::Textfield* sender, - const ui::MouseEvent& event) { - CheckUpdateImage(); - return event.type() == ui::ET_MOUSE_RELEASED; -} - -bool NotificationInputTextfieldMD::HandleGestureEvent( - views::Textfield* sender, - const ui::GestureEvent& event) { - CheckUpdateImage(); - return false; -} - void NotificationInputTextfieldMD::set_placeholder( const base::string16& placeholder) { if (placeholder.empty()) { @@ -458,7 +422,7 @@ NotificationInputDelegate* delegate) : delegate_(delegate), ink_drop_container_(new views::InkDropContainerView()), - textfield_(new NotificationInputTextfieldMD(delegate)), + textfield_(new NotificationInputTextfieldMD(this)), button_(new NotificationInputReplyButtonMD(this)) { auto* layout = SetLayoutManager(std::make_unique<views::BoxLayout>( views::BoxLayout::kHorizontal, gfx::Insets(), 0)); @@ -514,6 +478,25 @@ return kInputContainerBackgroundColor; } +bool NotificationInputContainerMD::HandleKeyEvent(views::Textfield* sender, + const ui::KeyEvent& event) { + if (event.type() == ui::ET_KEY_PRESSED && + event.key_code() == ui::VKEY_RETURN) { + delegate_->OnNotificationInputSubmit(textfield_->index(), + textfield_->text()); + return true; + } + return event.type() == ui::ET_KEY_RELEASED; +} + +void NotificationInputContainerMD::OnAfterUserAction(views::Textfield* sender) { + if (textfield_->text().empty()) { + button_->SetPlaceholderImage(); + } else { + button_->SetNormalImage(); + } +} + void NotificationInputContainerMD::ButtonPressed(views::Button* sender, const ui::Event& event) { if (sender == button_) { @@ -824,14 +807,6 @@ } } -void NotificationViewMD::SetNormalImageToReplyButton() { - inline_reply_->button()->SetNormalImage(); -} - -void NotificationViewMD::SetPlaceholderImageToReplyButton() { - inline_reply_->button()->SetPlaceholderImage(); -} - void NotificationViewMD::OnNotificationInputSubmit(size_t index, const base::string16& text) { MessageCenter::Get()->ClickOnNotificationButtonWithReply(notification_id(), @@ -848,10 +823,9 @@ void NotificationViewMD::CreateOrUpdateContextTitleView( const Notification& notification) { - header_row_->SetAccentColor( - notification.accent_color() == SK_ColorTRANSPARENT - ? message_center::kNotificationDefaultAccentColor - : notification.accent_color()); + header_row_->SetAccentColor(notification.accent_color() == SK_ColorTRANSPARENT + ? kNotificationDefaultAccentColor + : notification.accent_color()); header_row_->SetTimestamp(notification.timestamp()); base::string16 app_name = notification.display_source(); @@ -957,8 +931,8 @@ if (!progress_bar_view_) { progress_bar_view_ = new views::ProgressBar(kProgressBarHeight, /* allow_round_corner */ false); - progress_bar_view_->SetBorder(views::CreateEmptyBorder( - message_center::kProgressBarTopPadding, 0, 0, 0)); + progress_bar_view_->SetBorder( + views::CreateEmptyBorder(kProgressBarTopPadding, 0, 0, 0)); left_content_->AddChildView(progress_bar_view_); } @@ -1020,8 +994,13 @@ void NotificationViewMD::CreateOrUpdateIconView( const Notification& notification) { + const bool use_image_for_icon = notification.icon().IsEmpty(); + + gfx::ImageSkia icon = use_image_for_icon ? notification.image().AsImageSkia() + : notification.icon().AsImageSkia(); + if (notification.type() == NOTIFICATION_TYPE_PROGRESS || - notification.type() == NOTIFICATION_TYPE_MULTIPLE) { + notification.type() == NOTIFICATION_TYPE_MULTIPLE || icon.isNull()) { DCHECK(!icon_view_ || right_content_->Contains(icon_view_)); delete icon_view_; icon_view_ = nullptr; @@ -1033,12 +1012,6 @@ right_content_->AddChildView(icon_view_); } - const bool use_image_for_icon = notification.icon().IsEmpty(); - gfx::ImageSkia icon; - if (use_image_for_icon) - icon = notification.image().AsImageSkia(); - else - icon = notification.icon().AsImageSkia(); icon_view_->SetImage(icon, icon.size()); // Hide the icon on the right side when the notification is expanded. @@ -1089,8 +1062,7 @@ for (size_t i = 0; i < buttons.size(); ++i) { ButtonInfo button_info = buttons[i]; if (new_buttons) { - bool is_inline_reply = - button_info.type == message_center::ButtonType::TEXT; + bool is_inline_reply = button_info.type == ButtonType::TEXT; NotificationButtonMD* button = new NotificationButtonMD( this, is_inline_reply, button_info.title, button_info.placeholder); action_buttons_.push_back(button); @@ -1223,10 +1195,9 @@ list_items_count_ - (expanded ? item_views_.size() : kMaxLinesForMessageView)); - if (icon_view_) - icon_view_->SetVisible(!hide_icon_on_expanded_ || !expanded); - - if (icon_view_ && icon_view_->visible()) { + right_content_->SetVisible(icon_view_ && + (!hide_icon_on_expanded_ || !expanded)); + if (right_content_->visible()) { left_content_->SetBorder( views::CreateEmptyBorder(kLeftContentPaddingWithIcon));
diff --git a/ui/message_center/views/notification_view_md.h b/ui/message_center/views/notification_view_md.h index 6a89940..331cc05 100644 --- a/ui/message_center/views/notification_view_md.h +++ b/ui/message_center/views/notification_view_md.h
@@ -36,7 +36,7 @@ // message next to each other within a single column. class ItemView : public views::View { public: - explicit ItemView(const message_center::NotificationItem& item); + explicit ItemView(const NotificationItem& item); ~ItemView() override; const char* GetClassName() const override; @@ -139,37 +139,22 @@ class NotificationInputDelegate { public: - virtual void SetNormalImageToReplyButton() = 0; - virtual void SetPlaceholderImageToReplyButton() = 0; virtual void OnNotificationInputSubmit(size_t index, const base::string16& text) = 0; virtual ~NotificationInputDelegate() = default; }; -class NotificationInputTextfieldMD : public views::Textfield, - public views::TextfieldController { +class NotificationInputTextfieldMD : public views::Textfield { public: - NotificationInputTextfieldMD(NotificationInputDelegate* delegate); + NotificationInputTextfieldMD(views::TextfieldController* controller); ~NotificationInputTextfieldMD() override; - void CheckUpdateImage(); - bool HandleKeyEvent(views::Textfield* sender, - const ui::KeyEvent& key_event) override; - bool HandleMouseEvent(views::Textfield* sender, - const ui::MouseEvent& mouse_event) override; - bool HandleGestureEvent(views::Textfield* sender, - const ui::GestureEvent& gesture_event) override; - void set_index(size_t index) { index_ = index; } void set_placeholder(const base::string16& placeholder); size_t index() const { return index_; }; private: - NotificationInputDelegate* const delegate_; - - bool is_empty_ = true; - // |index_| is the notification action index that should be passed as the // argument of ClickOnNotificationButtonWithReply. size_t index_ = 0; @@ -190,7 +175,8 @@ }; class NotificationInputContainerMD : public views::InkDropHostView, - public views::ButtonListener { + public views::ButtonListener, + public views::TextfieldController { public: NotificationInputContainerMD(NotificationInputDelegate* delegate); ~NotificationInputContainerMD() override; @@ -203,6 +189,11 @@ std::unique_ptr<views::InkDropRipple> CreateInkDropRipple() const override; SkColor GetInkDropBaseColor() const override; + // Overridden from views::TextfieldController: + bool HandleKeyEvent(views::Textfield* sender, + const ui::KeyEvent& key_event) override; + void OnAfterUserAction(views::Textfield* sender) override; + // Overridden from views::ButtonListener: void ButtonPressed(views::Button* sender, const ui::Event& event) override; @@ -256,8 +247,6 @@ void OnSettingsButtonPressed() override; // Overridden from NotificationInputDelegate: - void SetNormalImageToReplyButton() override; - void SetPlaceholderImageToReplyButton() override; void OnNotificationInputSubmit(size_t index, const base::string16& text) override; @@ -274,6 +263,7 @@ FRIEND_TEST_ALL_PREFIXES(NotificationViewMDTest, ExpandLongMessage); FRIEND_TEST_ALL_PREFIXES(NotificationViewMDTest, TestAccentColor); FRIEND_TEST_ALL_PREFIXES(NotificationViewMDTest, UseImageAsIcon); + FRIEND_TEST_ALL_PREFIXES(NotificationViewMDTest, NotificationWithoutIcon); FRIEND_TEST_ALL_PREFIXES(NotificationViewMDTest, InlineSettings); friend class NotificationViewMDTest;
diff --git a/ui/message_center/views/notification_view_md_unittest.cc b/ui/message_center/views/notification_view_md_unittest.cc index 6c69cd16..3786067 100644 --- a/ui/message_center/views/notification_view_md_unittest.cc +++ b/ui/message_center/views/notification_view_md_unittest.cc
@@ -313,8 +313,7 @@ EXPECT_EQ(nullptr, notification_view()->title_view_); EXPECT_EQ(nullptr, notification_view()->message_view_); EXPECT_EQ(nullptr, notification_view()->image_container_view_); - // We still expect an icon view for all layouts. - EXPECT_NE(nullptr, notification_view()->icon_view_); + EXPECT_EQ(nullptr, notification_view()->icon_view_); } TEST_F(NotificationViewMDTest, TestIconSizing) { @@ -709,7 +708,7 @@ // By default, header does not have accent color (default grey), and // buttons have default accent color. - EXPECT_EQ(message_center::kNotificationDefaultAccentColor, + EXPECT_EQ(kNotificationDefaultAccentColor, notification_view()->header_row_->accent_color_for_testing()); EXPECT_EQ( kActionButtonTextColor, @@ -744,24 +743,43 @@ UpdateNotificationViews(); EXPECT_FALSE(notification_view()->expanded_); EXPECT_TRUE(notification_view()->icon_view_->visible()); + EXPECT_TRUE(notification_view()->right_content_->visible()); // Icon on the right side is still visible when expanded. notification_view()->ToggleExpanded(); EXPECT_TRUE(notification_view()->expanded_); EXPECT_TRUE(notification_view()->icon_view_->visible()); + EXPECT_TRUE(notification_view()->right_content_->visible()); notification_view()->ToggleExpanded(); EXPECT_FALSE(notification_view()->expanded_); - // Test notification with use_image_as_icon e.g. screenshot preview. + // Test notification with |use_image_for_icon| e.g. screenshot preview. notification()->set_icon(gfx::Image()); UpdateNotificationViews(); EXPECT_TRUE(notification_view()->icon_view_->visible()); + EXPECT_TRUE(notification_view()->right_content_->visible()); // Icon on the right side is not visible when expanded. notification_view()->ToggleExpanded(); EXPECT_TRUE(notification_view()->expanded_); - EXPECT_FALSE(notification_view()->icon_view_->visible()); + EXPECT_TRUE(notification_view()->icon_view_->visible()); + EXPECT_FALSE(notification_view()->right_content_->visible()); +} + +TEST_F(NotificationViewMDTest, NotificationWithoutIcon) { + notification()->set_icon(gfx::Image()); + notification()->set_image(gfx::Image()); + UpdateNotificationViews(); + + // If the notification has no icon, |icon_view_| shouldn't be created. + EXPECT_FALSE(notification_view()->icon_view_); + EXPECT_FALSE(notification_view()->right_content_->visible()); + + // Toggling should not affect the icon. + notification_view()->ToggleExpanded(); + EXPECT_FALSE(notification_view()->icon_view_); + EXPECT_FALSE(notification_view()->right_content_->visible()); } TEST_F(NotificationViewMDTest, InlineSettings) {
diff --git a/ui/message_center/views/notification_view_unittest.cc b/ui/message_center/views/notification_view_unittest.cc index 39bc379..aba5451 100644 --- a/ui/message_center/views/notification_view_unittest.cc +++ b/ui/message_center/views/notification_view_unittest.cc
@@ -562,10 +562,10 @@ "veryveryveryveryveyryveryveryveryveryveyryveryvery.veryveryveyrylong." "chromium.org/hello"; - Notification notification1( - NOTIFICATION_TYPE_BASE_FORMAT, std::string(""), base::UTF8ToUTF16(""), - base::UTF8ToUTF16(""), CreateTestImage(80, 80), base::UTF8ToUTF16(""), - GURL(), message_center::NotifierId(GURL()), *data(), NULL); + Notification notification1(NOTIFICATION_TYPE_BASE_FORMAT, std::string(""), + base::UTF8ToUTF16(""), base::UTF8ToUTF16(""), + CreateTestImage(80, 80), base::UTF8ToUTF16(""), + GURL(), NotifierId(GURL()), *data(), NULL); notification1.set_context_message(base::ASCIIToUTF16(kRegularContextText)); base::string16 result = @@ -579,7 +579,7 @@ Notification notification2( NOTIFICATION_TYPE_BASE_FORMAT, std::string(""), base::UTF8ToUTF16(""), base::UTF8ToUTF16(""), CreateTestImage(80, 80), base::UTF8ToUTF16(""), - GURL(kUrlContext), message_center::NotifierId(GURL()), *data(), NULL); + GURL(kUrlContext), NotifierId(GURL()), *data(), NULL); notification2.set_context_message(base::ASCIIToUTF16("")); result = notification_view()->FormatContextMessage(notification2); @@ -590,7 +590,7 @@ Notification notification3( NOTIFICATION_TYPE_BASE_FORMAT, std::string(""), base::UTF8ToUTF16(""), base::UTF8ToUTF16(""), CreateTestImage(80, 80), base::UTF8ToUTF16(""), - GURL(kChromeUrl), message_center::NotifierId(GURL()), *data(), NULL); + GURL(kChromeUrl), NotifierId(GURL()), *data(), NULL); notification3.set_context_message(base::ASCIIToUTF16("")); result = notification_view()->FormatContextMessage(notification3); EXPECT_TRUE(result.empty()); @@ -599,7 +599,7 @@ Notification notification4( NOTIFICATION_TYPE_BASE_FORMAT, std::string(""), base::UTF8ToUTF16(""), base::UTF8ToUTF16(""), CreateTestImage(80, 80), base::UTF8ToUTF16(""), - GURL(kLongUrlContext), message_center::NotifierId(GURL()), *data(), NULL); + GURL(kLongUrlContext), NotifierId(GURL()), *data(), NULL); notification4.set_context_message(base::ASCIIToUTF16("")); result = notification_view()->FormatContextMessage(notification4);
diff --git a/ui/message_center/views/proportional_image_view.cc b/ui/message_center/views/proportional_image_view.cc index 8a260960..b0d0d3c 100644 --- a/ui/message_center/views/proportional_image_view.cc +++ b/ui/message_center/views/proportional_image_view.cc
@@ -53,7 +53,7 @@ gfx::Size max_size = max_image_size_; max_size.SetToMin(GetContentsBounds().size()); - return message_center::GetImageSizeForContainerSize(max_size, image_.size()); + return GetImageSizeForContainerSize(max_size, image_.size()); } } // namespace message_center
diff --git a/ui/views/touchui/touch_selection_menu_runner_views.cc b/ui/views/touchui/touch_selection_menu_runner_views.cc index 75ab64c9..3b283a14 100644 --- a/ui/views/touchui/touch_selection_menu_runner_views.cc +++ b/ui/views/touchui/touch_selection_menu_runner_views.cc
@@ -10,6 +10,8 @@ #include "base/strings/utf_string_conversions.h" #include "ui/aura/window.h" #include "ui/base/l10n/l10n_util.h" +#include "ui/display/display.h" +#include "ui/display/screen.h" #include "ui/gfx/canvas.h" #include "ui/gfx/geometry/insets.h" #include "ui/gfx/geometry/rect.h" @@ -120,7 +122,16 @@ SetAnchorRect(adjusted_anchor_rect); BubbleDialogDelegateView::CreateBubble(this); - GetWidget()->Show(); + Widget* widget = GetWidget(); + gfx::Rect bounds = widget->GetWindowBoundsInScreen(); + gfx::Rect work_area = display::Screen::GetScreen() + ->GetDisplayNearestPoint(bounds.origin()) + .work_area(); + if (!work_area.IsEmpty()) { + bounds.AdjustToFit(work_area); + widget->SetBounds(bounds); + } + widget->Show(); } bool TouchSelectionMenuRunnerViews::Menu::IsMenuAvailable(
diff --git a/ui/views/view.cc b/ui/views/view.cc index 6d3e4c9..8568fae 100644 --- a/ui/views/view.cc +++ b/ui/views/view.cc
@@ -96,21 +96,22 @@ namespace internal { #if DCHECK_IS_ON() - class ScopedChildrenLock { - public: - explicit ScopedChildrenLock(const View* view) - : reset_(&view->iterating_, true) {} - ~ScopedChildrenLock() {} - private: - base::AutoReset<bool> reset_; - DISALLOW_COPY_AND_ASSIGN(ScopedChildrenLock); - }; +class ScopedChildrenLock { + public: + explicit ScopedChildrenLock(const View* view) + : reset_(&view->iterating_, true) {} + ~ScopedChildrenLock() {} + + private: + base::AutoReset<bool> reset_; + DISALLOW_COPY_AND_ASSIGN(ScopedChildrenLock); +}; #else - class ScopedChildrenLock { - public: - explicit ScopedChildrenLock(const View* view) {} - ~ScopedChildrenLock() {} - }; +class ScopedChildrenLock { + public: + explicit ScopedChildrenLock(const View* view) {} + ~ScopedChildrenLock() {} +}; #endif } // namespace internal @@ -127,7 +128,7 @@ : owned_by_client_(false), id_(0), group_(-1), - parent_(NULL), + parent_(nullptr), #if DCHECK_IS_ON() iterating_(false), #endif @@ -140,13 +141,13 @@ snap_layer_to_pixel_boundary_(false), flip_canvas_on_paint_for_rtl_ui_(false), paint_to_layer_(false), - accelerator_focus_manager_(NULL), + accelerator_focus_manager_(nullptr), registered_accelerator_count_(0), - next_focusable_view_(NULL), - previous_focusable_view_(NULL), + next_focusable_view_(nullptr), + previous_focusable_view_(nullptr), focus_behavior_(FocusBehavior::NEVER), - context_menu_controller_(NULL), - drag_controller_(NULL) { + context_menu_controller_(nullptr), + drag_controller_(nullptr) { SetTargetHandler(this); } @@ -157,7 +158,7 @@ { internal::ScopedChildrenLock lock(this); for (auto* child : children_) { - child->parent_ = NULL; + child->parent_ = nullptr; if (!child->owned_by_client_) delete child; } @@ -171,7 +172,7 @@ const Widget* View::GetWidget() const { // The root view holds a reference to this view hierarchy's Widget. - return parent_ ? parent_->GetWidget() : NULL; + return parent_ ? parent_->GetWidget() : nullptr; } Widget* View::GetWidget() { @@ -292,12 +293,13 @@ } void View::RemoveChildView(View* view) { - DoRemoveChildView(view, true, true, false, NULL); + DoRemoveChildView(view, true, true, false, nullptr); } void View::RemoveAllChildViews(bool delete_children) { while (!children_.empty()) - DoRemoveChildView(children_.front(), false, false, delete_children, NULL); + DoRemoveChildView(children_.front(), false, false, delete_children, + nullptr); UpdateTooltip(); } @@ -383,7 +385,7 @@ const View* view = this; gfx::Transform transform; - while (view != NULL && !vis_bounds.IsEmpty()) { + while (view != nullptr && !vis_bounds.IsEmpty()) { transform.ConcatTransform(view->GetTransform()); gfx::Transform translation; translation.Translate(static_cast<float>(view->GetMirroredX()), @@ -392,7 +394,7 @@ vis_bounds = view->ConvertRectToParent(vis_bounds); const View* ancestor = view->parent_; - if (ancestor != NULL) { + if (ancestor != nullptr) { ancestor_bounds.SetRect(0, 0, ancestor->width(), ancestor->height()); vis_bounds.Intersect(ancestor_bounds); } else if (!view->GetWidget()) { @@ -435,9 +437,9 @@ } void View::SizeToPreferredSize() { - gfx::Size prefsize = GetPreferredSize(); - if ((prefsize.width() != width()) || (prefsize.height() != height())) - SetBounds(x(), y(), prefsize.width(), prefsize.height()); + gfx::Size pref_size = GetPreferredSize(); + if ((pref_size.width() != width()) || (pref_size.height() != height())) + SetBounds(x(), y(), pref_size.width(), pref_size.height()); } gfx::Size View::GetMinimumSize() const { @@ -647,7 +649,7 @@ if (!strcmp(view->GetClassName(), name.c_str())) return view; } - return NULL; + return nullptr; } View* View::GetAncestorWithClassName(const std::string& name) { @@ -665,7 +667,7 @@ if (view) return view; } - return NULL; + return nullptr; } View* View::GetViewByID(int id) { @@ -698,7 +700,7 @@ View* View::GetSelectedViewForGroup(int group) { Views views; GetWidget()->GetRootView()->GetViewsInGroup(group, &views); - return views.empty() ? NULL : views[0]; + return views.empty() ? nullptr : views[0]; } // Coordinate conversion ------------------------------------------------------- @@ -746,7 +748,7 @@ DCHECK(src); DCHECK(p); - src->ConvertPointForAncestor(NULL, p); + src->ConvertPointForAncestor(nullptr, p); } // static @@ -754,7 +756,7 @@ DCHECK(dest); DCHECK(p); - dest->ConvertPointFromAncestor(NULL, p); + dest->ConvertPointFromAncestor(nullptr, p); } // static @@ -899,7 +901,7 @@ } ui::TransformRecorder transform_recorder(context); - SetupTransformRecorderForPainting(paint_info.offset_from_parent(), + SetUpTransformRecorderForPainting(paint_info.offset_from_parent(), &transform_recorder); // Note that the cache is not aware of the offset of the view @@ -980,7 +982,7 @@ View* View::GetTooltipHandlerForPoint(const gfx::Point& point) { // TODO(tdanderson): Move this implementation into ViewTargetDelegate. if (!HitTestPoint(point) || !CanProcessEventsWithinSubtree()) - return NULL; + return nullptr; // Walk the child Views recursively looking for the View that most // tightly encloses the specified point. @@ -1003,7 +1005,7 @@ #if defined(OS_WIN) static ui::Cursor arrow; if (!arrow.platform()) - arrow.SetPlatformCursor(LoadCursor(NULL, IDC_ARROW)); + arrow.SetPlatformCursor(LoadCursor(nullptr, IDC_ARROW)); return arrow; #else return gfx::kNullCursor; @@ -1058,7 +1060,7 @@ } void View::SetMouseHandler(View* new_mouse_handler) { - // |new_mouse_handler| may be NULL. + // |new_mouse_handler| may be nullptr. if (parent_) parent_->SetMouseHandler(new_mouse_handler); } @@ -1296,12 +1298,12 @@ FocusManager* View::GetFocusManager() { Widget* widget = GetWidget(); - return widget ? widget->GetFocusManager() : NULL; + return widget ? widget->GetFocusManager() : nullptr; } const FocusManager* View::GetFocusManager() const { const Widget* widget = GetWidget(); - return widget ? widget->GetFocusManager() : NULL; + return widget ? widget->GetFocusManager() : nullptr; } void View::RequestFocus() { @@ -1320,11 +1322,11 @@ } FocusTraversable* View::GetFocusTraversable() { - return NULL; + return nullptr; } FocusTraversable* View::GetPaneFocusTraversable() { - return NULL; + return nullptr; } // Tooltips -------------------------------------------------------------------- @@ -1602,7 +1604,7 @@ if (!layer()) return; - ui::Layer* parent_layer = NULL; + ui::Layer* parent_layer = nullptr; gfx::Vector2d offset(GetMirroredX(), y()); if (parent_) { @@ -1668,7 +1670,7 @@ if (new_parent) ReorderLayers(); - UpdateChildLayerBounds(CalculateOffsetToAncestorWithLayer(NULL)); + UpdateChildLayerBounds(CalculateOffsetToAncestorWithLayer(nullptr)); SchedulePaint(); @@ -1747,7 +1749,7 @@ if (widget) { // Reorder the widget's child NativeViews in case a child NativeView is - // associated with a view (eg via a NativeViewHost). Always do the + // associated with a view (e.g. via a NativeViewHost). Always do the // reordering because the associated NativeView's layer (if it has one) // is parented to the widget's layer regardless of whether the host view has // an ancestor with a layer. @@ -1775,7 +1777,7 @@ // Input ----------------------------------------------------------------------- View::DragInfo* View::GetDragInfo() { - return parent_ ? parent_->GetDragInfo() : NULL; + return parent_ ? parent_->GetDragInfo() : nullptr; } // Focus ----------------------------------------------------------------------- @@ -2002,7 +2004,7 @@ return visible_ && !size().IsEmpty(); } -void View::SetupTransformRecorderForPainting( +void View::SetUpTransformRecorderForPainting( const gfx::Vector2d& offset_from_parent, ui::TransformRecorder* recorder) const { // If the view is backed by a layer, it should paint with itself as the origin @@ -2051,7 +2053,7 @@ const ui::PaintContext& context = paint_info.context(); ui::TransformRecorder transform_recorder(context); - SetupTransformRecorderForPainting(paint_info.offset_from_parent(), + SetUpTransformRecorderForPainting(paint_info.offset_from_parent(), &transform_recorder); RecursivePaintHelper(&View::PaintDebugRects, paint_info); @@ -2276,7 +2278,7 @@ } else { // If our bounds have changed, then any descendant layer bounds may have // changed. Update them accordingly. - UpdateChildLayerBounds(CalculateOffsetToAncestorWithLayer(NULL)); + UpdateChildLayerBounds(CalculateOffsetToAncestorWithLayer(nullptr)); } OnBoundsChanged(previous_bounds); @@ -2356,7 +2358,7 @@ // Some code keeps a bare pointer to the layout manager for calling // derived-class-specific-functions. It's an easy mistake to create a new // unique_ptr and re-set the layout manager with a new unique_ptr, which - // will cause a crash. Re-setting to null is OK. + // will cause a crash. Re-setting to nullptr is OK. CHECK(!layout_manager.get() || layout_manager_.get() != layout_manager.get()); layout_manager_ = std::move(layout_manager); @@ -2562,7 +2564,7 @@ // Fall through to return value based on context menu controller. } // WARNING: we may have been deleted. - return (context_menu_controller != NULL) || possible_drag; + return (context_menu_controller != nullptr) || possible_drag; } void View::ProcessMouseReleased(const ui::MouseEvent& event) { @@ -2620,7 +2622,7 @@ if (GetWidget()) { if (accelerator_focus_manager_) { accelerator_focus_manager_->UnregisterAccelerators(this); - accelerator_focus_manager_ = NULL; + accelerator_focus_manager_ = nullptr; } if (!leave_data_intact) { accelerators_->clear(); @@ -2636,14 +2638,14 @@ int count = child_count(); if (count == 0) { - v->next_focusable_view_ = NULL; - v->previous_focusable_view_ = NULL; + v->next_focusable_view_ = nullptr; + v->previous_focusable_view_ = nullptr; } else { if (index == count) { // We are inserting at the end, but the end of the child list may not be // the last focusable element. Let's try to find an element with no next // focusable element to link to. - View* last_focusable_view = NULL; + View* last_focusable_view = nullptr; { internal::ScopedChildrenLock lock(this); for (auto* child : children_) { @@ -2653,7 +2655,7 @@ } } } - if (last_focusable_view == NULL) { + if (last_focusable_view == nullptr) { // Hum... there is a cycle in the focus list. Let's just insert ourself // after the last child. View* prev = children_[index - 1]; @@ -2663,7 +2665,7 @@ prev->next_focusable_view_ = v; } else { last_focusable_view->next_focusable_view_ = v; - v->next_focusable_view_ = NULL; + v->next_focusable_view_ = nullptr; v->previous_focusable_view_ = last_focusable_view; } } else { @@ -2680,7 +2682,7 @@ void View::AdvanceFocusIfNecessary() { // Focus should only be advanced if this is the focused view and has become // unfocusable. If the view is still focusable or is not focused, we can - // return early avoiding furthur unnecessary checks. Focusability check is + // return early avoiding further unnecessary checks. Focusability check is // performed first as it tends to be faster. if (IsAccessibilityFocusable() || !HasFocus()) return; @@ -2722,7 +2724,7 @@ void View::UpdateTooltip() { Widget* widget = GetWidget(); - // TODO(beng): The TooltipManager NULL check can be removed when we + // TODO(beng): The TooltipManager nullptr check can be removed when we // consolidate Init() methods and make views_unittests Init() all // Widgets that it uses. if (widget && widget->GetTooltipManager())
diff --git a/ui/views/view.h b/ui/views/view.h index 345d3d0e..8c04870d 100644 --- a/ui/views/view.h +++ b/ui/views/view.h
@@ -12,6 +12,7 @@ #include <memory> #include <set> #include <string> +#include <utility> #include <vector> #include "base/compiler_specific.h" @@ -52,7 +53,7 @@ class Insets; class Path; class Transform; -} +} // namespace gfx namespace ui { struct AXActionData; @@ -64,7 +65,7 @@ class PaintContext; class ThemeProvider; class TransformRecorder; -} +} // namespace ui namespace views { @@ -86,7 +87,7 @@ class PostEventDispatchHandler; class RootView; class ScopedChildrenLock; -} +} // namespace internal ///////////////////////////////////////////////////////////////////////////// // @@ -318,7 +319,7 @@ // position accessors. // Transformations are not applied on the size/position. For example, if // bounds is (0, 0, 100, 100) and it is scaled by 0.5 along the X axis, the - // width will still be 100 (although when painted, it will be 50x50, painted + // width will still be 100 (although when painted, it will be 50x100, painted // at location (0, 0)). void SetBounds(int x, int y, int width, int height); @@ -539,7 +540,7 @@ // Return the receiving view's class name. A view class is a string which // uniquely identifies the view class. It is intended to be used as a way to - // find out during run time if a view can be safely casted to a specific view + // find out during run time if a view can be safely cast to a specific view // subclass. The default implementation returns kViewClassName. virtual const char* GetClassName() const; @@ -750,7 +751,7 @@ // The provided event is in the receiver's coordinate system. // // Return true if you processed the event and want to receive subsequent - // MouseDraggged and MouseReleased events. This also stops the event from + // MouseDragged and MouseReleased events. This also stops the event from // bubbling. If you return false, the event will bubble through parent // views. // @@ -825,7 +826,7 @@ virtual void SetMouseHandler(View* new_mouse_handler); // Invoked when a key is pressed or released. - // Subclasser should return true if the event has been processed and false + // Subclasses should return true if the event has been processed and false // otherwise. If the event has not been processed, the parent will be given a // chance. virtual bool OnKeyPressed(const ui::KeyEvent& event); @@ -1004,7 +1005,7 @@ // Provides default implementation for context menu handling. The default // implementation calls the ShowContextMenu of the current // ContextMenuController (if it is not NULL). Overridden in subclassed views - // to provide right-click menu display triggerd by the keyboard (i.e. for the + // to provide right-click menu display triggered by the keyboard (i.e. for the // Chrome toolbar Back and Forward buttons). No source needs to be specified, // as it is always equal to the current View. virtual void ShowContextMenu(const gfx::Point& p, @@ -1138,7 +1139,7 @@ // The following methods are used by ScrollView to determine the amount // to scroll relative to the visible bounds of the view. For example, a - // return value of 10 indicates the scrollview should scroll 10 pixels in + // return value of 10 indicates the scroll_view should scroll 10 pixels in // the appropriate direction. // // Each method takes the following parameters: @@ -1442,7 +1443,7 @@ bool ShouldPaint() const; // Adjusts the transform of |recorder| in advance of painting. - void SetupTransformRecorderForPainting( + void SetUpTransformRecorderForPainting( const gfx::Vector2d& offset_from_parent, ui::TransformRecorder* recorder) const;
diff --git a/ui/views/widget/widget.cc b/ui/views/widget/widget.cc index d685bf4f..926519d 100644 --- a/ui/views/widget/widget.cc +++ b/ui/views/widget/widget.cc
@@ -525,6 +525,8 @@ if (work_area.IsEmpty()) { SetBounds(bounds); } else { + // TODO(https://crbug.com/806936): The following code doesn't actually do + // what the comment describing this function says it should. // Inset the work area slightly. work_area.Inset(10, 10, 10, 10); work_area.AdjustToFit(bounds);
diff --git a/ui/webui/resources/webui_resources.grd b/ui/webui/resources/webui_resources.grd index 980b689a..81e47309 100644 --- a/ui/webui/resources/webui_resources.grd +++ b/ui/webui/resources/webui_resources.grd
@@ -274,9 +274,11 @@ <structure name="IDR_WEBUI_HTML_ACTION_LINK" file="html/action_link.html" type="chrome_html" compress="gzip" /> - <structure name="IDR_WEBUI_HTML_ACTION_LINK_CSS" - file="html/action_link_css.html" type="chrome_html" - compress="gzip" /> + <if expr="not is_android and not is_ios"> + <structure name="IDR_WEBUI_HTML_ACTION_LINK_CSS" + file="html/action_link_css.html" type="chrome_html" + compress="gzip" /> + </if> <structure name="IDR_WEBUI_HTML_ASSERT" file="html/assert.html" type="chrome_html" compress="gzip" /> <structure name="IDR_WEBUI_HTML_PROMISE_RESOLVER" @@ -319,9 +321,11 @@ <structure name="IDR_WEBUI_HTML_CR_UI_FOCUS_ROW" file="html/cr/ui/focus_row.html" type="chrome_html" compress="gzip" /> - <structure name="IDR_WEBUI_HTML_CR_UI_FOCUS_WITHOUT_INK" - file="html/cr/ui/focus_without_ink.html" type="chrome_html" - compress="gzip" /> + <if expr="not is_android and not is_ios"> + <structure name="IDR_WEBUI_HTML_CR_UI_FOCUS_WITHOUT_INK" + file="html/cr/ui/focus_without_ink.html" type="chrome_html" + compress="gzip" /> + </if> <structure name="IDR_WEBUI_HTML_CR_UI_LIST" file="html/cr/ui/list.html" type="chrome_html" compress="gzip" /> @@ -366,25 +370,31 @@ <structure name="IDR_WEBUI_HTML_I18N_TEMPLATE" file="html/i18n_template.html" type="chrome_html" compress="gzip" /> - <structure name="IDR_WEBUI_HTML_MD_SELECT_CSS_HTML" - file="html/md_select_css.html" type="chrome_html" - compress="gzip" flattenhtml="true" /> + <if expr="not is_android and not is_ios"> + <structure name="IDR_WEBUI_HTML_MD_SELECT_CSS_HTML" + file="html/md_select_css.html" type="chrome_html" + compress="gzip" flattenhtml="true" /> + </if> <structure name="IDR_WEBUI_HTML_LOAD_TIME_DATA" file="html/load_time_data.html" type="chrome_html" compress="gzip" /> <structure name="IDR_WEBUI_HTML_PARSE_HTML_SUBSET" file="html/parse_html_subset.html" type="chrome_html" compress="gzip" /> - <structure name="IDR_WEBUI_HTML_POLYMER" - file="html/polymer.html" type="chrome_html" compress="gzip" /> - <structure name="IDR_WEBUI_HTML_I18N_BEHAVIOR" - file="html/i18n_behavior.html" type="chrome_html" - compress="gzip" /> + <if expr="not is_android and not is_ios"> + <structure name="IDR_WEBUI_HTML_POLYMER" + file="html/polymer.html" type="chrome_html" compress="gzip" /> + <structure name="IDR_WEBUI_HTML_I18N_BEHAVIOR" + file="html/i18n_behavior.html" type="chrome_html" + compress="gzip" /> + </if> <structure name="IDR_WEBUI_HTML_UTIL" file="html/util.html" type="chrome_html" compress="gzip" /> - <structure name="IDR_WEBUI_HTML_WEBUI_LISTENER_BEHAVIOR" - file="html/web_ui_listener_behavior.html" type="chrome_html" - compress="gzip" /> + <if expr="not is_android and not is_ios"> + <structure name="IDR_WEBUI_HTML_WEBUI_LISTENER_BEHAVIOR" + file="html/web_ui_listener_behavior.html" type="chrome_html" + compress="gzip" /> + </if> <structure name="IDR_WEBUI_HTML_WEBUI_LISTENER_TRACKER" file="html/webui_listener_tracker.html" type="chrome_html" compress="gzip" /> @@ -454,9 +464,11 @@ <structure name="IDR_WEBUI_JS_CR_UI_FOCUS_ROW" file="js/cr/ui/focus_row.js" type="chrome_html" compress="gzip" /> - <structure name="IDR_WEBUI_JS_CR_UI_FOCUS_WITHOUT_INK" - file="js/cr/ui/focus_without_ink.js" type="chrome_html" - compress="gzip" /> + <if expr="not is_android and not is_ios"> + <structure name="IDR_WEBUI_JS_CR_UI_FOCUS_WITHOUT_INK" + file="js/cr/ui/focus_without_ink.js" type="chrome_html" + compress="gzip" /> + </if> <structure name="IDR_WEBUI_JS_CR_UI_LIST" file="js/cr/ui/list.js" type="chrome_html" compress="gzip" /> <structure name="IDR_WEBUI_JS_CR_UI_LIST_ITEM" @@ -546,22 +558,26 @@ <structure name="IDR_WEBUI_JS_PARSE_HTML_SUBSET" file="js/parse_html_subset.js" type="chrome_html" compress="gzip" /> - <structure name="IDR_WEBUI_JS_POLYMER_CONFIG" - file="js/polymer_config.js" type="chrome_html" - compress="gzip" /> - <structure name="IDR_WEBUI_JS_I18N_BEHAVIOR" - file="js/i18n_behavior.js" type="chrome_html" - compress="gzip" /> + <if expr="not is_android and not is_ios"> + <structure name="IDR_WEBUI_JS_POLYMER_CONFIG" + file="js/polymer_config.js" type="chrome_html" + compress="gzip" /> + <structure name="IDR_WEBUI_JS_I18N_BEHAVIOR" + file="js/i18n_behavior.js" type="chrome_html" + compress="gzip" /> + </if> <structure name="IDR_WEBUI_JS_UTIL" file="js/util.js" type="chrome_html" compress="gzip" flattenhtml="true" /> - <structure name="IDR_WEBUI_JS_WEBUI_LISTENER_BEHAVIOR" - file="js/web_ui_listener_behavior.js" type="chrome_html" - compress="gzip" /> + <if expr="not is_android and not is_ios"> + <structure name="IDR_WEBUI_JS_WEBUI_LISTENER_BEHAVIOR" + file="js/web_ui_listener_behavior.js" type="chrome_html" + compress="gzip" /> + </if> <structure name="IDR_WEBUI_JS_WEBUI_RESOURCE_TEST" file="js/webui_resource_test.js" type="chrome_html" compress="gzip" /> - <if expr="not is_android"> + <if expr="not is_android and not is_ios"> <part file="cr_components/cr_components_resources.grdp" /> <part file="cr_elements_resources.grdp" /> <part file="polymer_resources.grdp" />
diff --git a/url/url_canon_icu.cc b/url/url_canon_icu.cc index 9513fc6..254d7e4 100644 --- a/url/url_canon_icu.cc +++ b/url/url_canon_icu.cc
@@ -13,6 +13,7 @@ #include "third_party/icu/source/common/unicode/ucnv.h" #include "third_party/icu/source/common/unicode/ucnv_cb.h" #include "third_party/icu/source/common/unicode/uidna.h" +#include "third_party/icu/source/common/unicode/utypes.h" #include "url/url_canon_icu.h" #include "url/url_canon_internal.h" // for _itoa_s @@ -101,7 +102,8 @@ // registrars, search engines) converge toward a consensus. value = uidna_openUTS46(UIDNA_CHECK_BIDI, &err); if (U_FAILURE(err)) { - CHECK(false) << "failed to open UTS46 data with error: " << err + CHECK(false) << "failed to open UTS46 data with error: " + << u_errorName(err) << ". If you see this error message in a test environment " << "your test environment likely lacks the required data " << "tables for libicu. See https://crbug.com/778929.";