diff --git a/DEPS b/DEPS index 24f84df..e993d86d 100644 --- a/DEPS +++ b/DEPS
@@ -83,7 +83,7 @@ # 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': 'f2df44f0b255dea0c96aa099807b891fabccfad4', + 'v8_revision': 'd14d7b029a107f0fa9d8a0379bca8f3937d6bdd6', # 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. @@ -91,11 +91,11 @@ # 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': '0690e1aa31d4e0c9f1ab641e5c0dab75a79c026e', + 'angle_revision': '0e1224c82c67aa9a85b571aa41af20ec16dc3911', # 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. - 'buildtools_revision': '1be57dc4c2c68fa564ee258a3af0cf8003007edf', + 'buildtools_revision': 'd3ad6b3bbb444a7df1dee6edacccd7fd9c40827e', # Three lines of non-changing comments so that # the commit queue can handle CLs rolling SwiftShader # and whatever else without interference from each other. @@ -103,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': '594b3eeeaa61a2c0a6d84df3e17ea587f3b15c23', + 'pdfium_revision': '640d8ffad8536c789103892c7a4e69e5d30172c8', # 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. @@ -135,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': 'd4706cb285d8caaa8e7c0334e0528efe7b9a26ff', + 'catapult_revision': '21f0b3554207e6e8178fa4e8f0c91b1249aeec79', # Three lines of non-changing comments so that # the commit queue can handle CLs rolling libFuzzer # and whatever else without interference from each other. @@ -264,7 +264,7 @@ }, 'src/third_party/android_tools': { - 'url': Var('chromium_git') + '/android_tools.git' + '@' + '7d781b3544ef67dfa8c7c0c1a347b818c49c42bc', + 'url': Var('chromium_git') + '/android_tools.git' + '@' + 'c78b25872734e0038ae2a333edc645cd96bc232d', 'condition': 'checkout_android', }, @@ -328,7 +328,7 @@ }, 'src/third_party/depot_tools': - Var('chromium_git') + '/chromium/tools/depot_tools.git' + '@' + '1edda746d22f903ee18f662d8463b707bd55febd', + Var('chromium_git') + '/chromium/tools/depot_tools.git' + '@' + '31c14787e48c1d032e8780a11aa1ddd4d63861b7', 'src/third_party/devtools-node-modules': Var('chromium_git') + '/external/github.com/ChromeDevTools/devtools-node-modules' + '@' + Var('devtools_node_modules_revision'), @@ -644,7 +644,7 @@ Var('chromium_git') + '/external/khronosgroup/webgl.git' + '@' + 'd458ada06171a85af00367251a4ed55db7fe2018', 'src/third_party/webrtc': - Var('webrtc_git') + '/src.git' + '@' + '62337e59dd01699eccb3c496bf7112ca930ec828', # commit position 20628 + Var('webrtc_git') + '/src.git' + '@' + 'a0f5f60c93edcf4105c38f1648f4ba1546a7db0c', # commit position 20628 'src/third_party/xdg-utils': { 'url': Var('chromium_git') + '/chromium/deps/xdg-utils.git' + '@' + 'd80274d5869b17b8c9067a1022e4416ee7ed5e0d', @@ -667,7 +667,7 @@ Var('chromium_git') + '/v8/v8.git' + '@' + Var('v8_revision'), 'src-internal': { - 'url': 'https://chrome-internal.googlesource.com/chrome/src-internal.git@d7cb2345a578931aab20cc6378c2fcb7f5f76ff5', + 'url': 'https://chrome-internal.googlesource.com/chrome/src-internal.git@5f3809d09f6b7fbafe6240188197ce3438ad44a2', 'condition': 'checkout_src_internal', }, }
diff --git a/WATCHLISTS b/WATCHLISTS index 0c09bd9..c8ddf5d5 100644 --- a/WATCHLISTS +++ b/WATCHLISTS
@@ -764,9 +764,6 @@ 'deep_memory_profiler': { 'filepath': 'tools/(deep_memory_profiler|find_runtime_symbols)', }, - 'developer_recommended_flags': { - 'filepath': 'developer_recommended_flags.gypi', - }, 'device_bluetooth': { 'filepath': 'device/.*bluetooth' }, @@ -1092,9 +1089,6 @@ 'mojo_top_level_directory': { 'filepath': '^mojo/', }, - 'mouse_lock': { - 'filepath': 'mouse_lock', - }, 'mus': { 'filepath': 'services/ui/'\ '|mojo/gpu/', @@ -1720,8 +1714,7 @@ 'blink_bindings_serialization': ['jbroman+watch@chromium.org'], 'blink_bluetooth': ['cco3+watch@chromium.org', 'mattreynolds+watch@chromium.org', - 'ortuno+watch@chromium.org', - 'scheib+watch@chromium.org'], + 'ortuno+watch@chromium.org'], 'blink_canvas2d': ['dongseong.hwang@intel.com', 'junov@chromium.org'], 'blink_client_hints': ['yoav@yoav.ws'], @@ -1953,8 +1946,7 @@ 'content': ['jam@chromium.org'], 'content_bluetooth': ['cco3+watch@chromium.org', 'mattreynolds+watch@chromium.org', - 'ortuno+watch@chromium.org', - 'scheib+watch@chromium.org'], + 'ortuno+watch@chromium.org'], 'content_loader': ['loading-reviews@chromium.org', 'rdsmith+watch@chromium.org'], 'content_network': ['asanka@chromium.org', @@ -1983,15 +1975,12 @@ 'custom_tabs': ['lizeb+watch-custom-tabs@chromium.org'], 'data_reduction_proxy': ['tbansal+watch-data-reduction-proxy@chromium.org'], 'deep_memory_profiler': ['dmikurube@chromium.org'], - 'developer_recommended_flags': ['scheib+watch@chromium.org'], 'device_bluetooth': ['cco3+watch@chromium.org', 'mattreynolds+watch@chromium.org', - 'ortuno+watch@chromium.org', - 'scheib+watch@chromium.org'], + 'ortuno+watch@chromium.org'], 'device_chooser': ['cco3+watch@chromium.org', 'juncai+watch@chromium.org', - 'mattreynolds+watch@chromium.org', - 'scheib+watch@chromium.org'], + 'mattreynolds+watch@chromium.org'], 'device_sensors': ['juncai+watch@chromium.org', 'mlamouri+watch-sensors@chromium.org', 'rijubrata.bhaumik@intel.com', @@ -2022,8 +2011,7 @@ 'fuchsia': ['sergeyu@chromium.org', 'wez@chromium.org'], 'fuzzing': ['fuzzing@chromium.org'], 'gamepad': ['cco3+watch@chromium.org', - 'mattreynolds+watch@chromium.org', - 'scheib+watch@chromium.org'], + 'mattreynolds+watch@chromium.org'], 'gcm': ['peter@chromium.org', 'zea+watch@chromium.org'], 'generic_sensor': ['alexander.shalamov@intel.com', @@ -2032,12 +2020,10 @@ 'mattreynolds+watch@chromium.org', 'mikhail.pozdnyakov@intel.com', 'timvolodine@chromium.org', - 'scheib+watch@chromium.org', 'wanming.lin@intel.com'], 'geolocation': ['cco3+watch@chromium.org', 'mattreynolds+watch@chromium.org', - 'mlamouri+watch-geolocation@chromium.org', - 'scheib+watch@chromium.org'], + 'mlamouri+watch-geolocation@chromium.org'], 'gfx_geometry': ['cc-bugs@chromium.org'], 'gfx_image': ['rsesek+watch@chromium.org'], 'gn': ['agrieve+watch@chromium.org', @@ -2130,7 +2116,6 @@ 'qsr+mojo@chromium.org', 'viettrungluu+watch@chromium.org'], 'mojo_top_level_directory': ['yzshen+watch@chromium.org'], - 'mouse_lock': ['scheib+watch@chromium.org'], 'mus': ['rjkroege@chromium.org'], 'nacl': ['native-client-reviews@googlegroups.com'], 'native_client_sdk': ['binji+watch@chromium.org', @@ -2147,8 +2132,7 @@ 'net_websockets': ['tyoshino+watch@chromium.org'], 'netinfo': ['jkarlin+watch@chromium.org'], 'nfc': ['cco3+watch@chromium.org', - 'mattreynolds+watch@chromium.org', - 'scheib+watch@chromium.org'], + 'mattreynolds+watch@chromium.org'], 'notifications': ['awdf+watch@chromium.org', 'mlamouri+watch-notifications@chromium.org', 'peter@chromium.org'], @@ -2294,8 +2278,7 @@ 'ui_resources': ['oshima+watch@chromium.org'], 'ui_strings': ['srahim+watch@chromium.org'], 'usb': ['cco3+watch@chromium.org', - 'mattreynolds+watch@chromium.org', - 'scheib+watch@chromium.org'], + 'mattreynolds+watch@chromium.org'], 'v4l2': ['acourbot+watch@chromium.org'], 'vaapi': ['vaapi-reviews@chromium.org'], 'valgrind': ['bruening+watch@chromium.org', @@ -2311,8 +2294,7 @@ 'yhanada+watchvk@chromium.org'], 'virtual_reality': ['feature-vr-reviews@chromium.org'], 'wake_lock': ['cco3+watch@chromium.org', - 'mattreynolds+watch@chromium.org', - 'scheib+watch@chromium.org'], + 'mattreynolds+watch@chromium.org'], 'web_share': ['mgiuca+watch@chromium.org'], 'webrtc_browser_tests': ['phoglund+watch@chromium.org'], 'website_settings': ['markusheintz@chromium.org',
diff --git a/android_webview/java/src/org/chromium/android_webview/AwContents.java b/android_webview/java/src/org/chromium/android_webview/AwContents.java index 16af2c7..86b143b 100644 --- a/android_webview/java/src/org/chromium/android_webview/AwContents.java +++ b/android_webview/java/src/org/chromium/android_webview/AwContents.java
@@ -78,6 +78,7 @@ import org.chromium.content_public.browser.NavigationController; import org.chromium.content_public.browser.NavigationHistory; import org.chromium.content_public.browser.SelectionClient; +import org.chromium.content_public.browser.SelectionPopupController; import org.chromium.content_public.browser.WebContents; import org.chromium.content_public.browser.WebContentsInternals; import org.chromium.content_public.browser.navigation_controller.LoadURLType; @@ -876,14 +877,14 @@ ViewAndroidDelegate viewDelegate, InternalAccessDelegate internalDispatcher, WebContents webContents, WindowAndroid windowAndroid) { contentViewCore.initialize(viewDelegate, internalDispatcher, webContents, windowAndroid); - contentViewCore.setActionModeCallback( - new AwActionModeCallback(mContext, this, - contentViewCore.getActionModeCallbackHelper())); + SelectionPopupController controller = SelectionPopupController.fromWebContents(webContents); + controller.setActionModeCallback( + new AwActionModeCallback(mContext, this, controller.getActionModeCallbackHelper())); if (mAutofillProvider != null) { - contentViewCore.setNonSelectionActionModeCallback( + controller.setNonSelectionActionModeCallback( new AutofillActionModeCallback(context, mAutofillProvider)); } - contentViewCore.setSelectionClient(SelectionClient.createSmartSelectionClient(webContents)); + controller.setSelectionClient(SelectionClient.createSmartSelectionClient(webContents)); // Listen for dpad events from IMEs (e.g. Samsung Cursor Control) so we know to enable // spatial navigation mode to allow these events to move focus out of the WebView. @@ -1119,11 +1120,16 @@ if (Build.VERSION.SDK_INT < Build.VERSION_CODES.O) { setNewAwContentsPreO(newAwContentsPtr); } else { - // Move the TextClassifier to the new ContentViewCore. - TextClassifier textClassifier = - mContentViewCore == null ? null : mContentViewCore.getCustomTextClassifier(); + // Move the TextClassifier to the new WebContents. + SelectionPopupController oldController = + SelectionPopupController.fromWebContents(mWebContents); + + TextClassifier textClassifier = oldController.getCustomTextClassifier(); setNewAwContentsPreO(newAwContentsPtr); - if (textClassifier != null) mContentViewCore.setTextClassifier(textClassifier); + if (textClassifier != null) { + SelectionPopupController.fromWebContents(mWebContents) + .setTextClassifier(textClassifier); + } } } @@ -2474,7 +2480,8 @@ public void onActivityResult(int requestCode, int resultCode, Intent data) { if (isDestroyedOrNoOperation(NO_WARN)) return; if (requestCode == PROCESS_TEXT_REQUEST_CODE) { - mContentViewCore.onReceivedProcessTextResult(resultCode, data); + SelectionPopupController.fromWebContents(mWebContents) + .onReceivedProcessTextResult(resultCode, data); } else { Log.e(TAG, "Received activity result for an unknown request code %d", requestCode); } @@ -2820,13 +2827,13 @@ } public void setTextClassifier(TextClassifier textClassifier) { - assert mContentViewCore != null; - mContentViewCore.setTextClassifier(textClassifier); + assert mWebContents != null; + SelectionPopupController.fromWebContents(mWebContents).setTextClassifier(textClassifier); } public TextClassifier getTextClassifier() { - assert mContentViewCore != null; - return mContentViewCore.getTextClassifier(); + assert mWebContents != null; + return SelectionPopupController.fromWebContents(mWebContents).getTextClassifier(); } //--------------------------------------------------------------------------------------------
diff --git a/android_webview/javatests/src/org/chromium/android_webview/test/PopupWindowTest.java b/android_webview/javatests/src/org/chromium/android_webview/test/PopupWindowTest.java index 67cff25..c7ae53c 100644 --- a/android_webview/javatests/src/org/chromium/android_webview/test/PopupWindowTest.java +++ b/android_webview/javatests/src/org/chromium/android_webview/test/PopupWindowTest.java
@@ -20,11 +20,11 @@ import org.chromium.base.ThreadUtils; import org.chromium.base.test.util.Feature; import org.chromium.base.test.util.RetryOnFailure; -import org.chromium.content.browser.ContentViewCore; import org.chromium.content.browser.test.util.Criteria; import org.chromium.content.browser.test.util.CriteriaHelper; import org.chromium.content.browser.test.util.DOMUtils; import org.chromium.content.browser.test.util.TestCallbackHelperContainer; +import org.chromium.content_public.browser.SelectionPopupController; import org.chromium.net.test.util.TestWebServer; /** @@ -140,15 +140,16 @@ // Now long press on some texts and see if the text handles show up. DOMUtils.longPressNode(popupContents.getContentViewCore(), "plain_text"); - assertWaitForSelectActionBarStatus(true, popupContents.getContentViewCore()); - Assert.assertTrue(ThreadUtils.runOnUiThreadBlocking(() -> popupContents.getContentViewCore() - .getSelectionPopupControllerForTesting().hasSelection())); + SelectionPopupController controller = + SelectionPopupController.fromWebContents(popupContents.getWebContents()); + assertWaitForSelectActionBarStatus(true, controller); + Assert.assertTrue(ThreadUtils.runOnUiThreadBlocking(() -> controller.hasSelection())); // Now hide the select action bar. This should hide the text handles and // clear the selection. - hideSelectActionMode(popupContents.getContentViewCore()); + hideSelectActionMode(controller); - assertWaitForSelectActionBarStatus(false, popupContents.getContentViewCore()); + assertWaitForSelectActionBarStatus(false, controller); String jsGetSelection = "window.getSelection().toString()"; // Test window.getSelection() returns empty string "" literally. Assert.assertEquals("\"\"", @@ -157,12 +158,14 @@ } // Copied from imeTest.java. - private void assertWaitForSelectActionBarStatus(boolean show, final ContentViewCore cvc) { - CriteriaHelper.pollUiThread(Criteria.equals(show, () -> cvc.isSelectActionBarShowing())); + private void assertWaitForSelectActionBarStatus( + boolean show, final SelectionPopupController controller) { + CriteriaHelper.pollUiThread( + Criteria.equals(show, () -> controller.isSelectActionBarShowing())); } - private void hideSelectActionMode(final ContentViewCore cvc) { + private void hideSelectActionMode(final SelectionPopupController controller) { InstrumentationRegistry.getInstrumentation().runOnMainSync( - () -> cvc.destroySelectActionMode()); + () -> controller.destroySelectActionMode()); } }
diff --git a/apps/DEPS b/apps/DEPS index ed600be3..c06c64fd 100644 --- a/apps/DEPS +++ b/apps/DEPS
@@ -13,7 +13,6 @@ specific_include_rules = { "(.*test\.cc|.*test_mac\.mm)": [ "+chrome/browser/extensions/extension_browsertest.h", - "+chrome/browser/extensions/extension_test_message_listener.h", "+chrome/browser/extensions/load_error_reporter.h", "+chrome/browser/extensions/test_extension_environment.h", "+chrome/browser/profiles/profile_manager.h",
diff --git a/ash/login/ui/login_pin_view.cc b/ash/login/ui/login_pin_view.cc index 38368c4..3e776b1 100644 --- a/ash/login/ui/login_pin_view.cc +++ b/ash/login/ui/login_pin_view.cc
@@ -42,10 +42,11 @@ constexpr const char kLoginPinViewClassName[] = "LoginPinView"; -// How long does the user have to long-press a button before it auto-submits? -const int kInitialLongPressDelayMs = 500; -// After the first auto-submit, how long until the next auto-submit event? -const int kRepeatingLongPressDelayMs = 150; +// How long does the user have to long-press the backspace button before it +// auto-submits? +const int kInitialBackspaceDelayMs = 500; +// After the first auto-submit, how long until the next backspace event fires? +const int kRepeatingBackspaceDelayMs = 150; base::string16 GetButtonLabelForNumber(int value) { DCHECK(value >= 0 && value < int{arraysize(kPinLabels)}); @@ -67,11 +68,8 @@ // A base class for pin button in the pin keyboard. class BasePinButton : public LoginButton, public views::ButtonListener { public: - explicit BasePinButton(const base::RepeatingClosure& on_press) - : LoginButton(this), - on_press_(on_press), - delay_timer_(std::make_unique<base::OneShotTimer>()), - repeat_timer_(std::make_unique<base::RepeatingTimer>()) { + explicit BasePinButton(const base::Closure& on_press) + : LoginButton(this), on_press_(on_press) { SetFocusBehavior(FocusBehavior::ALWAYS); SetPreferredSize( gfx::Size(LoginPinView::kButtonSizeDp, LoginPinView::kButtonSizeDp)); @@ -89,38 +87,9 @@ ~BasePinButton() override = default; - void SetTimersForTesting(std::unique_ptr<base::Timer> delay_timer, - std::unique_ptr<base::Timer> repeat_timer) { - delay_timer_ = std::move(delay_timer); - repeat_timer_ = std::move(repeat_timer); - } - - // LoginButton: - bool OnMousePressed(const ui::MouseEvent& event) override { - did_autosubmit_ = false; - - if (IsTriggerableEvent(event) && enabled() && - HitTestPoint(event.location())) { - delay_timer_->Start( - FROM_HERE, - base::TimeDelta::FromMilliseconds(kInitialLongPressDelayMs), - base::BindRepeating(&BasePinButton::DispatchRepeatablePressEvent, - base::Unretained(this))); - } - - return LoginButton::OnMousePressed(event); - } - void OnMouseReleased(const ui::MouseEvent& event) override { - delay_timer_->Stop(); - repeat_timer_->Stop(); - LoginButton::OnMouseReleased(event); - } - // views::ButtonListener: void ButtonPressed(Button* sender, const ui::Event& event) override { DCHECK(sender == this); - if (did_autosubmit_) - return; if (on_press_) on_press_.Run(); @@ -130,25 +99,6 @@ base::Closure on_press_; private: - void DispatchRepeatablePressEvent() { - // Start repeat timer if this was fired by the initial delay timer. - if (!repeat_timer_->IsRunning()) { - repeat_timer_->Start( - FROM_HERE, - base::TimeDelta::FromMilliseconds(kRepeatingLongPressDelayMs), - base::BindRepeating(&BasePinButton::DispatchRepeatablePressEvent, - base::Unretained(this))); - } - - did_autosubmit_ = true; - on_press_.Run(); - } - - // If true, then the button submitted from a long-press repeat. - bool did_autosubmit_ = false; - std::unique_ptr<base::Timer> delay_timer_; - std::unique_ptr<base::Timer> repeat_timer_; - DISALLOW_COPY_AND_ASSIGN(BasePinButton); }; @@ -156,7 +106,7 @@ class DigitPinButton : public BasePinButton { public: DigitPinButton(int value, const LoginPinView::OnPinKey& on_key) - : BasePinButton(base::BindRepeating(on_key, value)) { + : BasePinButton(base::Bind(on_key, value)) { set_id(GetViewIdForPinNumber(value)); const gfx::FontList& base_font_list = views::Label::GetDefaultFontList(); views::Label* label = new views::Label(GetButtonLabelForNumber(value), @@ -199,8 +149,10 @@ // A PIN button that displays backspace icon. class LoginPinView::BackspacePinButton : public BasePinButton { public: - BackspacePinButton(const base::RepeatingClosure& on_press) - : BasePinButton(on_press) { + BackspacePinButton(const base::Closure& on_press) + : BasePinButton(on_press), + delay_timer_(std::make_unique<base::OneShotTimer>()), + repeat_timer_(std::make_unique<base::RepeatingTimer>()) { SetImage(views::Button::STATE_NORMAL, gfx::CreateVectorIcon(kLockScreenBackspaceIcon, login_constants::kButtonEnabledColor)); @@ -216,7 +168,57 @@ ~BackspacePinButton() override = default; + void SetTimersForTesting(std::unique_ptr<base::Timer> delay_timer, + std::unique_ptr<base::Timer> repeat_timer) { + delay_timer_ = std::move(delay_timer); + repeat_timer_ = std::move(repeat_timer); + } + + // BasePinButton: + bool OnMousePressed(const ui::MouseEvent& event) override { + did_autosubmit_ = false; + + if (IsTriggerableEvent(event) && enabled() && + HitTestPoint(event.location())) { + delay_timer_->Start( + FROM_HERE, + base::TimeDelta::FromMilliseconds(kInitialBackspaceDelayMs), + base::Bind(&BackspacePinButton::DispatchRepeatablePressEvent, + base::Unretained(this))); + } + + return BasePinButton::OnMousePressed(event); + } + void OnMouseReleased(const ui::MouseEvent& event) override { + delay_timer_->Stop(); + repeat_timer_->Stop(); + BasePinButton::OnMouseReleased(event); + } + void ButtonPressed(Button* sender, const ui::Event& event) override { + if (did_autosubmit_) + return; + BasePinButton::ButtonPressed(sender, event); + } + private: + void DispatchRepeatablePressEvent() { + // Start repeat timer if this was fired by the initial delay timer. + if (!repeat_timer_->IsRunning()) { + repeat_timer_->Start( + FROM_HERE, + base::TimeDelta::FromMilliseconds(kRepeatingBackspaceDelayMs), + base::Bind(&BackspacePinButton::DispatchRepeatablePressEvent, + base::Unretained(this))); + } + + did_autosubmit_ = true; + on_press_.Run(); + } + + bool did_autosubmit_ = false; + std::unique_ptr<base::Timer> delay_timer_; + std::unique_ptr<base::Timer> repeat_timer_; + DISALLOW_COPY_AND_ASSIGN(BackspacePinButton); };
diff --git a/ash/system/tray/tray_background_view.cc b/ash/system/tray/tray_background_view.cc index f0eddd99..acc0811 100644 --- a/ash/system/tray/tray_background_view.cc +++ b/ash/system/tray/tray_background_view.cc
@@ -260,6 +260,19 @@ } } +void TrayBackgroundView::Layout() { + ActionableView::Layout(); + + // The tray itself expands to the right and bottom edge of the screen to make + // sure clicking on the edges brings up the popup. However, the focus border + // should be only around the container. + gfx::Rect paint_bounds(GetBackgroundBounds()); + paint_bounds.Inset(gfx::Insets(-kFocusBorderThickness)); + SetFocusPainter(views::Painter::CreateSolidFocusPainter( + kFocusBorderColor, kFocusBorderThickness, + GetLocalBounds().InsetsFrom(paint_bounds))); +} + const char* TrayBackgroundView::GetClassName() const { return kViewClassName; } @@ -380,15 +393,6 @@ void TrayBackgroundView::UpdateAfterShelfAlignmentChange() { tray_container_->UpdateAfterShelfAlignmentChange(); - - // The tray itself expands to the right and bottom edge of the screen to make - // sure clicking on the edges brings up the popup. However, the focus border - // should be only around the container. - gfx::Rect paint_bounds(GetBackgroundBounds()); - paint_bounds.Inset(gfx::Insets(-kFocusBorderThickness)); - SetFocusPainter(views::Painter::CreateSolidFocusPainter( - kFocusBorderColor, kFocusBorderThickness, - GetLocalBounds().InsetsFrom(paint_bounds))); } void TrayBackgroundView::AnchorUpdated() {
diff --git a/ash/system/tray/tray_background_view.h b/ash/system/tray/tray_background_view.h index 0fad2a3..8e61e27 100644 --- a/ash/system/tray/tray_background_view.h +++ b/ash/system/tray/tray_background_view.h
@@ -48,6 +48,7 @@ void OnGestureEvent(ui::GestureEvent* event) override; void AboutToRequestFocusFromTabTraversal(bool reverse) override; void GetAccessibleNodeData(ui::AXNodeData* node_data) override; + void Layout() override; void ChildPreferredSizeChanged(views::View* child) override; // ActionableView:
diff --git a/base/test/launcher/test_launcher.cc b/base/test/launcher/test_launcher.cc index c05d214c..4fa5412 100644 --- a/base/test/launcher/test_launcher.cc +++ b/base/test/launcher/test_launcher.cc
@@ -370,6 +370,17 @@ LOG(ERROR) << base::StringPrintf("about to process.Terminate() %x", process.Handle()); } + + // TODO(crbug.com/799268): Remove once we have debugged timed-out/hung + // test job processes. + LOG(ERROR) << "Dumping threads in process " << process.Pid(); + + CommandLine threads_cmdline(base::FilePath("/boot/bin/threads")); + threads_cmdline.AppendArg(IntToString(process.Pid())); + + LaunchOptions threads_options; + threads_options.wait = true; + LaunchProcess(threads_cmdline, threads_options); #endif // OS_FUCHSIA // Ensure that the process terminates. process.Terminate(-1, true);
diff --git a/base/win/OWNERS b/base/win/OWNERS index 25fafc3d..4593b2c 100644 --- a/base/win/OWNERS +++ b/base/win/OWNERS
@@ -1,7 +1,7 @@ +brucedawson@chromium.org grt@chromium.org jschuh@chromium.org robliao@chromium.org scottmg@chromium.org -brucedawson@chromium.org # COMPONENT: Internals>PlatformIntegration
diff --git a/build/android/gradle/generate_gradle.py b/build/android/gradle/generate_gradle.py index c8f4731..4807470 100755 --- a/build/android/gradle/generate_gradle.py +++ b/build/android/gradle/generate_gradle.py
@@ -770,7 +770,11 @@ args.canary) logging.warning('Creating project at: %s', generator.project_dir) - args.all = args.all or not args.split_projects + # Generate for "all targets" by default when not using --split-projects (too + # slow), and when no --target has been explicitly set. "all targets" means all + # java targets that are depended on by an apk or java_binary (leaf + # java_library targets will not be included). + args.all = args.all or (not args.split_projects and not args.targets) targets_from_args = set(args.targets or _DEFAULT_TARGETS) if args.extra_targets:
diff --git a/build/config/android/BUILD.gn b/build/config/android/BUILD.gn index 762faae..cac0a30a 100644 --- a/build/config/android/BUILD.gn +++ b/build/config/android/BUILD.gn
@@ -69,7 +69,7 @@ compile_api_level = 16 } else if (current_cpu == "mips64el") { # Place holder for mips64 support, not tested. - abi_target = "mips64el-linux-androideabi" + abi_target = "mips64el-linux-android" compile_api_level = 21 } else { assert(false, "Architecture not supported")
diff --git a/build/config/compiler/BUILD.gn b/build/config/compiler/BUILD.gn index 84730e8..c85dbc48 100644 --- a/build/config/compiler/BUILD.gn +++ b/build/config/compiler/BUILD.gn
@@ -1589,7 +1589,9 @@ if (is_official_build) { common_optimize_on_ldflags += [ "/OPT:REF" ] # Remove unreferenced data. - if (!use_lld) { + + # TODO(thakis): Remove is_clang here, https://crbug.com/598772 + if (!use_lld && !is_clang) { common_optimize_on_ldflags += [ # Set the number of LTCG code-gen threads to eight. The default is four. # This gives a 5-10% link speedup.
diff --git a/cc/debug/debug_colors.cc b/cc/debug/debug_colors.cc index db0fbd7..aec7ff5 100644 --- a/cc/debug/debug_colors.cc +++ b/cc/debug/debug_colors.cc
@@ -150,6 +150,22 @@ return 6; } +// Returns a color transform that shifts color toward red. +base::span<const float> +DebugColors::TintCompositedContentColorTransformMatrix() { + // The new colors are: + // new_R = R + 0.3 G + 0.3 B + // new_G = 0.7 G + // new_B = 0.7 B + // clang-format off + static constexpr float kColorTransform[] = {1.0f, 0.0f, 0.0f, 0.0f, + 0.3f, 0.7f, 0.0f, 0.0f, + 0.3f, 0.0f, 0.7f, 0.0f, + 0.0f, 0.0f, 0.0f, 1.0f}; + // clang-format on + return base::span<const float>(kColorTransform, sizeof(kColorTransform)); +} + // Compressed tile borders are blue. SkColor DebugColors::CompressedTileBorderColor() { return SkColorSetARGB(100, 20, 20, 240);
diff --git a/cc/debug/debug_colors.h b/cc/debug/debug_colors.h index cdb62dc..2d10b55 100644 --- a/cc/debug/debug_colors.h +++ b/cc/debug/debug_colors.h
@@ -5,6 +5,7 @@ #ifndef CC_DEBUG_DEBUG_COLORS_H_ #define CC_DEBUG_DEBUG_COLORS_H_ +#include "base/containers/span.h" #include "base/macros.h" #include "cc/debug/debug_export.h" #include "third_party/skia/include/core/SkColor.h" @@ -110,6 +111,8 @@ static SkColor GLCompositedTextureQuadBorderColor(int index); static int GLCompositedTextureQuadBoderWidth(); + static base::span<const float> TintCompositedContentColorTransformMatrix(); + static SkColor HUDBackgroundColor(); static SkColor HUDSeparatorLineColor(); static SkColor HUDIndicatorLineColor();
diff --git a/cc/layers/picture_layer_impl.cc b/cc/layers/picture_layer_impl.cc index c33aa1e..8602f48 100644 --- a/cc/layers/picture_layer_impl.cc +++ b/cc/layers/picture_layer_impl.cc
@@ -88,6 +88,18 @@ static_cast<int>(rb - ry)); } +// This function converts the given |device_pixels_size| to the expected size +// of content which was generated to fill it at 100%. This takes into account +// the ceil operations that occur as device pixels are converted to/from DIPs +// (content size must be a whole number of DIPs). +gfx::Size ApplyDsfAdjustment(gfx::Size device_pixels_size, float dsf) { + gfx::Size content_size_in_dips = + gfx::ScaleToCeiledSize(device_pixels_size, 1.0f / dsf); + gfx::Size content_size_in_dps = + gfx::ScaleToCeiledSize(content_size_in_dips, dsf); + return content_size_in_dps; +} + } // namespace namespace cc { @@ -895,8 +907,13 @@ // For GPU rasterization, we pick an ideal tile size using the viewport // so we don't need any settings. The current approach uses 4 tiles // to cover the viewport vertically. - int viewport_width = gpu_raster_max_texture_size_.width(); - int viewport_height = gpu_raster_max_texture_size_.height(); + + // Calculate the viewport based on |gpu_raster_max_texture_size_|, adjusting + // for ceil operations that may occur due to DSF. + gfx::Size viewport_size = ApplyDsfAdjustment( + gpu_raster_max_texture_size_, layer_tree_impl()->device_scale_factor()); + int viewport_width = viewport_size.width(); + int viewport_height = viewport_size.height(); default_tile_width = viewport_width; // Also, increase the height proportionally as the width decreases, and
diff --git a/cc/layers/picture_layer_impl_unittest.cc b/cc/layers/picture_layer_impl_unittest.cc index d2f16c18..5891196 100644 --- a/cc/layers/picture_layer_impl_unittest.cc +++ b/cc/layers/picture_layer_impl_unittest.cc
@@ -2618,6 +2618,31 @@ EXPECT_EQ(8u, NumberOfTilesRequired(active_layer()->HighResTiling())); } +TEST_F(CommitToActiveTreePictureLayerImplTest, + RequiredTilesWithGpuRasterizationAndFractionalDsf) { + host_impl()->SetHasGpuRasterizationTrigger(true); + host_impl()->CommitComplete(); + + gfx::Size viewport_size(1502, 2560); + host_impl()->SetViewportSize(viewport_size); + + float dsf = 3.5f; + gfx::Size layer_bounds = gfx::ScaleToCeiledSize(viewport_size, 1.0f / dsf); + SetupDefaultTrees(layer_bounds); + EXPECT_TRUE(host_impl()->use_gpu_rasterization()); + + SetContentsScaleOnBothLayers( + dsf /* contents_scale */, dsf /* device_scale_factor */, + 1.0f /* page_scale_factor */, 1.0f /* maximum_animation_contents_scale */, + 1.0f /* starting_animation_contents_scale */, + false /* animating_transform */); + + active_layer()->HighResTiling()->UpdateAllRequiredStateForTesting(); + + // High res tiling should have 4 tiles (1x4 tile grid). + EXPECT_EQ(4u, active_layer()->HighResTiling()->AllTilesForTesting().size()); +} + TEST_F(PictureLayerImplTest, NoTilingIfDoesNotDrawContent) { // Set up layers with tilings. SetupDefaultTrees(gfx::Size(10, 10));
diff --git a/cc/paint/paint_filter.cc b/cc/paint/paint_filter.cc index 649ce8f2..ac1be07bc 100644 --- a/cc/paint/paint_filter.cc +++ b/cc/paint/paint_filter.cc
@@ -24,6 +24,13 @@ #include "third_party/skia/include/effects/SkXfermodeImageFilter.h" namespace cc { +namespace { +bool AreFiltersEqual(const PaintFilter* one, const PaintFilter* two) { + if (!one || !two) + return !one && !two; + return *one == *two; +} +} // namespace PaintFilter::PaintFilter(Type type, const CropRect* crop_rect) : type_(type) { if (crop_rect) @@ -88,6 +95,95 @@ return "Unknown"; } +bool PaintFilter::operator==(const PaintFilter& other) const { + if (type_ != other.type_) + return false; + if (!!crop_rect_ != !!other.crop_rect_) + return false; + if (crop_rect_) { + if (crop_rect_->flags() != other.crop_rect_->flags() || + crop_rect_->rect() != other.crop_rect_->rect()) { + return false; + } + } + + switch (type_) { + case Type::kNullFilter: + return true; + case Type::kColorFilter: + return *static_cast<const ColorFilterPaintFilter*>(this) == + static_cast<const ColorFilterPaintFilter&>(other); + case Type::kBlur: + return *static_cast<const BlurPaintFilter*>(this) == + static_cast<const BlurPaintFilter&>(other); + case Type::kDropShadow: + return *static_cast<const DropShadowPaintFilter*>(this) == + static_cast<const DropShadowPaintFilter&>(other); + case Type::kMagnifier: + return *static_cast<const MagnifierPaintFilter*>(this) == + static_cast<const MagnifierPaintFilter&>(other); + case Type::kCompose: + return *static_cast<const ComposePaintFilter*>(this) == + static_cast<const ComposePaintFilter&>(other); + case Type::kAlphaThreshold: + return *static_cast<const AlphaThresholdPaintFilter*>(this) == + static_cast<const AlphaThresholdPaintFilter&>(other); + case Type::kSkImageFilter: + return *static_cast<const ImageFilterPaintFilter*>(this) == + static_cast<const ImageFilterPaintFilter&>(other); + case Type::kXfermode: + return *static_cast<const XfermodePaintFilter*>(this) == + static_cast<const XfermodePaintFilter&>(other); + case Type::kArithmetic: + return *static_cast<const ArithmeticPaintFilter*>(this) == + static_cast<const ArithmeticPaintFilter&>(other); + case Type::kMatrixConvolution: + return *static_cast<const MatrixConvolutionPaintFilter*>(this) == + static_cast<const MatrixConvolutionPaintFilter&>(other); + case Type::kDisplacementMapEffect: + return *static_cast<const DisplacementMapEffectPaintFilter*>(this) == + static_cast<const DisplacementMapEffectPaintFilter&>(other); + case Type::kImage: + return *static_cast<const ImageFilterPaintFilter*>(this) == + static_cast<const ImageFilterPaintFilter&>(other); + case Type::kPaintRecord: + return *static_cast<const RecordPaintFilter*>(this) == + static_cast<const RecordPaintFilter&>(other); + case Type::kMerge: + return *static_cast<const MergePaintFilter*>(this) == + static_cast<const MergePaintFilter&>(other); + case Type::kMorphology: + return *static_cast<const MorphologyPaintFilter*>(this) == + static_cast<const MorphologyPaintFilter&>(other); + case Type::kOffset: + return *static_cast<const OffsetPaintFilter*>(this) == + static_cast<const OffsetPaintFilter&>(other); + case Type::kTile: + return *static_cast<const TilePaintFilter*>(this) == + static_cast<const TilePaintFilter&>(other); + case Type::kTurbulence: + return *static_cast<const TurbulencePaintFilter*>(this) == + static_cast<const TurbulencePaintFilter&>(other); + case Type::kPaintFlags: + return *static_cast<const PaintFlagsPaintFilter*>(this) == + static_cast<const PaintFlagsPaintFilter&>(other); + case Type::kMatrix: + return *static_cast<const MatrixPaintFilter*>(this) == + static_cast<const MatrixPaintFilter&>(other); + case Type::kLightingDistant: + return *static_cast<const LightingDistantPaintFilter*>(this) == + static_cast<const LightingDistantPaintFilter&>(other); + case Type::kLightingPoint: + return *static_cast<const LightingPointPaintFilter*>(this) == + static_cast<const LightingPointPaintFilter&>(other); + case Type::kLightingSpot: + return *static_cast<const LightingSpotPaintFilter*>(this) == + static_cast<const LightingSpotPaintFilter&>(other); + } + NOTREACHED(); + return true; +} + ColorFilterPaintFilter::ColorFilterPaintFilter( sk_sp<SkColorFilter> color_filter, sk_sp<PaintFilter> input, @@ -102,6 +198,13 @@ ColorFilterPaintFilter::~ColorFilterPaintFilter() = default; +bool ColorFilterPaintFilter::operator==( + const ColorFilterPaintFilter& other) const { + return PaintOp::AreSkFlattenablesEqual(color_filter_.get(), + other.color_filter_.get()) && + AreFiltersEqual(input_.get(), other.input_.get()); +} + BlurPaintFilter::BlurPaintFilter(SkScalar sigma_x, SkScalar sigma_y, TileMode tile_mode, @@ -118,6 +221,13 @@ BlurPaintFilter::~BlurPaintFilter() = default; +bool BlurPaintFilter::operator==(const BlurPaintFilter& other) const { + return PaintOp::AreEqualEvenIfNaN(sigma_x_, other.sigma_x_) && + PaintOp::AreEqualEvenIfNaN(sigma_y_, other.sigma_y_) && + tile_mode_ == other.tile_mode_ && + AreFiltersEqual(input_.get(), other.input_.get()); +} + DropShadowPaintFilter::DropShadowPaintFilter(SkScalar dx, SkScalar dy, SkScalar sigma_x, @@ -141,6 +251,16 @@ DropShadowPaintFilter::~DropShadowPaintFilter() = default; +bool DropShadowPaintFilter::operator==( + const DropShadowPaintFilter& other) const { + return PaintOp::AreEqualEvenIfNaN(dx_, other.dx_) && + PaintOp::AreEqualEvenIfNaN(dy_, other.dy_) && + PaintOp::AreEqualEvenIfNaN(sigma_x_, other.sigma_x_) && + PaintOp::AreEqualEvenIfNaN(sigma_y_, other.sigma_y_) && + color_ == other.color_ && shadow_mode_ == other.shadow_mode_ && + AreFiltersEqual(input_.get(), other.input_.get()); +} + MagnifierPaintFilter::MagnifierPaintFilter(const SkRect& src_rect, SkScalar inset, sk_sp<PaintFilter> input, @@ -155,6 +275,12 @@ MagnifierPaintFilter::~MagnifierPaintFilter() = default; +bool MagnifierPaintFilter::operator==(const MagnifierPaintFilter& other) const { + return PaintOp::AreSkRectsEqual(src_rect_, other.src_rect_) && + PaintOp::AreEqualEvenIfNaN(inset_, other.inset_) && + AreFiltersEqual(input_.get(), other.input_.get()); +} + ComposePaintFilter::ComposePaintFilter(sk_sp<PaintFilter> outer, sk_sp<PaintFilter> inner) : PaintFilter(Type::kCompose, nullptr), @@ -166,6 +292,11 @@ ComposePaintFilter::~ComposePaintFilter() = default; +bool ComposePaintFilter::operator==(const ComposePaintFilter& other) const { + return AreFiltersEqual(outer_.get(), other.outer_.get()) && + AreFiltersEqual(inner_.get(), other.inner_.get()); +} + AlphaThresholdPaintFilter::AlphaThresholdPaintFilter(const SkRegion& region, SkScalar inner_min, SkScalar outer_max, @@ -182,6 +313,14 @@ AlphaThresholdPaintFilter::~AlphaThresholdPaintFilter() = default; +bool AlphaThresholdPaintFilter::operator==( + const AlphaThresholdPaintFilter& other) const { + return region_ == other.region_ && + PaintOp::AreEqualEvenIfNaN(inner_min_, other.inner_min_) && + PaintOp::AreEqualEvenIfNaN(outer_max_, other.outer_max_) && + AreFiltersEqual(input_.get(), other.input_.get()); +} + ImageFilterPaintFilter::ImageFilterPaintFilter(sk_sp<SkImageFilter> sk_filter) : PaintFilter(kType, nullptr), sk_filter_(std::move(sk_filter)) { cached_sk_filter_ = sk_filter_; @@ -189,6 +328,11 @@ ImageFilterPaintFilter::~ImageFilterPaintFilter() = default; +bool ImageFilterPaintFilter::operator==( + const ImageFilterPaintFilter& other) const { + return !!sk_filter_ == !!other.sk_filter_; +} + XfermodePaintFilter::XfermodePaintFilter(SkBlendMode blend_mode, sk_sp<PaintFilter> background, sk_sp<PaintFilter> foreground, @@ -204,6 +348,12 @@ XfermodePaintFilter::~XfermodePaintFilter() = default; +bool XfermodePaintFilter::operator==(const XfermodePaintFilter& other) const { + return blend_mode_ == other.blend_mode_ && + AreFiltersEqual(background_.get(), other.background_.get()) && + AreFiltersEqual(foreground_.get(), other.foreground_.get()); +} + ArithmeticPaintFilter::ArithmeticPaintFilter(float k1, float k2, float k3, @@ -227,6 +377,17 @@ ArithmeticPaintFilter::~ArithmeticPaintFilter() = default; +bool ArithmeticPaintFilter::operator==( + const ArithmeticPaintFilter& other) const { + return PaintOp::AreEqualEvenIfNaN(k1_, other.k1_) && + PaintOp::AreEqualEvenIfNaN(k2_, other.k2_) && + PaintOp::AreEqualEvenIfNaN(k3_, other.k3_) && + PaintOp::AreEqualEvenIfNaN(k4_, other.k4_) && + enforce_pm_color_ == other.enforce_pm_color_ && + AreFiltersEqual(background_.get(), other.background_.get()) && + AreFiltersEqual(foreground_.get(), other.foreground_.get()); +} + MatrixConvolutionPaintFilter::MatrixConvolutionPaintFilter( const SkISize& kernel_size, const SkScalar* kernel, @@ -256,6 +417,18 @@ MatrixConvolutionPaintFilter::~MatrixConvolutionPaintFilter() = default; +bool MatrixConvolutionPaintFilter::operator==( + const MatrixConvolutionPaintFilter& other) const { + return kernel_size_ == other.kernel_size_ && + kernel_.container() == other.kernel_.container() && + PaintOp::AreEqualEvenIfNaN(gain_, other.gain_) && + PaintOp::AreEqualEvenIfNaN(bias_, other.bias_) && + kernel_offset_ == other.kernel_offset_ && + tile_mode_ == other.tile_mode_ && + convolve_alpha_ == other.convolve_alpha_ && + AreFiltersEqual(input_.get(), other.input_.get()); +} + DisplacementMapEffectPaintFilter::DisplacementMapEffectPaintFilter( ChannelSelectorType channel_x, ChannelSelectorType channel_y, @@ -276,6 +449,14 @@ DisplacementMapEffectPaintFilter::~DisplacementMapEffectPaintFilter() = default; +bool DisplacementMapEffectPaintFilter::operator==( + const DisplacementMapEffectPaintFilter& other) const { + return channel_x_ == other.channel_x_ && channel_y_ == other.channel_y_ && + PaintOp::AreEqualEvenIfNaN(scale_, other.scale_) && + AreFiltersEqual(displacement_.get(), other.displacement_.get()) && + AreFiltersEqual(color_.get(), other.color_.get()); +} + ImagePaintFilter::ImagePaintFilter(PaintImage image, const SkRect& src_rect, const SkRect& dst_rect, @@ -291,6 +472,13 @@ ImagePaintFilter::~ImagePaintFilter() = default; +bool ImagePaintFilter::operator==(const ImagePaintFilter& other) const { + return !!image_ == !!other.image_ && + PaintOp::AreSkRectsEqual(src_rect_, other.src_rect_) && + PaintOp::AreSkRectsEqual(dst_rect_, other.dst_rect_) && + filter_quality_ == other.filter_quality_; +} + RecordPaintFilter::RecordPaintFilter(sk_sp<PaintRecord> record, const SkRect& record_bounds) : PaintFilter(kType, nullptr), @@ -302,6 +490,11 @@ RecordPaintFilter::~RecordPaintFilter() = default; +bool RecordPaintFilter::operator==(const RecordPaintFilter& other) const { + return !!record_ == !!other.record_ && + PaintOp::AreSkRectsEqual(record_bounds_, other.record_bounds_); +} + MergePaintFilter::MergePaintFilter(sk_sp<PaintFilter>* const filters, int count, const CropRect* crop_rect) @@ -320,6 +513,16 @@ MergePaintFilter::~MergePaintFilter() = default; +bool MergePaintFilter::operator==(const MergePaintFilter& other) const { + if (inputs_->size() != other.inputs_->size()) + return false; + for (size_t i = 0; i < inputs_->size(); ++i) { + if (!AreFiltersEqual(inputs_[i].get(), other.inputs_[i].get())) + return false; + } + return true; +} + MorphologyPaintFilter::MorphologyPaintFilter(MorphType morph_type, int radius_x, int radius_y, @@ -344,6 +547,13 @@ MorphologyPaintFilter::~MorphologyPaintFilter() = default; +bool MorphologyPaintFilter::operator==( + const MorphologyPaintFilter& other) const { + return morph_type_ == other.morph_type_ && radius_x_ == other.radius_x_ && + radius_y_ == other.radius_y_ && + AreFiltersEqual(input_.get(), other.input_.get()); +} + OffsetPaintFilter::OffsetPaintFilter(SkScalar dx, SkScalar dy, sk_sp<PaintFilter> input, @@ -358,6 +568,12 @@ OffsetPaintFilter::~OffsetPaintFilter() = default; +bool OffsetPaintFilter::operator==(const OffsetPaintFilter& other) const { + return PaintOp::AreEqualEvenIfNaN(dx_, other.dx_) && + PaintOp::AreEqualEvenIfNaN(dy_, other.dy_) && + AreFiltersEqual(input_.get(), other.input_.get()); +} + TilePaintFilter::TilePaintFilter(const SkRect& src, const SkRect& dst, sk_sp<PaintFilter> input) @@ -371,6 +587,12 @@ TilePaintFilter::~TilePaintFilter() = default; +bool TilePaintFilter::operator==(const TilePaintFilter& other) const { + return PaintOp::AreSkRectsEqual(src_, other.src_) && + PaintOp::AreSkRectsEqual(dst_, other.dst_) && + AreFiltersEqual(input_.get(), other.input_.get()); +} + TurbulencePaintFilter::TurbulencePaintFilter(TurbulenceType turbulence_type, SkScalar base_frequency_x, SkScalar base_frequency_y, @@ -406,6 +628,18 @@ TurbulencePaintFilter::~TurbulencePaintFilter() = default; +bool TurbulencePaintFilter::operator==( + const TurbulencePaintFilter& other) const { + return turbulence_type_ == other.turbulence_type_ && + PaintOp::AreEqualEvenIfNaN(base_frequency_x_, + other.base_frequency_x_) && + PaintOp::AreEqualEvenIfNaN(base_frequency_y_, + other.base_frequency_y_) && + num_octaves_ == other.num_octaves_ && + PaintOp::AreEqualEvenIfNaN(seed_, other.seed_) && + tile_size_ == other.tile_size_; +} + PaintFlagsPaintFilter::PaintFlagsPaintFilter(PaintFlags flags, const CropRect* crop_rect) : PaintFilter(kType, crop_rect), flags_(std::move(flags)) { @@ -414,6 +648,11 @@ PaintFlagsPaintFilter::~PaintFlagsPaintFilter() = default; +bool PaintFlagsPaintFilter::operator==( + const PaintFlagsPaintFilter& other) const { + return flags_ == other.flags_; +} + MatrixPaintFilter::MatrixPaintFilter(const SkMatrix& matrix, SkFilterQuality filter_quality, sk_sp<PaintFilter> input) @@ -427,6 +666,12 @@ MatrixPaintFilter::~MatrixPaintFilter() = default; +bool MatrixPaintFilter::operator==(const MatrixPaintFilter& other) const { + return PaintOp::AreSkMatricesEqual(matrix_, other.matrix_) && + filter_quality_ == other.filter_quality_ && + AreFiltersEqual(input_.get(), other.input_.get()); +} + LightingDistantPaintFilter::LightingDistantPaintFilter( LightingType lighting_type, const SkPoint3& direction, @@ -460,6 +705,17 @@ LightingDistantPaintFilter::~LightingDistantPaintFilter() = default; +bool LightingDistantPaintFilter::operator==( + const LightingDistantPaintFilter& other) const { + return lighting_type_ == other.lighting_type_ && + PaintOp::AreSkPoint3sEqual(direction_, other.direction_) && + light_color_ == other.light_color_ && + PaintOp::AreEqualEvenIfNaN(surface_scale_, other.surface_scale_) && + PaintOp::AreEqualEvenIfNaN(kconstant_, other.kconstant_) && + PaintOp::AreEqualEvenIfNaN(shininess_, other.shininess_) && + AreFiltersEqual(input_.get(), other.input_.get()); +} + LightingPointPaintFilter::LightingPointPaintFilter(LightingType lighting_type, const SkPoint3& location, SkColor light_color, @@ -492,6 +748,17 @@ LightingPointPaintFilter::~LightingPointPaintFilter() = default; +bool LightingPointPaintFilter::operator==( + const LightingPointPaintFilter& other) const { + return lighting_type_ == other.lighting_type_ && + PaintOp::AreSkPoint3sEqual(location_, other.location_) && + light_color_ == other.light_color_ && + PaintOp::AreEqualEvenIfNaN(surface_scale_, other.surface_scale_) && + PaintOp::AreEqualEvenIfNaN(kconstant_, other.kconstant_) && + PaintOp::AreEqualEvenIfNaN(shininess_, other.shininess_) && + AreFiltersEqual(input_.get(), other.input_.get()); +} + LightingSpotPaintFilter::LightingSpotPaintFilter(LightingType lighting_type, const SkPoint3& location, const SkPoint3& target, @@ -531,4 +798,19 @@ LightingSpotPaintFilter::~LightingSpotPaintFilter() = default; +bool LightingSpotPaintFilter::operator==( + const LightingSpotPaintFilter& other) const { + return lighting_type_ == other.lighting_type_ && + PaintOp::AreSkPoint3sEqual(location_, other.location_) && + PaintOp::AreSkPoint3sEqual(target_, other.target_) && + PaintOp::AreEqualEvenIfNaN(specular_exponent_, + other.specular_exponent_) && + PaintOp::AreEqualEvenIfNaN(cutoff_angle_, other.cutoff_angle_) && + light_color_ == other.light_color_ && + PaintOp::AreEqualEvenIfNaN(surface_scale_, other.surface_scale_) && + PaintOp::AreEqualEvenIfNaN(kconstant_, other.kconstant_) && + PaintOp::AreEqualEvenIfNaN(shininess_, other.shininess_) && + AreFiltersEqual(input_.get(), other.input_.get()); +} + } // namespace cc
diff --git a/cc/paint/paint_filter.h b/cc/paint/paint_filter.h index c815bfc..4cf086a6 100644 --- a/cc/paint/paint_filter.h +++ b/cc/paint/paint_filter.h
@@ -108,6 +108,15 @@ return crop_rect_ ? &*crop_rect_ : nullptr; } + // Note that this operation is potentially slow. It also only compares things + // that are easy to compare. As an example, it doesn't compare equality of + // images, rather only its existence. This is meant to be used only by tests + // and fuzzers. + // TODO(vmpstr): Rename this and places that its used to something like + // EqualsForTesting. + bool operator==(const PaintFilter& other) const; + bool operator!=(const PaintFilter& other) const { return !(*this == other); } + protected: PaintFilter(Type type, const CropRect* crop_rect); @@ -152,6 +161,8 @@ const sk_sp<SkColorFilter>& color_filter() const { return color_filter_; } const sk_sp<PaintFilter>& input() const { return input_; } + bool operator==(const ColorFilterPaintFilter& other) const; + private: sk_sp<SkColorFilter> color_filter_; sk_sp<PaintFilter> input_; @@ -174,6 +185,8 @@ SkScalar sigma_y() const { return sigma_y_; } TileMode tile_mode() const { return tile_mode_; } + bool operator==(const BlurPaintFilter& other) const; + private: SkScalar sigma_x_; SkScalar sigma_y_; @@ -201,7 +214,9 @@ SkScalar sigma_y() const { return sigma_y_; } SkColor color() const { return color_; } ShadowMode shadow_mode() const { return shadow_mode_; } - const sk_sp<PaintFilter> input() const { return input_; } + const sk_sp<PaintFilter>& input() const { return input_; } + + bool operator==(const DropShadowPaintFilter& other) const; private: SkScalar dx_; @@ -222,6 +237,12 @@ const CropRect* crop_rect = nullptr); ~MagnifierPaintFilter() override; + const SkRect& src_rect() const { return src_rect_; } + SkScalar inset() const { return inset_; } + const sk_sp<PaintFilter>& input() const { return input_; } + + bool operator==(const MagnifierPaintFilter& other) const; + private: SkRect src_rect_; SkScalar inset_; @@ -237,6 +258,8 @@ const sk_sp<PaintFilter>& outer() const { return outer_; } const sk_sp<PaintFilter>& inner() const { return inner_; } + bool operator==(const ComposePaintFilter& other) const; + private: sk_sp<PaintFilter> outer_; sk_sp<PaintFilter> inner_; @@ -252,6 +275,13 @@ const CropRect* crop_rect = nullptr); ~AlphaThresholdPaintFilter() override; + const SkRegion& region() const { return region_; } + SkScalar inner_min() const { return inner_min_; } + SkScalar outer_max() const { return outer_max_; } + const sk_sp<PaintFilter>& input() const { return input_; } + + bool operator==(const AlphaThresholdPaintFilter& other) const; + private: SkRegion region_; SkScalar inner_min_; @@ -264,6 +294,8 @@ static constexpr Type kType = Type::kSkImageFilter; const SkImageFilter* sk_filter() const { return sk_filter_.get(); } + bool operator==(const ImageFilterPaintFilter& other) const; + private: // For cross-process transport of FilterOperations. To be removed once // PaintFilters can be serialized directly. See crbug.com/777636. @@ -290,6 +322,8 @@ const sk_sp<PaintFilter>& background() const { return background_; } const sk_sp<PaintFilter>& foreground() const { return foreground_; } + bool operator==(const XfermodePaintFilter& other) const; + private: SkBlendMode blend_mode_; sk_sp<PaintFilter> background_; @@ -306,7 +340,7 @@ bool enforce_pm_color, sk_sp<PaintFilter> background, sk_sp<PaintFilter> foreground, - const CropRect* crop_rect); + const CropRect* crop_rect = nullptr); ~ArithmeticPaintFilter() override; float k1() const { return k1_; } @@ -314,8 +348,10 @@ float k3() const { return k3_; } float k4() const { return k4_; } bool enforce_pm_color() const { return enforce_pm_color_; } - const sk_sp<PaintFilter> background() const { return background_; } - const sk_sp<PaintFilter> foreground() const { return foreground_; } + const sk_sp<PaintFilter>& background() const { return background_; } + const sk_sp<PaintFilter>& foreground() const { return foreground_; } + + bool operator==(const ArithmeticPaintFilter& other) const; private: float k1_; @@ -342,6 +378,17 @@ const CropRect* crop_rect = nullptr); ~MatrixConvolutionPaintFilter() override; + const SkISize& kernel_size() const { return kernel_size_; } + SkScalar kernel_at(size_t i) const { return kernel_[i]; } + SkScalar gain() const { return gain_; } + SkScalar bias() const { return bias_; } + SkIPoint kernel_offset() const { return kernel_offset_; } + TileMode tile_mode() const { return tile_mode_; } + bool convolve_alpha() const { return convolve_alpha_; } + const sk_sp<PaintFilter>& input() const { return input_; } + + bool operator==(const MatrixConvolutionPaintFilter& other) const; + private: SkISize kernel_size_; base::StackVector<SkScalar, 3> kernel_; @@ -366,6 +413,14 @@ const CropRect* crop_rect = nullptr); ~DisplacementMapEffectPaintFilter() override; + ChannelSelectorType channel_x() const { return channel_x_; } + ChannelSelectorType channel_y() const { return channel_y_; } + SkScalar scale() const { return scale_; } + const sk_sp<PaintFilter>& displacement() const { return displacement_; } + const sk_sp<PaintFilter>& color() const { return color_; } + + bool operator==(const DisplacementMapEffectPaintFilter& other) const; + private: ChannelSelectorType channel_x_; ChannelSelectorType channel_y_; @@ -383,6 +438,13 @@ SkFilterQuality filter_quality); ~ImagePaintFilter() override; + const PaintImage& image() const { return image_; } + const SkRect& src_rect() const { return src_rect_; } + const SkRect& dst_rect() const { return dst_rect_; } + SkFilterQuality filter_quality() const { return filter_quality_; } + + bool operator==(const ImagePaintFilter& other) const; + private: PaintImage image_; SkRect src_rect_; @@ -399,6 +461,8 @@ const sk_sp<PaintRecord>& record() const { return record_; } SkRect record_bounds() const { return record_bounds_; } + bool operator==(const RecordPaintFilter& other) const; + private: sk_sp<PaintRecord> record_; SkRect record_bounds_; @@ -418,6 +482,8 @@ return inputs_[i].get(); } + bool operator==(const MergePaintFilter& other) const; + private: base::StackVector<sk_sp<PaintFilter>, 2> inputs_; }; @@ -438,6 +504,8 @@ int radius_y() const { return radius_y_; } const sk_sp<PaintFilter>& input() const { return input_; } + bool operator==(const MorphologyPaintFilter& other) const; + private: MorphType morph_type_; int radius_x_; @@ -456,7 +524,9 @@ SkScalar dx() const { return dx_; } SkScalar dy() const { return dy_; } - const sk_sp<PaintFilter> input() const { return input_; } + const sk_sp<PaintFilter>& input() const { return input_; } + + bool operator==(const OffsetPaintFilter& other) const; private: SkScalar dx_; @@ -472,6 +542,12 @@ sk_sp<PaintFilter> input); ~TilePaintFilter() override; + const SkRect& src() const { return src_; } + const SkRect& dst() const { return dst_; } + const sk_sp<PaintFilter>& input() const { return input_; } + + bool operator==(const TilePaintFilter& other) const; + private: SkRect src_; SkRect dst_; @@ -502,6 +578,8 @@ SkScalar seed() const { return seed_; } SkISize tile_size() const { return tile_size_; } + bool operator==(const TurbulencePaintFilter& other) const; + private: TurbulenceType turbulence_type_; SkScalar base_frequency_x_; @@ -518,6 +596,10 @@ const CropRect* crop_rect = nullptr); ~PaintFlagsPaintFilter() override; + const PaintFlags& flags() const { return flags_; } + + bool operator==(const PaintFlagsPaintFilter& other) const; + private: PaintFlags flags_; }; @@ -534,6 +616,8 @@ SkFilterQuality filter_quality() const { return filter_quality_; } const sk_sp<PaintFilter>& input() const { return input_; } + bool operator==(const MatrixPaintFilter& other) const; + private: SkMatrix matrix_; SkFilterQuality filter_quality_; @@ -562,7 +646,9 @@ SkScalar surface_scale() const { return surface_scale_; } SkScalar kconstant() const { return kconstant_; } SkScalar shininess() const { return shininess_; } - const sk_sp<PaintFilter> input() const { return input_; } + const sk_sp<PaintFilter>& input() const { return input_; } + + bool operator==(const LightingDistantPaintFilter& other) const; private: LightingType lighting_type_; @@ -598,6 +684,8 @@ SkScalar shininess() const { return shininess_; } const sk_sp<PaintFilter>& input() const { return input_; } + bool operator==(const LightingPointPaintFilter& other) const; + private: LightingType lighting_type_; SkPoint3 location_; @@ -638,6 +726,8 @@ SkScalar shininess() const { return shininess_; } const sk_sp<PaintFilter>& input() const { return input_; } + bool operator==(const LightingSpotPaintFilter& other) const; + private: LightingType lighting_type_; SkPoint3 location_;
diff --git a/cc/paint/paint_flags.cc b/cc/paint/paint_flags.cc index 5dd4089..a08298b 100644 --- a/cc/paint/paint_flags.cc +++ b/cc/paint/paint_flags.cc
@@ -6,7 +6,6 @@ #include "cc/paint/paint_filter.h" #include "cc/paint/paint_op_buffer.h" -#include "third_party/skia/include/core/SkFlattenableSerialization.h" namespace { @@ -141,16 +140,6 @@ return PaintOp::IsValidPaintFlagsSkBlendMode(getBlendMode()); } -static bool AreFlattenablesEqual(SkFlattenable* left, SkFlattenable* right) { - sk_sp<SkData> left_data(SkValidatingSerializeFlattenable(left)); - sk_sp<SkData> right_data(SkValidatingSerializeFlattenable(right)); - if (left_data->size() != right_data->size()) - return false; - if (!left_data->equals(right_data.get())) - return false; - return true; -} - bool PaintFlags::operator==(const PaintFlags& other) const { // Can't just ToSkPaint and operator== here as SkPaint does pointer // comparisons on all the ref'd skia objects on the SkPaint, which @@ -179,17 +168,27 @@ return false; // TODO(enne): compare typeface too - if (!AreFlattenablesEqual(getPathEffect().get(), other.getPathEffect().get())) + if (!PaintOp::AreSkFlattenablesEqual(getPathEffect().get(), + other.getPathEffect().get())) { return false; - if (!AreFlattenablesEqual(getMaskFilter().get(), other.getMaskFilter().get())) + } + if (!PaintOp::AreSkFlattenablesEqual(getMaskFilter().get(), + other.getMaskFilter().get())) { return false; - if (!AreFlattenablesEqual(getColorFilter().get(), - other.getColorFilter().get())) + } + if (!PaintOp::AreSkFlattenablesEqual(getColorFilter().get(), + other.getColorFilter().get())) { return false; - if (!AreFlattenablesEqual(getLooper().get(), other.getLooper().get())) + } + if (!PaintOp::AreSkFlattenablesEqual(getLooper().get(), + other.getLooper().get())) { return false; + } - // TODO(khushalsagar): Add filter comparison when adding serialization for it. + if (!getImageFilter() != !other.getImageFilter()) + return false; + if (getImageFilter() && *getImageFilter() != *other.getImageFilter()) + return false; if (!getShader() != !other.getShader()) return false;
diff --git a/cc/paint/paint_op_buffer.cc b/cc/paint/paint_op_buffer.cc index be31f65..ef7fb72c1 100644 --- a/cc/paint/paint_op_buffer.cc +++ b/cc/paint/paint_op_buffer.cc
@@ -15,6 +15,7 @@ #include "cc/paint/scoped_raster_flags.h" #include "third_party/skia/include/core/SkAnnotation.h" #include "third_party/skia/include/core/SkCanvas.h" +#include "third_party/skia/include/core/SkFlattenableSerialization.h" #include "third_party/skia/include/core/SkRegion.h" #include "third_party/skia/include/core/SkSerialProcs.h" @@ -1284,6 +1285,17 @@ } // static +bool PaintOp::AreSkPoint3sEqual(const SkPoint3& left, const SkPoint3& right) { + if (!AreEqualEvenIfNaN(left.fX, right.fX)) + return false; + if (!AreEqualEvenIfNaN(left.fY, right.fY)) + return false; + if (!AreEqualEvenIfNaN(left.fZ, right.fZ)) + return false; + return true; +} + +// static bool PaintOp::AreSkRectsEqual(const SkRect& left, const SkRect& right) { if (!AreEqualEvenIfNaN(left.fLeft, right.fLeft)) return false; @@ -1327,6 +1339,21 @@ return true; } +// static +bool PaintOp::AreSkFlattenablesEqual(SkFlattenable* left, + SkFlattenable* right) { + if (!right || !left) + return !right && !left; + + sk_sp<SkData> left_data(SkValidatingSerializeFlattenable(left)); + sk_sp<SkData> right_data(SkValidatingSerializeFlattenable(right)); + if (left_data->size() != right_data->size()) + return false; + if (!left_data->equals(right_data.get())) + return false; + return true; +} + bool AnnotateOp::AreEqual(const PaintOp* base_left, const PaintOp* base_right) { auto* left = static_cast<const AnnotateOp*>(base_left); auto* right = static_cast<const AnnotateOp*>(base_right);
diff --git a/cc/paint/paint_op_buffer.h b/cc/paint/paint_op_buffer.h index 619e9b89..120ab6ba 100644 --- a/cc/paint/paint_op_buffer.h +++ b/cc/paint/paint_op_buffer.h
@@ -225,9 +225,11 @@ return left == right; } static bool AreSkPointsEqual(const SkPoint& left, const SkPoint& right); + static bool AreSkPoint3sEqual(const SkPoint3& left, const SkPoint3& right); static bool AreSkRectsEqual(const SkRect& left, const SkRect& right); static bool AreSkRRectsEqual(const SkRRect& left, const SkRRect& right); static bool AreSkMatricesEqual(const SkMatrix& left, const SkMatrix& right); + static bool AreSkFlattenablesEqual(SkFlattenable* left, SkFlattenable* right); static constexpr bool kIsDrawOp = false; static constexpr bool kHasPaintFlags = false;
diff --git a/cc/paint/paint_op_buffer_unittest.cc b/cc/paint/paint_op_buffer_unittest.cc index 2eac177..ef7c27d 100644 --- a/cc/paint/paint_op_buffer_unittest.cc +++ b/cc/paint/paint_op_buffer_unittest.cc
@@ -2807,4 +2807,99 @@ buffer.Playback(&canvas, &image_provider); } +TEST(PaintOpBufferTest, FilterSerialization) { + SkScalar scalars[9] = {1.f, 2.f, 3.f, 4.f, 5.f, 6.f, 7.f, 8.f, 9.f}; + std::vector<sk_sp<PaintFilter>> filters = { + sk_sp<PaintFilter>{new ColorFilterPaintFilter( + SkColorFilter::MakeLinearToSRGBGamma(), nullptr)}, + sk_sp<PaintFilter>{new BlurPaintFilter( + 0.5f, 0.3f, SkBlurImageFilter::kRepeat_TileMode, nullptr)}, + sk_sp<PaintFilter>{new DropShadowPaintFilter( + 5.f, 10.f, 0.1f, 0.3f, SK_ColorBLUE, + SkDropShadowImageFilter::kDrawShadowOnly_ShadowMode, nullptr)}, + sk_sp<PaintFilter>{new MagnifierPaintFilter(SkRect::MakeXYWH(5, 6, 7, 8), + 10.5f, nullptr)}, + sk_sp<PaintFilter>{new AlphaThresholdPaintFilter( + SkRegion(SkIRect::MakeXYWH(0, 0, 100, 200)), 10.f, 20.f, nullptr)}, + sk_sp<PaintFilter>{new MatrixConvolutionPaintFilter( + SkISize::Make(3, 3), scalars, 30.f, 123.f, SkIPoint::Make(0, 0), + SkMatrixConvolutionImageFilter::kClampToBlack_TileMode, true, + nullptr)}, + sk_sp<PaintFilter>{ + new RecordPaintFilter(sk_sp<PaintRecord>{new PaintRecord}, + SkRect::MakeXYWH(10, 15, 20, 25))}, + sk_sp<PaintFilter>{new MorphologyPaintFilter( + MorphologyPaintFilter::MorphType::kErode, 15, 30, nullptr)}, + sk_sp<PaintFilter>{new OffsetPaintFilter(-1.f, -2.f, nullptr)}, + sk_sp<PaintFilter>{new TilePaintFilter( + SkRect::MakeXYWH(1, 2, 3, 4), SkRect::MakeXYWH(4, 3, 2, 1), nullptr)}, + sk_sp<PaintFilter>{new TurbulencePaintFilter( + TurbulencePaintFilter::TurbulenceType::kFractalNoise, 3.3f, 4.4f, 2, + 123, nullptr)}, + sk_sp<PaintFilter>{ + new MatrixPaintFilter(SkMatrix::I(), kHigh_SkFilterQuality, nullptr)}, + sk_sp<PaintFilter>{new LightingDistantPaintFilter( + PaintFilter::LightingType::kSpecular, SkPoint3::Make(1, 2, 3), + SK_ColorCYAN, 1.1f, 2.2f, 3.3f, nullptr)}, + sk_sp<PaintFilter>{new LightingPointPaintFilter( + PaintFilter::LightingType::kDiffuse, SkPoint3::Make(2, 3, 4), + SK_ColorRED, 1.2f, 3.4f, 5.6f, nullptr)}, + sk_sp<PaintFilter>{new LightingSpotPaintFilter( + PaintFilter::LightingType::kSpecular, SkPoint3::Make(100, 200, 300), + SkPoint3::Make(400, 500, 600), 1, 2, SK_ColorMAGENTA, 3, 4, 5, + nullptr)}}; + + filters.emplace_back(new ComposePaintFilter(filters[0], filters[1])); + filters.emplace_back( + new XfermodePaintFilter(SkBlendMode::kDst, filters[2], filters[3])); + filters.emplace_back(new ArithmeticPaintFilter( + 1.1f, 2.2f, 3.3f, 4.4f, false, filters[4], filters[5], nullptr)); + filters.emplace_back(new DisplacementMapEffectPaintFilter( + SkDisplacementMapEffect::kR_ChannelSelectorType, + SkDisplacementMapEffect::kG_ChannelSelectorType, 10, filters[6], + filters[7])); + filters.emplace_back(new MergePaintFilter(filters.data(), filters.size())); + + std::unique_ptr<char, base::AlignedFreeDeleter> memory( + static_cast<char*>(base::AlignedAlloc(PaintOpBuffer::kInitialBufferSize, + PaintOpBuffer::PaintOpAlign))); + TestOptionsProvider options_proivder; + PaintOpBufferSerializer::Preamble preamble; + for (size_t i = 0; i < filters.size(); ++i) { + SCOPED_TRACE(i); + auto& filter = filters[i]; + + PaintFlags flags; + flags.setImageFilter(filter); + PaintOpBuffer buffer; + buffer.push<DrawRectOp>(SkRect::MakeXYWH(1, 2, 3, 4), flags); + + SimpleBufferSerializer serializer(memory.get(), + PaintOpBuffer::kInitialBufferSize, + options_proivder.image_provider(), + options_proivder.transfer_cache_helper()); + serializer.Serialize(&buffer, nullptr, preamble); + ASSERT_TRUE(serializer.valid()); + ASSERT_GT(serializer.written(), 0u); + + auto deserialized_buffer = + PaintOpBuffer::MakeFromMemory(memory.get(), serializer.written(), + options_proivder.deserialize_options()); + PaintOpBuffer::Iterator it(deserialized_buffer.get()); + bool rect_op_found = false; + for (auto* op : it) { + // There may be various ops serialized as a part of the preamble, but + // we're only really looking for the draw rect op. + if (op->GetType() != PaintOpType::DrawRect) + continue; + EXPECT_FALSE(rect_op_found); + rect_op_found = true; + auto* rect_op = static_cast<DrawRectOp*>(op); + EXPECT_FLOAT_RECT_EQ(rect_op->rect, SkRect::MakeXYWH(1, 2, 3, 4)); + EXPECT_TRUE(*filter == *rect_op->flags.getImageFilter()); + } + EXPECT_TRUE(rect_op_found); + } +} + } // namespace cc
diff --git a/cc/paint/paint_op_reader.cc b/cc/paint/paint_op_reader.cc index b2e1bec..3d00071 100644 --- a/cc/paint/paint_op_reader.cc +++ b/cc/paint/paint_op_reader.cc
@@ -25,6 +25,8 @@ // If we have more than this many colors, abort deserialization. const size_t kMaxShaderColorsSupported = 10000; const size_t kMaxMergeFilterCount = 10000; +const long kMaxKernelSize = 1000; +const size_t kMaxRegionSize = 1000; struct TypefacesCatalog { TransferCacheDeserializeHelper* transfer_cache; @@ -483,6 +485,7 @@ crop_rect.emplace(rect, flags); } + AlignMemory(4); switch (type) { case PaintFilter::Type::kNullFilter: NOTREACHED(); @@ -565,7 +568,6 @@ sk_sp<SkColorFilter> color_filter; sk_sp<PaintFilter> input; - AlignMemory(4); ReadFlattenable(&color_filter); Read(&input); if (!valid_) @@ -626,7 +628,17 @@ void PaintOpReader::ReadMagnifierPaintFilter( sk_sp<PaintFilter>* filter, const base::Optional<PaintFilter::CropRect>& crop_rect) { - // TODO(vmpstr): Implement this. + SkRect src_rect = SkRect::MakeEmpty(); + SkScalar inset = 0.f; + sk_sp<PaintFilter> input; + + ReadSimple(&src_rect); + ReadSimple(&inset); + Read(&input); + if (!valid_) + return; + filter->reset(new MagnifierPaintFilter(src_rect, inset, std::move(input), + crop_rect ? &*crop_rect : nullptr)); } void PaintOpReader::ReadComposePaintFilter( @@ -645,7 +657,29 @@ void PaintOpReader::ReadAlphaThresholdPaintFilter( sk_sp<PaintFilter>* filter, const base::Optional<PaintFilter::CropRect>& crop_rect) { - // TODO(vmpstr): Implement this. + size_t region_size = 0; + SkScalar inner_min = 0.f; + SkScalar outer_max = 0.f; + sk_sp<PaintFilter> input; + ReadSimple(®ion_size); + if (region_size > kMaxRegionSize) + SetInvalid(); + if (!valid_) + return; + SkRegion region; + for (size_t i = 0; i < region_size; ++i) { + SkIRect rect; + ReadSimple(&rect); + region.op(rect, SkRegion::kUnion_Op); + } + ReadSimple(&inner_min); + ReadSimple(&outer_max); + Read(&input); + if (!valid_) + return; + filter->reset(new AlphaThresholdPaintFilter( + region, inner_min, outer_max, std::move(input), + crop_rect ? &*crop_rect : nullptr)); } void PaintOpReader::ReadImageFilterPaintFilter( @@ -703,13 +737,75 @@ void PaintOpReader::ReadMatrixConvolutionPaintFilter( sk_sp<PaintFilter>* filter, const base::Optional<PaintFilter::CropRect>& crop_rect) { - // TODO(vmpstr): Implement this. + SkISize kernel_size = SkISize::MakeEmpty(); + SkScalar gain = 0.f; + SkScalar bias = 0.f; + SkIPoint kernel_offset = SkIPoint::Make(0, 0); + uint32_t tile_mode_int = 0; + bool convolve_alpha = false; + sk_sp<PaintFilter> input; + + ReadSimple(&kernel_size); + if (!valid_) + return; + auto size = sk_64_mul(kernel_size.width(), kernel_size.height()); + if (size > kMaxKernelSize) { + SetInvalid(); + return; + } + std::vector<SkScalar> kernel(size); + for (long i = 0; i < size; ++i) + ReadSimple(&kernel[i]); + ReadSimple(&gain); + ReadSimple(&bias); + ReadSimple(&kernel_offset); + ReadSimple(&tile_mode_int); + ReadSimple(&convolve_alpha); + Read(&input); + if (tile_mode_int > SkMatrixConvolutionImageFilter::kMax_TileMode) + SetInvalid(); + if (!valid_) + return; + MatrixConvolutionPaintFilter::TileMode tile_mode = + static_cast<MatrixConvolutionPaintFilter::TileMode>(tile_mode_int); + filter->reset(new MatrixConvolutionPaintFilter( + kernel_size, kernel.data(), gain, bias, kernel_offset, tile_mode, + convolve_alpha, std::move(input), crop_rect ? &*crop_rect : nullptr)); } void PaintOpReader::ReadDisplacementMapEffectPaintFilter( sk_sp<PaintFilter>* filter, const base::Optional<PaintFilter::CropRect>& crop_rect) { - // TODO(vmpstr): Implement this. + // Unknown, R, G, B, A: max type is 4. + static const int kMaxChannelSelectorType = 4; + + uint32_t channel_x_int = 0; + uint32_t channel_y_int = 0; + SkScalar scale = 0.f; + sk_sp<PaintFilter> displacement; + sk_sp<PaintFilter> color; + + ReadSimple(&channel_x_int); + ReadSimple(&channel_y_int); + ReadSimple(&scale); + Read(&displacement); + Read(&color); + + if (channel_x_int > kMaxChannelSelectorType || + channel_y_int > kMaxChannelSelectorType) { + SetInvalid(); + } + if (!valid_) + return; + DisplacementMapEffectPaintFilter::ChannelSelectorType channel_x = + static_cast<DisplacementMapEffectPaintFilter::ChannelSelectorType>( + channel_x_int); + DisplacementMapEffectPaintFilter::ChannelSelectorType channel_y = + static_cast<DisplacementMapEffectPaintFilter::ChannelSelectorType>( + channel_y_int); + filter->reset(new DisplacementMapEffectPaintFilter( + channel_x, channel_y, scale, std::move(displacement), std::move(color), + crop_rect ? &*crop_rect : nullptr)); } void PaintOpReader::ReadImagePaintFilter( @@ -792,7 +888,16 @@ void PaintOpReader::ReadTilePaintFilter( sk_sp<PaintFilter>* filter, const base::Optional<PaintFilter::CropRect>& crop_rect) { - // TODO(vmpstr): Implement this. + SkRect src = SkRect::MakeEmpty(); + SkRect dst = SkRect::MakeEmpty(); + sk_sp<PaintFilter> input; + + ReadSimple(&src); + ReadSimple(&dst); + Read(&input); + if (!valid_) + return; + filter->reset(new TilePaintFilter(src, dst, std::move(input))); } void PaintOpReader::ReadTurbulencePaintFilter( @@ -828,7 +933,13 @@ void PaintOpReader::ReadPaintFlagsPaintFilter( sk_sp<PaintFilter>* filter, const base::Optional<PaintFilter::CropRect>& crop_rect) { - // TODO(vmpstr): Implement this. + AlignMemory(4); + PaintFlags flags; + Read(&flags); + if (!valid_) + return; + filter->reset( + new PaintFlagsPaintFilter(flags, crop_rect ? &*crop_rect : nullptr)); } void PaintOpReader::ReadMatrixPaintFilter(
diff --git a/cc/paint/paint_op_writer.cc b/cc/paint/paint_op_writer.cc index 62c8b03..44dff60 100644 --- a/cc/paint/paint_op_writer.cc +++ b/cc/paint/paint_op_writer.cc
@@ -283,6 +283,7 @@ if (!valid_) return; + AlignMemory(4); switch (filter->type()) { case PaintFilter::Type::kNullFilter: NOTREACHED(); @@ -360,7 +361,6 @@ } void PaintOpWriter::Write(const ColorFilterPaintFilter& filter) { - AlignMemory(4); WriteFlattenable(filter.color_filter().get()); Write(filter.input().get()); } @@ -383,7 +383,9 @@ } void PaintOpWriter::Write(const MagnifierPaintFilter& filter) { - // TODO(vmpstr): Implement this. + WriteSimple(filter.src_rect()); + WriteSimple(filter.inset()); + Write(filter.input().get()); } void PaintOpWriter::Write(const ComposePaintFilter& filter) { @@ -392,7 +394,15 @@ } void PaintOpWriter::Write(const AlphaThresholdPaintFilter& filter) { - // TODO(vmpstr): Implement this. + std::vector<SkIRect> region; + for (SkRegion::Iterator it(filter.region()); !it.done(); it.next()) + region.push_back(it.rect()); + WriteSimple(static_cast<size_t>(region.size())); + for (auto& rect : region) + WriteSimple(rect); + WriteSimple(filter.inner_min()); + WriteSimple(filter.outer_max()); + Write(filter.input().get()); } void PaintOpWriter::Write(const ImageFilterPaintFilter& filter) { @@ -416,11 +426,25 @@ } void PaintOpWriter::Write(const MatrixConvolutionPaintFilter& filter) { - // TODO(vmpstr): Implement this. + WriteSimple(filter.kernel_size()); + auto size = + sk_64_mul(filter.kernel_size().width(), filter.kernel_size().height()); + for (long i = 0; i < size; ++i) + WriteSimple(filter.kernel_at(i)); + WriteSimple(filter.gain()); + WriteSimple(filter.bias()); + WriteSimple(filter.kernel_offset()); + WriteSimple(static_cast<uint32_t>(filter.tile_mode())); + WriteSimple(filter.convolve_alpha()); + Write(filter.input().get()); } void PaintOpWriter::Write(const DisplacementMapEffectPaintFilter& filter) { - // TODO(vmpstr): Implement this. + WriteSimple(static_cast<uint32_t>(filter.channel_x())); + WriteSimple(static_cast<uint32_t>(filter.channel_y())); + WriteSimple(filter.scale()); + Write(filter.displacement().get()); + Write(filter.color().get()); } void PaintOpWriter::Write(const ImagePaintFilter& filter) { @@ -452,7 +476,9 @@ } void PaintOpWriter::Write(const TilePaintFilter& filter) { - // TODO(vmpstr): Implement this. + WriteSimple(filter.src()); + WriteSimple(filter.dst()); + Write(filter.input().get()); } void PaintOpWriter::Write(const TurbulencePaintFilter& filter) { @@ -465,7 +491,7 @@ } void PaintOpWriter::Write(const PaintFlagsPaintFilter& filter) { - // TODO(vmpstr): Implement this. + Write(filter.flags()); } void PaintOpWriter::Write(const MatrixPaintFilter& filter) {
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/ChromeActivity.java b/chrome/android/java/src/org/chromium/chrome/browser/ChromeActivity.java index 926b79b9..fd3f3aaf 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/ChromeActivity.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/ChromeActivity.java
@@ -147,6 +147,7 @@ import org.chromium.content.browser.ContentViewCore; import org.chromium.content.common.ContentSwitches; import org.chromium.content_public.browser.LoadUrlParams; +import org.chromium.content_public.browser.SelectionPopupController; import org.chromium.content_public.browser.WebContents; import org.chromium.policy.CombinedPolicyProvider; import org.chromium.policy.CombinedPolicyProvider.PolicyChangeListener; @@ -1758,9 +1759,9 @@ if (layoutManager != null && layoutManager.onBackPressed()) return; } - ContentViewCore contentViewCore = getContentViewCore(); - if (contentViewCore != null && contentViewCore.isSelectActionBarShowing()) { - contentViewCore.clearSelection(); + SelectionPopupController controller = getSelectionPopupController(); + if (controller != null && controller.isSelectActionBarShowing()) { + controller.clearSelection(); return; } @@ -1789,6 +1790,17 @@ return tab.getContentViewCore(); } + private WebContents getWebContents() { + Tab tab = getActivityTab(); + if (tab == null) return null; + return tab.getWebContents(); + } + + private SelectionPopupController getSelectionPopupController() { + WebContents webContents = getWebContents(); + return webContents != null ? SelectionPopupController.fromWebContents(webContents) : null; + } + @Override public void createContextualSearchTab(String searchUrl) { Tab currentTab = getActivityTab();
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/bookmarks/BookmarkManager.java b/chrome/android/java/src/org/chromium/chrome/browser/bookmarks/BookmarkManager.java index dacb0c1..d8fd4173 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/bookmarks/BookmarkManager.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/bookmarks/BookmarkManager.java
@@ -90,6 +90,12 @@ } } mSelectionDelegate.clearSelection(); + + // This is necessary as long as we rely on RecyclerView.ItemDecorations to apply padding + // at the bottom of the bookmarks list to avoid the bottom navigation menu. This ensures + // the item decorations are reapplied correctly when item indices change as the result + // of an item being deleted. + mAdapter.notifyDataSetChanged(); } @Override
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/compositor/CompositorSurfaceManager.java b/chrome/android/java/src/org/chromium/chrome/browser/compositor/CompositorSurfaceManager.java index c885a52..57a9e41 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/compositor/CompositorSurfaceManager.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/compositor/CompositorSurfaceManager.java
@@ -4,474 +4,63 @@ package org.chromium.chrome.browser.compositor; -import android.content.Context; -import android.graphics.PixelFormat; import android.graphics.drawable.Drawable; -import android.view.SurfaceHolder; -import android.view.SurfaceView; -import android.view.View; -import android.view.ViewGroup; -import android.widget.FrameLayout; +import android.view.Surface; /** - * Manage multiple SurfaceViews for the compositor, so that transitions between - * surfaces with and without an alpha channel can be visually smooth. + * Manages Surface(s), and SurfaceView(s) when necessary, for the compositor. * - * This class allows a client to request a 'translucent' or 'opaque' surface, and we will signal via - * SurfaceHolder.Callback when it's ready. We guarantee that the client will receive surfaceCreated - * / surfaceDestroyed only for a surface that represents the most recently requested PixelFormat. - * - * Internally, we maintain two SurfaceViews, since calling setFormat() to change the PixelFormat - * results in a visual glitch as the surface is torn down. crbug.com/679902 - * - * The client has the responsibility to call doneWithUnownedSurface() at some point between when we - * call back its surfaceCreated, when it is safe for us to hide the SurfaceView with the wrong - * format. It is okay if it requests multiple surfaces without calling doneWithUnownedSurface. - * - * If the client requests the same format more than once in a row, it will still receive destroyed / - * created / changed messages for it, even though we won't tear it down. - * - * The full design doc is at https://goo.gl/aAmQzR . + * See CompositorSurfaceManagerImpl for the standard implementation of this class. + * While in VR, the VRCompositorSurfaceManager will be used, which only partially implements the + * contract implied by this interface. See the comments there for details. */ -class CompositorSurfaceManager implements SurfaceHolder.Callback2 { - public interface SurfaceHolderCallbackTarget { - public void surfaceRedrawNeededAsync(SurfaceHolder holder, Runnable drawingFinished); - public void surfaceChanged(SurfaceHolder holder, int format, int width, int height); - public void surfaceCreated(SurfaceHolder holder); - public void surfaceDestroyed(SurfaceHolder holder); - } - - private static class SurfaceState { - public SurfaceView surfaceView; - - // Do we expect a surfaceCreated? - public boolean createPending; - - // Have we started destroying |surfaceView|, but haven't received surfaceDestroyed yet? - public boolean destroyPending; - - // Last PixelFormat that we received, or UNKNOWN if we don't know / don't want to cache it. - public int format; - - // Last known width, height for thsi surface. - public int width; - public int height; - - // Parent ViewGroup, or null. - private ViewGroup mParent; - - public SurfaceState(Context context, int format, SurfaceHolder.Callback2 callback) { - surfaceView = new SurfaceView(context); - surfaceView.setZOrderMediaOverlay(true); - surfaceView.setVisibility(View.INVISIBLE); - surfaceHolder().setFormat(format); - surfaceHolder().addCallback(callback); - - // Set this to UNKNOWN until we get a format back. - this.format = PixelFormat.UNKNOWN; - } - - public SurfaceHolder surfaceHolder() { - return surfaceView.getHolder(); - } - - public boolean isValid() { - return surfaceHolder().getSurface().isValid(); - } - - // Attach to |parent|, such that isAttached() will be correct immediately. Otherwise, - // attaching and detaching can cause surfaceCreated / surfaceDestroyed callbacks without - // View.hasParent being up to date. - public void attachTo(ViewGroup parent, FrameLayout.LayoutParams lp) { - mParent = parent; - mParent.addView(surfaceView, lp); - } - - public void detachFromParent() { - final ViewGroup parent = mParent; - // Since removeView can call surfaceDestroyed before returning, be sure that isAttached - // will return false. - mParent = null; - parent.removeView(surfaceView); - } - - public boolean isAttached() { - return mParent != null; - } - } - - // SurfaceView with a translucent PixelFormat. - private final SurfaceState mTranslucent; - - // SurfaceView with an opaque PixelFormat. - private final SurfaceState mOpaque; - - // Surface that we last gave to the client with surfaceCreated. Cleared when we call - // surfaceDestroyed on |mClient|. Note that it's not necessary that Android has notified us - // the surface has been destroyed; we deliberately keep it around until the client tells us that - // it's okay to get rid of it. - private SurfaceState mOwnedByClient; - - // Surface that was most recently requested by the client. - private SurfaceState mRequestedByClient; - - // Client that we notify about surface change events. - private SurfaceHolderCallbackTarget mClient; - - // View to which we'll attach the SurfaceView. - private final ViewGroup mParentView; - - public CompositorSurfaceManager(ViewGroup parentView, SurfaceHolderCallbackTarget client) { - mParentView = parentView; - mClient = client; - - mTranslucent = new SurfaceState(parentView.getContext(), PixelFormat.TRANSLUCENT, this); - mOpaque = new SurfaceState(mParentView.getContext(), PixelFormat.OPAQUE, this); +public interface CompositorSurfaceManager { + /** + * Delivers Surface lifecycle events to the target of this CompositorSurfaceManager. + */ + public interface SurfaceManagerCallbackTarget { + public void surfaceRedrawNeededAsync(Runnable drawingFinished); + public void surfaceChanged(Surface surface, int format, int width, int height); + public void surfaceCreated(Surface surface); + public void surfaceDestroyed(Surface surface); } /** * Turn off everything. */ - public void shutDown() { - mTranslucent.surfaceHolder().removeCallback(this); - mOpaque.surfaceHolder().removeCallback(this); - } + void shutDown(); /** - * Called by the client to request a surface. Once called, we guarantee that the next call to - * surfaceCreated will match the most recent value of |format|. If the surface is already + * Called by the client to request a surface. Once called, we guarantee that the next call to + * surfaceCreated will match the most recent value of |format|. If the surface is already * available for use, then we'll send synthetic callbacks as though it were destroyed and - * recreated. Note that |format| must be either OPAQUE or TRANSLUCENT. + * recreated. Note that |format| must be either OPAQUE or TRANSLUCENT. */ - public void requestSurface(int format) { - mRequestedByClient = (format == PixelFormat.TRANSLUCENT) ? mTranslucent : mOpaque; - - // If destruction is pending, then we must wait for it to complete. When we're notified - // that it is destroyed, we'll re-start construction if the client still wants this surface. - // Note that we could send a surfaceDestroyed for the owned surface, if there is one, but we - // defer it until later so that the client can still use it until the new one is ready. - if (mRequestedByClient.destroyPending) return; - - // The requested surface isn't being torn down. - - // If the surface isn't attached yet, then attach it. Otherwise, we're still waiting for - // the surface to be created, or we've already received surfaceCreated for it. - if (!mRequestedByClient.isAttached()) { - attachSurfaceNow(mRequestedByClient); - assert mRequestedByClient.isAttached(); - return; - } - - // Surface is not pending destroy, and is attached. See if we need to send any synthetic - // callbacks to the client. If we're expecting a callback from Android, then we'll handle - // it when it arrives instead. - if (mRequestedByClient.createPending) return; - - // Surface is attached and no create is pending. Send a synthetic create. Note that, if - // Android destroyed the surface itself, then we'd have set |createPending| at that point. - // We don't check |isValid| here, since, technically, there could be a destroy in flight - // from Android. It's okay; we'll just notify the client at that point. Either way, we - // must tell the client that it now owns the surface. - - // Send a notification about any owned surface. Note that this can be |mRequestedByClient| - // which is fine. We'll send destroy / create for it. Also note that we don't actually - // start tear-down of the owned surface; the client notifies us via doneWithUnownedSurface - // when it is safe to do that. - disownClientSurface(mOwnedByClient); - - // The client now owns |mRequestedByClient|. Notify it that it's ready. - mOwnedByClient = mRequestedByClient; - mClient.surfaceCreated(mOwnedByClient.surfaceHolder()); - - // See if we're expecting a surfaceChanged. If not, then send a synthetic one. - if (mOwnedByClient.format != PixelFormat.UNKNOWN) { - mClient.surfaceChanged(mOwnedByClient.surfaceHolder(), mOwnedByClient.format, - mOwnedByClient.width, mOwnedByClient.height); - } - } + void requestSurface(int format); /** - * Called to notify us that the client no longer needs the surface that it doesn't own. This - * tells us that we may destroy it. Note that it's okay if it never had an unowned surface. + * Called to notify us that the client no longer needs the surface that it doesn't own. This + * tells us that we may destroy it. Note that it's okay if it never had an unowned surface. */ - public void doneWithUnownedSurface() { - if (mOwnedByClient == null) return; - - SurfaceState unowned = (mOwnedByClient == mTranslucent) ? mOpaque : mTranslucent; - - if (mRequestedByClient == unowned) { - // Client is giving us back a surface that it's since requested but hasn't gotten yet. - // Do nothing. It will be notified when the new surface is ready, and it can call us - // again for the other surface, if it wants. - return; - } - - // Start destruction of this surface. To prevent recursive call-backs to the client, we - // post this for later. - detachSurfaceLater(unowned); - } + void doneWithUnownedSurface(); /** - * Return the currently owned SurfaceHolder, if any. + * Destroy and re-create the surface. Useful for a JB workaround needed by CompositorView. */ - public SurfaceHolder getHolder() { - return mOwnedByClient != null ? mOwnedByClient.surfaceHolder() : null; - } - - /** - * Destroy and re-create the surface. Useful for a JB workaround needed by CompositorView. - */ - public void recreateSurfaceForJellyBean() { - // If they don't have a surface, then they'll get a new one anyway. - if (mOwnedByClient == null) return; - - // Notify the client that it no longer owns this surface, then destroy it. When destruction - // completes, we will recreate it automatically, since it will look like the client since - // re-requested it. That's why we send surfaceDestroyed here rather than letting our - // surfaceDestroyed do it when destruction completes. If we just started destruction while - // the client still owns the surface, then our surfaceDestroyed would assume that Android - // initiated the destruction, and wait for Android to recreate it. - - mParentView.post(new Runnable() { - @Override - public void run() { - if (mOwnedByClient == null) return; - SurfaceState owned = mOwnedByClient; - mClient.surfaceDestroyed(mOwnedByClient.surfaceHolder()); - mOwnedByClient = null; - detachSurfaceNow(owned); - } - }); - } - - @Override - public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) { - SurfaceState state = getStateForHolder(holder); - assert state != null; - - // If this is the surface that the client currently cares about, then notify the client. - // Note that surfaceChanged is guaranteed to come only after surfaceCreated. Also, if the - // client has requested a different surface but hasn't gotten it yet, then skip this. - if (state == mOwnedByClient && state == mRequestedByClient) { - state.width = width; - state.height = height; - state.format = format; - mClient.surfaceChanged(holder, format, width, height); - } - } - - @Override - public void surfaceRedrawNeeded(SurfaceHolder holder) { - // Intentionally not implemented. - } - - @Override - public void surfaceRedrawNeededAsync(SurfaceHolder holder, Runnable drawingFinished) { - mClient.surfaceRedrawNeededAsync(holder, drawingFinished); - } - - @Override - public void surfaceCreated(SurfaceHolder holder) { - SurfaceState state = getStateForHolder(holder); - assert state != null; - // Note that |createPending| might not be set, if Android destroyed and recreated this - // surface on its own. - - if (state != mRequestedByClient) { - // Surface is created, but it's not the one that's been requested most recently. Just - // destroy it again. - detachSurfaceLater(state); - return; - } - - // No create is pending. - state.createPending = false; - - // A surfaceChanged should arrive. - state.format = PixelFormat.UNKNOWN; - - // The client requested a surface, and it's now available. If the client owns a surface, - // then notify it that it doesn't. Note that the client can't own |state| at this point, - // since we would have removed ownership when we got surfaceDestroyed. It's okay if the - // client doesn't own either surface. - assert mOwnedByClient != state; - disownClientSurface(mOwnedByClient); - - // The client now owns this surface, so notify it. - mOwnedByClient = mRequestedByClient; - mClient.surfaceCreated(mOwnedByClient.surfaceHolder()); - } - - @Override - public void surfaceDestroyed(SurfaceHolder holder) { - SurfaceState state = getStateForHolder(holder); - assert state != null; - - // If no destroy is pending, then Android chose to destroy this surface and will, hopefully, - // re-create it at some point. Otherwise, a destroy is either posted or has already - // detached this SurfaceView. If it's already detached, then the destruction is complete - // and we can clear |destroyPending|. Otherwise, Android has destroyed this surface while - // our destroy was posted, and might even return it before it runs. When the post runs, it - // can sort that out based on whether the surface is valid or not. - if (!state.destroyPending) { - state.createPending = true; - } else if (!state.isAttached()) { - state.destroyPending = false; - } - - state.format = PixelFormat.UNKNOWN; - - // If the client owns this surface, then notify it synchronously that it no longer does. - // This can happen if Android destroys the surface on its own. It's also possible that - // we've detached it, if a destroy was pending. Either way, notify the client. - if (state == mOwnedByClient) { - disownClientSurface(mOwnedByClient); - - // Do not re-request the surface here. If android gives the surface back, then we'll - // re-signal the client about construction. - return; - } - - // The client doesn't own this surface, but might want it. - // If the client has requested this surface, then start construction on it. The client will - // be notified when it completes. This can happen if the client re-requests a surface after - // we start destruction on it from a previous request, for example. We post this for later, - // since we might be called while removing |state| from the view tree. In general, posting - // from here is good. - if (state == mRequestedByClient && !state.isAttached()) { - attachSurfaceLater(state); - } else if (state != mRequestedByClient && state.isAttached()) { - // This isn't the requested surface. If android destroyed it, then also unhook it so - // that it isn't recreated later. - detachSurfaceLater(state); - } - } + void recreateSurfaceForJellyBean(); /** * Update the background drawable on all surfaces. */ - public void setBackgroundDrawable(Drawable background) { - mTranslucent.surfaceView.setBackgroundDrawable(background); - mOpaque.surfaceView.setBackgroundDrawable(background); - } + void setBackgroundDrawable(Drawable background); /** * Set |willNotDraw| on all surfaces. */ - public void setWillNotDraw(boolean willNotDraw) { - mTranslucent.surfaceView.setWillNotDraw(willNotDraw); - mOpaque.surfaceView.setWillNotDraw(willNotDraw); - } - - public void setVisibility(int visibility) { - mTranslucent.surfaceView.setVisibility(visibility); - mOpaque.surfaceView.setVisibility(visibility); - } + void setWillNotDraw(boolean willNotDraw); /** - * Return the SurfaceState for |holder|, or null if it isn't either. + * Set the visibility of the Managed SurfaceViews. */ - private SurfaceState getStateForHolder(SurfaceHolder holder) { - if (mTranslucent.surfaceHolder() == holder) return mTranslucent; - - if (mOpaque.surfaceHolder() == holder) return mOpaque; - - return null; - } - - /** - * Attach |state| to |mParentView| immedaitely. - */ - private void attachSurfaceNow(SurfaceState state) { - if (state.isAttached()) return; - - // If there is a destroy in-flight for this surface, then do nothing. - if (state.destroyPending) return; - - state.createPending = true; - FrameLayout.LayoutParams lp = new FrameLayout.LayoutParams( - ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT); - state.attachTo(mParentView, lp); - mParentView.bringChildToFront(state.surfaceView); - mParentView.postInvalidateOnAnimation(); - } - - /** - * Post a Runnable to attach |state|. This is helpful, since one cannot directly interact with - * the View heirarchy during Surface callbacks. - */ - private void attachSurfaceLater(final SurfaceState state) { - // We shouldn't try to post construction if there's an in-flight destroy. - assert !state.destroyPending; - state.createPending = true; - - mParentView.post(new Runnable() { - @Override - public void run() { - attachSurfaceNow(state); - } - }); - } - - /** - * Cause the client to disown |state| if it currently owns it. This involves notifying it that - * the surface has been destroyed (recall that ownership involves getting created). It's okay - * if |state| is null or isn't owned by the client. - */ - private void disownClientSurface(SurfaceState state) { - if (mOwnedByClient != state || state == null) return; - - mClient.surfaceDestroyed(mOwnedByClient.surfaceHolder()); - mOwnedByClient = null; - } - - /** - * Detach |state| from |mParentView| immediately. - */ - private void detachSurfaceNow(SurfaceState state) { - // If we're called while we're not attached, then do nothing. This makes it easier for the - // client, since it doesn't have to keep track of whether the outgoing surface has been - // destroyed or not. The client will be notified (or has already) when the surface is - // destroyed, if it currently owns it. - if (state.isAttached()) { - // We are attached. If the surface is not valid, then Android has destroyed it for some - // other reason, and we should clean up. Otherwise, just wait for Android to finish. - final boolean valid = state.isValid(); - - // If the surface is valid, then we expect a callback to surfaceDestroyed eventually. - state.destroyPending = valid; - - // Note that this might call back surfaceDestroyed before returning! - state.detachFromParent(); - - // If the surface was valid before, then we expect a surfaceDestroyed callback, which - // might have arrived during removeView. Either way, that callback will finish cleanup - // of |state|. - if (valid) return; - } - - // The surface isn't attached, or was attached but wasn't currently valid. Either way, - // we're not going to get a destroy, so notify the client now if needed. - disownClientSurface(state); - - // If the client has since re-requested the surface, then start construction. - if (state == mRequestedByClient) attachSurfaceNow(mRequestedByClient); - } - - /** - * Post detachment of |state|. This is safe during Surface callbacks. - */ - private void detachSurfaceLater(final SurfaceState state) { - // If |state| is not attached, then do nothing. There might be a destroy pending from - // Android, but in any case leave it be. - if (!state.isAttached()) return; - - state.destroyPending = true; - mParentView.post(new Runnable() { - @Override - public void run() { - detachSurfaceNow(state); - } - }); - } + void setVisibility(int visibility); }
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/compositor/CompositorSurfaceManagerImpl.java b/chrome/android/java/src/org/chromium/chrome/browser/compositor/CompositorSurfaceManagerImpl.java new file mode 100644 index 0000000..082912f --- /dev/null +++ b/chrome/android/java/src/org/chromium/chrome/browser/compositor/CompositorSurfaceManagerImpl.java
@@ -0,0 +1,455 @@ +// 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.chrome.browser.compositor; + +import android.content.Context; +import android.graphics.PixelFormat; +import android.graphics.drawable.Drawable; +import android.view.SurfaceHolder; +import android.view.SurfaceView; +import android.view.View; +import android.view.ViewGroup; +import android.widget.FrameLayout; + +/** + * Manage multiple SurfaceViews for the compositor, so that transitions between + * surfaces with and without an alpha channel can be visually smooth. + * + * This class allows a client to request a 'translucent' or 'opaque' surface, and we will signal via + * SurfaceHolder.Callback when it's ready. We guarantee that the client will receive surfaceCreated + * / surfaceDestroyed only for a surface that represents the most recently requested PixelFormat. + * + * Internally, we maintain two SurfaceViews, since calling setFormat() to change the PixelFormat + * results in a visual glitch as the surface is torn down. crbug.com/679902 + * + * The client has the responsibility to call doneWithUnownedSurface() at some point between when we + * call back its surfaceCreated, when it is safe for us to hide the SurfaceView with the wrong + * format. It is okay if it requests multiple surfaces without calling doneWithUnownedSurface. + * + * If the client requests the same format more than once in a row, it will still receive destroyed / + * created / changed messages for it, even though we won't tear it down. + * + * The full design doc is at https://goo.gl/aAmQzR . + */ +class CompositorSurfaceManagerImpl implements SurfaceHolder.Callback2, CompositorSurfaceManager { + private static class SurfaceState { + public SurfaceView surfaceView; + + // Do we expect a surfaceCreated? + public boolean createPending; + + // Have we started destroying |surfaceView|, but haven't received surfaceDestroyed yet? + public boolean destroyPending; + + // Last PixelFormat that we received, or UNKNOWN if we don't know / don't want to cache it. + public int format; + + // Last known width, height for thsi surface. + public int width; + public int height; + + // Parent ViewGroup, or null. + private ViewGroup mParent; + + public SurfaceState(Context context, int format, SurfaceHolder.Callback2 callback) { + surfaceView = new SurfaceView(context); + surfaceView.setZOrderMediaOverlay(true); + surfaceView.setVisibility(View.INVISIBLE); + surfaceHolder().setFormat(format); + surfaceHolder().addCallback(callback); + + // Set this to UNKNOWN until we get a format back. + this.format = PixelFormat.UNKNOWN; + } + + public SurfaceHolder surfaceHolder() { + return surfaceView.getHolder(); + } + + public boolean isValid() { + return surfaceHolder().getSurface().isValid(); + } + + // Attach to |parent|, such that isAttached() will be correct immediately. Otherwise, + // attaching and detaching can cause surfaceCreated / surfaceDestroyed callbacks without + // View.hasParent being up to date. + public void attachTo(ViewGroup parent, FrameLayout.LayoutParams lp) { + mParent = parent; + mParent.addView(surfaceView, lp); + } + + public void detachFromParent() { + final ViewGroup parent = mParent; + // Since removeView can call surfaceDestroyed before returning, be sure that isAttached + // will return false. + mParent = null; + parent.removeView(surfaceView); + } + + public boolean isAttached() { + return mParent != null; + } + } + + // SurfaceView with a translucent PixelFormat. + private final SurfaceState mTranslucent; + + // SurfaceView with an opaque PixelFormat. + private final SurfaceState mOpaque; + + // Surface that we last gave to the client with surfaceCreated. Cleared when we call + // surfaceDestroyed on |mClient|. Note that it's not necessary that Android has notified us + // the surface has been destroyed; we deliberately keep it around until the client tells us that + // it's okay to get rid of it. + private SurfaceState mOwnedByClient; + + // Surface that was most recently requested by the client. + private SurfaceState mRequestedByClient; + + // Client that we notify about surface change events. + private SurfaceManagerCallbackTarget mClient; + + // View to which we'll attach the SurfaceView. + private final ViewGroup mParentView; + + public CompositorSurfaceManagerImpl(ViewGroup parentView, SurfaceManagerCallbackTarget client) { + mParentView = parentView; + mClient = client; + + mTranslucent = new SurfaceState(parentView.getContext(), PixelFormat.TRANSLUCENT, this); + mOpaque = new SurfaceState(mParentView.getContext(), PixelFormat.OPAQUE, this); + } + + /** + * Turn off everything. + */ + @Override + public void shutDown() { + mRequestedByClient = null; + detachSurfaceNow(mOpaque); + detachSurfaceNow(mTranslucent); + + mTranslucent.surfaceHolder().removeCallback(this); + mOpaque.surfaceHolder().removeCallback(this); + } + + @Override + public void requestSurface(int format) { + mRequestedByClient = (format == PixelFormat.TRANSLUCENT) ? mTranslucent : mOpaque; + + // If destruction is pending, then we must wait for it to complete. When we're notified + // that it is destroyed, we'll re-start construction if the client still wants this surface. + // Note that we could send a surfaceDestroyed for the owned surface, if there is one, but we + // defer it until later so that the client can still use it until the new one is ready. + if (mRequestedByClient.destroyPending) return; + + // The requested surface isn't being torn down. + + // If the surface isn't attached yet, then attach it. Otherwise, we're still waiting for + // the surface to be created, or we've already received surfaceCreated for it. + if (!mRequestedByClient.isAttached()) { + attachSurfaceNow(mRequestedByClient); + assert mRequestedByClient.isAttached(); + return; + } + + // Surface is not pending destroy, and is attached. See if we need to send any synthetic + // callbacks to the client. If we're expecting a callback from Android, then we'll handle + // it when it arrives instead. + if (mRequestedByClient.createPending) return; + + // Surface is attached and no create is pending. Send a synthetic create. Note that, if + // Android destroyed the surface itself, then we'd have set |createPending| at that point. + // We don't check |isValid| here, since, technically, there could be a destroy in flight + // from Android. It's okay; we'll just notify the client at that point. Either way, we + // must tell the client that it now owns the surface. + + // Send a notification about any owned surface. Note that this can be |mRequestedByClient| + // which is fine. We'll send destroy / create for it. Also note that we don't actually + // start tear-down of the owned surface; the client notifies us via doneWithUnownedSurface + // when it is safe to do that. + disownClientSurface(mOwnedByClient); + + // The client now owns |mRequestedByClient|. Notify it that it's ready. + mOwnedByClient = mRequestedByClient; + mClient.surfaceCreated(mOwnedByClient.surfaceHolder().getSurface()); + + // See if we're expecting a surfaceChanged. If not, then send a synthetic one. + if (mOwnedByClient.format != PixelFormat.UNKNOWN) { + mClient.surfaceChanged(mOwnedByClient.surfaceHolder().getSurface(), + mOwnedByClient.format, mOwnedByClient.width, mOwnedByClient.height); + } + } + + @Override + public void doneWithUnownedSurface() { + if (mOwnedByClient == null) return; + + SurfaceState unowned = (mOwnedByClient == mTranslucent) ? mOpaque : mTranslucent; + + if (mRequestedByClient == unowned) { + // Client is giving us back a surface that it's since requested but hasn't gotten yet. + // Do nothing. It will be notified when the new surface is ready, and it can call us + // again for the other surface, if it wants. + return; + } + + // Start destruction of this surface. To prevent recursive call-backs to the client, we + // post this for later. + detachSurfaceLater(unowned); + } + + @Override + public void recreateSurfaceForJellyBean() { + // If they don't have a surface, then they'll get a new one anyway. + if (mOwnedByClient == null) return; + + // Notify the client that it no longer owns this surface, then destroy it. When destruction + // completes, we will recreate it automatically, since it will look like the client since + // re-requested it. That's why we send surfaceDestroyed here rather than letting our + // surfaceDestroyed do it when destruction completes. If we just started destruction while + // the client still owns the surface, then our surfaceDestroyed would assume that Android + // initiated the destruction, and wait for Android to recreate it. + + mParentView.post(new Runnable() { + @Override + public void run() { + if (mOwnedByClient == null) return; + SurfaceState owned = mOwnedByClient; + mClient.surfaceDestroyed(owned.surfaceHolder().getSurface()); + mOwnedByClient = null; + detachSurfaceNow(owned); + } + }); + } + + @Override + public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) { + SurfaceState state = getStateForHolder(holder); + assert state != null; + + // If this is the surface that the client currently cares about, then notify the client. + // Note that surfaceChanged is guaranteed to come only after surfaceCreated. Also, if the + // client has requested a different surface but hasn't gotten it yet, then skip this. + if (state == mOwnedByClient && state == mRequestedByClient) { + state.width = width; + state.height = height; + state.format = format; + mClient.surfaceChanged(holder.getSurface(), format, width, height); + } + } + + @Override + public void surfaceRedrawNeeded(SurfaceHolder holder) { + // Intentionally not implemented. + } + + @Override + public void surfaceRedrawNeededAsync(SurfaceHolder holder, Runnable drawingFinished) { + mClient.surfaceRedrawNeededAsync(drawingFinished); + } + + @Override + public void surfaceCreated(SurfaceHolder holder) { + SurfaceState state = getStateForHolder(holder); + assert state != null; + // Note that |createPending| might not be set, if Android destroyed and recreated this + // surface on its own. + + if (state != mRequestedByClient) { + // Surface is created, but it's not the one that's been requested most recently. Just + // destroy it again. + detachSurfaceLater(state); + return; + } + + // No create is pending. + state.createPending = false; + + // A surfaceChanged should arrive. + state.format = PixelFormat.UNKNOWN; + + // The client requested a surface, and it's now available. If the client owns a surface, + // then notify it that it doesn't. Note that the client can't own |state| at this point, + // since we would have removed ownership when we got surfaceDestroyed. It's okay if the + // client doesn't own either surface. + assert mOwnedByClient != state; + disownClientSurface(mOwnedByClient); + + // The client now owns this surface, so notify it. + mOwnedByClient = mRequestedByClient; + mClient.surfaceCreated(mOwnedByClient.surfaceHolder().getSurface()); + } + + @Override + public void surfaceDestroyed(SurfaceHolder holder) { + SurfaceState state = getStateForHolder(holder); + assert state != null; + + // If no destroy is pending, then Android chose to destroy this surface and will, hopefully, + // re-create it at some point. Otherwise, a destroy is either posted or has already + // detached this SurfaceView. If it's already detached, then the destruction is complete + // and we can clear |destroyPending|. Otherwise, Android has destroyed this surface while + // our destroy was posted, and might even return it before it runs. When the post runs, it + // can sort that out based on whether the surface is valid or not. + if (!state.destroyPending) { + state.createPending = true; + } else if (!state.isAttached()) { + state.destroyPending = false; + } + + state.format = PixelFormat.UNKNOWN; + + // If the client owns this surface, then notify it synchronously that it no longer does. + // This can happen if Android destroys the surface on its own. It's also possible that + // we've detached it, if a destroy was pending. Either way, notify the client. + if (state == mOwnedByClient) { + disownClientSurface(mOwnedByClient); + + // Do not re-request the surface here. If android gives the surface back, then we'll + // re-signal the client about construction. + return; + } + + // The client doesn't own this surface, but might want it. + // If the client has requested this surface, then start construction on it. The client will + // be notified when it completes. This can happen if the client re-requests a surface after + // we start destruction on it from a previous request, for example. We post this for later, + // since we might be called while removing |state| from the view tree. In general, posting + // from here is good. + if (state == mRequestedByClient && !state.isAttached()) { + attachSurfaceLater(state); + } else if (state != mRequestedByClient && state.isAttached()) { + // This isn't the requested surface. If android destroyed it, then also unhook it so + // that it isn't recreated later. + detachSurfaceLater(state); + } + } + + @Override + public void setBackgroundDrawable(Drawable background) { + mTranslucent.surfaceView.setBackgroundDrawable(background); + mOpaque.surfaceView.setBackgroundDrawable(background); + } + + @Override + public void setWillNotDraw(boolean willNotDraw) { + mTranslucent.surfaceView.setWillNotDraw(willNotDraw); + mOpaque.surfaceView.setWillNotDraw(willNotDraw); + } + + @Override + public void setVisibility(int visibility) { + mTranslucent.surfaceView.setVisibility(visibility); + mOpaque.surfaceView.setVisibility(visibility); + } + + /** + * Return the SurfaceState for |holder|, or null if it isn't either. + */ + private SurfaceState getStateForHolder(SurfaceHolder holder) { + if (mTranslucent.surfaceHolder() == holder) return mTranslucent; + + if (mOpaque.surfaceHolder() == holder) return mOpaque; + + return null; + } + + /** + * Attach |state| to |mParentView| immedaitely. + */ + private void attachSurfaceNow(SurfaceState state) { + if (state.isAttached()) return; + + // If there is a destroy in-flight for this surface, then do nothing. + if (state.destroyPending) return; + + state.createPending = true; + FrameLayout.LayoutParams lp = new FrameLayout.LayoutParams( + ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT); + state.attachTo(mParentView, lp); + mParentView.bringChildToFront(state.surfaceView); + mParentView.postInvalidateOnAnimation(); + } + + /** + * Post a Runnable to attach |state|. This is helpful, since one cannot directly interact with + * the View heirarchy during Surface callbacks. + */ + private void attachSurfaceLater(final SurfaceState state) { + // We shouldn't try to post construction if there's an in-flight destroy. + assert !state.destroyPending; + state.createPending = true; + + mParentView.post(new Runnable() { + @Override + public void run() { + attachSurfaceNow(state); + } + }); + } + + /** + * Cause the client to disown |state| if it currently owns it. This involves notifying it that + * the surface has been destroyed (recall that ownership involves getting created). It's okay + * if |state| is null or isn't owned by the client. + */ + private void disownClientSurface(SurfaceState state) { + if (mOwnedByClient != state || state == null) return; + + mClient.surfaceDestroyed(mOwnedByClient.surfaceHolder().getSurface()); + mOwnedByClient = null; + } + + /** + * Detach |state| from |mParentView| immediately. + */ + private void detachSurfaceNow(SurfaceState state) { + // If we're called while we're not attached, then do nothing. This makes it easier for the + // client, since it doesn't have to keep track of whether the outgoing surface has been + // destroyed or not. The client will be notified (or has already) when the surface is + // destroyed, if it currently owns it. + if (state.isAttached()) { + // We are attached. If the surface is not valid, then Android has destroyed it for some + // other reason, and we should clean up. Otherwise, just wait for Android to finish. + final boolean valid = state.isValid(); + + // If the surface is valid, then we expect a callback to surfaceDestroyed eventually. + state.destroyPending = valid; + + // Note that this might call back surfaceDestroyed before returning! + state.detachFromParent(); + + // If the surface was valid before, then we expect a surfaceDestroyed callback, which + // might have arrived during removeView. Either way, that callback will finish cleanup + // of |state|. + if (valid) return; + } + + // The surface isn't attached, or was attached but wasn't currently valid. Either way, + // we're not going to get a destroy, so notify the client now if needed. + disownClientSurface(state); + + // If the client has since re-requested the surface, then start construction. + if (state == mRequestedByClient) attachSurfaceNow(mRequestedByClient); + } + + /** + * Post detachment of |state|. This is safe during Surface callbacks. + */ + private void detachSurfaceLater(final SurfaceState state) { + // If |state| is not attached, then do nothing. There might be a destroy pending from + // Android, but in any case leave it be. + if (!state.isAttached()) return; + + state.destroyPending = true; + mParentView.post(new Runnable() { + @Override + public void run() { + detachSurfaceNow(state); + } + }); + } +}
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/compositor/CompositorView.java b/chrome/android/java/src/org/chromium/chrome/browser/compositor/CompositorView.java index 157b7a64..aecfe2f 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/compositor/CompositorView.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/compositor/CompositorView.java
@@ -12,8 +12,6 @@ import android.graphics.drawable.Drawable; import android.view.MotionEvent; import android.view.Surface; -import android.view.SurfaceHolder; -import android.view.SurfaceView; import android.view.View; import android.widget.FrameLayout; @@ -42,7 +40,7 @@ */ @JNINamespace("android") public class CompositorView - extends FrameLayout implements CompositorSurfaceManager.SurfaceHolderCallbackTarget { + extends FrameLayout implements CompositorSurfaceManager.SurfaceManagerCallbackTarget { private static final String TAG = "CompositorView"; private static final long NANOSECONDS_PER_MILLISECOND = 1000000; @@ -50,7 +48,7 @@ private final Rect mCacheAppRect = new Rect(); private final int[] mCacheViewPosition = new int[2]; - private final CompositorSurfaceManager mCompositorSurfaceManager; + private CompositorSurfaceManager mCompositorSurfaceManager; private boolean mOverlayVideoEnabled; private boolean mAlwaysTranslucent; @@ -85,7 +83,7 @@ super(c); mRenderHost = host; - mCompositorSurfaceManager = new CompositorSurfaceManager(this, this); + mCompositorSurfaceManager = new CompositorSurfaceManagerImpl(this, this); // Cover the black surface before it has valid content. Set this placeholder view to // visible, but don't yet make SurfaceView visible, in order to delay @@ -169,7 +167,7 @@ */ public void initNativeCompositor(boolean lowMemDevice, WindowAndroid windowAndroid, LayerTitleCache layerTitleCache, TabContentManager tabContentManager) { - mWindowAndroid = windowAndroid; + setWindowAndroid(windowAndroid); mLayerTitleCache = layerTitleCache; mTabContentManager = tabContentManager; @@ -201,19 +199,17 @@ nativeSetNeedsComposite(mNativeCompositorView); } + private void setWindowAndroid(WindowAndroid windowAndroid) { + mWindowAndroid = windowAndroid; + onWindowVisibilityChangedInternal(getWindowVisibility()); + } + @Override public boolean onTouchEvent(MotionEvent e) { return super.onTouchEvent(e); } /** - * @see SurfaceView#getHolder - */ - SurfaceHolder getHolder() { - return mCompositorSurfaceManager.getHolder(); - } - - /** * Enables/disables overlay video mode. Affects alpha blending on this view. * @param enabled Whether to enter or leave overlay video mode. */ @@ -234,22 +230,22 @@ } @Override - public void surfaceRedrawNeededAsync(SurfaceHolder holder, Runnable drawingFinished) { + public void surfaceRedrawNeededAsync(Runnable drawingFinished) { if (mDrawingFinishedCallbacks == null) mDrawingFinishedCallbacks = new ArrayList<>(); mDrawingFinishedCallbacks.add(drawingFinished); if (mNativeCompositorView != 0) nativeSetNeedsComposite(mNativeCompositorView); } @Override - public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) { + public void surfaceChanged(Surface surface, int format, int width, int height) { if (mNativeCompositorView == 0) return; - nativeSurfaceChanged(mNativeCompositorView, format, width, height, holder.getSurface()); + nativeSurfaceChanged(mNativeCompositorView, format, width, height, surface); mRenderHost.onSurfaceResized(width, height); } @Override - public void surfaceCreated(SurfaceHolder holder) { + public void surfaceCreated(Surface surface) { if (mNativeCompositorView == 0) return; nativeSurfaceCreated(mNativeCompositorView); @@ -258,7 +254,7 @@ } @Override - public void surfaceDestroyed(SurfaceHolder holder) { + public void surfaceDestroyed(Surface surface) { if (mNativeCompositorView == 0) return; nativeSurfaceDestroyed(mNativeCompositorView); @@ -267,6 +263,10 @@ @Override public void onWindowVisibilityChanged(int visibility) { super.onWindowVisibilityChanged(visibility); + onWindowVisibilityChangedInternal(visibility); + } + + private void onWindowVisibilityChangedInternal(int visibility) { if (mWindowAndroid == null) return; if (visibility == View.GONE) { mWindowAndroid.onVisibilityChanged(false); @@ -383,9 +383,8 @@ @Override public void setVisibility(int visibility) { super.setVisibility(visibility); - // Also set the visibility on any child SurfaceViews, since that hides - // the surface as well. Otherwise, the surface is kept, which can - // interfere with VR. + // Also set the visibility on any child SurfaceViews, since that hides the surface as + // well. Otherwise, the surface is kept, which can interfere with VR. mCompositorSurfaceManager.setVisibility(visibility); // Clear out any outstanding callbacks that won't run if set to invisible. if (visibility == View.INVISIBLE) { @@ -402,7 +401,39 @@ } } - // Implemented in native + /** + * Replaces the surface manager and swaps the window the compositor is attached to as tab + * reparenting doesn't handle replacing of the window the compositor uses. + * + * @param vrCompositorSurfaceManager The surface manager for VR. + * @param window The VR WindowAndroid to switch to. + */ + public void replaceSurfaceManagerForVr( + CompositorSurfaceManager vrCompositorSurfaceManager, WindowAndroid window) { + mCompositorSurfaceManager.shutDown(); + nativeSetCompositorWindow(mNativeCompositorView, window.getNativePointer()); + mCompositorSurfaceManager = vrCompositorSurfaceManager; + mCompositorSurfaceManager.requestSurface(PixelFormat.OPAQUE); + nativeSetNeedsComposite(mNativeCompositorView); + setWindowAndroid(window); + } + + /** + * Restores the non-VR surface manager and passes back control over the surface(s) to it. + * Also restores the non-VR WindowAndroid. + * + * @param windowToRestore The non-VR WindowAndroid to restore. + */ + public void onExitVr(WindowAndroid windowToRestore) { + setWindowAndroid(windowToRestore); + mCompositorSurfaceManager.shutDown(); + nativeSetCompositorWindow(mNativeCompositorView, mWindowAndroid.getNativePointer()); + mCompositorSurfaceManager = new CompositorSurfaceManagerImpl(this, this); + mCompositorSurfaceManager.requestSurface(getSurfacePixelFormat()); + nativeSetNeedsComposite(mNativeCompositorView); + mCompositorSurfaceManager.setVisibility(getVisibility()); + } + private native long nativeInit(boolean lowMemDevice, long nativeWindowAndroid, LayerTitleCache layerTitleCache, TabContentManager tabContentManager); private native void nativeDestroy(long nativeCompositorView); @@ -418,4 +449,5 @@ private native void nativeSetLayoutBounds(long nativeCompositorView); private native void nativeSetOverlayVideoMode(long nativeCompositorView, boolean enabled); private native void nativeSetSceneLayer(long nativeCompositorView, SceneLayer sceneLayer); + private native void nativeSetCompositorWindow(long nativeCompositorView, long nativeWindow); }
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/contextualsearch/ContextualSearchSelectionController.java b/chrome/android/java/src/org/chromium/chrome/browser/contextualsearch/ContextualSearchSelectionController.java index 76f2b8b..f3b5904 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/contextualsearch/ContextualSearchSelectionController.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/contextualsearch/ContextualSearchSelectionController.java
@@ -15,6 +15,7 @@ import org.chromium.chrome.browser.tab.Tab; import org.chromium.content.browser.ContentViewCore; import org.chromium.content_public.browser.GestureStateListener; +import org.chromium.content_public.browser.SelectionPopupController; import org.chromium.content_public.browser.WebContents; import org.chromium.ui.touch_selection.SelectionEventType; @@ -206,14 +207,20 @@ * Clears the selection. */ void clearSelection() { - ContentViewCore baseContentView = getBaseContentView(); - if (baseContentView != null) { - baseContentView.clearSelection(); - } + SelectionPopupController controller = getSelectionPopupController(); + if (controller != null) controller.clearSelection(); resetSelectionStates(); } /** + * @return The {@link SelectionPopupController} for the base WebContents. + */ + protected SelectionPopupController getSelectionPopupController() { + WebContents baseContents = getBaseWebContents(); + return baseContents != null ? SelectionPopupController.fromWebContents(baseContents) : null; + } + + /** * Handles a change in the current Selection. * @param selection The selection portion of the context. */ @@ -260,8 +267,8 @@ mWasTapGestureDetected = false; mSelectionType = SelectionType.LONG_PRESS; shouldHandleSelection = true; - ContentViewCore baseContentView = getBaseContentView(); - if (baseContentView != null) mSelectedText = baseContentView.getSelectedText(); + SelectionPopupController controller = getSelectionPopupController(); + if (controller != null) mSelectedText = controller.getSelectedText(); break; case SelectionEventType.SELECTION_HANDLES_CLEARED: mHandler.handleSelectionDismissal(); @@ -412,18 +419,6 @@ } /** - * Gets the base page ContentViewCore. - * Deprecated, use getBaseWebContents instead. - * @return The Base Page's {@link ContentViewCore}, or {@code null} if there is no current tab. - */ - @Deprecated - @Nullable - ContentViewCore getBaseContentView() { - Tab currentTab = mActivity.getActivityTab(); - return currentTab != null ? currentTab.getContentViewCore() : null; - } - - /** * @return The Base Page's {@link WebContents}, or {@code null} if there is no current tab or * the current tab has no {@link ContentViewCore}. */ @@ -533,11 +528,11 @@ * @return whether the given selection is considered a valid target for a search. */ private boolean isValidSelection(String selection) { - return isValidSelection(selection, getBaseContentView()); + return isValidSelection(selection, getSelectionPopupController()); } @VisibleForTesting - boolean isValidSelection(String selection, ContentViewCore baseContentView) { + boolean isValidSelection(String selection, SelectionPopupController controller) { if (selection.length() > MAX_SELECTION_LENGTH) { return false; } @@ -546,7 +541,7 @@ return false; } - if (baseContentView != null && baseContentView.isFocusedNodeEditable()) { + if (controller != null && controller.isFocusedNodeEditable()) { return false; }
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/contextualsearch/ContextualSearchTabHelper.java b/chrome/android/java/src/org/chromium/chrome/browser/contextualsearch/ContextualSearchTabHelper.java index 3c8d55c6..e5145600 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/contextualsearch/ContextualSearchTabHelper.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/contextualsearch/ContextualSearchTabHelper.java
@@ -18,9 +18,10 @@ import org.chromium.chrome.browser.search_engines.TemplateUrlService.TemplateUrlServiceObserver; import org.chromium.chrome.browser.tab.EmptyTabObserver; import org.chromium.chrome.browser.tab.Tab; -import org.chromium.content.browser.ContentViewCore; import org.chromium.content_public.browser.GestureListenerManager; import org.chromium.content_public.browser.GestureStateListener; +import org.chromium.content_public.browser.SelectionPopupController; +import org.chromium.content_public.browser.WebContents; import org.chromium.net.NetworkChangeNotifier; /** Manages the activation and gesture listeners for ContextualSearch on a given tab. */ @@ -33,9 +34,9 @@ private TemplateUrlServiceObserver mTemplateUrlObserver; /** - * The ContentViewCore associated with the Tab which this helper is monitoring, unless detached. + * The WebContents associated with the Tab which this helper is monitoring, unless detached. */ - private ContentViewCore mContentViewCore; + private WebContents mWebContents; /** * The {@link ContextualSearchManager} that's managing this tab. This may point to @@ -43,11 +44,11 @@ */ private ContextualSearchManager mContextualSearchManager; - /** The GestureListener used for handling events from the current ContentViewCore. */ + /** The GestureListener used for handling events from the current WebContents. */ private GestureStateListener mGestureStateListener; /** - * Manages incoming calls to Smart Select when available, for the current mBaseContentViewCore. + * Manages incoming calls to Smart Select when available, for the current base WebContents. */ private SelectionClientManager mSelectionClientManager; @@ -96,7 +97,7 @@ mTemplateUrlObserver = new TemplateUrlServiceObserver() { @Override public void onTemplateURLServiceChanged() { - updateContextualSearchHooks(mContentViewCore); + updateContextualSearchHooks(mWebContents); } }; TemplateUrlService.getInstance().addObserver(mTemplateUrlObserver); @@ -121,8 +122,8 @@ if (NetworkChangeNotifier.isInitialized()) { NetworkChangeNotifier.removeConnectionTypeObserver(this); } - removeContextualSearchHooks(mContentViewCore); - mContentViewCore = null; + removeContextualSearchHooks(mWebContents); + mWebContents = null; mContextualSearchManager = null; mSelectionClientManager = null; mGestureStateListener = null; @@ -141,7 +142,7 @@ if (isAttached) { updateHooksForTab(tab); } else { - removeContextualSearchHooks(mContentViewCore); + removeContextualSearchHooks(mWebContents); mContextualSearchManager = null; } } @@ -160,7 +161,7 @@ @Override public void onConnectionTypeChanged(int connectionType) { - updateContextualSearchHooks(mContentViewCore); + updateContextualSearchHooks(mWebContents); } // ============================================================================================ @@ -168,84 +169,88 @@ // ============================================================================================ /** - * Should be called whenever the Tab's ContentViewCore may have changed. Removes hooks from the - * existing ContentViewCore, if necessary, and then adds hooks for the new ContentViewCore. + * Should be called whenever the Tab's WebContents may have changed. Removes hooks from the + * existing WebContents, if necessary, and then adds hooks for the new ContentViewCore. * @param tab The current tab. */ private void updateHooksForTab(Tab tab) { - ContentViewCore currentContentViewCore = tab.getActiveContentViewCore(); - if (currentContentViewCore != mContentViewCore + WebContents currentWebContents = tab.getWebContents(); + if (currentWebContents != mWebContents || mContextualSearchManager != getContextualSearchManager(tab)) { - mContentViewCore = currentContentViewCore; + mWebContents = currentWebContents; mContextualSearchManager = getContextualSearchManager(tab); - if (mContentViewCore != null && mSelectionClientManager == null) { - mSelectionClientManager = new SelectionClientManager(mContentViewCore); + if (mWebContents != null && mSelectionClientManager == null) { + mSelectionClientManager = new SelectionClientManager(mWebContents); } - updateContextualSearchHooks(mContentViewCore); + updateContextualSearchHooks(mWebContents); } } /** * Updates the Contextual Search hooks, adding or removing them depending on whether it is - * currently active. If the current tab's {@link ContentViewCore} may have changed, call {@link + * currently active. If the current tab's {@link WebContents} may have changed, call {@link * #updateHooksForTab(Tab)} instead. * - * @param cvc The content view core to attach the gesture state listener to. + * @param webContents The WebContents to attach the gesture state listener to. */ - private void updateContextualSearchHooks(ContentViewCore cvc) { - if (cvc == null) return; + private void updateContextualSearchHooks(WebContents webContents) { + if (webContents == null) return; - removeContextualSearchHooks(cvc); - if (isContextualSearchActive(cvc)) addContextualSearchHooks(cvc); + removeContextualSearchHooks(webContents); + if (isContextualSearchActive(webContents)) addContextualSearchHooks(webContents); } /** - * Adds Contextual Search hooks for its client and listener to the given content view core. - * @param cvc The content view core to attach the gesture state listener to. + * Adds Contextual Search hooks for its client and listener to the given WebContents. + * @param webContents The WebContents to attach the gesture state listener to. */ - private void addContextualSearchHooks(ContentViewCore cvc) { - assert mTab.getContentViewCore() == null || mTab.getContentViewCore() == cvc; + private void addContextualSearchHooks(WebContents webContents) { + assert mTab.getWebContents() == null || mTab.getWebContents() == webContents; ContextualSearchManager contextualSearchManager = getContextualSearchManager(mTab); if (mGestureStateListener == null && contextualSearchManager != null) { mGestureStateListener = contextualSearchManager.getGestureStateListener(); - GestureListenerManager.fromWebContents(cvc.getWebContents()) - .addListener(mGestureStateListener); + GestureListenerManager.fromWebContents(webContents).addListener(mGestureStateListener); // If we needed to add our listener, we also need to add our selection client. - cvc.setSelectionClient(mSelectionClientManager.addContextualSearchSelectionClient( - contextualSearchManager.getContextualSearchSelectionClient())); + SelectionPopupController controller = + SelectionPopupController.fromWebContents(webContents); + controller.setSelectionClient( + mSelectionClientManager.addContextualSearchSelectionClient( + contextualSearchManager.getContextualSearchSelectionClient())); contextualSearchManager.suppressContextualSearchForSmartSelection( mSelectionClientManager.isSmartSelectionEnabledInChrome()); } } /** - * Removes Contextual Search hooks for its client and listener from the given content view core. - * @param cvc The content view core to detach the gesture state listener from. + * Removes Contextual Search hooks for its client and listener from the given WebContents. + * @param webContents The WebContents to detach the gesture state listener from. */ - private void removeContextualSearchHooks(ContentViewCore cvc) { - if (cvc == null) return; + private void removeContextualSearchHooks(WebContents webContents) { + if (webContents == null) return; if (mGestureStateListener != null) { - GestureListenerManager.fromWebContents(cvc.getWebContents()) + GestureListenerManager.fromWebContents(webContents) .removeListener(mGestureStateListener); mGestureStateListener = null; // If we needed to remove our listener, we also need to remove our selection client. if (mSelectionClientManager != null) { - cvc.setSelectionClient( + SelectionPopupController controller = + SelectionPopupController.fromWebContents(webContents); + controller.setSelectionClient( mSelectionClientManager.removeContextualSearchSelectionClient()); } } } /** @return whether Contextual Search is enabled and active in this tab. */ - private boolean isContextualSearchActive(ContentViewCore cvc) { - assert mTab.getContentViewCore() == null || mTab.getContentViewCore() == cvc; + private boolean isContextualSearchActive(WebContents webContents) { + assert mTab.getWebContents() == null || mTab.getWebContents() == webContents; ContextualSearchManager manager = getContextualSearchManager(mTab); if (manager == null) return false; - return !cvc.getWebContents().isIncognito() && FirstRunStatus.getFirstRunFlowComplete() + return !webContents.isIncognito() && FirstRunStatus.getFirstRunFlowComplete() && !PrefServiceBridge.getInstance().isContextualSearchDisabled() && TemplateUrlService.getInstance().isDefaultSearchEngineGoogle() && !LocaleManager.getInstance().needToCheckForSearchEnginePromo() @@ -283,7 +288,7 @@ @CalledByNative void onContextualSearchPrefChanged() { - updateContextualSearchHooks(mContentViewCore); + updateContextualSearchHooks(mWebContents); ContextualSearchManager manager = getContextualSearchManager(mTab); if (manager != null) {
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/contextualsearch/SelectionClientManager.java b/chrome/android/java/src/org/chromium/chrome/browser/contextualsearch/SelectionClientManager.java index 561e4a8..3163e34 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/contextualsearch/SelectionClientManager.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/contextualsearch/SelectionClientManager.java
@@ -10,9 +10,9 @@ import android.view.textclassifier.TextClassifier; import org.chromium.chrome.browser.ChromeFeatureList; -import org.chromium.content.browser.ContentViewCore; import org.chromium.content_public.browser.SelectionClient; import org.chromium.content_public.browser.SelectionMetricsLogger; +import org.chromium.content_public.browser.SelectionPopupController; import org.chromium.content_public.browser.WebContents; /** @@ -40,16 +40,16 @@ /** * Constructs an instance that can return a {@link SelectionClient} that's a mix of an optional * Smart Selection client and a transient Contextual Search client. - * @param contentViewCore The {@link ContentViewCore} that will show pupups for this client. + * @param webContents The {@link WebContents} that will show popups for this client. */ - SelectionClientManager(ContentViewCore contentViewCore) { + SelectionClientManager(WebContents webContents) { if (ChromeFeatureList.isEnabled(ChromeFeatureList.CHROME_SMART_SELECTION) && Build.VERSION.SDK_INT > Build.VERSION_CODES.O) { - assert contentViewCore != null; - WebContents webContents = contentViewCore.getWebContents(); assert webContents != null; mOptionalSelectionClient = SelectionClient.createSmartSelectionClient(webContents); - contentViewCore.setSelectionClient(mOptionalSelectionClient); + SelectionPopupController controller = + SelectionPopupController.fromWebContents(webContents); + controller.setSelectionClient(mOptionalSelectionClient); } mIsSmartSelectionEnabledInChrome = mOptionalSelectionClient != null; }
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/customtabs/CustomTabActivity.java b/chrome/android/java/src/org/chromium/chrome/browser/customtabs/CustomTabActivity.java index 3a35dff2..b5f06537 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/customtabs/CustomTabActivity.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/customtabs/CustomTabActivity.java
@@ -1162,7 +1162,7 @@ // Blink has rendered the page by this point, but we need to wait for the compositor // frame swap to avoid flash of white content. - getCompositorViewHolder().getCompositorView().surfaceRedrawNeededAsync(null, () -> { + getCompositorViewHolder().getCompositorView().surfaceRedrawNeededAsync(() -> { if (!tab.isInitialized() || isActivityDestroyed()) return; tab.getView().setBackgroundResource(0); });
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/firstrun/AccountFirstRunFragment.java b/chrome/android/java/src/org/chromium/chrome/browser/firstrun/AccountFirstRunFragment.java index 2e634492..7d6f55c5 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/firstrun/AccountFirstRunFragment.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/firstrun/AccountFirstRunFragment.java
@@ -84,13 +84,16 @@ } }; + final Bundle arguments; if (forceAccountTo == null) { - mView.initFromSelectionPage( - SigninAccessPoint.START_PAGE, isChildAccount, this, listener); + arguments = AccountSigninView.createArgumentsForDefaultFlow( + SigninAccessPoint.START_PAGE, isChildAccount); } else { - mView.initFromConfirmationPage(SigninAccessPoint.START_PAGE, isChildAccount, - forceAccountTo, false, AccountSigninView.UNDO_INVISIBLE, this, listener); + arguments = AccountSigninView.createArgumentsForConfirmationFlow( + SigninAccessPoint.START_PAGE, isChildAccount, forceAccountTo, false, + AccountSigninView.UNDO_INVISIBLE); } + mView.init(arguments, this, listener); RecordUserAction.record("MobileFre.SignInShown"); RecordUserAction.record("Signin_Signin_FromStartPage");
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/media/router/BaseMediaRouteProvider.java b/chrome/android/java/src/org/chromium/chrome/browser/media/router/cast/BaseMediaRouteProvider.java similarity index 94% rename from chrome/android/java/src/org/chromium/chrome/browser/media/router/BaseMediaRouteProvider.java rename to chrome/android/java/src/org/chromium/chrome/browser/media/router/cast/BaseMediaRouteProvider.java index 87ac3ed..7a852393 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/media/router/BaseMediaRouteProvider.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/media/router/cast/BaseMediaRouteProvider.java
@@ -1,7 +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. -package org.chromium.chrome.browser.media.router; +package org.chromium.chrome.browser.media.router.cast; import android.os.Handler; import android.support.v7.media.MediaRouteSelector; @@ -9,11 +9,10 @@ import android.support.v7.media.MediaRouter.RouteInfo; import org.chromium.base.Log; -import org.chromium.chrome.browser.media.router.cast.CastSession; -import org.chromium.chrome.browser.media.router.cast.ChromeCastSessionManager; -import org.chromium.chrome.browser.media.router.cast.DiscoveryCallback; -import org.chromium.chrome.browser.media.router.cast.MediaSink; -import org.chromium.chrome.browser.media.router.cast.MediaSource; +import org.chromium.chrome.browser.media.router.DiscoveryDelegate; +import org.chromium.chrome.browser.media.router.MediaRoute; +import org.chromium.chrome.browser.media.router.MediaRouteManager; +import org.chromium.chrome.browser.media.router.MediaRouteProvider; import java.util.ArrayList; import java.util.Collections;
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/media/router/cast/CastMediaRouteProvider.java b/chrome/android/java/src/org/chromium/chrome/browser/media/router/cast/CastMediaRouteProvider.java index f582175..f8ee3103 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/media/router/cast/CastMediaRouteProvider.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/media/router/cast/CastMediaRouteProvider.java
@@ -11,7 +11,6 @@ import org.chromium.base.Log; import org.chromium.base.VisibleForTesting; -import org.chromium.chrome.browser.media.router.BaseMediaRouteProvider; import org.chromium.chrome.browser.media.router.ChromeMediaRouter; import org.chromium.chrome.browser.media.router.MediaRoute; import org.chromium.chrome.browser.media.router.MediaRouteManager;
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/media/router/cast/remoting/RemotingMediaRouteProvider.java b/chrome/android/java/src/org/chromium/chrome/browser/media/router/cast/remoting/RemotingMediaRouteProvider.java index 40ca85d3..16dbf3ac 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/media/router/cast/remoting/RemotingMediaRouteProvider.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/media/router/cast/remoting/RemotingMediaRouteProvider.java
@@ -7,11 +7,11 @@ import org.chromium.base.Log; import org.chromium.base.VisibleForTesting; -import org.chromium.chrome.browser.media.router.BaseMediaRouteProvider; import org.chromium.chrome.browser.media.router.ChromeMediaRouter; import org.chromium.chrome.browser.media.router.MediaRoute; import org.chromium.chrome.browser.media.router.MediaRouteManager; import org.chromium.chrome.browser.media.router.MediaRouteProvider; +import org.chromium.chrome.browser.media.router.cast.BaseMediaRouteProvider; import org.chromium.chrome.browser.media.router.cast.ChromeCastSessionManager; import org.chromium.chrome.browser.media.router.cast.CreateRouteRequest; import org.chromium.chrome.browser.media.router.cast.MediaSink;
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/omnibox/UrlBar.java b/chrome/android/java/src/org/chromium/chrome/browser/omnibox/UrlBar.java index 8b5d13e1..0d54aa4 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/omnibox/UrlBar.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/omnibox/UrlBar.java
@@ -41,7 +41,8 @@ import org.chromium.chrome.browser.metrics.StartupMetrics; import org.chromium.chrome.browser.tab.Tab; import org.chromium.chrome.browser.util.UrlUtilities; -import org.chromium.content.browser.ContentViewCore; +import org.chromium.content_public.browser.SelectionPopupController; +import org.chromium.content_public.browser.WebContents; import org.chromium.ui.UiUtils; import java.net.MalformedURLException; @@ -425,8 +426,8 @@ Tab currentTab = mUrlBarDelegate.getCurrentTab(); if (event.getAction() == MotionEvent.ACTION_DOWN && currentTab != null) { // Make sure to hide the current ContentView ActionBar. - ContentViewCore viewCore = currentTab.getContentViewCore(); - if (viewCore != null) viewCore.destroySelectActionMode(); + SelectionPopupController controller = getSelectionPopupController(currentTab); + if (controller != null) controller.destroySelectActionMode(); } if (mSuppressingTouchMoveEventsForThisTouch @@ -448,6 +449,11 @@ } } + private SelectionPopupController getSelectionPopupController(Tab tab) { + WebContents webContents = tab.getWebContents(); + return webContents != null ? SelectionPopupController.fromWebContents(webContents) : null; + } + @Override public boolean performLongClick(float x, float y) { if (!shouldPerformLongClick()) return false;
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/signin/AccountSigninActivity.java b/chrome/android/java/src/org/chromium/chrome/browser/signin/AccountSigninActivity.java index 250062e..a2ba4f7c0 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/signin/AccountSigninActivity.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/signin/AccountSigninActivity.java
@@ -10,7 +10,6 @@ import android.os.Bundle; import android.support.annotation.IntDef; import android.support.v7.app.AppCompatActivity; -import android.view.LayoutInflater; import org.chromium.base.Log; import org.chromium.base.library_loader.ProcessInitException; @@ -32,23 +31,9 @@ public class AccountSigninActivity extends AppCompatActivity implements AccountSigninView.Listener, AccountSigninView.Delegate { private static final String TAG = "AccountSigninActivity"; - private static final String INTENT_SIGNIN_ACCESS_POINT = - "AccountSigninActivity.SigninAccessPoint"; - private static final String INTENT_SIGNIN_FLOW_TYPE = "AccountSigninActivity.SigninFlowType"; - private static final String INTENT_ACCOUNT_NAME = "AccountSigninActivity.AccountName"; - private static final String INTENT_IS_DEFAULT_ACCOUNT = - "AccountSigninActivity.IsDefaultAccount"; private static final String INTENT_IS_FROM_PERSONALIZED_PROMO = "AccountSigninActivity.IsFromPersonalizedPromo"; - @IntDef({SIGNIN_FLOW_DEFAULT, SIGNIN_FLOW_CONFIRMATION_ONLY, SIGNIN_FLOW_ADD_NEW_ACCOUNT}) - @Retention(RetentionPolicy.SOURCE) - private @interface SigninFlowType {} - - private static final int SIGNIN_FLOW_DEFAULT = 0; - private static final int SIGNIN_FLOW_CONFIRMATION_ONLY = 1; - private static final int SIGNIN_FLOW_ADD_NEW_ACCOUNT = 2; - @IntDef({SigninAccessPoint.SETTINGS, SigninAccessPoint.BOOKMARK_MANAGER, SigninAccessPoint.RECENT_TABS, SigninAccessPoint.SIGNIN_PROMO, SigninAccessPoint.NTP_CONTENT_SUGGESTIONS, SigninAccessPoint.AUTOFILL_DROPDOWN}) @@ -56,7 +41,7 @@ public @interface AccessPoint {} private @AccessPoint int mAccessPoint; - private @SigninFlowType int mSigninFlowType; + private @AccountSigninView.SigninFlowType int mSigninFlowType; private boolean mIsFromPersonalizedPromo; /** @@ -86,8 +71,9 @@ public static Intent createIntentForDefaultSigninFlow( Context context, @AccessPoint int accessPoint, boolean isFromPersonalizedPromo) { Intent intent = new Intent(context, AccountSigninActivity.class); - intent.putExtra(INTENT_SIGNIN_ACCESS_POINT, accessPoint); - intent.putExtra(INTENT_SIGNIN_FLOW_TYPE, SIGNIN_FLOW_DEFAULT); + Bundle viewArguments = AccountSigninView.createArgumentsForDefaultFlow( + accessPoint, false /* isChildAccount */); + intent.putExtras(viewArguments); intent.putExtra(INTENT_IS_FROM_PERSONALIZED_PROMO, isFromPersonalizedPromo); return intent; } @@ -106,10 +92,10 @@ @AccessPoint int accessPoint, String selectAccount, boolean isDefaultAccount, boolean isFromPersonalizedPromo) { Intent intent = new Intent(context, AccountSigninActivity.class); - intent.putExtra(INTENT_SIGNIN_ACCESS_POINT, accessPoint); - intent.putExtra(INTENT_SIGNIN_FLOW_TYPE, SIGNIN_FLOW_CONFIRMATION_ONLY); - intent.putExtra(INTENT_ACCOUNT_NAME, selectAccount); - intent.putExtra(INTENT_IS_DEFAULT_ACCOUNT, isDefaultAccount); + Bundle viewArguments = AccountSigninView.createArgumentsForConfirmationFlow(accessPoint, + false /* isChildAccount */, selectAccount, isDefaultAccount, + AccountSigninView.UNDO_ABORT); + intent.putExtras(viewArguments); intent.putExtra(INTENT_IS_FROM_PERSONALIZED_PROMO, isFromPersonalizedPromo); return intent; } @@ -124,8 +110,8 @@ public static Intent createIntentForAddAccountSigninFlow( Context context, @AccessPoint int accessPoint, boolean isFromPersonalizedPromo) { Intent intent = new Intent(context, AccountSigninActivity.class); - intent.putExtra(INTENT_SIGNIN_ACCESS_POINT, accessPoint); - intent.putExtra(INTENT_SIGNIN_FLOW_TYPE, SIGNIN_FLOW_ADD_NEW_ACCOUNT); + Bundle viewArguments = AccountSigninView.createArgumentsForAddAccountFlow(accessPoint); + intent.putExtras(viewArguments); intent.putExtra(INTENT_IS_FROM_PERSONALIZED_PROMO, isFromPersonalizedPromo); return intent; } @@ -146,7 +132,12 @@ // We don't trust android to restore the saved state correctly, so pass null. super.onCreate(null); - mAccessPoint = getIntent().getIntExtra(INTENT_SIGNIN_ACCESS_POINT, -1); + AccountSigninView view = + (AccountSigninView) getLayoutInflater().inflate(R.layout.account_signin_view, null); + + view.init(getIntent().getExtras(), this, this); + + mAccessPoint = view.getSigninAccessPoint(); assert mAccessPoint == SigninAccessPoint.BOOKMARK_MANAGER || mAccessPoint == SigninAccessPoint.RECENT_TABS || mAccessPoint == SigninAccessPoint.SETTINGS @@ -155,35 +146,10 @@ || mAccessPoint == SigninAccessPoint.AUTOFILL_DROPDOWN : "invalid access point: " + mAccessPoint; + mSigninFlowType = view.getSigninFlowType(); mIsFromPersonalizedPromo = getIntent().getBooleanExtra(INTENT_IS_FROM_PERSONALIZED_PROMO, false); - AccountSigninView view = (AccountSigninView) LayoutInflater.from(this).inflate( - R.layout.account_signin_view, null); - - mSigninFlowType = getIntent().getIntExtra(INTENT_SIGNIN_FLOW_TYPE, -1); - switch (mSigninFlowType) { - case SIGNIN_FLOW_DEFAULT: - view.initFromSelectionPage(mAccessPoint, false, this, this); - break; - case SIGNIN_FLOW_CONFIRMATION_ONLY: { - String accountName = getIntent().getStringExtra(INTENT_ACCOUNT_NAME); - if (accountName == null) { - throw new IllegalArgumentException("Account name can't be null!"); - } - boolean isDefaultAccount = - getIntent().getBooleanExtra(INTENT_IS_DEFAULT_ACCOUNT, false); - view.initFromConfirmationPage(mAccessPoint, false, accountName, isDefaultAccount, - AccountSigninView.UNDO_ABORT, this, this); - break; - } - case SIGNIN_FLOW_ADD_NEW_ACCOUNT: - view.initFromAddAccountPage(mAccessPoint, this, this); - break; - default: - throw new IllegalArgumentException("Unknown signin flow type: " + mSigninFlowType); - } - setContentView(view); SigninManager.logSigninStartAccessPoint(mAccessPoint); @@ -233,13 +199,13 @@ final String histogram; switch (mSigninFlowType) { - case SIGNIN_FLOW_ADD_NEW_ACCOUNT: + case AccountSigninView.SIGNIN_FLOW_ADD_NEW_ACCOUNT: histogram = "Signin.SigninCompletedAccessPoint.NewAccount"; break; - case SIGNIN_FLOW_CONFIRMATION_ONLY: + case AccountSigninView.SIGNIN_FLOW_CONFIRMATION_ONLY: histogram = "Signin.SigninCompletedAccessPoint.WithDefault"; break; - case SIGNIN_FLOW_DEFAULT: + case AccountSigninView.SIGNIN_FLOW_DEFAULT: histogram = "Signin.SigninCompletedAccessPoint.NotDefault"; break; default: @@ -257,13 +223,13 @@ final String histogram; switch (mSigninFlowType) { - case SIGNIN_FLOW_ADD_NEW_ACCOUNT: + case AccountSigninView.SIGNIN_FLOW_ADD_NEW_ACCOUNT: histogram = "Signin.SigninStartedAccessPoint.NewAccount"; break; - case SIGNIN_FLOW_CONFIRMATION_ONLY: + case AccountSigninView.SIGNIN_FLOW_CONFIRMATION_ONLY: histogram = "Signin.SigninStartedAccessPoint.WithDefault"; break; - case SIGNIN_FLOW_DEFAULT: + case AccountSigninView.SIGNIN_FLOW_DEFAULT: histogram = "Signin.SigninStartedAccessPoint.NotDefault"; break; default:
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/signin/AccountSigninView.java b/chrome/android/java/src/org/chromium/chrome/browser/signin/AccountSigninView.java index 72daa80..1dadc7c 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/signin/AccountSigninView.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/signin/AccountSigninView.java
@@ -7,6 +7,7 @@ import android.app.Activity; import android.app.FragmentManager; import android.content.Context; +import android.os.Bundle; import android.os.SystemClock; import android.support.annotation.IntDef; import android.support.annotation.StringRes; @@ -47,8 +48,7 @@ /** * This view allows the user to select an account to log in to, add an account, cancel account - * selection, etc. Users of this class should call {@link #initFromSelectionPage} or - * {@link #initFromConfirmationPage} after the view has been inflated. + * selection, etc. Users of this class should call {@link #init} after the view has been inflated. */ public class AccountSigninView extends FrameLayout { /** @@ -105,6 +105,21 @@ private static final String SETTINGS_LINK_OPEN = "<LINK1>"; private static final String SETTINGS_LINK_CLOSE = "</LINK1>"; + private static final String ARGUMENT_ACCESS_POINT = "AccountSigninView.AccessPoint"; + private static final String ARGUMENT_SIGNIN_FLOW_TYPE = "AccountSigninView.FlowType"; + private static final String ARGUMENT_ACCOUNT_NAME = "AccountSigninView.AccountName"; + private static final String ARGUMENT_IS_DEFAULT_ACCOUNT = "AccountSigninView.IsDefaultAccount"; + private static final String ARGUMENT_IS_CHILD_ACCOUNT = "AccountSigninView.IsChildAccount"; + private static final String ARGUMENT_UNDO_BEHAVIOR = "AccountSigninView.UndoBehavior"; + + @IntDef({SIGNIN_FLOW_DEFAULT, SIGNIN_FLOW_CONFIRMATION_ONLY, SIGNIN_FLOW_ADD_NEW_ACCOUNT}) + @Retention(RetentionPolicy.SOURCE) + public @interface SigninFlowType {} + + public static final int SIGNIN_FLOW_DEFAULT = 0; + public static final int SIGNIN_FLOW_CONFIRMATION_ONLY = 1; + public static final int SIGNIN_FLOW_ADD_NEW_ACCOUNT = 2; + /** Specifies different behaviors for "Undo" button on signin confirmation page. */ @IntDef({UNDO_INVISIBLE, UNDO_BACK_TO_SELECTION, UNDO_ABORT}) @Retention(RetentionPolicy.SOURCE) @@ -127,6 +142,8 @@ private Button mMoreButton; private Listener mListener; private Delegate mDelegate; + private @SigninAccessPoint int mSigninAccessPoint; + private @SigninFlowType int mSigninFlowType; private @UndoBehavior int mUndoBehavior; private String mSelectedAccountName; private boolean mIsDefaultAccountSelected; @@ -153,70 +170,110 @@ } /** - * Initializes the view from account selection page. After selecting the account, signin - * confirmation page will be opened. + * Creates an argument bundle to start AccountSigninView from the account selection page. * * @param accessPoint The access point for starting signin flow. * @param isChildAccount Whether this view is for a child account. - * @param delegate The UI object creation delegate. - * @param listener The account selection event listener. */ - public void initFromSelectionPage(@SigninAccessPoint int accessPoint, boolean isChildAccount, - Delegate delegate, Listener listener) { - initAccessPoint(accessPoint); - mIsChildAccount = isChildAccount; - mUndoBehavior = UNDO_BACK_TO_SELECTION; - mDelegate = delegate; - mListener = listener; - showSigninPage(); + public static Bundle createArgumentsForDefaultFlow( + @SigninAccessPoint int accessPoint, boolean isChildAccount) { + Bundle result = new Bundle(); + result.putInt(ARGUMENT_SIGNIN_FLOW_TYPE, SIGNIN_FLOW_DEFAULT); + result.putInt(ARGUMENT_ACCESS_POINT, accessPoint); + result.putBoolean(ARGUMENT_IS_CHILD_ACCOUNT, isChildAccount); + result.putInt(ARGUMENT_UNDO_BEHAVIOR, UNDO_BACK_TO_SELECTION); + return result; } /** - * Initializes the view from account selection page. After selecting the account, signin - * confirmation page will be opened. + * Creates an argument bundle to start AccountSigninView from the new account creation screen. * * @param accessPoint The access point for starting signin flow. - * @param delegate The UI object creation delegate. - * @param listener The account selection event listener. */ - public void initFromAddAccountPage( - @SigninAccessPoint int accessPoint, Delegate delegate, Listener listener) { - initAccessPoint(accessPoint); - mIsChildAccount = false; // Children profiles can't add accounts. - mUndoBehavior = UNDO_ABORT; - mDelegate = delegate; - mListener = listener; - showSigninPage(); - - RecordUserAction.record("Signin_AddAccountToDevice"); - mListener.onNewAccount(); + public static Bundle createArgumentsForAddAccountFlow(@SigninAccessPoint int accessPoint) { + Bundle result = new Bundle(); + result.putInt(ARGUMENT_SIGNIN_FLOW_TYPE, SIGNIN_FLOW_ADD_NEW_ACCOUNT); + result.putInt(ARGUMENT_ACCESS_POINT, accessPoint); + result.putBoolean(ARGUMENT_IS_CHILD_ACCOUNT, false); // Children profiles can't add accounts + result.putInt(ARGUMENT_UNDO_BEHAVIOR, UNDO_ABORT); + return result; } /** - * Initializes the view from signin confirmation page. The account name should be provided by - * the caller. + * Creates an argument bundle to start AccountSigninView from the signin confirmation page. * * @param accessPoint The access point for starting signin flow. * @param isChildAccount Whether this view is for a child account. * @param accountName An account that should be used for confirmation page and signin. * @param isDefaultAccount Whether {@param accountName} is a default account, used for metrics. * @param undoBehavior "Undo" button behavior (see {@link UndoBehavior}). + */ + public static Bundle createArgumentsForConfirmationFlow(@SigninAccessPoint int accessPoint, + boolean isChildAccount, String accountName, boolean isDefaultAccount, + @UndoBehavior int undoBehavior) { + Bundle result = new Bundle(); + result.putInt(ARGUMENT_SIGNIN_FLOW_TYPE, SIGNIN_FLOW_CONFIRMATION_ONLY); + result.putInt(ARGUMENT_ACCESS_POINT, accessPoint); + result.putBoolean(ARGUMENT_IS_CHILD_ACCOUNT, isChildAccount); + result.putString(ARGUMENT_ACCOUNT_NAME, accountName); + result.putBoolean(ARGUMENT_IS_DEFAULT_ACCOUNT, isDefaultAccount); + result.putInt(ARGUMENT_UNDO_BEHAVIOR, undoBehavior); + return result; + } + + /** + * Initializes the view. + * + * @param arguments The argument bundle created by {@link #createArgumentsForDefaultFlow}, + * {@link #createArgumentsForAddAccountFlow} or + * {@link #createArgumentsForConfirmationFlow}. * @param delegate The UI object creation delegate. * @param listener The account selection event listener. */ - public void initFromConfirmationPage(@SigninAccessPoint int accessPoint, boolean isChildAccount, - String accountName, boolean isDefaultAccount, @UndoBehavior int undoBehavior, - Delegate delegate, Listener listener) { + public void init(Bundle arguments, Delegate delegate, Listener listener) { + @SigninAccessPoint int accessPoint = arguments.getInt(ARGUMENT_ACCESS_POINT, -1); + assert accessPoint != -1; + initAccessPoint(accessPoint); - mIsChildAccount = isChildAccount; - mUndoBehavior = undoBehavior; + mIsChildAccount = arguments.getBoolean(ARGUMENT_IS_CHILD_ACCOUNT, false); + mUndoBehavior = arguments.getInt(ARGUMENT_UNDO_BEHAVIOR, -1); mDelegate = delegate; mListener = listener; - showConfirmSigninPageAccountTrackerServiceCheck(accountName, isDefaultAccount); - triggerUpdateAccounts(); + + mSigninFlowType = arguments.getInt(ARGUMENT_SIGNIN_FLOW_TYPE, -1); + switch (mSigninFlowType) { + case SIGNIN_FLOW_DEFAULT: + showSigninPage(); + break; + case SIGNIN_FLOW_CONFIRMATION_ONLY: { + String accountName = arguments.getString(ARGUMENT_ACCOUNT_NAME); + assert accountName != null; + boolean isDefaultAccount = arguments.getBoolean(ARGUMENT_IS_DEFAULT_ACCOUNT, false); + showConfirmSigninPageAccountTrackerServiceCheck(accountName, isDefaultAccount); + triggerUpdateAccounts(); + break; + } + case SIGNIN_FLOW_ADD_NEW_ACCOUNT: + showSigninPage(); + RecordUserAction.record("Signin_AddAccountToDevice"); + mListener.onNewAccount(); + break; + default: + assert false : "Unknown or missing signin flow type: " + mSigninFlowType; + return; + } + } + + public @SigninFlowType int getSigninFlowType() { + return mSigninFlowType; + } + + public @SigninAccessPoint int getSigninAccessPoint() { + return mSigninAccessPoint; } private void initAccessPoint(@SigninAccessPoint int accessPoint) { + mSigninAccessPoint = accessPoint; if (accessPoint == SigninAccessPoint.START_PAGE || accessPoint == SigninAccessPoint.SIGNIN_PROMO) { mCancelButtonTextId = R.string.no_thanks;
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/survey/ChromeHomeSurveyController.java b/chrome/android/java/src/org/chromium/chrome/browser/survey/ChromeHomeSurveyController.java index 817e63a..9532bcb8 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/survey/ChromeHomeSurveyController.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/survey/ChromeHomeSurveyController.java
@@ -91,17 +91,8 @@ mTabModelSelector = tabModelSelector; SurveyController surveyController = SurveyController.getInstance(); - CommandLine commandLine = CommandLine.getInstance(); - String siteId; - if (commandLine.hasSwitch(PARAM_NAME)) { - siteId = commandLine.getSwitchValue(PARAM_NAME); - } else if (ChromeFeatureList.isEnabled(ChromeFeatureList.CHROME_HOME_SURVEY)) { - siteId = TEST_SITE_ID; - } else { - siteId = VariationsAssociatedData.getVariationParamValue( - HAPPINESS_SURVEY_TRIAL_NAME, PARAM_NAME); - } + String siteId = getSiteId(); if (TextUtils.isEmpty(siteId)) return; Runnable onSuccessRunnable = new Runnable() { @@ -115,6 +106,18 @@ surveyController.downloadSurvey(context, siteId, onSuccessRunnable, siteContext); } + private String getSiteId() { + CommandLine commandLine = CommandLine.getInstance(); + if (commandLine.hasSwitch(PARAM_NAME)) { + return commandLine.getSwitchValue(PARAM_NAME); + } else if (ChromeFeatureList.isEnabled(ChromeFeatureList.CHROME_HOME_SURVEY)) { + return TEST_SITE_ID; + } else { + return VariationsAssociatedData.getVariationParamValue( + HAPPINESS_SURVEY_TRIAL_NAME, PARAM_NAME); + } + } + /** @return Whether the user qualifies for the survey. */ private boolean doesUserQualifyForSurvey() { if (DeviceFormFactor.isTablet()) return false; @@ -403,10 +406,14 @@ @Override protected Boolean doInBackground(Void... params) { if (!mController.doesUserQualifyForSurvey()) return false; - return mController.isRandomlySelectedForSurvey() - || CommandLine.getInstance().hasSwitch( - ChromeSwitches.CHROME_HOME_FORCE_ENABLE_SURVEY) - || ChromeFeatureList.isEnabled(ChromeFeatureList.CHROME_HOME_SURVEY); + if (SurveyController.getInstance().doesSurveyExist(mController.getSiteId(), mContext)) { + return true; + } else { + return mController.isRandomlySelectedForSurvey() + || CommandLine.getInstance().hasSwitch( + ChromeSwitches.CHROME_HOME_FORCE_ENABLE_SURVEY) + || ChromeFeatureList.isEnabled(ChromeFeatureList.CHROME_HOME_SURVEY); + } } @Override
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/survey/SurveyController.java b/chrome/android/java/src/org/chromium/chrome/browser/survey/SurveyController.java index 9b5d9c6..134fd85 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/survey/SurveyController.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/survey/SurveyController.java
@@ -28,6 +28,16 @@ } /** + * Returns if there already exists a downloaded survey from the provided site id. + * @param siteId The id of the site from where the survey should have been downloaded. + * @param context The context of the application. + * @return If the survey with a matching site id exists. + */ + public boolean doesSurveyExist(String siteId, Context context) { + return false; + } + + /** * Asynchronously downloads the survey using the provided parameters. * @param context The context used to register a broadcast receiver. * @param siteId The id of the site from where the survey will be downloaded.
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/tab/Tab.java b/chrome/android/java/src/org/chromium/chrome/browser/tab/Tab.java index 63b82c3..c2fb7222 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/tab/Tab.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/tab/Tab.java
@@ -113,6 +113,7 @@ import org.chromium.content_public.browser.GestureStateListener; import org.chromium.content_public.browser.ImeEventObserver; import org.chromium.content_public.browser.LoadUrlParams; +import org.chromium.content_public.browser.SelectionPopupController; import org.chromium.content_public.browser.WebContents; import org.chromium.content_public.common.BrowserControlsState; import org.chromium.content_public.common.Referrer; @@ -518,8 +519,10 @@ mFullscreenManager.setPersistentFullscreenMode(enable); } - if (enable && mContentViewCore != null) { - mContentViewCore.destroySelectActionMode(); + if (enable && getWebContents() != null) { + SelectionPopupController controller = + SelectionPopupController.fromWebContents(getWebContents()); + controller.destroySelectActionMode(); } // When going into fullscreen, we want to remove any cached thumbnail of the Tab. @@ -1793,9 +1796,10 @@ cv.setContentDescription(mThemedApplicationContext.getResources().getString( R.string.accessibility_content_view)); cvc.initialize(new TabViewAndroidDelegate(this, cv), cv, webContents, getWindowAndroid()); + SelectionPopupController controller = SelectionPopupController.fromWebContents(webContents); ChromeActionModeCallback actionModeCallback = new ChromeActionModeCallback( - mThemedApplicationContext, this, cvc.getActionModeCallbackHelper()); - cvc.setActionModeCallback(actionModeCallback); + mThemedApplicationContext, this, controller.getActionModeCallbackHelper()); + controller.setActionModeCallback(actionModeCallback); return cvc; }
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/tab/TabStateBrowserControlsVisibilityDelegate.java b/chrome/android/java/src/org/chromium/chrome/browser/tab/TabStateBrowserControlsVisibilityDelegate.java index 556c616..a8b0aef8 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/tab/TabStateBrowserControlsVisibilityDelegate.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/tab/TabStateBrowserControlsVisibilityDelegate.java
@@ -13,7 +13,7 @@ import org.chromium.chrome.browser.util.AccessibilityUtil; import org.chromium.components.dom_distiller.core.DomDistillerUrlUtils; import org.chromium.components.security_state.ConnectionSecurityLevel; -import org.chromium.content.browser.ContentViewCore; +import org.chromium.content_public.browser.SelectionPopupController; import org.chromium.content_public.browser.WebContents; /** @@ -145,8 +145,8 @@ enableHidingBrowserControls &= !AccessibilityUtil.isAccessibilityEnabled(); - ContentViewCore cvc = mTab.getContentViewCore(); - enableHidingBrowserControls &= cvc == null || !cvc.isFocusedNodeEditable(); + enableHidingBrowserControls &= + !SelectionPopupController.fromWebContents(webContents).isFocusedNodeEditable(); enableHidingBrowserControls &= !mTab.isShowingErrorPage(); enableHidingBrowserControls &= !webContents.isShowingInterstitialPage(); enableHidingBrowserControls &= !mTab.isRendererUnresponsive();
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/vr_shell/VrCompositorSurfaceManager.java b/chrome/android/java/src/org/chromium/chrome/browser/vr_shell/VrCompositorSurfaceManager.java new file mode 100644 index 0000000..2a592627 --- /dev/null +++ b/chrome/android/java/src/org/chromium/chrome/browser/vr_shell/VrCompositorSurfaceManager.java
@@ -0,0 +1,106 @@ +// 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. + +package org.chromium.chrome.browser.vr_shell; + +import android.graphics.drawable.Drawable; +import android.support.annotation.IntDef; +import android.view.Surface; + +import org.chromium.chrome.browser.compositor.CompositorSurfaceManager; + +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; + +/** + * Provides the texture-backed surface used for drawing Android UI in VR to the CompositorView. + * This class only partially fulfills the contract that the CompositorSurfaceManagerImpl fulfills. + * + * This class doesn't use SurfaceViews, as the texture-backed surface is drawn using GL during VR + * scene compositing. This class also doesn't really manage the Surface in any way, and fakes the + * standard Surface/View lifecycle so that the compositor remains unaware of this. The surface + * format requested by the compositor is also ignored. + */ +public class VrCompositorSurfaceManager implements CompositorSurfaceManager { + private static final int SURFACE_NOT_REQUESTED = 0; + private static final int SURFACE_REQUESTED = 1; + private static final int SURFACE_PROVIDED = 2; + + @Retention(RetentionPolicy.SOURCE) + @IntDef({SURFACE_NOT_REQUESTED, SURFACE_REQUESTED, SURFACE_PROVIDED}) + private @interface SurfaceState {} + + private @SurfaceState int mSurfaceState = SURFACE_NOT_REQUESTED; + private Surface mSurface; + private int mFormat; + private int mWidth; + private int mHeight; + + // Client that we notify about surface change events. + private SurfaceManagerCallbackTarget mClient; + + public VrCompositorSurfaceManager(SurfaceManagerCallbackTarget client) { + mClient = client; + } + + /* package */ void setSurface(Surface surface, int format, int width, int height) { + if (mSurfaceState == SURFACE_PROVIDED) shutDown(); + mSurface = surface; + mFormat = format; + mWidth = width; + mHeight = height; + if (mSurfaceState == SURFACE_REQUESTED) { + mClient.surfaceCreated(mSurface); + mClient.surfaceChanged(mSurface, mFormat, mWidth, mHeight); + mSurfaceState = SURFACE_PROVIDED; + } + } + + /* package */ void surfaceResized(int width, int height) { + assert mSurface != null; + mWidth = width; + mHeight = height; + if (mSurfaceState == SURFACE_PROVIDED) { + mClient.surfaceChanged(mSurface, mFormat, mWidth, mHeight); + } + } + + /* package */ void surfaceDestroyed() { + shutDown(); + mSurface = null; + } + + @Override + public void shutDown() { + if (mSurfaceState == SURFACE_PROVIDED) mClient.surfaceDestroyed(mSurface); + mSurfaceState = SURFACE_NOT_REQUESTED; + } + + @Override + public void requestSurface(int format) { + if (mSurface == null) { + mSurfaceState = SURFACE_REQUESTED; + return; + } + if (mSurfaceState == SURFACE_PROVIDED) shutDown(); + mClient.surfaceCreated(mSurface); + mClient.surfaceChanged(mSurface, mFormat, mWidth, mHeight); + mSurfaceState = SURFACE_PROVIDED; + } + + @Override + public void doneWithUnownedSurface() {} + + @Override + public void recreateSurfaceForJellyBean() {} + + @Override + public void setBackgroundDrawable(Drawable background) {} + + @Override + public void setWillNotDraw(boolean willNotDraw) {} + + @Override + public void setVisibility(int visibility) {} +}
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/webapps/WebappSplashScreenController.java b/chrome/android/java/src/org/chromium/chrome/browser/webapps/WebappSplashScreenController.java index 219c2ce4..dccf552 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/webapps/WebappSplashScreenController.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/webapps/WebappSplashScreenController.java
@@ -283,9 +283,8 @@ return; } - mCompositorViewHolder.getCompositorView().surfaceRedrawNeededAsync(null, () -> { - animateHidingSplashScreen(tab, reason); - }); + mCompositorViewHolder.getCompositorView().surfaceRedrawNeededAsync( + () -> { animateHidingSplashScreen(tab, reason); }); } /** Performs the splash screen hiding animation. */
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/widget/bottomsheet/BottomSheet.java b/chrome/android/java/src/org/chromium/chrome/browser/widget/bottomsheet/BottomSheet.java index e966222..db086ba 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/widget/bottomsheet/BottomSheet.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/widget/bottomsheet/BottomSheet.java
@@ -57,8 +57,9 @@ import org.chromium.chrome.browser.widget.bottomsheet.BottomSheetContentController.ContentType; import org.chromium.chrome.browser.widget.textbubble.TextBubble; import org.chromium.content.browser.BrowserStartupController; -import org.chromium.content.browser.ContentViewCore; import org.chromium.content_public.browser.LoadUrlParams; +import org.chromium.content_public.browser.SelectionPopupController; +import org.chromium.content_public.browser.WebContents; import org.chromium.content_public.common.BrowserControlsState; import org.chromium.ui.UiUtils; @@ -1352,9 +1353,9 @@ Tab activeTab = getActiveTab(); if (activeTab == null) return; - ContentViewCore contentViewCore = activeTab.getContentViewCore(); - if (contentViewCore == null) return; - contentViewCore.clearSelection(); + WebContents webContents = activeTab.getWebContents(); + if (webContents == null) return; + SelectionPopupController.fromWebContents(webContents).clearSelection(); } /**
diff --git a/chrome/android/java_sources.gni b/chrome/android/java_sources.gni index ea43e92..9c8741fd 100644 --- a/chrome/android/java_sources.gni +++ b/chrome/android/java_sources.gni
@@ -148,6 +148,7 @@ "java/src/org/chromium/chrome/browser/childaccounts/ChildAccountFeedbackReporter.java", "java/src/org/chromium/chrome/browser/childaccounts/ChildAccountService.java", "java/src/org/chromium/chrome/browser/compositor/CompositorSurfaceManager.java", + "java/src/org/chromium/chrome/browser/compositor/CompositorSurfaceManagerImpl.java", "java/src/org/chromium/chrome/browser/compositor/CompositorView.java", "java/src/org/chromium/chrome/browser/compositor/CompositorViewHolder.java", "java/src/org/chromium/chrome/browser/compositor/Invalidator.java", @@ -586,7 +587,6 @@ "java/src/org/chromium/chrome/browser/media/remote/RemoteVideoInfo.java", "java/src/org/chromium/chrome/browser/media/remote/PositionExtrapolator.java", "java/src/org/chromium/chrome/browser/media/router/BaseMediaRouteDialogManager.java", - "java/src/org/chromium/chrome/browser/media/router/BaseMediaRouteProvider.java", "java/src/org/chromium/chrome/browser/media/router/ChromeMediaRouter.java", "java/src/org/chromium/chrome/browser/media/router/ChromeMediaRouterDialogController.java", "java/src/org/chromium/chrome/browser/media/router/DiscoveryDelegate.java", @@ -597,6 +597,7 @@ "java/src/org/chromium/chrome/browser/media/router/MediaRouteDialogManager.java", "java/src/org/chromium/chrome/browser/media/router/MediaRouteManager.java", "java/src/org/chromium/chrome/browser/media/router/MediaRouteProvider.java", + "java/src/org/chromium/chrome/browser/media/router/cast/BaseMediaRouteProvider.java", "java/src/org/chromium/chrome/browser/media/router/cast/CastMediaRouteProvider.java", "java/src/org/chromium/chrome/browser/media/router/cast/CastMediaSource.java", "java/src/org/chromium/chrome/browser/media/router/cast/CastMessageHandler.java", @@ -1260,6 +1261,7 @@ "java/src/org/chromium/chrome/browser/vr/VrMainActivity.java", "java/src/org/chromium/chrome/browser/vr_shell/VrCancelAnimationActivity.java", "java/src/org/chromium/chrome/browser/vr_shell/VrClassesWrapper.java", + "java/src/org/chromium/chrome/browser/vr_shell/VrCompositorSurfaceManager.java", "java/src/org/chromium/chrome/browser/vr_shell/VrCoreVersionChecker.java", "java/src/org/chromium/chrome/browser/vr_shell/VrDaydreamApi.java", "java/src/org/chromium/chrome/browser/vr_shell/VrFeedbackStatus.java", @@ -1887,7 +1889,7 @@ "junit/src/org/chromium/chrome/browser/browseractions/BrowserActionsIntentTest.java", "junit/src/org/chromium/chrome/browser/compositor/animation/CompositorAnimatorTest.java", "junit/src/org/chromium/chrome/browser/compositor/overlays/strip/StripLayoutHelperTest.java", - "junit/src/org/chromium/chrome/browser/compositor/CompositorSurfaceManagerTest.java", + "junit/src/org/chromium/chrome/browser/compositor/CompositorSurfaceManagerImplTest.java", "junit/src/org/chromium/chrome/browser/contextualsearch/ContextualSearchContextForTest.java", "junit/src/org/chromium/chrome/browser/contextualsearch/ContextualSearchContextTest.java", "junit/src/org/chromium/chrome/browser/contextualsearch/ContextualSearchEntityHeuristicTest.java",
diff --git a/chrome/android/javatests/DEPS b/chrome/android/javatests/DEPS index 1076e2692..6387f971 100644 --- a/chrome/android/javatests/DEPS +++ b/chrome/android/javatests/DEPS
@@ -25,7 +25,6 @@ "!content/public/android/java/src/org/chromium/content/browser/ContentView.java", "!content/public/android/java/src/org/chromium/content/browser/InterstitialPageDelegateAndroid.java", "!content/public/android/java/src/org/chromium/content/browser/input/ChromiumBaseInputConnection.java", - "!content/public/android/java/src/org/chromium/content/browser/SelectionPopupController.java", "!content/public/android/java/src/org/chromium/content/common/ContentSwitches.java", "-content/public/android/javatests",
diff --git a/chrome/android/javatests/src/org/chromium/chrome/browser/TabsTest.java b/chrome/android/javatests/src/org/chromium/chrome/browser/TabsTest.java index f6799a0..3231f3b 100644 --- a/chrome/android/javatests/src/org/chromium/chrome/browser/TabsTest.java +++ b/chrome/android/javatests/src/org/chromium/chrome/browser/TabsTest.java
@@ -76,6 +76,7 @@ import org.chromium.content.browser.test.util.TouchCommon; import org.chromium.content.browser.test.util.UiUtils; import org.chromium.content.common.ContentSwitches; +import org.chromium.content_public.browser.SelectionPopupController; import org.chromium.content_public.browser.WebContents; import org.chromium.content_public.browser.WebContentsObserver; import org.chromium.net.test.EmbeddedTestServer; @@ -384,10 +385,11 @@ CriteriaHelper.pollUiThread(new Criteria() { @Override public boolean isSatisfied() { - final String actualText = mActivityTestRule.getActivity() - .getActivityTab() - .getContentViewCore() - .getSelectedText(); + WebContents webContents = + mActivityTestRule.getActivity().getActivityTab().getWebContents(); + SelectionPopupController controller = + SelectionPopupController.fromWebContents(webContents); + final String actualText = controller.getSelectedText(); updateFailureReason( "expected selected text: [" + text + "], but got: [" + actualText + "]"); return text.equals(actualText);
diff --git a/chrome/android/javatests/src/org/chromium/chrome/browser/contextualsearch/ContextualSearchManagerTest.java b/chrome/android/javatests/src/org/chromium/chrome/browser/contextualsearch/ContextualSearchManagerTest.java index 0f973f18..a4a15e9 100644 --- a/chrome/android/javatests/src/org/chromium/chrome/browser/contextualsearch/ContextualSearchManagerTest.java +++ b/chrome/android/javatests/src/org/chromium/chrome/browser/contextualsearch/ContextualSearchManagerTest.java
@@ -12,7 +12,6 @@ import android.app.Activity; import android.app.Instrumentation; import android.app.Instrumentation.ActivityMonitor; -import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.content.SharedPreferences; @@ -83,9 +82,10 @@ import org.chromium.content.browser.test.util.CriteriaHelper; import org.chromium.content.browser.test.util.DOMUtils; import org.chromium.content.browser.test.util.KeyUtils; -import org.chromium.content.browser.test.util.TestContentViewCore; +import org.chromium.content.browser.test.util.TestSelectionPopupController; import org.chromium.content.browser.test.util.TouchCommon; import org.chromium.content_public.browser.SelectionClient; +import org.chromium.content_public.browser.SelectionPopupController; import org.chromium.net.test.EmbeddedTestServer; import org.chromium.ui.base.PageTransition; import org.chromium.ui.test.util.UiDisableIf; @@ -581,20 +581,14 @@ } /** - * A ContentViewCore that has some methods stubbed out for testing. - * TODO(pedrosimonetti): consider using the real ContentViewCore instead. + * A SelectionPopupController that has some methods stubbed out for testing. */ - private static final class StubbedContentViewCore extends TestContentViewCore { + private static final class StubbedSelectionPopupController + extends TestSelectionPopupController { private boolean mIsFocusedNodeEditable; - public StubbedContentViewCore(Context context) { - super(context, ""); - } + public StubbedSelectionPopupController() {} - /** - * Mocks the result of isFocusedNodeEditable() for testing. - * @param isFocusedNodeEditable Whether the focused node is editable. - */ public void setIsFocusedNodeEditableForTest(boolean isFocusedNodeEditable) { mIsFocusedNodeEditable = isFocusedNodeEditable; } @@ -1185,21 +1179,17 @@ @SmallTest @Feature({"ContextualSearch"}) public void testIsValidSelection() { - StubbedContentViewCore stubbedCvc = - new StubbedContentViewCore(mActivityTestRule.getActivity().getBaseContext()); - Assert.assertTrue(mSelectionController.isValidSelection("valid", stubbedCvc)); - Assert.assertFalse(mSelectionController.isValidSelection(" ", stubbedCvc)); - stubbedCvc.setIsFocusedNodeEditableForTest(true); - Assert.assertFalse(mSelectionController.isValidSelection("editable", stubbedCvc)); - stubbedCvc.setIsFocusedNodeEditableForTest(false); + StubbedSelectionPopupController c = new StubbedSelectionPopupController(); + Assert.assertTrue(mSelectionController.isValidSelection("valid", c)); + Assert.assertFalse(mSelectionController.isValidSelection(" ", c)); + c.setIsFocusedNodeEditableForTest(true); + Assert.assertFalse(mSelectionController.isValidSelection("editable", c)); + c.setIsFocusedNodeEditableForTest(false); String numberString = "0123456789"; StringBuilder longStringBuilder = new StringBuilder(); - for (int i = 0; i < 11; i++) { - longStringBuilder.append(numberString); - } - Assert.assertTrue(mSelectionController.isValidSelection(numberString, stubbedCvc)); - Assert.assertFalse( - mSelectionController.isValidSelection(longStringBuilder.toString(), stubbedCvc)); + for (int i = 0; i < 11; i++) longStringBuilder.append(numberString); + Assert.assertTrue(mSelectionController.isValidSelection(numberString, c)); + Assert.assertFalse(mSelectionController.isValidSelection(longStringBuilder.toString(), c)); } /** @@ -2113,14 +2103,16 @@ CriteriaHelper.pollUiThread(Criteria.equals(visible, new Callable<Boolean>() { @Override public Boolean call() { - return mActivityTestRule.getActivity() - .getActivityTab() - .getContentViewCore() - .isSelectActionBarShowing(); + return getSelectionPopupController().isSelectActionBarShowing(); } })); } + private SelectionPopupController getSelectionPopupController() { + return SelectionPopupController.fromWebContents( + mActivityTestRule.getActivity().getActivityTab().getWebContents()); + } + /** * Tests that ContextualSearchObserver gets notified when user brings up contextual search * panel via long press and then dismisses the panel by tapping copy (hide select action mode). @@ -2136,13 +2128,11 @@ Assert.assertEquals(0, observer.getHideCount()); // Dismiss select action mode. - final ContentViewCore contentViewCore = - mActivityTestRule.getActivity().getActivityTab().getContentViewCore(); assertWaitForSelectActionBarVisible(true); ThreadUtils.runOnUiThreadBlocking(new Runnable() { @Override public void run() { - contentViewCore.destroySelectActionMode(); + getSelectionPopupController().destroySelectActionMode(); } }); assertWaitForSelectActionBarVisible(false);
diff --git a/chrome/android/javatests/src/org/chromium/chrome/browser/contextualsearch/ContextualSearchTapEventTest.java b/chrome/android/javatests/src/org/chromium/chrome/browser/contextualsearch/ContextualSearchTapEventTest.java index 78cfe52..93b2c58 100644 --- a/chrome/android/javatests/src/org/chromium/chrome/browser/contextualsearch/ContextualSearchTapEventTest.java +++ b/chrome/android/javatests/src/org/chromium/chrome/browser/contextualsearch/ContextualSearchTapEventTest.java
@@ -27,10 +27,9 @@ import org.chromium.chrome.browser.compositor.layouts.LayoutUpdateHost; import org.chromium.chrome.test.ChromeActivityTestRule; import org.chromium.chrome.test.ChromeJUnit4ClassRunner; -import org.chromium.content.browser.ContentViewCore; -import org.chromium.content.browser.SelectionPopupController; -import org.chromium.content.browser.test.util.TestContentViewCore; +import org.chromium.content.browser.test.util.TestSelectionPopupController; import org.chromium.content_public.browser.SelectionClient; +import org.chromium.content_public.browser.SelectionPopupController; import org.chromium.content_public.browser.WebContents; import org.chromium.ui.resources.dynamics.DynamicResourceLoader; import org.chromium.ui.touch_selection.SelectionEventType; @@ -80,12 +79,10 @@ public ContextualSearchManagerWrapper(ChromeActivity activity) { super(activity, null); setSelectionController(new MockCSSelectionController(activity, this)); - ContentViewCore contentView = getSelectionController().getBaseContentView(); WebContents webContents = WebContentsFactory.createWebContents(false, false); SelectionPopupController selectionPopupController = - new SelectionPopupController(activity, null, webContents, null); - contentView.setSelectionPopupControllerForTesting(selectionPopupController); - contentView.setSelectionClient(this.getContextualSearchSelectionClient()); + SelectionPopupController.createForTesting(activity, null, webContents, null); + selectionPopupController.setSelectionClient(this.getContextualSearchSelectionClient()); MockContextualSearchPolicy policy = new MockContextualSearchPolicy(); setContextualSearchPolicy(policy); mTranslateController = new MockedCSTranslateController(activity, policy, null); @@ -104,10 +101,11 @@ ContextualSearchContext contextualSearchContext, WebContents baseWebContents) {} /** - * @return A stubbed ContentViewCore for mocking text selection. + * @return A stubbed SelectionPopupController for mocking text selection. */ - public StubbedContentViewCore getBaseContentView() { - return (StubbedContentViewCore) getSelectionController().getBaseContentView(); + public StubbedSelectionPopupController getBaseSelectionPopupController() { + return (StubbedSelectionPopupController) getSelectionController() + .getSelectionPopupController(); } } @@ -117,17 +115,17 @@ * Selection controller that mocks out anything to do with a ContentViewCore. */ private static class MockCSSelectionController extends ContextualSearchSelectionController { - private StubbedContentViewCore mContentViewCore; + private StubbedSelectionPopupController mPopupController; public MockCSSelectionController(ChromeActivity activity, ContextualSearchSelectionHandler handler) { super(activity, handler); - mContentViewCore = new StubbedContentViewCore(activity); + mPopupController = new StubbedSelectionPopupController(); } @Override - StubbedContentViewCore getBaseContentView() { - return mContentViewCore; + protected SelectionPopupController getSelectionPopupController() { + return mPopupController; } } @@ -159,14 +157,13 @@ // -------------------------------------------------------------------------------------------- /** - * A ContentViewCore that has some methods stubbed out for testing. + * A SelectionPopupController that has some methods stubbed out for testing. */ - private static final class StubbedContentViewCore extends TestContentViewCore { + private static final class StubbedSelectionPopupController + extends TestSelectionPopupController { private String mCurrentText; - public StubbedContentViewCore(Context context) { - super(context, ""); - } + public StubbedSelectionPopupController() {} @Override public String getSelectedText() { @@ -184,7 +181,7 @@ * Trigger text selection on the contextual search manager. */ private void mockLongpressText(String text) { - mContextualSearchManager.getBaseContentView().setSelectedText(text); + mContextualSearchManager.getBaseSelectionPopupController().setSelectedText(text); ThreadUtils.runOnUiThreadBlocking(new Runnable() { @Override public void run() { @@ -198,7 +195,7 @@ * Trigger text selection on the contextual search manager. */ private void mockTapText(String text) { - mContextualSearchManager.getBaseContentView().setSelectedText(text); + mContextualSearchManager.getBaseSelectionPopupController().setSelectedText(text); ThreadUtils.runOnUiThreadBlocking(new Runnable() { @Override public void run() {
diff --git a/chrome/android/javatests/src/org/chromium/chrome/browser/fullscreen/FullscreenManagerTest.java b/chrome/android/javatests/src/org/chromium/chrome/browser/fullscreen/FullscreenManagerTest.java index 98346e0..4361b40 100644 --- a/chrome/android/javatests/src/org/chromium/chrome/browser/fullscreen/FullscreenManagerTest.java +++ b/chrome/android/javatests/src/org/chromium/chrome/browser/fullscreen/FullscreenManagerTest.java
@@ -51,6 +51,7 @@ import org.chromium.content.browser.test.util.TestTouchUtils; import org.chromium.content.browser.test.util.TouchCommon; import org.chromium.content.browser.test.util.UiUtils; +import org.chromium.content_public.browser.SelectionPopupController; import org.chromium.net.test.EmbeddedTestServer; import java.util.concurrent.Callable; @@ -521,8 +522,9 @@ CriteriaHelper.pollUiThread(new Criteria() { @Override public boolean isSatisfied() { - ContentViewCore contentViewCore = tab.getContentViewCore(); - return !contentViewCore.isFocusedNodeEditable(); + SelectionPopupController controller = + SelectionPopupController.fromWebContents(tab.getWebContents()); + return !controller.isFocusedNodeEditable(); } }); }
diff --git a/chrome/android/javatests/src/org/chromium/chrome/browser/payments/PaymentRequestRemoveBillingAddressTest.java b/chrome/android/javatests/src/org/chromium/chrome/browser/payments/PaymentRequestRemoveBillingAddressTest.java index 2cfae2fb..cfe83f5 100644 --- a/chrome/android/javatests/src/org/chromium/chrome/browser/payments/PaymentRequestRemoveBillingAddressTest.java +++ b/chrome/android/javatests/src/org/chromium/chrome/browser/payments/PaymentRequestRemoveBillingAddressTest.java
@@ -43,12 +43,12 @@ public void onMainActivityStarted() throws InterruptedException, ExecutionException, TimeoutException { AutofillTestHelper helper = new AutofillTestHelper(); - helper.setProfile(new AutofillProfile("", "https://example.com", - true, "Jane Smith", "Google", "1600 Amphitheatre Pkwy", "CA", "Mountain View", "", - "94043", "", "US", "555-555-5555", "jane.smith@google.com", "en-US")); + helper.setProfile(new AutofillProfile("", "https://example.com", true, "Jane Smith", + "Google", "1600 Amphitheatre Pkwy", "CA", "Mountain View", "", "94043", "", "US", + "515-543-5555", "jane.smith@google.com", "en-US")); String billingAddressId = helper.setProfile(new AutofillProfile("", "https://example.com", true, "Jon Doe", "Google", "340 Main St", "CA", "Los Angeles", "", "90291", "", - "US", "555-555-5555", "jon.doe@google.com", "en-US")); + "US", "515-543-5555", "jon.doe@google.com", "en-US")); helper.setCreditCard(new CreditCard("", "https://example.com", true, true, "Alice", "4111111111111111", "1111", "1", "2050", "visa", R.drawable.visa_card, CardType.UNKNOWN, billingAddressId, "" /* serverId */)); @@ -97,6 +97,6 @@ DialogInterface.BUTTON_POSITIVE, mPaymentRequestTestRule.getDismissed()); mPaymentRequestTestRule.expectResultContains(new String[] {"4111111111111111", "Alice", "12", "123", "Jane Smith", "Google", "1600 Amphitheatre Pkwy", "CA", - "Mountain View", "94043", "US", "+15555555555", "en-US"}); + "Mountain View", "94043", "US", "+15155435555", "en-US"}); } }
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 015eb9b4..7777776 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
@@ -252,4 +252,36 @@ Assert.assertTrue(VrTestFramework.pollJavaScriptBoolean( javascript, POLL_TIMEOUT_LONG_MS, mVrTestFramework.getFirstTabWebContents())); } + + /** + * Tests that entering WebVR presentation from the VR browser, exiting presentation, and + * re-entering presentation works. This is a regression test for crbug.com/799999. + */ + @Test + @CommandLineFlags.Add("enable-webvr") + @Restriction(RESTRICTION_TYPE_VIEWER_DAYDREAM) + @MediumTest + public void testWebVrReEntryFromVrBrowser() throws InterruptedException, TimeoutException { + VrTransitionUtils.forceEnterVr(); + VrTransitionUtils.waitForVrEntry(POLL_TIMEOUT_LONG_MS); + EmulatedVrController controller = new EmulatedVrController(mVrTestRule.getActivity()); + + mVrTestFramework.loadUrlAndAwaitInitialization( + VrTestFramework.getHtmlTestFile("test_webvr_reentry_from_vr_browser"), + PAGE_LOAD_TIMEOUT_S); + VrTransitionUtils.enterPresentationOrFail(mVrTestFramework.getFirstTabCvc()); + + VrTestFramework.executeStepAndWait( + "stepVerifyFirstPresent()", mVrTestFramework.getFirstTabWebContents()); + // The bug does not reproduce with vrDisplay.exitPresent(), so use the controller to exit. + controller.pressReleaseAppButton(); + VrTestFramework.executeStepAndWait( + "stepVerifyMagicWindow()", mVrTestFramework.getFirstTabWebContents()); + + VrTransitionUtils.enterPresentationOrFail(mVrTestFramework.getFirstTabCvc()); + VrTestFramework.executeStepAndWait( + "stepVerifySecondPresent()", mVrTestFramework.getFirstTabWebContents()); + + VrTestFramework.endTest(mVrTestFramework.getFirstTabWebContents()); + } }
diff --git a/chrome/android/junit/src/org/chromium/chrome/browser/compositor/CompositorSurfaceManagerTest.java b/chrome/android/junit/src/org/chromium/chrome/browser/compositor/CompositorSurfaceManagerImplTest.java similarity index 84% rename from chrome/android/junit/src/org/chromium/chrome/browser/compositor/CompositorSurfaceManagerTest.java rename to chrome/android/junit/src/org/chromium/chrome/browser/compositor/CompositorSurfaceManagerImplTest.java index 0c7b56e..7c95698 100644 --- a/chrome/android/junit/src/org/chromium/chrome/browser/compositor/CompositorSurfaceManagerTest.java +++ b/chrome/android/junit/src/org/chromium/chrome/browser/compositor/CompositorSurfaceManagerImplTest.java
@@ -41,13 +41,13 @@ import java.util.Set; /** - * Unit tests for the CompositorSurfaceManager. + * Unit tests for the CompositorSurfaceManagerImpl. */ @RunWith(LocalRobolectricTestRunner.class) @Config(manifest = Config.NONE) -public class CompositorSurfaceManagerTest { +public class CompositorSurfaceManagerImplTest { @Mock - private CompositorSurfaceManager.SurfaceHolderCallbackTarget mCallback; + private CompositorSurfaceManager.SurfaceManagerCallbackTarget mCallback; private CompositorSurfaceManager mManager; @@ -129,7 +129,7 @@ MockitoAnnotations.initMocks(this); Activity activity = Robolectric.buildActivity(Activity.class).setup().get(); mLayout = new FrameLayout(activity); - mManager = new CompositorSurfaceManager(mLayout, mCallback); + mManager = new CompositorSurfaceManagerImpl(mLayout, mCallback); } private void runDelayedTasks() { @@ -215,11 +215,10 @@ public void testRequestOpaqueSurface() { // Request a SurfaceView, and test in detail that it worked. SurfaceView opaque = requestSurface(PixelFormat.OPAQUE); - verify(mCallback, times(0)).surfaceCreated(ArgumentMatchers.<SurfaceHolder>any()); + verify(mCallback, times(0)).surfaceCreated(ArgumentMatchers.<Surface>any()); verify(mCallback, times(0)) - .surfaceChanged( - ArgumentMatchers.<SurfaceHolder>any(), anyInt(), anyInt(), anyInt()); - verify(mCallback, times(0)).surfaceDestroyed(ArgumentMatchers.<SurfaceHolder>any()); + .surfaceChanged(ArgumentMatchers.<Surface>any(), anyInt(), anyInt(), anyInt()); + verify(mCallback, times(0)).surfaceDestroyed(opaque.getHolder().getSurface()); // Check that there's an opaque SurfaceView . assertEquals(1, mLayout.getChildCount()); @@ -227,22 +226,23 @@ // Verify that we are notified when the surface is created. callbackFor(opaque).surfaceCreated(opaque.getHolder()); - verify(mCallback, times(1)).surfaceCreated(eq(opaque.getHolder())); - verify(mCallback, times(0)).surfaceDestroyed(ArgumentMatchers.<SurfaceHolder>any()); + verify(mCallback, times(1)).surfaceCreated(eq(opaque.getHolder().getSurface())); + verify(mCallback, times(0)).surfaceDestroyed(opaque.getHolder().getSurface()); // Verify that we are notified when the surface is changed. sendSurfaceChanged(opaque, PixelFormat.OPAQUE, 320, 240); - verify(mCallback, times(1)).surfaceCreated(eq(opaque.getHolder())); + verify(mCallback, times(1)).surfaceCreated(eq(opaque.getHolder().getSurface())); verify(mCallback, times(1)) - .surfaceChanged(eq(opaque.getHolder()), eq(mActualFormat), eq(mWidth), eq(mHeight)); - verify(mCallback, times(0)).surfaceDestroyed(ArgumentMatchers.<SurfaceHolder>any()); + .surfaceChanged(eq(opaque.getHolder().getSurface()), eq(mActualFormat), eq(mWidth), + eq(mHeight)); + verify(mCallback, times(0)).surfaceDestroyed(opaque.getHolder().getSurface()); // Verify that we are notified when the surface is destroyed. callbackFor(opaque).surfaceDestroyed(opaque.getHolder()); - verify(mCallback, times(1)).surfaceCreated(eq(opaque.getHolder())); + verify(mCallback, times(1)).surfaceCreated(eq(opaque.getHolder().getSurface())); verify(mCallback, times(1)) - .surfaceChanged(eq(opaque.getHolder()), anyInt(), anyInt(), anyInt()); - verify(mCallback, times(1)).surfaceDestroyed(eq(opaque.getHolder())); + .surfaceChanged(eq(opaque.getHolder().getSurface()), anyInt(), anyInt(), anyInt()); + verify(mCallback, times(1)).surfaceDestroyed(opaque.getHolder().getSurface()); } @Test @@ -254,10 +254,11 @@ SurfaceView translucent = requestThenCreateSurface(PixelFormat.TRANSLUCENT); // Verify that we received a destroy for |opaque| and created / changed for |translucent|. - verify(mCallback, times(1)).surfaceDestroyed(opaque.getHolder()); - verify(mCallback, times(1)).surfaceCreated(translucent.getHolder()); + verify(mCallback, times(1)).surfaceDestroyed(opaque.getHolder().getSurface()); + verify(mCallback, times(1)).surfaceCreated(translucent.getHolder().getSurface()); verify(mCallback, times(1)) - .surfaceChanged(eq(translucent.getHolder()), anyInt(), anyInt(), anyInt()); + .surfaceChanged( + eq(translucent.getHolder().getSurface()), anyInt(), anyInt(), anyInt()); // Both views should be present. assertEquals(2, mLayout.getChildCount()); @@ -276,17 +277,18 @@ // Request an opaque surface, get it, then request it again. Verify that we get synthetic // create / destroy callbacks. SurfaceView opaque = requestThenCreateSurface(PixelFormat.OPAQUE); - verify(mCallback, times(1)).surfaceCreated(eq(opaque.getHolder())); + verify(mCallback, times(1)).surfaceCreated(eq(opaque.getHolder().getSurface())); verify(mCallback, times(1)) - .surfaceChanged(eq(opaque.getHolder()), anyInt(), anyInt(), anyInt()); - verify(mCallback, times(0)).surfaceDestroyed(opaque.getHolder()); + .surfaceChanged(eq(opaque.getHolder().getSurface()), anyInt(), anyInt(), anyInt()); + verify(mCallback, times(0)).surfaceDestroyed(opaque.getHolder().getSurface()); // Surface is currently valid. Request again. We should get back a destroy and create. assertEquals(opaque, requestSurface(PixelFormat.OPAQUE)); - verify(mCallback, times(2)).surfaceCreated(opaque.getHolder()); + verify(mCallback, times(2)).surfaceCreated(opaque.getHolder().getSurface()); verify(mCallback, times(2)) - .surfaceChanged(eq(opaque.getHolder()), eq(mActualFormat), eq(mWidth), eq(mHeight)); - verify(mCallback, times(1)).surfaceDestroyed(eq(opaque.getHolder())); + .surfaceChanged(eq(opaque.getHolder().getSurface()), eq(mActualFormat), eq(mWidth), + eq(mHeight)); + verify(mCallback, times(1)).surfaceDestroyed(opaque.getHolder().getSurface()); assertEquals(1, mLayout.getChildCount()); } @@ -296,29 +298,30 @@ public void testRequestSameSurfaceBeforeReady() { // Request an opaque surface, then request it again before the first one shows up. SurfaceView opaque = requestSurface(PixelFormat.OPAQUE); - verify(mCallback, times(0)).surfaceCreated(opaque.getHolder()); + verify(mCallback, times(0)).surfaceCreated(opaque.getHolder().getSurface()); verify(mCallback, times(0)) - .surfaceChanged(eq(opaque.getHolder()), anyInt(), anyInt(), anyInt()); - verify(mCallback, times(0)).surfaceDestroyed(opaque.getHolder()); + .surfaceChanged(eq(opaque.getHolder().getSurface()), anyInt(), anyInt(), anyInt()); + verify(mCallback, times(0)).surfaceDestroyed(opaque.getHolder().getSurface()); // Request again. We shouldn't get any callbacks, since the surface is still pending. assertEquals(opaque, requestSurface(PixelFormat.OPAQUE)); - verify(mCallback, times(0)).surfaceCreated(opaque.getHolder()); + verify(mCallback, times(0)).surfaceCreated(opaque.getHolder().getSurface()); verify(mCallback, times(0)) - .surfaceChanged(eq(opaque.getHolder()), anyInt(), anyInt(), anyInt()); - verify(mCallback, times(0)).surfaceDestroyed(opaque.getHolder()); + .surfaceChanged(eq(opaque.getHolder().getSurface()), anyInt(), anyInt(), anyInt()); + verify(mCallback, times(0)).surfaceDestroyed(opaque.getHolder().getSurface()); // Only the opaque view should be attached. assertEquals(1, mLayout.getChildCount()); // When the surface is created, we should get notified created / changed, but not destroyed. callbackFor(opaque).surfaceCreated(opaque.getHolder()); - verify(mCallback, times(1)).surfaceCreated(opaque.getHolder()); + verify(mCallback, times(1)).surfaceCreated(opaque.getHolder().getSurface()); sendSurfaceChanged(opaque, PixelFormat.RGB_565, 320, 240); verify(mCallback, times(1)) - .surfaceChanged(eq(opaque.getHolder()), eq(mActualFormat), eq(mWidth), eq(mHeight)); - verify(mCallback, times(0)).surfaceDestroyed(opaque.getHolder()); + .surfaceChanged(eq(opaque.getHolder().getSurface()), eq(mActualFormat), eq(mWidth), + eq(mHeight)); + verify(mCallback, times(0)).surfaceDestroyed(opaque.getHolder().getSurface()); } @Test @@ -327,15 +330,15 @@ public void testRequestDifferentSurfacesBeforeReady() { // Request an opaque surface, then request the translucent one before the it one shows up. SurfaceView opaque = requestSurface(PixelFormat.OPAQUE); - verify(mCallback, times(0)).surfaceCreated(opaque.getHolder()); + verify(mCallback, times(0)).surfaceCreated(opaque.getHolder().getSurface()); verify(mCallback, times(0)) - .surfaceChanged(eq(opaque.getHolder()), anyInt(), anyInt(), anyInt()); - verify(mCallback, times(0)).surfaceDestroyed(opaque.getHolder()); + .surfaceChanged(eq(opaque.getHolder().getSurface()), anyInt(), anyInt(), anyInt()); + verify(mCallback, times(0)).surfaceDestroyed(opaque.getHolder().getSurface()); // Request translucent. We should get no callbacks, but both views should be attached. SurfaceView translucent = requestSurface(PixelFormat.TRANSLUCENT); - verify(mCallback, times(0)).surfaceCreated(opaque.getHolder()); - verify(mCallback, times(0)).surfaceCreated(translucent.getHolder()); + verify(mCallback, times(0)).surfaceCreated(opaque.getHolder().getSurface()); + verify(mCallback, times(0)).surfaceCreated(translucent.getHolder().getSurface()); assertEquals(2, mLayout.getChildCount()); // If the opaque surface arrives, we shouldn't hear about it. It should be detached, since @@ -343,14 +346,14 @@ callbackFor(opaque).surfaceCreated(opaque.getHolder()); runDelayedTasks(); assertEquals(1, mLayout.getChildCount()); - verify(mCallback, times(0)).surfaceCreated(opaque.getHolder()); - verify(mCallback, times(0)).surfaceCreated(translucent.getHolder()); - verify(mCallback, times(0)).surfaceDestroyed(opaque.getHolder()); + verify(mCallback, times(0)).surfaceCreated(opaque.getHolder().getSurface()); + verify(mCallback, times(0)).surfaceCreated(translucent.getHolder().getSurface()); + verify(mCallback, times(0)).surfaceDestroyed(opaque.getHolder().getSurface()); // When we create the translucent surface, we should be notified. callbackFor(translucent).surfaceCreated(translucent.getHolder()); - verify(mCallback, times(0)).surfaceCreated(opaque.getHolder()); - verify(mCallback, times(1)).surfaceCreated(translucent.getHolder()); + verify(mCallback, times(0)).surfaceCreated(opaque.getHolder().getSurface()); + verify(mCallback, times(1)).surfaceCreated(translucent.getHolder().getSurface()); } @Test @@ -364,22 +367,23 @@ runDelayedTasks(); // Sanity check. - verify(mCallback, times(1)).surfaceCreated(opaque.getHolder()); + verify(mCallback, times(1)).surfaceCreated(opaque.getHolder().getSurface()); verify(mCallback, times(0)) - .surfaceChanged(eq(opaque.getHolder()), anyInt(), anyInt(), anyInt()); + .surfaceChanged(eq(opaque.getHolder().getSurface()), anyInt(), anyInt(), anyInt()); // Re-request while 'changed' is still pending. We should get a synthetic 'destroyed' and // synthetic 'created'. assertEquals(opaque, requestSurface(PixelFormat.OPAQUE)); - verify(mCallback, times(2)).surfaceCreated(opaque.getHolder()); - verify(mCallback, times(1)).surfaceDestroyed(opaque.getHolder()); + verify(mCallback, times(2)).surfaceCreated(opaque.getHolder().getSurface()); + verify(mCallback, times(1)).surfaceDestroyed(opaque.getHolder().getSurface()); verify(mCallback, times(0)) - .surfaceChanged(eq(opaque.getHolder()), anyInt(), anyInt(), anyInt()); + .surfaceChanged(eq(opaque.getHolder().getSurface()), anyInt(), anyInt(), anyInt()); // Send 'changed', and expect that we'll receive it. sendSurfaceChanged(opaque, PixelFormat.OPAQUE, 320, 240); verify(mCallback, times(1)) - .surfaceChanged(eq(opaque.getHolder()), eq(mActualFormat), eq(mWidth), eq(mHeight)); + .surfaceChanged(eq(opaque.getHolder().getSurface()), eq(mActualFormat), eq(mWidth), + eq(mHeight)); } @Test @@ -389,27 +393,27 @@ // See if recreateSurfaceForJellyBean destroys / re-creates the surface. // should get a synthetic 'created', but a real 'changed' callback. SurfaceView opaque = requestThenCreateSurface(PixelFormat.OPAQUE); - verify(mCallback, times(1)).surfaceCreated(opaque.getHolder()); + verify(mCallback, times(1)).surfaceCreated(opaque.getHolder().getSurface()); assertEquals(1, mLayout.getChildCount()); // We should be notified that the surface was destroyed via synthetic callback, and the // surface should be detached. mManager.recreateSurfaceForJellyBean(); - verify(mCallback, times(1)).surfaceCreated(opaque.getHolder()); - verify(mCallback, times(1)).surfaceDestroyed(opaque.getHolder()); + verify(mCallback, times(1)).surfaceCreated(opaque.getHolder().getSurface()); + verify(mCallback, times(1)).surfaceDestroyed(opaque.getHolder().getSurface()); assertEquals(0, mLayout.getChildCount()); // When the surface really is destroyed, it should be re-attached. We should not be // notified again, though. callbackFor(opaque).surfaceDestroyed(opaque.getHolder()); - verify(mCallback, times(1)).surfaceCreated(opaque.getHolder()); - verify(mCallback, times(1)).surfaceDestroyed(opaque.getHolder()); + verify(mCallback, times(1)).surfaceCreated(opaque.getHolder().getSurface()); + verify(mCallback, times(1)).surfaceDestroyed(opaque.getHolder().getSurface()); assertEquals(1, mLayout.getChildCount()); // When the surface is re-created, we should be notified. callbackFor(opaque).surfaceCreated(opaque.getHolder()); - verify(mCallback, times(2)).surfaceCreated(opaque.getHolder()); - verify(mCallback, times(1)).surfaceDestroyed(opaque.getHolder()); + verify(mCallback, times(2)).surfaceCreated(opaque.getHolder().getSurface()); + verify(mCallback, times(1)).surfaceDestroyed(opaque.getHolder().getSurface()); assertEquals(1, mLayout.getChildCount()); } @@ -433,21 +437,21 @@ assertEquals(1, mLayout.getChildCount()); assertNotNull(findSurface(PixelFormat.TRANSLUCENT)); - // When the opaque surface is destroyed, then it should be re-attached. No callbacks shoud + // When the opaque surface is destroyed, then it should be re-attached. No callbacks should // have arrived yet, except for initial creation and (synthetic) destroyed when we got the // translucent surface. callbackFor(opaque).surfaceDestroyed(opaque.getHolder()); assertEquals(2, mLayout.getChildCount()); - verify(mCallback, times(1)).surfaceCreated(opaque.getHolder()); - verify(mCallback, times(1)).surfaceDestroyed(opaque.getHolder()); - verify(mCallback, times(0)).surfaceDestroyed(translucent.getHolder()); + verify(mCallback, times(1)).surfaceCreated(opaque.getHolder().getSurface()); + verify(mCallback, times(1)).surfaceDestroyed(opaque.getHolder().getSurface()); + verify(mCallback, times(0)).surfaceDestroyed(translucent.getHolder().getSurface()); // When the opaque surface becomes available, we'll get the synthetic destroy for the // translucent one that we lost ownership of, and the real create for the opaque one. callbackFor(opaque).surfaceCreated(opaque.getHolder()); assertEquals(2, mLayout.getChildCount()); - verify(mCallback, times(2)).surfaceCreated(opaque.getHolder()); - verify(mCallback, times(1)).surfaceDestroyed(opaque.getHolder()); - verify(mCallback, times(1)).surfaceDestroyed(translucent.getHolder()); + verify(mCallback, times(2)).surfaceCreated(opaque.getHolder().getSurface()); + verify(mCallback, times(1)).surfaceDestroyed(opaque.getHolder().getSurface()); + verify(mCallback, times(1)).surfaceDestroyed(translucent.getHolder().getSurface()); } }
diff --git a/chrome/android/webapk/libs/client/src/org/chromium/webapk/lib/client/WebApkValidator.java b/chrome/android/webapk/libs/client/src/org/chromium/webapk/lib/client/WebApkValidator.java index adb3c55..a936c568 100644 --- a/chrome/android/webapk/libs/client/src/org/chromium/webapk/lib/client/WebApkValidator.java +++ b/chrome/android/webapk/libs/client/src/org/chromium/webapk/lib/client/WebApkValidator.java
@@ -12,7 +12,6 @@ import android.content.Intent; import android.content.pm.PackageInfo; import android.content.pm.PackageManager; -import android.content.pm.PackageManager.NameNotFoundException; import android.content.pm.ResolveInfo; import android.content.pm.Signature; import android.os.StrictMode; @@ -134,8 +133,17 @@ selector.addCategory(Intent.CATEGORY_BROWSABLE); selector.setComponent(null); } - return context.getPackageManager().queryIntentActivities( - intent, PackageManager.GET_RESOLVED_FILTER); + List<ResolveInfo> resolveInfoList; + try { + resolveInfoList = context.getPackageManager().queryIntentActivities( + intent, PackageManager.GET_RESOLVED_FILTER); + } catch (Exception e) { + // We used to catch only java.util.MissingResourceException, but we need to catch more + // exceptions to handle "Package manager has died" exception. + // http://crbug.com/794363 + resolveInfoList = new LinkedList<>(); + } + return resolveInfoList; } /** @@ -171,7 +179,7 @@ try { packageInfo = context.getPackageManager().getPackageInfo(webappPackageName, PackageManager.GET_SIGNATURES | PackageManager.GET_META_DATA); - } catch (NameNotFoundException e) { + } catch (Exception e) { e.printStackTrace(); Log.d(TAG, "WebApk not found"); return false;
diff --git a/chrome/app/settings_strings.grdp b/chrome/app/settings_strings.grdp index c930003..0d8a1e1 100644 --- a/chrome/app/settings_strings.grdp +++ b/chrome/app/settings_strings.grdp
@@ -3797,7 +3797,7 @@ Restart computer </message> <message name="IDS_SETTINGS_RESET_CLEANUP_TITLE_DONE" desc="Message confirming that Chrome has removed harmful software. Exclamation point is nice in EN-US but is optional in your language; please use or omit as appropriate. The UI will also display a checkmark icon to indicate the operation is done. "> - Done! + Done! Harmful software removed. </message> <message name="IDS_SETTINGS_RESET_CLEANUP_TITLE_ERROR_CANT_REMOVE" desc="An error message, appearing on the Chrome Cleanup web page, that Chrome tried to clean up unwanted software, as requested by the user, but was unsuccessful. Omits subject, i.e. Chrome can't remove harmful software."> Can't remove harmful software
diff --git a/chrome/browser/BUILD.gn b/chrome/browser/BUILD.gn index 7688a680..817d2c9 100644 --- a/chrome/browser/BUILD.gn +++ b/chrome/browser/BUILD.gn
@@ -2594,6 +2594,9 @@ "resource_coordinator/discard_reason.h", "resource_coordinator/lifecycle_unit.cc", "resource_coordinator/lifecycle_unit.h", + "resource_coordinator/lifecycle_unit_base.cc", + "resource_coordinator/lifecycle_unit_base.h", + "resource_coordinator/lifecycle_unit_observer.h", "resource_coordinator/lifecycle_unit_source.h", "resource_coordinator/lifecycle_unit_source_base.cc", "resource_coordinator/lifecycle_unit_source_base.h", @@ -4092,10 +4095,10 @@ if (enable_webrtc) { sources += [ - "media/audio_debug_recordings_handler.h", + "media/webrtc/audio_debug_recordings_handler.cc", + "media/webrtc/audio_debug_recordings_handler.h", # TODO(brettw) should webrtc_log_list.cc go here? - "media/webrtc/audio_debug_recordings_handler.cc", "media/webrtc/webrtc_log_uploader.cc", "media/webrtc/webrtc_log_uploader.h", "media/webrtc/webrtc_log_util.cc",
diff --git a/chrome/browser/about_flags.cc b/chrome/browser/about_flags.cc index 5837de6..faf4b361 100644 --- a/chrome/browser/about_flags.cc +++ b/chrome/browser/about_flags.cc
@@ -1213,11 +1213,10 @@ {"composited-layer-borders", flag_descriptions::kCompositedLayerBordersName, flag_descriptions::kCompositedLayerBordersDescription, kOsAll, SINGLE_VALUE_TYPE(cc::switches::kShowCompositedLayerBorders)}, - {"gl-composited-overlay-candidate-quad-borders", - flag_descriptions::kGlCompositedOverlayCandidateQuadBordersName, - flag_descriptions::kGlCompositedOverlayCandidateQuadBordersDescription, - kOsAll, - SINGLE_VALUE_TYPE(switches::kGlCompositedOverlayCandidateQuadBorder)}, + {"tint-gl-composited-content", + flag_descriptions::kTintGlCompositedContentName, + flag_descriptions::kTintGlCompositedContentDescription, kOsAll, + SINGLE_VALUE_TYPE(switches::kTintGlCompositedContent)}, {"show-overdraw-feedback", flag_descriptions::kShowOverdrawFeedbackName, flag_descriptions::kShowOverdrawFeedbackDescription, kOsAll, SINGLE_VALUE_TYPE(switches::kShowOverdrawFeedback)}, @@ -1589,10 +1588,6 @@ flag_descriptions::kPasswordGenerationDescription, kOsAll, ENABLE_DISABLE_VALUE_TYPE(autofill::switches::kEnablePasswordGeneration, autofill::switches::kDisablePasswordGeneration)}, - {"enable-username-correction", - flag_descriptions::kEnableUsernameCorrectionName, - flag_descriptions::kEnableUsernameCorrectionDescription, kOsDesktop, - FEATURE_VALUE_TYPE(password_manager::features::kEnableUsernameCorrection)}, {"enable-password-force-saving", flag_descriptions::kPasswordForceSavingName, flag_descriptions::kPasswordForceSavingDescription, kOsAll, @@ -3506,10 +3501,6 @@ flag_descriptions::kParallelDownloadingDescription, kOsAll, FEATURE_VALUE_TYPE(features::kParallelDownloading)}, - {"enable-password-selection", flag_descriptions::kPasswordSelectionName, - flag_descriptions::kPasswordSelectionDescription, kOsDesktop, - FEATURE_VALUE_TYPE(password_manager::features::kEnablePasswordSelection)}, - {"enable-html-base-username-detector", flag_descriptions::kHtmlBasedUsernameDetectorName, flag_descriptions::kHtmlBasedUsernameDetectorDescription, kOsAll,
diff --git a/chrome/browser/android/compositor/compositor_view.cc b/chrome/browser/android/compositor/compositor_view.cc index 0584ce1..25f87cc7 100644 --- a/chrome/browser/android/compositor/compositor_view.cc +++ b/chrome/browser/android/compositor/compositor_view.cc
@@ -270,4 +270,11 @@ // through here but through BrowserChildProcessHostDisconnected() instead. } +void CompositorView::SetCompositorWindow(JNIEnv* env, + const JavaParamRef<jobject>& object, + jlong window_android) { + ui::WindowAndroid* wa = reinterpret_cast<ui::WindowAndroid*>(window_android); + compositor_->SetRootWindow(wa); +} + } // namespace android
diff --git a/chrome/browser/android/compositor/compositor_view.h b/chrome/browser/android/compositor/compositor_view.h index 90a8ecc..42d2f54 100644 --- a/chrome/browser/android/compositor/compositor_view.h +++ b/chrome/browser/android/compositor/compositor_view.h
@@ -81,6 +81,9 @@ void SetSceneLayer(JNIEnv* env, const base::android::JavaParamRef<jobject>& object, const base::android::JavaParamRef<jobject>& jscene_layer); + void SetCompositorWindow(JNIEnv* env, + const base::android::JavaParamRef<jobject>& object, + jlong window_android); // CompositorClient implementation: void UpdateLayerTreeHost() override;
diff --git a/chrome/browser/android/tab_android.cc b/chrome/browser/android/tab_android.cc index 1eab1808..8c6475562 100644 --- a/chrome/browser/android/tab_android.cc +++ b/chrome/browser/android/tab_android.cc
@@ -70,7 +70,7 @@ #include "content/public/browser/render_process_host.h" #include "content/public/browser/render_view_host.h" #include "content/public/browser/web_contents.h" -#include "content/public/common/resource_request_body.h" +#include "content/public/common/resource_request_body_android.h" #include "jni/Tab_jni.h" #include "mojo/public/cpp/bindings/strong_binding.h" #include "net/base/escape.h" @@ -273,8 +273,10 @@ ScopedJavaLocalRef<jstring> jheaders( ConvertUTF8ToJavaString(env, params->extra_headers)); ScopedJavaLocalRef<jobject> jpost_data; - if (params->uses_post && params->post_data) - jpost_data = params->post_data->ToJavaObject(env); + if (params->uses_post && params->post_data) { + jpost_data = content::ConvertResourceRequestBodyToJavaObject( + env, params->post_data); + } Java_Tab_openNewTab( env, jobj, jurl, jheaders, jpost_data, static_cast<int>(disposition), params->created_with_opener, params->is_renderer_initiated); @@ -568,7 +570,7 @@ load_params.load_type = content::NavigationController::LOAD_TYPE_HTTP_POST; load_params.post_data = - content::ResourceRequestBody::FromJavaObject(env, j_post_data); + content::ExtractResourceRequestBodyFromJavaObject(env, j_post_data); } load_params.transition_type = ui::PageTransitionFromInt(page_transition);
diff --git a/chrome/browser/android/vr_shell/vr_compositor.cc b/chrome/browser/android/vr_shell/vr_compositor.cc index 517d76f2..673efc0 100644 --- a/chrome/browser/android/vr_shell/vr_compositor.cc +++ b/chrome/browser/android/vr_shell/vr_compositor.cc
@@ -56,10 +56,6 @@ compositor_->SetWindowBounds(size); } -void VrCompositor::SetDeferCommits(bool defer_commits) { - compositor_->SetDeferCommits(defer_commits); -} - void VrCompositor::SurfaceChanged(jobject surface) { compositor_->SetSurface(surface); }
diff --git a/chrome/browser/android/vr_shell/vr_compositor.h b/chrome/browser/android/vr_shell/vr_compositor.h index eb4baf66..1f7f8a3 100644 --- a/chrome/browser/android/vr_shell/vr_compositor.h +++ b/chrome/browser/android/vr_shell/vr_compositor.h
@@ -36,7 +36,6 @@ void SurfaceDestroyed(); void SetWindowBounds(gfx::Size size); - void SetDeferCommits(bool defer_commits); void SurfaceChanged(jobject surface); void SetLayer(content::WebContents* web_contents);
diff --git a/chrome/browser/android/vr_shell/vr_shell.cc b/chrome/browser/android/vr_shell/vr_shell.cc index 8308a9e..d8ed85d3 100644 --- a/chrome/browser/android/vr_shell/vr_shell.cc +++ b/chrome/browser/android/vr_shell/vr_shell.cc
@@ -151,10 +151,6 @@ g_instance = this; j_vr_shell_.Reset(env, obj); - // Defer applying commits to the renderer until we know the desired - // content resolution and DPR. - compositor_->SetDeferCommits(true); - gl_thread_ = base::MakeUnique<VrGLThread>( weak_ptr_factory_.GetWeakPtr(), main_thread_task_runner_, gvr_api, ui_initial_state, reprojected_rendering_, HasDaydreamSupport(env)); @@ -785,7 +781,6 @@ JNIEnv* env = base::android::AttachCurrentThread(); Java_VrShellImpl_setContentCssSize(env, j_vr_shell_, window_size.width(), window_size.height(), dpr); - compositor_->SetDeferCommits(false); } void VrShell::SetVoiceSearchActive(bool active) {
diff --git a/chrome/browser/android/vr_shell/vr_shell.h b/chrome/browser/android/vr_shell/vr_shell.h index 27e39249..3cdef9ed 100644 --- a/chrome/browser/android/vr_shell/vr_shell.h +++ b/chrome/browser/android/vr_shell/vr_shell.h
@@ -9,6 +9,7 @@ #include <memory> +#include "base/android/scoped_java_ref.h" #include "base/callback.h" #include "base/macros.h" #include "base/memory/weak_ptr.h"
diff --git a/chrome/browser/apps/guest_view/extension_view/extension_view_browsertest.cc b/chrome/browser/apps/guest_view/extension_view/extension_view_browsertest.cc index c191e1e..1f28693 100644 --- a/chrome/browser/apps/guest_view/extension_view/extension_view_browsertest.cc +++ b/chrome/browser/apps/guest_view/extension_view/extension_view_browsertest.cc
@@ -118,28 +118,60 @@ skeleton_app->id(), ""); } -// Tests that verify that <extensionview> can call the load function. -// Flaky under MemorySanitizer: https://crbug.com/545656 -IN_PROC_BROWSER_TEST_P(ExtensionViewTest, DISABLED_LoadAPICall) { - const extensions::Extension* skeleton_app = - InstallPlatformApp("extension_view/skeleton"); - const extensions::Extension* skeleton_app_two = - InstallPlatformApp("extension_view/skeleton_two"); - TestHelper("testLoadAPIFunction", "extension_view/load_api", - skeleton_app->id(), - skeleton_app_two->id()); +class ExtensionViewLoadApiTest : public ExtensionViewTest { + public: + void TestLoadApiHelper(const std::string& test_name) { + const extensions::Extension* skeleton_app = + InstallPlatformApp("extension_view/skeleton"); + const extensions::Extension* skeleton_app_two = + InstallPlatformApp("extension_view/skeleton_two"); + TestHelper(test_name, "extension_view/load_api", skeleton_app->id(), + skeleton_app_two->id()); + } +}; + +INSTANTIATE_TEST_CASE_P(ExtensionViewTests, + ExtensionViewLoadApiTest, + testing::Bool()); + +IN_PROC_BROWSER_TEST_P(ExtensionViewLoadApiTest, LoadAPIFunction) { + TestLoadApiHelper("testLoadAPIFunction"); } -// Flaky under MemorySanitizer: https://crbug.com/512092 -// Flaky elsewhere: https://crbug.com/538114 -// Tests that verify that <extensionview> can queue up multiple calls to the -// load function. -IN_PROC_BROWSER_TEST_P(ExtensionViewTest, DISABLED_QueuedLoadAPICall) { - const extensions::Extension* skeleton_app = - InstallPlatformApp("extension_view/skeleton"); - const extensions::Extension* skeleton_app_two = - InstallPlatformApp("extension_view/skeleton_two"); - TestHelper("testQueuedLoadAPIFunction", "extension_view/load_api", - skeleton_app->id(), - skeleton_app_two->id()); +IN_PROC_BROWSER_TEST_P(ExtensionViewLoadApiTest, LoadAPISameIdAndSrc) { + TestLoadApiHelper("testLoadAPISameIdAndSrc"); +} + +IN_PROC_BROWSER_TEST_P(ExtensionViewLoadApiTest, LoadAPISameIdDifferentSrc) { + TestLoadApiHelper("testLoadAPISameIdDifferentSrc"); +} + +// extensionview cannot do cross extension navigation with OOPIF based guests. +// crbug.com/800407 +IN_PROC_BROWSER_TEST_P(ExtensionViewLoadApiTest, + DISABLED_LoadAPILoadOtherExtension) { + TestLoadApiHelper("testLoadAPILoadOtherExtension"); +} + +IN_PROC_BROWSER_TEST_P(ExtensionViewLoadApiTest, LoadAPIInvalidExtension) { + TestLoadApiHelper("testLoadAPIInvalidExtension"); +} + +IN_PROC_BROWSER_TEST_P(ExtensionViewLoadApiTest, LoadAPIAfterInvalidCall) { + TestLoadApiHelper("testLoadAPIAfterInvalidCall"); +} + +IN_PROC_BROWSER_TEST_P(ExtensionViewLoadApiTest, LoadAPINullExtension) { + TestLoadApiHelper("testLoadAPINullExtension"); +} + +IN_PROC_BROWSER_TEST_P(ExtensionViewLoadApiTest, QueuedLoadAPIFunction) { + TestLoadApiHelper("testQueuedLoadAPIFunction"); +} + +// extensionview cannot do cross extension navigation with OOPIF based guests. +// crbug.com/800407 +IN_PROC_BROWSER_TEST_P(ExtensionViewLoadApiTest, + DISABLED_QueuedLoadAPILoadOtherExtension) { + TestLoadApiHelper("testQueuedLoadAPILoadOtherExtension"); }
diff --git a/chrome/browser/browsing_data/autofill_counter_browsertest.cc b/chrome/browser/browsing_data/autofill_counter_browsertest.cc index 430077aa..7273ed6 100644 --- a/chrome/browser/browsing_data/autofill_counter_browsertest.cc +++ b/chrome/browser/browsing_data/autofill_counter_browsertest.cc
@@ -373,6 +373,22 @@ EXPECT_EQ(test_case.expected_num_credit_cards, GetNumCreditCards()); EXPECT_EQ(test_case.expected_num_addresses, GetNumAddresses()); } + + // Test the results for different ending points and base::Time as start. + counter.SetPeriodStartForTesting(base::Time()); + counter.SetPeriodEndForTesting(kTime2); + counter.Restart(); + WaitForCounting(); + EXPECT_EQ(1, GetNumSuggestions()); + EXPECT_EQ(1, GetNumCreditCards()); + EXPECT_EQ(1, GetNumAddresses()); + + counter.SetPeriodEndForTesting(kTime3); + counter.Restart(); + WaitForCounting(); + EXPECT_EQ(1, GetNumSuggestions()); + EXPECT_EQ(2, GetNumCreditCards()); + EXPECT_EQ(3, GetNumAddresses()); } } // namespace
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 da3ff40..f195bc2 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
@@ -48,6 +48,7 @@ #include "components/autofill/core/browser/credit_card.h" #include "components/autofill/core/browser/personal_data_manager.h" #include "components/autofill/core/browser/personal_data_manager_observer.h" +#include "components/autofill/core/browser/test_autofill_clock.h" #include "components/autofill/core/common/autofill_constants.h" #include "components/bookmarks/browser/bookmark_model.h" #include "components/bookmarks/test/bookmark_test_helpers.h" @@ -1508,6 +1509,45 @@ ASSERT_FALSE(tester.HasProfile()); } +// Verify the clearing of autofill profiles added / modified more than 30 days +// ago. +TEST_F(ChromeBrowsingDataRemoverDelegateTest, AutofillRemovalOlderThan30Days) { + GetProfile()->CreateWebDataService(); + RemoveAutofillTester tester(GetProfile()); + + const base::Time kNow = base::Time::Now(); + const base::Time k30DaysOld = kNow - base::TimeDelta::FromDays(30); + const base::Time k31DaysOld = kNow - base::TimeDelta::FromDays(31); + const base::Time k32DaysOld = kNow - base::TimeDelta::FromDays(32); + + // Add profiles and cards with modification date as 31 days old from now. + autofill::TestAutofillClock test_clock; + test_clock.SetNow(k31DaysOld); + + ASSERT_FALSE(tester.HasProfile()); + tester.AddProfilesAndCards(); + ASSERT_TRUE(tester.HasProfile()); + + BlockUntilBrowsingDataRemoved( + base::Time(), k32DaysOld, + ChromeBrowsingDataRemoverDelegate::DATA_TYPE_FORM_DATA, false); + ASSERT_TRUE(tester.HasProfile()); + + BlockUntilBrowsingDataRemoved( + k30DaysOld, base::Time::Max(), + ChromeBrowsingDataRemoverDelegate::DATA_TYPE_FORM_DATA, false); + ASSERT_TRUE(tester.HasProfile()); + + BlockUntilBrowsingDataRemoved( + base::Time(), k30DaysOld, + ChromeBrowsingDataRemoverDelegate::DATA_TYPE_FORM_DATA, false); + EXPECT_EQ(ChromeBrowsingDataRemoverDelegate::DATA_TYPE_FORM_DATA, + GetRemovalMask()); + EXPECT_EQ(content::BrowsingDataRemover::ORIGIN_TYPE_UNPROTECTED_WEB, + GetOriginTypeMask()); + ASSERT_FALSE(tester.HasProfile()); +} + TEST_F(ChromeBrowsingDataRemoverDelegateTest, AutofillRemovalEverything) { GetProfile()->CreateWebDataService(); RemoveAutofillTester tester(GetProfile());
diff --git a/chrome/browser/chrome_content_browser_client.cc b/chrome/browser/chrome_content_browser_client.cc index 9db5f06..f7ac4e0a 100644 --- a/chrome/browser/chrome_content_browser_client.cc +++ b/chrome/browser/chrome_content_browser_client.cc
@@ -301,7 +301,6 @@ #include "components/navigation_interception/intercept_navigation_delegate.h" #include "content/public/browser/android/java_interfaces.h" #include "services/proxy_resolver/proxy_resolver_service.h" -#include "services/proxy_resolver/public/interfaces/proxy_resolver.mojom.h" #include "services/service_manager/public/cpp/interface_provider.h" #include "third_party/WebKit/public/platform/modules/payments/payment_request.mojom.h" #include "ui/base/resource/resource_bundle_android.h" @@ -402,7 +401,7 @@ #endif #if BUILDFLAG(ENABLE_WEBRTC) -#include "chrome/browser/media/audio_debug_recordings_handler.h" +#include "chrome/browser/media/webrtc/audio_debug_recordings_handler.h" #include "chrome/browser/media/webrtc/webrtc_logging_handler_host.h" #endif @@ -1534,13 +1533,6 @@ // field trial may overwrite another. See Source/core/frame/Settings.in in // Blink for the list of valid keys. static const char* const kBlinkSettingsFieldTrials[] = { - // Keys: backgroundHtmlParserOutstandingTokenLimit - // backgroundHtmlParserPendingTokenLimit - "BackgroundHtmlParserTokenLimits", - - // Keys: doHtmlPreloadScanning - "HtmlPreloadScanning", - // Keys: disallowFetchForDocWrittenScriptsInMainFrame // disallowFetchForDocWrittenScriptsInMainFrameOnSlowConnections // disallowFetchForDocWrittenScriptsInMainFrameIfEffectively2G @@ -1838,7 +1830,6 @@ switches::kForcePNaClSubzero, #endif switches::kForceUIDirection, - switches::kIsolateOrigins, switches::kJavaScriptHarmony, switches::kOriginTrialDisabledFeatures, switches::kOriginTrialDisabledTokens,
diff --git a/chrome/browser/chrome_content_browser_client_unittest.cc b/chrome/browser/chrome_content_browser_client_unittest.cc index 6249451..e2a2e12 100644 --- a/chrome/browser/chrome_content_browser_client_unittest.cc +++ b/chrome/browser/chrome_content_browser_client_unittest.cc
@@ -184,10 +184,9 @@ class BlinkSettingsFieldTrialTest : public testing::Test { public: - static const char kParserFieldTrialName[]; - static const char kPreloadScanningFieldTrialName[]; + static const char kDisallowFetchFieldTrialName[]; + static const char kCSSExternalScannerFieldTrialName[]; static const char kFakeGroupName[]; - static const char kDefaultGroupName[]; BlinkSettingsFieldTrialTest() : trial_list_(NULL), @@ -240,12 +239,11 @@ content::TestBrowserThreadBundle thread_bundle_; }; -const char BlinkSettingsFieldTrialTest::kParserFieldTrialName[] = - "BackgroundHtmlParserTokenLimits"; -const char BlinkSettingsFieldTrialTest::kPreloadScanningFieldTrialName[] = - "HtmlPreloadScanning"; +const char BlinkSettingsFieldTrialTest::kDisallowFetchFieldTrialName[] = + "DisallowFetchForDocWrittenScriptsInMainFrame"; +const char BlinkSettingsFieldTrialTest::kCSSExternalScannerFieldTrialName[] = + "CSSExternalScanner"; const char BlinkSettingsFieldTrialTest::kFakeGroupName[] = "FakeGroup"; -const char BlinkSettingsFieldTrialTest::kDefaultGroupName[] = "Default"; TEST_F(BlinkSettingsFieldTrialTest, NoFieldTrial) { AppendContentBrowserClientSwitches(); @@ -253,14 +251,14 @@ } TEST_F(BlinkSettingsFieldTrialTest, FieldTrialWithoutParams) { - CreateFieldTrial(kParserFieldTrialName, kFakeGroupName); + CreateFieldTrial(kDisallowFetchFieldTrialName, kFakeGroupName); AppendContentBrowserClientSwitches(); EXPECT_FALSE(command_line().HasSwitch(switches::kBlinkSettings)); } TEST_F(BlinkSettingsFieldTrialTest, BlinkSettingsSwitchAlreadySpecified) { AppendBlinkSettingsSwitch("foo"); - CreateFieldTrialWithParams(kParserFieldTrialName, kFakeGroupName, + CreateFieldTrialWithParams(kDisallowFetchFieldTrialName, kFakeGroupName, "key1", "value1", "key2", "value2"); AppendContentBrowserClientSwitches(); EXPECT_TRUE(command_line().HasSwitch(switches::kBlinkSettings)); @@ -269,7 +267,7 @@ } TEST_F(BlinkSettingsFieldTrialTest, FieldTrialEnabled) { - CreateFieldTrialWithParams(kParserFieldTrialName, kFakeGroupName, + CreateFieldTrialWithParams(kDisallowFetchFieldTrialName, kFakeGroupName, "key1", "value1", "key2", "value2"); AppendContentBrowserClientSwitches(); EXPECT_TRUE(command_line().HasSwitch(switches::kBlinkSettings)); @@ -278,9 +276,9 @@ } TEST_F(BlinkSettingsFieldTrialTest, MultipleFieldTrialsEnabled) { - CreateFieldTrialWithParams(kParserFieldTrialName, kFakeGroupName, + CreateFieldTrialWithParams(kDisallowFetchFieldTrialName, kFakeGroupName, "key1", "value1", "key2", "value2"); - CreateFieldTrialWithParams(kPreloadScanningFieldTrialName, kFakeGroupName, + CreateFieldTrialWithParams(kCSSExternalScannerFieldTrialName, kFakeGroupName, "keyA", "valueA", "keyB", "valueB"); AppendContentBrowserClientSwitches(); EXPECT_TRUE(command_line().HasSwitch(switches::kBlinkSettings)); @@ -289,9 +287,9 @@ } TEST_F(BlinkSettingsFieldTrialTest, MultipleFieldTrialsDuplicateKeys) { - CreateFieldTrialWithParams(kParserFieldTrialName, kFakeGroupName, + CreateFieldTrialWithParams(kDisallowFetchFieldTrialName, kFakeGroupName, "key1", "value1", "key2", "value2"); - CreateFieldTrialWithParams(kPreloadScanningFieldTrialName, kFakeGroupName, + CreateFieldTrialWithParams(kCSSExternalScannerFieldTrialName, kFakeGroupName, "key2", "duplicate", "key3", "value3"); AppendContentBrowserClientSwitches(); EXPECT_TRUE(command_line().HasSwitch(switches::kBlinkSettings));
diff --git a/chrome/browser/chrome_site_per_process_browsertest.cc b/chrome/browser/chrome_site_per_process_browsertest.cc index ee3358b..0f1c3270 100644 --- a/chrome/browser/chrome_site_per_process_browsertest.cc +++ b/chrome/browser/chrome_site_per_process_browsertest.cc
@@ -854,9 +854,9 @@ content::BrowserThread::UI); ui_task_runner->PostTask( FROM_HERE, - base::Bind(&TestBrowserClientForSpellCheck::BindSpellCheckHostRequest, - base::Unretained(this), base::Passed(&request), - remote_info)); + base::BindOnce( + &TestBrowserClientForSpellCheck::BindSpellCheckHostRequest, + base::Unretained(this), base::Passed(&request), remote_info)); } #endif // !BUILDFLAG(USE_BROWSER_SPELLCHECKER)
diff --git a/chrome/browser/chromeos/DEPS b/chrome/browser/chromeos/DEPS index 02f87458..490ef60 100644 --- a/chrome/browser/chromeos/DEPS +++ b/chrome/browser/chromeos/DEPS
@@ -33,3 +33,13 @@ "-ui/ozone/public", "+ui/ozone/public/ozone_switches.h", ] + +specific_include_rules = { + "chrome_browser_main_chromeos\.cc": [ + "-ash", + # TODO(mash): Support EventRewriterController, http://crbug.com/647781. + "+ash/root_window_controller.h", + "+ash/shell.h", + "+ash/sticky_keys/sticky_keys_controller.h", + ], +}
diff --git a/chrome/browser/chromeos/chrome_browser_main_chromeos.cc b/chrome/browser/chromeos/chrome_browser_main_chromeos.cc index b129364..75be0e3 100644 --- a/chrome/browser/chromeos/chrome_browser_main_chromeos.cc +++ b/chrome/browser/chromeos/chrome_browser_main_chromeos.cc
@@ -10,10 +10,6 @@ #include <utility> #include <vector> -#include "ash/public/cpp/ash_switches.h" -#include "ash/public/cpp/shelf_model.h" -#include "ash/public/interfaces/constants.mojom.h" -#include "ash/public/interfaces/process_creation_time_recorder.mojom.h" #include "ash/root_window_controller.h" #include "ash/shell.h" #include "ash/sticky_keys/sticky_keys_controller.h" @@ -82,7 +78,6 @@ #include "chrome/browser/chromeos/net/network_pref_state_observer.h" #include "chrome/browser/chromeos/net/network_throttling_observer.h" #include "chrome/browser/chromeos/net/wake_on_wifi_manager.h" -#include "chrome/browser/chromeos/night_light/night_light_client.h" #include "chrome/browser/chromeos/note_taking_helper.h" #include "chrome/browser/chromeos/options/cert_library.h" #include "chrome/browser/chromeos/ownership/owner_settings_service_chromeos_factory.h" @@ -112,10 +107,6 @@ #include "chrome/browser/profiles/profile.h" #include "chrome/browser/profiles/profile_manager.h" #include "chrome/browser/task_manager/task_manager_interface.h" -#include "chrome/browser/ui/ash/ash_util.h" -#include "chrome/browser/ui/ash/launcher/chrome_launcher_controller.h" -#include "chrome/browser/ui/ash/tablet_mode_client.h" -#include "chrome/browser/ui/ash/wallpaper_controller_client.h" #include "chrome/common/channel_info.h" #include "chrome/common/chrome_constants.h" #include "chrome/common/chrome_features.h" @@ -162,7 +153,6 @@ #include "components/quirks/quirks_manager.h" #include "components/session_manager/core/session_manager.h" #include "components/signin/core/account_id/account_id.h" -#include "components/startup_metric_utils/browser/startup_metric_utils.h" #include "components/user_manager/user.h" #include "components/user_manager/user_manager.h" #include "components/user_manager/user_names.h" @@ -213,9 +203,9 @@ bool ShouldAutoLaunchKioskApp(const base::CommandLine& command_line) { KioskAppManager* app_manager = KioskAppManager::Get(); return command_line.HasSwitch(switches::kLoginManager) && - !command_line.HasSwitch(switches::kForceLoginManagerInTests) && - app_manager->IsAutoLaunchEnabled() && - KioskAppLaunchError::Get() == KioskAppLaunchError::NONE; + !command_line.HasSwitch(switches::kForceLoginManagerInTests) && + app_manager->IsAutoLaunchEnabled() && + KioskAppLaunchError::Get() == KioskAppLaunchError::NONE; } // Creates an instance of the NetworkPortalDetector implementation or a stub. @@ -275,66 +265,10 @@ #endif } -void PushProcessCreationTimeToAsh() { - ash::mojom::ProcessCreationTimeRecorderPtr recorder; - content::ServiceManagerConnection::GetForProcess() - ->GetConnector() - ->BindInterface(ash::mojom::kServiceName, &recorder); - DCHECK(!startup_metric_utils::MainEntryPointTicks().is_null()); - recorder->SetMainProcessCreationTime( - startup_metric_utils::MainEntryPointTicks()); -} - } // namespace namespace internal { -// Creates a ChromeLauncherController on the first active session notification. -// Used to avoid constructing a ChromeLauncherController with no active profile. -class ChromeLauncherControllerInitializer - : public session_manager::SessionManagerObserver { - public: - ChromeLauncherControllerInitializer() { - session_manager::SessionManager::Get()->AddObserver(this); - } - - ~ChromeLauncherControllerInitializer() override { - if (!chrome_launcher_controller_) - session_manager::SessionManager::Get()->RemoveObserver(this); - } - - // session_manager::SessionManagerObserver: - void OnSessionStateChanged() override { - DCHECK(!chrome_launcher_controller_); - DCHECK(!ChromeLauncherController::instance()); - - if (session_manager::SessionManager::Get()->session_state() == - session_manager::SessionState::ACTIVE) { - chrome_shelf_model_ = std::make_unique<ash::ShelfModel>(); - const bool should_synchronize_shelf_models = - ash_util::IsRunningInMash() || - !base::CommandLine::ForCurrentProcess()->HasSwitch( - ash::switches::kAshDisableShelfModelSynchronization); - ash::ShelfModel* model = should_synchronize_shelf_models - ? chrome_shelf_model_.get() - : ash::Shell::Get()->shelf_model(); - chrome_launcher_controller_ = - std::make_unique<ChromeLauncherController>(nullptr, model); - chrome_launcher_controller_->Init(); - session_manager::SessionManager::Get()->RemoveObserver(this); - } - } - - private: - // This shelf model is synced with Ash's ShelfController instance in Mash and - // if kAshDisableShelfModelSynchronization is not supplied in Classic Ash; - // otherwise ChromeLauncherController uses Ash's ShelfModel instance directly. - std::unique_ptr<ash::ShelfModel> chrome_shelf_model_; - std::unique_ptr<ChromeLauncherController> chrome_launcher_controller_; - - DISALLOW_COPY_AND_ASSIGN(ChromeLauncherControllerInitializer); -}; - // Wrapper class for initializing dbus related services and shutting them // down. This gets instantiated in a scoped_ptr so that shutdown methods in the // destructor will get called if and only if this has been instantiated. @@ -624,8 +558,7 @@ ChromeBrowserMainPartsChromeos::ChromeBrowserMainPartsChromeos( const content::MainFunctionParams& parameters) - : ChromeBrowserMainPartsLinux(parameters) { -} + : ChromeBrowserMainPartsLinux(parameters) {} ChromeBrowserMainPartsChromeos::~ChromeBrowserMainPartsChromeos() { // To be precise, logout (browser shutdown) is not yet done, but the @@ -662,8 +595,9 @@ chrome::kTestUserProfileDir); } LOG(WARNING) << "Running as stub user with profile dir: " - << singleton_command_line->GetSwitchValuePath( - switches::kLoginProfile).value(); + << singleton_command_line + ->GetSwitchValuePath(switches::kLoginProfile) + .value(); } #if defined(GOOGLE_CHROME_BUILD) @@ -783,9 +717,6 @@ g_browser_process->platform_part()->InitializeChromeUserManager(); g_browser_process->platform_part()->InitializeSessionManager(); - chrome_launcher_controller_initializer_ = - std::make_unique<internal::ChromeLauncherControllerInitializer>(); - ScreenLocker::InitClass(); // This forces the ProfileManager to be created and register for the @@ -800,8 +731,7 @@ // If kLoginUser is passed this indicates that user has already // logged in and we should behave accordingly. - bool immediate_login = - parsed_command_line().HasSwitch(switches::kLoginUser); + bool immediate_login = parsed_command_line().HasSwitch(switches::kLoginUser); if (immediate_login) { // Redirects Chrome logging to the user data dir. logging::RedirectChromeLogging(parsed_command_line()); @@ -823,7 +753,7 @@ AccessibilityManager::Initialize(); - if (!ash_util::IsRunningInMash()) { + if (chromeos::GetAshConfig() != ash::Config::MASH) { // Initialize magnification manager before ash tray is created. And this // must be placed after UserManager::SessionStarted(); // TODO(sad): These components expects the ash::Shell instance to be @@ -864,6 +794,14 @@ g_browser_process->platform_part()->RegisterKeepAlive(); } + // AccelerometerReader is used by ash and content (via DeviceSensor). + // TODO(mash): Initialize this for Mash or use owned instances in src/ash and + // src/device. http://crbug.com/525658. + chromeos::AccelerometerReader::GetInstance()->Initialize( + base::CreateSequencedTaskRunnerWithTraits( + {base::MayBlock(), base::TaskPriority::BACKGROUND, + base::TaskShutdownBehavior::SKIP_ON_SHUTDOWN})); + // NOTE: Calls ChromeBrowserMainParts::PreProfileInit() which calls // ChromeBrowserMainExtraPartsAsh::PreProfileInit() which initializes // ash::Shell. @@ -873,21 +811,6 @@ // loading the default profile). keyboard::InitializeKeyboard(); - // AccelerometerReader is used by ash and content (via DeviceSensor). - chromeos::AccelerometerReader::GetInstance()->Initialize( - base::CreateSequencedTaskRunnerWithTraits( - {base::MayBlock(), base::TaskPriority::BACKGROUND, - base::TaskShutdownBehavior::SKIP_ON_SHUTDOWN})); - - PushProcessCreationTimeToAsh(); - - // Makes mojo request to TabletModeController in ash. - tablet_mode_client_ = std::make_unique<TabletModeClient>(); - tablet_mode_client_->Init(); - - wallpaper_controller_client_ = std::make_unique<WallpaperControllerClient>(); - wallpaper_controller_client_->Init(); - if (lock_screen_apps::StateController::IsEnabled()) { lock_screen_apps_state_controller_ = base::MakeUnique<lock_screen_apps::StateController>(); @@ -933,8 +856,7 @@ class GuestLanguageSetCallbackData { public: - explicit GuestLanguageSetCallbackData(Profile* profile) : profile(profile) { - } + explicit GuestLanguageSetCallbackData(Profile* profile) : profile(profile) {} // Must match SwitchLanguageCallback type. static void Callback( @@ -992,8 +914,8 @@ &GuestLanguageSetCallbackData::Callback, base::Passed(std::move(data)))); const user_manager::User* const user = ProfileHelper::Get()->GetUserByProfile(profile); - UserSessionManager::GetInstance()->RespectLocalePreference( - profile, user, callback); + UserSessionManager::GetInstance()->RespectLocalePreference(profile, user, + callback); } void ChromeBrowserMainPartsChromeos::PostProfileInit() { @@ -1100,7 +1022,7 @@ } void ChromeBrowserMainPartsChromeos::PostBrowserStart() { - if (!ash_util::IsRunningInMash()) { + if (chromeos::GetAshConfig() != ash::Config::MASH) { // These are dependent on the ash::Shell singleton already having been // initialized. Consequently, these cannot be used when running as a mus // client. @@ -1129,12 +1051,6 @@ // fetch of the initial CrosSettings DeviceRebootOnShutdown policy. shutdown_policy_forwarder_ = base::MakeUnique<ShutdownPolicyForwarder>(); - if (ash::switches::IsNightLightEnabled()) { - night_light_client_ = base::MakeUnique<NightLightClient>( - g_browser_process->system_request_context()); - night_light_client_->Start(); - } - if (base::FeatureList::IsEnabled(features::kUserActivityEventLogging)) { user_activity_logging_controller_ = std::make_unique<power::ml::UserActivityLoggingController>(); @@ -1147,8 +1063,6 @@ void ChromeBrowserMainPartsChromeos::PostMainMessageLoopRun() { chromeos::ResourceReporter::GetInstance()->StopMonitoring(); - night_light_client_.reset(); - BootTimesRecorder::Get()->AddLogoutTimeMarker("UIMessageLoopEnded", true); if (lock_screen_apps_state_controller_) @@ -1199,13 +1113,12 @@ ScreenLocker::ShutDownClass(); keyboard_event_rewriters_.reset(); low_disk_notification_.reset(); - chrome_launcher_controller_initializer_.reset(); user_activity_logging_controller_.reset(); // Detach D-Bus clients before DBusThreadManager is shut down. idle_action_warning_observer_.reset(); - if (!ash_util::IsRunningInMash()) + if (chromeos::GetAshConfig() != ash::Config::MASH) MagnificationManager::Shutdown(); media::SoundsManager::Shutdown(); @@ -1219,8 +1132,6 @@ g_browser_process->platform_part()->user_manager()->Shutdown(); WallpaperManager::Shutdown(); - wallpaper_controller_client_.reset(); - // Let the DeviceDisablingManager unregister itself as an observer of the // CrosSettings singleton before it is destroyed. g_browser_process->platform_part()->ShutdownDeviceDisablingManager(); @@ -1238,8 +1149,9 @@ // Give BrowserPolicyConnectorChromeOS a chance to unregister any observers // on services that are going to be deleted later but before its Shutdown() // is called. - g_browser_process->platform_part()->browser_policy_connector_chromeos()-> - PreShutdown(); + g_browser_process->platform_part() + ->browser_policy_connector_chromeos() + ->PreShutdown(); // Close the notification client before destroying the profile manager. notification_client_.reset(); @@ -1247,10 +1159,6 @@ // NOTE: Closes ash and destroys ash::Shell. ChromeBrowserMainPartsLinux::PostMainMessageLoopRun(); - // Some observers (e.g. SigninScreenHandler) may not be removed until Ash is - // closed. - tablet_mode_client_.reset(); - // Destroy ArcKioskAppManager after its observers are removed when Ash is // closed above. arc_kiosk_app_manager_.reset(); @@ -1261,7 +1169,7 @@ // ChromeBrowserMainPartsLinux::PostMainMessageLoopRun(). arc_service_launcher_.reset(); - if (!ash_util::IsRunningInMash()) + if (chromeos::GetAshConfig() != ash::Config::MASH) AccessibilityManager::Shutdown(); input_method::Shutdown();
diff --git a/chrome/browser/chromeos/chrome_browser_main_chromeos.h b/chrome/browser/chromeos/chrome_browser_main_chromeos.h index f70a0cd..17e03d5f 100644 --- a/chrome/browser/chromeos/chrome_browser_main_chromeos.h +++ b/chrome/browser/chromeos/chrome_browser_main_chromeos.h
@@ -14,10 +14,7 @@ #include "chrome/browser/memory/memory_kills_monitor.h" #include "chromeos/system/version_loader.h" -class NightLightClient; class NotificationPlatformBridge; -class TabletModeClient; -class WallpaperControllerClient; namespace lock_screen_apps { class StateController; @@ -50,7 +47,6 @@ } namespace internal { -class ChromeLauncherControllerInitializer; class DBusServices; class SystemTokenCertDBInitializer; } @@ -61,6 +57,10 @@ } // namespace ml } // namespace power +// ChromeBrowserMainParts implementation for chromeos specific code. +// NOTE: Chromeos UI (Ash) support should be added to +// ChromeBrowserMainExtraPartsAsh instead. This class should not depend on +// src/ash or chrome/browser/ui/ash. class ChromeBrowserMainPartsChromeos : public ChromeBrowserMainPartsLinux { public: explicit ChromeBrowserMainPartsChromeos( @@ -101,9 +101,6 @@ std::unique_ptr<internal::SystemTokenCertDBInitializer> system_token_certdb_initializer_; - std::unique_ptr<internal::ChromeLauncherControllerInitializer> - chrome_launcher_controller_initializer_; - std::unique_ptr<ShutdownPolicyForwarder> shutdown_policy_forwarder_; std::unique_ptr<EventRewriterDelegateImpl> event_rewriter_delegate_; @@ -121,13 +118,9 @@ std::unique_ptr<memory::MemoryKillsMonitor::Handle> memory_kills_monitor_; - std::unique_ptr<TabletModeClient> tablet_mode_client_; std::unique_ptr<lock_screen_apps::StateController> lock_screen_apps_state_controller_; - std::unique_ptr<NightLightClient> night_light_client_; - std::unique_ptr<WallpaperControllerClient> wallpaper_controller_client_; - // TODO(estade): Remove this when Chrome OS uses native notifications by // default (as it will be instantiated elsewhere). For now it's necessary to // send notifier settings information to Ash.
diff --git a/chrome/browser/chromeos/smb_client/smb_provider.cc b/chrome/browser/chromeos/smb_client/smb_provider.cc index 4e27c60..c4ccf00 100644 --- a/chrome/browser/chromeos/smb_client/smb_provider.cc +++ b/chrome/browser/chromeos/smb_client/smb_provider.cc
@@ -16,7 +16,7 @@ : provider_id_(ProviderId::CreateFromNativeId("smb")), capabilities_(false /* configurable */, false /* watchable */, - false /* multiple_mounts */, + true /* multiple_mounts */, extensions::SOURCE_NETWORK), // TODO(baileyberro): Localize this string, so it shows correctly in all // languages. See l10n_util::GetStringUTF8.
diff --git a/chrome/browser/devtools/global_confirm_info_bar_browsertest.cc b/chrome/browser/devtools/global_confirm_info_bar_browsertest.cc index 5f27aab..b334f62 100644 --- a/chrome/browser/devtools/global_confirm_info_bar_browsertest.cc +++ b/chrome/browser/devtools/global_confirm_info_bar_browsertest.cc
@@ -15,7 +15,6 @@ #include "chrome/browser/ui/tabs/tab_strip_model.h" #include "chrome/test/base/in_process_browser_test.h" #include "components/infobars/core/infobar.h" -#include "components/infobars/core/infobars_switches.h" #include "content/public/test/test_utils.h" namespace { @@ -55,22 +54,6 @@ DISALLOW_COPY_AND_ASSIGN(GlobalConfirmInfoBarTest); }; -// Subclass for tests that require infobars to be disabled. -class GlobalConfirmInfoBarWithInfoBarDisabledTest - : public GlobalConfirmInfoBarTest { - public: - GlobalConfirmInfoBarWithInfoBarDisabledTest() = default; - ~GlobalConfirmInfoBarWithInfoBarDisabledTest() override = default; - - protected: - void SetUpCommandLine(base::CommandLine* command_line) override { - command_line->AppendSwitch(infobars::switches::kDisableInfoBars); - } - - private: - DISALLOW_COPY_AND_ASSIGN(GlobalConfirmInfoBarWithInfoBarDisabledTest); -}; - } // namespace // Creates a global confirm info bar on a browser with 2 tabs and closes it. @@ -146,17 +129,3 @@ for (int i = 0; i < tab_strip_model->count(); i++) EXPECT_EQ(0u, GetInfoBarServiceFromTabIndex(i)->infobar_count()); } - -IN_PROC_BROWSER_TEST_F(GlobalConfirmInfoBarWithInfoBarDisabledTest, - InfoBarsDisabled) { - ASSERT_EQ(1, browser()->tab_strip_model()->count()); - - auto delegate = base::MakeUnique<TestConfirmInfoBarDelegate>(); - base::WeakPtr<GlobalConfirmInfoBar> global_confirm_info_bar = - GlobalConfirmInfoBar::Show(std::move(delegate)); - - // In this case, the deletion is done asynchronously. - content::RunAllPendingInMessageLoop(); - - ASSERT_FALSE(global_confirm_info_bar); -}
diff --git a/chrome/browser/engagement/site_engagement_service.h b/chrome/browser/engagement/site_engagement_service.h index f8d8ae83..57f08ab 100644 --- a/chrome/browser/engagement/site_engagement_service.h +++ b/chrome/browser/engagement/site_engagement_service.h
@@ -204,6 +204,7 @@ FRIEND_TEST_ALL_PREFIXES(banners::AppBannerManagerBrowserTest, CheckOnLoadWithoutSufficientEngagement); FRIEND_TEST_ALL_PREFIXES(AppBannerSettingsHelperTest, SiteEngagementTrigger); + FRIEND_TEST_ALL_PREFIXES(HostedAppPWAOnlyTest, EngagementHistogram); #if defined(OS_ANDROID) // Shim class to expose the service to Java.
diff --git a/chrome/browser/extensions/api/webrtc_logging_private/webrtc_logging_private_api.h b/chrome/browser/extensions/api/webrtc_logging_private/webrtc_logging_private_api.h index 8df0e17..1646e48 100644 --- a/chrome/browser/extensions/api/webrtc_logging_private/webrtc_logging_private_api.h +++ b/chrome/browser/extensions/api/webrtc_logging_private/webrtc_logging_private_api.h
@@ -12,7 +12,7 @@ #include "media/media_features.h" #if BUILDFLAG(ENABLE_WEBRTC) -#include "chrome/browser/media/audio_debug_recordings_handler.h" +#include "chrome/browser/media/webrtc/audio_debug_recordings_handler.h" #include "chrome/browser/media/webrtc/webrtc_logging_handler_host.h" #endif
diff --git a/chrome/browser/extensions/extension_csp_bypass_browsertest.cc b/chrome/browser/extensions/extension_csp_bypass_browsertest.cc new file mode 100644 index 0000000..bd852ab --- /dev/null +++ b/chrome/browser/extensions/extension_csp_bypass_browsertest.cc
@@ -0,0 +1,119 @@ +// 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 "base/strings/stringprintf.h" +#include "chrome/browser/extensions/extension_browsertest.h" +#include "chrome/browser/extensions/test_extension_dir.h" +#include "chrome/browser/ui/tabs/tab_strip_model.h" +#include "chrome/common/url_constants.h" +#include "chrome/test/base/ui_test_utils.h" +#include "content/public/browser/render_frame_host.h" +#include "content/public/browser/web_contents.h" +#include "content/public/test/browser_test_utils.h" +#include "extensions/common/value_builder.h" + +namespace extensions { + +namespace { + +class ExtensionCSPBypassTest : public ExtensionBrowserTest { + public: + ExtensionCSPBypassTest() {} + + void SetUpOnMainThread() override { + ExtensionBrowserTest::SetUpOnMainThread(); + ASSERT_TRUE(embedded_test_server()->Start()); + } + + protected: + const Extension* AddExtension(bool is_component, bool all_urls_permission) { + auto dir = std::make_unique<TestExtensionDir>(); + + std::string unique_name = base::StringPrintf( + "component=%d, all_urls=%d", is_component, all_urls_permission); + DictionaryBuilder manifest; + manifest.Set("name", unique_name) + .Set("version", "1") + .Set("manifest_version", 2) + .Set("web_accessible_resources", ListBuilder().Append("*").Build()); + + if (all_urls_permission) { + manifest.Set("permissions", ListBuilder().Append("<all_urls>").Build()); + } + if (is_component) { + // LoadExtensionAsComponent requires the manifest to contain a key. + std::string key; + EXPECT_TRUE(Extension::ProducePEM(unique_name, &key)); + manifest.Set("key", key); + } + + dir->WriteFile(FILE_PATH_LITERAL("script.js"), ""); + dir->WriteManifest(manifest.ToJSON()); + + const Extension* extension = nullptr; + if (is_component) { + extension = LoadExtensionAsComponent(dir->UnpackedPath()); + } else { + extension = LoadExtension(dir->UnpackedPath()); + } + CHECK(extension); + temp_dirs_.push_back(std::move(dir)); + return extension; + } + + bool CanLoadScript(const Extension* extension) { + content::RenderFrameHost* rfh = + browser()->tab_strip_model()->GetActiveWebContents()->GetMainFrame(); + std::string code = base::StringPrintf( + R"( + var s = document.createElement('script'); + s.src = '%s'; + s.onload = function() { + // Not blocked by CSP. + window.domAutomationController.send(true); + }; + s.onerror = function() { + // Blocked by CSP. + window.domAutomationController.send(false); + }; + document.body.appendChild(s);)", + extension->GetResourceURL("script.js").spec().c_str()); + bool script_loaded = false; + EXPECT_TRUE(ExecuteScriptAndExtractBool(rfh, code, &script_loaded)); + return script_loaded; + } + + private: + std::vector<std::unique_ptr<TestExtensionDir>> temp_dirs_; + + DISALLOW_COPY_AND_ASSIGN(ExtensionCSPBypassTest); +}; + +} // namespace + +IN_PROC_BROWSER_TEST_F(ExtensionCSPBypassTest, LoadWebAccessibleScript) { + const Extension* component_ext_with_permission = AddExtension(true, true); + const Extension* component_ext_without_permission = AddExtension(true, false); + const Extension* ext_with_permission = AddExtension(false, true); + const Extension* ext_without_permission = AddExtension(false, false); + + // chrome-extension:-URLs can always bypass CSP in normal pages. + GURL non_webui_url(embedded_test_server()->GetURL("/empty.html")); + ui_test_utils::NavigateToURL(browser(), non_webui_url); + + EXPECT_TRUE(CanLoadScript(component_ext_with_permission)); + EXPECT_TRUE(CanLoadScript(component_ext_without_permission)); + EXPECT_TRUE(CanLoadScript(ext_with_permission)); + EXPECT_TRUE(CanLoadScript(ext_without_permission)); + + // chrome-extension:-URLs can never bypass CSP in WebUI. + ui_test_utils::NavigateToURL(browser(), GURL(chrome::kChromeUIVersionURL)); + + EXPECT_FALSE(CanLoadScript(component_ext_with_permission)); + EXPECT_FALSE(CanLoadScript(component_ext_without_permission)); + EXPECT_FALSE(CanLoadScript(ext_with_permission)); + EXPECT_FALSE(CanLoadScript(ext_without_permission)); +} + +} // namespace extensions
diff --git a/chrome/browser/flag_descriptions.cc b/chrome/browser/flag_descriptions.cc index e6e4c42..51f936a8 100644 --- a/chrome/browser/flag_descriptions.cc +++ b/chrome/browser/flag_descriptions.cc
@@ -533,11 +533,6 @@ "Wheel scroll latching enforces latching to a single element for the " "duration of a scroll sequence."; -const char kEnableUsernameCorrectionName[] = "Enable username correction"; -const char kEnableUsernameCorrectionDescription[] = - "While on the pending password state, add an edit button to the bubble so " - "that user can edit the username."; - const char kEnableUseZoomForDsfName[] = "Use Blink's zoom for device scale factor."; const char kEnableUseZoomForDsfDescription[] = @@ -704,12 +699,6 @@ "Enabling this option allows web applications to access experimental " "extensions to the Gamepad APIs."; -const char kGlCompositedOverlayCandidateQuadBordersName[] = - "GL composited overlay candidate quad borders"; -const char kGlCompositedOverlayCandidateQuadBordersDescription[] = - "Renders a border around GL composited overlay candidate quads to help " - "debug and study overlay support."; - const char kGpuRasterizationMsaaSampleCountName[] = "GPU rasterization MSAA sample count."; const char kGpuRasterizationMsaaSampleCountDescription[] = @@ -1096,11 +1085,6 @@ const char kPasswordImportDescription[] = "Import functionality in password settings."; -const char kPasswordSelectionName[] = - "Password selection and eye icon in prompt"; -const char kPasswordSelectionDescription[] = - "Show a password selector and an eye icon in prompt"; - const char kPermissionActionReportingName[] = "Permission Action Reporting"; const char kPermissionActionReportingDescription[] = "Enables permission action reporting to Safe Browsing servers for opted in " @@ -1401,6 +1385,11 @@ "SYN packet for a previously connected client, allowing faster data send " "start."; +const char kTintGlCompositedContentName[] = "Tint GL-composited content"; +const char kTintGlCompositedContentDescription[] = + "Tint contents composited using GL with a shade of red to help debug and " + "study overlay support."; + const char kTopChromeMd[] = "UI Layout for the browser's top chrome"; const char kTopChromeMdDescription[] = R"*(Toggles between normal and touch (formerly "hybrid") layouts.)*";
diff --git a/chrome/browser/flag_descriptions.h b/chrome/browser/flag_descriptions.h index c12c448..06df3d93 100644 --- a/chrome/browser/flag_descriptions.h +++ b/chrome/browser/flag_descriptions.h
@@ -344,9 +344,6 @@ extern const char kEnableTouchpadAndWheelScrollLatchingName[]; extern const char kEnableTouchpadAndWheelScrollLatchingDescription[]; -extern const char kEnableUsernameCorrectionName[]; -extern const char kEnableUsernameCorrectionDescription[]; - extern const char kEnableUseZoomForDsfName[]; extern const char kEnableUseZoomForDsfDescription[]; extern const char kEnableUseZoomForDsfChoiceDefault[]; @@ -443,9 +440,6 @@ extern const char kGamepadExtensionsName[]; extern const char kGamepadExtensionsDescription[]; -extern const char kGlCompositedOverlayCandidateQuadBordersName[]; -extern const char kGlCompositedOverlayCandidateQuadBordersDescription[]; - extern const char kGpuRasterizationMsaaSampleCountName[]; extern const char kGpuRasterizationMsaaSampleCountDescription[]; extern const char kGpuRasterizationMsaaSampleCountZero[]; @@ -685,9 +679,6 @@ extern const char kPasswordImportName[]; extern const char kPasswordImportDescription[]; -extern const char kPasswordSelectionName[]; -extern const char kPasswordSelectionDescription[]; - extern const char kPermissionActionReportingName[]; extern const char kPermissionActionReportingDescription[]; @@ -869,6 +860,9 @@ extern const char kTcpFastOpenName[]; extern const char kTcpFastOpenDescription[]; +extern const char kTintGlCompositedContentName[]; +extern const char kTintGlCompositedContentDescription[]; + extern const char kTopChromeMd[]; extern const char kTopChromeMdDescription[]; extern const char kTopChromeMdMaterial[];
diff --git a/chrome/browser/history/web_history_service_factory.cc b/chrome/browser/history/web_history_service_factory.cc index 703aca7..53d2e4c8 100644 --- a/chrome/browser/history/web_history_service_factory.cc +++ b/chrome/browser/history/web_history_service_factory.cc
@@ -4,8 +4,7 @@ #include "chrome/browser/history/web_history_service_factory.h" -#include "chrome/browser/signin/profile_oauth2_token_service_factory.h" -#include "chrome/browser/signin/signin_manager_factory.h" +#include "chrome/browser/signin/identity_manager_factory.h" #include "chrome/browser/sync/profile_sync_service_factory.h" #include "components/history/core/browser/web_history_service.h" #include "components/keyed_service/content/browser_context_dependency_manager.h" @@ -51,8 +50,7 @@ return nullptr; return new history::WebHistoryService( - ProfileOAuth2TokenServiceFactory::GetForProfile(profile), - SigninManagerFactory::GetForProfile(profile), + IdentityManagerFactory::GetForProfile(profile), profile->GetRequestContext()); } @@ -60,8 +58,7 @@ : BrowserContextKeyedServiceFactory( "WebHistoryServiceFactory", BrowserContextDependencyManager::GetInstance()) { - DependsOn(ProfileOAuth2TokenServiceFactory::GetInstance()); - DependsOn(SigninManagerFactory::GetInstance()); + DependsOn(IdentityManagerFactory::GetInstance()); } WebHistoryServiceFactory::~WebHistoryServiceFactory() {
diff --git a/chrome/browser/media/router/providers/wired_display/wired_display_media_route_provider.cc b/chrome/browser/media/router/providers/wired_display/wired_display_media_route_provider.cc index 2b3e3b8..65ccec4 100644 --- a/chrome/browser/media/router/providers/wired_display/wired_display_media_route_provider.cc +++ b/chrome/browser/media/router/providers/wired_display/wired_display_media_route_provider.cc
@@ -52,9 +52,16 @@ return sink_internal; } -// Returns true if |display1| is above |display2|, or if they are at the same -// height and |display1| is to the left of |display2|. -bool CompareDisplayBounds(const Display& display1, const Display& display2) { +// Returns true if |display1| should come before |display2| when displays are +// sorted. Primary displays and displays to the top-left take priority, in +// that order. +bool CompareDisplays(int64_t primary_id, + const Display& display1, + const Display& display2) { + if (display1.id() == primary_id) + return true; + if (display2.id() == primary_id) + return false; return display1.bounds().y() < display2.bounds().y() || (display1.bounds().y() == display2.bounds().y() && display1.bounds().x() < display2.bounds().x()); @@ -326,14 +333,22 @@ std::vector<Display> WiredDisplayMediaRouteProvider::GetAvailableDisplays() const { std::vector<Display> displays = GetAllDisplays(); - const gfx::Rect primary_display_bounds = GetPrimaryDisplay().bounds(); + const Display primary_display = GetPrimaryDisplay(); + std::sort( + displays.begin(), displays.end(), + [&primary_display](const Display& display1, const Display& display2) { + return CompareDisplays(primary_display.id(), display1, display2); + }); - // Remove the primary display and displays that mirror it. - base::EraseIf(displays, [&primary_display_bounds](const Display& display) { - return display.bounds() == primary_display_bounds; + // Remove displays that mirror the primary display. On some platforms such as + // Windows, mirrored displays are reported as one display. On others, mirrored + // displays are reported separately but with the same bounds. + base::EraseIf(displays, [&primary_display](const Display& display) { + return display.id() != primary_display.id() && + display.bounds() == primary_display.bounds(); }); - std::sort(displays.begin(), displays.end(), CompareDisplayBounds); - return displays; + // If there is only one display, the user should not be able to present to it. + return displays.size() == 1 ? std::vector<Display>() : displays; } void WiredDisplayMediaRouteProvider::ReportSinkAvailability(
diff --git a/chrome/browser/media/router/providers/wired_display/wired_display_media_route_provider.h b/chrome/browser/media/router/providers/wired_display/wired_display_media_route_provider.h index 1ac1211a..6b1dadc0 100644 --- a/chrome/browser/media/router/providers/wired_display/wired_display_media_route_provider.h +++ b/chrome/browser/media/router/providers/wired_display/wired_display_media_route_provider.h
@@ -28,8 +28,8 @@ class WiredDisplayPresentationReceiver; // A MediaRouteProvider class that provides wired displays as media sinks. -// A display can be used as a sink if it is secondary and does not mirror a -// primary display. +// Displays can be used as sinks when there are multiple dipslays that are not +// mirrored. class WiredDisplayMediaRouteProvider : public mojom::MediaRouteProvider, public display::DisplayObserver { public: @@ -153,11 +153,12 @@ base::Optional<display::Display> GetDisplayBySinkId( const std::string& sink_id) const; - // Returns a list of available sinks. A display can be a sink if it is - // secondary and does not mirror a primary display. + // Returns a list of available sinks. std::vector<MediaSinkInternal> GetSinks() const; - // Returns a list of displays that can be used as sinks. + // Returns a list of displays that can be used as sinks. Returns an empty list + // if there is only one display or if the secondary displays mirror the + // primary display. std::vector<display::Display> GetAvailableDisplays() const; // Binds |this| to the Mojo request passed into the ctor.
diff --git a/chrome/browser/media/router/providers/wired_display/wired_display_media_route_provider_unittest.cc b/chrome/browser/media/router/providers/wired_display/wired_display_media_route_provider_unittest.cc index 75be9c0..da1f69b 100644 --- a/chrome/browser/media/router/providers/wired_display/wired_display_media_route_provider_unittest.cc +++ b/chrome/browser/media/router/providers/wired_display/wired_display_media_route_provider_unittest.cc
@@ -149,12 +149,12 @@ class WiredDisplayMediaRouteProviderTest : public testing::Test { public: WiredDisplayMediaRouteProviderTest() - : sink_display1_bounds_(0, 0, 1920, 1080), // x, y, width, height. - sink_display2_bounds_(1920, 0, 1920, 1080), - primary_display_bounds_(0, 1080, 1920, 1080), - sink_display1_(10000001, sink_display1_bounds_), - sink_display2_(10000002, sink_display2_bounds_), + : primary_display_bounds_(0, 1080, 1920, 1080), + secondary_display1_bounds_(0, 0, 1920, 1080), // x, y, width, height. + secondary_display2_bounds_(1920, 0, 1920, 1080), primary_display_(10000003, primary_display_bounds_), + secondary_display1_(10000001, secondary_display1_bounds_), + secondary_display2_(10000002, secondary_display2_bounds_), mirror_display_(10000004, primary_display_bounds_) {} ~WiredDisplayMediaRouteProviderTest() override {} @@ -185,14 +185,13 @@ MockMojoMediaRouter router_; std::unique_ptr<mojo::Binding<mojom::MediaRouter>> router_binding_; - gfx::Rect sink_display1_bounds_; - gfx::Rect sink_display2_bounds_; gfx::Rect primary_display_bounds_; + gfx::Rect secondary_display1_bounds_; + gfx::Rect secondary_display2_bounds_; - Display sink_display1_; - Display sink_display2_; - // The displays below do not meet the criteria for being used as sinks. Display primary_display_; + Display secondary_display1_; + Display secondary_display2_; Display mirror_display_; // Has the same bounds as |primary_display_|. MockReceiverCreator receiver_creator_; @@ -204,46 +203,48 @@ }; TEST_F(WiredDisplayMediaRouteProviderTest, GetDisplaysAsSinks) { - // The primary display and the display mirroring it should not be provided - // as sinks. provider_->set_all_displays( - {sink_display1_, primary_display_, mirror_display_, sink_display2_}); + {secondary_display1_, primary_display_, secondary_display2_}); - const std::string sink_id1 = GetSinkId(sink_display1_); - const std::string sink_id2 = GetSinkId(sink_display2_); + const std::string primary_id = GetSinkId(primary_display_); + const std::string secondary_id1 = GetSinkId(secondary_display1_); + const std::string secondary_id2 = GetSinkId(secondary_display2_); EXPECT_CALL(router_, OnSinksReceived(kProviderId, kPresentationSource, _, IsEmpty())) - .WillOnce(WithArg<2>(Invoke( - [&sink_id1, &sink_id2](const std::vector<MediaSinkInternal>& sinks) { - EXPECT_EQ(sinks.size(), 2u); - EXPECT_TRUE(sinks[0].sink().id() == sink_id1 || - sinks[1].sink().id() == sink_id1); - EXPECT_TRUE(sinks[0].sink().id() == sink_id2 || - sinks[1].sink().id() == sink_id2); + .WillOnce( + WithArg<2>(Invoke([&primary_id, &secondary_id1, &secondary_id2]( + const std::vector<MediaSinkInternal>& sinks) { + EXPECT_EQ(sinks.size(), 3u); + EXPECT_EQ(sinks[0].sink().id(), primary_id); + EXPECT_EQ(sinks[1].sink().id(), secondary_id1); + EXPECT_EQ(sinks[2].sink().id(), secondary_id2); }))); provider_pointer_->StartObservingMediaSinks(kPresentationSource); base::RunLoop().RunUntilIdle(); } TEST_F(WiredDisplayMediaRouteProviderTest, NotifyOnDisplayChange) { - const std::string sink_id1 = GetSinkId(sink_display1_); + const std::string primary_id = GetSinkId(primary_display_); + const std::string secondary_id1 = GetSinkId(secondary_display1_); provider_pointer_->StartObservingMediaSinks(kPresentationSource); base::RunLoop().RunUntilIdle(); // Add an external display. MediaRouter should be notified of the sink and the // sink availability change. - provider_->set_all_displays({primary_display_, sink_display1_}); + provider_->set_all_displays({primary_display_, secondary_display1_}); EXPECT_CALL(router_, OnSinkAvailabilityUpdated( MediaRouteProviderId::WIRED_DISPLAY, mojom::MediaRouter::SinkAvailability::PER_SOURCE)); EXPECT_CALL(router_, OnSinksReceived(MediaRouteProviderId::WIRED_DISPLAY, _, _, _)) - .WillOnce(WithArg<2>( - Invoke([&sink_id1](const std::vector<MediaSinkInternal>& sinks) { - EXPECT_EQ(sinks.size(), 1u); - EXPECT_EQ(sinks[0].sink().id(), sink_id1); + .WillOnce( + WithArg<2>(Invoke([&primary_id, &secondary_id1]( + const std::vector<MediaSinkInternal>& sinks) { + EXPECT_EQ(sinks.size(), 2u); + EXPECT_EQ(sinks[0].sink().id(), primary_id); + EXPECT_EQ(sinks[1].sink().id(), secondary_id1); }))); - provider_->OnDisplayAdded(sink_display1_); + provider_->OnDisplayAdded(secondary_display1_); base::RunLoop().RunUntilIdle(); // Remove the external display. MediaRouter should be notified of the lack of @@ -254,7 +255,18 @@ mojom::MediaRouter::SinkAvailability::UNAVAILABLE)); EXPECT_CALL(router_, OnSinksReceived(MediaRouteProviderId::WIRED_DISPLAY, _, IsEmpty(), _)); - provider_->OnDisplayRemoved(sink_display1_); + provider_->OnDisplayRemoved(secondary_display1_); + base::RunLoop().RunUntilIdle(); + + // Add a display that mirrors the primary display. The sink list should still + // be empty. + provider_->set_all_displays({primary_display_, mirror_display_}); + EXPECT_CALL(router_, OnSinkAvailabilityUpdated( + MediaRouteProviderId::WIRED_DISPLAY, + mojom::MediaRouter::SinkAvailability::UNAVAILABLE)); + EXPECT_CALL(router_, OnSinksReceived(MediaRouteProviderId::WIRED_DISPLAY, _, + IsEmpty(), _)); + provider_->OnDisplayAdded(mirror_display_); base::RunLoop().RunUntilIdle(); } @@ -272,7 +284,7 @@ const std::string presentation_id = "presentationId"; MockCallback callback; - provider_->set_all_displays({sink_display1_, primary_display_}); + provider_->set_all_displays({secondary_display1_, primary_display_}); provider_pointer_->StartObservingMediaRoutes(kPresentationSource); base::RunLoop().RunUntilIdle(); @@ -294,7 +306,7 @@ EXPECT_CALL(*receiver_creator_.receiver(), Start(presentation_id, GURL(kPresentationSource))); provider_pointer_->CreateRoute( - kPresentationSource, GetSinkId(sink_display1_), presentation_id, + kPresentationSource, GetSinkId(secondary_display1_), presentation_id, url::Origin::Create(GURL(kPresentationSource)), 0, base::TimeDelta::FromSeconds(100), false, base::BindOnce(&MockCallback::CreateRoute, base::Unretained(&callback)));
diff --git a/chrome/browser/media/webrtc/audio_debug_recordings_handler.cc b/chrome/browser/media/webrtc/audio_debug_recordings_handler.cc index 45fc33c..6c45714b 100644 --- a/chrome/browser/media/webrtc/audio_debug_recordings_handler.cc +++ b/chrome/browser/media/webrtc/audio_debug_recordings_handler.cc
@@ -2,7 +2,7 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#include "chrome/browser/media/audio_debug_recordings_handler.h" +#include "chrome/browser/media/webrtc/audio_debug_recordings_handler.h" #include <string> #include <utility>
diff --git a/chrome/browser/media/audio_debug_recordings_handler.h b/chrome/browser/media/webrtc/audio_debug_recordings_handler.h similarity index 94% rename from chrome/browser/media/audio_debug_recordings_handler.h rename to chrome/browser/media/webrtc/audio_debug_recordings_handler.h index 1dd02c9..c547da5 100644 --- a/chrome/browser/media/audio_debug_recordings_handler.h +++ b/chrome/browser/media/webrtc/audio_debug_recordings_handler.h
@@ -2,8 +2,8 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#ifndef CHROME_BROWSER_MEDIA_AUDIO_DEBUG_RECORDINGS_HANDLER_H_ -#define CHROME_BROWSER_MEDIA_AUDIO_DEBUG_RECORDINGS_HANDLER_H_ +#ifndef CHROME_BROWSER_MEDIA_WEBRTC_AUDIO_DEBUG_RECORDINGS_HANDLER_H_ +#define CHROME_BROWSER_MEDIA_WEBRTC_AUDIO_DEBUG_RECORDINGS_HANDLER_H_ #include <stddef.h> #include <stdint.h> @@ -95,4 +95,4 @@ DISALLOW_COPY_AND_ASSIGN(AudioDebugRecordingsHandler); }; -#endif // CHROME_BROWSER_MEDIA_AUDIO_DEBUG_RECORDINGS_HANDLER_H_ +#endif // CHROME_BROWSER_MEDIA_WEBRTC_AUDIO_DEBUG_RECORDINGS_HANDLER_H_
diff --git a/chrome/browser/password_manager/password_manager_browsertest.cc b/chrome/browser/password_manager/password_manager_browsertest.cc index 3f77775..6338d60db 100644 --- a/chrome/browser/password_manager/password_manager_browsertest.cc +++ b/chrome/browser/password_manager/password_manager_browsertest.cc
@@ -1354,7 +1354,7 @@ // Wait until the username is filled, to make sure autofill kicked in. WaitForElementValue("username", "admin"); - CheckElementValue("password", "12345"); + WaitForElementValue("password", "12345"); } // https://crbug.com/713645 @@ -1622,7 +1622,7 @@ content::SimulateMouseClickAt( WebContents(), 0, blink::WebMouseEvent::Button::kLeft, gfx::Point(1, 1)); WaitForElementValue("username_field", "user"); - CheckElementValue("password_field", "12345"); + WaitForElementValue("password_field", "12345"); } // Tests that obsolete HTTP credentials are moved when a site migrated to HTTPS @@ -2546,24 +2546,7 @@ base::ASCIIToUTF16("pw")); } -// This is a subclass to enable kEnablePasswordSelection feature. -class PasswordManagerBrowserTestForPasswordSelection - : public PasswordManagerBrowserTestBase { - public: - PasswordManagerBrowserTestForPasswordSelection() = default; - ~PasswordManagerBrowserTestForPasswordSelection() override = default; - - void SetUp() override { - scoped_feature_list_.InitAndEnableFeature( - password_manager::features::kEnablePasswordSelection); - PasswordManagerBrowserTestBase::SetUp(); - } - - private: - base::test::ScopedFeatureList scoped_feature_list_; -}; - -IN_PROC_BROWSER_TEST_F(PasswordManagerBrowserTestForPasswordSelection, +IN_PROC_BROWSER_TEST_F(PasswordManagerBrowserTestBase, MultiplePasswordsWithPasswordSelectionEnabled) { NavigateToFile("/password/password_form.html"); NavigationObserver observer(WebContents()); @@ -2668,21 +2651,8 @@ content::SimulateMouseClickAt( WebContents(), 0, blink::WebMouseEvent::Button::kLeft, gfx::Point(1, 1)); - std::string get_username = - "window.domAutomationController.send(" - " document.getElementById('ambiguous_form').elements[0].value);"; - std::string actual_username; - ASSERT_TRUE(content::ExecuteScriptWithoutUserGestureAndExtractString( - RenderFrameHost(), get_username, &actual_username)); - EXPECT_EQ("myusername", actual_username); - - std::string get_password = - "window.domAutomationController.send(" - " document.getElementById('ambiguous_form').elements[1].value);"; - std::string actual_password; - ASSERT_TRUE(content::ExecuteScriptWithoutUserGestureAndExtractString( - RenderFrameHost(), get_password, &actual_password)); - EXPECT_EQ("mypassword", actual_password); + WaitForElementValue("ambiguous_form", 0 /* elements_index */, "myusername"); + WaitForElementValue("ambiguous_form", 1 /* elements_index */, "mypassword"); } // Test whether the password form having username and password fields without @@ -2710,21 +2680,8 @@ content::SimulateMouseClickAt( WebContents(), 0, blink::WebMouseEvent::Button::kLeft, gfx::Point(1, 1)); - std::string get_username = - "window.domAutomationController.send(" - " document.getElementById('no_name_id_form').elements[0].value);"; - std::string actual_username; - ASSERT_TRUE(content::ExecuteScriptWithoutUserGestureAndExtractString( - RenderFrameHost(), get_username, &actual_username)); - EXPECT_EQ("myusername", actual_username); - - std::string get_password = - "window.domAutomationController.send(" - " document.getElementById('no_name_id_form').elements[1].value);"; - std::string actual_password; - ASSERT_TRUE(content::ExecuteScriptWithoutUserGestureAndExtractString( - RenderFrameHost(), get_password, &actual_password)); - EXPECT_EQ("mypassword", actual_password); + WaitForElementValue("no_name_id_form", 0 /* elements_index */, "myusername"); + WaitForElementValue("no_name_id_form", 1 /* elements_index */, "mypassword"); } // Test whether the change password form having username and password fields @@ -2751,23 +2708,10 @@ content::SimulateMouseClickAt( WebContents(), 0, blink::WebMouseEvent::Button::kLeft, gfx::Point(1, 1)); - std::string get_username = - "window.domAutomationController.send(" - " document.getElementById(" - " 'change_pwd_but_no_autocomplete').elements[0].value);"; - std::string actual_username; - ASSERT_TRUE(content::ExecuteScriptWithoutUserGestureAndExtractString( - RenderFrameHost(), get_username, &actual_username)); - EXPECT_EQ("myusername", actual_username); - - std::string get_password = - "window.domAutomationController.send(" - " document.getElementById(" - " 'change_pwd_but_no_autocomplete').elements[1].value);"; - std::string actual_password; - ASSERT_TRUE(content::ExecuteScriptWithoutUserGestureAndExtractString( - RenderFrameHost(), get_password, &actual_password)); - EXPECT_EQ("mypassword", actual_password); + WaitForElementValue("change_pwd_but_no_autocomplete", 0 /* elements_index */, + "myusername"); + WaitForElementValue("change_pwd_but_no_autocomplete", 1 /* elements_index */, + "mypassword"); std::string get_new_password = "window.domAutomationController.send(" @@ -2805,21 +2749,8 @@ content::SimulateMouseClickAt( WebContents(), 0, blink::WebMouseEvent::Button::kLeft, gfx::Point(1, 1)); - std::string get_username = - "window.domAutomationController.send(" - " document.getElementById('change_pwd').elements[0].value);"; - std::string actual_username; - ASSERT_TRUE(content::ExecuteScriptWithoutUserGestureAndExtractString( - RenderFrameHost(), get_username, &actual_username)); - EXPECT_EQ("myusername", actual_username); - - std::string get_password = - "window.domAutomationController.send(" - " document.getElementById('change_pwd').elements[1].value);"; - std::string actual_password; - ASSERT_TRUE(content::ExecuteScriptWithoutUserGestureAndExtractString( - RenderFrameHost(), get_password, &actual_password)); - EXPECT_EQ("mypassword", actual_password); + WaitForElementValue("change_pwd", 0 /* elements_index */, "myusername"); + WaitForElementValue("change_pwd", 1 /* elements_index */, "mypassword"); std::string get_new_password = "window.domAutomationController.send(" @@ -3028,21 +2959,10 @@ content::SimulateMouseClickAt( WebContents(), 0, blink::WebMouseEvent::Button::kLeft, gfx::Point(1, 1)); - std::string get_username = - "window.domAutomationController.send(" - " document.getElementById('hidden_password_form').elements[0].value);"; - std::string actual_username; - ASSERT_TRUE(content::ExecuteScriptWithoutUserGestureAndExtractString( - RenderFrameHost(), get_username, &actual_username)); - EXPECT_EQ("myusername", actual_username); - - std::string get_password = - "window.domAutomationController.send(" - " document.getElementById('hidden_password_form').elements[2].value);"; - std::string actual_password; - ASSERT_TRUE(content::ExecuteScriptWithoutUserGestureAndExtractString( - RenderFrameHost(), get_password, &actual_password)); - EXPECT_EQ("mypassword", actual_password); + WaitForElementValue("hidden_password_form", 0 /* elements_index */, + "myusername"); + WaitForElementValue("hidden_password_form", 2 /* elements_index */, + "mypassword"); } // Check that the internals page contains logs from the renderer.
diff --git a/chrome/browser/password_manager/password_manager_test_base.cc b/chrome/browser/password_manager/password_manager_test_base.cc index 42b7095..68b2ffa 100644 --- a/chrome/browser/password_manager/password_manager_test_base.cc +++ b/chrome/browser/password_manager/password_manager_test_base.cc
@@ -269,6 +269,13 @@ EXPECT_TRUE(transport_security_state->ShouldUpgradeToSSL(host)); } +enum ReturnCodes { // Possible results of the JavaScript code. + RETURN_CODE_OK, + RETURN_CODE_NO_ELEMENT, + RETURN_CODE_WRONG_VALUE, + RETURN_CODE_INVALID, +}; + } // namespace NavigationObserver::NavigationObserver(content::WebContents* web_contents) @@ -523,12 +530,6 @@ const std::string& iframe_id, const std::string& element_id, const std::string& expected_value) { - enum ReturnCodes { // Possible results of the JavaScript code. - RETURN_CODE_OK, - RETURN_CODE_NO_ELEMENT, - RETURN_CODE_WRONG_VALUE, - RETURN_CODE_INVALID, - }; const std::string value_check_function = base::StringPrintf( "function valueCheck() {" " if (%s)" @@ -574,6 +575,45 @@ << ", expected_value = " << expected_value; } +void PasswordManagerBrowserTestBase::WaitForElementValue( + const std::string& form_id, + size_t elements_index, + const std::string& expected_value) { + const std::string value_check_function = base::StringPrintf( + "function valueCheck() {" + " var element = document.getElementById('%s').elements['%zu'];" + " return element && element.value == '%s';" + "}", + form_id.c_str(), elements_index, expected_value.c_str()); + const std::string script = + value_check_function + + base::StringPrintf( + "if (valueCheck()) {" + " /* Spin the event loop with setTimeout. */" + " setTimeout(window.domAutomationController.send(%d), 0);" + "} else {" + " var element = document.getElementById('%s').elements['%zu'];" + " if (!element)" + " window.domAutomationController.send(%d);" + " element.onchange = function() {" + " if (valueCheck()) {" + " /* Spin the event loop with setTimeout. */" + " setTimeout(window.domAutomationController.send(%d), 0);" + " } else {" + " window.domAutomationController.send(%d);" + " }" + " };" + "}", + RETURN_CODE_OK, form_id.c_str(), elements_index, + RETURN_CODE_NO_ELEMENT, RETURN_CODE_OK, RETURN_CODE_WRONG_VALUE); + int return_value = RETURN_CODE_INVALID; + ASSERT_TRUE(content::ExecuteScriptWithoutUserGestureAndExtractInt( + RenderFrameHost(), script, &return_value)); + EXPECT_EQ(RETURN_CODE_OK, return_value) + << "form_id = " << form_id << "elements_index=" << elements_index + << ", expected_value = " << expected_value; +} + void PasswordManagerBrowserTestBase::WaitForPasswordStore() { scoped_refptr<password_manager::PasswordStore> password_store = PasswordStoreFactory::GetForProfile(browser()->profile(),
diff --git a/chrome/browser/password_manager/password_manager_test_base.h b/chrome/browser/password_manager/password_manager_test_base.h index 1967c37d..e0f07c3 100644 --- a/chrome/browser/password_manager/password_manager_test_base.h +++ b/chrome/browser/password_manager/password_manager_test_base.h
@@ -169,6 +169,13 @@ void WaitForElementValue(const std::string& iframe_id, const std::string& element_id, const std::string& expected_value); + + // Same as above except the element has index |element_index| in elements() of + // the form |form_id|. + void WaitForElementValue(const std::string& form_id, + size_t element_index, + const std::string& expected_value); + // Make sure that the password store processed all the previous calls which // are executed on another thread. void WaitForPasswordStore();
diff --git a/chrome/browser/prerender/prerender_browsertest.cc b/chrome/browser/prerender/prerender_browsertest.cc index a9b4059..b5a7adee 100644 --- a/chrome/browser/prerender/prerender_browsertest.cc +++ b/chrome/browser/prerender/prerender_browsertest.cc
@@ -984,6 +984,10 @@ static bool first = true; if (first) { first = false; + // Need to leak the client pipe, or else the renderer will + // get a disconnect error and load the error page. + auto* leak_client = new content::mojom::URLLoaderClientPtr; + *leak_client = std::move(params->client); closure.Run(); return true; } @@ -1388,9 +1392,7 @@ } // crbug.com/708158 -// crbug.com/800373 -#if (defined(OS_MACOSX) && defined(ADDRESS_SANITIZER)) || \ - (defined(OS_LINUX) && !defined(NDEBUG)) +#if defined(OS_MACOSX) && defined(ADDRESS_SANITIZER) #define MAYBE_PrerenderNoCommitNoSwap DISABLED_PrerenderNoCommitNoSwap #else #define MAYBE_PrerenderNoCommitNoSwap PrerenderNoCommitNoSwap @@ -2832,16 +2834,8 @@ // Checks that non-http/https/chrome-extension subresource cancels the // prerender. -// Disabled on ChromeOS due to flakyness. See https://crbug.com/800311. -#if defined(OS_CHROMEOS) -#define MAYBE_PrerenderCancelSubresourceUnsupportedScheme \ - DISABLED_PrerenderCancelSubresourceUnsupportedScheme -#else -#define MAYBE_PrerenderCancelSubresourceUnsupportedScheme \ - PrerenderCancelSubresourceUnsupportedScheme -#endif IN_PROC_BROWSER_TEST_F(PrerenderBrowserTest, - MAYBE_PrerenderCancelSubresourceUnsupportedScheme) { + PrerenderCancelSubresourceUnsupportedScheme) { GURL image_url = GURL("invalidscheme://www.google.com/test.jpg"); base::StringPairs replacement_text; replacement_text.push_back( @@ -2849,7 +2843,9 @@ std::string replacement_path; net::test_server::GetFilePathWithReplacements( "/prerender/prerender_with_image.html", replacement_text, - &replacement_path); + &replacement_path); + // Disable load event checks because they race with cancellation. + DisableLoadEventCheck(); PrerenderTestURL(replacement_path, FINAL_STATUS_UNSUPPORTED_SCHEME, 0); }
diff --git a/chrome/browser/resource_coordinator/lifecycle_unit.cc b/chrome/browser/resource_coordinator/lifecycle_unit.cc index eee11d68..057f5aa 100644 --- a/chrome/browser/resource_coordinator/lifecycle_unit.cc +++ b/chrome/browser/resource_coordinator/lifecycle_unit.cc
@@ -19,13 +19,6 @@ return last_focused_time > other.last_focused_time; } -LifecycleUnit::LifecycleUnit() = default; LifecycleUnit::~LifecycleUnit() = default; -uint32_t LifecycleUnit::GetID() const { - return id_; -} - -uint32_t LifecycleUnit::next_id_ = 0; - } // namespace resource_coordinator
diff --git a/chrome/browser/resource_coordinator/lifecycle_unit.h b/chrome/browser/resource_coordinator/lifecycle_unit.h index 887888fc..da515b80 100644 --- a/chrome/browser/resource_coordinator/lifecycle_unit.h +++ b/chrome/browser/resource_coordinator/lifecycle_unit.h
@@ -9,13 +9,15 @@ #include <string> #include "base/containers/flat_set.h" -#include "base/macros.h" #include "base/strings/string16.h" #include "base/time/time.h" #include "chrome/browser/resource_coordinator/discard_reason.h" namespace resource_coordinator { +class LifecycleUnitObserver; +class TabLifecycleUnitExternal; + // A LifecycleUnit represents a unit that can switch between the "loaded" and // "discarded" states. When it is loaded, the unit uses system resources and // provides functionality to the user. When it is discarded, the unit doesn't @@ -43,11 +45,14 @@ base::TimeTicks last_focused_time; }; - LifecycleUnit(); virtual ~LifecycleUnit(); + // Returns the TabLifecycleUnitExternal associated with this LifecycleUnit, if + // any. + virtual TabLifecycleUnitExternal* AsTabLifecycleUnitExternal() = 0; + // Returns a unique id representing this LifecycleUnit. - uint32_t GetID() const; + virtual int32_t GetID() const = 0; // Returns a title describing this LifecycleUnit, or an empty string if no // title is available. @@ -91,13 +96,9 @@ // https://crbug.com/775644 virtual bool Discard(DiscardReason discard_reason) = 0; - private: - static uint32_t next_id_; - - // A unique id representing this LifecycleUnit. - const uint32_t id_ = ++next_id_; - - DISALLOW_COPY_AND_ASSIGN(LifecycleUnit); + // Adds/removes an observer to this LifecycleUnit. + virtual void AddObserver(LifecycleUnitObserver* observer) = 0; + virtual void RemoveObserver(LifecycleUnitObserver* observer) = 0; }; using LifecycleUnitSet = base::flat_set<LifecycleUnit*>;
diff --git a/chrome/browser/resource_coordinator/lifecycle_unit_base.cc b/chrome/browser/resource_coordinator/lifecycle_unit_base.cc new file mode 100644 index 0000000..33f7c03 --- /dev/null +++ b/chrome/browser/resource_coordinator/lifecycle_unit_base.cc
@@ -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 "chrome/browser/resource_coordinator/lifecycle_unit_base.h" + +#include "chrome/browser/resource_coordinator/lifecycle_unit_observer.h" + +namespace resource_coordinator { + +LifecycleUnitBase::LifecycleUnitBase() = default; + +LifecycleUnitBase::~LifecycleUnitBase() = default; + +int32_t LifecycleUnitBase::GetID() const { + return id_; +} + +LifecycleUnit::State LifecycleUnitBase::GetState() const { + return state_; +} + +void LifecycleUnitBase::AddObserver(LifecycleUnitObserver* observer) { + observers_.AddObserver(observer); +} + +void LifecycleUnitBase::RemoveObserver(LifecycleUnitObserver* observer) { + observers_.RemoveObserver(observer); +} + +void LifecycleUnitBase::SetState(State state) { + if (state == state_) + return; + state_ = state; + for (auto& observer : observers_) + observer.OnLifecycleUnitStateChanged(this); +} + +void LifecycleUnitBase::OnLifecycleUnitDestroyed() { + for (auto& observer : observers_) + observer.OnLifecycleUnitDestroyed(this); +} + +int32_t LifecycleUnitBase::next_id_ = 0; + +} // namespace resource_coordinator
diff --git a/chrome/browser/resource_coordinator/lifecycle_unit_base.h b/chrome/browser/resource_coordinator/lifecycle_unit_base.h new file mode 100644 index 0000000..1269368 --- /dev/null +++ b/chrome/browser/resource_coordinator/lifecycle_unit_base.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 CHROME_BROWSER_RESOURCE_COORDINATOR_LIFECYCLE_UNIT_BASE_H_ +#define CHROME_BROWSER_RESOURCE_COORDINATOR_LIFECYCLE_UNIT_BASE_H_ + +#include "base/macros.h" +#include "base/observer_list.h" +#include "chrome/browser/resource_coordinator/lifecycle_unit.h" + +namespace resource_coordinator { + +// Base class for a LifecycleUnit. +class LifecycleUnitBase : public LifecycleUnit { + public: + LifecycleUnitBase(); + ~LifecycleUnitBase() override; + + // LifecycleUnit: + int32_t GetID() const override; + State GetState() const override; + void AddObserver(LifecycleUnitObserver* observer) override; + void RemoveObserver(LifecycleUnitObserver* observer) override; + + protected: + // Sets the state of this LifecycleUnit to |state| and notifies observers. + void SetState(State state); + + // Notifies observers that the LifecycleUnit is being destroyed. This is + // invoked by derived classes rather than by the base class to avoid notifying + // observers when the LifecycleUnit has been partially destroyed. + void OnLifecycleUnitDestroyed(); + + private: + static int32_t next_id_; + + // A unique id representing this LifecycleUnit. + const int32_t id_ = ++next_id_; + + // Current state of this LifecycleUnit. + State state_ = State::LOADED; + + base::ObserverList<LifecycleUnitObserver> observers_; + + DISALLOW_COPY_AND_ASSIGN(LifecycleUnitBase); +}; + +} // namespace resource_coordinator + +#endif // CHROME_BROWSER_RESOURCE_COORDINATOR_LIFECYCLE_UNIT_BASE_H_
diff --git a/chrome/browser/resource_coordinator/lifecycle_unit_base_unittest.cc b/chrome/browser/resource_coordinator/lifecycle_unit_base_unittest.cc new file mode 100644 index 0000000..7bec0a2c --- /dev/null +++ b/chrome/browser/resource_coordinator/lifecycle_unit_base_unittest.cc
@@ -0,0 +1,97 @@ +// 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/browser/resource_coordinator/lifecycle_unit_base.h" + +#include "base/macros.h" +#include "chrome/browser/resource_coordinator/lifecycle_unit_observer.h" +#include "testing/gmock/include/gmock/gmock.h" +#include "testing/gtest/include/gtest/gtest.h" + +namespace resource_coordinator { + +namespace { + +class MockLifecycleUnitObserver : public LifecycleUnitObserver { + public: + MockLifecycleUnitObserver() = default; + + MOCK_METHOD1(OnLifecycleUnitStateChanged, void(LifecycleUnit*)); + MOCK_METHOD1(OnLifecycleUnitDestroyed, void(LifecycleUnit*)); + + private: + DISALLOW_COPY_AND_ASSIGN(MockLifecycleUnitObserver); +}; + +class DummyLifecycleUnit : public LifecycleUnitBase { + public: + using LifecycleUnitBase::SetState; + + DummyLifecycleUnit() = default; + ~DummyLifecycleUnit() override { OnLifecycleUnitDestroyed(); } + + // LifecycleUnit: + TabLifecycleUnitExternal* AsTabLifecycleUnitExternal() override { + return nullptr; + } + base::string16 GetTitle() const override { return base::string16(); } + std::string GetIconURL() const override { return std::string(); } + SortKey GetSortKey() const override { return SortKey(); } + State GetState() const override { return State::LOADED; } + int GetEstimatedMemoryFreedOnDiscardKB() const override { return 0; } + bool CanDiscard(DiscardReason reason) const override { return false; } + bool Discard(DiscardReason discard_reason) override { return false; } + + private: + DISALLOW_COPY_AND_ASSIGN(DummyLifecycleUnit); +}; + +} // namespace + +// Verify that GetID() returns different ids for different LifecycleUnits, but +// always the same id for the same LifecycleUnit. +TEST(LifecycleUnitBaseTest, GetID) { + DummyLifecycleUnit a; + DummyLifecycleUnit b; + DummyLifecycleUnit c; + + EXPECT_NE(a.GetID(), b.GetID()); + EXPECT_NE(a.GetID(), c.GetID()); + EXPECT_NE(b.GetID(), c.GetID()); + + EXPECT_EQ(a.GetID(), a.GetID()); + EXPECT_EQ(b.GetID(), b.GetID()); + EXPECT_EQ(c.GetID(), c.GetID()); +} + +// Verify that observers are notified when the state changes and when the +// LifecycleUnit is destroyed. +TEST(LifecycleUnitBaseTest, SetStateNotifiesObservers) { + testing::StrictMock<MockLifecycleUnitObserver> observer; + DummyLifecycleUnit lifecycle_unit; + lifecycle_unit.AddObserver(&observer); + + // Observer is notified when the state changes. + EXPECT_CALL(observer, OnLifecycleUnitStateChanged(&lifecycle_unit)); + lifecycle_unit.SetState(LifecycleUnit::State::DISCARDED); + testing::Mock::VerifyAndClear(&observer); + + // Observer isn't notified when the state stays the same. + lifecycle_unit.SetState(LifecycleUnit::State::DISCARDED); + + lifecycle_unit.RemoveObserver(&observer); +} + +// Verify that observers are notified when the LifecycleUnit is destroyed. +TEST(LifecycleUnitBaseTest, DestroyNotifiesObservers) { + testing::StrictMock<MockLifecycleUnitObserver> observer; + { + DummyLifecycleUnit lifecycle_unit; + lifecycle_unit.AddObserver(&observer); + EXPECT_CALL(observer, OnLifecycleUnitDestroyed(&lifecycle_unit)); + } + testing::Mock::VerifyAndClear(&observer); +} + +} // namespace resource_coordinator
diff --git a/chrome/browser/resource_coordinator/lifecycle_unit_observer.h b/chrome/browser/resource_coordinator/lifecycle_unit_observer.h new file mode 100644 index 0000000..8cad678a --- /dev/null +++ b/chrome/browser/resource_coordinator/lifecycle_unit_observer.h
@@ -0,0 +1,27 @@ +// 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_RESOURCE_COORDINATOR_LIFECYCLE_UNIT_OBSERVER_H_ +#define CHROME_BROWSER_RESOURCE_COORDINATOR_LIFECYCLE_UNIT_OBSERVER_H_ + +namespace resource_coordinator { + +class LifecycleUnit; + +// Interface to be notified when the state of a LifecycleUnit changes. +class LifecycleUnitObserver { + public: + virtual ~LifecycleUnitObserver() = default; + + // Invoked when the state of the observed LifecycleUnit changes. + virtual void OnLifecycleUnitStateChanged(LifecycleUnit* lifecycle_unit) = 0; + + // Invoked before the observed LifecycleUnit starts being destroyed (i.e. + // |lifecycle_unit| is still valid when this is inovked). + virtual void OnLifecycleUnitDestroyed(LifecycleUnit* lifecycle_unit) = 0; +}; + +} // namespace resource_coordinator + +#endif // CHROME_BROWSER_RESOURCE_COORDINATOR_LIFECYCLE_UNIT_OBSERVER_H_
diff --git a/chrome/browser/resource_coordinator/lifecycle_unit_unittest.cc b/chrome/browser/resource_coordinator/lifecycle_unit_unittest.cc index 16a0945..69aaad4 100644 --- a/chrome/browser/resource_coordinator/lifecycle_unit_unittest.cc +++ b/chrome/browser/resource_coordinator/lifecycle_unit_unittest.cc
@@ -4,33 +4,11 @@ #include "chrome/browser/resource_coordinator/lifecycle_unit.h" -#include "base/macros.h" #include "base/time/time.h" #include "testing/gtest/include/gtest/gtest.h" namespace resource_coordinator { -namespace { - -class DummyLifecycleUnit : public LifecycleUnit { - public: - DummyLifecycleUnit() = default; - - // LifecycleUnit: - base::string16 GetTitle() const override { return base::string16(); } - std::string GetIconURL() const override { return std::string(); } - SortKey GetSortKey() const override { return SortKey(); } - State GetState() const override { return State::LOADED; } - int GetEstimatedMemoryFreedOnDiscardKB() const override { return 0; } - bool CanDiscard(DiscardReason reason) const override { return false; } - bool Discard(DiscardReason discard_reason) override { return false; } - - private: - DISALLOW_COPY_AND_ASSIGN(DummyLifecycleUnit); -}; - -} // namespace - TEST(LifecycleUnitTest, SortKeyComparison) { constexpr base::TimeTicks kBaseTime; LifecycleUnit::SortKey a(kBaseTime); @@ -62,20 +40,4 @@ EXPECT_FALSE(c > c); } -// Verify that GetID() returns different ids for different LifecycleUnits, but -// always the same id for the same LifecycleUnit. -TEST(LifecycleUnitTest, GetID) { - DummyLifecycleUnit a; - DummyLifecycleUnit b; - DummyLifecycleUnit c; - - EXPECT_NE(a.GetID(), b.GetID()); - EXPECT_NE(a.GetID(), c.GetID()); - EXPECT_NE(b.GetID(), c.GetID()); - - EXPECT_EQ(a.GetID(), a.GetID()); - EXPECT_EQ(b.GetID(), b.GetID()); - EXPECT_EQ(c.GetID(), c.GetID()); -} - } // namespace resource_coordinator
diff --git a/chrome/browser/resource_coordinator/tab_lifecycle_unit.cc b/chrome/browser/resource_coordinator/tab_lifecycle_unit.cc index b0ece8b..cfc0fa0 100644 --- a/chrome/browser/resource_coordinator/tab_lifecycle_unit.cc +++ b/chrome/browser/resource_coordinator/tab_lifecycle_unit.cc
@@ -56,7 +56,7 @@ last_focused_time_ = focused ? base::TimeTicks::Max() : NowTicks(); if (focused && GetState() == State::DISCARDED) { - state_ = State::LOADED; + SetState(State::LOADED); // See comment in Discard() for an explanation of why "needs reload" is // false when a tab is discarded. // TODO(fdoray): Remove NavigationControllerImpl::needs_reload_ once session @@ -69,12 +69,15 @@ void TabLifecycleUnitSource::TabLifecycleUnit::SetRecentlyAudible( bool recently_audible) { - if (recently_audible) { + if (recently_audible) recently_audible_time_ = base::TimeTicks::Max(); - } else if (recently_audible_time_.is_null() || - recently_audible_time_ == base::TimeTicks::Max()) { + else if (recently_audible_time_ == base::TimeTicks::Max()) recently_audible_time_ = NowTicks(); - } +} + +TabLifecycleUnitExternal* +TabLifecycleUnitSource::TabLifecycleUnit::AsTabLifecycleUnitExternal() { + return this; } base::string16 TabLifecycleUnitSource::TabLifecycleUnit::GetTitle() const { @@ -95,11 +98,6 @@ return SortKey(last_focused_time_); } -LifecycleUnit::State TabLifecycleUnitSource::TabLifecycleUnit::GetState() - const { - return state_; -} - int TabLifecycleUnitSource::TabLifecycleUnit:: GetEstimatedMemoryFreedOnDiscardKB() const { // TODO(fdoray): Implement this. https://crbug.com/775644 @@ -168,8 +166,6 @@ return false; // Do not discard a tab that has recently been focused. - if (last_focused_time_.is_null()) - return true; const base::TimeDelta time_since_focused = NowTicks() - last_focused_time_; if (time_since_focused < kTabFocusedProtectionTime) return false; @@ -179,7 +175,7 @@ bool TabLifecycleUnitSource::TabLifecycleUnit::Discard( DiscardReason discard_reason) { - if (GetState() == State::DISCARDED) + if (IsDiscarded()) return false; UMA_HISTOGRAM_BOOLEAN( @@ -239,7 +235,7 @@ // RenderFrameProxyHosts. delete old_contents; - state_ = State::DISCARDED; + SetState(State::DISCARDED); ++discard_count_; OnDiscardedStateChange(); @@ -286,8 +282,8 @@ observer.OnAutoDiscardableStateChange(GetWebContents(), auto_discardable_); } -void TabLifecycleUnitSource::TabLifecycleUnit::DiscardTab() { - Discard(DiscardReason::kExternal); +bool TabLifecycleUnitSource::TabLifecycleUnit::DiscardTab() { + return Discard(DiscardReason::kExternal); } bool TabLifecycleUnitSource::TabLifecycleUnit::IsDiscarded() const { @@ -309,8 +305,8 @@ } void TabLifecycleUnitSource::TabLifecycleUnit::DidStartLoading() { - if (state_ == State::DISCARDED) { - state_ = State::LOADED; + if (GetState() == State::DISCARDED) { + SetState(State::LOADED); OnDiscardedStateChange(); } }
diff --git a/chrome/browser/resource_coordinator/tab_lifecycle_unit.h b/chrome/browser/resource_coordinator/tab_lifecycle_unit.h index 77aca15..3cfaa4f 100644 --- a/chrome/browser/resource_coordinator/tab_lifecycle_unit.h +++ b/chrome/browser/resource_coordinator/tab_lifecycle_unit.h
@@ -8,9 +8,10 @@ #include "base/macros.h" #include "base/observer_list.h" #include "base/time/time.h" -#include "chrome/browser/resource_coordinator/lifecycle_unit.h" +#include "chrome/browser/resource_coordinator/lifecycle_unit_base.h" #include "chrome/browser/resource_coordinator/tab_lifecycle_unit_external.h" #include "chrome/browser/resource_coordinator/tab_lifecycle_unit_source.h" +#include "chrome/browser/resource_coordinator/time.h" #include "content/public/browser/web_contents_observer.h" class TabStripModel; @@ -34,7 +35,7 @@ // Represents a tab. class TabLifecycleUnitSource::TabLifecycleUnit - : public LifecycleUnit, + : public LifecycleUnitBase, public TabLifecycleUnitExternal, public content::WebContentsObserver { public: @@ -69,10 +70,10 @@ void SetRecentlyAudible(bool recently_audible); // LifecycleUnit: + TabLifecycleUnitExternal* AsTabLifecycleUnitExternal() override; base::string16 GetTitle() const override; std::string GetIconURL() const override; SortKey GetSortKey() const override; - State GetState() const override; int GetEstimatedMemoryFreedOnDiscardKB() const override; bool CanDiscard(DiscardReason reason) const override; bool Discard(DiscardReason discard_reason) override; @@ -82,7 +83,7 @@ bool IsMediaTab() const override; bool IsAutoDiscardable() const override; void SetAutoDiscardable(bool auto_discardable) override; - void DiscardTab() override; + bool DiscardTab() override; bool IsDiscarded() const override; int GetDiscardCount() const override; @@ -103,15 +104,17 @@ // TabStripModel to which this tab belongs. TabStripModel* tab_strip_model_; - // Current state of this tab. - State state_ = State::LOADED; - // The number of times that this tab has been discarded. int discard_count_ = 0; // Last time at which this tab was focused, or TimeTicks::Max() if it is // currently focused. - base::TimeTicks last_focused_time_; + // + // TODO(fdoray): To keep old behavior (sort order and protection of recently + // focused tabs), this is initialized with NowTicks(). Consider initializing + // this with a null TimeTicks when the tab isn't initially focused. + // https://crbug.com/800885 + base::TimeTicks last_focused_time_ = NowTicks(); // When this is false, CanDiscard() always returns false. bool auto_discardable_ = true;
diff --git a/chrome/browser/resource_coordinator/tab_lifecycle_unit_external.h b/chrome/browser/resource_coordinator/tab_lifecycle_unit_external.h index ae1bc47..8b11fb7f 100644 --- a/chrome/browser/resource_coordinator/tab_lifecycle_unit_external.h +++ b/chrome/browser/resource_coordinator/tab_lifecycle_unit_external.h
@@ -36,7 +36,7 @@ virtual void SetAutoDiscardable(bool auto_discardable) = 0; // Discards the tab. - virtual void DiscardTab() = 0; + virtual bool DiscardTab() = 0; // Returns true if the tab is discarded. virtual bool IsDiscarded() const = 0;
diff --git a/chrome/browser/resource_coordinator/tab_lifecycle_unit_source_unittest.cc b/chrome/browser/resource_coordinator/tab_lifecycle_unit_source_unittest.cc index 3eec557..fbf9569 100644 --- a/chrome/browser/resource_coordinator/tab_lifecycle_unit_source_unittest.cc +++ b/chrome/browser/resource_coordinator/tab_lifecycle_unit_source_unittest.cc
@@ -70,10 +70,6 @@ base::TimeTicks::Max(); } -bool WasNeverFocused(LifecycleUnit* lifecycle_unit) { - return lifecycle_unit->GetSortKey().last_focused_time.is_null(); -} - class TabLifecycleUnitSourceTest : public ChromeRenderViewHostTestHarness { protected: TabLifecycleUnitSourceTest() @@ -111,14 +107,17 @@ // Add a foreground tab to the tab strip. test_clock_.Advance(kShortDelay); + auto time_before_first_tab = test_clock_.NowTicks(); EXPECT_CALL(source_observer_, OnLifecycleUnitCreated(testing::_)) .WillOnce(testing::Invoke([&](LifecycleUnit* lifecycle_unit) { *first_lifecycle_unit = lifecycle_unit; - if (focus_tab_strip) + if (focus_tab_strip) { EXPECT_TRUE(IsFocused(*first_lifecycle_unit)); - else - EXPECT_TRUE(WasNeverFocused(*first_lifecycle_unit)); + } else { + EXPECT_EQ(time_before_first_tab, + (*first_lifecycle_unit)->GetSortKey().last_focused_time); + } })); content::WebContents* first_web_contents = CreateAndNavigateWebContents(); tab_strip_model_->AppendWebContents(first_web_contents, true); @@ -137,8 +136,10 @@ (*first_lifecycle_unit)->GetSortKey().last_focused_time); EXPECT_TRUE(IsFocused(*second_lifecycle_unit)); } else { - EXPECT_TRUE(WasNeverFocused(*first_lifecycle_unit)); - EXPECT_TRUE(WasNeverFocused(*second_lifecycle_unit)); + EXPECT_EQ(time_before_first_tab, + (*first_lifecycle_unit)->GetSortKey().last_focused_time); + EXPECT_EQ(time_before_second_tab, + (*second_lifecycle_unit)->GetSortKey().last_focused_time); } })); content::WebContents* second_web_contents = CreateAndNavigateWebContents(); @@ -158,6 +159,8 @@ const base::TimeTicks first_tab_last_focused_time = first_lifecycle_unit->GetSortKey().last_focused_time; + const base::TimeTicks second_tab_last_focused_time = + second_lifecycle_unit->GetSortKey().last_focused_time; // Add a background tab to the focused tab strip. test_clock_.Advance(kShortDelay); @@ -171,10 +174,13 @@ first_lifecycle_unit->GetSortKey().last_focused_time); EXPECT_TRUE(IsFocused(second_lifecycle_unit)); } else { - EXPECT_TRUE(WasNeverFocused(first_lifecycle_unit)); - EXPECT_TRUE(WasNeverFocused(second_lifecycle_unit)); + EXPECT_EQ(first_tab_last_focused_time, + first_lifecycle_unit->GetSortKey().last_focused_time); + EXPECT_EQ(second_tab_last_focused_time, + second_lifecycle_unit->GetSortKey().last_focused_time); } - EXPECT_TRUE(WasNeverFocused(third_lifecycle_unit)); + EXPECT_EQ(NowTicks(), + third_lifecycle_unit->GetSortKey().last_focused_time); })); content::WebContents* third_web_contents = CreateAndNavigateWebContents(); tab_strip_model_->AppendWebContents(third_web_contents, false); @@ -295,6 +301,36 @@ // collaboration from the TabLifecycleUnitSource is required to replace the // WebContents in the TabLifecycleUnit. +TEST_F(TabLifecycleUnitSourceTest, Discard) { + const base::TimeTicks kDummyLastActiveTime = base::TimeTicks() + kShortDelay; + + LifecycleUnit* background_lifecycle_unit = nullptr; + LifecycleUnit* foreground_lifecycle_unit = nullptr; + CreateTwoTabs(true /* focus_tab_strip */, &background_lifecycle_unit, + &foreground_lifecycle_unit); + content::WebContents* initial_web_contents = + tab_strip_model_->GetWebContentsAt(0); + initial_web_contents->SetLastActiveTime(kDummyLastActiveTime); + + // Discard the tab. + EXPECT_EQ(LifecycleUnit::State::LOADED, + background_lifecycle_unit->GetState()); + EXPECT_CALL(tab_observer_, OnDiscardedStateChange(testing::_, true)); + background_lifecycle_unit->Discard(DiscardReason::kProactive); + testing::Mock::VerifyAndClear(&tab_observer_); + + // Expect the tab to be discarded and the last active time to be preserved. + EXPECT_EQ(LifecycleUnit::State::DISCARDED, + background_lifecycle_unit->GetState()); + EXPECT_NE(initial_web_contents, tab_strip_model_->GetWebContentsAt(0)); + EXPECT_FALSE( + tab_strip_model_->GetWebContentsAt(0)->GetController().GetPendingEntry()); + EXPECT_EQ(kDummyLastActiveTime, + tab_strip_model_->GetWebContentsAt(0)->GetLastActiveTime()); + + source_.SetFocusedTabStripModelForTesting(nullptr); +} + TEST_F(TabLifecycleUnitSourceTest, DiscardAndActivate) { LifecycleUnit* background_lifecycle_unit = nullptr; LifecycleUnit* foreground_lifecycle_unit = nullptr;
diff --git a/chrome/browser/resource_coordinator/tab_lifecycle_unit_unittest.cc b/chrome/browser/resource_coordinator/tab_lifecycle_unit_unittest.cc index 5d2d574..3512ad2 100644 --- a/chrome/browser/resource_coordinator/tab_lifecycle_unit_unittest.cc +++ b/chrome/browser/resource_coordinator/tab_lifecycle_unit_unittest.cc
@@ -89,10 +89,17 @@ DISALLOW_COPY_AND_ASSIGN(TabLifecycleUnitTest); }; +TEST_F(TabLifecycleUnitTest, AsTabLifecycleUnitExternal) { + TabLifecycleUnit tab_lifecycle_unit(&observers_, web_contents_.get(), + tab_strip_model_.get()); + EXPECT_EQ(&tab_lifecycle_unit, + tab_lifecycle_unit.AsTabLifecycleUnitExternal()); +} + TEST_F(TabLifecycleUnitTest, CanDiscardByDefault) { TabLifecycleUnit tab_lifecycle_unit(&observers_, web_contents_.get(), tab_strip_model_.get()); - test_clock_.Advance(kShortDelay); + test_clock_.Advance(kTabFocusedProtectionTime); EXPECT_TRUE(tab_lifecycle_unit.CanDiscard(DiscardReason::kExternal)); EXPECT_TRUE(tab_lifecycle_unit.CanDiscard(DiscardReason::kProactive)); @@ -100,16 +107,18 @@ } TEST_F(TabLifecycleUnitTest, SetFocused) { - test_clock_.Advance(kShortDelay); TabLifecycleUnit tab_lifecycle_unit(&observers_, web_contents_.get(), tab_strip_model_.get()); - EXPECT_EQ(base::TimeTicks(), - tab_lifecycle_unit.GetSortKey().last_focused_time); - EXPECT_TRUE(tab_lifecycle_unit.CanDiscard(DiscardReason::kExternal)); - EXPECT_TRUE(tab_lifecycle_unit.CanDiscard(DiscardReason::kProactive)); + EXPECT_EQ(NowTicks(), tab_lifecycle_unit.GetSortKey().last_focused_time); + EXPECT_FALSE(tab_lifecycle_unit.CanDiscard(DiscardReason::kExternal)); + EXPECT_FALSE(tab_lifecycle_unit.CanDiscard(DiscardReason::kProactive)); +#if defined(OS_CHROMEOS) EXPECT_TRUE(tab_lifecycle_unit.CanDiscard(DiscardReason::kUrgent)); +#else + EXPECT_FALSE(tab_lifecycle_unit.CanDiscard(DiscardReason::kUrgent)); +#endif - test_clock_.Advance(kShortDelay); + test_clock_.Advance(kTabFocusedProtectionTime); tab_lifecycle_unit.SetFocused(true); tab_strip_model_->ActivateTabAt(0, false); web_contents_->WasShown(); @@ -119,7 +128,7 @@ EXPECT_FALSE(tab_lifecycle_unit.CanDiscard(DiscardReason::kProactive)); EXPECT_FALSE(tab_lifecycle_unit.CanDiscard(DiscardReason::kUrgent)); - test_clock_.Advance(kShortDelay); + test_clock_.Advance(kTabFocusedProtectionTime); tab_lifecycle_unit.SetFocused(false); tab_strip_model_->ActivateTabAt(1, false); web_contents_->WasHidden(); @@ -142,6 +151,8 @@ TEST_F(TabLifecycleUnitTest, AutoDiscardable) { TabLifecycleUnit tab_lifecycle_unit(&observers_, web_contents_.get(), tab_strip_model_.get()); + test_clock_.Advance(kTabFocusedProtectionTime); + EXPECT_TRUE(tab_lifecycle_unit.IsAutoDiscardable()); EXPECT_TRUE(tab_lifecycle_unit.CanDiscard(DiscardReason::kExternal)); EXPECT_TRUE(tab_lifecycle_unit.CanDiscard(DiscardReason::kProactive)); @@ -169,6 +180,7 @@ TEST_F(TabLifecycleUnitTest, CannotDiscardCrashed) { TabLifecycleUnit tab_lifecycle_unit(&observers_, web_contents_.get(), tab_strip_model_.get()); + test_clock_.Advance(kTabFocusedProtectionTime); web_contents_->SetIsCrashed(base::TERMINATION_STATUS_PROCESS_CRASHED, 0); EXPECT_FALSE(tab_lifecycle_unit.CanDiscard(DiscardReason::kExternal)); @@ -180,8 +192,9 @@ TEST_F(TabLifecycleUnitTest, CannotDiscardActive) { TabLifecycleUnit tab_lifecycle_unit(&observers_, web_contents_.get(), tab_strip_model_.get()); - tab_strip_model_->ActivateTabAt(0, false); + test_clock_.Advance(kTabFocusedProtectionTime); + tab_strip_model_->ActivateTabAt(0, false); EXPECT_FALSE(tab_lifecycle_unit.CanDiscard(DiscardReason::kExternal)); EXPECT_FALSE(tab_lifecycle_unit.CanDiscard(DiscardReason::kProactive)); EXPECT_FALSE(tab_lifecycle_unit.CanDiscard(DiscardReason::kUrgent)); @@ -191,6 +204,7 @@ TEST_F(TabLifecycleUnitTest, CannotDiscardInvalidURL) { TabLifecycleUnit tab_lifecycle_unit(&observers_, web_contents_.get(), tab_strip_model_.get()); + test_clock_.Advance(kTabFocusedProtectionTime); web_contents_->SetLastCommittedURL(GURL("invalid :)")); EXPECT_FALSE(tab_lifecycle_unit.CanDiscard(DiscardReason::kExternal)); @@ -201,8 +215,9 @@ TEST_F(TabLifecycleUnitTest, CannotDiscardEmptyURL) { TabLifecycleUnit tab_lifecycle_unit(&observers_, web_contents_.get(), tab_strip_model_.get()); - web_contents_->SetLastCommittedURL(GURL()); + test_clock_.Advance(kTabFocusedProtectionTime); + web_contents_->SetLastCommittedURL(GURL()); EXPECT_FALSE(tab_lifecycle_unit.CanDiscard(DiscardReason::kExternal)); EXPECT_FALSE(tab_lifecycle_unit.CanDiscard(DiscardReason::kProactive)); EXPECT_FALSE(tab_lifecycle_unit.CanDiscard(DiscardReason::kUrgent)); @@ -211,6 +226,7 @@ TEST_F(TabLifecycleUnitTest, CannotDiscardVideoCapture) { TabLifecycleUnit tab_lifecycle_unit(&observers_, web_contents_.get(), tab_strip_model_.get()); + test_clock_.Advance(kTabFocusedProtectionTime); content::MediaStreamDevices video_devices(1); video_devices[0] = @@ -238,7 +254,7 @@ TEST_F(TabLifecycleUnitTest, CannotDiscardRecentlyAudible) { TabLifecycleUnit tab_lifecycle_unit(&observers_, web_contents_.get(), tab_strip_model_.get()); - test_clock_.Advance(kShortDelay); + test_clock_.Advance(kTabFocusedProtectionTime); // Cannot discard when the "recently audible" bit is set. tab_lifecycle_unit.SetRecentlyAudible(true); @@ -275,11 +291,24 @@ EXPECT_TRUE(tab_lifecycle_unit.CanDiscard(DiscardReason::kUrgent)); } +TEST_F(TabLifecycleUnitTest, CanDiscardNeverAudibleTab) { + TabLifecycleUnit tab_lifecycle_unit(&observers_, web_contents_.get(), + tab_strip_model_.get()); + test_clock_.Advance(kTabFocusedProtectionTime); + tab_lifecycle_unit.SetRecentlyAudible(false); + // Since the tab was never audible, it should be possible to discard it, + // even if there was a recent call to SetRecentlyAudible(false). + EXPECT_TRUE(tab_lifecycle_unit.CanDiscard(DiscardReason::kExternal)); + EXPECT_TRUE(tab_lifecycle_unit.CanDiscard(DiscardReason::kProactive)); + EXPECT_TRUE(tab_lifecycle_unit.CanDiscard(DiscardReason::kUrgent)); +} + TEST_F(TabLifecycleUnitTest, CannotDiscardPDF) { TabLifecycleUnit tab_lifecycle_unit(&observers_, web_contents_.get(), tab_strip_model_.get()); - web_contents_->SetMainFrameMimeType("application/pdf"); + test_clock_.Advance(kTabFocusedProtectionTime); + web_contents_->SetMainFrameMimeType("application/pdf"); EXPECT_FALSE(tab_lifecycle_unit.CanDiscard(DiscardReason::kExternal)); EXPECT_FALSE(tab_lifecycle_unit.CanDiscard(DiscardReason::kProactive)); EXPECT_FALSE(tab_lifecycle_unit.CanDiscard(DiscardReason::kUrgent));
diff --git a/chrome/browser/resources/print_preview/new/pages_settings.js b/chrome/browser/resources/print_preview/new/pages_settings.js index 49dbb41b..239dc5c 100644 --- a/chrome/browser/resources/print_preview/new/pages_settings.js +++ b/chrome/browser/resources/print_preview/new/pages_settings.js
@@ -51,6 +51,12 @@ 'inputString_, allSelected_, allPagesArray_)', }, + /** @private {!Array<{to: number, from: number}>} */ + rangesToPrint_: { + type: Array, + computed: 'computeRangesToPrint_(pagesToPrint_, allPagesArray_)', + }, + /** @private {!PagesInputErrorState} */ errorState_: { type: Number, @@ -60,7 +66,7 @@ }, observers: [ - 'onRangeChange_(errorState_, pagesToPrint_)', + 'onRangeChange_(errorState_, rangesToPrint_)', 'onRadioChange_(allSelected_, customSelected_)' ], @@ -129,6 +135,33 @@ }, /** + * Updates ranges to print. + * @return {!Array<{to: number, from: number}>} + * @private + */ + computeRangesToPrint_: function() { + let lastPage = 0; + if (this.pagesToPrint_.length == 0 || this.pagesToPrint_[0] == -1 || + this.pagesToPrint_ == this.allPagesArray_) + return []; + + let from = this.pagesToPrint_[0]; + let to = this.pagesToPrint_[0]; + let ranges = []; + for (let page of this.pagesToPrint_.slice(1)) { + if (page == to + 1) { + to = page; + continue; + } + ranges.push({from: from, to: to}); + from = page; + to = page; + } + ranges.push({from: from, to: to}); + return ranges; + }, + + /** * @return {!PagesInputErrorState} * @private */ @@ -155,7 +188,7 @@ } this.$$('.user-value').classList.remove('invalid'); this.setSettingValid('pages', true); - this.setSetting('pages', this.pagesToPrint_); + this.setSetting('pages', this.rangesToPrint_); }, /** @private */
diff --git a/chrome/browser/resources/settings/site_settings/site_settings_behavior.js b/chrome/browser/resources/settings/site_settings/site_settings_behavior.js index 1237c997..5d43d65 100644 --- a/chrome/browser/resources/settings/site_settings/site_settings_behavior.js +++ b/chrome/browser/resources/settings/site_settings/site_settings_behavior.js
@@ -101,6 +101,7 @@ * @private */ computeSiteIcon: function(site) { + site = this.removePatternWildcard(site); const url = this.ensureUrlHasScheme(site); return 'background-image: ' + cr.icon.getFavicon(url); },
diff --git a/chrome/browser/resources/vr/assets/PRESUBMIT.py b/chrome/browser/resources/vr/assets/PRESUBMIT.py new file mode 100644 index 0000000..9e68093 --- /dev/null +++ b/chrome/browser/resources/vr/assets/PRESUBMIT.py
@@ -0,0 +1,83 @@ +# 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 collections + + +def ParseVersion(lines): + version_keys = ['MAJOR', 'MINOR'] + version_vals = {} + for line in lines: + key, val = line.strip().split('=', 1) + if key in version_keys: + if key in version_vals or not val.isdigit(): + return None + version_vals[key] = int(val) + + if set(version_keys) != set(version_vals): + # We didn't see all parts of the version. + return None + + return collections.namedtuple('Version', ['major', 'minor'])( + major=version_vals['MAJOR'], minor=version_vals['MINOR']) + + +def IsNewer(old_version, new_version): + return (old_version and new_version and + (old_version.major < new_version.major or + (old_version.major == new_version.major and + old_version.minor < new_version.minor))) + + +def CheckVersion(input_api, output_api): + """Checks that + - the version was upraded if assets files were changed, + - the version was not downgraded. + """ + old_version = None + new_version = None + changed_assets = False + changed_version = False + for file in input_api.AffectedFiles(): + basename = input_api.os_path.basename(file.LocalPath()) + extension = input_api.os_path.splitext(basename)[1][1:].strip().lower() + if (extension == 'sha1'): + changed_assets = True + if (basename == 'VERSION'): + changed_version = True + old_version = ParseVersion(file.OldContents()) + new_version = ParseVersion(file.NewContents()) + + local_version_filename = input_api.os_path.join( + input_api.os_path.dirname(input_api.AffectedFiles()[0].LocalPath()), + 'VERSION') + + if changed_version and (not old_version or not new_version): + return [ + output_api.PresubmitError( + 'Cannot parse version in \'%s\'.' % local_version_filename) + ] + + version_upgraded = IsNewer(old_version, new_version) + if changed_assets and not version_upgraded: + return [ + output_api.PresubmitError( + 'Must increment version in \'%s\' when ' + 'updating VR assets.' % local_version_filename) + ] + if changed_version and not version_upgraded: + return [ + output_api.PresubmitError( + 'Must not downgrade version in \'%s\'.' % local_version_filename) + ] + + return [] + + +def CheckChangeOnUpload(input_api, output_api): + return CheckVersion(input_api, output_api) + + +def CheckChangeOnCommit(input_api, output_api): + return CheckVersion(input_api, output_api)
diff --git a/chrome/browser/spellchecker/spell_check_host_impl.cc b/chrome/browser/spellchecker/spell_check_host_impl.cc index d42bc43..0e59a20 100644 --- a/chrome/browser/spellchecker/spell_check_host_impl.cc +++ b/chrome/browser/spellchecker/spell_check_host_impl.cc
@@ -82,8 +82,8 @@ renderer_identity_.user_id()); client_.RequestTextCheck( context, SpellingServiceClient::SPELLCHECK, text, - base::Bind(&SpellCheckHostImpl::CallSpellingServiceDone, - base::Unretained(this), base::Passed(&callback))); + base::BindOnce(&SpellCheckHostImpl::CallSpellingServiceDone, + base::Unretained(this), base::Passed(&callback))); #else std::move(callback).Run(false, std::vector<SpellCheckResult>()); #endif
diff --git a/chrome/browser/spellchecker/spellcheck_custom_dictionary.cc b/chrome/browser/spellchecker/spellcheck_custom_dictionary.cc index b43268f..24a9f621 100644 --- a/chrome/browser/spellchecker/spellcheck_custom_dictionary.cc +++ b/chrome/browser/spellchecker/spellcheck_custom_dictionary.cc
@@ -282,10 +282,10 @@ DCHECK_CURRENTLY_ON(BrowserThread::UI); base::PostTaskAndReplyWithResult( task_runner_.get(), FROM_HERE, - base::Bind(&SpellcheckCustomDictionary::LoadDictionaryFile, - custom_dictionary_path_), - base::Bind(&SpellcheckCustomDictionary::OnLoaded, - weak_ptr_factory_.GetWeakPtr())); + base::BindOnce(&SpellcheckCustomDictionary::LoadDictionaryFile, + custom_dictionary_path_), + base::BindOnce(&SpellcheckCustomDictionary::OnLoaded, + weak_ptr_factory_.GetWeakPtr())); } syncer::SyncMergeResult SpellcheckCustomDictionary::MergeDataAndStartSyncing( @@ -434,8 +434,8 @@ if (!result->is_valid_file) { // Save cleaned up data only after startup. fix_invalid_file_.Reset( - base::Bind(&SpellcheckCustomDictionary::FixInvalidFile, - weak_ptr_factory_.GetWeakPtr(), base::Passed(&result))); + base::BindOnce(&SpellcheckCustomDictionary::FixInvalidFile, + weak_ptr_factory_.GetWeakPtr(), base::Passed(&result))); BrowserThread::PostAfterStartupTask( FROM_HERE, BrowserThread::GetTaskRunnerForThread(BrowserThread::UI), fix_invalid_file_.callback());
diff --git a/chrome/browser/spellchecker/spellcheck_custom_dictionary.h b/chrome/browser/spellchecker/spellcheck_custom_dictionary.h index 8cfac20e..e5cb273e 100644 --- a/chrome/browser/spellchecker/spellcheck_custom_dictionary.h +++ b/chrome/browser/spellchecker/spellcheck_custom_dictionary.h
@@ -220,7 +220,7 @@ bool is_loaded_; // A post-startup task to fix the invalid custom dictionary file. - base::CancelableClosure fix_invalid_file_; + base::CancelableOnceClosure fix_invalid_file_; // Used to create weak pointers for an instance of this class. base::WeakPtrFactory<SpellcheckCustomDictionary> weak_ptr_factory_;
diff --git a/chrome/browser/spellchecker/spellcheck_hunspell_dictionary.cc b/chrome/browser/spellchecker/spellcheck_hunspell_dictionary.cc index 6a09cf8..3a10b00 100644 --- a/chrome/browser/spellchecker/spellcheck_hunspell_dictionary.cc +++ b/chrome/browser/spellchecker/spellcheck_hunspell_dictionary.cc
@@ -128,7 +128,7 @@ spellcheck_platform::SetLanguage(language_); base::ThreadTaskRunnerHandle::Get()->PostTask( FROM_HERE, - base::Bind( + base::BindOnce( &SpellcheckHunspellDictionary::InformListenersOfInitialization, weak_ptr_factory_.GetWeakPtr())); return; @@ -140,8 +140,8 @@ #if !defined(OS_ANDROID) base::PostTaskAndReplyWithResult( task_runner_.get(), FROM_HERE, - base::Bind(&InitializeDictionaryLocation, language_), - base::Bind( + base::BindOnce(&InitializeDictionaryLocation, language_), + base::BindOnce( &SpellcheckHunspellDictionary::InitializeDictionaryLocationComplete, weak_ptr_factory_.GetWeakPtr())); #endif // !OS_ANDROID @@ -227,10 +227,10 @@ base::PostTaskAndReplyWithResult( task_runner_.get(), FROM_HERE, - base::Bind(&SaveDictionaryData, base::Passed(&data), - dictionary_file_.path), - base::Bind(&SpellcheckHunspellDictionary::SaveDictionaryDataComplete, - weak_ptr_factory_.GetWeakPtr())); + base::BindOnce(&SaveDictionaryData, base::Passed(&data), + dictionary_file_.path), + base::BindOnce(&SpellcheckHunspellDictionary::SaveDictionaryDataComplete, + weak_ptr_factory_.GetWeakPtr())); } GURL SpellcheckHunspellDictionary::GetDictionaryURL() {
diff --git a/chrome/browser/spellchecker/spellcheck_message_filter_platform_mac.cc b/chrome/browser/spellchecker/spellcheck_message_filter_platform_mac.cc index 27614554..d90b852d 100644 --- a/chrome/browser/spellchecker/spellcheck_message_filter_platform_mac.cc +++ b/chrome/browser/spellchecker/spellcheck_message_filter_platform_mac.cc
@@ -63,7 +63,7 @@ std::vector<SpellCheckResult> remote_results_; // Barrier closure for completion of both remote and local check. - base::Closure completion_barrier_; + base::RepeatingClosure completion_barrier_; bool remote_success_; SpellingServiceClient* client_; // Owned by |destination|. @@ -104,9 +104,8 @@ // Send the remote query out. The barrier owns |this|, ensuring it is deleted // after completion. completion_barrier_ = - BarrierClosure(2, - base::Bind(&SpellingRequest::OnCheckCompleted, - base::Owned(this))); + BarrierClosure(2, base::BindRepeating(&SpellingRequest::OnCheckCompleted, + base::Owned(this))); RequestRemoteCheck(); RequestLocalCheck(); } @@ -119,19 +118,16 @@ context = host->GetBrowserContext(); client_->RequestTextCheck( - context, - SpellingServiceClient::SPELLCHECK, - text_, - base::Bind(&SpellingRequest::OnRemoteCheckCompleted, - base::Unretained(this))); + context, SpellingServiceClient::SPELLCHECK, text_, + base::BindOnce(&SpellingRequest::OnRemoteCheckCompleted, + base::Unretained(this))); } void SpellingRequest::RequestLocalCheck() { spellcheck_platform::RequestTextCheck( - document_tag_, - text_, - base::Bind(&SpellingRequest::OnLocalCheckCompleted, - base::Unretained(this))); + document_tag_, text_, + base::BindOnce(&SpellingRequest::OnLocalCheckCompleted, + base::Unretained(this))); } void SpellingRequest::OnCheckCompleted() {
diff --git a/chrome/browser/spellchecker/spellcheck_message_filter_platform_mac_browsertest.cc b/chrome/browser/spellchecker/spellcheck_message_filter_platform_mac_browsertest.cc index 3f9ddae..6db6c068 100644 --- a/chrome/browser/spellchecker/spellcheck_message_filter_platform_mac_browsertest.cc +++ b/chrome/browser/spellchecker/spellcheck_message_filter_platform_mac_browsertest.cc
@@ -24,19 +24,20 @@ // allows verification by the test case. class TestingSpellCheckMessageFilter : public SpellCheckMessageFilterPlatform { public: - explicit TestingSpellCheckMessageFilter(const base::Closure& quit_closure) - : SpellCheckMessageFilterPlatform(0), quit_closure_(quit_closure) {} + explicit TestingSpellCheckMessageFilter(base::OnceClosure&& quit_closure) + : SpellCheckMessageFilterPlatform(0), + quit_closure_(std::move(quit_closure)) {} bool Send(IPC::Message* message) override { sent_messages_.push_back(base::WrapUnique(message)); - main_thread_task_runner_->PostTask(FROM_HERE, quit_closure_); + main_thread_task_runner_->PostTask(FROM_HERE, std::move(quit_closure_)); return true; } std::vector<std::unique_ptr<IPC::Message>> sent_messages_; const scoped_refptr<base::SingleThreadTaskRunner> main_thread_task_runner_ = base::ThreadTaskRunnerHandle::Get(); - const base::Closure quit_closure_; + base::OnceClosure quit_closure_; private: ~TestingSpellCheckMessageFilter() override {}
diff --git a/chrome/browser/spellchecker/spellcheck_service_browsertest.cc b/chrome/browser/spellchecker/spellcheck_service_browsertest.cc index 48f7c91..6aca4e68 100644 --- a/chrome/browser/spellchecker/spellcheck_service_browsertest.cc +++ b/chrome/browser/spellchecker/spellcheck_service_browsertest.cc
@@ -82,8 +82,8 @@ // interface so we can test the SpellChecker request flow. renderer_->OverrideBinderForTesting( spellcheck::mojom::SpellChecker::Name_, - base::Bind(&SpellcheckServiceBrowserTest::Bind, - base::Unretained(this))); + base::BindRepeating(&SpellcheckServiceBrowserTest::Bind, + base::Unretained(this))); } void EnableSpellcheck(bool enable_spellcheck) {
diff --git a/chrome/browser/spellchecker/spelling_service_client_unittest.cc b/chrome/browser/spellchecker/spelling_service_client_unittest.cc index db94d67..dab82e2 100644 --- a/chrome/browser/spellchecker/spelling_service_client_unittest.cc +++ b/chrome/browser/spellchecker/spelling_service_client_unittest.cc
@@ -348,11 +348,10 @@ pref->Set(spellcheck::prefs::kSpellCheckDictionaries, dictionary); client_.RequestTextCheck( - &profile_, - kTests[i].request_type, + &profile_, kTests[i].request_type, base::WideToUTF16(kTests[i].request_text), - base::Bind(&SpellingServiceClientTest::OnTextCheckComplete, - base::Unretained(this), 0)); + base::BindOnce(&SpellingServiceClientTest::OnTextCheckComplete, + base::Unretained(this), 0)); client_.CallOnURLFetchComplete(); } }
diff --git a/chrome/browser/themes/theme_service.cc b/chrome/browser/themes/theme_service.cc index ca302dd..2a666c5c 100644 --- a/chrome/browser/themes/theme_service.cc +++ b/chrome/browser/themes/theme_service.cc
@@ -703,6 +703,13 @@ SkColor ThemeService::GetColor(int id, bool incognito) const { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); + // The incognito NTP always uses the default background color, unless there is + // a custom NTP background image. See also https://crbug.com/21798#c114. + if (id == ThemeProperties::COLOR_NTP_BACKGROUND && incognito && + !HasCustomImage(IDR_THEME_NTP_BACKGROUND)) { + return ThemeProperties::GetDefaultColor(id, incognito); + } + // For legacy reasons, |theme_supplier_| requires the incognito variants // of color IDs. int theme_supplier_id = id;
diff --git a/chrome/browser/ui/app_list/search/common/url_icon_source.cc b/chrome/browser/ui/app_list/search/common/url_icon_source.cc index 5e240b8..76dfe07 100644 --- a/chrome/browser/ui/app_list/search/common/url_icon_source.cc +++ b/chrome/browser/ui/app_list/search/common/url_icon_source.cc
@@ -7,10 +7,14 @@ #include <string> #include <utility> +#include "content/public/browser/browser_context.h" #include "content/public/browser/browser_thread.h" +#include "content/public/browser/storage_partition.h" +#include "content/public/common/resource_request.h" +#include "content/public/common/simple_url_loader.h" +#include "content/public/common/url_loader_factory.mojom.h" #include "net/base/load_flags.h" -#include "net/url_request/url_fetcher.h" -#include "net/url_request/url_request_status.h" +#include "net/traffic_annotation/network_traffic_annotation.h" #include "ui/base/resource/resource_bundle.h" #include "ui/gfx/image/image_skia_operations.h" @@ -19,12 +23,12 @@ namespace app_list { UrlIconSource::UrlIconSource(const IconLoadedCallback& icon_loaded_callback, - net::URLRequestContextGetter* context_getter, + content::BrowserContext* browser_context, const GURL& icon_url, int icon_size, int default_icon_resource_id) : icon_loaded_callback_(icon_loaded_callback), - context_getter_(context_getter), + browser_context_(browser_context), icon_url_(icon_url), icon_size_(icon_size), default_icon_resource_id_(default_icon_resource_id), @@ -38,11 +42,37 @@ void UrlIconSource::StartIconFetch() { icon_fetch_attempted_ = true; - icon_fetcher_ = - net::URLFetcher::Create(icon_url_, net::URLFetcher::GET, this); - icon_fetcher_->SetRequestContext(context_getter_); - icon_fetcher_->SetLoadFlags(net::LOAD_DO_NOT_SAVE_COOKIES); - icon_fetcher_->Start(); + auto resource_request = std::make_unique<content::ResourceRequest>(); + resource_request->url = icon_url_; + resource_request->load_flags = net::LOAD_DO_NOT_SAVE_COOKIES; + net::NetworkTrafficAnnotationTag traffic_annotation = + net::DefineNetworkTrafficAnnotation("url_icon_source_fetch", R"( + semantics { + sender: "URL Icon Source" + description: + "Chrome OS downloads an icon for a web store result." + trigger: + "When a user initiates a web store search and views results. " + data: + "URL of the icon. " + "No user information is sent." + destination: WEBSITE + } + policy { + cookies_allowed: YES + cookies_store: "user" + setting: "Unconditionally enabled on Chrome OS." + policy_exception_justification: + "Not implemented, considered not useful." + })"); + simple_loader_ = content::SimpleURLLoader::Create(std::move(resource_request), + traffic_annotation); + content::mojom::URLLoaderFactory* loader_factory = + content::BrowserContext::GetDefaultStoragePartition(browser_context_) + ->GetURLLoaderFactoryForBrowserProcess(); + simple_loader_->DownloadToStringOfUnboundedSizeUntilCrashAndDie( + loader_factory, base::BindOnce(&UrlIconSource::OnSimpleLoaderComplete, + base::Unretained(this))); } gfx::ImageSkiaRep UrlIconSource::GetImageForScale(float scale) { @@ -56,21 +86,15 @@ .GetImageSkiaNamed(default_icon_resource_id_)->GetRepresentation(scale); } -void UrlIconSource::OnURLFetchComplete( - const net::URLFetcher* source) { - CHECK_EQ(icon_fetcher_.get(), source); - - std::unique_ptr<net::URLFetcher> fetcher(std::move(icon_fetcher_)); - - if (!fetcher->GetStatus().is_success() || - fetcher->GetResponseCode() != 200) { +void UrlIconSource::OnSimpleLoaderComplete( + std::unique_ptr<std::string> response_body) { + if (!response_body) { return; } - std::string unsafe_icon_data; - fetcher->GetResponseAsString(&unsafe_icon_data); - - ImageDecoder::Start(this, unsafe_icon_data); + // Call start to begin decoding. The ImageDecoder will call OnImageDecoded + // with the data when it is done. + ImageDecoder::Start(this, *response_body); } void UrlIconSource::OnImageDecoded(const SkBitmap& decoded_image) {
diff --git a/chrome/browser/ui/app_list/search/common/url_icon_source.h b/chrome/browser/ui/app_list/search/common/url_icon_source.h index 4e640ef0..4f5c8d1b 100644 --- a/chrome/browser/ui/app_list/search/common/url_icon_source.h +++ b/chrome/browser/ui/app_list/search/common/url_icon_source.h
@@ -6,19 +6,19 @@ #define CHROME_BROWSER_UI_APP_LIST_SEARCH_COMMON_URL_ICON_SOURCE_H_ #include <memory> +#include <string> #include "base/callback.h" #include "base/macros.h" #include "base/memory/ref_counted.h" #include "chrome/browser/image_decoder.h" -#include "net/url_request/url_fetcher_delegate.h" #include "ui/gfx/image/image_skia.h" #include "ui/gfx/image/image_skia_source.h" #include "url/gurl.h" -namespace net { -class URLFetcher; -class URLRequestContextGetter; +namespace content { +class BrowserContext; +class SimpleURLLoader; } namespace app_list { @@ -26,7 +26,6 @@ // An ImageSkiaSource for icons fetched from a URL. Till the URL icon is // fetched, the default icon (specified by it's resource id) is shown. class UrlIconSource : public gfx::ImageSkiaSource, - public net::URLFetcherDelegate, public ImageDecoder::ImageRequest { public: typedef base::Closure IconLoadedCallback; @@ -34,7 +33,7 @@ // Create a URL Icon source with the given URL. The post_process parameter // specifies a function to post-process the result icon before displaying it. UrlIconSource(const IconLoadedCallback& icon_loaded_callback, - net::URLRequestContextGetter* context_getter, + content::BrowserContext* browser_context, const GURL& icon_url, int icon_size, int default_icon_resource_id); @@ -45,24 +44,24 @@ // ImageSkia gets painted on screen. void StartIconFetch(); + // Invoked from SimpleURLLoader after download is complete. + void OnSimpleLoaderComplete(std::unique_ptr<std::string> response_body); + // gfx::ImageSkiaSource overrides: gfx::ImageSkiaRep GetImageForScale(float scale) override; - // net::URLFetcherDelegate overrides: - void OnURLFetchComplete(const net::URLFetcher* source) override; - // ImageDecoder::ImageRequest overrides: void OnImageDecoded(const SkBitmap& decoded_image) override; void OnDecodeImageFailed() override; IconLoadedCallback icon_loaded_callback_; - net::URLRequestContextGetter* context_getter_; + content::BrowserContext* browser_context_; const GURL icon_url_; const int icon_size_; const int default_icon_resource_id_; bool icon_fetch_attempted_; - std::unique_ptr<net::URLFetcher> icon_fetcher_; + std::unique_ptr<content::SimpleURLLoader> simple_loader_; gfx::ImageSkia icon_;
diff --git a/chrome/browser/ui/app_list/search/webstore/webstore_result.cc b/chrome/browser/ui/app_list/search/webstore/webstore_result.cc index fbaeddf..ce841735 100644 --- a/chrome/browser/ui/app_list/search/webstore/webstore_result.cc +++ b/chrome/browser/ui/app_list/search/webstore/webstore_result.cc
@@ -24,6 +24,9 @@ #include "chrome/grit/chromium_strings.h" #include "chrome/grit/generated_resources.h" #include "chrome/grit/theme_resources.h" +#include "content/public/browser/storage_partition.h" +#include "content/public/browser/web_contents.h" +#include "content/public/common/url_loader_factory.mojom.h" #include "extensions/browser/extension_registry.h" #include "extensions/browser/extension_system.h" #include "extensions/common/extension_urls.h" @@ -60,8 +63,7 @@ icon_ = gfx::ImageSkia( base::MakeUnique<UrlIconSource>( base::Bind(&WebstoreResult::OnIconLoaded, weak_factory_.GetWeakPtr()), - profile_->GetRequestContext(), icon_url_, icon_dimension, - IDR_WEBSTORE_ICON_32), + profile_, icon_url_, icon_dimension, IDR_WEBSTORE_ICON_32), gfx::Size(icon_dimension, icon_dimension)); SetIcon(icon_); }
diff --git a/chrome/browser/ui/ash/chrome_browser_main_extra_parts_ash.cc b/chrome/browser/ui/ash/chrome_browser_main_extra_parts_ash.cc index ca9e7dc8..9f9eaf4e 100644 --- a/chrome/browser/ui/ash/chrome_browser_main_extra_parts_ash.cc +++ b/chrome/browser/ui/ash/chrome_browser_main_extra_parts_ash.cc
@@ -4,33 +4,46 @@ #include "chrome/browser/ui/ash/chrome_browser_main_extra_parts_ash.h" +#include "ash/public/cpp/ash_switches.h" #include "ash/public/cpp/mus_property_mirror_ash.h" +#include "ash/public/cpp/shelf_model.h" #include "ash/public/cpp/window_pin_type.h" #include "ash/public/cpp/window_properties.h" #include "ash/public/cpp/window_state_type.h" +#include "ash/public/interfaces/constants.mojom.h" +#include "ash/public/interfaces/process_creation_time_recorder.mojom.h" #include "ash/public/interfaces/window_pin_type.mojom.h" #include "ash/public/interfaces/window_properties.mojom.h" #include "ash/public/interfaces/window_state_type.mojom.h" #include "ash/shell.h" +#include "base/command_line.h" #include "base/memory/ptr_util.h" +#include "chrome/browser/browser_process.h" +#include "chrome/browser/chromeos/ash_config.h" +#include "chrome/browser/chromeos/night_light/night_light_client.h" #include "chrome/browser/ui/ash/accessibility/accessibility_controller_client.h" #include "chrome/browser/ui/ash/ash_shell_init.h" -#include "chrome/browser/ui/ash/ash_util.h" #include "chrome/browser/ui/ash/cast_config_client_media_router.h" #include "chrome/browser/ui/ash/chrome_new_window_client.h" #include "chrome/browser/ui/ash/chrome_shell_content_state.h" #include "chrome/browser/ui/ash/ime_controller_client.h" +#include "chrome/browser/ui/ash/launcher/chrome_launcher_controller.h" #include "chrome/browser/ui/ash/login_screen_client.h" #include "chrome/browser/ui/ash/media_client.h" #include "chrome/browser/ui/ash/session_controller_client.h" #include "chrome/browser/ui/ash/system_tray_client.h" #include "chrome/browser/ui/ash/tab_scrubber.h" +#include "chrome/browser/ui/ash/tablet_mode_client.h" #include "chrome/browser/ui/ash/volume_controller.h" #include "chrome/browser/ui/ash/vpn_list_forwarder.h" +#include "chrome/browser/ui/ash/wallpaper_controller_client.h" #include "chrome/browser/ui/views/frame/immersive_context_mus.h" #include "chrome/browser/ui/views/frame/immersive_handler_factory_mus.h" #include "chrome/browser/ui/views/select_file_dialog_extension.h" #include "chrome/browser/ui/views/select_file_dialog_extension_factory.h" +#include "components/session_manager/core/session_manager.h" +#include "components/session_manager/core/session_manager_observer.h" +#include "components/startup_metric_utils/browser/startup_metric_utils.h" #include "content/public/common/service_manager_connection.h" #include "services/service_manager/public/cpp/connector.h" #include "services/ui/public/interfaces/constants.mojom.h" @@ -45,13 +58,81 @@ #include "chrome/browser/exo_parts.h" #endif +namespace { + +void PushProcessCreationTimeToAsh() { + ash::mojom::ProcessCreationTimeRecorderPtr recorder; + content::ServiceManagerConnection::GetForProcess() + ->GetConnector() + ->BindInterface(ash::mojom::kServiceName, &recorder); + DCHECK(!startup_metric_utils::MainEntryPointTicks().is_null()); + recorder->SetMainProcessCreationTime( + startup_metric_utils::MainEntryPointTicks()); +} + +} // namespace + +namespace internal { + +// Creates a ChromeLauncherController on the first active session notification. +// Used to avoid constructing a ChromeLauncherController with no active profile. +class ChromeLauncherControllerInitializer + : public session_manager::SessionManagerObserver { + public: + ChromeLauncherControllerInitializer() { + session_manager::SessionManager::Get()->AddObserver(this); + } + + ~ChromeLauncherControllerInitializer() override { + if (!chrome_launcher_controller_) + session_manager::SessionManager::Get()->RemoveObserver(this); + } + + // session_manager::SessionManagerObserver: + void OnSessionStateChanged() override { + DCHECK(!chrome_launcher_controller_); + DCHECK(!ChromeLauncherController::instance()); + + if (session_manager::SessionManager::Get()->session_state() == + session_manager::SessionState::ACTIVE) { + ash::ShelfModel* model; + if (chromeos::GetAshConfig() == ash::Config::MASH || + !base::CommandLine::ForCurrentProcess()->HasSwitch( + ash::switches::kAshDisableShelfModelSynchronization)) { + // Synchronize shelf models. + chrome_shelf_model_ = std::make_unique<ash::ShelfModel>(); + model = chrome_shelf_model_.get(); + } else { + // Use Ash's shelf model directly. + model = ash::Shell::Get()->shelf_model(); + } + chrome_launcher_controller_ = + std::make_unique<ChromeLauncherController>(nullptr, model); + chrome_launcher_controller_->Init(); + + session_manager::SessionManager::Get()->RemoveObserver(this); + } + } + + private: + // By default |chrome_shelf_model_| is synced with Ash's ShelfController + // instance in Mash and in Classic Ash; otherwise this is not created and + // Ash's ShelfModel instance is used directly. + std::unique_ptr<ash::ShelfModel> chrome_shelf_model_; + std::unique_ptr<ChromeLauncherController> chrome_launcher_controller_; + + DISALLOW_COPY_AND_ASSIGN(ChromeLauncherControllerInitializer); +}; + +} // namespace internal + ChromeBrowserMainExtraPartsAsh::ChromeBrowserMainExtraPartsAsh() {} ChromeBrowserMainExtraPartsAsh::~ChromeBrowserMainExtraPartsAsh() {} void ChromeBrowserMainExtraPartsAsh::ServiceManagerConnectionStarted( content::ServiceManagerConnection* connection) { - if (ash_util::IsRunningInMash()) { + if (chromeos::GetAshConfig() == ash::Config::MASH) { // ash::Shell will not be created because ash is running out-of-process. ash::Shell::SetIsBrowserProcessWithMash(); @@ -92,66 +173,89 @@ ash::kShelfIDKey, ui::mojom::WindowManager::kShelfID_Property); mus_client->SetMusPropertyMirror( - base::MakeUnique<ash::MusPropertyMirrorAsh>()); + std::make_unique<ash::MusPropertyMirrorAsh>()); } } void ChromeBrowserMainExtraPartsAsh::PreProfileInit() { - if (ash_util::ShouldOpenAshOnStartup()) + if (chromeos::GetAshConfig() != ash::Config::MASH) { ash_shell_init_ = std::make_unique<AshShellInit>(); - - if (ash_util::IsRunningInMash()) { - immersive_context_ = base::MakeUnique<ImmersiveContextMus>(); - immersive_handler_factory_ = base::MakeUnique<ImmersiveHandlerFactoryMus>(); + } else { + immersive_context_ = std::make_unique<ImmersiveContextMus>(); + immersive_handler_factory_ = std::make_unique<ImmersiveHandlerFactoryMus>(); // Enterprise support in the browser can monitor user activity. Connect to // the UI service to monitor activity. The ash process has its own monitor. - user_activity_detector_ = base::MakeUnique<ui::UserActivityDetector>(); + user_activity_detector_ = std::make_unique<ui::UserActivityDetector>(); ui::mojom::UserActivityMonitorPtr user_activity_monitor; content::ServiceManagerConnection::GetForProcess() ->GetConnector() ->BindInterface(ui::mojom::kServiceName, &user_activity_monitor); - user_activity_forwarder_ = base::MakeUnique<aura::UserActivityForwarder>( + user_activity_forwarder_ = std::make_unique<aura::UserActivityForwarder>( std::move(user_activity_monitor), user_activity_detector_.get()); } - session_controller_client_ = base::MakeUnique<SessionControllerClient>(); - session_controller_client_->Init(); - // Must be available at login screen, so initialize before profile. accessibility_controller_client_ = std::make_unique<AccessibilityControllerClient>(); accessibility_controller_client_->Init(); - system_tray_client_ = base::MakeUnique<SystemTrayClient>(); - ime_controller_client_ = base::MakeUnique<ImeControllerClient>( + + chrome_new_window_client_ = std::make_unique<ChromeNewWindowClient>(); + + ime_controller_client_ = std::make_unique<ImeControllerClient>( chromeos::input_method::InputMethodManager::Get()); ime_controller_client_->Init(); - new_window_client_ = base::MakeUnique<ChromeNewWindowClient>(); - volume_controller_ = base::MakeUnique<VolumeController>(); - vpn_list_forwarder_ = base::MakeUnique<VpnListForwarder>(); + + session_controller_client_ = std::make_unique<SessionControllerClient>(); + session_controller_client_->Init(); + + system_tray_client_ = std::make_unique<SystemTrayClient>(); + + // Makes mojo request to TabletModeController in ash. + tablet_mode_client_ = std::make_unique<TabletModeClient>(); + tablet_mode_client_->Init(); + + volume_controller_ = std::make_unique<VolumeController>(); + + vpn_list_forwarder_ = std::make_unique<VpnListForwarder>(); + + wallpaper_controller_client_ = std::make_unique<WallpaperControllerClient>(); + wallpaper_controller_client_->Init(); + + chrome_launcher_controller_initializer_ = + std::make_unique<internal::ChromeLauncherControllerInitializer>(); ui::SelectFileDialog::SetFactory(new SelectFileDialogExtensionFactory); #if BUILDFLAG(ENABLE_WAYLAND_SERVER) exo_parts_ = ExoParts::CreateIfNecessary(); #endif + + PushProcessCreationTimeToAsh(); } void ChromeBrowserMainExtraPartsAsh::PostProfileInit() { - if (ash_util::IsRunningInMash()) - chrome_shell_content_state_ = base::MakeUnique<ChromeShellContentState>(); + if (chromeos::GetAshConfig() == ash::Config::MASH) + chrome_shell_content_state_ = std::make_unique<ChromeShellContentState>(); cast_config_client_media_router_ = - base::MakeUnique<CastConfigClientMediaRouter>(); - media_client_ = base::MakeUnique<MediaClient>(); - login_screen_client_ = base::MakeUnique<LoginScreenClient>(); + std::make_unique<CastConfigClientMediaRouter>(); + login_screen_client_ = std::make_unique<LoginScreenClient>(); + media_client_ = std::make_unique<MediaClient>(); // TODO(mash): Port TabScrubber. - if (ash_util::IsRunningInMash()) - return; + if (chromeos::GetAshConfig() != ash::Config::MASH) { + // Initialize TabScrubber after the Ash Shell has been initialized. + TabScrubber::GetInstance(); + } +} - // Initialize TabScrubber after the Ash Shell has been initialized. - TabScrubber::GetInstance(); +void ChromeBrowserMainExtraPartsAsh::PostBrowserStart() { + if (ash::switches::IsNightLightEnabled()) { + night_light_client_ = std::make_unique<NightLightClient>( + g_browser_process->system_request_context()); + night_light_client_->Start(); + } } void ChromeBrowserMainExtraPartsAsh::PostMainMessageLoopRun() { @@ -161,16 +265,26 @@ exo_parts_.reset(); #endif + night_light_client_.reset(); + + chrome_launcher_controller_initializer_.reset(); + + wallpaper_controller_client_.reset(); vpn_list_forwarder_.reset(); volume_controller_.reset(); - new_window_client_.reset(); - ime_controller_client_.reset(); + system_tray_client_.reset(); - accessibility_controller_client_.reset(); - login_screen_client_.reset(); - media_client_.reset(); - cast_config_client_media_router_.reset(); session_controller_client_.reset(); + chrome_new_window_client_.reset(); + media_client_.reset(); + login_screen_client_.reset(); + ime_controller_client_.reset(); + cast_config_client_media_router_.reset(); + accessibility_controller_client_.reset(); ash_shell_init_.reset(); + + // Views code observes TabletModeClient and may not be destroyed until + // ash::Shell is so destroy |tablet_mode_client_| after ash::Shell. + tablet_mode_client_.reset(); }
diff --git a/chrome/browser/ui/ash/chrome_browser_main_extra_parts_ash.h b/chrome/browser/ui/ash/chrome_browser_main_extra_parts_ash.h index fb95ccb..7971797 100644 --- a/chrome/browser/ui/ash/chrome_browser_main_extra_parts_ash.h +++ b/chrome/browser/ui/ash/chrome_browser_main_extra_parts_ash.h
@@ -24,22 +24,29 @@ class CastConfigClientMediaRouter; class ChromeNewWindowClient; class ChromeShellContentState; -class LoginScreenClient; class ImeControllerClient; class ImmersiveContextMus; class ImmersiveHandlerFactoryMus; +class LoginScreenClient; class MediaClient; +class NightLightClient; class SessionControllerClient; class SystemTrayClient; +class TabletModeClient; class VolumeController; class VpnListForwarder; +class WallpaperControllerClient; #if BUILDFLAG(ENABLE_WAYLAND_SERVER) class ExoParts; #endif -// Browser initialization for Ash UI. Only use this for initialization of -// chrome/browser/ui/ash classes. +namespace internal { +class ChromeLauncherControllerInitializer; +} + +// Browser initialization for Ash UI. Only use this for Ash specific +// intitialization (e.g. initialization of chrome/browser/ui/ash classes). class ChromeBrowserMainExtraPartsAsh : public ChromeBrowserMainExtraParts { public: ChromeBrowserMainExtraPartsAsh(); @@ -50,33 +57,49 @@ content::ServiceManagerConnection* connection) override; void PreProfileInit() override; void PostProfileInit() override; + void PostBrowserStart() override; void PostMainMessageLoopRun() override; private: + // Initialized in PreProfileInit if ash config != MASH: + std::unique_ptr<AshShellInit> ash_shell_init_; + + // Initialized in PreProfileInit if ash config == MASH: + std::unique_ptr<ImmersiveContextMus> immersive_context_; + std::unique_ptr<ImmersiveHandlerFactoryMus> immersive_handler_factory_; + std::unique_ptr<aura::UserActivityForwarder> user_activity_forwarder_; + std::unique_ptr<ui::UserActivityDetector> user_activity_detector_; + + // Initialized in PreProfileInit in all configs: std::unique_ptr<AccessibilityControllerClient> accessibility_controller_client_; - std::unique_ptr<ChromeShellContentState> chrome_shell_content_state_; - std::unique_ptr<CastConfigClientMediaRouter> cast_config_client_media_router_; - std::unique_ptr<MediaClient> media_client_; - std::unique_ptr<ImmersiveHandlerFactoryMus> immersive_handler_factory_; - std::unique_ptr<ImmersiveContextMus> immersive_context_; + std::unique_ptr<ChromeNewWindowClient> chrome_new_window_client_; + std::unique_ptr<ImeControllerClient> ime_controller_client_; std::unique_ptr<SessionControllerClient> session_controller_client_; std::unique_ptr<SystemTrayClient> system_tray_client_; - std::unique_ptr<ImeControllerClient> ime_controller_client_; - std::unique_ptr<ChromeNewWindowClient> new_window_client_; + std::unique_ptr<TabletModeClient> tablet_mode_client_; std::unique_ptr<VolumeController> volume_controller_; std::unique_ptr<VpnListForwarder> vpn_list_forwarder_; - std::unique_ptr<AshShellInit> ash_shell_init_; - std::unique_ptr<LoginScreenClient> login_screen_client_; + std::unique_ptr<WallpaperControllerClient> wallpaper_controller_client_; - // Used only for mash. - std::unique_ptr<ui::UserActivityDetector> user_activity_detector_; - std::unique_ptr<aura::UserActivityForwarder> user_activity_forwarder_; + std::unique_ptr<internal::ChromeLauncherControllerInitializer> + chrome_launcher_controller_initializer_; #if BUILDFLAG(ENABLE_WAYLAND_SERVER) std::unique_ptr<ExoParts> exo_parts_; #endif + // Initialized in PostProfileInit if ash config == MASH: + std::unique_ptr<ChromeShellContentState> chrome_shell_content_state_; + + // Initialized in PostProfileInit in all configs: + std::unique_ptr<CastConfigClientMediaRouter> cast_config_client_media_router_; + std::unique_ptr<LoginScreenClient> login_screen_client_; + std::unique_ptr<MediaClient> media_client_; + + // Initialized in PostBrowserStart in all configs: + std::unique_ptr<NightLightClient> night_light_client_; + DISALLOW_COPY_AND_ASSIGN(ChromeBrowserMainExtraPartsAsh); };
diff --git a/chrome/browser/ui/cocoa/passwords/passwords_bubble_controller_unittest.mm b/chrome/browser/ui/cocoa/passwords/passwords_bubble_controller_unittest.mm index 3cc24cd3d..26287f45c 100644 --- a/chrome/browser/ui/cocoa/passwords/passwords_bubble_controller_unittest.mm +++ b/chrome/browser/ui/cocoa/passwords/passwords_bubble_controller_unittest.mm
@@ -106,9 +106,6 @@ // https://crbug.com/774033 TEST_F(ManagePasswordsBubbleControllerTest, TransitionToSignInPromoAfterEditingPassword) { - base::test::ScopedFeatureList feature_list; - feature_list.InitAndEnableFeature( - password_manager::features::kEnablePasswordSelection); SetUpSavePendingState(); GetModelAndCreateIfNull()->allow_passwords_revealing(); [controller() showWindow:nil];
diff --git a/chrome/browser/ui/cocoa/passwords/save_pending_password_view_controller.mm b/chrome/browser/ui/cocoa/passwords/save_pending_password_view_controller.mm index 23f40f4..90073262 100644 --- a/chrome/browser/ui/cocoa/passwords/save_pending_password_view_controller.mm +++ b/chrome/browser/ui/cocoa/passwords/save_pending_password_view_controller.mm
@@ -185,10 +185,7 @@ [[NSView alloc] initWithFrame:NSZeroRect]); // Create the elements. - bool enableUsernameEditing = - base::FeatureList::IsEnabled( - password_manager::features::kEnableUsernameCorrection) && - self.model->enable_editing(); + bool enableUsernameEditing = self.model->enable_editing(); const autofill::PasswordForm& form = self.model->pending_password(); if (enableUsernameEditing) usernameField_.reset([EditableField(form.username_value) retain]); @@ -196,43 +193,36 @@ usernameField_.reset([Label(GetDisplayUsername(form)) retain]); [container addSubview:usernameField_]; - bool enablePasswordEditing = base::FeatureList::IsEnabled( - password_manager::features::kEnablePasswordSelection); if (form.federation_origin.unique()) { - if (enablePasswordEditing) { - if (form.all_possible_passwords.size() > 1) { - passwordSelectionField_.reset( - [[NSPopUpButton alloc] initWithFrame:NSZeroRect pullsDown:NO]); - FillPasswordPopup( - form, self.model->are_passwords_revealed_when_bubble_is_opened(), - passwordSelectionField_.get()); - [passwordSelectionField_ sizeToFit]; + if (form.all_possible_passwords.size() > 1) { + passwordSelectionField_.reset( + [[NSPopUpButton alloc] initWithFrame:NSZeroRect pullsDown:NO]); + FillPasswordPopup( + form, self.model->are_passwords_revealed_when_bubble_is_opened(), + passwordSelectionField_.get()); + [passwordSelectionField_ sizeToFit]; + } else { // Only one password. + if (self.model->are_passwords_revealed_when_bubble_is_opened()) { + passwordStaticField_.reset([Label(form.password_value) retain]); } else { - if (self.model->are_passwords_revealed_when_bubble_is_opened()) { - passwordStaticField_.reset([Label(form.password_value) retain]); - } else { - passwordStaticField_.reset([Label(base::string16( - form.password_value.length(), kBulletChar)) retain]); - } - // Overwrite the height of the password field because it's higher in the - // editable mode. - [passwordStaticField_ - setFrameSize:NSMakeSize( - NSWidth([passwordStaticField_ frame]), - std::max(NSHeight([passwordStaticField_ frame]), - NSHeight([EditableField( - form.password_value) frame])))]; + passwordStaticField_.reset([Label( + base::string16(form.password_value.length(), kBulletChar)) retain]); } - passwordViewButton_.reset( - [EyeIcon(self, @selector(onEyeClicked:)) retain]); - if (self.model->are_passwords_revealed_when_bubble_is_opened()) - [passwordViewButton_ setState:NSOnState]; - else - [passwordViewButton_ setState:NSOffState]; - [container addSubview:passwordViewButton_]; - } else { - passwordStaticField_.reset([PasswordLabel(form.password_value) retain]); + // Overwrite the height of the password field because it's higher in the + // editable mode. + [passwordStaticField_ + setFrameSize:NSMakeSize( + NSWidth([passwordStaticField_ frame]), + std::max(NSHeight([passwordStaticField_ frame]), + NSHeight([EditableField(form.password_value) + frame])))]; } + passwordViewButton_.reset([EyeIcon(self, @selector(onEyeClicked:)) retain]); + if (self.model->are_passwords_revealed_when_bubble_is_opened()) + [passwordViewButton_ setState:NSOnState]; + else + [passwordViewButton_ setState:NSOffState]; + [container addSubview:passwordViewButton_]; } else { base::string16 text = l10n_util::GetStringFUTF16( IDS_PASSWORDS_VIA_FEDERATION,
diff --git a/chrome/browser/ui/cocoa/passwords/save_pending_password_view_controller_unittest.mm b/chrome/browser/ui/cocoa/passwords/save_pending_password_view_controller_unittest.mm index ba20562..c40c93b9 100644 --- a/chrome/browser/ui/cocoa/passwords/save_pending_password_view_controller_unittest.mm +++ b/chrome/browser/ui/cocoa/passwords/save_pending_password_view_controller_unittest.mm
@@ -79,33 +79,16 @@ EXPECT_TRUE([delegate() dismissed]); } -TEST_F(SavePendingPasswordViewControllerTest, - UsernameEditableWhenFeatureEnabled) { - base::test::ScopedFeatureList feature_list; - feature_list.InitAndEnableFeature( - password_manager::features::kEnableUsernameCorrection); +TEST_F(SavePendingPasswordViewControllerTest, UsernameEditable) { SetUpSavePendingState("admin", "12345", {}); EXPECT_TRUE(controller().usernameField.editable); EXPECT_NSEQ(@"admin", [controller().usernameField stringValue]); } TEST_F(SavePendingPasswordViewControllerTest, - UsernameStaticWhenFeatureDisabled) { - base::test::ScopedFeatureList feature_list; - feature_list.InitAndDisableFeature( - password_manager::features::kEnableUsernameCorrection); - SetUpSavePendingState("admin", "12345", {}); - EXPECT_FALSE(controller().usernameField.editable); - EXPECT_NSEQ(@"admin", [controller().usernameField stringValue]); -} - -TEST_F(SavePendingPasswordViewControllerTest, ShouldSaveEditedUsernameAndDismissWhenSaveClicked) { profile()->GetPrefs()->SetBoolean( password_manager::prefs::kWasSignInPasswordPromoClicked, true); - base::test::ScopedFeatureList feature_list; - feature_list.InitAndEnableFeature( - password_manager::features::kEnableUsernameCorrection); SetUpSavePendingState("admin", "12345", {}); [controller().usernameField setStringValue:@"editedusername"]; @@ -121,9 +104,6 @@ } TEST_F(SavePendingPasswordViewControllerTest, SelectAnotherPassword) { - base::test::ScopedFeatureList feature_list; - feature_list.InitAndEnableFeature( - password_manager::features::kEnablePasswordSelection); SetUpSavePendingState("username", "12345", {"111", "222"}); NSPopUpButton* passwordSelection = controller().passwordSelectionField; @@ -140,9 +120,6 @@ } TEST_F(SavePendingPasswordViewControllerTest, ViewAndSelectPassword) { - base::test::ScopedFeatureList feature_list; - feature_list.InitAndEnableFeature( - password_manager::features::kEnablePasswordSelection); SetUpSavePendingState("username", "12345", {"111", "222"}); NSPopUpButton* passwordSelection = controller().passwordSelectionField; @@ -157,9 +134,6 @@ } TEST_F(SavePendingPasswordViewControllerTest, ViewSelectAndMaskPassword) { - base::test::ScopedFeatureList feature_list; - feature_list.InitAndEnableFeature( - password_manager::features::kEnablePasswordSelection); SetUpSavePendingState("username", "12345", {"111", "222"}); NSPopUpButton* passwordSelection = controller().passwordSelectionField;
diff --git a/chrome/browser/ui/extensions/hosted_app_browser_controller.cc b/chrome/browser/ui/extensions/hosted_app_browser_controller.cc index 42499dc..852668f 100644 --- a/chrome/browser/ui/extensions/hosted_app_browser_controller.cc +++ b/chrome/browser/ui/extensions/hosted_app_browser_controller.cc
@@ -4,6 +4,8 @@ #include "chrome/browser/ui/extensions/hosted_app_browser_controller.h" +#include "base/metrics/histogram_macros.h" +#include "chrome/browser/engagement/site_engagement_service.h" #include "chrome/browser/extensions/tab_helper.h" #include "chrome/browser/profiles/profile.h" #include "chrome/browser/ssl/security_state_tab_helper.h" @@ -13,9 +15,11 @@ #include "chrome/browser/ui/tabs/tab_strip_model.h" #include "chrome/browser/web_applications/web_app.h" #include "chrome/common/chrome_features.h" +#include "chrome/common/extensions/api/url_handlers/url_handlers_parser.h" #include "chrome/common/extensions/manifest_handlers/app_launch_info.h" #include "chrome/common/extensions/manifest_handlers/app_theme_color_info.h" #include "components/security_state/core/security_state.h" +#include "content/public/browser/browser_context.h" #include "content/public/browser/navigation_entry.h" #include "content/public/browser/web_contents.h" #include "extensions/browser/extension_registry.h" @@ -54,6 +58,9 @@ } // namespace +const char kPwaWindowEngagementTypeHistogram[] = + "Webapp.Engagement.EngagementType"; + // static bool HostedAppBrowserController::IsForHostedApp(const Browser* browser) { const std::string extension_id = @@ -72,12 +79,32 @@ } HostedAppBrowserController::HostedAppBrowserController(Browser* browser) - : browser_(browser), + : SiteEngagementObserver(SiteEngagementService::Get(browser->profile())), + browser_(browser), extension_id_( web_app::GetExtensionIdFromApplicationName(browser->app_name())) {} HostedAppBrowserController::~HostedAppBrowserController() {} +bool HostedAppBrowserController::IsForInstalledPwa( + content::WebContents* web_contents) const { + if (!web_contents || + web_contents != browser_->tab_strip_model()->GetActiveWebContents()) { + return false; + } + + if (!browser_->is_app()) + return false; + + // If a bookmark app has a URL handler, then it is a PWA. + // TODO(https://crbug.com/774918): Replace once there is a more explicit + // indicator of a Bookmark App for an installable website. + if (extensions::UrlHandlers::GetUrlHandlers(GetExtension()) == nullptr) + return false; + + return true; +} + bool HostedAppBrowserController::ShouldShowLocationBar() const { const Extension* extension = GetExtension(); @@ -178,4 +205,16 @@ net::registry_controlled_domains::INCLUDE_PRIVATE_REGISTRIES); } +void HostedAppBrowserController::OnEngagementEvent( + content::WebContents* web_contents, + const GURL& /*url*/, + double /*score*/, + SiteEngagementService::EngagementType type) { + if (!IsForInstalledPwa(web_contents)) + return; + + UMA_HISTOGRAM_ENUMERATION(kPwaWindowEngagementTypeHistogram, type, + SiteEngagementService::ENGAGEMENT_LAST); +} + } // namespace extensions
diff --git a/chrome/browser/ui/extensions/hosted_app_browser_controller.h b/chrome/browser/ui/extensions/hosted_app_browser_controller.h index 65ba7429..3f973040 100644 --- a/chrome/browser/ui/extensions/hosted_app_browser_controller.h +++ b/chrome/browser/ui/extensions/hosted_app_browser_controller.h
@@ -9,6 +9,7 @@ #include "base/macros.h" #include "base/optional.h" +#include "chrome/browser/engagement/site_engagement_observer.h" #include "third_party/skia/include/core/SkColor.h" class Browser; @@ -19,10 +20,12 @@ namespace extensions { +extern const char kPwaWindowEngagementTypeHistogram[]; + class Extension; // Class to encapsulate logic to control the browser UI for hosted apps. -class HostedAppBrowserController { +class HostedAppBrowserController : public SiteEngagementObserver { public: // Indicates whether |browser| is a hosted app browser. static bool IsForHostedApp(const Browser* browser); @@ -31,7 +34,10 @@ static bool IsForExperimentalHostedAppBrowser(const Browser* browser); explicit HostedAppBrowserController(Browser* browser); - ~HostedAppBrowserController(); + ~HostedAppBrowserController() override; + + // Returns whether the associated browser is for an installed PWA window. + bool IsForInstalledPwa(content::WebContents* web_contents) const; // Whether the browser being controlled should be currently showing the // location bar. @@ -63,6 +69,12 @@ // Gets the extension for this controller. const Extension* GetExtension() const; + // SiteEngagementObserver overrides. + void OnEngagementEvent(content::WebContents* web_contents, + const GURL& url, + double score, + SiteEngagementService::EngagementType type) override; + private: Browser* const browser_; const std::string extension_id_;
diff --git a/chrome/browser/ui/extensions/hosted_app_browsertest.cc b/chrome/browser/ui/extensions/hosted_app_browsertest.cc index 23fa3bc..15c4512 100644 --- a/chrome/browser/ui/extensions/hosted_app_browsertest.cc +++ b/chrome/browser/ui/extensions/hosted_app_browsertest.cc
@@ -9,9 +9,11 @@ #include "base/json/json_reader.h" #include "base/strings/stringprintf.h" #include "base/strings/utf_string_conversions.h" +#include "base/test/histogram_tester.h" #include "base/test/scoped_feature_list.h" #include "build/build_config.h" #include "chrome/app/chrome_command_ids.h" +#include "chrome/browser/engagement/site_engagement_service.h" #include "chrome/browser/extensions/extension_browsertest.h" #include "chrome/browser/extensions/extension_service.h" #include "chrome/browser/extensions/extension_util.h" @@ -57,6 +59,7 @@ namespace { constexpr const char kExampleURL[] = "http://example.org/"; +constexpr const char kExampleURL2[] = "http://example.com/"; constexpr const char kAppDotComManifest[] = R"( { "name": "Hosted App", "version": "1", "manifest_version": 2, @@ -468,6 +471,108 @@ GetAppInfoDialogCreatedCallbackForTesting().Reset(); } +IN_PROC_BROWSER_TEST_P(HostedAppPWAOnlyTest, EngagementHistogram) { + base::HistogramTester histograms; + WebApplicationInfo web_app_info; + web_app_info.app_url = GURL(kExampleURL); + web_app_info.scope = GURL(kExampleURL); + web_app_info.theme_color = base::Optional<SkColor>(); + const extensions::Extension* app = InstallBookmarkApp(web_app_info); + Browser* app_browser = LaunchAppBrowser(app); + NavigateToURLAndWait(app_browser, GURL(kExampleURL)); + + // Test shortcut launch. + EXPECT_EQ(web_app::GetExtensionIdFromApplicationName(app_browser->app_name()), + app->id()); + + histograms.ExpectUniqueSample( + extensions::kPwaWindowEngagementTypeHistogram, + SiteEngagementService::ENGAGEMENT_WEBAPP_SHORTCUT_LAUNCH, 1); + + // Test some other engagement events by directly calling into + // SiteEngagementService. + content::WebContents* web_contents = + app_browser->tab_strip_model()->GetActiveWebContents(); + SiteEngagementService* site_engagement_service = + SiteEngagementService::Get(app_browser->profile()); + site_engagement_service->HandleMediaPlaying(web_contents, false); + site_engagement_service->HandleMediaPlaying(web_contents, true); + site_engagement_service->HandleNavigation(web_contents, + ui::PAGE_TRANSITION_TYPED); + site_engagement_service->HandleUserInput( + web_contents, SiteEngagementService::ENGAGEMENT_MOUSE); + + histograms.ExpectTotalCount(extensions::kPwaWindowEngagementTypeHistogram, 5); + histograms.ExpectBucketCount(extensions::kPwaWindowEngagementTypeHistogram, + SiteEngagementService::ENGAGEMENT_MEDIA_VISIBLE, + 1); + histograms.ExpectBucketCount(extensions::kPwaWindowEngagementTypeHistogram, + SiteEngagementService::ENGAGEMENT_MEDIA_HIDDEN, + 1); + histograms.ExpectBucketCount(extensions::kPwaWindowEngagementTypeHistogram, + SiteEngagementService::ENGAGEMENT_NAVIGATION, 1); + histograms.ExpectBucketCount(extensions::kPwaWindowEngagementTypeHistogram, + SiteEngagementService::ENGAGEMENT_MOUSE, 1); +} + +IN_PROC_BROWSER_TEST_P(HostedAppPWAOnlyTest, + EngagementHistogramNotRecordedIfNoScope) { + base::HistogramTester histograms; + WebApplicationInfo web_app_info; + // App with no scope. + web_app_info.app_url = GURL(kExampleURL); + web_app_info.theme_color = base::Optional<SkColor>(); + const extensions::Extension* app = InstallBookmarkApp(web_app_info); + Browser* app_browser = LaunchAppBrowser(app); + + EXPECT_EQ(web_app::GetExtensionIdFromApplicationName(app_browser->app_name()), + app->id()); + + histograms.ExpectTotalCount(extensions::kPwaWindowEngagementTypeHistogram, 0); +} + +IN_PROC_BROWSER_TEST_P(HostedAppPWAOnlyTest, EngagementHistogramTwoApps) { + base::HistogramTester histograms; + const extensions::Extension *app1, *app2; + + // Install two apps. + { + WebApplicationInfo web_app_info; + web_app_info.app_url = GURL(kExampleURL); + web_app_info.scope = GURL(kExampleURL); + web_app_info.theme_color = base::Optional<SkColor>(); + app1 = InstallBookmarkApp(web_app_info); + } + { + WebApplicationInfo web_app_info; + web_app_info.app_url = GURL(kExampleURL2); + web_app_info.scope = GURL(kExampleURL2); + web_app_info.theme_color = base::Optional<SkColor>(); + app2 = InstallBookmarkApp(web_app_info); + } + + // Launch them three times. This ensures that each launch only logs once. + // (Since all apps receive the notification on launch, there is a danger that + // we might log too many times.) + Browser* app_browser1 = LaunchAppBrowser(app1); + Browser* app_browser2 = LaunchAppBrowser(app1); + Browser* app_browser3 = LaunchAppBrowser(app2); + + EXPECT_EQ( + web_app::GetExtensionIdFromApplicationName(app_browser1->app_name()), + app1->id()); + EXPECT_EQ( + web_app::GetExtensionIdFromApplicationName(app_browser2->app_name()), + app1->id()); + EXPECT_EQ( + web_app::GetExtensionIdFromApplicationName(app_browser3->app_name()), + app2->id()); + + histograms.ExpectUniqueSample( + extensions::kPwaWindowEngagementTypeHistogram, + SiteEngagementService::ENGAGEMENT_WEBAPP_SHORTCUT_LAUNCH, 3); +} + // Common app manifest for HostedAppProcessModelTests. constexpr const char kHostedAppProcessModelManifest[] = R"( { "name": "Hosted App Process Model Test",
diff --git a/chrome/browser/ui/views/passwords/manage_passwords_bubble_view.cc b/chrome/browser/ui/views/passwords/manage_passwords_bubble_view.cc index 4232c3c24..1575a77 100644 --- a/chrome/browser/ui/views/passwords/manage_passwords_bubble_view.cc +++ b/chrome/browser/ui/views/passwords/manage_passwords_bubble_view.cc
@@ -497,9 +497,7 @@ const autofill::PasswordForm& password_form = parent_->model()->pending_password(); const bool is_password_credential = password_form.federation_origin.unique(); - if (base::FeatureList::IsEnabled( - password_manager::features::kEnableUsernameCorrection) && - parent_->model()->enable_editing()) { + if (parent_->model()->enable_editing()) { username_field_ = CreateUsernameEditable(password_form).release(); } else { username_field_ = CreateUsernameLabel(password_form).release(); @@ -507,9 +505,7 @@ CreatePasswordField(); - if (base::FeatureList::IsEnabled( - password_manager::features::kEnablePasswordSelection) && - is_password_credential) { + if (is_password_credential) { password_view_button_ = CreatePasswordViewButton(this, are_passwords_revealed_).release(); } @@ -522,9 +518,7 @@ l10n_util::GetStringUTF16(IDS_PASSWORD_MANAGER_BUBBLE_BLACKLIST_BUTTON)); CreateAndSetLayout(is_password_credential); - if (base::FeatureList::IsEnabled( - password_manager::features::kEnableUsernameCorrection) && - parent_->model()->enable_editing() && + if (parent_->model()->enable_editing() && parent_->model()->pending_password().username_value.empty()) { parent_->set_initially_focused_view(username_field_); } else { @@ -586,12 +580,9 @@ } void ManagePasswordsBubbleView::PendingView::CreatePasswordField() { - const bool enable_password_selection = base::FeatureList::IsEnabled( - password_manager::features::kEnablePasswordSelection); const autofill::PasswordForm& password_form = parent_->model()->pending_password(); - if (enable_password_selection && - password_form.all_possible_passwords.size() > 1 && + if (password_form.all_possible_passwords.size() > 1 && parent_->model()->enable_editing()) { password_dropdown_ = CreatePasswordDropdownView(password_form, are_passwords_revealed_) @@ -623,13 +614,8 @@ void ManagePasswordsBubbleView::PendingView:: UpdateUsernameAndPasswordInModel() { - const bool username_editable = - base::FeatureList::IsEnabled( - password_manager::features::kEnableUsernameCorrection) && - parent_->model()->enable_editing(); + const bool username_editable = parent_->model()->enable_editing(); const bool password_editable = - base::FeatureList::IsEnabled( - password_manager::features::kEnablePasswordSelection) && password_dropdown_ && parent_->model()->enable_editing(); if (!username_editable && !password_editable) return;
diff --git a/chrome/browser/ui/views/payments/contact_info_editor_view_controller.cc b/chrome/browser/ui/views/payments/contact_info_editor_view_controller.cc index ff870473..7d7884d 100644 --- a/chrome/browser/ui/views/payments/contact_info_editor_view_controller.cc +++ b/chrome/browser/ui/views/payments/contact_info_editor_view_controller.cc
@@ -198,8 +198,8 @@ case autofill::PHONE_HOME_WHOLE_NUMBER: { const std::string default_region_code = autofill::AutofillCountry::CountryCodeForLocale(locale_); - if (!autofill::IsValidPhoneNumber(textfield->text(), - default_region_code)) { + if (!autofill::IsPossiblePhoneNumber(textfield->text(), + default_region_code)) { is_valid = false; if (error_message) { *error_message = l10n_util::GetStringUTF16(
diff --git a/chrome/browser/ui/views/payments/shipping_address_editor_view_controller.cc b/chrome/browser/ui/views/payments/shipping_address_editor_view_controller.cc index 206fdee5..7149cec 100644 --- a/chrome/browser/ui/views/payments/shipping_address_editor_view_controller.cc +++ b/chrome/browser/ui/views/payments/shipping_address_editor_view_controller.cc
@@ -317,7 +317,7 @@ if (!value.empty()) { if (field_.type == autofill::PHONE_HOME_WHOLE_NUMBER && controller_->chosen_country_index_ < controller_->countries_.size() && - !autofill::IsValidPhoneNumber( + !autofill::IsPossiblePhoneNumber( value, controller_->countries_[controller_->chosen_country_index_] .first)) { if (error_message) {
diff --git a/chrome/browser/ui/views/payments/shipping_address_editor_view_controller_browsertest.cc b/chrome/browser/ui/views/payments/shipping_address_editor_view_controller_browsertest.cc index d1b97dae..a5e93633 100644 --- a/chrome/browser/ui/views/payments/shipping_address_editor_view_controller_browsertest.cc +++ b/chrome/browser/ui/views/payments/shipping_address_editor_view_controller_browsertest.cc
@@ -682,19 +682,38 @@ ClickOnDialogViewAndWait(DialogViewID::SAVE_ADDRESS_BUTTON); } -// Tests that the editor doesn't accept a local phone from another country. +// Tests that the editor accepts a phone number looks like a possible number +// but is actually invalid. IN_PROC_BROWSER_TEST_F(PaymentRequestShippingAddressEditorTest, - AddLocalPhoneNumberFromOtherCountry) { + AddPossiblePhoneNumber) { NavigateTo("/payment_request_dynamic_shipping_test.html"); InvokePaymentRequestUI(); OpenShippingAddressEditorScreen(); SetCommonFields(); - // Set an Australian phone number in international format. + // Set an Australian phone number in local format. This is an invalid + // US number as there is no area code 029, but it can be considered and parsed + // as a US number. SetEditorTextfieldValue(base::UTF8ToUTF16("02 9374 4000"), autofill::PHONE_HOME_WHOLE_NUMBER); + EXPECT_FALSE(IsEditorTextfieldInvalid(autofill::PHONE_HOME_WHOLE_NUMBER)); +} + +// Tests that the editor does not accept a impossible phone number. +IN_PROC_BROWSER_TEST_F(PaymentRequestShippingAddressEditorTest, + AddImpossiblePhoneNumber) { + NavigateTo("/payment_request_dynamic_shipping_test.html"); + InvokePaymentRequestUI(); + OpenShippingAddressEditorScreen(); + + SetCommonFields(); + + // Trying to set an impossible number, note it has 11 digits. + SetEditorTextfieldValue(base::UTF8ToUTF16("02 9374 40001"), + autofill::PHONE_HOME_WHOLE_NUMBER); + EXPECT_TRUE(IsEditorTextfieldInvalid(autofill::PHONE_HOME_WHOLE_NUMBER)); } @@ -786,9 +805,10 @@ static_cast<int>(DialogViewID::PROFILE_LABEL_ERROR))); } -// Tests that there is an error label for an local phone from another country. +// Tests that there is no error label for an phone number that can be +// technically parsed as a US number even if it is actually invalid. IN_PROC_BROWSER_TEST_F(PaymentRequestShippingAddressEditorTest, - ErrorLabelForLocalPhoneNumberFromOtherCountry) { + NoErrorLabelForPossibleButInvalidPhoneNumber) { NavigateTo("/payment_request_dynamic_shipping_test.html"); // Create a profile in the US and add a valid AU phone number in local format. autofill::AutofillProfile california = autofill::test::GetFullProfile(); @@ -800,6 +820,28 @@ InvokePaymentRequestUI(); OpenShippingAddressSectionScreen(); + // There should not be an error label for the phone number. + views::View* sheet = dialog_view()->GetViewByID( + static_cast<int>(DialogViewID::SHIPPING_ADDRESS_SHEET_LIST_VIEW)); + ASSERT_EQ(1, sheet->child_count()); + EXPECT_EQ(nullptr, sheet->child_at(0)->GetViewByID( + static_cast<int>(DialogViewID::PROFILE_LABEL_ERROR))); +} + +// Tests that there is error label for an impossible phone number. +IN_PROC_BROWSER_TEST_F(PaymentRequestShippingAddressEditorTest, + ErrorLabelForImpossiblePhoneNumber) { + NavigateTo("/payment_request_dynamic_shipping_test.html"); + // Create a profile in the US and add a impossible number. + autofill::AutofillProfile california = autofill::test::GetFullProfile(); + california.set_use_count(50U); + california.SetRawInfo(autofill::PHONE_HOME_WHOLE_NUMBER, + base::UTF8ToUTF16("02 9374 40001")); + AddAutofillProfile(california); + + InvokePaymentRequestUI(); + OpenShippingAddressSectionScreen(); + // There should be an error label for the phone number. views::View* sheet = dialog_view()->GetViewByID( static_cast<int>(DialogViewID::SHIPPING_ADDRESS_SHEET_LIST_VIEW));
diff --git a/chrome/browser/ui/webui/ntp/ntp_resource_cache.cc b/chrome/browser/ui/webui/ntp/ntp_resource_cache.cc index c0ff97b..0ce8d87 100644 --- a/chrome/browser/ui/webui/ntp/ntp_resource_cache.cc +++ b/chrome/browser/ui/webui/ntp/ntp_resource_cache.cc
@@ -453,17 +453,8 @@ } void NTPResourceCache::CreateNewTabIncognitoCSS() { - // TODO(estade): this returns a subtly incorrect theme provider because - // |profile_| is actually not the incognito profile. See crbug.com/568388 - const ui::ThemeProvider& tp = - ThemeService::GetThemeProviderForProfile(profile_); - - // Get our theme colors - SkColor color_background = - tp.HasCustomImage(IDR_THEME_NTP_BACKGROUND) - ? GetThemeColor(tp, ThemeProperties::COLOR_NTP_BACKGROUND) - : ThemeProperties::GetDefaultColor( - ThemeProperties::COLOR_NTP_BACKGROUND, true /* incognito */); + const ui::ThemeProvider& tp = ThemeService::GetThemeProviderForProfile( + profile_->GetOffTheRecordProfile()); // Generate the replacements. ui::TemplateReplacements substitutions; @@ -473,8 +464,8 @@ profile_->GetPrefs()->GetString(prefs::kCurrentThemeID); // Colors. - substitutions["colorBackground"] = - color_utils::SkColorToRgbaString(color_background); + substitutions["colorBackground"] = color_utils::SkColorToRgbaString( + GetThemeColor(tp, ThemeProperties::COLOR_NTP_BACKGROUND)); substitutions["backgroundBarDetached"] = GetNewTabBackgroundCSS(tp, false); substitutions["backgroundBarAttached"] = GetNewTabBackgroundCSS(tp, true); substitutions["backgroundTiling"] = GetNewTabBackgroundTilingCSS(tp); @@ -495,7 +486,7 @@ const ui::ThemeProvider& tp = ThemeService::GetThemeProviderForProfile(profile_); - // Get our theme colors + // Get our theme colors. SkColor color_background = GetThemeColor(tp, ThemeProperties::COLOR_NTP_BACKGROUND); SkColor color_text = GetThemeColor(tp, ThemeProperties::COLOR_NTP_TEXT);
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 72823519..e1fa943 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
@@ -770,7 +770,6 @@ IDS_SETTINGS_RESET_CLEANUP_REMOVE_BUTTON_LABEL}, {"chromeCleanupRestartButtonLabel", IDS_SETTINGS_RESET_CLEANUP_RESTART_BUTTON_LABEL}, - {"chromeCleanupTitleDone", IDS_SETTINGS_RESET_CLEANUP_TITLE_DONE}, {"chromeCleanupTitleErrorCantRemove", IDS_SETTINGS_RESET_CLEANUP_TITLE_ERROR_CANT_REMOVE}, {"chromeCleanupTitleErrorPermissions", @@ -782,7 +781,10 @@ {"chromeCleanupTitleNothingFound", IDS_SETTINGS_RESET_CLEANUP_TITLE_NOTHING_FOUND}, {"chromeCleanupTitleRemove", IDS_SETTINGS_RESET_CLEANUP_TITLE_REMOVE}, - {"chromeCleanupTitleRemoved", IDS_SETTINGS_RESET_CLEANUP_TITLE_REMOVED}, + {"chromeCleanupTitleRemoved", + safe_browsing::UserInitiatedCleanupsEnabled() + ? IDS_SETTINGS_RESET_CLEANUP_TITLE_DONE + : IDS_SETTINGS_RESET_CLEANUP_TITLE_REMOVED}, {"chromeCleanupTitleRemoving", IDS_SETTINGS_RESET_CLEANUP_TITLE_REMOVING}, {"chromeCleanupTitleRestart", IDS_SETTINGS_RESET_CLEANUP_TITLE_RESTART}, {"chromeCleanupTitleScanning", IDS_SETTINGS_RESET_CLEANUP_TITLE_SCANNING},
diff --git a/chrome/common/chrome_features.cc b/chrome/common/chrome_features.cc index 6bfa93f..88d674d 100644 --- a/chrome/common/chrome_features.cc +++ b/chrome/common/chrome_features.cc
@@ -579,7 +579,7 @@ // Enables or disables the bulk printer policies on Chrome OS. const base::Feature kBulkPrinters{"BulkPrinters", - base::FEATURE_DISABLED_BY_DEFAULT}; + base::FEATURE_ENABLED_BY_DEFAULT}; // Enables or disables flash component updates on Chrome OS. const base::Feature kCrosCompUpdates{"CrosCompUpdates",
diff --git a/chrome/renderer/autofill/password_autofill_agent_browsertest.cc b/chrome/renderer/autofill/password_autofill_agent_browsertest.cc index b24e895a..8e9e56b 100644 --- a/chrome/renderer/autofill/password_autofill_agent_browsertest.cc +++ b/chrome/renderer/autofill/password_autofill_agent_browsertest.cc
@@ -3323,4 +3323,36 @@ EXPECT_EQ(1, fake_driver_.show_pw_suggestions_key()); } +// Tests that PSL matched password is not autofilled even when there is +// a prefilled username. +TEST_F(PasswordAutofillAgentTest, PSLMatchedPasswordIsNotAutofill) { + const char kFormWithPrefilledUsernameHTML[] = + "<FORM id='LoginTestForm' action='http://www.bidule.com'>" + " <INPUT type='text' id='username' value='prefilledusername'/>" + " <INPUT type='password' id='password'/>" + "</FORM>"; + LoadHTML(kFormWithPrefilledUsernameHTML); + + // Retrieve the input elements so the test can access them. + UpdateUsernameAndPasswordElements(); + + // Set the expected form origin and action URLs. + UpdateOriginForHTML(kFormWithPrefilledUsernameHTML); + + // Add PSL matched credentials with username equal to prefilled one. + PasswordAndRealm psl_credentials; + psl_credentials.password = ASCIIToUTF16("pslpassword"); + // Non-empty realm means PSL matched credentials. + psl_credentials.realm = "example.com"; + fill_data_.additional_logins[ASCIIToUTF16("prefilledusername")] = + psl_credentials; + + // Simulate the browser sending back the login info, it triggers the + // autocomplete. + SimulateOnFillPasswordForm(fill_data_); + + // Test that PSL matched password is not autofilled. + CheckTextFieldsState("prefilledusername", false, "", false); +} + } // namespace autofill
diff --git a/chrome/renderer/security_filter_peer.cc b/chrome/renderer/security_filter_peer.cc index 8202932..2d4f6046 100644 --- a/chrome/renderer/security_filter_peer.cc +++ b/chrome/renderer/security_filter_peer.cc
@@ -12,17 +12,18 @@ #include "base/strings/stringprintf.h" #include "chrome/grit/generated_resources.h" #include "content/public/renderer/fixed_received_data.h" +#include "net/base/escape.h" #include "net/base/net_errors.h" #include "net/http/http_response_headers.h" #include "services/network/public/cpp/url_loader_completion_status.h" #include "ui/base/l10n/l10n_util.h" SecurityFilterPeer::SecurityFilterPeer( - std::unique_ptr<content::RequestPeer> peer) - : original_peer_(std::move(peer)) {} - -SecurityFilterPeer::~SecurityFilterPeer() { -} + std::unique_ptr<content::RequestPeer> peer, + const std::string& mime_type, + const std::string& data) + : original_peer_(std::move(peer)), mime_type_(mime_type), data_(data) {} +SecurityFilterPeer::~SecurityFilterPeer() {} // static std::unique_ptr<content::RequestPeer> @@ -45,36 +46,32 @@ case net::ERR_CERT_WEAK_KEY: case net::ERR_CERT_NAME_CONSTRAINT_VIOLATION: case net::ERR_INSECURE_RESPONSE: - case net::ERR_SSL_PINNED_KEY_NOT_IN_CERT_CHAIN: - if (content::IsResourceTypeFrame(resource_type)) - return CreateSecurityFilterPeerForFrame(std::move(peer), os_error); - // Any other content is entirely filtered-out. - return base::MakeUnique<ReplaceContentPeer>(std::move(peer), - std::string(), std::string()); + case net::ERR_SSL_PINNED_KEY_NOT_IN_CERT_CHAIN: { + std::string mime_type; + std::string data; + if (content::IsResourceTypeFrame(resource_type)) { + // TODO(jcampan): use a different message when getting a + // phishing/malware error. + data = base::StringPrintf( + "<html><meta charset='UTF-8'>" + "<body style='background-color:#990000;color:white;'>" + "%s</body></html>", + net::EscapeForHTML( + l10n_util::GetStringUTF8(IDS_UNSAFE_FRAME_MESSAGE)) + .c_str()); + mime_type = "text/html"; + } + return base::WrapUnique( + new SecurityFilterPeer(std::move(peer), mime_type, data)); + } default: // For other errors, we use our normal error handling. return peer; } } -// static -std::unique_ptr<content::RequestPeer> -SecurityFilterPeer::CreateSecurityFilterPeerForFrame( - std::unique_ptr<content::RequestPeer> peer, - int os_error) { - // TODO(jcampan): use a different message when getting a phishing/malware - // error. - std::string html = base::StringPrintf( - "<html><meta charset='UTF-8'>" - "<body style='background-color:#990000;color:white;'>" - "%s</body></html>", - l10n_util::GetStringUTF8(IDS_UNSAFE_FRAME_MESSAGE).c_str()); - return base::MakeUnique<ReplaceContentPeer>(std::move(peer), "text/html", - html); -} - void SecurityFilterPeer::OnUploadProgress(uint64_t position, uint64_t size) { - original_peer_->OnUploadProgress(position, size); + NOTREACHED(); } bool SecurityFilterPeer::OnReceivedRedirect( @@ -84,18 +81,41 @@ return false; } -void SecurityFilterPeer::OnTransferSizeUpdated(int transfer_size_diff) { - original_peer_->OnTransferSizeUpdated(transfer_size_diff); +void SecurityFilterPeer::OnReceivedResponse( + const content::ResourceResponseInfo& info) { + NOTREACHED(); } -// static -void ProcessResponseInfo(const content::ResourceResponseInfo& info_in, - content::ResourceResponseInfo* info_out, - const std::string& mime_type) { - DCHECK(info_out); - *info_out = info_in; - info_out->mime_type = mime_type; - // Let's create our own HTTP headers. +void SecurityFilterPeer::OnDownloadedData(int len, int encoded_data_length) { + NOTREACHED(); +} + +void SecurityFilterPeer::OnReceivedData(std::unique_ptr<ReceivedData> data) { + NOTREACHED(); +} + +void SecurityFilterPeer::OnTransferSizeUpdated(int transfer_size_diff) { + NOTREACHED(); +} + +void SecurityFilterPeer::OnCompletedRequest( + const network::URLLoaderCompletionStatus& status) { + content::ResourceResponseInfo info; + info.mime_type = mime_type_; + info.headers = CreateHeaders(mime_type_); + info.content_length = static_cast<int>(data_.size()); + original_peer_->OnReceivedResponse(info); + if (!data_.empty()) { + original_peer_->OnReceivedData(base::MakeUnique<content::FixedReceivedData>( + data_.data(), data_.size())); + } + network::URLLoaderCompletionStatus ok_status(status); + ok_status.error_code = net::OK; + original_peer_->OnCompletedRequest(ok_status); +} + +scoped_refptr<net::HttpResponseHeaders> SecurityFilterPeer::CreateHeaders( + const std::string& mime_type) { std::string raw_headers; raw_headers.append("HTTP/1.1 200 OK"); raw_headers.push_back('\0'); @@ -111,43 +131,5 @@ raw_headers.push_back('\0'); } raw_headers.push_back('\0'); - net::HttpResponseHeaders* new_headers = - new net::HttpResponseHeaders(raw_headers); - info_out->headers = new_headers; -} - -//////////////////////////////////////////////////////////////////////////////// -// ReplaceContentPeer - -ReplaceContentPeer::ReplaceContentPeer( - std::unique_ptr<content::RequestPeer> peer, - const std::string& mime_type, - const std::string& data) - : SecurityFilterPeer(std::move(peer)), mime_type_(mime_type), data_(data) {} - -ReplaceContentPeer::~ReplaceContentPeer() { -} - -void ReplaceContentPeer::OnReceivedResponse( - const content::ResourceResponseInfo& info) { - // Ignore this, we'll serve some alternate content in OnCompletedRequest. -} - -void ReplaceContentPeer::OnReceivedData(std::unique_ptr<ReceivedData> data) { - // Ignore this, we'll serve some alternate content in OnCompletedRequest. -} - -void ReplaceContentPeer::OnCompletedRequest( - const network::URLLoaderCompletionStatus& status) { - content::ResourceResponseInfo info; - ProcessResponseInfo(info, &info, mime_type_); - info.content_length = static_cast<int>(data_.size()); - original_peer_->OnReceivedResponse(info); - if (!data_.empty()) { - original_peer_->OnReceivedData(base::MakeUnique<content::FixedReceivedData>( - data_.data(), data_.size())); - } - network::URLLoaderCompletionStatus ok_status(status); - ok_status.error_code = net::OK; - original_peer_->OnCompletedRequest(ok_status); + return base::MakeRefCounted<net::HttpResponseHeaders>(raw_headers); }
diff --git a/chrome/renderer/security_filter_peer.h b/chrome/renderer/security_filter_peer.h index 5a08833a..f8c0ca6 100644 --- a/chrome/renderer/security_filter_peer.h +++ b/chrome/renderer/security_filter_peer.h
@@ -20,7 +20,10 @@ // unsafe resources (such as mixed-content resource). // Call the factory method CreateSecurityFilterPeer() to obtain an instance of // SecurityFilterPeer based on the original Peer. -class SecurityFilterPeer : public content::RequestPeer { +// A SecurityFilterPeer is created only when the associated request is rejected, +// which means content::RequestPeer methods other than OnCompletedRequest must +// not be called. +class SecurityFilterPeer final : public content::RequestPeer { public: ~SecurityFilterPeer() override; @@ -30,50 +33,30 @@ std::unique_ptr<content::RequestPeer> peer, int os_error); - static std::unique_ptr<content::RequestPeer> CreateSecurityFilterPeerForFrame( - std::unique_ptr<content::RequestPeer> peer, - int os_error); - // content::RequestPeer methods. void OnUploadProgress(uint64_t position, uint64_t size) override; bool OnReceivedRedirect(const net::RedirectInfo& redirect_info, const content::ResourceResponseInfo& info) override; - void OnDownloadedData(int len, int encoded_data_length) override {} - void OnTransferSizeUpdated(int transfer_size_diff) override; - - protected: - explicit SecurityFilterPeer(std::unique_ptr<content::RequestPeer> peer); - - std::unique_ptr<content::RequestPeer> original_peer_; - - private: - DISALLOW_COPY_AND_ASSIGN(SecurityFilterPeer); -}; - -// The ReplaceContentPeer cancels the request and serves the provided data as -// content instead. -// TODO(jcampan): For now the resource is still being fetched, but ignored, as -// once we have provided the replacement content, the associated pending request -// in ResourceDispatcher is removed and further OnReceived* notifications are -// ignored. -class ReplaceContentPeer : public SecurityFilterPeer { - public: - ReplaceContentPeer(std::unique_ptr<content::RequestPeer> peer, - const std::string& mime_type, - const std::string& data); - ~ReplaceContentPeer() override; - - // content::RequestPeer Implementation. void OnReceivedResponse(const content::ResourceResponseInfo& info) override; + void OnDownloadedData(int len, int encoded_data_length) override; void OnReceivedData(std::unique_ptr<ReceivedData> data) override; + void OnTransferSizeUpdated(int transfer_size_diff) override; void OnCompletedRequest( const network::URLLoaderCompletionStatus& status) override; private: + SecurityFilterPeer(std::unique_ptr<content::RequestPeer> peer, + const std::string& mime_type, + const std::string& data); + + static scoped_refptr<net::HttpResponseHeaders> CreateHeaders( + const std::string& mime_type); + + std::unique_ptr<content::RequestPeer> original_peer_; std::string mime_type_; std::string data_; - DISALLOW_COPY_AND_ASSIGN(ReplaceContentPeer); + DISALLOW_COPY_AND_ASSIGN(SecurityFilterPeer); }; #endif // CHROME_RENDERER_SECURITY_FILTER_PEER_H_
diff --git a/chrome/test/BUILD.gn b/chrome/test/BUILD.gn index 1802bfe..8c6ea5ab 100644 --- a/chrome/test/BUILD.gn +++ b/chrome/test/BUILD.gn
@@ -1216,6 +1216,7 @@ "../browser/extensions/extension_browsertest.cc", "../browser/extensions/extension_browsertest.h", "../browser/extensions/extension_context_menu_browsertest.cc", + "../browser/extensions/extension_csp_bypass_browsertest.cc", "../browser/extensions/extension_disabled_ui_browsertest.cc", "../browser/extensions/extension_dom_clipboard_apitest.cc", "../browser/extensions/extension_fileapi_apitest.cc", @@ -2802,6 +2803,7 @@ "../browser/metrics/tab_stats_tracker_unittest.cc", "../browser/page_load_metrics/observers/session_restore_page_load_metrics_observer_unittest.cc", "../browser/resource_coordinator/background_tab_navigation_throttle_unittest.cc", + "../browser/resource_coordinator/lifecycle_unit_base_unittest.cc", "../browser/resource_coordinator/lifecycle_unit_unittest.cc", "../browser/resource_coordinator/tab_lifecycle_unit_source_unittest.cc", "../browser/resource_coordinator/tab_lifecycle_unit_unittest.cc",
diff --git a/chrome/test/chromedriver/run_buildbot_steps.py b/chrome/test/chromedriver/run_buildbot_steps.py index 48a91ad..d2b42556 100755 --- a/chrome/test/chromedriver/run_buildbot_steps.py +++ b/chrome/test/chromedriver/run_buildbot_steps.py
@@ -96,7 +96,8 @@ A dictionary where the keys are commit positions and the values are booleans indicating whether the tests passed. """ - temp_log = tempfile.mkstemp()[1] + (temp_fd, temp_log) = tempfile.mkstemp() + os.close(temp_fd) log_name = TEST_LOG_FORMAT % platform result = slave_utils.GSUtilDownloadFile( '%s/%s' % (GS_CHROMEDRIVER_DATA_BUCKET, log_name), temp_log)
diff --git a/chrome/test/data/extensions/platform_apps/extension_view/load_api/main.js b/chrome/test/data/extensions/platform_apps/extension_view/load_api/main.js index ba00c365..140190b0 100644 --- a/chrome/test/data/extensions/platform_apps/extension_view/load_api/main.js +++ b/chrome/test/data/extensions/platform_apps/extension_view/load_api/main.js
@@ -47,168 +47,197 @@ embedder.test.assertEq(expectedValue, element.src); }; -// Tests begin. -function testLoadAPIFunction(extensionIdOne, extensionIdTwo) { - var extensionScheme = 'chrome-extension://'; - var srcOne = 'data:text/html,<body>One</body>'; - var srcTwo = 'data:text/html,<body>Two</body>'; - var invalidExtensionId = 'fakeExtension'; +var extensionScheme = 'chrome-extension://'; +var srcOne = 'data:text/html,<body>One</body>'; +var srcTwo = 'data:text/html,<body>Two</body>'; +// Tests begin. + +// Call load with a specified extension ID and src. +function testLoadAPIFunction(extensionId) { var extensionview = document.querySelector('extensionview'); - var runStepOne = function() { - // Call load with a specified extension ID and src. - extensionview.load(extensionScheme + extensionIdOne + '/' + srcOne) - .then(function onLoadResolved() { - checkExtensionAttribute(extensionview, extensionIdOne); - checkSrcAttribute(extensionview, extensionScheme + extensionIdOne + - '/' + srcOne); - runStepTwo(); - }, function onLoadRejected() { - embedder.test.fail(); - }); - }; - - var runStepTwo = function() { - // Call load with the same extension Id and src. - extensionview.load(extensionScheme + extensionIdOne + '/' + srcOne) - .then(function onLoadResolved() { - checkExtensionAttribute(extensionview, extensionIdOne); - checkSrcAttribute(extensionview, extensionScheme + extensionIdOne + - '/' + srcOne); - runStepThree(); - }, function onLoadRejected() { - embedder.test.fail(); - }); - }; - - var runStepThree = function() { - // Call load with the same extension Id and different src. - extensionview.load(extensionScheme + extensionIdOne + '/' + srcTwo) - .then(function onLoadResolved() { - checkExtensionAttribute(extensionview, extensionIdOne); - checkSrcAttribute(extensionview, extensionScheme + extensionIdOne + - '/' + srcTwo); - runStepFour(); - }, function onLoadRejected() { - embedder.test.fail(); - }); - }; - - var runStepFour = function() { - // Call load with a new extension Id and src. - extensionview.load(extensionScheme + extensionIdTwo + '/' + srcOne) - .then(function onLoadResolved() { - checkExtensionAttribute(extensionview, extensionIdTwo); - checkSrcAttribute(extensionview, extensionScheme + extensionIdTwo + - '/' + srcOne); - runStepFive(); - }, function onLoadRejected() { - embedder.test.fail(); - }); - }; - - var runStepFive = function() { - // Call load with an invalid extension. - extensionview.load(extensionScheme + invalidExtensionId + '/' + srcOne) - .then(function onLoadResolved() { - embedder.test.fail(); - }, function onLoadRejected() { - runStepSix(); - }); - }; - - var runStepSix = function() { - // Call load with a valid extension Id and src after an invalid call. - extensionview.load(extensionScheme + extensionIdOne + '/' + srcTwo) - .then(function onLoadResolved() { - runStepSeven(); - }, function onLoadRejected() { - embedder.test.fail(); - }); - }; - - var runStepSeven = function() { - // Call load with a null extension. - extensionview.load(null) - .then(function onLoadResolved() { - embedder.test.fail(); - }, function onLoadRejected() { - embedder.test.succeed(); - }); - }; - - runStepOne(); + extensionview.load(extensionScheme + extensionId + '/' + srcOne) + .then(function() { + checkExtensionAttribute(extensionview, extensionId); + checkSrcAttribute( + extensionview, extensionScheme + extensionId + '/' + srcOne); + }) + .then(embedder.test.succeed, embedder.test.fail); }; -function testQueuedLoadAPIFunction(extensionIdOne, extensionIdTwo) { - var extensionScheme = 'chrome-extension://'; - var srcOne = 'data:text/html,<body>One</body>'; - var srcTwo = 'data:text/html,<body>Two</body>'; - var loadCallCount = 1; +// Call load with the same extension Id and src. +function testLoadAPISameIdAndSrc(extensionId) { + var extensionview = document.querySelector('extensionview'); + extensionview.load(extensionScheme + extensionId + '/' + srcOne) + .then(function() { + return extensionview.load(extensionScheme + extensionId + '/' + srcOne); + }) + .then(function() { + checkExtensionAttribute(extensionview, extensionId); + checkSrcAttribute( + extensionview, extensionScheme + extensionId + '/' + srcOne); + }) + .then(embedder.test.succeed, embedder.test.fail); +}; +// Call load with the same extension Id and different src. +function testLoadAPISameIdDifferentSrc(extensionId) { + var extensionview = document.querySelector('extensionview'); + extensionview.load(extensionScheme + extensionId + '/' + srcOne) + .then(function() { + return extensionview.load(extensionScheme + extensionId + '/' + srcTwo); + }) + .then(function() { + checkExtensionAttribute(extensionview, extensionId); + checkSrcAttribute( + extensionview, extensionScheme + extensionId + '/' + srcTwo); + }) + .then(embedder.test.succeed, embedder.test.fail); +}; + +// Call load with a new extension Id and src. +function testLoadAPILoadOtherExtension(extensionIdOne, extensionIdTwo) { + var extensionview = document.querySelector('extensionview'); + extensionview.load(extensionScheme + extensionIdOne + '/' + srcOne) + .then(function() { + return extensionview.load( + extensionScheme + extensionIdTwo + '/' + srcTwo); + }) + .then(function() { + checkExtensionAttribute(extensionview, extensionIdTwo); + checkSrcAttribute( + extensionview, extensionScheme + extensionIdTwo + '/' + srcTwo); + // Try another load of the first extension again to make sure the + // previous load managed to complete without stalling the action queue. + return extensionview.load( + extensionScheme + extensionIdOne + '/' + srcOne); + }) + .then(function() { + checkExtensionAttribute(extensionview, extensionIdTwo); + checkSrcAttribute( + extensionview, extensionScheme + extensionIdTwo + '/' + srcOne); + }) + .then(embedder.test.succeed, embedder.test.fail); +}; + +// Call load with an invalid extension. +function testLoadAPIInvalidExtension() { + var invalidExtensionId = 'fakeExtension'; + var extensionview = document.querySelector('extensionview'); + extensionview.load(extensionScheme + invalidExtensionId + '/' + srcOne) + .then(embedder.test.fail, embedder.test.succeed); +}; + +// Call load with a valid extension Id and src after an invalid call. +function testLoadAPIAfterInvalidCall(extensionId) { + var invalidExtensionId = 'fakeExtension'; + var extensionview = document.querySelector('extensionview'); + extensionview.load(extensionScheme + invalidExtensionId + '/' + srcOne) + .then( + embedder.test.fail, + function() { + return extensionview.load( + extensionScheme + extensionId + '/' + srcTwo); + }) + .then(embedder.test.succeed, embedder.test.fail); +}; + +// Call load with a null extension. +function testLoadAPINullExtension() { + var extensionview = document.querySelector('extensionview'); + extensionview.load(null).then(embedder.test.fail, embedder.test.succeed); +}; + +function testQueuedLoadAPIFunction(extensionId) { var extensionview = document.querySelector('extensionview'); + var loadCallCount = 0; + var load_promises = []; + // Call load a first time with a specified extension ID and src. - extensionview.load(extensionScheme + extensionIdOne + '/' + srcOne) - .then(function onLoadResolved() { - // First load call has completed. - checkExtensionAttribute(extensionview, extensionIdOne); - checkSrcAttribute(extensionview, extensionScheme + extensionIdOne + - '/' + srcOne); - embedder.test.assertEq(1, loadCallCount); - // Checked for expected attributes and call order. - loadCallCount++; - }, function onLoadRejected() { - embedder.test.fail(); - }); + load_promises.push( + extensionview.load(extensionScheme + extensionId + '/' + srcOne) + .then(function() { + loadCallCount++; + embedder.test.assertEq(1, loadCallCount); + })); // Call load a second time with the same extension Id and src. - extensionview.load(extensionScheme + extensionIdOne + '/' + srcOne) - .then(function onLoadResolved() { - // Second load call has completed. - checkExtensionAttribute(extensionview, extensionIdOne); - checkSrcAttribute(extensionview, extensionScheme + extensionIdOne + - '/' + srcOne); - embedder.test.assertEq(2, loadCallCount); - // Checked for expected attributes and call order. - loadCallCount++; - }, function onLoadRejected() { - embedder.test.fail(); - }); + load_promises.push( + extensionview.load(extensionScheme + extensionId + '/' + srcOne) + .then(function() { + loadCallCount++; + embedder.test.assertEq(2, loadCallCount); + })); // Call load a third time with the same extension Id and different src. - extensionview.load(extensionScheme + extensionIdOne + '/' + srcTwo) - .then(function onLoadResolved() { - // Third load call has completed. - checkExtensionAttribute(extensionview, extensionIdOne); - checkSrcAttribute(extensionview, extensionScheme + extensionIdOne + - '/' + srcTwo); - embedder.test.assertEq(3, loadCallCount); - // Checked for expected attributes and call order. - loadCallCount++; - }, function onLoadRejected() { - embedder.test.fail(); - }); + load_promises.push( + extensionview.load(extensionScheme + extensionId + '/' + srcTwo) + .then(function() { + loadCallCount++; + embedder.test.assertEq(3, loadCallCount); + })); - // Call load a fourth time with a new extension Id and src. - extensionview.load(extensionScheme + extensionIdTwo + '/' + srcOne) - .then(function onLoadResolved() { - // Fourth load call has completed. - checkExtensionAttribute(extensionview, extensionIdTwo); - checkSrcAttribute(extensionview, extensionScheme + extensionIdTwo + - '/' + srcOne); - embedder.test.assertEq(4, loadCallCount); - // Checked for expected attributes and call order. - embedder.test.succeed(); - }, function onLoadRejected() { - embedder.test.fail(); - }); + Promise.all(load_promises) + .then(function() { + // Ensure we have the expected attributes for the most recent load. + checkExtensionAttribute(extensionview, extensionId); + checkSrcAttribute( + extensionview, extensionScheme + extensionId + '/' + srcTwo); + }) + .then(embedder.test.succeed, embedder.test.fail); +}; + +function testQueuedLoadAPILoadOtherExtension(extensionIdOne, extensionIdTwo) { + var extensionview = document.querySelector('extensionview'); + + var loadCallCount = 0; + var load_promises = []; + + load_promises.push( + extensionview.load(extensionScheme + extensionIdOne + '/' + srcOne) + .then(function() { + loadCallCount++; + embedder.test.assertEq(1, loadCallCount); + })); + + // Enqueue a load to another extension. + load_promises.push( + extensionview.load(extensionScheme + extensionIdTwo + '/' + srcTwo) + .then(function() { + loadCallCount++; + embedder.test.assertEq(2, loadCallCount); + })); + + // Enqueue a load to back to the original extension. + load_promises.push( + extensionview.load(extensionScheme + extensionIdOne + '/' + srcOne) + .then(function() { + loadCallCount++; + embedder.test.assertEq(3, loadCallCount); + })); + + Promise.all(load_promises) + .then(function() { + // Ensure we have the expected attributes for the most recent load. + checkExtensionAttribute(extensionview, extensionIdOne); + checkSrcAttribute( + extensionview, extensionScheme + extensionIdOne + '/' + srcOne); + }) + .then(embedder.test.succeed, embedder.test.fail); }; embedder.test.testList = { 'testLoadAPIFunction': testLoadAPIFunction, + 'testLoadAPISameIdAndSrc': testLoadAPISameIdAndSrc, + 'testLoadAPISameIdDifferentSrc': testLoadAPISameIdDifferentSrc, + 'testLoadAPILoadOtherExtension': testLoadAPILoadOtherExtension, + 'testLoadAPIInvalidExtension': testLoadAPIInvalidExtension, + 'testLoadAPIAfterInvalidCall': testLoadAPIAfterInvalidCall, + 'testLoadAPINullExtension': testLoadAPINullExtension, 'testQueuedLoadAPIFunction': testQueuedLoadAPIFunction, + 'testQueuedLoadAPILoadOtherExtension': testQueuedLoadAPILoadOtherExtension, }; onload = function() {
diff --git a/chrome/test/data/vr/e2e_test_files/html/test_gamepad_button.html b/chrome/test/data/vr/e2e_test_files/html/test_gamepad_button.html index 39acdae..4c49607 100644 --- a/chrome/test/data/vr/e2e_test_files/html/test_gamepad_button.html +++ b/chrome/test/data/vr/e2e_test_files/html/test_gamepad_button.html
@@ -26,7 +26,7 @@ }); index = e.gamepad.index; }); - onAnimationFrameCallback = function() { + onPresentingAnimationFrameCallback = function() { if (index == -1) return; if (!canStartTest) return; var gp = navigator.getGamepads()[index];
diff --git a/chrome/test/data/vr/e2e_test_files/html/test_presentation_locks_focus.html b/chrome/test/data/vr/e2e_test_files/html/test_presentation_locks_focus.html index bb1084d..3d6a496d 100644 --- a/chrome/test/data/vr/e2e_test_files/html/test_presentation_locks_focus.html +++ b/chrome/test/data/vr/e2e_test_files/html/test_presentation_locks_focus.html
@@ -16,13 +16,13 @@ var t = async_test("Focus is locked to presentation"); var rafCount = 0; window.onfocus = function() { - onAnimationFrameCallback = null; + onPresentingAnimationFrameCallback = null; setTimeout(function() { document.getElementById('externalframe').contentWindow.focus(); }, 1000); }; window.onblur = function() { - onAnimationFrameCallback = function() { + onPresentingAnimationFrameCallback = function() { if (rafCount == 3) { t.done(); }
diff --git a/chrome/test/data/vr/e2e_test_files/html/test_webvr_reentry_from_vr_browser.html b/chrome/test/data/vr/e2e_test_files/html/test_webvr_reentry_from_vr_browser.html new file mode 100644 index 0000000..5a7a1fe1 --- /dev/null +++ b/chrome/test/data/vr/e2e_test_files/html/test_webvr_reentry_from_vr_browser.html
@@ -0,0 +1,39 @@ +<!doctype html> +<!-- +Tests that WebVR continues to work (rAFs continue to fire) after re-entering +presentation from the VR browser. +--> +<html> + <head> + <link rel="stylesheet" type="text/css" href="../resources/webvr_e2e.css"> + </head> + <body> + <canvas id="webgl-canvas"></canvas> + <script src="../../../../../../third_party/WebKit/LayoutTests/resources/testharness.js"></script> + <script src="../resources/webvr_e2e.js"></script> + <script src="../resources/webvr_boilerplate.js"></script> + <script> + var t = async_test("rAFs continue to fire after presentation re-entry"); + + function stepVerifyFirstPresent() { + onPresentingAnimationFrameCallback = () => { + onPresentingAnimationFrameCallback = null; + finishJavaScriptStep(); + }; + } + + function stepVerifyMagicWindow() { + onMagicWindowAnimationFrameCallback = () => { + onMagicWindowAnimationFrameCallback = null; + finishJavaScriptStep(); + }; + } + + function stepVerifySecondPresent() { + onPresentingAnimationFrameCallback = () => { + t.done(); + }; + } + </script> + </body> +</html> \ No newline at end of file
diff --git a/chrome/test/data/vr/e2e_test_files/html/webvr_page_submits_once.html b/chrome/test/data/vr/e2e_test_files/html/webvr_page_submits_once.html index 8047a1c..8b83250c 100644 --- a/chrome/test/data/vr/e2e_test_files/html/webvr_page_submits_once.html +++ b/chrome/test/data/vr/e2e_test_files/html/webvr_page_submits_once.html
@@ -12,14 +12,12 @@ <script src="../resources/webvr_boilerplate.js"></script> <script> var has_submitted = false; - onAnimationFrameCallback = function() { - if (vrDisplay.isPresenting) { - if (has_submitted) { - shouldSubmitFrame = false; - finishJavaScriptStep(); - } - has_submitted = true; + onPresentingAnimationFrameCallback = function() { + if (has_submitted) { + shouldSubmitFrame = false; + finishJavaScriptStep(); } + has_submitted = true; }; </script> </body>
diff --git a/chrome/test/data/vr/e2e_test_files/resources/webvr_boilerplate.js b/chrome/test/data/vr/e2e_test_files/resources/webvr_boilerplate.js index 9708fac1..c789f65 100644 --- a/chrome/test/data/vr/e2e_test_files/resources/webvr_boilerplate.js +++ b/chrome/test/data/vr/e2e_test_files/resources/webvr_boilerplate.js
@@ -18,7 +18,8 @@ var gl = webglCanvas.getContext("webgl", glAttribs); var vrDisplay = null; var frameData = null; -var onAnimationFrameCallback = null; +var onMagicWindowAnimationFrameCallback = null; +var onPresentingAnimationFrameCallback = null; var shouldSubmitFrame = true; function onResize() { @@ -51,7 +52,9 @@ vrDisplay.requestAnimationFrame(onAnimationFrame); // If presenting, set canvas to blue. Otherwise, red. if (vrDisplay.isPresenting) { - if (onAnimationFrameCallback) onAnimationFrameCallback(); + if (onPresentingAnimationFrameCallback) { + onPresentingAnimationFrameCallback(); + } vrDisplay.getFrameData(frameData); gl.clearColor(0.0, 0.0, 1.0, 1.0); @@ -63,6 +66,9 @@ if (shouldSubmitFrame) vrDisplay.submitFrame(); } else { + if (onMagicWindowAnimationFrameCallback) { + onMagicWindowAnimationFrameCallback(); + } gl.clearColor(1.0, 0.0, 0.0, 1.0); gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT);
diff --git a/chrome/test/data/webui/print_preview/new_print_preview_ui_browsertest.js b/chrome/test/data/webui/print_preview/new_print_preview_ui_browsertest.js index 1deb74c..b173809 100644 --- a/chrome/test/data/webui/print_preview/new_print_preview_ui_browsertest.js +++ b/chrome/test/data/webui/print_preview/new_print_preview_ui_browsertest.js
@@ -93,6 +93,10 @@ this.runMochaTest(settings_sections_tests.TestNames.Other); }); +TEST_F('PrintPreviewSettingsSectionsTest', 'SetPages', function() { + this.runMochaTest(settings_sections_tests.TestNames.SetPages); +}); + TEST_F('PrintPreviewSettingsSectionsTest', 'SetCopies', function() { this.runMochaTest(settings_sections_tests.TestNames.SetCopies); });
diff --git a/chrome/test/data/webui/print_preview/settings_section_test.js b/chrome/test/data/webui/print_preview/settings_section_test.js index f83d8795..ffab4841 100644 --- a/chrome/test/data/webui/print_preview/settings_section_test.js +++ b/chrome/test/data/webui/print_preview/settings_section_test.js
@@ -13,6 +13,7 @@ Dpi: 'dpi', Scaling: 'scaling', Other: 'other', + SetPages: 'set pages', SetCopies: 'set copies', SetLayout: 'set layout', SetColor: 'set color', @@ -54,6 +55,7 @@ info.init(!isPdf, 'title', hasSelection); if (isPdf) info.fitToPageScaling_ = '98'; + info.updatePageCount(3); page.set('documentInfo_', info); } @@ -307,6 +309,65 @@ expectEquals(false, duplex.hidden); }); + test(assert(TestNames.SetPages), function() { + const pagesElement = page.$$('print-preview-pages-settings'); + // This section is always visible. + expectEquals(false, pagesElement.hidden); + + // Default value is all pages. Print ticket expects this to be empty. + const allRadio = pagesElement.$$('#all-radio-button'); + const customRadio = pagesElement.$$('#custom-radio-button'); + const pagesInput = pagesElement.$$('#page-settings-custom-input'); + const hint = pagesElement.$$('.hint'); + + /** + * @param {boolean} allChecked Whether the all pages radio button is + * selected. + * @param {string} inputString The expected string in the pages input. + * @param {boolean} valid Whether the input string is valid. + */ + const validateInputState = function(allChecked, inputString, valid) { + expectEquals(allChecked, allRadio.checked); + expectEquals(!allChecked, customRadio.checked); + expectEquals(inputString, pagesInput.value); + expectEquals(valid, hint.hidden); + }; + validateInputState(true, '', true); + expectEquals(0, page.settings.pages.value.length); + expectEquals(true, page.settings.pages.valid); + + // Set selection of pages 1 and 2. + customRadio.checked = true; + allRadio.dispatchEvent(new CustomEvent('change')); + pagesInput.value = '1-2'; + pagesInput.dispatchEvent(new CustomEvent('input')); + validateInputState(false, '1-2', true); + assertEquals(1, page.settings.pages.value.length); + expectEquals(1, page.settings.pages.value[0].from); + expectEquals(2, page.settings.pages.value[0].to); + expectEquals(true, page.settings.pages.valid); + + // Select pages 1 and 3 + pagesInput.value = '1, 3'; + pagesInput.dispatchEvent(new CustomEvent('input')); + validateInputState(false, '1, 3', true); + assertEquals(2, page.settings.pages.value.length); + expectEquals(1, page.settings.pages.value[0].from); + expectEquals(1, page.settings.pages.value[0].to); + expectEquals(3, page.settings.pages.value[1].from); + expectEquals(3, page.settings.pages.value[1].to); + expectEquals(true, page.settings.pages.valid); + + // Enter an out of bounds value. + pagesInput.value = '5'; + pagesInput.dispatchEvent(new CustomEvent('input')); + + // Now the pages settings value should be invalid, and the error + // message should be displayed. + validateInputState(false, '5', false); + expectEquals(false, page.settings.pages.valid); + }); + test(assert(TestNames.SetCopies), function() { const copiesElement = page.$$('print-preview-copies-settings'); expectEquals(false, copiesElement.hidden);
diff --git a/chrome/tools/build/win/makecab.py b/chrome/tools/build/win/makecab.py index dedd100f..722a59def7 100755 --- a/chrome/tools/build/win/makecab.py +++ b/chrome/tools/build/win/makecab.py
@@ -6,6 +6,7 @@ """usage: makecab.py [options] source [destination] Makes cab archives of single files, using zip compression. Acts like Microsoft makecab.exe would act if passed `/D CompressionType=MSZIP`. +If [destination] is omitted, uses source with last character replaced with _. options: -h, --help: print this message @@ -22,7 +23,6 @@ from __future__ import print_function from collections import namedtuple -import argparse import datetime import os import struct @@ -30,8 +30,11 @@ import zlib +class FlagParseError(Exception): pass + + def ParseFlags(flags): - """Parses |flags| and returns the parsed flags.""" + """Parses |flags| and returns the parsed flags; returns None for --help.""" # Can't use optparse / argparse because of /-style flags :-/ input = None output = None @@ -41,37 +44,30 @@ while i < len(flags): flag = flags[i] if flag == '-h' or flag == '--help': - print(__doc__) - sys.exit(0) + return None if flag.startswith('/V'): i += 1 # Ignore /V1 and friends. elif flag in ['/D', '/L']: if i == len(flags) - 1: - print('makecab.py: argument needed after', flag, file=sys.stderr) - sys.exit(1) + raise FlagParseError('argument needed after ' + flag) if flag == '/L': output_dir = flags[i + 1] # Ignore all /D flags silently. i += 2 elif (flag.startswith('-') or (flag.startswith('/') and not os.path.exists(flag))): - print('makecab.py: error: unknown flag', flag, file=sys.stderr) - print(__doc__, file=sys.stderr) - sys.exit(1) + raise FlagParseError('unknown flag ' + flag) else: - if input: - if output: - print('makecab.py: error: too many paths:', input, output, flag, - file=sys.stderr) - sys.exit(1) + if not input: + input = flag + elif not output: output = flag else: - input = flag + raise FlagParseError('too many paths: %s %s %s' % (input, output, flag)) i += 1 # Validate and set default values. if not input: - print('makecab.py: error: no input file', file=sys.stderr) - sys.exit(1) + raise FlagParseError('no input file') if not output: output = os.path.basename(input)[:-1] + '_' Flags = namedtuple('Flags', ['input', 'output', 'output_dir']) @@ -84,10 +80,10 @@ in output_file. cab_stored_filename is the filename stored in the cab file, input_size is the size of the input file, and input_mtimestamp the mtime timestamp of the input file (must be at least midnight 1980-1-1).""" - # Need to write: + # Need to write (all in little-endian):: # 36 bytes CFHEADER cab header # 8 bytes CFFOLDER (a set of files compressed with the same parameters) - # 16 bytes + filename CFFFILE + # 16 bytes + filename (+ 1 byte trailing \0 for filename) CFFFILE # Many 8 bytes CFDATA blocks, representing 32kB chunks of uncompressed data, # each followed by the compressed data. cffile_offset = 36 + 8 @@ -103,6 +99,7 @@ 'I' # reserved1, set to 0 'I' # cbCabinet, size of file in bytes. Not yet known, filled in later. 'I' # reserved2, set to 0 + 'I' # coffFiles, offset of first (and here, only) CFFILE. 'I' # reserved3, set to 0 'B' # versionMinor, currently 3. Yes, minor version is first. @@ -110,11 +107,14 @@ 'H' # cFolders, number of CFFOLDER entries. 'H' # cFiles, number of CFFILE entries. 'H' # flags, for multi-file cabinets. 0 here. + 'H' # setID, for multi-file cabinets. 0 here. 'H' # iCabinet, index in multi-file cabinets. 0 here. ) - output_file.write(struct.pack( - CFHEADER, 'MSCF', 0, 0, 0, cffile_offset, 0, 3, 1, 1, 1, 0, 0, 0)) + output_file.write(struct.pack(CFHEADER, + 'MSCF', 0, 0, 0, + cffile_offset, 0, 3, 1, 1, 1, 0, + 0, 0)) # Write single CFFOLDER. CFFOLDER = ('<' @@ -141,18 +141,14 @@ # 0x80: name contains UTF ) # Followed by szFile, the file's name. assert output_file.tell() == cffile_offset - input_mtime = datetime.datetime.fromtimestamp(input_mtimestamp) - date = (input_mtime.year-1980) << 9 | input_mtime.month << 5 | input_mtime.day + mtime = datetime.datetime.fromtimestamp(input_mtimestamp) + date = (mtime.year - 1980) << 9 | mtime.month << 5 | mtime.day # TODO(thakis): hour seems to be off by 1 from makecab.exe (DST?) - time = input_mtime.hour << 11 | input_mtime.minute << 5 | input_mtime.second/2 + time = mtime.hour << 11 | mtime.minute << 5 | mtime.second / 2 output_file.write(struct.pack(CFFILE, input_size, 0, 0, date, time, 0)) output_file.write(cab_stored_filename + '\0') # Write num_chunks many CFDATA headers, followed by the compressed data. - # cab spec: "Each data block represents 32k uncompressed, except that the - # last block in a folder may be smaller. A two-byte MSZIP signature precedes - # the compressed encoding in each block, consisting of the bytes 0x43, 0x4B. - # The maximum compressed size of each MSZIP block is 32k + 12 bytes." assert output_file.tell() == cfdata_offset CFDATA = ('<' 'I' # checksum. Optional and expensive to compute in Python, so write 0. @@ -170,11 +166,16 @@ # 4.8% larger -- so it might be possible to write an LZX compressor that's # much faster without being so much larger.) Compression level 9 isn't # very different. Level 1 is another ~30% faster and 10% larger. - # Since 6 is ok and the default, let's go with that. (-1 == default == 6) + # Since 6 is ok and the default, let's go with that. # Remember: User-shipped bits get recompressed on the signing server. - zlib_obj = zlib.compressobj(-1, zlib.DEFLATED, -zlib.MAX_WBITS) + zlib_obj = zlib.compressobj( + zlib.Z_DEFAULT_COMPRESSION, zlib.DEFLATED, -zlib.MAX_WBITS) compressed = zlib_obj.compress(chunk) + zlib_obj.flush() compressed_size = 2 + len(compressed) # Also count 0x43 0x4b magic header. + # cab spec: "Each data block represents 32k uncompressed, except that the + # last block in a folder may be smaller. A two-byte MSZIP signature precedes + # the compressed encoding in each block, consisting of the bytes 0x43, 0x4B. + # The maximum compressed size of each MSZIP block is 32k + 12 bytes." assert compressed_size < chunk_size + 12 output_file.write(struct.pack(CFDATA, 0, compressed_size, len(chunk))) output_file.write('\x43\x4b') # MSZIP magic block header. @@ -187,7 +188,15 @@ def main(): - flags = ParseFlags(sys.argv[1:]) + try: + flags = ParseFlags(sys.argv[1:]) + except FlagParseError as arg_error: + print('makecab.py: error:', arg_error.message, file=sys.stderr) + print('pass --help for usage', file=sys.stderr) + sys.exit(1) + if not flags: # --help got passed + print(__doc__) + sys.exit(0) if not os.path.exists(flags.input): print('makecab.py: error: input file %s does not exist' % flags.input, file=sys.stderr)
diff --git a/chrome/tools/build/win/makecab_test.py b/chrome/tools/build/win/makecab_test.py index 69ac7b3a..782efac 100755 --- a/chrome/tools/build/win/makecab_test.py +++ b/chrome/tools/build/win/makecab_test.py
@@ -3,11 +3,12 @@ # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. -from StringIO import StringIO import makecab -import unittest + +from StringIO import StringIO import sys import time +import unittest # Test flag parsing. class ParseFlagsTest(unittest.TestCase): @@ -35,6 +36,20 @@ self.assertEquals(flags.output, 'd/foo.cab') self.assertEquals(flags.output_dir, 'outdir') + def testHelp(self): + self.assertEquals(makecab.ParseFlags(['foo.txt', '--help']), None) + + def assertFlagParseError(self, flags, expected_message_part): + with self.assertRaises(makecab.FlagParseError) as context: + makecab.ParseFlags(flags) + self.assertIn(expected_message_part, context.exception.message) + + def testErrors(self): + for f in ['/D', '/L']: + self.assertFlagParseError([f], 'argument needed after') + self.assertFlagParseError(['/asdf'], 'unknown flag') + self.assertFlagParseError(['in', 'out', 'what'], 'too many paths') + self.assertFlagParseError([], 'no input file') # Test that compression doesn't throw, and on Windows also check that # expand.exe is able to recover input data. @@ -46,19 +61,17 @@ makecab.WriteCab(output, StringIO(input_data), 'a.txt', len(input_data), mtime) if sys.platform == 'win32': - import os, subprocess, tempfile - cab_handle, cab_path = tempfile.mkstemp(suffix='.makecab_test.cab') - os.write(cab_handle, output.getvalue()) - os.close(cab_handle) - out_handle, out_path = tempfile.mkstemp(suffix='.makecab_test.out') - # Closing out_handle immediately defeats the purpose of mkstemp(), but I - # can't figure out how to write to the temp file on Windows otherwise. - os.close(out_handle) - FNULL = open(os.devnull, 'w') - subprocess.check_call(['expand.exe', cab_path, out_path], stdout=FNULL) - self.assertEquals(input_data, open(out_path, 'rb').read()) - os.remove(cab_path) - os.remove(out_path) + import os, shutil, subprocess, tempfile + temp_dir = tempfile.mkdtemp(suffix='.makecab_test') + try: + cab_path = os.path.join(temp_dir, 'file.cab') + out_path = os.path.join(temp_dir, 'file.out') + open(cab_path, 'wb').write(output.getvalue()) + FNULL = open(os.devnull, 'w') + subprocess.check_call(['expand.exe', cab_path, out_path], stdout=FNULL) + self.assertEquals(input_data, open(out_path, 'rb').read()) + finally: + shutil.rmtree(temp_dir) if __name__ == '__main__':
diff --git a/chromeos/components/tether/synchronous_shutdown_object_container_impl.cc b/chromeos/components/tether/synchronous_shutdown_object_container_impl.cc index bf7f8258..5219388 100644 --- a/chromeos/components/tether/synchronous_shutdown_object_container_impl.cc +++ b/chromeos/components/tether/synchronous_shutdown_object_container_impl.cc
@@ -161,7 +161,8 @@ notification_presenter, host_connection_metrics_logger_.get(), asychronous_container->disconnect_tethering_request_sender(), - asychronous_container->wifi_hotspot_disconnector())), + asychronous_container->wifi_hotspot_disconnector(), + clock_.get())), tether_disconnector_(std::make_unique<TetherDisconnectorImpl>( active_host_.get(), asychronous_container->wifi_hotspot_disconnector(),
diff --git a/chromeos/components/tether/tether_connector_impl.cc b/chromeos/components/tether/tether_connector_impl.cc index 9a53747..90465d6 100644 --- a/chromeos/components/tether/tether_connector_impl.cc +++ b/chromeos/components/tether/tether_connector_impl.cc
@@ -5,6 +5,8 @@ #include "chromeos/components/tether/tether_connector_impl.h" #include "base/bind.h" +#include "base/metrics/histogram_macros.h" +#include "base/time/clock.h" #include "chromeos/components/tether/active_host.h" #include "chromeos/components/tether/device_id_tether_network_guid_map.h" #include "chromeos/components/tether/disconnect_tethering_request_sender.h" @@ -46,7 +48,8 @@ NotificationPresenter* notification_presenter, HostConnectionMetricsLogger* host_connection_metrics_logger, DisconnectTetheringRequestSender* disconnect_tethering_request_sender, - WifiHotspotDisconnector* wifi_hotspot_disconnector) + WifiHotspotDisconnector* wifi_hotspot_disconnector, + base::Clock* clock) : network_state_handler_(network_state_handler), wifi_hotspot_connector_(wifi_hotspot_connector), active_host_(active_host), @@ -59,6 +62,7 @@ host_connection_metrics_logger_(host_connection_metrics_logger), disconnect_tethering_request_sender_(disconnect_tethering_request_sender), wifi_hotspot_disconnector_(wifi_hotspot_disconnector), + clock_(clock), weak_ptr_factory_(this) {} TetherConnectorImpl::~TetherConnectorImpl() { @@ -101,6 +105,7 @@ device_id_pending_connection_ = device_id; success_callback_ = success_callback; error_callback_ = error_callback; + connect_to_host_start_time_ = clock_->Now(); active_host_->SetActiveHostConnecting(device_id, tether_network_guid); tether_host_fetcher_->FetchTetherHost( @@ -297,6 +302,9 @@ host_connection_metrics_logger_->RecordConnectionToHostResult( HostConnectionMetricsLogger::ConnectionToHostResult:: CONNECTION_RESULT_SUCCESS); + UMA_HISTOGRAM_MEDIUM_TIMES( + "InstantTethering.Performance.ConnectToHostDuration", + clock_->Now() - connect_to_host_start_time_); notification_presenter_->RemoveSetupRequiredNotification();
diff --git a/chromeos/components/tether/tether_connector_impl.h b/chromeos/components/tether/tether_connector_impl.h index b4a21939..a7430cd3 100644 --- a/chromeos/components/tether/tether_connector_impl.h +++ b/chromeos/components/tether/tether_connector_impl.h
@@ -12,6 +12,10 @@ #include "chromeos/components/tether/tether_connector.h" #include "chromeos/network/network_connection_handler.h" +namespace base { +class Clock; +} // namespace base + namespace chromeos { class NetworkStateHandler; @@ -49,7 +53,8 @@ NotificationPresenter* notification_presenter, HostConnectionMetricsLogger* host_connection_metrics_logger, DisconnectTetheringRequestSender* disconnect_tethering_request_sender, - WifiHotspotDisconnector* wifi_hotspot_disconnector); + WifiHotspotDisconnector* wifi_hotspot_disconnector, + base::Clock* clock_); ~TetherConnectorImpl() override; void ConnectToNetwork( @@ -103,11 +108,13 @@ HostConnectionMetricsLogger* host_connection_metrics_logger_; DisconnectTetheringRequestSender* disconnect_tethering_request_sender_; WifiHotspotDisconnector* wifi_hotspot_disconnector_; + base::Clock* clock_; std::string device_id_pending_connection_; base::Closure success_callback_; network_handler::StringResultCallback error_callback_; std::unique_ptr<ConnectTetheringOperation> connect_tethering_operation_; + base::Time connect_to_host_start_time_; base::WeakPtrFactory<TetherConnectorImpl> weak_ptr_factory_; DISALLOW_COPY_AND_ASSIGN(TetherConnectorImpl);
diff --git a/chromeos/components/tether/tether_connector_impl_unittest.cc b/chromeos/components/tether/tether_connector_impl_unittest.cc index 36d503d..46766ae 100644 --- a/chromeos/components/tether/tether_connector_impl_unittest.cc +++ b/chromeos/components/tether/tether_connector_impl_unittest.cc
@@ -7,6 +7,8 @@ #include <memory> #include "base/message_loop/message_loop.h" +#include "base/test/histogram_tester.h" +#include "base/test/simple_test_clock.h" #include "chromeos/components/tether/connect_tethering_operation.h" #include "chromeos/components/tether/device_id_tether_network_guid_map.h" #include "chromeos/components/tether/fake_active_host.h" @@ -46,6 +48,8 @@ const char kWifiNetworkGuid[] = "wifiNetworkGuid"; +constexpr base::TimeDelta kConnectToHostTime = base::TimeDelta::FromSeconds(13); + std::string CreateWifiConfigurationJsonString() { std::stringstream ss; ss << "{" @@ -162,6 +166,8 @@ std::make_unique<FakeDisconnectTetheringRequestSender>(); fake_wifi_hotspot_disconnector_ = std::make_unique<FakeWifiHotspotDisconnector>(); + test_clock_ = std::make_unique<base::SimpleTestClock>(); + test_clock_->SetNow(base::Time::UnixEpoch()); result_.clear(); @@ -174,7 +180,7 @@ fake_notification_presenter_.get(), mock_host_connection_metrics_logger_.get(), fake_disconnect_tethering_request_sender_.get(), - fake_wifi_hotspot_disconnector_.get())); + fake_wifi_hotspot_disconnector_.get(), test_clock_.get())); SetUpTetherNetworks(); } @@ -233,6 +239,7 @@ } void SuccessfullyJoinWifiNetwork() { + test_clock_->Advance(kConnectToHostTime); ConfigureService(CreateWifiConfigurationJsonString()); fake_wifi_hotspot_connector_->CallMostRecentCallback(kWifiNetworkGuid); } @@ -296,6 +303,8 @@ GetResultAndReset()); EXPECT_TRUE(fake_notification_presenter_ ->is_connection_failed_notification_shown()); + histogram_tester_.ExpectTotalCount( + "InstantTethering.Performance.ConnectToHostDuration", 0 /* count */); } std::string GetResultAndReset() { @@ -324,8 +333,10 @@ std::unique_ptr<FakeDisconnectTetheringRequestSender> fake_disconnect_tethering_request_sender_; std::unique_ptr<FakeWifiHotspotDisconnector> fake_wifi_hotspot_disconnector_; + std::unique_ptr<base::SimpleTestClock> test_clock_; std::string result_; + base::HistogramTester histogram_tester_; std::unique_ptr<TetherConnectorImpl> tether_connector_; @@ -351,6 +362,8 @@ EXPECT_EQ(NetworkConnectionHandler::kErrorConnectFailed, GetResultAndReset()); EXPECT_TRUE( fake_notification_presenter_->is_connection_failed_notification_shown()); + histogram_tester_.ExpectTotalCount( + "InstantTethering.Performance.ConnectToHostDuration", 0 /* count */); } TEST_F(TetherConnectorImplTest, TestCancelWhileOperationActive) { @@ -386,6 +399,8 @@ fake_disconnect_tethering_request_sender_->device_ids_sent_requests()); EXPECT_FALSE( fake_notification_presenter_->is_connection_failed_notification_shown()); + histogram_tester_.ExpectTotalCount( + "InstantTethering.Performance.ConnectToHostDuration", 0 /* count */); } TEST_F(TetherConnectorImplTest, @@ -509,6 +524,8 @@ EXPECT_EQ(NetworkConnectionHandler::kErrorConnectFailed, GetResultAndReset()); EXPECT_TRUE( fake_notification_presenter_->is_connection_failed_notification_shown()); + histogram_tester_.ExpectTotalCount( + "InstantTethering.Performance.ConnectToHostDuration", 0 /* count */); } TEST_F(TetherConnectorImplTest, TestCancelWhileConnectingToWifi) { @@ -557,6 +574,8 @@ EXPECT_EQ( kWifiNetworkGuid, fake_wifi_hotspot_disconnector_->last_disconnected_wifi_network_guid()); + histogram_tester_.ExpectTotalCount( + "InstantTethering.Performance.ConnectToHostDuration", 0 /* count */); } TEST_F(TetherConnectorImplTest, TestSuccessfulConnection) { @@ -594,6 +613,7 @@ EXPECT_EQ(kPassword, fake_wifi_hotspot_connector_->most_recent_password()); EXPECT_EQ(fake_active_host_->GetTetherNetworkGuid(), fake_wifi_hotspot_connector_->most_recent_tether_network_guid()); + SuccessfullyJoinWifiNetwork(); // The active host should now be connected. @@ -604,6 +624,9 @@ EXPECT_EQ(GetTetherNetworkGuid(test_devices_[0].GetDeviceId()), fake_active_host_->GetTetherNetworkGuid()); EXPECT_EQ(kWifiNetworkGuid, fake_active_host_->GetWifiNetworkGuid()); + histogram_tester_.ExpectTimeBucketCount( + "InstantTethering.Performance.ConnectToHostDuration", kConnectToHostTime, + 1 /* count */); EXPECT_EQ(kSuccessResult, GetResultAndReset()); EXPECT_FALSE( @@ -642,6 +665,9 @@ EXPECT_EQ(kSuccessResult, GetResultAndReset()); EXPECT_FALSE( fake_notification_presenter_->is_connection_failed_notification_shown()); + histogram_tester_.ExpectTimeBucketCount( + "InstantTethering.Performance.ConnectToHostDuration", kConnectToHostTime, + 1 /* count */); } TEST_F(TetherConnectorImplTest, @@ -651,6 +677,10 @@ RecordConnectionToHostResult( HostConnectionMetricsLogger::ConnectionToHostResult:: CONNECTION_RESULT_FAILURE_CLIENT_CONNECTION_CANCELED_BY_USER)); + EXPECT_CALL(*mock_host_connection_metrics_logger_, + RecordConnectionToHostResult( + HostConnectionMetricsLogger::ConnectionToHostResult:: + CONNECTION_RESULT_SUCCESS)); CallConnect(GetTetherNetworkGuid(test_devices_[0].GetDeviceId())); EXPECT_EQ(ActiveHost::ActiveHostStatus::CONNECTING, @@ -664,6 +694,11 @@ // An operation should have been created. EXPECT_EQ(1u, fake_operation_factory_->created_operations().size()); + // Simulate the progression of some time in the connection process. + base::TimeDelta firstConnectToHostAttemptTime = + base::TimeDelta::FromSeconds(7); + test_clock_->Advance(firstConnectToHostAttemptTime); + // Before the created operation replies, start a new connection to device 1. CallConnect(GetTetherNetworkGuid(test_devices_[1].GetDeviceId())); // The first connection attempt should have resulted in a connect canceled @@ -672,6 +707,8 @@ GetResultAndReset()); EXPECT_FALSE( fake_notification_presenter_->is_connection_failed_notification_shown()); + histogram_tester_.ExpectTotalCount( + "InstantTethering.Performance.ConnectToHostDuration", 0 /* count */); // Now, the active host should be the second device. EXPECT_EQ(ActiveHost::ActiveHostStatus::CONNECTING, @@ -701,6 +738,15 @@ EXPECT_EQ(kPassword, fake_wifi_hotspot_connector_->most_recent_password()); EXPECT_EQ(fake_active_host_->GetTetherNetworkGuid(), fake_wifi_hotspot_connector_->most_recent_tether_network_guid()); + + const base::TimeDelta kSecondConnectToHostAttemptAdditionalTime = + base::TimeDelta::FromSeconds(2); + test_clock_->Advance(kSecondConnectToHostAttemptAdditionalTime); + SuccessfullyJoinWifiNetwork(); + histogram_tester_.ExpectTimeBucketCount( + "InstantTethering.Performance.ConnectToHostDuration", + kConnectToHostTime + kSecondConnectToHostAttemptAdditionalTime, + 1 /* count */); } TEST_F(TetherConnectorImplTest, @@ -710,6 +756,10 @@ RecordConnectionToHostResult( HostConnectionMetricsLogger::ConnectionToHostResult:: CONNECTION_RESULT_FAILURE_CLIENT_CONNECTION_CANCELED_BY_USER)); + EXPECT_CALL(*mock_host_connection_metrics_logger_, + RecordConnectionToHostResult( + HostConnectionMetricsLogger::ConnectionToHostResult:: + CONNECTION_RESULT_SUCCESS)); CallConnect(GetTetherNetworkGuid(test_devices_[0].GetDeviceId())); EXPECT_EQ(ActiveHost::ActiveHostStatus::CONNECTING, @@ -749,6 +799,24 @@ EXPECT_EQ(GetTetherNetworkGuid(test_devices_[1].GetDeviceId()), fake_active_host_->GetTetherNetworkGuid()); EXPECT_TRUE(fake_active_host_->GetWifiNetworkGuid().empty()); + histogram_tester_.ExpectTotalCount( + "InstantTethering.Performance.ConnectToHostDuration", 0 /* count */); + + // The second operation replies successfully, and this response should + // result in a Wi-Fi connection attempt. + fake_operation_factory_->created_operations()[1] + ->NotifyConnectTetheringRequestSent(); + fake_operation_factory_->created_operations()[1]->SendSuccessfulResponse( + kSsid, kPassword); + EXPECT_EQ(kSsid, fake_wifi_hotspot_connector_->most_recent_ssid()); + EXPECT_EQ(kPassword, fake_wifi_hotspot_connector_->most_recent_password()); + EXPECT_EQ(fake_active_host_->GetTetherNetworkGuid(), + fake_wifi_hotspot_connector_->most_recent_tether_network_guid()); + + SuccessfullyJoinWifiNetwork(); + histogram_tester_.ExpectTimeBucketCount( + "InstantTethering.Performance.ConnectToHostDuration", + kConnectToHostTime * 2, 1 /* count */); } } // namespace tether
diff --git a/chromeos/network/auto_connect_handler.cc b/chromeos/network/auto_connect_handler.cc index 42476152..1dcdb94 100644 --- a/chromeos/network/auto_connect_handler.cc +++ b/chromeos/network/auto_connect_handler.cc
@@ -54,8 +54,8 @@ client_certs_resolved_(false), applied_autoconnect_policy_(false), connect_to_best_services_after_scan_(false), - weak_ptr_factory_(this) { -} + auto_connect_reasons_(0), + weak_ptr_factory_(this) {} AutoConnectHandler::~AutoConnectHandler() { if (LoginState::IsInitialized()) @@ -106,7 +106,7 @@ // that we just connected. DisconnectIfPolicyRequires(); NET_LOG_DEBUG("RequestBestConnection", "User logged in"); - RequestBestConnection(); + RequestBestConnection(AutoConnectReason::AUTO_CONNECT_REASON_LOGGED_IN); } void AutoConnectHandler::ConnectToNetworkRequested( @@ -137,7 +137,8 @@ DCHECK(managed_networks); if (!managed_networks->empty()) { NET_LOG_DEBUG("RequestBestConnection", "Policy applied"); - RequestBestConnection(); + RequestBestConnection( + AutoConnectReason::AUTO_CONNECT_REASON_POLICY_APPLIED); } else { CheckBestConnection(); } @@ -164,14 +165,30 @@ if (network_properties_changed) { NET_LOG_DEBUG("RequestBestConnection", "Client certificate patterns resolved"); - RequestBestConnection(); + RequestBestConnection( + AutoConnectReason::AUTO_CONNECT_REASON_CERTIFICATE_RESOLVED); } else { CheckBestConnection(); } } -void AutoConnectHandler::RequestBestConnection() { +void AutoConnectHandler::AddObserver(Observer* observer) { + observer_list_.AddObserver(observer); +} + +void AutoConnectHandler::RemoveObserver(Observer* observer) { + observer_list_.RemoveObserver(observer); +} + +void AutoConnectHandler::NotifyAutoConnectInitiated(int auto_connect_reasons) { + for (auto& observer : observer_list_) + observer.OnAutoConnectedInitiated(auto_connect_reasons); +} + +void AutoConnectHandler::RequestBestConnection( + AutoConnectReason auto_connect_reason) { request_best_connection_pending_ = true; + auto_connect_reasons_ |= auto_connect_reason; CheckBestConnection(); } @@ -273,13 +290,15 @@ } } -void AutoConnectHandler::CallShillConnectToBestServices() const { +void AutoConnectHandler::CallShillConnectToBestServices() { NET_LOG_EVENT("ConnectToBestServices", ""); + DBusThreadManager::Get()->GetShillManagerClient()->ConnectToBestServices( - base::Bind(&base::DoNothing), + base::Bind(&AutoConnectHandler::NotifyAutoConnectInitiated, + weak_ptr_factory_.GetWeakPtr(), auto_connect_reasons_), base::Bind(&network_handler::ShillErrorCallbackFunction, - "ConnectToBestServices Failed", - "", network_handler::ErrorCallback())); + "ConnectToBestServices Failed", "", + network_handler::ErrorCallback())); } } // namespace chromeos
diff --git a/chromeos/network/auto_connect_handler.h b/chromeos/network/auto_connect_handler.h index 6d990be..650b9fc 100644 --- a/chromeos/network/auto_connect_handler.h +++ b/chromeos/network/auto_connect_handler.h
@@ -9,6 +9,7 @@ #include "base/macros.h" #include "base/memory/weak_ptr.h" +#include "base/observer_list.h" #include "chromeos/chromeos_export.h" #include "chromeos/login/login_state.h" #include "chromeos/network/client_cert_resolver.h" @@ -25,6 +26,19 @@ public NetworkStateHandlerObserver, public ClientCertResolver::Observer { public: + enum AutoConnectReason { + AUTO_CONNECT_REASON_LOGGED_IN = 1, + AUTO_CONNECT_REASON_POLICY_APPLIED = 1 << 1, + AUTO_CONNECT_REASON_CERTIFICATE_RESOLVED = 1 << 2 + }; + + class Observer { + public: + // Note: |auto_connect_reasons| is computed by applying the bitwise OR + // operation to all AutoConnectReasons which triggered auto-connect. + virtual void OnAutoConnectedInitiated(int auto_connect_reasons) = 0; + }; + ~AutoConnectHandler() override; // LoginState::Observer @@ -43,9 +57,16 @@ // ClientCertResolver::Observer void ResolveRequestCompleted(bool network_properties_changed) override; + void AddObserver(Observer* observer); + void RemoveObserver(Observer* observer); + + protected: + void NotifyAutoConnectInitiated(int auto_connect_reasons); + private: friend class NetworkHandler; friend class AutoConnectHandlerTest; + friend class AutoConnectNotifierTest; AutoConnectHandler(); @@ -71,7 +92,7 @@ // Requests and if possible connects to the 'best' available network, see // CheckBestConnection(). - void RequestBestConnection(); + void RequestBestConnection(AutoConnectReason auto_connect_reason); // If a request to connect to the best network is pending and all requirements // are fulfilled (like policy loaded, certificate patterns being resolved), @@ -79,7 +100,7 @@ void CheckBestConnection(); // Calls Shill.Manager.ConnectToBestServices(). - void CallShillConnectToBestServices() const; + void CallShillConnectToBestServices(); // Local references to the associated handler instances. ClientCertResolver* client_cert_resolver_; @@ -112,6 +133,12 @@ // When true, trigger ConnectToBestServices after the next scan completion. bool connect_to_best_services_after_scan_; + // The bitwise OR of all AutoConnectReason which have triggered auto- + // connection. + int auto_connect_reasons_; + + base::ObserverList<Observer> observer_list_; + base::WeakPtrFactory<AutoConnectHandler> weak_ptr_factory_; DISALLOW_COPY_AND_ASSIGN(AutoConnectHandler);
diff --git a/chromeos/network/auto_connect_handler_unittest.cc b/chromeos/network/auto_connect_handler_unittest.cc index f957c1fd..9e82629c 100644 --- a/chromeos/network/auto_connect_handler_unittest.cc +++ b/chromeos/network/auto_connect_handler_unittest.cc
@@ -37,6 +37,26 @@ namespace { +class TestAutoConnectHandlerObserver : public AutoConnectHandler::Observer { + public: + TestAutoConnectHandlerObserver() = default; + virtual ~TestAutoConnectHandlerObserver() = default; + + int num_auto_connect_events() { return num_auto_connect_events_; } + + int auto_connect_reasons() { return auto_connect_reasons_; } + + // AutoConnectHandler::Observer: + void OnAutoConnectedInitiated(int auto_connect_reasons) override { + ++num_auto_connect_events_; + auto_connect_reasons_ = auto_connect_reasons; + } + + private: + int num_auto_connect_events_ = 0; + int auto_connect_reasons_ = 0; +}; + class TestCertResolveObserver : public ClientCertResolver::Observer { public: explicit TestCertResolveObserver(ClientCertResolver* cert_resolver) @@ -143,6 +163,9 @@ client_cert_resolver_.get(), test_network_connection_handler_.get(), network_state_handler(), managed_config_handler_.get()); + test_observer_.reset(new TestAutoConnectHandlerObserver()); + auto_connect_handler_->AddObserver(test_observer_.get()); + scoped_task_environment_.RunUntilIdle(); } @@ -248,6 +271,7 @@ std::unique_ptr<NetworkProfileHandler> network_profile_handler_; crypto::ScopedTestNSSDB test_nssdb_; std::unique_ptr<net::NSSCertDatabaseChromeOS> test_nsscertdb_; + std::unique_ptr<TestAutoConnectHandlerObserver> test_observer_; private: DISALLOW_COPY_AND_ASSIGN(AutoConnectHandlerTest); @@ -322,6 +346,10 @@ StartCertLoader(); EXPECT_EQ(shill::kStateIdle, GetServiceState("wifi0")); EXPECT_EQ(shill::kStateOnline, GetServiceState("wifi1")); + EXPECT_EQ(1, test_observer_->num_auto_connect_events()); + EXPECT_EQ(AutoConnectHandler::AUTO_CONNECT_REASON_LOGGED_IN | + AutoConnectHandler::AUTO_CONNECT_REASON_POLICY_APPLIED, + test_observer_->auto_connect_reasons()); } TEST_F(AutoConnectHandlerTest, ReconnectOnCertPatternResolved) { @@ -337,6 +365,11 @@ SetupPolicy(kPolicyCertPattern, base::DictionaryValue(), // no global config true); // load as user policy + EXPECT_EQ(2, test_observer_->num_auto_connect_events()); + EXPECT_EQ(AutoConnectHandler::AUTO_CONNECT_REASON_LOGGED_IN | + AutoConnectHandler::AUTO_CONNECT_REASON_POLICY_APPLIED | + AutoConnectHandler::AUTO_CONNECT_REASON_CERTIFICATE_RESOLVED, + test_observer_->auto_connect_reasons()); EXPECT_EQ(shill::kStateOnline, GetServiceState("wifi0")); EXPECT_EQ(shill::kStateIdle, GetServiceState("wifi1")); @@ -352,6 +385,11 @@ EXPECT_EQ(shill::kStateIdle, GetServiceState("wifi0")); EXPECT_EQ(shill::kStateOnline, GetServiceState("wifi1")); + EXPECT_EQ(3, test_observer_->num_auto_connect_events()); + EXPECT_EQ(AutoConnectHandler::AUTO_CONNECT_REASON_LOGGED_IN | + AutoConnectHandler::AUTO_CONNECT_REASON_POLICY_APPLIED | + AutoConnectHandler::AUTO_CONNECT_REASON_CERTIFICATE_RESOLVED, + test_observer_->auto_connect_reasons()); } // Ensure that resolving of certificate patterns only triggers a reconnect if at @@ -383,6 +421,10 @@ EXPECT_EQ(shill::kStateOnline, GetServiceState("wifi0")); EXPECT_EQ(shill::kStateIdle, GetServiceState("wifi1")); + EXPECT_EQ(1, test_observer_->num_auto_connect_events()); + EXPECT_EQ(AutoConnectHandler::AUTO_CONNECT_REASON_LOGGED_IN | + AutoConnectHandler::AUTO_CONNECT_REASON_POLICY_APPLIED, + test_observer_->auto_connect_reasons()); } TEST_F(AutoConnectHandlerTest, DisconnectOnPolicyLoading) { @@ -414,6 +456,7 @@ SetupPolicy(std::string(), base::DictionaryValue(), true); EXPECT_EQ(shill::kStateIdle, GetServiceState("wifi0")); EXPECT_EQ(shill::kStateIdle, GetServiceState("wifi1")); + EXPECT_EQ(0, test_observer_->num_auto_connect_events()); } TEST_F(AutoConnectHandlerTest, @@ -446,6 +489,7 @@ SetupPolicy(std::string(), base::DictionaryValue(), true); EXPECT_EQ(shill::kStateIdle, GetServiceState("wifi0")); EXPECT_EQ(shill::kStateIdle, GetServiceState("wifi1")); + EXPECT_EQ(0, test_observer_->num_auto_connect_events()); } // After login a reconnect is triggered even if there is no managed network. @@ -476,6 +520,9 @@ true); // load as user policy EXPECT_EQ(shill::kStateIdle, GetServiceState("wifi0")); EXPECT_EQ(shill::kStateOnline, GetServiceState("wifi1")); + EXPECT_EQ(1, test_observer_->num_auto_connect_events()); + EXPECT_EQ(AutoConnectHandler::AUTO_CONNECT_REASON_LOGGED_IN, + test_observer_->auto_connect_reasons()); } TEST_F(AutoConnectHandlerTest, ManualConnectAbortsReconnectAfterLogin) { @@ -505,6 +552,7 @@ true); // load as user policy EXPECT_EQ(shill::kStateOnline, GetServiceState("wifi0")); EXPECT_EQ(shill::kStateIdle, GetServiceState("wifi1")); + EXPECT_EQ(0, test_observer_->num_auto_connect_events()); } } // namespace chromeos
diff --git a/chromeos/network/network_state_handler.cc b/chromeos/network/network_state_handler.cc index 128993b0..506e964 100644 --- a/chromeos/network/network_state_handler.cc +++ b/chromeos/network/network_state_handler.cc
@@ -1263,8 +1263,10 @@ if (!default_network_path_.empty()) { const NetworkState* default_network = GetNetworkState(default_network_path_); - if (default_network && default_network->device_path() == path) + if (default_network && default_network->device_path() == path) { + NotifyNetworkPropertiesUpdated(default_network); NotifyDefaultNetworkChanged(default_network); + } } } }
diff --git a/components/arc/common/notifications.mojom b/components/arc/common/notifications.mojom index b63bde26..ee6475d 100644 --- a/components/arc/common/notifications.mojom +++ b/components/arc/common/notifications.mojom
@@ -2,7 +2,7 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // -// Next MinVersion: 15 +// Next MinVersion: 16 module arc.mojom; @@ -135,6 +135,8 @@ // of the notification. [MinVersion=14] Rect? swipe_input_rect; + [MinVersion=15] + string? package_name; }; [MinVersion=2]
diff --git a/components/autofill/content/renderer/password_autofill_agent.cc b/components/autofill/content/renderer/password_autofill_agent.cc index d2b003f..ebfdd46 100644 --- a/components/autofill/content/renderer/password_autofill_agent.cc +++ b/components/autofill/content/renderer/password_autofill_agent.cc
@@ -399,6 +399,13 @@ } else { // Scan additional logins for a match. for (const auto& it : fill_data.additional_logins) { + if (!it.second.realm.empty()) { + // Non-empty realm means PSL match. Do not autofill PSL matched + // credentials. The reason for this is that PSL matched sites are + // different sites, so a password for a PSL matched site should be never + // filled without explicit user selection. + continue; + } if (DoUsernamesMatch(it.first, current_username, exact_username_match)) { *username = it.first; *password = it.second.password;
diff --git a/components/autofill/content/renderer/password_form_conversion_utils.cc b/components/autofill/content/renderer/password_form_conversion_utils.cc index abb165f1..9b14427 100644 --- a/components/autofill/content/renderer/password_form_conversion_utils.cc +++ b/components/autofill/content/renderer/password_form_conversion_utils.cc
@@ -678,30 +678,26 @@ LocateSpecificPasswords(passwords, &password, &new_password, &confirmation_password); - if (base::FeatureList::IsEnabled( - password_manager::features::kEnablePasswordSelection)) { - bool form_has_autofilled_value = false; - // Add non-empty unique possible passwords to the vector. - std::vector<base::string16> all_possible_passwords; - for (const WebInputElement& password_element : - passwords_without_heuristics) { - const base::string16 value = password_element.Value().Utf16(); - if (value.empty()) - continue; - bool element_has_autofilled_value = FieldHasPropertiesMask( - field_value_and_properties_map, password_element, - FieldPropertiesFlags::AUTOFILLED); - form_has_autofilled_value |= element_has_autofilled_value; - if (find(all_possible_passwords.begin(), all_possible_passwords.end(), - value) == all_possible_passwords.end()) { - all_possible_passwords.push_back(std::move(value)); - } + bool form_has_autofilled_value = false; + // Add non-empty unique possible passwords to the vector. + std::vector<base::string16> all_possible_passwords; + for (const WebInputElement& password_element : passwords_without_heuristics) { + const base::string16 value = password_element.Value().Utf16(); + if (value.empty()) + continue; + bool element_has_autofilled_value = + FieldHasPropertiesMask(field_value_and_properties_map, password_element, + FieldPropertiesFlags::AUTOFILLED); + form_has_autofilled_value |= element_has_autofilled_value; + if (find(all_possible_passwords.begin(), all_possible_passwords.end(), + value) == all_possible_passwords.end()) { + all_possible_passwords.push_back(std::move(value)); } + } - if (!all_possible_passwords.empty()) { - password_form->all_possible_passwords = std::move(all_possible_passwords); - password_form->form_has_autofilled_value = form_has_autofilled_value; - } + if (!all_possible_passwords.empty()) { + password_form->all_possible_passwords = std::move(all_possible_passwords); + password_form->form_has_autofilled_value = form_has_autofilled_value; } // Base heuristic for username detection.
diff --git a/components/autofill/content/renderer/password_form_conversion_utils_browsertest.cc b/components/autofill/content/renderer/password_form_conversion_utils_browsertest.cc index 08e1c2f..961cb49 100644 --- a/components/autofill/content/renderer/password_form_conversion_utils_browsertest.cc +++ b/components/autofill/content/renderer/password_form_conversion_utils_browsertest.cc
@@ -1796,10 +1796,6 @@ } TEST_F(MAYBE_PasswordFormConversionUtilsTest, SetOtherPossiblePasswords) { - base::test::ScopedFeatureList feature_list; - feature_list.InitAndEnableFeature( - password_manager::features::kEnablePasswordSelection); - PasswordFormBuilder builder(kTestFormActionURL); builder.AddTextField("username1", "John", nullptr); builder.AddPasswordField("password1", "alpha1", nullptr); @@ -1829,10 +1825,6 @@ TEST_F(MAYBE_PasswordFormConversionUtilsTest, AllPossiblePasswordsIncludeAutofilledValue) { - base::test::ScopedFeatureList feature_list; - feature_list.InitAndEnableFeature( - password_manager::features::kEnablePasswordSelection); - for (bool autofilled_value_was_modified_by_user : {false, true}) { PasswordFormBuilder builder(kTestFormActionURL); builder.AddTextField("username1", "John", nullptr);
diff --git a/components/autofill/core/browser/address_normalizer_impl_unittest.cc b/components/autofill/core/browser/address_normalizer_impl_unittest.cc index bf96e4e..26d534e 100644 --- a/components/autofill/core/browser/address_normalizer_impl_unittest.cc +++ b/components/autofill/core/browser/address_normalizer_impl_unittest.cc
@@ -260,6 +260,39 @@ AutofillProfile profile = autofill::test::GetFullProfile(); profile.SetRawInfo(PHONE_HOME_WHOLE_NUMBER, + base::UTF8ToUTF16("(515) 223-1234")); + profile.SetRawInfo(ADDRESS_HOME_STATE, base::ASCIIToUTF16("California")); + const std::string kCountryCode = + base::UTF16ToUTF8(profile.GetRawInfo(ADDRESS_HOME_COUNTRY)); + + // Load the rules. + normalizer()->LoadRulesForRegion(kCountryCode); + EXPECT_TRUE(AreRulesLoadedForRegion(kCountryCode)); + + // Do the normalization. + normalizer()->NormalizeAddressAsync( + profile, /*timeout_seconds=*/5, + base::BindOnce(&AddressNormalizerTest::OnAddressNormalized, + base::Unretained(this))); + + // Expect that the phone number was formatted and address normalizer + EXPECT_TRUE(normalization_successful()); + EXPECT_EQ( + "+15152231234", + base::UTF16ToUTF8(result_profile().GetRawInfo(PHONE_HOME_WHOLE_NUMBER))); + EXPECT_EQ("CA", + base::UTF16ToUTF8(result_profile().GetRawInfo(ADDRESS_HOME_STATE))); +} + +// Tests that the invalid but possible phone number is minimumly formatted(not +// to E164 but simply having non-digit letters stripped) when the address is +// normalized. +TEST_F(AddressNormalizerTest, FormatInvalidPhone_AddressNormalizedAsync) { + WaitForAddressValidatorInitialization(); + + AutofillProfile profile = autofill::test::GetFullProfile(); + // The number below is not a valid US number. + profile.SetRawInfo(PHONE_HOME_WHOLE_NUMBER, base::UTF8ToUTF16("(515) 123-1234")); profile.SetRawInfo(ADDRESS_HOME_STATE, base::ASCIIToUTF16("California")); const std::string kCountryCode = @@ -278,7 +311,7 @@ // Expect that the phone number was formatted and address normalizer EXPECT_TRUE(normalization_successful()); EXPECT_EQ( - "+15151231234", + "5151231234", base::UTF16ToUTF8(result_profile().GetRawInfo(PHONE_HOME_WHOLE_NUMBER))); EXPECT_EQ("CA", base::UTF16ToUTF8(result_profile().GetRawInfo(ADDRESS_HOME_STATE))); @@ -292,7 +325,7 @@ AutofillProfile profile = autofill::test::GetFullProfile(); profile.SetRawInfo(ADDRESS_HOME_STATE, base::ASCIIToUTF16("California")); profile.SetRawInfo(PHONE_HOME_WHOLE_NUMBER, - base::UTF8ToUTF16("515-123-1234")); + base::UTF8ToUTF16("515-223-1234")); // Make sure the rules will not be loaded in the NormalizeAddressAsync // call. @@ -312,7 +345,7 @@ // Expect that the phone number was formatted. EXPECT_EQ( - "+15151231234", + "+15152231234", base::UTF16ToUTF8(result_profile().GetRawInfo(PHONE_HOME_WHOLE_NUMBER))); EXPECT_EQ("California", base::UTF16ToUTF8(result_profile().GetRawInfo(ADDRESS_HOME_STATE))); @@ -326,7 +359,7 @@ AutofillProfile profile = autofill::test::GetFullProfile(); profile.SetRawInfo(ADDRESS_HOME_STATE, base::ASCIIToUTF16("California")); profile.SetRawInfo(PHONE_HOME_WHOLE_NUMBER, - base::UTF8ToUTF16("515-123-1234")); + base::UTF8ToUTF16("515-223-1234")); // Do the normalization. EXPECT_FALSE(normalizer()->NormalizeAddressSync(&profile)); @@ -336,7 +369,7 @@ EXPECT_EQ("California", base::UTF16ToUTF8(profile.GetRawInfo(ADDRESS_HOME_STATE))); // Phone number is still formatted. - EXPECT_EQ("+15151231234", + EXPECT_EQ("+15152231234", base::UTF16ToUTF8(profile.GetRawInfo(PHONE_HOME_WHOLE_NUMBER))); } @@ -348,7 +381,7 @@ AutofillProfile profile = autofill::test::GetFullProfile(); profile.SetRawInfo(ADDRESS_HOME_STATE, base::ASCIIToUTF16("California")); profile.SetRawInfo(PHONE_HOME_WHOLE_NUMBER, - base::UTF8ToUTF16("515-123-1234")); + base::UTF8ToUTF16("515-223-1234")); const std::string kCountryCode = base::UTF16ToUTF8(profile.GetRawInfo(ADDRESS_HOME_COUNTRY)); @@ -362,7 +395,7 @@ // The rules were loaded before the call to NormalizeAddressSync. // Normalization succeeds. EXPECT_EQ("CA", base::UTF16ToUTF8(profile.GetRawInfo(ADDRESS_HOME_STATE))); - EXPECT_EQ("+15151231234", + EXPECT_EQ("+15152231234", base::UTF16ToUTF8(profile.GetRawInfo(PHONE_HOME_WHOLE_NUMBER))); } @@ -373,7 +406,7 @@ AutofillProfile profile = autofill::test::GetFullProfile(); profile.SetRawInfo(ADDRESS_HOME_STATE, base::ASCIIToUTF16("California")); profile.SetRawInfo(PHONE_HOME_WHOLE_NUMBER, - base::UTF8ToUTF16("515-123-1234")); + base::UTF8ToUTF16("515-223-1234")); const std::string kCountryCode = base::UTF16ToUTF8(profile.GetRawInfo(ADDRESS_HOME_COUNTRY)); @@ -387,7 +420,7 @@ // Normalization will succeed the next time. EXPECT_TRUE(normalizer()->NormalizeAddressSync(&profile)); EXPECT_EQ("CA", base::UTF16ToUTF8(profile.GetRawInfo(ADDRESS_HOME_STATE))); - EXPECT_EQ("+15151231234", + EXPECT_EQ("+15152231234", base::UTF16ToUTF8(profile.GetRawInfo(PHONE_HOME_WHOLE_NUMBER))); }
diff --git a/components/autofill/core/browser/phone_number_i18n.cc b/components/autofill/core/browser/phone_number_i18n.cc index 06e7e5b..6fdd966 100644 --- a/components/autofill/core/browser/phone_number_i18n.cc +++ b/components/autofill/core/browser/phone_number_i18n.cc
@@ -46,24 +46,6 @@ return AutofillCountry::CountryCodeForLocale(app_locale); } -// Returns true if |phone_number| is a possible number. -bool IsPossiblePhoneNumber( - const ::i18n::phonenumbers::PhoneNumber& phone_number) { - PhoneNumberUtil* phone_util = PhoneNumberUtil::GetInstance(); - return phone_util->IsPossibleNumber(phone_number); -} - -bool IsPossiblePhoneNumber(const std::string& phone_number, - const std::string& country_code) { - ::i18n::phonenumbers::PhoneNumber parsed_number; - PhoneNumberUtil* phone_util = PhoneNumberUtil::GetInstance(); - auto result = phone_util->ParseAndKeepRawInput(phone_number, country_code, - &parsed_number); - - return result == ::i18n::phonenumbers::PhoneNumberUtil::NO_PARSING_ERROR && - phone_util->IsPossibleNumber(parsed_number); -} - // Formats the given |number| as a human-readable string, and writes the result // into |formatted_number|. Also, normalizes the formatted number, and writes // that result into |normalized_number|. This function should only be called @@ -111,6 +93,35 @@ namespace i18n { +// Returns true if |phone_number| is a possible number. +bool IsPossiblePhoneNumber( + const ::i18n::phonenumbers::PhoneNumber& phone_number) { + PhoneNumberUtil* phone_util = PhoneNumberUtil::GetInstance(); + return phone_util->IsPossibleNumber(phone_number); +} + +bool IsPossiblePhoneNumber(const std::string& phone_number, + const std::string& country_code) { + ::i18n::phonenumbers::PhoneNumber parsed_number; + PhoneNumberUtil* phone_util = PhoneNumberUtil::GetInstance(); + auto result = phone_util->ParseAndKeepRawInput(phone_number, country_code, + &parsed_number); + + return result == ::i18n::phonenumbers::PhoneNumberUtil::NO_PARSING_ERROR && + phone_util->IsPossibleNumber(parsed_number); +} + +bool IsValidPhoneNumber(const std::string& phone_number, + const std::string& country_code) { + ::i18n::phonenumbers::PhoneNumber parsed_number; + PhoneNumberUtil* phone_util = PhoneNumberUtil::GetInstance(); + auto result = phone_util->ParseAndKeepRawInput(phone_number, country_code, + &parsed_number); + + return result == ::i18n::phonenumbers::PhoneNumberUtil::NO_PARSING_ERROR && + phone_util->IsValidNumber(parsed_number); +} + // Parses the number stored in |value| as it should be interpreted in the given // |default_region|, and stores the results into the remaining arguments. // The |default_region| should be sanitized prior to calling this function. @@ -272,24 +283,37 @@ // being a valid number. const std::string country_code = autofill::data_util::GetCountryCodeWithFallback(profile, locale); - if (IsPossiblePhoneNumber(tentative_intl_phone, country_code)) { + if (IsValidPhoneNumber(tentative_intl_phone, country_code)) { return base::UTF8ToUTF16( - FormatPhoneForDisplay(tentative_intl_phone, country_code)); + FormatPhoneNumber(tentative_intl_phone, country_code, + PhoneNumberUtil::PhoneNumberFormat::INTERNATIONAL)); } - return base::UTF8ToUTF16(FormatPhoneForDisplay(phone, country_code)); + if (IsValidPhoneNumber(phone, country_code)) { + return base::UTF8ToUTF16( + FormatPhoneNumber(phone, country_code, + PhoneNumberUtil::PhoneNumberFormat::INTERNATIONAL)); + } + + return base::UTF8ToUTF16(phone); } std::string FormatPhoneForDisplay(const std::string& phone_number, const std::string& country_code) { - return FormatPhoneNumber(phone_number, country_code, - PhoneNumberUtil::PhoneNumberFormat::INTERNATIONAL); + if (IsValidPhoneNumber(phone_number, country_code)) { + return FormatPhoneNumber(phone_number, country_code, + PhoneNumberUtil::PhoneNumberFormat::INTERNATIONAL); + } + return phone_number; } std::string FormatPhoneForResponse(const std::string& phone_number, const std::string& country_code) { - return FormatPhoneNumber(phone_number, country_code, - PhoneNumberUtil::PhoneNumberFormat::E164); + if (IsValidPhoneNumber(phone_number, country_code)) { + return FormatPhoneNumber(phone_number, country_code, + PhoneNumberUtil::PhoneNumberFormat::E164); + } + return phone_number; } PhoneObject::PhoneObject(const base::string16& number,
diff --git a/components/autofill/core/browser/phone_number_i18n.h b/components/autofill/core/browser/phone_number_i18n.h index 5baa44a..72500a4 100644 --- a/components/autofill/core/browser/phone_number_i18n.h +++ b/components/autofill/core/browser/phone_number_i18n.h
@@ -15,8 +15,8 @@ namespace i18n { namespace phonenumbers { class PhoneNumber; -} -} +} // namespace phonenumbers +} // namespace i18n namespace autofill { @@ -25,6 +25,20 @@ // Utilities to process, normalize and compare international phone numbers. namespace i18n { +// Return true if the given |phone_number| object is likely to be a phone number +// This method uses IsPossibleNumber from libphonenumber, instead of +// IsValidNumber. IsPossibleNumber does a less strict check, it will not try to +// check for carrier code validility. +bool IsPossiblePhoneNumber( + const ::i18n::phonenumbers::PhoneNumber& phone_number); + +// Return true if the given |phone_number| is likely to be a phone number for +// the |country_code|. This method uses IsPossibleNumber from libphonenumber, +// instead of IsValidNumber. IsPossibleNumber does a less strict check, it +// will not try to check for carrier code validility. +bool IsPossiblePhoneNumber(const std::string& phone_number, + const std::string& country_code); + // Most of the following functions require |region| to operate. The |region| is // a ISO 3166 standard code ("US" for USA, "CZ" for Czech Republic, etc.). @@ -35,14 +49,14 @@ // |default_region| if |value| has an international country code, for example). // This is an internal function, exposed in the header file so that it can be // tested. -bool ParsePhoneNumber( - const base::string16& value, - const std::string& default_region, - base::string16* country_code, - base::string16* city_code, - base::string16* number, - std::string* inferred_region, - ::i18n::phonenumbers::PhoneNumber* i18n_number) WARN_UNUSED_RESULT; +bool ParsePhoneNumber(const base::string16& value, + const std::string& default_region, + base::string16* country_code, + base::string16* city_code, + base::string16* number, + std::string* inferred_region, + ::i18n::phonenumbers::PhoneNumber* i18n_number) + WARN_UNUSED_RESULT; // Normalizes phone number, by changing digits in the extended fonts // (such as \xFF1x) into '0'-'9'. Also strips out non-digit characters. @@ -71,6 +85,9 @@ const std::string& app_locale); // Returns the phone number from the given |profile| formatted for display. +// If it's valid number for the country of profile, or for the |locale| given +// as a fall back, return the number in internaional format; otherwise return +// the raw number string from profile. base::string16 GetFormattedPhoneNumberForDisplay(const AutofillProfile& profile, const std::string& locale); @@ -85,14 +102,15 @@ // i18n::phonenumbers::PhoneNumberUtil::Format, as defined in the Payment // Request spec // (https://w3c.github.io/browser-payment-api/#paymentrequest-updated-algorithm) +// if the number is a valid number for the given country code. +// Returns the given_number without formatting if the number is invalid. std::string FormatPhoneForResponse(const std::string& phone_number, const std::string& country_code); // The cached phone number, does parsing only once, improves performance. class PhoneObject { public: - PhoneObject(const base::string16& number, - const std::string& default_region); + PhoneObject(const base::string16& number, const std::string& default_region); PhoneObject(const PhoneObject&); PhoneObject(); ~PhoneObject();
diff --git a/components/autofill/core/browser/phone_number_i18n_unittest.cc b/components/autofill/core/browser/phone_number_i18n_unittest.cc index 7bdba17..7f5a368 100644 --- a/components/autofill/core/browser/phone_number_i18n_unittest.cc +++ b/components/autofill/core/browser/phone_number_i18n_unittest.cc
@@ -234,17 +234,26 @@ // Tests that the phone numbers are correctly formatted for the Payment // Response. TEST(PhoneNumberUtilTest, FormatPhoneForResponse) { - EXPECT_EQ("+15151231234", - i18n::FormatPhoneForResponse("(515) 123-1234", "US")); - EXPECT_EQ("+15151231234", - i18n::FormatPhoneForResponse("(1) 515-123-1234", "US")); + EXPECT_EQ("+15152231234", + i18n::FormatPhoneForResponse("(515) 223-1234", "US")); + EXPECT_EQ("+15152231234", + i18n::FormatPhoneForResponse("(1) 515-223-1234", "US")); EXPECT_EQ("+33142685300", i18n::FormatPhoneForResponse("1 42 68 53 00", "FR")); + + // Invalid numbers are not formatted. + EXPECT_EQ("(515) 123-1234", + i18n::FormatPhoneForResponse("(515) 123-1234", "US")); + EXPECT_EQ("(1) 515-123-1234", + i18n::FormatPhoneForResponse("(1) 515-123-1234", "US")); } // Tests that the phone numbers are correctly formatted to display to the user. TEST(PhoneNumberUtilTest, FormatPhoneForDisplay) { - EXPECT_EQ("+1 515-123-1234", i18n::FormatPhoneForDisplay("5151231234", "US")); + // Invalid number is not formatted. + EXPECT_EQ("5151231234", i18n::FormatPhoneForDisplay("5151231234", "US")); + // Valid number is formatted. + EXPECT_EQ("+1 515-223-1234", i18n::FormatPhoneForDisplay("5152231234", "US")); EXPECT_EQ("+33 1 42 68 53 00", i18n::FormatPhoneForDisplay("142685300", "FR")); } @@ -317,8 +326,11 @@ PhoneNumberFormatCase("+1 415-555-5555", "AU", "+1 415-555-5555"), PhoneNumberFormatCase("1 415-555-5555", "AU", "+1 415-555-5555"), // Without a country code, the phone is formatted for the profile's - // country, even if it's invalid. - PhoneNumberFormatCase("415-555-5555", "AU", "+61 4155555555"), + // country, if it's valid. + PhoneNumberFormatCase("2 9374 4000", "AU", "+61 2 9374 4000"), + // Without a country code, formatting returns the number as entered by + // user, if it's invalid. + PhoneNumberFormatCase("415-555-5555", "AU", "4155555555"), ////////////////////////// // US phone in MX. @@ -355,12 +367,13 @@ PhoneNumberFormatCase("61 2 9374 4000", "US", "+61 2 9374 4000"), // Without a country code, the phone is formatted for the profile's // country. - // This local AU number fits the length of a US number, so it's - // formatted for US. - PhoneNumberFormatCase("02 9374 4000", "US", "+1 029-374-4000"), - // This local AU number is formatted as an US number, even if it's - // invlaid. - PhoneNumberFormatCase("2 9374 4000", "US", "+1 293744000"), + // This local AU number is associated with US profile, the number is + // not a valid US number, therefore formatting will just return what + // user entered. + PhoneNumberFormatCase("02 9374 4000", "US", "0293744000"), + // This local GR(Greece) number is formatted as an US number, if it's + // valid US number. + PhoneNumberFormatCase("22 6800 0090", "US", "+1 226-800-0090"), ////////////////////////// // MX phone in MX. @@ -381,8 +394,8 @@ // number. PhoneNumberFormatCase("+52 55 5342 8400", "US", "+52 55 5342 8400"), PhoneNumberFormatCase("52 55 5342 8400", "US", "+52 55 5342 8400"), - // This number will be recognized as a BR(55) number. - PhoneNumberFormatCase("55 5342 8400", "US", "+55 53428400"))); + // This number is not a valid US number, we won't try to format. + PhoneNumberFormatCase("55 5342 8400", "US", "5553428400"))); INSTANTIATE_TEST_CASE_P( GetFormattedPhoneNumberForDisplay_EdgeCases, @@ -397,10 +410,18 @@ "+52 55 5342 8400", "es_MX"), PhoneNumberFormatCase("55 5342 8400", "", "+52 55 5342 8400", "es_MX"), - PhoneNumberFormatCase("55 5342 8400", "", "+55 53428400", "en_US"), PhoneNumberFormatCase("61 2 9374 4000", "", "+61 2 9374 4000", "en_AU"), PhoneNumberFormatCase("02 9374 4000", "", "+61 2 9374 4000", "en_AU"), + // Numbers in local format yet are invalid with user locale, user might + // be trying to enter a foreign number, calling formatting will just + // return what the user entered. + PhoneNumberFormatCase("55 5342 8400", "", "5553428400", "en_US"), + PhoneNumberFormatCase("55 5342 8400", "", "5553428400"), + PhoneNumberFormatCase("226 123 1234", "", "2261231234", "en_US"), + PhoneNumberFormatCase("293744000", "", "293744000"), + PhoneNumberFormatCase("02 9374 4000", "", "0293744000"), + ////////////////////////// // No country or locale. ////////////////////////// @@ -408,10 +429,7 @@ PhoneNumberFormatCase("61 2 9374 4000", "", "+61 2 9374 4000"), PhoneNumberFormatCase("52 55 5342 8400", "", "+52 55 5342 8400"), PhoneNumberFormatCase("1 415 555 5555", "", "+1 415-555-5555"), - PhoneNumberFormatCase("55 5342 8400", "", "+55 53428400"), // If no country code is found, formats for US. - PhoneNumberFormatCase("02 9374 4000", "", "+1 029-374-4000"), - PhoneNumberFormatCase("2 9374 4000", "", "+1 293744000"), PhoneNumberFormatCase("415-555-5555", "", "+1 415-555-5555"))); } // namespace autofill
diff --git a/components/autofill/core/browser/validation.cc b/components/autofill/core/browser/validation.cc index a2940bf..299fe00 100644 --- a/components/autofill/core/browser/validation.cc +++ b/components/autofill/core/browser/validation.cc
@@ -15,12 +15,12 @@ #include "components/autofill/core/browser/autofill_data_util.h" #include "components/autofill/core/browser/credit_card.h" #include "components/autofill/core/browser/personal_data_manager.h" +#include "components/autofill/core/browser/phone_number_i18n.h" #include "components/autofill/core/browser/state_names.h" #include "components/autofill/core/common/autofill_clock.h" #include "components/autofill/core/common/autofill_regex_constants.h" #include "components/autofill/core/common/autofill_regexes.h" #include "components/strings/grit/components_strings.h" -#include "third_party/libphonenumber/phonenumber_api.h" #include "ui/base/l10n/l10n_util.h" namespace autofill { @@ -91,8 +91,7 @@ int sum = 0; bool odd = false; for (base::string16::reverse_iterator iter = number.rbegin(); - iter != number.rend(); - ++iter) { + iter != number.rend(); ++iter) { if (!base::IsAsciiDigit(*iter)) return false; @@ -217,18 +216,9 @@ !state_names::GetNameForAbbreviation(text).empty(); } -bool IsValidPhoneNumber(const base::string16& text, - const std::string& country_code) { - ::i18n::phonenumbers::PhoneNumber parsed_number; - ::i18n::phonenumbers::PhoneNumberUtil* phone_number_util = - ::i18n::phonenumbers::PhoneNumberUtil::GetInstance(); - if (phone_number_util->Parse(base::UTF16ToUTF8(text), country_code, - &parsed_number) != - ::i18n::phonenumbers::PhoneNumberUtil::NO_PARSING_ERROR) { - return false; - } - - return phone_number_util->IsValidNumber(parsed_number); +bool IsPossiblePhoneNumber(const base::string16& text, + const std::string& country_code) { + return i18n::IsPossiblePhoneNumber(base::UTF16ToUTF8(text), country_code); } bool IsValidZip(const base::string16& text) { @@ -268,30 +258,28 @@ return false; int area; - if (!base::StringToInt(base::StringPiece16(number_string.begin(), - number_string.begin() + 3), - &area)) { + if (!base::StringToInt( + base::StringPiece16(number_string.begin(), number_string.begin() + 3), + &area)) { return false; } - if (area < 1 || - area == 666 || - area >= 900) { + if (area < 1 || area == 666 || area >= 900) { return false; } int group; if (!base::StringToInt(base::StringPiece16(number_string.begin() + 3, number_string.begin() + 5), - &group) - || group == 0) { + &group) || + group == 0) { return false; } int serial; if (!base::StringToInt(base::StringPiece16(number_string.begin() + 5, number_string.begin() + 9), - &serial) - || serial == 0) { + &serial) || + serial == 0) { return false; }
diff --git a/components/autofill/core/browser/validation.h b/components/autofill/core/browser/validation.h index 76d499fc..65873ed 100644 --- a/components/autofill/core/browser/validation.h +++ b/components/autofill/core/browser/validation.h
@@ -87,11 +87,11 @@ // insensitive. Valid for US states only. bool IsValidState(const base::string16& text); -// Returns whether the number contained in |text| is valid, either in -// international format, or in the national format associated with +// Returns whether the number contained in |text| is possible phone number, +// either in international format, or in the national format associated with // |country_code|. Callers should cache the result as the parsing is expensive. -bool IsValidPhoneNumber(const base::string16& text, - const std::string& country_code); +bool IsPossiblePhoneNumber(const base::string16& text, + const std::string& country_code); // Returns true if |text| looks like a valid zip code. // Valid for US zip codes only.
diff --git a/components/autofill/core/browser/webdata/autofill_table.h b/components/autofill/core/browser/webdata/autofill_table.h index bc498b9..28c783d 100644 --- a/components/autofill/core/browser/webdata/autofill_table.h +++ b/components/autofill/core/browser/webdata/autofill_table.h
@@ -501,6 +501,9 @@ FRIEND_TEST_ALL_PREFIXES( AutofillTableTest, Autofill_RemoveFormElementsAddedBetween_UsedDuringAndAfter); + FRIEND_TEST_ALL_PREFIXES( + AutofillTableTest, + Autofill_RemoveFormElementsAddedBetween_OlderThan30Days); FRIEND_TEST_ALL_PREFIXES(AutofillTableTest, Autofill_AddFormFieldValues); FRIEND_TEST_ALL_PREFIXES(AutofillTableTest, AutofillProfile); FRIEND_TEST_ALL_PREFIXES(AutofillTableTest, UpdateAutofillProfile);
diff --git a/components/autofill/core/browser/webdata/autofill_table_unittest.cc b/components/autofill/core/browser/webdata/autofill_table_unittest.cc index 5df7e968..abcd0a4 100644 --- a/components/autofill/core/browser/webdata/autofill_table_unittest.cc +++ b/components/autofill/core/browser/webdata/autofill_table_unittest.cc
@@ -734,6 +734,43 @@ EXPECT_EQ(base::Time::FromTimeT(90), date_last_used); } +TEST_F(AutofillTableTest, + Autofill_RemoveFormElementsAddedBetween_OlderThan30Days) { + const base::Time kNow = base::Time::Now(); + const base::Time k29DaysOld = kNow - base::TimeDelta::FromDays(29); + const base::Time k30DaysOld = kNow - base::TimeDelta::FromDays(30); + const base::Time k31DaysOld = kNow - base::TimeDelta::FromDays(31); + + // Add some form field entries. + AutofillChangeList changes; + FormFieldData field; + field.name = ASCIIToUTF16("Name"); + field.value = ASCIIToUTF16("Superman"); + EXPECT_TRUE(table_->AddFormFieldValueTime(field, &changes, kNow)); + field.value = ASCIIToUTF16("Clark Kent"); + EXPECT_TRUE(table_->AddFormFieldValueTime(field, &changes, k29DaysOld)); + field.value = ASCIIToUTF16("Clark Sutter"); + EXPECT_TRUE(table_->AddFormFieldValueTime(field, &changes, k31DaysOld)); + EXPECT_EQ(3U, changes.size()); + + // Removing all elements added before 30days from the database. + changes.clear(); + EXPECT_TRUE(table_->RemoveFormElementsAddedBetween(base::Time(), k30DaysOld, + &changes)); + ASSERT_EQ(1U, changes.size()); + EXPECT_EQ(AutofillChange(AutofillChange::REMOVE, + AutofillKey(ASCIIToUTF16("Name"), + ASCIIToUTF16("Clark Sutter"))), + changes[0]); + EXPECT_EQ(0, GetAutofillEntryCount(ASCIIToUTF16("Name"), + ASCIIToUTF16("Clark Sutter"), db_.get())); + EXPECT_EQ(1, GetAutofillEntryCount(ASCIIToUTF16("Name"), + ASCIIToUTF16("Superman"), db_.get())); + EXPECT_EQ(1, GetAutofillEntryCount(ASCIIToUTF16("Name"), + ASCIIToUTF16("Clark Kent"), db_.get())); + changes.clear(); +} + TEST_F(AutofillTableTest, AutofillProfile) { // Add a 'Home' profile with non-default data. The specific values are not // important.
diff --git a/components/browsing_data/core/counters/autofill_counter.cc b/components/browsing_data/core/counters/autofill_counter.cc index 30127cb..8e62d7c 100644 --- a/components/browsing_data/core/counters/autofill_counter.cc +++ b/components/browsing_data/core/counters/autofill_counter.cc
@@ -57,10 +57,18 @@ period_start_for_testing_ = period_start_for_testing; } +void AutofillCounter::SetPeriodEndForTesting( + const base::Time& period_end_for_testing) { + period_end_for_testing_ = period_end_for_testing; +} + void AutofillCounter::Count() { const base::Time start = period_start_for_testing_.is_null() ? GetPeriodStart() : period_start_for_testing_; + const base::Time end = period_end_for_testing_.is_null() + ? GetPeriodEnd() + : period_end_for_testing_; CancelAllRequests(); @@ -70,7 +78,7 @@ // and last modified time) lies within the deletion time range. Otherwise, // it only decreases the count property, but always to a nonzero value, // and the suggestion is retained. Therefore here as well, we must only count - // the entries that are entirely contained in [start, base::Time::Max()). + // the entries that are entirely contained in [start, end). // Further, many of these entries may contain the same values, as they are // simply the same data point entered on different forms. For example, // [name, value] pairs such as: @@ -81,9 +89,9 @@ // they constitute the same suggestion - "my email". Therefore, for the final // output, we will consider all entries with the same value as one suggestion, // and increment the counter only if all entries with the given value are - // contained in the interval [start, base::Time::Max()). - suggestions_query_ = web_data_service_->GetCountOfValuesContainedBetween( - start, base::Time::Max(), this); + // contained in the interval [start, end). + suggestions_query_ = + web_data_service_->GetCountOfValuesContainedBetween(start, end, this); // Count the credit cards. credit_cards_query_ = web_data_service_->GetCreditCards(this); @@ -117,6 +125,9 @@ const base::Time start = period_start_for_testing_.is_null() ? GetPeriodStart() : period_start_for_testing_; + const base::Time end = period_end_for_testing_.is_null() + ? GetPeriodEnd() + : period_end_for_testing_; if (handle == suggestions_query_) { // Autocomplete suggestions. @@ -136,8 +147,9 @@ num_credit_cards_ = std::count_if( credit_cards.begin(), credit_cards.end(), - [start](const std::unique_ptr<autofill::CreditCard>& card) { - return card->modification_date() >= start; + [start, end](const std::unique_ptr<autofill::CreditCard>& card) { + return (card->modification_date() >= start && + card->modification_date() < end); }); credit_cards_query_ = 0; @@ -152,8 +164,10 @@ num_addresses_ = std::count_if( addresses.begin(), addresses.end(), - [start](const std::unique_ptr<autofill::AutofillProfile>& address) { - return address->modification_date() >= start; + [start, + end](const std::unique_ptr<autofill::AutofillProfile>& address) { + return (address->modification_date() >= start && + address->modification_date() < end); }); addresses_query_ = 0;
diff --git a/components/browsing_data/core/counters/autofill_counter.h b/components/browsing_data/core/counters/autofill_counter.h index 8c657dc..ccf8cdc 100644 --- a/components/browsing_data/core/counters/autofill_counter.h +++ b/components/browsing_data/core/counters/autofill_counter.h
@@ -59,6 +59,9 @@ // time periods instead of BrowsingDataRemover::TimePeriod. void SetPeriodStartForTesting(const base::Time& period_start_for_testing); + // Set the ending of the time period for testing. + void SetPeriodEndForTesting(const base::Time& period_end_for_testing); + private: void Count() override; @@ -84,6 +87,7 @@ ResultInt num_addresses_; base::Time period_start_for_testing_; + base::Time period_end_for_testing_; DISALLOW_COPY_AND_ASSIGN(AutofillCounter); };
diff --git a/components/download/downloader/in_progress/BUILD.gn b/components/download/downloader/in_progress/BUILD.gn index e9aba57c..5b7a1b15 100644 --- a/components/download/downloader/in_progress/BUILD.gn +++ b/components/download/downloader/in_progress/BUILD.gn
@@ -22,6 +22,7 @@ deps = [ "//base", "//components/download/downloader/in_progress/proto", + "//services/metrics/public/cpp:metrics_cpp", ] }
diff --git a/components/download/downloader/in_progress/DEPS b/components/download/downloader/in_progress/DEPS new file mode 100644 index 0000000..18f63456 --- /dev/null +++ b/components/download/downloader/in_progress/DEPS
@@ -0,0 +1,3 @@ +include_rules = [ + "+services/metrics/public" +]
diff --git a/components/download/downloader/in_progress/download_entry.cc b/components/download/downloader/in_progress/download_entry.cc index 0bb3a60..e80a799 100644 --- a/components/download/downloader/in_progress/download_entry.cc +++ b/components/download/downloader/in_progress/download_entry.cc
@@ -10,18 +10,28 @@ DownloadEntry::DownloadEntry(const DownloadEntry& other) = default; +DownloadEntry::DownloadEntry(const std::string& guid, int64_t ukm_download_id) + : guid(guid), ukm_download_id(ukm_download_id) {} + DownloadEntry::DownloadEntry(const std::string& guid, const std::string& request_origin, - DownloadSource download_source) + DownloadSource download_source, + int64_t ukm_download_id) : guid(guid), request_origin(request_origin), - download_source(download_source) {} + download_source(download_source), + ukm_download_id(ukm_download_id) {} DownloadEntry::~DownloadEntry() = default; bool DownloadEntry::operator==(const DownloadEntry& other) const { return guid == other.guid && request_origin == other.request_origin && - download_source == other.download_source; + download_source == other.download_source && + ukm_download_id == other.ukm_download_id; +} + +bool DownloadEntry::operator!=(const DownloadEntry& other) const { + return !(*this == other); } } // namespace download
diff --git a/components/download/downloader/in_progress/download_entry.h b/components/download/downloader/in_progress/download_entry.h index cd5ae77..d06cd46 100644 --- a/components/download/downloader/in_progress/download_entry.h +++ b/components/download/downloader/in_progress/download_entry.h
@@ -8,6 +8,7 @@ #include <string> #include "components/download/downloader/in_progress/download_source.h" +#include "services/metrics/public/cpp/ukm_source_id.h" namespace download { @@ -16,13 +17,17 @@ public: DownloadEntry(); DownloadEntry(const DownloadEntry& other); + DownloadEntry(const std::string& guid, int64_t ukm_id); DownloadEntry(const std::string& guid, const std::string& request_origin, - DownloadSource download_source); + DownloadSource download_source, + int64_t ukm_id); ~DownloadEntry(); bool operator==(const DownloadEntry& other) const; + bool operator!=(const DownloadEntry& other) const; + // A unique GUID that represents this download. std::string guid; @@ -31,6 +36,10 @@ // The source that triggered the download. DownloadSource download_source = DownloadSource::UNKNOWN; + + // Unique ID that tracks the download UKM entry, where 0 means the + // download_id is not yet initialized. + uint64_t ukm_download_id = 0; }; } // namespace download
diff --git a/components/download/downloader/in_progress/in_progress_cache_impl_unittest.cc b/components/download/downloader/in_progress/in_progress_cache_impl_unittest.cc index 4e9c4f1..d3f6b4b 100644 --- a/components/download/downloader/in_progress/in_progress_cache_impl_unittest.cc +++ b/components/download/downloader/in_progress/in_progress_cache_impl_unittest.cc
@@ -68,7 +68,7 @@ // Add entry. std::string guid1("guid"); - DownloadEntry entry1(guid1, "request origin", DownloadSource::UNKNOWN); + DownloadEntry entry1(guid1, "request origin", DownloadSource::UNKNOWN, 999); cache_->AddOrReplaceEntry(entry1); base::Optional<DownloadEntry> retrieved_entry1 = cache_->RetrieveEntry(guid1); @@ -87,7 +87,8 @@ // Add another entry. std::string guid2("guid2"); - DownloadEntry entry2(guid2, "other request origin", DownloadSource::UNKNOWN); + DownloadEntry entry2(guid2, "other request origin", DownloadSource::UNKNOWN, + 888); cache_->AddOrReplaceEntry(entry2); base::Optional<DownloadEntry> retrieved_entry2 = cache_->RetrieveEntry(guid2);
diff --git a/components/download/downloader/in_progress/in_progress_conversions.cc b/components/download/downloader/in_progress/in_progress_conversions.cc index 44947832..807c92e 100644 --- a/components/download/downloader/in_progress/in_progress_conversions.cc +++ b/components/download/downloader/in_progress/in_progress_conversions.cc
@@ -16,6 +16,7 @@ entry.guid = proto.guid(); entry.request_origin = proto.request_origin(); entry.download_source = DownloadSourceFromProto(proto.download_source()); + entry.ukm_download_id = proto.ukm_download_id(); return entry; } @@ -25,6 +26,7 @@ proto.set_guid(entry.guid); proto.set_request_origin(entry.request_origin); proto.set_download_source(DownloadSourceToProto(entry.download_source)); + proto.set_ukm_download_id(entry.ukm_download_id); return proto; }
diff --git a/components/download/downloader/in_progress/in_progress_conversions_unittest.cc b/components/download/downloader/in_progress/in_progress_conversions_unittest.cc index 1a10589..f48d788 100644 --- a/components/download/downloader/in_progress/in_progress_conversions_unittest.cc +++ b/components/download/downloader/in_progress/in_progress_conversions_unittest.cc
@@ -22,6 +22,7 @@ entry.guid = "guid"; entry.request_origin = "request origin"; entry.download_source = DownloadSource::DRAG_AND_DROP; + entry.ukm_download_id = 123; EXPECT_EQ(entry, DownloadEntryFromProto(DownloadEntryToProto(entry))); } @@ -32,12 +33,12 @@ // Entries vector with one entry. entries.push_back( - DownloadEntry("guid", "request origin", DownloadSource::UNKNOWN)); + DownloadEntry("guid", "request origin", DownloadSource::UNKNOWN, 123)); EXPECT_EQ(entries, DownloadEntriesFromProto(DownloadEntriesToProto(entries))); // Entries vector with multiple entries. entries.push_back( - DownloadEntry("guid2", "request origin", DownloadSource::UNKNOWN)); + DownloadEntry("guid2", "request origin", DownloadSource::UNKNOWN, 456)); EXPECT_EQ(entries, DownloadEntriesFromProto(DownloadEntriesToProto(entries))); }
diff --git a/components/download/downloader/in_progress/proto/download_entry.proto b/components/download/downloader/in_progress/proto/download_entry.proto index beb8d244..8b010dd0 100644 --- a/components/download/downloader/in_progress/proto/download_entry.proto +++ b/components/download/downloader/in_progress/proto/download_entry.proto
@@ -15,6 +15,7 @@ optional string guid = 1; optional string request_origin = 2; optional DownloadSource download_source = 3; + optional int64 ukm_download_id = 4; } // Contains a list of entries.
diff --git a/components/history/DEPS b/components/history/DEPS index 3208ad1..d73616b 100644 --- a/components/history/DEPS +++ b/components/history/DEPS
@@ -3,7 +3,6 @@ "+components/keyed_service", "+components/query_parser", "+components/prefs", - "+components/signin/core", "+components/sync", "+google_apis/gaia", "+net",
diff --git a/components/history/core/browser/BUILD.gn b/components/history/core/browser/BUILD.gn index f4af57b..e4b67e5f 100644 --- a/components/history/core/browser/BUILD.gn +++ b/components/history/core/browser/BUILD.gn
@@ -111,13 +111,13 @@ "//components/keyed_service/core", "//components/prefs", "//components/query_parser", - "//components/signin/core/browser", "//components/sync", "//components/url_formatter", "//components/variations", "//components/version_info", "//google_apis", "//net", + "//services/identity/public/cpp", "//sql", "//third_party/sqlite", "//ui/base", @@ -225,11 +225,10 @@ "//components/history/core/common", "//components/history/core/test", "//components/prefs:test_support", - "//components/signin/core/browser", - "//components/signin/core/browser:test_support", "//components/sync", "//components/sync:test_support_driver", "//components/sync:test_support_model", + "//net:test_support", "//sql", "//sql:test_support", "//testing/gtest",
diff --git a/components/history/core/browser/DEPS b/components/history/core/browser/DEPS index dd2ef5d..d8117751 100644 --- a/components/history/core/browser/DEPS +++ b/components/history/core/browser/DEPS
@@ -1,4 +1,5 @@ include_rules = [ "+components/data_use_measurement/core", "+components/variations", + "+services/identity/public", ]
diff --git a/components/history/core/browser/web_history_service.cc b/components/history/core/browser/web_history_service.cc index b54c4f1..6a6ae16 100644 --- a/components/history/core/browser/web_history_service.cc +++ b/components/history/core/browser/web_history_service.cc
@@ -20,12 +20,10 @@ #include "components/data_use_measurement/core/data_use_user_data.h" #include "components/history/core/browser/history_service_observer.h" #include "components/history/core/browser/web_history_service_observer.h" -#include "components/signin/core/browser/signin_manager.h" #include "components/sync/driver/sync_util.h" #include "components/sync/protocol/history_status.pb.h" #include "google_apis/gaia/gaia_urls.h" #include "google_apis/gaia/google_service_auth_error.h" -#include "google_apis/gaia/oauth2_token_service.h" #include "net/base/load_flags.h" #include "net/base/url_util.h" #include "net/http/http_status_code.h" @@ -33,6 +31,7 @@ #include "net/url_request/url_fetcher.h" #include "net/url_request/url_fetcher_delegate.h" #include "net/url_request/url_request_context_getter.h" +#include "services/identity/public/cpp/identity_manager.h" #include "ui/base/device_form_factor.h" #include "url/gurl.h" @@ -68,7 +67,6 @@ const size_t kMaxRetries = 1; class RequestImpl : public WebHistoryService::Request, - private OAuth2TokenService::Consumer, private net::URLFetcherDelegate { public: ~RequestImpl() override {} @@ -86,15 +84,12 @@ friend class history::WebHistoryService; RequestImpl( - OAuth2TokenService* token_service, - SigninManagerBase* signin_manager, + identity::IdentityManager* identity_manager, const scoped_refptr<net::URLRequestContextGetter>& request_context, const GURL& url, const WebHistoryService::CompletionCallback& callback, const net::PartialNetworkTrafficAnnotationTag& partial_traffic_annotation) - : OAuth2TokenService::Consumer("web_history"), - token_service_(token_service), - signin_manager_(signin_manager), + : identity_manager_(identity_manager), request_context_(request_context), url_(url), post_data_mime_type_(kPostDataMimeType), @@ -103,18 +98,45 @@ callback_(callback), is_pending_(false), partial_traffic_annotation_(partial_traffic_annotation) { - DCHECK(token_service_); - DCHECK(signin_manager_); + DCHECK(identity_manager_); DCHECK(request_context_); } + void OnAccessTokenFetchComplete(const GoogleServiceAuthError& error, + const std::string& access_token) { + access_token_fetcher_.reset(); + + if (error.state() != GoogleServiceAuthError::NONE) { + is_pending_ = false; + UMA_HISTOGRAM_BOOLEAN("WebHistory.OAuthTokenCompletion", false); + callback_.Run(this, false); + + // It is valid for the callback to delete |this|, so do not access any + // members below here. + return; + } + + DCHECK(!access_token.empty()); + access_token_ = access_token; + + UMA_HISTOGRAM_BOOLEAN("WebHistory.OAuthTokenCompletion", true); + + // Got an access token -- start the actual API request. + url_fetcher_ = CreateUrlFetcher(access_token); + url_fetcher_->Start(); + } + // Tells the request to do its thang. void Start() override { OAuth2TokenService::ScopeSet oauth_scopes; oauth_scopes.insert(kHistoryOAuthScope); - token_request_ = token_service_->StartRequest( - signin_manager_->GetAuthenticatedAccountId(), oauth_scopes, this); + access_token_fetcher_ = + identity_manager_->CreateAccessTokenFetcherForPrimaryAccount( + "web_history", oauth_scopes, + base::BindOnce(&RequestImpl::OnAccessTokenFetchComplete, + base::Unretained(this)), + identity::PrimaryAccountAccessTokenFetcher::Mode::kImmediate); is_pending_ = true; } @@ -132,8 +154,8 @@ if (response_code_ == net::HTTP_UNAUTHORIZED && ++auth_retry_count_ <= 1) { OAuth2TokenService::ScopeSet oauth_scopes; oauth_scopes.insert(kHistoryOAuthScope); - token_service_->InvalidateAccessToken( - signin_manager_->GetAuthenticatedAccountId(), oauth_scopes, + identity_manager_->RemoveAccessTokenFromCache( + identity_manager_->GetPrimaryAccountInfo(), oauth_scopes, access_token_); access_token_.clear(); @@ -148,33 +170,6 @@ // members below here. } - // OAuth2TokenService::Consumer interface. - void OnGetTokenSuccess(const OAuth2TokenService::Request* request, - const std::string& access_token, - const base::Time& expiration_time) override { - token_request_.reset(); - DCHECK(!access_token.empty()); - access_token_ = access_token; - - UMA_HISTOGRAM_BOOLEAN("WebHistory.OAuthTokenCompletion", true); - - // Got an access token -- start the actual API request. - url_fetcher_ = CreateUrlFetcher(access_token); - url_fetcher_->Start(); - } - - void OnGetTokenFailure(const OAuth2TokenService::Request* request, - const GoogleServiceAuthError& error) override { - token_request_.reset(); - is_pending_ = false; - - UMA_HISTOGRAM_BOOLEAN("WebHistory.OAuthTokenCompletion", false); - - callback_.Run(this, false); - // It is valid for the callback to delete |this|, so do not access any - // members below here. - } - // Helper for creating a new URLFetcher for the API request. std::unique_ptr<net::URLFetcher> CreateUrlFetcher( const std::string& access_token) { @@ -233,8 +228,7 @@ user_agent_ = user_agent; } - OAuth2TokenService* token_service_; - SigninManagerBase* signin_manager_; + identity::IdentityManager* identity_manager_; scoped_refptr<net::URLRequestContextGetter> request_context_; // The URL of the API endpoint. @@ -249,8 +243,8 @@ // The user agent header used with this request. std::string user_agent_; - // The OAuth2 access token request. - std::unique_ptr<OAuth2TokenService::Request> token_request_; + std::unique_ptr<identity::PrimaryAccountAccessTokenFetcher> + access_token_fetcher_; // The current OAuth2 access token. std::string access_token_; @@ -353,14 +347,11 @@ } WebHistoryService::WebHistoryService( - OAuth2TokenService* token_service, - SigninManagerBase* signin_manager, + identity::IdentityManager* identity_manager, const scoped_refptr<net::URLRequestContextGetter>& request_context) - : token_service_(token_service), - signin_manager_(signin_manager), + : identity_manager_(identity_manager), request_context_(request_context), - weak_ptr_factory_(this) { -} + weak_ptr_factory_(this) {} WebHistoryService::~WebHistoryService() { } @@ -377,8 +368,8 @@ const GURL& url, const CompletionCallback& callback, const net::PartialNetworkTrafficAnnotationTag& partial_traffic_annotation) { - return new RequestImpl(token_service_, signin_manager_, request_context_, url, - callback, partial_traffic_annotation); + return new RequestImpl(identity_manager_, request_context_, url, callback, + partial_traffic_annotation); } // static
diff --git a/components/history/core/browser/web_history_service.h b/components/history/core/browser/web_history_service.h index 3016fad..9693f74 100644 --- a/components/history/core/browser/web_history_service.h +++ b/components/history/core/browser/web_history_service.h
@@ -25,6 +25,10 @@ class DictionaryValue; } +namespace identity { +class IdentityManager; +} + namespace net { class URLRequestContextGetter; } @@ -33,9 +37,6 @@ enum class Channel; } -class OAuth2TokenService; -class SigninManagerBase; - namespace history { class WebHistoryServiceObserver; @@ -96,8 +97,7 @@ typedef base::Callback<void(Request*, bool success)> CompletionCallback; WebHistoryService( - OAuth2TokenService* token_service, - SigninManagerBase* signin_manager, + identity::IdentityManager* identity_manager, const scoped_refptr<net::URLRequestContextGetter>& request_context); ~WebHistoryService() override; @@ -218,10 +218,9 @@ private: friend class WebHistoryServiceTest; - // Stores pointer to OAuth2TokenService and SigninManagerBase instance. They - // must outlive the WebHistoryService and can be null during tests. - OAuth2TokenService* token_service_; - SigninManagerBase* signin_manager_; + // Stores pointer to IdentityManager instance. It must outlive the + // WebHistoryService and can be null during tests. + identity::IdentityManager* identity_manager_; // Request context getter to use. scoped_refptr<net::URLRequestContextGetter> request_context_;
diff --git a/components/history/core/browser/web_history_service_unittest.cc b/components/history/core/browser/web_history_service_unittest.cc index 05e9ad7b..3b58611 100644 --- a/components/history/core/browser/web_history_service_unittest.cc +++ b/components/history/core/browser/web_history_service_unittest.cc
@@ -30,10 +30,12 @@ class TestingWebHistoryService : public WebHistoryService { public: explicit TestingWebHistoryService( - OAuth2TokenService* token_service, - SigninManagerBase* signin_manager, const scoped_refptr<net::URLRequestContextGetter>& request_context) - : WebHistoryService(token_service, signin_manager, request_context), + // NOTE: Simply pass null object for IdentityManager. WebHistoryService's + // only usage of this object is to fetch access tokens via RequestImpl, + // and TestWebHistoryService deliberately replaces this flow with + // TestRequest. + : WebHistoryService(nullptr, request_context), expected_url_(GURL()), expected_audio_history_value_(false), current_expected_post_data_("") {} @@ -215,12 +217,7 @@ WebHistoryServiceTest() : url_request_context_(new net::TestURLRequestContextGetter( base::ThreadTaskRunnerHandle::Get())), - // NOTE: Simply pass null ojects for - // SigninManager/OAuth2TokenService. WebHistoryService's only - // usage of those objects is to fetch access tokens via RequestImpl, - // and TestWebHistoryService deliberately replaces this flow with - // TestRequest. - web_history_service_(nullptr, nullptr, url_request_context_) {} + web_history_service_(url_request_context_) {} ~WebHistoryServiceTest() override {}
diff --git a/components/history/core/test/fake_web_history_service.cc b/components/history/core/test/fake_web_history_service.cc index 3bafb03..3d682268 100644 --- a/components/history/core/test/fake_web_history_service.cc +++ b/components/history/core/test/fake_web_history_service.cc
@@ -179,12 +179,11 @@ FakeWebHistoryService::FakeWebHistoryService( const scoped_refptr<net::URLRequestContextGetter>& request_context) - // NOTE: Simply pass null ojects for - // SigninManager/OAuth2TokenService. WebHistoryService's only - // usage of those objects is to fetch access tokens via RequestImpl, - // and FakeWebHistoryService deliberately replaces this flow with + // NOTE: Simply pass null object for IdentityManager. WebHistoryService's + // only usage of this object is to fetch access tokens via RequestImpl, and + // FakeWebHistoryService deliberately replaces this flow with // FakeWebHistoryService::FakeRequest. - : history::WebHistoryService(nullptr, nullptr, request_context), + : history::WebHistoryService(nullptr, request_context), emulate_success_(true), emulate_response_code_(net::HTTP_OK), web_and_app_activity_enabled_(false),
diff --git a/components/infobars/core/BUILD.gn b/components/infobars/core/BUILD.gn index 103e359..acb9374 100644 --- a/components/infobars/core/BUILD.gn +++ b/components/infobars/core/BUILD.gn
@@ -21,8 +21,6 @@ "infobar_delegate.h", "infobar_manager.cc", "infobar_manager.h", - "infobars_switches.cc", - "infobars_switches.h", "simple_alert_infobar_delegate.cc", "simple_alert_infobar_delegate.h", ]
diff --git a/components/infobars/core/infobar_manager.cc b/components/infobars/core/infobar_manager.cc index 7f6a4c9..7005855 100644 --- a/components/infobars/core/infobar_manager.cc +++ b/components/infobars/core/infobar_manager.cc
@@ -8,7 +8,6 @@ #include "base/command_line.h" #include "components/infobars/core/infobar.h" -#include "components/infobars/core/infobars_switches.h" namespace infobars { @@ -38,9 +37,6 @@ InfoBar* InfoBarManager::AddInfoBar(std::unique_ptr<InfoBar> infobar, bool replace_existing) { DCHECK(infobar); - if (!infobars_enabled_) - return nullptr; - for (InfoBars::const_iterator i(infobars_.begin()); i != infobars_.end(); ++i) { if ((*i)->delegate()->EqualsDelegate(infobar->delegate())) { @@ -71,8 +67,6 @@ InfoBar* InfoBarManager::ReplaceInfoBar(InfoBar* old_infobar, std::unique_ptr<InfoBar> new_infobar) { DCHECK(old_infobar); - if (!infobars_enabled_) - return AddInfoBar(std::move(new_infobar)); // Deletes the infobar. DCHECK(new_infobar); InfoBars::iterator i(std::find(infobars_.begin(), infobars_.end(), @@ -103,9 +97,6 @@ } InfoBarManager::InfoBarManager() { - if (base::CommandLine::ForCurrentProcess()->HasSwitch( - switches::kDisableInfoBars)) - infobars_enabled_ = false; } InfoBarManager::~InfoBarManager() {} @@ -142,11 +133,6 @@ void InfoBarManager::RemoveInfoBarInternal(InfoBar* infobar, bool animate) { DCHECK(infobar); - if (!infobars_enabled_) { - DCHECK(infobars_.empty()); - return; - } - InfoBars::iterator i(std::find(infobars_.begin(), infobars_.end(), infobar)); DCHECK(i != infobars_.end());
diff --git a/components/infobars/core/infobar_manager.h b/components/infobars/core/infobar_manager.h index 2d44965..9ae6c06 100644 --- a/components/infobars/core/infobar_manager.h +++ b/components/infobars/core/infobar_manager.h
@@ -132,7 +132,6 @@ void RemoveInfoBarInternal(InfoBar* infobar, bool animate); InfoBars infobars_; - bool infobars_enabled_ = true; bool animations_enabled_ = true; base::ObserverList<Observer, true> observer_list_;
diff --git a/components/infobars/core/infobars_switches.cc b/components/infobars/core/infobars_switches.cc deleted file mode 100644 index deb21a76..0000000 --- a/components/infobars/core/infobars_switches.cc +++ /dev/null
@@ -1,14 +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 "components/infobars/core/infobars_switches.h" - -namespace infobars { -namespace switches { - -// Prevent infobars from appearing. -const char kDisableInfoBars[] = "disable-infobars"; - -} // namespace switches -} // namespace infobars
diff --git a/components/infobars/core/infobars_switches.h b/components/infobars/core/infobars_switches.h deleted file mode 100644 index d24a09a4..0000000 --- a/components/infobars/core/infobars_switches.h +++ /dev/null
@@ -1,16 +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 COMPONENTS_INFOBARS_CORE_INFOBARS_SWITCHES_H_ -#define COMPONENTS_INFOBARS_CORE_INFOBARS_SWITCHES_H_ - -namespace infobars { -namespace switches { - -extern const char kDisableInfoBars[]; - -} // namespace switches -} // namespace infobars - -#endif // COMPONENTS_INFOBARS_CORE_INFOBARS_SWITCHES_H_
diff --git a/components/password_manager/core/browser/form_saver.h b/components/password_manager/core/browser/form_saver.h index 634c6a7..65185337 100644 --- a/components/password_manager/core/browser/form_saver.h +++ b/components/password_manager/core/browser/form_saver.h
@@ -28,12 +28,11 @@ virtual void PermanentlyBlacklist(autofill::PasswordForm* observed) = 0; // Saves the |pending| form and updates the stored preference on - // |best_matches|. If |old_primary_key| is given, uses it for saving - // |pending|. - virtual void Save(const autofill::PasswordForm& pending, - const std::map<base::string16, - const autofill::PasswordForm*>& best_matches, - const autofill::PasswordForm* old_primary_key) = 0; + // |best_matches|. + virtual void Save( + const autofill::PasswordForm& pending, + const std::map<base::string16, const autofill::PasswordForm*>& + best_matches) = 0; // Updates the |pending| form and updates the stored preference on // |best_matches|. If |old_primary_key| is given, uses it for saving
diff --git a/components/password_manager/core/browser/form_saver_impl.cc b/components/password_manager/core/browser/form_saver_impl.cc index be12e073..802cd1c 100644 --- a/components/password_manager/core/browser/form_saver_impl.cc +++ b/components/password_manager/core/browser/form_saver_impl.cc
@@ -37,9 +37,8 @@ void FormSaverImpl::Save( const PasswordForm& pending, - const std::map<base::string16, const PasswordForm*>& best_matches, - const PasswordForm* old_primary_key) { - SaveImpl(pending, true, best_matches, nullptr, old_primary_key); + const std::map<base::string16, const PasswordForm*>& best_matches) { + SaveImpl(pending, true, best_matches, nullptr, nullptr); } void FormSaverImpl::Update(
diff --git a/components/password_manager/core/browser/form_saver_impl.h b/components/password_manager/core/browser/form_saver_impl.h index 7fa8459..0833dc0a 100644 --- a/components/password_manager/core/browser/form_saver_impl.h +++ b/components/password_manager/core/browser/form_saver_impl.h
@@ -27,8 +27,7 @@ void PermanentlyBlacklist(autofill::PasswordForm* observed) override; void Save(const autofill::PasswordForm& pending, const std::map<base::string16, const autofill::PasswordForm*>& - best_matches, - const autofill::PasswordForm* old_primary_key) override; + best_matches) override; void Update(const autofill::PasswordForm& pending, const std::map<base::string16, const autofill::PasswordForm*>& best_matches,
diff --git a/components/password_manager/core/browser/form_saver_impl_unittest.cc b/components/password_manager/core/browser/form_saver_impl_unittest.cc index bd5ed867..49766a74 100644 --- a/components/password_manager/core/browser/form_saver_impl_unittest.cc +++ b/components/password_manager/core/browser/form_saver_impl_unittest.cc
@@ -107,8 +107,7 @@ EXPECT_CALL(*mock_store_, AddLogin(_)).WillOnce(SaveArg<0>(&saved)); EXPECT_CALL(*mock_store_, UpdateLogin(_)).Times(0); EXPECT_CALL(*mock_store_, UpdateLoginWithPrimaryKey(_, _)).Times(0); - form_saver_.Save(pending, std::map<base::string16, const PasswordForm*>(), - nullptr); + form_saver_.Save(pending, std::map<base::string16, const PasswordForm*>()); EXPECT_EQ(ASCIIToUTF16("nameofuser"), saved.username_value); EXPECT_EQ(ASCIIToUTF16("wordToP4a55"), saved.password_value); } @@ -206,7 +205,7 @@ EXPECT_CALL(*mock_store_, AddLogin(_)).WillOnce(SaveArg<0>(&saved)); EXPECT_CALL(*mock_store_, UpdateLogin(_)).WillOnce(SaveArg<0>(&updated)); EXPECT_CALL(*mock_store_, UpdateLoginWithPrimaryKey(_, _)).Times(0); - form_saver_.Save(pending, best_matches, nullptr); + form_saver_.Save(pending, best_matches); EXPECT_EQ(ASCIIToUTF16("nameofuser"), saved.username_value); EXPECT_EQ(ASCIIToUTF16("wordToP4a55"), saved.password_value); EXPECT_TRUE(saved.preferred); @@ -237,7 +236,7 @@ EXPECT_CALL(*mock_store_, UpdateLogin(_)).Times(0); EXPECT_CALL(*mock_store_, UpdateLoginWithPrimaryKey(_, _)).Times(0); EXPECT_CALL(*mock_store_, RemoveLogin(_)).WillOnce(SaveArg<0>(&removed)); - form_saver_.Save(pending, best_matches, nullptr); + form_saver_.Save(pending, best_matches); EXPECT_EQ(ASCIIToUTF16("nameofuser"), saved.username_value); EXPECT_EQ(ASCIIToUTF16("wordToP4a55"), saved.password_value); EXPECT_TRUE(removed.username_value.empty()); @@ -265,7 +264,7 @@ EXPECT_CALL(*mock_store_, UpdateLogin(_)).Times(0); EXPECT_CALL(*mock_store_, UpdateLoginWithPrimaryKey(_, _)).Times(0); EXPECT_CALL(*mock_store_, RemoveLogin(_)).Times(0); - form_saver_.Save(pending, best_matches, nullptr); + form_saver_.Save(pending, best_matches); EXPECT_EQ(ASCIIToUTF16("nameofuser"), saved.username_value); EXPECT_EQ(ASCIIToUTF16("wordToP4a55"), saved.password_value); } @@ -291,7 +290,7 @@ EXPECT_CALL(*mock_store_, UpdateLogin(_)).Times(0); EXPECT_CALL(*mock_store_, UpdateLoginWithPrimaryKey(_, _)).Times(0); EXPECT_CALL(*mock_store_, RemoveLogin(_)).Times(0); - form_saver_.Save(pending, best_matches, nullptr); + form_saver_.Save(pending, best_matches); EXPECT_EQ(ASCIIToUTF16("abc"), saved.username_value); EXPECT_EQ(ASCIIToUTF16("def"), saved.password_value); } @@ -314,7 +313,7 @@ EXPECT_CALL(*mock_store_, UpdateLogin(_)).Times(0); EXPECT_CALL(*mock_store_, UpdateLoginWithPrimaryKey(_, _)).Times(0); EXPECT_CALL(*mock_store_, RemoveLogin(_)).Times(0); - form_saver_.Save(pending, best_matches, nullptr); + form_saver_.Save(pending, best_matches); EXPECT_TRUE(saved.username_value.empty()); EXPECT_EQ(ASCIIToUTF16("wordToP4a55"), saved.password_value); } @@ -338,7 +337,7 @@ EXPECT_CALL(*mock_store_, UpdateLogin(_)).Times(0); EXPECT_CALL(*mock_store_, UpdateLoginWithPrimaryKey(_, _)).Times(0); EXPECT_CALL(*mock_store_, RemoveLogin(_)).Times(0); - form_saver_.Save(pending, best_matches, nullptr); + form_saver_.Save(pending, best_matches); EXPECT_EQ(ASCIIToUTF16("nameofuser"), saved.username_value); EXPECT_EQ(ASCIIToUTF16("wordToP4a55"), saved.password_value); } @@ -361,7 +360,7 @@ EXPECT_CALL(*mock_store_, UpdateLogin(_)).Times(0); EXPECT_CALL(*mock_store_, UpdateLoginWithPrimaryKey(_, _)).Times(0); EXPECT_CALL(*mock_store_, RemoveLogin(_)).Times(0); - form_saver_.Save(pending, best_matches, nullptr); + form_saver_.Save(pending, best_matches); EXPECT_EQ(ASCIIToUTF16("nameofuser"), saved.username_value); EXPECT_EQ(ASCIIToUTF16("wordToP4a55"), saved.password_value); } @@ -416,8 +415,7 @@ EXPECT_CALL(*mock_store_, UpdateLogin(_)).Times(0); EXPECT_CALL(*mock_store_, UpdateLoginWithPrimaryKey(_, _)) .WillOnce(DoAll(SaveArg<0>(&saved_new), SaveArg<1>(&saved_old))); - form_saver_.Save(pending, std::map<base::string16, const PasswordForm*>(), - nullptr); + form_saver_.Save(pending, std::map<base::string16, const PasswordForm*>()); EXPECT_EQ(ASCIIToUTF16("generatedU"), saved_old.username_value); EXPECT_EQ(ASCIIToUTF16("generatedP"), saved_old.password_value); EXPECT_EQ(ASCIIToUTF16("nameofuser"), saved_new.username_value);
diff --git a/components/password_manager/core/browser/password_form_manager.cc b/components/password_manager/core/browser/password_form_manager.cc index b703fe8..45793e3 100644 --- a/components/password_manager/core/browser/password_form_manager.cc +++ b/components/password_manager/core/browser/password_form_manager.cc
@@ -416,7 +416,7 @@ SanitizePossibleUsernames(&pending_credentials_); pending_credentials_.date_created = base::Time::Now(); SendVotesOnSave(); - form_saver_->Save(pending_credentials_, best_matches_, nullptr); + form_saver_->Save(pending_credentials_, best_matches_); } else { ProcessUpdate(); std::vector<PasswordForm> credentials_to_update;
diff --git a/components/password_manager/core/browser/password_form_manager_unittest.cc b/components/password_manager/core/browser/password_form_manager_unittest.cc index fe335f4..48a8ca09 100644 --- a/components/password_manager/core/browser/password_form_manager_unittest.cc +++ b/components/password_manager/core/browser/password_form_manager_unittest.cc
@@ -87,11 +87,10 @@ // FormSaver: MOCK_METHOD1(PermanentlyBlacklist, void(autofill::PasswordForm* observed)); - MOCK_METHOD3( + MOCK_METHOD2( Save, void(const autofill::PasswordForm& pending, - const std::map<base::string16, const PasswordForm*>& best_matches, - const autofill::PasswordForm* old_primary_key)); + const std::map<base::string16, const PasswordForm*>& best_matches)); MOCK_METHOD4( Update, void(const autofill::PasswordForm& pending, @@ -1124,7 +1123,7 @@ EXPECT_CALL( *client()->mock_driver()->mock_autofill_download_manager(), StartUploadRequest(_, false, expected_available_field_types, _, true)); - EXPECT_CALL(MockFormSaver::Get(form_manager()), Save(_, _, nullptr)) + EXPECT_CALL(MockFormSaver::Get(form_manager()), Save(_, _)) .WillOnce(SaveArg<0>(&actual_saved_form)); form_manager()->Save(); @@ -1540,7 +1539,7 @@ credentials, PasswordFormManager::ALLOW_OTHER_POSSIBLE_USERNAMES); PasswordForm saved_result; - EXPECT_CALL(MockFormSaver::Get(form_manager()), Save(_, _, nullptr)) + EXPECT_CALL(MockFormSaver::Get(form_manager()), Save(_, _)) .WillOnce(SaveArg<0>(&saved_result)); form_manager()->Save(); @@ -1576,7 +1575,7 @@ credentials, PasswordFormManager::ALLOW_OTHER_POSSIBLE_USERNAMES); PasswordForm saved_result; - EXPECT_CALL(MockFormSaver::Get(form_manager()), Save(_, _, nullptr)) + EXPECT_CALL(MockFormSaver::Get(form_manager()), Save(_, _)) .WillOnce(SaveArg<0>(&saved_result)); form_manager()->Save(); @@ -2099,7 +2098,7 @@ EXPECT_TRUE(form_manager()->IsNewLogin()); PasswordForm saved_result; - EXPECT_CALL(MockFormSaver::Get(form_manager()), Save(_, _, nullptr)) + EXPECT_CALL(MockFormSaver::Get(form_manager()), Save(_, _)) .WillOnce(SaveArg<0>(&saved_result)); form_manager()->Save(); @@ -2408,7 +2407,7 @@ // User clicks save, the edited username is saved. PasswordForm saved_result; - EXPECT_CALL(MockFormSaver::Get(&form_manager), Save(_, IsEmpty(), nullptr)) + EXPECT_CALL(MockFormSaver::Get(&form_manager), Save(_, IsEmpty())) .WillOnce(SaveArg<0>(&saved_result)); // Expect a username edited vote. FieldTypeMap expected_types; @@ -2557,10 +2556,8 @@ // no username vote is uploaded. PasswordForm actual_saved_form; EXPECT_CALL(MockFormSaver::Get(&form_manager), - Save(_, - ElementsAre(Pair(saved_match()->username_value, - Pointee(*saved_match()))), - nullptr)) + Save(_, ElementsAre(Pair(saved_match()->username_value, + Pointee(*saved_match()))))) .WillOnce(SaveArg<0>(&actual_saved_form)); EXPECT_CALL( *client()->mock_driver()->mock_autofill_download_manager(), @@ -2603,7 +2600,7 @@ // The user clicks save, empty username is saved. PasswordForm saved_result; - EXPECT_CALL(MockFormSaver::Get(&form_manager), Save(_, IsEmpty(), nullptr)) + EXPECT_CALL(MockFormSaver::Get(&form_manager), Save(_, IsEmpty())) .WillOnce(SaveArg<0>(&saved_result)); EXPECT_CALL( *client()->mock_driver()->mock_autofill_download_manager(), @@ -2641,10 +2638,8 @@ // The user clicks save, the edited username is saved. PasswordForm saved_result; EXPECT_CALL(MockFormSaver::Get(form_manager()), - Save(_, - ElementsAre(Pair(psl_saved_match()->username_value, - Pointee(*psl_saved_match()))), - nullptr)) + Save(_, ElementsAre(Pair(psl_saved_match()->username_value, + Pointee(*psl_saved_match()))))) .WillOnce(SaveArg<0>(&saved_result)); // As the credential is re-used successfully, expect a username vote. EXPECT_CALL(*client()->mock_driver()->mock_autofill_download_manager(), @@ -2677,7 +2672,7 @@ // User clicks save, selected password is saved. PasswordForm saved_result; - EXPECT_CALL(MockFormSaver::Get(form_manager()), Save(_, IsEmpty(), nullptr)) + EXPECT_CALL(MockFormSaver::Get(form_manager()), Save(_, IsEmpty())) .WillOnce(SaveArg<0>(&saved_result)); form_manager()->Save(); EXPECT_EQ(ASCIIToUTF16("username"), saved_result.username_value); @@ -2995,7 +2990,7 @@ // PSL matched credential should not be updated, since we are not sure that // this is the same credential as submitted one. PasswordForm new_credentials; - EXPECT_CALL(MockFormSaver::Get(&form_manager), Save(_, _, nullptr)) + EXPECT_CALL(MockFormSaver::Get(&form_manager), Save(_, _)) .WillOnce(testing::SaveArg<0>(&new_credentials)); // As the username is re-used, expect a username vote. EXPECT_CALL(*client()->mock_driver()->mock_autofill_download_manager(), @@ -3343,7 +3338,7 @@ EXPECT_TRUE(form_manager.IsNewLogin()); PasswordForm new_credentials; - EXPECT_CALL(MockFormSaver::Get(&form_manager), Save(_, _, nullptr)) + EXPECT_CALL(MockFormSaver::Get(&form_manager), Save(_, _)) .WillOnce(SaveArg<0>(&new_credentials)); form_manager.Save(); @@ -4207,7 +4202,7 @@ std::unique_ptr<PasswordFormManager> clone = form_manager->Clone(); PasswordForm passed; - EXPECT_CALL(MockFormSaver::Get(clone.get()), Save(_, IsEmpty(), nullptr)) + EXPECT_CALL(MockFormSaver::Get(clone.get()), Save(_, IsEmpty())) .WillOnce(SaveArg<0>(&passed)); clone->Save(); // The date is expected to be different. Reset it so that we can easily @@ -4260,7 +4255,7 @@ form_manager.reset(); PasswordForm passed; - EXPECT_CALL(MockFormSaver::Get(clone.get()), Save(_, IsEmpty(), nullptr)) + EXPECT_CALL(MockFormSaver::Get(clone.get()), Save(_, IsEmpty())) .WillOnce(SaveArg<0>(&passed)); clone->Save(); // The date is expected to be different. Reset it so that we can easily
diff --git a/components/password_manager/core/browser/stub_form_saver.h b/components/password_manager/core/browser/stub_form_saver.h index 769fe43..af31ff8 100644 --- a/components/password_manager/core/browser/stub_form_saver.h +++ b/components/password_manager/core/browser/stub_form_saver.h
@@ -21,8 +21,7 @@ void PermanentlyBlacklist(autofill::PasswordForm* observed) override {} void Save(const autofill::PasswordForm& pending, const std::map<base::string16, const autofill::PasswordForm*>& - best_matches, - const autofill::PasswordForm* old_primary_key) override {} + best_matches) override {} void Update(const autofill::PasswordForm& pending, const std::map<base::string16, const autofill::PasswordForm*>& best_matches,
diff --git a/components/password_manager/core/common/password_manager_features.cc b/components/password_manager/core/common/password_manager_features.cc index 278c59af..ec02900 100644 --- a/components/password_manager/core/common/password_manager_features.cc +++ b/components/password_manager/core/common/password_manager_features.cc
@@ -51,14 +51,6 @@ const base::Feature kEnableManualPasswordGeneration = { "enable-manual-password-generation", base::FEATURE_ENABLED_BY_DEFAULT}; -// Enables username correction while saving username and password details. -const base::Feature kEnableUsernameCorrection{"EnableUsernameCorrection", - base::FEATURE_ENABLED_BY_DEFAULT}; - -// Enables password selection while saving username and password details. -const base::Feature kEnablePasswordSelection{"EnablePasswordSelection", - base::FEATURE_ENABLED_BY_DEFAULT}; - // Enables the "Show all saved passwords" option in Context Menu. const base::Feature kEnableShowAllSavedPasswordsContextMenu{ "kEnableShowAllSavedPasswordsContextMenu",
diff --git a/components/password_manager/core/common/password_manager_features.h b/components/password_manager/core/common/password_manager_features.h index 2c10d4c..3643ea1 100644 --- a/components/password_manager/core/common/password_manager_features.h +++ b/components/password_manager/core/common/password_manager_features.h
@@ -25,9 +25,7 @@ extern const base::Feature kEnableManualPasswordGeneration; extern const base::Feature kEnableManualSaving; extern const base::Feature kEnablePasswordForceSaving; -extern const base::Feature kEnablePasswordSelection; extern const base::Feature kEnableShowAllSavedPasswordsContextMenu; -extern const base::Feature kEnableUsernameCorrection; extern const base::Feature kFillOnAccountSelect; extern const base::Feature kPasswordExport; extern const base::Feature kPasswordImport;
diff --git a/components/payments/content/payment_response_helper_unittest.cc b/components/payments/content/payment_response_helper_unittest.cc index 38c46b0..d11179a 100644 --- a/components/payments/content/payment_response_helper_unittest.cc +++ b/components/payments/content/payment_response_helper_unittest.cc
@@ -248,10 +248,29 @@ EXPECT_FALSE(response()->payer_email.has_value()); } -// Tests the the generated PaymentResponse has the correct values for the -// contact details when all values are requested. +// Tests the the generated PaymentResponse has phone number formatted to E.164 +// if the number is valid. TEST_F(PaymentResponseHelperTest, - GeneratePaymentResponse_ContactPhoneIsFormatted) { + GeneratePaymentResponse_ContactPhoneIsFormattedWhenValid) { + // Request one contact detail value. + mojom::PaymentOptionsPtr options = mojom::PaymentOptions::New(); + options->request_payer_phone = true; + test_address()->SetRawInfo(autofill::PHONE_HOME_WHOLE_NUMBER, + base::UTF8ToUTF16("(515) 223-1234")); + RecreateSpecWithOptions(std::move(options)); + + PaymentResponseHelper helper("en-US", spec(), test_instrument(), + test_payment_request_delegate(), test_address(), + test_address(), this); + + // Check that the phone was formatted. + EXPECT_EQ("+15152231234", response()->payer_phone.value()); +} + +// Tests the the generated PaymentResponse has phone number minimumly formatted +// (removing non-digit letters), if the number is invalid +TEST_F(PaymentResponseHelperTest, + GeneratePaymentResponse_ContactPhoneIsMinimumlyFormattedWhenInvalid) { // Request one contact detail value. mojom::PaymentOptionsPtr options = mojom::PaymentOptions::New(); options->request_payer_phone = true; @@ -264,7 +283,7 @@ test_address(), this); // Check that the phone was formatted. - EXPECT_EQ("+15151231234", response()->payer_phone.value()); + EXPECT_EQ("5151231234", response()->payer_phone.value()); } } // namespace payments
diff --git a/components/payments/core/payments_profile_comparator.cc b/components/payments/core/payments_profile_comparator.cc index eff005e..dda44679 100644 --- a/components/payments/core/payments_profile_comparator.cc +++ b/components/payments/core/payments_profile_comparator.cc
@@ -225,8 +225,8 @@ base::string16 phone = profile.GetInfo( autofill::AutofillType(autofill::PHONE_HOME_WHOLE_NUMBER), app_locale()); base::string16 intl_phone = base::UTF8ToUTF16("+" + base::UTF16ToUTF8(phone)); - if (!(autofill::IsValidPhoneNumber(phone, country) || - autofill::IsValidPhoneNumber(intl_phone, country))) + if (!(autofill::IsPossiblePhoneNumber(phone, country) || + autofill::IsPossiblePhoneNumber(intl_phone, country))) missing |= kPhone; base::string16 email = profile.GetInfo(
diff --git a/components/search_provider_logos/logo_common.h b/components/search_provider_logos/logo_common.h index fdc20e24..1a5bc0d7 100644 --- a/components/search_provider_logos/logo_common.h +++ b/components/search_provider_logos/logo_common.h
@@ -67,8 +67,8 @@ // SIMPLE, ANIMATED: ignored // INTERACTIVE: appropriate dimensions for the iframe. - int iframe_width_px; - int iframe_height_px; + int iframe_width_px = 0; + int iframe_height_px = 0; // For use by LogoService ---------------------------------------------------
diff --git a/components/security_interstitials/core/browser/resources/interstitial_large.js b/components/security_interstitials/core/browser/resources/interstitial_large.js index 066e8b6..0fa7dbf 100644 --- a/components/security_interstitials/core/browser/resources/interstitial_large.js +++ b/components/security_interstitials/core/browser/resources/interstitial_large.js
@@ -13,7 +13,10 @@ * @param {string} e The key that was just pressed. */ function handleKeypress(e) { - var BYPASS_SEQUENCE = 'thisisnotsafe'; + // HTTPS errors are serious and should not be ignored. For testing purposes, + // other approaches are both safer and have fewer side-effects. + // See https://goo.gl/ZcZixP for more details. + var BYPASS_SEQUENCE = window.atob('dGhpc2lzdW5zYWZl'); if (BYPASS_SEQUENCE.charCodeAt(keyPressState) == e.keyCode) { keyPressState++; if (keyPressState == BYPASS_SEQUENCE.length) {
diff --git a/components/spellcheck/browser/spellcheck_platform.h b/components/spellcheck/browser/spellcheck_platform.h index 28450af..c9ff4959 100644 --- a/components/spellcheck/browser/spellcheck_platform.h +++ b/components/spellcheck/browser/spellcheck_platform.h
@@ -18,9 +18,9 @@ namespace spellcheck_platform { -typedef base::Callback<void( - const std::vector<SpellCheckResult>& /* results */)> - TextCheckCompleteCallback; +typedef base::OnceCallback<void( + const std::vector<SpellCheckResult>& /* results */)> + TextCheckCompleteCallback; // Get the languages supported by the platform spellchecker and store them in // |spellcheck_languages|. Note that they must be converted to
diff --git a/components/spellcheck/browser/spellcheck_platform_mac.mm b/components/spellcheck/browser/spellcheck_platform_mac.mm index 0461807..a6373ec8b 100644 --- a/components/spellcheck/browser/spellcheck_platform_mac.mm +++ b/components/spellcheck/browser/spellcheck_platform_mac.mm
@@ -240,9 +240,10 @@ void RequestTextCheck(int document_tag, const base::string16& text, - TextCheckCompleteCallback callback) { + TextCheckCompleteCallback passed_callback) { NSString* text_to_check = base::SysUTF16ToNSString(text); NSRange range_to_check = NSMakeRange(0, [text_to_check length]); + __block TextCheckCompleteCallback callback(std::move(passed_callback)); [SharedSpellChecker() requestCheckingOfString:text_to_check @@ -270,7 +271,7 @@ [result range].length)); } // TODO(groby): Verify we don't need to post from here. - callback.Run(check_results); + std::move(callback).Run(check_results); }]; }
diff --git a/components/spellcheck/browser/spellcheck_platform_mac_unittest.cc b/components/spellcheck/browser/spellcheck_platform_mac_unittest.cc index 466d25b..429d4239 100644 --- a/components/spellcheck/browser/spellcheck_platform_mac_unittest.cc +++ b/components/spellcheck/browser/spellcheck_platform_mac_unittest.cc
@@ -22,8 +22,8 @@ class SpellcheckPlatformMacTest: public testing::Test { public: SpellcheckPlatformMacTest() - : callback_(base::Bind(&SpellcheckPlatformMacTest::CompletionCallback, - base::Unretained(this))), + : callback_(base::BindOnce(&SpellcheckPlatformMacTest::CompletionCallback, + base::Unretained(this))), callback_finished_(false) {} void WaitForCallback() { @@ -44,8 +44,8 @@ results_ = results; callback_finished_ = true; message_loop_.task_runner()->PostTask( - FROM_HERE, base::Bind(&SpellcheckPlatformMacTest::QuitMessageLoop, - base::Unretained(this))); + FROM_HERE, base::BindOnce(&SpellcheckPlatformMacTest::QuitMessageLoop, + base::Unretained(this))); } base::MessageLoopForUI message_loop_; @@ -388,7 +388,7 @@ // RequestTextCheck results. TEST_F(SpellcheckPlatformMacTest, SpellCheckIgnoresOrthography) { base::string16 test_string(base::ASCIIToUTF16("Icland is awesome.")); - spellcheck_platform::RequestTextCheck(0, test_string, callback_); + spellcheck_platform::RequestTextCheck(0, test_string, std::move(callback_)); WaitForCallback(); EXPECT_TRUE(callback_finished_); EXPECT_EQ(1U, results_.size());
diff --git a/components/spellcheck/browser/spelling_service_client.cc b/components/spellcheck/browser/spelling_service_client.cc index bd52b5c..5ab8b6b 100644 --- a/components/spellcheck/browser/spelling_service_client.cc +++ b/components/spellcheck/browser/spelling_service_client.cc
@@ -55,10 +55,10 @@ content::BrowserContext* context, ServiceType type, const base::string16& text, - const TextCheckCompleteCallback& callback) { + TextCheckCompleteCallback callback) { DCHECK(type == SUGGEST || type == SPELLCHECK); if (!context || !IsAvailable(context, type)) { - callback.Run(false, text, std::vector<SpellCheckResult>()); + std::move(callback).Run(false, text, std::vector<SpellCheckResult>()); return false; } @@ -148,7 +148,7 @@ fetcher->SetLoadFlags(net::LOAD_DO_NOT_SEND_COOKIES | net::LOAD_DO_NOT_SAVE_COOKIES); spellcheck_fetchers_[fetcher] = base::MakeUnique<TextCheckCallbackData>( - base::WrapUnique(fetcher), callback, text); + base::WrapUnique(fetcher), std::move(callback), text); fetcher->Start(); return true; } @@ -279,9 +279,9 @@ SpellingServiceClient::TextCheckCallbackData::TextCheckCallbackData( std::unique_ptr<net::URLFetcher> fetcher, - TextCheckCompleteCallback callback, + TextCheckCompleteCallback&& callback, base::string16 text) - : fetcher(std::move(fetcher)), callback(callback), text(text) {} + : fetcher(std::move(fetcher)), callback(std::move(callback)), text(text) {} SpellingServiceClient::TextCheckCallbackData::~TextCheckCallbackData() {} @@ -301,7 +301,7 @@ // The callback may release the last (transitive) dependency on |this|. It // MUST be the last function called. - callback_data->callback.Run(success, callback_data->text, results); + std::move(callback_data->callback).Run(success, callback_data->text, results); } std::unique_ptr<net::URLFetcher> SpellingServiceClient::CreateURLFetcher(
diff --git a/components/spellcheck/browser/spelling_service_client.h b/components/spellcheck/browser/spelling_service_client.h index 29971d7..c3d4c08 100644 --- a/components/spellcheck/browser/spelling_service_client.h +++ b/components/spellcheck/browser/spelling_service_client.h
@@ -50,8 +50,8 @@ // void MyTextCheck(BrowserContext* context, const base::string16& text) { // client_.reset(new SpellingServiceClient); // client_->RequestTextCheck(context, 0, text, -// base::Bind(&MyClient::OnTextCheckComplete, -// base::Unretained(this)); +// base::BindOnce(&MyClient::OnTextCheckComplete, +// base::Unretained(this)); // } // private: // std::unique_ptr<SpellingServiceClient> client_; @@ -69,11 +69,11 @@ SUGGEST = 1, SPELLCHECK = 2, }; - typedef base::Callback<void( + typedef base::OnceCallback<void( bool /* success */, const base::string16& /* text */, const std::vector<SpellCheckResult>& /* results */)> - TextCheckCompleteCallback; + TextCheckCompleteCallback; SpellingServiceClient(); ~SpellingServiceClient() override; @@ -85,7 +85,7 @@ bool RequestTextCheck(content::BrowserContext* context, ServiceType type, const base::string16& text, - const TextCheckCompleteCallback& callback); + TextCheckCompleteCallback callback); // Returns whether the specified service is available for the given context. static bool IsAvailable(content::BrowserContext* context, ServiceType type); @@ -98,7 +98,7 @@ private: struct TextCheckCallbackData { TextCheckCallbackData(std::unique_ptr<net::URLFetcher> fetcher, - TextCheckCompleteCallback callback, + TextCheckCompleteCallback&& callback, base::string16 text); ~TextCheckCallbackData();
diff --git a/components/spellcheck/renderer/spellcheck.cc b/components/spellcheck/renderer/spellcheck.cc index 03c25d5..387beca7 100644 --- a/components/spellcheck/renderer/spellcheck.cc +++ b/components/spellcheck/renderer/spellcheck.cc
@@ -181,9 +181,9 @@ DCHECK(service_manager_connection); auto registry = base::MakeUnique<service_manager::BinderRegistry>(); - registry->AddInterface( - base::Bind(&SpellCheck::SpellCheckerRequest, base::Unretained(this)), - base::ThreadTaskRunnerHandle::Get()); + registry->AddInterface(base::BindRepeating(&SpellCheck::SpellCheckerRequest, + base::Unretained(this)), + base::ThreadTaskRunnerHandle::Get()); service_manager_connection->AddConnectionFilter( base::MakeUnique<content::SimpleConnectionFilter>(std::move(registry))); @@ -447,8 +447,8 @@ return; base::ThreadTaskRunnerHandle::Get()->PostTask( - FROM_HERE, base::Bind(&SpellCheck::PerformSpellCheck, AsWeakPtr(), - base::Owned(request))); + FROM_HERE, base::BindOnce(&SpellCheck::PerformSpellCheck, AsWeakPtr(), + base::Owned(request))); } #endif
diff --git a/components/spellcheck/renderer/spellcheck_panel.cc b/components/spellcheck/renderer/spellcheck_panel.cc index 7fa65377..4aebd5a1 100644 --- a/components/spellcheck/renderer/spellcheck_panel.cc +++ b/components/spellcheck/renderer/spellcheck_panel.cc
@@ -21,8 +21,8 @@ spelling_panel_visible_(false), embedder_provider_(embedder_provider) { DCHECK(render_frame); - registry->AddInterface(base::Bind(&SpellCheckPanel::SpellCheckPanelRequest, - base::Unretained(this))); + registry->AddInterface(base::BindRepeating( + &SpellCheckPanel::SpellCheckPanelRequest, base::Unretained(this))); render_frame->GetWebFrame()->SetSpellCheckPanelHostClient(this); }
diff --git a/components/spellcheck/renderer/spellcheck_provider.cc b/components/spellcheck/renderer/spellcheck_provider.cc index 805ca007..54e0d03d 100644 --- a/components/spellcheck/renderer/spellcheck_provider.cc +++ b/components/spellcheck/renderer/spellcheck_provider.cc
@@ -95,8 +95,8 @@ if (!spell_check_host_ && !content::RenderThread::Get()) return; // NULL in tests that do not provide a spell_check_host_. GetSpellCheckHost().CallSpellingService( - text, base::Bind(&SpellCheckProvider::OnRespondSpellingService, - base::Unretained(this), last_identifier_, text)); + text, base::BindOnce(&SpellCheckProvider::OnRespondSpellingService, + base::Unretained(this), last_identifier_, text)); #endif // !USE_BROWSER_SPELLCHECKER }
diff --git a/components/startup_metric_utils/browser/startup_metric_utils.cc b/components/startup_metric_utils/browser/startup_metric_utils.cc index 16c50ef8..08e93ee 100644 --- a/components/startup_metric_utils/browser/startup_metric_utils.cc +++ b/components/startup_metric_utils/browser/startup_metric_utils.cc
@@ -42,23 +42,17 @@ // Note that at the time of this writing, access is only on the UI thread. volatile bool g_main_window_startup_interrupted = false; -base::LazyInstance<base::TimeTicks>::Leaky g_process_creation_ticks = - LAZY_INSTANCE_INITIALIZER; - -base::LazyInstance<base::TimeTicks>::Leaky - g_browser_main_entry_point_ticks_computed_from_time = - LAZY_INSTANCE_INITIALIZER; +base::TimeTicks g_process_creation_ticks; base::TimeTicks g_browser_main_entry_point_ticks; -base::LazyInstance<base::TimeTicks>::Leaky g_renderer_main_entry_point_ticks = - LAZY_INSTANCE_INITIALIZER; +base::TimeTicks g_browser_main_entry_point_ticks_computed_from_time; -base::LazyInstance<base::TimeTicks>::Leaky - g_browser_exe_main_entry_point_ticks = LAZY_INSTANCE_INITIALIZER; +base::TimeTicks g_renderer_main_entry_point_ticks; -base::LazyInstance<base::TimeTicks>::Leaky g_message_loop_start_ticks = - LAZY_INSTANCE_INITIALIZER; +base::TimeTicks g_browser_exe_main_entry_point_ticks; + +base::TimeTicks g_message_loop_start_ticks; // An enumeration of startup temperatures. This must be kept in sync with the // UMA StartupType enumeration defined in histograms.xml. @@ -304,14 +298,14 @@ // Returns the system uptime on process launch. base::TimeDelta GetSystemUptimeOnProcessLaunch() { // Process launch time is not available on Android. - if (g_process_creation_ticks.Get().is_null()) + if (g_process_creation_ticks.is_null()) return base::TimeDelta(); // base::SysInfo::Uptime returns the time elapsed between system boot and now. // Substract the time elapsed between process launch and now to get the time // elapsed between system boot and process launch. return base::SysInfo::Uptime() - - (base::TimeTicks::Now() - g_process_creation_ticks.Get()); + (base::TimeTicks::Now() - g_process_creation_ticks); } void RecordSystemUptimeHistogram() { @@ -425,28 +419,23 @@ return trace_ticks_base - delta_since_base; } -// Record renderer main entry time histogram. void RecordRendererMainEntryHistogram() { - const base::TimeTicks browser_main_entry_point_ticks = - g_browser_main_entry_point_ticks_computed_from_time.Get(); - const base::TimeTicks renderer_main_entry_point_ticks = - g_renderer_main_entry_point_ticks.Get(); - - if (!browser_main_entry_point_ticks.is_null() && - !renderer_main_entry_point_ticks.is_null()) { + if (!g_browser_main_entry_point_ticks_computed_from_time.is_null() && + !g_renderer_main_entry_point_ticks.is_null()) { UMA_HISTOGRAM_AND_TRACE_WITH_TEMPERATURE_AND_SAME_VERSION_COUNT( UMA_HISTOGRAM_LONG_TIMES_100, "Startup.BrowserMainToRendererMain", - browser_main_entry_point_ticks, renderer_main_entry_point_ticks); + g_browser_main_entry_point_ticks_computed_from_time, + g_renderer_main_entry_point_ticks); } } void AddStartupEventsForTelemetry() { - DCHECK(!g_browser_main_entry_point_ticks_computed_from_time.Get().is_null()); + DCHECK(!g_browser_main_entry_point_ticks_computed_from_time.is_null()); TRACE_EVENT_INSTANT_WITH_TIMESTAMP0( "startup", "Startup.BrowserMainEntryPoint", 0, - g_browser_main_entry_point_ticks_computed_from_time.Get()); + g_browser_main_entry_point_ticks_computed_from_time); } // Logs the Startup.TimeSinceLastStartup histogram. Obtains the timestamp of the @@ -515,7 +504,7 @@ bool ShouldLogStartupHistogram() { return !WasMainWindowStartupInterrupted() && - !g_process_creation_ticks.Get().is_null(); + !g_process_creation_ticks.is_null(); } } // namespace @@ -540,9 +529,9 @@ } void RecordStartupProcessCreationTime(base::Time time) { - DCHECK(g_process_creation_ticks.Get().is_null()); - g_process_creation_ticks.Get() = StartupTimeToTimeTicks(time); - DCHECK(!g_process_creation_ticks.Get().is_null()); + DCHECK(g_process_creation_ticks.is_null()); + g_process_creation_ticks = StartupTimeToTimeTicks(time); + DCHECK(!g_process_creation_ticks.is_null()); } void RecordMainEntryPointTime(base::Time wall_time, base::TimeTicks ticks) { @@ -550,22 +539,22 @@ g_browser_main_entry_point_ticks = ticks; DCHECK(!g_browser_main_entry_point_ticks.is_null()); - DCHECK(g_browser_main_entry_point_ticks_computed_from_time.Get().is_null()); - g_browser_main_entry_point_ticks_computed_from_time.Get() = + DCHECK(g_browser_main_entry_point_ticks_computed_from_time.is_null()); + g_browser_main_entry_point_ticks_computed_from_time = StartupTimeToTimeTicks(wall_time); - DCHECK(!g_browser_main_entry_point_ticks_computed_from_time.Get().is_null()); + DCHECK(!g_browser_main_entry_point_ticks_computed_from_time.is_null()); } void RecordExeMainEntryPointTicks(base::TimeTicks ticks) { - DCHECK(g_browser_exe_main_entry_point_ticks.Get().is_null()); - g_browser_exe_main_entry_point_ticks.Get() = ticks; - DCHECK(!g_browser_exe_main_entry_point_ticks.Get().is_null()); + DCHECK(g_browser_exe_main_entry_point_ticks.is_null()); + g_browser_exe_main_entry_point_ticks = ticks; + DCHECK(!g_browser_exe_main_entry_point_ticks.is_null()); } void RecordMessageLoopStartTicks(base::TimeTicks ticks) { - DCHECK(g_message_loop_start_ticks.Get().is_null()); - g_message_loop_start_ticks.Get() = ticks; - DCHECK(!g_message_loop_start_ticks.Get().is_null()); + DCHECK(g_message_loop_start_ticks.is_null()); + g_message_loop_start_ticks = ticks; + DCHECK(!g_message_loop_start_ticks.is_null()); } void RecordBrowserMainMessageLoopStart(base::TimeTicks ticks, @@ -584,11 +573,10 @@ // Record timing of the browser message-loop start time. base::StackSamplingProfiler::SetProcessMilestone( metrics::CallStackProfileMetricsProvider::MAIN_LOOP_START); - const base::TimeTicks process_creation_ticks = g_process_creation_ticks.Get(); - if (!is_first_run && !process_creation_ticks.is_null()) { + if (!is_first_run && !g_process_creation_ticks.is_null()) { UMA_HISTOGRAM_AND_TRACE_WITH_TEMPERATURE_AND_SAME_VERSION_COUNT( UMA_HISTOGRAM_LONG_TIMES_100, "Startup.BrowserMessageLoopStartTime", - process_creation_ticks, ticks); + g_process_creation_ticks, ticks); } // Record timing between the shared library's main() entry and the browser @@ -597,14 +585,14 @@ UMA_HISTOGRAM_AND_TRACE_WITH_TEMPERATURE( UMA_HISTOGRAM_LONG_TIMES, "Startup.BrowserMessageLoopStartTimeFromMainEntry.FirstRun2", - g_browser_main_entry_point_ticks_computed_from_time.Get(), ticks); + g_browser_main_entry_point_ticks_computed_from_time, ticks); } else { // TODO(pasko): Stop recording the "...MainEntry2" histogram after M65 hits // Stable. UMA_HISTOGRAM_AND_TRACE_WITH_TEMPERATURE_AND_SAME_VERSION_COUNT( UMA_HISTOGRAM_LONG_TIMES, "Startup.BrowserMessageLoopStartTimeFromMainEntry2", - g_browser_main_entry_point_ticks_computed_from_time.Get(), ticks); + g_browser_main_entry_point_ticks_computed_from_time, ticks); UMA_HISTOGRAM_AND_TRACE_WITH_TEMPERATURE_AND_SAME_VERSION_COUNT( UMA_HISTOGRAM_LONG_TIMES, "Startup.BrowserMessageLoopStartTimeFromMainEntry3", @@ -617,27 +605,25 @@ // Record timings between process creation, the main() in the executable being // reached and the main() in the shared library being reached. - if (!process_creation_ticks.is_null() && - !g_browser_exe_main_entry_point_ticks.Get().is_null()) { - const base::TimeTicks exe_main_ticks = - g_browser_exe_main_entry_point_ticks.Get(); - const base::TimeTicks main_entry_ticks = - g_browser_main_entry_point_ticks_computed_from_time.Get(); + if (!g_process_creation_ticks.is_null() && + !g_browser_exe_main_entry_point_ticks.is_null()) { // Process create to chrome.exe:main(). UMA_HISTOGRAM_AND_TRACE_WITH_TEMPERATURE_AND_SAME_VERSION_COUNT( UMA_HISTOGRAM_LONG_TIMES, "Startup.LoadTime.ProcessCreateToExeMain2", - process_creation_ticks, exe_main_ticks); + g_process_creation_ticks, g_browser_exe_main_entry_point_ticks); // chrome.exe:main() to chrome.dll:main(). UMA_HISTOGRAM_AND_TRACE_WITH_TEMPERATURE_AND_SAME_VERSION_COUNT( UMA_HISTOGRAM_LONG_TIMES, "Startup.LoadTime.ExeMainToDllMain2", - exe_main_ticks, main_entry_ticks); + g_browser_exe_main_entry_point_ticks, + g_browser_main_entry_point_ticks_computed_from_time); // Process create to chrome.dll:main(). Reported as a histogram only as // the other two events above are sufficient for tracing purposes. UMA_HISTOGRAM_WITH_TEMPERATURE_AND_SAME_VERSION_COUNT( UMA_HISTOGRAM_LONG_TIMES, "Startup.LoadTime.ProcessCreateToDllMain2", - main_entry_ticks - process_creation_ticks); + g_browser_main_entry_point_ticks_computed_from_time - + g_process_creation_ticks); } } @@ -651,7 +637,7 @@ UMA_HISTOGRAM_AND_TRACE_WITH_TEMPERATURE_AND_SAME_VERSION_COUNT( UMA_HISTOGRAM_LONG_TIMES, "Startup.BrowserWindowDisplay", - g_process_creation_ticks.Get(), ticks); + g_process_creation_ticks, ticks); } void RecordBrowserOpenTabsDelta(base::TimeDelta delta) { @@ -667,8 +653,8 @@ void RecordRendererMainEntryTime(base::TimeTicks ticks) { // Record the renderer main entry time, but don't log the UMA metric // immediately because the startup temperature is not known yet. - if (g_renderer_main_entry_point_ticks.Get().is_null()) - g_renderer_main_entry_point_ticks.Get() = ticks; + if (g_renderer_main_entry_point_ticks.is_null()) + g_renderer_main_entry_point_ticks = ticks; } void RecordFirstWebContentsMainFrameLoad(base::TimeTicks ticks) { @@ -681,7 +667,7 @@ UMA_HISTOGRAM_AND_TRACE_WITH_TEMPERATURE_AND_SAME_VERSION_COUNT( UMA_HISTOGRAM_LONG_TIMES_100, "Startup.FirstWebContents.MainFrameLoad2", - g_process_creation_ticks.Get(), ticks); + g_process_creation_ticks, ticks); } void RecordFirstWebContentsNonEmptyPaint( @@ -703,11 +689,11 @@ metrics::CallStackProfileMetricsProvider::FIRST_NONEMPTY_PAINT); UMA_HISTOGRAM_AND_TRACE_WITH_TEMPERATURE_AND_SAME_VERSION_COUNT( UMA_HISTOGRAM_LONG_TIMES_100, "Startup.FirstWebContents.NonEmptyPaint2", - g_process_creation_ticks.Get(), now); + g_process_creation_ticks, now); UMA_HISTOGRAM_WITH_TEMPERATURE( UMA_HISTOGRAM_LONG_TIMES_100, "Startup.BrowserMessageLoopStart.To.NonEmptyPaint2", - now - g_message_loop_start_ticks.Get()); + now - g_message_loop_start_ticks); UMA_HISTOGRAM_WITH_TEMPERATURE( UMA_HISTOGRAM_LONG_TIMES_100, @@ -728,12 +714,12 @@ metrics::CallStackProfileMetricsProvider::MAIN_NAVIGATION_START); UMA_HISTOGRAM_AND_TRACE_WITH_TEMPERATURE_AND_SAME_VERSION_COUNT( UMA_HISTOGRAM_LONG_TIMES_100, - "Startup.FirstWebContents.MainNavigationStart", - g_process_creation_ticks.Get(), ticks); + "Startup.FirstWebContents.MainNavigationStart", g_process_creation_ticks, + ticks); UMA_HISTOGRAM_WITH_TEMPERATURE( UMA_HISTOGRAM_LONG_TIMES_100, "Startup.BrowserMessageLoopStart.To.MainNavigationStart", - ticks - g_message_loop_start_ticks.Get()); + ticks - g_message_loop_start_ticks); // Log extra information about this startup's workload. Only added to this // histogram as this extra suffix can help making it less noisy but isn't @@ -742,12 +728,12 @@ UMA_HISTOGRAM_WITH_TEMPERATURE( UMA_HISTOGRAM_LONG_TIMES_100, "Startup.FirstWebContents.MainNavigationStart.SingleTab", - ticks - g_process_creation_ticks.Get()); + ticks - g_process_creation_ticks); } else { UMA_HISTOGRAM_WITH_TEMPERATURE( UMA_HISTOGRAM_LONG_TIMES_100, "Startup.FirstWebContents.MainNavigationStart.MultiTabs", - ticks - g_process_creation_ticks.Get()); + ticks - g_process_creation_ticks); } } @@ -764,7 +750,7 @@ UMA_HISTOGRAM_AND_TRACE_WITH_TEMPERATURE_AND_SAME_VERSION_COUNT( UMA_HISTOGRAM_LONG_TIMES_100, "Startup.FirstWebContents.MainNavigationFinished", - g_process_creation_ticks.Get(), ticks); + g_process_creation_ticks, ticks); } void RecordBrowserWindowFirstPaint(base::TimeTicks ticks) { @@ -775,9 +761,9 @@ if (!ShouldLogStartupHistogram()) return; - UMA_HISTOGRAM_AND_TRACE_WITH_TEMPERATURE( - UMA_HISTOGRAM_LONG_TIMES_100, "Startup.BrowserWindow.FirstPaint", - g_process_creation_ticks.Get(), ticks); + UMA_HISTOGRAM_AND_TRACE_WITH_TEMPERATURE(UMA_HISTOGRAM_LONG_TIMES_100, + "Startup.BrowserWindow.FirstPaint", + g_process_creation_ticks, ticks); } void RecordBrowserWindowFirstPaintCompositingEnded( @@ -792,11 +778,11 @@ UMA_HISTOGRAM_AND_TRACE_WITH_TEMPERATURE( UMA_HISTOGRAM_LONG_TIMES_100, "Startup.BrowserWindow.FirstPaint.CompositingEnded", - g_process_creation_ticks.Get(), ticks); + g_process_creation_ticks, ticks); } base::TimeTicks MainEntryPointTicks() { - return g_browser_main_entry_point_ticks_computed_from_time.Get(); + return g_browser_main_entry_point_ticks_computed_from_time; } } // namespace startup_metric_utils
diff --git a/components/viz/common/display/renderer_settings.h b/components/viz/common/display/renderer_settings.h index 653b258..dece05fe 100644 --- a/components/viz/common/display/renderer_settings.h +++ b/components/viz/common/display/renderer_settings.h
@@ -26,7 +26,7 @@ bool finish_rendering_on_resize = false; bool should_clear_root_render_pass = true; bool release_overlay_resources_after_gpu_query = false; - bool gl_composited_overlay_candidate_quad_border = false; + bool tint_gl_composited_content = false; bool show_overdraw_feedback = false; bool enable_draw_occlusion = false; bool use_skia_renderer = false;
diff --git a/components/viz/host/renderer_settings_creation.cc b/components/viz/host/renderer_settings_creation.cc index 8c46467..991c6b1 100644 --- a/components/viz/host/renderer_settings_creation.cc +++ b/components/viz/host/renderer_settings_creation.cc
@@ -49,9 +49,8 @@ #elif defined(OS_MACOSX) renderer_settings.release_overlay_resources_after_gpu_query = true; #endif - renderer_settings.gl_composited_overlay_candidate_quad_border = - command_line->HasSwitch( - switches::kGlCompositedOverlayCandidateQuadBorder); + renderer_settings.tint_gl_composited_content = + command_line->HasSwitch(switches::kTintGlCompositedContent); renderer_settings.show_overdraw_feedback = command_line->HasSwitch(switches::kShowOverdrawFeedback); renderer_settings.enable_draw_occlusion =
diff --git a/components/viz/service/display/gl_renderer.cc b/components/viz/service/display/gl_renderer.cc index e31cf7ef..07b625da 100644 --- a/components/viz/service/display/gl_renderer.cc +++ b/components/viz/service/display/gl_renderer.cc
@@ -413,8 +413,6 @@ &texture_deleter_, base::BindRepeating(&GLRenderer::MoveFromDrawToWindowSpace, base::Unretained(this))), - gl_composited_overlay_candidate_quad_border_( - settings->gl_composited_overlay_candidate_quad_border), bound_geometry_(NO_BINDING), color_lut_cache_(gl_, output_surface_->context_provider() @@ -1434,11 +1432,12 @@ sampler_type = SamplerTypeFromTextureTarget(params->mask_resource_lock->target()); } - SetUseProgram(ProgramKey::RenderPass( - tex_coord_precision, sampler_type, shader_blend_mode, - params->use_aa ? USE_AA : NO_AA, mask_mode, - mask_for_background, params->use_color_matrix), - params->contents_and_bypass_color_space, target_color_space); + SetUseProgram( + ProgramKey::RenderPass( + tex_coord_precision, sampler_type, shader_blend_mode, + params->use_aa ? USE_AA : NO_AA, mask_mode, mask_for_background, + params->use_color_matrix, tint_gl_composited_content_), + params->contents_and_bypass_color_space, target_color_space); } void GLRenderer::UpdateRPDQUniforms(DrawRenderPassDrawQuadParams* params) { @@ -1518,6 +1517,7 @@ gl_->UniformMatrix4fv(current_program_->color_matrix_location(), 1, false, matrix); } + static const float kScale = 1.0f / 255.0f; if (current_program_->color_offset_location() != -1) { float offset[4]; @@ -1527,6 +1527,12 @@ gl_->Uniform4fv(current_program_->color_offset_location(), 1, offset); } + if (current_program_->tint_color_matrix_location() != -1) { + auto matrix = cc::DebugColors::TintCompositedContentColorTransformMatrix(); + gl_->UniformMatrix4fv(current_program_->tint_color_matrix_location(), 1, + false, matrix.data()); + } + if (current_program_->backdrop_location() != -1) { DCHECK(params->background_texture || params->background_image_id); DCHECK_NE(current_program_->backdrop_location(), 0); @@ -1888,11 +1894,18 @@ clip_region, &local_quad, edge); gfx::ColorSpace quad_color_space = gfx::ColorSpace::CreateSRGB(); - SetUseProgram(ProgramKey::SolidColor(use_aa ? USE_AA : NO_AA), + SetUseProgram(ProgramKey::SolidColor(use_aa ? USE_AA : NO_AA, + tint_gl_composited_content_), quad_color_space, current_frame()->current_render_pass->color_space); SetShaderColor(color, opacity); + if (current_program_->tint_color_matrix_location() != -1) { + auto matrix = cc::DebugColors::TintCompositedContentColorTransformMatrix(); + gl_->UniformMatrix4fv(current_program_->tint_color_matrix_location(), 1, + false, matrix.data()); + } + if (use_aa) { gl_->Uniform3fv(current_program_->edge_location(), 8, edge); } @@ -1935,19 +1948,6 @@ void GLRenderer::DrawTileQuad(const TileDrawQuad* quad, const gfx::QuadF* clip_region) { DrawContentQuad(quad, quad->resource_id(), clip_region); - // Draw the border if requested. - if (gl_composited_overlay_candidate_quad_border_) { - float gl_matrix[16]; - // Generate the transform matrix - gfx::Transform quad_rect_matrix; - QuadRectTransform(&quad_rect_matrix, - quad->shared_quad_state->quad_to_target_transform, - gfx::RectF(quad->rect)); - quad_rect_matrix = current_frame()->projection_matrix * quad_rect_matrix; - ToGLMatrix(gl_matrix, quad_rect_matrix); - - DrawOverlayCandidateQuadBorder(gl_matrix); - } } void GLRenderer::DrawContentQuad(const ContentDrawQuadBase* quad, @@ -2058,10 +2058,17 @@ SetUseProgram( ProgramKey::Tile(tex_coord_precision, sampler, USE_AA, - quad->swizzle_contents ? DO_SWIZZLE : NO_SWIZZLE, false), + quad->swizzle_contents ? DO_SWIZZLE : NO_SWIZZLE, false, + tint_gl_composited_content_), quad_resource_lock.color_space(), current_frame()->current_render_pass->color_space); + if (current_program_->tint_color_matrix_location() != -1) { + auto matrix = cc::DebugColors::TintCompositedContentColorTransformMatrix(); + gl_->UniformMatrix4fv(current_program_->tint_color_matrix_location(), 1, + false, matrix.data()); + } + gl_->Uniform3fv(current_program_->edge_location(), 8, edge); gl_->Uniform4f(current_program_->vertex_tex_transform_location(), @@ -2136,10 +2143,17 @@ SetUseProgram( ProgramKey::Tile(tex_coord_precision, sampler, NO_AA, quad->swizzle_contents ? DO_SWIZZLE : NO_SWIZZLE, - !quad->ShouldDrawWithBlending()), + !quad->ShouldDrawWithBlending(), + tint_gl_composited_content_), quad_resource_lock.color_space(), current_frame()->current_render_pass->color_space); + if (current_program_->tint_color_matrix_location() != -1) { + auto matrix = cc::DebugColors::TintCompositedContentColorTransformMatrix(); + gl_->UniformMatrix4fv(current_program_->tint_color_matrix_location(), 1, + false, matrix.data()); + } + gl_->Uniform4f(current_program_->vertex_tex_transform_location(), vertex_tex_translate_x, vertex_tex_translate_y, vertex_tex_scale_x, vertex_tex_scale_y); @@ -2245,9 +2259,16 @@ // All planes must have the same sampler type. SamplerType sampler = SamplerTypeFromTextureTarget(y_plane_lock.target()); - SetUseProgram(ProgramKey::YUVVideo(tex_coord_precision, sampler, - alpha_texture_mode, uv_texture_mode), - src_color_space, dst_color_space); + SetUseProgram( + ProgramKey::YUVVideo(tex_coord_precision, sampler, alpha_texture_mode, + uv_texture_mode, tint_gl_composited_content_), + src_color_space, dst_color_space); + + if (current_program_->tint_color_matrix_location() != -1) { + auto matrix = cc::DebugColors::TintCompositedContentColorTransformMatrix(); + gl_->UniformMatrix4fv(current_program_->tint_color_matrix_location(), 1, + false, matrix.data()); + } gfx::SizeF ya_tex_scale(1.0f, 1.0f); gfx::SizeF uv_tex_scale(1.0f, 1.0f); @@ -2393,26 +2414,6 @@ } } -void GLRenderer::DrawOverlayCandidateQuadBorder(float* gl_matrix) { - SetBlendEnabled(false); - SetUseProgram(ProgramKey::DebugBorder(), gfx::ColorSpace::CreateSRGB(), - current_frame()->current_render_pass->color_space); - - gl_->UniformMatrix4fv(current_program_->matrix_location(), 1, false, - gl_matrix); - - // Pick a random color based on the scale on X and Y. - int colorIndex = static_cast<int>(gl_matrix[0] * gl_matrix[5]); - SkColor color = - cc::DebugColors::GLCompositedTextureQuadBorderColor(colorIndex); - SetShaderColor(color, 1.f); - - gl_->LineWidth(cc::DebugColors::GLCompositedTextureQuadBoderWidth()); - // The indices for the line are stored in the same array as the triangle - // indices. - gl_->DrawElements(GL_LINE_LOOP, 4, GL_UNSIGNED_SHORT, nullptr); -} - void GLRenderer::FlushTextureQuadCache(BoundGeometry flush_binding) { // Check to see if we have anything to draw. if (draw_cache_.is_empty) @@ -2449,6 +2450,12 @@ static_cast<int>(draw_cache_.uv_xform_data.size()), reinterpret_cast<float*>(&draw_cache_.uv_xform_data.front())); + if (current_program_->tint_color_matrix_location() != -1) { + auto matrix = cc::DebugColors::TintCompositedContentColorTransformMatrix(); + gl_->UniformMatrix4fv(current_program_->tint_color_matrix_location(), 1, + false, matrix.data()); + } + if (current_program_->tex_clamp_rect_location() != -1) { // Draw batching is not allowed with texture clamping. DCHECK_EQ(1u, draw_cache_.matrix_data.size()); @@ -2479,14 +2486,6 @@ GL_UNSIGNED_SHORT, nullptr); num_triangles_drawn_ += 2 * static_cast<int>(draw_cache_.matrix_data.size()); - // Draw the border if requested. - if (gl_composited_overlay_candidate_quad_border_) { - // When we draw the composited borders we have one flush per quad. - DCHECK_EQ(1u, draw_cache_.matrix_data.size()); - DrawOverlayCandidateQuadBorder( - reinterpret_cast<float*>(&draw_cache_.matrix_data.front())); - } - // Clear the cache. draw_cache_.is_empty = true; draw_cache_.resource_id = -1; @@ -2527,7 +2526,8 @@ ProgramKey program_key = ProgramKey::Texture( tex_coord_precision, sampler, quad->premultiplied_alpha ? PREMULTIPLIED_ALPHA : NON_PREMULTIPLIED_ALPHA, - quad->background_color != SK_ColorTRANSPARENT, need_tex_clamp_rect); + quad->background_color != SK_ColorTRANSPARENT, need_tex_clamp_rect, + tint_gl_composited_content_); int resource_id = quad->resource_id(); size_t max_quads = StaticGeometryBinding::NUM_QUADS; @@ -2609,8 +2609,7 @@ PrepareGeometry(CLIPPED_BINDING); clipped_geometry_->InitializeCustomQuadWithUVs(scaled_region, uv); FlushTextureQuadCache(CLIPPED_BINDING); - } else if (gl_composited_overlay_candidate_quad_border_ || - need_tex_clamp_rect) { + } else if (need_tex_clamp_rect) { FlushTextureQuadCache(SHARED_BINDING); } } @@ -2952,7 +2951,7 @@ void GLRenderer::BindFramebufferToOutputSurface() { current_framebuffer_texture_ = nullptr; output_surface_->BindFramebuffer(); - + tint_gl_composited_content_ = settings_->tint_gl_composited_content; if (overdraw_feedback_) { // Output surfaces that require an external stencil test should not allow // overdraw feedback by setting |supports_stencil| to false. @@ -2968,6 +2967,7 @@ } void GLRenderer::BindFramebufferToTexture(const RenderPassId render_pass_id) { + tint_gl_composited_content_ = false; gl_->BindFramebuffer(GL_FRAMEBUFFER, offscreen_framebuffer_id_); auto contents_texture_it = render_pass_textures_.find(render_pass_id);
diff --git a/components/viz/service/display/gl_renderer.h b/components/viz/service/display/gl_renderer.h index 8ff5ba3..b3ddb34 100644 --- a/components/viz/service/display/gl_renderer.h +++ b/components/viz/service/display/gl_renderer.h
@@ -385,9 +385,8 @@ bool use_occlusion_query_ = false; bool use_swap_with_bounds_ = false; - // If true, draw a green border after compositing a overlay candidate quad - // using GL. - bool gl_composited_overlay_candidate_quad_border_; + // If true, tints all the composited content to red. + bool tint_gl_composited_content_ = true; // The method FlippedFramebuffer determines whether the framebuffer associated // with a DrawingFrame is flipped. It makes the assumption that the
diff --git a/components/viz/service/display/gl_renderer_unittest.cc b/components/viz/service/display/gl_renderer_unittest.cc index 4674bb7d..862f1cf 100644 --- a/components/viz/service/display/gl_renderer_unittest.cc +++ b/components/viz/service/display/gl_renderer_unittest.cc
@@ -206,12 +206,12 @@ void TestBasicShaders() { TestShader(ProgramKey::DebugBorder()); - TestShader(ProgramKey::SolidColor(NO_AA)); - TestShader(ProgramKey::SolidColor(USE_AA)); + TestShader(ProgramKey::SolidColor(NO_AA, false)); + TestShader(ProgramKey::SolidColor(USE_AA, false)); TestShadersWithOutputColorMatrix(ProgramKey::DebugBorder()); - TestShadersWithOutputColorMatrix(ProgramKey::SolidColor(NO_AA)); - TestShadersWithOutputColorMatrix(ProgramKey::SolidColor(USE_AA)); + TestShadersWithOutputColorMatrix(ProgramKey::SolidColor(NO_AA, false)); + TestShadersWithOutputColorMatrix(ProgramKey::SolidColor(USE_AA, false)); } void TestColorShaders() { @@ -240,7 +240,7 @@ gfx::ColorSpace::CreateCustom(primaries, transfer_fns[i]); renderer()->SetCurrentFrameForTesting(GLRenderer::DrawingFrame()); - renderer()->SetUseProgram(ProgramKey::SolidColor(NO_AA), src, + renderer()->SetUseProgram(ProgramKey::SolidColor(NO_AA, false), src, gfx::ColorSpace::CreateXYZD50()); EXPECT_TRUE(renderer()->current_program_->initialized()); } @@ -257,9 +257,9 @@ void TestShadersWithPrecisionAndBlend(TexCoordPrecision precision, BlendMode blend_mode) { TestShader(ProgramKey::RenderPass(precision, SAMPLER_TYPE_2D, blend_mode, - NO_AA, NO_MASK, false, false)); + NO_AA, NO_MASK, false, false, false)); TestShader(ProgramKey::RenderPass(precision, SAMPLER_TYPE_2D, blend_mode, - USE_AA, NO_MASK, false, false)); + USE_AA, NO_MASK, false, false, false)); } void TestShadersWithPrecisionAndSampler(TexCoordPrecision precision, @@ -271,27 +271,33 @@ } TestShader(ProgramKey::Texture(precision, sampler, PREMULTIPLIED_ALPHA, - false, true)); + false, true, false)); TestShader(ProgramKey::Texture(precision, sampler, PREMULTIPLIED_ALPHA, - false, false)); + false, false, false)); TestShader(ProgramKey::Texture(precision, sampler, PREMULTIPLIED_ALPHA, - true, true)); + true, true, false)); TestShader(ProgramKey::Texture(precision, sampler, PREMULTIPLIED_ALPHA, - true, false)); + true, false, false)); TestShader(ProgramKey::Texture(precision, sampler, NON_PREMULTIPLIED_ALPHA, - false, true)); + false, true, false)); TestShader(ProgramKey::Texture(precision, sampler, NON_PREMULTIPLIED_ALPHA, - false, false)); + false, false, false)); TestShader(ProgramKey::Texture(precision, sampler, NON_PREMULTIPLIED_ALPHA, - true, true)); + true, true, false)); TestShader(ProgramKey::Texture(precision, sampler, NON_PREMULTIPLIED_ALPHA, - true, false)); - TestShader(ProgramKey::Tile(precision, sampler, NO_AA, NO_SWIZZLE, false)); - TestShader(ProgramKey::Tile(precision, sampler, NO_AA, DO_SWIZZLE, false)); - TestShader(ProgramKey::Tile(precision, sampler, USE_AA, NO_SWIZZLE, false)); - TestShader(ProgramKey::Tile(precision, sampler, USE_AA, DO_SWIZZLE, false)); - TestShader(ProgramKey::Tile(precision, sampler, NO_AA, NO_SWIZZLE, true)); - TestShader(ProgramKey::Tile(precision, sampler, NO_AA, DO_SWIZZLE, true)); + true, false, false)); + TestShader( + ProgramKey::Tile(precision, sampler, NO_AA, NO_SWIZZLE, false, false)); + TestShader( + ProgramKey::Tile(precision, sampler, NO_AA, DO_SWIZZLE, false, false)); + TestShader( + ProgramKey::Tile(precision, sampler, USE_AA, NO_SWIZZLE, false, false)); + TestShader( + ProgramKey::Tile(precision, sampler, USE_AA, DO_SWIZZLE, false, false)); + TestShader( + ProgramKey::Tile(precision, sampler, NO_AA, NO_SWIZZLE, true, false)); + TestShader( + ProgramKey::Tile(precision, sampler, NO_AA, DO_SWIZZLE, true, false)); // Iterate over alpha plane, nv12, and color_lut parameters. UVTextureMode uv_modes[2] = {UV_TEXTURE_MODE_UV, UV_TEXTURE_MODE_U_V}; @@ -299,8 +305,8 @@ YUV_HAS_ALPHA_TEXTURE}; for (int j = 0; j < 2; j++) { for (int k = 0; k < 2; k++) { - TestShader( - ProgramKey::YUVVideo(precision, sampler, a_modes[j], uv_modes[k])); + TestShader(ProgramKey::YUVVideo(precision, sampler, a_modes[j], + uv_modes[k], false)); } } } @@ -316,13 +322,17 @@ } TestShader(ProgramKey::RenderPass(precision, sampler, blend_mode, NO_AA, - HAS_MASK, mask_for_background, false)); + HAS_MASK, mask_for_background, false, + false)); TestShader(ProgramKey::RenderPass(precision, sampler, blend_mode, NO_AA, - HAS_MASK, mask_for_background, true)); + HAS_MASK, mask_for_background, true, + false)); TestShader(ProgramKey::RenderPass(precision, sampler, blend_mode, USE_AA, - HAS_MASK, mask_for_background, false)); + HAS_MASK, mask_for_background, false, + false)); TestShader(ProgramKey::RenderPass(precision, sampler, blend_mode, USE_AA, - HAS_MASK, mask_for_background, true)); + HAS_MASK, mask_for_background, true, + false)); } }; @@ -503,7 +513,7 @@ BlendMode blend_mode) { const Program* program = renderer_->GetProgramIfInitialized( ProgramKey::RenderPass(precision, SAMPLER_TYPE_2D, blend_mode, NO_AA, - NO_MASK, false, false)); + NO_MASK, false, false, false)); EXPECT_PROGRAM_VALID(program); EXPECT_EQ(program, renderer_->current_program_); } @@ -512,7 +522,7 @@ BlendMode blend_mode) { const Program* program = renderer_->GetProgramIfInitialized( ProgramKey::RenderPass(precision, SAMPLER_TYPE_2D, blend_mode, NO_AA, - NO_MASK, false, true)); + NO_MASK, false, true, false)); EXPECT_PROGRAM_VALID(program); EXPECT_EQ(program, renderer_->current_program_); } @@ -520,9 +530,9 @@ void TestRenderPassMaskProgram(TexCoordPrecision precision, SamplerType sampler, BlendMode blend_mode) { - const Program* program = - renderer_->GetProgramIfInitialized(ProgramKey::RenderPass( - precision, sampler, blend_mode, NO_AA, HAS_MASK, false, false)); + const Program* program = renderer_->GetProgramIfInitialized( + ProgramKey::RenderPass(precision, sampler, blend_mode, NO_AA, HAS_MASK, + false, false, false)); EXPECT_PROGRAM_VALID(program); EXPECT_EQ(program, renderer_->current_program_); } @@ -530,9 +540,9 @@ void TestRenderPassMaskColorMatrixProgram(TexCoordPrecision precision, SamplerType sampler, BlendMode blend_mode) { - const Program* program = - renderer_->GetProgramIfInitialized(ProgramKey::RenderPass( - precision, sampler, blend_mode, NO_AA, HAS_MASK, false, true)); + const Program* program = renderer_->GetProgramIfInitialized( + ProgramKey::RenderPass(precision, sampler, blend_mode, NO_AA, HAS_MASK, + false, true, false)); EXPECT_PROGRAM_VALID(program); EXPECT_EQ(program, renderer_->current_program_); } @@ -541,7 +551,7 @@ BlendMode blend_mode) { const Program* program = renderer_->GetProgramIfInitialized( ProgramKey::RenderPass(precision, SAMPLER_TYPE_2D, blend_mode, USE_AA, - NO_MASK, false, false)); + NO_MASK, false, false, false)); EXPECT_PROGRAM_VALID(program); EXPECT_EQ(program, renderer_->current_program_); } @@ -550,7 +560,7 @@ BlendMode blend_mode) { const Program* program = renderer_->GetProgramIfInitialized( ProgramKey::RenderPass(precision, SAMPLER_TYPE_2D, blend_mode, USE_AA, - NO_MASK, false, true)); + NO_MASK, false, true, false)); EXPECT_PROGRAM_VALID(program); EXPECT_EQ(program, renderer_->current_program_); } @@ -558,9 +568,9 @@ void TestRenderPassMaskProgramAA(TexCoordPrecision precision, SamplerType sampler, BlendMode blend_mode) { - const Program* program = - renderer_->GetProgramIfInitialized(ProgramKey::RenderPass( - precision, sampler, blend_mode, USE_AA, HAS_MASK, false, false)); + const Program* program = renderer_->GetProgramIfInitialized( + ProgramKey::RenderPass(precision, sampler, blend_mode, USE_AA, HAS_MASK, + false, false, false)); EXPECT_PROGRAM_VALID(program); EXPECT_EQ(program, renderer_->current_program_); } @@ -568,16 +578,16 @@ void TestRenderPassMaskColorMatrixProgramAA(TexCoordPrecision precision, SamplerType sampler, BlendMode blend_mode) { - const Program* program = - renderer_->GetProgramIfInitialized(ProgramKey::RenderPass( - precision, sampler, blend_mode, USE_AA, HAS_MASK, false, true)); + const Program* program = renderer_->GetProgramIfInitialized( + ProgramKey::RenderPass(precision, sampler, blend_mode, USE_AA, HAS_MASK, + false, true, false)); EXPECT_PROGRAM_VALID(program); EXPECT_EQ(program, renderer_->current_program_); } void TestSolidColorProgramAA() { - const Program* program = - renderer_->GetProgramIfInitialized(ProgramKey::SolidColor(USE_AA)); + const Program* program = renderer_->GetProgramIfInitialized( + ProgramKey::SolidColor(USE_AA, false)); EXPECT_PROGRAM_VALID(program); EXPECT_EQ(program, renderer_->current_program_); }
diff --git a/components/viz/service/display/program_binding.cc b/components/viz/service/display/program_binding.cc index 3124169..8ed6bb0 100644 --- a/components/viz/service/display/program_binding.cc +++ b/components/viz/service/display/program_binding.cc
@@ -50,10 +50,11 @@ } // static -ProgramKey ProgramKey::SolidColor(AAMode aa_mode) { +ProgramKey ProgramKey::SolidColor(AAMode aa_mode, bool tint_color) { ProgramKey result; result.type_ = PROGRAM_TYPE_SOLID_COLOR; result.aa_mode_ = aa_mode; + result.has_tint_color_matrix_ = tint_color; return result; } @@ -62,7 +63,8 @@ SamplerType sampler, AAMode aa_mode, SwizzleMode swizzle_mode, - bool is_opaque) { + bool is_opaque, + bool tint_color) { ProgramKey result; result.type_ = PROGRAM_TYPE_TILE; result.precision_ = precision; @@ -70,6 +72,7 @@ result.aa_mode_ = aa_mode; result.swizzle_mode_ = swizzle_mode; result.is_opaque_ = is_opaque; + result.has_tint_color_matrix_ = tint_color; return result; } @@ -78,7 +81,8 @@ SamplerType sampler, PremultipliedAlphaMode premultiplied_alpha, bool has_background_color, - bool has_tex_clamp_rect) { + bool has_tex_clamp_rect, + bool tint_color) { ProgramKey result; result.type_ = PROGRAM_TYPE_TEXTURE; result.precision_ = precision; @@ -86,6 +90,7 @@ result.premultiplied_alpha_ = premultiplied_alpha; result.has_background_color_ = has_background_color; result.has_tex_clamp_rect_ = has_tex_clamp_rect; + result.has_tint_color_matrix_ = tint_color; return result; } @@ -96,7 +101,8 @@ AAMode aa_mode, MaskMode mask_mode, bool mask_for_background, - bool has_color_matrix) { + bool has_color_matrix, + bool tint_color) { ProgramKey result; result.type_ = PROGRAM_TYPE_RENDER_PASS; result.precision_ = precision; @@ -106,6 +112,7 @@ result.mask_mode_ = mask_mode; result.mask_for_background_ = mask_for_background; result.has_color_matrix_ = has_color_matrix; + result.has_tint_color_matrix_ = tint_color; return result; } @@ -122,7 +129,8 @@ ProgramKey ProgramKey::YUVVideo(TexCoordPrecision precision, SamplerType sampler, YUVAlphaTextureMode yuv_alpha_texture_mode, - UVTextureMode uv_texture_mode) { + UVTextureMode uv_texture_mode, + bool tint_color) { ProgramKey result; result.type_ = PROGRAM_TYPE_YUV_VIDEO; result.precision_ = precision; @@ -133,6 +141,7 @@ result.uv_texture_mode_ = uv_texture_mode; DCHECK(uv_texture_mode == UV_TEXTURE_MODE_UV || uv_texture_mode == UV_TEXTURE_MODE_U_V); + result.has_tint_color_matrix_ = tint_color; return result; }
diff --git a/components/viz/service/display/program_binding.h b/components/viz/service/display/program_binding.h index c7899a5..2586347 100644 --- a/components/viz/service/display/program_binding.h +++ b/components/viz/service/display/program_binding.h
@@ -77,17 +77,19 @@ ~ProgramKey(); static ProgramKey DebugBorder(); - static ProgramKey SolidColor(AAMode aa_mode); + static ProgramKey SolidColor(AAMode aa_mode, bool tint_color); static ProgramKey Tile(TexCoordPrecision precision, SamplerType sampler, AAMode aa_mode, SwizzleMode swizzle_mode, - bool is_opaque); + bool is_opaque, + bool tint_color); static ProgramKey Texture(TexCoordPrecision precision, SamplerType sampler, PremultipliedAlphaMode premultiplied_alpha, bool has_background_color, - bool has_tex_clamp_rect); + bool has_tex_clamp_rect, + bool tint_color); // TODO(ccameron): Merge |mask_for_background| into MaskMode. static ProgramKey RenderPass(TexCoordPrecision precision, @@ -96,12 +98,14 @@ AAMode aa_mode, MaskMode mask_mode, bool mask_for_background, - bool has_color_matrix); + bool has_color_matrix, + bool tint_color); static ProgramKey VideoStream(TexCoordPrecision precision); static ProgramKey YUVVideo(TexCoordPrecision precision, SamplerType sampler, YUVAlphaTextureMode yuv_alpha_texture_mode, - UVTextureMode uv_texture_mode); + UVTextureMode uv_texture_mode, + bool tint_color); bool operator==(const ProgramKey& other) const; bool operator!=(const ProgramKey& other) const; @@ -141,6 +145,7 @@ bool has_tex_clamp_rect_ = false; bool has_output_color_matrix_ = false; + bool has_tint_color_matrix_ = false; }; struct ProgramKeyHash { @@ -161,7 +166,8 @@ (static_cast<size_t>(key.uv_texture_mode_) << 25) ^ (static_cast<size_t>(key.color_conversion_mode_) << 26) ^ (static_cast<size_t>(key.has_tex_clamp_rect_) << 28) ^ - (static_cast<size_t>(key.has_output_color_matrix_) << 29); + (static_cast<size_t>(key.has_output_color_matrix_) << 29) ^ + (static_cast<size_t>(key.has_tint_color_matrix_) << 30); } }; @@ -183,6 +189,7 @@ fragment_shader_.color_conversion_mode_ = key.color_conversion_mode_; fragment_shader_.color_transform_ = key.color_transform_; fragment_shader_.has_output_color_matrix_ = key.has_output_color_matrix_; + fragment_shader_.has_tint_color_matrix_ = key.has_tint_color_matrix_; switch (key.type_) { case PROGRAM_TYPE_DEBUG_BORDER: @@ -308,6 +315,9 @@ int output_color_matrix_location() const { return fragment_shader_.output_color_matrix_location_; } + int tint_color_matrix_location() const { + return fragment_shader_.tint_color_matrix_location_; + } private: void InitializeDebugBorderProgram() { @@ -351,7 +361,6 @@ fragment_shader_.frag_color_mode_ = FRAG_COLOR_MODE_APPLY_BLEND_MODE; fragment_shader_.has_uniform_alpha_ = true; } - // AA changes the texture coordinate mode (affecting both shaders). if (key.aa_mode_ == USE_AA) { vertex_shader_.tex_coord_source_ = TEX_COORD_SOURCE_POSITION;
diff --git a/components/viz/service/display/shader.cc b/components/viz/service/display/shader.cc index 655bc84..2daf4dc2 100644 --- a/components/viz/service/display/shader.cc +++ b/components/viz/service/display/shader.cc
@@ -472,6 +472,9 @@ if (has_output_color_matrix_) uniforms.emplace_back("output_color_matrix"); + if (has_tint_color_matrix_) + uniforms.emplace_back("tint_color_matrix"); + locations.resize(uniforms.size()); GetProgramUniformLocations(context, program, uniforms.size(), uniforms.data(), @@ -531,6 +534,9 @@ if (has_output_color_matrix_) output_color_matrix_location_ = locations[index++]; + if (has_tint_color_matrix_) + tint_color_matrix_location_ = locations[index++]; + DCHECK_EQ(index, locations.size()); } @@ -1024,6 +1030,13 @@ SRC("texColor = output_color_matrix * texColor;"); } + // Tint the final color. Used for debugging composited content. + if (has_tint_color_matrix_) { + HDR("uniform mat4 tint_color_matrix;"); + SRC("// Apply the tint color matrix"); + SRC("texColor = tint_color_matrix * texColor;"); + } + // Include header text for alpha. if (has_uniform_alpha_) { HDR("uniform float alpha;");
diff --git a/components/viz/service/display/shader.h b/components/viz/service/display/shader.h index a51e584..c9e6dcc 100644 --- a/components/viz/service/display/shader.h +++ b/components/viz/service/display/shader.h
@@ -297,6 +297,9 @@ bool has_output_color_matrix_ = false; int output_color_matrix_location_ = -1; + bool has_tint_color_matrix_ = false; + int tint_color_matrix_location_ = -1; + // YUV uniform locations. int y_texture_location_ = -1; int u_texture_location_ = -1;
diff --git a/components/viz/service/display/skia_renderer.cc b/components/viz/service/display/skia_renderer.cc index 3a8d4273..6141e96 100644 --- a/components/viz/service/display/skia_renderer.cc +++ b/components/viz/service/display/skia_renderer.cc
@@ -613,10 +613,16 @@ RenderPassBacking& content_texture = render_pass_backings_[quad->render_pass_id]; DCHECK(content_texture.gl_id); - cc::DisplayResourceProvider::ScopedReadLockSkImage lock( - resource_provider_, content_texture.gl_id); - if (!lock.sk_image()) - return; + + GrGLTextureInfo texture_info; + texture_info.fID = content_texture.gl_id; + texture_info.fTarget = GL_TEXTURE_2D; + GrBackendTexture backend_texture( + content_texture.size.width(), content_texture.size.height(), + ToGrPixelConfig(content_texture.format), texture_info); + sk_sp<SkImage> content = SkImage::MakeFromTexture( + output_surface_->context_provider()->GrContext(), backend_texture, + kTopLeft_GrSurfaceOrigin, kPremul_SkAlphaType, nullptr); SkRect dest_rect = gfx::RectFToSkRect(QuadVertexRect()); SkRect dest_visible_rect = @@ -625,10 +631,8 @@ gfx::RectF(quad->visible_rect))); SkRect content_rect = RectFToSkRect(quad->tex_coord_rect); - const SkImage* content = lock.sk_image(); - - current_canvas_->drawImageRect(lock.sk_image(), content_rect, - dest_visible_rect, ¤t_paint_); + current_canvas_->drawImageRect(content, content_rect, dest_visible_rect, + ¤t_paint_); const cc::FilterOperations* filters = FiltersForPass(quad->render_pass_id);
diff --git a/components/web_contents_delegate_android/web_contents_delegate_android.cc b/components/web_contents_delegate_android/web_contents_delegate_android.cc index 7d89ab6..296832bf 100644 --- a/components/web_contents_delegate_android/web_contents_delegate_android.cc +++ b/components/web_contents_delegate_android/web_contents_delegate_android.cc
@@ -19,6 +19,7 @@ #include "content/public/browser/render_widget_host_view.h" #include "content/public/browser/web_contents.h" #include "content/public/common/referrer.h" +#include "content/public/common/resource_request_body_android.h" #include "jni/WebContentsDelegateAndroid_jni.h" #include "ui/base/window_open_disposition.h" #include "ui/gfx/geometry/rect.h" @@ -90,8 +91,10 @@ ScopedJavaLocalRef<jstring> extra_headers = ConvertUTF8ToJavaString(env, params.extra_headers); ScopedJavaLocalRef<jobject> post_data; - if (params.uses_post && params.post_data) - post_data = params.post_data->ToJavaObject(env); + if (params.uses_post && params.post_data) { + post_data = content::ConvertResourceRequestBodyToJavaObject( + env, params.post_data); + } Java_WebContentsDelegateAndroid_openNewTab( env, obj, java_url, extra_headers, post_data, static_cast<int>(disposition), params.is_renderer_initiated);
diff --git a/content/app/strings/content_strings.grd b/content/app/strings/content_strings.grd index f8f5134..0f24ccd 100644 --- a/content/app/strings/content_strings.grd +++ b/content/app/strings/content_strings.grd
@@ -818,6 +818,15 @@ <message name="IDS_MEDIA_REMOTING_CAST_TO_UNKNOWN_DEVICE_TEXT" desc="Text message shown to the user when casting a video to an unknown remote device."> Now casting to your TV </message> + <message name = "IDS_MEDIA_REMOTING_STOP_TEXT" desc="The transient text shown on top of the video when switching from media remoting to mirroring."> + Switched to mirroring + </message> + <message name = "IDS_MEDIA_REMOTING_STOP_BY_PLAYBACK_QUALITY_TEXT" desc="The transient text shown on top of the video when switching from media remoting to mirroring due to poor playback quality."> + Poor playback quality + </message> + <message name = "IDS_MEDIA_REMOTING_STOP_BY_ERROR_TEXT" desc="The transient text shown on top of the video when switching from media remoting to mirroring due to errors."> + Video playback error + </message> <message name="IDS_MEDIA_TRACKS_NO_LABEL" desc="Menu item label for a text track that has no name specified. The number represents the track number in the list of tracks."> Track <ph name="NUMBER">$1<ex>1</ex></ph> </message>
diff --git a/content/browser/BUILD.gn b/content/browser/BUILD.gn index 72fa6d3..0bde87b 100644 --- a/content/browser/BUILD.gn +++ b/content/browser/BUILD.gn
@@ -714,6 +714,8 @@ "download/download_stats.h", "download/download_task_runner.cc", "download/download_task_runner.h", + "download/download_ukm_helper.cc", + "download/download_ukm_helper.h", "download/download_utils.cc", "download/download_utils.h", "download/download_worker.cc", @@ -2116,6 +2118,7 @@ "//media/capture/content/android", "//media/capture/video/android", "//ui/android", + "//ui/compositor", ] defines += [ "APPCACHE_USE_SIMPLE_CACHE",
diff --git a/content/browser/android/overscroll_controller_android_unittest.cc b/content/browser/android/overscroll_controller_android_unittest.cc index 21b2012a..e9de8e7 100644 --- a/content/browser/android/overscroll_controller_android_unittest.cc +++ b/content/browser/android/overscroll_controller_android_unittest.cc
@@ -33,6 +33,7 @@ class MockCompositor : public WindowAndroidCompositor { public: + ~MockCompositor() override {} void AttachLayerForReadback(scoped_refptr<cc::Layer>) override {} void RequestCopyOfOutputOnRootLayer( std::unique_ptr<viz::CopyOutputRequest>) override {} @@ -41,6 +42,12 @@ MOCK_METHOD0(GetFrameSinkId, viz::FrameSinkId()); void AddChildFrameSink(const viz::FrameSinkId& frame_sink_id) override {} void RemoveChildFrameSink(const viz::FrameSinkId& frame_sink_id) override {} + std::unique_ptr<ui::CompositorLock> GetCompositorLock( + ui::CompositorLockClient* client, + base::TimeDelta timeout) override { + return nullptr; + } + bool IsDrawingFirstVisibleFrame() const override { return false; } }; class MockGlowClient : public OverscrollGlowClient {
diff --git a/content/browser/android/selection_popup_controller.cc b/content/browser/android/selection_popup_controller.cc index c86c4555..2191c039 100644 --- a/content/browser/android/selection_popup_controller.cc +++ b/content/browser/android/selection_popup_controller.cc
@@ -11,7 +11,7 @@ #include "content/browser/renderer_host/render_widget_host_view_android.h" #include "content/browser/web_contents/web_contents_impl.h" #include "content/public/common/context_menu_params.h" -#include "jni/SelectionPopupController_jni.h" +#include "jni/SelectionPopupControllerImpl_jni.h" #include "third_party/WebKit/public/web/WebContextMenuData.h" #include "ui/gfx/geometry/point_conversions.h" @@ -24,7 +24,7 @@ namespace content { -void JNI_SelectionPopupController_Init( +void JNI_SelectionPopupControllerImpl_Init( JNIEnv* env, const JavaParamRef<jobject>& obj, const JavaParamRef<jobject>& jweb_contents) { @@ -50,7 +50,7 @@ if (obj.is_null()) return nullptr; - return Java_SelectionPopupController_getContext(env, obj); + return Java_SelectionPopupControllerImpl_getContext(env, obj); } std::unique_ptr<ui::TouchHandleDrawable> @@ -106,7 +106,7 @@ if (obj.is_null()) return; - Java_SelectionPopupController_onSelectionEvent( + Java_SelectionPopupControllerImpl_onSelectionEvent( env, obj, event, selection_rect.x(), selection_rect.y(), selection_rect.right(), selection_rect.bottom(), bound_middle_point.x(), bound_middle_point.y()); @@ -118,7 +118,7 @@ if (obj.is_null()) return; ScopedJavaLocalRef<jstring> jtext = ConvertUTF8ToJavaString(env, text); - Java_SelectionPopupController_onSelectionChanged(env, obj, jtext); + Java_SelectionPopupControllerImpl_onSelectionChanged(env, obj, jtext); } bool SelectionPopupController::ShowSelectionMenu( @@ -158,7 +158,7 @@ const bool should_suggest = params.source_type == ui::MENU_SOURCE_TOUCH || params.source_type == ui::MENU_SOURCE_LONG_PRESS; - Java_SelectionPopupController_showSelectionMenu( + Java_SelectionPopupControllerImpl_showSelectionMenu( env, obj, params.selection_rect.x(), params.selection_rect.y(), params.selection_rect.right(), params.selection_rect.bottom(), handle_height, params.is_editable, is_password_type, jselected_text, @@ -173,7 +173,7 @@ ScopedJavaLocalRef<jobject> obj = java_obj_.get(env); if (obj.is_null()) return; - Java_SelectionPopupController_onShowUnhandledTapUIIfNeeded( + Java_SelectionPopupControllerImpl_onShowUnhandledTapUIIfNeeded( env, obj, static_cast<jint>(x_px), static_cast<jint>(y_px)); } @@ -184,7 +184,7 @@ ScopedJavaLocalRef<jobject> obj = java_obj_.get(env); if (obj.is_null()) return; - Java_SelectionPopupController_onSelectWordAroundCaretAck( + Java_SelectionPopupControllerImpl_onSelectWordAroundCaretAck( env, obj, did_select, start_adjust, end_adjust); }
diff --git a/content/browser/devtools/devtools_session.cc b/content/browser/devtools/devtools_session.cc index 5fc3bdb6..8c9cac4 100644 --- a/content/browser/devtools/devtools_session.cc +++ b/content/browser/devtools/devtools_session.cc
@@ -196,37 +196,19 @@ void DevToolsSession::DispatchProtocolMessage( blink::mojom::DevToolsMessageChunkPtr chunk) { - if (chunk->is_first) { - if (response_message_buffer_size_ != 0) { - ReceivedBadMessage(); - return; - } - if (chunk->is_last) { - response_message_buffer_size_ = chunk->data.size(); - } else { - response_message_buffer_size_ = chunk->message_size; - response_message_buffer_.reserve(chunk->message_size); - } - } - - if (response_message_buffer_.size() + chunk->data.size() > - response_message_buffer_size_) { + if (chunk->is_first && !response_message_buffer_.empty()) { ReceivedBadMessage(); return; } - response_message_buffer_.append(std::move(chunk->data)); + + response_message_buffer_ += std::move(chunk->data); if (!chunk->is_last) return; - if (response_message_buffer_.size() != response_message_buffer_size_) { - ReceivedBadMessage(); - return; - } if (!chunk->post_state.empty()) state_cookie_ = std::move(chunk->post_state); waiting_for_response_messages_.erase(chunk->call_id); - response_message_buffer_size_ = 0; std::string message; message.swap(response_message_buffer_); client_->DispatchProtocolMessage(agent_host_, message);
diff --git a/content/browser/download/download_create_info.cc b/content/browser/download/download_create_info.cc index e7741fb..c982cc7 100644 --- a/content/browser/download/download_create_info.cc +++ b/content/browser/download/download_create_info.cc
@@ -26,7 +26,8 @@ save_info(std::move(save_info)), accept_range(false), connection_info(net::HttpResponseInfo::CONNECTION_INFO_UNKNOWN), - method("GET") {} + method("GET"), + ukm_source_id(ukm::kInvalidSourceId) {} DownloadCreateInfo::DownloadCreateInfo() : DownloadCreateInfo(base::Time(),
diff --git a/content/browser/download/download_create_info.h b/content/browser/download/download_create_info.h index acc0da42..c9ce1e31 100644 --- a/content/browser/download/download_create_info.h +++ b/content/browser/download/download_create_info.h
@@ -21,6 +21,7 @@ #include "content/public/browser/download_interrupt_reasons.h" #include "content/public/browser/download_save_info.h" #include "net/http/http_response_info.h" +#include "services/metrics/public/cpp/ukm_source_id.h" #include "ui/base/page_transition_types.h" #include "url/gurl.h" @@ -142,6 +143,9 @@ // response. bool fetch_error_body = false; + // Source ID generated for UKM. + ukm::SourceId ukm_source_id; + private: DISALLOW_COPY_AND_ASSIGN(DownloadCreateInfo); };
diff --git a/content/browser/download/download_manager_impl.cc b/content/browser/download/download_manager_impl.cc index fed07b1..70585955 100644 --- a/content/browser/download/download_manager_impl.cc +++ b/content/browser/download/download_manager_impl.cc
@@ -16,6 +16,7 @@ #include "base/memory/weak_ptr.h" #include "base/message_loop/message_loop.h" #include "base/metrics/histogram_macros.h" +#include "base/rand_util.h" #include "base/stl_util.h" #include "base/strings/stringprintf.h" #include "base/strings/sys_string_conversions.h" @@ -60,6 +61,7 @@ #include "net/base/request_priority.h" #include "net/base/upload_bytes_element_reader.h" #include "net/url_request/url_request_context.h" +#include "services/metrics/public/cpp/ukm_source_id.h" #include "storage/browser/blob/blob_url_request_job_factory.h" #include "url/origin.h" @@ -131,6 +133,16 @@ params->callback())); } +download::DownloadEntry CreateDownloadEntryFromItem(const DownloadItem& item) { + // Get a new UKM download_id that is not 0. + uint64_t download_id = 0; + do { + download_id = base::RandUint64(); + } while (download_id == 0); + + return download::DownloadEntry(item.GetGuid(), download_id); +} + DownloadManagerImpl::UniqueUrlDownloadHandlerPtr BeginDownload( std::unique_ptr<DownloadUrlParameters> params, content::ResourceContext* resource_context, @@ -547,6 +559,17 @@ #endif if (delegate_) { + download::InProgressCache* in_progress_cache = + delegate_->GetInProgressCache(); + if (in_progress_cache) { + base::Optional<download::DownloadEntry> entry_opt = + in_progress_cache->RetrieveEntry(download->GetGuid()); + if (!entry_opt.has_value()) { + in_progress_cache->AddOrReplaceEntry( + CreateDownloadEntryFromItem(*download)); + } + } + if (!in_progress_download_observer_) { in_progress_download_observer_.reset( new InProgressDownloadObserver(delegate_->GetInProgressCache())); @@ -629,12 +652,13 @@ const GURL& page_url, const std::string& mime_type, std::unique_ptr<DownloadRequestHandleInterface> request_handle, + const ukm::SourceId ukm_source_id, const DownloadItemImplCreated& item_created) { DCHECK_CURRENTLY_ON(BrowserThread::UI); GetNextId(base::Bind( &DownloadManagerImpl::CreateSavePackageDownloadItemWithId, weak_factory_.GetWeakPtr(), main_file_path, page_url, mime_type, - base::Passed(std::move(request_handle)), item_created)); + base::Passed(std::move(request_handle)), ukm_source_id, item_created)); } void DownloadManagerImpl::CreateSavePackageDownloadItemWithId( @@ -642,6 +666,7 @@ const GURL& page_url, const std::string& mime_type, std::unique_ptr<DownloadRequestHandleInterface> request_handle, + const ukm::SourceId ukm_source_id, const DownloadItemImplCreated& item_created, uint32_t id) { DCHECK_CURRENTLY_ON(BrowserThread::UI); @@ -656,6 +681,21 @@ observer.OnDownloadCreated(this, download_item); if (!item_created.is_null()) item_created.Run(download_item); + + // Add download_id and source_id for UKM. + auto* delegate = GetDelegate(); + if (delegate) { + download::InProgressCache* in_progress_cache = + delegate_->GetInProgressCache(); + if (in_progress_cache) { + base::Optional<download::DownloadEntry> entry_opt = + in_progress_cache->RetrieveEntry(download_item->GetGuid()); + if (!entry_opt.has_value()) { + in_progress_cache->AddOrReplaceEntry( + CreateDownloadEntryFromItem(*download_item)); + } + } + } } // Resume a download of a specific URL. We send the request to the @@ -1038,14 +1078,6 @@ void DownloadManagerImpl::BeginDownloadInternal( std::unique_ptr<content::DownloadUrlParameters> params, uint32_t id) { - download::InProgressCache* in_progress_cache = - GetBrowserContext()->GetDownloadManagerDelegate()->GetInProgressCache(); - if (in_progress_cache) { - in_progress_cache->AddOrReplaceEntry( - download::DownloadEntry(params->guid(), params->request_origin(), - ToDownloadSource(params->download_source()))); - } - if (base::FeatureList::IsEnabled(features::kNetworkService)) { std::unique_ptr<ResourceRequest> request = CreateResourceRequest( params.get());
diff --git a/content/browser/download/download_manager_impl.h b/content/browser/download/download_manager_impl.h index b09a8a1..2988038 100644 --- a/content/browser/download/download_manager_impl.h +++ b/content/browser/download/download_manager_impl.h
@@ -29,6 +29,7 @@ #include "content/public/browser/download_manager_delegate.h" #include "content/public/browser/download_url_parameters.h" #include "content/public/browser/ssl_status.h" +#include "services/metrics/public/cpp/ukm_source_id.h" namespace content { class DownloadFileFactory; @@ -60,6 +61,7 @@ const GURL& page_url, const std::string& mime_type, std::unique_ptr<DownloadRequestHandleInterface> request_handle, + const ukm::SourceId ukm_source_id, const DownloadItemImplCreated& item_created); // DownloadManager functions. @@ -175,6 +177,7 @@ const GURL& page_url, const std::string& mime_type, std::unique_ptr<DownloadRequestHandleInterface> request_handle, + const ukm::SourceId ukm_source_id, const DownloadItemImplCreated& on_started, uint32_t id);
diff --git a/content/browser/download/download_resource_handler.cc b/content/browser/download/download_resource_handler.cc index 8d037024..704e448 100644 --- a/content/browser/download/download_resource_handler.cc +++ b/content/browser/download/download_resource_handler.cc
@@ -17,6 +17,7 @@ #include "content/browser/download/download_manager_impl.h" #include "content/browser/download/download_request_handle.h" #include "content/browser/download/download_task_runner.h" +#include "content/browser/download/download_ukm_helper.h" #include "content/browser/frame_host/frame_tree_node.h" #include "content/browser/loader/resource_controller.h" #include "content/browser/loader/resource_dispatcher_host_impl.h" @@ -25,7 +26,6 @@ #include "content/public/browser/download_interrupt_reasons.h" #include "content/public/browser/navigation_entry.h" #include "content/public/browser/render_frame_host.h" -#include "content/public/browser/web_contents.h" #include "content/public/common/browser_side_navigation_policy.h" #include "content/public/common/resource_response.h" @@ -34,6 +34,7 @@ struct DownloadResourceHandler::DownloadTabInfo { GURL tab_url; GURL tab_referrer_url; + ukm::SourceId ukm_source_id; }; namespace { @@ -77,6 +78,7 @@ info->tab_url = tab_info->tab_url; info->tab_referrer_url = tab_info->tab_referrer_url; + info->ukm_source_id = tab_info->ukm_source_id; info->site_url = frame_host->GetSiteInstance()->GetSiteURL(); download_manager->StartDownload( @@ -96,6 +98,10 @@ if (entry) { tab_info->tab_url = entry->GetURL(); tab_info->tab_referrer_url = entry->GetReferrer().url; + + tab_info->ukm_source_id = ukm::UkmRecorder::GetNewSourceID(); + DownloadUkmHelper::UpdateSourceURL(ukm::UkmRecorder::Get(), + tab_info->ukm_source_id, web_contents); } } }
diff --git a/content/browser/download/download_resource_handler.h b/content/browser/download/download_resource_handler.h index ad2b38e..bbeca16 100644 --- a/content/browser/download/download_resource_handler.h +++ b/content/browser/download/download_resource_handler.h
@@ -18,6 +18,8 @@ #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" namespace net { class URLRequest;
diff --git a/content/browser/download/download_ukm_helper.cc b/content/browser/download/download_ukm_helper.cc new file mode 100644 index 0000000..350853c --- /dev/null +++ b/content/browser/download/download_ukm_helper.cc
@@ -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. + +#include "content/browser/download/download_ukm_helper.h" + +namespace content { + +void DownloadUkmHelper::UpdateSourceURL(ukm::UkmRecorder* ukm_recorder, + ukm::SourceId source_id, + WebContents* web_contents) { + if (ukm_recorder) { + ukm_recorder->UpdateSourceURL(source_id, + web_contents->GetLastCommittedURL()); + } +} + +} // namespace content
diff --git a/content/browser/download/download_ukm_helper.h b/content/browser/download/download_ukm_helper.h new file mode 100644 index 0000000..2686b8f3 --- /dev/null +++ b/content/browser/download/download_ukm_helper.h
@@ -0,0 +1,31 @@ +// 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. + +// Holds helpers for gathering UKM stats about downloads. + +#ifndef CONTENT_BROWSER_DOWNLOAD_DOWNLOAD_UKM_HELPER_H_ +#define CONTENT_BROWSER_DOWNLOAD_DOWNLOAD_UKM_HELPER_H_ + +#include "content/public/browser/web_contents.h" +#include "services/metrics/public/cpp/ukm_recorder.h" + +namespace content { + +class CONTENT_EXPORT DownloadUkmHelper { + public: + // Friended Helper for recording main frame URLs to UKM. + static void UpdateSourceURL(ukm::UkmRecorder* ukm_recorder, + ukm::SourceId source_id, + WebContents* web_contents); + + private: + DownloadUkmHelper(); + ~DownloadUkmHelper(); + + DISALLOW_COPY_AND_ASSIGN(DownloadUkmHelper); +}; + +} // namespace content + +#endif // CONTENT_BROWSER_DOWNLOAD_DOWNLOAD_UKM_HELPER_H_
diff --git a/content/browser/download/save_package.cc b/content/browser/download/save_package.cc index 185e2d5..eed1b2c1 100644 --- a/content/browser/download/save_package.cc +++ b/content/browser/download/save_package.cc
@@ -30,6 +30,7 @@ #include "content/browser/download/download_manager_impl.h" #include "content/browser/download/download_stats.h" #include "content/browser/download/download_task_runner.h" +#include "content/browser/download/download_ukm_helper.h" #include "content/browser/download/save_file.h" #include "content/browser/download/save_file_manager.h" #include "content/browser/download/save_item.h" @@ -57,6 +58,7 @@ #include "net/base/io_buffer.h" #include "net/base/mime_util.h" #include "net/url_request/url_request_context.h" +#include "services/metrics/public/cpp/ukm_recorder.h" #include "url/url_constants.h" namespace content { @@ -275,12 +277,16 @@ std::unique_ptr<DownloadRequestHandleInterface> request_handle( new SavePackageRequestHandle(AsWeakPtr())); + // The download manager keeps ownership but adds us as an observer. + ukm::SourceId ukm_source_id = ukm::UkmRecorder::GetNewSourceID(); + DownloadUkmHelper::UpdateSourceURL(ukm::UkmRecorder::Get(), ukm_source_id, + web_contents()); download_manager_->CreateSavePackageDownloadItem( saved_main_file_path_, page_url_, ((save_type_ == SAVE_PAGE_TYPE_AS_MHTML) ? "multipart/related" : "text/html"), - std::move(request_handle), + std::move(request_handle), std::move(ukm_source_id), base::Bind(&SavePackage::InitWithDownloadItem, AsWeakPtr(), download_created_callback)); return true;
diff --git a/content/browser/frame_host/navigation_controller_android.cc b/content/browser/frame_host/navigation_controller_android.cc index c016daa..80cb927 100644 --- a/content/browser/frame_host/navigation_controller_android.cc +++ b/content/browser/frame_host/navigation_controller_android.cc
@@ -15,6 +15,7 @@ #include "content/public/browser/browser_context.h" #include "content/public/browser/ssl_host_state_delegate.h" #include "content/public/common/resource_request_body.h" +#include "content/public/common/resource_request_body_android.h" #include "jni/NavigationControllerImpl_jni.h" #include "net/base/data_url.h" #include "ui/gfx/android/java_bitmap.h" @@ -209,7 +210,7 @@ if (extra_headers) params.extra_headers = ConvertJavaStringToUTF8(env, extra_headers); - params.post_data = ResourceRequestBody::FromJavaObject(env, j_post_data); + params.post_data = ExtractResourceRequestBodyFromJavaObject(env, j_post_data); if (base_url_for_data_url) { params.base_url_for_data_url =
diff --git a/content/browser/isolated_origin_browsertest.cc b/content/browser/isolated_origin_browsertest.cc index b9c3c94..89fc7f4b 100644 --- a/content/browser/isolated_origin_browsertest.cc +++ b/content/browser/isolated_origin_browsertest.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 <sstream> + #include "base/command_line.h" #include "base/macros.h" #include "base/test/scoped_feature_list.h" @@ -1075,4 +1077,74 @@ policy->IsIsolatedOrigin(url::Origin::Create(GURL("https://bar.com/")))); } +// This is a regresion test for https://crbug.com/793350 - the long list of +// origins to isolate used to be unnecessarily propagated to the renderer +// process, trigerring a crash due to exceeding kZygoteMaxMessageLength. +class IsolatedOriginLongListTest : public ContentBrowserTest { + public: + IsolatedOriginLongListTest() {} + ~IsolatedOriginLongListTest() override {} + + void SetUpCommandLine(base::CommandLine* command_line) override { + ASSERT_TRUE(embedded_test_server()->InitializeAndListen()); + + std::ostringstream origin_list; + origin_list + << embedded_test_server()->GetURL("isolated.foo.com", "/").spec(); + for (int i = 0; i < 1000; i++) { + std::ostringstream hostname; + hostname << "foo" << i << ".com"; + + origin_list << "," + << embedded_test_server()->GetURL(hostname.str(), "/").spec(); + } + command_line->AppendSwitchASCII(switches::kIsolateOrigins, + origin_list.str()); + } + + void SetUpOnMainThread() override { + host_resolver()->AddRule("*", "127.0.0.1"); + embedded_test_server()->StartAcceptingConnections(); + } +}; + +IN_PROC_BROWSER_TEST_F(IsolatedOriginLongListTest, Test) { + GURL test_url(embedded_test_server()->GetURL( + "bar1.com", + "/cross_site_iframe_factory.html?" + "bar1.com(isolated.foo.com,foo999.com,bar2.com)")); + EXPECT_TRUE(NavigateToURL(shell(), test_url)); + + EXPECT_EQ(4u, shell()->web_contents()->GetAllFrames().size()); + RenderFrameHost* main_frame = shell()->web_contents()->GetMainFrame(); + RenderFrameHost* subframe1 = shell()->web_contents()->GetAllFrames()[1]; + RenderFrameHost* subframe2 = shell()->web_contents()->GetAllFrames()[2]; + RenderFrameHost* subframe3 = shell()->web_contents()->GetAllFrames()[3]; + EXPECT_EQ("bar1.com", main_frame->GetLastCommittedOrigin().GetURL().host()); + EXPECT_EQ("isolated.foo.com", + subframe1->GetLastCommittedOrigin().GetURL().host()); + EXPECT_EQ("foo999.com", subframe2->GetLastCommittedOrigin().GetURL().host()); + EXPECT_EQ("bar2.com", subframe3->GetLastCommittedOrigin().GetURL().host()); + + // bar1.com and bar2.com are not on the list of origins to isolate - they + // should stay in the same process, unless --site-per-process has also been + // specified. + if (!AreAllSitesIsolatedForTesting()) { + EXPECT_EQ(main_frame->GetProcess()->GetID(), + subframe3->GetProcess()->GetID()); + EXPECT_EQ(main_frame->GetSiteInstance(), subframe3->GetSiteInstance()); + } + + // isolated.foo.com and foo999.com are on the list of origins to isolate - + // they should be isolated from everything else. + EXPECT_NE(main_frame->GetProcess()->GetID(), + subframe1->GetProcess()->GetID()); + EXPECT_NE(main_frame->GetSiteInstance(), subframe1->GetSiteInstance()); + EXPECT_NE(main_frame->GetProcess()->GetID(), + subframe2->GetProcess()->GetID()); + EXPECT_NE(main_frame->GetSiteInstance(), subframe2->GetSiteInstance()); + EXPECT_NE(subframe1->GetProcess()->GetID(), subframe2->GetProcess()->GetID()); + EXPECT_NE(subframe1->GetSiteInstance(), subframe2->GetSiteInstance()); +} + } // namespace content
diff --git a/content/browser/renderer_host/compositor_impl_android.cc b/content/browser/renderer_host/compositor_impl_android.cc index cc39016..fd964eab 100644 --- a/content/browser/renderer_host/compositor_impl_android.cc +++ b/content/browser/renderer_host/compositor_impl_android.cc
@@ -480,10 +480,10 @@ window_(NULL), surface_handle_(gpu::kNullSurfaceHandle), client_(client), - root_window_(root_window), needs_animate_(false), pending_frames_(0U), layer_tree_frame_sink_request_pending_(false), + lock_manager_(base::ThreadTaskRunnerHandle::Get(), this), weak_factory_(this) { GetHostFrameSinkManager()->RegisterFrameSinkId(frame_sink_id_, this); #if DCHECK_IS_ON() @@ -491,15 +491,8 @@ "CompositorImpl"); #endif DCHECK(client); - DCHECK(root_window); - DCHECK(root_window->GetLayer() == nullptr); - root_window->SetLayer(cc::Layer::Create()); - readback_layer_tree_ = cc::Layer::Create(); - readback_layer_tree_->SetHideLayerAndSubtree(true); - root_window->GetLayer()->AddChild(readback_layer_tree_); - root_window->AttachCompositor(this); - CreateLayerTreeHost(); - resource_manager_.Init(host_->GetUIResourceManager()); + + SetRootWindow(root_window); // Listen to display density change events and update painted device scale // factor accordingly. @@ -508,13 +501,17 @@ CompositorImpl::~CompositorImpl() { display::Screen::GetScreen()->RemoveObserver(this); - root_window_->DetachCompositor(); - root_window_->SetLayer(nullptr); + DetachRootWindow(); // Clean-up any surface references. SetSurface(NULL); GetHostFrameSinkManager()->InvalidateFrameSinkId(frame_sink_id_); } +void CompositorImpl::DetachRootWindow() { + root_window_->DetachCompositor(); + root_window_->SetLayer(nullptr); +} + bool CompositorImpl::IsForSubframe() { return false; } @@ -527,14 +524,50 @@ return resource_manager_; } +void CompositorImpl::SetRootWindow(gfx::NativeWindow root_window) { + DCHECK(root_window); + DCHECK(!root_window->GetLayer()); + + // TODO(mthiesse): Right now we only support swapping the root window without + // a surface. If we want to support swapping with a surface we need to + // handle visibility, swapping begin frame sources, etc. + // These checks ensure we have no begin frame source, and that we don't need + // to register one on the new window. + DCHECK(!display_); + DCHECK(!window_); + + scoped_refptr<cc::Layer> root_layer; + if (root_window_) { + root_layer = root_window_->GetLayer(); + DetachRootWindow(); + } + + root_window_ = root_window; + root_window_->SetLayer(root_layer ? root_layer : cc::Layer::Create()); + root_window_->GetLayer()->SetBounds(size_); + if (!readback_layer_tree_) { + readback_layer_tree_ = cc::Layer::Create(); + readback_layer_tree_->SetHideLayerAndSubtree(true); + } + root_window->GetLayer()->AddChild(readback_layer_tree_); + root_window->AttachCompositor(this); + if (!host_) { + CreateLayerTreeHost(); + resource_manager_.Init(host_->GetUIResourceManager()); + } + host_->SetRootLayer(root_window_->GetLayer()); + host_->SetPaintedDeviceScaleFactor(root_window_->GetDipScale()); +} + void CompositorImpl::SetRootLayer(scoped_refptr<cc::Layer> root_layer) { if (subroot_layer_.get()) { subroot_layer_->RemoveFromParent(); - subroot_layer_ = NULL; + subroot_layer_ = nullptr; } if (root_window_->GetLayer()) { subroot_layer_ = root_window_->GetLayer(); - root_window_->GetLayer()->AddChild(root_layer); + subroot_layer_->RemoveAllChildren(); + subroot_layer_->AddChild(root_layer); } } @@ -599,11 +632,9 @@ params.mutator_host = animation_host_.get(); host_ = cc::LayerTreeHost::CreateSingleThreaded(this, ¶ms); DCHECK(!host_->IsVisible()); - host_->SetRootLayer(root_window_->GetLayer()); host_->SetFrameSinkId(frame_sink_id_); host_->SetViewportSize(size_); host_->SetDeviceScaleFactor(1); - host_->SetPaintedDeviceScaleFactor(root_window_->GetDipScale()); if (needs_animate_) host_->SetNeedsAnimate(); @@ -631,6 +662,7 @@ display_.reset(); } else { host_->SetVisible(true); + has_submitted_frame_since_became_visible_ = false; if (layer_tree_frame_sink_request_pending_) HandlePendingLayerTreeFrameSinkRequest(); } @@ -648,10 +680,6 @@ root_window_->GetLayer()->SetBounds(size); } -void CompositorImpl::SetDeferCommits(bool defer_commits) { - host_->SetDeferCommits(defer_commits); -} - void CompositorImpl::SetRequiresAlphaChannel(bool flag) { requires_alpha_channel_ = flag; } @@ -879,6 +907,7 @@ void CompositorImpl::DidSubmitCompositorFrame() { TRACE_EVENT0("compositor", "CompositorImpl::DidSubmitCompositorFrame"); pending_frames_++; + has_submitted_frame_since_became_visible_ = true; } void CompositorImpl::DidReceiveCompositorFrameAck() { @@ -961,4 +990,19 @@ return !readback_layer_tree_->children().empty(); } +std::unique_ptr<ui::CompositorLock> CompositorImpl::GetCompositorLock( + ui::CompositorLockClient* client, + base::TimeDelta timeout) { + return lock_manager_.GetCompositorLock(client, timeout); +} + +bool CompositorImpl::IsDrawingFirstVisibleFrame() const { + return !has_submitted_frame_since_became_visible_; +} + +void CompositorImpl::OnCompositorLockStateChanged(bool locked) { + if (host_) + host_->SetDeferCommits(locked); +} + } // namespace content
diff --git a/content/browser/renderer_host/compositor_impl_android.h b/content/browser/renderer_host/compositor_impl_android.h index 80fabcb..be66cc8f 100644 --- a/content/browser/renderer_host/compositor_impl_android.h +++ b/content/browser/renderer_host/compositor_impl_android.h
@@ -28,6 +28,7 @@ #include "ui/android/resources/resource_manager_impl.h" #include "ui/android/resources/ui_resource_provider.h" #include "ui/android/window_android_compositor.h" +#include "ui/compositor/compositor_lock.h" #include "ui/display/display_observer.h" struct ANativeWindow; @@ -57,6 +58,7 @@ : public Compositor, public cc::LayerTreeHostClient, public cc::LayerTreeHostSingleThreadClient, + public ui::CompositorLockManagerClient, public ui::UIResourceProvider, public ui::WindowAndroidCompositor, public viz::HostFrameSinkClient, @@ -78,11 +80,11 @@ private: // Compositor implementation. + void SetRootWindow(gfx::NativeWindow root_window) override; void SetRootLayer(scoped_refptr<cc::Layer> root) override; void SetSurface(jobject surface) override; void SetBackgroundColor(int color) override; void SetWindowBounds(const gfx::Size& size) override; - void SetDeferCommits(bool defer_commits) override; void SetRequiresAlphaChannel(bool flag) override; void SetNeedsComposite() override; ui::UIResourceProvider& GetUIResourceProvider() override; @@ -124,6 +126,10 @@ viz::FrameSinkId GetFrameSinkId() override; void AddChildFrameSink(const viz::FrameSinkId& frame_sink_id) override; void RemoveChildFrameSink(const viz::FrameSinkId& frame_sink_id) override; + std::unique_ptr<ui::CompositorLock> GetCompositorLock( + ui::CompositorLockClient* client, + base::TimeDelta timeout) override; + bool IsDrawingFirstVisibleFrame() const override; // viz::HostFrameSinkClient implementation. void OnFirstSurfaceActivation(const viz::SurfaceInfo& surface_info) override; @@ -133,6 +139,9 @@ void OnDisplayMetricsChanged(const display::Display& display, uint32_t changed_metrics) override; + // ui::CompositorLockManagerClient implementation. + void OnCompositorLockStateChanged(bool locked) override; + void SetVisible(bool visible); void CreateLayerTreeHost(); @@ -151,6 +160,8 @@ bool HavePendingReadbacks(); + void DetachRootWindow(); + viz::FrameSinkId frame_sink_id_; // root_layer_ is the persistent internal root layer, while subroot_layer_ @@ -176,7 +187,7 @@ CompositorClient* client_; - gfx::NativeWindow root_window_; + gfx::NativeWindow root_window_ = nullptr; // Whether we need to update animations on the next composite. bool needs_animate_; @@ -195,6 +206,8 @@ bool has_layer_tree_frame_sink_ = false; std::unordered_set<viz::FrameSinkId, viz::FrameSinkIdHash> pending_child_frame_sink_ids_; + ui::CompositorLockManager lock_manager_; + bool has_submitted_frame_since_became_visible_ = false; base::WeakPtrFactory<CompositorImpl> weak_factory_; DISALLOW_COPY_AND_ASSIGN(CompositorImpl);
diff --git a/content/browser/renderer_host/render_process_host_impl.cc b/content/browser/renderer_host/render_process_host_impl.cc index 959cbbf..1083763 100644 --- a/content/browser/renderer_host/render_process_host_impl.cc +++ b/content/browser/renderer_host/render_process_host_impl.cc
@@ -2622,7 +2622,6 @@ switches::kForceVideoOverlays, switches::kFullMemoryCrashReport, switches::kIPCConnectionTimeout, - switches::kIsolateOrigins, switches::kJavaScriptFlags, switches::kLoggingLevel, switches::kMainFrameResizesAreOrientationChanges,
diff --git a/content/browser/renderer_host/render_widget_host_impl.cc b/content/browser/renderer_host/render_widget_host_impl.cc index e2a3b86..6a2e6aa 100644 --- a/content/browser/renderer_host/render_widget_host_impl.cc +++ b/content/browser/renderer_host/render_widget_host_impl.cc
@@ -1183,7 +1183,22 @@ blink::WebInputEvent::kGestureFlingStart) { if (gesture_event.source_device == blink::WebGestureDevice::kWebGestureDeviceTouchpad) { - if (GetView()->wheel_scroll_latching_enabled()) { + // TODO(sahel): Remove the VR specific case when motion events are used + // for Android VR event processing and VR touchpad scrolling is handled by + // sending wheel events rather than directly injecting Gesture Scroll + // Events. https://crbug.com/797322 + if (GetView()->IsInVR()) { + // Regardless of the state of the wheel scroll latching + // WebContentsEventForwarder doesn't inject any GSE events before GFS. + DCHECK(is_in_gesture_scroll_[gesture_event.source_device]); + + // Reset the is_in_gesture_scroll since while scrolling in Android VR + // the first wheel event sent by the FlingController will cause a GSB + // generation in MouseWheelEventQueue. This is because GSU events before + // the GFS are directly injected to RWHI rather than being generated + // from wheel events in MouseWheelEventQueue. + is_in_gesture_scroll_[gesture_event.source_device] = false; + } else if (GetView()->wheel_scroll_latching_enabled()) { // When wheel scroll latching is enabled, no GSE is sent before GFS, so // is_in_gesture_scroll must be true. DCHECK(is_in_gesture_scroll_[gesture_event.source_device]); @@ -1191,22 +1206,14 @@ // The FlingController handles GFS with touchpad source and sends wheel // events to progress the fling, the wheel events will get processed by // the MouseWheelEventQueue and GSU events with inertial phase will be - // sent to the renderer. - if (GetView()->IsInVR()) { - // Reset the is_in_gesture_scroll since while scrolling in Android VR - // the first wheel event sent by the FlingController will cause a GSB - // generation in MouseWheelEventQueue. This is because - // WebContentsEventForwarder injects gesture scroll events to the RWHI - // rather than wheel events. TODO(sahel): Remove this when motion - // events are used for Android VR event processing. - // https://crbug.com/797322 - is_in_gesture_scroll_[gesture_event.source_device] = false; - } else { - // is_in_gesture_scroll must stay true till the fling progress is - // finished. Then the FlingController will generate and send a GSE - // event to show the end of a scroll sequence. - } - } else { // !GetView()->wheel_scroll_latching_enabled() + // sent to the renderer. is_in_gesture_scroll must stay true till the + // fling progress is finished. Then the FlingController will generate + // and send a wheel event with phaseEnded. MouseWheelEventQueue will + // process the wheel event to generate and send a GSE which shows the + // end of a scroll sequence. + } else { // !GetView()->IsInVR() && + // !GetView()->wheel_scroll_latching_enabled() + // When wheel scroll latching is disabled a GSE is sent before a GFS. // The GSE has already finished the scroll sequence. DCHECK(!is_in_gesture_scroll_[gesture_event.source_device]);
diff --git a/content/browser/renderer_host/render_widget_host_input_event_router.cc b/content/browser/renderer_host/render_widget_host_input_event_router.cc index 18390f9..dcd495de 100644 --- a/content/browser/renderer_host/render_widget_host_input_event_router.cc +++ b/content/browser/renderer_host/render_widget_host_input_event_router.cc
@@ -24,12 +24,26 @@ namespace { -void TransformEventTouchPositions(blink::WebTouchEvent* event, - const gfx::Vector2dF& delta) { +// Transforms WebTouchEvent touch positions from the root view coordinate +// space to the target view coordinate space. +void TransformEventTouchPositions( + blink::WebTouchEvent* event, + content::RenderWidgetHostViewBase* root_view, + content::RenderWidgetHostViewBase* target_view) { + if (!target_view || target_view == root_view) + return; + for (unsigned i = 0; i < event->touches_length; ++i) { - event->touches[i].SetPositionInWidget( - event->touches[i].PositionInWidget().x + delta.x(), - event->touches[i].PositionInWidget().y + delta.y()); + gfx::PointF transformed_point(event->touches[i].PositionInWidget()); + // TODO(wjmaclean): For multiple touch points this might be inefficient; + // we should investigate whether it's better to transform arrays of + // points all at once. + if (root_view->TransformPointToCoordSpaceForView( + event->touches[i].PositionInWidget(), target_view, + &transformed_point)) { + event->touches[i].SetPositionInWidget(transformed_point.x(), + transformed_point.y()); + } } } @@ -478,99 +492,87 @@ touchscreen_gesture_target_map_.erase(unique_touch_event_id); } +RenderWidgetTargetResult RenderWidgetHostInputEventRouter::FindTouchEventTarget( + RenderWidgetHostViewBase* root_view, + const blink::WebTouchEvent& event) { + // Tests may call this without an initial TouchStart, so check event type + // explicitly here. + if (active_touches_ || event.GetType() != blink::WebInputEvent::kTouchStart) + return {nullptr, false, base::nullopt}; + + active_touches_ += CountChangedTouchPoints(event); + gfx::PointF original_point = gfx::PointF(event.touches[0].PositionInWidget()); + gfx::PointF original_point_in_screen(event.touches[0].PositionInScreen()); + gfx::PointF transformed_point; + + return FindViewAtLocation(root_view, original_point, original_point_in_screen, + viz::EventSource::TOUCH, &transformed_point); +} + +void RenderWidgetHostInputEventRouter::DispatchTouchEvent( + RenderWidgetHostViewBase* root_view, + RenderWidgetHostViewBase* target, + const blink::WebTouchEvent& touch_event, + const ui::LatencyInfo& latency) { + DCHECK(blink::WebInputEvent::IsTouchEventType(touch_event.GetType()) && + touch_event.GetType() != blink::WebInputEvent::kTouchScrollStarted); + + bool is_sequence_start = !touch_target_.target && target; + if (is_sequence_start) { + touch_target_.target = target; + + DCHECK(touchscreen_gesture_target_map_.find( + touch_event.unique_touch_event_id) == + touchscreen_gesture_target_map_.end()); + touchscreen_gesture_target_map_[touch_event.unique_touch_event_id] = + touch_target_; + } else if (touch_event.GetType() == blink::WebInputEvent::kTouchStart) { + active_touches_ += CountChangedTouchPoints(touch_event); + } + + // Test active_touches_ before decrementing, since its value can be + // reset to 0 in OnRenderWidgetHostViewBaseDestroyed, and this can + // happen between the TouchStart and a subsequent TouchMove/End/Cancel. + if ((touch_event.GetType() == blink::WebInputEvent::kTouchEnd || + touch_event.GetType() == blink::WebInputEvent::kTouchCancel) && + active_touches_) { + active_touches_ -= CountChangedTouchPoints(touch_event); + } + DCHECK_GE(active_touches_, 0); + + if (!touch_target_.target) { + TouchEventWithLatencyInfo touch_with_latency(touch_event, latency); + root_view->ProcessAckedTouchEvent(touch_with_latency, + INPUT_EVENT_ACK_STATE_NO_CONSUMER_EXISTS); + return; + } + + if (is_sequence_start) { + if (touch_target_.target == bubbling_gesture_scroll_target_.target) { + SendGestureScrollEnd( + bubbling_gesture_scroll_target_.target, + DummyGestureScrollUpdate(touch_event.TimeStampSeconds())); + CancelScrollBubbling(bubbling_gesture_scroll_target_.target); + } + } + + blink::WebTouchEvent event(touch_event); + TransformEventTouchPositions(&event, root_view, touch_target_.target); + touch_target_.target->ProcessTouchEvent(event, latency); + + if (!active_touches_) + touch_target_.target = nullptr; +} + void RenderWidgetHostInputEventRouter::RouteTouchEvent( RenderWidgetHostViewBase* root_view, blink::WebTouchEvent* event, const ui::LatencyInfo& latency) { - switch (event->GetType()) { - case blink::WebInputEvent::kTouchStart: { - int current_active_touches = active_touches_; - active_touches_ += CountChangedTouchPoints(*event); - DCHECK(active_touches_); - if (!current_active_touches) { - // Since this is the first touch, it defines the target for the rest - // of this sequence. - DCHECK(!touch_target_.target); - gfx::PointF transformed_point; - gfx::PointF original_point(event->touches[0].PositionInWidget().x, - event->touches[0].PositionInWidget().y); - gfx::PointF original_point_in_screen( - event->touches[0].PositionInScreen().x, - event->touches[0].PositionInScreen().y); - auto result = FindViewAtLocation( - root_view, original_point, original_point_in_screen, - viz::EventSource::TOUCH, &transformed_point); - // TODO(crbug.com/796656): Do not ignore |result.should_query_view|. - touch_target_.target = result.view; - - // TODO(wjmaclean): Instead of just computing a delta, we should extract - // the complete transform. We assume it doesn't change for the duration - // of the touch sequence, though this could be wrong; a better approach - // might be to always transform each point to the |touch_target_.target| - // for the duration of the sequence. - touch_target_.delta = transformed_point - original_point; - DCHECK(touchscreen_gesture_target_map_.find( - event->unique_touch_event_id) == - touchscreen_gesture_target_map_.end()); - touchscreen_gesture_target_map_[event->unique_touch_event_id] = - touch_target_; - - if (!touch_target_.target) { - TouchEventWithLatencyInfo touch_with_latency(*event, latency); - root_view->ProcessAckedTouchEvent( - touch_with_latency, INPUT_EVENT_ACK_STATE_NO_CONSUMER_EXISTS); - return; - } - - if (touch_target_.target == bubbling_gesture_scroll_target_.target) { - SendGestureScrollEnd( - bubbling_gesture_scroll_target_.target, - DummyGestureScrollUpdate(event->TimeStampSeconds())); - CancelScrollBubbling(bubbling_gesture_scroll_target_.target); - } - } - - if (touch_target_.target) { - TransformEventTouchPositions(event, touch_target_.delta); - touch_target_.target->ProcessTouchEvent(*event, latency); - } - break; - } - case blink::WebInputEvent::kTouchMove: - if (!touch_target_.target) { - TouchEventWithLatencyInfo touch_with_latency(*event, latency); - root_view->ProcessAckedTouchEvent( - touch_with_latency, INPUT_EVENT_ACK_STATE_NO_CONSUMER_EXISTS); - return; - } - - TransformEventTouchPositions(event, touch_target_.delta); - touch_target_.target->ProcessTouchEvent(*event, latency); - break; - case blink::WebInputEvent::kTouchEnd: - case blink::WebInputEvent::kTouchCancel: - // Test active_touches_ before decrementing, since its value can be - // reset to 0 in OnRenderWidgetHostViewBaseDestroyed, and this can - // happen between the TouchStart and a subsequent TouchMove/End/Cancel. - if (active_touches_) - active_touches_ -= CountChangedTouchPoints(*event); - DCHECK_GE(active_touches_, 0); - - if (!touch_target_.target) { - TouchEventWithLatencyInfo touch_with_latency(*event, latency); - root_view->ProcessAckedTouchEvent( - touch_with_latency, INPUT_EVENT_ACK_STATE_NO_CONSUMER_EXISTS); - return; - } - - TransformEventTouchPositions(event, touch_target_.delta); - touch_target_.target->ProcessTouchEvent(*event, latency); - if (!active_touches_) - touch_target_.target = nullptr; - break; - default: - NOTREACHED(); - } + // Note: this code is short term until we enable async routing for touch, + // and will ultimately use |event_targeter_| like RouteMouseEvent() does. + RenderWidgetTargetResult event_target = + FindTouchEventTarget(root_view, *event); + DispatchTouchEvent(root_view, event_target.view, *event, latency); } void RenderWidgetHostInputEventRouter::SendMouseEnterOrLeaveEvents( @@ -943,13 +945,39 @@ .view->GetRenderWidgetHost()); } -void RenderWidgetHostInputEventRouter::RouteTouchscreenGestureEvent( +RenderWidgetTargetResult +RenderWidgetHostInputEventRouter::FindTouchscreenGestureEventTarget( RenderWidgetHostViewBase* root_view, - blink::WebGestureEvent* event, - const ui::LatencyInfo& latency) { - DCHECK_EQ(blink::kWebGestureDeviceTouchscreen, event->source_device); + const blink::WebGestureEvent& gesture_event) { + // Since DispatchTouchscreenGestureEvent() doesn't pay any attention to the + // target we could just return nullptr for pinch events, but since we know + // where they are going we return the correct target. + if (blink::WebInputEvent::IsPinchGestureEventType(gesture_event.GetType())) + return {root_view, false, base::nullopt}; - if (event->GetType() == blink::WebInputEvent::kGesturePinchBegin) { + // Android sends gesture events that have no corresponding touch sequence, so + // these we hit-test explicitly. + if (gesture_event.unique_touch_event_id == 0) { + gfx::PointF transformed_point; + gfx::PointF original_point(gesture_event.x, gesture_event.y); + gfx::PointF original_point_in_screen(gesture_event.global_x, + gesture_event.global_y); + return FindViewAtLocation(root_view, original_point, + original_point_in_screen, viz::EventSource::TOUCH, + &transformed_point); + } + + // Remaining gesture events will defer to the gesture event target queue + // during dispatch. + return {nullptr, false, base::nullopt}; +} + +void RenderWidgetHostInputEventRouter::DispatchTouchscreenGestureEvent( + RenderWidgetHostViewBase* root_view, + RenderWidgetHostViewBase* target, + const blink::WebGestureEvent& gesture_event, + const ui::LatencyInfo& latency) { + if (gesture_event.GetType() == blink::WebInputEvent::kGesturePinchBegin) { in_touchscreen_gesture_pinch_ = true; // If the root view wasn't already receiving the gesture stream, then we // need to wrap the diverted pinch events in a GestureScrollBegin/End. @@ -964,13 +992,13 @@ if (root_view != touchscreen_gesture_target_.target && !rwhi->is_in_touchscreen_gesture_scroll()) { gesture_pinch_did_send_scroll_begin_ = true; - SendGestureScrollBegin(root_view, *event); + SendGestureScrollBegin(root_view, gesture_event); } } if (in_touchscreen_gesture_pinch_) { - root_view->ProcessGestureEvent(*event, latency); - if (event->GetType() == blink::WebInputEvent::kGesturePinchEnd) { + root_view->ProcessGestureEvent(gesture_event, latency); + if (gesture_event.GetType() == blink::WebInputEvent::kGesturePinchEnd) { in_touchscreen_gesture_pinch_ = false; // If the root view wasn't already receiving the gesture stream, then we // need to wrap the diverted pinch events in a GestureScrollBegin/End. @@ -979,7 +1007,7 @@ if (root_view != touchscreen_gesture_target_.target && gesture_pinch_did_send_scroll_begin_ && rwhi->is_in_touchscreen_gesture_scroll()) { - SendGestureScrollEnd(root_view, *event); + SendGestureScrollEnd(root_view, gesture_event); } gesture_pinch_did_send_scroll_begin_ = false; } @@ -987,7 +1015,7 @@ } auto gesture_target_it = - touchscreen_gesture_target_map_.find(event->unique_touch_event_id); + touchscreen_gesture_target_map_.find(gesture_event.unique_touch_event_id); bool no_matching_id = gesture_target_it == touchscreen_gesture_target_map_.end(); @@ -997,35 +1025,37 @@ // ET_GESTURE_BEGIN and GestureTapDown is sent to the previous target, in // case it is still in a fling. bool is_gesture_start = - event->GetType() == blink::WebInputEvent::kGestureTapDown; + gesture_event.GetType() == blink::WebInputEvent::kGestureTapDown; - // On Android it is possible for touchscreen gesture events to arrive that - // are not associated with touch events, because non-synthetic events can be - // created by ContentView. - // These gesture events should always have a unique_touch_event_id of 0. - bool no_gesture_target = - event->unique_touch_event_id != 0 && no_matching_id && is_gesture_start; - - if (no_gesture_target) { - UMA_HISTOGRAM_BOOLEAN("Event.FrameEventRouting.NoGestureTarget", - no_gesture_target); - NOTREACHED() << "Gesture sequence start detected with no target available."; + if (gesture_event.unique_touch_event_id == 0) { + // On Android it is possible for touchscreen gesture events to arrive that + // are not associated with touch events, because non-synthetic events can be + // created by ContentView. These will use the target found by the + // RenderWidgetTargeter. These gesture events should always have a + // unique_touch_event_id of 0. + touchscreen_gesture_target_.target = target; + } else if (no_matching_id && is_gesture_start) { + // A long-standing Windows issues where occasionally a GestureStart is + // encountered with no targets in the event queue. We never had a repro for + // this, but perhaps we should drop these events and wait to see if a bug + // (with a repro) gets filed, then just fix it. + // + // For now, we do a synchronous-only hit test here, which even though + // incorrect is not likely to have a large effect in the short term. + UMA_HISTOGRAM_BOOLEAN("Event.FrameEventRouting.NoGestureTarget", true); + LOG(ERROR) << "Gesture sequence start detected with no target available."; // It is still safe to continue; we will recalculate the target. - } - - // If this is a non-touch gesture or there was an no_matching_id error on - // gesture start, then the target must be recalculated. - if (event->unique_touch_event_id == 0 || - (no_matching_id && is_gesture_start)) { gfx::PointF transformed_point; - gfx::PointF original_point(event->x, event->y); - gfx::PointF original_point_in_screen(event->global_x, event->global_y); + gfx::PointF original_point(gesture_event.x, gesture_event.y); + gfx::PointF original_point_in_screen(gesture_event.global_x, + gesture_event.global_y); auto result = FindViewAtLocation(root_view, original_point, original_point_in_screen, viz::EventSource::TOUCH, &transformed_point); - // TODO(crbug.com/796656): Do not ignore |result.should_query_view|. + // Re https://crbug.com/796656): Since we are already in an error case, + // don't worry about the fact we're ignoring |result.should_query_view|, as + // this is the best we can do until we fix https://crbug.com/595422. touchscreen_gesture_target_.target = result.view; - touchscreen_gesture_target_.delta = transformed_point - original_point; } else if (is_gesture_start) { touchscreen_gesture_target_ = gesture_target_it->second; touchscreen_gesture_target_map_.erase(gesture_target_it); @@ -1034,22 +1064,44 @@ if (touchscreen_gesture_target_.target && touchscreen_gesture_target_.target == bubbling_gesture_scroll_target_.target) { - SendGestureScrollEnd(bubbling_gesture_scroll_target_.target, - DummyGestureScrollUpdate(event->TimeStampSeconds())); + SendGestureScrollEnd( + bubbling_gesture_scroll_target_.target, + DummyGestureScrollUpdate(gesture_event.TimeStampSeconds())); CancelScrollBubbling(bubbling_gesture_scroll_target_.target); } } if (!touchscreen_gesture_target_.target) { - root_view->GestureEventAck(*event, + root_view->GestureEventAck(gesture_event, INPUT_EVENT_ACK_STATE_NO_CONSUMER_EXISTS); return; } - // TODO(mohsen): Add tests to check event location. - event->x += touchscreen_gesture_target_.delta.x(); - event->y += touchscreen_gesture_target_.delta.y(); - touchscreen_gesture_target_.target->ProcessGestureEvent(*event, latency); + blink::WebGestureEvent event(gesture_event); + gfx::PointF transformed_point; + if (root_view->TransformPointToCoordSpaceForView( + gesture_event.PositionInWidget(), touchscreen_gesture_target_.target, + &transformed_point)) { + // TODO(wjmaclean): Add SetPositionInWidget() to WebGestureEvent. + event.x = transformed_point.x(); + event.y = transformed_point.y(); + } else { + // TODO(wjmaclean): we can get here in Android tests. We should figure out + // why, then make this a NOTREACHED(). + LOG(ERROR) << "Unable to convert event coordinates."; + } + touchscreen_gesture_target_.target->ProcessGestureEvent(event, latency); +} + +void RenderWidgetHostInputEventRouter::RouteTouchscreenGestureEvent( + RenderWidgetHostViewBase* root_view, + blink::WebGestureEvent* event, + const ui::LatencyInfo& latency) { + DCHECK_EQ(blink::kWebGestureDeviceTouchscreen, event->source_device); + RenderWidgetTargetResult event_target = + FindTouchscreenGestureEventTarget(root_view, *event); + DispatchTouchscreenGestureEvent(root_view, event_target.view, *event, + latency); } void RenderWidgetHostInputEventRouter::RouteTouchpadGestureEvent(
diff --git a/content/browser/renderer_host/render_widget_host_input_event_router.h b/content/browser/renderer_host/render_widget_host_input_event_router.h index 14173e7..be848bb9 100644 --- a/content/browser/renderer_host/render_widget_host_input_event_router.h +++ b/content/browser/renderer_host/render_widget_host_input_event_router.h
@@ -175,12 +175,31 @@ RenderWidgetHostViewBase* root_view, const blink::WebMouseWheelEvent& event, gfx::PointF* transformed_point) const; + // Returns target for first TouchStart in a sequence, or a null target + // otherwise. + RenderWidgetTargetResult FindTouchEventTarget( + RenderWidgetHostViewBase* root_view, + const blink::WebTouchEvent& event); + RenderWidgetTargetResult FindTouchscreenGestureEventTarget( + RenderWidgetHostViewBase* root_view, + const blink::WebGestureEvent& gesture_event); // |mouse_event| is in the coord-space of |target|. void DispatchMouseEvent(RenderWidgetHostViewBase* root_view, RenderWidgetHostViewBase* target, const blink::WebMouseEvent& mouse_event, const ui::LatencyInfo& latency); + // Assumes |touch_event| has coordinates in the root view's coordinate space. + void DispatchTouchEvent(RenderWidgetHostViewBase* root_view, + RenderWidgetHostViewBase* target, + const blink::WebTouchEvent& touch_event, + const ui::LatencyInfo& latency); + // Assumes |gesture_event| has coordinates in root view's coordinate space. + void DispatchTouchscreenGestureEvent( + RenderWidgetHostViewBase* root_view, + RenderWidgetHostViewBase* target, + const blink::WebGestureEvent& gesture_event, + const ui::LatencyInfo& latency); // RenderWidgetTargeter::Delegate: RenderWidgetTargetResult FindTargetSynchronously(
diff --git a/content/browser/renderer_host/render_widget_host_input_event_router_unittest.cc b/content/browser/renderer_host/render_widget_host_input_event_router_unittest.cc index 17d922e6..2c81b9d 100644 --- a/content/browser/renderer_host/render_widget_host_input_event_router_unittest.cc +++ b/content/browser/renderer_host/render_widget_host_input_event_router_unittest.cc
@@ -66,6 +66,13 @@ return frame_sink_id_map_[current_hittest_result_]; } + bool TransformPointToCoordSpaceForView( + const gfx::PointF& point, + RenderWidgetHostViewBase* target_view, + gfx::PointF* transformed_point) override { + return true; + } + void SetHittestResult(MockRenderWidgetHostView* view) { current_hittest_result_ = view; }
diff --git a/content/browser/renderer_host/render_widget_host_view_aura_unittest.cc b/content/browser/renderer_host/render_widget_host_view_aura_unittest.cc index 9393d1df..2a7b4ba 100644 --- a/content/browser/renderer_host/render_widget_host_view_aura_unittest.cc +++ b/content/browser/renderer_host/render_widget_host_view_aura_unittest.cc
@@ -2359,13 +2359,7 @@ // Checks that InputMsg_CursorVisibilityChange IPC messages are dispatched // to the renderer at the correct times. -// Flaky on OS_FUCHSIA: http://crbug.com/800415 -#if defined(OS_FUCHSIA) -#define MAYBE_CursorVisibilityChange DISABLED_CursorVisibilityChange -#else -#define MAYBE_CursorVisibilityChange CursorVisibilityChange -#endif -TEST_F(RenderWidgetHostViewAuraTest, MAYBE_CursorVisibilityChange) { +TEST_F(RenderWidgetHostViewAuraTest, CursorVisibilityChange) { view_->InitAsChild(nullptr); aura::client::ParentWindowWithContext( view_->GetNativeView(),
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 dc20cdd2..6dc8047 100644 --- a/content/browser/renderer_host/render_widget_host_view_base.cc +++ b/content/browser/renderer_host/render_widget_host_view_base.cc
@@ -452,7 +452,7 @@ gfx::ConvertPointToPixel(device_scale_factor, point); viz::SurfaceId surface_id = GetCurrentSurfaceId(); if (!surface_id.is_valid()) { - return viz::FrameSinkId(); + return GetFrameSinkId(); } viz::SurfaceHittest hittest(delegate, GetFrameSinkManager()->surface_manager());
diff --git a/content/browser/shared_worker/shared_worker_instance.cc b/content/browser/shared_worker/shared_worker_instance.cc index 07d8173..67e1d88 100644 --- a/content/browser/shared_worker/shared_worker_instance.cc +++ b/content/browser/shared_worker/shared_worker_instance.cc
@@ -46,6 +46,12 @@ if (!constructor_origin_.IsSameOriginWith(constructor_origin) || url_ != url || name_ != name) return false; + + // TODO(https://crbug.com/794098): file:// URLs should be treated as opaque + // origins, but not in url::Origin. Therefore, we manually check it here. + if (url.SchemeIsFile() || constructor_origin.scheme() == url::kFileScheme) + return false; + return true; }
diff --git a/content/browser/shared_worker/shared_worker_instance_unittest.cc b/content/browser/shared_worker/shared_worker_instance_unittest.cc index c336b70c0..779d67f 100644 --- a/content/browser/shared_worker/shared_worker_instance_unittest.cc +++ b/content/browser/shared_worker/shared_worker_instance_unittest.cc
@@ -44,6 +44,7 @@ TEST_F(SharedWorkerInstanceTest, MatchesTest) { const std::string kDataURL("data:text/javascript;base64,Ly8gSGVsbG8h"); + const std::string kFileURL("file:///w.js"); // SharedWorker that doesn't have a name option. GURL script_url1("http://example.com/w.js"); @@ -62,6 +63,8 @@ EXPECT_FALSE(Matches(instance1, "http://example.net/w2.js", "name")); EXPECT_FALSE(Matches(instance1, kDataURL, "")); EXPECT_FALSE(Matches(instance1, kDataURL, "name")); + EXPECT_FALSE(Matches(instance1, kFileURL, "")); + EXPECT_FALSE(Matches(instance1, kFileURL, "name")); // SharedWorker that has a name option. GURL script_url2("http://example.com/w.js"); @@ -84,10 +87,13 @@ EXPECT_FALSE(Matches(instance2, "http://example.net/w2.js", "name2")); EXPECT_FALSE(Matches(instance2, kDataURL, "")); EXPECT_FALSE(Matches(instance2, kDataURL, "name")); + EXPECT_FALSE(Matches(instance2, kFileURL, "")); + EXPECT_FALSE(Matches(instance2, kFileURL, "name")); } TEST_F(SharedWorkerInstanceTest, MatchesTest_DataURLWorker) { const std::string kDataURL("data:text/javascript;base64,Ly8gSGVsbG8h"); + const std::string kFileURL("file:///w.js"); // SharedWorker created from a data: URL without a name option. GURL script_url1(kDataURL); @@ -113,6 +119,8 @@ // constructor origin. EXPECT_TRUE(Matches(instance1, kDataURL, "")); EXPECT_FALSE(Matches(instance1, kDataURL, "name")); + EXPECT_FALSE(Matches(instance1, kFileURL, "")); + EXPECT_FALSE(Matches(instance1, kFileURL, "name")); // SharedWorker created from a data: URL with a name option. GURL script_url2(kDataURL); @@ -138,6 +146,8 @@ // This should match because the instance has the same data: URL, name, and // constructor origin. EXPECT_TRUE(Matches(instance2, kDataURL, "name")); + EXPECT_FALSE(Matches(instance2, kFileURL, "")); + EXPECT_FALSE(Matches(instance2, kFileURL, "name")); // SharedWorker created from a data: URL on a remote origin (i.e., example.net // opposed to example.com) without a name option. @@ -164,6 +174,8 @@ // origin. EXPECT_FALSE(Matches(instance3, kDataURL, "")); EXPECT_FALSE(Matches(instance3, kDataURL, "name")); + EXPECT_FALSE(Matches(instance3, kFileURL, "")); + EXPECT_FALSE(Matches(instance3, kFileURL, "name")); // SharedWorker created from a data: URL on a remote origin (i.e., example.net // opposed to example.com) with a name option. @@ -190,6 +202,63 @@ // This should not match because the instance has a different constructor // origin. EXPECT_FALSE(Matches(instance4, kDataURL, "name")); + EXPECT_FALSE(Matches(instance4, kFileURL, "")); + EXPECT_FALSE(Matches(instance4, kFileURL, "name")); +} + +TEST_F(SharedWorkerInstanceTest, MatchesTest_FileURLWorker) { + const std::string kDataURL("data:text/javascript;base64,Ly8gSGVsbG8h"); + const std::string kFileURL("file:///w.js"); + + // SharedWorker created from a file:// URL without a name option. + GURL script_url1(kFileURL); + std::string name1(""); + url::Origin constructor_origin1 = url::Origin::Create(GURL(kFileURL)); + SharedWorkerInstance instance1 = + CreateInstance(script_url1, name1, constructor_origin1); + + EXPECT_FALSE(Matches(instance1, "http://example.com/w.js", "")); + EXPECT_FALSE(Matches(instance1, "http://example.com/w2.js", "")); + EXPECT_FALSE(Matches(instance1, "http://example.net/w.js", "")); + EXPECT_FALSE(Matches(instance1, "http://example.net/w2.js", "")); + EXPECT_FALSE(Matches(instance1, "http://example.com/w.js", "name")); + EXPECT_FALSE(Matches(instance1, "http://example.com/w2.js", "name")); + EXPECT_FALSE(Matches(instance1, "http://example.net/w.js", "name")); + EXPECT_FALSE(Matches(instance1, "http://example.net/w2.js", "name")); + EXPECT_FALSE(Matches(instance1, "http://example.com/w.js", "name2")); + EXPECT_FALSE(Matches(instance1, "http://example.com/w2.js", "name2")); + EXPECT_FALSE(Matches(instance1, "http://example.net/w.js", "name2")); + EXPECT_FALSE(Matches(instance1, "http://example.net/w2.js", "name2")); + EXPECT_FALSE(Matches(instance1, kDataURL, "")); + EXPECT_FALSE(Matches(instance1, kDataURL, "name")); + // This should not match because file:// URL is treated as an opaque origin. + EXPECT_FALSE(Matches(instance1, kFileURL, "")); + EXPECT_FALSE(Matches(instance1, kFileURL, "name")); + + // SharedWorker created from a file:// URL with a name option. + GURL script_url2(kFileURL); + std::string name2("name"); + url::Origin constructor_origin2 = url::Origin::Create(GURL(kFileURL)); + SharedWorkerInstance instance2 = + CreateInstance(script_url2, name2, constructor_origin2); + + EXPECT_FALSE(Matches(instance2, "http://example.com/w.js", "")); + EXPECT_FALSE(Matches(instance2, "http://example.com/w2.js", "")); + EXPECT_FALSE(Matches(instance2, "http://example.net/w.js", "")); + EXPECT_FALSE(Matches(instance2, "http://example.net/w2.js", "")); + EXPECT_FALSE(Matches(instance2, "http://example.com/w.js", "name")); + EXPECT_FALSE(Matches(instance2, "http://example.com/w2.js", "name")); + EXPECT_FALSE(Matches(instance2, "http://example.net/w.js", "name")); + EXPECT_FALSE(Matches(instance2, "http://example.net/w2.js", "name")); + EXPECT_FALSE(Matches(instance2, "http://example.com/w.js", "name2")); + EXPECT_FALSE(Matches(instance2, "http://example.com/w2.js", "name2")); + EXPECT_FALSE(Matches(instance2, "http://example.net/w.js", "name2")); + EXPECT_FALSE(Matches(instance2, "http://example.net/w2.js", "name2")); + EXPECT_FALSE(Matches(instance2, kDataURL, "")); + EXPECT_FALSE(Matches(instance2, kDataURL, "name")); + EXPECT_FALSE(Matches(instance2, kFileURL, "")); + // This should not match because file:// URL is treated as an opaque origin. + EXPECT_FALSE(Matches(instance2, kFileURL, "name")); } TEST_F(SharedWorkerInstanceTest, AddressSpace) {
diff --git a/content/browser/shared_worker/worker_browsertest.cc b/content/browser/shared_worker/worker_browsertest.cc index 2af16a39..dc7afdd 100644 --- a/content/browser/shared_worker/worker_browsertest.cc +++ b/content/browser/shared_worker/worker_browsertest.cc
@@ -71,10 +71,7 @@ return GetFileUrlWithQuery(test_file_path, query); } - void RunTest(Shell* window, - const std::string& test_case, - const std::string& query) { - GURL url = GetTestURL(test_case, query); + void RunTest(Shell* window, const GURL& url) { const base::string16 expected_title = base::ASCIIToUTF16("OK"); TitleWatcher title_watcher(window->web_contents(), expected_title); NavigateToURL(window, url); @@ -82,9 +79,7 @@ EXPECT_EQ(expected_title, final_title); } - void RunTest(const std::string& test_case, const std::string& query) { - RunTest(shell(), test_case, query); - } + void RunTest(const GURL& url) { RunTest(shell(), url); } static void QuitUIMessageLoop(base::Callback<void()> callback) { BrowserThread::PostTask(BrowserThread::UI, FROM_HERE, callback); @@ -108,18 +103,18 @@ }; IN_PROC_BROWSER_TEST_F(WorkerTest, SingleWorker) { - RunTest("single_worker.html", std::string()); + RunTest(GetTestURL("single_worker.html", std::string())); } IN_PROC_BROWSER_TEST_F(WorkerTest, MultipleWorkers) { - RunTest("multi_worker.html", std::string()); + RunTest(GetTestURL("multi_worker.html", std::string())); } IN_PROC_BROWSER_TEST_F(WorkerTest, SingleSharedWorker) { if (!SupportsSharedWorker()) return; - RunTest("single_worker.html", "shared=true"); + RunTest(GetTestURL("single_worker.html", "shared=true")); } // http://crbug.com/96435 @@ -127,7 +122,7 @@ if (!SupportsSharedWorker()) return; - RunTest("multi_worker.html", "shared=true"); + RunTest(GetTestURL("multi_worker.html", "shared=true")); } // Incognito windows should not share workers with non-incognito windows @@ -136,11 +131,17 @@ if (!SupportsSharedWorker()) return; + // Launch the server to host a shared worker on http environment because a + // local file (file://) is treated like it has an opaque origin and the + // shared worker on the origin cannot be shared. + ASSERT_TRUE(embedded_test_server()->Start()); + // Load a non-incognito tab and have it create a shared worker - RunTest("incognito_worker.html", std::string()); + RunTest(embedded_test_server()->GetURL("/workers/incognito_worker.html")); // Incognito worker should not share with non-incognito - RunTest(CreateOffTheRecordBrowser(), "incognito_worker.html", std::string()); + RunTest(CreateOffTheRecordBrowser(), + embedded_test_server()->GetURL("/workers/incognito_worker.html")); } // Make sure that auth dialog is displayed from worker context. @@ -179,9 +180,10 @@ https_server.SetSSLConfig(net::EmbeddedTestServer::CERT_OK, ssl_config); ASSERT_TRUE(https_server.Start()); - RunTest("worker_tls_client_auth.html", - "test=import&url=" + net::EscapeQueryParamValue( - https_server.GetURL("/").spec(), true)); + RunTest(GetTestURL( + "worker_tls_client_auth.html", + "test=import&url=" + + net::EscapeQueryParamValue(https_server.GetURL("/").spec(), true))); EXPECT_EQ(1, select_certificate_count()); } @@ -196,9 +198,10 @@ https_server.SetSSLConfig(net::EmbeddedTestServer::CERT_OK, ssl_config); ASSERT_TRUE(https_server.Start()); - RunTest("worker_tls_client_auth.html", - "test=fetch&url=" + net::EscapeQueryParamValue( - https_server.GetURL("/").spec(), true)); + RunTest(GetTestURL( + "worker_tls_client_auth.html", + "test=fetch&url=" + + net::EscapeQueryParamValue(https_server.GetURL("/").spec(), true))); EXPECT_EQ(1, select_certificate_count()); } @@ -217,10 +220,10 @@ https_server.SetSSLConfig(net::EmbeddedTestServer::CERT_OK, ssl_config); ASSERT_TRUE(https_server.Start()); - RunTest( + RunTest(GetTestURL( "worker_tls_client_auth.html", "test=import&shared=true&url=" + - net::EscapeQueryParamValue(https_server.GetURL("/").spec(), true)); + net::EscapeQueryParamValue(https_server.GetURL("/").spec(), true))); EXPECT_EQ(0, select_certificate_count()); } @@ -252,7 +255,7 @@ if (!SupportsSharedWorker()) return; - RunTest("pass_messageport_to_sharedworker.html", ""); + RunTest(GetTestURL("pass_messageport_to_sharedworker.html", "")); } IN_PROC_BROWSER_TEST_F(WorkerTest, @@ -260,7 +263,8 @@ if (!SupportsSharedWorker()) return; - RunTest("pass_messageport_to_sharedworker_dont_wait_for_connect.html", ""); + RunTest(GetTestURL( + "pass_messageport_to_sharedworker_dont_wait_for_connect.html", "")); } } // namespace content
diff --git a/content/browser/site_per_process_browsertest.cc b/content/browser/site_per_process_browsertest.cc index 3f6e916..2e11cec 100644 --- a/content/browser/site_per_process_browsertest.cc +++ b/content/browser/site_per_process_browsertest.cc
@@ -217,14 +217,13 @@ public: explicit RenderWidgetHostMouseEventMonitor(RenderWidgetHost* host) : host_(host), event_received_(false) { - host_->AddMouseEventCallback( + mouse_callback_ = base::Bind(&RenderWidgetHostMouseEventMonitor::MouseEventCallback, - base::Unretained(this))); + base::Unretained(this)); + host_->AddMouseEventCallback(mouse_callback_); } ~RenderWidgetHostMouseEventMonitor() { - host_->RemoveMouseEventCallback( - base::Bind(&RenderWidgetHostMouseEventMonitor::MouseEventCallback, - base::Unretained(this))); + host_->RemoveMouseEventCallback(mouse_callback_); } bool EventWasReceived() const { return event_received_; } void ResetEventReceived() { event_received_ = false; } @@ -236,6 +235,7 @@ event_ = event; return false; } + RenderWidgetHost::MouseEventCallback mouse_callback_; RenderWidgetHost* host_; bool event_received_; blink::WebMouseEvent event_; @@ -302,6 +302,34 @@ waiter.Wait(); } +void DispatchMouseEventAndWaitUntilDispatch( + WebContentsImpl* web_contents, + RenderWidgetHostViewBase* location_view, + const gfx::PointF& location, + RenderWidgetHostViewBase* expected_target, + const gfx::PointF& expected_location) { + auto* router = web_contents->GetInputEventRouter(); + + RenderWidgetHostMouseEventMonitor monitor( + expected_target->GetRenderWidgetHost()); + gfx::PointF root_location = + location_view->TransformPointToRootCoordSpaceF(location); + blink::WebMouseEvent down_event(blink::WebInputEvent::kMouseDown, + blink::WebInputEvent::kNoModifiers, + blink::WebInputEvent::kTimeStampForTesting); + down_event.button = blink::WebPointerProperties::Button::kLeft; + down_event.SetPositionInWidget(root_location.x(), root_location.y()); + down_event.click_count = 1; + FrameTreeNode* root = web_contents->GetFrameTree()->root(); + auto* root_view = static_cast<RenderWidgetHostViewBase*>( + root->current_frame_host()->GetRenderWidgetHost()->GetView()); + RouteMouseEventAndWaitUntilDispatch(router, root_view, expected_target, + &down_event); + EXPECT_TRUE(monitor.EventWasReceived()); + EXPECT_NEAR(expected_location.x(), monitor.event().PositionInWidget().x, 2); + EXPECT_NEAR(expected_location.y(), monitor.event().PositionInWidget().y, 2); +} + // Helper function that performs a surface hittest. void SurfaceHitTestTestHelper( Shell* shell, @@ -309,11 +337,10 @@ GURL main_url(embedded_test_server->GetURL( "/frame_tree/page_with_positioned_frame.html")); EXPECT_TRUE(NavigateToURL(shell, main_url)); + auto* web_contents = static_cast<WebContentsImpl*>(shell->web_contents()); // It is safe to obtain the root frame tree node here, as it doesn't change. - FrameTreeNode* root = static_cast<WebContentsImpl*>(shell->web_contents()) - ->GetFrameTree() - ->root(); + FrameTreeNode* root = web_contents->GetFrameTree()->root(); ASSERT_EQ(1U, root->child_count()); FrameTreeNode* child_node = root->child_at(0); @@ -322,110 +349,6 @@ EXPECT_NE(shell->web_contents()->GetSiteInstance(), child_node->current_frame_host()->GetSiteInstance()); - // Create listeners for mouse events. - RenderWidgetHostMouseEventMonitor main_frame_monitor( - root->current_frame_host()->GetRenderWidgetHost()); - RenderWidgetHostMouseEventMonitor child_frame_monitor( - child_node->current_frame_host()->GetRenderWidgetHost()); - - RenderWidgetHostInputEventRouter* router = - static_cast<WebContentsImpl*>(shell->web_contents()) - ->GetInputEventRouter(); - - RenderWidgetHostViewBase* root_view = static_cast<RenderWidgetHostViewBase*>( - root->current_frame_host()->GetRenderWidgetHost()->GetView()); - RenderWidgetHostViewBase* rwhv_child = static_cast<RenderWidgetHostViewBase*>( - child_node->current_frame_host()->GetRenderWidgetHost()->GetView()); - - WaitForChildFrameSurfaceReady(child_node->current_frame_host()); - - // Target input event to child frame. - gfx::PointF child_location(5, 5); - child_location = rwhv_child->TransformPointToRootCoordSpaceF(child_location); - blink::WebMouseEvent child_event(blink::WebInputEvent::kMouseDown, - blink::WebInputEvent::kNoModifiers, - blink::WebInputEvent::kTimeStampForTesting); - child_event.button = blink::WebPointerProperties::Button::kLeft; - child_event.SetPositionInWidget(child_location.x(), child_location.y()); - child_event.click_count = 1; - - // Check the renderer hit-test API return the correct frame for - // the cross site iframe. - base::RunLoop run_loop; - viz::FrameSinkId received_frame_sink_id; - base::Closure quit_closure = - content::GetDeferredQuitTaskForRunLoop(&run_loop); - DCHECK_NE(root->current_frame_host()->GetInputTargetClient(), nullptr); - root->current_frame_host()->GetInputTargetClient()->FrameSinkIdAt( - gfx::ToCeiledPoint(child_event.PositionInWidget()), - base::BindLambdaForTesting([&](const viz::FrameSinkId& id) { - received_frame_sink_id = id; - quit_closure.Run(); - })); - content::RunThisRunLoop(&run_loop); - ASSERT_EQ(rwhv_child->GetFrameSinkId(), received_frame_sink_id); - - main_frame_monitor.ResetEventReceived(); - child_frame_monitor.ResetEventReceived(); - RouteMouseEventAndWaitUntilDispatch(router, root_view, rwhv_child, - &child_event); - - EXPECT_TRUE(child_frame_monitor.EventWasReceived()); - // The expected result coordinates are (5, 5), but can get slightly - // different results due to rounding error with some page scale factors. - EXPECT_NEAR(5, child_frame_monitor.event().PositionInWidget().x, 2); - EXPECT_NEAR(5, child_frame_monitor.event().PositionInWidget().y, 2); - EXPECT_FALSE(main_frame_monitor.EventWasReceived()); - - child_frame_monitor.ResetEventReceived(); - main_frame_monitor.ResetEventReceived(); - - // Target input event to main frame. - blink::WebMouseEvent main_event(blink::WebInputEvent::kMouseDown, - blink::WebInputEvent::kNoModifiers, - blink::WebInputEvent::kTimeStampForTesting); - main_event.button = blink::WebPointerProperties::Button::kLeft; - main_event.SetPositionInWidget(2, 2); - main_event.click_count = 1; - // Ladies and gentlemen, THIS is the main_event! - RouteMouseEventAndWaitUntilDispatch(router, root_view, root_view, - &main_event); - - EXPECT_FALSE(child_frame_monitor.EventWasReceived()); - EXPECT_TRUE(main_frame_monitor.EventWasReceived()); - EXPECT_NEAR(2, main_frame_monitor.event().PositionInWidget().x, 2); - EXPECT_NEAR(2, main_frame_monitor.event().PositionInWidget().y, 2); -} - -void OverlapSurfaceHitTestHelper( - Shell* shell, - net::test_server::EmbeddedTestServer* embedded_test_server) { - GURL main_url(embedded_test_server->GetURL( - "/frame_tree/page_with_content_overlap_positioned_frame.html")); - EXPECT_TRUE(NavigateToURL(shell, main_url)); - - // It is safe to obtain the root frame tree node here, as it doesn't change. - FrameTreeNode* root = static_cast<WebContentsImpl*>(shell->web_contents()) - ->GetFrameTree() - ->root(); - ASSERT_EQ(1U, root->child_count()); - - FrameTreeNode* child_node = root->child_at(0); - GURL site_url(embedded_test_server->GetURL("baz.com", "/title1.html")); - EXPECT_EQ(site_url, child_node->current_url()); - EXPECT_NE(shell->web_contents()->GetSiteInstance(), - child_node->current_frame_host()->GetSiteInstance()); - - // Create listeners for mouse events. - RenderWidgetHostMouseEventMonitor main_frame_monitor( - root->current_frame_host()->GetRenderWidgetHost()); - RenderWidgetHostMouseEventMonitor child_frame_monitor( - child_node->current_frame_host()->GetRenderWidgetHost()); - - RenderWidgetHostInputEventRouter* router = - static_cast<WebContentsImpl*>(shell->web_contents()) - ->GetInputEventRouter(); - RenderWidgetHostViewBase* rwhv_root = static_cast<RenderWidgetHostViewBase*>( root->current_frame_host()->GetRenderWidgetHost()->GetView()); RenderWidgetHostViewBase* rwhv_child = static_cast<RenderWidgetHostViewBase*>( @@ -433,50 +356,48 @@ WaitForChildFrameSurfaceReady(child_node->current_frame_host()); - // Target input event to the button overlapping the child frame. - gfx::PointF button_location(5, 5); - button_location = - rwhv_child->TransformPointToRootCoordSpaceF(button_location); - blink::WebMouseEvent button_event(blink::WebInputEvent::kMouseDown, - blink::WebInputEvent::kNoModifiers, - blink::WebInputEvent::kTimeStampForTesting); - button_event.button = blink::WebPointerProperties::Button::kLeft; - button_event.SetPositionInWidget(button_location.x(), button_location.y()); - button_event.click_count = 1; + DispatchMouseEventAndWaitUntilDispatch(web_contents, rwhv_child, + gfx::PointF(5, 5), rwhv_child, + gfx::PointF(5, 5)); - main_frame_monitor.ResetEventReceived(); - child_frame_monitor.ResetEventReceived(); - RouteMouseEventAndWaitUntilDispatch(router, rwhv_root, rwhv_root, - &button_event); + DispatchMouseEventAndWaitUntilDispatch( + web_contents, rwhv_root, gfx::PointF(2, 2), rwhv_root, gfx::PointF(2, 2)); +} - // The main-frame should receive the event at the same location it was - // dispatched to. - EXPECT_TRUE(main_frame_monitor.EventWasReceived()); - EXPECT_NEAR(button_location.x(), - main_frame_monitor.event().PositionInWidget().x, 2); - EXPECT_NEAR(button_location.y(), - main_frame_monitor.event().PositionInWidget().y, 2); - EXPECT_FALSE(child_frame_monitor.EventWasReceived()); +void OverlapSurfaceHitTestHelper( + Shell* shell, + net::test_server::EmbeddedTestServer* embedded_test_server) { + GURL main_url(embedded_test_server->GetURL( + "/frame_tree/page_with_content_overlap_positioned_frame.html")); + EXPECT_TRUE(NavigateToURL(shell, main_url)); + auto* web_contents = static_cast<WebContentsImpl*>(shell->web_contents()); - // Now send an event that should go to the bottom-right edge of child. - gfx::PointF event_location(95, 95); - event_location = rwhv_child->TransformPointToRootCoordSpaceF(event_location); - blink::WebMouseEvent child_event(blink::WebInputEvent::kMouseDown, - blink::WebInputEvent::kNoModifiers, - blink::WebInputEvent::kTimeStampForTesting); - child_event.SetPositionInWidget(event_location.x(), event_location.y()); - child_event.click_count = 1; - main_frame_monitor.ResetEventReceived(); - child_frame_monitor.ResetEventReceived(); - RouteMouseEventAndWaitUntilDispatch(router, rwhv_root, rwhv_child, - &child_event); - EXPECT_TRUE(child_frame_monitor.EventWasReceived()); - // The expected result coordinates are (5, 5) from the bottom-right edge (and - // it's sized 100x100), but can get slightly different results due to rounding - // error with some page scale factors. - EXPECT_NEAR(95, child_frame_monitor.event().PositionInWidget().x, 2); - EXPECT_NEAR(95, child_frame_monitor.event().PositionInWidget().y, 2); - EXPECT_FALSE(main_frame_monitor.EventWasReceived()); + // It is safe to obtain the root frame tree node here, as it doesn't change. + FrameTreeNode* root = web_contents->GetFrameTree()->root(); + ASSERT_EQ(1U, root->child_count()); + + FrameTreeNode* child_node = root->child_at(0); + GURL site_url(embedded_test_server->GetURL("baz.com", "/title1.html")); + EXPECT_EQ(site_url, child_node->current_url()); + EXPECT_NE(shell->web_contents()->GetSiteInstance(), + child_node->current_frame_host()->GetSiteInstance()); + + RenderWidgetHostViewBase* rwhv_root = static_cast<RenderWidgetHostViewBase*>( + root->current_frame_host()->GetRenderWidgetHost()->GetView()); + RenderWidgetHostViewBase* rwhv_child = static_cast<RenderWidgetHostViewBase*>( + child_node->current_frame_host()->GetRenderWidgetHost()->GetView()); + + WaitForChildFrameSurfaceReady(child_node->current_frame_host()); + + gfx::PointF parent_location = gfx::PointF(5, 5); + parent_location = + rwhv_child->TransformPointToRootCoordSpaceF(parent_location); + DispatchMouseEventAndWaitUntilDispatch( + web_contents, rwhv_child, gfx::PointF(5, 5), rwhv_root, parent_location); + + DispatchMouseEventAndWaitUntilDispatch(web_contents, rwhv_child, + gfx::PointF(95, 95), rwhv_child, + gfx::PointF(95, 95)); } // Helper function that performs a surface hittest in nested frame. @@ -507,17 +428,6 @@ EXPECT_NE(parent_iframe_node->current_frame_host()->GetSiteInstance(), nested_iframe_node->current_frame_host()->GetSiteInstance()); - // Create listeners for mouse events. - RenderWidgetHostMouseEventMonitor main_frame_monitor( - root->current_frame_host()->GetRenderWidgetHost()); - RenderWidgetHostMouseEventMonitor nested_frame_monitor( - nested_iframe_node->current_frame_host()->GetRenderWidgetHost()); - - RenderWidgetHostInputEventRouter* router = - web_contents->GetInputEventRouter(); - - RenderWidgetHostViewBase* root_view = static_cast<RenderWidgetHostViewBase*>( - root->current_frame_host()->GetRenderWidgetHost()->GetView()); RenderWidgetHostViewBase* rwhv_nested = static_cast<RenderWidgetHostViewBase*>( nested_iframe_node->current_frame_host() @@ -526,36 +436,101 @@ WaitForChildFrameSurfaceReady(nested_iframe_node->current_frame_host()); - float scale_factor = GetPageScaleFactor(shell); + DispatchMouseEventAndWaitUntilDispatch(web_contents, rwhv_nested, + gfx::PointF(10, 10), rwhv_nested, + gfx::PointF(10, 10)); +} - // Get the view bounds of the nested iframe, which should account for the - // relative offset of its direct parent within the root frame, for use in - // targeting the input event. - gfx::Rect bounds = rwhv_nested->GetViewBounds(); +void HitTestLayerSquashing( + Shell* shell, + net::test_server::EmbeddedTestServer* embedded_test_server) { + GURL main_url(embedded_test_server->GetURL( + "/frame_tree/oopif_hit_test_layer_squashing.html")); + EXPECT_TRUE(NavigateToURL(shell, main_url)); + auto* web_contents = static_cast<WebContentsImpl*>(shell->web_contents()); - // Target input event to nested frame. - blink::WebMouseEvent nested_event(blink::WebInputEvent::kMouseDown, - blink::WebInputEvent::kNoModifiers, - blink::WebInputEvent::kTimeStampForTesting); - nested_event.button = blink::WebPointerProperties::Button::kLeft; - nested_event.SetPositionInWidget( - gfx::ToCeiledInt((bounds.x() - root_view->GetViewBounds().x() + 10) * - scale_factor), - gfx::ToCeiledInt((bounds.y() - root_view->GetViewBounds().y() + 10) * - scale_factor)); - nested_event.click_count = 1; - nested_frame_monitor.ResetEventReceived(); - main_frame_monitor.ResetEventReceived(); - auto* rwhv_child = nested_iframe_node->current_frame_host() - ->GetRenderWidgetHost() - ->GetView(); - RouteMouseEventAndWaitUntilDispatch(router, root_view, rwhv_child, - &nested_event); + // It is safe to obtain the root frame tree node here, as it doesn't change. + FrameTreeNode* root = web_contents->GetFrameTree()->root(); + ASSERT_EQ(1U, root->child_count()); - EXPECT_TRUE(nested_frame_monitor.EventWasReceived()); - EXPECT_NEAR(10, nested_frame_monitor.event().PositionInWidget().x, 2); - EXPECT_NEAR(10, nested_frame_monitor.event().PositionInWidget().y, 2); - EXPECT_FALSE(main_frame_monitor.EventWasReceived()); + FrameTreeNode* child_node = root->child_at(0); + GURL site_url(embedded_test_server->GetURL("baz.com", "/title1.html")); + EXPECT_EQ(site_url, child_node->current_url()); + EXPECT_NE(shell->web_contents()->GetSiteInstance(), + child_node->current_frame_host()->GetSiteInstance()); + + RenderWidgetHostViewBase* rwhv_root = static_cast<RenderWidgetHostViewBase*>( + root->current_frame_host()->GetRenderWidgetHost()->GetView()); + RenderWidgetHostViewBase* rwhv_child = static_cast<RenderWidgetHostViewBase*>( + child_node->current_frame_host()->GetRenderWidgetHost()->GetView()); + + WaitForChildFrameSurfaceReady(child_node->current_frame_host()); + + gfx::Vector2dF child_offset = rwhv_child->GetViewBounds().origin() - + rwhv_root->GetViewBounds().origin(); + // Send a mouse-down on #B. The main-frame should receive it. + DispatchMouseEventAndWaitUntilDispatch(web_contents, rwhv_root, + gfx::PointF(195, 11), rwhv_root, + gfx::PointF(195, 11)); + // Send another event just below. The child-frame should receive it. + DispatchMouseEventAndWaitUntilDispatch(web_contents, rwhv_root, + gfx::PointF(195, 30), rwhv_child, + gfx::PointF(195, 30) - child_offset); + // Send a mouse-down on #C. + DispatchMouseEventAndWaitUntilDispatch(web_contents, rwhv_root, + gfx::PointF(35, 195), rwhv_root, + gfx::PointF(35, 195)); + // Send a mouse-down to the right of #C so that it goes to the child frame. + DispatchMouseEventAndWaitUntilDispatch(web_contents, rwhv_root, + gfx::PointF(55, 195), rwhv_child, + gfx::PointF(55, 195) - child_offset); + // Send a mouse-down to the right-bottom edge of the iframe. + DispatchMouseEventAndWaitUntilDispatch(web_contents, rwhv_root, + gfx::PointF(195, 235), rwhv_child, + gfx::PointF(195, 235) - child_offset); +} + +void HitTestWatermark( + Shell* shell, + net::test_server::EmbeddedTestServer* embedded_test_server) { + GURL main_url(embedded_test_server->GetURL( + "/frame_tree/oopif_hit_test_watermark.html")); + EXPECT_TRUE(NavigateToURL(shell, main_url)); + auto* web_contents = static_cast<WebContentsImpl*>(shell->web_contents()); + + // It is safe to obtain the root frame tree node here, as it doesn't change. + FrameTreeNode* root = web_contents->GetFrameTree()->root(); + ASSERT_EQ(1U, root->child_count()); + + FrameTreeNode* child_node = root->child_at(0); + GURL site_url(embedded_test_server->GetURL("baz.com", "/title1.html")); + EXPECT_EQ(site_url, child_node->current_url()); + EXPECT_NE(shell->web_contents()->GetSiteInstance(), + child_node->current_frame_host()->GetSiteInstance()); + + RenderWidgetHostViewBase* rwhv_root = static_cast<RenderWidgetHostViewBase*>( + root->current_frame_host()->GetRenderWidgetHost()->GetView()); + RenderWidgetHostViewBase* rwhv_child = static_cast<RenderWidgetHostViewBase*>( + child_node->current_frame_host()->GetRenderWidgetHost()->GetView()); + + WaitForChildFrameSurfaceReady(child_node->current_frame_host()); + + gfx::Vector2dF child_offset = rwhv_child->GetViewBounds().origin() - + rwhv_root->GetViewBounds().origin(); + const gfx::PointF child_location(100, 120); + // Send a mouse-down at the center of the iframe. This should go to the + // main-frame (since there's a translucent div on top of it). + DispatchMouseEventAndWaitUntilDispatch(web_contents, rwhv_child, + child_location, rwhv_root, + child_location + child_offset); + + // Set 'pointer-events: none' on the div. + EXPECT_TRUE(ExecuteScript(web_contents, "W.style.pointerEvents = 'none';")); + + // Dispatch another event at the same location. It should reach the oopif this + // time. + DispatchMouseEventAndWaitUntilDispatch( + web_contents, rwhv_child, child_location, rwhv_child, child_location); } class RedirectNotificationObserver : public NotificationObserver { @@ -2381,6 +2356,23 @@ OverlapSurfaceHitTestHelper(shell(), embedded_test_server()); } +IN_PROC_BROWSER_TEST_F(SitePerProcessBrowserTest, HitTestLayerSquashing) { + HitTestLayerSquashing(shell(), embedded_test_server()); +} + +IN_PROC_BROWSER_TEST_F(SitePerProcessHighDPIBrowserTest, + HitTestLayerSquashing) { + HitTestLayerSquashing(shell(), embedded_test_server()); +} + +IN_PROC_BROWSER_TEST_F(SitePerProcessBrowserTest, HitTestWatermark) { + HitTestWatermark(shell(), embedded_test_server()); +} + +IN_PROC_BROWSER_TEST_F(SitePerProcessHighDPIBrowserTest, HitTestWatermark) { + HitTestWatermark(shell(), embedded_test_server()); +} + // This test tests that browser process hittesting ignores frames with // pointer-events: none. IN_PROC_BROWSER_TEST_F(SitePerProcessBrowserTest,
diff --git a/content/child/blink_platform_impl.cc b/content/child/blink_platform_impl.cc index fc37e0d..94f50767 100644 --- a/content/child/blink_platform_impl.cc +++ b/content/child/blink_platform_impl.cc
@@ -184,6 +184,14 @@ return IDS_MEDIA_REMOTING_CAST_TEXT; case WebLocalizedString::kMediaRemotingCastToUnknownDeviceText: return IDS_MEDIA_REMOTING_CAST_TO_UNKNOWN_DEVICE_TEXT; + case WebLocalizedString::kMediaRemotingStopByErrorText: + return IDS_MEDIA_REMOTING_STOP_BY_ERROR_TEXT; + case WebLocalizedString::kMediaRemotingStopByPlaybackQualityText: + return IDS_MEDIA_REMOTING_STOP_BY_PLAYBACK_QUALITY_TEXT; + case WebLocalizedString::kMediaRemotingStopNoText: + return -1; // This string name is used only to indicate an empty string. + case WebLocalizedString::kMediaRemotingStopText: + return IDS_MEDIA_REMOTING_STOP_TEXT; case WebLocalizedString::kMultipleFileUploadText: return IDS_FORM_FILE_MULTIPLE_UPLOAD; case WebLocalizedString::kOtherColorLabel:
diff --git a/content/common/BUILD.gn b/content/common/BUILD.gn index 996530af..64e94f8c 100644 --- a/content/common/BUILD.gn +++ b/content/common/BUILD.gn
@@ -45,8 +45,6 @@ "android/hash_set.h", "android/media_metadata_android.cc", "android/media_metadata_android.h", - "android/resource_request_body_android.cc", - "android/resource_request_body_android.h", "android/sync_compositor_statics.cc", "android/sync_compositor_statics.h", "appcache_interfaces.cc",
diff --git a/content/public/android/BUILD.gn b/content/public/android/BUILD.gn index 3eb9436c..02b7b3c 100644 --- a/content/public/android/BUILD.gn +++ b/content/public/android/BUILD.gn
@@ -148,7 +148,7 @@ "java/src/org/chromium/content/browser/SelectionEventProxyImpl.java", "java/src/org/chromium/content/browser/SelectionIndicesConverter.java", "java/src/org/chromium/content/browser/SelectionInsertionHandleObserver.java", - "java/src/org/chromium/content/browser/SelectionPopupController.java", + "java/src/org/chromium/content/browser/SelectionPopupControllerImpl.java", "java/src/org/chromium/content/browser/SmartClipProvider.java", "java/src/org/chromium/content/browser/SmartSelectionClient.java", "java/src/org/chromium/content/browser/SmartSelectionMetricsLogger.java", @@ -248,6 +248,7 @@ "java/src/org/chromium/content_public/browser/ScreenOrientationDelegateManager.java", "java/src/org/chromium/content_public/browser/SelectionClient.java", "java/src/org/chromium/content_public/browser/SelectionMetricsLogger.java", + "java/src/org/chromium/content_public/browser/SelectionPopupController.java", "java/src/org/chromium/content_public/browser/SmartClipCallback.java", "java/src/org/chromium/content_public/browser/WebContents.java", "java/src/org/chromium/content_public/browser/WebContentsInternals.java", @@ -366,7 +367,7 @@ "java/src/org/chromium/content/browser/NfcHost.java", "java/src/org/chromium/content/browser/PopupZoomer.java", "java/src/org/chromium/content/browser/ScreenOrientationProvider.java", - "java/src/org/chromium/content/browser/SelectionPopupController.java", + "java/src/org/chromium/content/browser/SelectionPopupControllerImpl.java", "java/src/org/chromium/content/browser/SmartSelectionClient.java", "java/src/org/chromium/content/browser/SpeechRecognition.java", "java/src/org/chromium/content/browser/SyntheticGestureTarget.java",
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 54faae9..378486f 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
@@ -6,11 +6,9 @@ import android.annotation.TargetApi; import android.content.Context; -import android.content.Intent; import android.content.res.Configuration; import android.os.Build; import android.os.Bundle; -import android.view.ActionMode; import android.view.KeyEvent; import android.view.MotionEvent; import android.view.View; @@ -19,16 +17,13 @@ import android.view.accessibility.AccessibilityNodeProvider; import android.view.inputmethod.EditorInfo; import android.view.inputmethod.InputConnection; -import android.view.textclassifier.TextClassifier; import org.chromium.base.VisibleForTesting; import org.chromium.content.browser.accessibility.WebContentsAccessibility; import org.chromium.content.browser.input.ImeAdapter; import org.chromium.content.browser.input.SelectPopup; import org.chromium.content.browser.input.TextSuggestionHost; -import org.chromium.content_public.browser.ActionModeCallbackHelper; import org.chromium.content_public.browser.ImeEventObserver; -import org.chromium.content_public.browser.SelectionClient; import org.chromium.content_public.browser.WebContents; import org.chromium.ui.base.ViewAndroidDelegate; import org.chromium.ui.base.WindowAndroid; @@ -148,24 +143,6 @@ void updateWindowAndroid(WindowAndroid windowAndroid); /** - * Set {@link ActionMode.Callback} used by {@link SelectionPopupController}. - * @param callback ActionMode.Callback instance. - */ - void setActionModeCallback(ActionMode.Callback callback); - - /** - * Set {@link ActionMode.Callback} used by {@link SelectionPopupController} when no text is - * selected. - * @param callback ActionMode.Callback instance. - */ - void setNonSelectionActionModeCallback(ActionMode.Callback callback); - - /** - * @return {@link SelectionClient.ResultCallback} instance. - */ - SelectionClient.ResultCallback getPopupControllerResultCallback(); - - /** * Sets a new container view for this {@link ContentViewCore}. * * <p>WARNING: This method can also be used to replace the existing container view, @@ -221,11 +198,6 @@ int getViewportHeightPix(); /** - * @return Whether the current focused node is editable. - */ - boolean isFocusedNodeEditable(); - - /** * @return Whether a scroll targeting web content is in progress. */ boolean isScrollInProgress(); @@ -262,16 +234,6 @@ void onHide(); /** - * Hide action mode and put into destroyed state. - */ - void destroySelectActionMode(); - - /** - * @return {@code true} if select action bar is showing. - */ - boolean isSelectActionBarShowing(); - - /** * Whether or not the associated ContentView is currently attached to a window. */ boolean isAttachedToWindow(); @@ -429,16 +391,6 @@ void selectPopupMenuItems(int[] indices); /** - * @return {@link ActionModeCallbackHelper} object. - */ - ActionModeCallbackHelper getActionModeCallbackHelper(); - - /** - * Clears the current text selection. - */ - void clearSelection(); - - /** * Ensure the selection is preserved the next time the view loses focus. */ void preserveSelectionOnNextLossOfFocus(); @@ -490,14 +442,6 @@ void setObscuredByAnotherView(boolean isObscured); /** - * Called when the processed text is replied from an activity that supports - * Intent.ACTION_PROCESS_TEXT. - * @param resultCode the code that indicates if the activity successfully processed the text - * @param data the reply that contains the processed text. - */ - void onReceivedProcessTextResult(int resultCode, Intent data); - - /** * Returns true if accessibility is on and touch exploration is enabled. */ boolean isTouchExplorationEnabled(); @@ -537,38 +481,9 @@ */ void setFullscreenRequiredForOrientationLock(boolean value); - /** Sets the given {@link SelectionClient} in the selection popup controller. */ - void setSelectionClient(SelectionClient selectionClient); - - /** - * Sets TextClassifier for Smart Text selection. - */ - void setTextClassifier(TextClassifier textClassifier); - - /** - * Returns TextClassifier that is used for Smart Text selection. If the custom classifier - * has been set with setTextClassifier, returns that object, otherwise returns the system - * classifier. - */ - TextClassifier getTextClassifier(); - - /** - * Returns the TextClassifier which has been set with setTextClassifier(), or null. - */ - TextClassifier getCustomTextClassifier(); - // Test-only methods /** - * @return The SelectionPopupController that handles select action mode on web contents. - */ - @VisibleForTesting - SelectionPopupController getSelectionPopupControllerForTesting(); - - @VisibleForTesting - void setSelectionPopupControllerForTesting(SelectionPopupController actionMode); - - /** * @return The TextSuggestionHost that handles displaying the text suggestion menu. */ @VisibleForTesting @@ -587,12 +502,6 @@ void setPopupZoomerForTest(PopupZoomer popupZoomer); /** - * @return The selected text (empty if no text selected). - */ - @VisibleForTesting - String getSelectedText(); - - /** * @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 d0129086..f107e00 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
@@ -8,14 +8,12 @@ import android.annotation.TargetApi; import android.app.assist.AssistStructure.ViewNode; import android.content.Context; -import android.content.Intent; import android.content.res.Configuration; import android.graphics.Rect; import android.os.Build; import android.os.Build.VERSION_CODES; import android.os.Bundle; import android.os.SystemClock; -import android.view.ActionMode; import android.view.HapticFeedbackConstants; import android.view.InputDevice; import android.view.KeyEvent; @@ -30,7 +28,6 @@ import android.view.accessibility.AccessibilityNodeProvider; import android.view.inputmethod.EditorInfo; import android.view.inputmethod.InputConnection; -import android.view.textclassifier.TextClassifier; import org.chromium.base.ObserverList; import org.chromium.base.TraceEvent; @@ -57,7 +54,6 @@ import org.chromium.content_public.browser.GestureListenerManager; import org.chromium.content_public.browser.GestureStateListener; import org.chromium.content_public.browser.ImeEventObserver; -import org.chromium.content_public.browser.SelectionClient; import org.chromium.content_public.browser.WebContents; import org.chromium.content_public.browser.WebContentsObserver; import org.chromium.device.gamepad.GamepadList; @@ -190,7 +186,6 @@ private boolean mIsMobileOptimizedHint; - private SelectionPopupController mSelectionPopupController; private boolean mPreserveSelectionOnNextLossOfFocus; // Whether native accessibility, i.e. without any script injection, is allowed. @@ -302,23 +297,16 @@ @VisibleForTesting @Override - public SelectionPopupController getSelectionPopupControllerForTesting() { - return mSelectionPopupController; - } - - @VisibleForTesting - @Override - public void setSelectionPopupControllerForTesting(SelectionPopupController actionMode) { - mSelectionPopupController = actionMode; - } - - @VisibleForTesting - @Override public TextSuggestionHost getTextSuggestionHostForTesting() { return mTextSuggestionHost; } @VisibleForTesting + void setWebContentsForTesting(WebContentsImpl webContents) { + mWebContents = webContents; + } + + @VisibleForTesting @Override public void setTextSuggestionHostForTesting(TextSuggestionHost textSuggestionHost) { mTextSuggestionHost = textSuggestionHost; @@ -365,7 +353,6 @@ InternalAccessDelegate internalDispatcher, WebContents webContents, WindowAndroid windowAndroid) { mViewAndroidDelegate = viewDelegate; - setContainerView(viewDelegate.getContainerView()); long windowNativePointer = windowAndroid.getNativePointer(); assert windowNativePointer != 0; @@ -374,6 +361,11 @@ mNativeContentViewCore = nativeInit(webContents, mViewAndroidDelegate, windowNativePointer, dipScale); mWebContents = (WebContentsImpl) nativeGetWebContentsAndroid(mNativeContentViewCore); + ViewGroup containerView = viewDelegate.getContainerView(); + SelectionPopupControllerImpl controller = SelectionPopupControllerImpl.create( + mContext, windowAndroid, webContents, containerView); + controller.setActionModeCallback(ActionModeCallbackHelper.EMPTY_CALLBACK); + setContainerView(containerView); mRenderCoordinates = mWebContents.getRenderCoordinates(); mRenderCoordinates.setDeviceScaleFactor(dipScale, windowAndroid.getContext().get()); @@ -385,11 +377,6 @@ mImeAdapter.addEventObserver(this); mTextSuggestionHost = new TextSuggestionHost(this); - mSelectionPopupController = - new SelectionPopupController(mContext, windowAndroid, webContents, mContainerView); - mSelectionPopupController.setCallback(ActionModeCallbackHelper.EMPTY_CALLBACK); - mSelectionPopupController.setContainerView(mContainerView); - mWebContentsObserver = new ContentViewWebContentsObserver(this); mShouldRequestUnbufferedDispatch = Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP @@ -422,21 +409,6 @@ return getWebContents().getEventForwarder(); } - @Override - public void setActionModeCallback(ActionMode.Callback callback) { - mSelectionPopupController.setCallback(callback); - } - - @Override - public void setNonSelectionActionModeCallback(ActionMode.Callback callback) { - mSelectionPopupController.setNonSelectionCallback(callback); - } - - @Override - public SelectionClient.ResultCallback getPopupControllerResultCallback() { - return mSelectionPopupController.getResultCallback(); - } - private void addDisplayAndroidObserverIfNeeded() { if (!mAttachedToWindow) return; WindowAndroid windowAndroid = getWindowAndroid(); @@ -467,14 +439,16 @@ mContainerView = containerView; mContainerView.setClickable(true); - if (mSelectionPopupController != null) { - mSelectionPopupController.setContainerView(containerView); - } + getSelectionPopupController().setContainerView(containerView); } finally { TraceEvent.end("ContentViewCore.setContainerView"); } } + private SelectionPopupControllerImpl getSelectionPopupController() { + return SelectionPopupControllerImpl.fromWebContents(mWebContents); + } + @CalledByNative private void onNativeContentViewCoreDestroyed(long nativeContentViewCore) { assert nativeContentViewCore == mNativeContentViewCore; @@ -501,10 +475,9 @@ mWebContentsObserver.destroy(); mWebContentsObserver = null; mImeAdapter.resetAndHideKeyboard(); + hidePopupsAndPreserveSelection(); mWebContents = null; mNativeContentViewCore = 0; - hidePopupsAndPreserveSelection(); - destroyPastePopup(); // See warning in javadoc before adding more clean up code here. } @@ -537,12 +510,6 @@ @VisibleForTesting @Override - public String getSelectedText() { - return mSelectionPopupController.getSelectedText(); - } - - @VisibleForTesting - @Override public int getTopControlsShrinkBlinkHeightForTesting() { // TODO(jinsukkim): Let callsites provide with its own top controls height to remove // the test-only method in content layer. @@ -550,11 +517,6 @@ return nativeGetTopControlsShrinkBlinkHeightPixForTesting(mNativeContentViewCore); } - @Override - public boolean isFocusedNodeEditable() { - return mSelectionPopupController.isSelectionEditable(); - } - @CalledByNative private void requestDisallowInterceptTouchEvent() { mContainerView.requestDisallowInterceptTouchEvent(true); @@ -567,7 +529,7 @@ private void setTouchScrollInProgress(boolean inProgress) { mTouchScrollInProgress = inProgress; - mSelectionPopupController.setScrollInProgress(inProgress, isScrollInProgress()); + getSelectionPopupController().setScrollInProgress(inProgress, isScrollInProgress()); } /** @@ -630,8 +592,10 @@ } private void hidePopupsAndClearSelection() { - mSelectionPopupController.destroyActionModeAndUnselect(); - destroyPastePopup(); + if (isAlive()) { + getSelectionPopupController().destroyActionModeAndUnselect(); + destroyPastePopup(); + } hideSelectPopupWithCancelMessage(); mPopupZoomer.hide(false); mTextSuggestionHost.hidePopups(); @@ -640,25 +604,17 @@ @CalledByNative private void hidePopupsAndPreserveSelection() { - mSelectionPopupController.destroyActionModeAndKeepSelection(); - destroyPastePopup(); + if (isAlive()) { + getSelectionPopupController().destroyActionModeAndKeepSelection(); + destroyPastePopup(); + } hideSelectPopupWithCancelMessage(); mPopupZoomer.hide(false); mTextSuggestionHost.hidePopups(); } private void restoreSelectionPopupsIfNecessary() { - mSelectionPopupController.restoreSelectionPopupsIfNecessary(); - } - - @Override - public void destroySelectActionMode() { - mSelectionPopupController.finishActionMode(); - } - - @Override - public boolean isSelectActionBarShowing() { - return mSelectionPopupController.isActionModeValid(); + getSelectionPopupController().restoreSelectionPopupsIfNecessary(); } private void resetGestureDetection() { @@ -712,7 +668,7 @@ // Override the handle visibility explicitly to address this, but // preserve the underlying selection for detachment cases like screen // locking and app switching. - updateTextSelectionUI(false); + if (isAlive()) updateTextSelectionUI(false); mSystemCaptioningBridge.removeListener(this); if (mWebContentsAccessibility != null) { mWebContentsAccessibility.onDetachedFromWindow(); @@ -792,7 +748,7 @@ public void onWindowFocusChanged(boolean hasWindowFocus) { mImeAdapter.onWindowFocusChanged(hasWindowFocus); if (!hasWindowFocus) resetGestureDetection(); - mSelectionPopupController.onWindowFocusChanged(hasWindowFocus); + if (isAlive()) getSelectionPopupController().onWindowFocusChanged(hasWindowFocus); mGestureListenerManager.updateOnWindowFocusChanged(hasWindowFocus); } @@ -802,7 +758,8 @@ mHasViewFocus = gainFocus; mImeAdapter.onViewFocusChanged(gainFocus, hideKeyboardOnBlur); - mJoystickScrollEnabled = gainFocus && !isFocusedNodeEditable(); + mJoystickScrollEnabled = + gainFocus && !getSelectionPopupController().isFocusedNodeEditable(); if (gainFocus) { restoreSelectionPopupsIfNecessary(); @@ -816,7 +773,7 @@ // Clear the selection. The selection is cleared on destroying IME // and also here since we may receive destroy first, for example // when focus is lost in webview. - clearSelection(); + if (isAlive()) getSelectionPopupController().clearSelection(); } } if (mNativeContentViewCore != 0) nativeSetFocus(mNativeContentViewCore, gainFocus); @@ -1027,20 +984,6 @@ } @Override - public ActionModeCallbackHelper getActionModeCallbackHelper() { - return mSelectionPopupController; - } - - private void showSelectActionMode() { - mSelectionPopupController.showActionModeOrClearOnFailure(); - } - - @Override - public void clearSelection() { - mSelectionPopupController.clearSelection(); - } - - @Override public void preserveSelectionOnNextLossOfFocus() { mPreserveSelectionOnNextLossOfFocus = true; } @@ -1106,7 +1049,7 @@ @Override public void onNodeAttributeUpdated(boolean editable, boolean password) { mJoystickScrollEnabled = !editable; - mSelectionPopupController.updateSelectionState(editable, password); + getSelectionPopupController().updateSelectionState(editable, password); } @Override @@ -1182,7 +1125,7 @@ } private void destroyPastePopup() { - mSelectionPopupController.destroyPastePopup(); + getSelectionPopupController().destroyPastePopup(); } @SuppressWarnings("unused") @@ -1332,11 +1275,6 @@ } @Override - public void onReceivedProcessTextResult(int resultCode, Intent data) { - mSelectionPopupController.onReceivedProcessTextResult(resultCode, data); - } - - @Override public boolean isTouchExplorationEnabled() { return mTouchExplorationEnabled; } @@ -1412,9 +1350,9 @@ // action mode menu items according to the new rotation. So Chrome // has to re-create the action mode. if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M - && mSelectionPopupController.isActionModeValid()) { + && getSelectionPopupController().isActionModeValid()) { hidePopupsAndPreserveSelection(); - showSelectActionMode(); + getSelectionPopupController().showActionModeOrClearOnFailure(); } mTextSuggestionHost.hidePopups(); @@ -1460,32 +1398,6 @@ return mFullscreenRequiredForOrientationLock; } - @Override - public void setSelectionClient(SelectionClient selectionClient) { - mSelectionPopupController.setSelectionClient(selectionClient); - } - - @Override - public void setTextClassifier(TextClassifier textClassifier) { - assert Build.VERSION.SDK_INT >= Build.VERSION_CODES.O; - SelectionClient client = mSelectionPopupController.getSelectionClient(); - if (client != null) client.setTextClassifier(textClassifier); - } - - @Override - public TextClassifier getTextClassifier() { - assert Build.VERSION.SDK_INT >= Build.VERSION_CODES.O; - SelectionClient client = mSelectionPopupController.getSelectionClient(); - return client == null ? null : client.getTextClassifier(); - } - - @Override - public TextClassifier getCustomTextClassifier() { - assert Build.VERSION.SDK_INT >= Build.VERSION_CODES.O; - SelectionClient client = mSelectionPopupController.getSelectionClient(); - return client == null ? null : client.getCustomTextClassifier(); - } - @NativeClassQualifiedName("ContentViewCore") private native long nativeInit(WebContents webContents, ViewAndroidDelegate viewAndroidDelegate, long windowAndroidPtr, float dipScale);
diff --git a/content/public/android/java/src/org/chromium/content/browser/SelectionPopupController.java b/content/public/android/java/src/org/chromium/content/browser/SelectionPopupControllerImpl.java similarity index 88% rename from content/public/android/java/src/org/chromium/content/browser/SelectionPopupController.java rename to content/public/android/java/src/org/chromium/content/browser/SelectionPopupControllerImpl.java index e8d32a8..d688604 100644 --- a/content/public/android/java/src/org/chromium/content/browser/SelectionPopupController.java +++ b/content/public/android/java/src/org/chromium/content/browser/SelectionPopupControllerImpl.java
@@ -31,6 +31,7 @@ import android.view.View; import android.view.ViewConfiguration; import android.view.WindowManager; +import android.view.textclassifier.TextClassifier; import org.chromium.base.ApiCompatibilityUtils; import org.chromium.base.Log; @@ -45,8 +46,11 @@ import org.chromium.content.browser.input.PastePopupMenu; import org.chromium.content.browser.input.PastePopupMenu.PastePopupMenuDelegate; 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.ActionModeCallbackHelper; import org.chromium.content_public.browser.SelectionClient; +import org.chromium.content_public.browser.SelectionPopupController; import org.chromium.content_public.browser.WebContents; import org.chromium.ui.base.DeviceFormFactor; import org.chromium.ui.base.MenuSourceType; @@ -56,17 +60,12 @@ import java.util.List; /** - * A class that handles input-related web content selection UI like action mode - * and paste popup view. It wraps an {@link ActionMode} created by the associated view, - * providing modified interaction with it. - * - * Embedders can use {@link ActionModeCallbackHelper} implemented by this class - * to create {@link ActionMode.Callback} instance and configure the selection action - * mode tasks to their requirements. + * Implementation of the interface {@link SelectionPopupController}. */ @JNINamespace("content") @TargetApi(Build.VERSION_CODES.M) -public class SelectionPopupController extends ActionModeCallbackHelper { +public class SelectionPopupControllerImpl + extends ActionModeCallbackHelper implements SelectionPopupController { private static final String TAG = "SelectionPopupCtlr"; // 20 char limit /** @@ -91,9 +90,14 @@ // does not require ordering information. private static final int MENU_ITEM_ORDER_TEXT_PROCESS_START = 100; - private final Context mContext; - private final WindowAndroid mWindowAndroid; - private final WebContentsImpl mWebContents; + private static final class UserDataFactoryLazyHolder { + private static final UserDataFactory<SelectionPopupControllerImpl> INSTANCE = + SelectionPopupControllerImpl::new; + } + + private Context mContext; + private WindowAndroid mWindowAndroid; + private WebContentsImpl mWebContents; private ActionMode.Callback mCallback; private SelectionClient.ResultCallback mResultCallback; @@ -106,7 +110,7 @@ // Self-repeating task that repeatedly hides the ActionMode. This is // required because ActionMode only exposes a temporary hide routine. - private final Runnable mRepeatingHideRunnable; + private Runnable mRepeatingHideRunnable; private View mView; private ActionMode mActionMode; @@ -151,6 +155,8 @@ // Whether a scroll is in progress. private boolean mScrollInProgress; + private boolean mInitialized; + /** * The {@link SelectionInsertionHandleObserver} that processes handle events, or {@code null} if * none exists. @@ -166,30 +172,58 @@ * @param webContents WebContents instance. * @param view Container view. */ - public SelectionPopupController( + public static SelectionPopupControllerImpl create( Context context, WindowAndroid window, WebContents webContents, View view) { - this(context, window, webContents, view, /* initializeNative = */ true); + SelectionPopupControllerImpl controller = WebContentsUserData.fromWebContents(webContents, + SelectionPopupControllerImpl.class, UserDataFactoryLazyHolder.INSTANCE); + assert controller != null && !controller.initialized(); + controller.init(context, window, view, true); + return controller; + } + + /** + * Get {@link SelectionPopupController} object used for the give WebContents. + * {@link #create()} should precede any calls to this. + * @param webContents {@link WebContents} object. + * @return {@link SelectionPopupController} object. {@code null} if not available because + * {@link #create()} is not called yet. + */ + public static SelectionPopupControllerImpl fromWebContents(WebContents webContents) { + return WebContentsUserData.fromWebContents( + webContents, SelectionPopupControllerImpl.class, null); } /** * Create {@link SelectionPopupController} instance. Note that it will create an instance with - * no link to native side. + * no link to native side for testing only. * @param context Context for action mode. * @param window WindowAndroid instance. * @param webContents WebContents instance. * @param view Container view. */ - public static SelectionPopupController createForTesting( + public static SelectionPopupControllerImpl createForTesting( Context context, WindowAndroid window, WebContents webContents, View view) { - return new SelectionPopupController( - context, window, webContents, view, /* initializeNative = */ false); + SelectionPopupControllerImpl controller = new SelectionPopupControllerImpl(webContents); + controller.init(context, window, view, false); + return controller; } - private SelectionPopupController(Context context, WindowAndroid window, WebContents webContents, - View view, boolean initializeNative) { + /** + * Create {@link SelectionPopupControllerImpl} instance. + * @param webContents WebContents instance. + */ + public SelectionPopupControllerImpl(WebContents webContents) { + mWebContents = (WebContentsImpl) webContents; + } + + /** + * @param context Context for action mode. + * @param window WindowAndroid instance. + * @param view Container view. + */ + private void init(Context context, WindowAndroid window, View view, boolean initializeNative) { mContext = context; mWindowAndroid = window; - mWebContents = (WebContentsImpl) webContents; mView = view; // The menu items are allowed by default. @@ -212,7 +246,19 @@ mHandleObserver = ContentClassFactory.get().createHandleObserver(view); mDragStarted = false; - if (initializeNative) nativeInit(webContents); + if (initializeNative) nativeInit(mWebContents); + + mInitialized = true; + } + + private boolean initialized() { + return mInitialized; + } + + public static String sanitizeQuery(String query, int maxLength) { + if (TextUtils.isEmpty(query) || query.length() < maxLength) return query; + Log.w(TAG, "Truncating oversized query (" + query.length() + ")."); + return query.substring(0, maxLength) + "…"; } /** @@ -229,18 +275,17 @@ mView = view; } - /** - * Set the action mode callback. - * @param callback ActionMode.Callback handling the callbacks from action mode. - */ - void setCallback(ActionMode.Callback callback) { + @Override + public void setActionModeCallback(ActionMode.Callback callback) { mCallback = callback; } - void setNonSelectionCallback(ActionMode.Callback callback) { + @Override + public void setNonSelectionActionModeCallback(ActionMode.Callback callback) { mNonSelectionCallback = callback; } + @Override public SelectionClient.ResultCallback getResultCallback() { return mResultCallback; } @@ -360,9 +405,8 @@ destroyActionModeAndKeepSelection(); assert mWebContents != null; - ActionMode actionMode = supportsFloatingActionMode() - ? startFloatingActionMode() - : mView.startActionMode(mCallback); + ActionMode actionMode = supportsFloatingActionMode() ? startFloatingActionMode() + : mView.startActionMode(mCallback); if (actionMode != null) { // This is to work around an LGE email issue. See crbug.com/651706 for more details. LGEmailActionModeWorkaround.runIfNecessary(mContext, actionMode); @@ -390,34 +434,34 @@ PastePopupMenuDelegate delegate = new PastePopupMenuDelegate() { @Override public void paste() { - SelectionPopupController.this.paste(); + SelectionPopupControllerImpl.this.paste(); mWebContents.dismissTextHandles(); } @Override public void pasteAsPlainText() { - SelectionPopupController.this.pasteAsPlainText(); + SelectionPopupControllerImpl.this.pasteAsPlainText(); mWebContents.dismissTextHandles(); } @Override public boolean canPaste() { - return SelectionPopupController.this.canPaste(); + return SelectionPopupControllerImpl.this.canPaste(); } @Override public void selectAll() { - SelectionPopupController.this.selectAll(); + SelectionPopupControllerImpl.this.selectAll(); } @Override public boolean canSelectAll() { - return SelectionPopupController.this.canSelectAll(); + return SelectionPopupControllerImpl.this.canSelectAll(); } @Override public boolean canPasteAsPlainText() { - return SelectionPopupController.this.canPasteAsPlainText(); + return SelectionPopupControllerImpl.this.canPasteAsPlainText(); } }; Context windowContext = mWindowAndroid.getContext().get(); @@ -530,8 +574,7 @@ } private boolean isFloatingActionMode() { - return supportsFloatingActionMode() - && isActionModeValid() + return supportsFloatingActionMode() && isActionModeValid() && mActionMode.getType() == ActionMode.TYPE_FLOATING; } @@ -605,7 +648,7 @@ updateAssistMenuItem(descriptor); - if (!isSelectionEditable() || !canPaste()) { + if (!isFocusedNodeEditable() || !canPaste()) { descriptor.removeItem(R.id.select_action_menu_paste); descriptor.removeItem(R.id.select_action_menu_paste_as_plain_text); } @@ -623,15 +666,15 @@ return descriptor; } - if (!isSelectionEditable()) { + if (!isFocusedNodeEditable()) { descriptor.removeItem(R.id.select_action_menu_cut); } - if (isSelectionEditable() || !isSelectActionModeAllowed(MENU_ITEM_SHARE)) { + if (isFocusedNodeEditable() || !isSelectActionModeAllowed(MENU_ITEM_SHARE)) { descriptor.removeItem(R.id.select_action_menu_share); } - if (isSelectionEditable() || isIncognito() + if (isFocusedNodeEditable() || isIncognito() || !isSelectActionModeAllowed(MENU_ITEM_WEB_SEARCH)) { descriptor.removeItem(R.id.select_action_menu_web_search); } @@ -649,8 +692,8 @@ } private boolean canPaste() { - ClipboardManager clipMgr = (ClipboardManager) - mContext.getSystemService(Context.CLIPBOARD_SERVICE); + ClipboardManager clipMgr = + (ClipboardManager) mContext.getSystemService(Context.CLIPBOARD_SERVICE); return clipMgr.hasPrimaryClip(); } @@ -721,7 +764,7 @@ ResolveInfo resolveInfo = supportedActivities.get(i); CharSequence label = resolveInfo.loadLabel(mContext.getPackageManager()); menu.add(R.id.select_action_menu_text_processing_menus, Menu.NONE, - MENU_ITEM_ORDER_TEXT_PROCESS_START + i, label) + MENU_ITEM_ORDER_TEXT_PROCESS_START + i, label) .setIntent(createProcessTextIntentForResolveInfo(resolveInfo)) .setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM); } @@ -734,7 +777,7 @@ @TargetApi(Build.VERSION_CODES.M) private Intent createProcessTextIntentForResolveInfo(ResolveInfo info) { - boolean isReadOnly = !isSelectionEditable(); + boolean isReadOnly = !isFocusedNodeEditable(); return createProcessTextIntent() .putExtra(Intent.EXTRA_PROCESS_TEXT_READONLY, isReadOnly) .setClassName(info.activityInfo.packageName, info.activityInfo.name); @@ -885,7 +928,7 @@ mClassificationResult = null; // Even though the above statement logged a SelectAll user action, we want to // track whether the focus was in an editable field, so log that too. - if (isSelectionEditable()) { + if (isFocusedNodeEditable()) { RecordUserAction.record("MobileActionMode.SelectAllWasEditable"); } else { RecordUserAction.record("MobileActionMode.SelectAllWasNonEditable"); @@ -999,10 +1042,8 @@ return mIsPasswordType; } - /** - * @return true iff the current selection is editable (e.g. text within an input field). - */ - boolean isSelectionEditable() { + @Override + public boolean isFocusedNodeEditable() { return mEditable; } @@ -1031,15 +1072,6 @@ } /** - * @see ActionModeCallbackHelper#sanitizeQuery(String, int) - */ - public static String sanitizeQuery(String query, int maxLength) { - if (TextUtils.isEmpty(query) || query.length() < maxLength) return query; - Log.w(TAG, "Truncating oversized query (" + query.length() + ")."); - return query.substring(0, maxLength) + "…"; - } - - /** * @param actionModeItem the flag for the action mode item in question. The valid flags are * {@link #MENU_ITEM_SHARE}, {@link #MENU_ITEM_WEB_SEARCH}, and * {@link #MENU_ITEM_PROCESS_TEXT}. @@ -1059,7 +1091,7 @@ if (mWebContents == null || resultCode != Activity.RESULT_OK || data == null) return; // Do not handle the result if no text is selected or current selection is not editable. - if (!hasSelection() || !isSelectionEditable()) return; + if (!hasSelection() || !isFocusedNodeEditable()) return; CharSequence result = data.getCharSequenceExtra(Intent.EXTRA_PROCESS_TEXT); if (result != null) { @@ -1194,11 +1226,8 @@ } } - /** - * Clears the current text selection. Note that we will try to move cursor to selection - * end if applicable. - */ - void clearSelection() { + @Override + public void clearSelection() { if (mWebContents == null || !isActionModeSupported()) return; mWebContents.collapseSelection(); mClassificationResult = null; @@ -1228,8 +1257,8 @@ /** * Sets the client that implements selection augmenting functionality, or null if none exists. */ - @VisibleForTesting - void setSelectionClient(@Nullable SelectionClient selectionClient) { + @Override + public void setSelectionClient(@Nullable SelectionClient selectionClient) { mSelectionClient = selectionClient; if (mSelectionClient != null) { mSelectionMetricsLogger = @@ -1277,17 +1306,14 @@ void updateSelectionState(boolean editable, boolean isPassword) { if (!editable) destroyPastePopup(); - if (editable != isSelectionEditable() || isPassword != isSelectionPassword()) { + if (editable != isFocusedNodeEditable() || isPassword != isSelectionPassword()) { mEditable = editable; mIsPasswordType = isPassword; if (isActionModeValid()) mActionMode.invalidate(); } } - /** - * @return Whether the page has an active, touch-controlled selection region. - */ - @VisibleForTesting + @Override public boolean hasSelection() { return mHasSelection; } @@ -1300,8 +1326,10 @@ private boolean isShareAvailable() { Intent intent = new Intent(Intent.ACTION_SEND); intent.setType("text/plain"); - return mContext.getPackageManager().queryIntentActivities(intent, - PackageManager.MATCH_DEFAULT_ONLY).size() > 0; + return mContext.getPackageManager() + .queryIntentActivities(intent, PackageManager.MATCH_DEFAULT_ONLY) + .size() + > 0; } // The callback class that delivers the result from a SmartSelectionClient. @@ -1350,5 +1378,41 @@ } }; + @Override + public void destroySelectActionMode() { + finishActionMode(); + } + + @Override + public boolean isSelectActionBarShowing() { + return isActionModeValid(); + } + + @Override + public ActionModeCallbackHelper getActionModeCallbackHelper() { + return this; + } + + @Override + public void setTextClassifier(TextClassifier textClassifier) { + assert Build.VERSION.SDK_INT >= Build.VERSION_CODES.O; + SelectionClient client = getSelectionClient(); + if (client != null) client.setTextClassifier(textClassifier); + } + + @Override + public TextClassifier getTextClassifier() { + assert Build.VERSION.SDK_INT >= Build.VERSION_CODES.O; + SelectionClient client = getSelectionClient(); + return client == null ? null : client.getTextClassifier(); + } + + @Override + public TextClassifier getCustomTextClassifier() { + assert Build.VERSION.SDK_INT >= Build.VERSION_CODES.O; + SelectionClient client = getSelectionClient(); + return client == null ? null : client.getCustomTextClassifier(); + } + private native void nativeInit(WebContents webContents); }
diff --git a/content/public/android/java/src/org/chromium/content/browser/input/FloatingPastePopupMenu.java b/content/public/android/java/src/org/chromium/content/browser/input/FloatingPastePopupMenu.java index 0dcd631..b9f8d3f 100644 --- a/content/public/android/java/src/org/chromium/content/browser/input/FloatingPastePopupMenu.java +++ b/content/public/android/java/src/org/chromium/content/browser/input/FloatingPastePopupMenu.java
@@ -14,7 +14,7 @@ import android.view.View; import org.chromium.content.R; -import org.chromium.content.browser.SelectionPopupController; +import org.chromium.content.browser.SelectionPopupControllerImpl; import org.chromium.ui.base.DeviceFormFactor; /** @@ -86,14 +86,14 @@ ? mContext.getString(R.string.actionbar_textselection_title) : null); mode.setSubtitle(null); - SelectionPopupController.initializeMenu(mContext, mode, menu); + SelectionPopupControllerImpl.initializeMenu(mContext, mode, menu); if (!mDelegate.canPaste()) menu.removeItem(R.id.select_action_menu_paste); if (!mDelegate.canSelectAll()) menu.removeItem(R.id.select_action_menu_select_all); if (!mDelegate.canPasteAsPlainText()) { menu.removeItem(R.id.select_action_menu_paste_as_plain_text); } - SelectionPopupController.setPasteAsPlainTextMenuItemTitle(menu); + SelectionPopupControllerImpl.setPasteAsPlainTextMenuItemTitle(menu); menu.removeItem(R.id.select_action_menu_cut); menu.removeItem(R.id.select_action_menu_copy);
diff --git a/content/public/android/java/src/org/chromium/content/browser/webcontents/WebContentsUserData.java b/content/public/android/java/src/org/chromium/content/browser/webcontents/WebContentsUserData.java index fa5d451..af95887 100644 --- a/content/public/android/java/src/org/chromium/content/browser/webcontents/WebContentsUserData.java +++ b/content/public/android/java/src/org/chromium/content/browser/webcontents/WebContentsUserData.java
@@ -55,11 +55,12 @@ } /** - * Looks up the generic object of the given web contents. If not present, create one. + * Looks up the generic object of the given web contents. * * @param webContents The web contents for which to lookup the object. * @param key Class instance of the object used as the key. - * @param userDataFactory Factory that creates an object of the generic class. + * @param userDataFactory Factory that creates an object of the generic class. Create a new + * instance if the object is not available and the factory is non-null. * @return The object (possibly null) of the given web contents. */ @SuppressWarnings("unchecked") @@ -73,7 +74,7 @@ if (userDataMap == null) return null; WebContentsUserData data = userDataMap.get(key); - if (data == null) { + if (data == null && userDataFactory != null) { T object = userDataFactory.create(webContents); assert object.getClass() == key; webContentsImpl.setUserData(key, new WebContentsUserData(object));
diff --git a/content/public/android/java/src/org/chromium/content_public/browser/ActionModeCallbackHelper.java b/content/public/android/java/src/org/chromium/content_public/browser/ActionModeCallbackHelper.java index 8f06e68..384f7d3 100644 --- a/content/public/android/java/src/org/chromium/content_public/browser/ActionModeCallbackHelper.java +++ b/content/public/android/java/src/org/chromium/content_public/browser/ActionModeCallbackHelper.java
@@ -12,7 +12,7 @@ import android.view.View; import android.webkit.WebSettings; -import org.chromium.content.browser.SelectionPopupController; +import org.chromium.content.browser.SelectionPopupControllerImpl; /** * Helper class for {@link WebActionMode} encapsulating @@ -20,6 +20,7 @@ * for embedder to provide with the callback instance that interacts with it. */ public abstract class ActionModeCallbackHelper { + private static final String TAG = "ActionModeHelper"; /** Google search doesn't support requests slightly larger than this. */ public static final int MAX_SEARCH_QUERY_LENGTH = 1000; @@ -37,7 +38,7 @@ * @param maxLength maximum length to which the query will be truncated. */ public static String sanitizeQuery(String query, int maxLength) { - return SelectionPopupController.sanitizeQuery(query, maxLength); + return SelectionPopupControllerImpl.sanitizeQuery(query, maxLength); } /**
diff --git a/content/public/android/java/src/org/chromium/content_public/browser/SelectionClient.java b/content/public/android/java/src/org/chromium/content_public/browser/SelectionClient.java index b1cc65ac..0ba274ce 100644 --- a/content/public/android/java/src/org/chromium/content_public/browser/SelectionClient.java +++ b/content/public/android/java/src/org/chromium/content_public/browser/SelectionClient.java
@@ -11,7 +11,6 @@ import android.view.textclassifier.TextClassifier; import android.view.textclassifier.TextSelection; -import org.chromium.content.browser.ContentViewCore; import org.chromium.content.browser.SmartSelectionClient; /** @@ -165,7 +164,7 @@ /** Creates a {@link SelectionClient} instance. */ public static SelectionClient createSmartSelectionClient(WebContents webContents) { SelectionClient.ResultCallback callback = - ContentViewCore.fromWebContents(webContents).getPopupControllerResultCallback(); + SelectionPopupController.fromWebContents(webContents).getResultCallback(); return SmartSelectionClient.create(callback, webContents); } }
diff --git a/content/public/android/java/src/org/chromium/content_public/browser/SelectionPopupController.java b/content/public/android/java/src/org/chromium/content_public/browser/SelectionPopupController.java new file mode 100644 index 0000000..77cb0ee3 --- /dev/null +++ b/content/public/android/java/src/org/chromium/content_public/browser/SelectionPopupController.java
@@ -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. + +package org.chromium.content_public.browser; + +import android.content.Context; +import android.content.Intent; +import android.view.ActionMode; +import android.view.View; +import android.view.textclassifier.TextClassifier; + +import org.chromium.content.browser.SelectionPopupControllerImpl; +import org.chromium.ui.base.WindowAndroid; + +/** + * An interface that handles input-related web content selection UI like action mode + * and paste popup view. It wraps an {@link ActionMode} created by the associated view, + * providing modified interaction with it. + * + * Embedders can use {@link ActionModeCallbackHelper} provided by the implementation of + * this interface to create {@link ActionMode.Callback} instance and configure the selection + * action mode tasks to their requirements. + */ +public interface SelectionPopupController { + /** + * @param webContents {@link WebContents} object. + * @return {@link SelectionPopupController} object used for the give WebContents. + * {@code null} if not available. + */ + static SelectionPopupController fromWebContents(WebContents webContents) { + return SelectionPopupControllerImpl.fromWebContents(webContents); + } + + /** + * Set {@link ActionMode.Callback} used by {@link SelectionPopupController}. + * @param callback ActionMode.Callback instance. + */ + void setActionModeCallback(ActionMode.Callback callback); + + /** + * Set {@link ActionMode.Callback} used by {@link SelectionPopupController} when no text is + * selected. + * @param callback ActionMode.Callback instance. + */ + void setNonSelectionActionModeCallback(ActionMode.Callback callback); + + /** + * @return {@link SelectionClient.ResultCallback} instance. + */ + SelectionClient.ResultCallback getResultCallback(); + + /** + * @return The selected text (empty if no text selected). + */ + String getSelectedText(); + + /** + * @return Whether the current focused node is editable. + */ + boolean isFocusedNodeEditable(); + + /** + * @return Whether the page has an active, touch-controlled selection region. + */ + boolean hasSelection(); + + /** + * Hide action mode and put into destroyed state. + */ + void destroySelectActionMode(); + + boolean isSelectActionBarShowing(); + + /** + * @return {@link ActionModeCallbackHelper} object. + */ + ActionModeCallbackHelper getActionModeCallbackHelper(); + + /** + * Clears the current text selection. Note that we will try to move cursor to selection + * end if applicable. + */ + void clearSelection(); + + /** + * Called when the processed text is replied from an activity that supports + * Intent.ACTION_PROCESS_TEXT. + * @param resultCode the code that indicates if the activity successfully processed the text + * @param data the reply that contains the processed text. + */ + void onReceivedProcessTextResult(int resultCode, Intent data); + + /** Sets the given {@link SelectionClient} in the selection popup controller. */ + void setSelectionClient(SelectionClient selectionClient); + + /** + * Sets TextClassifier for Smart Text selection. + */ + void setTextClassifier(TextClassifier textClassifier); + + /** + * Returns TextClassifier that is used for Smart Text selection. If the custom classifier + * has been set with setTextClassifier, returns that object, otherwise returns the system + * classifier. + */ + TextClassifier getTextClassifier(); + + /** + * Returns the TextClassifier which has been set with setTextClassifier(), or null. + */ + TextClassifier getCustomTextClassifier(); + + /** + * Create and initialize a new instance for testing. + * + * @param webContents {@link WebContents} object. + * @return {@link SelectionPopupController} object used for the give WebContents. + * Creates one if not present. + */ + static SelectionPopupController createForTesting( + Context context, WindowAndroid window, WebContents webContents, View view) { + return SelectionPopupControllerImpl.createForTesting(context, window, webContents, view); + } +}
diff --git a/content/public/android/javatests/src/org/chromium/content/browser/ContentViewCoreSelectionTest.java b/content/public/android/javatests/src/org/chromium/content/browser/ContentViewCoreSelectionTest.java index 8b7a58a..8325763 100644 --- a/content/public/android/javatests/src/org/chromium/content/browser/ContentViewCoreSelectionTest.java +++ b/content/public/android/javatests/src/org/chromium/content/browser/ContentViewCoreSelectionTest.java
@@ -58,7 +58,7 @@ + "<div id=\"rich_div\" contentEditable=\"true\" >Rich Editor</div>" + "</form></body></html>"); private ContentViewCore mContentViewCore; - private SelectionPopupController mSelectionPopupController; + private SelectionPopupControllerImpl mSelectionPopupController; private static class TestSelectionClient implements SelectionClient { private SelectionClient.Result mResult; @@ -107,7 +107,8 @@ mActivityTestRule.waitForActiveShellToBeDoneLoading(); mContentViewCore = mActivityTestRule.getContentViewCore(); - mSelectionPopupController = mContentViewCore.getSelectionPopupControllerForTesting(); + mSelectionPopupController = + SelectionPopupControllerImpl.fromWebContents(mContentViewCore.getWebContents()); waitForSelectActionBarVisible(false); waitForPastePopupStatus(false); } @@ -415,7 +416,7 @@ waitForSelectActionBarVisible(true); Assert.assertTrue(mSelectionPopupController.hasSelection()); Assert.assertTrue(mSelectionPopupController.isActionModeValid()); - Assert.assertTrue(mSelectionPopupController.isSelectionEditable()); + Assert.assertTrue(mSelectionPopupController.isFocusedNodeEditable()); Assert.assertFalse(mSelectionPopupController.isSelectionPassword()); } @@ -427,7 +428,7 @@ waitForSelectActionBarVisible(true); Assert.assertTrue(mSelectionPopupController.hasSelection()); Assert.assertTrue(mSelectionPopupController.isActionModeValid()); - Assert.assertTrue(mSelectionPopupController.isSelectionEditable()); + Assert.assertTrue(mSelectionPopupController.isFocusedNodeEditable()); Assert.assertTrue(mSelectionPopupController.isSelectionPassword()); } @@ -439,7 +440,7 @@ waitForSelectActionBarVisible(true); Assert.assertTrue(mSelectionPopupController.hasSelection()); Assert.assertTrue(mSelectionPopupController.isActionModeValid()); - Assert.assertFalse(mSelectionPopupController.isSelectionEditable()); + Assert.assertFalse(mSelectionPopupController.isFocusedNodeEditable()); Assert.assertFalse(mSelectionPopupController.isSelectionPassword()); } @@ -451,7 +452,7 @@ waitForSelectActionBarVisible(true); Assert.assertTrue(mSelectionPopupController.hasSelection()); Assert.assertTrue(mSelectionPopupController.isActionModeValid()); - Assert.assertTrue(mSelectionPopupController.isSelectionEditable()); + Assert.assertTrue(mSelectionPopupController.isFocusedNodeEditable()); Assert.assertFalse(mSelectionPopupController.isSelectionPassword()); } @@ -830,7 +831,7 @@ ThreadUtils.runOnUiThreadBlocking(new Runnable() { @Override public void run() { - mContentViewCore.destroySelectActionMode(); + mSelectionPopupController.destroySelectActionMode(); } }); } @@ -852,7 +853,7 @@ CriteriaHelper.pollUiThread(Criteria.equals(visible, new Callable<Boolean>() { @Override public Boolean call() { - return mContentViewCore.isSelectActionBarShowing(); + return mSelectionPopupController.isSelectActionBarShowing(); } })); }
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 c4e0d8a..00f6834 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
@@ -27,6 +27,7 @@ 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.WebContents; import org.chromium.content_shell_apk.ContentShellActivityTestRule; @@ -103,8 +104,7 @@ Context context = mActivityTestRule.getActivity(); WebContents webContents = mActivityTestRule.getContentViewCore().getWebContents(); mContentViewCore = (ContentViewCoreImpl) ContentViewCore.create(context, ""); - mContentViewCore.setSelectionPopupControllerForTesting( - new SelectionPopupController(context, null, webContents, null)); + mContentViewCore.setWebContentsForTesting((WebContentsImpl) webContents); ViewGroup containerView = mActivityTestRule.getContentViewCore().getContainerView(); mContentViewCore.setImeAdapterForTest(new ImeAdapter(webContents, containerView, new TestInputMethodManagerWrapper(mContentViewCore)));
diff --git a/content/public/android/javatests/src/org/chromium/content/browser/input/ImeActivityTestRule.java b/content/public/android/javatests/src/org/chromium/content/browser/input/ImeActivityTestRule.java index d495884..f2e9472 100644 --- a/content/public/android/javatests/src/org/chromium/content/browser/input/ImeActivityTestRule.java +++ b/content/public/android/javatests/src/org/chromium/content/browser/input/ImeActivityTestRule.java
@@ -21,7 +21,7 @@ import org.chromium.base.ThreadUtils; import org.chromium.content.browser.ContentViewCore; -import org.chromium.content.browser.SelectionPopupController; +import org.chromium.content.browser.SelectionPopupControllerImpl; import org.chromium.content.browser.test.util.Criteria; import org.chromium.content.browser.test.util.CriteriaHelper; import org.chromium.content.browser.test.util.DOMUtils; @@ -51,14 +51,15 @@ static final String PASSWORD_FORM_HTML = "content/test/data/android/input/password_form.html"; private ContentViewCore mContentViewCore; - private SelectionPopupController mSelectionPopupController; + private SelectionPopupControllerImpl mSelectionPopupController; private TestCallbackHelperContainer mCallbackContainer; private TestInputMethodManagerWrapper mInputMethodManagerWrapper; public void setUpForUrl(String url) throws Exception { launchContentShellWithUrlSync(url); mContentViewCore = getContentViewCore(); - mSelectionPopupController = mContentViewCore.getSelectionPopupControllerForTesting(); + mSelectionPopupController = + SelectionPopupControllerImpl.fromWebContents(mContentViewCore.getWebContents()); mInputMethodManagerWrapper = new TestInputMethodManagerWrapper(mContentViewCore) { private boolean mExpectsSelectionOutsideComposition; @@ -119,7 +120,7 @@ resetAllStates(); } - SelectionPopupController getSelectionPopupController() { + SelectionPopupControllerImpl getSelectionPopupController() { return mSelectionPopupController; } @@ -246,7 +247,7 @@ CriteriaHelper.pollUiThread(Criteria.equals(show, new Callable<Boolean>() { @Override public Boolean call() { - return mContentViewCore.isSelectActionBarShowing(); + return mSelectionPopupController.isSelectActionBarShowing(); } })); }
diff --git a/content/public/android/junit/src/org/chromium/content/browser/SelectionPopupControllerTest.java b/content/public/android/junit/src/org/chromium/content/browser/SelectionPopupControllerTest.java index 284cfb5..25d5ac0 100644 --- a/content/public/android/junit/src/org/chromium/content/browser/SelectionPopupControllerTest.java +++ b/content/public/android/junit/src/org/chromium/content/browser/SelectionPopupControllerTest.java
@@ -39,6 +39,7 @@ import org.chromium.content.browser.webcontents.WebContentsImpl; import org.chromium.content_public.browser.SelectionClient; import org.chromium.content_public.browser.SelectionMetricsLogger; +import org.chromium.content_public.browser.SelectionPopupController; import org.chromium.testing.local.LocalRobolectricTestRunner; import org.chromium.ui.base.MenuSourceType; import org.chromium.ui.base.WindowAndroid; @@ -50,7 +51,7 @@ @RunWith(LocalRobolectricTestRunner.class) @Config(manifest = Config.NONE) public class SelectionPopupControllerTest { - private SelectionPopupController mController; + private SelectionPopupControllerImpl mController; private Context mContext; private WindowAndroid mWindowAndroid; private WebContentsImpl mWebContents; @@ -140,7 +141,7 @@ when(mWebContents.getRenderCoordinates()).thenReturn(mRenderCoordinates); when(mRenderCoordinates.getDeviceScaleFactor()).thenReturn(1.f); - mController = SelectionPopupController.createForTesting( + mController = SelectionPopupControllerImpl.createForTesting( mContext, mWindowAndroid, mWebContents, mView); }
diff --git a/content/public/browser/android/compositor.h b/content/public/browser/android/compositor.h index e454121..78322158 100644 --- a/content/public/browser/android/compositor.h +++ b/content/public/browser/android/compositor.h
@@ -59,15 +59,14 @@ static Compositor* Create(CompositorClient* client, gfx::NativeWindow root_window); + virtual void SetRootWindow(gfx::NativeWindow root_window) = 0; + // Attaches the layer tree. virtual void SetRootLayer(scoped_refptr<cc::Layer> root) = 0; // Set the output surface bounds. virtual void SetWindowBounds(const gfx::Size& size) = 0; - // Defer commits on the layer tree host. - virtual void SetDeferCommits(bool defer_commits) = 0; - // Set the output surface which the compositor renders into. virtual void SetSurface(jobject surface) = 0;
diff --git a/content/public/common/BUILD.gn b/content/public/common/BUILD.gn index b9bcb47..dc155b0 100644 --- a/content/public/common/BUILD.gn +++ b/content/public/common/BUILD.gn
@@ -206,6 +206,8 @@ "resource_request.h", "resource_request_body.cc", "resource_request_body.h", + "resource_request_body_android.cc", + "resource_request_body_android.h", "resource_response.cc", "resource_response.h", "resource_response_info.cc", @@ -307,6 +309,10 @@ deps += [ "//ui/aura" ] } + if (is_android) { + deps += [ "//content/public/android:jni" ] + } + # //content/common needs to include public headers. allow_circular_includes_from = [ ":interfaces",
diff --git a/content/public/common/resource_request.cc b/content/public/common/resource_request.cc index 2672e5b..f851f82 100644 --- a/content/public/common/resource_request.cc +++ b/content/public/common/resource_request.cc
@@ -4,13 +4,9 @@ #include "content/public/common/resource_request.h" -#include "content/public/common/appcache_info.h" - namespace content { -// kAppCacheNoHostId can't be used in the header, because appcache_info.h -// includes a webkit file with a Status enum, and X11 #defines Status. -ResourceRequest::ResourceRequest() : appcache_host_id(kAppCacheNoHostId) {} +ResourceRequest::ResourceRequest() {} ResourceRequest::ResourceRequest(const ResourceRequest& request) = default; ResourceRequest::~ResourceRequest() {}
diff --git a/content/public/common/resource_request.h b/content/public/common/resource_request.h index 9cf6bc2..8447139 100644 --- a/content/public/common/resource_request.h +++ b/content/public/common/resource_request.h
@@ -85,7 +85,7 @@ // Indicates which frame (or worker context) the request is being loaded into, // or kAppCacheNoHostId. - int appcache_host_id; + int appcache_host_id = 0; // True if corresponding AppCache group should be resetted. bool should_reset_appcache = false;
diff --git a/content/public/common/resource_request_body.cc b/content/public/common/resource_request_body.cc index 579a652..d649740c 100644 --- a/content/public/common/resource_request_body.cc +++ b/content/public/common/resource_request_body.cc
@@ -4,10 +4,6 @@ #include "content/public/common/resource_request_body.h" -#if defined(OS_ANDROID) -#include "content/common/android/resource_request_body_android.h" -#endif - namespace content { ResourceRequestBody::ResourceRequestBody() @@ -22,21 +18,6 @@ return result; } -#if defined(OS_ANDROID) -base::android::ScopedJavaLocalRef<jobject> ResourceRequestBody::ToJavaObject( - JNIEnv* env) { - return ConvertResourceRequestBodyToJavaObject( - env, static_cast<ResourceRequestBody*>(this)); -} - -// static -scoped_refptr<ResourceRequestBody> ResourceRequestBody::FromJavaObject( - JNIEnv* env, - const base::android::JavaParamRef<jobject>& java_object) { - return ExtractResourceRequestBodyFromJavaObject(env, java_object); -} -#endif - void ResourceRequestBody::AppendBytes(const char* bytes, int bytes_len) { if (bytes_len > 0) { elements_.push_back(Element());
diff --git a/content/public/common/resource_request_body.h b/content/public/common/resource_request_body.h index ad6c7b1..25d32fe4 100644 --- a/content/public/common/resource_request_body.h +++ b/content/public/common/resource_request_body.h
@@ -19,11 +19,6 @@ #include "storage/common/data_element.h" #include "url/gurl.h" -#if defined(OS_ANDROID) -#include <jni.h> -#include "base/android/scoped_java_ref.h" -#endif - namespace content { // ResourceRequestBody represents body (i.e. upload data) of a HTTP request. @@ -38,18 +33,6 @@ static scoped_refptr<ResourceRequestBody> CreateFromBytes(const char* bytes, size_t length); -#if defined(OS_ANDROID) - // Returns a org.chromium.content_public.common.ResourceRequestBody Java - // object that wraps a ref-counted pointer to the |resource_request_body|. - base::android::ScopedJavaLocalRef<jobject> ToJavaObject(JNIEnv* env); - - // Extracts and returns a C++ object out of Java's - // org.chromium.content_public.common.ResourceRequestBody. - static scoped_refptr<ResourceRequestBody> FromJavaObject( - JNIEnv* env, - const base::android::JavaParamRef<jobject>& java_object); -#endif - void AppendBytes(const char* bytes, int bytes_len); void AppendFileRange(const base::FilePath& file_path, uint64_t offset,
diff --git a/content/common/android/resource_request_body_android.cc b/content/public/common/resource_request_body_android.cc similarity index 97% rename from content/common/android/resource_request_body_android.cc rename to content/public/common/resource_request_body_android.cc index ca7d105..a2af9cc 100644 --- a/content/common/android/resource_request_body_android.cc +++ b/content/public/common/resource_request_body_android.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 "content/common/android/resource_request_body_android.h" +#include "content/public/common/resource_request_body_android.h" #include <jni.h>
diff --git a/content/common/android/resource_request_body_android.h b/content/public/common/resource_request_body_android.h similarity index 69% rename from content/common/android/resource_request_body_android.h rename to content/public/common/resource_request_body_android.h index fafd611..79dc95b1 100644 --- a/content/common/android/resource_request_body_android.h +++ b/content/public/common/resource_request_body_android.h
@@ -2,13 +2,14 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#ifndef CONTENT_BROWSER_ANDROID_RESOURCE_REQUEST_BODY_JNI_H_ -#define CONTENT_BROWSER_ANDROID_RESOURCE_REQUEST_BODY_JNI_H_ +#ifndef CONTENT_PUBLIC_COMMON_RESOURCE_REQUEST_BODY_ANDROID_H_ +#define CONTENT_PUBLIC_COMMON_RESOURCE_REQUEST_BODY_ANDROID_H_ #include <jni.h> #include "base/android/scoped_java_ref.h" #include "base/memory/ref_counted.h" +#include "content/common/content_export.h" namespace content { @@ -16,7 +17,7 @@ // Returns an instance of org.chromium.content_public.common.ResourceRequestBody // that contains serialized representation of the |native_object|. -base::android::ScopedJavaLocalRef<jobject> +CONTENT_EXPORT base::android::ScopedJavaLocalRef<jobject> ConvertResourceRequestBodyToJavaObject( JNIEnv* env, const scoped_refptr<ResourceRequestBody>& native_object); @@ -24,10 +25,11 @@ // Reconstructs the native C++ content::ResourceRequestBody object based on // org.chromium.content_public.common.ResourceRequestBody (|java_object|) passed // in as an argument. -scoped_refptr<ResourceRequestBody> ExtractResourceRequestBodyFromJavaObject( +CONTENT_EXPORT scoped_refptr<ResourceRequestBody> +ExtractResourceRequestBodyFromJavaObject( JNIEnv* env, const base::android::JavaParamRef<jobject>& java_object); } // namespace content -#endif // CONTENT_BROWSER_ANDROID_RESOURCE_REQUEST_BODY_JNI_H_ +#endif // CONTENT_PUBLIC_COMMON_RESOURCE_REQUEST_BODY_ANDROID_H_
diff --git a/content/public/common/simple_url_loader.cc b/content/public/common/simple_url_loader.cc index ce4498b..e6813fd 100644 --- a/content/public/common/simple_url_loader.cc +++ b/content/public/common/simple_url_loader.cc
@@ -28,20 +28,25 @@ #include "content/public/common/url_loader.mojom.h" #include "content/public/common/url_loader_factory.mojom.h" #include "mojo/public/cpp/bindings/binding.h" +#include "mojo/public/cpp/bindings/binding_set.h" #include "mojo/public/cpp/system/data_pipe.h" #include "mojo/public/cpp/system/simple_watcher.h" #include "net/base/net_errors.h" #include "net/base/request_priority.h" #include "net/http/http_request_headers.h" #include "net/traffic_annotation/network_traffic_annotation.h" +#include "services/network/public/interfaces/data_pipe_getter.mojom.h" #include "storage/common/data_element.h" namespace content { +const size_t SimpleURLLoader::kMaxBoundedStringDownloadSize = 1024 * 1024; +const size_t SimpleURLLoader::kMaxUploadStringSizeToCopy = 256 * 1024; + namespace { // This file contains SimpleURLLoaderImpl, several BodyHandler implementations, -// and BodyReader. +// BodyReader, and StringUploadDataPipeGetter. // // SimpleURLLoaderImpl implements URLLoaderClient and drives the URLLoader. // @@ -54,6 +59,116 @@ // the BodyPipe. This isn't handled by the SimpleURLLoader as some BodyHandlers // consume data off thread, so having it as a separate class allows the data // pipe to be used off thread, reducing use of the main thread. +// +// StringUploadDataPipeGetter is a class to stream a string upload body to the +// network service, rather than to copy it all at once. + +class StringUploadDataPipeGetter : public network::mojom::DataPipeGetter { + public: + explicit StringUploadDataPipeGetter(const std::string& upload_string) + : upload_string_(upload_string) {} + ~StringUploadDataPipeGetter() override = default; + + // Returns a DataPipeGetterPtr for a new upload attempt, closing all + // previously opened pipes. + network::mojom::DataPipeGetterPtr GetPtrForNewUpload() { + // If this is a retry, need to close all bindings, since only one consumer + // can read from the data pipe at a time. + binding_set_.CloseAllBindings(); + // Not strictly needed, but seems best to close the old body pipe and stop + // any pending reads. + ResetBodyPipe(); + + network::mojom::DataPipeGetterPtr data_pipe_getter; + binding_set_.AddBinding(this, mojo::MakeRequest(&data_pipe_getter)); + return data_pipe_getter; + } + + private: + // DataPipeGetter implementation: + + void Read(mojo::ScopedDataPipeProducerHandle pipe, + ReadCallback callback) override { + // Close any previous body pipe, to avoid confusion between the two, if the + // consumer wants to restart reading from the file. + ResetBodyPipe(); + + std::move(callback).Run(net::OK, upload_string_.length()); + upload_body_pipe_ = std::move(pipe); + handle_watcher_ = std::make_unique<mojo::SimpleWatcher>( + FROM_HERE, mojo::SimpleWatcher::ArmingPolicy::MANUAL); + handle_watcher_->Watch( + upload_body_pipe_.get(), + // Don't bother watching for close - rely on read pipes for errors. + MOJO_HANDLE_SIGNAL_WRITABLE, MOJO_WATCH_CONDITION_SATISFIED, + base::BindRepeating(&StringUploadDataPipeGetter::MojoReadyCallback, + base::Unretained(this))); + WriteData(); + } + + void Clone(network::mojom::DataPipeGetterRequest request) override { + binding_set_.AddBinding(this, std::move(request)); + } + + void MojoReadyCallback(MojoResult result, + const mojo::HandleSignalsState& state) { + WriteData(); + } + + void WriteData() { + DCHECK_LE(write_position_, upload_string_.length()); + + while (true) { + uint32_t write_size = static_cast<uint32_t>( + std::min(static_cast<size_t>(32 * 1024), + upload_string_.length() - write_position_)); + if (write_size == 0) { + // Upload is done. Close the uplaod body pipe and wait for another call + // to Read(). + ResetBodyPipe(); + return; + } + + int result = + upload_body_pipe_->WriteData(upload_string_.data() + write_position_, + &write_size, MOJO_WRITE_DATA_FLAG_NONE); + if (result == MOJO_RESULT_SHOULD_WAIT) { + handle_watcher_->ArmOrNotify(); + return; + } + + if (result != MOJO_RESULT_OK) { + // Ignore the pipe being closed - the upload may still be retried with + // another call to Read. + ResetBodyPipe(); + return; + } + + write_position_ += write_size; + DCHECK_LE(write_position_, upload_string_.length()); + } + } + + // Closes the body pipe, and resets the position the class is writing from. + // Should be called either when a new binding is created, or a new read + // through the file is started. + void ResetBodyPipe() { + handle_watcher_.reset(); + upload_body_pipe_.reset(); + write_position_ = 0; + } + + mojo::BindingSet<network::mojom::DataPipeGetter> binding_set_; + + mojo::ScopedDataPipeProducerHandle upload_body_pipe_; + // Must be below |write_pipe_|, so it's deleted first. + std::unique_ptr<mojo::SimpleWatcher> handle_watcher_; + size_t write_position_ = 0; + + const std::string upload_string_; + + DISALLOW_COPY_AND_ASSIGN(StringUploadDataPipeGetter); +}; class BodyHandler; @@ -84,6 +199,8 @@ const OnRedirectCallback& on_redirect_callback) override; void SetAllowPartialResults(bool allow_partial_results) override; void SetAllowHttpErrorResults(bool allow_http_error_results) override; + void AttachStringForUpload(const std::string& upload_data, + const std::string& upload_content_type) override; void AttachFileForUpload(const base::FilePath& upload_file_path, const std::string& upload_content_type) override; void SetRetryOptions(int max_retries, int retry_mode) override; @@ -204,6 +321,8 @@ mojo::Binding<mojom::URLLoaderClient> client_binding_; mojom::URLLoaderPtr url_loader_; + std::unique_ptr<StringUploadDataPipeGetter> string_upload_data_pipe_getter_; + // Per-request state. Always non-null, but re-created on redirect. std::unique_ptr<RequestState> request_state_; @@ -501,8 +620,8 @@ // same location, don't invoke the callback until any partially downloaded // file has been destroyed. file_writer_->DeleteFile( - base::Bind(&SaveToFileBodyHandler::InvokeCallbackAsynchronously, - weak_ptr_factory_.GetWeakPtr())); + base::BindOnce(&SaveToFileBodyHandler::InvokeCallbackAsynchronously, + weak_ptr_factory_.GetWeakPtr())); FileWriter::Destroy(std::move(file_writer_)); return; } @@ -843,10 +962,37 @@ allow_http_error_results_ = allow_http_error_results; } +void SimpleURLLoaderImpl::AttachStringForUpload( + const std::string& upload_data, + const std::string& upload_content_type) { + // Currently only allow a single string to be attached. + DCHECK(!resource_request_->request_body); + DCHECK(resource_request_->method != "GET" && + resource_request_->method != "HEAD"); + + resource_request_->request_body = new ResourceRequestBody(); + + if (upload_data.length() <= kMaxUploadStringSizeToCopy) { + int copy_length = static_cast<int>(upload_data.length()); + DCHECK_EQ(static_cast<size_t>(copy_length), upload_data.length()); + resource_request_->request_body->AppendBytes(upload_data.c_str(), + copy_length); + } else { + // Don't attach the upload body here. A new pipe will need to be created + // each time the request is tried. + string_upload_data_pipe_getter_ = + std::make_unique<StringUploadDataPipeGetter>(upload_data); + } + + resource_request_->headers.SetHeader(net::HttpRequestHeaders::kContentType, + upload_content_type); +} + void SimpleURLLoaderImpl::AttachFileForUpload( const base::FilePath& upload_file_path, const std::string& upload_content_type) { DCHECK(!upload_file_path.empty()); + // Currently only allow a single file to be attached. DCHECK(!resource_request_->request_body); DCHECK(resource_request_->method != "GET" && @@ -873,6 +1019,19 @@ remaining_retries_ = max_retries; retry_mode_ = retry_mode; + +#if DCHECK_IS_ON() + if (max_retries > 0 && resource_request_->request_body) { + for (const storage::DataElement& element : + *resource_request_->request_body->elements()) { + // Data pipes are single-use, so can't retry uploads when there's a data + // pipe. + // TODO(mmenke): Data pipes can be Cloned(), though, so maybe update code + // to do that? + DCHECK(element.type() != storage::DataElement::TYPE_DATA_PIPE); + } + } +#endif // DCHECK_IS_ON() } int SimpleURLLoaderImpl::NetError() const { @@ -950,6 +1109,15 @@ client_binding_.Bind(mojo::MakeRequest(&client_ptr)); client_binding_.set_connection_error_handler(base::BindOnce( &SimpleURLLoaderImpl::OnConnectionError, base::Unretained(this))); + // Data elements that use pipes aren't reuseable, currently (Since the IPC + // code doesn't call the Clone() method), so need to create another one, if + // uploading a string via a data pipe. + if (string_upload_data_pipe_getter_) { + resource_request_->request_body = new ResourceRequestBody(); + network::mojom::DataPipeGetterPtr data_pipe_getter; + resource_request_->request_body->AppendDataPipe( + string_upload_data_pipe_getter_->GetPtrForNewUpload()); + } url_loader_factory->CreateLoaderAndStart( mojo::MakeRequest(&url_loader_), 0 /* routing_id */, 0 /* request_id */, 0 /* options */, *resource_request_, std::move(client_ptr), @@ -973,9 +1141,9 @@ request_state_ = std::make_unique<RequestState>(); - body_handler_->PrepareToRetry(base::Bind(&SimpleURLLoaderImpl::StartRequest, - weak_ptr_factory_.GetWeakPtr(), - url_loader_factory_ptr_.get())); + body_handler_->PrepareToRetry(base::BindOnce( + &SimpleURLLoaderImpl::StartRequest, weak_ptr_factory_.GetWeakPtr(), + url_loader_factory_ptr_.get())); } void SimpleURLLoaderImpl::OnReceiveResponse(
diff --git a/content/public/common/simple_url_loader.h b/content/public/common/simple_url_loader.h index 5cf66b33..c60b880 100644 --- a/content/public/common/simple_url_loader.h +++ b/content/public/common/simple_url_loader.h
@@ -63,7 +63,17 @@ }; // The maximum size DownloadToString will accept. - const size_t kMaxBoundedStringDownloadSize = 1024 * 1024; + static const size_t kMaxBoundedStringDownloadSize; + + // Maximum upload body size to send as a block to the URLLoaderFactory. This + // data may appear in memory twice for a while, in the retry case, and there + // may briefly be 3 to 5 copies as it's copied over the Mojo pipe: This + // class's copy (with retries enabled), the source mojo pipe's input copy, the + // copy on the IPC buffer, the destination mojo pipe's copy, and the network + // service's copy. + // + // Only exposed for tests. + static const size_t kMaxUploadStringSizeToCopy; // Callback used when downloading the response body as a std::string. // |response_body| is the body of the response, or nullptr on failure. @@ -171,15 +181,26 @@ // TODO(mmenke): Consider adding a new error code for this. virtual void SetAllowHttpErrorResults(bool allow_http_error_results) = 0; + // Attaches the specified string as the upload body. Depending on the length + // of the string, the string may be copied to the URLLoader, or may be + // streamed to it from the current process. May only be called once, and only + // if ResourceRequest passed to the constructor had a null |request_body|. + // + // |content_type| will overwrite any Content-Type header in the + // ResourceRequest passed to Create(). + // + // TODO(mmenke): This currently always requires a copy. Update DataElement not + // to require this. + virtual void AttachStringForUpload( + const std::string& upload_data, + const std::string& upload_content_type) = 0; + // Helper method to attach a file for upload, so the consumer won't need to // open the file itself off-thread. May only be called once, and only if the // ResourceRequest passed to the constructor had a null |request_body|. // // |content_type| will overwrite any Content-Type header in the // ResourceRequest passed to Create(). - // - // TODO(mmenke): This current attaches the upload as a FilePath. Make it open - // the file off-thread and attach it as a base::File instead. virtual void AttachFileForUpload(const base::FilePath& upload_file_path, const std::string& upload_content_type) = 0; @@ -196,6 +217,9 @@ // // Calling this multiple times will overwrite the values previously passed to // this method. May only be called before the request is started. + // + // Cannot retry requests with an upload body that contains a data pipe that + // was added the ResourceRequest passed to Create() by the consumer. virtual void SetRetryOptions(int max_retries, int retry_mode) = 0; // Returns the net::Error representing the final status of the request. May
diff --git a/content/public/common/simple_url_loader_unittest.cc b/content/public/common/simple_url_loader_unittest.cc index 1715b7df..177e27d 100644 --- a/content/public/common/simple_url_loader_unittest.cc +++ b/content/public/common/simple_url_loader_unittest.cc
@@ -68,6 +68,22 @@ // Server path returns a 5xx error once, then returns the request body. const char kFailOnceThenEchoBody[] = "/fail-once-then-echo-body"; +// Used in string upload tests. +const char kShortUploadBody[] = + "Though this upload be but little, it is fierce."; + +// Returns a string longer than +// SimpleURLLoader::kMaxUploadStringAsStringLength, to test the path where +// strings are streamed to the URLLoader. +std::string GetLongUploadBody() { + std::string long_string; + long_string.reserve(SimpleURLLoader::kMaxUploadStringSizeToCopy); + while (long_string.length() <= SimpleURLLoader::kMaxUploadStringSizeToCopy) { + long_string.append(kShortUploadBody); + } + return long_string; +} + // Class to make it easier to start a SimpleURLLoader, wait for it to complete, // and check the result. class SimpleLoaderTestHelper { @@ -377,9 +393,12 @@ mojo::MakeRequest(&url_loader_factory_), 0); test_server_.AddDefaultHandlers(base::FilePath(FILE_PATH_LITERAL(""))); - test_server_.RegisterRequestHandler(base::Bind(&HandleResponseSize)); - test_server_.RegisterRequestHandler(base::Bind(&HandleInvalidGzip)); - test_server_.RegisterRequestHandler(base::Bind(&HandleTruncatedBody)); + test_server_.RegisterRequestHandler( + base::BindRepeating(&HandleResponseSize)); + test_server_.RegisterRequestHandler( + base::BindRepeating(&HandleInvalidGzip)); + test_server_.RegisterRequestHandler( + base::BindRepeating(&HandleTruncatedBody)); test_server_.RegisterRequestHandler(base::BindRepeating( &FailOnceThenEchoBody, base::Owned(new bool(false)))); @@ -510,7 +529,7 @@ int num_redirects = 0; net::RedirectInfo redirect_info; ResourceResponseHead response_head; - test_helper->simple_url_loader()->SetOnRedirectCallback(base::Bind( + test_helper->simple_url_loader()->SetOnRedirectCallback(base::BindRepeating( [](int* num_redirects, net::RedirectInfo* redirect_info_ptr, ResourceResponseHead* response_head_ptr, const net::RedirectInfo& redirect_info, @@ -541,7 +560,7 @@ .GetURL("/server-redirect?" + test_server_.GetURL("/echo").spec()) .spec())); int num_redirects = 0; - test_helper->simple_url_loader()->SetOnRedirectCallback(base::Bind( + test_helper->simple_url_loader()->SetOnRedirectCallback(base::BindRepeating( [](int* num_redirects, const net::RedirectInfo& redirect_info, const ResourceResponseHead& response_head) { ++*num_redirects; }, base::Unretained(&num_redirects))); @@ -561,17 +580,64 @@ SimpleLoaderTestHelper* unowned_test_helper = test_helper.get(); base::RunLoop run_loop; - unowned_test_helper->simple_url_loader()->SetOnRedirectCallback(base::Bind( - [](std::unique_ptr<SimpleLoaderTestHelper> test_helper, - base::RunLoop* run_loop, const net::RedirectInfo& redirect_info, - const ResourceResponseHead& response_head) { run_loop->Quit(); }, - base::Passed(std::move(test_helper)), &run_loop)); + unowned_test_helper->simple_url_loader()->SetOnRedirectCallback( + base::BindRepeating( + [](std::unique_ptr<SimpleLoaderTestHelper> test_helper, + base::RunLoop* run_loop, const net::RedirectInfo& redirect_info, + const ResourceResponseHead& response_head) { run_loop->Quit(); }, + base::Passed(std::move(test_helper)), &run_loop)); unowned_test_helper->StartSimpleLoader(url_loader_factory_.get()); run_loop.Run(); } +TEST_P(SimpleURLLoaderTest, UploadShortStringWithRedirect) { + // Use a 307 redirect to preserve the body across the redirect. + std::unique_ptr<SimpleLoaderTestHelper> test_helper = CreateHelperForURL( + test_server_.GetURL("/server-redirect-307?" + + test_server_.GetURL("/echo").spec()), + "POST"); + test_helper->simple_url_loader()->AttachStringForUpload(kShortUploadBody, + "text/plain"); + + int num_redirects = 0; + test_helper->simple_url_loader()->SetOnRedirectCallback(base::BindRepeating( + [](int* num_redirects, const net::RedirectInfo& redirect_info, + const ResourceResponseHead& response_head) { ++*num_redirects; }, + base::Unretained(&num_redirects))); + + test_helper->StartSimpleLoaderAndWait(url_loader_factory_.get()); + EXPECT_EQ(net::OK, test_helper->simple_url_loader()->NetError()); + ASSERT_TRUE(test_helper->response_body()); + EXPECT_EQ(kShortUploadBody, *test_helper->response_body()); + // Make sure request really was redirected. + EXPECT_EQ(1, num_redirects); +} + +TEST_P(SimpleURLLoaderTest, UploadLongStringWithRedirect) { + // Use a 307 redirect to preserve the body across the redirect. + std::unique_ptr<SimpleLoaderTestHelper> test_helper = CreateHelperForURL( + test_server_.GetURL("/server-redirect-307?" + + test_server_.GetURL("/echo").spec()), + "POST"); + test_helper->simple_url_loader()->AttachStringForUpload(GetLongUploadBody(), + "text/plain"); + + int num_redirects = 0; + test_helper->simple_url_loader()->SetOnRedirectCallback(base::BindRepeating( + [](int* num_redirects, const net::RedirectInfo& redirect_info, + const ResourceResponseHead& response_head) { ++*num_redirects; }, + base::Unretained(&num_redirects))); + + test_helper->StartSimpleLoaderAndWait(url_loader_factory_.get()); + EXPECT_EQ(net::OK, test_helper->simple_url_loader()->NetError()); + ASSERT_TRUE(test_helper->response_body()); + EXPECT_EQ(GetLongUploadBody(), *test_helper->response_body()); + // Make sure request really was redirected. + EXPECT_EQ(1, num_redirects); +} + // Check the case where a URLLoaderFactory with a closed Mojo pipe was passed // in. TEST_P(SimpleURLLoaderTest, DisconnectedURLLoader) { @@ -863,6 +929,77 @@ ASSERT_FALSE(test_helper->simple_url_loader()->ResponseInfo()); } +TEST_P(SimpleURLLoaderTest, UploadShortString) { + std::unique_ptr<SimpleLoaderTestHelper> test_helper = + CreateHelperForURL(test_server_.GetURL("/echo"), "POST"); + test_helper->simple_url_loader()->AttachStringForUpload(kShortUploadBody, + "text/plain"); + test_helper->StartSimpleLoaderAndWait(url_loader_factory_.get()); + EXPECT_EQ(net::OK, test_helper->simple_url_loader()->NetError()); + ASSERT_TRUE(test_helper->response_body()); + EXPECT_EQ(kShortUploadBody, *test_helper->response_body()); +} + +TEST_P(SimpleURLLoaderTest, UploadLongString) { + std::string long_string = GetLongUploadBody(); + std::unique_ptr<SimpleLoaderTestHelper> test_helper = + CreateHelperForURL(test_server_.GetURL("/echo"), "POST"); + test_helper->simple_url_loader()->AttachStringForUpload(long_string, + "text/plain"); + test_helper->StartSimpleLoaderAndWait(url_loader_factory_.get()); + EXPECT_EQ(net::OK, test_helper->simple_url_loader()->NetError()); + ASSERT_TRUE(test_helper->response_body()); + EXPECT_EQ(long_string, *test_helper->response_body()); +} + +TEST_P(SimpleURLLoaderTest, UploadEmptyString) { + std::unique_ptr<SimpleLoaderTestHelper> test_helper = + CreateHelperForURL(test_server_.GetURL("/echo"), "POST"); + test_helper->simple_url_loader()->AttachStringForUpload("", "text/plain"); + test_helper->StartSimpleLoaderAndWait(url_loader_factory_.get()); + EXPECT_EQ(net::OK, test_helper->simple_url_loader()->NetError()); + ASSERT_TRUE(test_helper->response_body()); + EXPECT_EQ("", *test_helper->response_body()); + + // Also make sure the correct method was sent, with the right content-type. + test_helper = CreateHelperForURL(test_server_.GetURL("/echoall"), "POST"); + test_helper->simple_url_loader()->AttachStringForUpload("", "text/plain"); + test_helper->StartSimpleLoaderAndWait(url_loader_factory_.get()); + EXPECT_EQ(net::OK, test_helper->simple_url_loader()->NetError()); + ASSERT_TRUE(test_helper->response_body()); + EXPECT_NE(std::string::npos, + test_helper->response_body()->find("Content-Type: text/plain")); + EXPECT_NE(std::string::npos, test_helper->response_body()->find("POST /")); + EXPECT_EQ(std::string::npos, test_helper->response_body()->find("PUT /")); +} + +TEST_P(SimpleURLLoaderTest, UploadShortStringWithRetry) { + std::unique_ptr<SimpleLoaderTestHelper> test_helper = + CreateHelperForURL(test_server_.GetURL(kFailOnceThenEchoBody), "POST"); + test_helper->simple_url_loader()->AttachStringForUpload(kShortUploadBody, + "text/plain"); + test_helper->simple_url_loader()->SetRetryOptions( + 1, SimpleURLLoader::RETRY_ON_5XX); + test_helper->StartSimpleLoaderAndWait(url_loader_factory_.get()); + EXPECT_EQ(net::OK, test_helper->simple_url_loader()->NetError()); + ASSERT_TRUE(test_helper->response_body()); + EXPECT_EQ(kShortUploadBody, *test_helper->response_body()); +} + +TEST_P(SimpleURLLoaderTest, UploadLongStringWithRetry) { + std::string long_string = GetLongUploadBody(); + std::unique_ptr<SimpleLoaderTestHelper> test_helper = + CreateHelperForURL(test_server_.GetURL(kFailOnceThenEchoBody), "POST"); + test_helper->simple_url_loader()->AttachStringForUpload(long_string, + "text/plain"); + test_helper->simple_url_loader()->SetRetryOptions( + 1, SimpleURLLoader::RETRY_ON_5XX); + test_helper->StartSimpleLoaderAndWait(url_loader_factory_.get()); + EXPECT_EQ(net::OK, test_helper->simple_url_loader()->NetError()); + ASSERT_TRUE(test_helper->response_body()); + EXPECT_EQ(long_string, *test_helper->response_body()); +} + TEST_P(SimpleURLLoaderTest, UploadFile) { std::unique_ptr<SimpleLoaderTestHelper> test_helper = CreateHelperForURL(test_server_.GetURL("/echo"), "POST"); @@ -911,7 +1048,7 @@ EXPECT_NE(std::string::npos, test_helper->response_body()->find("PUT /")); } -TEST_P(SimpleURLLoaderTest, UploadWithRetry) { +TEST_P(SimpleURLLoaderTest, UploadFileWithRetry) { std::unique_ptr<SimpleLoaderTestHelper> test_helper = CreateHelperForURL(test_server_.GetURL(kFailOnceThenEchoBody), "POST"); test_helper->simple_url_loader()->AttachFileForUpload(GetTestFilePath(), @@ -968,6 +1105,22 @@ } enum class TestLoaderEvent { + // States related to reading the long upload body (Returned by + // GetLongUploadBody()). They expect the ResourceRequest to have a request + // body with a single DataPipeGetter. + + // Call Read() on the DataPipeGetter. + kStartReadLongUploadBody, + // Wait for Read() to complete, expecting it to succeed and return the size of + // the string returned by GetLongUploadBody(). + kWaitForLongUploadBodySize, + // Read the entire body, expecting it to equal the string returned by + // GetLongUploadBody(). + kReadLongUploadBody, + // Read the first byte of the upload body. Cannot be followed by a call to + // kReadLongUploadBody. + kReadFirstByteOfLongUploadBody, + kReceivedRedirect, // Receive a response with a 200 status code. kReceivedResponse, @@ -1000,15 +1153,91 @@ MockURLLoader(base::test::ScopedTaskEnvironment* scoped_task_environment, mojom::URLLoaderRequest url_loader_request, mojom::URLLoaderClientPtr client, - std::vector<TestLoaderEvent> test_events) + std::vector<TestLoaderEvent> test_events, + scoped_refptr<content::ResourceRequestBody> request_body) : scoped_task_environment_(scoped_task_environment), binding_(this, std::move(url_loader_request)), client_(std::move(client)), - test_events_(std::move(test_events)) {} + test_events_(std::move(test_events)), + weak_factory_for_data_pipe_callbacks_(this) { + if (request_body && request_body->elements()->size() == 1 && + (*request_body->elements())[0].type() == + storage::DataElement::TYPE_DATA_PIPE) { + // The const_cast is weird, but it's how the current API works. + data_pipe_getter_ = + const_cast<storage::DataElement*>(&(*request_body->elements())[0]) + ->ReleaseDataPipeGetter(); + DCHECK(data_pipe_getter_); + } + } void RunTest() { for (auto test_event : test_events_) { switch (test_event) { + case TestLoaderEvent::kStartReadLongUploadBody: { + ASSERT_TRUE(data_pipe_getter_); + upload_data_pipe_.reset(); + weak_factory_for_data_pipe_callbacks_.InvalidateWeakPtrs(); + read_run_loop_ = std::make_unique<base::RunLoop>(); + mojo::DataPipe data_pipe; + data_pipe_getter_->Read( + std::move(data_pipe.producer_handle), + base::BindOnce( + &MockURLLoader::OnReadComplete, + weak_factory_for_data_pipe_callbacks_.GetWeakPtr())); + upload_data_pipe_ = std::move(data_pipe.consumer_handle); + // Continue instead of break, to avoid spinning the message loop - + // only wait for the response if next step indicates to do so. + continue; + } + case TestLoaderEvent::kWaitForLongUploadBodySize: { + ASSERT_TRUE(data_pipe_getter_); + ASSERT_TRUE(read_run_loop_); + read_run_loop_->Run(); + break; + } + case TestLoaderEvent::kReadLongUploadBody: { + ASSERT_TRUE(data_pipe_getter_); + ASSERT_TRUE(upload_data_pipe_.is_valid()); + std::string upload_body; + while (true) { + char read_buffer[32 * 1024]; + uint32_t read_size = sizeof(read_buffer); + MojoResult result = upload_data_pipe_->ReadData( + read_buffer, &read_size, MOJO_READ_DATA_FLAG_NONE); + if (result == MOJO_RESULT_SHOULD_WAIT) { + base::RunLoop().RunUntilIdle(); + continue; + } + if (result != MOJO_RESULT_OK) + break; + upload_body.append(read_buffer, read_size); + } + EXPECT_EQ(GetLongUploadBody(), upload_body); + break; + } + case TestLoaderEvent::kReadFirstByteOfLongUploadBody: { + ASSERT_TRUE(data_pipe_getter_); + ASSERT_TRUE(upload_data_pipe_.is_valid()); + MojoResult result; + char byte; + uint32_t read_size; + while (true) { + read_size = 1; + result = upload_data_pipe_->ReadData(&byte, &read_size, + MOJO_READ_DATA_FLAG_NONE); + if (result != MOJO_RESULT_SHOULD_WAIT) + break; + base::RunLoop().RunUntilIdle(); + } + if (result != MOJO_RESULT_OK) { + ADD_FAILURE() << "Expected to read one byte of data."; + break; + } + EXPECT_EQ(1u, read_size); + EXPECT_EQ(GetLongUploadBody()[0], byte); + break; + } case TestLoaderEvent::kReceivedRedirect: { net::RedirectInfo redirect_info; redirect_info.new_method = "GET"; @@ -1151,6 +1380,12 @@ return total_bytes; } + void OnReadComplete(int32_t status, uint64_t size) { + EXPECT_EQ(net::OK, status); + EXPECT_EQ(GetLongUploadBody().size(), size); + read_run_loop_->Quit(); + } + base::test::ScopedTaskEnvironment* scoped_task_environment_; std::unique_ptr<net::URLRequest> url_request_; @@ -1161,6 +1396,13 @@ mojo::ScopedDataPipeProducerHandle body_stream_; + network::mojom::DataPipeGetterPtr data_pipe_getter_; + mojo::ScopedDataPipeConsumerHandle upload_data_pipe_; + + std::unique_ptr<base::RunLoop> read_run_loop_; + + base::WeakPtrFactory<MockURLLoader> weak_factory_for_data_pipe_callbacks_; + DISALLOW_COPY_AND_ASSIGN(MockURLLoader); }; @@ -1185,7 +1427,7 @@ requested_urls_.push_back(url_request.url); url_loaders_.push_back(std::make_unique<MockURLLoader>( scoped_task_environment_, std::move(url_loader_request), - std::move(client), test_events_.front())); + std::move(client), test_events_.front(), url_request.request_body)); test_events_.pop_front(); url_loader_queue_.push_back(url_loaders_.back().get()); @@ -1656,7 +1898,7 @@ CreateHelperForURL(kInitialURL); test_helper->simple_url_loader()->SetRetryOptions( 1, SimpleURLLoader::RETRY_ON_5XX); - test_helper->simple_url_loader()->SetOnRedirectCallback(base::Bind( + test_helper->simple_url_loader()->SetOnRedirectCallback(base::BindRepeating( [](int* num_redirects, const net::RedirectInfo& redirect_info, const ResourceResponseHead& response_head) { ++*num_redirects; }, base::Unretained(&num_redirects))); @@ -1820,6 +2062,56 @@ EXPECT_FALSE(test_helper->response_body()); } +// Test the case where DataPipeGetter::Read is called twice in a row, +// with no intervening reads of the data on the pipe. +TEST_P(SimpleURLLoaderTest, UploadLongStringStartReadTwice) { + std::string long_string = GetLongUploadBody(); + MockURLLoaderFactory loader_factory(&scoped_task_environment_); + loader_factory.AddEvents( + {TestLoaderEvent::kStartReadLongUploadBody, + TestLoaderEvent::kStartReadLongUploadBody, + TestLoaderEvent::kWaitForLongUploadBodySize, + TestLoaderEvent::kReadLongUploadBody, TestLoaderEvent::kReceivedResponse, + TestLoaderEvent::kBodyBufferReceived, TestLoaderEvent::kResponseComplete, + TestLoaderEvent::kBodyBufferClosed}); + std::unique_ptr<SimpleLoaderTestHelper> test_helper = + CreateHelperForURL(GURL("foo://bar/"), "POST"); + test_helper->simple_url_loader()->AttachStringForUpload(long_string, + "text/plain"); + loader_factory.RunTest(test_helper.get()); + + EXPECT_EQ(net::OK, test_helper->simple_url_loader()->NetError()); + ASSERT_TRUE(test_helper->response_body()); + EXPECT_EQ("", *test_helper->response_body()); +} + +// Test the case where DataPipeGetter::Read is called a second time, after only +// reading part of the response, with no intervening reads of the data on the +// pipe. +TEST_P(SimpleURLLoaderTest, + UploadLongStringReadPartOfUploadBodyBeforeRestartBodyRead) { + std::string long_string = GetLongUploadBody(); + MockURLLoaderFactory loader_factory(&scoped_task_environment_); + loader_factory.AddEvents( + {TestLoaderEvent::kStartReadLongUploadBody, + TestLoaderEvent::kWaitForLongUploadBodySize, + TestLoaderEvent::kReadFirstByteOfLongUploadBody, + TestLoaderEvent::kStartReadLongUploadBody, + TestLoaderEvent::kWaitForLongUploadBodySize, + TestLoaderEvent::kReadLongUploadBody, TestLoaderEvent::kReceivedResponse, + TestLoaderEvent::kBodyBufferReceived, TestLoaderEvent::kResponseComplete, + TestLoaderEvent::kBodyBufferClosed}); + std::unique_ptr<SimpleLoaderTestHelper> test_helper = + CreateHelperForURL(GURL("foo://bar/"), "POST"); + test_helper->simple_url_loader()->AttachStringForUpload(long_string, + "text/plain"); + loader_factory.RunTest(test_helper.get()); + + EXPECT_EQ(net::OK, test_helper->simple_url_loader()->NetError()); + ASSERT_TRUE(test_helper->response_body()); + EXPECT_EQ("", *test_helper->response_body()); +} + INSTANTIATE_TEST_CASE_P( /* No prefix */, SimpleURLLoaderTest,
diff --git a/content/public/test/android/BUILD.gn b/content/public/test/android/BUILD.gn index b7654365..ee6ce6c5 100644 --- a/content/public/test/android/BUILD.gn +++ b/content/public/test/android/BUILD.gn
@@ -51,6 +51,7 @@ "javatests/src/org/chromium/content/browser/test/util/TestCallbackHelperContainer.java", "javatests/src/org/chromium/content/browser/test/util/TestContentViewCore.java", "javatests/src/org/chromium/content/browser/test/util/TestInputMethodManagerWrapper.java", + "javatests/src/org/chromium/content/browser/test/util/TestSelectionPopupController.java", "javatests/src/org/chromium/content/browser/test/util/TestTouchUtils.java", "javatests/src/org/chromium/content/browser/test/util/TestWebContentsObserver.java", "javatests/src/org/chromium/content/browser/test/util/TouchCommon.java",
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 e3dd113..8ec1ebb 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
@@ -5,10 +5,8 @@ package org.chromium.content.browser.test.util; import android.content.Context; -import android.content.Intent; import android.content.res.Configuration; import android.os.Bundle; -import android.view.ActionMode; import android.view.KeyEvent; import android.view.MotionEvent; import android.view.ViewGroup; @@ -16,21 +14,17 @@ import android.view.accessibility.AccessibilityNodeProvider; import android.view.inputmethod.EditorInfo; import android.view.inputmethod.InputConnection; -import android.view.textclassifier.TextClassifier; import org.chromium.base.VisibleForTesting; import org.chromium.content.browser.ContentViewCore; import org.chromium.content.browser.ContentViewCore.InternalAccessDelegate; import org.chromium.content.browser.PopupZoomer; -import org.chromium.content.browser.SelectionPopupController; import org.chromium.content.browser.WindowAndroidChangedObserver; import org.chromium.content.browser.accessibility.WebContentsAccessibility; import org.chromium.content.browser.input.ImeAdapter; import org.chromium.content.browser.input.SelectPopup; import org.chromium.content.browser.input.TextSuggestionHost; -import org.chromium.content_public.browser.ActionModeCallbackHelper; import org.chromium.content_public.browser.ImeEventObserver; -import org.chromium.content_public.browser.SelectionClient; import org.chromium.content_public.browser.WebContents; import org.chromium.ui.base.ViewAndroidDelegate; import org.chromium.ui.base.WindowAndroid; @@ -63,14 +57,6 @@ } @Override - public SelectionPopupController getSelectionPopupControllerForTesting() { - return null; - } - - @Override - public void setSelectionPopupControllerForTesting(SelectionPopupController actionMode) {} - - @Override public TextSuggestionHost getTextSuggestionHostForTesting() { return null; } @@ -105,17 +91,6 @@ public void updateWindowAndroid(WindowAndroid windowAndroid) {} @Override - public void setActionModeCallback(ActionMode.Callback callback) {} - - @Override - public void setNonSelectionActionModeCallback(ActionMode.Callback callback) {} - - @Override - public SelectionClient.ResultCallback getPopupControllerResultCallback() { - return null; - } - - @Override public void setContainerView(ViewGroup containerView) {} @Override @@ -144,16 +119,6 @@ } @Override - public String getSelectedText() { - return null; - } - - @Override - public boolean isFocusedNodeEditable() { - return false; - } - - @Override public boolean isScrollInProgress() { return false; } @@ -179,14 +144,6 @@ public void onHide() {} @Override - public void destroySelectActionMode() {} - - @Override - public boolean isSelectActionBarShowing() { - return false; - } - - @Override public boolean isAttachedToWindow() { return false; } @@ -294,14 +251,6 @@ public void selectPopupMenuItems(int[] indices) {} @Override - public ActionModeCallbackHelper getActionModeCallbackHelper() { - return null; - } - - @Override - public void clearSelection() {} - - @Override public void preserveSelectionOnNextLossOfFocus() {} @Override @@ -336,9 +285,6 @@ public void setObscuredByAnotherView(boolean isObscured) {} @Override - public void onReceivedProcessTextResult(int resultCode, Intent data) {} - - @Override public boolean isTouchExplorationEnabled() { return false; } @@ -361,22 +307,6 @@ public void setFullscreenRequiredForOrientationLock(boolean value) {} @Override - public void setSelectionClient(SelectionClient selectionClient) {} - - @Override - public void setTextClassifier(TextClassifier textClassifier) {} - - @Override - public TextClassifier getTextClassifier() { - return null; - } - - @Override - public TextClassifier getCustomTextClassifier() { - return null; - } - - @Override public int getTopControlsShrinkBlinkHeightForTesting() { return 0; }
diff --git a/content/public/test/android/javatests/src/org/chromium/content/browser/test/util/TestSelectionPopupController.java b/content/public/test/android/javatests/src/org/chromium/content/browser/test/util/TestSelectionPopupController.java new file mode 100644 index 0000000..9ad35df8 --- /dev/null +++ b/content/public/test/android/javatests/src/org/chromium/content/browser/test/util/TestSelectionPopupController.java
@@ -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. + +package org.chromium.content.browser.test.util; + +import android.content.Intent; +import android.view.ActionMode; +import android.view.textclassifier.TextClassifier; + +import org.chromium.content_public.browser.ActionModeCallbackHelper; +import org.chromium.content_public.browser.SelectionClient; +import org.chromium.content_public.browser.SelectionPopupController; + +/** + * A dummy {@link SelectionPopupController} implementation that can be overriden by tests + * to customize behavior. + */ +public class TestSelectionPopupController implements SelectionPopupController { + public TestSelectionPopupController() {} + + @Override + public void setActionModeCallback(ActionMode.Callback callback) {} + + @Override + public void setNonSelectionActionModeCallback(ActionMode.Callback callback) {} + + @Override + public SelectionClient.ResultCallback getResultCallback() { + return null; + } + + @Override + public String getSelectedText() { + return null; + } + + @Override + public boolean isFocusedNodeEditable() { + return false; + } + + @Override + public boolean hasSelection() { + return false; + } + + @Override + public void destroySelectActionMode() {} + + @Override + public boolean isSelectActionBarShowing() { + return false; + } + + @Override + public ActionModeCallbackHelper getActionModeCallbackHelper() { + return null; + } + + @Override + public void clearSelection() {} + + @Override + public void onReceivedProcessTextResult(int resultCode, Intent data) {} + + @Override + public void setSelectionClient(SelectionClient selectionClient) {} + + @Override + public void setTextClassifier(TextClassifier textClassifier) {} + + @Override + public TextClassifier getTextClassifier() { + return null; + } + + @Override + public TextClassifier getCustomTextClassifier() { + return null; + } +}
diff --git a/content/renderer/BUILD.gn b/content/renderer/BUILD.gn index 1c4a15a..78afd8ef 100644 --- a/content/renderer/BUILD.gn +++ b/content/renderer/BUILD.gn
@@ -926,7 +926,7 @@ "//third_party/webrtc/api/audio_codecs/opus:audio_encoder_opus", "//third_party/webrtc/api/video_codecs:video_codecs_api", "//third_party/webrtc/common_video:common_video", - "//third_party/webrtc/media:rtc_audio_video", + "//third_party/webrtc/media:rtc_internal_video_codecs", "//third_party/webrtc/media:rtc_media", "//third_party/webrtc/media:rtc_media_base", "//third_party/webrtc/modules/audio_device",
diff --git a/content/renderer/media/media_stream_audio_processor.cc b/content/renderer/media/media_stream_audio_processor.cc index b874972..43e97d2 100644 --- a/content/renderer/media/media_stream_audio_processor.cc +++ b/content/renderer/media/media_stream_audio_processor.cc
@@ -679,7 +679,7 @@ } // Create and configure the webrtc::AudioProcessing. - audio_processing_.reset(webrtc::AudioProcessing::Create(config)); + audio_processing_.reset(webrtc::AudioProcessingBuilder().Create(config)); // Enable the audio processing components. webrtc::AudioProcessing::Config apm_config;
diff --git a/content/renderer/media/media_stream_video_capturer_source.cc b/content/renderer/media/media_stream_video_capturer_source.cc index 715f92ae..a148e7a 100644 --- a/content/renderer/media/media_stream_video_capturer_source.cc +++ b/content/renderer/media/media_stream_video_capturer_source.cc
@@ -227,6 +227,11 @@ } state_ = STOPPING_FOR_RESTART; source_->StopCapture(); + + // Force state update for nondevice sources, since they do not + // automatically update state after StopCapture(). + if (device().type == MEDIA_NO_SERVICE) + OnRunStateChanged(capture_params_, false); } void MediaStreamVideoCapturerSource::RestartSourceImpl(
diff --git a/content/renderer/media/media_stream_video_source.cc b/content/renderer/media/media_stream_video_source.cc index 220b49c..5a8acb28 100644 --- a/content/renderer/media/media_stream_video_source.cc +++ b/content/renderer/media/media_stream_video_source.cc
@@ -106,7 +106,7 @@ if (tracks_.empty()) { if (callback) { - // Using StopForRestart() in order to get a notification of when the + // Use StopForRestart() in order to get a notification of when the // source is actually stopped (if supported). The source will not be // restarted. // The intent is to have the same effect as StopSource() (i.e., having
diff --git a/content/renderer/media/media_stream_video_track.cc b/content/renderer/media/media_stream_video_track.cc index 44913dab..b190a5d 100644 --- a/content/renderer/media/media_stream_video_track.cc +++ b/content/renderer/media/media_stream_video_track.cc
@@ -352,6 +352,8 @@ if (source_) { source_->RemoveTrack(this, std::move(callback)); source_ = nullptr; + } else if (callback) { + std::move(callback).Run(); } OnReadyStateChanged(blink::WebMediaStreamSource::kReadyStateEnded); }
diff --git a/content/renderer/media/webmediaplayer_ms_unittest.cc b/content/renderer/media/webmediaplayer_ms_unittest.cc index caba08f..b547abc 100644 --- a/content/renderer/media/webmediaplayer_ms_unittest.cc +++ b/content/renderer/media/webmediaplayer_ms_unittest.cc
@@ -525,7 +525,8 @@ void ActivateViewportIntersectionMonitoring(bool activate) override {} void MediaRemotingStarted( const blink::WebString& remote_device_friendly_name) override {} - void MediaRemotingStopped() override {} + void MediaRemotingStopped( + blink::WebLocalizedString::Name error_msg) override {} // Implementation of cc::VideoFrameProvider::Client void StopUsingProvider() override;
diff --git a/content/renderer/media/webrtc/media_stream_remote_video_source.cc b/content/renderer/media/webrtc/media_stream_remote_video_source.cc index 4407dcf..8b56e8e 100644 --- a/content/renderer/media/webrtc/media_stream_remote_video_source.cc +++ b/content/renderer/media/webrtc/media_stream_remote_video_source.cc
@@ -18,7 +18,7 @@ #include "media/base/video_frame.h" #include "media/base/video_util.h" #include "third_party/webrtc/api/video/i420_buffer.h" -#include "third_party/webrtc/media/base/videosinkinterface.h" +#include "third_party/webrtc/api/videosinkinterface.h" namespace content {
diff --git a/content/shell/android/java/src/org/chromium/content_shell/Shell.java b/content/shell/android/java/src/org/chromium/content_shell/Shell.java index e8153f3..532e685 100644 --- a/content/shell/android/java/src/org/chromium/content_shell/Shell.java +++ b/content/shell/android/java/src/org/chromium/content_shell/Shell.java
@@ -36,6 +36,7 @@ import org.chromium.content_public.browser.ActionModeCallbackHelper; import org.chromium.content_public.browser.LoadUrlParams; import org.chromium.content_public.browser.NavigationController; +import org.chromium.content_public.browser.SelectionPopupController; import org.chromium.content_public.browser.WebContents; import org.chromium.ui.base.WindowAndroid; @@ -301,8 +302,9 @@ ContentView cv = ContentView.createContentView(context, mContentViewCore); mViewAndroidDelegate = new ShellViewAndroidDelegate(cv); mContentViewCore.initialize(mViewAndroidDelegate, cv, webContents, mWindow); - mContentViewCore.setActionModeCallback(defaultActionCallback()); mWebContents = mContentViewCore.getWebContents(); + SelectionPopupController controller = SelectionPopupController.fromWebContents(webContents); + controller.setActionModeCallback(defaultActionCallback()); mNavigationController = mWebContents.getNavigationController(); if (getParent() != null) mContentViewCore.onShow(); if (mWebContents.getVisibleUrl() != null) { @@ -322,7 +324,8 @@ */ private ActionMode.Callback defaultActionCallback() { final ActionModeCallbackHelper helper = - mContentViewCore.getActionModeCallbackHelper(); + SelectionPopupController.fromWebContents(mWebContents) + .getActionModeCallbackHelper(); return new ActionMode.Callback() { @Override
diff --git a/content/test/data/frame_tree/oopif_hit_test_layer_squashing.html b/content/test/data/frame_tree/oopif_hit_test_layer_squashing.html new file mode 100644 index 0000000..16ead0e --- /dev/null +++ b/content/test/data/frame_tree/oopif_hit_test_layer_squashing.html
@@ -0,0 +1,45 @@ +<!DOCTYPE html> +<html> +<head> +<meta charset="utf-8"> +<meta name="viewport" content="width=device-width"> +<style> +#A { + /* Dummy layer which is not allowed to squash */ + top: 0; + left: 0; + width: 20px; + height: 20px; +} + +#B { + top: 0px; + width: 200px; + height: 20px; +} + +#C { + top: 0px; + left: 0px; + width: 40px; + height: 200px; +} + +div { + position: absolute; + background: #a0a0ee; + border: 3px solid #1010ff; +} + +iframe { + backface-visibility: hidden; /* force compositing */ +} +</style> +</head> +<body> + <iframe id="I" width="200" height="240" src="/cross-site/baz.com/title1.html" frameborder="0" allowfullscreen=""></iframe> + <div id="A"></div> + <div id="B"></div> + <div id="C"></div> +</body> +</html>
diff --git a/content/test/data/frame_tree/oopif_hit_test_watermark.html b/content/test/data/frame_tree/oopif_hit_test_watermark.html new file mode 100644 index 0000000..7930b955 --- /dev/null +++ b/content/test/data/frame_tree/oopif_hit_test_watermark.html
@@ -0,0 +1,25 @@ +<!DOCTYPE html> +<html> +<head> +<meta charset="utf-8"> +<meta name="viewport" content="width=device-width"> +<style> +#W { + top: 0; + left: 0; + width: 200px; + height: 240px; + position: absolute; + background-color: rgba(255, 0, 0, 0.2); +} + +iframe { + backface-visibility: hidden; /* force compositing */ +} +</style> +</head> +<body> + <iframe id="I" width="200" height="240" src="/cross-site/baz.com/title1.html" frameborder="0" allowfullscreen=""></iframe> + <div id="W"></div> +</body> +</html>
diff --git a/extensions/browser/DEPS b/extensions/browser/DEPS index cf63876..0f7d473 100644 --- a/extensions/browser/DEPS +++ b/extensions/browser/DEPS
@@ -51,7 +51,6 @@ "+chrome/browser/extensions/extension_function_test_utils.h", "+chrome/browser/extensions/extension_service.h", "+chrome/browser/extensions/extension_service_test_base.h", - "+chrome/browser/extensions/extension_test_message_listener.h", "+chrome/browser/extensions/test_extension_dir.h", "+chrome/browser/ui/browser.h", "+chrome/common/chrome_switches.h",
diff --git a/gpu/ipc/service/gpu_channel_manager.cc b/gpu/ipc/service/gpu_channel_manager.cc index 15ca2459e..f8bcb0cce 100644 --- a/gpu/ipc/service/gpu_channel_manager.cc +++ b/gpu/ipc/service/gpu_channel_manager.cc
@@ -266,10 +266,6 @@ void GpuChannelManager::OnApplicationStateChange( base::android::ApplicationState state) { - // TODO(ericrk): Temporarily disable the context release logic due to - // https://crbug.com/792120. Re-enable when the fix lands. - return; - if (state != base::android::APPLICATION_STATE_HAS_STOPPED_ACTIVITIES || !is_running_on_low_end_mode_) { return;
diff --git a/headless/lib/browser/headless_devtools_client_impl.cc b/headless/lib/browser/headless_devtools_client_impl.cc index d8b59c0a..1c21cd70 100644 --- a/headless/lib/browser/headless_devtools_client_impl.cc +++ b/headless/lib/browser/headless_devtools_client_impl.cc
@@ -144,7 +144,7 @@ base::JSONReader::Read(json_message, base::JSON_PARSE_RFC); const base::DictionaryValue* message_dict; if (!message || !message->GetAsDictionary(&message_dict)) { - NOTREACHED() << "Badly formed reply"; + NOTREACHED() << "Badly formed reply " << json_message; return; }
diff --git a/headless/lib/virtual_time_browsertest.cc b/headless/lib/virtual_time_browsertest.cc index 7a0a6a6..ef5b1a2f 100644 --- a/headless/lib/virtual_time_browsertest.cc +++ b/headless/lib/virtual_time_browsertest.cc
@@ -7,7 +7,6 @@ #include "base/strings/stringprintf.h" #include "content/public/test/browser_test.h" #include "headless/public/devtools/domains/emulation.h" -#include "headless/public/devtools/domains/page.h" #include "headless/public/devtools/domains/runtime.h" #include "headless/public/headless_devtools_client.h" #include "headless/public/util/testing/test_in_memory_protocol_handler.h" @@ -23,7 +22,6 @@ class VirtualTimeBrowserTest : public HeadlessAsyncDevTooledBrowserTest, public emulation::ExperimentalObserver, - public page::ExperimentalObserver, public runtime::Observer { public: void SetInitialURL(const std::string& initial_url) { @@ -32,19 +30,11 @@ void RunDevTooledTest() override { devtools_client_->GetEmulation()->GetExperimental()->AddObserver(this); - devtools_client_->GetPage()->GetExperimental()->AddObserver(this); devtools_client_->GetRuntime()->AddObserver(this); - - devtools_client_->GetPage()->Enable(base::Bind( - &VirtualTimeBrowserTest::PageEnabled, base::Unretained(this))); devtools_client_->GetRuntime()->Enable(base::Bind( &VirtualTimeBrowserTest::RuntimeEnabled, base::Unretained(this))); } - void PageEnabled() { - page_enabled = true; - MaybeSetVirtualTimePolicy(); - } void RuntimeEnabled() { runtime_enabled = true; @@ -52,7 +42,7 @@ } virtual void MaybeSetVirtualTimePolicy() { - if (!page_enabled || !runtime_enabled) + if (!runtime_enabled) return; // To avoid race conditions start with virtual time paused. @@ -62,6 +52,8 @@ .Build(), base::Bind(&VirtualTimeBrowserTest::SetVirtualTimePolicyDone, base::Unretained(this))); + + SetAfterLoadVirtualTimePolicy(); } void SetVirtualTimePolicyDone( @@ -71,18 +63,13 @@ devtools_client_->GetPage()->Navigate(initial_url_); } - void OnFrameStartedLoading( - const page::FrameStartedLoadingParams& params) override { - if (initial_load_seen_) - return; - initial_load_seen_ = true; - // The navigation is underway, so allow virtual time to advance while - // network fetches are not pending. + virtual void SetAfterLoadVirtualTimePolicy() { devtools_client_->GetEmulation()->GetExperimental()->SetVirtualTimePolicy( emulation::SetVirtualTimePolicyParams::Builder() .SetPolicy( emulation::VirtualTimePolicy::PAUSE_IF_NETWORK_FETCHES_PENDING) .SetBudget(5000) + .SetWaitForNavigation(true) .Build()); } @@ -99,7 +86,6 @@ std::string initial_url_; std::vector<std::string> log_; bool initial_load_seen_ = false; - bool page_enabled = false; bool runtime_enabled = false; }; @@ -114,7 +100,8 @@ // emulation::Observer implementation: void OnVirtualTimeBudgetExpired( const emulation::VirtualTimeBudgetExpiredParams& params) override { - std::vector<std::string> expected_log = {"step1", + std::vector<std::string> expected_log = {"Paused @ 0ms", + "step1", "Advanced to 100ms", "step2", "Paused @ 100ms", @@ -160,19 +147,14 @@ .spec()); } - void OnFrameStartedLoading( - const page::FrameStartedLoadingParams& params) override { - if (initial_load_seen_) - return; - initial_load_seen_ = true; - // The navigation is underway, so allow virtual time to advance while - // network fetches are not pending. + void SetAfterLoadVirtualTimePolicy() override { devtools_client_->GetEmulation()->GetExperimental()->SetVirtualTimePolicy( emulation::SetVirtualTimePolicyParams::Builder() .SetPolicy( emulation::VirtualTimePolicy::PAUSE_IF_NETWORK_FETCHES_PENDING) - .SetBudget(4000) + .SetBudget(4001) .SetMaxVirtualTimeTaskStarvationCount(100) + .SetWaitForNavigation(true) .Build()); } @@ -292,19 +274,14 @@ .spec()); } - void OnFrameStartedLoading( - const page::FrameStartedLoadingParams& params) override { - if (initial_load_seen_) - return; - initial_load_seen_ = true; - // The navigation is underway, so allow virtual time to advance while - // network fetches are not pending. + void SetAfterLoadVirtualTimePolicy() override { devtools_client_->GetEmulation()->GetExperimental()->SetVirtualTimePolicy( emulation::SetVirtualTimePolicyParams::Builder() .SetPolicy( emulation::VirtualTimePolicy::PAUSE_IF_NETWORK_FETCHES_PENDING) .SetBudget(4001) .SetMaxVirtualTimeTaskStarvationCount(100) + .SetWaitForNavigation(true) .Build()); } @@ -347,19 +324,14 @@ .spec()); } - void OnFrameStartedLoading( - const page::FrameStartedLoadingParams& params) override { - if (initial_load_seen_) - return; - initial_load_seen_ = true; - // The navigation is underway, so allow virtual time to advance while - // network fetches are not pending. + void SetAfterLoadVirtualTimePolicy() override { devtools_client_->GetEmulation()->GetExperimental()->SetVirtualTimePolicy( emulation::SetVirtualTimePolicyParams::Builder() .SetPolicy( emulation::VirtualTimePolicy::PAUSE_IF_NETWORK_FETCHES_PENDING) .SetBudget(4001) .SetMaxVirtualTimeTaskStarvationCount(100) + .SetWaitForNavigation(true) .Build()); }
diff --git a/headless/test/headless_render_test.cc b/headless/test/headless_render_test.cc index 733607be..75ec55c8 100644 --- a/headless/test/headless_render_test.cc +++ b/headless/test/headless_render_test.cc
@@ -49,8 +49,16 @@ devtools_client_->GetEmulation()->GetExperimental()->SetVirtualTimePolicy( emulation::SetVirtualTimePolicyParams::Builder() .SetPolicy(emulation::VirtualTimePolicy::PAUSE) + .Build()); + devtools_client_->GetEmulation()->GetExperimental()->SetVirtualTimePolicy( + emulation::SetVirtualTimePolicyParams::Builder() + .SetPolicy( + emulation::VirtualTimePolicy::PAUSE_IF_NETWORK_FETCHES_PENDING) + .SetBudget(4001) + .SetWaitForNavigation(true) .Build(), base::Bind(&SetVirtualTimePolicyDoneCallback, &run_loop)); + base::MessageLoop::ScopedNestableTaskAllower nest_loop( base::MessageLoop::current()); run_loop.Run();
diff --git a/ios/chrome/browser/history/web_history_service_factory.cc b/ios/chrome/browser/history/web_history_service_factory.cc index fdece29..16e381c2 100644 --- a/ios/chrome/browser/history/web_history_service_factory.cc +++ b/ios/chrome/browser/history/web_history_service_factory.cc
@@ -14,8 +14,7 @@ #include "components/signin/core/browser/signin_manager.h" #include "components/sync/driver/sync_service.h" #include "ios/chrome/browser/browser_state/chrome_browser_state.h" -#include "ios/chrome/browser/signin/oauth2_token_service_factory.h" -#include "ios/chrome/browser/signin/signin_manager_factory.h" +#include "ios/chrome/browser/signin/identity_manager_factory.h" #include "ios/chrome/browser/sync/ios_chrome_profile_sync_service_factory.h" #include "net/url_request/url_request_context_getter.h" @@ -56,8 +55,7 @@ "WebHistoryService", BrowserStateDependencyManager::GetInstance()) { DependsOn(IOSChromeProfileSyncServiceFactory::GetInstance()); - DependsOn(OAuth2TokenServiceFactory::GetInstance()); - DependsOn(ios::SigninManagerFactory::GetInstance()); + DependsOn(IdentityManagerFactory::GetInstance()); } WebHistoryServiceFactory::~WebHistoryServiceFactory() { @@ -68,8 +66,7 @@ ios::ChromeBrowserState* browser_state = ios::ChromeBrowserState::FromBrowserState(context); return base::MakeUnique<history::WebHistoryService>( - OAuth2TokenServiceFactory::GetForBrowserState(browser_state), - ios::SigninManagerFactory::GetForBrowserState(browser_state), + IdentityManagerFactory::GetForBrowserState(browser_state), browser_state->GetRequestContext()); }
diff --git a/ios/chrome/browser/payments/payment_response_helper_unittest.mm b/ios/chrome/browser/payments/payment_response_helper_unittest.mm index 2f543776..572ff69 100644 --- a/ios/chrome/browser/payments/payment_response_helper_unittest.mm +++ b/ios/chrome/browser/payments/payment_response_helper_unittest.mm
@@ -258,9 +258,9 @@ } // Tests that the phone number in the contact information of the generated -// PaymentResponse is formatted. +// PaymentResponse is formatted into E.164 if the number is valid. TEST_F(PaymentRequestPaymentResponseHelperTest, - PaymentResponseContactPhoneIsFormatted) { + PaymentResponseContactPhoneIsFormatted_IfNumberIsValid) { // Mock the consumer. id consumer = [OCMockObject mockForProtocol:@protocol(PaymentResponseHelperConsumer)]; @@ -270,7 +270,35 @@ @selector(paymentResponseHelperDidCompleteWithPaymentResponse:); [consumer_mock onSelector:selector callBlockExpectation:^(const PaymentResponse& response) { - EXPECT_EQ(base::ASCIIToUTF16("+15151231234"), response.payer_phone); + EXPECT_EQ(base::ASCIIToUTF16("+15152231234"), response.payer_phone); + }]; + + payment_request()->selected_contact_profile()->SetRawInfo( + autofill::PHONE_HOME_WHOLE_NUMBER, base::UTF8ToUTF16("(515) 223-1234")); + + payment_request()->web_payment_request().options.request_payer_name = false; + payment_request()->web_payment_request().options.request_payer_email = false; + PaymentResponseHelper payment_response_helper(consumer_mock, + payment_request()); + payment_response_helper.OnInstrumentDetailsReady(GetMethodName(), + GetStringifiedDetails()); +} + +// Tests that the phone number in the contact information of the generated +// PaymentResponse is not minimumly formatted(removing non-digit letters) if +// the number is invalid. +TEST_F(PaymentRequestPaymentResponseHelperTest, + PaymentResponseContactPhoneIsMinimumlyFormatted_IfNumberIsInValid) { + // Mock the consumer. + id consumer = + [OCMockObject mockForProtocol:@protocol(PaymentResponseHelperConsumer)]; + id consumer_mock([[PaymentResponseHelperConsumerMock alloc] + initWithRepresentedObject:consumer]); + SEL selector = + @selector(paymentResponseHelperDidCompleteWithPaymentResponse:); + [consumer_mock onSelector:selector + callBlockExpectation:^(const PaymentResponse& response) { + EXPECT_EQ(base::ASCIIToUTF16("5151231234"), response.payer_phone); }]; payment_request()->selected_contact_profile()->SetRawInfo(
diff --git a/ios/chrome/browser/ui/BUILD.gn b/ios/chrome/browser/ui/BUILD.gn index b7a6b86..4cd61297 100644 --- a/ios/chrome/browser/ui/BUILD.gn +++ b/ios/chrome/browser/ui/BUILD.gn
@@ -352,6 +352,7 @@ "//ios/chrome/browser/ui/tabs/requirements", "//ios/chrome/browser/ui/toolbar:toolbar_ui", "//ios/chrome/browser/ui/toolbar:toolbar_ui_broadcasting_util", + "//ios/chrome/browser/ui/toolbar/adaptive", "//ios/chrome/browser/ui/toolbar/clean:toolbar_ui", "//ios/chrome/browser/ui/toolbar/public", "//ios/chrome/browser/ui/toolbar/public:toolbar_base_feature",
diff --git a/ios/chrome/browser/ui/browser_view_controller.mm b/ios/chrome/browser/ui/browser_view_controller.mm index 529bdb6..cda0e70 100644 --- a/ios/chrome/browser/ui/browser_view_controller.mm +++ b/ios/chrome/browser/ui/browser_view_controller.mm
@@ -191,6 +191,8 @@ #import "ios/chrome/browser/ui/tabs/requirements/tab_strip_constants.h" #import "ios/chrome/browser/ui/tabs/requirements/tab_strip_presentation.h" #import "ios/chrome/browser/ui/tabs/tab_strip_legacy_coordinator.h" +#import "ios/chrome/browser/ui/toolbar/adaptive/primary_toolbar_coordinator.h" +#import "ios/chrome/browser/ui/toolbar/adaptive/secondary_toolbar_coordinator.h" #include "ios/chrome/browser/ui/toolbar/legacy_toolbar_coordinator.h" #import "ios/chrome/browser/ui/toolbar/legacy_toolbar_ui_updater.h" #import "ios/chrome/browser/ui/toolbar/public/primary_toolbar_coordinator.h" @@ -585,6 +587,12 @@ // Coordinator for the toolbar. LegacyToolbarCoordinator* _toolbarCoordinator; + // Coordinator for the primary toolbar, displayed on top. + PrimaryToolbarCoordinator* _topToolbarCoordinator; + + // Coordinator for the secondary toolbar, displayed on bottom. + SecondaryToolbarCoordinator* _bottomToolbarCoordinator; + // The toolbar UI updater for the toolbar managed by |_toolbarCoordinator|. LegacyToolbarUIUpdater* _toolbarUIUpdater; @@ -686,6 +694,9 @@ // Primary toolbar. @property(nonatomic, readonly) id<PrimaryToolbarCoordinator> primaryToolbarCoordinator; +// Secondary toolbar. +@property(nonatomic, readonly) + SecondaryToolbarCoordinator* secondaryToolbarCoordinator; // TODO(crbug.com/788705): Removes this property and associated calls. // Returns the LegacyToolbarCoordinator. This property is here to separate // methods which will be removed during cleanup to other methods. Uses this @@ -1253,10 +1264,10 @@ return results; if (!IsIPadIdiom()) { - if (self.primaryToolbarCoordinator.toolbarViewController.view) { + if (self.primaryToolbarCoordinator.viewController.view) { [results addObject:[HeaderDefinition definitionWithView:self.primaryToolbarCoordinator - .toolbarViewController.view + .viewController.view headerBehaviour:Hideable heightAdjustment:0.0 inset:0.0]]; @@ -1268,10 +1279,10 @@ heightAdjustment:0.0 inset:0.0]]; } - if (self.primaryToolbarCoordinator.toolbarViewController.view) { + if (self.primaryToolbarCoordinator.viewController.view) { [results addObject:[HeaderDefinition definitionWithView:self.primaryToolbarCoordinator - .toolbarViewController.view + .viewController.view headerBehaviour:Hideable heightAdjustment:0.0 inset:0.0]]; @@ -1298,7 +1309,15 @@ } - (id<PrimaryToolbarCoordinator>)primaryToolbarCoordinator { - return _toolbarCoordinator; + if (base::FeatureList::IsEnabled(kAdaptiveToolbar)) { + return _topToolbarCoordinator; + } else { + return _toolbarCoordinator; + } +} + +- (SecondaryToolbarCoordinator*)secondaryToolbarCoordinator { + return _bottomToolbarCoordinator; } - (LegacyToolbarCoordinator*)legacyToolbarCoordinator { @@ -1490,6 +1509,8 @@ self.tabStripCoordinator = nil; [_toolbarCoordinator stop]; _toolbarCoordinator = nil; + [_topToolbarCoordinator stop]; + _topToolbarCoordinator = nil; self.tabStripView = nil; _infoBarContainer = nil; _readingListMenuNotifier = nil; @@ -1696,6 +1717,7 @@ _readingListCoordinator = nil; self.recentTabsCoordinator = nil; _toolbarCoordinator = nil; + _topToolbarCoordinator = nil; [_toolbarUIUpdater stopUpdating]; _toolbarUIUpdater = nil; _toolbarModelDelegate = nil; @@ -1911,25 +1933,43 @@ new ToolbarModelDelegateIOS([_model webStateList])); _toolbarModelIOS.reset([_dependencyFactory newToolbarModelIOSWithDelegate:_toolbarModelDelegate.get()]); - _toolbarCoordinator = [[LegacyToolbarCoordinator alloc] - initWithBaseViewController:self - toolsMenuConfigurationProvider:self - dispatcher:self.dispatcher - browserState:_browserState]; + + if (base::FeatureList::IsEnabled(kAdaptiveToolbar)) { + _topToolbarCoordinator = [[PrimaryToolbarCoordinator alloc] + initWithToolsMenuConfigurationProvider:self + dispatcher:self.dispatcher + browserState:_browserState]; + _topToolbarCoordinator.delegate = self; + _topToolbarCoordinator.URLLoader = self; + _topToolbarCoordinator.webStateList = [_model webStateList]; + [_topToolbarCoordinator start]; + _bottomToolbarCoordinator = [[SecondaryToolbarCoordinator alloc] + initWithBaseViewController:nil + browserState:_browserState]; + _bottomToolbarCoordinator.dispatcher = self.dispatcher; + [_bottomToolbarCoordinator start]; + } else { + _toolbarCoordinator = [[LegacyToolbarCoordinator alloc] + initWithBaseViewController:self + toolsMenuConfigurationProvider:self + dispatcher:self.dispatcher + browserState:_browserState]; + [_toolbarCoordinator + setToolbarController: + [_dependencyFactory + newToolbarControllerWithDelegate:self + urlLoader:self + dispatcher:self.dispatcher]]; + + [_toolbarCoordinator start]; + } self.sideSwipeController.toolbarInteractionHandler = self.primaryToolbarCoordinator; - [_toolbarCoordinator - setToolbarController: - [_dependencyFactory - newToolbarControllerWithDelegate:self - urlLoader:self - dispatcher:self.dispatcher]]; [_dispatcher startDispatchingToTarget:self.primaryToolbarCoordinator forProtocol:@protocol(OmniboxFocuser)]; [self.legacyToolbarCoordinator setTabCount:[_model count]]; - [_toolbarCoordinator start]; [self updateBroadcastState]; if (_voiceSearchController) _voiceSearchController->SetDelegate( @@ -1968,15 +2008,25 @@ [self.legacyToolbarCoordinator adjustToolbarHeight]; self.primaryToolbarOffsetConstraint = - [self.primaryToolbarCoordinator.toolbarViewController.view.topAnchor + [self.primaryToolbarCoordinator.viewController.view.topAnchor constraintEqualToAnchor:topAnchor]; [NSLayoutConstraint activateConstraints:@[ self.primaryToolbarOffsetConstraint, - [self.primaryToolbarCoordinator.toolbarViewController.view.leadingAnchor + [self.primaryToolbarCoordinator.viewController.view.leadingAnchor constraintEqualToAnchor:[self view].leadingAnchor], - [self.primaryToolbarCoordinator.toolbarViewController.view.trailingAnchor + [self.primaryToolbarCoordinator.viewController.view.trailingAnchor constraintEqualToAnchor:[self view].trailingAnchor], ]]; + if (self.secondaryToolbarCoordinator) { + [NSLayoutConstraint activateConstraints:@[ + [self.secondaryToolbarCoordinator.viewController.view.leadingAnchor + constraintEqualToAnchor:[self view].leadingAnchor], + [self.secondaryToolbarCoordinator.viewController.view.trailingAnchor + constraintEqualToAnchor:[self view].trailingAnchor], + [self.secondaryToolbarCoordinator.viewController.view.bottomAnchor + constraintEqualToAnchor:[self view].bottomAnchor], + ]]; + } [[self view] layoutIfNeeded]; } @@ -2075,17 +2125,21 @@ // Position the toolbar next, either at the top of the browser view or // directly under the tabstrip. - if (initialLayout) - [self addChildViewController:_toolbarCoordinator.toolbarViewController]; + if (initialLayout) { + [self addChildViewController:self.primaryToolbarCoordinator.viewController]; + if (self.secondaryToolbarCoordinator) + [self addChildViewController:self.secondaryToolbarCoordinator + .viewController]; + } if (!IsSafeAreaCompatibleToolbarEnabled()) { CGFloat minY = self.headerOffset; if (self.tabStripView) { minY += CGRectGetHeight([self.tabStripView frame]); } - CGRect toolbarFrame = _toolbarCoordinator.toolbarViewController.view.frame; + CGRect toolbarFrame = _toolbarCoordinator.viewController.view.frame; toolbarFrame.origin = CGPointMake(0, minY); toolbarFrame.size.width = widthOfView; - [_toolbarCoordinator.toolbarViewController.view setFrame:toolbarFrame]; + [_toolbarCoordinator.viewController.view setFrame:toolbarFrame]; } // Place the infobar container above the content area. @@ -2096,17 +2150,28 @@ // Place the toolbar controller above the infobar container and adds the // layout guides. if (initialLayout) { - [[self view] insertSubview:_toolbarCoordinator.toolbarViewController.view - aboveSubview:infoBarContainerView]; + [[self view] + insertSubview:self.primaryToolbarCoordinator.viewController.view + aboveSubview:infoBarContainerView]; + if (self.secondaryToolbarCoordinator) { + [[self view] + insertSubview:self.secondaryToolbarCoordinator.viewController.view + aboveSubview:infoBarContainerView]; + } AddNamedGuide(kOmniboxGuide, self.view); AddNamedGuide(kBackButtonGuide, self.view); AddNamedGuide(kForwardButtonGuide, self.view); AddNamedGuide(kToolsMenuGuide, self.view); AddNamedGuide(kTabSwitcherGuide, self.view); } - if (initialLayout) - [_toolbarCoordinator.toolbarViewController + if (initialLayout) { + [self.primaryToolbarCoordinator.viewController didMoveToParentViewController:self]; + if (self.secondaryToolbarCoordinator) { + [self.secondaryToolbarCoordinator.viewController + didMoveToParentViewController:self]; + } + } // Adjust the content area to be under the toolbar, for fullscreen or below // the toolbar is not fullscreen. @@ -2215,8 +2280,7 @@ ![self.primaryToolbarCoordinator isOmniboxFirstResponder] && ![self.primaryToolbarCoordinator showingOmniboxPopup]; } - [self.primaryToolbarCoordinator.toolbarViewController.view - setHidden:hideToolbar]; + [self.primaryToolbarCoordinator.viewController.view setHidden:hideToolbar]; } } @@ -2284,8 +2348,7 @@ for (HeaderDefinition* header in headers) { CGFloat yOrigin = height - headerOffset - header.inset; BOOL isPrimaryToolbar = - header.view == - self.primaryToolbarCoordinator.toolbarViewController.view; + header.view == self.primaryToolbarCoordinator.viewController.view; // Make sure the toolbarView's constraints are also updated. Leaving the // -setFrame call to minimize changes in this CL -- otherwise the way // toolbar_view manages it's alpha changes would also need to be updated. @@ -2497,8 +2560,6 @@ - (void)presentNewIncognitoTabTipBubble { DCHECK(self.browserState); - DCHECK([self.legacyToolbarCoordinator - respondsToSelector:@selector(anchorPointForToolsMenuButton:)]); // If the BVC is not visible, do not present the bubble. if (!self.viewVisible) return; @@ -2522,6 +2583,8 @@ toolsButtonAnchor = [guide.owningView convertPoint:anchorPoint toView:guide.owningView.window]; } else { + DCHECK([self.legacyToolbarCoordinator + respondsToSelector:@selector(anchorPointForToolsMenuButton:)]); toolsButtonAnchor = [self.legacyToolbarCoordinator anchorPointForToolsMenuButton:BubbleArrowDirectionUp]; } @@ -3631,11 +3694,11 @@ } - (UIView*)headerView { - return self.primaryToolbarCoordinator.toolbarViewController.view; + return self.primaryToolbarCoordinator.viewController.view; } - (UIView*)toolbarSnapshotView { - return [self.primaryToolbarCoordinator.toolbarViewController.view + return [self.primaryToolbarCoordinator.viewController.view snapshotViewAfterScreenUpdates:NO]; } @@ -4664,12 +4727,12 @@ } - (CGRect)toolbarFrame { - return _toolbarCoordinator.toolbarViewController.view.frame; + return _toolbarCoordinator.viewController.view.frame; } - (id<ToolbarSnapshotProviding>)toolbarSnapshotProvider { id<ToolbarSnapshotProviding> toolbarSnapshotProvider = nil; - if (_toolbarCoordinator.toolbarViewController.view.hidden) { + if (_toolbarCoordinator.viewController.view.hidden) { Tab* currentTab = [_model currentTab]; if (currentTab.webState && UrlHasChromeScheme(currentTab.webState->GetLastCommittedURL())) { @@ -5126,7 +5189,7 @@ BOOL seenInfoBarContainer = NO; BOOL seenContentArea = NO; for (UIView* view in views.subviews) { - if (view == _toolbarCoordinator.toolbarViewController.view) + if (view == _toolbarCoordinator.viewController.view) seenToolbar = YES; else if (view == _infoBarContainer->view()) seenInfoBarContainer = YES;
diff --git a/ios/chrome/browser/ui/payments/address_edit_mediator.mm b/ios/chrome/browser/ui/payments/address_edit_mediator.mm index 1b178f2c..dbbc9f1 100644 --- a/ios/chrome/browser/ui/payments/address_edit_mediator.mm +++ b/ios/chrome/browser/ui/payments/address_edit_mediator.mm
@@ -192,8 +192,8 @@ case AutofillUITypeProfileHomePhoneWholeNumber: { const std::string selectedCountryCode = base::SysNSStringToUTF8(self.selectedCountryCode); - if (!autofill::IsValidPhoneNumber(base::SysNSStringToUTF16(field.value), - selectedCountryCode)) { + if (!autofill::IsPossiblePhoneNumber( + base::SysNSStringToUTF16(field.value), selectedCountryCode)) { return l10n_util::GetNSString( IDS_PAYMENTS_PHONE_INVALID_VALIDATION_MESSAGE); }
diff --git a/ios/chrome/browser/ui/payments/contact_info_edit_mediator.mm b/ios/chrome/browser/ui/payments/contact_info_edit_mediator.mm index 6874804..adcd91ed 100644 --- a/ios/chrome/browser/ui/payments/contact_info_edit_mediator.mm +++ b/ios/chrome/browser/ui/payments/contact_info_edit_mediator.mm
@@ -116,8 +116,8 @@ const std::string countryCode = autofill::AutofillCountry::CountryCodeForLocale( self.paymentRequest->GetApplicationLocale()); - if (!autofill::IsValidPhoneNumber(base::SysNSStringToUTF16(field.value), - countryCode)) { + if (!autofill::IsPossiblePhoneNumber( + base::SysNSStringToUTF16(field.value), countryCode)) { return l10n_util::GetNSString( IDS_PAYMENTS_PHONE_INVALID_VALIDATION_MESSAGE); }
diff --git a/ios/chrome/browser/ui/toolbar/adaptive/BUILD.gn b/ios/chrome/browser/ui/toolbar/adaptive/BUILD.gn new file mode 100644 index 0000000..95c31d4 --- /dev/null +++ b/ios/chrome/browser/ui/toolbar/adaptive/BUILD.gn
@@ -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. + +source_set("adaptive") { + sources = [ + "primary_toolbar_coordinator.h", + "primary_toolbar_coordinator.mm", + "secondary_toolbar_coordinator.h", + "secondary_toolbar_coordinator.mm", + ] + deps = [ + ":adaptive_ui", + "//base", + "//components/google/core/browser", + "//ios/chrome/browser/browser_state", + "//ios/chrome/browser/ui", + "//ios/chrome/browser/ui/coordinators:chrome_coordinators", + "//ios/chrome/browser/ui/location_bar", + "//ios/chrome/browser/ui/omnibox", + "//ios/chrome/browser/ui/omnibox:omnibox_internal", + "//ios/chrome/browser/ui/omnibox/popup", + "//ios/chrome/browser/ui/toolbar", + "//ios/chrome/browser/ui/toolbar/clean:toolbar", + "//ios/chrome/browser/ui/toolbar/clean:toolbar_components_ui", + "//ios/chrome/browser/ui/toolbar/public", + "//ios/chrome/browser/web_state_list", + "//ios/web", + ] + configs += [ "//build/config/compiler:enable_arc" ] +} + +source_set("adaptive_ui") { + sources = [ + "primary_toolbar_view.h", + "primary_toolbar_view.mm", + "primary_toolbar_view_controller.h", + "primary_toolbar_view_controller.mm", + "secondary_toolbar_view.h", + "secondary_toolbar_view.mm", + "secondary_toolbar_view_controller.h", + "secondary_toolbar_view_controller.mm", + ] + deps = [ + "//base", + "//ios/chrome/browser/ui/toolbar/clean:toolbar_components_ui", + "//ios/chrome/browser/ui/toolbar/public", + "//ios/chrome/browser/ui/util:constraints_ui", + ] + configs += [ "//build/config/compiler:enable_arc" ] +}
diff --git a/ios/chrome/browser/ui/toolbar/adaptive/primary_toolbar_coordinator.h b/ios/chrome/browser/ui/toolbar/adaptive/primary_toolbar_coordinator.h new file mode 100644 index 0000000..ea370e9 --- /dev/null +++ b/ios/chrome/browser/ui/toolbar/adaptive/primary_toolbar_coordinator.h
@@ -0,0 +1,55 @@ +// 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_TOOLBAR_ADAPTIVE_PRIMARY_TOOLBAR_COORDINATOR_H_ +#define IOS_CHROME_BROWSER_UI_TOOLBAR_ADAPTIVE_PRIMARY_TOOLBAR_COORDINATOR_H_ + +#import <UIKit/UIKit.h> + +#import "ios/chrome/browser/ui/coordinators/chrome_coordinator.h" +#import "ios/chrome/browser/ui/toolbar/public/primary_toolbar_coordinator.h" + +@protocol ApplicationCommands; +@protocol BrowserCommands; +@class CommandDispatcher; +@protocol ToolbarCommands; +@protocol ToolbarCoordinatorDelegate; +@protocol ToolsMenuConfigurationProvider; +@protocol UrlLoader; +class WebStateList; + +// Coordinator for the primary toolbar. In an adaptive toolbar paradigm, this is +// the toolbar always displayed. +@interface PrimaryToolbarCoordinator + : ChromeCoordinator<PrimaryToolbarCoordinator> + +- (instancetype) +initWithToolsMenuConfigurationProvider: + (id<ToolsMenuConfigurationProvider>)configurationProvider + dispatcher:(CommandDispatcher*)dispatcher + browserState:(ios::ChromeBrowserState*)browserState + NS_DESIGNATED_INITIALIZER; +- (instancetype)initWithBaseViewController:(UIViewController*)viewController + NS_UNAVAILABLE; +- (instancetype)initWithBaseViewController:(UIViewController*)viewController + browserState: + (ios::ChromeBrowserState*)browserState + NS_UNAVAILABLE; + +// Dispatcher. +@property(nonatomic, weak) + id<ApplicationCommands, BrowserCommands, ToolbarCommands> + dispatcher; +// The web state list this ToolbarCoordinator is handling. +@property(nonatomic, assign) WebStateList* webStateList; +// Delegate for this coordinator. +// TODO(crbug.com/799446): Change this. +@property(nonatomic, weak) id<ToolbarCoordinatorDelegate> delegate; +// URL loader for the toolbar. +// TODO(crbug.com/799446): Remove this. +@property(nonatomic, weak) id<UrlLoader> URLLoader; + +@end + +#endif // IOS_CHROME_BROWSER_UI_TOOLBAR_ADAPTIVE_PRIMARY_TOOLBAR_COORDINATOR_H_
diff --git a/ios/chrome/browser/ui/toolbar/adaptive/primary_toolbar_coordinator.mm b/ios/chrome/browser/ui/toolbar/adaptive/primary_toolbar_coordinator.mm new file mode 100644 index 0000000..8608ceaa --- /dev/null +++ b/ios/chrome/browser/ui/toolbar/adaptive/primary_toolbar_coordinator.mm
@@ -0,0 +1,255 @@ +// 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/toolbar/adaptive/primary_toolbar_coordinator.h" + +#import <CoreLocation/CoreLocation.h> + +#include "base/metrics/histogram_macros.h" +#include "base/strings/sys_string_conversions.h" +#include "components/google/core/browser/google_util.h" +#include "ios/chrome/browser/browser_state/chrome_browser_state.h" +#import "ios/chrome/browser/ui/location_bar/location_bar_coordinator.h" +#include "ios/chrome/browser/ui/omnibox/location_bar_controller_impl.h" +#include "ios/chrome/browser/ui/omnibox/location_bar_delegate.h" +#import "ios/chrome/browser/ui/omnibox/omnibox_popup_positioner.h" +#import "ios/chrome/browser/ui/omnibox/popup/omnibox_popup_coordinator.h" +#import "ios/chrome/browser/ui/toolbar/adaptive/primary_toolbar_view_controller.h" +#import "ios/chrome/browser/ui/toolbar/clean/toolbar_button_factory.h" +#import "ios/chrome/browser/ui/toolbar/clean/toolbar_button_visibility_configuration.h" +#import "ios/chrome/browser/ui/toolbar/clean/toolbar_coordinator_delegate.h" +#import "ios/chrome/browser/ui/toolbar/public/web_toolbar_controller_constants.h" +#include "ios/chrome/browser/ui/toolbar/toolbar_model_ios.h" +#import "ios/chrome/browser/ui/url_loader.h" +#import "ios/chrome/browser/web_state_list/web_state_list.h" +#include "ios/web/public/referrer.h" + +#if !defined(__has_feature) || !__has_feature(objc_arc) +#error "This file requires ARC support." +#endif + +@interface PrimaryToolbarCoordinator ()<LocationBarDelegate, + OmniboxPopupPositioner> { + std::unique_ptr<LocationBarControllerImpl> _locationBar; +} + +// Whether this coordinator has been started. +@property(nonatomic, assign) BOOL started; +// The Toolbar view controller owned by this coordinator. +@property(nonatomic, strong) + PrimaryToolbarViewController* toolbarViewController; +// The coordinator for the location bar in the toolbar. +@property(nonatomic, strong) LocationBarCoordinator* locationBarCoordinator; +// Coordinator for the omnibox popup. +@property(nonatomic, strong) OmniboxPopupCoordinator* omniboxPopupCoordinator; + +@end + +@implementation PrimaryToolbarCoordinator +@synthesize delegate = _delegate; +@synthesize dispatcher = _dispatcher; +@synthesize locationBarCoordinator = _locationBarCoordinator; +@synthesize omniboxPopupCoordinator = _omniboxPopupCoordinator; +@synthesize started = _started; +@synthesize toolbarViewController = _toolbarViewController; +@synthesize URLLoader = _URLLoader; +@synthesize webStateList = _webStateList; + +#pragma mark - ChromeCoordinator + +- (instancetype) +initWithToolsMenuConfigurationProvider:(id)configurationProvider + dispatcher:(id)dispatcher + browserState:(ios::ChromeBrowserState*)browserState { + self = [super initWithBaseViewController:nil browserState:browserState]; + if (self) { + // TODO(crbug.com/799422): Initialize the toolsMenu. + _dispatcher = dispatcher; + } + return self; +} + +- (void)start { + if (self.started) + return; + + self.started = YES; + BOOL isIncognito = self.browserState->IsOffTheRecord(); + + self.locationBarCoordinator = [[LocationBarCoordinator alloc] init]; + self.locationBarCoordinator.browserState = self.browserState; + self.locationBarCoordinator.dispatcher = self.dispatcher; + [self.locationBarCoordinator start]; + + // TODO(crbug.com/785253): Move this to the LocationBarCoordinator once it is + // created. + _locationBar = std::make_unique<LocationBarControllerImpl>( + self.locationBarCoordinator.locationBarView, self.browserState, self, + self.dispatcher); + self.omniboxPopupCoordinator = _locationBar->CreatePopupCoordinator(self); + [self.omniboxPopupCoordinator start]; + // End of TODO(crbug.com/785253):. + + ToolbarStyle style = isIncognito ? INCOGNITO : NORMAL; + ToolbarButtonFactory* buttonFactory = + [[ToolbarButtonFactory alloc] initWithStyle:style]; + buttonFactory.dispatcher = self.dispatcher; + buttonFactory.visibilityConfiguration = + [[ToolbarButtonVisibilityConfiguration alloc] initWithType:PRIMARY]; + + self.toolbarViewController = [[PrimaryToolbarViewController alloc] + initWithButtonFactory:buttonFactory]; + self.toolbarViewController.dispatcher = self.dispatcher; + self.toolbarViewController.locationBarView = + self.locationBarCoordinator.locationBarView; +} + +#pragma mark - Property Accessors + +- (UIViewController*)viewController { + return self.toolbarViewController; +} + +#pragma mark - PrimaryToolbarCoordinator + +- (id<VoiceSearchControllerDelegate>)voiceSearchDelegate { + // TODO(crbug.com/799438): Implement that. + return nil; +} + +- (id<QRScannerResultLoading>)QRScannerResultLoader { + // TODO(crbug.com/799438): Implement that. + return nil; +} + +- (id<TabHistoryPositioner>)tabHistoryPositioner { + // TODO(crbug.com/799438): Implement that. + return nil; +} + +- (id<TabHistoryUIUpdater>)tabHistoryUIUpdater { + // TODO(crbug.com/799438): Implement that. + return nil; +} + +- (id<ActivityServicePositioner>)activityServicePositioner { + // TODO(crbug.com/799438): Implement that. + return nil; +} + +- (void)showPrerenderingAnimation { + // TODO(crbug.com/799438): Implement that. +} + +- (BOOL)isOmniboxFirstResponder { + return + [self.locationBarCoordinator.locationBarView.textField isFirstResponder]; +} + +- (BOOL)showingOmniboxPopup { + OmniboxViewIOS* omniboxViewIOS = + static_cast<OmniboxViewIOS*>(_locationBar.get()->GetLocationEntry()); + return omniboxViewIOS->IsPopupOpen(); +} + +#pragma mark - OmniboxFocuser + +- (void)focusOmnibox { + // TODO(crbug.com/799438): Implement that. +} + +- (void)cancelOmniboxEdit { + // TODO(crbug.com/799438): Implement that. +} + +- (void)focusFakebox { + // TODO(crbug.com/799438): Implement that. +} + +- (void)onFakeboxBlur { + // TODO(crbug.com/799438): Implement that. +} + +- (void)onFakeboxAnimationComplete { + // TODO(crbug.com/799438): Implement that. +} + +#pragma mark - SideSwipeToolbarInteracting + +- (UIView*)toolbarView { + return self.viewController.view; +} + +- (BOOL)canBeginToolbarSwipe { + return ![self isOmniboxFirstResponder] && ![self showingOmniboxPopup]; +} + +- (UIImage*)toolbarSideSwipeSnapshotForTab:(Tab*)tab { + // TODO(crbug.com/799438): Implement that. + return nil; +} + +// TODO(crbug.com/786940): This protocol should move to the ViewController +// owning the Toolbar. This can wait until the omnibox and toolbar refactoring +// is more advanced. +#pragma mark OmniboxPopupPositioner methods. + +- (UIView*)popupAnchorView { + return self.toolbarViewController.view; +} + +#pragma mark - LocationBarDelegate + +- (void)loadGURLFromLocationBar:(const GURL&)url + transition:(ui::PageTransition)transition { + if (url.SchemeIs(url::kJavaScriptScheme)) { + // Evaluate the URL as JavaScript if its scheme is JavaScript. + NSString* jsToEval = [base::SysUTF8ToNSString(url.GetContent()) + stringByRemovingPercentEncoding]; + [self.URLLoader loadJavaScriptFromLocationBar:jsToEval]; + } else { + // When opening a URL, force the omnibox to resign first responder. This + // will also close the popup. + + // TODO(crbug.com/785244): Is it ok to call |cancelOmniboxEdit| after + // |loadURL|? It doesn't seem to be causing major problems. If we call + // cancel before load, then any prerendered pages get destroyed before the + // call to load. + [self.URLLoader loadURL:url + referrer:web::Referrer() + transition:transition + rendererInitiated:NO]; + + if (google_util::IsGoogleSearchUrl(url)) { + UMA_HISTOGRAM_ENUMERATION( + kOmniboxQueryLocationAuthorizationStatusHistogram, + [CLLocationManager authorizationStatus], + kLocationAuthorizationStatusCount); + } + } + [self cancelOmniboxEdit]; +} + +- (void)locationBarHasBecomeFirstResponder { + [self.delegate locationBarDidBecomeFirstResponder]; +} + +- (void)locationBarHasResignedFirstResponder { + [self.delegate locationBarDidResignFirstResponder]; +} + +- (void)locationBarBeganEdit { + [self.delegate locationBarBeganEdit]; +} + +- (web::WebState*)getWebState { + return self.webStateList->GetActiveWebState(); +} + +- (ToolbarModel*)toolbarModel { + ToolbarModelIOS* toolbarModelIOS = [self.delegate toolbarModelIOS]; + return toolbarModelIOS ? toolbarModelIOS->GetToolbarModel() : nullptr; +} + +@end
diff --git a/ios/chrome/browser/ui/toolbar/adaptive/primary_toolbar_view.h b/ios/chrome/browser/ui/toolbar/adaptive/primary_toolbar_view.h new file mode 100644 index 0000000..f4e34c4 --- /dev/null +++ b/ios/chrome/browser/ui/toolbar/adaptive/primary_toolbar_view.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 IOS_CHROME_BROWSER_UI_TOOLBAR_ADAPTIVE_PRIMARY_TOOLBAR_VIEW_H_ +#define IOS_CHROME_BROWSER_UI_TOOLBAR_ADAPTIVE_PRIMARY_TOOLBAR_VIEW_H_ + +#import <UIKit/UIKit.h> + +@class ToolbarButton; +@class ToolbarButtonFactory; + +// View for the primary toolbar. In an adaptive toolbar paradigm, this is the +// toolbar always presented. +@interface PrimaryToolbarView : UIView + +// Top anchor at the bottom of the safeAreaLayoutGuide. Used so views don't +// overlap with the Status Bar. +@property(nonatomic, strong) NSLayoutYAxisAnchor* topSafeAnchor; +// Factory used to create the buttons. +@property(nonatomic, strong) ToolbarButtonFactory* buttonFactory; +// The location bar view, containing the omnibox. +@property(nonatomic, strong) UIView* locationBarView; + +// Property to get all the buttons in this view. +@property(nonatomic, readonly) NSArray<ToolbarButton*>* allButtons; + +@end + +#endif // IOS_CHROME_BROWSER_UI_TOOLBAR_ADAPTIVE_PRIMARY_TOOLBAR_VIEW_H_
diff --git a/ios/chrome/browser/ui/toolbar/adaptive/primary_toolbar_view.mm b/ios/chrome/browser/ui/toolbar/adaptive/primary_toolbar_view.mm new file mode 100644 index 0000000..d9cf5ac --- /dev/null +++ b/ios/chrome/browser/ui/toolbar/adaptive/primary_toolbar_view.mm
@@ -0,0 +1,208 @@ +// 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/toolbar/adaptive/primary_toolbar_view.h" + +#include "base/logging.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_tools_menu_button.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 PrimaryToolbarView () +// Container for the location bar. +@property(nonatomic, strong) UIView* locationBarContainer; + +// StackView containing the leading buttons (relative to the location bar). It +// should only contain ToolbarButtons. +@property(nonatomic, strong) UIStackView* leadingStackView; +// Buttons from the leading stack view. +@property(nonatomic, strong) NSArray<ToolbarButton*>* leadingStackViewButtons; +// StackView containing the trailing buttons (relative to the location bar). It +// should only contain ToolbarButtons. +@property(nonatomic, strong) UIStackView* trailingStackView; +// Buttons from the trailing stack view. +@property(nonatomic, strong) NSArray<ToolbarButton*>* trailingStackViewButtons; + +#pragma mark** Buttons in the leading stack view. ** +// Button to navigate back. +@property(nonatomic, strong) ToolbarButton* backButton; +// Button to navigate forward, leading position. +@property(nonatomic, strong) ToolbarButton* forwardLeadingButton; +// Button to display the TabGrid. +@property(nonatomic, strong) ToolbarButton* tabGridButton; +// Button to stop the loading of the page. +@property(nonatomic, strong) ToolbarButton* stopButton; +// Button to reload the page. +@property(nonatomic, strong) ToolbarButton* reloadButton; + +#pragma mark** Buttons in the trailing stack view. ** +// Button to navigate forward, trailing position. +@property(nonatomic, strong) ToolbarButton* forwardTrailingButton; +// Button to display the share menu. +@property(nonatomic, strong) ToolbarButton* shareButton; +// Button to manage the bookmarks of this page. +@property(nonatomic, strong) ToolbarButton* bookmarkButton; +// Button to display the tools menu, redefined as readwrite. +@property(nonatomic, strong) ToolbarToolsMenuButton* toolsMenuButton; + +@end + +@implementation PrimaryToolbarView + +@synthesize locationBarView = _locationBarView; +@synthesize topSafeAnchor = _topSafeAnchor; +@synthesize buttonFactory = _buttonFactory; +@synthesize allButtons = _allButtons; +@synthesize leadingStackView = _leadingStackView; +@synthesize leadingStackViewButtons = _leadingStackViewButtons; +@synthesize backButton = _backButton; +@synthesize forwardLeadingButton = _forwardLeadingButton; +@synthesize tabGridButton = _tabGridButton; +@synthesize stopButton = _stopButton; +@synthesize reloadButton = _reloadButton; +@synthesize locationBarContainer = _locationBarContainer; +@synthesize trailingStackView = _trailingStackView; +@synthesize trailingStackViewButtons = _trailingStackViewButtons; +@synthesize forwardTrailingButton = _forwardTrailingButton; +@synthesize shareButton = _shareButton; +@synthesize bookmarkButton = _bookmarkButton; +@synthesize toolsMenuButton = _toolsMenuButton; + +#pragma mark - UIView + +- (void)willMoveToSuperview:(UIView*)newSuperview { + [self setUp]; + [super willMoveToSuperview:newSuperview]; +} + +#pragma mark - Setup + +// Sets all the subviews and constraints of this view. +- (void)setUp { + if (self.subviews.count > 0) { + // Setup the view only once. + return; + } + DCHECK(self.buttonFactory); + + self.translatesAutoresizingMaskIntoConstraints = NO; + self.locationBarContainer = [[UIView alloc] init]; + self.locationBarContainer.backgroundColor = [UIColor whiteColor]; + [self.locationBarContainer + setContentHuggingPriority:UILayoutPriorityDefaultLow + forAxis:UILayoutConstraintAxisHorizontal]; + self.locationBarContainer.translatesAutoresizingMaskIntoConstraints = NO; + [self addSubview:self.locationBarContainer]; + + [self setUpLeadingStackView]; + [self setUpTrailingStackView]; + + [self setUpConstraints]; +} + +// Sets the leading stack view. +- (void)setUpLeadingStackView { + self.backButton = [self.buttonFactory backButton]; + self.forwardLeadingButton = [self.buttonFactory forwardButton]; + self.tabGridButton = [self.buttonFactory tabSwitcherStripButton]; + self.stopButton = [self.buttonFactory stopButton]; + self.stopButton.hiddenInCurrentState = YES; + self.reloadButton = [self.buttonFactory reloadButton]; + + self.leadingStackViewButtons = @[ + self.backButton, self.forwardLeadingButton, self.tabGridButton, + self.stopButton, self.reloadButton + ]; + self.leadingStackView = [[UIStackView alloc] + initWithArrangedSubviews:self.leadingStackViewButtons]; + self.leadingStackView.translatesAutoresizingMaskIntoConstraints = NO; + [self addSubview:self.leadingStackView]; +} + +// Sets the trailing stack view. +- (void)setUpTrailingStackView { + self.forwardTrailingButton = [self.buttonFactory forwardButton]; + self.shareButton = [self.buttonFactory shareButton]; + self.bookmarkButton = [self.buttonFactory bookmarkButton]; + self.toolsMenuButton = [self.buttonFactory toolsMenuButton]; + + self.trailingStackViewButtons = @[ + self.forwardTrailingButton, self.shareButton, self.bookmarkButton, + self.toolsMenuButton + ]; + self.trailingStackView = [[UIStackView alloc] + initWithArrangedSubviews:self.trailingStackViewButtons]; + self.trailingStackView.translatesAutoresizingMaskIntoConstraints = NO; + [self addSubview:self.trailingStackView]; +} + +// Sets the constraints up. +- (void)setUpConstraints { + id<LayoutGuideProvider> safeArea = SafeAreaLayoutGuideForView(self); + + // Leading StackView constraints + [NSLayoutConstraint activateConstraints:@[ + [self.leadingStackView.leadingAnchor + constraintEqualToAnchor:safeArea.leadingAnchor], + [self.leadingStackView.bottomAnchor + constraintEqualToAnchor:safeArea.bottomAnchor], + [self.leadingStackView.topAnchor + constraintEqualToAnchor:self.topSafeAnchor], + ]]; + + // LocationBar constraints. + [NSLayoutConstraint activateConstraints:@[ + [self.locationBarContainer.leadingAnchor + constraintEqualToAnchor:self.leadingStackView.trailingAnchor], + [self.locationBarContainer.trailingAnchor + constraintEqualToAnchor:self.trailingStackView.leadingAnchor], + [self.locationBarContainer.bottomAnchor + constraintEqualToAnchor:safeArea.bottomAnchor], + [self.locationBarContainer.topAnchor + constraintEqualToAnchor:self.topSafeAnchor], + [self.locationBarContainer.heightAnchor + constraintEqualToConstant:kToolbarHeight], + ]]; + + // Trailing StackView constraints. + [NSLayoutConstraint activateConstraints:@[ + [self.trailingStackView.trailingAnchor + constraintEqualToAnchor:safeArea.trailingAnchor], + [self.trailingStackView.bottomAnchor + constraintEqualToAnchor:safeArea.bottomAnchor], + [self.trailingStackView.topAnchor + constraintEqualToAnchor:self.topSafeAnchor], + ]]; +} + +#pragma mark - Property accessors + +- (void)setLocationBarView:(UIView*)locationBarView { + if (_locationBarView == locationBarView) { + return; + } + [_locationBarView removeFromSuperview]; + + locationBarView.translatesAutoresizingMaskIntoConstraints = NO; + [locationBarView setContentHuggingPriority:UILayoutPriorityDefaultLow + forAxis:UILayoutConstraintAxisHorizontal]; + [self.locationBarContainer addSubview:locationBarView]; + AddSameConstraints(self.locationBarContainer, locationBarView); + _locationBarView = locationBarView; +} + +- (NSArray<ToolbarButton*>*)allButtons { + if (!_allButtons) { + _allButtons = [self.leadingStackViewButtons + arrayByAddingObjectsFromArray:self.trailingStackViewButtons]; + } + return _allButtons; +} + +@end
diff --git a/ios/chrome/browser/ui/toolbar/adaptive/primary_toolbar_view_controller.h b/ios/chrome/browser/ui/toolbar/adaptive/primary_toolbar_view_controller.h new file mode 100644 index 0000000..4de7eb2 --- /dev/null +++ b/ios/chrome/browser/ui/toolbar/adaptive/primary_toolbar_view_controller.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_TOOLBAR_ADAPTIVE_PRIMARY_TOOLBAR_VIEW_CONTROLLER_H_ +#define IOS_CHROME_BROWSER_UI_TOOLBAR_ADAPTIVE_PRIMARY_TOOLBAR_VIEW_CONTROLLER_H_ + +#import <UIKit/UIKit.h> + +@protocol ApplicationCommands; +@class ToolbarButtonFactory; +@protocol BrowserCommands; + +// ViewController for the primary toolbar. In an adaptive toolbar paradigm, this +// is the toolbar always presented. +@interface PrimaryToolbarViewController : UIViewController + +- (instancetype)initWithButtonFactory:(ToolbarButtonFactory*)buttonFactory; + +- (instancetype)init NS_UNAVAILABLE; +- (instancetype)initWithCoder:(NSCoder*)aDecoder NS_UNAVAILABLE; +- (instancetype)initWithNibName:(NSString*)nibNameOrNil + bundle:(NSBundle*)nibBundleOrNil NS_UNAVAILABLE; + +// Dispatcher for the ViewController. +@property(nonatomic, weak) id<ApplicationCommands, BrowserCommands> dispatcher; + +// Sets the location bar view, containing the omnibox. +- (void)setLocationBarView:(UIView*)locationBarView; + +@end + +#endif // IOS_CHROME_BROWSER_UI_TOOLBAR_ADAPTIVE_PRIMARY_TOOLBAR_VIEW_CONTROLLER_H_
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 new file mode 100644 index 0000000..727d29a --- /dev/null +++ b/ios/chrome/browser/ui/toolbar/adaptive/primary_toolbar_view_controller.mm
@@ -0,0 +1,77 @@ +// 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/toolbar/adaptive/primary_toolbar_view_controller.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" + +#if !defined(__has_feature) || !__has_feature(objc_arc) +#error "This file requires ARC support." +#endif + +@interface PrimaryToolbarViewController () + +// Button factory. +@property(nonatomic, strong) ToolbarButtonFactory* buttonFactory; +// Redefined to be a PrimaryToolbarView. +@property(nonatomic, strong) PrimaryToolbarView* view; + +@end + +@implementation PrimaryToolbarViewController +@dynamic view; +@synthesize buttonFactory = _buttonFactory; +@synthesize dispatcher = _dispatcher; + +#pragma mark - Public + +- (instancetype)initWithButtonFactory:(ToolbarButtonFactory*)buttonFactory { + self = [super initWithNibName:nil bundle:nil]; + if (self) { + _buttonFactory = buttonFactory; + } + return self; +} + +#pragma mark - UIViewController + +- (void)loadView { + self.view = [[PrimaryToolbarView alloc] init]; + self.view.buttonFactory = self.buttonFactory; + if (@available(iOS 11, *)) { + self.view.topSafeAnchor = self.view.safeAreaLayoutGuide.topAnchor; + } else { + self.view.topSafeAnchor = self.topLayoutGuide.bottomAnchor; + } +} + +- (void)viewDidAppear:(BOOL)animated { + [super viewDidAppear:animated]; + [self updateAllButtonsVisibility]; +} + +- (void)traitCollectionDidChange:(UITraitCollection*)previousTraitCollection { + [super traitCollectionDidChange:previousTraitCollection]; + [self updateAllButtonsVisibility]; +} + +#pragma mark - Property accessors + +- (void)setLocationBarView:(UIView*)locationBarView { + self.view.locationBarView = locationBarView; +} + +#pragma mark - Private + +// Updates all buttons visibility to match any recent WebState or SizeClass +// change. +- (void)updateAllButtonsVisibility { + for (ToolbarButton* button in self.view.allButtons) { + [button updateHiddenInCurrentSizeClass]; + } +} + +@end
diff --git a/ios/chrome/browser/ui/toolbar/adaptive/secondary_toolbar_coordinator.h b/ios/chrome/browser/ui/toolbar/adaptive/secondary_toolbar_coordinator.h new file mode 100644 index 0000000..b4c4448 --- /dev/null +++ b/ios/chrome/browser/ui/toolbar/adaptive/secondary_toolbar_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_TOOLBAR_ADAPTIVE_SECONDARY_TOOLBAR_COORDINATOR_H_ +#define IOS_CHROME_BROWSER_UI_TOOLBAR_ADAPTIVE_SECONDARY_TOOLBAR_COORDINATOR_H_ + +#import <UIKit/UIKit.h> + +#import "ios/chrome/browser/ui/coordinators/chrome_coordinator.h" + +@protocol ApplicationCommands; +@protocol BrowserCommands; +@protocol ToolbarCommands; + +// Coordinator for the secondary toolbar. The secondary toolbar contains actions +// and shortcuts that are not displayed on the primary toolbar. +@interface SecondaryToolbarCoordinator : ChromeCoordinator + +- (nullable instancetype)initWithBaseViewController: + (nullable UIViewController*)viewController NS_UNAVAILABLE; + +// UIViewController managed by this coordinator; +@property(nonatomic, strong, readonly, nullable) + UIViewController* viewController; +// Dispatcher. +@property(nonatomic, weak, nullable) + id<ApplicationCommands, BrowserCommands, ToolbarCommands> + dispatcher; + +@end + +#endif // IOS_CHROME_BROWSER_UI_TOOLBAR_ADAPTIVE_SECONDARY_TOOLBAR_COORDINATOR_H_
diff --git a/ios/chrome/browser/ui/toolbar/adaptive/secondary_toolbar_coordinator.mm b/ios/chrome/browser/ui/toolbar/adaptive/secondary_toolbar_coordinator.mm new file mode 100644 index 0000000..4de9185 --- /dev/null +++ b/ios/chrome/browser/ui/toolbar/adaptive/secondary_toolbar_coordinator.mm
@@ -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. + +#import "ios/chrome/browser/ui/toolbar/adaptive/secondary_toolbar_coordinator.h" + +#include "ios/chrome/browser/browser_state/chrome_browser_state.h" +#import "ios/chrome/browser/ui/toolbar/adaptive/secondary_toolbar_view_controller.h" +#import "ios/chrome/browser/ui/toolbar/clean/toolbar_button_factory.h" +#import "ios/chrome/browser/ui/toolbar/clean/toolbar_button_visibility_configuration.h" + +#if !defined(__has_feature) || !__has_feature(objc_arc) +#error "This file requires ARC support." +#endif + +@interface SecondaryToolbarCoordinator () + +// The ViewController, defined as a SecondaryToolbarViewController. +@property(nonatomic, strong) + SecondaryToolbarViewController* toolbarViewController; + +@end + +@implementation SecondaryToolbarCoordinator + +@synthesize dispatcher = _dispatcher; +@synthesize toolbarViewController = _toolbarViewController; + +#pragma mark - ChromeCoordinator + +- (void)start { + BOOL isIncognito = self.browserState->IsOffTheRecord(); + + ToolbarStyle style = isIncognito ? INCOGNITO : NORMAL; + ToolbarButtonFactory* buttonFactory = + [[ToolbarButtonFactory alloc] initWithStyle:style]; + buttonFactory.dispatcher = self.dispatcher; + buttonFactory.dispatcher = self.dispatcher; + buttonFactory.visibilityConfiguration = + [[ToolbarButtonVisibilityConfiguration alloc] initWithType:PRIMARY]; + + self.toolbarViewController = [[SecondaryToolbarViewController alloc] + initWithButtonFactory:buttonFactory]; +} + +#pragma mark - Property accessors + +- (UIViewController*)viewController { + return self.toolbarViewController; +} + +@end
diff --git a/ios/chrome/browser/ui/toolbar/adaptive/secondary_toolbar_view.h b/ios/chrome/browser/ui/toolbar/adaptive/secondary_toolbar_view.h new file mode 100644 index 0000000..7ee5a0b --- /dev/null +++ b/ios/chrome/browser/ui/toolbar/adaptive/secondary_toolbar_view.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_TOOLBAR_ADAPTIVE_SECONDARY_TOOLBAR_VIEW_H_ +#define IOS_CHROME_BROWSER_UI_TOOLBAR_ADAPTIVE_SECONDARY_TOOLBAR_VIEW_H_ + +#import <UIKit/UIKit.h> + +@class ToolbarButton; +@class ToolbarButtonFactory; +@class ToolbarToolsMenuButton; + +// View for the secondary toolbar. +@interface SecondaryToolbarView : UIView + +// Factory used to create the buttons. +@property(nonatomic, strong) ToolbarButtonFactory* buttonFactory; + +// Button to display the tools menu. +@property(nonatomic, strong, readonly) ToolbarToolsMenuButton* toolsMenuButton; +// Button to display the tab grid. +@property(nonatomic, strong, readonly) ToolbarButton* tabGridButton; +// Button to display the share menu. +@property(nonatomic, strong, readonly) ToolbarButton* shareButton; +// Button to focus the omnibox. +@property(nonatomic, strong, readonly) ToolbarButton* omniboxButton; +// Button to manage the bookmarks of this page. +@property(nonatomic, strong, readonly) ToolbarButton* bookmarksButton; + +@end + +#endif // IOS_CHROME_BROWSER_UI_TOOLBAR_ADAPTIVE_SECONDARY_TOOLBAR_VIEW_H_
diff --git a/ios/chrome/browser/ui/toolbar/adaptive/secondary_toolbar_view.mm b/ios/chrome/browser/ui/toolbar/adaptive/secondary_toolbar_view.mm new file mode 100644 index 0000000..e8d0431 --- /dev/null +++ b/ios/chrome/browser/ui/toolbar/adaptive/secondary_toolbar_view.mm
@@ -0,0 +1,78 @@ +// 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/toolbar/adaptive/secondary_toolbar_view.h" + +#include "base/logging.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_tools_menu_button.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 SecondaryToolbarView () + +// The stack view containing the buttons. +@property(nonatomic, strong) UIStackView* stackView; + +// Redefined as readwrite +@property(nonatomic, strong, readwrite) ToolbarToolsMenuButton* toolsMenuButton; +@property(nonatomic, strong, readwrite) ToolbarButton* tabGridButton; +@property(nonatomic, strong, readwrite) ToolbarButton* shareButton; +@property(nonatomic, strong, readwrite) ToolbarButton* omniboxButton; +@property(nonatomic, strong, readwrite) ToolbarButton* bookmarksButton; + +@end + +@implementation SecondaryToolbarView + +@synthesize buttonFactory = _buttonFactory; +@synthesize stackView = _stackView; +@synthesize toolsMenuButton = _toolsMenuButton; +@synthesize shareButton = _shareButton; +@synthesize omniboxButton = _omniboxButton; +@synthesize bookmarksButton = _bookmarksButton; +@synthesize tabGridButton = _tabGridButton; + +#pragma mark - UIView + +- (void)willMoveToSuperview:(UIView*)newSuperview { + [self setUp]; + [super willMoveToSuperview:newSuperview]; +} + +#pragma mark - Setup + +// Sets all the subviews and constraints of this view. +- (void)setUp { + if (self.subviews.count > 0) { + // Make sure the view is instantiated only once. + return; + } + DCHECK(self.buttonFactory); + + self.translatesAutoresizingMaskIntoConstraints = NO; + self.backgroundColor = [UIColor whiteColor]; + + self.tabGridButton = [self.buttonFactory tabSwitcherStripButton]; + self.shareButton = [self.buttonFactory shareButton]; + self.omniboxButton = [self.buttonFactory omniboxButton]; + self.bookmarksButton = [self.buttonFactory bookmarkButton]; + self.toolsMenuButton = [self.buttonFactory toolsMenuButton]; + + self.stackView = [[UIStackView alloc] initWithArrangedSubviews:@[ + self.tabGridButton, self.shareButton, self.omniboxButton, + self.bookmarksButton, self.toolsMenuButton + ]]; + self.stackView.distribution = UIStackViewDistributionEqualSpacing; + self.stackView.translatesAutoresizingMaskIntoConstraints = NO; + [self addSubview:self.stackView]; + + PinToSafeArea(self.stackView, self); +} + +@end
diff --git a/ios/chrome/browser/ui/toolbar/adaptive/secondary_toolbar_view_controller.h b/ios/chrome/browser/ui/toolbar/adaptive/secondary_toolbar_view_controller.h new file mode 100644 index 0000000..e234a88 --- /dev/null +++ b/ios/chrome/browser/ui/toolbar/adaptive/secondary_toolbar_view_controller.h
@@ -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. + +#ifndef IOS_CHROME_BROWSER_UI_TOOLBAR_ADAPTIVE_SECONDARY_TOOLBAR_VIEW_CONTROLLER_H_ +#define IOS_CHROME_BROWSER_UI_TOOLBAR_ADAPTIVE_SECONDARY_TOOLBAR_VIEW_CONTROLLER_H_ + +#import <UIKit/UIKit.h> + +@class ToolbarButtonFactory; + +// The ViewController for the secondary toolbar. +@interface SecondaryToolbarViewController : UIViewController + +- (instancetype)initWithButtonFactory:(ToolbarButtonFactory*)buttonFactory; + +- (instancetype)init NS_UNAVAILABLE; +- (instancetype)initWithCoder:(NSCoder*)aDecoder NS_UNAVAILABLE; +- (instancetype)initWithNibName:(NSString*)nibNameOrNil + bundle:(NSBundle*)nibBundleOrNil NS_UNAVAILABLE; + +@end + +#endif // IOS_CHROME_BROWSER_UI_TOOLBAR_ADAPTIVE_SECONDARY_TOOLBAR_VIEW_CONTROLLER_H_
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 new file mode 100644 index 0000000..c7ba897 --- /dev/null +++ b/ios/chrome/browser/ui/toolbar/adaptive/secondary_toolbar_view_controller.mm
@@ -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. + +#import "ios/chrome/browser/ui/toolbar/adaptive/secondary_toolbar_view_controller.h" + +#import "ios/chrome/browser/ui/toolbar/adaptive/secondary_toolbar_view.h" +#import "ios/chrome/browser/ui/toolbar/clean/toolbar_button_factory.h" + +#if !defined(__has_feature) || !__has_feature(objc_arc) +#error "This file requires ARC support." +#endif + +@interface SecondaryToolbarViewController () + +// Button factory. +@property(nonatomic, strong) ToolbarButtonFactory* buttonFactory; +// Redefined to be a PrimaryToolbarView. +@property(nonatomic, strong) SecondaryToolbarView* view; + +@end + +@implementation SecondaryToolbarViewController +@dynamic view; +@synthesize buttonFactory = _buttonFactory; + +#pragma mark - Public + +- (instancetype)initWithButtonFactory:(ToolbarButtonFactory*)buttonFactory { + self = [super initWithNibName:nil bundle:nil]; + if (self) { + _buttonFactory = buttonFactory; + } + return self; +} + +#pragma mark - UIViewController + +- (void)loadView { + self.view = [[SecondaryToolbarView alloc] init]; + self.view.buttonFactory = self.buttonFactory; +} + +@end
diff --git a/ios/chrome/browser/ui/toolbar/clean/toolbar_button_factory.h b/ios/chrome/browser/ui/toolbar/clean/toolbar_button_factory.h index ef1dadc7..d8f1a56 100644 --- a/ios/chrome/browser/ui/toolbar/clean/toolbar_button_factory.h +++ b/ios/chrome/browser/ui/toolbar/clean/toolbar_button_factory.h
@@ -60,6 +60,8 @@ - (ToolbarButton*)voiceSearchButton; // ContractToolbar ToolbarButton. - (ToolbarButton*)contractButton; +// ToolbarButton to focus the omnibox. +- (ToolbarButton*)omniboxButton; // LocationBar LeadingButton. Currently used for the incognito icon when the // Toolbar is expanded on incognito mode. It can return nil. - (ToolbarButton*)locationBarLeadingButton;
diff --git a/ios/chrome/browser/ui/toolbar/clean/toolbar_button_factory.mm b/ios/chrome/browser/ui/toolbar/clean/toolbar_button_factory.mm index 257c7eb..6a2cf2de 100644 --- a/ios/chrome/browser/ui/toolbar/clean/toolbar_button_factory.mm +++ b/ios/chrome/browser/ui/toolbar/clean/toolbar_button_factory.mm
@@ -323,6 +323,15 @@ return contractButton; } +- (ToolbarButton*)omniboxButton { + ToolbarButton* omniboxButton = [ToolbarButton + toolbarButtonWithImageForNormalState:NativeImage(IDR_IOS_OMNIBOX_SEARCH) + imageForHighlightedState:NativeImage(IDR_IOS_OMNIBOX_SEARCH) + imageForDisabledState:nil]; + [self configureButton:omniboxButton width:kToolbarButtonWidth]; + return omniboxButton; +} + - (ToolbarButton*)locationBarLeadingButton { ToolbarButton* locationBarLeadingButton; if (self.style == INCOGNITO) {
diff --git a/ios/chrome/browser/ui/toolbar/clean/toolbar_button_visibility_configuration.mm b/ios/chrome/browser/ui/toolbar/clean/toolbar_button_visibility_configuration.mm index 40545b8..525ac35 100644 --- a/ios/chrome/browser/ui/toolbar/clean/toolbar_button_visibility_configuration.mm +++ b/ios/chrome/browser/ui/toolbar/clean/toolbar_button_visibility_configuration.mm
@@ -48,7 +48,7 @@ switch (self.type) { case PRIMARY: return ToolbarComponentVisibilityAlways & - !ToolbarComponentVisibilityRegularWidthRegularHeight; + ~ToolbarComponentVisibilityRegularWidthRegularHeight; case SECONDARY: return ToolbarComponentVisibilityAlways; case LEGACY: @@ -71,7 +71,7 @@ switch (self.type) { case PRIMARY: return ToolbarComponentVisibilityAlways & - !ToolbarComponentVisibilityCompactWidthRegularHeight; + ~ToolbarComponentVisibilityCompactWidthRegularHeight; case SECONDARY: return ToolbarComponentVisibilityAlways; case LEGACY: @@ -108,7 +108,7 @@ switch (self.type) { case PRIMARY: return ToolbarComponentVisibilityAlways & - !ToolbarComponentVisibilityCompactWidthRegularHeight; + ~ToolbarComponentVisibilityCompactWidthRegularHeight; case SECONDARY: return ToolbarComponentVisibilityAlways; case LEGACY:
diff --git a/ios/chrome/browser/ui/toolbar/clean/toolbar_constants.h b/ios/chrome/browser/ui/toolbar/clean/toolbar_constants.h index 27fc512..3455e3d7 100644 --- a/ios/chrome/browser/ui/toolbar/clean/toolbar_constants.h +++ b/ios/chrome/browser/ui/toolbar/clean/toolbar_constants.h
@@ -35,9 +35,6 @@ extern const CGFloat kLocationBarShadowInset; extern const CGFloat kIcongnitoLocationBackgroundColor; -// Location bar StackView constraints. -extern const CGFloat klocationBarStackViewBottomMargin; - // Progress Bar Height. extern const CGFloat kProgressBarHeight;
diff --git a/ios/chrome/browser/ui/toolbar/clean/toolbar_constants.mm b/ios/chrome/browser/ui/toolbar/clean/toolbar_constants.mm index 56333210..ce3e7e2 100644 --- a/ios/chrome/browser/ui/toolbar/clean/toolbar_constants.mm +++ b/ios/chrome/browser/ui/toolbar/clean/toolbar_constants.mm
@@ -25,8 +25,6 @@ const CGFloat kLocationBarShadowInset = 1.0f; const CGFloat kIcongnitoLocationBackgroundColor = 0x737373; -const CGFloat klocationBarStackViewBottomMargin = 8.0f; - const CGFloat kProgressBarHeight = 2.0f; const CGFloat kToolsMenuButtonWidth = 44.0f;
diff --git a/ios/chrome/browser/ui/toolbar/clean/toolbar_coordinator.h b/ios/chrome/browser/ui/toolbar/clean/toolbar_coordinator.h index 4d167af..77cb97c7 100644 --- a/ios/chrome/browser/ui/toolbar/clean/toolbar_coordinator.h +++ b/ios/chrome/browser/ui/toolbar/clean/toolbar_coordinator.h
@@ -42,8 +42,10 @@ // The web state list this ToolbarCoordinator is handling. @property(nonatomic, assign) WebStateList* webStateList; // Delegate for this coordinator. +// TODO(crbug.com/799446): Change this. @property(nonatomic, weak) id<ToolbarCoordinatorDelegate> delegate; // URL loader for the toolbar. +// TODO(crbug.com/799446): Remove this. @property(nonatomic, weak) id<UrlLoader> URLLoader; // UIViewController managed by this coordinator. @property(nonatomic, strong, readonly) UIViewController* viewController;
diff --git a/ios/chrome/browser/ui/toolbar/clean/toolbar_view.mm b/ios/chrome/browser/ui/toolbar/clean/toolbar_view.mm index 1ce516d..4af59ce 100644 --- a/ios/chrome/browser/ui/toolbar/clean/toolbar_view.mm +++ b/ios/chrome/browser/ui/toolbar/clean/toolbar_view.mm
@@ -459,14 +459,16 @@ [NSLayoutConstraint activateConstraints:@[ [self.locationBarContainerStackView.bottomAnchor constraintEqualToAnchor:self.bottomAnchor - constant:-(klocationBarStackViewBottomMargin + - kLocationBarVerticalMargin)], + constant:-kLocationBarVerticalMargin], [self.locationBarContainerStackView.trailingAnchor constraintEqualToAnchor:locationBarContainerSafeAreaGuide .trailingAnchor], [self.locationBarContainerStackView.leadingAnchor constraintEqualToAnchor:locationBarContainerSafeAreaGuide .leadingAnchor], + [self.locationBarContainerStackView.heightAnchor + constraintEqualToConstant:kToolbarHeight - + 2 * kLocationBarVerticalMargin], ]]; }
diff --git a/ios/chrome/browser/ui/toolbar/legacy_toolbar_coordinator.mm b/ios/chrome/browser/ui/toolbar/legacy_toolbar_coordinator.mm index 2b6e3ec..5473c89 100644 --- a/ios/chrome/browser/ui/toolbar/legacy_toolbar_coordinator.mm +++ b/ios/chrome/browser/ui/toolbar/legacy_toolbar_coordinator.mm
@@ -33,7 +33,6 @@ @end @implementation LegacyToolbarCoordinator -@synthesize toolbarViewController = _toolbarViewController; @synthesize toolbarController = _toolbarController; - (instancetype)initWithBaseViewController:(UIViewController*)viewController @@ -81,11 +80,8 @@ self.toolbarController = nil; } -- (UIViewController*)toolbarViewController { - if (!_toolbarViewController) - _toolbarViewController = self.toolbarController.viewController; - - return _toolbarViewController; +- (UIViewController*)viewController { + return self.toolbarController.viewController; } #pragma mark - Delegates @@ -194,7 +190,7 @@ #pragma mark - SideSwipeToolbarInteracting - (UIView*)toolbarView { - return self.toolbarViewController.view; + return self.viewController.view; } - (BOOL)canBeginToolbarSwipe { @@ -204,7 +200,7 @@ - (UIImage*)toolbarSideSwipeSnapshotForTab:(Tab*)tab { [self.toolbarController updateToolbarForSideSwipeSnapshot:tab]; UIImage* toolbarSnapshot = CaptureViewWithOption( - [self.toolbarViewController view], [[UIScreen mainScreen] scale], + [self.viewController view], [[UIScreen mainScreen] scale], kClientSideRendering); [self.toolbarController resetToolbarAfterSideSwipeSnapshot]; @@ -215,33 +211,32 @@ - (UIView*)snapshotForTabSwitcher { UIView* toolbarSnapshotView; - if ([self.toolbarViewController.view window]) { + if ([self.viewController.view window]) { toolbarSnapshotView = - [self.toolbarViewController.view snapshotViewAfterScreenUpdates:NO]; + [self.viewController.view snapshotViewAfterScreenUpdates:NO]; } else { toolbarSnapshotView = - [[UIView alloc] initWithFrame:self.toolbarViewController.view.frame]; - [toolbarSnapshotView layer].contents = - static_cast<id>(CaptureViewWithOption(self.toolbarViewController.view, - 0, kClientSideRendering) - .CGImage); + [[UIView alloc] initWithFrame:self.viewController.view.frame]; + [toolbarSnapshotView layer].contents = static_cast<id>( + CaptureViewWithOption(self.viewController.view, 0, kClientSideRendering) + .CGImage); } return toolbarSnapshotView; } - (UIView*)snapshotForStackViewWithWidth:(CGFloat)width safeAreaInsets:(UIEdgeInsets)safeAreaInsets { - CGRect oldFrame = self.toolbarViewController.view.superview.frame; + CGRect oldFrame = self.viewController.view.superview.frame; CGRect newFrame = oldFrame; newFrame.size.width = width; - self.toolbarViewController.view.superview.frame = newFrame; + self.viewController.view.superview.frame = newFrame; [self.toolbarController activateFakeSafeAreaInsets:safeAreaInsets]; - [self.toolbarViewController.view.superview layoutIfNeeded]; + [self.viewController.view.superview layoutIfNeeded]; UIView* toolbarSnapshotView = [self snapshotForTabSwitcher]; - self.toolbarViewController.view.superview.frame = oldFrame; + self.viewController.view.superview.frame = oldFrame; [self.toolbarController deactivateFakeSafeAreaInsets]; return toolbarSnapshotView; @@ -253,7 +248,7 @@ self.toolbarController.backgroundView.alpha == 0) { // If the background view isn't visible, use the base toolbar view's // background color. - toolbarBackgroundColor = self.toolbarViewController.view.backgroundColor; + toolbarBackgroundColor = self.viewController.view.backgroundColor; } return toolbarBackgroundColor; }
diff --git a/ios/chrome/browser/ui/toolbar/public/primary_toolbar_coordinator.h b/ios/chrome/browser/ui/toolbar/public/primary_toolbar_coordinator.h index aec08d1..556a2ea 100644 --- a/ios/chrome/browser/ui/toolbar/public/primary_toolbar_coordinator.h +++ b/ios/chrome/browser/ui/toolbar/public/primary_toolbar_coordinator.h
@@ -20,7 +20,7 @@ @protocol PrimaryToolbarCoordinator<OmniboxFocuser, SideSwipeToolbarInteracting> // The toolbar ViewController. -@property(nonatomic, strong) UIViewController* toolbarViewController; +@property(nonatomic, strong, readonly) UIViewController* viewController; // Returns the different protocols and superclass now implemented by the // internal ViewController.
diff --git a/ios/chrome/browser/ui/toolbar/web_toolbar_controller.mm b/ios/chrome/browser/ui/toolbar/web_toolbar_controller.mm index 66aad3a..0920fc96 100644 --- a/ios/chrome/browser/ui/toolbar/web_toolbar_controller.mm +++ b/ios/chrome/browser/ui/toolbar/web_toolbar_controller.mm
@@ -1924,9 +1924,9 @@ - (void)viewSafeAreaInsetsDidChange { [super viewSafeAreaInsetsDidChange]; - [self adjustToolbarHeight]; - if (!IsIPadIdiom()) { - if (IsSafeAreaCompatibleToolbarEnabled()) { + if (IsSafeAreaCompatibleToolbarEnabled()) { + [self adjustToolbarHeight]; + if (!IsIPadIdiom()) { // The clipping view's height is supposed to match the toolbar's height. // The clipping view can't match the toolbar's height with autoresizing // masks because the clipping view is not a direct child of the toolbar.
diff --git a/ios/web/BUILD.gn b/ios/web/BUILD.gn index 2f6b241..57993c5 100644 --- a/ios/web/BUILD.gn +++ b/ios/web/BUILD.gn
@@ -373,6 +373,7 @@ "//ios/testing:ios_test_support", "//ios/testing:ocmock_support", "//ios/web", + "//ios/web/navigation", "//ios/web/public", "//ios/web/public/test", "//ios/web/public/test/fakes",
diff --git a/ios/web/web_state/ui/crw_web_controller.mm b/ios/web/web_state/ui/crw_web_controller.mm index 7349f541..661945ad 100644 --- a/ios/web/web_state/ui/crw_web_controller.mm +++ b/ios/web/web_state/ui/crw_web_controller.mm
@@ -473,10 +473,11 @@ - (void)resetContainerView; // Called when the web page has changed document and/or URL, and so the page // navigation should be reported to the delegate, and internal state updated to -// reflect the fact that the navigation has occurred. +// reflect the fact that the navigation has occurred. |context| contains +// information about the navigation that triggered the document/URL change. // TODO(stuartmorgan): The code conflates URL changes and document object // changes; the two need to be separated and handled differently. -- (void)webPageChanged; +- (void)webPageChangedWithContext:(const web::NavigationContext*)context; // Resets any state that is associated with a specific document object (e.g., // page interaction tracking). - (void)resetDocumentSpecificState; @@ -586,7 +587,11 @@ - (void)loadCompleteWithSuccess:(BOOL)loadSuccess forNavigation:(WKNavigation*)navigation; // Called after URL is finished loading and _loadPhase is set to PAGE_LOADED. -- (void)didFinishWithURL:(const GURL&)currentURL loadSuccess:(BOOL)loadSuccess; +// |context| contains information about the navigation associated with the URL. +// It is nil if currentURL is invalid. +- (void)didFinishWithURL:(const GURL&)currentURL + loadSuccess:(BOOL)loadSuccess + context:(nullable const web::NavigationContext*)context; // Navigates forwards or backwards by |delta| pages. No-op if delta is out of // bounds. Reloads if delta is 0. // TODO(crbug.com/661316): Move this method to NavigationManager. @@ -651,7 +656,7 @@ // |urlOnStartLoading_| and |_lastRegisteredRequestURL| to the current // NavigationItem's URL. This is necessary so that sites that depend on URL // params/fragments continue to work correctly and that checks for the URL don't -// incorrectly trigger |-webPageChanged| calls. +// incorrectly trigger |-webPageChangedWithContext| calls. - (void)injectHTML5HistoryScriptWithHashChange:(BOOL)dispatchHashChange sameDocumentNavigation:(BOOL)sameDocumentNavigation; @@ -1390,7 +1395,11 @@ if (self.navigationManagerImpl->GetPendingItem()) { // Update the existing pending entry. // Typically on PAGE_TRANSITION_CLIENT_REDIRECT. - self.navigationManagerImpl->UpdatePendingItemUrl(requestURL); + // Don't update if request is a placeholder entry because the pending item + // should have the original target URL. + if (!IsPlaceholderUrl(requestURL)) { + self.navigationManagerImpl->UpdatePendingItemUrl(requestURL); + } } else { self.navigationManagerImpl->AddPendingItem( requestURL, referrer, transition, @@ -1420,7 +1429,9 @@ context->SetIsPost([self isCurrentNavigationItemPOST]); context->SetIsSameDocument(sameDocumentNavigation); - _webStateImpl->SetIsLoading(true); + if (!IsPlaceholderUrl(requestURL)) { + _webStateImpl->SetIsLoading(true); + } [_webUIManager loadWebUIForURL:requestURL]; return context; } @@ -1551,7 +1562,7 @@ // Load the url. The UIWebView delegate callbacks take care of updating the // session history and UI. if (!targetURL.is_valid()) { - [self didFinishWithURL:targetURL loadSuccess:NO]; + [self didFinishWithURL:targetURL loadSuccess:NO context:nullptr]; return; } @@ -1680,7 +1691,7 @@ } // Perform post-load-finished updates. - [self didFinishWithURL:currentURL loadSuccess:loadSuccess]; + [self didFinishWithURL:currentURL loadSuccess:loadSuccess context:context]; NSString* title = [self.nativeController title]; if (title) { @@ -1776,6 +1787,12 @@ NSURLRequest* request = [NSURLRequest requestWithURL:net::NSURLWithGURL(placeholderURL)]; WKNavigation* navigation = [_webView loadRequest:request]; + [_navigationStates setState:web::WKNavigationState::REQUESTED + forNavigation:navigation]; + std::unique_ptr<web::NavigationContextImpl> navigationContext = + [self registerLoadRequestForURL:placeholderURL sameDocumentNavigation:NO]; + [_navigationStates setContext:std::move(navigationContext) + forNavigation:navigation]; [CRWPlaceholderNavigationInfo createForNavigation:navigation withCompletionHandler:completionHandler]; } @@ -1943,7 +1960,9 @@ [self optOutScrollsToTopForSubviews]; // Perform post-load-finished updates. - [self didFinishWithURL:currentURL loadSuccess:loadSuccess]; + const web::NavigationContext* context = + [_navigationStates contextForNavigation:navigation]; + [self didFinishWithURL:currentURL loadSuccess:loadSuccess context:context]; // Execute the pending LoadCompleteActions. for (ProceduralBlock action in _pendingLoadCompleteActions) { @@ -1952,7 +1971,9 @@ [_pendingLoadCompleteActions removeAllObjects]; } -- (void)didFinishWithURL:(const GURL&)currentURL loadSuccess:(BOOL)loadSuccess { +- (void)didFinishWithURL:(const GURL&)currentURL + loadSuccess:(BOOL)loadSuccess + context:(nullable const web::NavigationContext*)context { DCHECK(_loadPhase == web::PAGE_LOADED); // Rather than creating a new WKBackForwardListItem when loading WebUI pages, // WKWebView will cache the WebUI HTML in the previous WKBackForwardListItem @@ -1976,8 +1997,12 @@ } [self restoreStateFromHistory]; - _webStateImpl->SetIsLoading(false); - _webStateImpl->OnPageLoaded(currentURL, loadSuccess); + // Placeholder navigation is implementation details so should not notify + // WebStateObservers. + if (!context || !IsPlaceholderUrl(context->GetUrl())) { + _webStateImpl->SetIsLoading(false); + _webStateImpl->OnPageLoaded(currentURL, loadSuccess); + } } - (void)rendererInitiatedGoDelta:(int)delta { @@ -2691,10 +2716,9 @@ // TODO(stuartmorgan): This method conflates document changes and URL changes; // we should be distinguishing better, and be clear about the expected // WebDelegate and WCO callbacks in each case. -- (void)webPageChanged { - DCHECK(_loadPhase == web::LOAD_REQUESTED); +- (void)webPageChangedWithContext:(const web::NavigationContext*)context { + DCHECK_EQ(_loadPhase, web::LOAD_REQUESTED); - const GURL currentURL([self currentURL]); web::Referrer referrer = [self currentReferrer]; // If no referrer was known in advance, record it now. (If there was one, // keep it since it will have a more accurate URL and policy than what can @@ -2709,7 +2733,11 @@ [self resetDocumentSpecificState]; [self didStartLoading]; - self.navigationManagerImpl->CommitPendingItem(); + // Do not commit pending item in the middle of loading a placeholder URL. The + // item will be committed when the native content or webUI is displayed. + if (!IsPlaceholderUrl(context->GetUrl())) { + self.navigationManagerImpl->CommitPendingItem(); + } } - (void)resetDocumentSpecificState { @@ -4244,35 +4272,6 @@ GURL webViewURL = net::GURLWithNSURL(webView.URL); - // If this is a placeholder URL, there are only two possibilities: - // 1. This navigation is initiated by |loadPlaceholderInWebViewForURL| in - // preparation for loading a native controller or WebUI. - // In this case, do not update the page navigation states as they will be - // updated by the completion handler of the placeholder navigation. - // - // 2. This is a back-forward navigation to an app-specific URL. - // In this case, restart the app-specific URL load to properly capture state. - if (web::GetWebClient()->IsSlimNavigationManagerEnabled() && - IsPlaceholderUrl(webViewURL)) { - GURL originalURL = ExtractUrlFromPlaceholderUrl(webViewURL); - if (!originalURL.is_valid()) { - [self abortLoad]; - return; - } - - // Back-forward navigation to placeholder URL. - // TODO(crbug.com/760113): This implementation destroys forward history. - // Investigate if we can rely on WKWebView's back/forward navigation and - // only reload the native controller / WebUI portion to preserve forward - // history. - if (![CRWPlaceholderNavigationInfo infoForNavigation:navigation]) { - [self abortLoad]; - NavigationManager::WebLoadParams params(originalURL); - self.navigationManagerImpl->LoadURLWithParams(params); - } - return; - } - [_navigationStates setState:web::WKNavigationState::STARTED forNavigation:navigation]; @@ -4429,17 +4428,6 @@ webViewURL = net::GURLWithNSURL(webView.backForwardList.currentItem.URL); } - // If this is a placeholder navigation or if |navigation| has been previous - // aborted, return without modifying the navigation states. The latter case - // seems to happen due to asychronous nature of WKWebView; sometimes - // |didCommitNavigation| callback arrives after |stopLoading| has been called. - if (web::GetWebClient()->IsSlimNavigationManagerEnabled() && - (IsPlaceholderUrl(webViewURL) || - [_navigationStates stateForNavigation:navigation] == - web::WKNavigationState::NONE)) { - return; - } - [self displayWebView]; bool navigationFinished = [_navigationStates stateForNavigation:navigation] == @@ -4493,7 +4481,7 @@ } if (isLastNavigation) { - [self webPageChanged]; + [self webPageChangedWithContext:context]; } else { // WKWebView has more than one in progress navigation, and committed // navigation was not the latest. Change last committed item to one that @@ -4512,8 +4500,10 @@ [self updateSSLStatusForCurrentNavigationItem]; - // Attempt to update the HTML5 history state. - [self updateHTML5HistoryState]; + // Attempt to update the HTML5 history state if this is a normal web page. + if (!IsPlaceholderUrl(context->GetUrl())) { + [self updateHTML5HistoryState]; + } // This is the point where pending entry has been committed, and navigation // item title should be updated. @@ -4556,7 +4546,7 @@ [self updateHTML5HistoryState]; [self setDocumentURL:URL]; _webStateImpl->OnNavigationFinished(context.get()); - [self didFinishWithURL:URL loadSuccess:YES]; + [self didFinishWithURL:URL loadSuccess:YES context:context.get()]; } - (void)webView:(WKWebView*)webView @@ -4568,6 +4558,13 @@ // If this is a placeholder navigation for an app-specific URL, finish // loading by running the completion handler. if (web::GetWebClient()->IsSlimNavigationManagerEnabled()) { + // Sometimes |didFinishNavigation| callback arrives after |stopLoading| has + // been called. Abort in this case. + if ([_navigationStates stateForNavigation:navigation] == + web::WKNavigationState::NONE) { + return; + } + if (IsPlaceholderUrl(webViewURL)) { CRWPlaceholderNavigationInfo* placeholderNavigationInfo = [CRWPlaceholderNavigationInfo infoForNavigation:navigation]; @@ -4579,13 +4576,6 @@ return; [placeholderNavigationInfo runCompletionHandler]; } - return; - } - // Sometimes |didFinishNavigation| callback arrives after |stopLoading| has - // been called. Abort in this case. - if ([_navigationStates stateForNavigation:navigation] == - web::WKNavigationState::NONE) { - return; } } @@ -4801,13 +4791,13 @@ BOOL isSameDocumentNavigation = [self isKVOChangePotentialSameDocumentNavigationToURL:webViewURL]; [self setDocumentURL:webViewURL]; - [self webPageChanged]; if (!existingContext) { // This URL was not seen before, so register new load request. std::unique_ptr<web::NavigationContextImpl> newContext = [self registerLoadRequestForURL:webViewURL sameDocumentNavigation:isSameDocumentNavigation]; + [self webPageChangedWithContext:newContext.get()]; _webStateImpl->OnNavigationFinished(newContext.get()); // TODO(crbug.com/792515): It is OK, but very brittle, to call // |didFinishNavigation:| here because the gating condition is mutually @@ -4817,6 +4807,8 @@ [self didFinishNavigation:nil]; } } else { + [self webPageChangedWithContext:existingContext]; + // Same document navigation does not contain response headers. net::HttpResponseHeaders* headers = isSameDocumentNavigation ? nullptr
diff --git a/ios/web/web_state/web_state_impl.mm b/ios/web/web_state/web_state_impl.mm index f875aab..d86faf4d 100644 --- a/ios/web/web_state/web_state_impl.mm +++ b/ios/web/web_state/web_state_impl.mm
@@ -17,6 +17,7 @@ #import "ios/web/navigation/crw_session_controller.h" #import "ios/web/navigation/legacy_navigation_manager_impl.h" #import "ios/web/navigation/navigation_item_impl.h" +#include "ios/web/navigation/placeholder_navigation_util.h" #import "ios/web/navigation/session_storage_builder.h" #import "ios/web/navigation/wk_based_navigation_manager_impl.h" #include "ios/web/public/browser_state.h" @@ -48,6 +49,8 @@ #error "This file requires ARC support." #endif +using web::placeholder_navigation_util::IsPlaceholderUrl; + namespace web { /* static */ @@ -245,6 +248,11 @@ } void WebStateImpl::OnPageLoaded(const GURL& url, bool load_success) { + // Native Content and WebUI placeholder URL is an internal implementation + // detail of //ios/web/ navigation. Do not trigger external callbacks. + if (IsPlaceholderUrl(url)) + return; + PageLoadCompletionStatus load_completion_status = load_success ? PageLoadCompletionStatus::SUCCESS : PageLoadCompletionStatus::FAILURE; @@ -673,7 +681,8 @@ GURL WebStateImpl::GetCurrentURL(URLVerificationTrustLevel* trust_level) const { GURL URL = [web_controller_ currentURLWithTrustLevel:trust_level]; bool equalOrigins = URL.GetOrigin() == GetLastCommittedURL().GetOrigin(); - DCHECK(equalOrigins); + DCHECK(equalOrigins) << "Origin mismatch. URL: " << URL.spec() + << " Last committed: " << GetLastCommittedURL().spec(); UMA_HISTOGRAM_BOOLEAN("Web.CurrentOriginEqualsLastCommittedOrigin", equalOrigins); return URL; @@ -726,11 +735,21 @@ } void WebStateImpl::OnNavigationStarted(web::NavigationContext* context) { + // Native Content and WebUI placeholder URL is an internal implementation + // detail of //ios/web/ navigation. Do not trigger external callbacks. + if (IsPlaceholderUrl(context->GetUrl())) + return; + for (auto& observer : observers_) observer.DidStartNavigation(this, context); } void WebStateImpl::OnNavigationFinished(web::NavigationContext* context) { + // Native Content and WebUI placeholder URL is an internal implementation + // detail of //ios/web/ navigation. Do not trigger external callbacks. + if (IsPlaceholderUrl(context->GetUrl())) + return; + for (auto& observer : observers_) observer.DidFinishNavigation(this, context);
diff --git a/ios/web/web_state/web_state_impl_unittest.mm b/ios/web/web_state/web_state_impl_unittest.mm index d187bd8..fc1b4cc3 100644 --- a/ios/web/web_state/web_state_impl_unittest.mm +++ b/ios/web/web_state/web_state_impl_unittest.mm
@@ -16,6 +16,7 @@ #import "base/mac/bind_objc_block.h" #include "base/memory/ptr_util.h" #import "base/test/ios/wait_util.h" +#include "ios/web/navigation/placeholder_navigation_util.h" #import "ios/web/public/java_script_dialog_presenter.h" #include "ios/web/public/load_committed_details.h" #import "ios/web/public/test/fakes/fake_navigation_context.h" @@ -476,6 +477,28 @@ EXPECT_EQ(nullptr, observer->web_state()); } +// Tests that placeholder navigations are not visible to WebStateObservers. +TEST_F(WebStateImplTest, PlaceholderNavigationNotExposedToObservers) { + TestWebStateObserver observer(web_state_.get()); + FakeNavigationContext context; + context.SetUrl(placeholder_navigation_util::CreatePlaceholderUrlForUrl( + GURL("chrome://newtab"))); + + // Test that OnPageLoaded() is not called. + web_state_->OnPageLoaded(context.GetUrl(), true /* load_success */); + EXPECT_FALSE(observer.load_page_info()); + web_state_->OnPageLoaded(context.GetUrl(), false /* load_success */); + EXPECT_FALSE(observer.load_page_info()); + + // Test that OnNavigationStarted() is not called. + web_state_->OnNavigationStarted(&context); + EXPECT_FALSE(observer.did_start_navigation_info()); + + // Test that OnNavigationFinished() is not called. + web_state_->OnNavigationFinished(&context); + EXPECT_FALSE(observer.did_finish_navigation_info()); +} + // Tests that WebStateDelegate methods appropriately called. TEST_F(WebStateImplTest, DelegateTest) { TestWebStateDelegate delegate;
diff --git a/media/audio/alsa/alsa_output_unittest.cc b/media/audio/alsa/alsa_output_unittest.cc index 10c9e03..a5b316b 100644 --- a/media/audio/alsa/alsa_output_unittest.cc +++ b/media/audio/alsa/alsa_output_unittest.cc
@@ -3,9 +3,9 @@ // found in the LICENSE file. #include <stdint.h> +#include <memory> #include "base/macros.h" -#include "base/memory/ptr_util.h" #include "base/run_loop.h" #include "base/strings/stringprintf.h" #include "base/test/simple_test_tick_clock.h" @@ -81,7 +81,7 @@ class MockAudioManagerAlsa : public AudioManagerAlsa { public: MockAudioManagerAlsa() - : AudioManagerAlsa(base::MakeUnique<TestAudioThread>(), + : AudioManagerAlsa(std::make_unique<TestAudioThread>(), &fake_audio_log_factory_) {} MOCK_METHOD0(Init, void()); MOCK_METHOD0(HasAudioOutputDevices, bool());
diff --git a/media/audio/android/audio_android_unittest.cc b/media/audio/android/audio_android_unittest.cc index f358b38..78354fe5f6 100644 --- a/media/audio/android/audio_android_unittest.cc +++ b/media/audio/android/audio_android_unittest.cc
@@ -420,7 +420,7 @@ AudioAndroidOutputTest() : loop_(new base::MessageLoopForUI()), audio_manager_(AudioManager::CreateForTesting( - base::MakeUnique<TestAudioThread>())), + std::make_unique<TestAudioThread>())), audio_manager_device_info_(audio_manager_.get()), audio_output_stream_(NULL) { // Flush the message loop to ensure that AudioManager is fully initialized.
diff --git a/media/audio/android/audio_manager_android.cc b/media/audio/android/audio_manager_android.cc index 61abb0cc..e3162e5eb 100644 --- a/media/audio/android/audio_manager_android.cc +++ b/media/audio/android/audio_manager_android.cc
@@ -4,13 +4,14 @@ #include "media/audio/android/audio_manager_android.h" +#include <memory> + #include "base/android/build_info.h" #include "base/android/jni_array.h" #include "base/android/jni_string.h" #include "base/android/scoped_java_ref.h" #include "base/bind.h" #include "base/logging.h" -#include "base/memory/ptr_util.h" #include "base/message_loop/message_loop.h" #include "base/strings/string_number_conversions.h" #include "jni/AudioManagerAndroid_jni.h" @@ -51,7 +52,7 @@ std::unique_ptr<AudioManager> CreateAudioManager( std::unique_ptr<AudioThread> audio_thread, AudioLogFactory* audio_log_factory) { - return base::MakeUnique<AudioManagerAndroid>(std::move(audio_thread), + return std::make_unique<AudioManagerAndroid>(std::move(audio_thread), audio_log_factory); }
diff --git a/media/audio/audio_debug_recording_helper.cc b/media/audio/audio_debug_recording_helper.cc index a21f12cf..ff10a5aa 100644 --- a/media/audio/audio_debug_recording_helper.cc +++ b/media/audio/audio_debug_recording_helper.cc
@@ -4,9 +4,10 @@ #include "media/audio/audio_debug_recording_helper.h" +#include <memory> + #include "base/bind.h" #include "base/files/file_path.h" -#include "base/memory/ptr_util.h" #include "base/single_thread_task_runner.h" #include "media/audio/audio_debug_file_writer.h" @@ -92,7 +93,7 @@ std::unique_ptr<AudioDebugFileWriter> AudioDebugRecordingHelper::CreateAudioDebugFileWriter( const AudioParameters& params) { - return base::MakeUnique<AudioDebugFileWriter>(params); + return std::make_unique<AudioDebugFileWriter>(params); } } // namespace media
diff --git a/media/audio/audio_debug_recording_helper_unittest.cc b/media/audio/audio_debug_recording_helper_unittest.cc index 2976f6e..7b9f4462 100644 --- a/media/audio/audio_debug_recording_helper_unittest.cc +++ b/media/audio/audio_debug_recording_helper_unittest.cc
@@ -4,6 +4,8 @@ #include "media/audio/audio_debug_recording_helper.h" +#include <memory> + #include "base/bind.h" #include "base/files/file_path.h" #include "base/logging.h" @@ -123,7 +125,7 @@ std::unique_ptr<AudioDebugRecordingHelper> CreateRecordingHelper( const AudioParameters& params, base::OnceClosure on_destruction_closure) { - return base::MakeUnique<AudioDebugRecordingHelperUnderTest>( + return std::make_unique<AudioDebugRecordingHelperUnderTest>( params, scoped_task_environment_.GetMainThreadTaskRunner(), std::move(on_destruction_closure)); }
diff --git a/media/audio/audio_debug_recording_manager.cc b/media/audio/audio_debug_recording_manager.cc index 0bca5cdc..685c833a 100644 --- a/media/audio/audio_debug_recording_manager.cc +++ b/media/audio/audio_debug_recording_manager.cc
@@ -4,6 +4,8 @@ #include "media/audio/audio_debug_recording_manager.h" +#include <memory> + #include "base/bind.h" #include "base/files/file_path.h" #include "base/memory/ptr_util.h" @@ -102,7 +104,7 @@ const AudioParameters& params, scoped_refptr<base::SingleThreadTaskRunner> task_runner, base::OnceClosure on_destruction_closure) { - return base::MakeUnique<AudioDebugRecordingHelper>( + return std::make_unique<AudioDebugRecordingHelper>( params, task_runner, std::move(on_destruction_closure)); }
diff --git a/media/audio/audio_debug_recording_manager_unittest.cc b/media/audio/audio_debug_recording_manager_unittest.cc index 9fea85d..7c4f3e5 100644 --- a/media/audio/audio_debug_recording_manager_unittest.cc +++ b/media/audio/audio_debug_recording_manager_unittest.cc
@@ -4,12 +4,12 @@ #include "media/audio/audio_debug_recording_manager.h" +#include <memory> #include <vector> #include "base/bind.h" #include "base/files/file_path.h" #include "base/logging.h" -#include "base/memory/ptr_util.h" #include "base/single_thread_task_runner.h" #include "base/strings/string_number_conversions.h" #include "base/test/test_message_loop.h" @@ -97,7 +97,7 @@ const AudioParameters& params, scoped_refptr<base::SingleThreadTaskRunner> task_runner, base::OnceClosure on_destruction_closure) override { - return base::MakeUnique<MockAudioDebugRecordingHelper>( + return std::make_unique<MockAudioDebugRecordingHelper>( params, std::move(task_runner), std::move(on_destruction_closure)); }
diff --git a/media/audio/audio_input_controller_unittest.cc b/media/audio/audio_input_controller_unittest.cc index 9e68797..c866827 100644 --- a/media/audio/audio_input_controller_unittest.cc +++ b/media/audio/audio_input_controller_unittest.cc
@@ -2,10 +2,11 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. +#include <memory> + #include "media/audio/audio_input_controller.h" #include "base/bind.h" #include "base/macros.h" -#include "base/memory/ptr_util.h" #include "base/message_loop/message_loop.h" #include "base/run_loop.h" #include "base/single_thread_task_runner.h" @@ -101,7 +102,7 @@ : suspend_event_(WaitableEvent::ResetPolicy::AUTOMATIC, WaitableEvent::InitialState::NOT_SIGNALED) { audio_manager_ = - AudioManager::CreateForTesting(base::MakeUnique<AudioThreadImpl>()); + AudioManager::CreateForTesting(std::make_unique<AudioThreadImpl>()); } ~AudioInputControllerTest() override { audio_manager_->Shutdown();
diff --git a/media/audio/audio_input_unittest.cc b/media/audio/audio_input_unittest.cc index 7327200..c74c738 100644 --- a/media/audio/audio_input_unittest.cc +++ b/media/audio/audio_input_unittest.cc
@@ -53,7 +53,7 @@ AudioInputTest() : message_loop_(base::MessageLoop::TYPE_UI), audio_manager_(AudioManager::CreateForTesting( - base::MakeUnique<TestAudioThread>())), + std::make_unique<TestAudioThread>())), audio_input_stream_(NULL) { base::RunLoop().RunUntilIdle(); }
diff --git a/media/audio/audio_low_latency_input_output_unittest.cc b/media/audio/audio_low_latency_input_output_unittest.cc index f888015..9ab51de 100644 --- a/media/audio/audio_low_latency_input_output_unittest.cc +++ b/media/audio/audio_low_latency_input_output_unittest.cc
@@ -76,7 +76,7 @@ protected: AudioLowLatencyInputOutputTest() { audio_manager_ = - AudioManager::CreateForTesting(base::MakeUnique<TestAudioThread>()); + AudioManager::CreateForTesting(std::make_unique<TestAudioThread>()); } ~AudioLowLatencyInputOutputTest() override { audio_manager_->Shutdown(); }
diff --git a/media/audio/audio_manager_base.cc b/media/audio/audio_manager_base.cc index 09dc482..858f586 100644 --- a/media/audio/audio_manager_base.cc +++ b/media/audio/audio_manager_base.cc
@@ -4,11 +4,12 @@ #include "media/audio/audio_manager_base.h" +#include <memory> + #include "base/bind.h" #include "base/bind_helpers.h" #include "base/command_line.h" #include "base/macros.h" -#include "base/memory/ptr_util.h" #include "base/metrics/histogram_macros.h" #include "base/optional.h" #include "base/single_thread_task_runner.h" @@ -395,7 +396,7 @@ } std::unique_ptr<DispatcherParams> dispatcher_params = - base::MakeUnique<DispatcherParams>(params, output_params, + std::make_unique<DispatcherParams>(params, output_params, output_device_id); auto it = std::find_if(output_dispatchers_.begin(), output_dispatchers_.end(), @@ -410,7 +411,7 @@ !output_params.IsBitstreamFormat()) { // Using unretained for |debug_recording_manager_| is safe since it // outlives the dispatchers (cleared in ShutdownOnAudioThread()). - dispatcher = base::MakeUnique<AudioOutputResampler>( + dispatcher = std::make_unique<AudioOutputResampler>( this, params, output_params, output_device_id, kCloseDelay, debug_recording_manager_ ? base::BindRepeating( @@ -419,7 +420,7 @@ FILE_PATH_LITERAL("output")) : base::BindRepeating(&GetNullptrAudioDebugRecorder)); } else { - dispatcher = base::MakeUnique<AudioOutputDispatcherImpl>( + dispatcher = std::make_unique<AudioOutputDispatcherImpl>( this, output_params, output_device_id, kCloseDelay); } @@ -589,7 +590,7 @@ std::unique_ptr<AudioDebugRecordingManager> AudioManagerBase::CreateAudioDebugRecordingManager( scoped_refptr<base::SingleThreadTaskRunner> task_runner) { - return base::MakeUnique<AudioDebugRecordingManager>(std::move(task_runner)); + return std::make_unique<AudioDebugRecordingManager>(std::move(task_runner)); } void AudioManagerBase::SetMaxStreamCountForTesting(int max_input,
diff --git a/media/audio/audio_manager_unittest.cc b/media/audio/audio_manager_unittest.cc index ee01d46a..60ed847 100644 --- a/media/audio/audio_manager_unittest.cc +++ b/media/audio/audio_manager_unittest.cc
@@ -12,7 +12,6 @@ #include "base/bind.h" #include "base/environment.h" #include "base/logging.h" -#include "base/memory/ptr_util.h" #include "base/run_loop.h" #include "base/single_thread_task_runner.h" #include "base/strings/string_number_conversions.h" @@ -68,7 +67,7 @@ struct TestAudioManagerFactory { static std::unique_ptr<AudioManager> Create( AudioLogFactory* audio_log_factory) { - return base::MakeUnique<T>(base::MakeUnique<TestAudioThread>(), + return std::make_unique<T>(std::make_unique<TestAudioThread>(), audio_log_factory); } }; @@ -82,8 +81,8 @@ pa_context* pa_context = nullptr; if (!pulse::InitPulse(&pa_mainloop, &pa_context)) return nullptr; - return base::MakeUnique<AudioManagerPulse>( - base::MakeUnique<TestAudioThread>(), audio_log_factory, pa_mainloop, + return std::make_unique<AudioManagerPulse>( + std::make_unique<TestAudioThread>(), audio_log_factory, pa_mainloop, pa_context); } }; @@ -93,7 +92,7 @@ struct TestAudioManagerFactory<std::nullptr_t> { static std::unique_ptr<AudioManager> Create( AudioLogFactory* audio_log_factory) { - return AudioManager::CreateForTesting(base::MakeUnique<TestAudioThread>()); + return AudioManager::CreateForTesting(std::make_unique<TestAudioThread>()); } }; @@ -389,7 +388,7 @@ // TODO(alokp): We should perhaps do this in AudioManager::Create(). base::RunLoop().RunUntilIdle(); device_info_accessor_ = - base::MakeUnique<AudioDeviceInfoAccessorForTests>(audio_manager_.get()); + std::make_unique<AudioDeviceInfoAccessorForTests>(audio_manager_.get()); } base::TestMessageLoop message_loop_; @@ -674,7 +673,7 @@ std::unique_ptr<AudioDebugRecordingManager> CreateAudioDebugRecordingManager( scoped_refptr<base::SingleThreadTaskRunner> task_runner) override { - return base::MakeUnique<MockAudioDebugRecordingManager>( + return std::make_unique<MockAudioDebugRecordingManager>( std::move(task_runner)); } };
diff --git a/media/audio/audio_output_controller_unittest.cc b/media/audio/audio_output_controller_unittest.cc index f1e1c106..d6ff909 100644 --- a/media/audio/audio_output_controller_unittest.cc +++ b/media/audio/audio_output_controller_unittest.cc
@@ -115,7 +115,7 @@ public: AudioOutputControllerTest() : audio_manager_(AudioManager::CreateForTesting( - base::MakeUnique<TestAudioThread>())) { + std::make_unique<TestAudioThread>())) { EXPECT_CALL(mock_event_handler_, OnLog(_)).Times(testing::AnyNumber()); base::RunLoop().RunUntilIdle(); }
diff --git a/media/audio/audio_output_proxy_unittest.cc b/media/audio/audio_output_proxy_unittest.cc index 295a98c6..81d463e 100644 --- a/media/audio/audio_output_proxy_unittest.cc +++ b/media/audio/audio_output_proxy_unittest.cc
@@ -8,7 +8,6 @@ #include <string> #include <utility> -#include "base/memory/ptr_util.h" #include "base/message_loop/message_loop.h" #include "base/run_loop.h" #include "base/single_thread_task_runner.h" @@ -101,7 +100,7 @@ class MockAudioManager : public AudioManagerBase { public: MockAudioManager() - : AudioManagerBase(base::MakeUnique<TestAudioThread>(), + : AudioManagerBase(std::make_unique<TestAudioThread>(), &fake_audio_log_factory_) {} ~MockAudioManager() override { Shutdown(); } @@ -183,7 +182,7 @@ } virtual void InitDispatcher(base::TimeDelta close_delay) { - dispatcher_impl_ = base::MakeUnique<AudioOutputDispatcherImpl>( + dispatcher_impl_ = std::make_unique<AudioOutputDispatcherImpl>( &manager(), params_, std::string(), close_delay); } @@ -505,7 +504,7 @@ resampler_params_ = AudioParameters( AudioParameters::AUDIO_PCM_LOW_LATENCY, CHANNEL_LAYOUT_STEREO, 16000, 16, 1024); - resampler_ = base::MakeUnique<AudioOutputResampler>( + resampler_ = std::make_unique<AudioOutputResampler>( &manager(), params_, resampler_params_, std::string(), close_delay, base::BindRepeating(&RegisterDebugRecording)); }
diff --git a/media/audio/audio_output_unittest.cc b/media/audio/audio_output_unittest.cc index f647df02..22cfcd4a 100644 --- a/media/audio/audio_output_unittest.cc +++ b/media/audio/audio_output_unittest.cc
@@ -26,9 +26,9 @@ public: AudioOutputTest() { audio_manager_ = - AudioManager::CreateForTesting(base::MakeUnique<TestAudioThread>()); + AudioManager::CreateForTesting(std::make_unique<TestAudioThread>()); audio_manager_device_info_ = - base::MakeUnique<AudioDeviceInfoAccessorForTests>(audio_manager_.get()); + std::make_unique<AudioDeviceInfoAccessorForTests>(audio_manager_.get()); base::RunLoop().RunUntilIdle(); } ~AudioOutputTest() override {
diff --git a/media/audio/cras/cras_input_unittest.cc b/media/audio/cras/cras_input_unittest.cc index 63d0f0f8..8b1db70db 100644 --- a/media/audio/cras/cras_input_unittest.cc +++ b/media/audio/cras/cras_input_unittest.cc
@@ -45,7 +45,7 @@ class MockAudioManagerCrasInput : public AudioManagerCras { public: MockAudioManagerCrasInput() - : AudioManagerCras(base::MakeUnique<TestAudioThread>(), + : AudioManagerCras(std::make_unique<TestAudioThread>(), &fake_audio_log_factory_) {} // We need to override this function in order to skip checking the number
diff --git a/media/audio/cras/cras_unified_unittest.cc b/media/audio/cras/cras_unified_unittest.cc index 7da8fc0..b47b469 100644 --- a/media/audio/cras/cras_unified_unittest.cc +++ b/media/audio/cras/cras_unified_unittest.cc
@@ -41,7 +41,7 @@ class MockAudioManagerCras : public AudioManagerCras { public: MockAudioManagerCras() - : AudioManagerCras(base::MakeUnique<TestAudioThread>(), + : AudioManagerCras(std::make_unique<TestAudioThread>(), &fake_audio_log_factory_) {} // We need to override this function in order to skip the checking the number
diff --git a/media/audio/fake_audio_input_stream.cc b/media/audio/fake_audio_input_stream.cc index edca251..969eb3e1 100644 --- a/media/audio/fake_audio_input_stream.cc +++ b/media/audio/fake_audio_input_stream.cc
@@ -132,9 +132,9 @@ << switches::kUseFileForFakeAudioCapture << "."; looping = false; } - return base::MakeUnique<FileSource>(params_, path_to_wav_file, looping); + return std::make_unique<FileSource>(params_, path_to_wav_file, looping); } - return base::MakeUnique<BeepingSource>(params_); + return std::make_unique<BeepingSource>(params_); } void FakeAudioInputStream::BeepOnce() {
diff --git a/media/audio/fake_audio_log_factory.cc b/media/audio/fake_audio_log_factory.cc index 562540b..d097a80 100644 --- a/media/audio/fake_audio_log_factory.cc +++ b/media/audio/fake_audio_log_factory.cc
@@ -4,10 +4,9 @@ #include "media/audio/fake_audio_log_factory.h" +#include <memory> #include <string> -#include "base/memory/ptr_util.h" - namespace media { class FakeAudioLogImpl : public AudioLog { @@ -32,7 +31,7 @@ std::unique_ptr<AudioLog> FakeAudioLogFactory::CreateAudioLog( AudioComponent component) { - return base::MakeUnique<FakeAudioLogImpl>(); + return std::make_unique<FakeAudioLogImpl>(); } } // namespace media
diff --git a/media/audio/fuchsia/audio_manager_fuchsia.cc b/media/audio/fuchsia/audio_manager_fuchsia.cc index a11fff48..7e7a96a 100644 --- a/media/audio/fuchsia/audio_manager_fuchsia.cc +++ b/media/audio/fuchsia/audio_manager_fuchsia.cc
@@ -4,9 +4,10 @@ #include "media/audio/fuchsia/audio_manager_fuchsia.h" +#include <memory> + #include <media/audio.h> -#include "base/memory/ptr_util.h" #include "media/audio/fuchsia/audio_output_stream_fuchsia.h" namespace media { @@ -141,7 +142,7 @@ std::unique_ptr<AudioManager> CreateAudioManager( std::unique_ptr<AudioThread> audio_thread, AudioLogFactory* audio_log_factory) { - return base::MakeUnique<AudioManagerFuchsia>(std::move(audio_thread), + return std::make_unique<AudioManagerFuchsia>(std::move(audio_thread), audio_log_factory); }
diff --git a/media/audio/linux/audio_manager_linux.cc b/media/audio/linux/audio_manager_linux.cc index 97b2c5ca..5d70354 100644 --- a/media/audio/linux/audio_manager_linux.cc +++ b/media/audio/linux/audio_manager_linux.cc
@@ -2,8 +2,9 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. +#include <memory> + #include "base/command_line.h" -#include "base/memory/ptr_util.h" #include "base/metrics/histogram_macros.h" #include "media/base/media_switches.h" @@ -35,7 +36,7 @@ #if defined(USE_CRAS) if (base::CommandLine::ForCurrentProcess()->HasSwitch(switches::kUseCras)) { UMA_HISTOGRAM_ENUMERATION("Media.LinuxAudioIO", kCras, kAudioIOMax + 1); - return base::MakeUnique<AudioManagerCras>(std::move(audio_thread), + return std::make_unique<AudioManagerCras>(std::move(audio_thread), audio_log_factory); } #endif @@ -45,7 +46,7 @@ pa_context* pa_context = nullptr; if (pulse::InitPulse(&pa_mainloop, &pa_context)) { UMA_HISTOGRAM_ENUMERATION("Media.LinuxAudioIO", kPulse, kAudioIOMax + 1); - return base::MakeUnique<AudioManagerPulse>( + return std::make_unique<AudioManagerPulse>( std::move(audio_thread), audio_log_factory, pa_mainloop, pa_context); } DVLOG(1) << "PulseAudio is not available on the OS"; @@ -53,10 +54,10 @@ #if defined(USE_ALSA) UMA_HISTOGRAM_ENUMERATION("Media.LinuxAudioIO", kAlsa, kAudioIOMax + 1); - return base::MakeUnique<AudioManagerAlsa>(std::move(audio_thread), + return std::make_unique<AudioManagerAlsa>(std::move(audio_thread), audio_log_factory); #else - return base::MakeUnique<FakeAudioManager>(std::move(audio_thread), + return std::make_unique<FakeAudioManager>(std::move(audio_thread), audio_log_factory); #endif }
diff --git a/media/audio/mac/audio_auhal_mac_unittest.cc b/media/audio/mac/audio_auhal_mac_unittest.cc index 1af1fee..03eb7544 100644 --- a/media/audio/mac/audio_auhal_mac_unittest.cc +++ b/media/audio/mac/audio_auhal_mac_unittest.cc
@@ -41,7 +41,7 @@ AUHALStreamTest() : message_loop_(base::MessageLoop::TYPE_UI), manager_(AudioManager::CreateForTesting( - base::MakeUnique<TestAudioThread>())), + std::make_unique<TestAudioThread>())), manager_device_info_(manager_.get()) { // Wait for the AudioManager to finish any initialization on the audio loop. base::RunLoop().RunUntilIdle();
diff --git a/media/audio/mac/audio_low_latency_input_mac_unittest.cc b/media/audio/mac/audio_low_latency_input_mac_unittest.cc index 64d6c05..73a24b6 100644 --- a/media/audio/mac/audio_low_latency_input_mac_unittest.cc +++ b/media/audio/mac/audio_low_latency_input_mac_unittest.cc
@@ -113,7 +113,7 @@ MacAudioInputTest() : message_loop_(base::MessageLoop::TYPE_UI), audio_manager_(AudioManager::CreateForTesting( - base::MakeUnique<TestAudioThread>())) { + std::make_unique<TestAudioThread>())) { // Wait for the AudioManager to finish any initialization on the audio loop. base::RunLoop().RunUntilIdle(); }
diff --git a/media/audio/mac/audio_manager_mac.cc b/media/audio/mac/audio_manager_mac.cc index b09620b0..1601952 100644 --- a/media/audio/mac/audio_manager_mac.cc +++ b/media/audio/mac/audio_manager_mac.cc
@@ -1392,7 +1392,7 @@ std::unique_ptr<AudioManager> CreateAudioManager( std::unique_ptr<AudioThread> audio_thread, AudioLogFactory* audio_log_factory) { - return base::MakeUnique<AudioManagerMac>(std::move(audio_thread), + return std::make_unique<AudioManagerMac>(std::move(audio_thread), audio_log_factory); }
diff --git a/media/audio/sounds/audio_stream_handler_unittest.cc b/media/audio/sounds/audio_stream_handler_unittest.cc index 52bfde3..b71edb6 100644 --- a/media/audio/sounds/audio_stream_handler_unittest.cc +++ b/media/audio/sounds/audio_stream_handler_unittest.cc
@@ -32,7 +32,7 @@ void SetUp() override { audio_manager_ = - AudioManager::CreateForTesting(base::MakeUnique<TestAudioThread>()); + AudioManager::CreateForTesting(std::make_unique<TestAudioThread>()); base::RunLoop().RunUntilIdle(); base::StringPiece data(kTestAudioData, arraysize(kTestAudioData));
diff --git a/media/audio/sounds/sounds_manager_unittest.cc b/media/audio/sounds/sounds_manager_unittest.cc index 0fad2d0..ddc433b 100644 --- a/media/audio/sounds/sounds_manager_unittest.cc +++ b/media/audio/sounds/sounds_manager_unittest.cc
@@ -28,7 +28,7 @@ void SetUp() override { audio_manager_ = - AudioManager::CreateForTesting(base::MakeUnique<TestAudioThread>()); + AudioManager::CreateForTesting(std::make_unique<TestAudioThread>()); SoundsManager::Create(); base::RunLoop().RunUntilIdle(); }
diff --git a/media/audio/test_audio_thread.cc b/media/audio/test_audio_thread.cc index 8b4cebcd..aef2ea41 100644 --- a/media/audio/test_audio_thread.cc +++ b/media/audio/test_audio_thread.cc
@@ -13,7 +13,7 @@ TestAudioThread::TestAudioThread(bool use_real_thread) { if (use_real_thread) { - thread_ = base::MakeUnique<base::Thread>("AudioThread"); + thread_ = std::make_unique<base::Thread>("AudioThread"); #if defined(OS_WIN) thread_->init_com_with_mta(true); #endif
diff --git a/media/audio/win/audio_low_latency_input_win_unittest.cc b/media/audio/win/audio_low_latency_input_win_unittest.cc index 96a41fa..3a25097d 100644 --- a/media/audio/win/audio_low_latency_input_win_unittest.cc +++ b/media/audio/win/audio_low_latency_input_win_unittest.cc
@@ -15,7 +15,6 @@ #include "base/environment.h" #include "base/files/file_util.h" #include "base/macros.h" -#include "base/memory/ptr_util.h" #include "base/message_loop/message_loop.h" #include "base/path_service.h" #include "base/run_loop.h" @@ -266,7 +265,7 @@ public: WinAudioInputTest() { audio_manager_ = - AudioManager::CreateForTesting(base::MakeUnique<TestAudioThread>()); + AudioManager::CreateForTesting(std::make_unique<TestAudioThread>()); base::RunLoop().RunUntilIdle(); } ~WinAudioInputTest() override { audio_manager_->Shutdown(); }
diff --git a/media/audio/win/audio_low_latency_output_win_unittest.cc b/media/audio/win/audio_low_latency_output_win_unittest.cc index ce702dd..a57ec87 100644 --- a/media/audio/win/audio_low_latency_output_win_unittest.cc +++ b/media/audio/win/audio_low_latency_output_win_unittest.cc
@@ -239,7 +239,7 @@ public: WASAPIAudioOutputStreamTest() { audio_manager_ = - AudioManager::CreateForTesting(base::MakeUnique<TestAudioThread>()); + AudioManager::CreateForTesting(std::make_unique<TestAudioThread>()); base::RunLoop().RunUntilIdle(); } ~WASAPIAudioOutputStreamTest() override { audio_manager_->Shutdown(); }
diff --git a/media/audio/win/audio_manager_win.cc b/media/audio/win/audio_manager_win.cc index c1e0941c..3e8015df 100644 --- a/media/audio/win/audio_manager_win.cc +++ b/media/audio/win/audio_manager_win.cc
@@ -359,7 +359,7 @@ std::unique_ptr<AudioManager> CreateAudioManager( std::unique_ptr<AudioThread> audio_thread, AudioLogFactory* audio_log_factory) { - return base::MakeUnique<AudioManagerWin>(std::move(audio_thread), + return std::make_unique<AudioManagerWin>(std::move(audio_thread), audio_log_factory); }
diff --git a/media/audio/win/audio_output_win_unittest.cc b/media/audio/win/audio_output_win_unittest.cc index 24f0793c..975c222 100644 --- a/media/audio/win/audio_output_win_unittest.cc +++ b/media/audio/win/audio_output_win_unittest.cc
@@ -156,9 +156,9 @@ public: WinAudioTest() { audio_manager_ = - AudioManager::CreateForTesting(base::MakeUnique<TestAudioThread>()); + AudioManager::CreateForTesting(std::make_unique<TestAudioThread>()); audio_manager_device_info_ = - base::MakeUnique<AudioDeviceInfoAccessorForTests>(audio_manager_.get()); + std::make_unique<AudioDeviceInfoAccessorForTests>(audio_manager_.get()); base::RunLoop().RunUntilIdle(); } ~WinAudioTest() override { audio_manager_->Shutdown(); }
diff --git a/media/base/android/media_drm_bridge.cc b/media/base/android/media_drm_bridge.cc index c95eb22..916ebea 100644 --- a/media/base/android/media_drm_bridge.cc +++ b/media/base/android/media_drm_bridge.cc
@@ -6,6 +6,7 @@ #include <stddef.h> #include <algorithm> +#include <memory> #include <utility> #include "base/android/build_info.h" @@ -18,7 +19,6 @@ #include "base/location.h" #include "base/logging.h" #include "base/macros.h" -#include "base/memory/ptr_util.h" #include "base/single_thread_task_runner.h" #include "base/strings/string_number_conversions.h" #include "base/strings/string_util.h" @@ -386,7 +386,7 @@ } // MediaDrmStorage may be lazy created in MediaDrmStorageBridge. - auto storage = base::MakeUnique<MediaDrmStorageBridge>(); + auto storage = std::make_unique<MediaDrmStorageBridge>(); MediaDrmStorageBridge* raw_storage = storage.get(); CreateMediaDrmBridgeCB create_media_drm_bridge_cb = base::BindOnce( @@ -424,7 +424,7 @@ } return CreateInternal( - scheme_uuid, security_level, base::MakeUnique<MediaDrmStorageBridge>(), + scheme_uuid, security_level, std::make_unique<MediaDrmStorageBridge>(), create_fetcher_cb, SessionMessageCB(), SessionClosedCB(), SessionKeysChangeCB(), SessionExpirationUpdateCB(), origin_id); } @@ -797,7 +797,7 @@ << key_status; cdm_keys_info.push_back( - base::MakeUnique<CdmKeyInformation>(key_id, key_status, 0)); + std::make_unique<CdmKeyInformation>(key_id, key_status, 0)); } task_runner_->PostTask(
diff --git a/media/base/android/media_service_throttler.cc b/media/base/android/media_service_throttler.cc index 5e502652..911c05f 100644 --- a/media/base/android/media_service_throttler.cc +++ b/media/base/android/media_service_throttler.cc
@@ -4,8 +4,9 @@ #include "media/base/android/media_service_throttler.h" +#include <memory> + #include "base/bind.h" -#include "base/memory/ptr_util.h" #include "base/threading/thread_task_runner_handle.h" #include "base/time/default_tick_clock.h" #include "media/base/android/media_server_crash_listener.h" @@ -194,7 +195,7 @@ if (!crash_listener_) { // base::Unretained is safe here because the MediaServiceThrottler will live // until the process is terminated. - crash_listener_ = base::MakeUnique<MediaServerCrashListener>( + crash_listener_ = std::make_unique<MediaServerCrashListener>( base::Bind(&MediaServiceThrottler::OnMediaServerCrash, base::Unretained(this)), crash_listener_task_runner_); @@ -222,7 +223,7 @@ crash_listener_task_runner_ = crash_listener_task_runner; // Re-create the crash listener. - crash_listener_ = base::MakeUnique<MediaServerCrashListener>( + crash_listener_ = std::make_unique<MediaServerCrashListener>( MediaServerCrashListener::OnMediaServerCrashCB(), crash_listener_task_runner_); }
diff --git a/media/base/android/mock_android_overlay.cc b/media/base/android/mock_android_overlay.cc index 84c2aa9..e20e5eb 100644 --- a/media/base/android/mock_android_overlay.cc +++ b/media/base/android/mock_android_overlay.cc
@@ -4,8 +4,9 @@ #include "media/base/android/mock_android_overlay.h" +#include <memory> + #include "base/bind.h" -#include "base/memory/ptr_util.h" #include "testing/gtest/include/gtest/gtest.h" namespace media { @@ -19,7 +20,7 @@ MockAndroidOverlay::~MockAndroidOverlay() {} void MockAndroidOverlay::SetConfig(AndroidOverlayConfig config) { - config_ = base::MakeUnique<AndroidOverlayConfig>(std::move(config)); + config_ = std::make_unique<AndroidOverlayConfig>(std::move(config)); } MockAndroidOverlay::Callbacks MockAndroidOverlay::GetCallbacks() {
diff --git a/media/base/android/mock_media_codec_bridge.cc b/media/base/android/mock_media_codec_bridge.cc index e459075..e75d08e 100644 --- a/media/base/android/mock_media_codec_bridge.cc +++ b/media/base/android/mock_media_codec_bridge.cc
@@ -57,7 +57,7 @@ const VideoColorSpace& color_space, const base::Optional<HDRMetadata>& hdr_metadata, bool allow_adaptive_playback) { - return base::MakeUnique<MockMediaCodecBridge>(); + return std::make_unique<MockMediaCodecBridge>(); } } // namespace media
diff --git a/media/base/android/test_destruction_observable.cc b/media/base/android/test_destruction_observable.cc index 0732515..ee9a817 100644 --- a/media/base/android/test_destruction_observable.cc +++ b/media/base/android/test_destruction_observable.cc
@@ -15,7 +15,7 @@ std::unique_ptr<DestructionObserver> DestructionObservable::CreateDestructionObserver() { - return base::MakeUnique<DestructionObserver>(this); + return std::make_unique<DestructionObserver>(this); } DestructionObserver::DestructionObserver(DestructionObservable* observable)
diff --git a/media/base/audio_converter_unittest.cc b/media/base/audio_converter_unittest.cc index d1cd44f..f9abac00 100644 --- a/media/base/audio_converter_unittest.cc +++ b/media/base/audio_converter_unittest.cc
@@ -9,7 +9,6 @@ #include <memory> #include "base/macros.h" -#include "base/memory/ptr_util.h" #include "base/strings/string_number_conversions.h" #include "media/base/audio_timestamp_helper.h" #include "media/base/fake_audio_render_callback.h" @@ -69,7 +68,7 @@ for (int i = 0; i < count; ++i) { fake_callbacks_.push_back( - base::MakeUnique<FakeAudioRenderCallback>(step, kSampleRate)); + std::make_unique<FakeAudioRenderCallback>(step, kSampleRate)); converter_->AddInput(fake_callbacks_[i].get()); } }
diff --git a/media/base/audio_renderer_mixer_unittest.cc b/media/base/audio_renderer_mixer_unittest.cc index 9dbfb77..54b1b19 100644 --- a/media/base/audio_renderer_mixer_unittest.cc +++ b/media/base/audio_renderer_mixer_unittest.cc
@@ -11,7 +11,6 @@ #include "base/bind.h" #include "base/bind_helpers.h" #include "base/macros.h" -#include "base/memory/ptr_util.h" #include "base/synchronization/waitable_event.h" #include "base/threading/platform_thread.h" #include "media/base/audio_renderer_mixer_input.h" @@ -120,7 +119,7 @@ static_cast<double>(output_parameters_.frames_per_buffer())); for (int j = 0; j < inputs_per_sample_rate; ++j, ++input) { - fake_callbacks_.push_back(base::MakeUnique<FakeAudioRenderCallback>( + fake_callbacks_.push_back(std::make_unique<FakeAudioRenderCallback>( step, output_parameters_.sample_rate())); mixer_inputs_.push_back(CreateMixerInput()); mixer_inputs_[input]->Initialize(input_parameters_[i],
diff --git a/media/base/bind_to_current_loop.h b/media/base/bind_to_current_loop.h index 73b28c0..8c07621 100644 --- a/media/base/bind_to_current_loop.h +++ b/media/base/bind_to_current_loop.h
@@ -9,7 +9,6 @@ #include "base/bind.h" #include "base/location.h" -#include "base/memory/ptr_util.h" #include "base/sequenced_task_runner.h" #include "base/single_thread_task_runner.h" #include "base/threading/thread_task_runner_handle.h" @@ -90,7 +89,7 @@ RunnerType run = &Helper::Run; // TODO(tzik): Propagate FROM_HERE from the caller. return base::BindRepeating( - run, base::MakeUnique<Helper>( + run, std::make_unique<Helper>( FROM_HERE, base::ThreadTaskRunnerHandle::Get(), std::move(cb))); } @@ -103,7 +102,7 @@ RunnerType run = &Helper::Run; // TODO(tzik): Propagate FROM_HERE from the caller. return base::BindOnce( - run, base::MakeUnique<Helper>( + run, std::make_unique<Helper>( FROM_HERE, base::ThreadTaskRunnerHandle::Get(), std::move(cb))); }
diff --git a/media/base/bind_to_current_loop_unittest.cc b/media/base/bind_to_current_loop_unittest.cc index 6d0a1a4..c3680460 100644 --- a/media/base/bind_to_current_loop_unittest.cc +++ b/media/base/bind_to_current_loop_unittest.cc
@@ -139,12 +139,12 @@ bool bool_val = false; base::RepeatingCallback<void(std::unique_ptr<bool>)> cb = BindToCurrentLoop( base::BindRepeating(&BoundBoolSetFromUniquePtr, &bool_val)); - cb.Run(base::MakeUnique<bool>(true)); + cb.Run(std::make_unique<bool>(true)); EXPECT_FALSE(bool_val); base::RunLoop().RunUntilIdle(); EXPECT_TRUE(bool_val); - cb.Run(base::MakeUnique<bool>(false)); + cb.Run(std::make_unique<bool>(false)); EXPECT_TRUE(bool_val); base::RunLoop().RunUntilIdle(); EXPECT_FALSE(bool_val); @@ -154,7 +154,7 @@ bool bool_val = false; base::OnceCallback<void(std::unique_ptr<bool>)> cb = BindToCurrentLoop(base::BindOnce(&BoundBoolSetFromUniquePtr, &bool_val)); - std::move(cb).Run(base::MakeUnique<bool>(true)); + std::move(cb).Run(std::make_unique<bool>(true)); EXPECT_FALSE(bool_val); base::RunLoop().RunUntilIdle(); EXPECT_TRUE(bool_val); @@ -325,7 +325,7 @@ // if the last reference to the callback is dropped on the other thread. base::RepeatingClosure cb = BindToCurrentLoop( base::BindRepeating(&ThreadRestrictionChecker::Run, - base::MakeUnique<ThreadRestrictionChecker>())); + std::make_unique<ThreadRestrictionChecker>())); target_thread.task_runner()->PostTask(FROM_HERE, std::move(cb)); ASSERT_FALSE(cb); target_thread.FlushForTesting(); @@ -335,7 +335,7 @@ // the callback is destroyed without invocation. cb = BindToCurrentLoop( base::BindRepeating(&ThreadRestrictionChecker::Run, - base::MakeUnique<ThreadRestrictionChecker>())); + std::make_unique<ThreadRestrictionChecker>())); target_thread.task_runner()->PostTask( FROM_HERE, base::BindOnce(&ClearReference, std::move(cb))); target_thread.FlushForTesting(); @@ -353,7 +353,7 @@ // if the last reference to the callback is dropped on the other thread. base::OnceClosure cb = BindToCurrentLoop( base::BindOnce(&ThreadRestrictionChecker::Run, - base::MakeUnique<ThreadRestrictionChecker>())); + std::make_unique<ThreadRestrictionChecker>())); target_thread.task_runner()->PostTask(FROM_HERE, std::move(cb)); ASSERT_FALSE(cb); target_thread.FlushForTesting(); @@ -363,7 +363,7 @@ // the callback is destroyed without invocation. cb = BindToCurrentLoop( base::BindOnce(&ThreadRestrictionChecker::Run, - base::MakeUnique<ThreadRestrictionChecker>())); + std::make_unique<ThreadRestrictionChecker>())); target_thread.task_runner()->PostTask( FROM_HERE, base::BindOnce(&ClearReference, std::move(cb))); target_thread.FlushForTesting();
diff --git a/media/base/decoder_buffer_unittest.cc b/media/base/decoder_buffer_unittest.cc index a9a57df3..bdbc273 100644 --- a/media/base/decoder_buffer_unittest.cc +++ b/media/base/decoder_buffer_unittest.cc
@@ -5,9 +5,9 @@ #include "media/base/decoder_buffer.h" #include <stdint.h> +#include <memory> #include "base/macros.h" -#include "base/memory/ptr_util.h" #include "base/strings/string_util.h" #include "build/build_config.h" #include "testing/gtest/include/gtest/gtest.h" @@ -118,7 +118,7 @@ DecryptConfig decrypt_config(kKeyId, kIv, subsamples); buffer->set_decrypt_config( - base::MakeUnique<DecryptConfig>(kKeyId, kIv, subsamples)); + std::make_unique<DecryptConfig>(kKeyId, kIv, subsamples)); EXPECT_TRUE(buffer->decrypt_config()); EXPECT_TRUE(buffer->decrypt_config()->Matches(decrypt_config));
diff --git a/media/base/fake_demuxer_stream.cc b/media/base/fake_demuxer_stream.cc index 963414c..b97effa 100644 --- a/media/base/fake_demuxer_stream.cc +++ b/media/base/fake_demuxer_stream.cc
@@ -5,6 +5,7 @@ #include "media/base/fake_demuxer_stream.h" #include <stdint.h> +#include <memory> #include <vector> @@ -13,7 +14,6 @@ #include "base/location.h" #include "base/logging.h" #include "base/macros.h" -#include "base/memory/ptr_util.h" #include "base/single_thread_task_runner.h" #include "base/threading/thread_task_runner_handle.h" #include "media/base/bind_to_current_loop.h" @@ -189,7 +189,7 @@ // TODO(xhwang): Output out-of-order buffers if needed. if (is_encrypted_) { - buffer->set_decrypt_config(base::MakeUnique<DecryptConfig>( + buffer->set_decrypt_config(std::make_unique<DecryptConfig>( std::string(kKeyId, kKeyId + arraysize(kKeyId)), std::string(kIv, kIv + arraysize(kIv)), std::vector<SubsampleEntry>())); }
diff --git a/media/base/media_observer.h b/media/base/media_observer.h index e1ca88f..a7bc673 100644 --- a/media/base/media_observer.h +++ b/media/base/media_observer.h
@@ -13,6 +13,14 @@ class MEDIA_EXPORT MediaObserverClient { public: + // Reasons to switch to local renderer from using remote renderer. + enum class ReasonToSwitchToLocal { + NORMAL, // Remoting is disabled or media no longer occupies the viewport. + POOR_PLAYBACK_QUALITY, // Playback quality is poor. + PIPELINE_ERROR, // Error occurred. + ROUTE_TERMINATED, // No longer show the media on remote screen. + }; + virtual ~MediaObserverClient() {} // Requests to restart the media pipeline and create a new renderer as soon as @@ -21,7 +29,10 @@ // |remote_device_friendly_name| can be empty if the remote device is unknown. virtual void SwitchToRemoteRenderer( const std::string& remote_device_friendly_name) = 0; - virtual void SwitchToLocalRenderer() = 0; + + // Requests to switch to local renderer. According to |reason|, a text message + // may be displayed to explain why the switch occurred. + virtual void SwitchToLocalRenderer(ReasonToSwitchToLocal reason) = 0; // Requests to activate monitoring changes on viewport intersection. virtual void ActivateViewportIntersectionMonitoring(bool activate) = 0;
diff --git a/media/base/media_tracks.cc b/media/base/media_tracks.cc index 859ca42..e257f92 100644 --- a/media/base/media_tracks.cc +++ b/media/base/media_tracks.cc
@@ -4,8 +4,9 @@ #include "media/base/media_tracks.h" +#include <memory> + #include "base/bind.h" -#include "base/memory/ptr_util.h" #include "media/base/audio_decoder_config.h" #include "media/base/video_decoder_config.h" @@ -23,7 +24,7 @@ const std::string& language) { DCHECK(config.IsValidConfig()); CHECK(audio_configs_.find(bytestream_track_id) == audio_configs_.end()); - std::unique_ptr<MediaTrack> track = base::MakeUnique<MediaTrack>( + std::unique_ptr<MediaTrack> track = std::make_unique<MediaTrack>( MediaTrack::Audio, bytestream_track_id, kind, label, language); MediaTrack* track_ptr = track.get(); tracks_.push_back(std::move(track)); @@ -39,7 +40,7 @@ const std::string& language) { DCHECK(config.IsValidConfig()); CHECK(video_configs_.find(bytestream_track_id) == video_configs_.end()); - std::unique_ptr<MediaTrack> track = base::MakeUnique<MediaTrack>( + std::unique_ptr<MediaTrack> track = std::make_unique<MediaTrack>( MediaTrack::Video, bytestream_track_id, kind, label, language); MediaTrack* track_ptr = track.get(); tracks_.push_back(std::move(track));
diff --git a/media/base/multi_channel_resampler.cc b/media/base/multi_channel_resampler.cc index f816aaf1..069c56e 100644 --- a/media/base/multi_channel_resampler.cc +++ b/media/base/multi_channel_resampler.cc
@@ -5,11 +5,11 @@ #include "media/base/multi_channel_resampler.h" #include <algorithm> +#include <memory> #include "base/bind.h" #include "base/bind_helpers.h" #include "base/logging.h" -#include "base/memory/ptr_util.h" #include "media/base/audio_bus.h" namespace media { @@ -24,7 +24,7 @@ // Allocate each channel's resampler. resamplers_.reserve(channels); for (int i = 0; i < channels; ++i) { - resamplers_.push_back(base::MakeUnique<SincResampler>( + resamplers_.push_back(std::make_unique<SincResampler>( io_sample_rate_ratio, request_size, base::Bind(&MultiChannelResampler::ProvideInput, base::Unretained(this), i)));
diff --git a/media/base/renderer_factory_selector_unittest.cc b/media/base/renderer_factory_selector_unittest.cc index 105121a..d44d49c 100644 --- a/media/base/renderer_factory_selector_unittest.cc +++ b/media/base/renderer_factory_selector_unittest.cc
@@ -6,7 +6,6 @@ #include "base/bind.h" #include "base/macros.h" -#include "base/memory/ptr_util.h" #include "media/base/overlay_info.h" #include "media/base/renderer_factory_selector.h" #include "testing/gtest/include/gtest/gtest.h" @@ -41,7 +40,7 @@ ; void AddFactory(FactoryType type) { - selector_.AddFactory(type, base::MakeUnique<FakeFactory>(type)); + selector_.AddFactory(type, std::make_unique<FakeFactory>(type)); }; FactoryType GetCurrentlySelectedFactoryType() {
diff --git a/media/base/text_renderer_unittest.cc b/media/base/text_renderer_unittest.cc index edfbd76..4190174 100644 --- a/media/base/text_renderer_unittest.cc +++ b/media/base/text_renderer_unittest.cc
@@ -12,7 +12,6 @@ #include "base/bind.h" #include "base/callback_helpers.h" #include "base/macros.h" -#include "base/memory/ptr_util.h" #include "base/message_loop/message_loop.h" #include "base/run_loop.h" #include "media/base/audio_decoder_config.h" @@ -77,7 +76,7 @@ const std::string& language, bool expect_read) { const size_t idx = text_track_streams_.size(); - text_track_streams_.push_back(base::MakeUnique<FakeTextTrackStream>()); + text_track_streams_.push_back(std::make_unique<FakeTextTrackStream>()); if (expect_read) ExpectRead(idx);
diff --git a/media/base/user_input_monitor_linux.cc b/media/base/user_input_monitor_linux.cc index 41fc05c..5aeb40eff 100644 --- a/media/base/user_input_monitor_linux.cc +++ b/media/base/user_input_monitor_linux.cc
@@ -7,6 +7,7 @@ #include <stddef.h> #include <sys/select.h> #include <unistd.h> +#include <memory> #include "base/bind.h" #include "base/callback.h" @@ -15,7 +16,6 @@ #include "base/location.h" #include "base/logging.h" #include "base/macros.h" -#include "base/memory/ptr_util.h" #include "base/message_loop/message_loop.h" #include "base/single_thread_task_runner.h" #include "base/synchronization/lock.h" @@ -292,7 +292,7 @@ std::unique_ptr<UserInputMonitor> UserInputMonitor::Create( const scoped_refptr<base::SingleThreadTaskRunner>& io_task_runner, const scoped_refptr<base::SingleThreadTaskRunner>& ui_task_runner) { - return base::MakeUnique<UserInputMonitorLinux>(io_task_runner); + return std::make_unique<UserInputMonitorLinux>(io_task_runner); } } // namespace media
diff --git a/media/base/user_input_monitor_mac.cc b/media/base/user_input_monitor_mac.cc index 42450d2..96fd3bb 100644 --- a/media/base/user_input_monitor_mac.cc +++ b/media/base/user_input_monitor_mac.cc
@@ -6,9 +6,9 @@ #include <ApplicationServices/ApplicationServices.h> #include <stddef.h> +#include <memory> #include "base/macros.h" -#include "base/memory/ptr_util.h" namespace media { namespace { @@ -47,7 +47,7 @@ std::unique_ptr<UserInputMonitor> UserInputMonitor::Create( const scoped_refptr<base::SingleThreadTaskRunner>& input_task_runner, const scoped_refptr<base::SingleThreadTaskRunner>& ui_task_runner) { - return base::MakeUnique<UserInputMonitorMac>(); + return std::make_unique<UserInputMonitorMac>(); } } // namespace media
diff --git a/media/base/user_input_monitor_win.cc b/media/base/user_input_monitor_win.cc index 5278e94..b8e92317 100644 --- a/media/base/user_input_monitor_win.cc +++ b/media/base/user_input_monitor_win.cc
@@ -6,12 +6,12 @@ #include <stddef.h> #include <stdint.h> +#include <memory> #include "base/bind.h" #include "base/location.h" #include "base/logging.h" #include "base/macros.h" -#include "base/memory/ptr_util.h" #include "base/message_loop/message_loop.h" #include "base/single_thread_task_runner.h" #include "base/strings/stringprintf.h" @@ -122,7 +122,7 @@ return; std::unique_ptr<base::win::MessageWindow> window = - base::MakeUnique<base::win::MessageWindow>(); + std::make_unique<base::win::MessageWindow>(); if (!window->Create(base::Bind(&UserInputMonitorWinCore::HandleMessage, base::Unretained(this)))) { PLOG(ERROR) << "Failed to create the raw input window"; @@ -252,7 +252,7 @@ std::unique_ptr<UserInputMonitor> UserInputMonitor::Create( const scoped_refptr<base::SingleThreadTaskRunner>& io_task_runner, const scoped_refptr<base::SingleThreadTaskRunner>& ui_task_runner) { - return base::MakeUnique<UserInputMonitorWin>(ui_task_runner); + return std::make_unique<UserInputMonitorWin>(ui_task_runner); } } // namespace media
diff --git a/media/base/video_frame_unittest.cc b/media/base/video_frame_unittest.cc index 36d6d11..8f11bbc 100644 --- a/media/base/video_frame_unittest.cc +++ b/media/base/video_frame_unittest.cc
@@ -6,13 +6,13 @@ #include <stddef.h> #include <stdint.h> +#include <memory> #include "base/bind.h" #include "base/callback_helpers.h" #include "base/format_macros.h" #include "base/macros.h" #include "base/memory/aligned_memory.h" -#include "base/memory/ptr_util.h" #include "base/strings/stringprintf.h" #include "gpu/command_buffer/common/mailbox_holder.h" #include "testing/gtest/include/gtest/gtest.h" @@ -555,7 +555,7 @@ metadata.Clear(); EXPECT_FALSE(metadata.HasKey(key)); - metadata.SetValue(key, base::MakeUnique<base::Value>()); + metadata.SetValue(key, std::make_unique<base::Value>()); EXPECT_TRUE(metadata.HasKey(key)); const base::Value* const null_value = metadata.GetValue(key); EXPECT_TRUE(null_value);
diff --git a/media/blink/cdm_session_adapter.cc b/media/blink/cdm_session_adapter.cc index 0d8b779e..1f337ee 100644 --- a/media/blink/cdm_session_adapter.cc +++ b/media/blink/cdm_session_adapter.cc
@@ -4,11 +4,11 @@ #include "media/blink/cdm_session_adapter.h" +#include <memory> #include <utility> #include "base/bind.h" #include "base/logging.h" -#include "base/memory/ptr_util.h" #include "base/metrics/histogram.h" #include "base/metrics/histogram_functions.h" #include "base/stl_util.h" @@ -79,7 +79,7 @@ std::unique_ptr<WebContentDecryptionModuleSessionImpl> CdmSessionAdapter::CreateSession() { - return base::MakeUnique<WebContentDecryptionModuleSessionImpl>(this); + return std::make_unique<WebContentDecryptionModuleSessionImpl>(this); } bool CdmSessionAdapter::RegisterSession(
diff --git a/media/blink/multibuffer_data_source_unittest.cc b/media/blink/multibuffer_data_source_unittest.cc index 8b8a911..233dc05 100644 --- a/media/blink/multibuffer_data_source_unittest.cc +++ b/media/blink/multibuffer_data_source_unittest.cc
@@ -84,7 +84,7 @@ std::unique_ptr<MultiBuffer::DataProvider> CreateWriter(const BlockId& pos, bool) override { - auto writer = base::MakeUnique<TestMultiBufferDataProvider>(url_data_, pos); + auto writer = std::make_unique<TestMultiBufferDataProvider>(url_data_, pos); writer->Start(); return writer; } @@ -212,10 +212,10 @@ MultibufferDataSourceTest() : preload_(MultibufferDataSource::AUTO) { ON_CALL(fetch_context_, CreateUrlLoader(_)) .WillByDefault(Invoke([](const blink::WebAssociatedURLLoaderOptions&) { - return base::MakeUnique<NiceMock<MockWebAssociatedURLLoader>>(); + return std::make_unique<NiceMock<MockWebAssociatedURLLoader>>(); })); - url_index_ = base::MakeUnique<TestUrlIndex>(&fetch_context_); + url_index_ = std::make_unique<TestUrlIndex>(&fetch_context_); } MOCK_METHOD1(OnInitialize, void(bool));
diff --git a/media/blink/resource_multibuffer_data_provider_unittest.cc b/media/blink/resource_multibuffer_data_provider_unittest.cc index b0d703b..fa8b5f27 100644 --- a/media/blink/resource_multibuffer_data_provider_unittest.cc +++ b/media/blink/resource_multibuffer_data_provider_unittest.cc
@@ -73,7 +73,7 @@ class ResourceMultiBufferDataProviderTest : public testing::Test { public: ResourceMultiBufferDataProviderTest() - : url_index_(base::MakeUnique<UrlIndex>(&fetch_context_, 0)) { + : url_index_(std::make_unique<UrlIndex>(&fetch_context_, 0)) { for (int i = 0; i < kDataSize; ++i) { data_[i] = i; } @@ -208,7 +208,7 @@ protected: std::unique_ptr<blink::WebAssociatedURLLoader> CreateUrlLoader( const blink::WebAssociatedURLLoaderOptions& options) { - auto url_loader = base::MakeUnique<NiceMock<MockWebAssociatedURLLoader>>(); + auto url_loader = std::make_unique<NiceMock<MockWebAssociatedURLLoader>>(); EXPECT_CALL( *url_loader.get(), LoadAsynchronously(Truly(CorrectAcceptEncodingAndProxy), loader_));
diff --git a/media/blink/url_index.cc b/media/blink/url_index.cc index 22a94b5..801735c1 100644 --- a/media/blink/url_index.cc +++ b/media/blink/url_index.cc
@@ -29,7 +29,7 @@ std::unique_ptr<MultiBuffer::DataProvider> ResourceMultiBuffer::CreateWriter( const MultiBufferBlockId& pos, bool is_client_audio_element) { - auto writer = base::MakeUnique<ResourceMultiBufferDataProvider>( + auto writer = std::make_unique<ResourceMultiBufferDataProvider>( url_data_, pos, is_client_audio_element); writer->Start(); return writer;
diff --git a/media/blink/video_decode_stats_reporter_unittest.cc b/media/blink/video_decode_stats_reporter_unittest.cc index a9afd322..e956ba5 100644 --- a/media/blink/video_decode_stats_reporter_unittest.cc +++ b/media/blink/video_decode_stats_reporter_unittest.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 "media/blink/video_decode_stats_reporter.h" #include "base/memory/ptr_util.h" #include "base/memory/ref_counted.h" @@ -167,7 +169,7 @@ mojom::VideoDecodeStatsRecorderPtr recorder_ptr; SetupRecordInterceptor(&recorder_ptr, &interceptor_); - reporter_ = base::MakeUnique<VideoDecodeStatsReporter>( + reporter_ = std::make_unique<VideoDecodeStatsReporter>( std::move(recorder_ptr), base::Bind(&VideoDecodeStatsReporterTest::GetPipelineStatsCB, base::Unretained(this)),
diff --git a/media/blink/video_frame_compositor_unittest.cc b/media/blink/video_frame_compositor_unittest.cc index 45fab78c..e975f37 100644 --- a/media/blink/video_frame_compositor_unittest.cc +++ b/media/blink/video_frame_compositor_unittest.cc
@@ -57,12 +57,12 @@ submitter_ = client_.get(); if (!IsSurfaceLayerForVideoEnabled()) { - compositor_ = base::MakeUnique<VideoFrameCompositor>( + compositor_ = std::make_unique<VideoFrameCompositor>( message_loop.task_runner(), nullptr); compositor_->SetVideoFrameProviderClient(client_.get()); } else { EXPECT_CALL(*submitter_, Initialize(_)); - compositor_ = base::MakeUnique<VideoFrameCompositor>( + compositor_ = std::make_unique<VideoFrameCompositor>( message_loop.task_runner(), std::move(client_)); base::RunLoop().RunUntilIdle(); EXPECT_CALL(*submitter_, StartSubmitting(_));
diff --git a/media/blink/watch_time_reporter_unittest.cc b/media/blink/watch_time_reporter_unittest.cc index 89f9d96..57fc3fe0 100644 --- a/media/blink/watch_time_reporter_unittest.cc +++ b/media/blink/watch_time_reporter_unittest.cc
@@ -193,7 +193,7 @@ void AcquireWatchTimeRecorder( mojom::PlaybackPropertiesPtr properties, mojom::WatchTimeRecorderRequest request) override { - mojo::MakeStrongBinding(base::MakeUnique<WatchTimeInterceptor>(parent_), + mojo::MakeStrongBinding(std::make_unique<WatchTimeInterceptor>(parent_), std::move(request)); } void AcquireVideoDecodeStatsRecorder(
diff --git a/media/blink/webcontentdecryptionmodulesession_impl.cc b/media/blink/webcontentdecryptionmodulesession_impl.cc index c62e48e..cc4e85ff 100644 --- a/media/blink/webcontentdecryptionmodulesession_impl.cc +++ b/media/blink/webcontentdecryptionmodulesession_impl.cc
@@ -4,10 +4,11 @@ #include "webcontentdecryptionmodulesession_impl.h" +#include <memory> + #include "base/bind.h" #include "base/callback_helpers.h" #include "base/logging.h" -#include "base/memory/ptr_util.h" #include "base/metrics/histogram_functions.h" #include "base/numerics/safe_conversions.h" #include "base/strings/string_util.h" @@ -256,7 +257,7 @@ // session will be gone. if (!is_closed_ && !has_close_been_called_) { adapter_->CloseSession(session_id_, - base::MakeUnique<IgnoreResponsePromise>()); + std::make_unique<IgnoreResponsePromise>()); } } }
diff --git a/media/blink/webencryptedmediaclient_impl.cc b/media/blink/webencryptedmediaclient_impl.cc index 5a0e760..7b9aec8 100644 --- a/media/blink/webencryptedmediaclient_impl.cc +++ b/media/blink/webencryptedmediaclient_impl.cc
@@ -4,10 +4,10 @@ #include "media/blink/webencryptedmediaclient_impl.h" +#include <memory> #include <utility> #include "base/bind.h" -#include "base/memory/ptr_util.h" #include "base/metrics/histogram_functions.h" #include "base/strings/string_util.h" #include "base/strings/utf_string_conversions.h" @@ -169,7 +169,7 @@ std::string uma_name = GetKeySystemNameForUMA(key_system_ascii); std::unique_ptr<Reporter>& reporter = reporters_[uma_name]; if (!reporter) - reporter = base::MakeUnique<Reporter>(uma_name); + reporter = std::make_unique<Reporter>(uma_name); return reporter.get(); }
diff --git a/media/blink/webmediaplayer_impl.cc b/media/blink/webmediaplayer_impl.cc index ad18408..8afda5d 100644 --- a/media/blink/webmediaplayer_impl.cc +++ b/media/blink/webmediaplayer_impl.cc
@@ -7,6 +7,7 @@ #include <algorithm> #include <cmath> #include <limits> +#include <memory> #include <string> #include <utility> @@ -18,7 +19,6 @@ #include "base/debug/alias.h" #include "base/debug/crash_logging.h" #include "base/location.h" -#include "base/memory/ptr_util.h" #include "base/metrics/histogram_macros.h" #include "base/single_thread_task_runner.h" #include "base/strings/string_number_conversions.h" @@ -54,6 +54,7 @@ #include "media/filters/chunk_demuxer.h" #include "media/filters/ffmpeg_demuxer.h" #include "third_party/WebKit/public/platform/WebEncryptedMediaTypes.h" +#include "third_party/WebKit/public/platform/WebLocalizedString.h" #include "third_party/WebKit/public/platform/WebMediaPlayerClient.h" #include "third_party/WebKit/public/platform/WebMediaPlayerEncryptedMediaClient.h" #include "third_party/WebKit/public/platform/WebMediaPlayerSource.h" @@ -150,6 +151,23 @@ // Maximum number, per-WMPI, of media logs of playback rate changes. constexpr int kMaxNumPlaybackRateLogs = 10; +blink::WebLocalizedString::Name GetSwitchToLocalMessage( + MediaObserverClient::ReasonToSwitchToLocal reason) { + switch (reason) { + case MediaObserverClient::ReasonToSwitchToLocal::NORMAL: + return blink::WebLocalizedString::kMediaRemotingStopText; + case MediaObserverClient::ReasonToSwitchToLocal::POOR_PLAYBACK_QUALITY: + return blink::WebLocalizedString::kMediaRemotingStopByPlaybackQualityText; + case MediaObserverClient::ReasonToSwitchToLocal::PIPELINE_ERROR: + return blink::WebLocalizedString::kMediaRemotingStopByErrorText; + case MediaObserverClient::ReasonToSwitchToLocal::ROUTE_TERMINATED: + return blink::WebLocalizedString::kMediaRemotingStopNoText; + } + NOTREACHED(); + // To suppress compiler warning on Windows. + return blink::WebLocalizedString::kMediaRemotingStopNoText; +} + } // namespace class BufferedDataSourceHostImpl; @@ -183,7 +201,7 @@ worker_task_runner_(params->worker_task_runner()), media_log_(params->take_media_log()), pipeline_controller_( - base::MakeUnique<PipelineImpl>(media_task_runner_, media_log_.get()), + std::make_unique<PipelineImpl>(media_task_runner_, media_log_.get()), base::Bind(&WebMediaPlayerImpl::CreateRenderer, base::Unretained(this)), base::Bind(&WebMediaPlayerImpl::OnPipelineSeeked, AsWeakPtr()), @@ -329,7 +347,8 @@ // Destruct compositor resources in the proper order. client_->SetWebLayer(nullptr); - client_->MediaRemotingStopped(); + client_->MediaRemotingStopped( + blink::WebLocalizedString::kMediaRemotingStopNoText); if (!surface_layer_for_video_enabled_ && video_weblayer_) { static_cast<cc::VideoLayer*>(video_weblayer_->layer())->StopUsingProvider(); @@ -2218,7 +2237,7 @@ if (base::FeatureList::IsEnabled(kMemoryPressureBasedSourceBufferGC)) { // base::Unretained is safe because |this| owns memory_pressure_listener_. memory_pressure_listener_ = - base::MakeUnique<base::MemoryPressureListener>(base::Bind( + std::make_unique<base::MemoryPressureListener>(base::Bind( &WebMediaPlayerImpl::OnMemoryPressure, base::Unretained(this))); } } @@ -2850,7 +2869,8 @@ } } -void WebMediaPlayerImpl::SwitchToLocalRenderer() { +void WebMediaPlayerImpl::SwitchToLocalRenderer( + MediaObserverClient::ReasonToSwitchToLocal reason) { DCHECK(main_task_runner_->BelongsToCurrentThread()); disable_pipeline_auto_suspend_ = false; @@ -2861,7 +2881,7 @@ // the |renderer_factory_selector_|. ScheduleRestart(); if (client_) - client_->MediaRemotingStopped(); + client_->MediaRemotingStopped(GetSwitchToLocalMessage(reason)); } void WebMediaPlayerImpl::RecordUnderflowDuration(base::TimeDelta duration) {
diff --git a/media/blink/webmediaplayer_impl.h b/media/blink/webmediaplayer_impl.h index 0ae21e2..7de0feb9 100644 --- a/media/blink/webmediaplayer_impl.h +++ b/media/blink/webmediaplayer_impl.h
@@ -256,7 +256,8 @@ // MediaObserverClient implementation. void SwitchToRemoteRenderer( const std::string& remote_device_friendly_name) override; - void SwitchToLocalRenderer() override; + void SwitchToLocalRenderer( + MediaObserverClient::ReasonToSwitchToLocal reason) override; void ActivateViewportIntersectionMonitoring(bool activate) override; void UpdateRemotePlaybackCompatibility(bool is_compatible) override;
diff --git a/media/blink/webmediaplayer_impl_unittest.cc b/media/blink/webmediaplayer_impl_unittest.cc index 55ba120..408365a2 100644 --- a/media/blink/webmediaplayer_impl_unittest.cc +++ b/media/blink/webmediaplayer_impl_unittest.cc
@@ -11,7 +11,6 @@ #include "base/bind.h" #include "base/callback_helpers.h" #include "base/command_line.h" -#include "base/memory/ptr_util.h" #include "base/memory/ref_counted.h" #include "base/memory/weak_ptr.h" #include "base/message_loop/message_loop.h" @@ -134,7 +133,8 @@ void ActivateViewportIntersectionMonitoring(bool activate) override {} void MediaRemotingStarted( const blink::WebString& remote_device_friendly_name) override {} - void MediaRemotingStopped() override {} + void MediaRemotingStopped( + blink::WebLocalizedString::Name error_msg) override {} void set_is_autoplaying_muted(bool value) { is_autoplaying_muted_ = value; } @@ -280,10 +280,10 @@ ASSERT_FALSE(media_log_) << "Reinitialization of media_log_ is disallowed"; media_log_ = media_log.get(); - auto factory_selector = base::MakeUnique<RendererFactorySelector>(); + auto factory_selector = std::make_unique<RendererFactorySelector>(); factory_selector->AddFactory( RendererFactorySelector::FactoryType::DEFAULT, - base::MakeUnique<DefaultRendererFactory>( + std::make_unique<DefaultRendererFactory>( media_log.get(), nullptr, DefaultRendererFactory::GetGpuFactoriesCB())); factory_selector->SetBaseFactoryType( @@ -297,7 +297,7 @@ // will start DCHECK failing. provider->Initialize(false, false, url::Origin()); - auto params = base::MakeUnique<WebMediaPlayerParams>( + auto params = std::make_unique<WebMediaPlayerParams>( std::move(media_log), WebMediaPlayerParams::DeferLoadCB(), scoped_refptr<SwitchableAudioRendererSink>(), media_thread_.task_runner(), message_loop_.task_runner(), @@ -311,7 +311,7 @@ base::Unretained(this)), cc::TestContextProvider::Create()); - auto compositor = base::MakeUnique<StrictMock<MockVideoFrameCompositor>>( + auto compositor = std::make_unique<StrictMock<MockVideoFrameCompositor>>( params->video_frame_compositor_task_runner()); compositor_ = compositor.get(); @@ -322,7 +322,7 @@ .WillOnce(ReturnRef(id_)); } - wmpi_ = base::MakeUnique<WebMediaPlayerImpl>( + wmpi_ = std::make_unique<WebMediaPlayerImpl>( web_local_frame_, &client_, nullptr, &delegate_, std::move(factory_selector), url_index_.get(), std::move(compositor), std::move(params)); @@ -1016,7 +1016,7 @@ InitializeWebMediaPlayerImpl(); std::unique_ptr<cc_blink::WebLayerImpl> web_layer = - base::MakeUnique<cc_blink::WebLayerImpl>(); + std::make_unique<cc_blink::WebLayerImpl>(); EXPECT_CALL(*surface_layer_bridge_ptr_, GetWebLayer()) .WillRepeatedly(Return(web_layer.get()));
diff --git a/media/capture/video/chromeos/camera_device_delegate.cc b/media/capture/video/chromeos/camera_device_delegate.cc index 714cf5e..0383a05 100644 --- a/media/capture/video/chromeos/camera_device_delegate.cc +++ b/media/capture/video/chromeos/camera_device_delegate.cc
@@ -4,11 +4,11 @@ #include "media/capture/video/chromeos/camera_device_delegate.h" +#include <memory> #include <string> #include <utility> #include <vector> -#include "base/memory/ptr_util.h" #include "media/base/bind_to_current_loop.h" #include "media/capture/video/chromeos/camera_buffer_factory.h" #include "media/capture/video/chromeos/camera_device_context.h" @@ -257,10 +257,10 @@ arc::mojom::Camera3CallbackOpsPtr callback_ops_ptr; arc::mojom::Camera3CallbackOpsRequest callback_ops_request = mojo::MakeRequest(&callback_ops_ptr); - stream_buffer_manager_ = base::MakeUnique<StreamBufferManager>( + stream_buffer_manager_ = std::make_unique<StreamBufferManager>( std::move(callback_ops_request), - base::MakeUnique<StreamCaptureInterfaceImpl>(GetWeakPtr()), - device_context_, base::MakeUnique<CameraBufferFactory>(), + std::make_unique<StreamCaptureInterfaceImpl>(GetWeakPtr()), + device_context_, std::make_unique<CameraBufferFactory>(), ipc_task_runner_); device_ops_->Initialize( std::move(callback_ops_ptr),
diff --git a/media/capture/video/chromeos/camera_device_delegate_unittest.cc b/media/capture/video/chromeos/camera_device_delegate_unittest.cc index 2c9da84..8103886f 100644 --- a/media/capture/video/chromeos/camera_device_delegate_unittest.cc +++ b/media/capture/video/chromeos/camera_device_delegate_unittest.cc
@@ -10,7 +10,6 @@ #include <memory> #include <utility> -#include "base/memory/ptr_util.h" #include "base/run_loop.h" #include "base/test/scoped_task_environment.h" #include "media/base/bind_to_current_loop.h" @@ -144,7 +143,7 @@ ASSERT_FALSE(device_delegate_thread_.IsRunning()); ASSERT_FALSE(camera_device_delegate_); device_delegate_thread_.Start(); - camera_device_delegate_ = base::MakeUnique<CameraDeviceDelegate>( + camera_device_delegate_ = std::make_unique<CameraDeviceDelegate>( descriptor, camera_hal_delegate_, device_delegate_thread_.task_runner()); } @@ -354,10 +353,10 @@ unittest_internal::MockVideoCaptureClient* ResetDeviceContext() { auto mock_client = - base::MakeUnique<unittest_internal::MockVideoCaptureClient>(); + std::make_unique<unittest_internal::MockVideoCaptureClient>(); auto* client_ptr = mock_client.get(); device_context_ = - base::MakeUnique<CameraDeviceContext>(std::move(mock_client)); + std::make_unique<CameraDeviceContext>(std::move(mock_client)); return client_ptr; }
diff --git a/media/capture/video/chromeos/camera_hal_delegate.cc b/media/capture/video/chromeos/camera_hal_delegate.cc index 1a2f4484..b139c7d 100644 --- a/media/capture/video/chromeos/camera_hal_delegate.cc +++ b/media/capture/video/chromeos/camera_hal_delegate.cc
@@ -61,7 +61,7 @@ void CameraHalDelegate::RegisterCameraClient() { CameraHalDispatcherImpl::GetInstance()->AddClientObserver( - base::MakeUnique<LocalCameraClientObserver>(this)); + std::make_unique<LocalCameraClientObserver>(this)); } void CameraHalDelegate::SetCameraModule(
diff --git a/media/capture/video/chromeos/camera_hal_dispatcher_impl.cc b/media/capture/video/chromeos/camera_hal_dispatcher_impl.cc index 4c5f17d..690a47a 100644 --- a/media/capture/video/chromeos/camera_hal_dispatcher_impl.cc +++ b/media/capture/video/chromeos/camera_hal_dispatcher_impl.cc
@@ -184,7 +184,7 @@ arc::mojom::CameraHalClientPtr client) { DCHECK(proxy_task_runner_->BelongsToCurrentThread()); auto client_observer = - base::MakeUnique<MojoCameraClientObserver>(std::move(client)); + std::make_unique<MojoCameraClientObserver>(std::move(client)); client_observer->client().set_connection_error_handler(base::Bind( &CameraHalDispatcherImpl::OnCameraHalClientConnectionError, base::Unretained(this), base::Unretained(client_observer.get())));
diff --git a/media/capture/video/chromeos/camera_hal_dispatcher_impl_unittest.cc b/media/capture/video/chromeos/camera_hal_dispatcher_impl_unittest.cc index d14966c..6791b01 100644 --- a/media/capture/video/chromeos/camera_hal_dispatcher_impl_unittest.cc +++ b/media/capture/video/chromeos/camera_hal_dispatcher_impl_unittest.cc
@@ -7,7 +7,6 @@ #include <memory> #include <utility> -#include "base/memory/ptr_util.h" #include "base/run_loop.h" #include "base/test/scoped_task_environment.h" #include "media/capture/video/chromeos/mojo/arc_camera3_service.mojom.h" @@ -128,8 +127,8 @@ TEST_F(CameraHalDispatcherImplTest, ServerConnectionError) { // First verify that a the CameraHalDispatcherImpl establishes a Mojo channel // between the server and the client. - auto mock_server = base::MakeUnique<MockCameraHalServer>(); - auto mock_client = base::MakeUnique<MockCameraHalClient>(); + auto mock_server = std::make_unique<MockCameraHalServer>(); + auto mock_client = std::make_unique<MockCameraHalClient>(); EXPECT_CALL(*mock_server, DoCreateChannel(_)).Times(1); EXPECT_CALL(*mock_client, DoSetUpChannel(_)) @@ -152,7 +151,7 @@ DoLoop(); // Re-create a new server to simulate a server crash. - mock_server = base::MakeUnique<MockCameraHalServer>(); + mock_server = std::make_unique<MockCameraHalServer>(); // Make sure we creates a new Mojo channel from the new server to the same // client. @@ -177,8 +176,8 @@ TEST_F(CameraHalDispatcherImplTest, ClientConnectionError) { // First verify that a the CameraHalDispatcherImpl establishes a Mojo channel // between the server and the client. - auto mock_server = base::MakeUnique<MockCameraHalServer>(); - auto mock_client = base::MakeUnique<MockCameraHalClient>(); + auto mock_server = std::make_unique<MockCameraHalServer>(); + auto mock_client = std::make_unique<MockCameraHalClient>(); EXPECT_CALL(*mock_server, DoCreateChannel(_)).Times(1); EXPECT_CALL(*mock_client, DoSetUpChannel(_)) @@ -201,7 +200,7 @@ DoLoop(); // Re-create a new server to simulate a server crash. - mock_client = base::MakeUnique<MockCameraHalClient>(); + mock_client = std::make_unique<MockCameraHalClient>(); // Make sure we re-create the Mojo channel from the same server to the new // client.
diff --git a/media/capture/video/chromeos/local_gpu_memory_buffer_manager.cc b/media/capture/video/chromeos/local_gpu_memory_buffer_manager.cc index 43551253..7c213cb 100644 --- a/media/capture/video/chromeos/local_gpu_memory_buffer_manager.cc +++ b/media/capture/video/chromeos/local_gpu_memory_buffer_manager.cc
@@ -6,8 +6,7 @@ #include <drm_fourcc.h> #include <xf86drm.h> - -#include "base/memory/ptr_util.h" +#include <memory> namespace media { @@ -218,7 +217,7 @@ return std::unique_ptr<gfx::GpuMemoryBuffer>(); } - return base::MakeUnique<GpuMemoryBufferImplGbm>(format, buffer_object); + return std::make_unique<GpuMemoryBufferImplGbm>(format, buffer_object); } void LocalGpuMemoryBufferManager::SetDestructionSyncToken(
diff --git a/media/capture/video/chromeos/mock_gpu_memory_buffer_manager.cc b/media/capture/video/chromeos/mock_gpu_memory_buffer_manager.cc index 3fea2cc..529f9da2 100644 --- a/media/capture/video/chromeos/mock_gpu_memory_buffer_manager.cc +++ b/media/capture/video/chromeos/mock_gpu_memory_buffer_manager.cc
@@ -4,7 +4,7 @@ #include "media/capture/video/chromeos/mock_gpu_memory_buffer_manager.h" -#include "base/memory/ptr_util.h" +#include <memory> using ::testing::Return; @@ -40,7 +40,7 @@ size.width(), handle.native_pixmap_handle.planes[0].size, size.width() * size.height() / 2, 0)); - auto mock_buffer = base::MakeUnique<MockGpuMemoryBuffer>(); + auto mock_buffer = std::make_unique<MockGpuMemoryBuffer>(); ON_CALL(*mock_buffer, Map()).WillByDefault(Return(true)); ON_CALL(*mock_buffer, memory(0)) .WillByDefault(Return(reinterpret_cast<void*>(0xdeafbeef)));
diff --git a/media/capture/video/chromeos/stream_buffer_manager.cc b/media/capture/video/chromeos/stream_buffer_manager.cc index 8bba363f8..73272c4f 100644 --- a/media/capture/video/chromeos/stream_buffer_manager.cc +++ b/media/capture/video/chromeos/stream_buffer_manager.cc
@@ -5,8 +5,8 @@ #include "media/capture/video/chromeos/stream_buffer_manager.h" #include <sync/sync.h> +#include <memory> -#include "base/memory/ptr_util.h" #include "media/capture/video/chromeos/camera_buffer_factory.h" #include "media/capture/video/chromeos/camera_device_context.h" #include "media/capture/video/chromeos/camera_metadata_utils.h" @@ -68,7 +68,7 @@ } partial_result_count_ = partial_result_count; - stream_context_ = base::MakeUnique<StreamContext>(); + stream_context_ = std::make_unique<StreamContext>(); stream_context_->capture_format = capture_format; stream_context_->stream = std::move(stream);
diff --git a/media/capture/video/chromeos/stream_buffer_manager_unittest.cc b/media/capture/video/chromeos/stream_buffer_manager_unittest.cc index 90ef0581..db86343 100644 --- a/media/capture/video/chromeos/stream_buffer_manager_unittest.cc +++ b/media/capture/video/chromeos/stream_buffer_manager_unittest.cc
@@ -9,7 +9,6 @@ #include <utility> #include <vector> -#include "base/memory/ptr_util.h" #include "base/run_loop.h" #include "base/test/scoped_task_environment.h" #include "base/threading/thread.h" @@ -82,7 +81,7 @@ std::unique_ptr<gfx::GpuMemoryBuffer> CreateMockGpuMemoryBuffer( const gfx::Size& size, gfx::BufferFormat format) { - auto mock_buffer = base::MakeUnique<unittest_internal::MockGpuMemoryBuffer>(); + auto mock_buffer = std::make_unique<unittest_internal::MockGpuMemoryBuffer>(); gfx::GpuMemoryBufferHandle fake_handle; fake_handle.native_pixmap_handle.fds.push_back( base::FileDescriptor(0, false)); @@ -100,7 +99,7 @@ } std::unique_ptr<CameraBufferFactory> CreateMockCameraBufferFactory() { - auto buffer_factory = base::MakeUnique<MockCameraBufferFactory>(); + auto buffer_factory = std::make_unique<MockCameraBufferFactory>(); EXPECT_CALL(*buffer_factory, CreateGpuMemoryBuffer(_, _)) .WillRepeatedly(Invoke(CreateMockGpuMemoryBuffer)); EXPECT_CALL(*buffer_factory, ResolveStreamBufferFormat(_)) @@ -117,12 +116,12 @@ quit_ = false; arc::mojom::Camera3CallbackOpsRequest callback_ops_request = mojo::MakeRequest(&mock_callback_ops_); - device_context_ = base::MakeUnique<CameraDeviceContext>( - base::MakeUnique<unittest_internal::MockVideoCaptureClient>()); + device_context_ = std::make_unique<CameraDeviceContext>( + std::make_unique<unittest_internal::MockVideoCaptureClient>()); - stream_buffer_manager_ = base::MakeUnique<StreamBufferManager>( + stream_buffer_manager_ = std::make_unique<StreamBufferManager>( std::move(callback_ops_request), - base::MakeUnique<MockStreamCaptureInterface>(), device_context_.get(), + std::make_unique<MockStreamCaptureInterface>(), device_context_.get(), CreateMockCameraBufferFactory(), base::ThreadTaskRunnerHandle::Get()); }
diff --git a/media/capture/video/chromeos/video_capture_device_arc_chromeos.cc b/media/capture/video/chromeos/video_capture_device_arc_chromeos.cc index 557df72..91da489c 100644 --- a/media/capture/video/chromeos/video_capture_device_arc_chromeos.cc +++ b/media/capture/video/chromeos/video_capture_device_arc_chromeos.cc
@@ -4,11 +4,11 @@ #include "media/capture/video/chromeos/video_capture_device_arc_chromeos.h" +#include <memory> #include <string> #include <utility> #include "base/bind_helpers.h" -#include "base/memory/ptr_util.h" #include "base/synchronization/waitable_event.h" #include "base/threading/platform_thread.h" #include "chromeos/dbus/dbus_thread_manager.h" @@ -68,8 +68,8 @@ return; } capture_params_ = params; - device_context_ = base::MakeUnique<CameraDeviceContext>(std::move(client)); - camera_device_delegate_ = base::MakeUnique<CameraDeviceDelegate>( + device_context_ = std::make_unique<CameraDeviceContext>(std::move(client)); + camera_device_delegate_ = std::make_unique<CameraDeviceDelegate>( device_descriptor_, camera_hal_delegate_, camera_device_ipc_thread_.task_runner()); OpenDevice();
diff --git a/media/capture/video/fake_video_capture_device.cc b/media/capture/video/fake_video_capture_device.cc index 532afb4..ff7f453a 100644 --- a/media/capture/video/fake_video_capture_device.cc +++ b/media/capture/video/fake_video_capture_device.cc
@@ -197,7 +197,7 @@ painter_format = PacmanFramePainter::Format::I420; } auto frame_painter = - base::MakeUnique<PacmanFramePainter>(painter_format, device_state_); + std::make_unique<PacmanFramePainter>(painter_format, device_state_); FakeVideoCaptureDevice::DeliveryMode delivery_mode = delivery_mode_; if (format.pixel_format == PIXEL_FORMAT_MJPEG && @@ -213,14 +213,14 @@ switch (delivery_mode) { case FakeVideoCaptureDevice::DeliveryMode::USE_DEVICE_INTERNAL_BUFFERS: if (format.pixel_format == PIXEL_FORMAT_MJPEG) { - return base::MakeUnique<JpegEncodingFrameDeliverer>( + return std::make_unique<JpegEncodingFrameDeliverer>( std::move(frame_painter)); } else { - return base::MakeUnique<OwnBufferFrameDeliverer>( + return std::make_unique<OwnBufferFrameDeliverer>( std::move(frame_painter)); } case FakeVideoCaptureDevice::DeliveryMode::USE_CLIENT_PROVIDED_BUFFERS: - return base::MakeUnique<ClientBufferFrameDeliverer>( + return std::make_unique<ClientBufferFrameDeliverer>( std::move(frame_painter)); } NOTREACHED();
diff --git a/media/capture/video/fake_video_capture_device_factory.cc b/media/capture/video/fake_video_capture_device_factory.cc index f668a61cf..48578c92 100644 --- a/media/capture/video/fake_video_capture_device_factory.cc +++ b/media/capture/video/fake_video_capture_device_factory.cc
@@ -131,18 +131,18 @@ } const VideoCaptureFormat& initial_format = settings.supported_formats.front(); - auto device_state = base::MakeUnique<FakeDeviceState>( + auto device_state = std::make_unique<FakeDeviceState>( kInitialZoom, initial_format.frame_rate, initial_format.pixel_format); - auto photo_frame_painter = base::MakeUnique<PacmanFramePainter>( + auto photo_frame_painter = std::make_unique<PacmanFramePainter>( PacmanFramePainter::Format::SK_N32, device_state.get()); - auto photo_device = base::MakeUnique<FakePhotoDevice>( + auto photo_device = std::make_unique<FakePhotoDevice>( std::move(photo_frame_painter), device_state.get(), settings.photo_device_config); - return base::MakeUnique<FakeVideoCaptureDevice>( + return std::make_unique<FakeVideoCaptureDevice>( settings.supported_formats, - base::MakeUnique<FrameDelivererFactory>(settings.delivery_mode, + std::make_unique<FrameDelivererFactory>(settings.delivery_mode, device_state.get()), std::move(photo_device), std::move(device_state)); } @@ -164,7 +164,7 @@ // static std::unique_ptr<VideoCaptureDevice> FakeVideoCaptureDeviceFactory::CreateErrorDevice() { - return base::MakeUnique<ErrorFakeDevice>(); + return std::make_unique<ErrorFakeDevice>(); } void FakeVideoCaptureDeviceFactory::SetToDefaultDevicesConfig(
diff --git a/media/capture/video/fake_video_capture_device_unittest.cc b/media/capture/video/fake_video_capture_device_unittest.cc index e27f359..b606ca001 100644 --- a/media/capture/video/fake_video_capture_device_unittest.cc +++ b/media/capture/video/fake_video_capture_device_unittest.cc
@@ -12,7 +12,6 @@ #include "base/bind.h" #include "base/command_line.h" -#include "base/memory/ptr_util.h" #include "base/run_loop.h" #include "base/test/scoped_task_environment.h" #include "base/test/test_timeouts.h" @@ -71,7 +70,7 @@ std::unique_ptr<VideoCaptureBufferHandle> GetHandleForInProcessAccess() override { - return base::MakeUnique<StubBufferHandle>(mapped_size_, data_); + return std::make_unique<StubBufferHandle>(mapped_size_, data_); } private: @@ -95,8 +94,8 @@ const int arbitrary_frame_feedback_id = 0; return VideoCaptureDevice::Client::Buffer( buffer_id, arbitrary_frame_feedback_id, - base::MakeUnique<StubBufferHandleProvider>(mapped_size, buffer), - base::MakeUnique<StubReadWritePermission>(buffer)); + std::make_unique<StubBufferHandleProvider>(mapped_size, buffer), + std::make_unique<StubReadWritePermission>(buffer)); }; class MockClient : public VideoCaptureDevice::Client {
diff --git a/media/capture/video/linux/v4l2_capture_delegate_unittest.cc b/media/capture/video/linux/v4l2_capture_delegate_unittest.cc index 71a1edff..8ba6719c 100644 --- a/media/capture/video/linux/v4l2_capture_delegate_unittest.cc +++ b/media/capture/video/linux/v4l2_capture_delegate_unittest.cc
@@ -216,7 +216,7 @@ public: V4L2CaptureDelegateTest() : device_descriptor_("Device 0", "/dev/video0"), - delegate_(base::MakeUnique<V4L2CaptureDelegate>( + delegate_(std::make_unique<V4L2CaptureDelegate>( device_descriptor_, base::ThreadTaskRunnerHandle::Get(), 50)) {}
diff --git a/media/capture/video/linux/video_capture_device_linux.cc b/media/capture/video/linux/video_capture_device_linux.cc index 2883ccee..594596a 100644 --- a/media/capture/video/linux/video_capture_device_linux.cc +++ b/media/capture/video/linux/video_capture_device_linux.cc
@@ -7,6 +7,7 @@ #include <stddef.h> #include <list> +#include <memory> #include "base/bind.h" #include "base/single_thread_task_runner.h" @@ -57,7 +58,7 @@ const int line_frequency = TranslatePowerLineFrequencyToV4L2(GetPowerLineFrequency(params)); - capture_impl_ = base::MakeUnique<V4L2CaptureDelegate>( + capture_impl_ = std::make_unique<V4L2CaptureDelegate>( device_descriptor_, v4l2_thread_.task_runner(), line_frequency); if (!capture_impl_) { client->OnError(FROM_HERE, "Failed to create VideoCaptureDelegate");
diff --git a/media/capture/video/video_capture_buffer_tracker_factory_impl.cc b/media/capture/video/video_capture_buffer_tracker_factory_impl.cc index b9a9c97..fe1df4f 100644 --- a/media/capture/video/video_capture_buffer_tracker_factory_impl.cc +++ b/media/capture/video/video_capture_buffer_tracker_factory_impl.cc
@@ -4,7 +4,7 @@ #include "media/capture/video/video_capture_buffer_tracker_factory_impl.h" -#include "base/memory/ptr_util.h" +#include <memory> #include "media/capture/video/shared_memory_buffer_tracker.h" @@ -13,7 +13,7 @@ std::unique_ptr<VideoCaptureBufferTracker> VideoCaptureBufferTrackerFactoryImpl::CreateTracker(VideoPixelStorage storage) { DCHECK_EQ(VideoPixelStorage::CPU, storage); - return base::MakeUnique<SharedMemoryBufferTracker>(); + return std::make_unique<SharedMemoryBufferTracker>(); } } // namespace media
diff --git a/media/capture/video/video_capture_device_client.cc b/media/capture/video/video_capture_device_client.cc index e2e9e706..3b0063e 100644 --- a/media/capture/video/video_capture_device_client.cc +++ b/media/capture/video/video_capture_device_client.cc
@@ -5,12 +5,12 @@ #include "media/capture/video/video_capture_device_client.h" #include <algorithm> +#include <memory> #include <utility> #include "base/bind.h" #include "base/command_line.h" #include "base/location.h" -#include "base/memory/ptr_util.h" #include "base/strings/stringprintf.h" #include "base/trace_event/trace_event.h" #include "build/build_config.h" @@ -91,8 +91,8 @@ int frame_feedback_id) { return Buffer( buffer_id, frame_feedback_id, - base::MakeUnique<BufferPoolBufferHandleProvider>(buffer_pool, buffer_id), - base::MakeUnique<ScopedBufferPoolReservation<ProducerReleaseTraits>>( + std::make_unique<BufferPoolBufferHandleProvider>(buffer_pool, buffer_id), + std::make_unique<ScopedBufferPoolReservation<ProducerReleaseTraits>>( buffer_pool, buffer_id)); } @@ -313,7 +313,7 @@ if (!base::ContainsValue(buffer_ids_known_by_receiver_, buffer_id)) { receiver_->OnNewBufferHandle( - buffer_id, base::MakeUnique<BufferPoolBufferHandleProvider>( + buffer_id, std::make_unique<BufferPoolBufferHandleProvider>( buffer_pool_, buffer_id)); buffer_ids_known_by_receiver_.push_back(buffer_id); } @@ -357,7 +357,7 @@ buffer_pool_->HoldForConsumers(buffer.id, 1); receiver_->OnFrameReadyInBuffer( buffer.id, buffer.frame_feedback_id, - base::MakeUnique<ScopedBufferPoolReservation<ConsumerReleaseTraits>>( + std::make_unique<ScopedBufferPoolReservation<ConsumerReleaseTraits>>( buffer_pool_, buffer.id), std::move(info)); }
diff --git a/media/capture/video/video_capture_device_client_unittest.cc b/media/capture/video/video_capture_device_client_unittest.cc index 8966d20..1fcaa724 100644 --- a/media/capture/video/video_capture_device_client_unittest.cc +++ b/media/capture/video/video_capture_device_client_unittest.cc
@@ -47,10 +47,10 @@ VideoCaptureDeviceClientTest() { scoped_refptr<VideoCaptureBufferPoolImpl> buffer_pool( new VideoCaptureBufferPoolImpl( - base::MakeUnique<VideoCaptureBufferTrackerFactoryImpl>(), 1)); - auto controller = base::MakeUnique<MockVideoFrameReceiver>(); + std::make_unique<VideoCaptureBufferTrackerFactoryImpl>(), 1)); + auto controller = std::make_unique<MockVideoFrameReceiver>(); receiver_ = controller.get(); - device_client_ = base::MakeUnique<VideoCaptureDeviceClient>( + device_client_ = std::make_unique<VideoCaptureDeviceClient>( std::move(controller), buffer_pool, base::Bind(&ReturnNullPtrAsJpecDecoder)); }
diff --git a/media/capture/video/video_capture_device_factory.cc b/media/capture/video/video_capture_device_factory.cc index 2f535ec..37018978 100644 --- a/media/capture/video/video_capture_device_factory.cc +++ b/media/capture/video/video_capture_device_factory.cc
@@ -33,7 +33,7 @@ command_line->GetSwitchValueASCII( switches::kUseFakeDeviceForMediaStream), &config); - auto result = base::MakeUnique<FakeVideoCaptureDeviceFactory>(); + auto result = std::make_unique<FakeVideoCaptureDeviceFactory>(); result->SetToCustomDevicesConfig(config); return std::move(result); }
diff --git a/media/capture/video/video_capture_device_unittest.cc b/media/capture/video/video_capture_device_unittest.cc index b2af0ba..92c3016 100644 --- a/media/capture/video/video_capture_device_unittest.cc +++ b/media/capture/video/video_capture_device_unittest.cc
@@ -253,7 +253,7 @@ void SetUp() override { #if defined(OS_CHROMEOS) dbus_setter_->SetPowerManagerClient( - base::MakeUnique<chromeos::FakePowerManagerClient>()); + std::make_unique<chromeos::FakePowerManagerClient>()); #endif #if defined(OS_ANDROID) static_cast<VideoCaptureDeviceFactoryAndroid*>( @@ -290,7 +290,7 @@ for (const auto& descriptor : *device_descriptors_) { if (IsDeviceUsableForTesting(descriptor)) { DLOG(INFO) << "Using camera " << descriptor.GetNameAndModel(); - return base::MakeUnique<VideoCaptureDeviceDescriptor>(descriptor); + return std::make_unique<VideoCaptureDeviceDescriptor>(descriptor); } } DLOG(WARNING) << "No usable camera found"; @@ -312,7 +312,7 @@ << device_descriptors_->front().GetNameAndModel(); #endif - return base::MakeUnique<VideoCaptureDeviceDescriptor>( + return std::make_unique<VideoCaptureDeviceDescriptor>( device_descriptors_->front()); }
diff --git a/media/cast/BUILD.gn b/media/cast/BUILD.gn index 864cf10..d693f14 100644 --- a/media/cast/BUILD.gn +++ b/media/cast/BUILD.gn
@@ -102,6 +102,8 @@ "net/rtp/rtp_parser.h", "net/rtp/rtp_sender.cc", "net/rtp/rtp_sender.h", + "net/udp_packet_pipe.cc", + "net/udp_packet_pipe.h", "net/udp_transport.cc", "net/udp_transport.h", ] @@ -109,6 +111,7 @@ deps = [ ":common", "//base", + "//media/mojo/common", "//net", ] @@ -311,6 +314,7 @@ "net/rtp/rtp_packet_builder.h", "net/rtp/rtp_packetizer_unittest.cc", "net/rtp/rtp_parser_unittest.cc", + "net/udp_packet_pipe_unittest.cc", "net/udp_transport_unittest.cc", "receiver/audio_decoder_unittest.cc", "receiver/frame_receiver_unittest.cc", @@ -336,9 +340,9 @@ ":sender", ":test_support", "//base", - "//base/test:run_all_unittests", "//base/test:test_support", "//media:test_support", + "//media/test:run_all_unittests", "//net", "//testing/gmock", "//testing/gtest",
diff --git a/media/cast/logging/stats_event_subscriber.cc b/media/cast/logging/stats_event_subscriber.cc index 4f6594c8..26033ed 100644 --- a/media/cast/logging/stats_event_subscriber.cc +++ b/media/cast/logging/stats_event_subscriber.cc
@@ -6,11 +6,11 @@ #include <algorithm> #include <cmath> +#include <memory> #include <utility> #include "base/format_macros.h" #include "base/logging.h" -#include "base/memory/ptr_util.h" #include "base/strings/stringprintf.h" #include "base/values.h" @@ -227,9 +227,9 @@ std::unique_ptr<base::DictionaryValue> StatsEventSubscriber::GetStats() const { StatsMap stats_map; GetStatsInternal(&stats_map); - auto ret = base::MakeUnique<base::DictionaryValue>(); + auto ret = std::make_unique<base::DictionaryValue>(); - auto stats = base::MakeUnique<base::DictionaryValue>(); + auto stats = std::make_unique<base::DictionaryValue>(); for (StatsMap::const_iterator it = stats_map.begin(); it != stats_map.end(); ++it) { // Round to 3 digits after the decimal point.
diff --git a/media/cast/net/DEPS b/media/cast/net/DEPS index 46778a3..4da296c0 100644 --- a/media/cast/net/DEPS +++ b/media/cast/net/DEPS
@@ -6,6 +6,7 @@ "+media/cast/constants.h", "+media/cast/logging", "+media/cast/net", + "+media/mojo/common", "+net", ]
diff --git a/media/cast/net/cast_transport_impl_unittest.cc b/media/cast/net/cast_transport_impl_unittest.cc index 123453cc..4992d29 100644 --- a/media/cast/net/cast_transport_impl_unittest.cc +++ b/media/cast/net/cast_transport_impl_unittest.cc
@@ -108,7 +108,7 @@ rtp_config.feedback_ssrc = 2; rtp_config.rtp_payload_type = RtpPayloadType::VIDEO_VP8; transport_sender_->InitializeStream(rtp_config, - base::MakeUnique<StubRtcpObserver>()); + std::make_unique<StubRtcpObserver>()); } void InitializeAudio() { @@ -117,7 +117,7 @@ rtp_config.feedback_ssrc = 3; rtp_config.rtp_payload_type = RtpPayloadType::AUDIO_OPUS; transport_sender_->InitializeStream(rtp_config, - base::MakeUnique<StubRtcpObserver>()); + std::make_unique<StubRtcpObserver>()); } base::SimpleTestTickClock testing_clock_; @@ -156,7 +156,7 @@ transport_ = new FakePacketSender(); transport_sender_.reset( new CastTransportImpl(&testing_clock_, base::TimeDelta(), - base::MakeUnique<TransportClient>(nullptr), + std::make_unique<TransportClient>(nullptr), base::WrapUnique(transport_), task_runner_)); task_runner_->RunTasks(); } @@ -170,7 +170,7 @@ transport_ = new FakePacketSender(); transport_sender_.reset( new CastTransportImpl(&testing_clock_, base::TimeDelta(), - base::MakeUnique<TransportClient>(nullptr), + std::make_unique<TransportClient>(nullptr), base::WrapUnique(transport_), task_runner_)); transport_sender_->SetOptions(*options); task_runner_->RunTasks(); @@ -180,7 +180,7 @@ transport_ = new FakePacketSender(); transport_sender_.reset(new CastTransportImpl( &testing_clock_, base::TimeDelta::FromMilliseconds(10), - base::MakeUnique<TransportClient>(this), base::WrapUnique(transport_), + std::make_unique<TransportClient>(this), base::WrapUnique(transport_), task_runner_)); task_runner_->RunTasks(); }
diff --git a/media/cast/net/udp_packet_pipe.cc b/media/cast/net/udp_packet_pipe.cc new file mode 100644 index 0000000..a2480630 --- /dev/null +++ b/media/cast/net/udp_packet_pipe.cc
@@ -0,0 +1,106 @@ +// 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 "media/cast/net/udp_packet_pipe.h" + +#include <cstring> + +#include "base/callback.h" +#include "base/logging.h" +#include "base/memory/ptr_util.h" + +namespace media { +namespace cast { + +// UdpPacketPipeReader + +UdpPacketPipeReader::UdpPacketPipeReader( + mojo::ScopedDataPipeConsumerHandle consumer_handle) + : data_pipe_reader_(std::move(consumer_handle)) { + DCHECK(data_pipe_reader_.IsPipeValid()); +} + +UdpPacketPipeReader::~UdpPacketPipeReader() {} + +void UdpPacketPipeReader::Read(ReadCB cb) { + DCHECK(!cb.is_null()); + data_pipe_reader_.Read(reinterpret_cast<uint8_t*>(¤t_packet_size_), + sizeof(uint16_t), + base::BindOnce(&UdpPacketPipeReader::ReadPacketPayload, + base::Unretained(this), std::move(cb))); +} + +void UdpPacketPipeReader::ReadPacketPayload(ReadCB cb, bool success) { + if (!success) { + OnPacketRead(nullptr, std::move(cb), false); + return; + } + auto packet = std::make_unique<Packet>(current_packet_size_); + uint8_t* packet_data = packet->data(); + data_pipe_reader_.Read( + packet_data, current_packet_size_, + base::BindOnce(&UdpPacketPipeReader::OnPacketRead, base::Unretained(this), + std::move(packet), std::move(cb))); +} + +void UdpPacketPipeReader::OnPacketRead(std::unique_ptr<Packet> packet, + ReadCB cb, + bool success) { + DCHECK(!cb.is_null()); + if (!success) { + VLOG(1) << "Failed when reading the packet."; + // The data pipe should have been closed. + } + std::move(cb).Run(std::move(packet)); +} + +// UdpPacketPipeWriter + +UdpPacketPipeWriter::UdpPacketPipeWriter( + mojo::ScopedDataPipeProducerHandle producer_handle) + : data_pipe_writer_(std::move(producer_handle)) { + DCHECK(data_pipe_writer_.IsPipeValid()); +} + +UdpPacketPipeWriter::~UdpPacketPipeWriter() {} + +void UdpPacketPipeWriter::Write(PacketRef packet, base::OnceClosure done_cb) { + DCHECK(!done_cb.is_null()); + current_packet_size_ = packet->data.size(); + data_pipe_writer_.Write( + reinterpret_cast<uint8_t*>(¤t_packet_size_), sizeof(uint16_t), + base::BindOnce(&UdpPacketPipeWriter::WritePacketPayload, + base::Unretained(this), std::move(packet), + std::move(done_cb))); +} + +void UdpPacketPipeWriter::WritePacketPayload(PacketRef packet, + base::OnceClosure done_cb, + bool success) { + if (!success) { + OnPacketWritten(PacketRef(), std::move(done_cb), false); + return; + } + const uint8_t* buffer = packet->data.data(); + const int buffer_size = packet->data.size(); + data_pipe_writer_.Write( + buffer, buffer_size, + base::BindOnce(&UdpPacketPipeWriter::OnPacketWritten, + base::Unretained(this), std::move(packet), + std::move(done_cb))); +} + +void UdpPacketPipeWriter::OnPacketWritten(PacketRef packet, + base::OnceClosure done_cb, + bool success) { + DCHECK(!done_cb.is_null()); + if (!success) { + VLOG(1) << "Failed to write the packet."; + // The data pipe should have been closed. + } + std::move(done_cb).Run(); +} + +} // namespace cast +} // namespace media
diff --git a/media/cast/net/udp_packet_pipe.h b/media/cast/net/udp_packet_pipe.h new file mode 100644 index 0000000..b0527367 --- /dev/null +++ b/media/cast/net/udp_packet_pipe.h
@@ -0,0 +1,81 @@ +// 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 MEDIA_CAST_NET_UDP_PACKET_PIPE_H_ +#define MEDIA_CAST_NET_UDP_PACKET_PIPE_H_ + +#include "media/cast/net/cast_transport_defines.h" +#include "media/mojo/common/mojo_data_pipe_read_write.h" + +namespace media { +namespace cast { + +// Reads UDP packets from the mojo data pipe. Assuming the size of each UDP +// packet was written before the packet itself was written into the pipe. +class UdpPacketPipeReader { + public: + explicit UdpPacketPipeReader( + mojo::ScopedDataPipeConsumerHandle consumer_handle); + + ~UdpPacketPipeReader(); + + using ReadCB = base::OnceCallback<void(std::unique_ptr<Packet>)>; + // Reads one UDP packet from the data pipe. This should only be called when + // there is no other reading in process. + void Read(ReadCB cb); + + private: + // Reads packet payload from the data pipe. |success| indicates whether the + // size of the packet was successfully read from the data pipe. |cb| will be + // called after reading is done. + void ReadPacketPayload(ReadCB cb, bool success); + + // Called by |data_pipe_reader_| when the reading completes. + void OnPacketRead(std::unique_ptr<Packet> packet, ReadCB cb, bool success); + + MojoDataPipeReader data_pipe_reader_; + + uint16_t current_packet_size_; + + DISALLOW_COPY_AND_ASSIGN(UdpPacketPipeReader); +}; + +// Writes UDP packets into the data mojo pipe. The size of each packet is +// written before the packet itself is written into the data pipe. +class UdpPacketPipeWriter { + public: + explicit UdpPacketPipeWriter( + mojo::ScopedDataPipeProducerHandle producer_handle); + + ~UdpPacketPipeWriter(); + + // Writes the |packet| into the mojo data pipe. |done_cb| will be + // called when the writing completes. This should only be called when there is + // no other writing in process. + void Write(PacketRef packet, base::OnceClosure done_cb); + + private: + // Writes the |packet| payload in the data pipe. |success| indicates whether + // the size of the packet was successfully written in the data pipe. |done_cb| + // will be called after writing is done. + void WritePacketPayload(PacketRef packet, + base::OnceClosure done_cb, + bool success); + + // Called by |data_pipe_writer_| when the writing completes. + void OnPacketWritten(PacketRef packet, + base::OnceClosure done_cb, + bool success); + + MojoDataPipeWriter data_pipe_writer_; + + uint16_t current_packet_size_ = 0; + + DISALLOW_COPY_AND_ASSIGN(UdpPacketPipeWriter); +}; + +} // namespace cast +} // namespace media + +#endif // MEDIA_CAST_NET_UDP_PACKET_PIPE_H_
diff --git a/media/cast/net/udp_packet_pipe_unittest.cc b/media/cast/net/udp_packet_pipe_unittest.cc new file mode 100644 index 0000000..c993c3a --- /dev/null +++ b/media/cast/net/udp_packet_pipe_unittest.cc
@@ -0,0 +1,96 @@ +// 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 "media/cast/net/udp_packet_pipe.h" + +#include <string> + +#include "base/bind.h" +#include "base/callback.h" +#include "base/containers/circular_deque.h" +#include "base/macros.h" +#include "base/memory/ptr_util.h" +#include "base/test/mock_callback.h" +#include "base/test/scoped_task_environment.h" +#include "testing/gtest/include/gtest/gtest.h" + +namespace media { +namespace cast { + +namespace { +constexpr uint32_t kDefaultDataPipeCapacityBytes = 10; +} // namespace + +class UdpPacketPipeTest : public ::testing::Test { + public: + UdpPacketPipeTest() { + mojo::DataPipe data_pipe(kDefaultDataPipeCapacityBytes); + writer_ = base::MakeUnique<UdpPacketPipeWriter>( + std::move(data_pipe.producer_handle)); + reader_ = base::MakeUnique<UdpPacketPipeReader>( + std::move(data_pipe.consumer_handle)); + } + + ~UdpPacketPipeTest() override = default; + + void OnPacketRead(std::unique_ptr<Packet> packet) { + packets_read_.push_back(std::move(packet)); + } + + protected: + base::test::ScopedTaskEnvironment scoped_task_environment_; + std::unique_ptr<UdpPacketPipeWriter> writer_; + std::unique_ptr<UdpPacketPipeReader> reader_; + base::circular_deque<std::unique_ptr<Packet>> packets_read_; + + private: + DISALLOW_COPY_AND_ASSIGN(UdpPacketPipeTest); +}; + +TEST_F(UdpPacketPipeTest, Normal) { + std::string data1 = "test"; + std::string data2 = "Hello!"; + Packet packet1(data1.begin(), data1.end()); + Packet packet2(data2.begin(), data2.end()); + + // Writes |packet1|. Expected to be done successfully. + base::MockCallback<base::OnceClosure> done_callback; + EXPECT_CALL(done_callback, Run()).Times(1); + writer_->Write(new base::RefCountedData<Packet>(packet1), + done_callback.Get()); + scoped_task_environment_.RunUntilIdle(); + + // |packet2| can not be completely written in the data pipe due to capacity + // limit. + base::MockCallback<base::OnceClosure> done_callback2; + EXPECT_CALL(done_callback2, Run()).Times(0); + writer_->Write(new base::RefCountedData<Packet>(packet2), + done_callback2.Get()); + scoped_task_environment_.RunUntilIdle(); + testing::Mock::VerifyAndClearExpectations(&done_callback2); + EXPECT_TRUE(packets_read_.empty()); + + // |packet2| is expected to complete writing after |packet1| is read. + EXPECT_CALL(done_callback2, Run()).Times(1); + reader_->Read( + base::BindOnce(&UdpPacketPipeTest::OnPacketRead, base::Unretained(this))); + scoped_task_environment_.RunUntilIdle(); + EXPECT_EQ(1u, packets_read_.size()); + EXPECT_EQ(0, std::memcmp(packet1.data(), packets_read_.front()->data(), + packet1.size())); + packets_read_.pop_front(); + + // Reads |packet2| from the pipe. + reader_->Read( + base::BindOnce(&UdpPacketPipeTest::OnPacketRead, base::Unretained(this))); + scoped_task_environment_.RunUntilIdle(); + EXPECT_EQ(1u, packets_read_.size()); + EXPECT_EQ(0, std::memcmp(packet2.data(), packets_read_.front()->data(), + packet2.size())); + packets_read_.pop_front(); + EXPECT_TRUE(packets_read_.empty()); +} + +} // namespace cast +} // namespace media
diff --git a/media/cast/sender/audio_sender_unittest.cc b/media/cast/sender/audio_sender_unittest.cc index f176afa..95eddbc8 100644 --- a/media/cast/sender/audio_sender_unittest.cc +++ b/media/cast/sender/audio_sender_unittest.cc
@@ -108,7 +108,7 @@ transport_ = new TestPacketSender(); transport_sender_.reset(new CastTransportImpl( - &testing_clock_, base::TimeDelta(), base::MakeUnique<TransportClient>(), + &testing_clock_, base::TimeDelta(), std::make_unique<TransportClient>(), base::WrapUnique(transport_), task_runner_)); OperationalStatus operational_status = STATUS_UNINITIALIZED; audio_sender_.reset(new AudioSender(
diff --git a/media/cast/sender/frame_sender.cc b/media/cast/sender/frame_sender.cc index 2d48010..1707182c 100644 --- a/media/cast/sender/frame_sender.cc +++ b/media/cast/sender/frame_sender.cc
@@ -6,11 +6,11 @@ #include <algorithm> #include <limits> +#include <memory> #include <utility> #include <vector> #include "base/macros.h" -#include "base/memory/ptr_util.h" #include "base/numerics/safe_conversions.h" #include "base/trace_event/trace_event.h" #include "media/cast/constants.h" @@ -96,7 +96,7 @@ transport_sender->InitializeStream( transport_config, - base::MakeUnique<FrameSender::RtcpClient>(weak_factory_.GetWeakPtr())); + std::make_unique<FrameSender::RtcpClient>(weak_factory_.GetWeakPtr())); } FrameSender::~FrameSender() = default;
diff --git a/media/cast/sender/video_sender_unittest.cc b/media/cast/sender/video_sender_unittest.cc index 0077531..32e7b5f 100644 --- a/media/cast/sender/video_sender_unittest.cc +++ b/media/cast/sender/video_sender_unittest.cc
@@ -161,7 +161,7 @@ last_pixel_value_ = kPixelValue; transport_ = new TestPacketSender(); transport_sender_.reset(new CastTransportImpl( - &testing_clock_, base::TimeDelta(), base::MakeUnique<TransportClient>(), + &testing_clock_, base::TimeDelta(), std::make_unique<TransportClient>(), base::WrapUnique(transport_), task_runner_)); }
diff --git a/media/cast/test/cast_benchmarks.cc b/media/cast/test/cast_benchmarks.cc index bd8a18f..612a56a 100644 --- a/media/cast/test/cast_benchmarks.cc +++ b/media/cast/test/cast_benchmarks.cc
@@ -26,6 +26,7 @@ #include <stdint.h> #include <map> +#include <memory> #include <utility> #include <vector> @@ -474,14 +475,14 @@ transport_sender_.Init( new CastTransportImpl( &testing_clock_sender_, base::TimeDelta::FromSeconds(1), - base::MakeUnique<TransportClient>(nullptr), + std::make_unique<TransportClient>(nullptr), base::WrapUnique(sender_to_receiver_), task_runner_sender_), &video_bytes_encoded_, &audio_bytes_encoded_); receiver_to_sender_ = new LoopBackTransport(cast_environment_receiver_); transport_receiver_.reset(new CastTransportImpl( &testing_clock_receiver_, base::TimeDelta::FromSeconds(1), - base::MakeUnique<TransportClient>(this), + std::make_unique<TransportClient>(this), base::WrapUnique(receiver_to_sender_), task_runner_receiver_)); cast_receiver_ =
diff --git a/media/cast/test/end2end_unittest.cc b/media/cast/test/end2end_unittest.cc index 780f2b9..fd0531f 100644 --- a/media/cast/test/end2end_unittest.cc +++ b/media/cast/test/end2end_unittest.cc
@@ -17,6 +17,7 @@ #include <functional> #include <list> #include <map> +#include <memory> #include <utility> #include "base/bind.h" @@ -915,13 +916,13 @@ void End2EndTest::Create() { transport_sender_.reset(new CastTransportImpl( &testing_clock_sender_, base::TimeDelta::FromMilliseconds(1), - base::MakeUnique<TransportClient>(cast_environment_sender_->logger(), + std::make_unique<TransportClient>(cast_environment_sender_->logger(), nullptr), base::WrapUnique(sender_to_receiver_), task_runner_sender_)); transport_receiver_.reset(new CastTransportImpl( &testing_clock_sender_, base::TimeDelta::FromMilliseconds(1), - base::MakeUnique<TransportClient>(cast_environment_receiver_->logger(), + std::make_unique<TransportClient>(cast_environment_receiver_->logger(), this), base::WrapUnique(receiver_to_sender_), task_runner_sender_));
diff --git a/media/cast/test/receiver.cc b/media/cast/test/receiver.cc index 5866fa3..50305f2 100644 --- a/media/cast/test/receiver.cc +++ b/media/cast/test/receiver.cc
@@ -563,7 +563,7 @@ // Start up Chromium audio system. auto audio_manager = media::AudioManager::CreateForTesting( - base::MakeUnique<media::TestAudioThread>()); + std::make_unique<media::TestAudioThread>()); CHECK(media::AudioManager::Get()); media::cast::FrameReceiverConfig audio_config =
diff --git a/media/cast/test/sender.cc b/media/cast/test/sender.cc index d876b1d..5e30057 100644 --- a/media/cast/test/sender.cc +++ b/media/cast/test/sender.cc
@@ -16,7 +16,6 @@ #include "base/files/file_path.h" #include "base/json/json_writer.h" #include "base/logging.h" -#include "base/memory/ptr_util.h" #include "base/message_loop/message_loop.h" #include "base/path_service.h" #include "base/run_loop.h" @@ -265,8 +264,8 @@ std::unique_ptr<media::cast::CastTransport> transport_sender = media::cast::CastTransport::Create( cast_environment->Clock(), base::TimeDelta::FromSeconds(1), - base::MakeUnique<TransportClient>(cast_environment->logger()), - base::MakeUnique<media::cast::UdpTransport>( + std::make_unique<TransportClient>(cast_environment->logger()), + std::make_unique<media::cast::UdpTransport>( nullptr, io_message_loop.task_runner(), net::IPEndPoint(), remote_endpoint, base::Bind(&UpdateCastTransportStatus)), io_message_loop.task_runner());
diff --git a/media/cast/test/simulator.cc b/media/cast/test/simulator.cc index f6d3e71..4c180bc 100644 --- a/media/cast/test/simulator.cc +++ b/media/cast/test/simulator.cc
@@ -37,6 +37,7 @@ #include <stddef.h> #include <stdint.h> +#include <memory> #include <utility> #include "base/at_exit.h" @@ -391,7 +392,7 @@ // Cast receiver. std::unique_ptr<CastTransport> transport_receiver(new CastTransportImpl( &testing_clock, base::TimeDelta::FromSeconds(1), - base::MakeUnique<TransportClient>(receiver_env->logger(), &packet_proxy), + std::make_unique<TransportClient>(receiver_env->logger(), &packet_proxy), base::WrapUnique(receiver_to_sender), task_runner)); std::unique_ptr<CastReceiver> cast_receiver( CastReceiver::Create(receiver_env, audio_receiver_config, @@ -402,7 +403,7 @@ // Cast sender and transport sender. std::unique_ptr<CastTransport> transport_sender(new CastTransportImpl( &testing_clock, base::TimeDelta::FromSeconds(1), - base::MakeUnique<TransportClient>(sender_env->logger(), nullptr), + std::make_unique<TransportClient>(sender_env->logger(), nullptr), base::WrapUnique(sender_to_receiver), task_runner)); std::unique_ptr<CastSender> cast_sender( CastSender::Create(sender_env, transport_sender.get()));
diff --git a/media/cast/test/utility/in_process_receiver.cc b/media/cast/test/utility/in_process_receiver.cc index e4c3e3eb..a78282f 100644 --- a/media/cast/test/utility/in_process_receiver.cc +++ b/media/cast/test/utility/in_process_receiver.cc
@@ -4,6 +4,7 @@ #include "media/cast/test/utility/in_process_receiver.h" +#include <memory> #include <utility> #include "base/bind_helpers.h" @@ -98,7 +99,7 @@ transport_ = CastTransport::Create( cast_environment_->Clock(), base::TimeDelta(), base::WrapUnique(new InProcessReceiver::TransportClient(this)), - base::MakeUnique<UdpTransport>( + std::make_unique<UdpTransport>( nullptr, cast_environment_->GetTaskRunner(CastEnvironment::MAIN), local_end_point_, remote_end_point_, base::Bind(&InProcessReceiver::UpdateCastTransportStatus,
diff --git a/media/cdm/aes_decryptor.cc b/media/cdm/aes_decryptor.cc index a4ff4e5..b1d9a33 100644 --- a/media/cdm/aes_decryptor.cc +++ b/media/cdm/aes_decryptor.cc
@@ -6,13 +6,13 @@ #include <stddef.h> #include <list> +#include <memory> #include <utility> #include <vector> #include "base/bind.h" #include "base/logging.h" #include "base/macros.h" -#include "base/memory/ptr_util.h" #include "base/strings/string_number_conversions.h" #include "base/time/time.h" #include "crypto/encryptor.h" @@ -751,7 +751,7 @@ for (const auto& item : key_map_) { if (item.second->Contains(session_id)) { keys_info.push_back( - base::MakeUnique<CdmKeyInformation>(item.first, status, 0)); + std::make_unique<CdmKeyInformation>(item.first, status, 0)); } } }
diff --git a/media/cdm/cdm_adapter.cc b/media/cdm/cdm_adapter.cc index 5550542..c2d840f 100644 --- a/media/cdm/cdm_adapter.cc +++ b/media/cdm/cdm_adapter.cc
@@ -5,12 +5,12 @@ #include "media/cdm/cdm_adapter.h" #include <stddef.h> +#include <memory> #include <utility> #include "base/bind.h" #include "base/callback_helpers.h" #include "base/logging.h" -#include "base/memory/ptr_util.h" #include "base/message_loop/message_loop.h" #include "base/metrics/histogram_functions.h" #include "base/metrics/histogram_macros.h" @@ -471,7 +471,7 @@ session_closed_cb, session_keys_change_cb, session_expiration_update_cb); // |cdm| ownership passed to the promise. - cdm->Initialize(base::MakeUnique<CdmInitializedPromise>(cdm_created_cb, cdm)); + cdm->Initialize(std::make_unique<CdmInitializedPromise>(cdm_created_cb, cdm)); } CdmAdapter::CdmAdapter( @@ -978,7 +978,7 @@ keys.reserve(keys_info_count); for (uint32_t i = 0; i < keys_info_count; ++i) { const auto& info = keys_info[i]; - keys.push_back(base::MakeUnique<CdmKeyInformation>( + keys.push_back(std::make_unique<CdmKeyInformation>( info.key_id, info.key_id_size, ToCdmKeyInformationKeyStatus(info.status), info.system_code)); }
diff --git a/media/cdm/json_web_key.cc b/media/cdm/json_web_key.cc index c156da5e..d851ff3 100644 --- a/media/cdm/json_web_key.cc +++ b/media/cdm/json_web_key.cc
@@ -15,7 +15,6 @@ #include "base/json/string_escape.h" #include "base/logging.h" #include "base/macros.h" -#include "base/memory/ptr_util.h" #include "base/strings/string_number_conversions.h" #include "base/strings/string_piece.h" #include "base/strings/string_util.h" @@ -63,7 +62,7 @@ base::StringPiece(reinterpret_cast<const char*>(key_id), key_id_length), base::Base64UrlEncodePolicy::OMIT_PADDING, &key_id_string); - auto jwk = base::MakeUnique<base::DictionaryValue>(); + auto jwk = std::make_unique<base::DictionaryValue>(); jwk->SetString(kKeyTypeTag, kKeyTypeOct); jwk->SetString(kKeyTag, key_string); jwk->SetString(kKeyIdTag, key_id_string); @@ -75,7 +74,7 @@ const uint8_t* key_id, int key_id_length) { // Create the JWK, and wrap it into a JWK Set. - auto list = base::MakeUnique<base::ListValue>(); + auto list = std::make_unique<base::ListValue>(); list->Append(CreateJSONDictionary(key, key_length, key_id, key_id_length)); base::DictionaryValue jwk_set; jwk_set.Set(kKeysTag, std::move(list)); @@ -89,7 +88,7 @@ std::string GenerateJWKSet(const KeyIdAndKeyPairs& keys, CdmSessionType session_type) { - auto list = base::MakeUnique<base::ListValue>(); + auto list = std::make_unique<base::ListValue>(); for (const auto& key_pair : keys) { list->Append(CreateJSONDictionary( reinterpret_cast<const uint8_t*>(key_pair.second.data()), @@ -304,8 +303,8 @@ CdmSessionType session_type, std::vector<uint8_t>* license) { // Create the license request. - auto request = base::MakeUnique<base::DictionaryValue>(); - auto list = base::MakeUnique<base::ListValue>(); + auto request = std::make_unique<base::DictionaryValue>(); + auto list = std::make_unique<base::ListValue>(); for (const auto& key_id : key_ids) { std::string key_id_string; base::Base64UrlEncode( @@ -342,8 +341,8 @@ void CreateKeyIdsInitData(const KeyIdList& key_ids, std::vector<uint8_t>* init_data) { // Create the init_data. - auto dictionary = base::MakeUnique<base::DictionaryValue>(); - auto list = base::MakeUnique<base::ListValue>(); + auto dictionary = std::make_unique<base::DictionaryValue>(); + auto list = std::make_unique<base::ListValue>(); for (const auto& key_id : key_ids) { std::string key_id_string; base::Base64UrlEncode(
diff --git a/media/cdm/ppapi/clear_key_cdm/clear_key_persistent_session_cdm.cc b/media/cdm/ppapi/clear_key_cdm/clear_key_persistent_session_cdm.cc index f63894c..d93bde7 100644 --- a/media/cdm/ppapi/clear_key_cdm/clear_key_persistent_session_cdm.cc +++ b/media/cdm/ppapi/clear_key_cdm/clear_key_persistent_session_cdm.cc
@@ -4,10 +4,11 @@ #include "media/cdm/ppapi/clear_key_cdm/clear_key_persistent_session_cdm.h" +#include <memory> + #include "base/bind.h" #include "base/callback.h" #include "base/macros.h" -#include "base/memory/ptr_util.h" #include "base/memory/ref_counted.h" #include "media/base/cdm_promise.h" @@ -119,7 +120,7 @@ } else { // Since it's a persistent session, we need to save the session ID after // it's been created. - new_promise = base::MakeUnique<NewPersistentSessionCdmPromise>( + new_promise = std::make_unique<NewPersistentSessionCdmPromise>( base::Bind(&ClearKeyPersistentSessionCdm::AddPersistentSession, weak_factory_.GetWeakPtr()), std::move(promise));
diff --git a/media/cdm/simple_cdm_allocator.cc b/media/cdm/simple_cdm_allocator.cc index d0512269..e5200530 100644 --- a/media/cdm/simple_cdm_allocator.cc +++ b/media/cdm/simple_cdm_allocator.cc
@@ -4,8 +4,9 @@ #include "media/cdm/simple_cdm_allocator.h" +#include <memory> + #include "base/bind.h" -#include "base/memory/ptr_util.h" #include "media/base/video_frame.h" #include "media/cdm/cdm_helpers.h" #include "media/cdm/simple_cdm_buffer.h" @@ -69,7 +70,7 @@ // Creates a new SimpleCdmVideoFrame on every request. std::unique_ptr<VideoFrameImpl> SimpleCdmAllocator::CreateCdmVideoFrame() { - return base::MakeUnique<SimpleCdmVideoFrame>(); + return std::make_unique<SimpleCdmVideoFrame>(); } } // namespace media
diff --git a/media/filters/chunk_demuxer.cc b/media/filters/chunk_demuxer.cc index 7d8e94b..e6ee082 100644 --- a/media/filters/chunk_demuxer.cc +++ b/media/filters/chunk_demuxer.cc
@@ -6,13 +6,13 @@ #include <algorithm> #include <limits> +#include <memory> #include <utility> #include "base/bind.h" #include "base/callback_helpers.h" #include "base/location.h" #include "base/macros.h" -#include "base/memory/ptr_util.h" #include "base/metrics/histogram_macros.h" #include "base/strings/string_number_conversions.h" #include "base/threading/thread_task_runner_handle.h" @@ -1285,7 +1285,7 @@ } std::unique_ptr<ChunkDemuxerStream> stream = - base::MakeUnique<ChunkDemuxerStream>( + std::make_unique<ChunkDemuxerStream>( type, media_track_id, (buffering_by_pts_ ? ChunkDemuxerStream::RangeApi::kNewByPts : ChunkDemuxerStream::RangeApi::kLegacyByDts));
diff --git a/media/filters/frame_processor.cc b/media/filters/frame_processor.cc index 056cc28b..ffc99733 100644 --- a/media/filters/frame_processor.cc +++ b/media/filters/frame_processor.cc
@@ -5,11 +5,11 @@ #include "media/filters/frame_processor.h" #include <stdint.h> +#include <memory> #include <cstdlib> #include "base/macros.h" -#include "base/memory/ptr_util.h" #include "media/base/stream_parser_buffer.h" #include "media/base/timestamp_constants.h" @@ -416,7 +416,7 @@ } track_buffers_[id] = - base::MakeUnique<MseTrackBuffer>(stream, media_log_, parse_warning_cb_); + std::make_unique<MseTrackBuffer>(stream, media_log_, parse_warning_cb_); return true; }
diff --git a/media/filters/frame_processor_unittest.cc b/media/filters/frame_processor_unittest.cc index 92a157ad..54fcfd33 100644 --- a/media/filters/frame_processor_unittest.cc +++ b/media/filters/frame_processor_unittest.cc
@@ -6,12 +6,12 @@ #include <stdint.h> #include <map> +#include <memory> #include <string> #include <vector> #include "base/bind.h" #include "base/macros.h" -#include "base/memory/ptr_util.h" #include "base/message_loop/message_loop.h" #include "base/run_loop.h" #include "base/strings/string_number_conversions.h" @@ -95,7 +95,7 @@ use_sequence_mode_ = params.use_sequence_mode; range_api_ = params.range_api; - frame_processor_ = base::MakeUnique<FrameProcessor>( + frame_processor_ = std::make_unique<FrameProcessor>( base::Bind( &FrameProcessorTestCallbackHelper::OnPossibleDurationIncrease, base::Unretained(&callbacks_)),
diff --git a/media/filters/source_buffer_range_by_dts.cc b/media/filters/source_buffer_range_by_dts.cc index d9831caf..e37b558 100644 --- a/media/filters/source_buffer_range_by_dts.cc +++ b/media/filters/source_buffer_range_by_dts.cc
@@ -5,8 +5,8 @@ #include "media/filters/source_buffer_range_by_dts.h" #include <algorithm> +#include <memory> -#include "base/memory/ptr_util.h" #include "media/base/timestamp_constants.h" namespace media { @@ -186,7 +186,7 @@ // Create a new range with |removed_buffers|. std::unique_ptr<SourceBufferRangeByDts> split_range = - base::MakeUnique<SourceBufferRangeByDts>(gap_policy_, removed_buffers, + std::make_unique<SourceBufferRangeByDts>(gap_policy_, removed_buffers, new_range_start_decode_timestamp, interbuffer_distance_cb_);
diff --git a/media/filters/source_buffer_range_by_pts.cc b/media/filters/source_buffer_range_by_pts.cc index 316aa5f..422921f 100644 --- a/media/filters/source_buffer_range_by_pts.cc +++ b/media/filters/source_buffer_range_by_pts.cc
@@ -5,11 +5,11 @@ #include "media/filters/source_buffer_range_by_pts.h" #include <algorithm> +#include <memory> #include <sstream> #include <string> #include "base/logging.h" -#include "base/memory/ptr_util.h" #include "media/base/timestamp_constants.h" namespace media { @@ -226,7 +226,7 @@ // Create a new range with |removed_buffers|. std::unique_ptr<SourceBufferRangeByPts> split_range = - base::MakeUnique<SourceBufferRangeByPts>(gap_policy_, removed_buffers, + std::make_unique<SourceBufferRangeByPts>(gap_policy_, removed_buffers, new_range_start_pts, interbuffer_distance_cb_);
diff --git a/media/filters/source_buffer_stream.cc b/media/filters/source_buffer_stream.cc index de4fb507..2b9c753 100644 --- a/media/filters/source_buffer_stream.cc +++ b/media/filters/source_buffer_stream.cc
@@ -6,12 +6,12 @@ #include <algorithm> #include <map> +#include <memory> #include <sstream> #include <string> #include "base/bind.h" #include "base/logging.h" -#include "base/memory/ptr_util.h" #include "base/trace_event/trace_event.h" #include "media/base/demuxer_memory_limit.h" #include "media/base/media_switches.h" @@ -2435,7 +2435,7 @@ SourceBufferStream<SourceBufferRangeByDts>::RangeNew( const BufferQueue& new_buffers, DecodeTimestamp range_start_time) { - return base::MakeUnique<SourceBufferRangeByDts>( + return std::make_unique<SourceBufferRangeByDts>( TypeToGapPolicy<SourceBufferRangeByDts>(GetType()), new_buffers, range_start_time, base::BindRepeating( @@ -2449,7 +2449,7 @@ SourceBufferStream<SourceBufferRangeByPts>::RangeNew( const BufferQueue& new_buffers, DecodeTimestamp range_start_time) { - return base::MakeUnique<SourceBufferRangeByPts>( + return std::make_unique<SourceBufferRangeByPts>( TypeToGapPolicy<SourceBufferRangeByPts>(GetType()), new_buffers, range_start_time.ToPresentationTime(), base::BindRepeating(
diff --git a/media/filters/video_frame_stream_unittest.cc b/media/filters/video_frame_stream_unittest.cc index cbcfa058..6c59d38 100644 --- a/media/filters/video_frame_stream_unittest.cc +++ b/media/filters/video_frame_stream_unittest.cc
@@ -8,7 +8,6 @@ #include "base/bind.h" #include "base/callback_helpers.h" #include "base/macros.h" -#include "base/memory/ptr_util.h" #include "base/message_loop/message_loop.h" #include "base/run_loop.h" #include "base/strings/string_number_conversions.h" @@ -143,7 +142,7 @@ // parameterized tests which need to pass in all combinations. std::vector<std::unique_ptr<VideoDecoder>> decoders; for (int i = 0; i < 3; ++i) { - auto decoder = base::MakeUnique<FakeVideoDecoder>( + auto decoder = std::make_unique<FakeVideoDecoder>( GetDecoderName(i), GetParam().decoding_delay, GetParam().parallel_decoding, base::Bind(&VideoFrameStreamTest::OnBytesDecoded,
diff --git a/media/formats/mp2t/mp2t_stream_parser.cc b/media/formats/mp2t/mp2t_stream_parser.cc index 947d6e62..cd4a8bc 100644 --- a/media/formats/mp2t/mp2t_stream_parser.cc +++ b/media/formats/mp2t/mp2t_stream_parser.cc
@@ -9,7 +9,6 @@ #include "base/bind.h" #include "base/callback_helpers.h" -#include "base/memory/ptr_util.h" #include "media/base/media_tracks.h" #include "media/base/stream_parser_buffer.h" #include "media/base/text_track_config.h" @@ -396,7 +395,7 @@ auto on_emit_video_buffer = base::Bind(&Mp2tStreamParser::OnEmitVideoBuffer, base::Unretained(this), pes_pid); - return base::MakeUnique<EsParserH264>(on_video_config_changed, + return std::make_unique<EsParserH264>(on_video_config_changed, on_emit_video_buffer); } @@ -405,7 +404,7 @@ &Mp2tStreamParser::OnAudioConfigChanged, base::Unretained(this), pes_pid); auto on_emit_audio_buffer = base::Bind(&Mp2tStreamParser::OnEmitAudioBuffer, base::Unretained(this), pes_pid); - return base::MakeUnique<EsParserAdts>(on_audio_config_changed, + return std::make_unique<EsParserAdts>(on_audio_config_changed, on_emit_audio_buffer, sbr_in_mimetype_); } @@ -415,7 +414,7 @@ &Mp2tStreamParser::OnAudioConfigChanged, base::Unretained(this), pes_pid); auto on_emit_audio_buffer = base::Bind(&Mp2tStreamParser::OnEmitAudioBuffer, base::Unretained(this), pes_pid); - return base::MakeUnique<EsParserMpeg1Audio>(on_audio_config_changed, + return std::make_unique<EsParserMpeg1Audio>(on_audio_config_changed, on_emit_audio_buffer, media_log_); } @@ -436,7 +435,7 @@ base::Unretained(this), pes_pid); auto get_decrypt_config = base::Bind(&Mp2tStreamParser::GetDecryptConfig, base::Unretained(this)); - return base::MakeUnique<EsParserH264>( + return std::make_unique<EsParserH264>( on_video_config_changed, on_emit_video_buffer, true, get_decrypt_config); } @@ -448,7 +447,7 @@ base::Unretained(this), pes_pid); auto get_decrypt_config = base::Bind(&Mp2tStreamParser::GetDecryptConfig, base::Unretained(this)); - return base::MakeUnique<EsParserAdts>( + return std::make_unique<EsParserAdts>( on_audio_config_changed, on_emit_audio_buffer, get_decrypt_config, true, sbr_in_mimetype_); }
diff --git a/media/formats/mpeg/adts_stream_parser_unittest.cc b/media/formats/mpeg/adts_stream_parser_unittest.cc index ddb1295..8b3a0554 100644 --- a/media/formats/mpeg/adts_stream_parser_unittest.cc +++ b/media/formats/mpeg/adts_stream_parser_unittest.cc
@@ -6,7 +6,6 @@ #include <memory> -#include "base/memory/ptr_util.h" #include "media/formats/common/stream_parser_test_base.h" #include "testing/gtest/include/gtest/gtest.h" @@ -15,7 +14,7 @@ class ADTSStreamParserTest : public StreamParserTestBase, public testing::Test { public: ADTSStreamParserTest() - : StreamParserTestBase(base::MakeUnique<ADTSStreamParser>()) {} + : StreamParserTestBase(std::make_unique<ADTSStreamParser>()) {} }; // Test parsing with small prime sized chunks to smoke out "power of
diff --git a/media/formats/mpeg/mpeg1_audio_stream_parser_unittest.cc b/media/formats/mpeg/mpeg1_audio_stream_parser_unittest.cc index f403ca1b..0315436 100644 --- a/media/formats/mpeg/mpeg1_audio_stream_parser_unittest.cc +++ b/media/formats/mpeg/mpeg1_audio_stream_parser_unittest.cc
@@ -8,7 +8,6 @@ #include <memory> -#include "base/memory/ptr_util.h" #include "media/base/test_data_util.h" #include "media/formats/common/stream_parser_test_base.h" #include "testing/gtest/include/gtest/gtest.h" @@ -19,7 +18,7 @@ : public StreamParserTestBase, public testing::Test { public: MPEG1AudioStreamParserTest() - : StreamParserTestBase(base::MakeUnique<MPEG1AudioStreamParser>()) {} + : StreamParserTestBase(std::make_unique<MPEG1AudioStreamParser>()) {} }; // Test parsing with small prime sized chunks to smoke out "power of
diff --git a/media/formats/webm/opus_packet_builder.cc b/media/formats/webm/opus_packet_builder.cc index 90b9f2d..c629bfb 100644 --- a/media/formats/webm/opus_packet_builder.cc +++ b/media/formats/webm/opus_packet_builder.cc
@@ -5,7 +5,6 @@ #include "media/formats/webm/opus_packet_builder.h" #include "base/logging.h" -#include "base/memory/ptr_util.h" #include "media/formats/webm/webm_cluster_parser.h" namespace media { @@ -72,14 +71,14 @@ opus_config_num++) { bool is_VBR = false; opus_packets.push_back( - base::MakeUnique<OpusPacket>(opus_config_num, frame_count, is_VBR)); + std::make_unique<OpusPacket>(opus_config_num, frame_count, is_VBR)); if (frame_count >= 2) { // Add another packet with VBR flag toggled. For frame counts >= 2, // VBR triggers changes to packet framing. is_VBR = true; opus_packets.push_back( - base::MakeUnique<OpusPacket>(opus_config_num, frame_count, is_VBR)); + std::make_unique<OpusPacket>(opus_config_num, frame_count, is_VBR)); } } }
diff --git a/media/gpu/android/android_video_decode_accelerator_unittest.cc b/media/gpu/android/android_video_decode_accelerator_unittest.cc index c5f0968..65ddf27 100644 --- a/media/gpu/android/android_video_decode_accelerator_unittest.cc +++ b/media/gpu/android/android_video_decode_accelerator_unittest.cc
@@ -10,7 +10,6 @@ #include "base/bind.h" #include "base/logging.h" -#include "base/memory/ptr_util.h" #include "base/memory/weak_ptr.h" #include "base/message_loop/message_loop.h" #include "base/run_loop.h" @@ -97,12 +96,12 @@ gl::GLContextAttribs()); context_->MakeCurrent(surface_.get()); - codec_allocator_ = base::MakeUnique<FakeCodecAllocator>( + codec_allocator_ = std::make_unique<FakeCodecAllocator>( base::SequencedTaskRunnerHandle::Get()); - device_info_ = base::MakeUnique<NiceMock<MockDeviceInfo>>(); + device_info_ = std::make_unique<NiceMock<MockDeviceInfo>>(); chooser_that_is_usually_null_ = - base::MakeUnique<NiceMock<MockAndroidVideoSurfaceChooser>>(); + std::make_unique<NiceMock<MockAndroidVideoSurfaceChooser>>(); chooser_ = chooser_that_is_usually_null_.get(); feature_info_ = new gpu::gles2::FeatureInfo(); @@ -156,7 +155,7 @@ // Have the factory provide an overlay, and verify that codec creation is // provided with that overlay. std::unique_ptr<MockAndroidOverlay> overlay = - base::MakeUnique<MockAndroidOverlay>(); + std::make_unique<MockAndroidOverlay>(); overlay_callbacks_ = overlay->GetCallbacks(); // Set the expectations first, since ProvideOverlay might cause callbacks. @@ -436,7 +435,7 @@ SetHasUnrenderedPictureBuffers(true); EXPECT_CALL(*codec_allocator_->most_recent_codec, SetSurface(_)).Times(0); std::unique_ptr<MockAndroidOverlay> overlay = - base::MakeUnique<MockAndroidOverlay>(); + std::make_unique<MockAndroidOverlay>(); // Make sure that the overlay is not destroyed too soon. std::unique_ptr<DestructionObserver> observer = overlay->CreateDestructionObserver();
diff --git a/media/gpu/android/android_video_surface_chooser_impl.cc b/media/gpu/android/android_video_surface_chooser_impl.cc index 135ff51..2ff375a 100644 --- a/media/gpu/android/android_video_surface_chooser_impl.cc +++ b/media/gpu/android/android_video_surface_chooser_impl.cc
@@ -4,7 +4,8 @@ #include "media/gpu/android/android_video_surface_chooser_impl.h" -#include "base/memory/ptr_util.h" +#include <memory> + #include "base/time/default_tick_clock.h" namespace media { @@ -22,7 +23,7 @@ weak_factory_(this) { // Use a DefaultTickClock if one wasn't provided. if (!tick_clock_) { - optional_tick_clock_ = base::MakeUnique<base::DefaultTickClock>(); + optional_tick_clock_ = std::make_unique<base::DefaultTickClock>(); tick_clock_ = optional_tick_clock_.get(); } }
diff --git a/media/gpu/android/android_video_surface_chooser_impl_unittest.cc b/media/gpu/android/android_video_surface_chooser_impl_unittest.cc index 24045f10..76e760d 100644 --- a/media/gpu/android/android_video_surface_chooser_impl_unittest.cc +++ b/media/gpu/android/android_video_surface_chooser_impl_unittest.cc
@@ -10,7 +10,6 @@ #include "base/bind.h" #include "base/logging.h" -#include "base/memory/ptr_util.h" #include "base/test/simple_test_tick_clock.h" #include "media/base/android/mock_android_overlay.h" #include "testing/gmock/include/gmock/gmock.h" @@ -99,7 +98,7 @@ ~AndroidVideoSurfaceChooserImplTest() override {} void SetUp() override { - overlay_ = base::MakeUnique<MockAndroidOverlay>(); + overlay_ = std::make_unique<MockAndroidOverlay>(); // Advance the clock just so we're not at 0. tick_clock_.Advance(base::TimeDelta::FromSeconds(10)); @@ -126,7 +125,7 @@ // Start the chooser, providing |factory| as the initial factory. void StartChooser(AndroidOverlayFactoryCB factory) { - chooser_ = base::MakeUnique<AndroidVideoSurfaceChooserImpl>(allow_dynamic_, + chooser_ = std::make_unique<AndroidVideoSurfaceChooserImpl>(allow_dynamic_, &tick_clock_); chooser_->SetClientCallbacks( base::Bind(&MockClient::UseOverlayImpl, base::Unretained(&client_)),
diff --git a/media/gpu/android/avda_codec_allocator.cc b/media/gpu/android/avda_codec_allocator.cc index f724da7a..8113140 100644 --- a/media/gpu/android/avda_codec_allocator.cc +++ b/media/gpu/android/avda_codec_allocator.cc
@@ -291,7 +291,7 @@ FROM_HERE, base::BindOnce(&AVDACodecAllocator::ForwardOrDropCodecOnClientThread, base::Unretained(this), client, - base::MakeUnique<MediaCodecAndSurface>( + std::make_unique<MediaCodecAndSurface>( std::move(media_codec), std::move(surface_bundle)))); }
diff --git a/media/gpu/android/avda_codec_allocator_unittest.cc b/media/gpu/android/avda_codec_allocator_unittest.cc index 6e7fe85..2de118a 100644 --- a/media/gpu/android/avda_codec_allocator_unittest.cc +++ b/media/gpu/android/avda_codec_allocator_unittest.cc
@@ -167,7 +167,7 @@ // Create a SurfaceBundle that provides an overlay. It will provide a null // java ref if requested. std::unique_ptr<MockAndroidOverlay> overlay = - base::MakeUnique<NiceMock<MockAndroidOverlay>>(); + std::make_unique<NiceMock<MockAndroidOverlay>>(); scoped_refptr<CodecConfig> codec_config(new CodecConfig); ON_CALL(*overlay, GetJavaSurface()) .WillByDefault(ReturnRef(null_java_ref_));
diff --git a/media/gpu/android/codec_image_group_unittest.cc b/media/gpu/android/codec_image_group_unittest.cc index e0f632d..cd568d1 100644 --- a/media/gpu/android/codec_image_group_unittest.cc +++ b/media/gpu/android/codec_image_group_unittest.cc
@@ -77,7 +77,7 @@ // Create an image group for a surface bundle with an overlay. Record CreateImageGroup() { std::unique_ptr<MockAndroidOverlay> overlay = - base::MakeUnique<MockAndroidOverlay>(); + std::make_unique<MockAndroidOverlay>(); EXPECT_CALL(*overlay.get(), MockAddSurfaceDestroyedCallback()); Record rec; rec.surface_bundle =
diff --git a/media/gpu/android/codec_image_unittest.cc b/media/gpu/android/codec_image_unittest.cc index b955398..b8c12df9 100644 --- a/media/gpu/android/codec_image_unittest.cc +++ b/media/gpu/android/codec_image_unittest.cc
@@ -2,10 +2,11 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. +#include <memory> + #include "media/gpu/android/codec_image.h" #include "base/bind.h" #include "base/logging.h" -#include "base/memory/ptr_util.h" #include "base/test/mock_callback.h" #include "base/test/scoped_task_environment.h" #include "gpu/command_buffer/service/texture_manager.h" @@ -38,9 +39,9 @@ CodecImageTest() = default; void SetUp() override { - auto codec = base::MakeUnique<NiceMock<MockMediaCodecBridge>>(); + auto codec = std::make_unique<NiceMock<MockMediaCodecBridge>>(); codec_ = codec.get(); - wrapper_ = base::MakeUnique<CodecWrapper>( + wrapper_ = std::make_unique<CodecWrapper>( CodecSurfacePair(std::move(codec), new AVDASurfaceBundle()), base::Bind(&base::DoNothing)); ON_CALL(*codec_, DequeueOutputBuffer(_, _, _, _, _, _, _))
diff --git a/media/gpu/android/codec_wrapper_unittest.cc b/media/gpu/android/codec_wrapper_unittest.cc index a5a1ec8..7ed54f3 100644 --- a/media/gpu/android/codec_wrapper_unittest.cc +++ b/media/gpu/android/codec_wrapper_unittest.cc
@@ -2,10 +2,11 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. +#include <memory> + #include "media/gpu/android/codec_wrapper.h" #include "base/bind.h" #include "base/logging.h" -#include "base/memory/ptr_util.h" #include "base/memory/ref_counted.h" #include "base/message_loop/message_loop.h" #include "base/test/mock_callback.h" @@ -29,10 +30,10 @@ class CodecWrapperTest : public testing::Test { public: CodecWrapperTest() { - auto codec = base::MakeUnique<NiceMock<MockMediaCodecBridge>>(); + auto codec = std::make_unique<NiceMock<MockMediaCodecBridge>>(); codec_ = codec.get(); surface_bundle_ = base::MakeRefCounted<AVDASurfaceBundle>(); - wrapper_ = base::MakeUnique<CodecWrapper>( + wrapper_ = std::make_unique<CodecWrapper>( CodecSurfacePair(std::move(codec), surface_bundle_), output_buffer_release_cb_.Get()); ON_CALL(*codec_, DequeueOutputBuffer(_, _, _, _, _, _, _))
diff --git a/media/gpu/android/content_video_view_overlay.cc b/media/gpu/android/content_video_view_overlay.cc index 76d0a16..626075f 100644 --- a/media/gpu/android/content_video_view_overlay.cc +++ b/media/gpu/android/content_video_view_overlay.cc
@@ -4,9 +4,10 @@ #include "media/gpu/android/content_video_view_overlay.h" +#include <memory> + #include "base/bind.h" #include "base/logging.h" -#include "base/memory/ptr_util.h" #include "base/threading/thread_task_runner_handle.h" #include "gpu/ipc/common/gpu_surface_lookup.h" @@ -16,7 +17,7 @@ std::unique_ptr<AndroidOverlay> ContentVideoViewOverlay::Create( int surface_id, AndroidOverlayConfig config) { - return base::MakeUnique<ContentVideoViewOverlay>(surface_id, + return std::make_unique<ContentVideoViewOverlay>(surface_id, std::move(config)); }
diff --git a/media/gpu/android/fake_codec_allocator.cc b/media/gpu/android/fake_codec_allocator.cc index 3cdf0c39..1c9f5d5 100644 --- a/media/gpu/android/fake_codec_allocator.cc +++ b/media/gpu/android/fake_codec_allocator.cc
@@ -6,7 +6,6 @@ #include <memory> -#include "base/memory/ptr_util.h" #include "base/memory/weak_ptr.h" #include "media/base/android/mock_media_codec_bridge.h" #include "media/gpu/android/avda_codec_allocator.h" @@ -35,7 +34,7 @@ std::unique_ptr<MockMediaCodecBridge> codec; if (allow_sync_creation) { - codec = base::MakeUnique<MockMediaCodecBridge>(); + codec = std::make_unique<MockMediaCodecBridge>(); most_recent_codec = codec.get(); most_recent_codec_destruction_observer = codec->CreateDestructionObserver(); most_recent_codec_destruction_observer->DoNotAllowDestruction(); @@ -77,7 +76,7 @@ return nullptr; auto mock_codec = codec ? std::move(codec) - : base::MakeUnique<NiceMock<MockMediaCodecBridge>>(); + : std::make_unique<NiceMock<MockMediaCodecBridge>>(); auto* raw_codec = mock_codec.get(); most_recent_codec = raw_codec; most_recent_codec_destruction_observer = @@ -101,7 +100,7 @@ most_recent_surface_texture = config->surface_bundle->surface_texture.get(); most_recent_config->media_crypto = config->media_crypto - ? base::MakeUnique<base::android::ScopedJavaGlobalRef<jobject>>( + ? std::make_unique<base::android::ScopedJavaGlobalRef<jobject>>( *config->media_crypto) : nullptr; most_recent_config->requires_secure_codec = config->requires_secure_codec;
diff --git a/media/gpu/android/media_codec_video_decoder.cc b/media/gpu/android/media_codec_video_decoder.cc index e0670c8..002d4fd 100644 --- a/media/gpu/android/media_codec_video_decoder.cc +++ b/media/gpu/android/media_codec_video_decoder.cc
@@ -4,11 +4,12 @@ #include "media/gpu/android/media_codec_video_decoder.h" +#include <memory> + #include "base/callback.h" #include "base/callback_helpers.h" #include "base/command_line.h" #include "base/logging.h" -#include "base/memory/ptr_util.h" #include "base/memory/weak_ptr.h" #include "base/metrics/histogram_macros.h" #include "media/base/android/media_codec_bridge_impl.h" @@ -393,7 +394,7 @@ config->requires_secure_codec = requires_secure_codec_; // TODO(liberato): per android_util.h, remove JavaObjectPtr. config->media_crypto = - base::MakeUnique<base::android::ScopedJavaGlobalRef<jobject>>( + std::make_unique<base::android::ScopedJavaGlobalRef<jobject>>( media_crypto_); config->initial_expected_coded_size = decoder_config_.coded_size(); config->surface_bundle = target_surface_bundle_; @@ -414,7 +415,7 @@ EnterTerminalState(State::kError); return; } - codec_ = base::MakeUnique<CodecWrapper>( + codec_ = std::make_unique<CodecWrapper>( CodecSurfacePair(std::move(codec), std::move(surface_bundle)), BindToCurrentLoop(base::Bind(&MediaCodecVideoDecoder::StartTimer, weak_factory_.GetWeakPtr())));
diff --git a/media/gpu/android/media_codec_video_decoder_unittest.cc b/media/gpu/android/media_codec_video_decoder_unittest.cc index 372d482..303e311 100644 --- a/media/gpu/android/media_codec_video_decoder_unittest.cc +++ b/media/gpu/android/media_codec_video_decoder_unittest.cc
@@ -105,9 +105,9 @@ void SetUp() override { uint8_t data = 0; fake_decoder_buffer_ = DecoderBuffer::CopyFrom(&data, 1); - codec_allocator_ = base::MakeUnique<FakeCodecAllocator>( + codec_allocator_ = std::make_unique<FakeCodecAllocator>( base::ThreadTaskRunnerHandle::Get()); - device_info_ = base::MakeUnique<NiceMock<MockDeviceInfo>>(); + device_info_ = std::make_unique<NiceMock<MockDeviceInfo>>(); } void TearDown() override { @@ -118,7 +118,7 @@ void CreateMcvd() { auto surface_chooser = - base::MakeUnique<NiceMock<MockAndroidVideoSurfaceChooser>>(); + std::make_unique<NiceMock<MockAndroidVideoSurfaceChooser>>(); surface_chooser_ = surface_chooser.get(); auto surface_texture = @@ -127,7 +127,7 @@ surface_texture_ = surface_texture.get(); auto video_frame_factory = - base::MakeUnique<NiceMock<MockVideoFrameFactory>>(); + std::make_unique<NiceMock<MockVideoFrameFactory>>(); video_frame_factory_ = video_frame_factory.get(); // Set up VFF to pass |surface_texture_| via its InitCb. const bool want_promotion_hint = @@ -150,7 +150,7 @@ } void CreateCdm(bool require_secure_video_decoder) { - cdm_ = base::MakeUnique<MockMediaDrmBridgeCdmContext>(cdm_id_); + cdm_ = std::make_unique<MockMediaDrmBridgeCdmContext>(cdm_id_); require_secure_video_decoder_ = require_secure_video_decoder; // We need to send an object as the media crypto, but MCVD shouldn't @@ -177,7 +177,7 @@ // for the media crypto object. // TODO(liberato): why does CreateJavaObjectPtr() not link? cdm_->media_crypto_ready_cb.Run( - base::MakeUnique<base::android::ScopedJavaGlobalRef<jobject>>( + std::make_unique<base::android::ScopedJavaGlobalRef<jobject>>( media_crypto_), require_secure_video_decoder_); base::RunLoop().RunUntilIdle(); @@ -195,7 +195,7 @@ OverlayInfo info; info.routing_token = base::UnguessableToken::Deserialize(1, 2); provide_overlay_info_cb_.Run(info); - auto overlay_ptr = base::MakeUnique<MockAndroidOverlay>(); + auto overlay_ptr = std::make_unique<MockAndroidOverlay>(); auto* overlay = overlay_ptr.get(); surface_chooser_->ProvideOverlay(std::move(overlay_ptr)); return overlay; @@ -435,7 +435,7 @@ TEST_F(MediaCodecVideoDecoderTest, SurfaceChangedWhileCodecCreationPending) { auto* overlay = InitializeWithOverlay_OneDecodePending(); overlay->OnSurfaceDestroyed(); - auto codec = base::MakeUnique<NiceMock<MockMediaCodecBridge>>(); + auto codec = std::make_unique<NiceMock<MockMediaCodecBridge>>(); // SetSurface() is called as soon as the codec is created to switch away from // the destroyed surface. @@ -501,7 +501,7 @@ // Set a pending transition to an overlay, and then back to a surface texture. // They should cancel each other out and leave the codec as-is. EXPECT_CALL(*codec, SetSurface(_)).Times(0); - auto overlay = base::MakeUnique<MockAndroidOverlay>(); + auto overlay = std::make_unique<MockAndroidOverlay>(); auto observer = overlay->CreateDestructionObserver(); surface_chooser_->ProvideOverlay(std::move(overlay));
diff --git a/media/gpu/android/promotion_hint_aggregator_impl.cc b/media/gpu/android/promotion_hint_aggregator_impl.cc index ec5ab788..d36a5aa 100644 --- a/media/gpu/android/promotion_hint_aggregator_impl.cc +++ b/media/gpu/android/promotion_hint_aggregator_impl.cc
@@ -4,8 +4,9 @@ #include "media/gpu/android/promotion_hint_aggregator_impl.h" +#include <memory> + #include "base/bind.h" -#include "base/memory/ptr_util.h" #include "base/time/default_tick_clock.h" namespace media { @@ -30,7 +31,7 @@ base::TickClock* tick_clock) : weak_ptr_factory_(this) { if (!tick_clock) { - clock_we_own_ = base::MakeUnique<base::DefaultTickClock>(); + clock_we_own_ = std::make_unique<base::DefaultTickClock>(); tick_clock = clock_we_own_.get(); }
diff --git a/media/gpu/android/promotion_hint_aggregator_impl_unittest.cc b/media/gpu/android/promotion_hint_aggregator_impl_unittest.cc index da7e333..113b1c9 100644 --- a/media/gpu/android/promotion_hint_aggregator_impl_unittest.cc +++ b/media/gpu/android/promotion_hint_aggregator_impl_unittest.cc
@@ -10,7 +10,6 @@ #include "base/bind.h" #include "base/logging.h" -#include "base/memory/ptr_util.h" #include "base/test/simple_test_tick_clock.h" #include "testing/gtest/include/gtest/gtest.h" @@ -31,7 +30,7 @@ void SetUp() override { // Advance the clock so that time 0 isn't recent. tick_clock_.Advance(TimeDelta::FromSeconds(10000)); - impl_ = base::MakeUnique<PromotionHintAggregatorImpl>(&tick_clock_); + impl_ = std::make_unique<PromotionHintAggregatorImpl>(&tick_clock_); } void TearDown() override {}
diff --git a/media/gpu/android/surface_chooser_helper.cc b/media/gpu/android/surface_chooser_helper.cc index 489c5479..50211a9a 100644 --- a/media/gpu/android/surface_chooser_helper.cc +++ b/media/gpu/android/surface_chooser_helper.cc
@@ -4,7 +4,8 @@ #include "media/gpu/android/surface_chooser_helper.h" -#include "base/memory/ptr_util.h" +#include <memory> + #include "base/time/default_tick_clock.h" #include "base/time/tick_clock.h" #include "media/gpu/android/android_video_surface_chooser.h" @@ -39,9 +40,9 @@ promotion_hint_aggregator_( promotion_hint_aggregator ? std::move(promotion_hint_aggregator) - : base::MakeUnique<PromotionHintAggregatorImpl>()), + : std::make_unique<PromotionHintAggregatorImpl>()), tick_clock_(tick_clock ? std::move(tick_clock) - : base::MakeUnique<base::DefaultTickClock>()) { + : std::make_unique<base::DefaultTickClock>()) { surface_chooser_state_.is_required = is_overlay_required_; surface_chooser_state_.promote_aggressively = promote_aggressively; }
diff --git a/media/gpu/android/surface_chooser_helper_unittest.cc b/media/gpu/android/surface_chooser_helper_unittest.cc index 5c69b8c2..e88e86c 100644 --- a/media/gpu/android/surface_chooser_helper_unittest.cc +++ b/media/gpu/android/surface_chooser_helper_unittest.cc
@@ -10,7 +10,6 @@ #include "base/bind.h" #include "base/logging.h" -#include "base/memory/ptr_util.h" #include "base/test/simple_test_tick_clock.h" #include "media/gpu/android/mock_android_video_surface_chooser.h" #include "media/gpu/android/mock_promotion_hint_aggregator.h" @@ -37,17 +36,17 @@ void ReplaceHelper(bool is_overlay_required, bool promote_aggressively) { // Advance the clock so that time 0 isn't recent. std::unique_ptr<base::SimpleTestTickClock> tick_clock = - base::MakeUnique<base::SimpleTestTickClock>(); + std::make_unique<base::SimpleTestTickClock>(); tick_clock_ = tick_clock.get(); tick_clock_->Advance(TimeDelta::FromSeconds(10000)); std::unique_ptr<MockAndroidVideoSurfaceChooser> chooser = - base::MakeUnique<MockAndroidVideoSurfaceChooser>(); + std::make_unique<MockAndroidVideoSurfaceChooser>(); chooser_ = chooser.get(); std::unique_ptr<MockPromotionHintAggregator> aggregator = - base::MakeUnique<MockPromotionHintAggregator>(); + std::make_unique<MockPromotionHintAggregator>(); aggregator_ = aggregator.get(); - helper_ = base::MakeUnique<SurfaceChooserHelper>( + helper_ = std::make_unique<SurfaceChooserHelper>( std::move(chooser), is_overlay_required, promote_aggressively, std::move(aggregator), std::move(tick_clock)); }
diff --git a/media/gpu/android/video_frame_factory_impl.cc b/media/gpu/android/video_frame_factory_impl.cc index 165037be4..333ff118 100644 --- a/media/gpu/android/video_frame_factory_impl.cc +++ b/media/gpu/android/video_frame_factory_impl.cc
@@ -50,7 +50,7 @@ InitCb init_cb) { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); DCHECK(!gpu_video_frame_factory_); - gpu_video_frame_factory_ = base::MakeUnique<GpuVideoFrameFactory>(); + gpu_video_frame_factory_ = std::make_unique<GpuVideoFrameFactory>(); base::PostTaskAndReplyWithResult( gpu_task_runner_.get(), FROM_HERE, base::Bind(&GpuVideoFrameFactory::Initialize,
diff --git a/media/gpu/android/video_frame_factory_impl_unittest.cc b/media/gpu/android/video_frame_factory_impl_unittest.cc index 73ba53f..9125ae4 100644 --- a/media/gpu/android/video_frame_factory_impl_unittest.cc +++ b/media/gpu/android/video_frame_factory_impl_unittest.cc
@@ -54,7 +54,7 @@ void AddImage(ImageKind kind, Phase phase, Expectation expectation) { owned_images_.push_back( - base::MakeUnique<NiceMock<MockImage>>(kind, phase, expectation)); + std::make_unique<NiceMock<MockImage>>(kind, phase, expectation)); images_.push_back(owned_images_.back().get()); }
diff --git a/media/gpu/gles2_decoder_helper.cc b/media/gpu/gles2_decoder_helper.cc index 10b86f90..6c376ff 100644 --- a/media/gpu/gles2_decoder_helper.cc +++ b/media/gpu/gles2_decoder_helper.cc
@@ -4,8 +4,9 @@ #include "media/gpu/gles2_decoder_helper.h" +#include <memory> + #include "base/macros.h" -#include "base/memory/ptr_util.h" #include "base/threading/thread_checker.h" #include "gpu/command_buffer/common/mailbox.h" #include "gpu/command_buffer/service/context_group.h" @@ -118,7 +119,7 @@ gpu::DecoderContext* decoder) { if (!decoder) return nullptr; - return base::MakeUnique<GLES2DecoderHelperImpl>(decoder); + return std::make_unique<GLES2DecoderHelperImpl>(decoder); } } // namespace media
diff --git a/media/gpu/gpu_jpeg_decode_accelerator_factory.cc b/media/gpu/gpu_jpeg_decode_accelerator_factory.cc index a82a2e0..55265ac 100644 --- a/media/gpu/gpu_jpeg_decode_accelerator_factory.cc +++ b/media/gpu/gpu_jpeg_decode_accelerator_factory.cc
@@ -45,14 +45,14 @@ #if BUILDFLAG(USE_VAAPI) std::unique_ptr<JpegDecodeAccelerator> CreateVaapiJDA( scoped_refptr<base::SingleThreadTaskRunner> io_task_runner) { - return base::MakeUnique<VaapiJpegDecodeAccelerator>( + return std::make_unique<VaapiJpegDecodeAccelerator>( std::move(io_task_runner)); } #endif std::unique_ptr<JpegDecodeAccelerator> CreateFakeJDA( scoped_refptr<base::SingleThreadTaskRunner> io_task_runner) { - return base::MakeUnique<FakeJpegDecodeAccelerator>(std::move(io_task_runner)); + return std::make_unique<FakeJpegDecodeAccelerator>(std::move(io_task_runner)); } } // namespace
diff --git a/media/gpu/gpu_video_decode_accelerator_factory.cc b/media/gpu/gpu_video_decode_accelerator_factory.cc index 2e72cb5..0a84cf39 100644 --- a/media/gpu/gpu_video_decode_accelerator_factory.cc +++ b/media/gpu/gpu_video_decode_accelerator_factory.cc
@@ -4,6 +4,8 @@ #include "media/gpu/gpu_video_decode_accelerator_factory.h" +#include <memory> + #include "base/memory/ptr_util.h" #include "base/threading/thread_task_runner_handle.h" #include "build/build_config.h" @@ -240,7 +242,7 @@ std::unique_ptr<VideoDecodeAccelerator> decoder; decoder.reset(new AndroidVideoDecodeAccelerator( AVDACodecAllocator::GetInstance(base::ThreadTaskRunnerHandle::Get()), - base::MakeUnique<AndroidVideoSurfaceChooserImpl>( + std::make_unique<AndroidVideoSurfaceChooserImpl>( DeviceInfo::GetInstance()->IsSetOutputSurfaceSupported()), make_context_current_cb_, get_context_group_cb_, overlay_factory_cb_, DeviceInfo::GetInstance()));
diff --git a/media/gpu/jpeg_decode_accelerator_unittest.cc b/media/gpu/jpeg_decode_accelerator_unittest.cc index 4fe70a3..d50e610 100644 --- a/media/gpu/jpeg_decode_accelerator_unittest.cc +++ b/media/gpu/jpeg_decode_accelerator_unittest.cc
@@ -18,7 +18,6 @@ #include "base/files/file_util.h" #include "base/logging.h" #include "base/macros.h" -#include "base/memory/ptr_util.h" #include "base/path_service.h" #include "base/strings/string_piece.h" #include "base/strings/string_split.h" @@ -405,7 +404,7 @@ base::TRIM_WHITESPACE, base::SPLIT_WANT_ALL); for (const auto& filename : filenames) { base::FilePath input_file = GetOriginalOrTestDataFilePath(filename); - auto image_data = base::MakeUnique<TestImageFile>(filename); + auto image_data = std::make_unique<TestImageFile>(filename); ASSERT_NO_FATAL_FAILURE(ReadTestJpegImage(input_file, image_data.get())); image_data_user_.push_back(std::move(image_data)); } @@ -492,8 +491,8 @@ std::vector<std::unique_ptr<JpegClient>> clients; for (size_t i = 0; i < num_concurrent_decoders; i++) { - notes.push_back(base::MakeUnique<ClientStateNotification<ClientState>>()); - clients.push_back(base::MakeUnique<JpegClient>(test_image_files_, + notes.push_back(std::make_unique<ClientStateNotification<ClientState>>()); + clients.push_back(std::make_unique<JpegClient>(test_image_files_, notes.back().get(), false)); decoder_thread.task_runner()->PostTask( FROM_HERE, base::Bind(&JpegClient::CreateJpegDecoder, @@ -529,9 +528,9 @@ ASSERT_TRUE(decoder_thread.Start()); std::unique_ptr<ClientStateNotification<ClientState>> note = - base::MakeUnique<ClientStateNotification<ClientState>>(); + std::make_unique<ClientStateNotification<ClientState>>(); std::unique_ptr<JpegClient> client = - base::MakeUnique<JpegClient>(test_image_files_, note.get(), true); + std::make_unique<JpegClient>(test_image_files_, note.get(), true); decoder_thread.task_runner()->PostTask( FROM_HERE, base::Bind(&JpegClient::CreateJpegDecoder, @@ -558,9 +557,9 @@ LOG_ASSERT(test_image_files_.size() == 1); std::unique_ptr<ClientStateNotification<ClientState>> note = - base::MakeUnique<ClientStateNotification<ClientState>>(); + std::make_unique<ClientStateNotification<ClientState>>(); std::unique_ptr<JpegClient> client = - base::MakeUnique<JpegClient>(test_image_files_, note.get(), true); + std::make_unique<JpegClient>(test_image_files_, note.get(), true); const int32_t bitstream_buffer_id = 0; client->PrepareMemory(bitstream_buffer_id);
diff --git a/media/gpu/vaapi/vaapi_video_decode_accelerator.cc b/media/gpu/vaapi/vaapi_video_decode_accelerator.cc index d56746ad1..459a8973 100644 --- a/media/gpu/vaapi/vaapi_video_decode_accelerator.cc +++ b/media/gpu/vaapi/vaapi_video_decode_accelerator.cc
@@ -494,7 +494,7 @@ if (bitstream_buffer.size() == 0) { DCHECK(!base::SharedMemory::IsHandleValid(bitstream_buffer.handle())); // Dummy buffer for flush. - auto flush_buffer = base::MakeUnique<InputBuffer>(); + auto flush_buffer = std::make_unique<InputBuffer>(); DCHECK(flush_buffer->IsFlushRequest()); input_buffers_.push(std::move(flush_buffer)); } else { @@ -503,7 +503,7 @@ RETURN_AND_NOTIFY_ON_FAILURE(shm->Map(), "Failed to map input buffer", UNREADABLE_INPUT, ); - auto input_buffer = base::MakeUnique<InputBuffer>( + auto input_buffer = std::make_unique<InputBuffer>( bitstream_buffer.id(), std::move(shm), BindToCurrentLoop( base::Bind(&Client::NotifyEndOfBitstreamBuffer, client_)));
diff --git a/media/gpu/video_decode_accelerator_unittest.cc b/media/gpu/video_decode_accelerator_unittest.cc index cb85b791..3b8e9660 100644 --- a/media/gpu/video_decode_accelerator_unittest.cc +++ b/media/gpu/video_decode_accelerator_unittest.cc
@@ -36,7 +36,6 @@ #include "base/location.h" #include "base/macros.h" #include "base/md5.h" -#include "base/memory/ptr_util.h" #include "base/message_loop/message_loop.h" #include "base/process/process_handle.h" #include "base/run_loop.h" @@ -1202,7 +1201,7 @@ LOG_ASSERT(fields.size() >= 1U) << entries[index]; LOG_ASSERT(fields.size() <= 8U) << entries[index]; std::unique_ptr<TestVideoFile> video_file = - base::MakeUnique<TestVideoFile>(fields[0]); + std::make_unique<TestVideoFile>(fields[0]); if (!fields[1].empty()) LOG_ASSERT(base::StringToInt(fields[1], &video_file->width)); if (!fields[2].empty()) @@ -1383,7 +1382,7 @@ TestVideoFile* video_file = test_video_files_[index % test_video_files_.size()].get(); std::unique_ptr<ClientStateNotification<ClientState>> note = - base::MakeUnique<ClientStateNotification<ClientState>>(); + std::make_unique<ClientStateNotification<ClientState>>(); notes_[index] = std::move(note); int delay_after_frame_num = std::numeric_limits<int>::max(); @@ -1393,7 +1392,7 @@ } std::unique_ptr<GLRenderingVDAClient> client = - base::MakeUnique<GLRenderingVDAClient>( + std::make_unique<GLRenderingVDAClient>( index, &rendering_helper_, notes_[index].get(), video_file->data_str, num_in_flight_decodes, num_play_throughs, video_file->reset_after_frame_num, delete_decoder_state, @@ -1737,8 +1736,8 @@ // Measure the median of the decode time when VDA::Decode is called 30 times per // second. TEST_F(VideoDecodeAcceleratorTest, TestDecodeTimeMedian) { - notes_.push_back(base::MakeUnique<ClientStateNotification<ClientState>>()); - clients_.push_back(base::MakeUnique<GLRenderingVDAClient>( + notes_.push_back(std::make_unique<ClientStateNotification<ClientState>>()); + clients_.push_back(std::make_unique<GLRenderingVDAClient>( 0, &rendering_helper_, notes_[0].get(), test_video_files_[0]->data_str, 1, 1, test_video_files_[0]->reset_after_frame_num, CS_RESET, test_video_files_[0]->width, test_video_files_[0]->height, @@ -1765,8 +1764,8 @@ // is not considered as a failure because the input may be unsupported or // corrupted videos. TEST_F(VideoDecodeAcceleratorTest, NoCrash) { - notes_.push_back(base::MakeUnique<ClientStateNotification<ClientState>>()); - clients_.push_back(base::MakeUnique<GLRenderingVDAClient>( + notes_.push_back(std::make_unique<ClientStateNotification<ClientState>>()); + clients_.push_back(std::make_unique<GLRenderingVDAClient>( 0, &rendering_helper_, notes_[0].get(), test_video_files_[0]->data_str, 1, 1, test_video_files_[0]->reset_after_frame_num, CS_RESET, test_video_files_[0]->width, test_video_files_[0]->height,
diff --git a/media/gpu/video_encode_accelerator_unittest.cc b/media/gpu/video_encode_accelerator_unittest.cc index fe5f1df..581d3f49 100644 --- a/media/gpu/video_encode_accelerator_unittest.cc +++ b/media/gpu/video_encode_accelerator_unittest.cc
@@ -19,7 +19,6 @@ #include "base/files/file_util.h" #include "base/macros.h" #include "base/memory/aligned_memory.h" -#include "base/memory/ptr_util.h" #include "base/memory/ref_counted.h" #include "base/memory/weak_ptr.h" #include "base/message_loop/message_loop.h" @@ -391,7 +390,7 @@ } LOG_ASSERT(fields.size() >= 4U) << data; LOG_ASSERT(fields.size() <= 9U) << data; - auto test_stream = base::MakeUnique<TestStream>(); + auto test_stream = std::make_unique<TestStream>(); test_stream->in_filename = FilePathStringTypeToString(fields[0]); int width, height; @@ -1584,7 +1583,7 @@ ASSERT_GT(output_buffer_size_, 0UL); for (unsigned int i = 0; i < kNumOutputBuffers; ++i) { - auto shm = base::MakeUnique<base::SharedMemory>(); + auto shm = std::make_unique<base::SharedMemory>(); LOG_ASSERT(shm->CreateAndMapAnonymous(output_buffer_size_)); FeedEncoderWithOutput(shm.get()); output_shms_.push_back(std::move(shm)); @@ -2071,7 +2070,7 @@ ASSERT_GT(output_size, 0UL); for (unsigned int i = 0; i < kNumOutputBuffers; ++i) { - auto shm = base::MakeUnique<base::SharedMemory>(); + auto shm = std::make_unique<base::SharedMemory>(); LOG_ASSERT(shm->CreateAndMapAnonymous(output_size)); FeedEncoderWithOutput(shm.get(), output_size); output_shms_.push_back(std::move(shm)); @@ -2270,8 +2269,8 @@ (save_to_file && !g_env->test_streams_[test_stream_index]->out_filename.empty()); - notes.push_back(base::MakeUnique<ClientStateNotification<ClientState>>()); - clients.push_back(base::MakeUnique<VEAClient>( + notes.push_back(std::make_unique<ClientStateNotification<ClientState>>()); + clients.push_back(std::make_unique<VEAClient>( g_env->test_streams_[test_stream_index].get(), notes.back().get(), encoder_save_to_file, keyframe_period, force_bitrate, test_perf, mid_stream_bitrate_switch, mid_stream_framerate_switch, verify_output,
diff --git a/media/gpu/vt_video_decode_accelerator_mac.cc b/media/gpu/vt_video_decode_accelerator_mac.cc index 09048bde..ab4ba816 100644 --- a/media/gpu/vt_video_decode_accelerator_mac.cc +++ b/media/gpu/vt_video_decode_accelerator_mac.cc
@@ -17,7 +17,6 @@ #include "base/logging.h" #include "base/mac/mac_logging.h" #include "base/macros.h" -#include "base/memory/ptr_util.h" #include "base/metrics/histogram_macros.h" #include "base/strings/stringprintf.h" #include "base/sys_byteorder.h" @@ -1036,7 +1035,7 @@ DCHECK_LE(1u, picture.service_texture_ids().size()); picture_info_map_.insert(std::make_pair( picture.id(), - base::MakeUnique<PictureInfo>(picture.client_texture_ids()[0], + std::make_unique<PictureInfo>(picture.client_texture_ids()[0], picture.service_texture_ids()[0]))); }
diff --git a/media/gpu/windows/d3d11_video_decoder.cc b/media/gpu/windows/d3d11_video_decoder.cc index 5245254..5ab7d2d 100644 --- a/media/gpu/windows/d3d11_video_decoder.cc +++ b/media/gpu/windows/d3d11_video_decoder.cc
@@ -53,7 +53,7 @@ // Note that the output callback will hop to our thread, post the video // frame, and along with a callback that will hop back to the impl thread // when it's released. - impl_ = base::MakeUnique<D3D11VideoDecoderImpl>(get_stub_cb); + impl_ = std::make_unique<D3D11VideoDecoderImpl>(get_stub_cb); impl_weak_ = impl_->GetWeakPtr(); }
diff --git a/media/midi/midi_device_android.cc b/media/midi/midi_device_android.cc index 49c60f0..01db239 100644 --- a/media/midi/midi_device_android.cc +++ b/media/midi/midi_device_android.cc
@@ -4,10 +4,10 @@ #include "media/midi/midi_device_android.h" +#include <memory> #include <string> #include "base/android/jni_string.h" -#include "base/memory/ptr_util.h" #include "jni/MidiDeviceAndroid_jni.h" #include "media/midi/midi_output_port_android.h" @@ -37,7 +37,7 @@ for (jsize i = 0; i < num_input_ports; ++i) { jobject port = env->GetObjectArrayElement(raw_input_ports.obj(), i); input_ports_.push_back( - base::MakeUnique<MidiInputPortAndroid>(env, port, delegate)); + std::make_unique<MidiInputPortAndroid>(env, port, delegate)); } ScopedJavaLocalRef<jobjectArray> raw_output_ports = @@ -45,7 +45,7 @@ jsize num_output_ports = env->GetArrayLength(raw_output_ports.obj()); for (jsize i = 0; i < num_output_ports; ++i) { jobject port = env->GetObjectArrayElement(raw_output_ports.obj(), i); - output_ports_.push_back(base::MakeUnique<MidiOutputPortAndroid>(env, port)); + output_ports_.push_back(std::make_unique<MidiOutputPortAndroid>(env, port)); } }
diff --git a/media/midi/midi_manager_alsa.cc b/media/midi/midi_manager_alsa.cc index 5bd03f8a..2f9e46d 100644 --- a/media/midi/midi_manager_alsa.cc +++ b/media/midi/midi_manager_alsa.cc
@@ -17,7 +17,6 @@ #include "base/json/json_string_value_serializer.h" #include "base/logging.h" #include "base/macros.h" -#include "base/memory/ptr_util.h" #include "base/message_loop/message_loop.h" #include "base/posix/eintr_wrapper.h" #include "base/posix/safe_strerror.h" @@ -620,7 +619,7 @@ snd_seq_client_type_t type) { ClientExit(client_id); clients_.insert( - std::make_pair(client_id, base::MakeUnique<Client>(client_name, type))); + std::make_pair(client_id, std::make_unique<Client>(client_name, type))); if (IsCardClient(type, client_id)) ++card_client_count_; } @@ -647,7 +646,7 @@ auto it = clients_.find(client_id); if (it != clients_.end()) it->second->AddPort(port_id, - base::MakeUnique<Port>(port_name, direction, midi)); + std::make_unique<Port>(port_name, direction, midi)); } void MidiManagerAlsa::AlsaSeqState::PortExit(int client_id, int port_id) { @@ -720,13 +719,13 @@ PortDirection direction = port->direction(); if (direction == PortDirection::kInput || direction == PortDirection::kDuplex) { - midi_ports->push_back(base::MakeUnique<MidiPort>( + midi_ports->push_back(std::make_unique<MidiPort>( path, id, client_id, port_id, midi_device, client->name(), port->name(), manufacturer, version, MidiPort::Type::kInput)); } if (direction == PortDirection::kOutput || direction == PortDirection::kDuplex) { - midi_ports->push_back(base::MakeUnique<MidiPort>( + midi_ports->push_back(std::make_unique<MidiPort>( path, id, client_id, port_id, midi_device, client->name(), port->name(), manufacturer, version, MidiPort::Type::kOutput)); }
diff --git a/media/midi/midi_manager_mac_unittest.cc b/media/midi/midi_manager_mac_unittest.cc index 22e87ff..d7f6385 100644 --- a/media/midi/midi_manager_mac_unittest.cc +++ b/media/midi/midi_manager_mac_unittest.cc
@@ -12,7 +12,6 @@ #include "base/logging.h" #include "base/macros.h" -#include "base/memory/ptr_util.h" #include "base/message_loop/message_loop.h" #include "base/run_loop.h" #include "base/synchronization/lock.h" @@ -114,8 +113,8 @@ class MidiManagerMacTest : public ::testing::Test { public: MidiManagerMacTest() - : service_(base::MakeUnique<MidiService>()), - message_loop_(base::MakeUnique<base::MessageLoop>()) {} + : service_(std::make_unique<MidiService>()), + message_loop_(std::make_unique<base::MessageLoop>()) {} ~MidiManagerMacTest() override { service_->Shutdown(); base::RunLoop run_loop;
diff --git a/media/midi/midi_manager_usb.cc b/media/midi/midi_manager_usb.cc index 68b0416..71f2469 100644 --- a/media/midi/midi_manager_usb.cc +++ b/media/midi/midi_manager_usb.cc
@@ -4,10 +4,10 @@ #include "media/midi/midi_manager_usb.h" +#include <memory> #include <utility> #include "base/logging.h" -#include "base/memory/ptr_util.h" #include "base/message_loop/message_loop.h" #include "base/strings/stringprintf.h" #include "media/midi/midi_service.h" @@ -180,7 +180,7 @@ base::StringPrintf("usb:port-%d-%ld", device_id, static_cast<long>(j))); if (jacks[j].direction() == UsbMidiJack::DIRECTION_OUT) { output_streams_.push_back( - base::MakeUnique<UsbMidiOutputStream>(jacks[j])); + std::make_unique<UsbMidiOutputStream>(jacks[j])); AddOutputPort(MidiPortInfo(id, manufacturer, product_name, version, PortState::OPENED)); } else {
diff --git a/media/midi/midi_manager_win.cc b/media/midi/midi_manager_win.cc index 8bd84b9..4214a0b5 100644 --- a/media/midi/midi_manager_win.cc +++ b/media/midi/midi_manager_win.cc
@@ -17,7 +17,6 @@ #include "base/bind_helpers.h" #include "base/callback.h" #include "base/logging.h" -#include "base/memory/ptr_util.h" #include "base/single_thread_task_runner.h" #include "base/strings/string16.h" #include "base/strings/stringprintf.h" @@ -366,7 +365,7 @@ continue; } ports.push_back( - base::MakeUnique<InPort>(manager, instance_id, device_id, caps)); + std::make_unique<InPort>(manager, instance_id, device_id, caps)); } return ports; } @@ -476,7 +475,7 @@ LOG(ERROR) << "midiOutGetDevCaps fails on device " << device_id; continue; } - ports.push_back(base::MakeUnique<OutPort>(device_id, caps)); + ports.push_back(std::make_unique<OutPort>(device_id, caps)); } return ports; } @@ -689,7 +688,7 @@ MidiManagerWin::MidiManagerWin(MidiService* service) : MidiManager(service), instance_id_(IssueNextInstanceId()), - port_manager_(base::MakeUnique<PortManager>()) { + port_manager_(std::make_unique<PortManager>()) { base::AutoLock lock(*GetInstanceIdLock()); CHECK_EQ(kInvalidInstanceId, g_active_instance_id);
diff --git a/media/midi/task_service.cc b/media/midi/task_service.cc index bfa4e1b..a4e4996 100644 --- a/media/midi/task_service.cc +++ b/media/midi/task_service.cc
@@ -142,7 +142,7 @@ size_t thread = runner_id - 1; if (!threads_[thread]) { - threads_[thread] = base::MakeUnique<base::Thread>( + threads_[thread] = std::make_unique<base::Thread>( base::StringPrintf("MidiService_TaskService_Thread(%zu)", runner_id)); base::Thread::Options options; #if defined(OS_WIN)
diff --git a/media/midi/task_service_unittest.cc b/media/midi/task_service_unittest.cc index 2c60323..866c5bd6 100644 --- a/media/midi/task_service_unittest.cc +++ b/media/midi/task_service_unittest.cc
@@ -9,7 +9,6 @@ #include "base/bind.h" #include "base/bind_helpers.h" #include "base/callback.h" -#include "base/memory/ptr_util.h" #include "base/memory/ref_counted.h" #include "base/run_loop.h" #include "base/synchronization/lock.h" @@ -51,7 +50,7 @@ public: TaskServiceClient(TaskService* task_service) : task_service_(task_service), - wait_task_event_(base::MakeUnique<base::WaitableEvent>( + wait_task_event_(std::make_unique<base::WaitableEvent>( base::WaitableEvent::ResetPolicy::MANUAL, base::WaitableEvent::InitialState::NOT_SIGNALED)), count_(0u) { @@ -135,7 +134,7 @@ ResetEvent(); task_runner_ = new base::TestSimpleTaskRunner(); thread_task_runner_handle_ = - base::MakeUnique<base::ThreadTaskRunnerHandle>(task_runner_); + std::make_unique<base::ThreadTaskRunnerHandle>(task_runner_); } void TearDown() override { @@ -153,7 +152,7 @@ // Tests if posted tasks without calling BindInstance() are ignored. TEST_F(MidiTaskServiceTest, RunUnauthorizedBoundTask) { std::unique_ptr<TaskServiceClient> client = - base::MakeUnique<TaskServiceClient>(task_service()); + std::make_unique<TaskServiceClient>(task_service()); client->PostBoundTask(kFirstRunner); @@ -167,7 +166,7 @@ // make the service insanity. TEST_F(MidiTaskServiceTest, BindTwice) { std::unique_ptr<TaskServiceClient> client = - base::MakeUnique<TaskServiceClient>(task_service()); + std::make_unique<TaskServiceClient>(task_service()); EXPECT_TRUE(client->Bind()); @@ -183,7 +182,7 @@ // Tests if posted static tasks can be processed correctly. TEST_F(MidiTaskServiceTest, RunStaticTask) { std::unique_ptr<TaskServiceClient> client = - base::MakeUnique<TaskServiceClient>(task_service()); + std::make_unique<TaskServiceClient>(task_service()); EXPECT_TRUE(client->Bind()); // Should be able to post a static task while an instance is bound. @@ -203,7 +202,7 @@ // Tests functionalities to run bound tasks. TEST_F(MidiTaskServiceTest, RunBoundTasks) { std::unique_ptr<TaskServiceClient> client = - base::MakeUnique<TaskServiceClient>(task_service()); + std::make_unique<TaskServiceClient>(task_service()); EXPECT_TRUE(client->Bind()); @@ -219,7 +218,7 @@ // depends on timing. client->PostBoundTask(kFirstRunner); EXPECT_TRUE(client->Unbind()); - client = base::MakeUnique<TaskServiceClient>(task_service()); + client = std::make_unique<TaskServiceClient>(task_service()); // Tests if an immediate call of another BindInstance() works correctly. EXPECT_TRUE(client->Bind()); @@ -239,7 +238,7 @@ // Tests if a blocking task does not block other task runners. TEST_F(MidiTaskServiceTest, RunBlockingTask) { std::unique_ptr<TaskServiceClient> client = - base::MakeUnique<TaskServiceClient>(task_service()); + std::make_unique<TaskServiceClient>(task_service()); EXPECT_TRUE(client->Bind()); @@ -267,7 +266,7 @@ // Tests if a bound delayed task runs correctly. TEST_F(MidiTaskServiceTest, RunBoundDelayedTask) { std::unique_ptr<TaskServiceClient> client = - base::MakeUnique<TaskServiceClient>(task_service()); + std::make_unique<TaskServiceClient>(task_service()); EXPECT_TRUE(client->Bind()); @@ -285,7 +284,7 @@ // Tests if a bound task runs on the thread that bound the instance. TEST_F(MidiTaskServiceTest, RunBoundTaskOnDefaultRunner) { std::unique_ptr<TaskServiceClient> client = - base::MakeUnique<TaskServiceClient>(task_service()); + std::make_unique<TaskServiceClient>(task_service()); EXPECT_TRUE(client->Bind());
diff --git a/media/midi/usb_midi_device_factory_android.cc b/media/midi/usb_midi_device_factory_android.cc index 517edb0..faf5cbf5 100644 --- a/media/midi/usb_midi_device_factory_android.cc +++ b/media/midi/usb_midi_device_factory_android.cc
@@ -5,10 +5,10 @@ #include "media/midi/usb_midi_device_factory_android.h" #include <stddef.h> +#include <memory> #include "base/bind.h" #include "base/containers/hash_tables.h" -#include "base/memory/ptr_util.h" #include "base/message_loop/message_loop.h" #include "base/synchronization/lock.h" #include "jni/UsbMidiDeviceFactoryAndroid_jni.h" @@ -63,7 +63,7 @@ base::android::ScopedJavaLocalRef<jobject> raw_device( env, env->GetObjectArrayElement(devices, i)); devices_to_pass.push_back( - base::MakeUnique<UsbMidiDeviceAndroid>(raw_device, delegate_)); + std::make_unique<UsbMidiDeviceAndroid>(raw_device, delegate_)); } std::move(callback_).Run(true, &devices_to_pass); @@ -75,7 +75,7 @@ const JavaParamRef<jobject>& caller, const JavaParamRef<jobject>& device) { delegate_->OnDeviceAttached( - base::MakeUnique<UsbMidiDeviceAndroid>(device, delegate_)); + std::make_unique<UsbMidiDeviceAndroid>(device, delegate_)); } // Called from the Java world.
diff --git a/media/mojo/clients/mojo_audio_decoder_unittest.cc b/media/mojo/clients/mojo_audio_decoder_unittest.cc index 0a49100..146f21ae 100644 --- a/media/mojo/clients/mojo_audio_decoder_unittest.cc +++ b/media/mojo/clients/mojo_audio_decoder_unittest.cc
@@ -6,7 +6,6 @@ #include "base/bind.h" #include "base/macros.h" -#include "base/memory/ptr_util.h" #include "base/message_loop/message_loop.h" #include "base/run_loop.h" #include "base/single_thread_task_runner.h" @@ -118,7 +117,7 @@ .WillRepeatedly(RunCallback<0>()); mojo::MakeStrongBinding( - base::MakeUnique<MojoAudioDecoderService>( + std::make_unique<MojoAudioDecoderService>( &mojo_cdm_service_context_, std::move(mock_audio_decoder)), std::move(request)); }
diff --git a/media/mojo/clients/mojo_cdm_unittest.cc b/media/mojo/clients/mojo_cdm_unittest.cc index 63c055a..47b6af4a 100644 --- a/media/mojo/clients/mojo_cdm_unittest.cc +++ b/media/mojo/clients/mojo_cdm_unittest.cc
@@ -4,9 +4,10 @@ #include <stdint.h> +#include <memory> + #include "base/bind.h" #include "base/macros.h" -#include "base/memory/ptr_util.h" #include "base/memory/ref_counted.h" #include "base/run_loop.h" #include "base/test/test_message_loop.h" @@ -77,7 +78,7 @@ MojoCdmTest() : mojo_cdm_service_( - base::MakeUnique<MojoCdmService>(&mojo_cdm_service_context_, + std::make_unique<MojoCdmService>(&mojo_cdm_service_context_, &cdm_factory_)), cdm_binding_(mojo_cdm_service_.get()) {} @@ -159,7 +160,7 @@ mojo_cdm_->SetServerCertificate( certificate, - base::MakeUnique<MockCdmPromise>(expected_result == SUCCESS)); + std::make_unique<MockCdmPromise>(expected_result == SUCCESS)); base::RunLoop().RunUntilIdle(); } @@ -188,7 +189,7 @@ // request is generated. mojo_cdm_->CreateSessionAndGenerateRequest( session_type, data_type, key_id, - base::MakeUnique<MockCdmSessionPromise>(expected_result == SUCCESS, + std::make_unique<MockCdmSessionPromise>(expected_result == SUCCESS, &created_session_id)); base::RunLoop().RunUntilIdle(); @@ -217,7 +218,7 @@ } mojo_cdm_->LoadSession(session_type, session_id, - base::MakeUnique<MockCdmSessionPromise>( + std::make_unique<MockCdmSessionPromise>( expected_result == SUCCESS, &loaded_session_id)); base::RunLoop().RunUntilIdle(); @@ -252,7 +253,7 @@ mojo_cdm_->UpdateSession( session_id, response, - base::MakeUnique<MockCdmPromise>(expected_result == SUCCESS)); + std::make_unique<MockCdmPromise>(expected_result == SUCCESS)); base::RunLoop().RunUntilIdle(); } @@ -268,7 +269,7 @@ expected_result))); } - mojo_cdm_->CloseSession(session_id, base::MakeUnique<MockCdmPromise>( + mojo_cdm_->CloseSession(session_id, std::make_unique<MockCdmPromise>( expected_result == SUCCESS)); base::RunLoop().RunUntilIdle(); } @@ -285,7 +286,7 @@ expected_result))); } - mojo_cdm_->RemoveSession(session_id, base::MakeUnique<MockCdmPromise>( + mojo_cdm_->RemoveSession(session_id, std::make_unique<MockCdmPromise>( expected_result == SUCCESS)); base::RunLoop().RunUntilIdle(); }
diff --git a/media/mojo/clients/mojo_decoder_factory.cc b/media/mojo/clients/mojo_decoder_factory.cc index 67a6e51..ae70798 100644 --- a/media/mojo/clients/mojo_decoder_factory.cc +++ b/media/mojo/clients/mojo_decoder_factory.cc
@@ -4,8 +4,9 @@ #include "media/mojo/clients/mojo_decoder_factory.h" +#include <memory> + #include "base/feature_list.h" -#include "base/memory/ptr_util.h" #include "base/single_thread_task_runner.h" #include "build/build_config.h" #include "media/base/media_switches.h" @@ -33,7 +34,7 @@ mojom::AudioDecoderPtr audio_decoder_ptr; interface_factory_->CreateAudioDecoder(mojo::MakeRequest(&audio_decoder_ptr)); - audio_decoders->push_back(base::MakeUnique<MojoAudioDecoder>( + audio_decoders->push_back(std::make_unique<MojoAudioDecoder>( task_runner, std::move(audio_decoder_ptr))); #endif } @@ -51,7 +52,7 @@ mojom::VideoDecoderPtr video_decoder_ptr; interface_factory_->CreateVideoDecoder(mojo::MakeRequest(&video_decoder_ptr)); - video_decoders->push_back(base::MakeUnique<MojoVideoDecoder>( + video_decoders->push_back(std::make_unique<MojoVideoDecoder>( task_runner, gpu_factories, media_log, std::move(video_decoder_ptr), request_overlay_info_cb)); #endif
diff --git a/media/mojo/clients/mojo_media_log_service.cc b/media/mojo/clients/mojo_media_log_service.cc index 5403543..f9f5092 100644 --- a/media/mojo/clients/mojo_media_log_service.cc +++ b/media/mojo/clients/mojo_media_log_service.cc
@@ -7,7 +7,6 @@ #include <memory> #include "base/logging.h" -#include "base/memory/ptr_util.h" #include "media/base/media_log_event.h" namespace media { @@ -27,7 +26,7 @@ // Make a copy so that we can transfer ownership to |media_log_|. std::unique_ptr<media::MediaLogEvent> modified_event = - base::MakeUnique<media::MediaLogEvent>(event); + std::make_unique<media::MediaLogEvent>(event); // |id| is player-unique per-process, but the remote side does not know the // correct value (nor would we necessarily trust it). Overwrite with the
diff --git a/media/mojo/clients/mojo_renderer_factory.cc b/media/mojo/clients/mojo_renderer_factory.cc index 2cce793..5c5fa3a 100644 --- a/media/mojo/clients/mojo_renderer_factory.cc +++ b/media/mojo/clients/mojo_renderer_factory.cc
@@ -4,7 +4,8 @@ #include "media/mojo/clients/mojo_renderer_factory.h" -#include "base/memory/ptr_util.h" +#include <memory> + #include "base/single_thread_task_runner.h" #include "media/mojo/clients/mojo_renderer.h" #include "media/mojo/interfaces/interface_factory.mojom.h" @@ -48,7 +49,7 @@ // when we do not need to create video overlays. if (!get_gpu_factories_cb_.is_null()) { overlay_factory = - base::MakeUnique<VideoOverlayFactory>(get_gpu_factories_cb_.Run()); + std::make_unique<VideoOverlayFactory>(get_gpu_factories_cb_.Run()); } return std::unique_ptr<Renderer>(
diff --git a/media/mojo/clients/mojo_video_encode_accelerator.cc b/media/mojo/clients/mojo_video_encode_accelerator.cc index 160d3b5..d1cc5e4 100644 --- a/media/mojo/clients/mojo_video_encode_accelerator.cc +++ b/media/mojo/clients/mojo_video_encode_accelerator.cc
@@ -119,7 +119,7 @@ // Get a mojom::VideoEncodeAcceleratorClient bound to a local implementation // (VideoEncodeAcceleratorClient) and send the pointer remotely. mojom::VideoEncodeAcceleratorClientPtr vea_client_ptr; - vea_client_ = base::MakeUnique<VideoEncodeAcceleratorClient>( + vea_client_ = std::make_unique<VideoEncodeAcceleratorClient>( client, mojo::MakeRequest(&vea_client_ptr)); bool result = false;
diff --git a/media/mojo/clients/mojo_video_encode_accelerator_unittest.cc b/media/mojo/clients/mojo_video_encode_accelerator_unittest.cc index 6879823..201fd2fe 100644 --- a/media/mojo/clients/mojo_video_encode_accelerator_unittest.cc +++ b/media/mojo/clients/mojo_video_encode_accelerator_unittest.cc
@@ -122,7 +122,7 @@ void SetUp() override { mojom::VideoEncodeAcceleratorPtr mojo_vea; mojo_vea_binding_ = mojo::MakeStrongBinding( - base::MakeUnique<MockMojoVideoEncodeAccelerator>(), + std::make_unique<MockMojoVideoEncodeAccelerator>(), mojo::MakeRequest(&mojo_vea)); mojo_vea_.reset(new MojoVideoEncodeAccelerator( @@ -181,7 +181,7 @@ // This test verifies the Initialize() communication prologue in isolation. TEST_F(MojoVideoEncodeAcceleratorTest, InitializeAndRequireBistreamBuffers) { std::unique_ptr<MockVideoEncodeAcceleratorClient> mock_vea_client = - base::MakeUnique<MockVideoEncodeAcceleratorClient>(); + std::make_unique<MockVideoEncodeAcceleratorClient>(); Initialize(mock_vea_client.get()); } @@ -189,7 +189,7 @@ // sharing of a single bitstream buffer and the Encode() of one frame. TEST_F(MojoVideoEncodeAcceleratorTest, EncodeOneFrame) { std::unique_ptr<MockVideoEncodeAcceleratorClient> mock_vea_client = - base::MakeUnique<MockVideoEncodeAcceleratorClient>(); + std::make_unique<MockVideoEncodeAcceleratorClient>(); Initialize(mock_vea_client.get()); const int32_t kBitstreamBufferId = 17; @@ -244,7 +244,7 @@ // FakeVEA is configured to do so. TEST_F(MojoVideoEncodeAcceleratorTest, InitializeFailure) { std::unique_ptr<MockVideoEncodeAcceleratorClient> mock_vea_client = - base::MakeUnique<MockVideoEncodeAcceleratorClient>(); + std::make_unique<MockVideoEncodeAcceleratorClient>(); const uint32_t kInitialBitrate = 100000u;
diff --git a/media/mojo/common/media_type_converters.cc b/media/mojo/common/media_type_converters.cc index e6f110b..e71d071d 100644 --- a/media/mojo/common/media_type_converters.cc +++ b/media/mojo/common/media_type_converters.cc
@@ -6,8 +6,8 @@ #include <stddef.h> #include <stdint.h> +#include <memory> -#include "base/memory/ptr_util.h" #include "base/numerics/safe_conversions.h" #include "media/base/audio_buffer.h" #include "media/base/audio_decoder_config.h" @@ -51,7 +51,7 @@ TypeConverter<std::unique_ptr<media::DecryptConfig>, media::mojom::DecryptConfigPtr>:: Convert(const media::mojom::DecryptConfigPtr& input) { - return base::MakeUnique<media::DecryptConfig>(input->key_id, input->iv, + return std::make_unique<media::DecryptConfig>(input->key_id, input->iv, input->subsamples); } @@ -176,7 +176,7 @@ TypeConverter<std::unique_ptr<media::CdmKeyInformation>, media::mojom::CdmKeyInformationPtr>:: Convert(const media::mojom::CdmKeyInformationPtr& input) { - return base::MakeUnique<media::CdmKeyInformation>( + return std::make_unique<media::CdmKeyInformation>( input->key_id, input->status, input->system_code); }
diff --git a/media/mojo/common/media_type_converters_unittest.cc b/media/mojo/common/media_type_converters_unittest.cc index 28ab886..e1d6138c 100644 --- a/media/mojo/common/media_type_converters_unittest.cc +++ b/media/mojo/common/media_type_converters_unittest.cc
@@ -7,9 +7,9 @@ #include <stddef.h> #include <stdint.h> #include <string.h> +#include <memory> #include "base/macros.h" -#include "base/memory/ptr_util.h" #include "media/base/audio_buffer.h" #include "media/base/audio_decoder_config.h" #include "media/base/decoder_buffer.h" @@ -141,7 +141,7 @@ scoped_refptr<DecoderBuffer> buffer(DecoderBuffer::CopyFrom( reinterpret_cast<const uint8_t*>(&kData), kDataSize)); buffer->set_decrypt_config( - base::MakeUnique<DecryptConfig>(kKeyId, kIv, subsamples)); + std::make_unique<DecryptConfig>(kKeyId, kIv, subsamples)); // Convert from and back. mojom::DecoderBufferPtr ptr(mojom::DecoderBuffer::From(buffer)); @@ -154,7 +154,7 @@ EXPECT_TRUE(buffer->decrypt_config()->Matches(*result->decrypt_config())); // Test empty IV. This is used for clear buffer in an encrypted stream. - buffer->set_decrypt_config(base::MakeUnique<DecryptConfig>( + buffer->set_decrypt_config(std::make_unique<DecryptConfig>( kKeyId, "", std::vector<SubsampleEntry>())); result = mojom::DecoderBuffer::From(buffer).To<scoped_refptr<DecoderBuffer>>();
diff --git a/media/mojo/common/mojo_data_pipe_read_write_unittest.cc b/media/mojo/common/mojo_data_pipe_read_write_unittest.cc index e4a2487..045a889 100644 --- a/media/mojo/common/mojo_data_pipe_read_write_unittest.cc +++ b/media/mojo/common/mojo_data_pipe_read_write_unittest.cc
@@ -9,7 +9,6 @@ #include <memory> #include "base/macros.h" -#include "base/memory/ptr_util.h" #include "base/message_loop/message_loop.h" #include "base/run_loop.h" #include "base/test/mock_callback.h" @@ -29,9 +28,9 @@ uint32_t data_pipe_capacity_bytes = kDefaultDataPipeCapacityBytes) { mojo::DataPipe data_pipe(data_pipe_capacity_bytes); - writer_ = base::MakeUnique<MojoDataPipeWriter>( + writer_ = std::make_unique<MojoDataPipeWriter>( std::move(data_pipe.producer_handle)); - reader_ = base::MakeUnique<MojoDataPipeReader>( + reader_ = std::make_unique<MojoDataPipeReader>( std::move(data_pipe.consumer_handle)); }
diff --git a/media/mojo/common/mojo_decoder_buffer_converter_unittest.cc b/media/mojo/common/mojo_decoder_buffer_converter_unittest.cc index e3b62a2..65ee8f45 100644 --- a/media/mojo/common/mojo_decoder_buffer_converter_unittest.cc +++ b/media/mojo/common/mojo_decoder_buffer_converter_unittest.cc
@@ -9,7 +9,6 @@ #include <memory> #include "base/macros.h" -#include "base/memory/ptr_util.h" #include "base/message_loop/message_loop.h" #include "base/run_loop.h" #include "base/test/mock_callback.h" @@ -34,9 +33,9 @@ uint32_t data_pipe_capacity_bytes = kDefaultDataPipeCapacityBytes) { mojo::DataPipe data_pipe(data_pipe_capacity_bytes); - writer = base::MakeUnique<MojoDecoderBufferWriter>( + writer = std::make_unique<MojoDecoderBufferWriter>( std::move(data_pipe.producer_handle)); - reader = base::MakeUnique<MojoDecoderBufferReader>( + reader = std::make_unique<MojoDecoderBufferReader>( std::move(data_pipe.consumer_handle)); } @@ -125,14 +124,14 @@ scoped_refptr<DecoderBuffer> buffer(DecoderBuffer::CopyFrom( reinterpret_cast<const uint8_t*>(&kData), kDataSize)); buffer->set_decrypt_config( - base::MakeUnique<DecryptConfig>(kKeyId, kIv, subsamples)); + std::make_unique<DecryptConfig>(kKeyId, kIv, subsamples)); { MojoDecoderBufferConverter converter; converter.ConvertAndVerify(buffer); } // Test empty IV. This is used for clear buffer in an encrypted stream. - buffer->set_decrypt_config(base::MakeUnique<DecryptConfig>( + buffer->set_decrypt_config(std::make_unique<DecryptConfig>( kKeyId, "", std::vector<SubsampleEntry>())); { MojoDecoderBufferConverter converter;
diff --git a/media/mojo/services/android_mojo_media_client.cc b/media/mojo/services/android_mojo_media_client.cc index 0baf73ef..78489cb0 100644 --- a/media/mojo/services/android_mojo_media_client.cc +++ b/media/mojo/services/android_mojo_media_client.cc
@@ -6,7 +6,8 @@ #include <utility> -#include "base/memory/ptr_util.h" +#include <memory> + #include "media/base/android/android_cdm_factory.h" #include "media/base/audio_decoder.h" #include "media/base/cdm_factory.h" @@ -26,7 +27,7 @@ DCHECK(host_interfaces); mojom::ProvisionFetcherPtr provision_fetcher_ptr; service_manager::GetInterface(host_interfaces, &provision_fetcher_ptr); - return base::MakeUnique<MojoProvisionFetcher>( + return std::make_unique<MojoProvisionFetcher>( std::move(provision_fetcher_ptr)); } @@ -35,7 +36,7 @@ DCHECK(host_interfaces); mojom::MediaDrmStoragePtr media_drm_storage_ptr; service_manager::GetInterface(host_interfaces, &media_drm_storage_ptr); - return base::MakeUnique<MojoMediaDrmStorage>( + return std::make_unique<MojoMediaDrmStorage>( std::move(media_drm_storage_ptr)); } @@ -49,7 +50,7 @@ std::unique_ptr<AudioDecoder> AndroidMojoMediaClient::CreateAudioDecoder( scoped_refptr<base::SingleThreadTaskRunner> task_runner) { - return base::MakeUnique<MediaCodecAudioDecoder>(task_runner); + return std::make_unique<MediaCodecAudioDecoder>(task_runner); } std::unique_ptr<CdmFactory> AndroidMojoMediaClient::CreateCdmFactory( @@ -60,7 +61,7 @@ return nullptr; } - return base::MakeUnique<AndroidCdmFactory>( + return std::make_unique<AndroidCdmFactory>( base::Bind(&CreateProvisionFetcher, host_interfaces), base::Bind(&CreateMediaDrmStorage, host_interfaces)); }
diff --git a/media/mojo/services/gpu_mojo_media_client.cc b/media/mojo/services/gpu_mojo_media_client.cc index d3a8d0c..dc9a33c 100644 --- a/media/mojo/services/gpu_mojo_media_client.cc +++ b/media/mojo/services/gpu_mojo_media_client.cc
@@ -47,7 +47,7 @@ service_manager::mojom::InterfaceProvider* interface_provider) { mojom::ProvisionFetcherPtr provision_fetcher_ptr; service_manager::GetInterface(interface_provider, &provision_fetcher_ptr); - return base::MakeUnique<MojoProvisionFetcher>( + return std::make_unique<MojoProvisionFetcher>( std::move(provision_fetcher_ptr)); } @@ -56,7 +56,7 @@ DCHECK(host_interfaces); mojom::MediaDrmStoragePtr media_drm_storage_ptr; service_manager::GetInterface(host_interfaces, &media_drm_storage_ptr); - return base::MakeUnique<MojoMediaDrmStorage>( + return std::make_unique<MojoMediaDrmStorage>( std::move(media_drm_storage_ptr)); } #endif // defined(OS_ANDROID) @@ -100,7 +100,7 @@ std::unique_ptr<AudioDecoder> GpuMojoMediaClient::CreateAudioDecoder( scoped_refptr<base::SingleThreadTaskRunner> task_runner) { #if defined(OS_ANDROID) - return base::MakeUnique<MediaCodecAudioDecoder>(task_runner); + return std::make_unique<MediaCodecAudioDecoder>(task_runner); #else return nullptr; #endif // defined(OS_ANDROID) @@ -115,16 +115,16 @@ auto get_stub_cb = base::Bind(&GetCommandBufferStub, media_gpu_channel_manager_, command_buffer_id->channel_token, command_buffer_id->route_id); - return base::MakeUnique<MediaCodecVideoDecoder>( + return std::make_unique<MediaCodecVideoDecoder>( gpu_preferences_, DeviceInfo::GetInstance(), AVDACodecAllocator::GetInstance(gpu_task_runner_), - base::MakeUnique<AndroidVideoSurfaceChooserImpl>( + std::make_unique<AndroidVideoSurfaceChooserImpl>( DeviceInfo::GetInstance()->IsSetOutputSurfaceSupported()), android_overlay_factory_cb_, std::move(request_overlay_info_cb), - base::MakeUnique<VideoFrameFactoryImpl>(gpu_task_runner_, + std::make_unique<VideoFrameFactoryImpl>(gpu_task_runner_, std::move(get_stub_cb))); #elif defined(OS_WIN) && BUILDFLAG(ENABLE_D3D11_VIDEO_DECODER) - return base::MakeUnique<D3D11VideoDecoder>( + return std::make_unique<D3D11VideoDecoder>( gpu_task_runner_, base::BindRepeating(&GetCommandBufferStub, media_gpu_channel_manager_, command_buffer_id->channel_token, @@ -137,7 +137,7 @@ std::unique_ptr<CdmFactory> GpuMojoMediaClient::CreateCdmFactory( service_manager::mojom::InterfaceProvider* interface_provider) { #if defined(OS_ANDROID) - return base::MakeUnique<AndroidCdmFactory>( + return std::make_unique<AndroidCdmFactory>( base::Bind(&CreateProvisionFetcher, interface_provider), base::Bind(&CreateMediaDrmStorage, interface_provider)); #else
diff --git a/media/mojo/services/interface_factory_impl.cc b/media/mojo/services/interface_factory_impl.cc index a486c05..9bf336e 100644 --- a/media/mojo/services/interface_factory_impl.cc +++ b/media/mojo/services/interface_factory_impl.cc
@@ -4,9 +4,10 @@ #include "media/mojo/services/interface_factory_impl.h" +#include <memory> #include "base/guid.h" + #include "base/logging.h" -#include "base/memory/ptr_util.h" #include "base/single_thread_task_runner.h" #include "base/threading/thread_task_runner_handle.h" #include "media/base/media_log.h" @@ -118,7 +119,7 @@ } audio_decoder_bindings_.AddBinding( - base::MakeUnique<MojoAudioDecoderService>(&cdm_service_context_, + std::make_unique<MojoAudioDecoderService>(&cdm_service_context_, std::move(audio_decoder)), std::move(request)); #endif // BUILDFLAG(ENABLE_MOJO_AUDIO_DECODER) @@ -128,7 +129,7 @@ mojom::VideoDecoderRequest request) { #if BUILDFLAG(ENABLE_MOJO_VIDEO_DECODER) video_decoder_bindings_.AddBinding( - base::MakeUnique<MojoVideoDecoderService>(mojo_media_client_, + std::make_unique<MojoVideoDecoderService>(mojo_media_client_, &cdm_service_context_), std::move(request)); #endif // BUILDFLAG(ENABLE_MOJO_VIDEO_DECODER) @@ -158,7 +159,7 @@ } std::unique_ptr<MojoRendererService> mojo_renderer_service = - base::MakeUnique<MojoRendererService>( + std::make_unique<MojoRendererService>( &cdm_service_context_, std::move(audio_sink), std::move(video_sink), std::move(renderer), MojoRendererService::InitiateSurfaceRequestCB()); @@ -185,7 +186,7 @@ return; cdm_bindings_.AddBinding( - base::MakeUnique<MojoCdmService>(&cdm_service_context_, cdm_factory), + std::make_unique<MojoCdmService>(&cdm_service_context_, cdm_factory), std::move(request)); #endif // BUILDFLAG(ENABLE_MOJO_CDM) }
diff --git a/media/mojo/services/media_metrics_provider.cc b/media/mojo/services/media_metrics_provider.cc index 65de890..0dcd745 100644 --- a/media/mojo/services/media_metrics_provider.cc +++ b/media/mojo/services/media_metrics_provider.cc
@@ -42,7 +42,7 @@ // static void MediaMetricsProvider::Create(VideoDecodePerfHistory* perf_history, mojom::MediaMetricsProviderRequest request) { - mojo::MakeStrongBinding(base::MakeUnique<MediaMetricsProvider>(perf_history), + mojo::MakeStrongBinding(std::make_unique<MediaMetricsProvider>(perf_history), std::move(request)); } @@ -73,7 +73,7 @@ return; } - mojo::MakeStrongBinding(base::MakeUnique<WatchTimeRecorder>( + mojo::MakeStrongBinding(std::make_unique<WatchTimeRecorder>( std::move(properties), untrusted_top_origin_, is_top_frame_, player_id_), std::move(request)); @@ -87,7 +87,7 @@ } mojo::MakeStrongBinding( - base::MakeUnique<VideoDecodeStatsRecorder>( + std::make_unique<VideoDecodeStatsRecorder>( untrusted_top_origin_, is_top_frame_, player_id_, perf_history_), std::move(request)); }
diff --git a/media/mojo/services/media_service_factory.cc b/media/mojo/services/media_service_factory.cc index 0584ada..be65dd05 100644 --- a/media/mojo/services/media_service_factory.cc +++ b/media/mojo/services/media_service_factory.cc
@@ -4,8 +4,9 @@ #include "media/mojo/services/media_service_factory.h" +#include <memory> + #include "base/logging.h" -#include "base/memory/ptr_util.h" #include "media/mojo/services/gpu_mojo_media_client.h" #include "media/mojo/services/media_service.h" #include "media/mojo/services/test_mojo_media_client.h" @@ -21,7 +22,7 @@ return CreateMediaServiceForTesting(); #elif defined(OS_ANDROID) return std::unique_ptr<service_manager::Service>( - new MediaService(base::MakeUnique<AndroidMojoMediaClient>())); + new MediaService(std::make_unique<AndroidMojoMediaClient>())); #else NOTREACHED() << "No MediaService implementation available."; return nullptr; @@ -35,7 +36,7 @@ AndroidOverlayMojoFactoryCB android_overlay_factory_cb, CdmProxyFactoryCB cdm_proxy_factory_cb) { return std::unique_ptr<service_manager::Service>( - new MediaService(base::MakeUnique<GpuMojoMediaClient>( + new MediaService(std::make_unique<GpuMojoMediaClient>( gpu_preferences, task_runner, media_gpu_channel_manager, std::move(android_overlay_factory_cb), std::move(cdm_proxy_factory_cb)))); @@ -43,7 +44,7 @@ std::unique_ptr<service_manager::Service> CreateMediaServiceForTesting() { return std::unique_ptr<service_manager::Service>( - new MediaService(base::MakeUnique<TestMojoMediaClient>())); + new MediaService(std::make_unique<TestMojoMediaClient>())); } } // namespace media
diff --git a/media/mojo/services/media_service_unittest.cc b/media/mojo/services/media_service_unittest.cc index e56ceb3..86ddb583 100644 --- a/media/mojo/services/media_service_unittest.cc +++ b/media/mojo/services/media_service_unittest.cc
@@ -10,7 +10,6 @@ #include "base/bind.h" #include "base/callback.h" #include "base/macros.h" -#include "base/memory/ptr_util.h" #include "base/run_loop.h" #include "build/build_config.h" #include "media/base/cdm_config.h" @@ -88,7 +87,7 @@ connector()->BindInterface(media::mojom::kMediaServiceName, &media_service); service_manager::mojom::InterfaceProviderPtr interfaces; - auto provider = base::MakeUnique<MediaInterfaceProvider>( + auto provider = std::make_unique<MediaInterfaceProvider>( mojo::MakeRequest(&interfaces)); media_service->CreateInterfaceFactory( mojo::MakeRequest(&interface_factory_), std::move(interfaces));
diff --git a/media/mojo/services/mojo_audio_input_stream_unittest.cc b/media/mojo/services/mojo_audio_input_stream_unittest.cc index 51e135a..c8e8359 100644 --- a/media/mojo/services/mojo_audio_input_stream_unittest.cc +++ b/media/mojo/services/mojo_audio_input_stream_unittest.cc
@@ -104,7 +104,7 @@ base::PlatformFile fd; mojo::UnwrapPlatformFile(std::move(socket_handle), &fd); - socket_ = base::MakeUnique<base::CancelableSyncSocket>(fd); + socket_ = std::make_unique<base::CancelableSyncSocket>(fd); EXPECT_NE(socket_->handle(), base::CancelableSyncSocket::kInvalidHandle); size_t memory_length; @@ -115,7 +115,7 @@ &memory_length, &read_only), MOJO_RESULT_OK); EXPECT_TRUE(read_only); - buffer_ = base::MakeUnique<base::SharedMemory>(shmem_handle, read_only); + buffer_ = std::make_unique<base::SharedMemory>(shmem_handle, read_only); GotNotification(initially_muted); } @@ -150,13 +150,13 @@ class MojoAudioInputStreamTest : public Test { public: MojoAudioInputStreamTest() - : foreign_socket_(base::MakeUnique<TestCancelableSyncSocket>()), + : foreign_socket_(std::make_unique<TestCancelableSyncSocket>()), client_binding_(&client_, mojo::MakeRequest(&client_ptr_)) {} AudioInputStreamPtr CreateAudioInput() { AudioInputStreamPtr p; ExpectDelegateCreation(); - impl_ = base::MakeUnique<MojoAudioInputStream>( + impl_ = std::make_unique<MojoAudioInputStream>( mojo::MakeRequest(&p), std::move(client_ptr_), base::BindOnce(&MockDelegateFactory::CreateDelegate, base::Unretained(&mock_delegate_factory_)),
diff --git a/media/mojo/services/mojo_audio_output_stream_unittest.cc b/media/mojo/services/mojo_audio_output_stream_unittest.cc index cc69e472..7c6c358 100644 --- a/media/mojo/services/mojo_audio_output_stream_unittest.cc +++ b/media/mojo/services/mojo_audio_output_stream_unittest.cc
@@ -102,7 +102,7 @@ base::PlatformFile fd; mojo::UnwrapPlatformFile(std::move(socket_handle), &fd); - socket_ = base::MakeUnique<base::CancelableSyncSocket>(fd); + socket_ = std::make_unique<base::CancelableSyncSocket>(fd); EXPECT_NE(socket_->handle(), base::CancelableSyncSocket::kInvalidHandle); size_t memory_length; @@ -113,7 +113,7 @@ &memory_length, &read_only), MOJO_RESULT_OK); EXPECT_FALSE(read_only); - buffer_ = base::MakeUnique<base::SharedMemory>(shmem_handle, read_only); + buffer_ = std::make_unique<base::SharedMemory>(shmem_handle, read_only); GotNotification(); } @@ -143,13 +143,13 @@ class MojoAudioOutputStreamTest : public Test { public: MojoAudioOutputStreamTest() - : foreign_socket_(base::MakeUnique<TestCancelableSyncSocket>()), + : foreign_socket_(std::make_unique<TestCancelableSyncSocket>()), client_binding_(&client_, mojo::MakeRequest(&client_ptr_)) {} AudioOutputStreamPtr CreateAudioOutput() { AudioOutputStreamPtr p; ExpectDelegateCreation(); - impl_ = base::MakeUnique<MojoAudioOutputStream>( + impl_ = std::make_unique<MojoAudioOutputStream>( mojo::MakeRequest(&p), std::move(client_ptr_), base::BindOnce(&MockDelegateFactory::CreateDelegate, base::Unretained(&mock_delegate_factory_)),
diff --git a/media/mojo/services/mojo_cdm_allocator.cc b/media/mojo/services/mojo_cdm_allocator.cc index f302368..00727c0 100644 --- a/media/mojo/services/mojo_cdm_allocator.cc +++ b/media/mojo/services/mojo_cdm_allocator.cc
@@ -5,11 +5,11 @@ #include "media/mojo/services/mojo_cdm_allocator.h" #include <limits> +#include <memory> #include "base/bind.h" #include "base/callback.h" #include "base/compiler_specific.h" -#include "base/memory/ptr_util.h" #include "base/numerics/safe_conversions.h" #include "base/numerics/safe_math.h" #include "media/cdm/api/content_decryption_module.h" @@ -199,7 +199,7 @@ // Creates a new MojoCdmVideoFrame on every request. std::unique_ptr<VideoFrameImpl> MojoCdmAllocator::CreateCdmVideoFrame() { DCHECK(thread_checker_.CalledOnValidThread()); - return base::MakeUnique<MojoCdmVideoFrame>( + return std::make_unique<MojoCdmVideoFrame>( base::Bind(&MojoCdmAllocator::AddBufferToAvailableMap, weak_ptr_factory_.GetWeakPtr())); }
diff --git a/media/mojo/services/mojo_cdm_helper.cc b/media/mojo/services/mojo_cdm_helper.cc index a5abcbfc..5218ac8 100644 --- a/media/mojo/services/mojo_cdm_helper.cc +++ b/media/mojo/services/mojo_cdm_helper.cc
@@ -129,7 +129,7 @@ CdmAllocator* MojoCdmHelper::GetAllocator() { if (!allocator_) - allocator_ = base::MakeUnique<MojoCdmAllocator>(); + allocator_ = std::make_unique<MojoCdmAllocator>(); return allocator_.get(); }
diff --git a/media/mojo/services/mojo_cdm_service.cc b/media/mojo/services/mojo_cdm_service.cc index 27f57a9f..ad9599c3 100644 --- a/media/mojo/services/mojo_cdm_service.cc +++ b/media/mojo/services/mojo_cdm_service.cc
@@ -5,11 +5,11 @@ #include "media/mojo/services/mojo_cdm_service.h" #include <map> +#include <memory> #include <utility> #include "base/bind.h" #include "base/macros.h" -#include "base/memory/ptr_util.h" #include "base/synchronization/lock.h" #include "media/base/cdm_config.h" #include "media/base/cdm_context.h" @@ -81,7 +81,7 @@ DVLOG(2) << __func__; cdm_->SetServerCertificate( certificate_data, - base::MakeUnique<SimpleMojoCdmPromise>(std::move(callback))); + std::make_unique<SimpleMojoCdmPromise>(std::move(callback))); } void MojoCdmService::GetStatusForPolicy(HdcpVersion min_hdcp_version, @@ -89,7 +89,7 @@ DVLOG(2) << __func__; cdm_->GetStatusForPolicy( min_hdcp_version, - base::MakeUnique<KeyStatusMojoCdmPromise>(std::move(callback))); + std::make_unique<KeyStatusMojoCdmPromise>(std::move(callback))); } void MojoCdmService::CreateSessionAndGenerateRequest( @@ -100,7 +100,7 @@ DVLOG(2) << __func__; cdm_->CreateSessionAndGenerateRequest( session_type, init_data_type, init_data, - base::MakeUnique<NewSessionMojoCdmPromise>(std::move(callback))); + std::make_unique<NewSessionMojoCdmPromise>(std::move(callback))); } void MojoCdmService::LoadSession(CdmSessionType session_type, @@ -109,7 +109,7 @@ DVLOG(2) << __func__; cdm_->LoadSession( session_type, session_id, - base::MakeUnique<NewSessionMojoCdmPromise>(std::move(callback))); + std::make_unique<NewSessionMojoCdmPromise>(std::move(callback))); } void MojoCdmService::UpdateSession(const std::string& session_id, @@ -125,14 +125,14 @@ CloseSessionCallback callback) { DVLOG(2) << __func__; cdm_->CloseSession( - session_id, base::MakeUnique<SimpleMojoCdmPromise>(std::move(callback))); + session_id, std::make_unique<SimpleMojoCdmPromise>(std::move(callback))); } void MojoCdmService::RemoveSession(const std::string& session_id, RemoveSessionCallback callback) { DVLOG(2) << __func__; cdm_->RemoveSession( - session_id, base::MakeUnique<SimpleMojoCdmPromise>(std::move(callback))); + session_id, std::make_unique<SimpleMojoCdmPromise>(std::move(callback))); } scoped_refptr<ContentDecryptionModule> MojoCdmService::GetCdm() {
diff --git a/media/mojo/services/mojo_decryptor_service.cc b/media/mojo/services/mojo_decryptor_service.cc index 55a5704..901fadff 100644 --- a/media/mojo/services/mojo_decryptor_service.cc +++ b/media/mojo/services/mojo_decryptor_service.cc
@@ -260,7 +260,7 @@ // to it until the other side is done with the memory. mojom::FrameResourceReleaserPtr releaser; if (frame->storage_type() == VideoFrame::STORAGE_MOJO_SHARED_BUFFER) { - mojo::MakeStrongBinding(base::MakeUnique<FrameResourceReleaserImpl>(frame), + mojo::MakeStrongBinding(std::make_unique<FrameResourceReleaserImpl>(frame), mojo::MakeRequest(&releaser)); }
diff --git a/media/mojo/services/mojo_media_drm_storage.cc b/media/mojo/services/mojo_media_drm_storage.cc index 93df470..b8af9b97 100644 --- a/media/mojo/services/mojo_media_drm_storage.cc +++ b/media/mojo/services/mojo_media_drm_storage.cc
@@ -75,7 +75,7 @@ DVLOG(1) << __func__ << ": success = " << !!session_data; std::move(load_persistent_session_cb) - .Run(session_data ? base::MakeUnique<SessionData>( + .Run(session_data ? std::make_unique<SessionData>( std::move(session_data->key_set_id), std::move(session_data->mime_type)) : nullptr);
diff --git a/media/mojo/services/mojo_video_decoder_service.cc b/media/mojo/services/mojo_video_decoder_service.cc index 1d1a2ff..3ecedaf1 100644 --- a/media/mojo/services/mojo_video_decoder_service.cc +++ b/media/mojo/services/mojo_video_decoder_service.cc
@@ -126,7 +126,7 @@ mojom::MediaLogAssociatedPtr media_log_ptr; media_log_ptr.Bind(std::move(media_log)); - media_log_ = base::MakeUnique<MojoMediaLog>(std::move(media_log_ptr)); + media_log_ = std::make_unique<MojoMediaLog>(std::move(media_log_ptr)); video_frame_handle_releaser_ = mojo::MakeStrongBinding(std::make_unique<VideoFrameHandleReleaserImpl>(),
diff --git a/media/mojo/services/mojo_video_encode_accelerator_provider.cc b/media/mojo/services/mojo_video_encode_accelerator_provider.cc index 3d23adc32..f11c787 100644 --- a/media/mojo/services/mojo_video_encode_accelerator_provider.cc +++ b/media/mojo/services/mojo_video_encode_accelerator_provider.cc
@@ -21,7 +21,7 @@ const CreateAndInitializeVideoEncodeAcceleratorCallback& create_vea_callback, const gpu::GpuPreferences& gpu_preferences) { - mojo::MakeStrongBinding(base::MakeUnique<MojoVideoEncodeAcceleratorProvider>( + mojo::MakeStrongBinding(std::make_unique<MojoVideoEncodeAcceleratorProvider>( create_vea_callback, gpu_preferences), std::move(request)); }
diff --git a/media/mojo/services/mojo_video_encode_accelerator_service.cc b/media/mojo/services/mojo_video_encode_accelerator_service.cc index a1474ee..813b24f 100644 --- a/media/mojo/services/mojo_video_encode_accelerator_service.cc +++ b/media/mojo/services/mojo_video_encode_accelerator_service.cc
@@ -21,7 +21,7 @@ const CreateAndInitializeVideoEncodeAcceleratorCallback& create_vea_callback, const gpu::GpuPreferences& gpu_preferences) { - mojo::MakeStrongBinding(base::MakeUnique<MojoVideoEncodeAcceleratorService>( + mojo::MakeStrongBinding(std::make_unique<MojoVideoEncodeAcceleratorService>( create_vea_callback, gpu_preferences), std::move(request)); }
diff --git a/media/mojo/services/mojo_video_encode_accelerator_service_unittest.cc b/media/mojo/services/mojo_video_encode_accelerator_service_unittest.cc index a566391..ffdc07f 100644 --- a/media/mojo/services/mojo_video_encode_accelerator_service_unittest.cc +++ b/media/mojo/services/mojo_video_encode_accelerator_service_unittest.cc
@@ -34,7 +34,7 @@ VideoEncodeAccelerator::Client* client, const gpu::GpuPreferences& gpu_preferences) { // Use FakeVEA as scoped_ptr to guarantee proper destruction via Destroy(). - auto vea = base::MakeUnique<FakeVideoEncodeAccelerator>( + auto vea = std::make_unique<FakeVideoEncodeAccelerator>( base::ThreadTaskRunnerHandle::Get()); vea->SetWillInitializationSucceed(will_initialization_succeed); const bool result = vea->Initialize(input_format, input_visible_size, @@ -82,7 +82,7 @@ // upon initialization (by default) or not. void CreateMojoVideoEncodeAccelerator( bool will_fake_vea_initialization_succeed = true) { - mojo_vea_service_ = base::MakeUnique<MojoVideoEncodeAcceleratorService>( + mojo_vea_service_ = std::make_unique<MojoVideoEncodeAcceleratorService>( base::Bind(&CreateAndInitializeFakeVEA, will_fake_vea_initialization_succeed), gpu::GpuPreferences()); @@ -92,7 +92,7 @@ // Create an Mojo VEA Client InterfacePtr and point it to bind to our Mock. mojom::VideoEncodeAcceleratorClientPtr mojo_vea_client; mojo_vea_binding_ = mojo::MakeStrongBinding( - base::MakeUnique<MockMojoVideoEncodeAcceleratorClient>(), + std::make_unique<MockMojoVideoEncodeAcceleratorClient>(), mojo::MakeRequest(&mojo_vea_client)); EXPECT_CALL(*mock_mojo_vea_client(), @@ -204,7 +204,7 @@ mojom::VideoEncodeAcceleratorClientPtr mojo_vea_client; auto mojo_vea_binding = mojo::MakeStrongBinding( - base::MakeUnique<MockMojoVideoEncodeAcceleratorClient>(), + std::make_unique<MockMojoVideoEncodeAcceleratorClient>(), mojo::MakeRequest(&mojo_vea_client)); const uint32_t kInitialBitrate = 100000u;
diff --git a/media/mojo/services/test_mojo_media_client.cc b/media/mojo/services/test_mojo_media_client.cc index 53b2b94..d5def90 100644 --- a/media/mojo/services/test_mojo_media_client.cc +++ b/media/mojo/services/test_mojo_media_client.cc
@@ -4,7 +4,8 @@ #include "media/mojo/services/test_mojo_media_client.h" -#include "base/memory/ptr_util.h" +#include <memory> + #include "base/message_loop/message_loop.h" #include "base/run_loop.h" #include "base/threading/thread_task_runner_handle.h" @@ -43,7 +44,7 @@ AudioManager* audio_manager = AudioManager::Get(); if (!audio_manager) { audio_manager_ = media::AudioManager::CreateForTesting( - base::MakeUnique<AudioThreadImpl>()); + std::make_unique<AudioThreadImpl>()); // Flush the message loop to ensure that the audio manager is initialized. base::RunLoop().RunUntilIdle(); } @@ -56,21 +57,21 @@ std::unique_ptr<VideoRendererSink> TestMojoMediaClient::CreateVideoRendererSink( const scoped_refptr<base::SingleThreadTaskRunner>& task_runner) { - return base::MakeUnique<NullVideoSink>( + return std::make_unique<NullVideoSink>( false, base::TimeDelta::FromSecondsD(1.0 / 60), NullVideoSink::NewFrameCB(), task_runner); } std::unique_ptr<RendererFactory> TestMojoMediaClient::CreateRendererFactory( MediaLog* media_log) { - return base::MakeUnique<DefaultRendererFactory>( + return std::make_unique<DefaultRendererFactory>( media_log, nullptr, DefaultRendererFactory::GetGpuFactoriesCB()); } std::unique_ptr<CdmFactory> TestMojoMediaClient::CreateCdmFactory( service_manager::mojom::InterfaceProvider* /* host_interfaces */) { DVLOG(1) << __func__; - return base::MakeUnique<DefaultCdmFactory>(); + return std::make_unique<DefaultCdmFactory>(); } } // namespace media
diff --git a/media/mojo/test/mojo_video_encode_accelerator_integration_test.cc b/media/mojo/test/mojo_video_encode_accelerator_integration_test.cc index a739ffa4..aee2d75 100644 --- a/media/mojo/test/mojo_video_encode_accelerator_integration_test.cc +++ b/media/mojo/test/mojo_video_encode_accelerator_integration_test.cc
@@ -3,6 +3,7 @@ // found in the LICENSE file. #include <stddef.h> +#include <memory> #include "base/message_loop/message_loop.h" #include "base/run_loop.h" @@ -34,7 +35,7 @@ VideoEncodeAccelerator::Client* client, const gpu::GpuPreferences& gpu_preferences) { // Use FakeVEA as scoped_ptr to guarantee proper destruction via Destroy(). - auto vea = base::MakeUnique<FakeVideoEncodeAccelerator>( + auto vea = std::make_unique<FakeVideoEncodeAccelerator>( base::ThreadTaskRunnerHandle::Get()); const bool result = vea->Initialize(input_format, input_visible_size, output_profile, initial_bitrate, client); @@ -66,7 +67,7 @@ void SetUp() override { mojom::VideoEncodeAcceleratorPtr mojo_vea; mojo_vea_binding_ = mojo::MakeStrongBinding( - base::MakeUnique<MojoVideoEncodeAcceleratorService>( + std::make_unique<MojoVideoEncodeAcceleratorService>( base::Bind(&CreateAndInitializeFakeVEA), gpu::GpuPreferences()), mojo::MakeRequest(&mojo_vea)); @@ -122,7 +123,7 @@ TEST_F(MojoVideoEncodeAcceleratorIntegrationTest, CreateAndDestroy) {} TEST_F(MojoVideoEncodeAcceleratorIntegrationTest, Initialize) { - auto mock_vea_client = base::MakeUnique<MockVideoEncodeAcceleratorClient>(); + auto mock_vea_client = std::make_unique<MockVideoEncodeAcceleratorClient>(); Initialize(mock_vea_client.get()); // Make double sure that |kValidOutputProfile| is supported. @@ -145,7 +146,7 @@ // visible size, and NotifyError() gets pinged. TEST_F(MojoVideoEncodeAcceleratorIntegrationTest, InitializeWithInvalidDimensionsFails) { - auto mock_vea_client = base::MakeUnique<MockVideoEncodeAcceleratorClient>(); + auto mock_vea_client = std::make_unique<MockVideoEncodeAcceleratorClient>(); const gfx::Size kInvalidInputVisibleSize(limits::kMaxDimension + 1, 48); @@ -159,7 +160,7 @@ // This test is tantamount to forcing the remote Fake VEA to fail upon init. TEST_F(MojoVideoEncodeAcceleratorIntegrationTest, InitializeWithUnsupportedProfileFails) { - auto mock_vea_client = base::MakeUnique<MockVideoEncodeAcceleratorClient>(); + auto mock_vea_client = std::make_unique<MockVideoEncodeAcceleratorClient>(); const VideoCodecProfile kInvalidOutputProfile = VIDEO_CODEC_PROFILE_UNKNOWN; @@ -173,7 +174,7 @@ // the requested in RequireBitstreamBuffers() fails. TEST_F(MojoVideoEncodeAcceleratorIntegrationTest, UseOutputBitstreamBufferWithInvalidSizeFails) { - auto mock_vea_client = base::MakeUnique<MockVideoEncodeAcceleratorClient>(); + auto mock_vea_client = std::make_unique<MockVideoEncodeAcceleratorClient>(); Initialize(mock_vea_client.get()); const uint64_t kInvalidShMemSize = @@ -194,7 +195,7 @@ // buffer id fails. TEST_F(MojoVideoEncodeAcceleratorIntegrationTest, UseOutputBitstreamBufferWithInvalidIdFails) { - auto mock_vea_client = base::MakeUnique<MockVideoEncodeAcceleratorClient>(); + auto mock_vea_client = std::make_unique<MockVideoEncodeAcceleratorClient>(); Initialize(mock_vea_client.get()); const int32_t kInvalidBistreamBufferId = -18; @@ -214,7 +215,7 @@ // This test verifies the sharing of a single bitstream buffer and the Encode() // of one frame. TEST_F(MojoVideoEncodeAcceleratorIntegrationTest, EncodeOneFrame) { - auto mock_vea_client = base::MakeUnique<MockVideoEncodeAcceleratorClient>(); + auto mock_vea_client = std::make_unique<MockVideoEncodeAcceleratorClient>(); Initialize(mock_vea_client.get()); const int32_t kBistreamBufferId = 17; @@ -250,7 +251,7 @@ // different than those configured in Initialize() fails. TEST_F(MojoVideoEncodeAcceleratorIntegrationTest, EncodeWithInvalidDimensionsFails) { - auto mock_vea_client = base::MakeUnique<MockVideoEncodeAcceleratorClient>(); + auto mock_vea_client = std::make_unique<MockVideoEncodeAcceleratorClient>(); Initialize(mock_vea_client.get()); { @@ -288,7 +289,7 @@ // Tests that a RequestEncodingParametersChange() ripples through correctly. TEST_F(MojoVideoEncodeAcceleratorIntegrationTest, EncodingParametersChange) { - auto mock_vea_client = base::MakeUnique<MockVideoEncodeAcceleratorClient>(); + auto mock_vea_client = std::make_unique<MockVideoEncodeAcceleratorClient>(); Initialize(mock_vea_client.get()); const uint32_t kNewBitrate = 123123u; @@ -303,7 +304,7 @@ // this simulates the remote end of the communication going down. TEST_F(MojoVideoEncodeAcceleratorIntegrationTest, CallsAreIgnoredAfterBindingClosed) { - auto mock_vea_client = base::MakeUnique<MockVideoEncodeAcceleratorClient>(); + auto mock_vea_client = std::make_unique<MockVideoEncodeAcceleratorClient>(); Initialize(mock_vea_client.get()); {
diff --git a/media/muxers/webm_muxer.cc b/media/muxers/webm_muxer.cc index 59e68a0..bb05c845 100644 --- a/media/muxers/webm_muxer.cc +++ b/media/muxers/webm_muxer.cc
@@ -5,9 +5,9 @@ #include "media/muxers/webm_muxer.h" #include <algorithm> +#include <memory> #include "base/bind.h" -#include "base/memory/ptr_util.h" #include "media/base/audio_parameters.h" #include "media/base/limits.h" #include "media/base/video_frame.h" @@ -166,7 +166,7 @@ if (is_key_frame) // Upon Key frame reception, empty the encoded queue. encoded_frames_queue_.clear(); - encoded_frames_queue_.push_back(base::MakeUnique<EncodedVideoFrame>( + encoded_frames_queue_.push_back(std::make_unique<EncodedVideoFrame>( std::move(encoded_data), std::move(encoded_alpha), timestamp, is_key_frame)); return true; @@ -202,9 +202,9 @@ // Dump all saved encoded video frames if any. while (!encoded_frames_queue_.empty()) { const bool res = AddFrame( - base::MakeUnique<std::string>(*encoded_frames_queue_.front()->data), + std::make_unique<std::string>(*encoded_frames_queue_.front()->data), encoded_frames_queue_.front()->alpha_data - ? base::MakeUnique<std::string>( + ? std::make_unique<std::string>( *encoded_frames_queue_.front()->alpha_data) : nullptr, video_track_index_,
diff --git a/media/muxers/webm_muxer_fuzzertest.cc b/media/muxers/webm_muxer_fuzzertest.cc index 67c091f7..604761f 100644 --- a/media/muxers/webm_muxer_fuzzertest.cc +++ b/media/muxers/webm_muxer_fuzzertest.cc
@@ -5,11 +5,11 @@ #include <stddef.h> #include <stdint.h> +#include <memory> #include <random> #include "base/bind.h" #include "base/logging.h" -#include "base/memory/ptr_util.h" #include "base/message_loop/message_loop.h" #include "base/run_loop.h" #include "base/strings/string_piece.h" @@ -72,8 +72,8 @@ const auto has_alpha_frame = rng() % 4; muxer.OnEncodedVideo( WebmMuxer::VideoParameters(video_frame), - base::MakeUnique<std::string>(str), - has_alpha_frame ? base::MakeUnique<std::string>(str) : nullptr, + std::make_unique<std::string>(str), + has_alpha_frame ? std::make_unique<std::string>(str) : nullptr, base::TimeTicks(), is_key_frame); base::RunLoop run_loop; run_loop.RunUntilIdle(); @@ -88,7 +88,7 @@ const AudioParameters params( media::AudioParameters::AUDIO_PCM_LOW_LATENCY, layout, sample_rate, 16 /* bits_per_sample */, 60 * sample_rate); - muxer.OnEncodedAudio(params, base::MakeUnique<std::string>(str), + muxer.OnEncodedAudio(params, std::make_unique<std::string>(str), base::TimeTicks()); base::RunLoop run_loop; run_loop.RunUntilIdle();
diff --git a/media/muxers/webm_muxer_unittest.cc b/media/muxers/webm_muxer_unittest.cc index 454f3f7..e81c9e6 100644 --- a/media/muxers/webm_muxer_unittest.cc +++ b/media/muxers/webm_muxer_unittest.cc
@@ -6,6 +6,7 @@ #include <stddef.h> #include <stdint.h> +#include <memory> #include "base/bind.h" #include "base/location.h" @@ -147,7 +148,7 @@ webm_muxer_.ForceOneLibWebmErrorForTesting(); EXPECT_FALSE(webm_muxer_.OnEncodedVideo( WebmMuxer::VideoParameters(video_frame), - base::MakeUnique<std::string>(encoded_data), nullptr, + std::make_unique<std::string>(encoded_data), nullptr, base::TimeTicks::Now(), true /* keyframe */)); } @@ -203,7 +204,7 @@ webm_muxer_.ForceOneLibWebmErrorForTesting(); EXPECT_FALSE(webm_muxer_.OnEncodedVideo( WebmMuxer::VideoParameters(video_frame), - base::MakeUnique<std::string>(encoded_data), nullptr, + std::make_unique<std::string>(encoded_data), nullptr, base::TimeTicks::Now(), true /* keyframe */)); } @@ -226,7 +227,7 @@ .WillRepeatedly( WithArgs<0>(Invoke(this, &WebmMuxerTest::SaveEncodedDataLen))); EXPECT_TRUE(webm_muxer_.OnEncodedAudio( - audio_params, base::MakeUnique<std::string>(encoded_data), + audio_params, std::make_unique<std::string>(encoded_data), base::TimeTicks::Now())); // First time around WriteCallback() is pinged a number of times to write the @@ -242,7 +243,7 @@ .WillRepeatedly( WithArgs<0>(Invoke(this, &WebmMuxerTest::SaveEncodedDataLen))); EXPECT_TRUE(webm_muxer_.OnEncodedAudio( - audio_params, base::MakeUnique<std::string>(encoded_data), + audio_params, std::make_unique<std::string>(encoded_data), base::TimeTicks::Now())); // The second time around the callbacks should include a SimpleBlock header, @@ -257,7 +258,7 @@ // Force an error in libwebm and expect OnEncodedAudio to fail. webm_muxer_.ForceOneLibWebmErrorForTesting(); EXPECT_FALSE(webm_muxer_.OnEncodedAudio( - audio_params, base::MakeUnique<std::string>(encoded_data), + audio_params, std::make_unique<std::string>(encoded_data), base::TimeTicks::Now())); }
diff --git a/media/remoting/courier_renderer_factory.cc b/media/remoting/courier_renderer_factory.cc index 459338b..1091c41e 100644 --- a/media/remoting/courier_renderer_factory.cc +++ b/media/remoting/courier_renderer_factory.cc
@@ -4,8 +4,9 @@ #include "media/remoting/courier_renderer_factory.h" +#include <memory> + #include "base/logging.h" -#include "base/memory/ptr_util.h" #include "build/buildflag.h" #include "media/base/overlay_info.h" #include "media/media_features.h" @@ -32,7 +33,7 @@ const gfx::ColorSpace& target_color_space) { DCHECK(IsRemotingActive()); #if BUILDFLAG(ENABLE_MEDIA_REMOTING_RPC) - return base::MakeUnique<CourierRenderer>( + return std::make_unique<CourierRenderer>( media_task_runner, controller_->GetWeakPtr(), video_renderer_sink); #else return nullptr;
diff --git a/media/remoting/courier_renderer_unittest.cc b/media/remoting/courier_renderer_unittest.cc index e9ba2cd..f944cbe8 100644 --- a/media/remoting/courier_renderer_unittest.cc +++ b/media/remoting/courier_renderer_unittest.cc
@@ -4,7 +4,8 @@ #include "media/remoting/courier_renderer.h" -#include "base/memory/ptr_util.h" +#include <memory> + #include "base/run_loop.h" #include "base/test/scoped_task_environment.h" #include "base/test/simple_test_tick_clock.h" @@ -278,7 +279,7 @@ } void SetUp() override { - controller_ = base::MakeUnique<RendererController>( + controller_ = std::make_unique<RendererController>( FakeRemoterFactory::CreateSharedSession(false)); controller_->OnMetadataChanged(DefaultMetadata());
diff --git a/media/remoting/end2end_test_renderer.cc b/media/remoting/end2end_test_renderer.cc index f93fd1af4..ed21a693 100644 --- a/media/remoting/end2end_test_renderer.cc +++ b/media/remoting/end2end_test_renderer.cc
@@ -4,6 +4,8 @@ #include "media/remoting/end2end_test_renderer.h" +#include <memory> + #include "base/bind.h" #include "base/bind_helpers.h" #include "base/callback.h" @@ -134,7 +136,7 @@ mojom::RemotingSourcePtr remoting_source; auto remoting_source_request = mojo::MakeRequest(&remoting_source); mojom::RemoterPtr remoter; - std::unique_ptr<TestRemoter> test_remoter = base::MakeUnique<TestRemoter>( + std::unique_ptr<TestRemoter> test_remoter = std::make_unique<TestRemoter>( std::move(remoting_source), send_message_to_sink_cb, send_frame_to_sink_cb); mojo::MakeStrongBinding(std::move(test_remoter), mojo::MakeRequest(&remoter));
diff --git a/media/remoting/fake_remoter.cc b/media/remoting/fake_remoter.cc index d96982e4..b362c96 100644 --- a/media/remoting/fake_remoter.cc +++ b/media/remoting/fake_remoter.cc
@@ -4,10 +4,11 @@ #include "media/remoting/fake_remoter.h" +#include <memory> + #include "base/bind.h" #include "base/bind_helpers.h" #include "base/callback.h" -#include "base/memory/ptr_util.h" #include "base/threading/thread_task_runner_handle.h" #include "build/buildflag.h" #include "media/media_features.h" @@ -182,7 +183,7 @@ void FakeRemoterFactory::Create(mojom::RemotingSourcePtr source, mojom::RemoterRequest request) { mojo::MakeStrongBinding( - base::MakeUnique<FakeRemoter>(std::move(source), start_will_fail_), + std::make_unique<FakeRemoter>(std::move(source), start_will_fail_), std::move(request)); }
diff --git a/media/remoting/integration_test.cc b/media/remoting/integration_test.cc index 68ed1d8..90335a3 100644 --- a/media/remoting/integration_test.cc +++ b/media/remoting/integration_test.cc
@@ -2,7 +2,8 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#include "base/memory/ptr_util.h" +#include <memory> + #include "media/base/test_data_util.h" #include "media/remoting/end2end_test_renderer.h" #include "media/test/mock_media_source.h" @@ -30,7 +31,7 @@ std::unique_ptr<Renderer> renderer_impl = default_renderer_factory_->CreateRenderer(prepend_video_decoders_cb, prepend_audio_decoders_cb); - return base::MakeUnique<End2EndTestRenderer>(std::move(renderer_impl)); + return std::make_unique<End2EndTestRenderer>(std::move(renderer_impl)); } private:
diff --git a/media/remoting/remoting_cdm_factory.cc b/media/remoting/remoting_cdm_factory.cc index 8476d89..3080f9f 100644 --- a/media/remoting/remoting_cdm_factory.cc +++ b/media/remoting/remoting_cdm_factory.cc
@@ -4,8 +4,9 @@ #include "media/remoting/remoting_cdm_factory.h" +#include <memory> + #include "base/bind.h" -#include "base/memory/ptr_util.h" #include "base/single_thread_task_runner.h" #include "media/base/cdm_config.h" #include "media/remoting/remoting_cdm.h" @@ -43,7 +44,7 @@ // avoid the possible delay on OnSinkAvailable() call from browser. if (sink_observer_->IsRemoteDecryptionAvailable()) session->OnSinkAvailable(sink_observer_->sink_metadata().Clone()); - return base::MakeUnique<RemotingCdmController>(std::move(session)); + return std::make_unique<RemotingCdmController>(std::move(session)); } // TODO(xjz): Replace the callbacks with an interface. http://crbug.com/657940.
diff --git a/media/remoting/renderer_controller.cc b/media/remoting/renderer_controller.cc index 9aa78ec..384b2dc 100644 --- a/media/remoting/renderer_controller.cc +++ b/media/remoting/renderer_controller.cc
@@ -66,6 +66,43 @@ return UNKNOWN_STOP_TRIGGER; // To suppress compiler warning on Windows. } +MediaObserverClient::ReasonToSwitchToLocal GetSwitchReason( + StopTrigger stop_trigger) { + switch (stop_trigger) { + case FRAME_DROP_RATE_HIGH: + case PACING_TOO_SLOWLY: + return MediaObserverClient::ReasonToSwitchToLocal::POOR_PLAYBACK_QUALITY; + case EXITED_FULLSCREEN: + case BECAME_AUXILIARY_CONTENT: + case DISABLED_BY_PAGE: + case USER_DISABLED: + case UNKNOWN_STOP_TRIGGER: + return MediaObserverClient::ReasonToSwitchToLocal::NORMAL; + case UNSUPPORTED_AUDIO_CODEC: + case UNSUPPORTED_VIDEO_CODEC: + case UNSUPPORTED_AUDIO_AND_VIDEO_CODECS: + case DECRYPTION_ERROR: + case RECEIVER_INITIALIZE_FAILED: + case RECEIVER_PIPELINE_ERROR: + case PEERS_OUT_OF_SYNC: + case RPC_INVALID: + case DATA_PIPE_CREATE_ERROR: + case MOJO_PIPE_ERROR: + case MESSAGE_SEND_FAILED: + case DATA_SEND_FAILED: + case UNEXPECTED_FAILURE: + return MediaObserverClient::ReasonToSwitchToLocal::PIPELINE_ERROR; + case ROUTE_TERMINATED: + case MEDIA_ELEMENT_DESTROYED: + case START_RACE: + case SERVICE_GONE: + return MediaObserverClient::ReasonToSwitchToLocal::ROUTE_TERMINATED; + } + + // To suppress compiler warning on Windows. + return MediaObserverClient::ReasonToSwitchToLocal::ROUTE_TERMINATED; +} + } // namespace RendererController::RendererController(scoped_refptr<SharedSession> session) @@ -438,9 +475,9 @@ // force-stop the session when remoting has ended; so no need to call // StopRemoting() from here. DCHECK(!is_encrypted_); - DCHECK_NE(stop_trigger, UNKNOWN_STOP_TRIGGER); + DCHECK_NE(UNKNOWN_STOP_TRIGGER, stop_trigger); metrics_recorder_.WillStopSession(stop_trigger); - client_->SwitchToLocalRenderer(); + client_->SwitchToLocalRenderer(GetSwitchReason(stop_trigger)); VLOG(2) << "Request to stop remoting: stop_trigger=" << stop_trigger; session_->StopRemoting(this); } @@ -499,7 +536,7 @@ client_->SwitchToRemoteRenderer(session_->sink_name()); return; } - DCHECK_NE(start_trigger, UNKNOWN_START_TRIGGER); + DCHECK_NE(UNKNOWN_START_TRIGGER, start_trigger); metrics_recorder_.WillStartSession(start_trigger); // |MediaObserverClient::SwitchToRemoteRenderer()| will be called after // remoting is started successfully.
diff --git a/media/remoting/renderer_controller_unittest.cc b/media/remoting/renderer_controller_unittest.cc index 374e9dc..3e66955 100644 --- a/media/remoting/renderer_controller_unittest.cc +++ b/media/remoting/renderer_controller_unittest.cc
@@ -4,8 +4,9 @@ #include "media/remoting/renderer_controller.h" +#include <memory> + #include "base/callback.h" -#include "base/memory/ptr_util.h" #include "base/message_loop/message_loop.h" #include "base/run_loop.h" #include "base/test/simple_test_tick_clock.h" @@ -85,7 +86,7 @@ sink_name_ = remote_device_friendly_name; } - void SwitchToLocalRenderer() override { + void SwitchToLocalRenderer(ReasonToSwitchToLocal reason) override { is_rendering_remotely_ = false; disable_pipeline_suspend_ = false; sink_name_.clear(); @@ -109,7 +110,7 @@ const mojom::RemotingSinkMetadata& sink_metadata) { EXPECT_FALSE(is_rendering_remotely_); EXPECT_TRUE(sink_name_.empty()); - controller_ = base::MakeUnique<RendererController>(shared_session); + controller_ = std::make_unique<RendererController>(shared_session); controller_->clock_ = &clock_; clock_.Advance(base::TimeDelta::FromSeconds(1)); controller_->SetClient(this); @@ -452,7 +453,7 @@ const scoped_refptr<SharedSession> cdm_shared_session = FakeRemoterFactory::CreateSharedSession(false); std::unique_ptr<RemotingCdmController> cdm_controller = - base::MakeUnique<RemotingCdmController>(cdm_shared_session); + std::make_unique<RemotingCdmController>(cdm_shared_session); cdm_shared_session->OnSinkAvailable(GetDefaultSinkMetadata(true).Clone()); cdm_controller->ShouldCreateRemotingCdm( base::Bind(&RendererControllerTest::CreateCdm, base::Unretained(this))); @@ -466,7 +467,7 @@ SessionKeysChangeCB(), SessionExpirationUpdateCB(), CdmCreatedCB(), std::move(cdm_controller)); std::unique_ptr<RemotingCdmContext> remoting_cdm_context = - base::MakeUnique<RemotingCdmContext>(remoting_cdm.get()); + std::make_unique<RemotingCdmContext>(remoting_cdm.get()); controller_->OnSetCdm(remoting_cdm_context.get()); RunUntilIdle(); EXPECT_TRUE(is_rendering_remotely_); @@ -504,7 +505,7 @@ const scoped_refptr<SharedSession> cdm_shared_session = FakeRemoterFactory::CreateSharedSession(true); std::unique_ptr<RemotingCdmController> cdm_controller = - base::MakeUnique<RemotingCdmController>(cdm_shared_session); + std::make_unique<RemotingCdmController>(cdm_shared_session); cdm_shared_session->OnSinkAvailable(GetDefaultSinkMetadata(true).Clone()); cdm_controller->ShouldCreateRemotingCdm( base::Bind(&RendererControllerTest::CreateCdm, base::Unretained(this))); @@ -525,7 +526,7 @@ const scoped_refptr<SharedSession> cdm_shared_session = FakeRemoterFactory::CreateSharedSession(false); std::unique_ptr<RemotingCdmController> cdm_controller = - base::MakeUnique<RemotingCdmController>(cdm_shared_session); + std::make_unique<RemotingCdmController>(cdm_shared_session); cdm_shared_session->OnSinkAvailable(GetDefaultSinkMetadata(true).Clone()); cdm_controller->ShouldCreateRemotingCdm( base::Bind(&RendererControllerTest::CreateCdm, base::Unretained(this))); @@ -546,7 +547,7 @@ SessionKeysChangeCB(), SessionExpirationUpdateCB(), CdmCreatedCB(), std::move(cdm_controller)); std::unique_ptr<RemotingCdmContext> remoting_cdm_context = - base::MakeUnique<RemotingCdmContext>(remoting_cdm.get()); + std::make_unique<RemotingCdmContext>(remoting_cdm.get()); controller_->OnSetCdm(remoting_cdm_context.get()); RunUntilIdle(); // Switch to using the remoting renderer, even when the remoting CDM session
diff --git a/media/renderers/audio_renderer_impl.cc b/media/renderers/audio_renderer_impl.cc index 55aa8a26..abcb3df 100644 --- a/media/renderers/audio_renderer_impl.cc +++ b/media/renderers/audio_renderer_impl.cc
@@ -7,6 +7,7 @@ #include <math.h> #include <stddef.h> #include <algorithm> +#include <memory> #include <utility> #include "base/bind.h" @@ -374,7 +375,7 @@ current_decoder_config_ = stream->audio_decoder_config(); DCHECK(current_decoder_config_.IsValidConfig()); - audio_buffer_stream_ = base::MakeUnique<AudioBufferStream>( + audio_buffer_stream_ = std::make_unique<AudioBufferStream>( task_runner_, create_audio_decoders_cb_, media_log_); audio_buffer_stream_->set_config_change_observer(base::Bind(
diff --git a/media/renderers/audio_renderer_impl_unittest.cc b/media/renderers/audio_renderer_impl_unittest.cc index 5cd430f..15ed036 100644 --- a/media/renderers/audio_renderer_impl_unittest.cc +++ b/media/renderers/audio_renderer_impl_unittest.cc
@@ -12,7 +12,6 @@ #include "base/callback_helpers.h" #include "base/format_macros.h" #include "base/macros.h" -#include "base/memory/ptr_util.h" #include "base/message_loop/message_loop.h" #include "base/run_loop.h" #include "base/single_thread_task_runner.h" @@ -91,7 +90,7 @@ class AudioRendererImplTest : public ::testing::Test, public RendererClient { public: std::vector<std::unique_ptr<AudioDecoder>> CreateAudioDecoderForTest() { - auto decoder = base::MakeUnique<MockAudioDecoder>(); + auto decoder = std::make_unique<MockAudioDecoder>(); if (!enter_pending_decoder_init_) { EXPECT_CALL(*decoder, Initialize(_, _, _, _)) .WillOnce(DoAll(SaveArg<3>(&output_cb_),
diff --git a/media/renderers/default_renderer_factory.cc b/media/renderers/default_renderer_factory.cc index 93b26d9..e31dda85 100644 --- a/media/renderers/default_renderer_factory.cc +++ b/media/renderers/default_renderer_factory.cc
@@ -4,11 +4,11 @@ #include "media/renderers/default_renderer_factory.h" +#include <memory> #include <utility> #include "base/bind.h" #include "base/feature_list.h" -#include "base/memory/ptr_util.h" #include "base/single_thread_task_runner.h" #include "build/build_config.h" #include "build/buildflag.h" @@ -109,7 +109,7 @@ #if BUILDFLAG(ENABLE_AV1_DECODER) if (base::FeatureList::IsEnabled(kAv1Decoder)) - video_decoders.push_back(base::MakeUnique<AomVideoDecoder>(media_log_)); + video_decoders.push_back(std::make_unique<AomVideoDecoder>(media_log_)); #endif #if !defined(MEDIA_DISABLE_FFMPEG) && !defined(DISABLE_FFMPEG_VIDEO_DECODERS)
diff --git a/media/test/pipeline_integration_test.cc b/media/test/pipeline_integration_test.cc index fa40ca0..7e85e858 100644 --- a/media/test/pipeline_integration_test.cc +++ b/media/test/pipeline_integration_test.cc
@@ -11,7 +11,6 @@ #include "base/bind.h" #include "base/command_line.h" #include "base/macros.h" -#include "base/memory/ptr_util.h" #include "base/memory/ref_counted.h" #include "base/run_loop.h" #include "base/strings/string_split.h" @@ -440,7 +439,7 @@ media_interface_factory_->CreateRenderer(std::string(), mojo::MakeRequest(&mojo_renderer)); - return base::MakeUnique<MojoRenderer>(message_loop_.task_runner(), + return std::make_unique<MojoRenderer>(message_loop_.task_runner(), std::move(mojo_renderer)); } @@ -1802,7 +1801,7 @@ std::vector<std::unique_ptr<VideoDecoder>> CreateFailingVideoDecoder() { std::vector<std::unique_ptr<VideoDecoder>> failing_video_decoder; - failing_video_decoder.push_back(base::MakeUnique<FailingVideoDecoder>()); + failing_video_decoder.push_back(std::make_unique<FailingVideoDecoder>()); return failing_video_decoder; }
diff --git a/media/test/pipeline_integration_test_base.cc b/media/test/pipeline_integration_test_base.cc index 9343866..354fdb97 100644 --- a/media/test/pipeline_integration_test_base.cc +++ b/media/test/pipeline_integration_test_base.cc
@@ -4,11 +4,11 @@ #include "media/test/pipeline_integration_test_base.h" +#include <memory> #include <utility> #include "base/bind.h" #include "base/callback.h" -#include "base/memory/ptr_util.h" #include "base/memory/ref_counted.h" #include "base/run_loop.h" #include "base/single_thread_task_runner.h" @@ -67,7 +67,7 @@ #if BUILDFLAG(ENABLE_AV1_DECODER) if (base::FeatureList::IsEnabled(kAv1Decoder)) - video_decoders.push_back(base::MakeUnique<AomVideoDecoder>(media_log)); + video_decoders.push_back(std::make_unique<AomVideoDecoder>(media_log)); #endif // !defined(MEDIA_DISABLE_LIBVPX) // Android does not have an ffmpeg video decoder.
diff --git a/media/video/h264_parser_unittest.cc b/media/video/h264_parser_unittest.cc index 74e2b0e..44688a0c 100644 --- a/media/video/h264_parser_unittest.cc +++ b/media/video/h264_parser_unittest.cc
@@ -9,7 +9,6 @@ #include "base/command_line.h" #include "base/files/memory_mapped_file.h" #include "base/logging.h" -#include "base/memory/ptr_util.h" #include "base/optional.h" #include "base/strings/string_number_conversions.h" #include "media/base/test_data_util.h" @@ -24,7 +23,7 @@ public: // An exact clone of an SPS from Big Buck Bunny 480p. std::unique_ptr<H264SPS> MakeSPS_BBB480p() { - std::unique_ptr<H264SPS> sps = base::MakeUnique<H264SPS>(); + std::unique_ptr<H264SPS> sps = std::make_unique<H264SPS>(); sps->profile_idc = 100; sps->level_idc = 30; sps->chroma_format_idc = 1;
diff --git a/media/video/mock_gpu_video_accelerator_factories.cc b/media/video/mock_gpu_video_accelerator_factories.cc index 96ce3353..65ce444 100644 --- a/media/video/mock_gpu_video_accelerator_factories.cc +++ b/media/video/mock_gpu_video_accelerator_factories.cc
@@ -4,6 +4,8 @@ #include "media/video/mock_gpu_video_accelerator_factories.h" +#include <memory> + #include "base/memory/ptr_util.h" #include "ui/gfx/buffer_format_util.h" #include "ui/gfx/gpu_memory_buffer.h" @@ -95,7 +97,7 @@ gfx::BufferUsage /* usage */) { if (fail_to_allocate_gpu_memory_buffer_) return nullptr; - return base::MakeUnique<GpuMemoryBufferImpl>(size, format); + return std::make_unique<GpuMemoryBufferImpl>(size, format); } std::unique_ptr<base::SharedMemory> @@ -144,7 +146,7 @@ std::unique_ptr<GpuVideoAcceleratorFactories::ScopedGLContextLock> MockGpuVideoAcceleratorFactories::GetGLContextLock() { DCHECK(gles2_); - return base::MakeUnique<ScopedGLContextLockImpl>(this); + return std::make_unique<ScopedGLContextLockImpl>(this); } } // namespace media
diff --git a/net/disk_cache/blockfile/file.h b/net/disk_cache/blockfile/file.h index 0e34fab..6aa6ba2 100644 --- a/net/disk_cache/blockfile/file.h +++ b/net/disk_cache/blockfile/file.h
@@ -68,6 +68,8 @@ size_t GetLength(); // Blocks until |num_pending_io| IO operations complete. + // TODO(fdoray): Rename to WaitForPendingIOForTesting() since this should only + // be called in tests. static void WaitForPendingIO(int* num_pending_io); // Drops current pending operations without waiting for them to complete.
diff --git a/net/disk_cache/blockfile/file_posix.cc b/net/disk_cache/blockfile/file_posix.cc index 69058f1..e1d0b363 100644 --- a/net/disk_cache/blockfile/file_posix.cc +++ b/net/disk_cache/blockfile/file_posix.cc
@@ -9,36 +9,14 @@ #include <utility> #include "base/bind.h" -#include "base/lazy_instance.h" #include "base/location.h" #include "base/logging.h" #include "base/run_loop.h" -#include "base/task_runner_util.h" -#include "base/threading/sequenced_worker_pool.h" +#include "base/task_scheduler/post_task.h" +#include "base/task_scheduler/task_scheduler.h" #include "net/base/net_errors.h" #include "net/disk_cache/disk_cache.h" -namespace { - -// The maximum number of threads for this pool. -const int kMaxThreads = 5; - -class FileWorkerPool : public base::SequencedWorkerPool { - public: - FileWorkerPool() - : base::SequencedWorkerPool(kMaxThreads, - "CachePool", - base::TaskPriority::USER_BLOCKING) {} - - protected: - ~FileWorkerPool() override = default; -}; - -base::LazyInstance<FileWorkerPool>::Leaky s_worker_pool = - LAZY_INSTANCE_INITIALIZER; - -} // namespace - namespace disk_cache { File::File(base::File file) @@ -95,11 +73,11 @@ return false; } - base::PostTaskAndReplyWithResult( - s_worker_pool.Pointer(), FROM_HERE, - base::Bind(&File::DoRead, base::Unretained(this), buffer, buffer_len, - offset), - base::Bind(&File::OnOperationComplete, this, callback)); + base::PostTaskWithTraitsAndReplyWithResult( + FROM_HERE, {base::TaskPriority::USER_BLOCKING, base::MayBlock()}, + base::BindOnce(&File::DoRead, base::Unretained(this), buffer, buffer_len, + offset), + base::BindOnce(&File::OnOperationComplete, this, callback)); *completed = false; return true; @@ -119,11 +97,15 @@ return false; } - base::PostTaskAndReplyWithResult( - s_worker_pool.Pointer(), FROM_HERE, - base::Bind(&File::DoWrite, base::Unretained(this), buffer, buffer_len, - offset), - base::Bind(&File::OnOperationComplete, this, callback)); + // The priority is USER_BLOCKING because the cache waits for the write to + // finish before it reads from the network again. + // TODO(fdoray): Consider removing this from the critical path of network + // requests and changing the priority to BACKGROUND. + base::PostTaskWithTraitsAndReplyWithResult( + FROM_HERE, {base::TaskPriority::USER_BLOCKING, base::MayBlock()}, + base::BindOnce(&File::DoWrite, base::Unretained(this), buffer, buffer_len, + offset), + base::BindOnce(&File::OnOperationComplete, this, callback)); *completed = false; return true; @@ -151,10 +133,11 @@ // Static. void File::WaitForPendingIO(int* num_pending_io) { - // We are running unit tests so we should wait for all callbacks. Sadly, the - // worker pool only waits for tasks on the worker pool, not the "Reply" tasks - // so we have to let the current message loop to run. - s_worker_pool.Get().FlushForTesting(); + // We are running unit tests so we should wait for all callbacks. + + // This waits for callbacks running on worker threads. + base::TaskScheduler::GetInstance()->FlushForTesting(); + // This waits for the "Reply" tasks running on the current MessageLoop. base::RunLoop().RunUntilIdle(); }
diff --git a/net/http/http_network_transaction_unittest.cc b/net/http/http_network_transaction_unittest.cc index c05e021..25ae85c 100644 --- a/net/http/http_network_transaction_unittest.cc +++ b/net/http/http_network_transaction_unittest.cc
@@ -8512,20 +8512,21 @@ CreateMockWrite(stream2_priority, 3, ASYNC), }; + SpdySerializedFrame stream2_syn(spdy_util_.ConstructSpdyPush( + NULL, 0, 2, 1, "http://www.another-origin.com/foo.dat")); + SpdySerializedFrame stream1_reply( spdy_util_.ConstructSpdyGetReply(NULL, 0, 1)); SpdySerializedFrame stream1_body(spdy_util_.ConstructSpdyDataFrame(1, true)); - SpdySerializedFrame stream2_syn(spdy_util_.ConstructSpdyPush( - NULL, 0, 2, 1, "http://www.another-origin.com/foo.dat")); const char kPushedData[] = "pushed"; SpdySerializedFrame stream2_body(spdy_util_.ConstructSpdyDataFrame( 2, kPushedData, strlen(kPushedData), true)); MockRead spdy_reads[] = { - CreateMockRead(stream1_reply, 1, ASYNC), - CreateMockRead(stream2_syn, 2, ASYNC), + CreateMockRead(stream2_syn, 1, ASYNC), + CreateMockRead(stream1_reply, 2, ASYNC), CreateMockRead(stream1_body, 4, ASYNC), CreateMockRead(stream2_body, 5, ASYNC), MockRead(SYNCHRONOUS, ERR_IO_PENDING, 6), // Force a hang
diff --git a/net/nqe/network_quality_estimator.cc b/net/nqe/network_quality_estimator.cc index 8dca5156..73bc2307 100644 --- a/net/nqe/network_quality_estimator.cc +++ b/net/nqe/network_quality_estimator.cc
@@ -1229,7 +1229,8 @@ *transport_rtt != nqe::internal::InvalidRTT()) { // Use transport RTT to clamp the HTTP RTT between lower and upper bounds. // To improve accuracy, the transport RTT estimate is used only when the - // transport RTT estimate was computed using at least 5 observations. + // transport RTT estimate was computed using at least + // |params_->http_rtt_transport_rtt_min_count()| observations. if (transport_rtt_observation_count_last_ect_computation_ >= params_->http_rtt_transport_rtt_min_count()) { if (params_->lower_bound_http_rtt_transport_rtt_multiplier() > 0) {
diff --git a/net/nqe/network_quality_estimator_params.cc b/net/nqe/network_quality_estimator_params.cc index e05c7c8..a4a7150 100644 --- a/net/nqe/network_quality_estimator_params.cc +++ b/net/nqe/network_quality_estimator_params.cc
@@ -415,7 +415,7 @@ GetDoubleValueForVariationParamWithDefaultValue( params_, "lower_bound_http_rtt_transport_rtt_multiplier", - -1)), + 1.0)), upper_bound_http_rtt_transport_rtt_multiplier_( GetDoubleValueForVariationParamWithDefaultValue( params_,
diff --git a/net/nqe/network_quality_estimator_unittest.cc b/net/nqe/network_quality_estimator_unittest.cc index 11c27840..7c723ad 100644 --- a/net/nqe/network_quality_estimator_unittest.cc +++ b/net/nqe/network_quality_estimator_unittest.cc
@@ -1784,7 +1784,7 @@ { base::TimeDelta::FromMilliseconds(100), base::TimeDelta::FromMilliseconds(200), "", "", - base::TimeDelta::FromMilliseconds(100), EFFECTIVE_CONNECTION_TYPE_4G, + base::TimeDelta::FromMilliseconds(200), EFFECTIVE_CONNECTION_TYPE_4G, }, { base::TimeDelta::FromMilliseconds(100), @@ -1834,12 +1834,13 @@ { base::TimeDelta::FromMilliseconds(100), base::TimeDelta::FromMilliseconds(200), "foobar", "", - base::TimeDelta::FromMilliseconds(100), EFFECTIVE_CONNECTION_TYPE_4G, + base::TimeDelta::FromMilliseconds(200), EFFECTIVE_CONNECTION_TYPE_4G, }, { base::TimeDelta::FromMilliseconds(100), base::TimeDelta::FromMilliseconds(4000), "", "", - base::TimeDelta::FromMilliseconds(100), EFFECTIVE_CONNECTION_TYPE_4G, + base::TimeDelta::FromMilliseconds(4000), + EFFECTIVE_CONNECTION_TYPE_SLOW_2G, }, { base::TimeDelta::FromMilliseconds(100),
diff --git a/net/spdy/chromium/http2_push_promise_index.cc b/net/spdy/chromium/http2_push_promise_index.cc index 5864823..38c032b 100644 --- a/net/spdy/chromium/http2_push_promise_index.cc +++ b/net/spdy/chromium/http2_push_promise_index.cc
@@ -102,7 +102,6 @@ if (it->delegate->ValidatePushedStream(url, key)) { *session = it->delegate->GetWeakPtrToSession(); *stream_id = it->stream_id; - it->delegate->OnPushedStreamClaimed(it->url, it->stream_id); unclaimed_pushed_streams_.erase(it); return; }
diff --git a/net/spdy/chromium/http2_push_promise_index.h b/net/spdy/chromium/http2_push_promise_index.h index 09114764..d75cc43 100644 --- a/net/spdy/chromium/http2_push_promise_index.h +++ b/net/spdy/chromium/http2_push_promise_index.h
@@ -48,11 +48,6 @@ virtual bool ValidatePushedStream(const GURL& url, const SpdySessionKey& key) const = 0; - // Called when a pushed stream is claimed. Guaranateed to be called - // synchronously after ValidatePushedStream() is called and returns true. - virtual void OnPushedStreamClaimed(const GURL& url, - SpdyStreamId stream_id) = 0; - // Generate weak pointer. Guaranateed to be called synchronously after // ValidatePushedStream() is called and returns true. virtual base::WeakPtr<SpdySession> GetWeakPtrToSession() = 0;
diff --git a/net/spdy/chromium/http2_push_promise_index_test.cc b/net/spdy/chromium/http2_push_promise_index_test.cc index 1314313d..db72fae 100644 --- a/net/spdy/chromium/http2_push_promise_index_test.cc +++ b/net/spdy/chromium/http2_push_promise_index_test.cc
@@ -7,7 +7,6 @@ #include "net/base/host_port_pair.h" #include "net/base/privacy_mode.h" #include "net/test/gtest_util.h" -#include "testing/gmock/include/gmock/gmock.h" #include "testing/gtest/include/gtest/gtest.h" #include "url/gurl.h" @@ -36,29 +35,12 @@ return key == key_; } - void OnPushedStreamClaimed(const GURL& url, SpdyStreamId stream_id) override { - } - base::WeakPtr<SpdySession> GetWeakPtrToSession() override { return nullptr; } private: SpdySessionKey key_; }; -// Mock implementation. -class MockDelegate : public Http2PushPromiseIndex::Delegate { - public: - MockDelegate() = default; - ~MockDelegate() override {} - - MOCK_CONST_METHOD2(ValidatePushedStream, - bool(const GURL& url, const SpdySessionKey& key)); - MOCK_METHOD2(OnPushedStreamClaimed, - void(const GURL& url, SpdyStreamId stream_id)); - - base::WeakPtr<SpdySession> GetWeakPtrToSession() override { return nullptr; } -}; - } // namespace class Http2PushPromiseIndexPeer { @@ -376,45 +358,6 @@ EXPECT_FALSE(index_.UnregisterUnclaimedPushedStream(url1_, 4, &delegate2)); } -// Test that Delegate::ValidatePushedStream() is called by ClaimPushedStream(), -// and if it returns true, then Delegate::OnPushedStreamClaimed() is called with -// the appropriate arguments. -TEST_F(Http2PushPromiseIndexTest, MatchCallsOnPushedStreamClaimed) { - MockDelegate delegate; - EXPECT_CALL(delegate, ValidatePushedStream(url1_, key1_)) - .WillOnce(Return(true)); - EXPECT_CALL(delegate, OnPushedStreamClaimed(url1_, 2)).Times(1); - - EXPECT_TRUE(index_.RegisterUnclaimedPushedStream(url1_, 2, &delegate)); - - base::WeakPtr<SpdySession> session; - SpdyStreamId stream_id = kNoPushedStreamFound; - index_.ClaimPushedStream(key1_, url1_, &session, &stream_id); - EXPECT_EQ(2u, stream_id); - - // ClaimPushedStream() unregistered the entry. - EXPECT_FALSE(index_.UnregisterUnclaimedPushedStream(url1_, 2, &delegate)); -}; - -// Test that Delegate::ValidatePushedStream() is called by ClaimPushedStream(), -// and if it returns false, then Delegate::OnPushedStreamClaimed() is not -// called. -TEST_F(Http2PushPromiseIndexTest, MismatchDoesNotCallOnPushedStreamClaimed) { - MockDelegate delegate; - EXPECT_CALL(delegate, ValidatePushedStream(url1_, key1_)) - .WillOnce(Return(false)); - EXPECT_CALL(delegate, OnPushedStreamClaimed(_, _)).Times(0); - - EXPECT_TRUE(index_.RegisterUnclaimedPushedStream(url1_, 2, &delegate)); - - base::WeakPtr<SpdySession> session; - SpdyStreamId stream_id = 2; - index_.ClaimPushedStream(key1_, url1_, &session, &stream_id); - EXPECT_EQ(kNoPushedStreamFound, stream_id); - - EXPECT_TRUE(index_.UnregisterUnclaimedPushedStream(url1_, 2, &delegate)); -}; - // Test that an entry is equivalent to itself. TEST(Http2PushPromiseIndexCompareByUrlTest, Reflexivity) { // Test with two entries: with and without a pushed stream.
diff --git a/net/spdy/chromium/spdy_http_stream.cc b/net/spdy/chromium/spdy_http_stream.cc index aa35adc..74cf7a3 100644 --- a/net/spdy/chromium/spdy_http_stream.cc +++ b/net/spdy/chromium/spdy_http_stream.cc
@@ -78,9 +78,10 @@ return ERR_CONNECTION_CLOSED; request_info_ = request_info; - // TODO(bnc): Remove this condition once pushed headers are properly + // TODO(bnc): Remove condition on method once pushed headers are properly // validated. https://crbug.com/554220. - if (request_info_->method == "GET") { + if (request_info_->method == "GET" && + pushed_stream_id_ != kNoPushedStreamFound) { int error = spdy_session_->GetPushedStream(request_info_->url, pushed_stream_id_, priority, &stream_, stream_net_log);
diff --git a/net/spdy/chromium/spdy_http_stream_unittest.cc b/net/spdy/chromium/spdy_http_stream_unittest.cc index 5f3d5ddcd..1f0fde7 100644 --- a/net/spdy/chromium/spdy_http_stream_unittest.cc +++ b/net/spdy/chromium/spdy_http_stream_unittest.cc
@@ -1121,80 +1121,6 @@ EXPECT_FALSE(HasSpdySession(http_session_->spdy_session_pool(), key_)); } -// A SpdyHttpStream should use a matching pushed stream, even if it is -// constructed with |pushed_stream_id == kNoPushedStreamFound|. -TEST_F(SpdyHttpStreamTest, UsePushedStreamEvenWithKNoPushedStreamFound) { - SpdySerializedFrame req( - spdy_util_.ConstructSpdyGet(nullptr, 0, 1, LOWEST, true)); - SpdySerializedFrame priority( - spdy_util_.ConstructSpdyPriority(2, 1, IDLE, true)); - MockWrite writes[] = {CreateMockWrite(req, 0), CreateMockWrite(priority, 2)}; - SpdySerializedFrame push(spdy_util_.ConstructSpdyPush( - nullptr, 0, 2, 1, "https://www.example.org/foo.dat")); - SpdySerializedFrame resp(spdy_util_.ConstructSpdyGetReply(nullptr, 0, 1)); - MockRead reads[] = {CreateMockRead(push, 1), CreateMockRead(resp, 3), - MockRead(ASYNC, 0, 4)}; - InitSession(reads, arraysize(reads), writes, arraysize(writes)); - - // Create and initialize first stream. - NetLogWithSource net_log; - auto stream1 = std::make_unique<SpdyHttpStream>( - session_, kNoPushedStreamFound, true, net_log.source()); - - HttpRequestInfo request1; - request1.method = "GET"; - request1.url = url_; - int rv = stream1->InitializeStream(&request1, DEFAULT_PRIORITY, net_log, - CompletionCallback()); - EXPECT_THAT(rv, IsOk()); - - // Send request. - HttpResponseInfo response1; - TestCompletionCallback callback1; - rv = stream1->SendRequest(HttpRequestHeaders(), &response1, - callback1.callback()); - EXPECT_THAT(rv, IsError(ERR_IO_PENDING)); - rv = callback1.WaitForResult(); - EXPECT_THAT(rv, IsOk()); - - // Create and initialize second stream. - // This request must bind to the pushed stream, even though SpdyHttpStream - // constructor is called with kNoPushedStreamFound. - auto stream2 = std::make_unique<SpdyHttpStream>( - session_, kNoPushedStreamFound /* pushed_stream_id */, true, - net_log.source()); - - HttpRequestInfo request2; - request2.method = "GET"; - request2.url = GURL("https://www.example.org/foo.dat"); - rv = stream2->InitializeStream(&request2, DEFAULT_PRIORITY, net_log, - CompletionCallback()); - EXPECT_THAT(rv, IsOk()); - - // Send request. This should not send out any frames on the wire, because the - // request is served by a pushed stream. - HttpResponseInfo response2; - TestCompletionCallback callback2; - rv = stream2->SendRequest(HttpRequestHeaders(), &response2, - callback2.callback()); - EXPECT_THAT(rv, IsError(ERR_IO_PENDING)); - rv = callback2.WaitForResult(); - EXPECT_THAT(rv, IsOk()); - - // Read response headers for the second request. - rv = stream2->ReadResponseHeaders(callback2.callback()); - EXPECT_THAT(rv, IsOk()); - - // Read response headers for the first request. - rv = stream1->ReadResponseHeaders(callback1.callback()); - EXPECT_THAT(rv, IsError(ERR_IO_PENDING)); - rv = callback1.WaitForResult(); - EXPECT_THAT(rv, IsOk()); - - // Read EOF. - base::RunLoop().RunUntilIdle(); -} - // TODO(willchan): Write a longer test for SpdyStream that exercises all // methods.
diff --git a/net/spdy/chromium/spdy_network_transaction_unittest.cc b/net/spdy/chromium/spdy_network_transaction_unittest.cc index ee666d93..477590ec 100644 --- a/net/spdy/chromium/spdy_network_transaction_unittest.cc +++ b/net/spdy/chromium/spdy_network_transaction_unittest.cc
@@ -2980,15 +2980,14 @@ SpdySerializedFrame goaway(spdy_util_.ConstructSpdyGoAway( 2, ERROR_CODE_PROTOCOL_ERROR, "Received pushed stream id 4 on invalid stream id 2 (must be odd).")); - MockWrite writes[] = { - CreateMockWrite(stream1_syn, 0), CreateMockWrite(stream2_priority, 3), - CreateMockWrite(goaway, 8), - }; + MockWrite writes[] = {CreateMockWrite(stream1_syn, 0), + CreateMockWrite(stream2_priority, 3), + CreateMockWrite(goaway, 8)}; - SpdySerializedFrame stream1_reply( - spdy_util_.ConstructSpdyGetReply(nullptr, 0, 1)); SpdySerializedFrame stream2_syn(spdy_util_.ConstructSpdyPush( nullptr, 0, 2, 1, GetDefaultUrlWithPath("/foo.dat").c_str())); + SpdySerializedFrame stream1_reply( + spdy_util_.ConstructSpdyGetReply(nullptr, 0, 1)); SpdySerializedFrame stream1_body(spdy_util_.ConstructSpdyDataFrame(1, true)); const char kPushedData[] = "pushed"; SpdySerializedFrame stream2_body(spdy_util_.ConstructSpdyDataFrame( @@ -2997,10 +2996,9 @@ nullptr, 0, 4, 2, GetDefaultUrlWithPath("/bar.dat").c_str())); MockRead reads[] = { - CreateMockRead(stream1_reply, 1), CreateMockRead(stream2_syn, 2), + CreateMockRead(stream2_syn, 1), CreateMockRead(stream1_reply, 2), CreateMockRead(stream1_body, 4), CreateMockRead(stream2_body, 5), - MockRead(ASYNC, ERR_IO_PENDING, 6), CreateMockRead(stream3_syn, 7), - }; + MockRead(ASYNC, ERR_IO_PENDING, 6), CreateMockRead(stream3_syn, 7)}; SequencedSocketData data(reads, arraysize(reads), writes, arraysize(writes)); NormalSpdyTransactionHelper helper(request_, DEFAULT_PRIORITY, log_, nullptr);
diff --git a/net/spdy/chromium/spdy_session.cc b/net/spdy/chromium/spdy_session.cc index 1ca4fe2..9c202e5c 100644 --- a/net/spdy/chromium/spdy_session.cc +++ b/net/spdy/chromium/spdy_session.cc
@@ -824,31 +824,17 @@ SpdyStream** stream, const NetLogWithSource& stream_net_log) { CHECK(!in_io_loop_); - - *stream = nullptr; + // |pushed_stream_id| must be valid. + DCHECK_NE(pushed_stream_id, kNoPushedStreamFound); + // |pushed_stream_id| must already have been claimed. + DCHECK_NE(pushed_stream_id, + pool_->push_promise_index()->FindStream(url, this)); if (availability_state_ == STATE_DRAINING) { + *stream = nullptr; return ERR_CONNECTION_CLOSED; } - if (pushed_stream_id == kNoPushedStreamFound) { - // Even if no pushed stream has been claimed earlier, there could still be - // one corresponding the request, if the scheme is http (those pushes are - // not considered by Http2PushPromiseIndex::ClaimPushedStream()), or if the - // pushed stream was opened in the meanwhile. - pushed_stream_id = pool_->push_promise_index()->FindStream(url, this); - if (pushed_stream_id == kNoPushedStreamFound) - return OK; - - LogPushStreamClaimed(url, pushed_stream_id); - const bool success = - pool_->push_promise_index()->UnregisterUnclaimedPushedStream( - url, pushed_stream_id, this); - DCHECK(success); - } - - DCHECK_GT(pushed_stream_id, kNoPushedStreamFound); - ActiveStreamMap::iterator active_it = active_streams_.find(pushed_stream_id); if (active_it == active_streams_.end()) { // A previously claimed pushed stream might not be available, for example, @@ -856,6 +842,10 @@ return ERR_SPDY_PUSHED_STREAM_NOT_AVAILABLE; } + net_log_.AddEvent( + NetLogEventType::HTTP2_STREAM_ADOPTED_PUSH_STREAM, + base::Bind(&NetLogSpdyAdoptedPushStreamCallback, pushed_stream_id, &url)); + *stream = active_it->second; DCHECK_LT(streams_pushed_and_claimed_count_, streams_pushed_count_); @@ -1375,12 +1365,6 @@ VerifyDomainAuthentication(key.host_port_pair().host())); } -void SpdySession::OnPushedStreamClaimed(const GURL& url, - SpdyStreamId stream_id) { - DCHECK_NE(kNoPushedStreamFound, stream_id); - LogPushStreamClaimed(url, stream_id); -} - base::WeakPtr<SpdySession> SpdySession::GetWeakPtrToSession() { return GetWeakPtr(); } @@ -2522,13 +2506,6 @@ // LogAbandonedActiveStream() will increment the counters. } -void SpdySession::LogPushStreamClaimed(const GURL& url, - SpdyStreamId stream_id) { - net_log_.AddEvent( - NetLogEventType::HTTP2_STREAM_ADOPTED_PUSH_STREAM, - base::Bind(&NetLogSpdyAdoptedPushStreamCallback, stream_id, &url)); -} - void SpdySession::LogAbandonedActiveStream(ActiveStreamMap::const_iterator it, Error status) { DCHECK_GT(it->first, 0u);
diff --git a/net/spdy/chromium/spdy_session.h b/net/spdy/chromium/spdy_session.h index 3c67133..25bbecdd 100644 --- a/net/spdy/chromium/spdy_session.h +++ b/net/spdy/chromium/spdy_session.h
@@ -489,7 +489,6 @@ // Http2PushPromiseIndex::Delegate implementation: bool ValidatePushedStream(const GURL& url, const SpdySessionKey& key) const override; - void OnPushedStreamClaimed(const GURL& url, SpdyStreamId stream_id) override; base::WeakPtr<SpdySession> GetWeakPtrToSession() override; // Dumps memory allocation stats to |stats|. Sets |*is_session_active| to @@ -730,9 +729,6 @@ // reason other than being requested to by the stream. void LogAbandonedStream(SpdyStream* stream, Error status); - // Called when a pushed stream is claimed by a request. - void LogPushStreamClaimed(const GURL& url, SpdyStreamId stream_id); - // Called right before closing an active stream for a reason other // than being requested to by the stream. void LogAbandonedActiveStream(ActiveStreamMap::const_iterator it,
diff --git a/net/spdy/chromium/spdy_session_unittest.cc b/net/spdy/chromium/spdy_session_unittest.cc index 8adf0cb..cb30e81 100644 --- a/net/spdy/chromium/spdy_session_unittest.cc +++ b/net/spdy/chromium/spdy_session_unittest.cc
@@ -53,6 +53,7 @@ const char kHttpURLFromAnotherOrigin[] = "http://www.example2.org/a.dat"; const char kHttpsURLFromAnotherOrigin[] = "https://www.example2.org/b.dat"; +const char kPushedUrl[] = "https://www.example.org/a.dat"; const char kBodyData[] = "Body data"; const size_t kBodyDataSize = arraysize(kBodyData); @@ -1422,8 +1423,8 @@ spdy_util_.ConstructSpdyPriority(2, 1, IDLE, true)); MockWrite writes[] = {CreateMockWrite(req, 0), CreateMockWrite(priority, 2)}; - SpdySerializedFrame push(spdy_util_.ConstructSpdyPush( - nullptr, 0, 2, 1, "https://www.example.org/a.dat")); + SpdySerializedFrame push( + spdy_util_.ConstructSpdyPush(nullptr, 0, 2, 1, kPushedUrl)); SpdySerializedFrame push_body(spdy_util_.ConstructSpdyDataFrame(2, false)); MockRead reads[] = {CreateMockRead(push, 1), CreateMockRead(push_body, 3), MockRead(ASYNC, ERR_IO_PENDING, 4), @@ -1449,9 +1450,9 @@ base::RunLoop().RunUntilIdle(); // Verify that there is one unclaimed push stream. + const GURL pushed_url(kPushedUrl); EXPECT_EQ(1u, num_unclaimed_pushed_streams()); - EXPECT_TRUE(has_unclaimed_pushed_stream_for_url( - GURL("https://www.example.org/a.dat"))); + EXPECT_TRUE(has_unclaimed_pushed_stream_for_url(pushed_url)); // Unclaimed push body consumes bytes from the session window. EXPECT_EQ(kDefaultInitialWindowSize - kUploadDataSize, @@ -1464,8 +1465,7 @@ // Cancel the push after session goes away. The test must not crash. EXPECT_FALSE(session_); - EXPECT_TRUE( - test_push_delegate_->CancelPush(GURL("https://www.example.org/a.dat"))); + EXPECT_TRUE(test_push_delegate_->CancelPush(pushed_url)); histogram_tester.ExpectBucketCount("Net.SpdyStreamsPushedPerSession", 1, 1); histogram_tester.ExpectBucketCount("Net.SpdySession.PushedBytes", 6, 1); @@ -1490,8 +1490,8 @@ CreateMockWrite(rst, 5), }; - SpdySerializedFrame push(spdy_util_.ConstructSpdyPush( - nullptr, 0, 2, 1, "https://www.example.org/a.dat")); + SpdySerializedFrame push( + spdy_util_.ConstructSpdyPush(nullptr, 0, 2, 1, kPushedUrl)); SpdySerializedFrame push_body(spdy_util_.ConstructSpdyDataFrame(2, false)); MockRead reads[] = {CreateMockRead(push, 1), CreateMockRead(push_body, 2), MockRead(ASYNC, ERR_IO_PENDING, 4), @@ -1549,7 +1549,7 @@ task_runner->RunUntilIdle(); // Verify that there is one unclaimed push stream. - const GURL pushed_url("https://www.example.org/a.dat"); + const GURL pushed_url(kPushedUrl); EXPECT_EQ(1u, num_unclaimed_pushed_streams()); EXPECT_TRUE(has_unclaimed_pushed_stream_for_url(pushed_url)); @@ -1598,8 +1598,8 @@ spdy_util_.ConstructSpdyPriority(2, 1, IDLE, true)); MockWrite writes[] = {CreateMockWrite(req, 0), CreateMockWrite(priority, 3)}; - SpdySerializedFrame push(spdy_util_.ConstructSpdyPush( - nullptr, 0, 2, 1, "https://www.example.org/a.dat")); + SpdySerializedFrame push( + spdy_util_.ConstructSpdyPush(nullptr, 0, 2, 1, kPushedUrl)); SpdySerializedFrame push_body(spdy_util_.ConstructSpdyDataFrame(2, false)); MockRead reads[] = {CreateMockRead(push, 1), CreateMockRead(push_body, 2), MockRead(ASYNC, ERR_IO_PENDING, 4), @@ -1657,7 +1657,7 @@ task_runner->RunUntilIdle(); // Verify that there is one unclaimed push stream. - const GURL pushed_url("https://www.example.org/a.dat"); + const GURL pushed_url(kPushedUrl); EXPECT_EQ(1u, num_unclaimed_pushed_streams()); EXPECT_TRUE(has_unclaimed_pushed_stream_for_url(pushed_url)); @@ -1666,8 +1666,19 @@ session_recv_window_size()); EXPECT_EQ(0, session_unacked_recv_window_bytes()); + // Claim pushed stream from Http2PushPromiseIndex. + base::WeakPtr<SpdySession> session_with_pushed_stream; + SpdyStreamId pushed_stream_id; + spdy_session_pool_->push_promise_index()->ClaimPushedStream( + key_, pushed_url, &session_with_pushed_stream, &pushed_stream_id); + EXPECT_EQ(session_.get(), session_with_pushed_stream.get()); + EXPECT_EQ(2u, pushed_stream_id); + + // Verify that pushed stream is claimed. + EXPECT_EQ(0u, num_unclaimed_pushed_streams()); + SpdyStream* spdy_stream2; - rv = session_->GetPushedStream(pushed_url, kNoPushedStreamFound, MEDIUM, + rv = session_->GetPushedStream(pushed_url, pushed_stream_id, MEDIUM, &spdy_stream2, NetLogWithSource()); ASSERT_THAT(rv, IsOk()); ASSERT_TRUE(spdy_stream2); @@ -1675,9 +1686,6 @@ test::StreamDelegateDoNothing delegate2(spdy_stream2->GetWeakPtr()); spdy_stream2->SetDelegate(&delegate2); - // Verify that pushed stream is claimed. - EXPECT_EQ(0u, num_unclaimed_pushed_streams()); - // Fast forward to CancelPushedStreamIfUnclaimed() that was posted with a // delay. CancelPushedStreamIfUnclaimed() must be a no-op. task_runner->FastForwardUntilNoTasksRemain(); @@ -1707,8 +1715,8 @@ MockWrite writes[] = {CreateMockWrite(req, 0), CreateMockWrite(priority, 3), CreateMockWrite(rst, 5)}; - SpdySerializedFrame push(spdy_util_.ConstructSpdyPush( - nullptr, 0, 2, 1, "https://www.example.org/a.dat")); + SpdySerializedFrame push( + spdy_util_.ConstructSpdyPush(nullptr, 0, 2, 1, kPushedUrl)); SpdySerializedFrame push_body(spdy_util_.ConstructSpdyDataFrame(2, false)); MockRead reads[] = {CreateMockRead(push, 1), CreateMockRead(push_body, 2), MockRead(ASYNC, ERR_IO_PENDING, 4), @@ -1734,7 +1742,7 @@ base::RunLoop().RunUntilIdle(); // Verify that there is one unclaimed push stream. - const GURL pushed_url("https://www.example.org/a.dat"); + const GURL pushed_url(kPushedUrl); EXPECT_EQ(1u, num_unclaimed_pushed_streams()); EXPECT_TRUE(has_unclaimed_pushed_stream_for_url(pushed_url)); @@ -5084,8 +5092,8 @@ new_settings[SETTINGS_MAX_CONCURRENT_STREAMS] = 2; SpdySerializedFrame settings_frame( spdy_util_.ConstructSpdySettings(new_settings)); - SpdySerializedFrame pushed(spdy_util_.ConstructSpdyPush( - nullptr, 0, 2, 1, "https://www.example.org/a.dat")); + SpdySerializedFrame pushed( + spdy_util_.ConstructSpdyPush(nullptr, 0, 2, 1, kPushedUrl)); MockRead reads[] = { CreateMockRead(settings_frame, 0), MockRead(ASYNC, ERR_IO_PENDING, 3), @@ -5167,8 +5175,8 @@ } TEST_F(SpdySessionTest, RejectPushedStreamExceedingConcurrencyLimit) { - SpdySerializedFrame push_a(spdy_util_.ConstructSpdyPush( - nullptr, 0, 2, 1, "https://www.example.org/a.dat")); + SpdySerializedFrame push_a( + spdy_util_.ConstructSpdyPush(nullptr, 0, 2, 1, kPushedUrl)); SpdySerializedFrame push_b(spdy_util_.ConstructSpdyPush( nullptr, 0, 4, 1, "https://www.example.org/b.dat")); MockRead reads[] = { @@ -5406,8 +5414,8 @@ } TEST_F(SpdySessionTest, IgnoreReservedRemoteStreamsCount) { - SpdySerializedFrame push_a(spdy_util_.ConstructSpdyPush( - nullptr, 0, 2, 1, "https://www.example.org/a.dat")); + SpdySerializedFrame push_a( + spdy_util_.ConstructSpdyPush(nullptr, 0, 2, 1, kPushedUrl)); SpdyHeaderBlock push_headers; push_headers[":method"] = "GET"; spdy_util_.AddUrlToHeaderBlock("https://www.example.org/b.dat", @@ -5502,7 +5510,6 @@ } TEST_F(SpdySessionTest, CancelReservedStreamOnHeadersReceived) { - const char kPushedUrl[] = "https://www.example.org/a.dat"; SpdyHeaderBlock push_headers; push_headers[":method"] = "GET"; spdy_util_.AddUrlToHeaderBlock(kPushedUrl, &push_headers); @@ -5559,6 +5566,7 @@ EXPECT_EQ(0u, num_created_streams()); EXPECT_EQ(0u, num_pushed_streams()); EXPECT_EQ(0u, num_active_pushed_streams()); + EXPECT_EQ(0u, num_unclaimed_pushed_streams()); // Run until pushed stream is created. data.Resume(); @@ -5567,10 +5575,21 @@ EXPECT_EQ(0u, num_created_streams()); EXPECT_EQ(1u, num_pushed_streams()); EXPECT_EQ(0u, num_active_pushed_streams()); + EXPECT_EQ(1u, num_unclaimed_pushed_streams()); + + // Claim pushed stream from Http2PushPromiseIndex. + const GURL pushed_url(kPushedUrl); + base::WeakPtr<SpdySession> session_with_pushed_stream; + SpdyStreamId pushed_stream_id; + spdy_session_pool_->push_promise_index()->ClaimPushedStream( + key_, pushed_url, &session_with_pushed_stream, &pushed_stream_id); + EXPECT_EQ(session_.get(), session_with_pushed_stream.get()); + EXPECT_EQ(2u, pushed_stream_id); + EXPECT_EQ(0u, num_unclaimed_pushed_streams()); SpdyStream* pushed_stream; - int rv = session_->GetPushedStream(GURL(kPushedUrl), kNoPushedStreamFound, - IDLE, &pushed_stream, NetLogWithSource()); + int rv = session_->GetPushedStream(pushed_url, pushed_stream_id, IDLE, + &pushed_stream, NetLogWithSource()); ASSERT_THAT(rv, IsOk()); ASSERT_TRUE(pushed_stream); test::StreamDelegateCloseOnHeaders delegate2(pushed_stream->GetWeakPtr()); @@ -5584,6 +5603,7 @@ EXPECT_EQ(0u, num_created_streams()); EXPECT_EQ(0u, num_pushed_streams()); EXPECT_EQ(0u, num_active_pushed_streams()); + EXPECT_EQ(0u, num_unclaimed_pushed_streams()); // Read EOF. data.Resume(); @@ -5592,10 +5612,7 @@ EXPECT_TRUE(data.AllReadDataConsumed()); } -// Test GetPushedStream() behavior with |pushed_stream_id| arguments different -// from kNoPushedStreamFound. TEST_F(SpdySessionTest, GetPushedStream) { - const char kPushedUrl[] = "https://www.example.org/a.dat"; SpdyHeaderBlock push_headers; push_headers[":method"] = "GET"; spdy_util_.AddUrlToHeaderBlock(kPushedUrl, &push_headers); @@ -5652,9 +5669,10 @@ // No streams are pushed yet, therefore GetPushedStream() should return an // error. + const GURL pushed_url(kPushedUrl); SpdyStream* pushed_stream; - int rv = session_->GetPushedStream(GURL(kPushedUrl), 2 /* pushed_stream_id */, - IDLE, &pushed_stream, NetLogWithSource()); + int rv = session_->GetPushedStream(pushed_url, 2 /* pushed_stream_id */, IDLE, + &pushed_stream, NetLogWithSource()); EXPECT_THAT(rv, IsError(ERR_SPDY_PUSHED_STREAM_NOT_AVAILABLE)); // Read PUSH_PROMISE. @@ -5664,17 +5682,30 @@ EXPECT_EQ(0u, num_created_streams()); EXPECT_EQ(1u, num_pushed_streams()); EXPECT_EQ(0u, num_active_pushed_streams()); + EXPECT_EQ(1u, num_unclaimed_pushed_streams()); + + // Claim pushed stream from Http2PushPromiseIndex so that GetPushedStream() + // can be called. + base::WeakPtr<SpdySession> session_with_pushed_stream; + SpdyStreamId pushed_stream_id; + spdy_session_pool_->push_promise_index()->ClaimPushedStream( + key_, pushed_url, &session_with_pushed_stream, &pushed_stream_id); + EXPECT_EQ(session_.get(), session_with_pushed_stream.get()); + EXPECT_EQ(2u, pushed_stream_id); + + // Verify that pushed stream is claimed. + EXPECT_EQ(0u, num_unclaimed_pushed_streams()); // GetPushedStream() should return an error if there does not exist a pushed // stream with ID |pushed_stream_id|. - rv = session_->GetPushedStream(GURL(kPushedUrl), 4 /* pushed_stream_id */, - IDLE, &pushed_stream, NetLogWithSource()); + rv = session_->GetPushedStream(pushed_url, 4 /* pushed_stream_id */, IDLE, + &pushed_stream, NetLogWithSource()); EXPECT_THAT(rv, IsError(ERR_SPDY_PUSHED_STREAM_NOT_AVAILABLE)); // GetPushedStream() should return OK and return the pushed stream in // |pushed_stream| outparam if |pushed_stream_id| matches. - rv = session_->GetPushedStream(GURL(kPushedUrl), 2 /* pushed_stream_id */, - IDLE, &pushed_stream, NetLogWithSource()); + rv = session_->GetPushedStream(pushed_url, 2 /* pushed_stream_id */, IDLE, + &pushed_stream, NetLogWithSource()); EXPECT_THAT(rv, IsOk()); ASSERT_TRUE(pushed_stream); test::StreamDelegateCloseOnHeaders delegate2(pushed_stream->GetWeakPtr());
diff --git a/net/spdy/chromium/spdy_stream_unittest.cc b/net/spdy/chromium/spdy_stream_unittest.cc index cf6482d8..d7e864d 100644 --- a/net/spdy/chromium/spdy_stream_unittest.cc +++ b/net/spdy/chromium/spdy_stream_unittest.cc
@@ -23,8 +23,10 @@ #include "net/log/test_net_log_util.h" #include "net/socket/socket_test_util.h" #include "net/spdy/chromium/buffered_spdy_framer.h" +#include "net/spdy/chromium/http2_push_promise_index.h" #include "net/spdy/chromium/spdy_http_utils.h" #include "net/spdy/chromium/spdy_session.h" +#include "net/spdy/chromium/spdy_session_pool.h" #include "net/spdy/chromium/spdy_stream_test_util.h" #include "net/spdy/chromium/spdy_test_util_common.h" #include "net/spdy/core/spdy_protocol.h" @@ -136,6 +138,15 @@ session_deps_.socket_factory->AddSSLSocketDataProvider(&ssl_); } + static size_t num_pushed_streams(base::WeakPtr<SpdySession> session) { + return session->num_pushed_streams_; + } + + static SpdySessionPool* spdy_session_pool( + base::WeakPtr<SpdySession> session) { + return session->pool_; + } + const GURL url_; SpdyTestUtil spdy_util_; SpdySessionDependencies session_deps_; @@ -343,9 +354,18 @@ data.RunUntilPaused(); + const SpdySessionKey key(HostPortPair::FromURL(url_), ProxyServer::Direct(), + PRIVACY_MODE_DISABLED); + base::WeakPtr<SpdySession> session_with_pushed_stream; + SpdyStreamId pushed_stream_id; + spdy_session_pool(session)->push_promise_index()->ClaimPushedStream( + key, GURL(kPushUrl), &session_with_pushed_stream, &pushed_stream_id); + EXPECT_EQ(session.get(), session_with_pushed_stream.get()); + EXPECT_EQ(2u, pushed_stream_id); + SpdyStream* push_stream; - EXPECT_THAT(session->GetPushedStream(GURL(kPushUrl), kNoPushedStreamFound, - IDLE, &push_stream, NetLogWithSource()), + EXPECT_THAT(session->GetPushedStream(GURL(kPushUrl), pushed_stream_id, IDLE, + &push_stream, NetLogWithSource()), IsOk()); ASSERT_TRUE(push_stream); EXPECT_EQ(kPushUrl, push_stream->GetUrlFromHeaders().spec()); @@ -656,11 +676,7 @@ data.RunUntilPaused(); - SpdyStream* push_stream; - EXPECT_THAT(session->GetPushedStream(GURL(kPushUrl), kNoPushedStreamFound, - IDLE, &push_stream, NetLogWithSource()), - IsOk()); - EXPECT_FALSE(push_stream); + EXPECT_EQ(0u, num_pushed_streams(session)); data.Resume();
diff --git a/net/spdy/core/spdy_framer.cc b/net/spdy/core/spdy_framer.cc index 581c2229..eaefdde 100644 --- a/net/spdy/core/spdy_framer.cc +++ b/net/spdy/core/spdy_framer.cc
@@ -4,8 +4,6 @@ #include "net/spdy/core/spdy_framer.h" -#include <string.h> - #include <algorithm> #include <cctype> #include <ios> @@ -191,8 +189,8 @@ size_t bytes_remaining = 0; bytes_remaining = hpack_encoding.size() - std::min(hpack_encoding.size(), - SpdyFramer::kMaxControlFrameSendSize - - builder->length() - padding_payload_len); + kHttp2MaxControlFrameSendSize - builder->length() - + padding_payload_len); bool ret = builder->WriteBytes(&hpack_encoding[0], hpack_encoding.size() - bytes_remaining); if (padding_payload_len > 0) { @@ -203,8 +201,8 @@ // Tack on CONTINUATION frames for the overflow. while (bytes_remaining > 0 && ret) { size_t bytes_to_write = - std::min(bytes_remaining, SpdyFramer::kMaxControlFrameSendSize - - kContinuationFrameMinimumSize); + std::min(bytes_remaining, + kHttp2MaxControlFrameSendSize - kContinuationFrameMinimumSize); // Write CONTINUATION frame prefix. if (bytes_remaining == bytes_to_write) { flags |= end_flag; @@ -278,15 +276,9 @@ } // namespace -// Even though the length field is 24 bits, we keep this 16 kB -// limit on control frame size for legacy reasons and to -// mitigate DOS attacks. -const size_t SpdyFramer::kMaxControlFrameSendSize = - kHttp2DefaultFramePayloadLimit - 1; - SpdyFramer::SpdyFramer(CompressionOption option) : debug_visitor_(nullptr), compression_option_(option) { - static_assert(kMaxControlFrameSendSize <= kHttp2DefaultFrameSizeLimit, + static_assert(kHttp2MaxControlFrameSendSize <= kHttp2DefaultFrameSizeLimit, "Our send limit should be at most our receive limit."); } @@ -313,7 +305,8 @@ const size_t size_without_block = is_first_frame_ ? GetFrameSizeSansBlock() : kContinuationFrameMinimumSize; auto encoding = SpdyMakeUnique<SpdyString>(); - encoder_->Next(kMaxControlFrameSendSize - size_without_block, encoding.get()); + encoder_->Next(kHttp2MaxControlFrameSendSize - size_without_block, + encoding.get()); has_next_frame_ = encoder_->HasNext(); if (framer_->debug_visitor_ != nullptr) { @@ -592,7 +585,7 @@ GetHpackEncoder()->EncodeHeaderSet(headers.header_block(), hpack_encoding); *size = *size + hpack_encoding->size(); - if (*size > kMaxControlFrameSendSize) { + if (*size > kHttp2MaxControlFrameSendSize) { *size = *size + GetNumberRequiredContinuationFrames(*size) * kContinuationFrameMinimumSize; *flags = *flags & ~HEADERS_FLAG_END_HEADERS; @@ -611,7 +604,7 @@ // WritePayloadWithContinuation() will serialize CONTINUATION frames as // necessary. *length_field = - std::min(*length_field, kMaxControlFrameSendSize - kFrameHeaderSize); + std::min(*length_field, kHttp2MaxControlFrameSendSize - kFrameHeaderSize); } SpdySerializedFrame SpdyFramer::SerializeHeaders(const SpdyHeadersIR& headers) { @@ -686,7 +679,7 @@ GetHpackEncoder()->EncodeHeaderSet(push_promise.header_block(), hpack_encoding); *size = *size + hpack_encoding->size(); - if (*size > kMaxControlFrameSendSize) { + if (*size > kHttp2MaxControlFrameSendSize) { *size = *size + GetNumberRequiredContinuationFrames(*size) * kContinuationFrameMinimumSize; *flags = *flags & ~PUSH_PROMISE_FLAG_END_PUSH_PROMISE; @@ -702,7 +695,8 @@ &size); SpdyFrameBuilder builder(size); - size_t length = std::min(size, kMaxControlFrameSendSize) - kFrameHeaderSize; + size_t length = + std::min(size, kHttp2MaxControlFrameSendSize) - kFrameHeaderSize; builder.BeginNewFrame(SpdyFrameType::PUSH_PROMISE, flags, push_promise.stream_id(), length); int padding_payload_len = 0; @@ -1120,7 +1114,8 @@ bool ok = true; SpdyFrameBuilder builder(size, output); - size_t length = std::min(size, kMaxControlFrameSendSize) - kFrameHeaderSize; + size_t length = + std::min(size, kHttp2MaxControlFrameSendSize) - kFrameHeaderSize; ok = builder.BeginNewFrame(SpdyFrameType::PUSH_PROMISE, flags, push_promise.stream_id(), length); @@ -1272,15 +1267,6 @@ return visitor.Result() ? free_bytes_before - output->BytesFree() : 0; } -size_t SpdyFramer::GetNumberRequiredContinuationFrames(size_t size) { - DCHECK_GT(size, SpdyFramer::kMaxControlFrameSendSize); - size_t overflow = size - SpdyFramer::kMaxControlFrameSendSize; - int payload_size = - SpdyFramer::kMaxControlFrameSendSize - kContinuationFrameMinimumSize; - // This is ceiling(overflow/payload_size) using integer arithmetics. - return (overflow - 1) / payload_size + 1; -} - HpackEncoder* SpdyFramer::GetHpackEncoder() { if (hpack_encoder_.get() == nullptr) { hpack_encoder_ = SpdyMakeUnique<HpackEncoder>(ObtainHpackHuffmanTable());
diff --git a/net/spdy/core/spdy_framer.h b/net/spdy/core/spdy_framer.h index 38143205..3b999ab 100644 --- a/net/spdy/core/spdy_framer.h +++ b/net/spdy/core/spdy_framer.h
@@ -72,12 +72,6 @@ // Gets the serialized flags for the given |frame|. static uint8_t GetSerializedFlags(const SpdyFrameIR& frame); - // The maximum size of the control frames that we send, including the size of - // the header. This limit is arbitrary. We can enforce it here or at the - // application layer. We chose the framing layer, but this can be changed (or - // removed) if necessary later down the line. - static const size_t kMaxControlFrameSendSize; - // Serialize a data frame. static SpdySerializedFrame SerializeData(const SpdyDataIR& data_ir); // Serializes the data frame header and optionally padding length fields, @@ -369,8 +363,6 @@ }; private: - static size_t GetNumberRequiredContinuationFrames(size_t size); - void SerializeHeadersBuilderHelper(const SpdyHeadersIR& headers, uint8_t* flags, size_t* size,
diff --git a/net/spdy/core/spdy_framer_test.cc b/net/spdy/core/spdy_framer_test.cc index 9b4387f..c5fad9e 100644 --- a/net/spdy/core/spdy_framer_test.cc +++ b/net/spdy/core/spdy_framer_test.cc
@@ -5,7 +5,6 @@ #include "net/spdy/core/spdy_framer.h" #include <stdlib.h> -#include <string.h> #include <algorithm> #include <limits> @@ -27,6 +26,7 @@ #include "net/spdy/core/spdy_protocol.h" #include "net/spdy/core/spdy_test_utils.h" #include "net/spdy/platform/api/spdy_ptr_util.h" +#include "net/spdy/platform/api/spdy_string.h" #include "net/spdy/platform/api/spdy_string_utils.h" #include "testing/gmock/include/gmock/gmock.h" #include "testing/gtest/include/gtest/gtest.h" @@ -40,7 +40,7 @@ namespace { -const int64_t kSize = 64 * 1024; +const int64_t kSize = 1024 * 1024; char output_buffer[kSize] = ""; // frame_list_char is used to hold frames to be compared with output_buffer. @@ -218,11 +218,6 @@ class SpdyFramerPeer { public: - static size_t GetNumberRequiredContinuationFrames(SpdyFramer* framer, - size_t size) { - return framer->GetNumberRequiredContinuationFrames(size); - } - // TODO(dahollings): Remove these methods when deprecating non-incremental // header serialization path. static std::unique_ptr<SpdyHeadersIR> CloneSpdyHeadersIR( @@ -2418,14 +2413,10 @@ // Regression test for https://crbug.com/464748. TEST_P(SpdyFramerTest, GetNumberRequiredContinuationFrames) { - EXPECT_EQ(1u, SpdyFramerPeer::GetNumberRequiredContinuationFrames( - &framer_, 16383 + 16374)); - EXPECT_EQ(2u, SpdyFramerPeer::GetNumberRequiredContinuationFrames( - &framer_, 16383 + 16374 + 1)); - EXPECT_EQ(2u, SpdyFramerPeer::GetNumberRequiredContinuationFrames( - &framer_, 16383 + 2 * 16374)); - EXPECT_EQ(3u, SpdyFramerPeer::GetNumberRequiredContinuationFrames( - &framer_, 16383 + 2 * 16374 + 1)); + EXPECT_EQ(1u, GetNumberRequiredContinuationFrames(16383 + 16374)); + EXPECT_EQ(2u, GetNumberRequiredContinuationFrames(16383 + 16374 + 1)); + EXPECT_EQ(2u, GetNumberRequiredContinuationFrames(16383 + 2 * 16374)); + EXPECT_EQ(3u, GetNumberRequiredContinuationFrames(16383 + 2 * 16374 + 1)); } TEST_P(SpdyFramerTest, CreateContinuationUncompressed) { @@ -2574,7 +2565,7 @@ SpdyPushPromiseIR push_promise(/* stream_id = */ 42, /* promised_stream_id = */ 57); push_promise.set_padding_len(1); - SpdyString big_value(SpdyFramer::kMaxControlFrameSendSize, 'x'); + SpdyString big_value(kHttp2MaxControlFrameSendSize, 'x'); push_promise.SetHeader("xxx", big_value); SpdySerializedFrame frame(SpdyFramerPeer::SerializePushPromise( &framer, push_promise, use_output_ ? &output_ : nullptr)); @@ -2596,7 +2587,7 @@ // Length of everything listed above except big_value. int len_non_data_payload = 31; - EXPECT_EQ(SpdyFramer::kMaxControlFrameSendSize + len_non_data_payload, + EXPECT_EQ(kHttp2MaxControlFrameSendSize + len_non_data_payload, frame.size()); // Partially compare the PUSH_PROMISE frame against the template. @@ -2607,7 +2598,7 @@ kPartialPushPromiseFrameData, arraysize(kPartialPushPromiseFrameData)); // Compare the CONTINUATION frame against the template. - frame_data += SpdyFramer::kMaxControlFrameSendSize; + frame_data += kHttp2MaxControlFrameSendSize; CompareCharArraysWithHexError( kDescription, frame_data, arraysize(kContinuationFrameData), kContinuationFrameData, arraysize(kContinuationFrameData)); @@ -2763,12 +2754,12 @@ // Exact payload length will change with HPACK, but this should be long // enough to cause an overflow. - const size_t kBigValueSize = SpdyFramer::kMaxControlFrameSendSize; + const size_t kBigValueSize = kHttp2MaxControlFrameSendSize; SpdyString big_value(kBigValueSize, 'x'); headers.SetHeader("aa", big_value); SpdySerializedFrame control_frame(SpdyFramerPeer::SerializeHeaders( &framer, headers, use_output_ ? &output_ : nullptr)); - EXPECT_GT(control_frame.size(), SpdyFramer::kMaxControlFrameSendSize); + EXPECT_GT(control_frame.size(), kHttp2MaxControlFrameSendSize); TestSpdyVisitor visitor(SpdyFramer::DISABLE_COMPRESSION); visitor.SimulateInFramer( @@ -2788,7 +2779,7 @@ // Exact payload length will change with HPACK, but this should be long // enough to cause an overflow. - const size_t kBigValueSize = SpdyFramer::kMaxControlFrameSendSize; + const size_t kBigValueSize = kHttp2MaxControlFrameSendSize; SpdyString big_valuex(kBigValueSize, 'x'); headers->SetHeader("aa", big_valuex); SpdyString big_valuez(kBigValueSize, 'z'); @@ -2799,7 +2790,7 @@ EXPECT_TRUE(frame_it.HasNextFrame()); EXPECT_GT(frame_it.NextFrame(&output_), 0u); SpdySerializedFrame headers_frame(output_.Begin(), output_.Size(), false); - EXPECT_EQ(headers_frame.size(), SpdyFramer::kMaxControlFrameSendSize); + EXPECT_EQ(headers_frame.size(), kHttp2MaxControlFrameSendSize); TestSpdyVisitor visitor(SpdyFramer::DISABLE_COMPRESSION); visitor.SimulateInFramer( @@ -2815,7 +2806,7 @@ EXPECT_TRUE(frame_it.HasNextFrame()); EXPECT_GT(frame_it.NextFrame(&output_), 0u); SpdySerializedFrame first_cont_frame(output_.Begin(), output_.Size(), false); - EXPECT_EQ(first_cont_frame.size(), SpdyFramer::kMaxControlFrameSendSize); + EXPECT_EQ(first_cont_frame.size(), kHttp2MaxControlFrameSendSize); visitor.SimulateInFramer( reinterpret_cast<unsigned char*>(first_cont_frame.data()), @@ -2830,7 +2821,7 @@ EXPECT_TRUE(frame_it.HasNextFrame()); EXPECT_GT(frame_it.NextFrame(&output_), 0u); SpdySerializedFrame second_cont_frame(output_.Begin(), output_.Size(), false); - EXPECT_LT(second_cont_frame.size(), SpdyFramer::kMaxControlFrameSendSize); + EXPECT_LT(second_cont_frame.size(), kHttp2MaxControlFrameSendSize); visitor.SimulateInFramer( reinterpret_cast<unsigned char*>(second_cont_frame.data()), @@ -2853,7 +2844,7 @@ // Exact payload length will change with HPACK, but this should be long // enough to cause an overflow. - const size_t kBigValueSize = SpdyFramer::kMaxControlFrameSendSize; + const size_t kBigValueSize = kHttp2MaxControlFrameSendSize; SpdyString big_valuex(kBigValueSize, 'x'); push_promise->SetHeader("aa", big_valuex); SpdyString big_valuez(kBigValueSize, 'z'); @@ -2866,7 +2857,7 @@ EXPECT_GT(frame_it.NextFrame(&output_), 0u); SpdySerializedFrame push_promise_frame(output_.Begin(), output_.Size(), false); - EXPECT_EQ(push_promise_frame.size(), SpdyFramer::kMaxControlFrameSendSize); + EXPECT_EQ(push_promise_frame.size(), kHttp2MaxControlFrameSendSize); TestSpdyVisitor visitor(SpdyFramer::DISABLE_COMPRESSION); visitor.SimulateInFramer( @@ -2883,7 +2874,7 @@ EXPECT_GT(frame_it.NextFrame(&output_), 0u); SpdySerializedFrame first_cont_frame(output_.Begin(), output_.Size(), false); - EXPECT_EQ(first_cont_frame.size(), SpdyFramer::kMaxControlFrameSendSize); + EXPECT_EQ(first_cont_frame.size(), kHttp2MaxControlFrameSendSize); visitor.SimulateInFramer( reinterpret_cast<unsigned char*>(first_cont_frame.data()), first_cont_frame.size()); @@ -2897,7 +2888,7 @@ output_.Reset(); EXPECT_GT(frame_it.NextFrame(&output_), 0u); SpdySerializedFrame second_cont_frame(output_.Begin(), output_.Size(), false); - EXPECT_LT(second_cont_frame.size(), SpdyFramer::kMaxControlFrameSendSize); + EXPECT_LT(second_cont_frame.size(), kHttp2MaxControlFrameSendSize); visitor.SimulateInFramer( reinterpret_cast<unsigned char*>(second_cont_frame.data()), @@ -2982,12 +2973,12 @@ // Exact payload length will change with HPACK, but this should be long // enough to cause an overflow. - const size_t kBigValueSize = SpdyFramer::kMaxControlFrameSendSize; + const size_t kBigValueSize = kHttp2MaxControlFrameSendSize; SpdyString big_value(kBigValueSize, 'x'); push_promise.SetHeader("aa", big_value); SpdySerializedFrame control_frame(SpdyFramerPeer::SerializePushPromise( &framer, push_promise, use_output_ ? &output_ : nullptr)); - EXPECT_GT(control_frame.size(), SpdyFramer::kMaxControlFrameSendSize); + EXPECT_GT(control_frame.size(), kHttp2MaxControlFrameSendSize); TestSpdyVisitor visitor(SpdyFramer::DISABLE_COMPRESSION); visitor.SimulateInFramer( @@ -4891,6 +4882,90 @@ } } +namespace { +void CheckFrameAndIRSize(SpdyFrameIR* ir, + SpdyFramer* framer, + ArrayOutputBuffer* output_buffer) { + output_buffer->Reset(); + SpdyFrameType type = ir->frame_type(); + size_t ir_size = ir->size(); + framer->SerializeFrame(*ir, output_buffer); + if (type == SpdyFrameType::HEADERS || type == SpdyFrameType::PUSH_PROMISE) { + // For HEADERS and PUSH_PROMISE, the size is an estimate. + EXPECT_GE(ir_size, output_buffer->Size() * 9 / 10); + EXPECT_LT(ir_size, output_buffer->Size() * 11 / 10); + } else { + EXPECT_EQ(ir_size, output_buffer->Size()); + } +} +} // namespace + +TEST_P(SpdyFramerTest, SpdyFrameIRSize) { + SpdyFramer framer(SpdyFramer::DISABLE_COMPRESSION); + + const char bytes[] = "this is a very short data frame"; + SpdyDataIR data_ir(1, SpdyStringPiece(bytes, arraysize(bytes))); + CheckFrameAndIRSize(&data_ir, &framer, &output_); + + SpdyRstStreamIR rst_ir(/* stream_id = */ 1, ERROR_CODE_PROTOCOL_ERROR); + CheckFrameAndIRSize(&rst_ir, &framer, &output_); + + SpdySettingsIR settings_ir; + settings_ir.AddSetting(SETTINGS_HEADER_TABLE_SIZE, 5); + settings_ir.AddSetting(SETTINGS_ENABLE_PUSH, 6); + settings_ir.AddSetting(SETTINGS_MAX_CONCURRENT_STREAMS, 7); + CheckFrameAndIRSize(&settings_ir, &framer, &output_); + + SpdyPingIR ping_ir(42); + CheckFrameAndIRSize(&ping_ir, &framer, &output_); + + SpdyGoAwayIR goaway_ir(97, ERROR_CODE_NO_ERROR, "Goaway description"); + CheckFrameAndIRSize(&goaway_ir, &framer, &output_); + + SpdyHeadersIR headers_ir(1); + headers_ir.SetHeader("alpha", "beta"); + headers_ir.SetHeader("gamma", "charlie"); + headers_ir.SetHeader("cookie", "key1=value1; key2=value2"); + CheckFrameAndIRSize(&headers_ir, &framer, &output_); + + SpdyHeadersIR headers_ir_with_continuation(1); + headers_ir_with_continuation.SetHeader("alpha", SpdyString(100000, 'x')); + headers_ir_with_continuation.SetHeader("beta", SpdyString(100000, 'x')); + headers_ir_with_continuation.SetHeader("cookie", "key1=value1; key2=value2"); + CheckFrameAndIRSize(&headers_ir_with_continuation, &framer, &output_); + + SpdyWindowUpdateIR window_update_ir(4, 1024); + CheckFrameAndIRSize(&window_update_ir, &framer, &output_); + + SpdyPushPromiseIR push_promise_ir(3, 8); + push_promise_ir.SetHeader("alpha", SpdyString(100000, 'x')); + push_promise_ir.SetHeader("beta", SpdyString(100000, 'x')); + push_promise_ir.SetHeader("cookie", "key1=value1; key2=value2"); + CheckFrameAndIRSize(&push_promise_ir, &framer, &output_); + + SpdyAltSvcWireFormat::AlternativeService altsvc1( + "pid1", "host", 443, 5, SpdyAltSvcWireFormat::VersionVector()); + SpdyAltSvcWireFormat::AlternativeService altsvc2( + "p\"=i:d", "h_\\o\"st", 123, 42, SpdyAltSvcWireFormat::VersionVector{24}); + SpdyAltSvcWireFormat::AlternativeServiceVector altsvc_vector; + altsvc_vector.push_back(altsvc1); + altsvc_vector.push_back(altsvc2); + SpdyAltSvcIR altsvc_ir(0); + altsvc_ir.set_origin("o_r|g!n"); + altsvc_ir.add_altsvc(altsvc1); + altsvc_ir.add_altsvc(altsvc2); + CheckFrameAndIRSize(&altsvc_ir, &framer, &output_); + + SpdyPriorityIR priority_ir(3, 1, 256, false); + CheckFrameAndIRSize(&priority_ir, &framer, &output_); + + const char kDescription[] = "Unknown frame"; + const uint8_t kType = 0xaf; + const uint8_t kFlags = 0x11; + SpdyUnknownIR unknown_ir(2, kType, kFlags, kDescription); + CheckFrameAndIRSize(&unknown_ir, &framer, &output_); +} + } // namespace test } // namespace net
diff --git a/net/spdy/core/spdy_protocol.cc b/net/spdy/core/spdy_protocol.cc index 6beb2fa0..3b57e36 100644 --- a/net/spdy/core/spdy_protocol.cc +++ b/net/spdy/core/spdy_protocol.cc
@@ -206,6 +206,15 @@ return "UNKNOWN_ERROR_CODE"; } +size_t GetNumberRequiredContinuationFrames(size_t size) { + DCHECK_GT(size, kHttp2MaxControlFrameSendSize); + size_t overflow = size - kHttp2MaxControlFrameSendSize; + int payload_size = + kHttp2MaxControlFrameSendSize - kContinuationFrameMinimumSize; + // This is ceiling(overflow/payload_size) using integer arithmetics. + return (overflow - 1) / payload_size + 1; +} + const char* const kHttp2Npn = "h2"; const char* const kHttp2AuthorityHeader = ":authority"; @@ -272,7 +281,12 @@ } int SpdyDataIR::flow_control_window_consumed() const { - return padded() ? 1 + padding_payload_len() + data_len() : data_len(); + return padded_ ? 1 + padding_payload_len_ + data_len_ : data_len_; +} + +size_t SpdyDataIR::size() const { + return kFrameHeaderSize + + (padded() ? 1 + padding_payload_len() + data_len() : data_len()); } SpdyRstStreamIR::SpdyRstStreamIR(SpdyStreamId stream_id, @@ -291,6 +305,10 @@ return SpdyFrameType::RST_STREAM; } +size_t SpdyRstStreamIR::size() const { + return kRstStreamFrameSize; +} + SpdySettingsIR::SpdySettingsIR() : is_ack_(false) {} SpdySettingsIR::~SpdySettingsIR() = default; @@ -303,6 +321,10 @@ return SpdyFrameType::SETTINGS; } +size_t SpdySettingsIR::size() const { + return kFrameHeaderSize + values_.size() * kSettingsOneSettingSize; +} + void SpdyPingIR::Visit(SpdyFrameVisitor* visitor) const { return visitor->VisitPing(*this); } @@ -311,6 +333,10 @@ return SpdyFrameType::PING; } +size_t SpdyPingIR::size() const { + return kPingFrameSize; +} + SpdyGoAwayIR::SpdyGoAwayIR(SpdyStreamId last_good_stream_id, SpdyErrorCode error_code, SpdyStringPiece description) @@ -345,6 +371,10 @@ return SpdyFrameType::GOAWAY; } +size_t SpdyGoAwayIR::size() const { + return kGoawayFrameMinimumSize + description_.size(); +} + SpdyContinuationIR::SpdyContinuationIR(SpdyStreamId stream_id) : SpdyFrameIR(stream_id), end_headers_(false) { encoding_ = SpdyMakeUnique<SpdyString>(); @@ -360,6 +390,13 @@ return SpdyFrameType::CONTINUATION; } +size_t SpdyContinuationIR::size() const { + // We don't need to get the size of CONTINUATION frame directly. It is + // calculated in HEADERS or PUSH_PROMISE frame. + SPDY_BUG << "Shouldn't not call size() for CONTINUATION frame."; + return 0; +} + void SpdyHeadersIR::Visit(SpdyFrameVisitor* visitor) const { return visitor->VisitHeaders(*this); } @@ -368,6 +405,29 @@ return SpdyFrameType::HEADERS; } +size_t SpdyHeadersIR::size() const { + size_t size = kHeadersFrameMinimumSize; + + if (padded_) { + // Padding field length. + size += 1; + size += padding_payload_len_; + } + + if (has_priority_) { + size += 5; + } + + // Assume no hpack encoding is applied. + size += header_block().TotalBytesUsed() + + header_block().size() * kPerHeaderHpackOverhead; + if (size > kHttp2MaxControlFrameSendSize) { + size += GetNumberRequiredContinuationFrames(size) * + kContinuationFrameMinimumSize; + } + return size; +} + void SpdyWindowUpdateIR::Visit(SpdyFrameVisitor* visitor) const { return visitor->VisitWindowUpdate(*this); } @@ -376,6 +436,10 @@ return SpdyFrameType::WINDOW_UPDATE; } +size_t SpdyWindowUpdateIR::size() const { + return kWindowUpdateFrameSize; +} + void SpdyPushPromiseIR::Visit(SpdyFrameVisitor* visitor) const { return visitor->VisitPushPromise(*this); } @@ -384,6 +448,23 @@ return SpdyFrameType::PUSH_PROMISE; } +size_t SpdyPushPromiseIR::size() const { + size_t size = kPushPromiseFrameMinimumSize; + + if (padded_) { + // Padding length field. + size += 1; + size += padding_payload_len_; + } + + size += header_block().TotalBytesUsed(); + if (size > kHttp2MaxControlFrameSendSize) { + size += GetNumberRequiredContinuationFrames(size) * + kContinuationFrameMinimumSize; + } + return size; +} + SpdyAltSvcIR::SpdyAltSvcIR(SpdyStreamId stream_id) : SpdyFrameIR(stream_id) {} SpdyAltSvcIR::~SpdyAltSvcIR() = default; @@ -396,6 +477,16 @@ return SpdyFrameType::ALTSVC; } +size_t SpdyAltSvcIR::size() const { + size_t size = kGetAltSvcFrameMinimumSize; + size += origin_.length(); + // TODO(yasong): estimates the size without serializing the vector. + SpdyString str = + SpdyAltSvcWireFormat::SerializeHeaderFieldValue(altsvc_vector_); + size += str.size(); + return size; +} + void SpdyPriorityIR::Visit(SpdyFrameVisitor* visitor) const { return visitor->VisitPriority(*this); } @@ -404,6 +495,10 @@ return SpdyFrameType::PRIORITY; } +size_t SpdyPriorityIR::size() const { + return kPriorityFrameSize; +} + void SpdyUnknownIR::Visit(SpdyFrameVisitor* visitor) const { return visitor->VisitUnknown(*this); } @@ -412,6 +507,10 @@ return static_cast<SpdyFrameType>(type()); } +size_t SpdyUnknownIR::size() const { + return kFrameHeaderSize + payload_.size(); +} + int SpdyUnknownIR::flow_control_window_consumed() const { if (frame_type() == SpdyFrameType::DATA) { return payload_.size();
diff --git a/net/spdy/core/spdy_protocol.h b/net/spdy/core/spdy_protocol.h index 8b806a9a..be15a0a 100644 --- a/net/spdy/core/spdy_protocol.h +++ b/net/spdy/core/spdy_protocol.h
@@ -51,6 +51,12 @@ // the maximum control frame size we accept. const uint32_t kHttp2DefaultFramePayloadLimit = 1 << 14; +// The maximum size of the control frames that we send, including the size of +// the header. This limit is arbitrary. We can enforce it here or at the +// application layer. We chose the framing layer, but this can be changed (or +// removed) if necessary later down the line. +const size_t kHttp2MaxControlFrameSendSize = kHttp2DefaultFramePayloadLimit - 1; + // Number of octets in the frame header. const size_t kFrameHeaderSize = 9; @@ -276,6 +282,8 @@ // RST_STREAM frame has error_code (4 octets) field. const size_t kRstStreamFrameSize = kFrameHeaderSize + 4; const size_t kSettingsFrameMinimumSize = kFrameHeaderSize; +const size_t kSettingsOneSettingSize = + sizeof(uint32_t) + sizeof(SpdySettingsIds); // PUSH_PROMISE frame has promised_stream_id (4 octet) field. const size_t kPushPromiseFrameMinimumSize = kFrameHeaderSize + 4; // PING frame has opaque_bytes (8 octet) field. @@ -300,6 +308,10 @@ const int32_t kInitialSessionWindowSize = 64 * 1024 - 1; // The NPN string for HTTP2, "h2". extern const char* const kHttp2Npn; +// An estimate size of the HPACK overhead for each header field. 1 bytes for +// indexed literal, 1 bytes for key literal and length encoding, and 2 bytes for +// value literal and length encoding. +const size_t kPerHeaderHpackOverhead = 4; // Names of pseudo-headers defined for HTTP/2 requests. SPDY_EXPORT_PRIVATE extern const char* const kHttp2AuthorityHeader; @@ -310,6 +322,8 @@ // Name of pseudo-header defined for HTTP/2 responses. SPDY_EXPORT_PRIVATE extern const char* const kHttp2StatusHeader; +SPDY_EXPORT_PRIVATE size_t GetNumberRequiredContinuationFrames(size_t size); + // Variant type (i.e. tagged union) that is either a SPDY 3.x priority value, // or else an HTTP/2 stream dependency tuple {parent stream ID, weight, // exclusive bit}. Templated to allow for use by QUIC code; SPDY and HTTP/2 @@ -417,6 +431,9 @@ virtual SpdyFrameType frame_type() const = 0; SpdyStreamId stream_id() const { return stream_id_; } virtual bool fin() const; + // Returns an estimate of the size of the serialized frame, without applying + // compression. May not be exact. + virtual size_t size() const = 0; // Returns the number of bytes of flow control window that would be consumed // by this frame if written to the wire. @@ -535,6 +552,8 @@ int flow_control_window_consumed() const override; + size_t size() const override; + private: // Used to store data that this SpdyDataIR should own. std::unique_ptr<SpdyString> data_store_; @@ -561,6 +580,8 @@ SpdyFrameType frame_type() const override; + size_t size() const override; + private: SpdyErrorCode error_code_; @@ -583,6 +604,8 @@ SpdyFrameType frame_type() const override; + size_t size() const override; + private: SettingsMap values_; bool is_ack_; @@ -602,6 +625,8 @@ SpdyFrameType frame_type() const override; + size_t size() const override; + private: SpdyPingId id_; bool is_ack_; @@ -648,6 +673,8 @@ SpdyFrameType frame_type() const override; + size_t size() const override; + private: SpdyStreamId last_good_stream_id_; SpdyErrorCode error_code_; @@ -668,6 +695,8 @@ SpdyFrameType frame_type() const override; + size_t size() const override; + bool has_priority() const { return has_priority_; } void set_has_priority(bool has_priority) { has_priority_ = has_priority; } int weight() const { return weight_; } @@ -714,6 +743,8 @@ SpdyFrameType frame_type() const override; + size_t size() const override; + private: int32_t delta_; @@ -738,6 +769,8 @@ SpdyFrameType frame_type() const override; + size_t size() const override; + bool padded() const { return padded_; } int padding_payload_len() const { return padding_payload_len_; } void set_padding_len(int padding_len) { @@ -772,6 +805,7 @@ void take_encoding(std::unique_ptr<SpdyString> encoding) { encoding_ = std::move(encoding); } + size_t size() const override; private: std::unique_ptr<SpdyString> encoding_; @@ -798,6 +832,8 @@ SpdyFrameType frame_type() const override; + size_t size() const override; + private: SpdyString origin_; SpdyAltSvcWireFormat::AlternativeServiceVector altsvc_vector_; @@ -822,6 +858,8 @@ SpdyFrameType frame_type() const override; + size_t size() const override; + private: SpdyStreamId parent_stream_id_; int weight_; @@ -852,6 +890,8 @@ int flow_control_window_consumed() const override; + size_t size() const override; + protected: // Allows subclasses to overwrite the default length. void set_length(int length) { length_ = length; }
diff --git a/net/test/embedded_test_server/default_handlers.cc b/net/test/embedded_test_server/default_handlers.cc index caf9baa..05aa1037 100644 --- a/net/test/embedded_test_server/default_handlers.cc +++ b/net/test/embedded_test_server/default_handlers.cc
@@ -498,15 +498,16 @@ return std::move(http_response); } -// /server-redirect?URL -// Returns a server-redirect (301) to URL. -std::unique_ptr<HttpResponse> HandleServerRedirect(const HttpRequest& request) { +// /server-redirect?URL (Also /server-redirect-xxx?URL) +// Returns a server redirect to URL. +std::unique_ptr<HttpResponse> HandleServerRedirect(HttpStatusCode redirect_code, + const HttpRequest& request) { GURL request_url = request.GetURL(); std::string dest = net::UnescapeURLComponent(request_url.query(), kUnescapeAll); std::unique_ptr<BasicHttpResponse> http_response(new BasicHttpResponse); - http_response->set_code(HTTP_MOVED_PERMANENTLY); + http_response->set_code(redirect_code); http_response->AddCustomHeader("Location", dest); http_response->set_content_type("text/html"); http_response->set_content(base::StringPrintf( @@ -687,6 +688,8 @@ #define PREFIXED_HANDLER(prefix, handler) \ base::Bind(&HandlePrefixedRequest, prefix, base::Bind(handler)) +#define SERVER_REDIRECT_HANDLER(prefix, handler, status_code) \ + base::Bind(&HandlePrefixedRequest, prefix, base::Bind(handler, status_code)) void RegisterDefaultHandlers(EmbeddedTestServer* server) { server->RegisterDefaultHandler(base::Bind(&HandleDefaultConnect)); @@ -718,8 +721,20 @@ PREFIXED_HANDLER("/auth-basic", &HandleAuthBasic)); server->RegisterDefaultHandler( PREFIXED_HANDLER("/auth-digest", &HandleAuthDigest)); - server->RegisterDefaultHandler( - PREFIXED_HANDLER("/server-redirect", &HandleServerRedirect)); + + server->RegisterDefaultHandler(SERVER_REDIRECT_HANDLER( + "/server-redirect", &HandleServerRedirect, HTTP_MOVED_PERMANENTLY)); + server->RegisterDefaultHandler(SERVER_REDIRECT_HANDLER( + "/server-redirect-301", &HandleServerRedirect, HTTP_MOVED_PERMANENTLY)); + server->RegisterDefaultHandler(SERVER_REDIRECT_HANDLER( + "/server-redirect-302", &HandleServerRedirect, HTTP_FOUND)); + server->RegisterDefaultHandler(SERVER_REDIRECT_HANDLER( + "/server-redirect-303", &HandleServerRedirect, HTTP_SEE_OTHER)); + server->RegisterDefaultHandler(SERVER_REDIRECT_HANDLER( + "/server-redirect-307", &HandleServerRedirect, HTTP_TEMPORARY_REDIRECT)); + server->RegisterDefaultHandler(SERVER_REDIRECT_HANDLER( + "/server-redirect-308", &HandleServerRedirect, HTTP_PERMANENT_REDIRECT)); + server->RegisterDefaultHandler(base::Bind(&HandleCrossSiteRedirect, server)); server->RegisterDefaultHandler( PREFIXED_HANDLER("/client-redirect", &HandleClientRedirect));
diff --git a/remoting/ios/app/client_connection_view_controller.mm b/remoting/ios/app/client_connection_view_controller.mm index 8468a9b..889e1e8 100644 --- a/remoting/ios/app/client_connection_view_controller.mm +++ b/remoting/ios/app/client_connection_view_controller.mm
@@ -557,6 +557,9 @@ case SessionErrorOAuthTokenInvalid: message = l10n_util::GetNSString(IDS_ERROR_OAUTH_TOKEN_INVALID); break; + case SessionErrorThirdPartyAuthNotSupported: + message = l10n_util::GetNSString(IDS_THIRD_PARTY_AUTH_NOT_SUPPORTED); + break; } if (message) { _reconnectView.errorText = message; @@ -614,9 +617,6 @@ messageWithText:l10n_util::GetNSString( IDS_MESSAGE_SESSION_FINISHED)]]; break; - case SessionCancelled: - state = ClientViewClosed; - break; default: LOG(ERROR) << "Unknown State for Session, " << sessionDetails.state; return;
diff --git a/remoting/ios/domain/client_session_details.h b/remoting/ios/domain/client_session_details.h index afb9e0b..8162a8c 100644 --- a/remoting/ios/domain/client_session_details.h +++ b/remoting/ios/domain/client_session_details.h
@@ -20,7 +20,6 @@ SessionConnected, SessionFailed, SessionClosed, - SessionCancelled, }; // Session states that map to |remoting::protocol::ConnectionToHost::Error|. @@ -38,7 +37,10 @@ SessionErrorMaxSessionLength, SessionErrorHostConfigurationError, SessionErrorUnknownError, - SessionErrorOAuthTokenInvalid, // Custom for app. + + // Custom for app. + SessionErrorOAuthTokenInvalid, + SessionErrorThirdPartyAuthNotSupported, }; // The current state of a session and data needed for session context.
diff --git a/remoting/ios/session/remoting_client.mm b/remoting/ios/session/remoting_client.mm index cbf0854..1713039 100644 --- a/remoting/ios/session/remoting_client.mm +++ b/remoting/ios/session/remoting_client.mm
@@ -11,7 +11,6 @@ #include <memory> #import "base/mac/bind_objc_block.h" -#import "ios/third_party/material_components_ios/src/components/Dialogs/src/MaterialDialogs.h" #import "ios/third_party/material_components_ios/src/components/Snackbar/src/MaterialSnackbar.h" #import "remoting/ios/audio/audio_player_ios.h" #import "remoting/ios/display/gl_display_handler.h" @@ -326,12 +325,8 @@ clientId:(NSString*)clientId scope:(NSString*)scope { // Not supported for iOS yet. - _sessionDetails.state = SessionCancelled; - [self disconnectFromHost]; - NSString* message = [NSString - stringWithFormat:@"[ThirdPartyAuth] Unable to authenticate with %@.", - _sessionDetails.hostInfo.hostName]; - [MDCSnackbarManager showMessage:[MDCSnackbarMessage messageWithText:message]]; + _sessionDetails.state = SessionFailed; + _sessionDetails.error = SessionErrorThirdPartyAuthNotSupported; [[NSNotificationCenter defaultCenter] postNotificationName:kHostSessionStatusChanged object:self
diff --git a/remoting/protocol/webrtc_transport.cc b/remoting/protocol/webrtc_transport.cc index 044e5e68..8ff08698 100644 --- a/remoting/protocol/webrtc_transport.cc +++ b/remoting/protocol/webrtc_transport.cc
@@ -210,7 +210,14 @@ peer_connection_ = peer_connection_factory_->CreatePeerConnection( rtc_config, &constraints, std::move(port_allocator), nullptr, this); } + +// TODO(sakal): Remove this ifdef after migration to virtual PeerConnection +// observer is complete. +#ifdef VIRTUAL_PEERCONNECTION_OBSERVER_DESTRUCTOR + ~PeerConnectionWrapper() override { +#else virtual ~PeerConnectionWrapper() { +#endif // PeerConnection creates threads internally, which are stopped when the // connection is closed. Thread.Stop() is a blocking operation. // See crbug.com/660081.
diff --git a/remoting/protocol/webrtc_video_renderer_adapter.h b/remoting/protocol/webrtc_video_renderer_adapter.h index 11b9b55..78ff5e7 100644 --- a/remoting/protocol/webrtc_video_renderer_adapter.h +++ b/remoting/protocol/webrtc_video_renderer_adapter.h
@@ -14,7 +14,7 @@ #include "remoting/protocol/client_video_stats_dispatcher.h" #include "remoting/protocol/video_stats_stub.h" #include "third_party/webrtc/api/mediastreaminterface.h" -#include "third_party/webrtc/media/base/videosinkinterface.h" +#include "third_party/webrtc/api/videosinkinterface.h" namespace base { class SingleThreadTaskRunner;
diff --git a/remoting/resources/remoting_strings.grd b/remoting/resources/remoting_strings.grd index d5e8496..34e6e50e 100644 --- a/remoting/resources/remoting_strings.grd +++ b/remoting/resources/remoting_strings.grd
@@ -638,6 +638,9 @@ <message name="IDS_MOBILE_NETWORK_WARNING" desc="Message shown in an alert dialog that warns the user that they are trying to connect to a device over mobile network."> Data charges may apply when connecting to a device over mobile network. Do you want to continue? </message> + <message name="IDS_THIRD_PARTY_AUTH_NOT_SUPPORTED" desc="Error message shown when the user attempts to connect to a remote device under third party authentication, which is currently unsupported by the client."> + This device is not supported by this client because it requires third party authentication. + </message> <!-- Play Store listings text. These Android-specific strings are not marked with formatter_data="android_java" since they are used only for the Play
diff --git a/sandbox/linux/seccomp-bpf-helpers/syscall_parameters_restrictions.cc b/sandbox/linux/seccomp-bpf-helpers/syscall_parameters_restrictions.cc index 440ef20..ada0b8f2 100644 --- a/sandbox/linux/seccomp-bpf-helpers/syscall_parameters_restrictions.cc +++ b/sandbox/linux/seccomp-bpf-helpers/syscall_parameters_restrictions.cc
@@ -341,8 +341,13 @@ ResultExpr RestrictClockID() { static_assert(4 == sizeof(clockid_t), "clockid_t is not 32bit"); const Arg<clockid_t> clockid(0); - return Switch(clockid) - .CASES(( + + // Clock IDs < 0 are per pid/tid or are clockfds. + const unsigned int kIsPidBit = 1u<<31; + + return + If((clockid & kIsPidBit) == 0, + Switch(clockid).CASES(( #if defined(OS_ANDROID) CLOCK_BOOTTIME, #endif @@ -353,7 +358,12 @@ CLOCK_REALTIME_COARSE, CLOCK_THREAD_CPUTIME_ID), Allow()) - .Default(CrashSIGSYS()); + .Default(CrashSIGSYS())) +#if defined(OS_ANDROID) + // Allow per-pid and per-tid clocks. + .ElseIf((clockid & CPUCLOCK_CLOCK_MASK) != CLOCKFD, Allow()) +#endif + .Else(CrashSIGSYS()); } #if !defined(GRND_NONBLOCK)
diff --git a/sandbox/linux/seccomp-bpf-helpers/syscall_parameters_restrictions_unittests.cc b/sandbox/linux/seccomp-bpf-helpers/syscall_parameters_restrictions_unittests.cc index c068cd2d..b572a61 100644 --- a/sandbox/linux/seccomp-bpf-helpers/syscall_parameters_restrictions_unittests.cc +++ b/sandbox/linux/seccomp-bpf-helpers/syscall_parameters_restrictions_unittests.cc
@@ -86,6 +86,11 @@ CheckClock(CLOCK_REALTIME); CheckClock(CLOCK_REALTIME_COARSE); CheckClock(CLOCK_THREAD_CPUTIME_ID); +#if defined(OS_ANDROID) + clockid_t clock_id; + pthread_getcpuclockid(pthread_self(), &clock_id); + CheckClock(clock_id); +#endif } BPF_DEATH_TEST_C(ParameterRestrictions,
diff --git a/sandbox/linux/system_headers/linux_time.h b/sandbox/linux/system_headers/linux_time.h index e6c8112..8de1cc1 100644 --- a/sandbox/linux/system_headers/linux_time.h +++ b/sandbox/linux/system_headers/linux_time.h
@@ -7,6 +7,14 @@ #include <time.h> +#if !defined(CPUCLOCK_CLOCK_MASK) +#define CPUCLOCK_CLOCK_MASK 3 +#endif + +#if !defined(CLOCKFD) +#define CLOCKFD 3 +#endif + #if !defined(CLOCK_REALTIME_COARSE) #define CLOCK_REALTIME_COARSE 5 #endif
diff --git a/services/metrics/public/cpp/ukm_recorder.h b/services/metrics/public/cpp/ukm_recorder.h index 808148f..093d9f8e 100644 --- a/services/metrics/public/cpp/ukm_recorder.h +++ b/services/metrics/public/cpp/ukm_recorder.h
@@ -50,6 +50,7 @@ class CrossSiteDocumentResourceHandler; class WebContentsImpl; class PluginServiceImpl; +class DownloadUkmHelper; } // namespace content namespace password_manager { @@ -132,6 +133,7 @@ friend blink::Document; friend cc::UkmManager; friend content::CrossSiteDocumentResourceHandler; + friend content::DownloadUkmHelper; friend content::PluginServiceImpl; friend content::WebContentsImpl; friend internal::SourceUrlRecorderWebContentsObserver;
diff --git a/services/viz/privileged/interfaces/compositing/renderer_settings.mojom b/services/viz/privileged/interfaces/compositing/renderer_settings.mojom index 2acfcf2..c2d0d450 100644 --- a/services/viz/privileged/interfaces/compositing/renderer_settings.mojom +++ b/services/viz/privileged/interfaces/compositing/renderer_settings.mojom
@@ -12,7 +12,7 @@ bool finish_rendering_on_resize; bool force_antialiasing; bool force_blending_with_shaders; - bool gl_composited_overlay_candidate_quad_border; + bool tint_gl_composited_content; int32 highp_threshold_min; bool partial_swap_enabled; bool release_overlay_resources_after_gpu_query;
diff --git a/services/viz/privileged/interfaces/compositing/renderer_settings_struct_traits.cc b/services/viz/privileged/interfaces/compositing/renderer_settings_struct_traits.cc index 55d1a594..24ff8ef 100644 --- a/services/viz/privileged/interfaces/compositing/renderer_settings_struct_traits.cc +++ b/services/viz/privileged/interfaces/compositing/renderer_settings_struct_traits.cc
@@ -19,8 +19,7 @@ out->should_clear_root_render_pass = data.should_clear_root_render_pass(); out->release_overlay_resources_after_gpu_query = data.release_overlay_resources_after_gpu_query(); - out->gl_composited_overlay_candidate_quad_border = - data.gl_composited_overlay_candidate_quad_border(); + out->tint_gl_composited_content = data.tint_gl_composited_content(); out->show_overdraw_feedback = data.show_overdraw_feedback(); out->enable_draw_occlusion = data.enable_draw_occlusion(); out->highp_threshold_min = data.highp_threshold_min();
diff --git a/services/viz/privileged/interfaces/compositing/renderer_settings_struct_traits.h b/services/viz/privileged/interfaces/compositing/renderer_settings_struct_traits.h index 8b1c004..c1c5224 100644 --- a/services/viz/privileged/interfaces/compositing/renderer_settings_struct_traits.h +++ b/services/viz/privileged/interfaces/compositing/renderer_settings_struct_traits.h
@@ -47,9 +47,8 @@ return input.release_overlay_resources_after_gpu_query; } - static bool gl_composited_overlay_candidate_quad_border( - const viz::RendererSettings& input) { - return input.gl_composited_overlay_candidate_quad_border; + static bool tint_gl_composited_content(const viz::RendererSettings& input) { + return input.tint_gl_composited_content; } static bool show_overdraw_feedback(const viz::RendererSettings& input) {
diff --git a/services/viz/privileged/interfaces/struct_traits_unittest.cc b/services/viz/privileged/interfaces/struct_traits_unittest.cc index 7f5eeb9..5181b06 100644 --- a/services/viz/privileged/interfaces/struct_traits_unittest.cc +++ b/services/viz/privileged/interfaces/struct_traits_unittest.cc
@@ -37,7 +37,6 @@ input.finish_rendering_on_resize = true; input.should_clear_root_render_pass = false; input.release_overlay_resources_after_gpu_query = true; - input.gl_composited_overlay_candidate_quad_border = true; input.show_overdraw_feedback = true; input.enable_draw_occlusion = true; input.highp_threshold_min = -1; @@ -62,8 +61,8 @@ output.should_clear_root_render_pass); EXPECT_EQ(input.release_overlay_resources_after_gpu_query, output.release_overlay_resources_after_gpu_query); - EXPECT_EQ(input.gl_composited_overlay_candidate_quad_border, - output.gl_composited_overlay_candidate_quad_border); + EXPECT_EQ(input.tint_gl_composited_content, + output.tint_gl_composited_content); EXPECT_EQ(input.show_overdraw_feedback, output.show_overdraw_feedback); EXPECT_EQ(input.enable_draw_occlusion, output.enable_draw_occlusion); EXPECT_EQ(input.highp_threshold_min, output.highp_threshold_min);
diff --git a/testing/buildbot/filters/fuchsia.content_unittests.filter b/testing/buildbot/filters/fuchsia.content_unittests.filter index 19ba29a..aa824ed 100644 --- a/testing/buildbot/filters/fuchsia.content_unittests.filter +++ b/testing/buildbot/filters/fuchsia.content_unittests.filter
@@ -42,8 +42,12 @@ # Flaky: https://crbug.com/776424. -RenderWidgetHostViewAuraOverscrollTest.* -RenderWidgetHostViewAuraWheelScrollLatchingEnabledTest.* +-RenderWidgetHostViewAuraAsyncWheelEventsEnabledTest.* -RenderWidgetHostViewGuestSurfaceTest.TestGuestSurface +# Flaky: https://crbug.com/800415. +-RenderWidgetHostViewAuraTest.CursorVisibilityChange + # Flaky: https://crbug.com/777916. -NotificationDatabaseTest.NotificationIdCorruption
diff --git a/testing/buildbot/filters/mojo.fyi.network_browser_tests.filter b/testing/buildbot/filters/mojo.fyi.network_browser_tests.filter index e39e81a9..262e050 100644 --- a/testing/buildbot/filters/mojo.fyi.network_browser_tests.filter +++ b/testing/buildbot/filters/mojo.fyi.network_browser_tests.filter
@@ -11,17 +11,13 @@ -BrowserNavigatorTest.CloseSingletonTab -BrowserNavigatorTest.Disposition_CurrentTab -BrowserNavigatorTest.NavigateFromPageToOptionsInNewTab -# note: this passes locally but fails on bot. --BrowserTest.CancelBeforeUnloadResetsURL -BrowserTest.InterstitialCancelsGuestViewDialogs -BrowsingDataRemoverBrowserTest.Cache -BrowsingDataRemoverBrowserTest.CookieDeletion --BrowsingDataRemoverTransportSecurityStateBrowserTest.ClearTransportSecurityState -ChromeSecurityExploitBrowserTest.CreateFilesystemURLInExtensionOrigin -ChromeSitePerProcessTest.LaunchExternalProtocolFromSubframe -ContentFaviconDriverTest.ReloadBypassingCache -CredentialManagerBrowserTest.CreatePublicKeyCredentialAlgorithmNotSupported --CredentialManagerBrowserTest.CreatePublicKeyCredentialNotImplemented -CredentialManagerBrowserTest.MojoConnectionRecreatedAfterNavigation -CredentialManagerBrowserTest.StoreInUnloadHandler_CrossSite_OnDemandMojoPipe -CredentialManagerBrowserTest.StoreInUnloadHandler_CrossSite_PreestablishedPipe @@ -29,14 +25,6 @@ -CredentialManagerBrowserTest.StoreInUnloadHandler_SameSite_PreestablishedPipe -CredentialManagerBrowserTest.StoreSavesPSLMatchedCredential -CredentialManagerBrowserTest.UpdatingPSLMatchedCredentialCreatesSecondEntry --CrExtensionsManagerTest.ItemOrder --CrExtensionsManagerTest.UpdateItemData --CrExtensionsServiceTest.ProfileSettings --CrExtensionsServiceTest.ToggleEnable --CrExtensionsServiceTest.ToggleIncognito --CrExtensionsServiceTest.Uninstall --CrExtensionsShortcutTest.Basic --DataProxyScriptBrowserTest.Verify # DeclarativeContentApiTest.EnabledForSplitIncognito is flaky. -DeclarativeContentApiTest.EnabledForSplitIncognito -DeclarativeContentApiTest.UninstallWhileActivePageAction @@ -48,8 +36,6 @@ -DiceBrowserTest.SignoutSecondaryAccount -DiceFixAuthErrorsBrowserTest.ReauthFixAuthError -DiceFixAuthErrorsBrowserTest.SigninAccountMismatch --DiceMigrationBrowserTest.Signin --DiceMigrationBrowserTest.Signout -DicePrepareMigrationBrowserTest.Signin -DicePrepareMigrationBrowserTest.Signout -DicePrepareMigrationChromeSynEndpointBrowserTest.EnableSyncAfterToken @@ -90,8 +76,6 @@ -FeedbackTest.ExtraDiagnostics -FeedbackTest.ShowFeedback -FeedbackTest.ShowLoginFeedback --FileProxyScriptBrowserTest.Verify --FtpProxyScriptBrowserTest.Verify -InProcessBrowserTest.ExternalConnectionFail -InstantThemeTest.ThemeBackgroundAccess -IsolatedAppTest.CookieIsolation @@ -103,7 +87,6 @@ -LaunchWebAuthFlowFunctionTest.UserCloseWindow -LazyBackgroundPageApiTest.NaClInBackgroundPage -LazyBackgroundPageApiTest.NaClInView --LocalNTPJavascriptTest.LoadsIframe -LocalNTPJavascriptTest.SimpleJavascriptTests -LocalNTPVoiceJavascriptTest.MicrophoneTests -LocalNTPVoiceJavascriptTest.SpeechTests @@ -119,9 +102,7 @@ -NewlibPackagedAppTest.NoSocketPermissions -NewlibPackagedAppTest.SocketPermissions -NewlibPackagedAppTest.SuccessfulLoad --OutOfProcessProxyResolverBrowserTest.Verify -PageInfoBubbleViewBrowserTest.SiteSettingsLinkWithNonDefaultPort --PageInfoBubbleViewBrowserTest.SiteSettingsLinkWithSiteDetailsEnabledAndNonDefaultPort -PageLoadMetricsBrowserTest.ChromeErrorPage -PageLoadMetricsBrowserTest.LoadingMetrics -PageLoadMetricsBrowserTest.LoadingMetricsFailed @@ -202,8 +183,6 @@ -WebViewTests/WebViewTest.DownloadCookieIsolation/1 -WebViewTests/WebViewTest.DownloadCookieIsolation_CrossSession/0 -WebViewTests/WebViewTest.DownloadCookieIsolation_CrossSession/1 --WebViewTests/WebViewTest.DownloadPermission/0 --WebViewTests/WebViewTest.DownloadPermission/1 -WebViewTests/WebViewTest.OpenURLFromTab_CurrentTab_Succeed/0 -WebViewTests/WebViewTest.OpenURLFromTab_CurrentTab_Succeed/1 -WebViewTests/WebViewTest.Shim_TestNavigationToExternalProtocol/0 @@ -259,15 +238,12 @@ -PolicyTest.ForceGoogleSafeSearch -ProfileBrowserTest.SendHPKPReport -ProfileBrowserTest.SendHPKPReportServerHangs --SSLUITest.MarkBlobAsNonSecure/0 --SSLUITest.MarkBlobAsNonSecure/1 # Need to add SetRequireCTDelegateForTesting to NetworkContext. -SymantecMessageSSLUITest.ManySubresources -SymantecMessageSSLUITest.PostJune2016 # crbug.com/778793 --PreviewsBrowserTest.NoScriptPreviewsEnabled # Started failing in r514649. -PreviewsNoScriptBrowserTest.NoScriptPreviewsEnabled # Added in r519342. @@ -288,7 +264,6 @@ -SavePageBrowserTest.SaveUnauthorizedResource # crbug.com/779217 The NetworkContext is not created when the network service is enabled. --HotwordInstallerBrowserTest.AbortInstallOnShutdown -SpellingMenuObserverTest.SuggestionsForceTopSeparator # http://crbug.com/783990 @@ -338,9 +313,6 @@ -PrerenderBrowserTest.PrerenderSSLClientCertTopLevel -SSLUITestWithClientCert.TestWSSClientCert -# Started failing after r515789 --SSLUITestCommittedInterstitials.ProceedLinkOverridable - # http://crbug.com/721414 # TODO(rockot): add support for webRequest API. -DeclarativeApiTest.ExtensionLifetimeRulesHandling
diff --git a/testing/buildbot/filters/viz.content_browsertests.filter b/testing/buildbot/filters/viz.content_browsertests.filter index 96ee975..76b6b29e 100644 --- a/testing/buildbot/filters/viz.content_browsertests.filter +++ b/testing/buildbot/filters/viz.content_browsertests.filter
@@ -46,6 +46,8 @@ -SitePerProcessBrowserTest.InputEventRouterGesturePreventDefaultTargetMapTest -SitePerProcessBrowserTest.InputEventRouterGestureTargetMapTest -SitePerProcessBrowserTest.InputEventRouterTouchpadGestureTargetTest +-SitePerProcessBrowserTest.HitTestLayerSquashing +-SitePerProcessBrowserTest.HitTestWatermark -SitePerProcessBrowserTest.HitTestNestedFrames -SitePerProcessBrowserTest.NavigateCrashedSubframeToSameSite -SitePerProcessBrowserTest.NestedSurfaceHitTestTest
diff --git a/third_party/WebKit/LayoutTests/FlagExpectations/enable-blink-features=LayoutNG b/third_party/WebKit/LayoutTests/FlagExpectations/enable-blink-features=LayoutNG index e2d3cb47..4e48e2d 100644 --- a/third_party/WebKit/LayoutTests/FlagExpectations/enable-blink-features=LayoutNG +++ b/third_party/WebKit/LayoutTests/FlagExpectations/enable-blink-features=LayoutNG
@@ -22,9 +22,6 @@ crbug.com/707656 fast/inline-block/14498-positionForCoordinates.html [ Failure ] crbug.com/789878 fast/inline/inline-focus-ring.html [ Failure ] -# Fix only in NGPaint. -crbug.com/591099 fast/text/word-space.html [ Failure ] - # Non-interoperable behavior not worth to fix. crbug.com/591099 fast/text/apply-start-width-after-skipped-text.html [ Skip ] @@ -154,7 +151,7 @@ crbug.com/591099 animations/rotate-transform-equivalent.html [ Failure ] crbug.com/591099 animations/stability/element-animate-float-crash.html [ Failure ] crbug.com/591099 animations/state-at-end-event.html [ Failure ] -crbug.com/591099 animations/timing/timing-model.html [ Pass Timeout ] +crbug.com/591099 animations/timing/timing-model.html [ Timeout ] crbug.com/591099 bindings/blink-in-js-asan-crash.html [ Failure ] crbug.com/591099 compositing/animation/state-at-end-event-transform-layer.html [ Failure ] crbug.com/714962 compositing/background-color/view-blending-base-background.html [ Failure ] @@ -2016,7 +2013,7 @@ crbug.com/591099 editing/selection/extend-selection-bidi.html [ Failure ] crbug.com/591099 editing/selection/extend-selection-character.html [ Timeout ] crbug.com/591099 editing/selection/extend-selection-home-end.html [ Timeout ] -crbug.com/591099 editing/selection/extend-selection-word.html [ Timeout ] +crbug.com/591099 editing/selection/extend-selection-word.html [ Pass Timeout ] crbug.com/714962 editing/selection/extend-to-line-boundary.html [ Failure ] crbug.com/714962 editing/selection/focus-and-display-none.html [ Failure ] crbug.com/591099 editing/selection/focus-body.html [ Failure ] @@ -2149,7 +2146,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 [ Pass Timeout ] +crbug.com/714962 external/wpt/WebCryptoAPI/generateKey/failures_RSA-OAEP.https.worker.html [ 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 ] @@ -2199,9 +2196,9 @@ crbug.com/591099 external/wpt/css/css-backgrounds/scroll-positioned-multiple-background-images.html [ Failure Pass ] crbug.com/714962 external/wpt/css/css-display/display-contents-dynamic-before-after-001.html [ Failure ] crbug.com/714962 external/wpt/css/css-display/display-contents-dynamic-before-after-first-letter-001.html [ Failure ] -crbug.com/591099 external/wpt/css/css-display/display-contents-dynamic-table-001-inline.html [ Failure Pass ] -crbug.com/591099 external/wpt/css/css-display/display-contents-dynamic-table-002-inline.html [ Crash Pass ] +crbug.com/591099 external/wpt/css/css-display/display-contents-dynamic-table-001-inline.html [ Failure ] crbug.com/591099 external/wpt/css/css-display/display-contents-dynamic-table-002-none.html [ Crash ] +crbug.com/591099 external/wpt/css/css-display/display-contents-text-inherit-002.html [ Failure ] crbug.com/591099 external/wpt/css/css-display/display-contents-text-inherit.html [ Pass ] crbug.com/591099 external/wpt/css/css-display/display-flow-root-001.html [ Failure Pass ] crbug.com/591099 external/wpt/css/css-flexbox/percentage-heights-001.html [ Failure ] @@ -2486,7 +2483,7 @@ 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 Pass ] +crbug.com/591099 external/wpt/css/css-tables/table-model-fixup-2.html [ Failure ] crbug.com/714962 external/wpt/css/css-tables/visibility-collapse-colspan-003.html [ Failure ] crbug.com/591099 external/wpt/css/css-tables/visibility-collapse-rowcol-001.html [ Crash ] crbug.com/591099 external/wpt/css/css-tables/visibility-collapse-rowspan-crash.html [ Crash ] @@ -2528,6 +2525,7 @@ crbug.com/591099 external/wpt/css/css-transforms/transform-generated-001.html [ Failure ] crbug.com/591099 external/wpt/css/css-transforms/transform-input-015.html [ Crash ] crbug.com/714962 external/wpt/css/css-transforms/transform-origin-006.html [ Failure ] +crbug.com/591099 external/wpt/css/css-transforms/transform3d-perspective-008.html [ Pass ] crbug.com/591099 external/wpt/css/css-ui/box-sizing-007.html [ Failure ] crbug.com/591099 external/wpt/css/css-ui/box-sizing-008.html [ Failure ] crbug.com/591099 external/wpt/css/css-ui/box-sizing-009.html [ Failure ] @@ -2546,71 +2544,67 @@ crbug.com/714962 external/wpt/css/css-ui/text-overflow-016.html [ Failure ] crbug.com/591099 external/wpt/css/css-ui/text-overflow-022.html [ Failure ] crbug.com/591099 external/wpt/css/css-writing-modes/abs-pos-non-replaced-icb-vlr-003.xht [ Pass ] -crbug.com/591099 external/wpt/css/css-writing-modes/abs-pos-non-replaced-icb-vlr-005.xht [ Pass ] crbug.com/591099 external/wpt/css/css-writing-modes/abs-pos-non-replaced-icb-vlr-011.xht [ Pass ] -crbug.com/591099 external/wpt/css/css-writing-modes/abs-pos-non-replaced-icb-vlr-013.xht [ Pass ] crbug.com/591099 external/wpt/css/css-writing-modes/abs-pos-non-replaced-icb-vlr-033.xht [ Pass ] crbug.com/591099 external/wpt/css/css-writing-modes/abs-pos-non-replaced-icb-vrl-002.xht [ Pass ] -crbug.com/591099 external/wpt/css/css-writing-modes/abs-pos-non-replaced-icb-vrl-004.xht [ Pass ] crbug.com/591099 external/wpt/css/css-writing-modes/abs-pos-non-replaced-icb-vrl-006.xht [ Pass ] crbug.com/591099 external/wpt/css/css-writing-modes/abs-pos-non-replaced-icb-vrl-008.xht [ Pass ] crbug.com/591099 external/wpt/css/css-writing-modes/abs-pos-non-replaced-icb-vrl-010.xht [ Pass ] -crbug.com/591099 external/wpt/css/css-writing-modes/abs-pos-non-replaced-icb-vrl-012.xht [ Pass ] crbug.com/591099 external/wpt/css/css-writing-modes/abs-pos-non-replaced-icb-vrl-014.xht [ Pass ] crbug.com/591099 external/wpt/css/css-writing-modes/abs-pos-non-replaced-icb-vrl-016.xht [ Pass ] crbug.com/591099 external/wpt/css/css-writing-modes/abs-pos-non-replaced-icb-vrl-018.xht [ Pass ] crbug.com/591099 external/wpt/css/css-writing-modes/abs-pos-non-replaced-icb-vrl-020.xht [ Pass ] crbug.com/591099 external/wpt/css/css-writing-modes/abs-pos-non-replaced-icb-vrl-030.xht [ Pass ] -crbug.com/591099 external/wpt/css/css-writing-modes/abs-pos-non-replaced-vlr-003.xht [ Failure Pass ] +crbug.com/591099 external/wpt/css/css-writing-modes/abs-pos-non-replaced-vlr-003.xht [ Failure ] crbug.com/591099 external/wpt/css/css-writing-modes/abs-pos-non-replaced-vlr-005.xht [ Failure Pass ] -crbug.com/714962 external/wpt/css/css-writing-modes/abs-pos-non-replaced-vlr-007.xht [ Failure Pass ] +crbug.com/714962 external/wpt/css/css-writing-modes/abs-pos-non-replaced-vlr-007.xht [ Failure ] crbug.com/714962 external/wpt/css/css-writing-modes/abs-pos-non-replaced-vlr-009.xht [ Failure Pass ] -crbug.com/714962 external/wpt/css/css-writing-modes/abs-pos-non-replaced-vlr-011.xht [ Failure Pass ] +crbug.com/714962 external/wpt/css/css-writing-modes/abs-pos-non-replaced-vlr-011.xht [ Failure ] crbug.com/714962 external/wpt/css/css-writing-modes/abs-pos-non-replaced-vlr-013.xht [ Failure ] -crbug.com/714962 external/wpt/css/css-writing-modes/abs-pos-non-replaced-vlr-015.xht [ Failure Pass ] +crbug.com/714962 external/wpt/css/css-writing-modes/abs-pos-non-replaced-vlr-015.xht [ Failure ] crbug.com/591099 external/wpt/css/css-writing-modes/abs-pos-non-replaced-vlr-017.xht [ Failure ] crbug.com/714962 external/wpt/css/css-writing-modes/abs-pos-non-replaced-vlr-019.xht [ Failure Pass ] crbug.com/714962 external/wpt/css/css-writing-modes/abs-pos-non-replaced-vlr-021.xht [ Failure Pass ] crbug.com/714962 external/wpt/css/css-writing-modes/abs-pos-non-replaced-vlr-023.xht [ Failure Pass ] crbug.com/591099 external/wpt/css/css-writing-modes/abs-pos-non-replaced-vlr-025.xht [ Failure Pass ] crbug.com/714962 external/wpt/css/css-writing-modes/abs-pos-non-replaced-vlr-027.xht [ Failure ] -crbug.com/591099 external/wpt/css/css-writing-modes/abs-pos-non-replaced-vlr-029.xht [ Failure ] +crbug.com/591099 external/wpt/css/css-writing-modes/abs-pos-non-replaced-vlr-029.xht [ Failure Pass ] crbug.com/714962 external/wpt/css/css-writing-modes/abs-pos-non-replaced-vlr-031.xht [ Failure ] -crbug.com/714962 external/wpt/css/css-writing-modes/abs-pos-non-replaced-vlr-033.xht [ Failure Pass ] +crbug.com/714962 external/wpt/css/css-writing-modes/abs-pos-non-replaced-vlr-033.xht [ Failure ] crbug.com/714962 external/wpt/css/css-writing-modes/abs-pos-non-replaced-vlr-035.xht [ Failure ] crbug.com/714962 external/wpt/css/css-writing-modes/abs-pos-non-replaced-vlr-037.xht [ Failure ] crbug.com/714962 external/wpt/css/css-writing-modes/abs-pos-non-replaced-vlr-039.xht [ Failure Pass ] crbug.com/591099 external/wpt/css/css-writing-modes/abs-pos-non-replaced-vlr-041.xht [ Failure ] crbug.com/714962 external/wpt/css/css-writing-modes/abs-pos-non-replaced-vlr-043.xht [ Failure Pass ] -crbug.com/714962 external/wpt/css/css-writing-modes/abs-pos-non-replaced-vlr-045.xht [ Failure Pass ] +crbug.com/714962 external/wpt/css/css-writing-modes/abs-pos-non-replaced-vlr-045.xht [ Failure ] crbug.com/714962 external/wpt/css/css-writing-modes/abs-pos-non-replaced-vlr-047.xht [ Failure Pass ] crbug.com/714962 external/wpt/css/css-writing-modes/abs-pos-non-replaced-vlr-049.xht [ Failure Pass ] -crbug.com/714962 external/wpt/css/css-writing-modes/abs-pos-non-replaced-vlr-051.xht [ Failure Pass ] -crbug.com/591099 external/wpt/css/css-writing-modes/abs-pos-non-replaced-vlr-053.xht [ Failure Pass ] -crbug.com/714962 external/wpt/css/css-writing-modes/abs-pos-non-replaced-vlr-055.xht [ Failure Pass ] +crbug.com/714962 external/wpt/css/css-writing-modes/abs-pos-non-replaced-vlr-051.xht [ Failure ] +crbug.com/591099 external/wpt/css/css-writing-modes/abs-pos-non-replaced-vlr-053.xht [ Failure ] +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 Pass ] -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-059.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 Pass ] crbug.com/591099 external/wpt/css/css-writing-modes/abs-pos-non-replaced-vlr-065.xht [ Failure Pass ] -crbug.com/714962 external/wpt/css/css-writing-modes/abs-pos-non-replaced-vlr-067.xht [ Failure Pass ] -crbug.com/714962 external/wpt/css/css-writing-modes/abs-pos-non-replaced-vlr-069.xht [ Failure Pass ] -crbug.com/591099 external/wpt/css/css-writing-modes/abs-pos-non-replaced-vlr-071.xht [ Failure Pass ] +crbug.com/714962 external/wpt/css/css-writing-modes/abs-pos-non-replaced-vlr-067.xht [ Failure ] +crbug.com/714962 external/wpt/css/css-writing-modes/abs-pos-non-replaced-vlr-069.xht [ Failure ] +crbug.com/591099 external/wpt/css/css-writing-modes/abs-pos-non-replaced-vlr-071.xht [ Failure ] crbug.com/714962 external/wpt/css/css-writing-modes/abs-pos-non-replaced-vlr-073.xht [ Failure Pass ] crbug.com/714962 external/wpt/css/css-writing-modes/abs-pos-non-replaced-vlr-075.xht [ Failure Pass ] crbug.com/591099 external/wpt/css/css-writing-modes/abs-pos-non-replaced-vlr-077.xht [ Failure Pass ] -crbug.com/714962 external/wpt/css/css-writing-modes/abs-pos-non-replaced-vlr-079.xht [ Failure Pass ] -crbug.com/714962 external/wpt/css/css-writing-modes/abs-pos-non-replaced-vlr-081.xht [ Failure Pass ] -crbug.com/714962 external/wpt/css/css-writing-modes/abs-pos-non-replaced-vlr-083.xht [ Failure Pass ] +crbug.com/714962 external/wpt/css/css-writing-modes/abs-pos-non-replaced-vlr-079.xht [ Failure ] +crbug.com/714962 external/wpt/css/css-writing-modes/abs-pos-non-replaced-vlr-081.xht [ Failure ] +crbug.com/714962 external/wpt/css/css-writing-modes/abs-pos-non-replaced-vlr-083.xht [ Failure ] crbug.com/714962 external/wpt/css/css-writing-modes/abs-pos-non-replaced-vlr-085.xht [ Failure Pass ] -crbug.com/714962 external/wpt/css/css-writing-modes/abs-pos-non-replaced-vlr-087.xht [ Failure Pass ] +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 Pass ] -crbug.com/714962 external/wpt/css/css-writing-modes/abs-pos-non-replaced-vlr-093.xht [ Failure Pass ] +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/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-097.xht [ Failure ] crbug.com/714962 external/wpt/css/css-writing-modes/abs-pos-non-replaced-vlr-103.xht [ Failure Pass ] -crbug.com/591099 external/wpt/css/css-writing-modes/abs-pos-non-replaced-vlr-105.xht [ Failure Pass ] +crbug.com/591099 external/wpt/css/css-writing-modes/abs-pos-non-replaced-vlr-105.xht [ Failure ] crbug.com/714962 external/wpt/css/css-writing-modes/abs-pos-non-replaced-vlr-107.xht [ Failure ] crbug.com/591099 external/wpt/css/css-writing-modes/abs-pos-non-replaced-vlr-109.xht [ Failure ] crbug.com/714962 external/wpt/css/css-writing-modes/abs-pos-non-replaced-vlr-111.xht [ Failure ] @@ -2618,22 +2612,22 @@ crbug.com/714962 external/wpt/css/css-writing-modes/abs-pos-non-replaced-vlr-115.xht [ Failure ] crbug.com/714962 external/wpt/css/css-writing-modes/abs-pos-non-replaced-vlr-117.xht [ Failure Pass ] crbug.com/714962 external/wpt/css/css-writing-modes/abs-pos-non-replaced-vlr-119.xht [ Failure Pass ] -crbug.com/591099 external/wpt/css/css-writing-modes/abs-pos-non-replaced-vlr-121.xht [ Failure Pass ] +crbug.com/591099 external/wpt/css/css-writing-modes/abs-pos-non-replaced-vlr-121.xht [ Failure ] crbug.com/714962 external/wpt/css/css-writing-modes/abs-pos-non-replaced-vlr-123.xht [ Failure Pass ] -crbug.com/591099 external/wpt/css/css-writing-modes/abs-pos-non-replaced-vlr-125.xht [ Failure Pass ] +crbug.com/591099 external/wpt/css/css-writing-modes/abs-pos-non-replaced-vlr-125.xht [ Failure ] crbug.com/714962 external/wpt/css/css-writing-modes/abs-pos-non-replaced-vlr-127.xht [ Failure Pass ] crbug.com/714962 external/wpt/css/css-writing-modes/abs-pos-non-replaced-vlr-129.xht [ Failure Pass ] 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 Pass ] +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-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 ] +crbug.com/591099 external/wpt/css/css-writing-modes/abs-pos-non-replaced-vlr-137.xht [ Failure ] +crbug.com/714962 external/wpt/css/css-writing-modes/abs-pos-non-replaced-vlr-139.xht [ Failure ] crbug.com/591099 external/wpt/css/css-writing-modes/abs-pos-non-replaced-vlr-141.xht [ Failure Pass ] -crbug.com/714962 external/wpt/css/css-writing-modes/abs-pos-non-replaced-vlr-143.xht [ Failure Pass ] -crbug.com/714962 external/wpt/css/css-writing-modes/abs-pos-non-replaced-vlr-145.xht [ Failure Pass ] +crbug.com/714962 external/wpt/css/css-writing-modes/abs-pos-non-replaced-vlr-143.xht [ Failure ] +crbug.com/714962 external/wpt/css/css-writing-modes/abs-pos-non-replaced-vlr-145.xht [ Failure ] crbug.com/714962 external/wpt/css/css-writing-modes/abs-pos-non-replaced-vlr-147.xht [ Failure Pass ] crbug.com/714962 external/wpt/css/css-writing-modes/abs-pos-non-replaced-vlr-149.xht [ Failure Pass ] -crbug.com/714962 external/wpt/css/css-writing-modes/abs-pos-non-replaced-vlr-151.xht [ Failure Pass ] +crbug.com/714962 external/wpt/css/css-writing-modes/abs-pos-non-replaced-vlr-151.xht [ Failure ] crbug.com/591099 external/wpt/css/css-writing-modes/abs-pos-non-replaced-vlr-153.xht [ Failure Pass ] crbug.com/714962 external/wpt/css/css-writing-modes/abs-pos-non-replaced-vlr-155.xht [ Failure ] crbug.com/591099 external/wpt/css/css-writing-modes/abs-pos-non-replaced-vlr-157.xht [ Failure Pass ] @@ -2641,46 +2635,46 @@ crbug.com/714962 external/wpt/css/css-writing-modes/abs-pos-non-replaced-vlr-161.xht [ Failure Pass ] crbug.com/714962 external/wpt/css/css-writing-modes/abs-pos-non-replaced-vlr-163.xht [ Failure ] crbug.com/714962 external/wpt/css/css-writing-modes/abs-pos-non-replaced-vlr-165.xht [ Failure Pass ] -crbug.com/714962 external/wpt/css/css-writing-modes/abs-pos-non-replaced-vlr-167.xht [ Failure Pass ] -crbug.com/591099 external/wpt/css/css-writing-modes/abs-pos-non-replaced-vlr-169.xht [ Failure Pass ] -crbug.com/714962 external/wpt/css/css-writing-modes/abs-pos-non-replaced-vlr-171.xht [ Failure Pass ] +crbug.com/714962 external/wpt/css/css-writing-modes/abs-pos-non-replaced-vlr-167.xht [ Failure ] +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 Pass ] +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-177.xht [ Failure Pass ] -crbug.com/714962 external/wpt/css/css-writing-modes/abs-pos-non-replaced-vlr-179.xht [ Failure Pass ] -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-179.xht [ Failure ] +crbug.com/591099 external/wpt/css/css-writing-modes/abs-pos-non-replaced-vlr-181.xht [ Failure Pass ] crbug.com/714962 external/wpt/css/css-writing-modes/abs-pos-non-replaced-vlr-183.xht [ Failure Pass ] crbug.com/591099 external/wpt/css/css-writing-modes/abs-pos-non-replaced-vlr-185.xht [ Failure Pass ] 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 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-191.xht [ Failure ] crbug.com/714962 external/wpt/css/css-writing-modes/abs-pos-non-replaced-vlr-193.xht [ Failure Pass ] -crbug.com/714962 external/wpt/css/css-writing-modes/abs-pos-non-replaced-vlr-195.xht [ Failure Pass ] -crbug.com/714962 external/wpt/css/css-writing-modes/abs-pos-non-replaced-vlr-197.xht [ Failure Pass ] +crbug.com/714962 external/wpt/css/css-writing-modes/abs-pos-non-replaced-vlr-195.xht [ Failure ] +crbug.com/714962 external/wpt/css/css-writing-modes/abs-pos-non-replaced-vlr-197.xht [ Failure ] crbug.com/714962 external/wpt/css/css-writing-modes/abs-pos-non-replaced-vlr-199.xht [ Failure Pass ] -crbug.com/591099 external/wpt/css/css-writing-modes/abs-pos-non-replaced-vlr-201.xht [ Failure Pass ] -crbug.com/714962 external/wpt/css/css-writing-modes/abs-pos-non-replaced-vlr-203.xht [ Failure Pass ] -crbug.com/591099 external/wpt/css/css-writing-modes/abs-pos-non-replaced-vlr-205.xht [ Failure Pass ] -crbug.com/714962 external/wpt/css/css-writing-modes/abs-pos-non-replaced-vlr-207.xht [ Failure Pass ] +crbug.com/591099 external/wpt/css/css-writing-modes/abs-pos-non-replaced-vlr-201.xht [ Failure ] +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 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 Pass ] +crbug.com/714962 external/wpt/css/css-writing-modes/abs-pos-non-replaced-vlr-215.xht [ Failure ] crbug.com/591099 external/wpt/css/css-writing-modes/abs-pos-non-replaced-vlr-217.xht [ Failure Pass ] crbug.com/714962 external/wpt/css/css-writing-modes/abs-pos-non-replaced-vlr-219.xht [ Failure ] crbug.com/591099 external/wpt/css/css-writing-modes/abs-pos-non-replaced-vlr-221.xht [ Failure ] crbug.com/714962 external/wpt/css/css-writing-modes/abs-pos-non-replaced-vlr-223.xht [ Failure Pass ] -crbug.com/591099 external/wpt/css/css-writing-modes/abs-pos-non-replaced-vlr-225.xht [ Failure Pass ] -crbug.com/714962 external/wpt/css/css-writing-modes/abs-pos-non-replaced-vlr-227.xht [ Failure Pass ] +crbug.com/591099 external/wpt/css/css-writing-modes/abs-pos-non-replaced-vlr-225.xht [ Failure ] +crbug.com/714962 external/wpt/css/css-writing-modes/abs-pos-non-replaced-vlr-227.xht [ Failure ] crbug.com/591099 external/wpt/css/css-writing-modes/abs-pos-non-replaced-vlr-229.xht [ Failure Pass ] crbug.com/714962 external/wpt/css/css-writing-modes/abs-pos-non-replaced-vrl-002.xht [ Failure ] -crbug.com/591099 external/wpt/css/css-writing-modes/abs-pos-non-replaced-vrl-004.xht [ Failure Pass ] +crbug.com/591099 external/wpt/css/css-writing-modes/abs-pos-non-replaced-vrl-004.xht [ Failure ] crbug.com/714962 external/wpt/css/css-writing-modes/abs-pos-non-replaced-vrl-006.xht [ Failure ] crbug.com/714962 external/wpt/css/css-writing-modes/abs-pos-non-replaced-vrl-008.xht [ Failure ] -crbug.com/591099 external/wpt/css/css-writing-modes/abs-pos-non-replaced-vrl-010.xht [ Failure Pass ] +crbug.com/591099 external/wpt/css/css-writing-modes/abs-pos-non-replaced-vrl-010.xht [ Failure ] crbug.com/714962 external/wpt/css/css-writing-modes/abs-pos-non-replaced-vrl-012.xht [ Failure ] crbug.com/714962 external/wpt/css/css-writing-modes/abs-pos-non-replaced-vrl-014.xht [ Failure ] -crbug.com/591099 external/wpt/css/css-writing-modes/abs-pos-non-replaced-vrl-016.xht [ Failure Pass ] +crbug.com/591099 external/wpt/css/css-writing-modes/abs-pos-non-replaced-vrl-016.xht [ Failure ] crbug.com/714962 external/wpt/css/css-writing-modes/abs-pos-non-replaced-vrl-018.xht [ Failure ] crbug.com/714962 external/wpt/css/css-writing-modes/abs-pos-non-replaced-vrl-020.xht [ Failure ] crbug.com/714962 external/wpt/css/css-writing-modes/abs-pos-non-replaced-vrl-022.xht [ Failure Pass ] @@ -2692,10 +2686,10 @@ crbug.com/591099 external/wpt/css/css-writing-modes/abs-pos-non-replaced-vrl-034.xht [ Failure Pass ] crbug.com/714962 external/wpt/css/css-writing-modes/abs-pos-non-replaced-vrl-036.xht [ Failure ] crbug.com/714962 external/wpt/css/css-writing-modes/abs-pos-non-replaced-vrl-038.xht [ Failure ] -crbug.com/591099 external/wpt/css/css-writing-modes/abs-pos-non-replaced-vrl-040.xht [ Failure Pass ] +crbug.com/591099 external/wpt/css/css-writing-modes/abs-pos-non-replaced-vrl-040.xht [ Failure ] crbug.com/714962 external/wpt/css/css-writing-modes/abs-pos-non-replaced-vrl-042.xht [ Failure ] crbug.com/714962 external/wpt/css/css-writing-modes/abs-pos-non-replaced-vrl-044.xht [ Failure ] -crbug.com/714962 external/wpt/css/css-writing-modes/abs-pos-non-replaced-vrl-046.xht [ Failure Pass ] +crbug.com/714962 external/wpt/css/css-writing-modes/abs-pos-non-replaced-vrl-046.xht [ Failure ] crbug.com/714962 external/wpt/css/css-writing-modes/abs-pos-non-replaced-vrl-048.xht [ Failure ] crbug.com/714962 external/wpt/css/css-writing-modes/abs-pos-non-replaced-vrl-050.xht [ Failure ] crbug.com/591099 external/wpt/css/css-writing-modes/abs-pos-non-replaced-vrl-052.xht [ Failure ] @@ -2703,11 +2697,11 @@ crbug.com/714962 external/wpt/css/css-writing-modes/abs-pos-non-replaced-vrl-056.xht [ Failure ] crbug.com/714962 external/wpt/css/css-writing-modes/abs-pos-non-replaced-vrl-058.xht [ Failure Pass ] crbug.com/714962 external/wpt/css/css-writing-modes/abs-pos-non-replaced-vrl-060.xht [ Failure ] -crbug.com/714962 external/wpt/css/css-writing-modes/abs-pos-non-replaced-vrl-062.xht [ Failure Pass ] +crbug.com/714962 external/wpt/css/css-writing-modes/abs-pos-non-replaced-vrl-062.xht [ Failure ] crbug.com/591099 external/wpt/css/css-writing-modes/abs-pos-non-replaced-vrl-064.xht [ Failure Pass ] crbug.com/714962 external/wpt/css/css-writing-modes/abs-pos-non-replaced-vrl-066.xht [ Failure ] crbug.com/714962 external/wpt/css/css-writing-modes/abs-pos-non-replaced-vrl-068.xht [ Failure Pass ] -crbug.com/714962 external/wpt/css/css-writing-modes/abs-pos-non-replaced-vrl-070.xht [ Failure Pass ] +crbug.com/714962 external/wpt/css/css-writing-modes/abs-pos-non-replaced-vrl-070.xht [ Failure ] crbug.com/714962 external/wpt/css/css-writing-modes/abs-pos-non-replaced-vrl-072.xht [ Failure ] crbug.com/714962 external/wpt/css/css-writing-modes/abs-pos-non-replaced-vrl-074.xht [ Failure ] crbug.com/591099 external/wpt/css/css-writing-modes/abs-pos-non-replaced-vrl-076.xht [ Failure ] @@ -2719,14 +2713,14 @@ crbug.com/591099 external/wpt/css/css-writing-modes/abs-pos-non-replaced-vrl-088.xht [ Failure Pass ] crbug.com/714962 external/wpt/css/css-writing-modes/abs-pos-non-replaced-vrl-090.xht [ Failure ] crbug.com/714962 external/wpt/css/css-writing-modes/abs-pos-non-replaced-vrl-092.xht [ Failure ] -crbug.com/714962 external/wpt/css/css-writing-modes/abs-pos-non-replaced-vrl-094.xht [ Failure Pass ] +crbug.com/714962 external/wpt/css/css-writing-modes/abs-pos-non-replaced-vrl-094.xht [ Failure ] crbug.com/714962 external/wpt/css/css-writing-modes/abs-pos-non-replaced-vrl-096.xht [ Failure ] crbug.com/714962 external/wpt/css/css-writing-modes/abs-pos-non-replaced-vrl-102.xht [ Failure ] crbug.com/591099 external/wpt/css/css-writing-modes/abs-pos-non-replaced-vrl-104.xht [ Failure Pass ] crbug.com/714962 external/wpt/css/css-writing-modes/abs-pos-non-replaced-vrl-106.xht [ Failure ] crbug.com/591099 external/wpt/css/css-writing-modes/abs-pos-non-replaced-vrl-108.xht [ Failure ] crbug.com/714962 external/wpt/css/css-writing-modes/abs-pos-non-replaced-vrl-110.xht [ Failure ] -crbug.com/591099 external/wpt/css/css-writing-modes/abs-pos-non-replaced-vrl-112.xht [ Failure Pass ] +crbug.com/591099 external/wpt/css/css-writing-modes/abs-pos-non-replaced-vrl-112.xht [ Failure ] crbug.com/714962 external/wpt/css/css-writing-modes/abs-pos-non-replaced-vrl-114.xht [ Failure ] crbug.com/591099 external/wpt/css/css-writing-modes/abs-pos-non-replaced-vrl-116.xht [ Failure ] crbug.com/714962 external/wpt/css/css-writing-modes/abs-pos-non-replaced-vrl-118.xht [ Failure ] @@ -2734,7 +2728,7 @@ crbug.com/714962 external/wpt/css/css-writing-modes/abs-pos-non-replaced-vrl-122.xht [ Failure ] crbug.com/591099 external/wpt/css/css-writing-modes/abs-pos-non-replaced-vrl-124.xht [ Failure ] crbug.com/714962 external/wpt/css/css-writing-modes/abs-pos-non-replaced-vrl-126.xht [ Failure ] -crbug.com/591099 external/wpt/css/css-writing-modes/abs-pos-non-replaced-vrl-128.xht [ Failure Pass ] +crbug.com/591099 external/wpt/css/css-writing-modes/abs-pos-non-replaced-vrl-128.xht [ Failure ] crbug.com/714962 external/wpt/css/css-writing-modes/abs-pos-non-replaced-vrl-130.xht [ Failure ] crbug.com/714962 external/wpt/css/css-writing-modes/abs-pos-non-replaced-vrl-132.xht [ Failure ] crbug.com/714962 external/wpt/css/css-writing-modes/abs-pos-non-replaced-vrl-134.xht [ Failure ] @@ -2742,31 +2736,31 @@ crbug.com/714962 external/wpt/css/css-writing-modes/abs-pos-non-replaced-vrl-138.xht [ Failure ] crbug.com/591099 external/wpt/css/css-writing-modes/abs-pos-non-replaced-vrl-140.xht [ Failure ] crbug.com/714962 external/wpt/css/css-writing-modes/abs-pos-non-replaced-vrl-142.xht [ Failure ] -crbug.com/591099 external/wpt/css/css-writing-modes/abs-pos-non-replaced-vrl-144.xht [ Failure Pass ] +crbug.com/591099 external/wpt/css/css-writing-modes/abs-pos-non-replaced-vrl-144.xht [ Failure ] crbug.com/714962 external/wpt/css/css-writing-modes/abs-pos-non-replaced-vrl-146.xht [ Failure ] crbug.com/591099 external/wpt/css/css-writing-modes/abs-pos-non-replaced-vrl-148.xht [ Failure Pass ] crbug.com/714962 external/wpt/css/css-writing-modes/abs-pos-non-replaced-vrl-150.xht [ Failure ] -crbug.com/714962 external/wpt/css/css-writing-modes/abs-pos-non-replaced-vrl-152.xht [ Failure Pass ] +crbug.com/714962 external/wpt/css/css-writing-modes/abs-pos-non-replaced-vrl-152.xht [ Failure ] crbug.com/714962 external/wpt/css/css-writing-modes/abs-pos-non-replaced-vrl-154.xht [ Failure ] crbug.com/591099 external/wpt/css/css-writing-modes/abs-pos-non-replaced-vrl-156.xht [ Failure ] crbug.com/714962 external/wpt/css/css-writing-modes/abs-pos-non-replaced-vrl-158.xht [ Failure ] -crbug.com/591099 external/wpt/css/css-writing-modes/abs-pos-non-replaced-vrl-160.xht [ Failure Pass ] +crbug.com/591099 external/wpt/css/css-writing-modes/abs-pos-non-replaced-vrl-160.xht [ Failure ] crbug.com/714962 external/wpt/css/css-writing-modes/abs-pos-non-replaced-vrl-162.xht [ Failure ] crbug.com/714962 external/wpt/css/css-writing-modes/abs-pos-non-replaced-vrl-164.xht [ Failure ] -crbug.com/714962 external/wpt/css/css-writing-modes/abs-pos-non-replaced-vrl-166.xht [ Failure Pass ] +crbug.com/714962 external/wpt/css/css-writing-modes/abs-pos-non-replaced-vrl-166.xht [ Failure ] crbug.com/714962 external/wpt/css/css-writing-modes/abs-pos-non-replaced-vrl-168.xht [ Failure ] crbug.com/714962 external/wpt/css/css-writing-modes/abs-pos-non-replaced-vrl-170.xht [ Failure ] crbug.com/591099 external/wpt/css/css-writing-modes/abs-pos-non-replaced-vrl-172.xht [ Failure ] crbug.com/714962 external/wpt/css/css-writing-modes/abs-pos-non-replaced-vrl-174.xht [ Failure Pass ] 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 Pass ] -crbug.com/714962 external/wpt/css/css-writing-modes/abs-pos-non-replaced-vrl-184.xht [ Failure Pass ] +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 Pass ] +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 Pass ] -crbug.com/591099 external/wpt/css/css-writing-modes/abs-pos-non-replaced-vrl-192.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 Pass ] crbug.com/714962 external/wpt/css/css-writing-modes/abs-pos-non-replaced-vrl-198.xht [ Failure ] @@ -2800,20 +2794,20 @@ crbug.com/591099 external/wpt/css/css-writing-modes/clearance-calculations-vrl-006.xht [ Failure ] crbug.com/714962 external/wpt/css/css-writing-modes/clearance-calculations-vrl-008.xht [ Failure ] crbug.com/591099 external/wpt/css/css-writing-modes/different-block-flow-dir-002.xht [ Crash ] -crbug.com/714962 external/wpt/css/css-writing-modes/direction-vlr-003.xht [ Failure Pass ] -crbug.com/714962 external/wpt/css/css-writing-modes/direction-vlr-005.xht [ Failure Pass ] -crbug.com/714962 external/wpt/css/css-writing-modes/direction-vrl-002.xht [ Failure Pass ] +crbug.com/714962 external/wpt/css/css-writing-modes/direction-vlr-003.xht [ Failure ] +crbug.com/714962 external/wpt/css/css-writing-modes/direction-vlr-005.xht [ Failure ] +crbug.com/714962 external/wpt/css/css-writing-modes/direction-vrl-002.xht [ Failure ] crbug.com/714962 external/wpt/css/css-writing-modes/direction-vrl-004.xht [ Failure ] crbug.com/591099 external/wpt/css/css-writing-modes/float-contiguous-vrl-002.xht [ Failure ] crbug.com/591099 external/wpt/css/css-writing-modes/float-contiguous-vrl-004.xht [ Failure ] 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 Pass ] +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-007.xht [ Failure Pass ] 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 Pass ] -crbug.com/591099 external/wpt/css/css-writing-modes/float-vrl-006.xht [ Failure Pass ] +crbug.com/591099 external/wpt/css/css-writing-modes/float-vrl-006.xht [ Failure ] 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 ] crbug.com/591099 external/wpt/css/css-writing-modes/horizontal-rule-vrl-002.xht [ Failure ] @@ -2887,12 +2881,12 @@ crbug.com/714962 external/wpt/css/css-writing-modes/text-align-vlr-005.xht [ Failure Pass ] crbug.com/714962 external/wpt/css/css-writing-modes/text-align-vlr-007.xht [ Failure Pass ] crbug.com/714962 external/wpt/css/css-writing-modes/text-align-vlr-009.xht [ Failure Pass ] -crbug.com/591099 external/wpt/css/css-writing-modes/text-align-vlr-011.xht [ Failure Pass ] -crbug.com/714962 external/wpt/css/css-writing-modes/text-align-vlr-013.xht [ Failure Pass ] +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 ] 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 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-vlr-017.xht [ Failure ] +crbug.com/714962 external/wpt/css/css-writing-modes/text-align-vlr-019.xht [ Failure ] +crbug.com/714962 external/wpt/css/css-writing-modes/text-align-vrl-002.xht [ Failure ] 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 Pass ] crbug.com/714962 external/wpt/css/css-writing-modes/text-align-vrl-008.xht [ Failure Pass ] @@ -2905,12 +2899,12 @@ crbug.com/591099 external/wpt/css/css-writing-modes/text-baseline-vrl-006.xht [ Failure ] crbug.com/591099 external/wpt/css/css-writing-modes/text-combine-upright-decorations-001.html [ Failure ] crbug.com/591099 external/wpt/css/css-writing-modes/text-combine-upright-layout-rules-001.html [ Failure ] -crbug.com/714962 external/wpt/css/css-writing-modes/text-indent-vlr-003.xht [ Failure Pass ] -crbug.com/714962 external/wpt/css/css-writing-modes/text-indent-vlr-005.xht [ Failure ] +crbug.com/714962 external/wpt/css/css-writing-modes/text-indent-vlr-003.xht [ Failure ] +crbug.com/714962 external/wpt/css/css-writing-modes/text-indent-vlr-005.xht [ Failure Pass ] crbug.com/714962 external/wpt/css/css-writing-modes/text-indent-vlr-011.xht [ Failure ] -crbug.com/714962 external/wpt/css/css-writing-modes/text-indent-vlr-013.xht [ Failure ] +crbug.com/714962 external/wpt/css/css-writing-modes/text-indent-vlr-013.xht [ Failure Pass ] crbug.com/591099 external/wpt/css/css-writing-modes/text-indent-vrl-002.xht [ Failure ] -crbug.com/591099 external/wpt/css/css-writing-modes/text-indent-vrl-004.xht [ Failure ] +crbug.com/591099 external/wpt/css/css-writing-modes/text-indent-vrl-004.xht [ Failure Pass ] crbug.com/591099 external/wpt/css/css-writing-modes/text-indent-vrl-006.xht [ Failure ] crbug.com/591099 external/wpt/css/css-writing-modes/text-indent-vrl-008.xht [ Failure ] crbug.com/591099 external/wpt/css/css-writing-modes/text-indent-vrl-010.xht [ Failure ] @@ -2954,13 +2948,13 @@ 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 [ Pass Timeout ] -crbug.com/591099 external/wpt/css/geometry/interfaces.worker.html [ Pass Timeout ] +crbug.com/591099 external/wpt/css/geometry/interfaces.worker.html [ 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 ] crbug.com/714962 external/wpt/css/selectors/focus-within-007.html [ Failure ] crbug.com/714962 external/wpt/css/selectors/focus-within-008.html [ Failure ] crbug.com/591099 external/wpt/css/vendor-imports/mozilla/mozilla-central-reftests/flexbox/flexbox-align-content-vert-001a.xhtml [ Failure ] -crbug.com/591099 external/wpt/css/vendor-imports/mozilla/mozilla-central-reftests/flexbox/flexbox-baseline-multi-item-vert-001b.html [ Failure Pass ] +crbug.com/591099 external/wpt/css/vendor-imports/mozilla/mozilla-central-reftests/flexbox/flexbox-baseline-multi-item-vert-001b.html [ Failure ] crbug.com/714962 external/wpt/css/vendor-imports/mozilla/mozilla-central-reftests/flexbox/flexbox-basic-fieldset-horiz-001.xhtml [ Failure ] crbug.com/714962 external/wpt/css/vendor-imports/mozilla/mozilla-central-reftests/flexbox/flexbox-basic-img-horiz-001.xhtml [ Failure ] crbug.com/714962 external/wpt/css/vendor-imports/mozilla/mozilla-central-reftests/flexbox/flexbox-basic-textarea-horiz-001.xhtml [ Failure ] @@ -3007,7 +3001,7 @@ crbug.com/591099 external/wpt/editing/run/forecolor.html [ Timeout ] crbug.com/591099 external/wpt/editing/run/formatblock.html [ Timeout ] crbug.com/591099 external/wpt/editing/run/forwarddelete.html [ Timeout ] -crbug.com/591099 external/wpt/editing/run/hilitecolor.html [ Pass Timeout ] +crbug.com/591099 external/wpt/editing/run/hilitecolor.html [ Timeout ] crbug.com/591099 external/wpt/editing/run/indent.html [ Timeout ] crbug.com/591099 external/wpt/editing/run/inserthorizontalrule.html [ Timeout ] crbug.com/591099 external/wpt/editing/run/inserthtml.html [ Timeout ] @@ -3026,7 +3020,7 @@ crbug.com/591099 external/wpt/editing/run/removeformat.html [ Timeout ] crbug.com/591099 external/wpt/editing/run/strikethrough.html [ Timeout ] crbug.com/591099 external/wpt/editing/run/subscript.html [ Pass Timeout ] -crbug.com/591099 external/wpt/editing/run/superscript.html [ Pass Timeout ] +crbug.com/591099 external/wpt/editing/run/superscript.html [ Timeout ] crbug.com/591099 external/wpt/editing/run/underline.html [ Timeout ] crbug.com/591099 external/wpt/encoding/api-invalid-label.html [ Timeout ] crbug.com/591099 external/wpt/encoding/legacy-mb-japanese/euc-jp/eucjp-decode-cseucpkdfmtjapanese.html [ Timeout ] @@ -3136,11 +3130,11 @@ crbug.com/591099 external/wpt/html/dom/documents/resource-metadata-management/document-lastModified-01.html [ Pass ] crbug.com/591099 external/wpt/html/dom/interfaces.html [ Timeout ] crbug.com/591099 external/wpt/html/editing/focus/tabindex-focus-flag.html [ Crash ] -crbug.com/626703 external/wpt/html/form-elements/the-textarea-element/multiline-placeholder-crlf.html [ Failure ] +crbug.com/626703 external/wpt/html/form-elements/the-textarea-element/multiline-placeholder-crlf.html [ Failure Pass ] crbug.com/591099 external/wpt/html/infrastructure/safe-passing-of-structured-data/shared-array-buffers/window-messagechannel-success.html [ Pass ] crbug.com/591099 external/wpt/html/infrastructure/urls/resolving-urls/query-encoding/utf-16be.html [ Timeout ] crbug.com/591099 external/wpt/html/infrastructure/urls/resolving-urls/query-encoding/utf-16le.html [ Timeout ] -crbug.com/591099 external/wpt/html/infrastructure/urls/resolving-urls/query-encoding/utf-8.html [ Crash Timeout ] +crbug.com/591099 external/wpt/html/infrastructure/urls/resolving-urls/query-encoding/utf-8.html [ Timeout ] crbug.com/591099 external/wpt/html/infrastructure/urls/resolving-urls/query-encoding/windows-1251.html [ Timeout ] crbug.com/591099 external/wpt/html/infrastructure/urls/resolving-urls/query-encoding/windows-1252.html [ Timeout ] crbug.com/591099 external/wpt/html/rendering/non-replaced-elements/flow-content-0/dialog.html [ Crash ] @@ -3149,7 +3143,7 @@ crbug.com/714962 external/wpt/html/rendering/non-replaced-elements/the-fieldset-element-0/min-width-not-important.html [ Failure ] crbug.com/591099 external/wpt/html/rendering/replaced-elements/svg-embedded-sizing/svg-in-img-auto.html [ Failure ] crbug.com/591099 external/wpt/html/rendering/replaced-elements/svg-embedded-sizing/svg-in-img-percentage.html [ Failure ] -crbug.com/591099 external/wpt/html/rendering/replaced-elements/svg-inline-sizing/svg-inline.html [ Failure Timeout ] +crbug.com/591099 external/wpt/html/rendering/replaced-elements/svg-inline-sizing/svg-inline.html [ Timeout ] crbug.com/714962 external/wpt/html/rendering/the-css-user-agent-style-sheet-and-presentational-hints/body-bgcolor-attribute-change.html [ Failure ] crbug.com/591099 external/wpt/html/semantics/document-metadata/the-link-element/stylesheet-change-href.html [ Failure ] crbug.com/591099 external/wpt/html/semantics/forms/the-form-element/form-elements-filter.html [ Crash ] @@ -3215,7 +3209,7 @@ crbug.com/591099 external/wpt/pointerevents/pointerevent_disabled_form_control-manual.html [ Timeout ] crbug.com/591099 external/wpt/pointerevents/pointerevent_lostpointercapture_for_disconnected_node-manual.html [ Timeout ] crbug.com/714962 external/wpt/pointerevents/pointerevent_lostpointercapture_is_first-manual.html [ Timeout ] -crbug.com/591099 external/wpt/pointerevents/pointerevent_pointerleave_pen-manual.html [ Failure Timeout ] +crbug.com/591099 external/wpt/pointerevents/pointerevent_pointerleave_pen-manual.html [ Failure ] crbug.com/714962 external/wpt/pointerevents/pointerevent_releasepointercapture_onpointerup_mouse-manual.html [ Timeout ] crbug.com/714962 external/wpt/pointerevents/pointerevent_setpointercapture_relatedtarget-manual.html [ Timeout ] crbug.com/714962 external/wpt/pointerevents/pointerevent_touch-action-auto-css_touch-manual.html [ Timeout ] @@ -3461,7 +3455,7 @@ crbug.com/591099 fast/block/float/overlapping-floats-paint-hittest-order-2.html [ Failure ] crbug.com/714962 fast/block/float/relayout-nested-float-after-line.html [ Failure ] crbug.com/591099 fast/block/float/selection-gap-clip-out-tiger-crash.html [ Failure ] -crbug.com/591099 fast/block/geometry-map-assertion-with-tall-content.html [ Crash Failure ] +crbug.com/591099 fast/block/geometry-map-assertion-with-tall-content.html [ Failure ] crbug.com/714962 fast/block/layer-not-removed-from-parent-crash.html [ Failure ] crbug.com/591099 fast/block/line-layout/floats-do-not-fit-on-line.html [ Failure ] crbug.com/591099 fast/block/line-layout/line-break-removal-near-textarea-crash.html [ Failure ] @@ -3639,7 +3633,7 @@ crbug.com/591099 fast/box-shadow/scaled-box-shadow.html [ Failure ] crbug.com/591099 fast/box-shadow/spread.html [ Failure ] crbug.com/591099 fast/box-shadow/transform-fringing.html [ Failure ] -crbug.com/591099 fast/box-sizing/replaced.html [ Failure Pass ] +crbug.com/591099 fast/box-sizing/replaced.html [ Failure ] crbug.com/714962 fast/canvas-api/canvas-scroll-path-into-view.html [ Failure Pass ] crbug.com/591099 fast/canvas-api/fallback-content.html [ Crash ] crbug.com/591099 fast/canvas-api/toDataURL-supportedTypes.html [ Failure ] @@ -4144,8 +4138,8 @@ crbug.com/591099 fast/css/vertical-text-overflow-ellipsis-text-align-left.html [ Failure ] crbug.com/591099 fast/css/vertical-text-overflow-ellipsis-text-align-right.html [ Failure ] crbug.com/591099 fast/css/visibility-hit-test.html [ Failure ] -crbug.com/714962 fast/css/whitespace-between-text-flex-preserve.html [ Failure ] -crbug.com/714962 fast/css/whitespace-between-text-flex.html [ Failure ] +crbug.com/714962 fast/css/whitespace-between-text-flex-preserve.html [ Failure Pass ] +crbug.com/714962 fast/css/whitespace-between-text-flex.html [ Failure Pass ] crbug.com/591099 fast/css/word-space-extra.html [ Failure ] crbug.com/591099 fast/css/zoom-font-size.html [ Failure ] crbug.com/714962 fast/css3-text/css3-text-decoration/repaint/repaint-text-decoration-style.html [ Failure ] @@ -4438,7 +4432,7 @@ crbug.com/591099 fast/events/keypress-focus-change.html [ Failure ] crbug.com/591099 fast/events/media-element-focus-tab.html [ Failure ] crbug.com/714962 fast/events/middleClickAutoscroll-click-hyperlink.html [ Timeout ] -crbug.com/714962 fast/events/middleClickAutoscroll-latching.html [ Pass Timeout ] +crbug.com/714962 fast/events/middleClickAutoscroll-latching.html [ Timeout ] crbug.com/714962 fast/events/mouse-down-on-pseudo-element-remove-crash.html [ Failure ] crbug.com/591099 fast/events/mouse-drag-from-frame-to-other-frame.html [ Failure ] crbug.com/591099 fast/events/mouse-event-buttons-attribute.html [ Timeout ] @@ -4509,6 +4503,9 @@ crbug.com/591099 fast/events/touch/touch-slider-no-js-touch-listener.html [ Crash ] crbug.com/591099 fast/events/touch/touch-slider.html [ Crash ] crbug.com/591099 fast/events/wheel/latched-scroll-node-removed.html [ Pass ] +crbug.com/591099 fast/events/wheel/mainthread-touchpad-fling-latching.html [ Pass ] +crbug.com/591099 fast/events/wheel/mouse-wheel-scroll-latching.html [ Pass ] +crbug.com/591099 fast/events/wheel/wheel-scroll-latching-on-scrollbar.html [ Pass ] crbug.com/714962 fast/events/wheel/wheelevent-basic.html [ Failure ] crbug.com/591099 fast/events/window-events-bubble.html [ Failure ] crbug.com/591099 fast/events/window-events-bubble2.html [ Failure ] @@ -4667,7 +4664,7 @@ crbug.com/714962 fast/forms/label/label-click.html [ Failure ] crbug.com/591099 fast/forms/label/label-contains-other-interactive-content.html [ Crash ] crbug.com/714962 fast/forms/label/label-selection-by-dragging.html [ Failure ] -crbug.com/591099 fast/forms/label/label-selection-by-textSelection-and-click.html [ Failure Timeout ] +crbug.com/591099 fast/forms/label/label-selection-by-textSelection-and-click.html [ Failure ] crbug.com/591099 fast/forms/label/labelable-elements.html [ Crash ] crbug.com/591099 fast/forms/label/labels-add-htmlFor-label.html [ Crash ] crbug.com/591099 fast/forms/label/labels-add-parent-label.html [ Crash ] @@ -5108,7 +5105,7 @@ crbug.com/591099 fast/inline-block/vertical-align-top-and-bottom-2.html [ Failure ] crbug.com/591099 fast/inline/absolute-positioned-inline-in-centred-block.html [ Failure ] crbug.com/591099 fast/inline/br-client-rect.html [ Failure ] -crbug.com/591099 fast/inline/break-between-nobr.html [ Failure ] +crbug.com/591099 fast/inline/break-between-nobr.html [ Failure Pass ] crbug.com/714962 fast/inline/continuation-outlines-with-layers-2.html [ Failure ] crbug.com/591099 fast/inline/continuation-outlines-with-layers.html [ Failure ] crbug.com/591099 fast/inline/continuation-outlines.html [ Failure ] @@ -5169,7 +5166,6 @@ crbug.com/591099 fast/js/toString-and-valueOf-override.html [ Failure ] crbug.com/591099 fast/js/webidl-type-mapping.html [ Timeout ] crbug.com/591099 fast/layers/add-layer-with-nested-stacking.html [ Failure ] -crbug.com/591099 fast/layers/inline-dirty-z-order-lists.html [ Failure ] crbug.com/591099 fast/layers/layer-content-visibility-change.html [ Failure ] crbug.com/591099 fast/layers/layer-visibility-sublayer.html [ Failure ] crbug.com/591099 fast/layers/layer-visibility.html [ Failure ] @@ -5193,7 +5189,6 @@ crbug.com/591099 fast/lists/003.html [ Failure ] crbug.com/591099 fast/lists/004.html [ Failure ] crbug.com/591099 fast/lists/005-vertical.html [ Failure ] -crbug.com/591099 fast/lists/005.html [ Failure ] crbug.com/591099 fast/lists/006-vertical.html [ Failure ] crbug.com/591099 fast/lists/006.html [ Failure ] crbug.com/591099 fast/lists/007-vertical.html [ Failure ] @@ -5204,12 +5199,10 @@ crbug.com/591099 fast/lists/009.html [ Failure ] crbug.com/591099 fast/lists/alpha-boundary-values.html [ Failure ] crbug.com/591099 fast/lists/alpha-list-wrap.html [ Failure ] -crbug.com/591099 fast/lists/big-list-marker.html [ Failure ] crbug.com/591099 fast/lists/calc-width-with-space.html [ Failure ] crbug.com/591099 fast/lists/drag-into-marker.html [ Failure ] crbug.com/591099 fast/lists/dynamic-marker-crash.html [ Failure ] crbug.com/591099 fast/lists/inline-before-content-after-list-marker.html [ Failure ] -crbug.com/591099 fast/lists/inlineBoxWrapperNullCheck.html [ Failure ] crbug.com/591099 fast/lists/list-and-grid.html [ Failure ] crbug.com/591099 fast/lists/list-and-margin-collapse.html [ Failure ] crbug.com/591099 fast/lists/list-color-change-no-layout.html [ Failure ] @@ -5221,13 +5214,10 @@ crbug.com/591099 fast/lists/list-marker-before-float.html [ Failure ] crbug.com/591099 fast/lists/list-marker-inside-overflow-hidden.html [ Failure ] crbug.com/591099 fast/lists/marker-before-empty-inline.html [ Failure ] -crbug.com/591099 fast/lists/marker-image-error.html [ Failure ] crbug.com/591099 fast/lists/markers-in-selection.html [ Failure ] -crbug.com/591099 fast/lists/ol-display-types.html [ Failure ] crbug.com/591099 fast/lists/ordered-list-with-no-ol-tag.html [ Failure ] crbug.com/591099 fast/lists/remove-listmarker-and-make-anonblock-empty-2.html [ Failure ] crbug.com/591099 fast/lists/remove-listmarker-from-anonblock-with-continuation-crash.html [ Crash ] -crbug.com/591099 fast/lists/scrolled-marker-paint.html [ Failure ] crbug.com/591099 fast/loader/child-frame-add-after-back-forward.html [ Timeout ] crbug.com/591099 fast/loader/frame-creation-removal.html [ Failure ] crbug.com/591099 fast/loader/javascript-url-iframe-crash.html [ Crash ] @@ -6125,7 +6115,7 @@ crbug.com/591099 fast/table/percent-height-content-in-fixed-height-border-box-sized-cell-with-collapsed-border-on-table.html [ Failure ] crbug.com/591099 fast/table/percent-height-content-in-fixed-height-border-box-sized-cell-with-collapsed-border.html [ Failure ] crbug.com/591099 fast/table/percent-height-content-in-fixed-height-content-box-sized-cell.html [ Failure ] -crbug.com/591099 fast/table/percent-height-overflow-auto-content-in-cell.html [ Failure Pass ] +crbug.com/591099 fast/table/percent-height-overflow-auto-content-in-cell.html [ Failure ] crbug.com/591099 fast/table/percent-height-overflow-scroll-content-in-cell.html [ Failure Pass ] crbug.com/591099 fast/table/percent-widths-stretch-vertical.html [ Failure ] crbug.com/591099 fast/table/recalc-section-first-body-crash-main.html [ Failure ] @@ -6244,22 +6234,10 @@ crbug.com/591099 fast/text/container-align-with-inlines.html [ Failure ] crbug.com/714962 fast/text/content-following-inline-isolate-with-collapsed-whitespace.html [ Failure ] crbug.com/591099 fast/text/decorations-with-text-combine.html [ Failure ] -crbug.com/591099 fast/text/ellipsis-at-edge-of-ltr-text-in-rtl-flow.html [ Failure ] -crbug.com/591099 fast/text/ellipsis-at-edge-of-rtl-text-in-ltr-flow.html [ Failure ] -crbug.com/591099 fast/text/ellipsis-in-absolute-block.html [ Failure ] crbug.com/714962 fast/text/ellipsis-in-justified-text.html [ Failure ] crbug.com/591099 fast/text/ellipsis-in-relative-inline-right.html [ Failure ] crbug.com/591099 fast/text/ellipsis-in-relative-inline.html [ Failure ] -crbug.com/591099 fast/text/ellipsis-ltr-text-in-rtl-flow-leading-space.html [ Failure ] -crbug.com/591099 fast/text/ellipsis-ltr-text-in-rtl-flow-underline.html [ Failure ] -crbug.com/591099 fast/text/ellipsis-ltr-text-in-rtl-flow.html [ Failure ] -crbug.com/591099 fast/text/ellipsis-mixed-text-in-ltr-flow-underline-2.html [ Failure ] -crbug.com/591099 fast/text/ellipsis-mixed-text-in-ltr-flow-underline.html [ Failure ] -crbug.com/591099 fast/text/ellipsis-mixed-text-in-rtl-flow-underline-2.html [ Failure ] -crbug.com/591099 fast/text/ellipsis-mixed-text-in-rtl-flow-underline.html [ Failure ] crbug.com/591099 fast/text/ellipsis-platform-font-change.html [ Failure ] -crbug.com/591099 fast/text/ellipsis-rtl-text-in-ltr-flow-underline.html [ Failure ] -crbug.com/591099 fast/text/ellipsis-rtl-text-in-ltr-flow.html [ Failure ] crbug.com/591099 fast/text/ellipsis-with-list-marker-in-ltr-flow.html [ Failure ] crbug.com/591099 fast/text/ellipsis-with-list-marker-in-rtl-flow.html [ Failure ] crbug.com/591099 fast/text/emoji-web-font.html [ Pass ] @@ -6278,27 +6256,21 @@ crbug.com/714962 fast/text/glyph-reordering.html [ Failure ] crbug.com/591099 fast/text/hide-atomic-inlines-after-ellipsis.html [ Failure ] crbug.com/714962 fast/text/hyphen-min-preferred-width.html [ Failure ] -crbug.com/591099 fast/text/international/bidi-AN-after-empty-run.html [ Failure ] -crbug.com/591099 fast/text/international/bidi-LDB-2-CSS.html [ Failure ] -crbug.com/591099 fast/text/international/bidi-LDB-2-HTML.html [ Failure ] -crbug.com/591099 fast/text/international/bidi-LDB-2-formatting-characters.html [ Failure ] -crbug.com/591099 fast/text/international/bidi-ignored-for-first-child-inline.html [ Failure ] crbug.com/714962 fast/text/international/bidi-layout-across-linebreak.html [ Failure ] -crbug.com/591099 fast/text/international/bidi-linebreak-001.html [ Failure ] crbug.com/591099 fast/text/international/bidi-linebreak-002.html [ Failure ] crbug.com/591099 fast/text/international/bidi-linebreak-003.html [ Failure ] crbug.com/714962 fast/text/international/bidi-override.html [ Failure ] crbug.com/714962 fast/text/international/cjk-segmentation.html [ Failure ] -crbug.com/591099 fast/text/international/danda-space.html [ Failure ] crbug.com/714962 fast/text/international/hindi-whitespace.html [ Failure ] crbug.com/591099 fast/text/international/inline-plaintext-is-isolated.html [ Failure ] crbug.com/714962 fast/text/international/iso-8859-8.html [ Failure ] crbug.com/714962 fast/text/international/listbox-width-rtl.html [ Failure ] crbug.com/714962 fast/text/international/rtl-selection-rect-with-fallback.html [ Failure ] +crbug.com/796943 fast/text/international/shape-across-elements-simple.html [ Pass ] crbug.com/591099 fast/text/international/shape-across-elements.html [ Failure ] crbug.com/591099 fast/text/international/text-combine-image-test.html [ Failure ] crbug.com/714962 fast/text/international/thai-baht-space.html [ Failure ] -crbug.com/591099 fast/text/international/unicode-bidi-plaintext-line-wrap.html [ Failure ] +crbug.com/591099 fast/text/international/unicode-bidi-plaintext-line-wrap.html [ Failure Pass ] crbug.com/714962 fast/text/international/vertical-text-metrics-test.html [ Failure ] crbug.com/591099 fast/text/justify-ideograph-vertical.html [ Failure ] crbug.com/591099 fast/text/large-text-composed-char.html [ Timeout ] @@ -6351,8 +6323,6 @@ crbug.com/714962 fast/text/text-between-two-brs-in-nowrap-overflow.html [ Failure ] crbug.com/714962 fast/text/text-range-bounds.html [ Failure ] crbug.com/591099 fast/text/textIteratorNilRenderer.html [ Failure ] -crbug.com/591099 fast/text/trailing-white-space-2.html [ Failure ] -crbug.com/591099 fast/text/trailing-white-space.html [ Failure ] crbug.com/714962 fast/text/transform-text-first-line-capitalize.html [ Failure ] crbug.com/714962 fast/text/transform-text-first-line-lowercase.html [ Failure ] crbug.com/714962 fast/text/transform-text-first-line.html [ Failure ] @@ -6364,10 +6334,10 @@ crbug.com/591099 fast/text/whitespace/normal-after-nowrap-breaking.html [ Failure ] crbug.com/714962 fast/text/whitespace/nowrap-line-break-after-white-space.html [ Failure ] crbug.com/591099 fast/text/whitespace/pre-wrap-spaces-after-newline.html [ Failure ] -crbug.com/591099 fast/text/whitespace/reattach-before-pseudo-nondistributed-whitespace.html [ Failure ] -crbug.com/591099 fast/text/whitespace/reattach-before-pseudo-slot-fallback-whitespace.html [ Failure ] -crbug.com/591099 fast/text/whitespace/reattach-before-pseudo.html [ Failure ] -crbug.com/591099 fast/text/whitespace/reattach-slotted-whitespace.html [ Failure ] +crbug.com/591099 fast/text/whitespace/reattach-before-pseudo-nondistributed-whitespace.html [ Failure Pass ] +crbug.com/591099 fast/text/whitespace/reattach-before-pseudo-slot-fallback-whitespace.html [ Failure Pass ] +crbug.com/591099 fast/text/whitespace/reattach-before-pseudo.html [ Failure Pass ] +crbug.com/591099 fast/text/whitespace/reattach-slotted-whitespace.html [ Failure Pass ] crbug.com/591099 fast/text/writing-root-with-overflow-clip-baseline.html [ Crash ] crbug.com/591099 fast/text/zero-width-characters-complex-script.html [ Failure ] crbug.com/591099 fast/text/zero-width-characters.html [ Failure ] @@ -6550,7 +6520,7 @@ crbug.com/591099 fullscreen/model/fully-exit-fullscreen-nested-iframe.html [ Crash ] crbug.com/591099 fullscreen/non-ancestor-iframe.html [ Crash ] crbug.com/591099 hittesting/border-hittest-inlineFlowBox.html [ Failure ] -crbug.com/714962 hittesting/border-hittest-with-image-fallback.html [ Failure Pass ] +crbug.com/714962 hittesting/border-hittest-with-image-fallback.html [ Failure ] crbug.com/714962 hittesting/culled-inline.html [ Failure ] crbug.com/591099 hittesting/image-with-border-radius.html [ Failure ] crbug.com/714962 hittesting/image-with-clip-path.html [ Failure ] @@ -6716,16 +6686,16 @@ crbug.com/714962 http/tests/devtools/elements/edit/set-attribute.js [ Crash ] crbug.com/714962 http/tests/devtools/elements/edit/set-outer-html-2.js [ Crash ] crbug.com/714962 http/tests/devtools/elements/edit/set-outer-html-for-xhtml.js [ Crash ] -crbug.com/714962 http/tests/devtools/elements/edit/set-outer-html.js [ Crash Pass ] +crbug.com/714962 http/tests/devtools/elements/edit/set-outer-html.js [ Crash ] crbug.com/714962 http/tests/devtools/elements/edit/undo-dom-edits-2.js [ Crash ] crbug.com/714962 http/tests/devtools/elements/edit/undo-dom-edits.js [ Crash ] crbug.com/714962 http/tests/devtools/elements/edit/undo-set-outer-html-2.js [ Crash ] -crbug.com/591099 http/tests/devtools/elements/edit/undo-set-outer-html.js [ Crash Pass ] +crbug.com/591099 http/tests/devtools/elements/edit/undo-set-outer-html.js [ Crash ] crbug.com/591099 http/tests/devtools/elements/elements-delete-inline-style.js [ Crash Pass ] crbug.com/591099 http/tests/devtools/elements/elements-inspect-iframe-from-different-domain.js [ Crash Pass ] crbug.com/714962 http/tests/devtools/elements/elements-linkify-attributes.js [ Crash Pass ] crbug.com/591099 http/tests/devtools/elements/elements-panel-limited-children.js [ Crash ] -crbug.com/591099 http/tests/devtools/elements/elements-panel-rewrite-href.js [ Crash Failure Pass ] +crbug.com/591099 http/tests/devtools/elements/elements-panel-rewrite-href.js [ Crash Pass ] crbug.com/591099 http/tests/devtools/elements/elements-panel-search.js [ Crash Pass ] crbug.com/714962 http/tests/devtools/elements/elements-panel-selection-after-delete.js [ Crash ] crbug.com/714962 http/tests/devtools/elements/elements-treeoutline-copy.js [ Crash ] @@ -6758,7 +6728,7 @@ crbug.com/591099 http/tests/devtools/elements/styles-1/edit-media-text.js [ Crash Pass ] crbug.com/591099 http/tests/devtools/elements/styles-1/edit-value-inside-property.js [ Crash ] crbug.com/714962 http/tests/devtools/elements/styles-1/edit-value-url-with-color.js [ Crash ] -crbug.com/714962 http/tests/devtools/elements/styles-2/force-pseudo-state.js [ Crash Pass ] +crbug.com/714962 http/tests/devtools/elements/styles-2/force-pseudo-state.js [ Crash ] crbug.com/591099 http/tests/devtools/elements/styles-2/inject-stylesheet.js [ Crash Pass ] crbug.com/591099 http/tests/devtools/elements/styles-2/page-reload-update-sidebar.js [ Crash ] crbug.com/714962 http/tests/devtools/elements/styles-2/paste-property.js [ Crash Pass ] @@ -6792,7 +6762,8 @@ crbug.com/591099 http/tests/devtools/elements/styles-4/undo-add-rule-crash.js [ Crash ] crbug.com/591099 http/tests/devtools/elements/styles/cancel-upon-invalid-property.js [ Crash ] crbug.com/591099 http/tests/devtools/elements/styles/selector-line-deprecated.js [ Crash Pass ] -crbug.com/591099 http/tests/devtools/elements/styles/selector-line-sourcemap-header-deprecated.js [ Crash ] +crbug.com/591099 http/tests/devtools/elements/styles/selector-line-sourcemap-header-deprecated.js [ Crash Pass ] +crbug.com/591099 http/tests/devtools/elements/styles/styles-mouse-test.js [ Failure ] crbug.com/714962 http/tests/devtools/elements/styles/stylesheet-tracking.js [ Crash Pass ] crbug.com/591099 http/tests/devtools/elements/styles/undo-after-cancelled-editing.js [ Crash ] crbug.com/714962 http/tests/devtools/elements/styles/undo-change-property.js [ Crash Pass ] @@ -6804,9 +6775,7 @@ crbug.com/714962 http/tests/devtools/jump-to-previous-editing-location.js [ Failure ] crbug.com/714962 http/tests/devtools/layers/layer-canvas-log.js [ Failure ] crbug.com/591099 http/tests/devtools/modify-cross-domain-rule.js [ Crash ] -crbug.com/591099 http/tests/devtools/network/network-columns-visible.js [ Failure Pass ] crbug.com/591099 http/tests/devtools/network/network-datareceived.js [ Failure ] -crbug.com/591099 http/tests/devtools/persistence/persistence-tabbed-editor-opens-filesystem-uisourcecode.js [ Failure Pass Timeout ] crbug.com/591099 http/tests/devtools/runtime/runtime-getProperties.js [ Failure ] crbug.com/714962 http/tests/devtools/service-workers/service-workers-view.js [ Failure ] crbug.com/591099 http/tests/devtools/sources/debugger-pause/debugger-pause-in-internal.js [ Failure ] @@ -6833,7 +6802,7 @@ crbug.com/591099 http/tests/feature-policy/payment-enabledforall.php [ Pass ] crbug.com/591099 http/tests/filesystem/input-display.html [ Timeout ] crbug.com/591099 http/tests/images/restyle-decode-error.html [ Failure ] -crbug.com/783102 http/tests/incremental/frame-focus-before-load.html [ Timeout ] +crbug.com/783102 http/tests/incremental/frame-focus-before-load.html [ Pass Timeout ] crbug.com/591099 http/tests/incremental/slow-utf8-text.pl [ Pass Timeout ] crbug.com/591099 http/tests/inspector-protocol/network/response-interception-no-change-content-not-ready.js [ Pass ] crbug.com/591099 http/tests/inspector-protocol/network/response-interception-request-completes-network-closes.js [ Pass ] @@ -6921,10 +6890,10 @@ crbug.com/591099 http/tests/origin_trials/sample-api-workers.html [ Pass ] crbug.com/591099 http/tests/permissions/test-api-surface.html [ Pass ] crbug.com/591099 http/tests/security/XFrameOptions/x-frame-options-cached.html [ Failure ] -crbug.com/714962 http/tests/security/anchor-download-allow-blob.html [ Failure Timeout ] -crbug.com/714962 http/tests/security/anchor-download-allow-data.html [ Failure Timeout ] -crbug.com/714962 http/tests/security/anchor-download-allow-sameorigin.html [ Failure Timeout ] -crbug.com/714962 http/tests/security/anchor-download-block-crossorigin.html [ Failure Timeout ] +crbug.com/714962 http/tests/security/anchor-download-allow-blob.html [ Timeout ] +crbug.com/714962 http/tests/security/anchor-download-allow-data.html [ Timeout ] +crbug.com/714962 http/tests/security/anchor-download-allow-sameorigin.html [ Timeout ] +crbug.com/714962 http/tests/security/anchor-download-block-crossorigin.html [ Timeout ] crbug.com/591099 http/tests/security/contentSecurityPolicy/1.1/form-action-blocked-when-target-blank.html [ Failure ] crbug.com/591099 http/tests/security/contentSecurityPolicy/1.1/form-action-blocked-when-target-cross-site-window.html [ Failure ] crbug.com/591099 http/tests/security/contentSecurityPolicy/1.1/form-action-src-blocked.html [ Failure ] @@ -7099,9 +7068,6 @@ crbug.com/591099 images/cross-fade-tiled.html [ Failure ] crbug.com/714962 images/drag-image-transformed-parent.html [ Failure ] crbug.com/591099 images/embed-does-not-propagate-dimensions-to-object-ancestor.html [ Failure ] -crbug.com/591099 images/exif-orientation-css.html [ Failure ] -crbug.com/591099 images/exif-orientation-image-document.html [ Failure ] -crbug.com/591099 images/exif-orientation.html [ Failure ] crbug.com/591099 images/favicon-as-image.html [ Failure ] crbug.com/591099 images/gif-loop-count.html [ Failure ] crbug.com/591099 images/gif-short-app-extension-string.html [ Failure ] @@ -7118,20 +7084,11 @@ crbug.com/591099 images/image-map-zoom-alt-content.html [ Failure ] crbug.com/591099 images/image-map-zoom.html [ Failure ] crbug.com/591099 images/image-zoom-to-25.html [ Failure ] -crbug.com/591099 images/imagemap-circle-focus-ring.html [ Failure ] crbug.com/714962 images/imagemap-duplicate-outlines-crash.html [ Failure ] crbug.com/591099 images/imagemap-focus-ring-in-positioned-container.html [ Failure ] -crbug.com/591099 images/imagemap-focus-ring-outline-color-explicitly-inherited-from-map.html [ Failure ] crbug.com/591099 images/imagemap-focus-ring-outline-color-not-inherited-from-map.html [ Failure ] -crbug.com/591099 images/imagemap-focus-ring-outline-color.html [ Failure ] crbug.com/591099 images/imagemap-focus-ring-with-paint-root-offset.html [ Failure ] crbug.com/591099 images/imagemap-focus-ring-with-scale-transform.html [ Failure ] -crbug.com/591099 images/imagemap-focus-ring-zero-outline-width.html [ Failure ] -crbug.com/591099 images/imagemap-focus-ring-zoom.html [ Failure ] -crbug.com/591099 images/imagemap-focus-ring.html [ Failure ] -crbug.com/591099 images/imagemap-overflowing-circle-focus-ring.html [ Failure ] -crbug.com/591099 images/imagemap-overflowing-polygon-focus-ring.html [ Failure ] -crbug.com/591099 images/imagemap-polygon-focus-ring.html [ Failure ] crbug.com/591099 images/motion-jpeg-single-frame.html [ Failure ] crbug.com/591099 images/pdf-as-background.html [ Failure ] crbug.com/591099 images/pdf-as-tiled-background.html [ Failure ] @@ -7668,7 +7625,7 @@ crbug.com/714962 paint/invalidation/svg/clip-path-id-changes.svg [ Failure ] crbug.com/714962 paint/invalidation/svg/clip-path-units-changes.svg [ Failure ] crbug.com/714962 paint/invalidation/svg/container-repaint.svg [ Failure ] -crbug.com/714962 paint/invalidation/svg/deep-dynamic-updates.svg [ Failure ] +crbug.com/714962 paint/invalidation/svg/deep-dynamic-updates.svg [ Failure Pass ] crbug.com/591099 paint/invalidation/svg/deep-nested-embedded-svg-size-changes-no-layout-triggers-1.html [ Failure ] crbug.com/591099 paint/invalidation/svg/deep-nested-embedded-svg-size-changes-no-layout-triggers-2.html [ Failure ] crbug.com/591099 paint/invalidation/svg/embedded-svg-size-changes-no-layout-triggers.html [ Failure ] @@ -8018,7 +7975,7 @@ crbug.com/591099 security/autocomplete-cleared-on-back.html [ Failure ] crbug.com/591099 shadow-dom/event-composed-ua.html [ Timeout ] crbug.com/591099 shadow-dom/focus-navigation-with-delegatesFocus.html [ Timeout ] -crbug.com/714962 shadow-dom/host-pseudo-elements.html [ Failure ] +crbug.com/714962 shadow-dom/host-pseudo-elements.html [ Failure Pass ] crbug.com/591099 shadow-dom/range-caret-range-from-point-left-of-shadow.html [ Crash ] crbug.com/714962 shadow-dom/slotted-pseudo-element-dynamic-attribute-change.html [ Failure ] crbug.com/591099 shapedetection/detection-HTMLVideoElement.html [ Pass ] @@ -8065,11 +8022,11 @@ crbug.com/714962 svg/W3C-SVG-1.1/coords-viewattr-01-b.svg [ Failure ] crbug.com/714962 svg/W3C-SVG-1.1/coords-viewattr-02-b.svg [ Failure ] crbug.com/714962 svg/W3C-SVG-1.1/coords-viewattr-03-b.svg [ Failure ] -crbug.com/714962 svg/W3C-SVG-1.1/filters-color-01-b.svg [ Failure ] +crbug.com/714962 svg/W3C-SVG-1.1/filters-color-01-b.svg [ Failure Pass ] crbug.com/714962 svg/W3C-SVG-1.1/filters-gauss-01-b.svg [ Failure ] crbug.com/714962 svg/W3C-SVG-1.1/filters-light-04-f.svg [ Failure ] crbug.com/714962 svg/W3C-SVG-1.1/filters-turb-02-f.svg [ Failure ] -crbug.com/714962 svg/W3C-SVG-1.1/interact-events-01-b.svg [ Failure ] +crbug.com/714962 svg/W3C-SVG-1.1/interact-events-01-b.svg [ Failure Pass ] crbug.com/714962 svg/W3C-SVG-1.1/masking-intro-01-f.svg [ Failure ] crbug.com/714962 svg/W3C-SVG-1.1/masking-mask-01-b.svg [ Failure ] crbug.com/714962 svg/W3C-SVG-1.1/masking-opacity-01-b.svg [ Failure ] @@ -8131,37 +8088,37 @@ crbug.com/591099 svg/as-image/svg-non-integer-scaled-image.html [ Failure ] crbug.com/591099 svg/as-image/svgview-references-use-counters.html [ Failure ] crbug.com/591099 svg/as-object/object-box-sizing-no-width-height.html [ Failure ] -crbug.com/714962 svg/batik/filters/feTile.svg [ Failure ] -crbug.com/714962 svg/batik/filters/filterRegions.svg [ Failure ] +crbug.com/714962 svg/batik/filters/feTile.svg [ Failure Pass ] +crbug.com/714962 svg/batik/filters/filterRegions.svg [ Failure Pass ] crbug.com/714962 svg/batik/masking/maskRegions.svg [ Failure ] -crbug.com/714962 svg/batik/paints/gradientLimit.svg [ Failure ] -crbug.com/714962 svg/batik/paints/patternPreserveAspectRatioA.svg [ Failure ] -crbug.com/714962 svg/batik/paints/patternRegionA.svg [ Failure ] -crbug.com/714962 svg/batik/paints/patternRegions-positioned-objects.svg [ Failure ] -crbug.com/714962 svg/batik/paints/patternRegions.svg [ Failure ] -crbug.com/714962 svg/batik/text/longTextOnPath.svg [ Failure ] +crbug.com/714962 svg/batik/paints/gradientLimit.svg [ Failure Pass ] +crbug.com/714962 svg/batik/paints/patternPreserveAspectRatioA.svg [ Failure Pass ] +crbug.com/714962 svg/batik/paints/patternRegionA.svg [ Failure Pass ] +crbug.com/714962 svg/batik/paints/patternRegions-positioned-objects.svg [ Failure Pass ] +crbug.com/714962 svg/batik/paints/patternRegions.svg [ Failure Pass ] +crbug.com/714962 svg/batik/text/longTextOnPath.svg [ Failure Pass ] crbug.com/714962 svg/batik/text/smallFonts.svg [ Failure ] crbug.com/714962 svg/batik/text/textAnchor.svg [ Failure ] -crbug.com/714962 svg/batik/text/textDecoration.svg [ Failure ] -crbug.com/714962 svg/batik/text/textEffect.svg [ Failure ] +crbug.com/714962 svg/batik/text/textDecoration.svg [ Failure Pass ] +crbug.com/714962 svg/batik/text/textEffect.svg [ Failure Pass ] crbug.com/714962 svg/batik/text/textEffect2.svg [ Failure ] -crbug.com/714962 svg/batik/text/textEffect3.svg [ Failure ] -crbug.com/714962 svg/batik/text/textFeatures.svg [ Failure ] -crbug.com/714962 svg/batik/text/textLayout.svg [ Failure ] -crbug.com/714962 svg/batik/text/textLayout2.svg [ Failure ] -crbug.com/714962 svg/batik/text/textLength.svg [ Failure ] -crbug.com/714962 svg/batik/text/textOnPath.svg [ Failure ] -crbug.com/714962 svg/batik/text/textOnPathSpaces.svg [ Failure ] -crbug.com/714962 svg/batik/text/textPosition.svg [ Failure ] -crbug.com/714962 svg/batik/text/textPosition2.svg [ Failure ] +crbug.com/714962 svg/batik/text/textEffect3.svg [ Failure Pass ] +crbug.com/714962 svg/batik/text/textFeatures.svg [ Failure Pass ] +crbug.com/714962 svg/batik/text/textLayout.svg [ Failure Pass ] +crbug.com/714962 svg/batik/text/textLayout2.svg [ Failure Pass ] +crbug.com/714962 svg/batik/text/textLength.svg [ Failure Pass ] +crbug.com/714962 svg/batik/text/textOnPath.svg [ Failure Pass ] +crbug.com/714962 svg/batik/text/textOnPathSpaces.svg [ Failure Pass ] +crbug.com/714962 svg/batik/text/textPosition.svg [ Failure Pass ] +crbug.com/714962 svg/batik/text/textPosition2.svg [ Failure Pass ] crbug.com/714962 svg/batik/text/textProperties.svg [ Failure ] -crbug.com/714962 svg/batik/text/textProperties2.svg [ Failure ] -crbug.com/714962 svg/batik/text/textStyles.svg [ Failure ] -crbug.com/714962 svg/batik/text/verticalText.svg [ Failure ] -crbug.com/714962 svg/batik/text/verticalTextOnPath.svg [ Failure ] +crbug.com/714962 svg/batik/text/textProperties2.svg [ Failure Pass ] +crbug.com/714962 svg/batik/text/textStyles.svg [ Failure Pass ] +crbug.com/714962 svg/batik/text/verticalText.svg [ Failure Pass ] +crbug.com/714962 svg/batik/text/verticalTextOnPath.svg [ Failure Pass ] crbug.com/714962 svg/canvas/canvas-pattern-svg.html [ Failure ] -crbug.com/714962 svg/carto.net/scrollbar.svg [ Failure ] -crbug.com/714962 svg/carto.net/textbox.svg [ Failure ] +crbug.com/714962 svg/carto.net/scrollbar.svg [ Failure Pass ] +crbug.com/714962 svg/carto.net/textbox.svg [ Failure Pass ] crbug.com/714962 svg/clip-path/clip-in-clip.svg [ Failure ] crbug.com/714962 svg/clip-path/clip-in-mask-objectBoundingBox.svg [ Failure ] crbug.com/714962 svg/clip-path/clip-in-mask-userSpaceOnUse.svg [ Failure ] @@ -8254,7 +8211,7 @@ crbug.com/591099 svg/custom/image-parent-translation.xhtml [ Failure ] crbug.com/591099 svg/custom/image-rescale-clip.html [ Failure ] crbug.com/591099 svg/custom/image-rescale-scroll.html [ Failure ] -crbug.com/714962 svg/custom/image-with-preserveAspectRatio-none.html [ Failure ] +crbug.com/714962 svg/custom/image-with-preserveAspectRatio-none.html [ Failure Pass ] crbug.com/714962 svg/custom/image-with-transform-clip-filter.svg [ Failure ] crbug.com/591099 svg/custom/inline-svg-in-xhtml.xml [ Failure ] crbug.com/591099 svg/custom/inline-svg-use-available-width-in-stf.html [ Failure ] @@ -8288,7 +8245,7 @@ crbug.com/714962 svg/custom/svg-fonts-no-latin-glyph.html [ Failure ] crbug.com/591099 svg/custom/svg-fonts-with-no-element-reference.html [ Failure ] crbug.com/591099 svg/custom/svg-fonts-word-spacing.html [ Failure ] -crbug.com/714962 svg/custom/svg-overflow-types.svg [ Failure ] +crbug.com/714962 svg/custom/svg-overflow-types.svg [ Failure Pass ] crbug.com/591099 svg/custom/tabindex-order.html [ Failure ] crbug.com/714962 svg/custom/text-clip.svg [ Failure ] crbug.com/591099 svg/custom/text-match-highlight.html [ Failure ] @@ -8380,8 +8337,8 @@ crbug.com/591099 svg/in-html/circle.html [ Failure ] crbug.com/591099 svg/in-html/sizing/svg-inline.html [ Timeout ] crbug.com/591099 svg/overflow/overflow-on-foreignObject.svg [ Failure ] -crbug.com/714962 svg/overflow/overflow-on-inner-svg-element-defaults.svg [ Failure ] -crbug.com/714962 svg/overflow/overflow-on-inner-svg-element.svg [ Failure ] +crbug.com/714962 svg/overflow/overflow-on-inner-svg-element-defaults.svg [ Failure Pass ] +crbug.com/714962 svg/overflow/overflow-on-inner-svg-element.svg [ Failure Pass ] crbug.com/714962 svg/overflow/overflow-on-outermost-svg-element-horizontal-auto.svg [ Failure ] crbug.com/591099 svg/overflow/overflow-on-outermost-svg-element-in-xhtml-auto.xhtml [ Failure ] crbug.com/591099 svg/overflow/overflow-on-outermost-svg-element-in-xhtml-defaults.xhtml [ Failure ] @@ -8764,9 +8721,6 @@ crbug.com/591099 virtual/gpu-rasterization/images/cross-fade-tiled.html [ Failure ] crbug.com/714962 virtual/gpu-rasterization/images/drag-image-transformed-parent.html [ Failure ] crbug.com/591099 virtual/gpu-rasterization/images/embed-does-not-propagate-dimensions-to-object-ancestor.html [ Failure ] -crbug.com/591099 virtual/gpu-rasterization/images/exif-orientation-css.html [ Failure ] -crbug.com/591099 virtual/gpu-rasterization/images/exif-orientation-image-document.html [ Failure ] -crbug.com/591099 virtual/gpu-rasterization/images/exif-orientation.html [ Failure ] crbug.com/591099 virtual/gpu-rasterization/images/favicon-as-image.html [ Failure ] crbug.com/591099 virtual/gpu-rasterization/images/gif-loop-count.html [ Failure ] crbug.com/591099 virtual/gpu-rasterization/images/gif-short-app-extension-string.html [ Failure ] @@ -8783,20 +8737,11 @@ crbug.com/591099 virtual/gpu-rasterization/images/image-map-zoom-alt-content.html [ Failure ] crbug.com/591099 virtual/gpu-rasterization/images/image-map-zoom.html [ Failure ] crbug.com/591099 virtual/gpu-rasterization/images/image-zoom-to-25.html [ Failure ] -crbug.com/591099 virtual/gpu-rasterization/images/imagemap-circle-focus-ring.html [ Failure ] crbug.com/714962 virtual/gpu-rasterization/images/imagemap-duplicate-outlines-crash.html [ Failure ] crbug.com/591099 virtual/gpu-rasterization/images/imagemap-focus-ring-in-positioned-container.html [ Failure ] -crbug.com/591099 virtual/gpu-rasterization/images/imagemap-focus-ring-outline-color-explicitly-inherited-from-map.html [ Failure ] crbug.com/591099 virtual/gpu-rasterization/images/imagemap-focus-ring-outline-color-not-inherited-from-map.html [ Failure ] -crbug.com/591099 virtual/gpu-rasterization/images/imagemap-focus-ring-outline-color.html [ Failure ] crbug.com/591099 virtual/gpu-rasterization/images/imagemap-focus-ring-with-paint-root-offset.html [ Failure ] crbug.com/591099 virtual/gpu-rasterization/images/imagemap-focus-ring-with-scale-transform.html [ Failure ] -crbug.com/591099 virtual/gpu-rasterization/images/imagemap-focus-ring-zero-outline-width.html [ Failure ] -crbug.com/591099 virtual/gpu-rasterization/images/imagemap-focus-ring-zoom.html [ Failure ] -crbug.com/591099 virtual/gpu-rasterization/images/imagemap-focus-ring.html [ Failure ] -crbug.com/591099 virtual/gpu-rasterization/images/imagemap-overflowing-circle-focus-ring.html [ Failure ] -crbug.com/591099 virtual/gpu-rasterization/images/imagemap-overflowing-polygon-focus-ring.html [ Failure ] -crbug.com/591099 virtual/gpu-rasterization/images/imagemap-polygon-focus-ring.html [ Failure ] crbug.com/591099 virtual/gpu-rasterization/images/motion-jpeg-single-frame.html [ Failure ] crbug.com/591099 virtual/gpu-rasterization/images/pdf-as-background.html [ Failure ] crbug.com/591099 virtual/gpu-rasterization/images/pdf-as-tiled-background.html [ Failure ] @@ -8815,7 +8760,6 @@ crbug.com/591099 virtual/gpu-rasterization/images/rendering-broken-images.html [ Failure ] crbug.com/591099 virtual/gpu-rasterization/images/sprite-no-bleed.html [ Failure ] crbug.com/591099 virtual/gpu-rasterization/images/webp-flip.html [ Failure ] -crbug.com/591099 virtual/gpu/fast/canvas/OffscreenCanvas-filter-in-worker.html [ Pass Timeout ] crbug.com/591099 virtual/gpu/fast/canvas/canvas-createImageBitmap-colorClamping.html [ Pass ] crbug.com/591099 virtual/gpu/fast/canvas/canvas-createImageBitmap-drawImage.html [ Timeout ] crbug.com/714962 virtual/gpu/fast/canvas/canvas-css-clip-path.html [ Failure ] @@ -8840,7 +8784,7 @@ crbug.com/591099 virtual/incremental-shadow-dom/external/wpt/shadow-dom/untriaged/user-interaction/ranges-and-selections/test-002.html [ Pass ] crbug.com/714962 virtual/incremental-shadow-dom/fast/dom/shadow/content-pseudo-element-dynamic-attribute-change.html [ Failure ] crbug.com/714962 virtual/incremental-shadow-dom/fast/dom/shadow/cppevent-input-in-shadow.html [ Failure ] -crbug.com/714962 virtual/incremental-shadow-dom/fast/dom/shadow/drop-event-for-input-in-shadow.html [ Crash Failure ] +crbug.com/714962 virtual/incremental-shadow-dom/fast/dom/shadow/drop-event-for-input-in-shadow.html [ Failure ] crbug.com/591099 virtual/incremental-shadow-dom/fast/dom/shadow/focus-navigation-with-distributed-nodes.html [ Crash ] crbug.com/591099 virtual/incremental-shadow-dom/fast/dom/shadow/form-in-shadow.html [ Crash ] crbug.com/714962 virtual/incremental-shadow-dom/fast/dom/shadow/hover-active-drag-distributed-nodes.html [ Failure ] @@ -8864,7 +8808,7 @@ crbug.com/591099 virtual/incremental-shadow-dom/shadow-dom/focus-navigation-slots.html [ Pass ] crbug.com/714962 virtual/incremental-shadow-dom/shadow-dom/focus-navigation-with-delegatesFocus.html [ Timeout ] crbug.com/591099 virtual/incremental-shadow-dom/shadow-dom/focus-navigation.html [ Pass ] -crbug.com/591099 virtual/incremental-shadow-dom/shadow-dom/host-pseudo-elements.html [ Failure ] +crbug.com/591099 virtual/incremental-shadow-dom/shadow-dom/host-pseudo-elements.html [ Failure Pass ] crbug.com/591099 virtual/incremental-shadow-dom/shadow-dom/layout.html [ Pass ] crbug.com/591099 virtual/incremental-shadow-dom/shadow-dom/range-caret-range-from-point-left-of-shadow.html [ Crash ] crbug.com/591099 virtual/incremental-shadow-dom/shadow-dom/slots-1.html [ Pass ] @@ -9015,6 +8959,9 @@ crbug.com/591099 virtual/mouseevent_fractional/fast/events/touch/touch-slider-no-js-touch-listener.html [ Crash ] crbug.com/591099 virtual/mouseevent_fractional/fast/events/touch/touch-slider.html [ Crash ] crbug.com/591099 virtual/mouseevent_fractional/fast/events/wheel/latched-scroll-node-removed.html [ Pass ] +crbug.com/591099 virtual/mouseevent_fractional/fast/events/wheel/mainthread-touchpad-fling-latching.html [ Pass ] +crbug.com/591099 virtual/mouseevent_fractional/fast/events/wheel/mouse-wheel-scroll-latching.html [ Pass ] +crbug.com/591099 virtual/mouseevent_fractional/fast/events/wheel/wheel-scroll-latching-on-scrollbar.html [ Pass ] crbug.com/714962 virtual/mouseevent_fractional/fast/events/wheel/wheelevent-basic.html [ Failure ] crbug.com/591099 virtual/mouseevent_fractional/fast/events/window-events-bubble.html [ Failure ] crbug.com/591099 virtual/mouseevent_fractional/fast/events/window-events-bubble2.html [ Failure ]
diff --git a/third_party/WebKit/LayoutTests/NeverFixTests b/third_party/WebKit/LayoutTests/NeverFixTests index 3c2212da..d6c7d834 100644 --- a/third_party/WebKit/LayoutTests/NeverFixTests +++ b/third_party/WebKit/LayoutTests/NeverFixTests
@@ -1169,7 +1169,6 @@ external/wpt/css/css-backgrounds/border-image-width-005.xht [ WontFix ] external/wpt/css/css-backgrounds/border-image-width-006.xht [ WontFix ] external/wpt/css/css-backgrounds/border-image-width-007.xht [ WontFix ] -external/wpt/css/css-backgrounds/border-radius-011.xht [ WontFix ] external/wpt/css/css-backgrounds/border-radius-clipping.html [ WontFix ] external/wpt/css/css-backgrounds/box-shadow-syntax-001.xht [ WontFix ] external/wpt/css/css-backgrounds/css-border-radius-001.html [ WontFix ]
diff --git a/third_party/WebKit/LayoutTests/TestExpectations b/third_party/WebKit/LayoutTests/TestExpectations index e556a3b..c16d834 100644 --- a/third_party/WebKit/LayoutTests/TestExpectations +++ b/third_party/WebKit/LayoutTests/TestExpectations
@@ -79,19 +79,13 @@ crbug.com/769942 virtual/spv175/paint/invalidation/svg/resource-invalidate-on-target-update.svg [ Failure ] crbug.com/771643 virtual/spv175/compositing/overflow/nested-border-radius-clipping.html [ Failure ] -crbug.com/771643 virtual/spv175/compositing/visibility/visibility-image-layers.html [ Failure Pass ] crbug.com/771643 virtual/spv175/fast/borders/inline-mask-overlay-image-outset-vertical-rl.html [ Failure ] crbug.com/771643 virtual/spv175/fast/borders/inline-mask-overlay-image-outset.html [ Failure ] crbug.com/771643 virtual/spv175/fast/borders/inline-mask-overlay-image.html [ Failure ] crbug.com/771643 virtual/spv175/fast/multicol/border-radius-clipped-layer.html [ Failure ] crbug.com/771643 virtual/spv175/fast/multicol/mixed-opacity-test.html [ Failure ] -crbug.com/771643 virtual/spv175/paint/invalidation/forms/select-option-background-color.html [ Failure ] -crbug.com/771643 virtual/spv175/paint/invalidation/position/position-change-keeping-geometry.html [ Failure ] crbug.com/771643 virtual/spv175/paint/invalidation/svg/absolute-sized-content-with-resources.xhtml [ Failure ] crbug.com/771643 virtual/spv175/paint/invalidation/svg/deep-dynamic-updates.svg [ Failure ] -crbug.com/771643 virtual/spv175/paint/invalidation/svg/filter-refresh.svg [ Failure ] -crbug.com/771643 virtual/spv175/paint/invalidation/svg/paintorder-filtered.svg [ Failure ] -crbug.com/771643 virtual/spv175/paint/invalidation/svg/text-viewbox-rescale.html [ Failure ] # spv175+root-layer-scrolls failures. They also fail with root-layer-scrolls without enable-slimming-paint-v175. crbug.com/417782 virtual/spv175/compositing/overflow/border-radius-composited-subframe.html [ Failure ] @@ -324,6 +318,9 @@ # ====== LayoutNG-only failures from here ====== # LayoutNG - is a new layout system for Blink. +# Tests for LayoutNG to pass, but not planned to fix for pre-LayoutNG. +crbug.com/796943 fast/text/international/shape-across-elements-simple.html [ Failure ] + ### virtual/layout_ng/external/wpt/css/CSS2/floats crbug.com/711704 virtual/layout_ng/external/wpt/css/CSS2/floats/floats-rule3-outside-left-002.xht [ Failure ] crbug.com/711704 virtual/layout_ng/external/wpt/css/CSS2/floats/floats-rule3-outside-right-002.xht [ Failure ] @@ -1252,58 +1249,10 @@ # We're experimenting with changing the behavior of the 'nonce' attribute # These CSS Writing Modes Level 3 tests pass but causes 1px diff on images, notified to the submitter. -crbug.com/492664 [ Mac ] external/wpt/css/css-writing-modes/block-flow-direction-htb-001.xht [ Failure ] -crbug.com/492664 [ Mac ] external/wpt/css/css-writing-modes/block-flow-direction-vrl-002.xht [ Failure ] -crbug.com/492664 [ Mac ] external/wpt/css/css-writing-modes/block-flow-direction-vlr-003.xht [ Failure ] -crbug.com/492664 [ Mac ] external/wpt/css/css-writing-modes/block-flow-direction-004.xht [ Failure ] -crbug.com/492664 [ Mac ] external/wpt/css/css-writing-modes/block-flow-direction-vrl-005.xht [ Failure ] -crbug.com/492664 [ Mac ] external/wpt/css/css-writing-modes/block-flow-direction-vrl-006.xht [ Failure ] -crbug.com/492664 [ Mac ] external/wpt/css/css-writing-modes/block-flow-direction-vlr-007.xht [ Failure ] -crbug.com/492664 [ Mac ] external/wpt/css/css-writing-modes/block-flow-direction-vlr-008.xht [ Failure ] -crbug.com/492664 [ Mac ] external/wpt/css/css-writing-modes/block-flow-direction-vlr-010.xht [ Failure ] -crbug.com/492664 [ Mac ] external/wpt/css/css-writing-modes/block-flow-direction-vrl-011.xht [ Failure ] -crbug.com/492664 [ Mac ] external/wpt/css/css-writing-modes/block-flow-direction-vrl-012.xht [ Failure ] -crbug.com/492664 [ Mac ] external/wpt/css/css-writing-modes/block-flow-direction-vrl-013.xht [ Failure ] -crbug.com/492664 [ Mac ] external/wpt/css/css-writing-modes/block-flow-direction-vlr-014.xht [ Failure ] -crbug.com/492664 [ Mac ] external/wpt/css/css-writing-modes/block-flow-direction-vlr-015.xht [ Failure ] -crbug.com/492664 [ Mac ] external/wpt/css/css-writing-modes/block-flow-direction-vlr-016.xht [ Failure ] -crbug.com/492664 [ Mac ] external/wpt/css/css-writing-modes/block-flow-direction-vrl-019.xht [ Failure ] -crbug.com/492664 [ Mac ] external/wpt/css/css-writing-modes/block-flow-direction-vlr-020.xht [ Failure ] -crbug.com/492664 [ Mac ] external/wpt/css/css-writing-modes/block-flow-direction-vrl-021.xht [ Failure ] -crbug.com/492664 [ Mac ] external/wpt/css/css-writing-modes/block-flow-direction-vlr-022.xht [ Failure ] -crbug.com/492664 [ Mac ] external/wpt/css/css-writing-modes/block-flow-direction-vlr-023.xht [ Failure ] -crbug.com/492664 [ Mac ] external/wpt/css/css-writing-modes/block-flow-direction-vrl-024.xht [ Failure ] -crbug.com/492664 [ Mac ] external/wpt/css/css-writing-modes/inline-block-alignment-006.xht [ Failure ] -crbug.com/492664 [ Mac ] external/wpt/css/css-writing-modes/line-box-direction-htb-001.xht [ Failure ] -crbug.com/492664 [ Mac ] external/wpt/css/css-writing-modes/line-box-direction-vrl-002.xht [ Failure ] -crbug.com/492664 [ Mac ] external/wpt/css/css-writing-modes/line-box-direction-vlr-003.xht [ Failure ] -crbug.com/492664 [ Mac ] external/wpt/css/css-writing-modes/line-box-direction-vrl-005.xht [ Failure ] -crbug.com/492664 [ Mac ] external/wpt/css/css-writing-modes/line-box-direction-vrl-006.xht [ Failure ] -crbug.com/492664 [ Mac ] external/wpt/css/css-writing-modes/line-box-direction-vlr-007.xht [ Failure ] -crbug.com/492664 [ Mac ] external/wpt/css/css-writing-modes/line-box-direction-vlr-008.xht [ Failure ] -crbug.com/492664 [ Mac ] external/wpt/css/css-writing-modes/line-box-direction-vlr-010.xht [ Failure ] -crbug.com/492664 [ Mac ] external/wpt/css/css-writing-modes/line-box-direction-vrl-011.xht [ Failure ] -crbug.com/492664 [ Mac ] external/wpt/css/css-writing-modes/line-box-direction-vrl-012.xht [ Failure ] -crbug.com/492664 [ Mac ] external/wpt/css/css-writing-modes/line-box-direction-vlr-013.xht [ Failure ] -crbug.com/492664 [ Mac ] external/wpt/css/css-writing-modes/line-box-direction-vlr-014.xht [ Failure ] -crbug.com/492664 [ Mac ] external/wpt/css/css-writing-modes/line-box-direction-vrl-017.xht [ Failure ] -crbug.com/492664 [ Mac ] external/wpt/css/css-writing-modes/line-box-direction-vlr-018.xht [ Failure ] -crbug.com/492664 [ Mac ] external/wpt/css/css-writing-modes/line-box-direction-vrl-019.xht [ Failure ] -crbug.com/492664 [ Mac ] external/wpt/css/css-writing-modes/line-box-direction-vlr-020.xht [ Failure ] -crbug.com/492664 [ Mac ] external/wpt/css/css-writing-modes/row-progression-vrl-002.xht [ Failure ] -crbug.com/492664 [ Mac ] external/wpt/css/css-writing-modes/row-progression-vlr-003.xht [ Failure ] -crbug.com/492664 [ Mac ] external/wpt/css/css-writing-modes/row-progression-vrl-004.xht [ Failure ] -crbug.com/492664 [ Mac ] external/wpt/css/css-writing-modes/row-progression-vlr-005.xht [ Failure ] -crbug.com/492664 [ Mac ] external/wpt/css/css-writing-modes/row-progression-vrl-006.xht [ Failure ] -crbug.com/492664 [ Mac ] external/wpt/css/css-writing-modes/row-progression-vlr-007.xht [ Failure ] -crbug.com/492664 [ Mac ] external/wpt/css/css-writing-modes/row-progression-vrl-008.xht [ Failure ] -crbug.com/492664 [ Mac ] external/wpt/css/css-writing-modes/row-progression-vlr-009.xht [ Failure ] crbug.com/492664 [ Mac ] external/wpt/css/css-writing-modes/sizing-orthog-htb-in-vlr-008.xht [ Failure ] crbug.com/492664 [ Mac ] external/wpt/css/css-writing-modes/sizing-orthog-htb-in-vlr-020.xht [ Failure ] crbug.com/492664 [ Mac ] external/wpt/css/css-writing-modes/sizing-orthog-htb-in-vrl-008.xht [ Failure ] crbug.com/492664 [ Mac ] external/wpt/css/css-writing-modes/sizing-orthog-htb-in-vrl-020.xht [ Failure ] -crbug.com/492664 [ Mac ] external/wpt/css/css-writing-modes/text-baseline-vrl-006.xht [ Failure ] -crbug.com/492664 [ Mac ] external/wpt/css/css-writing-modes/text-baseline-vlr-007.xht [ Failure ] crbug.com/498845 [ Win ] fast/multicol/vertical-rl/float-content-break.html [ Failure ] crbug.com/443615 [ Linux Win ] external/wpt/css/css-shapes/shape-outside/supported-shapes/circle/shape-outside-circle-027.html [ Failure ] @@ -1893,6 +1842,11 @@ crbug.com/751952 http/tests/devtools/console/console-uncaught-promise.js [ Pass Failure ] crbug.com/751952 virtual/origin-trials-runtimeflags-disabled/http/tests/origin_trials/webexposed/budget-api-origin-trial-interfaces.html [ Pass Failure ] +crbug.com/800898 external/wpt/FileAPI/url/url-with-fetch.any.worker.html [ Pass Failure ] +crbug.com/800898 external/wpt/FileAPI/url/url-with-xhr.any.worker.html [ Pass Failure ] +crbug.com/800898 virtual/mojo-blobs/external/wpt/FileAPI/url/url-with-fetch.any.worker.html [ Pass Failure ] +crbug.com/800898 virtual/mojo-blobs/external/wpt/FileAPI/url/url-with-xhr.any.worker.html [ Pass Failure ] + # ====== New tests from wpt-importer added here ====== crbug.com/626703 external/wpt/css/css-tables/fixup-dynamic-anonymous-inline-table-002.html [ Failure ] crbug.com/626703 external/wpt/quirks/active-and-hover-manual.html [ Skip ] @@ -2348,6 +2302,7 @@ crbug.com/796733 [ Win ] external/wpt/css/css-ui/text-overflow-020.html [ Pass Failure ] crbug.com/796668 external/wpt/longtask-timing/longtask-in-sibling-iframe.html [ Skip ] +crbug.com/796668 external/wpt/longtask-timing/longtask-in-sibling-iframe-crossorigin.html [ Skip ] # This test times out on debug builds, see https://crbug.com/755810 crbug.com/626703 [ Debug ] external/wpt/html/semantics/tabular-data/processing-model-1/span-limits.html [ Skip ] @@ -2732,7 +2687,6 @@ crbug.com/709227 external/wpt/websockets/interfaces/WebSocket/send/011.html?wss [ Failure ] crbug.com/709227 external/wpt/websockets/interfaces/WebSocket/send/012.html?wss [ Failure ] crbug.com/709227 external/wpt/websockets/opening-handshake/002.html?wss [ Failure ] -crbug.com/709227 external/wpt/websockets/opening-handshake/003.html?wss [ Failure ] crbug.com/709227 external/wpt/websockets/opening-handshake/005.html [ Failure ] crbug.com/709227 external/wpt/websockets/unload-a-document/002.html [ Failure ] crbug.com/709227 external/wpt/websockets/unload-a-document/002.html?wss [ Failure ] @@ -2755,6 +2709,7 @@ crbug.com/709227 external/wpt/websockets/interfaces/WebSocket/send/010.html?wss [ Timeout ] crbug.com/709227 external/wpt/websockets/keeping-connection-open/001.html?wss [ Failure Timeout ] crbug.com/709227 external/wpt/websockets/opening-handshake/003-sets-origin.worker.html [ Timeout ] +crbug.com/709227 external/wpt/websockets/opening-handshake/003.html?wss [ Failure Timeout ] crbug.com/709227 external/wpt/websockets/opening-handshake/005.html?wss [ Failure Timeout ] crbug.com/709227 external/wpt/workers/nested_worker.worker.html [ Timeout ] @@ -2779,7 +2734,8 @@ crbug.com/678346 [ Debug ] fast/dom/shadow/selections-in-shadow.html [ Pass Timeout ] crbug.com/678346 [ Win7 Mac Debug ] storage/indexeddb/index-cursor.html [ Pass Timeout ] crbug.com/678346 [ Win7 Debug ] storage/indexeddb/mozilla/test_objectStore_openKeyCursor.html [ Pass Timeout ] -crbug.com/678346 [ Win7 Debug ] storage/indexeddb/structured-clone.html [ Pass Timeout ] +# Temporarily disabled due to conflicting NeedsManualRebaseline below +# crbug.com/678346 [ Win7 Debug ] storage/indexeddb/structured-clone.html [ Pass Timeout ] crbug.com/678492 http/tests/misc/webtiming-ssl.php [ Failure Pass ] crbug.com/678493 http/tests/permissions/chromium/test-request-window.html [ Timeout Pass ] @@ -2791,6 +2747,86 @@ crbug.com/701445 external/wpt/dom/events/EventListener-invoke-legacy.html [ Timeout Pass ] +# Rebaseline for v8's --harmony-function-tostring +crbug.com/753073 external/wpt/2dcontext/drawing-images-to-the-canvas/2d.drawImage.zerosource.image.html [ NeedsManualRebaseline ] +crbug.com/753073 external/wpt/2dcontext/fill-and-stroke-styles/2d.pattern.image.broken.html [ NeedsManualRebaseline ] +crbug.com/753073 external/wpt/2dcontext/pixel-manipulation/2d.imageData.create2.nonfinite.html [ NeedsManualRebaseline ] +crbug.com/753073 external/wpt/2dcontext/pixel-manipulation/2d.imageData.get.nonfinite.html [ NeedsManualRebaseline ] +crbug.com/753073 external/wpt/2dcontext/pixel-manipulation/2d.imageData.object.ctor.array.bounds.html [ NeedsManualRebaseline ] +crbug.com/753073 external/wpt/2dcontext/pixel-manipulation/2d.imageData.put.nonfinite.html [ NeedsManualRebaseline ] +crbug.com/753073 external/wpt/FileAPI/blob/Blob-constructor.html [ NeedsManualRebaseline ] +crbug.com/753073 external/wpt/FileAPI/file/File-constructor.html [ NeedsManualRebaseline ] +crbug.com/753073 external/wpt/cors/allow-headers.htm [ NeedsManualRebaseline ] +crbug.com/753073 external/wpt/cors/origin.htm [ NeedsManualRebaseline ] +crbug.com/753073 external/wpt/css/geometry/DOMPoint-001.html [ NeedsManualRebaseline ] +crbug.com/753073 external/wpt/dom/collections/HTMLCollection-supported-property-indices.html [ NeedsManualRebaseline ] +crbug.com/753073 external/wpt/domparsing/innerhtml-01.xhtml [ NeedsManualRebaseline ] +crbug.com/753073 external/wpt/eventsource/eventsource-constructor-url-bogus.htm [ NeedsManualRebaseline ] +crbug.com/753073 external/wpt/fetch/api/headers/headers-record.html [ NeedsManualRebaseline ] +crbug.com/753073 external/wpt/html/browsers/history/the-location-interface/location-prototype-setting-same-origin-domain.sub.html [ NeedsManualRebaseline ] +crbug.com/753073 external/wpt/html/browsers/history/the-location-interface/location-prototype-setting-same-origin.html [ NeedsManualRebaseline ] +crbug.com/753073 external/wpt/html/dom/interfaces.html [ NeedsManualRebaseline ] +crbug.com/753073 external/wpt/html/editing/dnd/synthetic/001.html [ NeedsManualRebaseline ] +crbug.com/753073 external/wpt/html/infrastructure/common-dom-interfaces/collections/htmlallcollection.html [ NeedsManualRebaseline ] +crbug.com/753073 external/wpt/html/semantics/embedded-content/media-elements/interfaces/TrackEvent/createEvent.html [ NeedsManualRebaseline ] +crbug.com/753073 external/wpt/html/semantics/embedded-content/the-canvas-element/imagedata.html [ NeedsManualRebaseline ] +crbug.com/753073 external/wpt/html/semantics/forms/the-form-element/form-indexed-element.html [ NeedsManualRebaseline ] +crbug.com/753073 external/wpt/html/webappapis/scripting/events/messageevent-constructor.https.html [ NeedsManualRebaseline ] +crbug.com/753073 external/wpt/keyboard-lock/idlharness.https.html [ NeedsManualRebaseline ] +crbug.com/753073 external/wpt/media-capabilities/idlharness.html [ NeedsManualRebaseline ] +crbug.com/753073 external/wpt/offscreen-canvas/pixel-manipulation/2d.imageData.create2.nonfinite.html [ NeedsManualRebaseline ] +crbug.com/753073 external/wpt/offscreen-canvas/pixel-manipulation/2d.imageData.get.nonfinite.html [ NeedsManualRebaseline ] +crbug.com/753073 external/wpt/offscreen-canvas/pixel-manipulation/2d.imageData.put.nonfinite.html [ NeedsManualRebaseline ] +crbug.com/753073 external/wpt/offscreen-canvas/the-offscreen-canvas/offscreencanvas.commit.html [ NeedsManualRebaseline ] +crbug.com/753073 external/wpt/offscreen-canvas/the-offscreen-canvas/offscreencanvas.transferrable.html [ NeedsManualRebaseline ] +crbug.com/753073 external/wpt/payment-request/rejects_if_not_active.https.html [ NeedsManualRebaseline ] +crbug.com/753073 external/wpt/screen-orientation/lock-bad-argument.html [ NeedsManualRebaseline ] +crbug.com/753073 external/wpt/selection/removeRange.html [ NeedsManualRebaseline ] +crbug.com/753073 external/wpt/uievents/legacy/Event-subclasses-init.html [ NeedsManualRebaseline ] +crbug.com/753073 external/wpt/url/historical.any.html [ NeedsManualRebaseline ] +crbug.com/753073 external/wpt/url/historical.any.worker.html [ NeedsManualRebaseline ] +crbug.com/753073 external/wpt/url/url-constructor.html [ NeedsManualRebaseline ] +crbug.com/753073 external/wpt/user-timing/invoke_with_timing_attributes.html [ NeedsManualRebaseline ] +crbug.com/753073 external/wpt/web-nfc/nfc_push.https.html [ NeedsManualRebaseline ] +crbug.com/753073 external/wpt/web-nfc/nfc_watch.https.html [ NeedsManualRebaseline ] +crbug.com/753073 external/wpt/webrtc/RTCPeerConnection-addIceCandidate.html [ NeedsManualRebaseline ] +crbug.com/753073 external/wpt/webrtc/RTCPeerConnection-constructor.html [ NeedsManualRebaseline ] +crbug.com/753073 external/wpt/webrtc/RTCPeerConnection-createAnswer.html [ NeedsManualRebaseline ] +crbug.com/753073 external/wpt/webrtc/RTCPeerConnection-getStats.https.html [ NeedsManualRebaseline ] +crbug.com/753073 external/wpt/webrtc/RTCPeerConnection-setLocalDescription-pranswer.html [ NeedsManualRebaseline ] +crbug.com/753073 external/wpt/webrtc/RTCPeerConnection-setRemoteDescription-answer.html [ NeedsManualRebaseline ] +crbug.com/753073 external/wpt/webrtc/RTCPeerConnection-setRemoteDescription-offer.html [ NeedsManualRebaseline ] +crbug.com/753073 external/wpt/webrtc/RTCPeerConnection-setRemoteDescription-pranswer.html [ NeedsManualRebaseline ] +crbug.com/753073 external/wpt/webstorage/storage_string_conversion.html [ NeedsManualRebaseline ] +crbug.com/753073 external/wpt/workers/interfaces/WorkerUtils/importScripts/002.worker.html [ NeedsManualRebaseline ] +crbug.com/753073 external/wpt/xhr/open-url-multi-window-2.htm [ NeedsManualRebaseline ] +crbug.com/753073 external/wpt/xhr/open-url-multi-window-3.htm [ NeedsManualRebaseline ] +crbug.com/753073 external/wpt/xhr/open-url-multi-window-5.htm [ NeedsManualRebaseline ] +crbug.com/753073 external/wpt/xhr/open-url-multi-window-6.htm [ NeedsManualRebaseline ] +crbug.com/753073 fast/dom/TreeWalker/acceptNode-filter.html [ NeedsManualRebaseline ] +crbug.com/753073 fast/dom/Window/anonymous-slot-with-changes.html [ NeedsManualRebaseline ] +crbug.com/753073 fast/dom/Window/window-postmessage-clone.html [ NeedsManualRebaseline ] +crbug.com/753073 fast/events/message-port-multi.html [ NeedsManualRebaseline ] +crbug.com/753073 fast/js/JSON-parse.html [ NeedsManualRebaseline ] +crbug.com/753073 fast/js/function-names.html [ NeedsManualRebaseline ] +crbug.com/753073 fast/js/function-prototype.html [ NeedsManualRebaseline ] +crbug.com/753073 fast/js/toString-and-valueOf-override.html [ NeedsManualRebaseline ] +crbug.com/753073 http/tests/devtools/startup/console/console-format-startup.js [ NeedsManualRebaseline ] +crbug.com/753073 http/tests/security/window-named-proto.html [ NeedsManualRebaseline ] +crbug.com/753073 http/tests/security/xss-exception.html [ NeedsManualRebaseline ] +crbug.com/753073 storage/domstorage/localstorage/string-conversion.html [ NeedsManualRebaseline ] +crbug.com/753073 storage/domstorage/sessionstorage/string-conversion.html [ NeedsManualRebaseline ] +crbug.com/753073 storage/indexeddb/structured-clone.html [ NeedsManualRebaseline ] +crbug.com/753073 virtual/mojo-blobs/external/wpt/FileAPI/blob/Blob-constructor.html [ NeedsManualRebaseline ] +crbug.com/753073 virtual/mojo-blobs/external/wpt/FileAPI/file/File-constructor.html [ NeedsManualRebaseline ] +crbug.com/753073 virtual/mojo-blobs/external/wpt/fetch/api/headers/headers-record.html [ NeedsManualRebaseline ] +crbug.com/753073 virtual/mojo-localstorage/external/wpt/webstorage/storage_string_conversion.html [ NeedsManualRebaseline ] +crbug.com/753073 virtual/mojo-localstorage/storage/domstorage/localstorage/string-conversion.html [ NeedsManualRebaseline ] +crbug.com/753073 virtual/mouseevent_fractional/fast/events/message-port-multi.html [ NeedsManualRebaseline ] +crbug.com/753073 virtual/outofblink-cors/external/wpt/fetch/api/headers/headers-record.html [ NeedsManualRebaseline ] +crbug.com/753073 webaudio/unit-tests/audit-failures.html [ NeedsManualRebaseline ] +crbug.com/753073 webaudio/unit-tests/audit.html [ NeedsManualRebaseline ] + # When WebAssembly is exposed in V8 (soon), this test has the wrong number of expected Object.getOwnPropertyNames() for global object. crbug.com/681468 fast/forms/suggestion-picker/date-suggestion-picker-appearance-zoom125.html [ Failure Pass ] @@ -3026,6 +3062,7 @@ # For Skia roll crbug.com/630695 fast/css/transformed-mask.html [ NeedsManualRebaseline ] +crbug.com/630695 svg/custom/massive-coordinates.svg [ NeedsManualRebaseline ] crbug.com/v8/4958 inspector-protocol/debugger/domdebugger-getEventListeners.js [ NeedsManualRebaseline ] crbug.com/v8/4958 http/tests/devtools/console/console-eval-scoped.js [ NeedsManualRebaseline ] @@ -3542,3 +3579,6 @@ # Sheriff failures 2018-01-09 crbug.com/798481 [ Linux ] virtual/spv175/compositing/gestures/gesture-tapHighlight-simple-window-scroll.html [ Pass Failure ] +# This test is flaky and times out on Windows 7 bots. It also times out on MSAN +# bots due to taling too long to complete. +crbug.com/800359 [ Win7 ] external/wpt/mimesniff/mime-types/parsing.any.worker.html [ Pass Timeout ]
diff --git a/third_party/WebKit/LayoutTests/external/wpt/css/css-display/display-contents-text-inherit-002.html b/third_party/WebKit/LayoutTests/external/wpt/css/css-display/display-contents-text-inherit-002.html new file mode 100644 index 0000000..51bf968 --- /dev/null +++ b/third_party/WebKit/LayoutTests/external/wpt/css/css-display/display-contents-text-inherit-002.html
@@ -0,0 +1,16 @@ +<!DOCTYPE html> +<meta charset="utf-8"> +<title>CSS Display: Apply white-space property of display:contents element to inline children</title> +<link rel="author" title="Rune Lillesveen" href="mailto:futhark@chromium.org"> +<link rel="help" href="https://drafts.csswg.org/css-display-3/#valdef-display-contents"> +<link rel="match" href="display-contents-text-inherit-ref.html"> +<p>The words "Two" and "lines" should not be on the same line.</p> +<div id="div" style="background-color:red"> + <span style="display:contents;white-space:pre-line">Two + lines + </span> +</div> +<script> + document.body.offsetTop; + div.style.backgroundColor = "transparent"; +</script>
diff --git a/third_party/WebKit/LayoutTests/external/wpt/dom/lists/DOMTokenList-coverage-for-attributes-expected.txt b/third_party/WebKit/LayoutTests/external/wpt/dom/lists/DOMTokenList-coverage-for-attributes-expected.txt deleted file mode 100644 index f0130941..0000000 --- a/third_party/WebKit/LayoutTests/external/wpt/dom/lists/DOMTokenList-coverage-for-attributes-expected.txt +++ /dev/null
@@ -1,179 +0,0 @@ -This is a testharness.js-based test. -Found 175 tests; 174 PASS, 1 FAIL, 0 TIMEOUT, 0 NOTRUN. -PASS a.classList in http://www.w3.org/1999/xhtml namespace should be DOMTokenList. -PASS area.classList in http://www.w3.org/1999/xhtml namespace should be DOMTokenList. -PASS link.classList in http://www.w3.org/1999/xhtml namespace should be DOMTokenList. -PASS iframe.classList in http://www.w3.org/1999/xhtml namespace should be DOMTokenList. -PASS output.classList in http://www.w3.org/1999/xhtml namespace should be DOMTokenList. -PASS td.classList in http://www.w3.org/1999/xhtml namespace should be DOMTokenList. -PASS th.classList in http://www.w3.org/1999/xhtml namespace should be DOMTokenList. -PASS a.classList in http://www.w3.org/2000/svg namespace should be DOMTokenList. -PASS area.classList in http://www.w3.org/2000/svg namespace should be DOMTokenList. -PASS link.classList in http://www.w3.org/2000/svg namespace should be DOMTokenList. -PASS iframe.classList in http://www.w3.org/2000/svg namespace should be DOMTokenList. -PASS output.classList in http://www.w3.org/2000/svg namespace should be DOMTokenList. -PASS td.classList in http://www.w3.org/2000/svg namespace should be DOMTokenList. -PASS th.classList in http://www.w3.org/2000/svg namespace should be DOMTokenList. -PASS a.classList in http://www.w3.org/1998/Math/MathML namespace should be DOMTokenList. -PASS area.classList in http://www.w3.org/1998/Math/MathML namespace should be DOMTokenList. -PASS link.classList in http://www.w3.org/1998/Math/MathML namespace should be DOMTokenList. -PASS iframe.classList in http://www.w3.org/1998/Math/MathML namespace should be DOMTokenList. -PASS output.classList in http://www.w3.org/1998/Math/MathML namespace should be DOMTokenList. -PASS td.classList in http://www.w3.org/1998/Math/MathML namespace should be DOMTokenList. -PASS th.classList in http://www.w3.org/1998/Math/MathML namespace should be DOMTokenList. -PASS a.classList in http://example.com/ namespace should be DOMTokenList. -PASS area.classList in http://example.com/ namespace should be DOMTokenList. -PASS link.classList in http://example.com/ namespace should be DOMTokenList. -PASS iframe.classList in http://example.com/ namespace should be DOMTokenList. -PASS output.classList in http://example.com/ namespace should be DOMTokenList. -PASS td.classList in http://example.com/ namespace should be DOMTokenList. -PASS th.classList in http://example.com/ namespace should be DOMTokenList. -PASS a.classList in null namespace should be DOMTokenList. -PASS area.classList in null namespace should be DOMTokenList. -PASS link.classList in null namespace should be DOMTokenList. -PASS iframe.classList in null namespace should be DOMTokenList. -PASS output.classList in null namespace should be DOMTokenList. -PASS td.classList in null namespace should be DOMTokenList. -PASS th.classList in null namespace should be DOMTokenList. -PASS a.htmlFor in http://www.w3.org/1999/xhtml namespace should be undefined. -PASS area.htmlFor in http://www.w3.org/1999/xhtml namespace should be undefined. -PASS link.htmlFor in http://www.w3.org/1999/xhtml namespace should be undefined. -PASS iframe.htmlFor in http://www.w3.org/1999/xhtml namespace should be undefined. -PASS output.htmlFor in http://www.w3.org/1999/xhtml namespace should be DOMTokenList. -PASS td.htmlFor in http://www.w3.org/1999/xhtml namespace should be undefined. -PASS th.htmlFor in http://www.w3.org/1999/xhtml namespace should be undefined. -PASS a.htmlFor in http://www.w3.org/2000/svg namespace should be undefined. -PASS area.htmlFor in http://www.w3.org/2000/svg namespace should be undefined. -PASS link.htmlFor in http://www.w3.org/2000/svg namespace should be undefined. -PASS iframe.htmlFor in http://www.w3.org/2000/svg namespace should be undefined. -PASS output.htmlFor in http://www.w3.org/2000/svg namespace should be undefined. -PASS td.htmlFor in http://www.w3.org/2000/svg namespace should be undefined. -PASS th.htmlFor in http://www.w3.org/2000/svg namespace should be undefined. -PASS a.htmlFor in http://www.w3.org/1998/Math/MathML namespace should be undefined. -PASS area.htmlFor in http://www.w3.org/1998/Math/MathML namespace should be undefined. -PASS link.htmlFor in http://www.w3.org/1998/Math/MathML namespace should be undefined. -PASS iframe.htmlFor in http://www.w3.org/1998/Math/MathML namespace should be undefined. -PASS output.htmlFor in http://www.w3.org/1998/Math/MathML namespace should be undefined. -PASS td.htmlFor in http://www.w3.org/1998/Math/MathML namespace should be undefined. -PASS th.htmlFor in http://www.w3.org/1998/Math/MathML namespace should be undefined. -PASS a.htmlFor in http://example.com/ namespace should be undefined. -PASS area.htmlFor in http://example.com/ namespace should be undefined. -PASS link.htmlFor in http://example.com/ namespace should be undefined. -PASS iframe.htmlFor in http://example.com/ namespace should be undefined. -PASS output.htmlFor in http://example.com/ namespace should be undefined. -PASS td.htmlFor in http://example.com/ namespace should be undefined. -PASS th.htmlFor in http://example.com/ namespace should be undefined. -PASS a.htmlFor in null namespace should be undefined. -PASS area.htmlFor in null namespace should be undefined. -PASS link.htmlFor in null namespace should be undefined. -PASS iframe.htmlFor in null namespace should be undefined. -PASS output.htmlFor in null namespace should be undefined. -PASS td.htmlFor in null namespace should be undefined. -PASS th.htmlFor in null namespace should be undefined. -PASS a.relList in http://www.w3.org/1999/xhtml namespace should be DOMTokenList. -FAIL area.relList in http://www.w3.org/1999/xhtml namespace should be DOMTokenList. assert_equals: expected "[object DOMTokenList]" but got "[object Undefined]" -PASS link.relList in http://www.w3.org/1999/xhtml namespace should be DOMTokenList. -PASS iframe.relList in http://www.w3.org/1999/xhtml namespace should be undefined. -PASS output.relList in http://www.w3.org/1999/xhtml namespace should be undefined. -PASS td.relList in http://www.w3.org/1999/xhtml namespace should be undefined. -PASS th.relList in http://www.w3.org/1999/xhtml namespace should be undefined. -PASS a.relList in http://www.w3.org/2000/svg namespace should be undefined. -PASS area.relList in http://www.w3.org/2000/svg namespace should be undefined. -PASS link.relList in http://www.w3.org/2000/svg namespace should be undefined. -PASS iframe.relList in http://www.w3.org/2000/svg namespace should be undefined. -PASS output.relList in http://www.w3.org/2000/svg namespace should be undefined. -PASS td.relList in http://www.w3.org/2000/svg namespace should be undefined. -PASS th.relList in http://www.w3.org/2000/svg namespace should be undefined. -PASS a.relList in http://www.w3.org/1998/Math/MathML namespace should be undefined. -PASS area.relList in http://www.w3.org/1998/Math/MathML namespace should be undefined. -PASS link.relList in http://www.w3.org/1998/Math/MathML namespace should be undefined. -PASS iframe.relList in http://www.w3.org/1998/Math/MathML namespace should be undefined. -PASS output.relList in http://www.w3.org/1998/Math/MathML namespace should be undefined. -PASS td.relList in http://www.w3.org/1998/Math/MathML namespace should be undefined. -PASS th.relList in http://www.w3.org/1998/Math/MathML namespace should be undefined. -PASS a.relList in http://example.com/ namespace should be undefined. -PASS area.relList in http://example.com/ namespace should be undefined. -PASS link.relList in http://example.com/ namespace should be undefined. -PASS iframe.relList in http://example.com/ namespace should be undefined. -PASS output.relList in http://example.com/ namespace should be undefined. -PASS td.relList in http://example.com/ namespace should be undefined. -PASS th.relList in http://example.com/ namespace should be undefined. -PASS a.relList in null namespace should be undefined. -PASS area.relList in null namespace should be undefined. -PASS link.relList in null namespace should be undefined. -PASS iframe.relList in null namespace should be undefined. -PASS output.relList in null namespace should be undefined. -PASS td.relList in null namespace should be undefined. -PASS th.relList in null namespace should be undefined. -PASS a.sandbox in http://www.w3.org/1999/xhtml namespace should be undefined. -PASS area.sandbox in http://www.w3.org/1999/xhtml namespace should be undefined. -PASS link.sandbox in http://www.w3.org/1999/xhtml namespace should be undefined. -PASS iframe.sandbox in http://www.w3.org/1999/xhtml namespace should be DOMTokenList. -PASS output.sandbox in http://www.w3.org/1999/xhtml namespace should be undefined. -PASS td.sandbox in http://www.w3.org/1999/xhtml namespace should be undefined. -PASS th.sandbox in http://www.w3.org/1999/xhtml namespace should be undefined. -PASS a.sandbox in http://www.w3.org/2000/svg namespace should be undefined. -PASS area.sandbox in http://www.w3.org/2000/svg namespace should be undefined. -PASS link.sandbox in http://www.w3.org/2000/svg namespace should be undefined. -PASS iframe.sandbox in http://www.w3.org/2000/svg namespace should be undefined. -PASS output.sandbox in http://www.w3.org/2000/svg namespace should be undefined. -PASS td.sandbox in http://www.w3.org/2000/svg namespace should be undefined. -PASS th.sandbox in http://www.w3.org/2000/svg namespace should be undefined. -PASS a.sandbox in http://www.w3.org/1998/Math/MathML namespace should be undefined. -PASS area.sandbox in http://www.w3.org/1998/Math/MathML namespace should be undefined. -PASS link.sandbox in http://www.w3.org/1998/Math/MathML namespace should be undefined. -PASS iframe.sandbox in http://www.w3.org/1998/Math/MathML namespace should be undefined. -PASS output.sandbox in http://www.w3.org/1998/Math/MathML namespace should be undefined. -PASS td.sandbox in http://www.w3.org/1998/Math/MathML namespace should be undefined. -PASS th.sandbox in http://www.w3.org/1998/Math/MathML namespace should be undefined. -PASS a.sandbox in http://example.com/ namespace should be undefined. -PASS area.sandbox in http://example.com/ namespace should be undefined. -PASS link.sandbox in http://example.com/ namespace should be undefined. -PASS iframe.sandbox in http://example.com/ namespace should be undefined. -PASS output.sandbox in http://example.com/ namespace should be undefined. -PASS td.sandbox in http://example.com/ namespace should be undefined. -PASS th.sandbox in http://example.com/ namespace should be undefined. -PASS a.sandbox in null namespace should be undefined. -PASS area.sandbox in null namespace should be undefined. -PASS link.sandbox in null namespace should be undefined. -PASS iframe.sandbox in null namespace should be undefined. -PASS output.sandbox in null namespace should be undefined. -PASS td.sandbox in null namespace should be undefined. -PASS th.sandbox in null namespace should be undefined. -PASS a.sizes in http://www.w3.org/1999/xhtml namespace should be undefined. -PASS area.sizes in http://www.w3.org/1999/xhtml namespace should be undefined. -PASS link.sizes in http://www.w3.org/1999/xhtml namespace should be DOMTokenList. -PASS iframe.sizes in http://www.w3.org/1999/xhtml namespace should be undefined. -PASS output.sizes in http://www.w3.org/1999/xhtml namespace should be undefined. -PASS td.sizes in http://www.w3.org/1999/xhtml namespace should be undefined. -PASS th.sizes in http://www.w3.org/1999/xhtml namespace should be undefined. -PASS a.sizes in http://www.w3.org/2000/svg namespace should be undefined. -PASS area.sizes in http://www.w3.org/2000/svg namespace should be undefined. -PASS link.sizes in http://www.w3.org/2000/svg namespace should be undefined. -PASS iframe.sizes in http://www.w3.org/2000/svg namespace should be undefined. -PASS output.sizes in http://www.w3.org/2000/svg namespace should be undefined. -PASS td.sizes in http://www.w3.org/2000/svg namespace should be undefined. -PASS th.sizes in http://www.w3.org/2000/svg namespace should be undefined. -PASS a.sizes in http://www.w3.org/1998/Math/MathML namespace should be undefined. -PASS area.sizes in http://www.w3.org/1998/Math/MathML namespace should be undefined. -PASS link.sizes in http://www.w3.org/1998/Math/MathML namespace should be undefined. -PASS iframe.sizes in http://www.w3.org/1998/Math/MathML namespace should be undefined. -PASS output.sizes in http://www.w3.org/1998/Math/MathML namespace should be undefined. -PASS td.sizes in http://www.w3.org/1998/Math/MathML namespace should be undefined. -PASS th.sizes in http://www.w3.org/1998/Math/MathML namespace should be undefined. -PASS a.sizes in http://example.com/ namespace should be undefined. -PASS area.sizes in http://example.com/ namespace should be undefined. -PASS link.sizes in http://example.com/ namespace should be undefined. -PASS iframe.sizes in http://example.com/ namespace should be undefined. -PASS output.sizes in http://example.com/ namespace should be undefined. -PASS td.sizes in http://example.com/ namespace should be undefined. -PASS th.sizes in http://example.com/ namespace should be undefined. -PASS a.sizes in null namespace should be undefined. -PASS area.sizes in null namespace should be undefined. -PASS link.sizes in null namespace should be undefined. -PASS iframe.sizes in null namespace should be undefined. -PASS output.sizes in null namespace should be undefined. -PASS td.sizes in null namespace should be undefined. -PASS th.sizes in null namespace should be undefined. -Harness: the test ran to completion. -
diff --git a/third_party/WebKit/LayoutTests/external/wpt/html/browsers/history/the-location-interface/location-stringifier-expected.txt b/third_party/WebKit/LayoutTests/external/wpt/html/browsers/history/the-location-interface/location-stringifier-expected.txt index 0cb5f37..59612a1b 100644 --- a/third_party/WebKit/LayoutTests/external/wpt/html/browsers/history/the-location-interface/location-stringifier-expected.txt +++ b/third_party/WebKit/LayoutTests/external/wpt/html/browsers/history/the-location-interface/location-stringifier-expected.txt
@@ -4,6 +4,6 @@ PASS Location stringifier 2 PASS Location stringifier 3 PASS Location stringifier 4 -FAIL Location stringifier 5 assert_true: expected true got false +FAIL Location stringifier 5 assert_equals: expected "function" but got "undefined" Harness: the test ran to completion.
diff --git a/third_party/WebKit/LayoutTests/external/wpt/html/dom/interfaces-expected.txt b/third_party/WebKit/LayoutTests/external/wpt/html/dom/interfaces-expected.txt index e35ecbde..9e2df41 100644 --- a/third_party/WebKit/LayoutTests/external/wpt/html/dom/interfaces-expected.txt +++ b/third_party/WebKit/LayoutTests/external/wpt/html/dom/interfaces-expected.txt
@@ -1,5 +1,5 @@ This is a testharness.js-based test. -Found 5263 tests; 5146 PASS, 117 FAIL, 0 TIMEOUT, 0 NOTRUN. +Found 5263 tests; 5148 PASS, 115 FAIL, 0 TIMEOUT, 0 NOTRUN. PASS Test driver PASS Document interface: attribute domain PASS Document interface: attribute referrer @@ -1755,7 +1755,7 @@ PASS HTMLAreaElement interface: attribute download PASS HTMLAreaElement interface: attribute ping PASS HTMLAreaElement interface: attribute rel -FAIL HTMLAreaElement interface: attribute relList assert_true: The prototype object must have a property "relList" expected true got false +PASS HTMLAreaElement interface: attribute relList PASS HTMLAreaElement interface: attribute referrerPolicy PASS HTMLAreaElement interface: attribute noHref PASS HTMLAreaElement interface: attribute href @@ -1779,7 +1779,7 @@ PASS HTMLAreaElement interface: document.createElement("area") must inherit property "download" with the proper type PASS HTMLAreaElement interface: document.createElement("area") must inherit property "ping" with the proper type PASS HTMLAreaElement interface: document.createElement("area") must inherit property "rel" with the proper type -FAIL HTMLAreaElement interface: document.createElement("area") must inherit property "relList" with the proper type assert_inherits: property "relList" not found in prototype chain +PASS HTMLAreaElement interface: document.createElement("area") must inherit property "relList" with the proper type PASS HTMLAreaElement interface: document.createElement("area") must inherit property "referrerPolicy" with the proper type PASS HTMLAreaElement interface: document.createElement("area") must inherit property "noHref" with the proper type PASS HTMLAreaElement interface: document.createElement("area") must inherit property "href" with the proper type
diff --git a/third_party/WebKit/LayoutTests/external/wpt/html/semantics/text-level-semantics/the-area-element/rellist-feature-detection.html b/third_party/WebKit/LayoutTests/external/wpt/html/semantics/text-level-semantics/the-area-element/rellist-feature-detection.html new file mode 100644 index 0000000..1c818760 --- /dev/null +++ b/third_party/WebKit/LayoutTests/external/wpt/html/semantics/text-level-semantics/the-area-element/rellist-feature-detection.html
@@ -0,0 +1,53 @@ +<!DOCTYPE html> +<title>HTMLAreaElement relList</title> +<script src="/resources/testharness.js"></script> +<script src="/resources/testharnessreport.js"></script> +<script> +test(function() { + var element = document.createElement("area"); + // Test that setting rel is also setting relList, for both + // valid and invalid values. + element.rel = "whatever"; + assert_true(element.relList.contains("whatever")); + element.rel = "prefetch"; + assert_true(element.relList.contains("prefetch")); + // Test that add() works. + element.relList.add("preloadwhatever"); + assert_equals(element.rel, "prefetch preloadwhatever"); + assert_true(element.relList.contains("preloadwhatever")); + // Test that remove() works. + element.relList.remove("preloadwhatever"); + assert_equals(element.rel, "prefetch"); + assert_false(element.relList.contains("preloadwhatever")); + // Test that toggle() works. + element.relList.toggle("prefetch", false); + assert_equals(element.rel, ""); + element.relList.toggle("prefetch", true); + assert_equals(element.rel, "prefetch"); + // Test that replace() works. + element.relList.replace("prefetch", "first"); + assert_equals(element.rel, "first"); + // Test that indexed item getter works. + element.relList.add("second"); + assert_equals(element.relList.length, 2); + assert_equals(element.relList[0], "first"); + assert_equals(element.relList[1], "second"); + + // Test that supports() is returning true for valid values + // and false for invalid ones. + assert_false(element.relList.supports("bogus")); + assert_false(element.relList.supports("alternate")); + assert_false(element.relList.supports("author")); + assert_false(element.relList.supports("bookmark")); + assert_false(element.relList.supports("external")); + assert_false(element.relList.supports("help")); + assert_false(element.relList.supports("license")); + assert_false(element.relList.supports("next")); + assert_false(element.relList.supports("nofollow")); + assert_false(element.relList.supports("prev")); + assert_false(element.relList.supports("search")); + assert_false(element.relList.supports("tag")); + assert_true(element.relList.supports("noreferrer")); + assert_true(element.relList.supports("noopener")); +}, "Make sure that relList based feature detection is working"); +</script>
diff --git a/third_party/WebKit/LayoutTests/external/wpt/keyboard-lock/idlharness.https-expected.txt b/third_party/WebKit/LayoutTests/external/wpt/keyboard-lock/idlharness.https-expected.txt index 05e04afc..e9bfe08 100644 --- a/third_party/WebKit/LayoutTests/external/wpt/keyboard-lock/idlharness.https-expected.txt +++ b/third_party/WebKit/LayoutTests/external/wpt/keyboard-lock/idlharness.https-expected.txt
@@ -1,10 +1,10 @@ This is a testharness.js-based test. -FAIL Navigator interface: operation requestKeyboardLock(sequence) assert_throws: calling operation with this = null didn't throw TypeError function "function () { +FAIL Navigator interface: operation keyboardLock(sequence) assert_throws: calling operation with this = null didn't throw TypeError function "function () { fn.apply(obj, args); }" did not throw -PASS Navigator interface: operation cancelKeyboardLock() -PASS Navigator interface: navigator must inherit property "requestKeyboardLock(sequence)" with the proper type -PASS Navigator interface: calling requestKeyboardLock(sequence) on navigator with too few arguments must throw TypeError -PASS Navigator interface: navigator must inherit property "cancelKeyboardLock()" with the proper type +PASS Navigator interface: operation keyboardUnlock() +PASS Navigator interface: navigator must inherit property "keyboardLock(sequence)" with the proper type +PASS Navigator interface: calling keyboardLock(sequence) on navigator with too few arguments must throw TypeError +PASS Navigator interface: navigator must inherit property "keyboardUnlock()" with the proper type Harness: the test ran to completion.
diff --git a/third_party/WebKit/LayoutTests/external/wpt/keyboard-lock/idlharness.https.html b/third_party/WebKit/LayoutTests/external/wpt/keyboard-lock/idlharness.https.html index 4e06d57..9caa379f 100644 --- a/third_party/WebKit/LayoutTests/external/wpt/keyboard-lock/idlharness.https.html +++ b/third_party/WebKit/LayoutTests/external/wpt/keyboard-lock/idlharness.https.html
@@ -14,7 +14,7 @@ }; </pre> <!-- - The reason of the failure of requestKeyboardLock test looks like a code defect in + The reason of the failure of keyboardLock test looks like a code defect in idlharness.js. media-capabilities/idlharness.html is also impacted by this issue. See https://codereview.chromium.org/2805763004/#ps620001, which includes a potential fix. @@ -22,8 +22,8 @@ --> <pre id="idl" style="display: none"> partial interface Navigator { - [SecureContext] Promise<void> requestKeyboardLock(optional sequence<DOMString> keyCodes = []); - [SecureContext] void cancelKeyboardLock(); + [SecureContext] Promise<void> keyboardLock(optional sequence<DOMString> keyCodes = []); + [SecureContext] void keyboardUnlock(); }; </pre> <script>
diff --git a/third_party/WebKit/LayoutTests/external/wpt/keyboard-lock/navigator-keyboardLock-two-parallel-requests.https-expected.txt b/third_party/WebKit/LayoutTests/external/wpt/keyboard-lock/navigator-keyboardLock-two-parallel-requests.https-expected.txt new file mode 100644 index 0000000..f718259 --- /dev/null +++ b/third_party/WebKit/LayoutTests/external/wpt/keyboard-lock/navigator-keyboardLock-two-parallel-requests.https-expected.txt
@@ -0,0 +1,4 @@ +This is a testharness.js-based test. +FAIL Keyboard Lock keyboardLock twice in parallel Test bug: need to pass exception to assert_throws() +Harness: the test ran to completion. +
diff --git a/third_party/WebKit/LayoutTests/external/wpt/keyboard-lock/navigator-keyboardLock-two-parallel-requests.https.html b/third_party/WebKit/LayoutTests/external/wpt/keyboard-lock/navigator-keyboardLock-two-parallel-requests.https.html new file mode 100644 index 0000000..d553c06 --- /dev/null +++ b/third_party/WebKit/LayoutTests/external/wpt/keyboard-lock/navigator-keyboardLock-two-parallel-requests.https.html
@@ -0,0 +1,15 @@ +<!DOCTYPE html> +<script src="/resources/testharness.js"></script> +<script src="/resources/testharnessreport.js"></script> +<script> +'use strict'; + +promise_test((t) => { + const p1 = navigator.keyboardLock(['a', 'b']); + const p2 = navigator.keyboardLock(['c', 'd']); + return promise_rejects(t, null, p2, + 'keyboardLock() should only be ' + + 'executed if another request has finished.'); +}, 'Keyboard Lock keyboardLock twice in parallel'); + +</script>
diff --git a/third_party/WebKit/LayoutTests/external/wpt/keyboard-lock/navigator-keyboardLock-two-sequential-requests.https.html b/third_party/WebKit/LayoutTests/external/wpt/keyboard-lock/navigator-keyboardLock-two-sequential-requests.https.html new file mode 100644 index 0000000..7670be4f --- /dev/null +++ b/third_party/WebKit/LayoutTests/external/wpt/keyboard-lock/navigator-keyboardLock-two-sequential-requests.https.html
@@ -0,0 +1,14 @@ +<!DOCTYPE html> +<script src="/resources/testharness.js"></script> +<script src="/resources/testharnessreport.js"></script> +<script> +'use strict'; + +promise_test(() => { + return navigator.keyboardLock(['a', 'b']) + .then(() => { + return navigator.keyboardLock(['c', 'd']); + }); +}, 'Keyboard Lock keyboardLock twice sequentially'); + +</script>
diff --git a/third_party/WebKit/LayoutTests/external/wpt/keyboard-lock/navigator-requestKeyboardLock.https.html b/third_party/WebKit/LayoutTests/external/wpt/keyboard-lock/navigator-keyboardLock.https.html similarity index 70% rename from third_party/WebKit/LayoutTests/external/wpt/keyboard-lock/navigator-requestKeyboardLock.https.html rename to third_party/WebKit/LayoutTests/external/wpt/keyboard-lock/navigator-keyboardLock.https.html index e6e0121..6711dec 100644 --- a/third_party/WebKit/LayoutTests/external/wpt/keyboard-lock/navigator-requestKeyboardLock.https.html +++ b/third_party/WebKit/LayoutTests/external/wpt/keyboard-lock/navigator-keyboardLock.https.html
@@ -5,9 +5,9 @@ 'use strict'; promise_test(() => { - const p = navigator.requestKeyboardLock(['a', 'b']); + const p = navigator.keyboardLock(['a', 'b']); assert_true(p instanceof Promise); return p; -}, 'Keyboard Lock requestKeyboardLock'); +}, 'Keyboard Lock keyboardLock'); </script>
diff --git a/third_party/WebKit/LayoutTests/external/wpt/keyboard-lock/navigator-cancelKeyboardLock.https.html b/third_party/WebKit/LayoutTests/external/wpt/keyboard-lock/navigator-keyboardUnlock.https.html similarity index 69% rename from third_party/WebKit/LayoutTests/external/wpt/keyboard-lock/navigator-cancelKeyboardLock.https.html rename to third_party/WebKit/LayoutTests/external/wpt/keyboard-lock/navigator-keyboardUnlock.https.html index 10fd50d3..ceb7a96 100644 --- a/third_party/WebKit/LayoutTests/external/wpt/keyboard-lock/navigator-cancelKeyboardLock.https.html +++ b/third_party/WebKit/LayoutTests/external/wpt/keyboard-lock/navigator-keyboardUnlock.https.html
@@ -5,8 +5,8 @@ 'use strict'; test(() => { - assert_equals(navigator.cancelKeyboardLock(), + assert_equals(navigator.keyboardUnlock(), undefined); -}, 'Keyboard Lock cancelKeyboardLock'); +}, 'Keyboard Lock keyboardUnlock'); </script>
diff --git a/third_party/WebKit/LayoutTests/external/wpt/keyboard-lock/navigator-requestKeyboardLock-two-parallel-requests.https-expected.txt b/third_party/WebKit/LayoutTests/external/wpt/keyboard-lock/navigator-requestKeyboardLock-two-parallel-requests.https-expected.txt deleted file mode 100644 index d74fd153..0000000 --- a/third_party/WebKit/LayoutTests/external/wpt/keyboard-lock/navigator-requestKeyboardLock-two-parallel-requests.https-expected.txt +++ /dev/null
@@ -1,4 +0,0 @@ -This is a testharness.js-based test. -FAIL Keyboard Lock requestKeyboardLock twice in parallel Test bug: need to pass exception to assert_throws() -Harness: the test ran to completion. -
diff --git a/third_party/WebKit/LayoutTests/external/wpt/keyboard-lock/navigator-requestKeyboardLock-two-parallel-requests.https.html b/third_party/WebKit/LayoutTests/external/wpt/keyboard-lock/navigator-requestKeyboardLock-two-parallel-requests.https.html deleted file mode 100644 index 8e84d14..0000000 --- a/third_party/WebKit/LayoutTests/external/wpt/keyboard-lock/navigator-requestKeyboardLock-two-parallel-requests.https.html +++ /dev/null
@@ -1,15 +0,0 @@ -<!DOCTYPE html> -<script src="/resources/testharness.js"></script> -<script src="/resources/testharnessreport.js"></script> -<script> -'use strict'; - -promise_test((t) => { - const p1 = navigator.requestKeyboardLock(['a', 'b']); - const p2 = navigator.requestKeyboardLock(['c', 'd']); - return promise_rejects(t, null, p2, - 'requestKeyboardLock() should only be ' + - 'executed if another request has finished.'); -}, 'Keyboard Lock requestKeyboardLock twice in parallel'); - -</script>
diff --git a/third_party/WebKit/LayoutTests/external/wpt/keyboard-lock/navigator-requestKeyboardLock-two-sequential-requests.https.html b/third_party/WebKit/LayoutTests/external/wpt/keyboard-lock/navigator-requestKeyboardLock-two-sequential-requests.https.html deleted file mode 100644 index 30f4905..0000000 --- a/third_party/WebKit/LayoutTests/external/wpt/keyboard-lock/navigator-requestKeyboardLock-two-sequential-requests.https.html +++ /dev/null
@@ -1,14 +0,0 @@ -<!DOCTYPE html> -<script src="/resources/testharness.js"></script> -<script src="/resources/testharnessreport.js"></script> -<script> -'use strict'; - -promise_test(() => { - return navigator.requestKeyboardLock(['a', 'b']) - .then(() => { - return navigator.requestKeyboardLock(['c', 'd']); - }); -}, 'Keyboard Lock requestKeyboardLock twice sequentially'); - -</script>
diff --git a/third_party/WebKit/LayoutTests/external/wpt/webrtc/RTCPeerConnection-track-stats.https-expected.txt b/third_party/WebKit/LayoutTests/external/wpt/webrtc/RTCPeerConnection-track-stats.https-expected.txt new file mode 100644 index 0000000..d45a3fa --- /dev/null +++ b/third_party/WebKit/LayoutTests/external/wpt/webrtc/RTCPeerConnection-track-stats.https-expected.txt
@@ -0,0 +1,9 @@ +This is a testharness.js-based test. +FAIL addTrack() without setLocalDescription() yields track stats assert_true: Has stats for track expected true got false +FAIL addTrack() without setLocalDescription() yields stream stats assert_true: Has stats for stream expected true got false +PASS addTrack() with setLocalDescription() yields track stats +FAIL addTrack() with setLocalDescription() yields stream stats assert_true: Has stats for stream expected true got false +FAIL addTrack(): Stream stats references track stats assert_true: Has stats for track and stream expected true got false +PASS Legacy addStream(): Stream stats references track stats +Harness: the test ran to completion. +
diff --git a/third_party/WebKit/LayoutTests/external/wpt/webrtc/RTCPeerConnection-track-stats.https.html b/third_party/WebKit/LayoutTests/external/wpt/webrtc/RTCPeerConnection-track-stats.https.html new file mode 100644 index 0000000..818121b0 --- /dev/null +++ b/third_party/WebKit/LayoutTests/external/wpt/webrtc/RTCPeerConnection-track-stats.https.html
@@ -0,0 +1,187 @@ +<!doctype html> +<meta charset=utf-8> +<title>RTCPeerConnection.prototype.getStats</title> +<script src="/resources/testharness.js"></script> +<script src="/resources/testharnessreport.js"></script> +<script src="RTCPeerConnection-helper.js"></script> +<script> + 'use strict'; + + // The following helper functions are called from RTCPeerConnection-helper.js: + // getUserMediaTracksAndStreams + + async_test(t => { + const pc = new RTCPeerConnection(); + let track; + return getUserMediaTracksAndStreams(1) + .then(t.step_func(([tracks, streams]) => { + track = tracks[0]; + pc.addTrack(track); + return pc.getStats(); + })) + .then(t.step_func(report => { + let trackStats = findStatsByTypeAndId(report, 'track', track.id); + assert_true(trackStats != null, 'Has stats for track'); + t.done(); + })) + .catch(t.step_func(reason => { + assert_unreached(reason); + })); + }, 'addTrack() without setLocalDescription() yields track stats'); + + async_test(t => { + const pc = new RTCPeerConnection(); + let stream; + return getUserMediaTracksAndStreams(1) + .then(t.step_func(([tracks, streams]) => { + let track = tracks[0]; + stream = streams[0]; + pc.addTrack(track, stream); + return pc.getStats(); + })) + .then(t.step_func(report => { + let streamStats = findStatsByTypeAndId(report, 'stream', stream.id); + assert_true(streamStats != null, 'Has stats for stream'); + t.done(); + })) + .catch(t.step_func(reason => { + assert_unreached(reason); + })); + }, 'addTrack() without setLocalDescription() yields stream stats'); + + async_test(t => { + const pc = new RTCPeerConnection(); + let track; + return getUserMediaTracksAndStreams(1) + .then(t.step_func(([tracks, streams]) => { + track = tracks[0]; + pc.addTrack(track); + return pc.createOffer(); + })) + .then(t.step_func(offer => { + return pc.setLocalDescription(offer); + })) + .then(t.step_func(() => { + return pc.getStats(); + })) + .then(t.step_func(report => { + let trackStats = findStatsByTypeAndId(report, 'track', track.id); + assert_true(trackStats != null, 'Has stats for track'); + t.done(); + })) + .catch(t.step_func(reason => { + assert_unreached(reason); + })); + }, 'addTrack() with setLocalDescription() yields track stats'); + + async_test(t => { + const pc = new RTCPeerConnection(); + let stream; + return getUserMediaTracksAndStreams(1) + .then(t.step_func(([tracks, streams]) => { + let track = tracks[0]; + stream = streams[0]; + pc.addTrack(track, stream); + return pc.createOffer(); + })) + .then(t.step_func(offer => { + return pc.setLocalDescription(offer); + })) + .then(t.step_func(() => { + return pc.getStats(); + })) + .then(t.step_func(report => { + let streamStats = findStatsByTypeAndId(report, 'stream', stream.id); + assert_true(streamStats != null, 'Has stats for stream'); + t.done(); + })) + .catch(t.step_func(reason => { + assert_unreached(reason); + })); + }, 'addTrack() with setLocalDescription() yields stream stats'); + + async_test(t => { + const pc = new RTCPeerConnection(); + let track; + let stream; + return getUserMediaTracksAndStreams(1) + .then(t.step_func(([tracks, streams]) => { + track = tracks[0]; + stream = streams[0]; + pc.addTrack(track, stream); + return pc.createOffer(); + })) + .then(t.step_func(offer => { + return pc.setLocalDescription(offer); + })) + .then(t.step_func(() => { + return pc.getStats(); + })) + .then(t.step_func(report => { + let trackStats = findStatsByTypeAndId(report, 'track', track.id); + let streamStats = findStatsByTypeAndId(report, 'stream', stream.id); + assert_true(trackStats != null && streamStats != null, + 'Has stats for track and stream'); + assert_array_equals(streamStats.trackIds, [ trackStats.id ], + 'streamStats.trackIds == [ trackStats.id ]'); + t.done(); + })) + .catch(t.step_func(reason => { + assert_unreached(reason); + })); + }, 'addTrack(): Stream stats references track stats'); + + // TODO(hbos): addStream() is legacy API not in the spec. Based on discussion + // whether to standardize in legacy section, consider removing this test or + // keeping it until addTrack() has wide support. + // https://github.com/w3c/webrtc-pc/issues/1705 + // https://github.com/w3c/webrtc-pc/issues/1125 + async_test(t => { + const pc = new RTCPeerConnection(); + let track; + let stream; + return getUserMediaTracksAndStreams(1) + .then(t.step_func(([tracks, streams]) => { + track = tracks[0]; + stream = streams[0]; + stream.addTrack(track); + pc.addStream(stream); + return pc.createOffer(); + })) + .then(t.step_func(offer => { + return pc.setLocalDescription(offer); + })) + .then(t.step_func(() => { + return pc.getStats(); + })) + .then(t.step_func(report => { + let trackStats = findStatsByTypeAndId(report, 'track', track.id); + let streamStats = findStatsByTypeAndId(report, 'stream', stream.id); + assert_true(trackStats != null && streamStats != null, + 'Has stats for track and stream'); + assert_array_equals(streamStats.trackIds, [ trackStats.id ], + 'streamStats.trackIds == [ trackStats.id ]'); + t.done(); + })) + .catch(t.step_func(reason => { + assert_unreached(reason); + })); + }, 'Legacy addStream(): Stream stats references track stats'); + + // Helpers. + + function findStatsByTypeAndId(report, type, identifier) { + return findStats(report, stats => { + return stats.type == type && stats[type + 'Identifier'] == identifier; + }); + } + + function findStats(report, findFunc) { + for (let it = report.values(), n = it.next(); !n.done; n = it.next()) { + if (findFunc(n.value)) + return n.value; + } + return null; + } + +</script>
diff --git a/third_party/WebKit/LayoutTests/external/wpt/webvtt/api/VTTRegion/constructor.html b/third_party/WebKit/LayoutTests/external/wpt/webvtt/api/VTTRegion/constructor.html index 53c1968..59eeaf8 100644 --- a/third_party/WebKit/LayoutTests/external/wpt/webvtt/api/VTTRegion/constructor.html +++ b/third_party/WebKit/LayoutTests/external/wpt/webvtt/api/VTTRegion/constructor.html
@@ -7,12 +7,53 @@ <script> test(function() { var region = new VTTRegion(); - assert_equals(region.width, 100); - assert_equals(region.lines, 3); - assert_equals(region.regionAnchorX, 0); - assert_equals(region.regionAnchorY, 100); + assert_true(region instanceof VTTRegion, "instanceof"); + + assert_equals(region.scroll, ""); assert_equals(region.viewportAnchorX, 0); assert_equals(region.viewportAnchorY, 100); - assert_equals(region.scroll, ''); -}, document.title + ' initial values'); + assert_equals(region.regionAnchorX, 0); + assert_equals(region.regionAnchorY, 100); + assert_equals(region.lines, 3); + assert_equals(region.width, 100); +}, document.title + " initial values"); + +test(function() { + var region = new VTTRegion(); + region.scroll = "invalid-scroll-value"; + assert_equals(region.scroll, ""); + + checkValues([-1, 101], "IndexSizeError"); + checkValues([-Infinity, Infinity, NaN], new TypeError); + function checkValues(invalidValues, exception) { + for (var value of invalidValues) { + assert_throws(exception, function() { region.viewportAnchorX = value; }); + assert_equals(region.viewportAnchorX, 0); + assert_throws(exception, function() { region.viewportAnchorY = value; }); + assert_equals(region.viewportAnchorY, 100); + assert_throws(exception, function() { region.regionAnchorX = value; }); + assert_equals(region.regionAnchorX, 0); + assert_throws(exception, function() { region.regionAnchorY = value; }); + assert_equals(region.regionAnchorY, 100); + assert_throws(exception, function() { region.width = value; }); + assert_equals(region.width, 100); + } + } + + assert_throws("IndexSizeError", function() { region.lines = -1; }); + assert_equals(region.lines, 3); + + region.lines = 130; + assert_equals(region.lines, 130); + region.viewportAnchorX = 64; + assert_equals(region.viewportAnchorX, 64); + region.viewportAnchorY = 32; + assert_equals(region.viewportAnchorY, 32); + region.regionAnchorX = 16; + assert_equals(region.regionAnchorX, 16); + region.regionAnchorY = 8; + assert_equals(region.regionAnchorY, 8); + region.width = 42; + assert_equals(region.width, 42); +}, document.title + " mutations"); </script>
diff --git a/third_party/WebKit/LayoutTests/media/track/regions-webvtt/vtt-region-non-visible-crash.html b/third_party/WebKit/LayoutTests/external/wpt/webvtt/api/VTTRegion/non-visible-cue-with-region.html similarity index 63% rename from third_party/WebKit/LayoutTests/media/track/regions-webvtt/vtt-region-non-visible-crash.html rename to third_party/WebKit/LayoutTests/external/wpt/webvtt/api/VTTRegion/non-visible-cue-with-region.html index c5dc3e3..5a48e46 100644 --- a/third_party/WebKit/LayoutTests/media/track/regions-webvtt/vtt-region-non-visible-crash.html +++ b/third_party/WebKit/LayoutTests/external/wpt/webvtt/api/VTTRegion/non-visible-cue-with-region.html
@@ -1,13 +1,13 @@ <!DOCTYPE html> -<title>Box-less VTTCue attached to VTTRegion should not crash</title> -<script src="../../../resources/testharness.js"></script> -<script src="../../../resources/testharnessreport.js"></script> -<script src="../../media-file.js"></script> +<title>Box-less VTTCue attached to VTTRegion</title> +<script src="/common/media.js"></script> +<script src="/resources/testharness.js"></script> +<script src="/resources/testharnessreport.js"></script> <video></video> <script> setup(function() { window.video = document.querySelector('video'); - video.src = findMediaFile('video', '../../content/test'); + video.src = getVideoURI('/media/test'); }); async_test(function(t) { let track = video.addTextTrack('subtitles');
diff --git a/third_party/WebKit/LayoutTests/media/track/regions-webvtt/vtt-region-parser.html b/third_party/WebKit/LayoutTests/external/wpt/webvtt/parsing/file-parsing/tests/header-regions.html similarity index 79% rename from third_party/WebKit/LayoutTests/media/track/regions-webvtt/vtt-region-parser.html rename to third_party/WebKit/LayoutTests/external/wpt/webvtt/parsing/file-parsing/tests/header-regions.html index f27add7..b10fcbc 100644 --- a/third_party/WebKit/LayoutTests/media/track/regions-webvtt/vtt-region-parser.html +++ b/third_party/WebKit/LayoutTests/external/wpt/webvtt/parsing/file-parsing/tests/header-regions.html
@@ -1,8 +1,8 @@ <!DOCTYPE html> <title>Tests proper parsing of various regions present in WebVTT header area.</title> -<script src="../../media-file.js"></script> -<script src="../../../resources/testharness.js"></script> -<script src="../../../resources/testharnessreport.js"></script> +<script src="/common/media.js"></script> +<script src="/resources/testharness.js"></script> +<script src="/resources/testharnessreport.js"></script> <script> const regionDefaults = { width: 100, @@ -18,7 +18,7 @@ for (var prop in regionDefaults) { if (!(prop in expected)) expected[prop] = regionDefaults[prop]; - assert_equals(region[prop], expected[prop], prop + ' (cue '+(i+1)+')'); + assert_equals(region[prop], expected[prop], prop + ' (cue ' + ( i + 1 ) + ')'); } } @@ -35,14 +35,14 @@ async_test(function(t) { var video = document.createElement('video'); - video.src = findMediaFile('video', '../../content/test'); + video.src = getVideoURI('/media/test'); var testTrack = document.createElement('track'); testTrack.onload = t.step_func_done(function() { var track = testTrack.track; assert_equals(track.cues.length, 9); checkCueRegions(track.cues); }); - testTrack.src = '../captions-webvtt/header-regions.vtt'; + testTrack.src = 'support/header-regions.vtt'; testTrack.kind = 'captions'; testTrack.default = true; video.appendChild(testTrack);
diff --git a/third_party/WebKit/LayoutTests/media/track/captions-webvtt/header-regions.vtt b/third_party/WebKit/LayoutTests/external/wpt/webvtt/parsing/file-parsing/tests/support/header-regions.vtt similarity index 100% rename from third_party/WebKit/LayoutTests/media/track/captions-webvtt/header-regions.vtt rename to third_party/WebKit/LayoutTests/external/wpt/webvtt/parsing/file-parsing/tests/support/header-regions.vtt
diff --git a/third_party/WebKit/LayoutTests/fast/dom/Window/window-appendages-cleared-expected.txt b/third_party/WebKit/LayoutTests/fast/dom/Window/window-appendages-cleared-expected.txt index 98b7a3b..d5f6195 100644 --- a/third_party/WebKit/LayoutTests/fast/dom/Window/window-appendages-cleared-expected.txt +++ b/third_party/WebKit/LayoutTests/fast/dom/Window/window-appendages-cleared-expected.txt
@@ -19,6 +19,7 @@ PASS location.reload == "LEFTOVER" is false PASS location.replace == "LEFTOVER" is false PASS location.search == "LEFTOVER" is false +PASS location.toString == "LEFTOVER" is false PASS locationbar.visible == "LEFTOVER" is false PASS menubar.visible == "LEFTOVER" is false PASS personalbar.visible == "LEFTOVER" is false
diff --git a/third_party/WebKit/LayoutTests/fast/invalid/residual-style-expected.html b/third_party/WebKit/LayoutTests/fast/invalid/residual-style-expected.html index 5b66239..a7c7dda 100644 --- a/third_party/WebKit/LayoutTests/fast/invalid/residual-style-expected.html +++ b/third_party/WebKit/LayoutTests/fast/invalid/residual-style-expected.html
@@ -1,6 +1,7 @@ <!DOCTYPE html> <head> <style> +html { font-kerning: none; } font { color: green } .expected-fail { color: red } .expected-fail-black { color: black; }
diff --git a/third_party/WebKit/LayoutTests/fast/invalid/residual-style.html b/third_party/WebKit/LayoutTests/fast/invalid/residual-style.html index 2934a55..ffd7093 100644 --- a/third_party/WebKit/LayoutTests/fast/invalid/residual-style.html +++ b/third_party/WebKit/LayoutTests/fast/invalid/residual-style.html
@@ -1,6 +1,7 @@ <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN"> <head> <style> +html { font-kerning: none; } font { color: green } .fail { color: red } address { display: inline; font-style: normal }
diff --git a/third_party/WebKit/LayoutTests/fast/js/toString-dontEnum-expected.txt b/third_party/WebKit/LayoutTests/fast/js/toString-dontEnum-expected.txt index 961b847..49c0c9c 100644 --- a/third_party/WebKit/LayoutTests/fast/js/toString-dontEnum-expected.txt +++ b/third_party/WebKit/LayoutTests/fast/js/toString-dontEnum-expected.txt
@@ -1,6 +1,5 @@ This tests that the toString() function does not enumerate. -PASS: the toString function is not enumerable for Location. PASS: the toString function is not enumerable for HTMLDivElement. PASS: the toString function is not enumerable for HTMLDocument. PASS: the toString function is not enumerable for Object.
diff --git a/third_party/WebKit/LayoutTests/fast/js/toString-dontEnum.html b/third_party/WebKit/LayoutTests/fast/js/toString-dontEnum.html index f7c7612..67a3c319 100644 --- a/third_party/WebKit/LayoutTests/fast/js/toString-dontEnum.html +++ b/third_party/WebKit/LayoutTests/fast/js/toString-dontEnum.html
@@ -24,9 +24,6 @@ if (window.testRunner) testRunner.dumpAsText(); - // DOM objects with custom toString() functions - test(window.location, "Location"); - // Other DOM objects test(document.createElement('div'), "HTMLDivElement"); test(document, "HTMLDocument");
diff --git a/third_party/WebKit/LayoutTests/fast/text/international/shape-across-elements-simple-expected.html b/third_party/WebKit/LayoutTests/fast/text/international/shape-across-elements-simple-expected.html new file mode 100644 index 0000000..b2c88b9a --- /dev/null +++ b/third_party/WebKit/LayoutTests/fast/text/international/shape-across-elements-simple-expected.html
@@ -0,0 +1,17 @@ +<!DOCTYPE html> +<style> +@font-face { + font-family: megalopolis; + src: url(../../../third_party/MEgalopolis/MEgalopolisExtra.woff) format("woff"); +} +html { + font-size: 50px; + font-family: megalopolis; +} +</style> +<body> +<div><span>AVA</span></div> +<div><span>ff fi ffi efi</span></div> +<div><span>سلام</span></div> +<div><span>سلام</span></div> +</body>
diff --git a/third_party/WebKit/LayoutTests/fast/text/international/shape-across-elements-simple.html b/third_party/WebKit/LayoutTests/fast/text/international/shape-across-elements-simple.html new file mode 100644 index 0000000..5f53961 --- /dev/null +++ b/third_party/WebKit/LayoutTests/fast/text/international/shape-across-elements-simple.html
@@ -0,0 +1,17 @@ +<!DOCTYPE html> +<style> +@font-face { + font-family: megalopolis; + src: url(../../../third_party/MEgalopolis/MEgalopolisExtra.woff) format("woff"); +} +html { + font-size: 50px; + font-family: megalopolis; +} +</style> +<body> +<div><span>A<span>V</span>A</span></div> +<div><span>f<span>f</span> f<span>i</span> f<span>f</span>i e<span>f</span>i</span></div> +<div><span>س<span>ل</span>ام</span></div> +<div><span>سل<span>ا</span>م</span></div> +</body>
diff --git a/third_party/WebKit/LayoutTests/fast/text/unmatched-surrogate-pair-expected.html b/third_party/WebKit/LayoutTests/fast/text/unmatched-surrogate-pair-expected.html index 61569ac..483bba97 100644 --- a/third_party/WebKit/LayoutTests/fast/text/unmatched-surrogate-pair-expected.html +++ b/third_party/WebKit/LayoutTests/fast/text/unmatched-surrogate-pair-expected.html
@@ -10,7 +10,9 @@ <div>Second part of surrogate pair, "�". Should print replacement character and rest of run.</div> <br> <div>Spanning text nodes:</div> + <!-- Rendering of unmatched surrogate pair is not interoperable. <div>- First part "��" second part.</div> + --> <div>After element.normalize():</div> <div>- First part "🌎" second part.</div> </body>
diff --git a/third_party/WebKit/LayoutTests/fast/text/unmatched-surrogate-pair.html b/third_party/WebKit/LayoutTests/fast/text/unmatched-surrogate-pair.html index 77cdc9ee4..42a0a88 100644 --- a/third_party/WebKit/LayoutTests/fast/text/unmatched-surrogate-pair.html +++ b/third_party/WebKit/LayoutTests/fast/text/unmatched-surrogate-pair.html
@@ -29,7 +29,8 @@ var container = document.createElement('div'); container.appendChild(nodeA); container.appendChild(nodeB); - document.body.appendChild(container); + // Rendering of unmatched surrogate pair is not interoperable. + // document.body.appendChild(container); appendLine('After element.normalize():'); var clone = container.cloneNode(true);
diff --git a/third_party/WebKit/LayoutTests/fast/workers/resources/shared-worker-file-url-window.html b/third_party/WebKit/LayoutTests/fast/workers/resources/shared-worker-file-url-window.html new file mode 100644 index 0000000..30308c5 --- /dev/null +++ b/third_party/WebKit/LayoutTests/fast/workers/resources/shared-worker-file-url-window.html
@@ -0,0 +1,17 @@ +<!DOCTYPE html> +<head> +<title>file:// URL shared worker</title> +</head> +<body> +<script> +onmessage = event => { + const kScriptURL = 'shared-worker-file-url-worker.js?different'; + const port = event.ports[0]; + const worker = new SharedWorker(kScriptURL); + worker.port.onmessage = e => port.postMessage(e.data); +}; + +window.opener.postMessage('LOADED', '*'); +</script> +</body> +</html>
diff --git a/third_party/WebKit/LayoutTests/fast/workers/resources/shared-worker-file-url-worker.js b/third_party/WebKit/LayoutTests/fast/workers/resources/shared-worker-file-url-worker.js new file mode 100644 index 0000000..f31806eb --- /dev/null +++ b/third_party/WebKit/LayoutTests/fast/workers/resources/shared-worker-file-url-worker.js
@@ -0,0 +1,7 @@ +// Sends back the count of connections with this shared worker. +onconnect = e => { + if (self.count === undefined) + self.count = 0; + self.count++; + e.ports[0].postMessage({ connection_count: self.count }); +};
diff --git a/third_party/WebKit/LayoutTests/fast/workers/shared-worker-file-url.html b/third_party/WebKit/LayoutTests/fast/workers/shared-worker-file-url.html new file mode 100644 index 0000000..4f5576f --- /dev/null +++ b/third_party/WebKit/LayoutTests/fast/workers/shared-worker-file-url.html
@@ -0,0 +1,70 @@ +<!DOCTYPE html> +<title>SharedWorker: </title> +<script src="../../resources/testharness.js"></script> +<script src="../../resources/testharnessreport.js"></script> +<script> + +function openWindow(url) { + return new Promise(resolve => { + const win = window.open(url, '_blank'); + add_completion_callback(() => win.close()); + window.onmessage = e => { + assert_equals(e.data, 'LOADED'); + resolve(win); + }; + }); +} + +promise_test(() => { + const kScriptURL = 'resources/shared-worker-file-url-worker.js?same'; + const workers = []; + + // Ensure this document and script is hosted on file:// URL. + assert_equals((new URL(location.href)).origin, 'file://'); + assert_equals((new URL(kScriptURL, location.href)).origin, 'file://'); + + return new Promise(resolve => { + workers.push(new SharedWorker(kScriptURL)); + workers[0].port.onmessage = resolve; + }) + .then(msg_event => { + assert_equals(msg_event.data.connection_count, 1); + workers.push(new SharedWorker(kScriptURL)); + return new Promise(resolve => workers[1].port.onmessage = resolve); + }) + .then(msg_event => { + // The connection count should be 1 because the file: URL document + // always connects to to a new shared worker instance. + assert_equals(msg_event.data.connection_count, 1); + }); +}, 'A file: URL document should not connect to an existing shared worker.'); + +promise_test(() => { + const kWindowURL = 'resources/shared-worker-file-url-window.html'; + const kScriptURL = 'resources/shared-worker-file-url-worker.js?different'; + let worker; + + // Ensure this document and script is hosted on file:// URL. + assert_equals((new URL(location.href)).origin, 'file://'); + assert_equals((new URL(kScriptURL, location.href)).origin, 'file://'); + + return openWindow(kWindowURL) + .then(win => { + const channel = new MessageChannel; + win.postMessage(channel.port1, '*', [channel.port1]); + return new Promise(resolve => channel.port2.onmessage = resolve); + }) + .then(msg_event => { + assert_equals(msg_event.data.connection_count, 1); + worker = new SharedWorker(kScriptURL); + return new Promise(resolve => worker.port.onmessage = resolve); + }) + .then(msg_event => { + // The connection count should be 1 because the file: URL document + // always connects to to a new shared worker instance. + assert_equals(msg_event.data.connection_count, 1); + }); +}, 'A file: URL document should not connect to an existing shared worker ' + + 'created by the other document in the different directory.'); + +</script>
diff --git a/third_party/WebKit/LayoutTests/flag-specific/enable-blink-features=LayoutNG/css1/text_properties/text_transform-expected.png b/third_party/WebKit/LayoutTests/flag-specific/enable-blink-features=LayoutNG/css1/text_properties/text_transform-expected.png index 4e7cb4e..c90efb6 100644 --- a/third_party/WebKit/LayoutTests/flag-specific/enable-blink-features=LayoutNG/css1/text_properties/text_transform-expected.png +++ b/third_party/WebKit/LayoutTests/flag-specific/enable-blink-features=LayoutNG/css1/text_properties/text_transform-expected.png Binary files differ
diff --git a/third_party/WebKit/LayoutTests/flag-specific/enable-blink-features=LayoutNG/css2.1/t1602-c546-txt-align-00-b-expected.png b/third_party/WebKit/LayoutTests/flag-specific/enable-blink-features=LayoutNG/css2.1/t1602-c546-txt-align-00-b-expected.png index 21c392a..3fd0a77 100644 --- a/third_party/WebKit/LayoutTests/flag-specific/enable-blink-features=LayoutNG/css2.1/t1602-c546-txt-align-00-b-expected.png +++ b/third_party/WebKit/LayoutTests/flag-specific/enable-blink-features=LayoutNG/css2.1/t1602-c546-txt-align-00-b-expected.png Binary files differ
diff --git a/third_party/WebKit/LayoutTests/flag-specific/enable-blink-features=LayoutNG/css2.1/t1602-c546-txt-align-00-b-expected.txt b/third_party/WebKit/LayoutTests/flag-specific/enable-blink-features=LayoutNG/css2.1/t1602-c546-txt-align-00-b-expected.txt index f64c167..9a5d203f 100644 --- a/third_party/WebKit/LayoutTests/flag-specific/enable-blink-features=LayoutNG/css2.1/t1602-c546-txt-align-00-b-expected.txt +++ b/third_party/WebKit/LayoutTests/flag-specific/enable-blink-features=LayoutNG/css2.1/t1602-c546-txt-align-00-b-expected.txt
@@ -12,5 +12,5 @@ LayoutNGBlockFlow {P} at (0,108) size 784x280 [color=#000080] LayoutText {#text} at (0,0) size 497x19 LayoutInline {SPAN} at (0,0) size 0x0 [color=#C0C0C0] - LayoutText {#text} at (0,0) size 785x279 - LayoutText {#text} at (0,0) size 381x19 + LayoutText {#text} at (0,0) size 784x279 + LayoutText {#text} at (0,0) size 382x19
diff --git a/third_party/WebKit/LayoutTests/flag-specific/enable-blink-features=LayoutNG/fast/inline/drawStyledEmptyInlines-expected.png b/third_party/WebKit/LayoutTests/flag-specific/enable-blink-features=LayoutNG/fast/inline/drawStyledEmptyInlines-expected.png index 23ad715..2ca4f83 100644 --- a/third_party/WebKit/LayoutTests/flag-specific/enable-blink-features=LayoutNG/fast/inline/drawStyledEmptyInlines-expected.png +++ b/third_party/WebKit/LayoutTests/flag-specific/enable-blink-features=LayoutNG/fast/inline/drawStyledEmptyInlines-expected.png Binary files differ
diff --git a/third_party/WebKit/LayoutTests/flag-specific/enable-blink-features=LayoutNG/fast/layers/inline-dirty-z-order-lists-expected.png b/third_party/WebKit/LayoutTests/flag-specific/enable-blink-features=LayoutNG/fast/layers/inline-dirty-z-order-lists-expected.png new file mode 100644 index 0000000..aef3b9a --- /dev/null +++ b/third_party/WebKit/LayoutTests/flag-specific/enable-blink-features=LayoutNG/fast/layers/inline-dirty-z-order-lists-expected.png Binary files differ
diff --git a/third_party/WebKit/LayoutTests/flag-specific/enable-blink-features=LayoutNG/fast/layers/inline-dirty-z-order-lists-expected.txt b/third_party/WebKit/LayoutTests/flag-specific/enable-blink-features=LayoutNG/fast/layers/inline-dirty-z-order-lists-expected.txt new file mode 100644 index 0000000..9afb89b --- /dev/null +++ b/third_party/WebKit/LayoutTests/flag-specific/enable-blink-features=LayoutNG/fast/layers/inline-dirty-z-order-lists-expected.txt
@@ -0,0 +1,19 @@ +layer at (0,0) size 800x600 + LayoutView at (0,0) size 800x600 +layer at (0,0) size 800x100 + LayoutNGBlockFlow {HTML} at (0,0) size 800x100 + LayoutNGBlockFlow {BODY} at (8,8) size 784x76 + LayoutNGBlockFlow {P} at (0,0) size 784x40 + LayoutText {#text} at (0,0) size 52x19 + LayoutInline {I} at (0,0) size 0x0 + LayoutInline {A} at (0,0) size 0x0 [color=#0000EE] + LayoutText {#text} at (0,0) size 308x19 + LayoutText {#text} at (0,0) size 770x39 + LayoutText {#text} at (0,0) size 5x19 + LayoutNGBlockFlow {P} at (0,56) size 784x20 + LayoutText {#text} at (0,0) size 735x19 + LayoutNGBlockFlow (anonymous) at (0,92) size 784x0 + LayoutText {#text} at (0,0) size 0x0 +layer at (8,100) size 0x0 + LayoutInline (relative positioned) {SPAN} at (0,0) size 0x0 + LayoutText {#text} at (0,0) size 0x0
diff --git a/third_party/WebKit/LayoutTests/flag-specific/enable-blink-features=LayoutNG/fast/lists/005-expected.png b/third_party/WebKit/LayoutTests/flag-specific/enable-blink-features=LayoutNG/fast/lists/005-expected.png new file mode 100644 index 0000000..1a31813 --- /dev/null +++ b/third_party/WebKit/LayoutTests/flag-specific/enable-blink-features=LayoutNG/fast/lists/005-expected.png Binary files differ
diff --git a/third_party/WebKit/LayoutTests/flag-specific/enable-blink-features=LayoutNG/fast/lists/big-list-marker-expected.png b/third_party/WebKit/LayoutTests/flag-specific/enable-blink-features=LayoutNG/fast/lists/big-list-marker-expected.png new file mode 100644 index 0000000..50498fb --- /dev/null +++ b/third_party/WebKit/LayoutTests/flag-specific/enable-blink-features=LayoutNG/fast/lists/big-list-marker-expected.png Binary files differ
diff --git a/third_party/WebKit/LayoutTests/flag-specific/enable-blink-features=LayoutNG/fast/lists/inlineBoxWrapperNullCheck-expected.png b/third_party/WebKit/LayoutTests/flag-specific/enable-blink-features=LayoutNG/fast/lists/inlineBoxWrapperNullCheck-expected.png new file mode 100644 index 0000000..a604489 --- /dev/null +++ b/third_party/WebKit/LayoutTests/flag-specific/enable-blink-features=LayoutNG/fast/lists/inlineBoxWrapperNullCheck-expected.png Binary files differ
diff --git a/third_party/WebKit/LayoutTests/flag-specific/enable-blink-features=LayoutNG/fast/lists/marker-image-error-expected.png b/third_party/WebKit/LayoutTests/flag-specific/enable-blink-features=LayoutNG/fast/lists/marker-image-error-expected.png new file mode 100644 index 0000000..aef7eba --- /dev/null +++ b/third_party/WebKit/LayoutTests/flag-specific/enable-blink-features=LayoutNG/fast/lists/marker-image-error-expected.png Binary files differ
diff --git a/third_party/WebKit/LayoutTests/flag-specific/enable-blink-features=LayoutNG/fast/lists/ol-display-types-expected.png b/third_party/WebKit/LayoutTests/flag-specific/enable-blink-features=LayoutNG/fast/lists/ol-display-types-expected.png new file mode 100644 index 0000000..e76b170 --- /dev/null +++ b/third_party/WebKit/LayoutTests/flag-specific/enable-blink-features=LayoutNG/fast/lists/ol-display-types-expected.png Binary files differ
diff --git a/third_party/WebKit/LayoutTests/flag-specific/enable-blink-features=LayoutNG/fast/lists/scrolled-marker-paint-expected.png b/third_party/WebKit/LayoutTests/flag-specific/enable-blink-features=LayoutNG/fast/lists/scrolled-marker-paint-expected.png new file mode 100644 index 0000000..dc7029b4 --- /dev/null +++ b/third_party/WebKit/LayoutTests/flag-specific/enable-blink-features=LayoutNG/fast/lists/scrolled-marker-paint-expected.png Binary files differ
diff --git a/third_party/WebKit/LayoutTests/flag-specific/enable-blink-features=LayoutNG/fast/text/atomic-inline-before-ellipsis-expected.png b/third_party/WebKit/LayoutTests/flag-specific/enable-blink-features=LayoutNG/fast/text/atomic-inline-before-ellipsis-expected.png new file mode 100644 index 0000000..a6747884 --- /dev/null +++ b/third_party/WebKit/LayoutTests/flag-specific/enable-blink-features=LayoutNG/fast/text/atomic-inline-before-ellipsis-expected.png Binary files differ
diff --git a/third_party/WebKit/LayoutTests/flag-specific/enable-blink-features=LayoutNG/fast/text/ellipsis-at-edge-of-ltr-text-in-rtl-flow-expected.png b/third_party/WebKit/LayoutTests/flag-specific/enable-blink-features=LayoutNG/fast/text/ellipsis-at-edge-of-ltr-text-in-rtl-flow-expected.png new file mode 100644 index 0000000..0792523 --- /dev/null +++ b/third_party/WebKit/LayoutTests/flag-specific/enable-blink-features=LayoutNG/fast/text/ellipsis-at-edge-of-ltr-text-in-rtl-flow-expected.png Binary files differ
diff --git a/third_party/WebKit/LayoutTests/flag-specific/enable-blink-features=LayoutNG/fast/text/ellipsis-at-edge-of-rtl-text-in-ltr-flow-expected.png b/third_party/WebKit/LayoutTests/flag-specific/enable-blink-features=LayoutNG/fast/text/ellipsis-at-edge-of-rtl-text-in-ltr-flow-expected.png new file mode 100644 index 0000000..096af53 --- /dev/null +++ b/third_party/WebKit/LayoutTests/flag-specific/enable-blink-features=LayoutNG/fast/text/ellipsis-at-edge-of-rtl-text-in-ltr-flow-expected.png Binary files differ
diff --git a/third_party/WebKit/LayoutTests/flag-specific/enable-blink-features=LayoutNG/fast/text/ellipsis-in-absolute-block-expected.png b/third_party/WebKit/LayoutTests/flag-specific/enable-blink-features=LayoutNG/fast/text/ellipsis-in-absolute-block-expected.png new file mode 100644 index 0000000..5a3d23c --- /dev/null +++ b/third_party/WebKit/LayoutTests/flag-specific/enable-blink-features=LayoutNG/fast/text/ellipsis-in-absolute-block-expected.png Binary files differ
diff --git a/third_party/WebKit/LayoutTests/flag-specific/enable-blink-features=LayoutNG/fast/text/ellipsis-ltr-text-in-rtl-flow-expected.png b/third_party/WebKit/LayoutTests/flag-specific/enable-blink-features=LayoutNG/fast/text/ellipsis-ltr-text-in-rtl-flow-expected.png new file mode 100644 index 0000000..4b76efb2 --- /dev/null +++ b/third_party/WebKit/LayoutTests/flag-specific/enable-blink-features=LayoutNG/fast/text/ellipsis-ltr-text-in-rtl-flow-expected.png Binary files differ
diff --git a/third_party/WebKit/LayoutTests/flag-specific/enable-blink-features=LayoutNG/fast/text/ellipsis-ltr-text-in-rtl-flow-leading-space-expected.png b/third_party/WebKit/LayoutTests/flag-specific/enable-blink-features=LayoutNG/fast/text/ellipsis-ltr-text-in-rtl-flow-leading-space-expected.png new file mode 100644 index 0000000..21e357bf --- /dev/null +++ b/third_party/WebKit/LayoutTests/flag-specific/enable-blink-features=LayoutNG/fast/text/ellipsis-ltr-text-in-rtl-flow-leading-space-expected.png Binary files differ
diff --git a/third_party/WebKit/LayoutTests/flag-specific/enable-blink-features=LayoutNG/fast/text/ellipsis-ltr-text-in-rtl-flow-underline-expected.png b/third_party/WebKit/LayoutTests/flag-specific/enable-blink-features=LayoutNG/fast/text/ellipsis-ltr-text-in-rtl-flow-underline-expected.png new file mode 100644 index 0000000..84a5fa9 --- /dev/null +++ b/third_party/WebKit/LayoutTests/flag-specific/enable-blink-features=LayoutNG/fast/text/ellipsis-ltr-text-in-rtl-flow-underline-expected.png Binary files differ
diff --git a/third_party/WebKit/LayoutTests/flag-specific/enable-blink-features=LayoutNG/fast/text/ellipsis-mixed-text-in-ltr-flow-underline-2-expected.png b/third_party/WebKit/LayoutTests/flag-specific/enable-blink-features=LayoutNG/fast/text/ellipsis-mixed-text-in-ltr-flow-underline-2-expected.png new file mode 100644 index 0000000..9ef4d02 --- /dev/null +++ b/third_party/WebKit/LayoutTests/flag-specific/enable-blink-features=LayoutNG/fast/text/ellipsis-mixed-text-in-ltr-flow-underline-2-expected.png Binary files differ
diff --git a/third_party/WebKit/LayoutTests/flag-specific/enable-blink-features=LayoutNG/fast/text/ellipsis-mixed-text-in-ltr-flow-underline-expected.png b/third_party/WebKit/LayoutTests/flag-specific/enable-blink-features=LayoutNG/fast/text/ellipsis-mixed-text-in-ltr-flow-underline-expected.png new file mode 100644 index 0000000..332e5055 --- /dev/null +++ b/third_party/WebKit/LayoutTests/flag-specific/enable-blink-features=LayoutNG/fast/text/ellipsis-mixed-text-in-ltr-flow-underline-expected.png Binary files differ
diff --git a/third_party/WebKit/LayoutTests/flag-specific/enable-blink-features=LayoutNG/fast/text/ellipsis-mixed-text-in-rtl-flow-underline-2-expected.png b/third_party/WebKit/LayoutTests/flag-specific/enable-blink-features=LayoutNG/fast/text/ellipsis-mixed-text-in-rtl-flow-underline-2-expected.png new file mode 100644 index 0000000..117c823 --- /dev/null +++ b/third_party/WebKit/LayoutTests/flag-specific/enable-blink-features=LayoutNG/fast/text/ellipsis-mixed-text-in-rtl-flow-underline-2-expected.png Binary files differ
diff --git a/third_party/WebKit/LayoutTests/flag-specific/enable-blink-features=LayoutNG/fast/text/ellipsis-mixed-text-in-rtl-flow-underline-expected.png b/third_party/WebKit/LayoutTests/flag-specific/enable-blink-features=LayoutNG/fast/text/ellipsis-mixed-text-in-rtl-flow-underline-expected.png new file mode 100644 index 0000000..a1362791 --- /dev/null +++ b/third_party/WebKit/LayoutTests/flag-specific/enable-blink-features=LayoutNG/fast/text/ellipsis-mixed-text-in-rtl-flow-underline-expected.png Binary files differ
diff --git a/third_party/WebKit/LayoutTests/flag-specific/enable-blink-features=LayoutNG/fast/text/ellipsis-rtl-text-in-ltr-flow-expected.png b/third_party/WebKit/LayoutTests/flag-specific/enable-blink-features=LayoutNG/fast/text/ellipsis-rtl-text-in-ltr-flow-expected.png new file mode 100644 index 0000000..5f355d2 --- /dev/null +++ b/third_party/WebKit/LayoutTests/flag-specific/enable-blink-features=LayoutNG/fast/text/ellipsis-rtl-text-in-ltr-flow-expected.png Binary files differ
diff --git a/third_party/WebKit/LayoutTests/flag-specific/enable-blink-features=LayoutNG/fast/text/ellipsis-rtl-text-in-ltr-flow-underline-expected.png b/third_party/WebKit/LayoutTests/flag-specific/enable-blink-features=LayoutNG/fast/text/ellipsis-rtl-text-in-ltr-flow-underline-expected.png new file mode 100644 index 0000000..34b087f --- /dev/null +++ b/third_party/WebKit/LayoutTests/flag-specific/enable-blink-features=LayoutNG/fast/text/ellipsis-rtl-text-in-ltr-flow-underline-expected.png Binary files differ
diff --git a/third_party/WebKit/LayoutTests/flag-specific/enable-blink-features=LayoutNG/fast/text/font-features/caps-native-synthesis-expected.png b/third_party/WebKit/LayoutTests/flag-specific/enable-blink-features=LayoutNG/fast/text/font-features/caps-native-synthesis-expected.png new file mode 100644 index 0000000..b9c86e3 --- /dev/null +++ b/third_party/WebKit/LayoutTests/flag-specific/enable-blink-features=LayoutNG/fast/text/font-features/caps-native-synthesis-expected.png Binary files differ
diff --git a/third_party/WebKit/LayoutTests/flag-specific/enable-blink-features=LayoutNG/fast/text/international/bidi-AN-after-empty-run-expected.png b/third_party/WebKit/LayoutTests/flag-specific/enable-blink-features=LayoutNG/fast/text/international/bidi-AN-after-empty-run-expected.png new file mode 100644 index 0000000..e932f76 --- /dev/null +++ b/third_party/WebKit/LayoutTests/flag-specific/enable-blink-features=LayoutNG/fast/text/international/bidi-AN-after-empty-run-expected.png Binary files differ
diff --git a/third_party/WebKit/LayoutTests/flag-specific/enable-blink-features=LayoutNG/fast/text/international/bidi-LDB-2-CSS-expected.png b/third_party/WebKit/LayoutTests/flag-specific/enable-blink-features=LayoutNG/fast/text/international/bidi-LDB-2-CSS-expected.png new file mode 100644 index 0000000..74a0422 --- /dev/null +++ b/third_party/WebKit/LayoutTests/flag-specific/enable-blink-features=LayoutNG/fast/text/international/bidi-LDB-2-CSS-expected.png Binary files differ
diff --git a/third_party/WebKit/LayoutTests/flag-specific/enable-blink-features=LayoutNG/fast/text/international/bidi-LDB-2-HTML-expected.png b/third_party/WebKit/LayoutTests/flag-specific/enable-blink-features=LayoutNG/fast/text/international/bidi-LDB-2-HTML-expected.png new file mode 100644 index 0000000..42fd31eb --- /dev/null +++ b/third_party/WebKit/LayoutTests/flag-specific/enable-blink-features=LayoutNG/fast/text/international/bidi-LDB-2-HTML-expected.png Binary files differ
diff --git a/third_party/WebKit/LayoutTests/flag-specific/enable-blink-features=LayoutNG/fast/text/international/bidi-LDB-2-formatting-characters-expected.png b/third_party/WebKit/LayoutTests/flag-specific/enable-blink-features=LayoutNG/fast/text/international/bidi-LDB-2-formatting-characters-expected.png new file mode 100644 index 0000000..347de86b --- /dev/null +++ b/third_party/WebKit/LayoutTests/flag-specific/enable-blink-features=LayoutNG/fast/text/international/bidi-LDB-2-formatting-characters-expected.png Binary files differ
diff --git a/third_party/WebKit/LayoutTests/flag-specific/enable-blink-features=LayoutNG/fast/text/international/bidi-ignored-for-first-child-inline-expected.png b/third_party/WebKit/LayoutTests/flag-specific/enable-blink-features=LayoutNG/fast/text/international/bidi-ignored-for-first-child-inline-expected.png new file mode 100644 index 0000000..247ac90 --- /dev/null +++ b/third_party/WebKit/LayoutTests/flag-specific/enable-blink-features=LayoutNG/fast/text/international/bidi-ignored-for-first-child-inline-expected.png Binary files differ
diff --git a/third_party/WebKit/LayoutTests/flag-specific/enable-blink-features=LayoutNG/fast/text/international/bidi-linebreak-001-expected.png b/third_party/WebKit/LayoutTests/flag-specific/enable-blink-features=LayoutNG/fast/text/international/bidi-linebreak-001-expected.png new file mode 100644 index 0000000..1ded1861 --- /dev/null +++ b/third_party/WebKit/LayoutTests/flag-specific/enable-blink-features=LayoutNG/fast/text/international/bidi-linebreak-001-expected.png Binary files differ
diff --git a/third_party/WebKit/LayoutTests/flag-specific/enable-blink-features=LayoutNG/fast/text/international/danda-space-expected.png b/third_party/WebKit/LayoutTests/flag-specific/enable-blink-features=LayoutNG/fast/text/international/danda-space-expected.png index 47f071a..516876b 100644 --- a/third_party/WebKit/LayoutTests/flag-specific/enable-blink-features=LayoutNG/fast/text/international/danda-space-expected.png +++ b/third_party/WebKit/LayoutTests/flag-specific/enable-blink-features=LayoutNG/fast/text/international/danda-space-expected.png Binary files differ
diff --git a/third_party/WebKit/LayoutTests/flag-specific/enable-blink-features=LayoutNG/fast/text/international/thai-baht-space-expected.png b/third_party/WebKit/LayoutTests/flag-specific/enable-blink-features=LayoutNG/fast/text/international/thai-baht-space-expected.png index adbd52a..06701ac 100644 --- a/third_party/WebKit/LayoutTests/flag-specific/enable-blink-features=LayoutNG/fast/text/international/thai-baht-space-expected.png +++ b/third_party/WebKit/LayoutTests/flag-specific/enable-blink-features=LayoutNG/fast/text/international/thai-baht-space-expected.png Binary files differ
diff --git a/third_party/WebKit/LayoutTests/flag-specific/enable-blink-features=LayoutNG/fast/text/trailing-white-space-2-expected.png b/third_party/WebKit/LayoutTests/flag-specific/enable-blink-features=LayoutNG/fast/text/trailing-white-space-2-expected.png new file mode 100644 index 0000000..b392835 --- /dev/null +++ b/third_party/WebKit/LayoutTests/flag-specific/enable-blink-features=LayoutNG/fast/text/trailing-white-space-2-expected.png Binary files differ
diff --git a/third_party/WebKit/LayoutTests/flag-specific/enable-blink-features=LayoutNG/fast/text/trailing-white-space-expected.png b/third_party/WebKit/LayoutTests/flag-specific/enable-blink-features=LayoutNG/fast/text/trailing-white-space-expected.png new file mode 100644 index 0000000..66d5b49 --- /dev/null +++ b/third_party/WebKit/LayoutTests/flag-specific/enable-blink-features=LayoutNG/fast/text/trailing-white-space-expected.png Binary files differ
diff --git a/third_party/WebKit/LayoutTests/flag-specific/enable-blink-features=LayoutNG/fast/text/word-space-expected.png b/third_party/WebKit/LayoutTests/flag-specific/enable-blink-features=LayoutNG/fast/text/word-space-expected.png new file mode 100644 index 0000000..e8832d9 --- /dev/null +++ b/third_party/WebKit/LayoutTests/flag-specific/enable-blink-features=LayoutNG/fast/text/word-space-expected.png Binary files differ
diff --git a/third_party/WebKit/LayoutTests/flag-specific/enable-blink-features=LayoutNG/images/exif-orientation-css-expected.png b/third_party/WebKit/LayoutTests/flag-specific/enable-blink-features=LayoutNG/images/exif-orientation-css-expected.png new file mode 100644 index 0000000..5b9308cb --- /dev/null +++ b/third_party/WebKit/LayoutTests/flag-specific/enable-blink-features=LayoutNG/images/exif-orientation-css-expected.png Binary files differ
diff --git a/third_party/WebKit/LayoutTests/flag-specific/enable-blink-features=LayoutNG/images/exif-orientation-css-expected.txt b/third_party/WebKit/LayoutTests/flag-specific/enable-blink-features=LayoutNG/images/exif-orientation-css-expected.txt new file mode 100644 index 0000000..55dce31 --- /dev/null +++ b/third_party/WebKit/LayoutTests/flag-specific/enable-blink-features=LayoutNG/images/exif-orientation-css-expected.txt
@@ -0,0 +1,32 @@ +None of the images should be rotated. This test is only valid when run with testRunner (or with WebKitShouldRespectImageOrientation manually set to true). + + +Normal +Flipped horizontally +Rotated 180° +Flipped vertically + +Rotated 90° CCW and flipped vertically +Rotated 90° CCW +Rotated 90° CW and flipped vertically +Rotated 90° CW + +Rotated 90° CCW and flipped vertically +Rotated 90° CCW +Rotated 90° CW and flipped vertically +Rotated 90° CW + +Undefined (invalid value) +img1 size = 100px by 50px +img2 size = 100px by 50px +img3 size = 100px by 50px +img4 size = 100px by 50px +img5 size = 100px by 50px +img6 size = 100px by 50px +img7 size = 100px by 50px +img8 size = 100px by 50px +img9 size = 100px by 100px +img10 size = 100px by 100px +img11 size = 100px by 100px +img12 size = 100px by 100px +img13 size = 100px by 50px
diff --git a/third_party/WebKit/LayoutTests/flag-specific/enable-blink-features=LayoutNG/images/exif-orientation-expected.png b/third_party/WebKit/LayoutTests/flag-specific/enable-blink-features=LayoutNG/images/exif-orientation-expected.png new file mode 100644 index 0000000..14aa9f7 --- /dev/null +++ b/third_party/WebKit/LayoutTests/flag-specific/enable-blink-features=LayoutNG/images/exif-orientation-expected.png Binary files differ
diff --git a/third_party/WebKit/LayoutTests/flag-specific/enable-blink-features=LayoutNG/images/exif-orientation-expected.txt b/third_party/WebKit/LayoutTests/flag-specific/enable-blink-features=LayoutNG/images/exif-orientation-expected.txt new file mode 100644 index 0000000..e9b281fd2 --- /dev/null +++ b/third_party/WebKit/LayoutTests/flag-specific/enable-blink-features=LayoutNG/images/exif-orientation-expected.txt
@@ -0,0 +1,23 @@ +The images should be rotated respecting their EXIF orientation. This test can only be run with testRunner (or by manually setting WebKitShouldRespectImageOrientation to true). + + +Normal +Flipped horizontally +Rotated 180° +Flipped vertically + +Rotated 90° CCW and flipped vertically +Rotated 90° CCW +Rotated 90° CW and flipped vertically +Rotated 90° CW + +Undefined (invalid value) +img1 size = 100px by 50px +img2 size = 100px by 50px +img3 size = 100px by 50px +img4 size = 100px by 50px +img5 size = 50px by 100px +img6 size = 50px by 100px +img7 size = 50px by 100px +img8 size = 50px by 100px +img9 size = 100px by 50px
diff --git a/third_party/WebKit/LayoutTests/flag-specific/enable-blink-features=LayoutNG/images/exif-orientation-image-document-expected.png b/third_party/WebKit/LayoutTests/flag-specific/enable-blink-features=LayoutNG/images/exif-orientation-image-document-expected.png new file mode 100644 index 0000000..b86fd2d --- /dev/null +++ b/third_party/WebKit/LayoutTests/flag-specific/enable-blink-features=LayoutNG/images/exif-orientation-image-document-expected.png Binary files differ
diff --git a/third_party/WebKit/LayoutTests/flag-specific/enable-blink-features=LayoutNG/images/exif-orientation-image-document-expected.txt b/third_party/WebKit/LayoutTests/flag-specific/enable-blink-features=LayoutNG/images/exif-orientation-image-document-expected.txt new file mode 100644 index 0000000..625076d3 --- /dev/null +++ b/third_party/WebKit/LayoutTests/flag-specific/enable-blink-features=LayoutNG/images/exif-orientation-image-document-expected.txt
@@ -0,0 +1,6 @@ +The images should be rotated respecting their EXIF orientation. In image documents, this happens independent of WebKitShouldRespectImageOrientation. + + + + +PASS
diff --git a/third_party/WebKit/LayoutTests/flag-specific/enable-blink-features=LayoutNG/images/imagemap-circle-focus-ring-expected.png b/third_party/WebKit/LayoutTests/flag-specific/enable-blink-features=LayoutNG/images/imagemap-circle-focus-ring-expected.png new file mode 100644 index 0000000..4fd8b25e --- /dev/null +++ b/third_party/WebKit/LayoutTests/flag-specific/enable-blink-features=LayoutNG/images/imagemap-circle-focus-ring-expected.png Binary files differ
diff --git a/third_party/WebKit/LayoutTests/flag-specific/enable-blink-features=LayoutNG/images/imagemap-circle-focus-ring-expected.txt b/third_party/WebKit/LayoutTests/flag-specific/enable-blink-features=LayoutNG/images/imagemap-circle-focus-ring-expected.txt new file mode 100644 index 0000000..93f66fe --- /dev/null +++ b/third_party/WebKit/LayoutTests/flag-specific/enable-blink-features=LayoutNG/images/imagemap-circle-focus-ring-expected.txt
@@ -0,0 +1,15 @@ +layer at (0,0) size 800x600 + LayoutView at (0,0) size 800x600 +layer at (0,0) size 800x205 + LayoutNGBlockFlow {HTML} at (0,0) size 800x205 + LayoutNGBlockFlow {BODY} at (8,8) size 784x189 + LayoutNGBlockFlow {P} at (0,0) size 784x40 + LayoutText {#text} at (0,0) size 763x39 + LayoutNGBlockFlow (anonymous) at (0,56) size 784x133 + LayoutInline {MAP} at (0,0) size 0x0 + LayoutText {#text} at (0,0) size 0x0 + LayoutInline {AREA} at (0,0) size 0x0 + LayoutText {#text} at (0,0) size 0x0 + LayoutText {#text} at (0,0) size 0x0 + LayoutImage {IMG} at (0,0) size 128x128 + LayoutText {#text} at (0,0) size 0x0
diff --git a/third_party/WebKit/LayoutTests/flag-specific/enable-blink-features=LayoutNG/images/imagemap-focus-ring-expected.png b/third_party/WebKit/LayoutTests/flag-specific/enable-blink-features=LayoutNG/images/imagemap-focus-ring-expected.png new file mode 100644 index 0000000..033b006 --- /dev/null +++ b/third_party/WebKit/LayoutTests/flag-specific/enable-blink-features=LayoutNG/images/imagemap-focus-ring-expected.png Binary files differ
diff --git a/third_party/WebKit/LayoutTests/flag-specific/enable-blink-features=LayoutNG/images/imagemap-focus-ring-expected.txt b/third_party/WebKit/LayoutTests/flag-specific/enable-blink-features=LayoutNG/images/imagemap-focus-ring-expected.txt new file mode 100644 index 0000000..deebca7 --- /dev/null +++ b/third_party/WebKit/LayoutTests/flag-specific/enable-blink-features=LayoutNG/images/imagemap-focus-ring-expected.txt
@@ -0,0 +1,15 @@ +layer at (0,0) size 800x600 + LayoutView at (0,0) size 800x600 +layer at (0,0) size 800x205 + LayoutNGBlockFlow {HTML} at (0,0) size 800x205 + LayoutNGBlockFlow {BODY} at (8,8) size 784x189 + LayoutNGBlockFlow {P} at (0,0) size 784x40 + LayoutText {#text} at (0,0) size 724x39 + LayoutNGBlockFlow (anonymous) at (0,56) size 784x133 + LayoutInline {MAP} at (0,0) size 0x0 + LayoutText {#text} at (0,0) size 0x0 + LayoutInline {AREA} at (0,0) size 0x0 + LayoutText {#text} at (0,0) size 0x0 + LayoutText {#text} at (0,0) size 0x0 + LayoutImage {IMG} at (0,0) size 128x128 + LayoutText {#text} at (0,0) size 0x0
diff --git a/third_party/WebKit/LayoutTests/flag-specific/enable-blink-features=LayoutNG/images/imagemap-focus-ring-outline-color-expected.png b/third_party/WebKit/LayoutTests/flag-specific/enable-blink-features=LayoutNG/images/imagemap-focus-ring-outline-color-expected.png new file mode 100644 index 0000000..829b083e --- /dev/null +++ b/third_party/WebKit/LayoutTests/flag-specific/enable-blink-features=LayoutNG/images/imagemap-focus-ring-outline-color-expected.png Binary files differ
diff --git a/third_party/WebKit/LayoutTests/flag-specific/enable-blink-features=LayoutNG/images/imagemap-focus-ring-outline-color-expected.txt b/third_party/WebKit/LayoutTests/flag-specific/enable-blink-features=LayoutNG/images/imagemap-focus-ring-outline-color-expected.txt new file mode 100644 index 0000000..396e6df5 --- /dev/null +++ b/third_party/WebKit/LayoutTests/flag-specific/enable-blink-features=LayoutNG/images/imagemap-focus-ring-outline-color-expected.txt
@@ -0,0 +1,15 @@ +layer at (0,0) size 800x600 + LayoutView at (0,0) size 800x600 +layer at (0,0) size 800x205 + LayoutNGBlockFlow {HTML} at (0,0) size 800x205 + LayoutNGBlockFlow {BODY} at (8,8) size 784x189 + LayoutNGBlockFlow {P} at (0,0) size 784x40 + LayoutText {#text} at (0,0) size 776x39 + LayoutNGBlockFlow (anonymous) at (0,56) size 784x133 + LayoutInline {MAP} at (0,0) size 0x0 + LayoutText {#text} at (0,0) size 0x0 + LayoutInline {AREA} at (0,0) size 0x0 + LayoutText {#text} at (0,0) size 0x0 + LayoutText {#text} at (0,0) size 0x0 + LayoutImage {IMG} at (0,0) size 128x128 + LayoutText {#text} at (0,0) size 0x0
diff --git a/third_party/WebKit/LayoutTests/flag-specific/enable-blink-features=LayoutNG/images/imagemap-focus-ring-outline-color-explicitly-inherited-from-map-expected.png b/third_party/WebKit/LayoutTests/flag-specific/enable-blink-features=LayoutNG/images/imagemap-focus-ring-outline-color-explicitly-inherited-from-map-expected.png new file mode 100644 index 0000000..3247645f --- /dev/null +++ b/third_party/WebKit/LayoutTests/flag-specific/enable-blink-features=LayoutNG/images/imagemap-focus-ring-outline-color-explicitly-inherited-from-map-expected.png Binary files differ
diff --git a/third_party/WebKit/LayoutTests/flag-specific/enable-blink-features=LayoutNG/images/imagemap-focus-ring-outline-color-explicitly-inherited-from-map-expected.txt b/third_party/WebKit/LayoutTests/flag-specific/enable-blink-features=LayoutNG/images/imagemap-focus-ring-outline-color-explicitly-inherited-from-map-expected.txt new file mode 100644 index 0000000..b1dcbd09 --- /dev/null +++ b/third_party/WebKit/LayoutTests/flag-specific/enable-blink-features=LayoutNG/images/imagemap-focus-ring-outline-color-explicitly-inherited-from-map-expected.txt
@@ -0,0 +1,15 @@ +layer at (0,0) size 800x600 + LayoutView at (0,0) size 800x600 +layer at (0,0) size 800x225 + LayoutNGBlockFlow {HTML} at (0,0) size 800x225 + LayoutNGBlockFlow {BODY} at (8,8) size 784x209 + LayoutNGBlockFlow {P} at (0,0) size 784x60 + LayoutText {#text} at (0,0) size 768x59 + LayoutNGBlockFlow (anonymous) at (0,76) size 784x133 + LayoutInline {MAP} at (0,0) size 0x0 + LayoutText {#text} at (0,0) size 0x0 + LayoutInline {AREA} at (0,0) size 0x0 + LayoutText {#text} at (0,0) size 0x0 + LayoutText {#text} at (0,0) size 0x0 + LayoutImage {IMG} at (0,0) size 128x128 + LayoutText {#text} at (0,0) size 0x0
diff --git a/third_party/WebKit/LayoutTests/flag-specific/enable-blink-features=LayoutNG/images/imagemap-focus-ring-zero-outline-width-expected.png b/third_party/WebKit/LayoutTests/flag-specific/enable-blink-features=LayoutNG/images/imagemap-focus-ring-zero-outline-width-expected.png new file mode 100644 index 0000000..a589e551 --- /dev/null +++ b/third_party/WebKit/LayoutTests/flag-specific/enable-blink-features=LayoutNG/images/imagemap-focus-ring-zero-outline-width-expected.png Binary files differ
diff --git a/third_party/WebKit/LayoutTests/flag-specific/enable-blink-features=LayoutNG/images/imagemap-focus-ring-zero-outline-width-expected.txt b/third_party/WebKit/LayoutTests/flag-specific/enable-blink-features=LayoutNG/images/imagemap-focus-ring-zero-outline-width-expected.txt new file mode 100644 index 0000000..4e1d54b --- /dev/null +++ b/third_party/WebKit/LayoutTests/flag-specific/enable-blink-features=LayoutNG/images/imagemap-focus-ring-zero-outline-width-expected.txt
@@ -0,0 +1,15 @@ +layer at (0,0) size 800x600 + LayoutView at (0,0) size 800x600 +layer at (0,0) size 800x220 + LayoutNGBlockFlow {HTML} at (0,0) size 800x220 + LayoutNGBlockFlow {BODY} at (8,8) size 784x204 + LayoutNGBlockFlow {P} at (0,0) size 784x60 + LayoutText {#text} at (0,0) size 748x59 + LayoutNGBlockFlow (anonymous) at (0,76) size 784x128 + LayoutInline {MAP} at (0,0) size 0x0 + LayoutText {#text} at (0,0) size 0x0 + LayoutInline {AREA} at (0,0) size 0x0 + LayoutText {#text} at (0,0) size 0x0 + LayoutText {#text} at (0,0) size 0x0 + LayoutImage {IMG} at (0,0) size 128x128 + LayoutText {#text} at (0,0) size 0x0
diff --git a/third_party/WebKit/LayoutTests/flag-specific/enable-blink-features=LayoutNG/images/imagemap-focus-ring-zoom-expected.png b/third_party/WebKit/LayoutTests/flag-specific/enable-blink-features=LayoutNG/images/imagemap-focus-ring-zoom-expected.png new file mode 100644 index 0000000..9bd00d29 --- /dev/null +++ b/third_party/WebKit/LayoutTests/flag-specific/enable-blink-features=LayoutNG/images/imagemap-focus-ring-zoom-expected.png Binary files differ
diff --git a/third_party/WebKit/LayoutTests/flag-specific/enable-blink-features=LayoutNG/images/imagemap-focus-ring-zoom-expected.txt b/third_party/WebKit/LayoutTests/flag-specific/enable-blink-features=LayoutNG/images/imagemap-focus-ring-zoom-expected.txt new file mode 100644 index 0000000..97a2cbd --- /dev/null +++ b/third_party/WebKit/LayoutTests/flag-specific/enable-blink-features=LayoutNG/images/imagemap-focus-ring-zoom-expected.txt
@@ -0,0 +1,13 @@ +layer at (0,0) size 800x600 + LayoutView at (0,0) size 800x600 +layer at (0,0) size 800x268 + LayoutNGBlockFlow {HTML} at (0,0) size 800x268.34 + LayoutNGBlockFlow {BODY} at (11.52,11.52) size 776.97x245.31 + LayoutText {#text} at (0,0) size 727x245 + LayoutInline {MAP} at (0,0) size 0x0 + LayoutText {#text} at (0,0) size 0x0 + LayoutInline {AREA} at (0,0) size 0x0 + LayoutText {#text} at (0,0) size 0x0 + LayoutText {#text} at (0,0) size 0x0 + LayoutImage {IMG} at (515,54) size 184.31x184.31 + LayoutText {#text} at (0,0) size 0x0
diff --git a/third_party/WebKit/LayoutTests/flag-specific/enable-blink-features=LayoutNG/images/imagemap-overflowing-circle-focus-ring-expected.png b/third_party/WebKit/LayoutTests/flag-specific/enable-blink-features=LayoutNG/images/imagemap-overflowing-circle-focus-ring-expected.png new file mode 100644 index 0000000..b6fa040 --- /dev/null +++ b/third_party/WebKit/LayoutTests/flag-specific/enable-blink-features=LayoutNG/images/imagemap-overflowing-circle-focus-ring-expected.png Binary files differ
diff --git a/third_party/WebKit/LayoutTests/flag-specific/enable-blink-features=LayoutNG/images/imagemap-overflowing-circle-focus-ring-expected.txt b/third_party/WebKit/LayoutTests/flag-specific/enable-blink-features=LayoutNG/images/imagemap-overflowing-circle-focus-ring-expected.txt new file mode 100644 index 0000000..57e041bc --- /dev/null +++ b/third_party/WebKit/LayoutTests/flag-specific/enable-blink-features=LayoutNG/images/imagemap-overflowing-circle-focus-ring-expected.txt
@@ -0,0 +1,15 @@ +layer at (0,0) size 800x600 + LayoutView at (0,0) size 800x600 +layer at (0,0) size 800x225 + LayoutNGBlockFlow {HTML} at (0,0) size 800x225 + LayoutNGBlockFlow {BODY} at (8,8) size 784x209 + LayoutNGBlockFlow {P} at (0,0) size 784x60 + LayoutText {#text} at (0,0) size 763x59 + LayoutNGBlockFlow (anonymous) at (0,76) size 784x133 + LayoutInline {MAP} at (0,0) size 0x0 + LayoutText {#text} at (0,0) size 0x0 + LayoutInline {AREA} at (0,0) size 0x0 + LayoutText {#text} at (0,0) size 0x0 + LayoutText {#text} at (0,0) size 0x0 + LayoutImage {IMG} at (0,0) size 128x128 + LayoutText {#text} at (0,0) size 0x0
diff --git a/third_party/WebKit/LayoutTests/flag-specific/enable-blink-features=LayoutNG/images/imagemap-overflowing-polygon-focus-ring-expected.png b/third_party/WebKit/LayoutTests/flag-specific/enable-blink-features=LayoutNG/images/imagemap-overflowing-polygon-focus-ring-expected.png new file mode 100644 index 0000000..5343ba786 --- /dev/null +++ b/third_party/WebKit/LayoutTests/flag-specific/enable-blink-features=LayoutNG/images/imagemap-overflowing-polygon-focus-ring-expected.png Binary files differ
diff --git a/third_party/WebKit/LayoutTests/flag-specific/enable-blink-features=LayoutNG/images/imagemap-overflowing-polygon-focus-ring-expected.txt b/third_party/WebKit/LayoutTests/flag-specific/enable-blink-features=LayoutNG/images/imagemap-overflowing-polygon-focus-ring-expected.txt new file mode 100644 index 0000000..4ccbbc4 --- /dev/null +++ b/third_party/WebKit/LayoutTests/flag-specific/enable-blink-features=LayoutNG/images/imagemap-overflowing-polygon-focus-ring-expected.txt
@@ -0,0 +1,15 @@ +layer at (0,0) size 800x600 + LayoutView at (0,0) size 800x600 +layer at (0,0) size 800x225 + LayoutNGBlockFlow {HTML} at (0,0) size 800x225 + LayoutNGBlockFlow {BODY} at (8,8) size 784x209 + LayoutNGBlockFlow {P} at (0,0) size 784x60 + LayoutText {#text} at (0,0) size 781x59 + LayoutNGBlockFlow (anonymous) at (0,76) size 784x133 + LayoutInline {MAP} at (0,0) size 0x0 + LayoutText {#text} at (0,0) size 0x0 + LayoutInline {AREA} at (0,0) size 0x0 + LayoutText {#text} at (0,0) size 0x0 + LayoutText {#text} at (0,0) size 0x0 + LayoutImage {IMG} at (0,0) size 128x128 + LayoutText {#text} at (0,0) size 0x0
diff --git a/third_party/WebKit/LayoutTests/flag-specific/enable-blink-features=LayoutNG/images/imagemap-polygon-focus-ring-expected.png b/third_party/WebKit/LayoutTests/flag-specific/enable-blink-features=LayoutNG/images/imagemap-polygon-focus-ring-expected.png new file mode 100644 index 0000000..93ff41d6 --- /dev/null +++ b/third_party/WebKit/LayoutTests/flag-specific/enable-blink-features=LayoutNG/images/imagemap-polygon-focus-ring-expected.png Binary files differ
diff --git a/third_party/WebKit/LayoutTests/flag-specific/enable-blink-features=LayoutNG/images/imagemap-polygon-focus-ring-expected.txt b/third_party/WebKit/LayoutTests/flag-specific/enable-blink-features=LayoutNG/images/imagemap-polygon-focus-ring-expected.txt new file mode 100644 index 0000000..93f66fe --- /dev/null +++ b/third_party/WebKit/LayoutTests/flag-specific/enable-blink-features=LayoutNG/images/imagemap-polygon-focus-ring-expected.txt
@@ -0,0 +1,15 @@ +layer at (0,0) size 800x600 + LayoutView at (0,0) size 800x600 +layer at (0,0) size 800x205 + LayoutNGBlockFlow {HTML} at (0,0) size 800x205 + LayoutNGBlockFlow {BODY} at (8,8) size 784x189 + LayoutNGBlockFlow {P} at (0,0) size 784x40 + LayoutText {#text} at (0,0) size 763x39 + LayoutNGBlockFlow (anonymous) at (0,56) size 784x133 + LayoutInline {MAP} at (0,0) size 0x0 + LayoutText {#text} at (0,0) size 0x0 + LayoutInline {AREA} at (0,0) size 0x0 + LayoutText {#text} at (0,0) size 0x0 + LayoutText {#text} at (0,0) size 0x0 + LayoutImage {IMG} at (0,0) size 128x128 + LayoutText {#text} at (0,0) size 0x0
diff --git a/third_party/WebKit/LayoutTests/flag-specific/enable-blink-features=LayoutNG/tables/mozilla/bugs/bug8411-expected.png b/third_party/WebKit/LayoutTests/flag-specific/enable-blink-features=LayoutNG/tables/mozilla/bugs/bug8411-expected.png new file mode 100644 index 0000000..726c73b --- /dev/null +++ b/third_party/WebKit/LayoutTests/flag-specific/enable-blink-features=LayoutNG/tables/mozilla/bugs/bug8411-expected.png Binary files differ
diff --git a/third_party/WebKit/LayoutTests/flag-specific/enable-blink-features=LayoutNG/virtual/gpu-rasterization/images/exif-orientation-css-expected.png b/third_party/WebKit/LayoutTests/flag-specific/enable-blink-features=LayoutNG/virtual/gpu-rasterization/images/exif-orientation-css-expected.png new file mode 100644 index 0000000..03a81df --- /dev/null +++ b/third_party/WebKit/LayoutTests/flag-specific/enable-blink-features=LayoutNG/virtual/gpu-rasterization/images/exif-orientation-css-expected.png Binary files differ
diff --git a/third_party/WebKit/LayoutTests/flag-specific/enable-blink-features=LayoutNG/virtual/gpu-rasterization/images/exif-orientation-css-expected.txt b/third_party/WebKit/LayoutTests/flag-specific/enable-blink-features=LayoutNG/virtual/gpu-rasterization/images/exif-orientation-css-expected.txt new file mode 100644 index 0000000..55dce31 --- /dev/null +++ b/third_party/WebKit/LayoutTests/flag-specific/enable-blink-features=LayoutNG/virtual/gpu-rasterization/images/exif-orientation-css-expected.txt
@@ -0,0 +1,32 @@ +None of the images should be rotated. This test is only valid when run with testRunner (or with WebKitShouldRespectImageOrientation manually set to true). + + +Normal +Flipped horizontally +Rotated 180° +Flipped vertically + +Rotated 90° CCW and flipped vertically +Rotated 90° CCW +Rotated 90° CW and flipped vertically +Rotated 90° CW + +Rotated 90° CCW and flipped vertically +Rotated 90° CCW +Rotated 90° CW and flipped vertically +Rotated 90° CW + +Undefined (invalid value) +img1 size = 100px by 50px +img2 size = 100px by 50px +img3 size = 100px by 50px +img4 size = 100px by 50px +img5 size = 100px by 50px +img6 size = 100px by 50px +img7 size = 100px by 50px +img8 size = 100px by 50px +img9 size = 100px by 100px +img10 size = 100px by 100px +img11 size = 100px by 100px +img12 size = 100px by 100px +img13 size = 100px by 50px
diff --git a/third_party/WebKit/LayoutTests/flag-specific/enable-blink-features=LayoutNG/virtual/gpu-rasterization/images/exif-orientation-expected.png b/third_party/WebKit/LayoutTests/flag-specific/enable-blink-features=LayoutNG/virtual/gpu-rasterization/images/exif-orientation-expected.png new file mode 100644 index 0000000..460f498 --- /dev/null +++ b/third_party/WebKit/LayoutTests/flag-specific/enable-blink-features=LayoutNG/virtual/gpu-rasterization/images/exif-orientation-expected.png Binary files differ
diff --git a/third_party/WebKit/LayoutTests/flag-specific/enable-blink-features=LayoutNG/virtual/gpu-rasterization/images/exif-orientation-expected.txt b/third_party/WebKit/LayoutTests/flag-specific/enable-blink-features=LayoutNG/virtual/gpu-rasterization/images/exif-orientation-expected.txt new file mode 100644 index 0000000..e9b281fd2 --- /dev/null +++ b/third_party/WebKit/LayoutTests/flag-specific/enable-blink-features=LayoutNG/virtual/gpu-rasterization/images/exif-orientation-expected.txt
@@ -0,0 +1,23 @@ +The images should be rotated respecting their EXIF orientation. This test can only be run with testRunner (or by manually setting WebKitShouldRespectImageOrientation to true). + + +Normal +Flipped horizontally +Rotated 180° +Flipped vertically + +Rotated 90° CCW and flipped vertically +Rotated 90° CCW +Rotated 90° CW and flipped vertically +Rotated 90° CW + +Undefined (invalid value) +img1 size = 100px by 50px +img2 size = 100px by 50px +img3 size = 100px by 50px +img4 size = 100px by 50px +img5 size = 50px by 100px +img6 size = 50px by 100px +img7 size = 50px by 100px +img8 size = 50px by 100px +img9 size = 100px by 50px
diff --git a/third_party/WebKit/LayoutTests/flag-specific/enable-blink-features=LayoutNG/virtual/gpu-rasterization/images/exif-orientation-image-document-expected.png b/third_party/WebKit/LayoutTests/flag-specific/enable-blink-features=LayoutNG/virtual/gpu-rasterization/images/exif-orientation-image-document-expected.png new file mode 100644 index 0000000..0d8af5ebb --- /dev/null +++ b/third_party/WebKit/LayoutTests/flag-specific/enable-blink-features=LayoutNG/virtual/gpu-rasterization/images/exif-orientation-image-document-expected.png Binary files differ
diff --git a/third_party/WebKit/LayoutTests/flag-specific/enable-blink-features=LayoutNG/virtual/gpu-rasterization/images/exif-orientation-image-document-expected.txt b/third_party/WebKit/LayoutTests/flag-specific/enable-blink-features=LayoutNG/virtual/gpu-rasterization/images/exif-orientation-image-document-expected.txt new file mode 100644 index 0000000..625076d3 --- /dev/null +++ b/third_party/WebKit/LayoutTests/flag-specific/enable-blink-features=LayoutNG/virtual/gpu-rasterization/images/exif-orientation-image-document-expected.txt
@@ -0,0 +1,6 @@ +The images should be rotated respecting their EXIF orientation. In image documents, this happens independent of WebKitShouldRespectImageOrientation. + + + + +PASS
diff --git a/third_party/WebKit/LayoutTests/flag-specific/enable-blink-features=LayoutNG/virtual/gpu-rasterization/images/imagemap-circle-focus-ring-expected.png b/third_party/WebKit/LayoutTests/flag-specific/enable-blink-features=LayoutNG/virtual/gpu-rasterization/images/imagemap-circle-focus-ring-expected.png new file mode 100644 index 0000000..8ed8cf43 --- /dev/null +++ b/third_party/WebKit/LayoutTests/flag-specific/enable-blink-features=LayoutNG/virtual/gpu-rasterization/images/imagemap-circle-focus-ring-expected.png Binary files differ
diff --git a/third_party/WebKit/LayoutTests/flag-specific/enable-blink-features=LayoutNG/virtual/gpu-rasterization/images/imagemap-circle-focus-ring-expected.txt b/third_party/WebKit/LayoutTests/flag-specific/enable-blink-features=LayoutNG/virtual/gpu-rasterization/images/imagemap-circle-focus-ring-expected.txt new file mode 100644 index 0000000..93f66fe --- /dev/null +++ b/third_party/WebKit/LayoutTests/flag-specific/enable-blink-features=LayoutNG/virtual/gpu-rasterization/images/imagemap-circle-focus-ring-expected.txt
@@ -0,0 +1,15 @@ +layer at (0,0) size 800x600 + LayoutView at (0,0) size 800x600 +layer at (0,0) size 800x205 + LayoutNGBlockFlow {HTML} at (0,0) size 800x205 + LayoutNGBlockFlow {BODY} at (8,8) size 784x189 + LayoutNGBlockFlow {P} at (0,0) size 784x40 + LayoutText {#text} at (0,0) size 763x39 + LayoutNGBlockFlow (anonymous) at (0,56) size 784x133 + LayoutInline {MAP} at (0,0) size 0x0 + LayoutText {#text} at (0,0) size 0x0 + LayoutInline {AREA} at (0,0) size 0x0 + LayoutText {#text} at (0,0) size 0x0 + LayoutText {#text} at (0,0) size 0x0 + LayoutImage {IMG} at (0,0) size 128x128 + LayoutText {#text} at (0,0) size 0x0
diff --git a/third_party/WebKit/LayoutTests/flag-specific/enable-blink-features=LayoutNG/virtual/gpu-rasterization/images/imagemap-focus-ring-expected.png b/third_party/WebKit/LayoutTests/flag-specific/enable-blink-features=LayoutNG/virtual/gpu-rasterization/images/imagemap-focus-ring-expected.png new file mode 100644 index 0000000..fb7f7cb3e --- /dev/null +++ b/third_party/WebKit/LayoutTests/flag-specific/enable-blink-features=LayoutNG/virtual/gpu-rasterization/images/imagemap-focus-ring-expected.png Binary files differ
diff --git a/third_party/WebKit/LayoutTests/flag-specific/enable-blink-features=LayoutNG/virtual/gpu-rasterization/images/imagemap-focus-ring-expected.txt b/third_party/WebKit/LayoutTests/flag-specific/enable-blink-features=LayoutNG/virtual/gpu-rasterization/images/imagemap-focus-ring-expected.txt new file mode 100644 index 0000000..deebca7 --- /dev/null +++ b/third_party/WebKit/LayoutTests/flag-specific/enable-blink-features=LayoutNG/virtual/gpu-rasterization/images/imagemap-focus-ring-expected.txt
@@ -0,0 +1,15 @@ +layer at (0,0) size 800x600 + LayoutView at (0,0) size 800x600 +layer at (0,0) size 800x205 + LayoutNGBlockFlow {HTML} at (0,0) size 800x205 + LayoutNGBlockFlow {BODY} at (8,8) size 784x189 + LayoutNGBlockFlow {P} at (0,0) size 784x40 + LayoutText {#text} at (0,0) size 724x39 + LayoutNGBlockFlow (anonymous) at (0,56) size 784x133 + LayoutInline {MAP} at (0,0) size 0x0 + LayoutText {#text} at (0,0) size 0x0 + LayoutInline {AREA} at (0,0) size 0x0 + LayoutText {#text} at (0,0) size 0x0 + LayoutText {#text} at (0,0) size 0x0 + LayoutImage {IMG} at (0,0) size 128x128 + LayoutText {#text} at (0,0) size 0x0
diff --git a/third_party/WebKit/LayoutTests/flag-specific/enable-blink-features=LayoutNG/virtual/gpu-rasterization/images/imagemap-focus-ring-outline-color-expected.png b/third_party/WebKit/LayoutTests/flag-specific/enable-blink-features=LayoutNG/virtual/gpu-rasterization/images/imagemap-focus-ring-outline-color-expected.png new file mode 100644 index 0000000..8295a46 --- /dev/null +++ b/third_party/WebKit/LayoutTests/flag-specific/enable-blink-features=LayoutNG/virtual/gpu-rasterization/images/imagemap-focus-ring-outline-color-expected.png Binary files differ
diff --git a/third_party/WebKit/LayoutTests/flag-specific/enable-blink-features=LayoutNG/virtual/gpu-rasterization/images/imagemap-focus-ring-outline-color-expected.txt b/third_party/WebKit/LayoutTests/flag-specific/enable-blink-features=LayoutNG/virtual/gpu-rasterization/images/imagemap-focus-ring-outline-color-expected.txt new file mode 100644 index 0000000..396e6df5 --- /dev/null +++ b/third_party/WebKit/LayoutTests/flag-specific/enable-blink-features=LayoutNG/virtual/gpu-rasterization/images/imagemap-focus-ring-outline-color-expected.txt
@@ -0,0 +1,15 @@ +layer at (0,0) size 800x600 + LayoutView at (0,0) size 800x600 +layer at (0,0) size 800x205 + LayoutNGBlockFlow {HTML} at (0,0) size 800x205 + LayoutNGBlockFlow {BODY} at (8,8) size 784x189 + LayoutNGBlockFlow {P} at (0,0) size 784x40 + LayoutText {#text} at (0,0) size 776x39 + LayoutNGBlockFlow (anonymous) at (0,56) size 784x133 + LayoutInline {MAP} at (0,0) size 0x0 + LayoutText {#text} at (0,0) size 0x0 + LayoutInline {AREA} at (0,0) size 0x0 + LayoutText {#text} at (0,0) size 0x0 + LayoutText {#text} at (0,0) size 0x0 + LayoutImage {IMG} at (0,0) size 128x128 + LayoutText {#text} at (0,0) size 0x0
diff --git a/third_party/WebKit/LayoutTests/flag-specific/enable-blink-features=LayoutNG/virtual/gpu-rasterization/images/imagemap-focus-ring-outline-color-explicitly-inherited-from-map-expected.png b/third_party/WebKit/LayoutTests/flag-specific/enable-blink-features=LayoutNG/virtual/gpu-rasterization/images/imagemap-focus-ring-outline-color-explicitly-inherited-from-map-expected.png new file mode 100644 index 0000000..5aa5ea3e --- /dev/null +++ b/third_party/WebKit/LayoutTests/flag-specific/enable-blink-features=LayoutNG/virtual/gpu-rasterization/images/imagemap-focus-ring-outline-color-explicitly-inherited-from-map-expected.png Binary files differ
diff --git a/third_party/WebKit/LayoutTests/flag-specific/enable-blink-features=LayoutNG/virtual/gpu-rasterization/images/imagemap-focus-ring-outline-color-explicitly-inherited-from-map-expected.txt b/third_party/WebKit/LayoutTests/flag-specific/enable-blink-features=LayoutNG/virtual/gpu-rasterization/images/imagemap-focus-ring-outline-color-explicitly-inherited-from-map-expected.txt new file mode 100644 index 0000000..b1dcbd09 --- /dev/null +++ b/third_party/WebKit/LayoutTests/flag-specific/enable-blink-features=LayoutNG/virtual/gpu-rasterization/images/imagemap-focus-ring-outline-color-explicitly-inherited-from-map-expected.txt
@@ -0,0 +1,15 @@ +layer at (0,0) size 800x600 + LayoutView at (0,0) size 800x600 +layer at (0,0) size 800x225 + LayoutNGBlockFlow {HTML} at (0,0) size 800x225 + LayoutNGBlockFlow {BODY} at (8,8) size 784x209 + LayoutNGBlockFlow {P} at (0,0) size 784x60 + LayoutText {#text} at (0,0) size 768x59 + LayoutNGBlockFlow (anonymous) at (0,76) size 784x133 + LayoutInline {MAP} at (0,0) size 0x0 + LayoutText {#text} at (0,0) size 0x0 + LayoutInline {AREA} at (0,0) size 0x0 + LayoutText {#text} at (0,0) size 0x0 + LayoutText {#text} at (0,0) size 0x0 + LayoutImage {IMG} at (0,0) size 128x128 + LayoutText {#text} at (0,0) size 0x0
diff --git a/third_party/WebKit/LayoutTests/flag-specific/enable-blink-features=LayoutNG/virtual/gpu-rasterization/images/imagemap-focus-ring-zero-outline-width-expected.png b/third_party/WebKit/LayoutTests/flag-specific/enable-blink-features=LayoutNG/virtual/gpu-rasterization/images/imagemap-focus-ring-zero-outline-width-expected.png new file mode 100644 index 0000000..4f97cd1 --- /dev/null +++ b/third_party/WebKit/LayoutTests/flag-specific/enable-blink-features=LayoutNG/virtual/gpu-rasterization/images/imagemap-focus-ring-zero-outline-width-expected.png Binary files differ
diff --git a/third_party/WebKit/LayoutTests/flag-specific/enable-blink-features=LayoutNG/virtual/gpu-rasterization/images/imagemap-focus-ring-zero-outline-width-expected.txt b/third_party/WebKit/LayoutTests/flag-specific/enable-blink-features=LayoutNG/virtual/gpu-rasterization/images/imagemap-focus-ring-zero-outline-width-expected.txt new file mode 100644 index 0000000..4e1d54b --- /dev/null +++ b/third_party/WebKit/LayoutTests/flag-specific/enable-blink-features=LayoutNG/virtual/gpu-rasterization/images/imagemap-focus-ring-zero-outline-width-expected.txt
@@ -0,0 +1,15 @@ +layer at (0,0) size 800x600 + LayoutView at (0,0) size 800x600 +layer at (0,0) size 800x220 + LayoutNGBlockFlow {HTML} at (0,0) size 800x220 + LayoutNGBlockFlow {BODY} at (8,8) size 784x204 + LayoutNGBlockFlow {P} at (0,0) size 784x60 + LayoutText {#text} at (0,0) size 748x59 + LayoutNGBlockFlow (anonymous) at (0,76) size 784x128 + LayoutInline {MAP} at (0,0) size 0x0 + LayoutText {#text} at (0,0) size 0x0 + LayoutInline {AREA} at (0,0) size 0x0 + LayoutText {#text} at (0,0) size 0x0 + LayoutText {#text} at (0,0) size 0x0 + LayoutImage {IMG} at (0,0) size 128x128 + LayoutText {#text} at (0,0) size 0x0
diff --git a/third_party/WebKit/LayoutTests/flag-specific/enable-blink-features=LayoutNG/virtual/gpu-rasterization/images/imagemap-focus-ring-zoom-expected.png b/third_party/WebKit/LayoutTests/flag-specific/enable-blink-features=LayoutNG/virtual/gpu-rasterization/images/imagemap-focus-ring-zoom-expected.png new file mode 100644 index 0000000..d72b005 --- /dev/null +++ b/third_party/WebKit/LayoutTests/flag-specific/enable-blink-features=LayoutNG/virtual/gpu-rasterization/images/imagemap-focus-ring-zoom-expected.png Binary files differ
diff --git a/third_party/WebKit/LayoutTests/flag-specific/enable-blink-features=LayoutNG/virtual/gpu-rasterization/images/imagemap-focus-ring-zoom-expected.txt b/third_party/WebKit/LayoutTests/flag-specific/enable-blink-features=LayoutNG/virtual/gpu-rasterization/images/imagemap-focus-ring-zoom-expected.txt new file mode 100644 index 0000000..97a2cbd --- /dev/null +++ b/third_party/WebKit/LayoutTests/flag-specific/enable-blink-features=LayoutNG/virtual/gpu-rasterization/images/imagemap-focus-ring-zoom-expected.txt
@@ -0,0 +1,13 @@ +layer at (0,0) size 800x600 + LayoutView at (0,0) size 800x600 +layer at (0,0) size 800x268 + LayoutNGBlockFlow {HTML} at (0,0) size 800x268.34 + LayoutNGBlockFlow {BODY} at (11.52,11.52) size 776.97x245.31 + LayoutText {#text} at (0,0) size 727x245 + LayoutInline {MAP} at (0,0) size 0x0 + LayoutText {#text} at (0,0) size 0x0 + LayoutInline {AREA} at (0,0) size 0x0 + LayoutText {#text} at (0,0) size 0x0 + LayoutText {#text} at (0,0) size 0x0 + LayoutImage {IMG} at (515,54) size 184.31x184.31 + LayoutText {#text} at (0,0) size 0x0
diff --git a/third_party/WebKit/LayoutTests/flag-specific/enable-blink-features=LayoutNG/virtual/gpu-rasterization/images/imagemap-overflowing-circle-focus-ring-expected.png b/third_party/WebKit/LayoutTests/flag-specific/enable-blink-features=LayoutNG/virtual/gpu-rasterization/images/imagemap-overflowing-circle-focus-ring-expected.png new file mode 100644 index 0000000..d89962c --- /dev/null +++ b/third_party/WebKit/LayoutTests/flag-specific/enable-blink-features=LayoutNG/virtual/gpu-rasterization/images/imagemap-overflowing-circle-focus-ring-expected.png Binary files differ
diff --git a/third_party/WebKit/LayoutTests/flag-specific/enable-blink-features=LayoutNG/virtual/gpu-rasterization/images/imagemap-overflowing-circle-focus-ring-expected.txt b/third_party/WebKit/LayoutTests/flag-specific/enable-blink-features=LayoutNG/virtual/gpu-rasterization/images/imagemap-overflowing-circle-focus-ring-expected.txt new file mode 100644 index 0000000..57e041bc --- /dev/null +++ b/third_party/WebKit/LayoutTests/flag-specific/enable-blink-features=LayoutNG/virtual/gpu-rasterization/images/imagemap-overflowing-circle-focus-ring-expected.txt
@@ -0,0 +1,15 @@ +layer at (0,0) size 800x600 + LayoutView at (0,0) size 800x600 +layer at (0,0) size 800x225 + LayoutNGBlockFlow {HTML} at (0,0) size 800x225 + LayoutNGBlockFlow {BODY} at (8,8) size 784x209 + LayoutNGBlockFlow {P} at (0,0) size 784x60 + LayoutText {#text} at (0,0) size 763x59 + LayoutNGBlockFlow (anonymous) at (0,76) size 784x133 + LayoutInline {MAP} at (0,0) size 0x0 + LayoutText {#text} at (0,0) size 0x0 + LayoutInline {AREA} at (0,0) size 0x0 + LayoutText {#text} at (0,0) size 0x0 + LayoutText {#text} at (0,0) size 0x0 + LayoutImage {IMG} at (0,0) size 128x128 + LayoutText {#text} at (0,0) size 0x0
diff --git a/third_party/WebKit/LayoutTests/flag-specific/enable-blink-features=LayoutNG/virtual/gpu-rasterization/images/imagemap-overflowing-polygon-focus-ring-expected.png b/third_party/WebKit/LayoutTests/flag-specific/enable-blink-features=LayoutNG/virtual/gpu-rasterization/images/imagemap-overflowing-polygon-focus-ring-expected.png new file mode 100644 index 0000000..f5b85b9e --- /dev/null +++ b/third_party/WebKit/LayoutTests/flag-specific/enable-blink-features=LayoutNG/virtual/gpu-rasterization/images/imagemap-overflowing-polygon-focus-ring-expected.png Binary files differ
diff --git a/third_party/WebKit/LayoutTests/flag-specific/enable-blink-features=LayoutNG/virtual/gpu-rasterization/images/imagemap-overflowing-polygon-focus-ring-expected.txt b/third_party/WebKit/LayoutTests/flag-specific/enable-blink-features=LayoutNG/virtual/gpu-rasterization/images/imagemap-overflowing-polygon-focus-ring-expected.txt new file mode 100644 index 0000000..4ccbbc4 --- /dev/null +++ b/third_party/WebKit/LayoutTests/flag-specific/enable-blink-features=LayoutNG/virtual/gpu-rasterization/images/imagemap-overflowing-polygon-focus-ring-expected.txt
@@ -0,0 +1,15 @@ +layer at (0,0) size 800x600 + LayoutView at (0,0) size 800x600 +layer at (0,0) size 800x225 + LayoutNGBlockFlow {HTML} at (0,0) size 800x225 + LayoutNGBlockFlow {BODY} at (8,8) size 784x209 + LayoutNGBlockFlow {P} at (0,0) size 784x60 + LayoutText {#text} at (0,0) size 781x59 + LayoutNGBlockFlow (anonymous) at (0,76) size 784x133 + LayoutInline {MAP} at (0,0) size 0x0 + LayoutText {#text} at (0,0) size 0x0 + LayoutInline {AREA} at (0,0) size 0x0 + LayoutText {#text} at (0,0) size 0x0 + LayoutText {#text} at (0,0) size 0x0 + LayoutImage {IMG} at (0,0) size 128x128 + LayoutText {#text} at (0,0) size 0x0
diff --git a/third_party/WebKit/LayoutTests/flag-specific/enable-blink-features=LayoutNG/virtual/gpu-rasterization/images/imagemap-polygon-focus-ring-expected.png b/third_party/WebKit/LayoutTests/flag-specific/enable-blink-features=LayoutNG/virtual/gpu-rasterization/images/imagemap-polygon-focus-ring-expected.png new file mode 100644 index 0000000..8bfdb5b --- /dev/null +++ b/third_party/WebKit/LayoutTests/flag-specific/enable-blink-features=LayoutNG/virtual/gpu-rasterization/images/imagemap-polygon-focus-ring-expected.png Binary files differ
diff --git a/third_party/WebKit/LayoutTests/flag-specific/enable-blink-features=LayoutNG/virtual/gpu-rasterization/images/imagemap-polygon-focus-ring-expected.txt b/third_party/WebKit/LayoutTests/flag-specific/enable-blink-features=LayoutNG/virtual/gpu-rasterization/images/imagemap-polygon-focus-ring-expected.txt new file mode 100644 index 0000000..93f66fe --- /dev/null +++ b/third_party/WebKit/LayoutTests/flag-specific/enable-blink-features=LayoutNG/virtual/gpu-rasterization/images/imagemap-polygon-focus-ring-expected.txt
@@ -0,0 +1,15 @@ +layer at (0,0) size 800x600 + LayoutView at (0,0) size 800x600 +layer at (0,0) size 800x205 + LayoutNGBlockFlow {HTML} at (0,0) size 800x205 + LayoutNGBlockFlow {BODY} at (8,8) size 784x189 + LayoutNGBlockFlow {P} at (0,0) size 784x40 + LayoutText {#text} at (0,0) size 763x39 + LayoutNGBlockFlow (anonymous) at (0,56) size 784x133 + LayoutInline {MAP} at (0,0) size 0x0 + LayoutText {#text} at (0,0) size 0x0 + LayoutInline {AREA} at (0,0) size 0x0 + LayoutText {#text} at (0,0) size 0x0 + LayoutText {#text} at (0,0) size 0x0 + LayoutImage {IMG} at (0,0) size 128x128 + LayoutText {#text} at (0,0) size 0x0
diff --git a/third_party/WebKit/LayoutTests/http/tests/devtools/user-metrics-expected.txt b/third_party/WebKit/LayoutTests/http/tests/devtools/user-metrics-expected.txt index 17e806d78..2619391 100644 --- a/third_party/WebKit/LayoutTests/http/tests/devtools/user-metrics-expected.txt +++ b/third_party/WebKit/LayoutTests/http/tests/devtools/user-metrics-expected.txt
@@ -43,7 +43,7 @@ audits2 : 18 console : 8 drawer-animations : 11 - drawer-console : 10 + drawer-console-view : 10 drawer-network.config : 12 drawer-rendering : 13 drawer-sensors : 14 @@ -61,3 +61,11 @@ Panel shown: js_profiler Panel shown: timeline +Test that drawer usage is recorded by PanelShown +Show drawer: +Panel shown: drawer-console-view +Selecting tab from triple dots menu: +Panel shown: drawer-animations +Selecting tab from tabbed pane header: +Panel shown: drawer-console-view +
diff --git a/third_party/WebKit/LayoutTests/http/tests/devtools/user-metrics.js b/third_party/WebKit/LayoutTests/http/tests/devtools/user-metrics.js index f11fafa..6abd21d5 100644 --- a/third_party/WebKit/LayoutTests/http/tests/devtools/user-metrics.js +++ b/third_party/WebKit/LayoutTests/http/tests/devtools/user-metrics.js
@@ -32,5 +32,13 @@ UI.viewManager.showView('js_profiler'); UI.viewManager.showView('timeline'); + TestRunner.addResult('\nTest that drawer usage is recorded by PanelShown'); + TestRunner.addResult('Show drawer:'); + UI.inspectorView._showDrawer(true); + TestRunner.addResult('Selecting tab from triple dots menu:'); + UI.inspectorView._drawerTabbedLocation.showView(UI.inspectorView._drawerTabbedLocation._views.get("animations"), undefined, true); + TestRunner.addResult('Selecting tab from tabbed pane header:'); + UI.inspectorView._drawerTabbedLocation._tabbedPane._tabs[0]._tabElement.dispatchEvent(new MouseEvent("mousedown")); + TestRunner.completeTest(); })();
diff --git a/third_party/WebKit/LayoutTests/fast/workers/resources/create-shared-worker-frame.html b/third_party/WebKit/LayoutTests/http/tests/workers/resources/create-shared-worker-frame.html similarity index 100% rename from third_party/WebKit/LayoutTests/fast/workers/resources/create-shared-worker-frame.html rename to third_party/WebKit/LayoutTests/http/tests/workers/resources/create-shared-worker-frame.html
diff --git a/third_party/WebKit/LayoutTests/http/tests/workers/resources/shared-worker-common.js b/third_party/WebKit/LayoutTests/http/tests/workers/resources/shared-worker-common.js new file mode 100644 index 0000000..1c1dac3 --- /dev/null +++ b/third_party/WebKit/LayoutTests/http/tests/workers/resources/shared-worker-common.js
@@ -0,0 +1,32 @@ +function generateError() +{ + // Generate an exception by accessing an undefined variable. + foo.bar = 0; +} + +onconnect = function(event) { + event.ports[0].onmessage = function(evt) { handleMessage(evt, event.ports[0]); }; +}; + +function handleMessage(event, port) { + self.port = port; + if (event.data == "ping") + port.postMessage("PASS: Received ping message"); + else if (event.data == "close") + close(); + else if (event.data == "done") + port.postMessage("DONE"); + else if (event.data == "throw") + generateError(); + else if (event.data == "testingNameAttribute") + port.postMessage(self.name); + else if (/eval.+/.test(event.data)) { + try { + port.postMessage(event.data.substr(5) + ": " + eval(event.data.substr(5))); + } catch (ex) { + port.postMessage(event.data.substr(5) + ": " + ex); + } + } + else + port.postMessage("FAILURE: Received unknown message: " + event.data); +}
diff --git a/third_party/WebKit/LayoutTests/fast/workers/resources/shared-worker-count-connections.js b/third_party/WebKit/LayoutTests/http/tests/workers/resources/shared-worker-count-connections.js similarity index 100% rename from third_party/WebKit/LayoutTests/fast/workers/resources/shared-worker-count-connections.js rename to third_party/WebKit/LayoutTests/http/tests/workers/resources/shared-worker-count-connections.js
diff --git a/third_party/WebKit/LayoutTests/http/tests/workers/resources/shared-worker-create-common.js b/third_party/WebKit/LayoutTests/http/tests/workers/resources/shared-worker-create-common.js new file mode 100644 index 0000000..383695a --- /dev/null +++ b/third_party/WebKit/LayoutTests/http/tests/workers/resources/shared-worker-create-common.js
@@ -0,0 +1,8 @@ +// Make a SharedWorker that has the same external interface as a DedicatedWorker, to use in shared test code. +function createWorker() +{ + var worker = new SharedWorker('resources/shared-worker-common.js', 'name'); + worker.port.onmessage = function(evt) { worker.onmessage(evt); }; + worker.postMessage = function(msg, port) { worker.port.postMessage(msg, port); }; + return worker; +}
diff --git a/third_party/WebKit/LayoutTests/fast/workers/resources/shared-worker-iframe.html b/third_party/WebKit/LayoutTests/http/tests/workers/resources/shared-worker-iframe.html similarity index 100% rename from third_party/WebKit/LayoutTests/fast/workers/resources/shared-worker-iframe.html rename to third_party/WebKit/LayoutTests/http/tests/workers/resources/shared-worker-iframe.html
diff --git a/third_party/WebKit/LayoutTests/fast/workers/resources/shared-worker-lifecycle.js b/third_party/WebKit/LayoutTests/http/tests/workers/resources/shared-worker-lifecycle.js similarity index 100% rename from third_party/WebKit/LayoutTests/fast/workers/resources/shared-worker-lifecycle.js rename to third_party/WebKit/LayoutTests/http/tests/workers/resources/shared-worker-lifecycle.js
diff --git a/third_party/WebKit/LayoutTests/fast/workers/resources/shared-worker-name.js b/third_party/WebKit/LayoutTests/http/tests/workers/resources/shared-worker-name.js similarity index 100% rename from third_party/WebKit/LayoutTests/fast/workers/resources/shared-worker-name.js rename to third_party/WebKit/LayoutTests/http/tests/workers/resources/shared-worker-name.js
diff --git a/third_party/WebKit/LayoutTests/fast/workers/shared-worker-in-iframe-expected.txt b/third_party/WebKit/LayoutTests/http/tests/workers/shared-worker-in-iframe-expected.txt similarity index 100% rename from third_party/WebKit/LayoutTests/fast/workers/shared-worker-in-iframe-expected.txt rename to third_party/WebKit/LayoutTests/http/tests/workers/shared-worker-in-iframe-expected.txt
diff --git a/third_party/WebKit/LayoutTests/fast/workers/shared-worker-in-iframe.html b/third_party/WebKit/LayoutTests/http/tests/workers/shared-worker-in-iframe.html similarity index 100% rename from third_party/WebKit/LayoutTests/fast/workers/shared-worker-in-iframe.html rename to third_party/WebKit/LayoutTests/http/tests/workers/shared-worker-in-iframe.html
diff --git a/third_party/WebKit/LayoutTests/fast/workers/shared-worker-lifecycle-expected.txt b/third_party/WebKit/LayoutTests/http/tests/workers/shared-worker-lifecycle-expected.txt similarity index 100% rename from third_party/WebKit/LayoutTests/fast/workers/shared-worker-lifecycle-expected.txt rename to third_party/WebKit/LayoutTests/http/tests/workers/shared-worker-lifecycle-expected.txt
diff --git a/third_party/WebKit/LayoutTests/fast/workers/shared-worker-lifecycle.html b/third_party/WebKit/LayoutTests/http/tests/workers/shared-worker-lifecycle.html similarity index 85% rename from third_party/WebKit/LayoutTests/fast/workers/shared-worker-lifecycle.html rename to third_party/WebKit/LayoutTests/http/tests/workers/shared-worker-lifecycle.html index f6353af..227dd63 100644 --- a/third_party/WebKit/LayoutTests/fast/workers/shared-worker-lifecycle.html +++ b/third_party/WebKit/LayoutTests/http/tests/workers/shared-worker-lifecycle.html
@@ -1,7 +1,7 @@ <body> <p>Test SharedWorker lifecycle. Will print PASS multiple times, followed by DONE.</p> <div id=result></div> -<script src="../../resources/gc.js"></script> +<script src="/js-test-resources/gc.js"></script> <script src="resources/shared-worker-create-common.js"></script> <script src="resources/worker-util.js"></script> <script src="resources/shared-worker-lifecycle.js"></script>
diff --git a/third_party/WebKit/LayoutTests/fast/workers/shared-worker-name-expected.txt b/third_party/WebKit/LayoutTests/http/tests/workers/shared-worker-name-expected.txt similarity index 100% rename from third_party/WebKit/LayoutTests/fast/workers/shared-worker-name-expected.txt rename to third_party/WebKit/LayoutTests/http/tests/workers/shared-worker-name-expected.txt
diff --git a/third_party/WebKit/LayoutTests/fast/workers/shared-worker-name.html b/third_party/WebKit/LayoutTests/http/tests/workers/shared-worker-name.html similarity index 71% rename from third_party/WebKit/LayoutTests/fast/workers/shared-worker-name.html rename to third_party/WebKit/LayoutTests/http/tests/workers/shared-worker-name.html index 99b268d..5ccc758 100644 --- a/third_party/WebKit/LayoutTests/fast/workers/shared-worker-name.html +++ b/third_party/WebKit/LayoutTests/http/tests/workers/shared-worker-name.html
@@ -1,5 +1,5 @@ <head> -<script src="../../resources/js-test.js"></script> +<script src="/js-test-resources/js-test.js"></script> </head> <body> <script src="resources/worker-util.js"></script>
diff --git a/third_party/WebKit/LayoutTests/fast/workers/shared-worker-shared-expected.txt b/third_party/WebKit/LayoutTests/http/tests/workers/shared-worker-shared-expected.txt similarity index 100% rename from third_party/WebKit/LayoutTests/fast/workers/shared-worker-shared-expected.txt rename to third_party/WebKit/LayoutTests/http/tests/workers/shared-worker-shared-expected.txt
diff --git a/third_party/WebKit/LayoutTests/fast/workers/shared-worker-shared.html b/third_party/WebKit/LayoutTests/http/tests/workers/shared-worker-shared.html similarity index 100% rename from third_party/WebKit/LayoutTests/fast/workers/shared-worker-shared.html rename to third_party/WebKit/LayoutTests/http/tests/workers/shared-worker-shared.html
diff --git a/third_party/WebKit/LayoutTests/media/track/regions-webvtt/vtt-region-constructor.html b/third_party/WebKit/LayoutTests/media/track/regions-webvtt/vtt-region-constructor.html deleted file mode 100644 index d0c263d..0000000 --- a/third_party/WebKit/LayoutTests/media/track/regions-webvtt/vtt-region-constructor.html +++ /dev/null
@@ -1,65 +0,0 @@ -<!DOCTYPE html> -<title>Tests the constructor and mutation of VTTRegion.</title> -<script src="../../../resources/testharness.js"></script> -<script src="../../../resources/testharnessreport.js"></script> -<script> -test(function() { - var region = new VTTRegion(); - assert_true(region instanceof VTTRegion, "instanceof"); - - assert_equals(region.scroll, ""); - assert_equals(region.viewportAnchorX, 0); - assert_equals(region.viewportAnchorY, 100); - assert_equals(region.regionAnchorX, 0); - assert_equals(region.regionAnchorY, 100); - assert_equals(region.lines, 3); - assert_equals(region.width, 100); - - region.scroll = "invalid-scroll-value"; - assert_equals(region.scroll, ""); - - var invalidPercentageValues = [-1, 101]; - for (var value of invalidPercentageValues) { - assert_throws("IndexSizeError", function() { region.viewportAnchorX = value; }); - assert_equals(region.viewportAnchorX, 0); - assert_throws("IndexSizeError", function() { region.viewportAnchorY = value; }); - assert_equals(region.viewportAnchorY, 100); - assert_throws("IndexSizeError", function() { region.regionAnchorX = value; }); - assert_equals(region.regionAnchorX, 0); - assert_throws("IndexSizeError", function() { region.regionAnchorY = value; }); - assert_equals(region.regionAnchorY, 100); - assert_throws("IndexSizeError", function() { region.width = value; }); - assert_equals(region.width, 100); - } - - invalidPercentageValues = [-Infinity, Infinity, NaN]; - for (var value of invalidPercentageValues) { - assert_throws(new TypeError, function() { region.viewportAnchorX = value; }); - assert_equals(region.viewportAnchorX, 0); - assert_throws(new TypeError, function() { region.viewportAnchorY = value; }); - assert_equals(region.viewportAnchorY, 100); - assert_throws(new TypeError, function() { region.regionAnchorX = value; }); - assert_equals(region.regionAnchorX, 0); - assert_throws(new TypeError, function() { region.regionAnchorY = value; }); - assert_equals(region.regionAnchorY, 100); - assert_throws(new TypeError, function() { region.width = value; }); - assert_equals(region.width, 100); - } - - assert_throws("IndexSizeError", function() { region.lines = -1; }); - assert_equals(region.lines, 3); - - region.lines = 130; - assert_equals(region.lines, 130); - region.viewportAnchorX = 64; - assert_equals(region.viewportAnchorX, 64); - region.viewportAnchorY = 32; - assert_equals(region.viewportAnchorY, 32); - region.regionAnchorX = 16; - assert_equals(region.regionAnchorX, 16); - region.regionAnchorY = 8; - assert_equals(region.regionAnchorY, 8); - region.width = 42; - assert_equals(region.width, 42); -}); -</script>
diff --git a/third_party/WebKit/LayoutTests/platform/linux/virtual/layout_ng/fast/block/float/016-expected.png b/third_party/WebKit/LayoutTests/platform/linux/virtual/layout_ng/fast/block/float/016-expected.png new file mode 100644 index 0000000..ebf07019 --- /dev/null +++ b/third_party/WebKit/LayoutTests/platform/linux/virtual/layout_ng/fast/block/float/016-expected.png Binary files differ
diff --git a/third_party/WebKit/LayoutTests/platform/mac/virtual/layout_ng/fast/block/float/016-expected.png b/third_party/WebKit/LayoutTests/platform/mac/virtual/layout_ng/fast/block/float/016-expected.png index edcd05b..d3eaa55 100644 --- a/third_party/WebKit/LayoutTests/platform/mac/virtual/layout_ng/fast/block/float/016-expected.png +++ b/third_party/WebKit/LayoutTests/platform/mac/virtual/layout_ng/fast/block/float/016-expected.png Binary files differ
diff --git a/third_party/WebKit/LayoutTests/platform/win/virtual/layout_ng/fast/block/float/016-expected.png b/third_party/WebKit/LayoutTests/platform/win/virtual/layout_ng/fast/block/float/016-expected.png new file mode 100644 index 0000000..1b7d291 --- /dev/null +++ b/third_party/WebKit/LayoutTests/platform/win/virtual/layout_ng/fast/block/float/016-expected.png Binary files differ
diff --git a/third_party/WebKit/LayoutTests/typedcssom/the-stylepropertymap/computed/computed-expected.txt b/third_party/WebKit/LayoutTests/typedcssom/the-stylepropertymap/computed/computed-expected.txt index f8c7b866..d51f9ce 100644 --- a/third_party/WebKit/LayoutTests/typedcssom/the-stylepropertymap/computed/computed-expected.txt +++ b/third_party/WebKit/LayoutTests/typedcssom/the-stylepropertymap/computed/computed-expected.txt
@@ -1,5 +1,5 @@ This is a testharness.js-based test. -FAIL Computed StylePropertyMap contains every CSS property assert_equals: expected 296 but got 294 +FAIL Computed StylePropertyMap contains every CSS property assert_not_equals: got disallowed value null PASS Computed StylePropertyMap contains CSS property declarations in style rules PASS Computed StylePropertyMap contains custom property declarations in style rules PASS Computed StylePropertyMap contains CSS property declarations in inline styles
diff --git a/third_party/WebKit/LayoutTests/typedcssom/the-stylepropertymap/computed/computed.html b/third_party/WebKit/LayoutTests/typedcssom/the-stylepropertymap/computed/computed.html index 4a77ab4..7f9c4b96 100644 --- a/third_party/WebKit/LayoutTests/typedcssom/the-stylepropertymap/computed/computed.html +++ b/third_party/WebKit/LayoutTests/typedcssom/the-stylepropertymap/computed/computed.html
@@ -15,8 +15,10 @@ const target = document.getElementById('target'); const styleMap = target.computedStyleMap(); +// FIXME(crbug.com/788904): Test currently fails because the 'content' property returns +// incorrect initial CSS value. test(() => { - const computedStyle = getComputedStyle(target); + const computedStyle = [...getComputedStyle(target)].sort(); const properties = styleMap.getProperties(); // Two extra entries for custom properties
diff --git a/third_party/WebKit/LayoutTests/typedcssom/the-stylepropertymap/computed/getProperties-expected.txt b/third_party/WebKit/LayoutTests/typedcssom/the-stylepropertymap/computed/getProperties-expected.txt deleted file mode 100644 index 3ee9bd2881..0000000 --- a/third_party/WebKit/LayoutTests/typedcssom/the-stylepropertymap/computed/getProperties-expected.txt +++ /dev/null
@@ -1,4 +0,0 @@ -This is a testharness.js-based test. -FAIL StylePropertyMap.getProperties returns property names in correct order assert_array_equals: lengths differ, expected 297 got 294 -Harness: the test ran to completion. -
diff --git a/third_party/WebKit/LayoutTests/typedcssom/the-stylepropertymap/computed/iterable-expected.txt b/third_party/WebKit/LayoutTests/typedcssom/the-stylepropertymap/computed/iterable-expected.txt deleted file mode 100644 index 28bb1a4a..0000000 --- a/third_party/WebKit/LayoutTests/typedcssom/the-stylepropertymap/computed/iterable-expected.txt +++ /dev/null
@@ -1,7 +0,0 @@ -This is a testharness.js-based test. -FAIL StylePropertyMap iterates properties in correct order assert_array_equals: lengths differ, expected 297 got 294 -PASS StylePropertyMap iterator returns CSS properties with the correct CSSStyleValue -PASS StylePropertyMap iterator returns list-valued properties with the correct CSSStyleValue -FAIL StylePropertyMap iterator returns custom properties with the correct CSSStyleValue assert_equals: expected object "--A" but got null -Harness: the test ran to completion. -
diff --git a/third_party/WebKit/LayoutTests/typedcssom/the-stylepropertymap/computed/iterable.html b/third_party/WebKit/LayoutTests/typedcssom/the-stylepropertymap/computed/iterable.html index 5391376..315ad41c 100644 --- a/third_party/WebKit/LayoutTests/typedcssom/the-stylepropertymap/computed/iterable.html +++ b/third_party/WebKit/LayoutTests/typedcssom/the-stylepropertymap/computed/iterable.html
@@ -19,7 +19,7 @@ test(t => { const styleMap = createComputedStyleMap(t, '--A: A; width: 10px; --C: C; transition-duration: 1s, 2s; color: red; --B: B;'); const expectedKeys = [...getComputedStyle(document.body)].sort().concat('--A', '--B', '--C'); - assert_array_equals([...styleMap], expectedKeys); + assert_array_equals([...styleMap.keys()], expectedKeys); }, 'StylePropertyMap iterates properties in correct order'); test(t => { @@ -34,9 +34,9 @@ test(t => { const styleMap = createComputedStyleMap(t, '--A: A; --C: C; color: red; --B: B;'); - assert_style_value_equals(findInStyleMap(styleMap, '--A'), new CSSUnparsedValue('--A')); - assert_style_value_equals(findInStyleMap(styleMap, '--B'), new CSSUnparsedValue('--B')); - assert_style_value_equals(findInStyleMap(styleMap, '--C'), new CSSUnparsedValue('--C')); + assert_style_value_equals(findInStyleMap(styleMap, '--A'), new CSSUnparsedValue(' A')); + assert_style_value_equals(findInStyleMap(styleMap, '--B'), new CSSUnparsedValue(' B')); + assert_style_value_equals(findInStyleMap(styleMap, '--C'), new CSSUnparsedValue(' C')); }, 'StylePropertyMap iterator returns custom properties with the correct CSSStyleValue'); </script>
diff --git a/third_party/WebKit/LayoutTests/virtual/spv175/paint/invalidation/forms/select-option-background-color-expected.txt b/third_party/WebKit/LayoutTests/virtual/spv175/paint/invalidation/forms/select-option-background-color-expected.txt index ed1f4325..85028ad 100644 --- a/third_party/WebKit/LayoutTests/virtual/spv175/paint/invalidation/forms/select-option-background-color-expected.txt +++ b/third_party/WebKit/LayoutTests/virtual/spv175/paint/invalidation/forms/select-option-background-color-expected.txt
@@ -3,10 +3,30 @@ { "name": "LayoutView #document", "bounds": [800, 600], + "backgroundColor": "#FFFFFF" + }, + { + "name": "Scrolling Layer", + "bounds": [800, 600], + "drawsContent": false + }, + { + "name": "Scrolling Contents Layer", + "bounds": [800, 600], "contentsOpaque": true, "backgroundColor": "#FFFFFF", "paintInvalidations": [ { + "object": "VerticalScrollbar", + "rect": [14, 37, 15, 68], + "reason": "appeared" + }, + { + "object": "VerticalScrollbar", + "rect": [14, 37, 15, 68], + "reason": "disappeared" + }, + { "object": "LayoutListBox SELECT", "rect": [1, 37, 13, 17], "reason": "appeared"
diff --git a/third_party/WebKit/LayoutTests/virtual/spv175/paint/invalidation/position/absolute-position-change-containing-block-expected.txt b/third_party/WebKit/LayoutTests/virtual/spv175/paint/invalidation/position/absolute-position-change-containing-block-expected.txt index d0c35fd..39f12cd 100644 --- a/third_party/WebKit/LayoutTests/virtual/spv175/paint/invalidation/position/absolute-position-change-containing-block-expected.txt +++ b/third_party/WebKit/LayoutTests/virtual/spv175/paint/invalidation/position/absolute-position-change-containing-block-expected.txt
@@ -31,14 +31,6 @@ ], "objectPaintInvalidations": [ { - "object": "LayoutBlockFlow DIV id='container' class='fixed blue'", - "reason": "style change" - }, - { - "object": "LayoutBlockFlow (positioned) DIV class='absolute green'", - "reason": "style change" - }, - { "object": "LayoutBlockFlow BODY", "reason": "style change" },
diff --git a/third_party/WebKit/LayoutTests/virtual/spv175/paint/invalidation/position/fixed-to-relative-position-with-absolute-child-expected.txt b/third_party/WebKit/LayoutTests/virtual/spv175/paint/invalidation/position/fixed-to-relative-position-with-absolute-child-expected.txt index 2e20c155..cffcfb16 100644 --- a/third_party/WebKit/LayoutTests/virtual/spv175/paint/invalidation/position/fixed-to-relative-position-with-absolute-child-expected.txt +++ b/third_party/WebKit/LayoutTests/virtual/spv175/paint/invalidation/position/fixed-to-relative-position-with-absolute-child-expected.txt
@@ -41,14 +41,6 @@ ], "objectPaintInvalidations": [ { - "object": "LayoutBlockFlow (relative positioned) DIV id='container' class='fixed blue'", - "reason": "style change" - }, - { - "object": "LayoutBlockFlow (positioned) DIV class='absolute green'", - "reason": "style change" - }, - { "object": "LayoutBlockFlow BODY", "reason": "style change" },
diff --git a/third_party/WebKit/LayoutTests/virtual/spv175/paint/invalidation/position/position-change-keeping-geometry-expected.txt b/third_party/WebKit/LayoutTests/virtual/spv175/paint/invalidation/position/position-change-keeping-geometry-expected.txt new file mode 100644 index 0000000..e6c50142 --- /dev/null +++ b/third_party/WebKit/LayoutTests/virtual/spv175/paint/invalidation/position/position-change-keeping-geometry-expected.txt
@@ -0,0 +1,21 @@ +{ + "layers": [ + { + "name": "LayoutView #document", + "bounds": [800, 600], + "backgroundColor": "#FFFFFF" + }, + { + "name": "Scrolling Layer", + "bounds": [800, 600], + "drawsContent": false + }, + { + "name": "Scrolling Contents Layer", + "bounds": [800, 600], + "contentsOpaque": true, + "backgroundColor": "#FFFFFF" + } + ] +} +
diff --git a/third_party/WebKit/LayoutTests/virtual/spv175/paint/invalidation/scroll/fixed-after-scroll-expected.txt b/third_party/WebKit/LayoutTests/virtual/spv175/paint/invalidation/scroll/fixed-after-scroll-expected.txt index 02d279b..63f4481 100644 --- a/third_party/WebKit/LayoutTests/virtual/spv175/paint/invalidation/scroll/fixed-after-scroll-expected.txt +++ b/third_party/WebKit/LayoutTests/virtual/spv175/paint/invalidation/scroll/fixed-after-scroll-expected.txt
@@ -46,10 +46,6 @@ { "object": "LayoutBlockFlow (positioned) DIV id='t' class='green absolute'", "reason": "style change" - }, - { - "object": "LayoutBlockFlow (positioned) DIV id='t' class='green absolute'", - "reason": "style change" } ] }
diff --git a/third_party/WebKit/LayoutTests/virtual/spv175/paint/invalidation/scroll/scroll-descendant-with-cached-cliprects-expected.txt b/third_party/WebKit/LayoutTests/virtual/spv175/paint/invalidation/scroll/scroll-descendant-with-cached-cliprects-expected.txt index b6cfbcd..595fc22 100644 --- a/third_party/WebKit/LayoutTests/virtual/spv175/paint/invalidation/scroll/scroll-descendant-with-cached-cliprects-expected.txt +++ b/third_party/WebKit/LayoutTests/virtual/spv175/paint/invalidation/scroll/scroll-descendant-with-cached-cliprects-expected.txt
@@ -58,22 +58,6 @@ { "object": "LayoutBlockFlow DIV", "reason": "style change" - }, - { - "object": "LayoutBlockFlow (positioned) DIV id='scrollpanel'", - "reason": "style change" - }, - { - "object": "LayoutBlockFlow (relative positioned) DIV class='container'", - "reason": "style change" - }, - { - "object": "LayoutBlockFlow (relative positioned) DIV id='ul'", - "reason": "style change" - }, - { - "object": "LayoutBlockFlow DIV", - "reason": "style change" } ] }
diff --git a/third_party/WebKit/LayoutTests/virtual/spv175/paint/invalidation/svg/filter-refresh-expected.txt b/third_party/WebKit/LayoutTests/virtual/spv175/paint/invalidation/svg/filter-refresh-expected.txt new file mode 100644 index 0000000..1b27974 --- /dev/null +++ b/third_party/WebKit/LayoutTests/virtual/spv175/paint/invalidation/svg/filter-refresh-expected.txt
@@ -0,0 +1,256 @@ +{ + "layers": [ + { + "name": "LayoutView #document", + "bounds": [800, 600], + "backgroundColor": "#FFFFFF" + }, + { + "name": "Scrolling Layer", + "bounds": [800, 600], + "drawsContent": false + }, + { + "name": "Scrolling Contents Layer", + "bounds": [800, 600], + "contentsOpaque": true, + "backgroundColor": "#FFFFFF", + "paintInvalidations": [ + { + "object": "LayoutSVGContainer g", + "rect": [10, 170, 132, 36], + "reason": "SVG resource change" + }, + { + "object": "LayoutSVGContainer g", + "rect": [10, 130, 132, 36], + "reason": "SVG resource change" + }, + { + "object": "LayoutSVGRect rect id='separate2'", + "rect": [140, 140, 36, 36], + "reason": "full" + }, + { + "object": "LayoutSVGRect rect id='filtered'", + "rect": [140, 100, 36, 36], + "reason": "full" + }, + { + "object": "LayoutSVGContainer g", + "rect": [140, 60, 36, 36], + "reason": "SVG resource change" + }, + { + "object": "LayoutSVGContainer g", + "rect": [90, 90, 36, 36], + "reason": "SVG resource change" + }, + { + "object": "LayoutSVGContainer g", + "rect": [90, 50, 36, 36], + "reason": "SVG resource change" + }, + { + "object": "LayoutSVGContainer g", + "rect": [50, 90, 36, 36], + "reason": "SVG resource change" + }, + { + "object": "LayoutSVGContainer g", + "rect": [50, 50, 36, 36], + "reason": "SVG resource change" + }, + { + "object": "LayoutSVGContainer g", + "rect": [10, 90, 36, 36], + "reason": "SVG resource change" + }, + { + "object": "LayoutSVGContainer g", + "rect": [10, 50, 36, 36], + "reason": "SVG resource change" + } + ] + } + ], + "objectPaintInvalidations": [ + { + "object": "LayoutSVGContainer g", + "reason": "SVG resource change" + }, + { + "object": "LayoutSVGContainer use", + "reason": "SVG resource change" + }, + { + "object": "LayoutSVGRect rect id='rect'", + "reason": "appeared" + }, + { + "object": "LayoutSVGContainer g", + "reason": "SVG resource change" + }, + { + "object": "LayoutSVGContainer g", + "reason": "SVG resource change" + }, + { + "object": "LayoutSVGContainer use", + "reason": "SVG resource change" + }, + { + "object": "LayoutSVGRect rect id='rect'", + "reason": "appeared" + }, + { + "object": "LayoutSVGContainer g", + "reason": "SVG resource change" + }, + { + "object": "LayoutSVGContainer g", + "reason": "SVG resource change" + }, + { + "object": "LayoutSVGContainer use", + "reason": "SVG resource change" + }, + { + "object": "LayoutSVGRect rect id='rect'", + "reason": "appeared" + }, + { + "object": "LayoutSVGContainer g", + "reason": "SVG resource change" + }, + { + "object": "LayoutSVGContainer use", + "reason": "SVG resource change" + }, + { + "object": "LayoutSVGRect rect id='rect'", + "reason": "appeared" + }, + { + "object": "LayoutSVGContainer g", + "reason": "SVG resource change" + }, + { + "object": "LayoutSVGContainer g", + "reason": "SVG resource change" + }, + { + "object": "LayoutSVGContainer use", + "reason": "SVG resource change" + }, + { + "object": "LayoutSVGRect rect id='rect'", + "reason": "appeared" + }, + { + "object": "LayoutSVGContainer g", + "reason": "SVG resource change" + }, + { + "object": "LayoutSVGContainer g", + "reason": "SVG resource change" + }, + { + "object": "LayoutSVGContainer use", + "reason": "SVG resource change" + }, + { + "object": "LayoutSVGRect rect id='rect'", + "reason": "appeared" + }, + { + "object": "LayoutSVGContainer g", + "reason": "SVG resource change" + }, + { + "object": "LayoutSVGContainer use", + "reason": "SVG resource change" + }, + { + "object": "LayoutSVGRect rect id='rect'", + "reason": "appeared" + }, + { + "object": "LayoutSVGContainer g", + "reason": "SVG resource change" + }, + { + "object": "LayoutSVGContainer use", + "reason": "SVG resource change" + }, + { + "object": "LayoutSVGRect rect id='rect'", + "reason": "appeared" + }, + { + "object": "LayoutSVGContainer g", + "reason": "SVG resource change" + }, + { + "object": "LayoutSVGContainer use", + "reason": "SVG resource change" + }, + { + "object": "LayoutSVGRect rect id='rect'", + "reason": "appeared" + }, + { + "object": "LayoutSVGContainer g", + "reason": "SVG resource change" + }, + { + "object": "LayoutSVGContainer use", + "reason": "SVG resource change" + }, + { + "object": "LayoutSVGRect rect id='rect'", + "reason": "appeared" + }, + { + "object": "LayoutSVGContainer g", + "reason": "SVG resource change" + }, + { + "object": "LayoutSVGContainer use", + "reason": "SVG resource change" + }, + { + "object": "LayoutSVGRect rect id='rect'", + "reason": "appeared" + }, + { + "object": "LayoutSVGContainer g", + "reason": "SVG resource change" + }, + { + "object": "LayoutSVGContainer use", + "reason": "SVG resource change" + }, + { + "object": "LayoutSVGRect rect id='rect'", + "reason": "appeared" + }, + { + "object": "LayoutSVGContainer g", + "reason": "SVG resource change" + }, + { + "object": "LayoutSVGRect rect id='separate1'", + "reason": "style change" + }, + { + "object": "LayoutSVGRect rect id='filtered'", + "reason": "style change" + }, + { + "object": "LayoutSVGRect rect id='separate2'", + "reason": "style change" + } + ] +} +
diff --git a/third_party/WebKit/LayoutTests/virtual/spv175/paint/invalidation/svg/paintorder-filtered-expected.png b/third_party/WebKit/LayoutTests/virtual/spv175/paint/invalidation/svg/paintorder-filtered-expected.png new file mode 100644 index 0000000..f9d2932 --- /dev/null +++ b/third_party/WebKit/LayoutTests/virtual/spv175/paint/invalidation/svg/paintorder-filtered-expected.png Binary files differ
diff --git a/third_party/WebKit/LayoutTests/virtual/spv175/paint/invalidation/svg/paintorder-filtered-expected.txt b/third_party/WebKit/LayoutTests/virtual/spv175/paint/invalidation/svg/paintorder-filtered-expected.txt new file mode 100644 index 0000000..6d4079f --- /dev/null +++ b/third_party/WebKit/LayoutTests/virtual/spv175/paint/invalidation/svg/paintorder-filtered-expected.txt
@@ -0,0 +1,89 @@ +{ + "layers": [ + { + "name": "LayoutView #document", + "bounds": [800, 600], + "backgroundColor": "#FFFFFF" + }, + { + "name": "Scrolling Layer", + "bounds": [800, 600], + "drawsContent": false + }, + { + "name": "Scrolling Contents Layer", + "bounds": [800, 600], + "contentsOpaque": true, + "backgroundColor": "#FFFFFF", + "paintInvalidations": [ + { + "object": "LayoutSVGContainer use", + "rect": [451, 160, 140, 140], + "reason": "SVG resource change" + }, + { + "object": "LayoutSVGContainer use id='t2'", + "rect": [179, 160, 140, 140], + "reason": "style change" + }, + { + "object": "LayoutSVGContainer use id='t1'", + "rect": [42, 160, 140, 140], + "reason": "style change" + }, + { + "object": "LayoutSVGViewportContainer svg", + "rect": [318, 163, 137, 137], + "reason": "SVG resource change" + } + ] + } + ], + "objectPaintInvalidations": [ + { + "object": "LayoutSVGContainer use id='t1'", + "reason": "style change" + }, + { + "object": "LayoutSVGViewportContainer svg id='poly'", + "reason": "style change" + }, + { + "object": "LayoutSVGPath polygon", + "reason": "style change" + }, + { + "object": "LayoutSVGContainer use id='t2'", + "reason": "style change" + }, + { + "object": "LayoutSVGViewportContainer svg id='poly'", + "reason": "style change" + }, + { + "object": "LayoutSVGPath polygon", + "reason": "style change" + }, + { + "object": "LayoutSVGViewportContainer svg", + "reason": "SVG resource change" + }, + { + "object": "LayoutSVGPath polygon id='t3'", + "reason": "style change" + }, + { + "object": "LayoutSVGContainer use", + "reason": "SVG resource change" + }, + { + "object": "LayoutSVGViewportContainer svg id='poly2'", + "reason": "SVG resource change" + }, + { + "object": "LayoutSVGPath polygon", + "reason": "style change" + } + ] +} +
diff --git a/third_party/WebKit/LayoutTests/virtual/spv175/paint/invalidation/svg/text-viewbox-rescale-expected.txt b/third_party/WebKit/LayoutTests/virtual/spv175/paint/invalidation/svg/text-viewbox-rescale-expected.txt new file mode 100644 index 0000000..fa34c90c --- /dev/null +++ b/third_party/WebKit/LayoutTests/virtual/spv175/paint/invalidation/svg/text-viewbox-rescale-expected.txt
@@ -0,0 +1,126 @@ +{ + "layers": [ + { + "name": "LayoutView #document", + "bounds": [800, 600], + "backgroundColor": "#FFFFFF" + }, + { + "name": "Scrolling Layer", + "bounds": [800, 600], + "drawsContent": false + }, + { + "name": "Scrolling Contents Layer", + "bounds": [800, 600], + "contentsOpaque": true, + "backgroundColor": "#FFFFFF", + "paintInvalidations": [ + { + "object": "LayoutSVGViewportContainer svg id='inner1'", + "rect": [0, 0, 200, 200], + "reason": "appeared" + }, + { + "object": "InlineTextBox 'PASS '", + "rect": [0, 100, 200, 100], + "reason": "appeared" + }, + { + "object": "InlineTextBox 'PASS '", + "rect": [0, 100, 200, 100], + "reason": "disappeared" + }, + { + "object": "InlineTextBox 'PASS'", + "rect": [0, 100, 200, 100], + "reason": "appeared" + }, + { + "object": "InlineTextBox 'PASS'", + "rect": [0, 100, 200, 100], + "reason": "disappeared" + } + ] + } + ], + "objectPaintInvalidations": [ + { + "object": "LayoutSVGViewportContainer svg id='inner1'", + "reason": "full" + }, + { + "object": "LayoutSVGText text", + "reason": "full" + }, + { + "object": "RootInlineBox", + "reason": "full" + }, + { + "object": "LayoutSVGInlineText #text", + "reason": "geometry" + }, + { + "object": "InlineTextBox 'PASS '", + "reason": "geometry" + }, + { + "object": "LayoutSVGTSpan tspan", + "reason": "full" + }, + { + "object": "InlineFlowBox", + "reason": "full" + }, + { + "object": "LayoutSVGInlineText #text", + "reason": "geometry" + }, + { + "object": "InlineTextBox 'PASS'", + "reason": "geometry" + }, + { + "object": "LayoutSVGInlineText #text", + "reason": "geometry" + }, + { + "object": "LayoutSVGViewportContainer svg id='inner2'", + "reason": "full" + }, + { + "object": "LayoutSVGText text", + "reason": "full" + }, + { + "object": "RootInlineBox", + "reason": "full" + }, + { + "object": "LayoutSVGInlineText #text", + "reason": "geometry" + }, + { + "object": "InlineTextBox 'PASS '", + "reason": "geometry" + }, + { + "object": "LayoutSVGTSpan tspan", + "reason": "full" + }, + { + "object": "InlineFlowBox", + "reason": "full" + }, + { + "object": "LayoutSVGInlineText #text", + "reason": "geometry" + }, + { + "object": "InlineTextBox 'PASS'", + "reason": "geometry" + } + ] +} +
diff --git a/third_party/WebKit/LayoutTests/virtual/stable/webexposed/element-instance-property-listing-expected.txt b/third_party/WebKit/LayoutTests/virtual/stable/webexposed/element-instance-property-listing-expected.txt index 1b030abd..4958f5d 100644 --- a/third_party/WebKit/LayoutTests/virtual/stable/webexposed/element-instance-property-listing-expected.txt +++ b/third_party/WebKit/LayoutTests/virtual/stable/webexposed/element-instance-property-listing-expected.txt
@@ -288,6 +288,7 @@ property protocol property referrerPolicy property rel + property relList property search property shape property target
diff --git a/third_party/WebKit/LayoutTests/virtual/stable/webexposed/global-interface-listing-expected.txt b/third_party/WebKit/LayoutTests/virtual/stable/webexposed/global-interface-listing-expected.txt index c5e099c..4d98ae0 100644 --- a/third_party/WebKit/LayoutTests/virtual/stable/webexposed/global-interface-listing-expected.txt +++ b/third_party/WebKit/LayoutTests/virtual/stable/webexposed/global-interface-listing-expected.txt
@@ -1602,6 +1602,7 @@ getter protocol getter referrerPolicy getter rel + getter relList getter search getter shape getter target @@ -1623,6 +1624,7 @@ setter protocol setter referrerPolicy setter rel + setter relList setter search setter shape setter target
diff --git a/third_party/WebKit/LayoutTests/webaudio/internals/cycle-connection-gc-render-expected.txt b/third_party/WebKit/LayoutTests/webaudio/internals/cycle-connection-gc-render-expected.txt new file mode 100644 index 0000000..c9af512 --- /dev/null +++ b/third_party/WebKit/LayoutTests/webaudio/internals/cycle-connection-gc-render-expected.txt
@@ -0,0 +1,13 @@ +Cycles of AudioNode connections should be collected, after rendering. + +On success, you will see a series of "PASS" messages, followed by "TEST COMPLETE". + + +A cycle was created: +PASS internals.audioHandlerCount() > initialCount is true +GC happened: +PASS internals.audioHandlerCount() is initialCount +PASS successfullyParsed is true + +TEST COMPLETE +
diff --git a/third_party/WebKit/LayoutTests/webaudio/internals/cycle-connection-gc-render.html b/third_party/WebKit/LayoutTests/webaudio/internals/cycle-connection-gc-render.html new file mode 100644 index 0000000..c59381b --- /dev/null +++ b/third_party/WebKit/LayoutTests/webaudio/internals/cycle-connection-gc-render.html
@@ -0,0 +1,40 @@ +<!DOCTYPE html> +<html> + <head> + <title> + cycle-connection-gc.html + </title> + <script src="../../resources/js-test.js"></script> + </head> + <body> + <script id="layout-test-code"> + description( + 'Cycles of AudioNode connections should be collected, after rendering.'); + window.jsTestIsAsync = true; + + let context = new OfflineAudioContext(2, 1024, 44100); + let initialCount = internals.audioHandlerCount(); + gc(); + createCycle(); + debug('A cycle was created:'); + shouldBeTrue('internals.audioHandlerCount() > initialCount'); + gc(); + debug('GC happened:'); + context.startRendering() + .then(() => { + shouldBe('internals.audioHandlerCount()', 'initialCount'); + }) + .then(finishJSTest); + + function createCycle() { + let source = context.createBufferSource(); + let delay1 = context.createDelay(); + let delay2 = context.createDelay(); + source.connect(delay1); + delay1.connect(delay2); + delay2.connect(delay1); + delay1.connect(context.destination); + } + </script> + </body> +</html>
diff --git a/third_party/WebKit/LayoutTests/webaudio/internals/cycle-connection-gc.html b/third_party/WebKit/LayoutTests/webaudio/internals/cycle-connection-gc.html index caa12aad..7faa59d4d 100644 --- a/third_party/WebKit/LayoutTests/webaudio/internals/cycle-connection-gc.html +++ b/third_party/WebKit/LayoutTests/webaudio/internals/cycle-connection-gc.html
@@ -9,12 +9,13 @@ <body> <script id="layout-test-code"> description('Cycles of AudioNode connections should be collected.'); - let context = new OfflineAudioContext(2, 44100, 44100); gc(); let initialCount = internals.audioHandlerCount(); + let context = new OfflineAudioContext(2, 1024, 44100); createCycle(); debug('A cycle was created:'); shouldBeTrue('internals.audioHandlerCount() > initialCount'); + context = null; gc(); debug('GC happened:'); shouldBe('internals.audioHandlerCount()', 'initialCount');
diff --git a/third_party/WebKit/LayoutTests/webexposed/element-instance-property-listing-expected.txt b/third_party/WebKit/LayoutTests/webexposed/element-instance-property-listing-expected.txt index 53e6209..f528338 100644 --- a/third_party/WebKit/LayoutTests/webexposed/element-instance-property-listing-expected.txt +++ b/third_party/WebKit/LayoutTests/webexposed/element-instance-property-listing-expected.txt
@@ -299,6 +299,7 @@ property protocol property referrerPolicy property rel + property relList property search property shape property target
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 773df45db..7388a86 100644 --- a/third_party/WebKit/LayoutTests/webexposed/global-interface-listing-expected.txt +++ b/third_party/WebKit/LayoutTests/webexposed/global-interface-listing-expected.txt
@@ -2198,6 +2198,7 @@ getter protocol getter referrerPolicy getter rel + getter relList getter search getter shape getter target @@ -2219,6 +2220,7 @@ setter protocol setter referrerPolicy setter rel + setter relList setter search setter shape setter target @@ -4509,7 +4511,6 @@ getter webkitPersistentStorage getter webkitTemporaryStorage getter xr - method cancelKeyboardLock method constructor method getBattery method getGamepads @@ -4517,8 +4518,9 @@ method getUserMedia method getVRDisplays method javaEnabled + method keyboardLock + method keyboardUnlock method registerProtocolHandler - method requestKeyboardLock method requestMIDIAccess method requestMediaKeySystemAccess method sendBeacon
diff --git a/third_party/WebKit/PerformanceTests/inspector/console-300-lines.html b/third_party/WebKit/PerformanceTests/inspector/console-300-lines.html deleted file mode 100644 index 38a0e78..0000000 --- a/third_party/WebKit/PerformanceTests/inspector/console-300-lines.html +++ /dev/null
@@ -1,80 +0,0 @@ -<html> -<head> -<script src="../../LayoutTests/http/tests/inspector/inspector-test.js"></script> -<script src="performance-test.js"></script> -<script> - -function makeConsoleEvents(count) -{ - for (var i = 0; i < count; ++i) - console.log("Console log: " + i); -} - -function test() -{ - var message = { - "method":"Console.messageAdded", - "params":{ - "message":{ - "source":"console-api", - "level":"log", - "text":"Console log message", - "type":"log", - "line":10, - "url":"file://./console-300-lines.html", - "repeatCount":1, - "parameters":[{ - "type":"string", - "value":"Console log: 42" - }], - "stackTrace":[ - { - "functionName":"makeConsoleEvents", - "url":"file://./console-300-lines.html", - "lineNumber":10, - "columnNumber":17 - }, - { - "functionName":"", - "url":"file://./console-300-lines.html", - "lineNumber":37, - "columnNumber":9 - } - ] - } - } - }; - - WebInspector.showPanel("console"); - - function test(timer) - { - WebInspector.console.clearMessages(); - InspectorTest.addSniffer(WebInspector.consoleView.promptElement, "scrollIntoView", finish); - - var cookie = timer.start("console-300-lines"); - for (var i = 0; i < 300; ++i) - InspectorBackend.connection().dispatch(message); - - function finish() - { - timer.finish(cookie); - timer.done("panel-update"); - } - } - - InspectorTest.runPerformanceTest(test, 10000); -} - -if (!window.testRunner) { - setTimeout(function() { - makeConsoleEvents(300); - }, 3000); -} - -</script> -</head> - -<body onload="runTest()"> -</body> -</html>
diff --git a/third_party/WebKit/PerformanceTests/inspector/first-open-elements.html b/third_party/WebKit/PerformanceTests/inspector/first-open-elements.html deleted file mode 100644 index 0c75a88f..0000000 --- a/third_party/WebKit/PerformanceTests/inspector/first-open-elements.html +++ /dev/null
@@ -1,42 +0,0 @@ -<html> -<head> -<script src="../../LayoutTests/http/tests/inspector/inspector-test.js"></script> -<script src="performance-test.js"></script> -<script> - -function test() -{ - WebInspector.showPanel("audits"); - - - function test(timer) - { - WebInspector.showPanel("audits"); - WebInspector.domModel._setDocument(null); - - var showPanelTimerCookie = timer.start("first-open-elements"); - InspectorTest.addBackendResponseSniffer(DOMAgent, "requestChildNodes", function() { - timer.finish(showPanelTimerCookie); - timer.done("first-open"); - }); - WebInspector.showPanel("elements"); - } - - InspectorTest.runPerformanceTest(test, 5000); -} - -</script> -</head> - -<body onload="runTest()"> - -<div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div> -<div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div> -<div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div> -<div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div> -<div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div> -<div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div> - -</body> -</body> -</html>
diff --git a/third_party/WebKit/PerformanceTests/inspector/first-open-resources.html b/third_party/WebKit/PerformanceTests/inspector/first-open-resources.html deleted file mode 100644 index cb96af6..0000000 --- a/third_party/WebKit/PerformanceTests/inspector/first-open-resources.html +++ /dev/null
@@ -1,44 +0,0 @@ -<html> -<head> -<script src="../../LayoutTests/http/tests/inspector/inspector-test.js"></script> -<script src="performance-test.js"></script> -<script> - -function test() -{ - WebInspector.showPanel("resources"); - WebInspector.settings.resourcesLastSelectedItem.set(WebInspector.inspectedPageURL); - - function test(timer) - { - WebInspector.showPanel("audits"); - var resources = WebInspector.panels.resources; - resources.reset(); - var treeModel = WebInspector.resourceTreeModel; - treeModel.removeEventListener(WebInspector.ResourceTreeModel.EventTypes.FrameAdded, resources._frameAdded, resources); - treeModel.removeEventListener(WebInspector.ResourceTreeModel.EventTypes.FrameNavigated, resources._frameNavigated, resources); - treeModel.removeEventListener(WebInspector.ResourceTreeModel.EventTypes.FrameDetached, resources._frameDetached, resources); - treeModel.removeEventListener(WebInspector.ResourceTreeModel.EventTypes.ResourceAdded, resources._resourceAdded, resources); - resources._initialized = false; - - InspectorTest.addBackendResponseSniffer(ApplicationCacheAgent, "getFramesWithManifests", finish); - var showPanelTimerCookie = timer.start("first-open-resources"); - treeModel._fetchResourceTree(); - WebInspector.showPanel("resources"); - - function finish() - { - timer.finish(showPanelTimerCookie); - timer.done("first-open"); - } - } - InspectorTest.runPerformanceTest(test, 5000); -} - -</script> -</head> -<body onload="runTest()"> -</body> -</body> -</html> -
diff --git a/third_party/WebKit/PerformanceTests/inspector/first-open-scripts.html.broken b/third_party/WebKit/PerformanceTests/inspector/first-open-scripts.html.broken deleted file mode 100644 index 357dd3d..0000000 --- a/third_party/WebKit/PerformanceTests/inspector/first-open-scripts.html.broken +++ /dev/null
@@ -1,39 +0,0 @@ -<html> -<head> -<script src="../../LayoutTests/http/tests/inspector/inspector-test.js"></script> -<script src="performance-test.js"></script> -<script> - -function test() -{ - WebInspector.showPanel("scripts"); - var files = WebInspector.panels.scripts._fileSelector._filesSelectElement; - for (var i = 0; i < files.options.length; ++i) { - if (files.options[i].value.indexOf("inspector-test.js") !== -1) { - files.selectedIndex = i; - WebInspector.panels.scripts._fileSelector._filesSelectChanged(); - break; - } - } - - function test(timer) - { - WebInspector.showPanel("audits"); - var showPanelTimerCookie = timer.start("first-open-scripts"); - WebInspector.showPanel("scripts"); - var count = WebInspector.panels.scripts.visibleView._textEditor._mainPanel._textChunks.length; - WebInspector.panels.scripts.visibleView._textEditor._mainPanel._expandChunks(0, count); - WebInspector.panels.scripts.visibleView._textEditor._mainPanel._paintScheduledLines(); - timer.finish(showPanelTimerCookie); - timer.done("first-open"); - } - - InspectorTest.runAfterPendingDispatches(InspectorTest.runPerformanceTest.bind(null, test, 5000)); -} - -</script> -</head> -<body onload="runTest()"> -</body> -</html> -
diff --git a/third_party/WebKit/PerformanceTests/inspector/heap-snapshot-advanced.html b/third_party/WebKit/PerformanceTests/inspector/heap-snapshot-advanced.html deleted file mode 100644 index 58b48f0..0000000 --- a/third_party/WebKit/PerformanceTests/inspector/heap-snapshot-advanced.html +++ /dev/null
@@ -1,35 +0,0 @@ -<html> -<head> - <script src="../../LayoutTests/http/tests/inspector/inspector-test.js"></script> - <script src="../../LayoutTests/inspector/profiler/heap-snapshot-test.js"></script> - <script src="performance-test.js"></script> - <script src="heap-snapshot-performance-test.js"></script> -<script> - -function makeLinkedList(n) -{ - var node = {}; - while (--n) - node = { next: node }; - return node; -} - -function makeDoubleLinkedList(n) -{ - var tail = {}; - var head = tail; - while (--n) { - head = { next: head }; - head.next.prev = head; - } - return { head: head, tail: tail }; -} - -var list = makeLinkedList(20000); -var double_list = makeDoubleLinkedList(5000); - -</script> -</head> -<body onload="runTest()"> -</body> -</html>
diff --git a/third_party/WebKit/PerformanceTests/inspector/heap-snapshot-performance-test.js b/third_party/WebKit/PerformanceTests/inspector/heap-snapshot-performance-test.js deleted file mode 100644 index a084b88..0000000 --- a/third_party/WebKit/PerformanceTests/inspector/heap-snapshot-performance-test.js +++ /dev/null
@@ -1,75 +0,0 @@ -function test() -{ - WebInspector.showPanel("profiles"); - InspectorTest.measureFunction(WebInspector.JSHeapSnapshot.prototype, "_buildEdgeIndexes"); - InspectorTest.measureFunction(WebInspector.JSHeapSnapshot.prototype, "_buildRetainers"); - InspectorTest.measureFunction(WebInspector.JSHeapSnapshot.prototype, "_buildDominatedNodes"); - InspectorTest.measureFunction(WebInspector.JSHeapSnapshot.prototype, "_calculateFlags"); - InspectorTest.measureFunction(WebInspector.JSHeapSnapshot.prototype, "_buildAggregates"); - InspectorTest.measureFunction(WebInspector.JSHeapSnapshot.prototype, "_calculateClassesRetainedSize"); - InspectorTest.measureFunction(WebInspector.JSHeapSnapshot.prototype, "_calculateDistances"); - InspectorTest.measureFunction(WebInspector.JSHeapSnapshot.prototype, "_calculateRetainedSizes"); - InspectorTest.measureFunction(WebInspector.JSHeapSnapshot.prototype, "_markDetachedDOMTreeNodes"); - InspectorTest.measureFunction(WebInspector.JSHeapSnapshot.prototype, "_markQueriableHeapObjects"); - InspectorTest.measureFunction(WebInspector.JSHeapSnapshot.prototype, "_markPageOwnedNodes"); - InspectorTest.measureFunction(WebInspector.JSHeapSnapshot.prototype, "_splitNodesAndContainmentEdges"); - InspectorTest.measureFunction(WebInspector.JSHeapSnapshot.prototype, "_buildPostOrderIndex"); - InspectorTest.measureFunction(WebInspector.JSHeapSnapshot.prototype, "_buildDominatorTree"); - InspectorTest.measureFunction(WebInspector.HeapSnapshotConstructorsDataGrid.prototype, "_aggregatesReceived"); - - function performanceTest(timer) - { - var transferTimerCookie; - var showTimerCookie; - var changeViewTimerCookie; - var clearTimerCookie; - - var testName = /([^\/]+)\.html$/.exec(WebInspector.inspectedPageURL)[1]; - var fullTimerCookie = timer.start("full-summary-snapshot-time"); - var type = WebInspector.panels.profiles.getProfileType("HEAP"); - - var backendTimerCookie = timer.start("take-snapshot"); - type._takeHeapSnapshot(step0); - - function step0() - { - timer.finish(backendTimerCookie); - transferTimerCookie = timer.start("transfer-snapshot"); - var profiles = type.getProfiles(); - InspectorTest.addSniffer(profiles[0]._transferHandler, "_updateProgress", onUpdateProgress, true); - InspectorTest.addSniffer(profiles[0], "_wasShown", step2); - } - - function onUpdateProgress(saved, total) - { - if (saved !== total) - return; - timer.finish(transferTimerCookie); - showTimerCookie = timer.start("show-snapshot"); - } - - function step2() - { - timer.finish(showTimerCookie); - changeViewTimerCookie = timer.start("switch-to-containment-view"); - InspectorTest.switchToView("Containment", cleanup); - } - - function cleanup() - { - timer.finish(changeViewTimerCookie); - timer.finish(fullTimerCookie); - clearTimerCookie = timer.start("clear-snapshot"); - HeapProfilerAgent.clearProfiles(done); - WebInspector.panels.profiles._reset(); - } - - function done() - { - timer.finish(clearTimerCookie); - timer.done(testName); - } - } - - InspectorTest.runPerformanceTest(performanceTest, 60000); -}
diff --git a/third_party/WebKit/PerformanceTests/inspector/heap-snapshot.html b/third_party/WebKit/PerformanceTests/inspector/heap-snapshot.html deleted file mode 100644 index 0fabb21..0000000 --- a/third_party/WebKit/PerformanceTests/inspector/heap-snapshot.html +++ /dev/null
@@ -1,33 +0,0 @@ -<html> -<head> - <script src="../../LayoutTests/http/tests/inspector/inspector-test.js"></script> - <script src="../../LayoutTests/inspector/profiler/heap-snapshot-test.js"></script> - <script src="performance-test.js"></script> - <script src="heap-snapshot-performance-test.js"></script> -<script> - -var counter = 0; - -function makeObjectsTree(deep) -{ - var node = {}; - node.text = "some text " + counter; - if (deep === 0) - return node; - for (var i = 0; i < 2; ++i) - node[counter++] = makeObjectsTree(deep - 1); - return node; -} - -function makeObjectsTree2(name, deep) -{ - window[name] = makeObjectsTree(deep); -} - -makeObjectsTree2("t", 16); - -</script> -</head> -<body onload="runTest()"> -</body> -</html>
diff --git a/third_party/WebKit/PerformanceTests/inspector/inspector-startup-time.html b/third_party/WebKit/PerformanceTests/inspector/inspector-startup-time.html deleted file mode 100644 index 391b004..0000000 --- a/third_party/WebKit/PerformanceTests/inspector/inspector-startup-time.html +++ /dev/null
@@ -1,57 +0,0 @@ -<!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML//EN"> -<html> -<head> -<script src="../../LayoutTests/http/tests/inspector/inspector-test.js"></script> -<script src="performance-test.js"></script> -<script> - -function onload() -{ - testRunner.waitUntilDone(); - times = []; - startTime = Date.now(); - testStartTime = startTime; - runTest(); -} - -function inspectorIsReady() -{ - times.push(Date.now() - startTime); - if (Date.now() - testStartTime > 20000) { - testRunner.evaluateInWebInspector(2, "InspectorTest.dumpTestStats('inspector-startup-time', 'time', " + JSON.stringify(times) + ", 'ms')") - testRunner.evaluateInWebInspector(3, "(InspectorTest.completeTest())") - return; - } - testRunner.closeWebInspector(); - startTime = Date.now(); - testRunner.showWebInspector(); - runTest(); -} - -function test() -{ - WebInspector.domModel._setDocument(null); - - InspectorTest.addBackendResponseSniffer(DOMAgent, "requestChildNodes", function() { - WebInspector.inspectorView._lastActivePanelSetting.set("audits"); - InspectorTest.evaluateInPage("inspectorIsReady()"); - }); - WebInspector.showPanel("elements"); -} - -</script> - -</head> -<body onload="onload()"> -<div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div> -<div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div> -<div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div> -<div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div> -<div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div> -<div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div> -<div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div> -<div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div> -<div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div> -<div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div> -</body> -</html>
diff --git a/third_party/WebKit/PerformanceTests/inspector/network-append-30-requests.html.broken b/third_party/WebKit/PerformanceTests/inspector/network-append-30-requests.html.broken deleted file mode 100644 index 357cbc9..0000000 --- a/third_party/WebKit/PerformanceTests/inspector/network-append-30-requests.html.broken +++ /dev/null
@@ -1,52 +0,0 @@ -<html> -<head> -<script src="../../LayoutTests/http/tests/inspector/inspector-test.js"></script> -<script src="performance-test.js"></script> -<script> - -function makeXHRRequests(count) -{ - for (var i = 0; i < count; ++i) { - var xhr = new XMLHttpRequest(); - xhr.open("GET", document.URL, true); - xhr.send(); - } -} - -function test() -{ - WebInspector.showPanel("network"); - - var originalRefresh = InspectorTest.override(WebInspector.panels.network._networkLogView, "refresh", timeTrackingRefresh, true); - WebInspector.panels.network._networkLogView._defaultRefreshDelay = 30; - function timeTrackingRefresh() - { - var cookie = InspectorTest.timer.start("network-append-30-requests"); - originalRefresh.call(this); - InspectorTest.timer.finish(cookie); - WebInspector.panels.network._networkLogView._reset(); - // In real life this array is cleaning up at navigation event. - WebInspector.networkLog._resources = []; - InspectorTest.timer.done("panel-update"); - } - - function test(timer) - { - InspectorTest.evaluateInPage("makeXHRRequests(30)"); - } - - InspectorTest.runPerformanceTest(test, 15000); -} - -if (!window.testRunner) { - setTimeout(function() { - makeXHRRequests(30); - }, 3000); -} - -</script> -</head> - -<body onload="runTest()"> -</body> -</html>
diff --git a/third_party/WebKit/PerformanceTests/inspector/performance-test.js b/third_party/WebKit/PerformanceTests/inspector/performance-test.js deleted file mode 100644 index fec1dd30..0000000 --- a/third_party/WebKit/PerformanceTests/inspector/performance-test.js +++ /dev/null
@@ -1,155 +0,0 @@ -var initialize_TimeTracker = function() { - -InspectorTest.runPerformanceTest = function(perfTest, executeTime, callback) -{ - var Timer = function(test, callback) - { - this._callback = callback; - this._test = test; - this._times = {}; - this._sizes = {}; - this._testStartTime = new Date(); - this._heapSizeDeltas = []; - this._jsHeapSize = this._getJSHeapSize(); - } - - Timer.prototype = { - start: function(name) - { - return {name: name, startTime: new Date()}; - }, - - finish: function(cookie) - { - var endTime = new Date(); - if (!this._times[cookie.name]) - this._times[cookie.name] = []; - this._times[cookie.name].push(endTime - cookie.startTime); - }, - - reportSize: function(name, size) - { - if (!this._sizes[name]) - this._sizes[name] = []; - this._sizes[name].push(size); - }, - - _getJSHeapSize: function() - { - if (window.gc) { - window.gc(); - window.gc(); - } - return console.memory.usedJSHeapSize; - }, - - done: function(groupName) - { - var newJSHeapSize = this._getJSHeapSize(); - this._heapSizeDeltas.push(newJSHeapSize - this._jsHeapSize); - this._jsHeapSize = newJSHeapSize; - - var time = new Date(); - if (time - this._testStartTime < executeTime) - this._runTest(); - else { - if (this._complete) - return; - this._complete = true; - - this._dump(groupName); - if (this._callback) - this._callback(); - else - InspectorTest.completeTest(); - } - }, - - _runTest: function() - { - if (this._guard) { - setTimeout(this._runTest.bind(this), 0); - return; - } - - this._guard = true; - var safeTest = InspectorTest.safeWrap(this._test); - safeTest(this); - this._guard = false; - }, - - _dump: function(groupName) - { - for (var testName in this._times) - InspectorTest.dumpTestStats(groupName, testName, this._times[testName], "ms"); - - for (var testName in this._sizes) - InspectorTest.dumpTestStats(groupName, testName, this._sizes[testName], "kB", 1024); - - var url = WebInspector.inspectedPageURL; - var regExp = /([^\/]+)\.html/; - var matches = regExp.exec(url); - InspectorTest.dumpTestStats("heap-delta", matches[1], this._heapSizeDeltas, "kB", 1024); - }, - } - - InspectorTest.timer = new Timer(perfTest, callback); - InspectorTest.timer._runTest(); -} - -InspectorTest.measureFunction = function(object, functionName) -{ - function measure() { - var timer = InspectorTest.timer; - var cookie; - if (timer) - cookie = timer.start(functionName); - var result = func.apply(this, arguments); - - if (timer) - timer.finish(cookie); - return result; - } - var func = object[functionName]; - object[functionName] = measure; -} - -InspectorTest.mark = function(markerName) -{ - var timer = InspectorTest.timer; - if (!timer) - return; - - if (InspectorTest.lastMarkCookie) - timer.finish(InspectorTest.lastMarkCookie); - - InspectorTest.lastMarkCookie = markerName ? timer.start(markerName) : null; -} - -InspectorTest.dumpTestStats = function(groupName, testName, samples, units, divider) -{ - divider = divider || 1; - var stripNResults = Math.floor(samples.length / 10); - samples.sort(function(a, b) { return a - b; }); - var sum = 0; - for (var i = stripNResults; i < samples.length - stripNResults; ++i) - sum += samples[i]; - InspectorTest.addResult("RESULT " + groupName + ': ' + testName + "= " + Math.floor(sum / (samples.length - stripNResults * 2) / divider) + " " + units); -} - -InspectorTest.addBackendResponseSniffer = function(object, methodName, override, opt_sticky) -{ - var originalMethod = InspectorTest.override(object, methodName, backendCall, opt_sticky); - function backendCall() - { - var args = Array.prototype.slice.call(arguments); - var callback = (args.length && typeof args[args.length - 1] === "function") ? args.pop() : 0; - args.push(function() { - callback.apply(null, arguments); - override.apply(null, arguments); - }); - originalMethod.apply(object, args); - } -} - -}
diff --git a/third_party/WebKit/PerformanceTests/inspector/show-panel.html.broken b/third_party/WebKit/PerformanceTests/inspector/show-panel.html.broken deleted file mode 100644 index b59f062..0000000 --- a/third_party/WebKit/PerformanceTests/inspector/show-panel.html.broken +++ /dev/null
@@ -1,66 +0,0 @@ -<html> -<head> -<script src="../../LayoutTests/http/tests/inspector/inspector-test.js"></script> -<script src="performance-test.js"></script> -<script> - -function makeXHRRequests(count) -{ - for (var i = 0; i < count; ++i) { - var xhr = new XMLHttpRequest(); - xhr.open("GET", document.URL, true); - xhr.send(); - } -} - -function test() -{ - WebInspector.showPanel("scripts"); - var files = WebInspector.panels.scripts._fileSelector._filesSelectElement; - for (var i = 0; i < files.options.length; ++i) { - if (files.options[i].value.indexOf("inspector-test.js") !== -1) { - files.selectedIndex = i; - WebInspector.panels.scripts._fileSelector._filesSelectChanged(); - break; - } - } - - WebInspector.showPanel("resources"); - WebInspector.settings.resourcesLastSelectedItem.set(WebInspector.inspectedPageURL); - - WebInspector.showPanel("network"); - InspectorTest.evaluateInPage("makeXHRRequests(200)", runTest); - - function runTest() - { - InspectorTest.runPerformanceTest(perfTest, 10000); - } - - function perfTest(timer) - { - WebInspector.showPanel("audits"); - for (var panelName in WebInspector.panels) { - var timerCookie = timer.start("show-panel-" + panelName); - WebInspector.showPanel(panelName); - InspectorTest.evaluateInPage("testRunner.display();"); - timer.finish(timerCookie); - } - timer.done("panel-switch"); - } -} -</script> -</head> - -<body onload="runTest()"> -<div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div> -<div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div> -<div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div> -<div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div> -<div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div> -<div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div> -<div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div> -<div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div> -<div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div> -<div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div> -</body> -</html>
diff --git a/third_party/WebKit/Source/core/css/CSSGradientValue.cpp b/third_party/WebKit/Source/core/css/CSSGradientValue.cpp index 2a79f30..6a888d4e 100644 --- a/third_party/WebKit/Source/core/css/CSSGradientValue.cpp +++ b/third_party/WebKit/Source/core/css/CSSGradientValue.cpp
@@ -115,11 +115,7 @@ if (!Clients().Contains(&client)) return nullptr; - // Need to look up our size. Create a string of width*height to use as a - // hash key. - Image* result = - this->CSSImageGeneratorValue::GetImage(&client, document, style, size); - if (result) + if (Image* result = CSSImageGeneratorValue::GetImage(&client, size)) return result; }
diff --git a/third_party/WebKit/Source/core/css/CSSImageGeneratorValue.cpp b/third_party/WebKit/Source/core/css/CSSImageGeneratorValue.cpp index 0d490078..7a5c8baf 100644 --- a/third_party/WebKit/Source/core/css/CSSImageGeneratorValue.cpp +++ b/third_party/WebKit/Source/core/css/CSSImageGeneratorValue.cpp
@@ -28,7 +28,6 @@ #include "core/css/CSSCrossfadeValue.h" #include "core/css/CSSGradientValue.h" #include "core/css/CSSPaintValue.h" -#include "core/layout/LayoutObject.h" #include "platform/graphics/Image.h" namespace blink { @@ -93,8 +92,6 @@ } Image* CSSImageGeneratorValue::GetImage(const ImageResourceObserver* client, - const Document&, - const ComputedStyle&, const LayoutSize& size) { ClientSizeCountMap::iterator it = clients_.find(client); if (it != clients_.end()) {
diff --git a/third_party/WebKit/Source/core/css/CSSImageGeneratorValue.h b/third_party/WebKit/Source/core/css/CSSImageGeneratorValue.h index 12ea3741d..d99403c 100644 --- a/third_party/WebKit/Source/core/css/CSSImageGeneratorValue.h +++ b/third_party/WebKit/Source/core/css/CSSImageGeneratorValue.h
@@ -81,10 +81,7 @@ protected: explicit CSSImageGeneratorValue(ClassType); - Image* GetImage(const ImageResourceObserver*, - const Document&, - const ComputedStyle&, - const LayoutSize&); + Image* GetImage(const ImageResourceObserver*, const LayoutSize&); void PutImage(const LayoutSize&, scoped_refptr<Image>); const ClientSizeCountMap& Clients() const { return clients_; }
diff --git a/third_party/WebKit/Source/core/css/cssom/ComputedStylePropertyMap.cpp b/third_party/WebKit/Source/core/css/cssom/ComputedStylePropertyMap.cpp index d67b2533..967e918 100644 --- a/third_party/WebKit/Source/core/css/cssom/ComputedStylePropertyMap.cpp +++ b/third_party/WebKit/Source/core/css/cssom/ComputedStylePropertyMap.cpp
@@ -4,10 +4,12 @@ #include "core/css/cssom/ComputedStylePropertyMap.h" +#include "core/css/CSSCustomPropertyDeclaration.h" #include "core/css/CSSVariableData.h" #include "core/css/ComputedStyleCSSValueMapping.h" #include "core/dom/Document.h" #include "core/dom/PseudoElement.h" +#include "core/style/ComputedStyle.h" namespace blink { @@ -80,6 +82,16 @@ if (value) callback(property->GetPropertyName(), *value); } + + const auto& variables = ComputedStyleCSSValueMapping::GetVariables(*style); + if (variables) { + for (const auto& name_value : *variables) { + if (name_value.value) { + callback(name_value.key, *CSSCustomPropertyDeclaration::Create( + name_value.key, name_value.value)); + } + } + } } } // namespace blink
diff --git a/third_party/WebKit/Source/core/dom/Element.cpp b/third_party/WebKit/Source/core/dom/Element.cpp index 4f50b7d..d0fa7b1 100644 --- a/third_party/WebKit/Source/core/dom/Element.cpp +++ b/third_party/WebKit/Source/core/dom/Element.cpp
@@ -1276,7 +1276,7 @@ return rare_data.EnsureAccessibleNode(this); } -ComputedAccessibleNode* Element::ComputedAccessibleNode() { +ComputedAccessibleNode* Element::GetComputedAccessibleNode() { if (!RuntimeEnabledFeatures::AccessibilityObjectModelEnabled()) return nullptr;
diff --git a/third_party/WebKit/Source/core/dom/Element.h b/third_party/WebKit/Source/core/dom/Element.h index 733596b..986e31a 100644 --- a/third_party/WebKit/Source/core/dom/Element.h +++ b/third_party/WebKit/Source/core/dom/Element.h
@@ -295,7 +295,7 @@ AccessibleNode* ExistingAccessibleNode() const; AccessibleNode* accessibleNode(); - ComputedAccessibleNode* ComputedAccessibleNode(); + ComputedAccessibleNode* GetComputedAccessibleNode(); void DidMoveToNewDocument(Document&) override;
diff --git a/third_party/WebKit/Source/core/dom/FlatTreeTraversal.cpp b/third_party/WebKit/Source/core/dom/FlatTreeTraversal.cpp index f815c08f..48810bf 100644 --- a/third_party/WebKit/Source/core/dom/FlatTreeTraversal.cpp +++ b/third_party/WebKit/Source/core/dom/FlatTreeTraversal.cpp
@@ -28,19 +28,12 @@ #include "core/dom/Element.h" #include "core/dom/ElementShadow.h" +#include "core/dom/ng/flat_tree_traversal_ng.h" #include "core/html/HTMLShadowElement.h" #include "core/html/HTMLSlotElement.h" namespace blink { -static inline ElementShadow* ShadowFor(const Node& node) { - return node.IsElementNode() ? ToElement(node).Shadow() : nullptr; -} - -static inline bool CanBeDistributedToV0InsertionPoint(const Node& node) { - return node.IsInV0ShadowTree() || node.IsChildOfV0ShadowHost(); -} - Node* FlatTreeTraversal::TraverseChild(const Node& node, TraversalDirection direction) { ElementShadow* shadow = ShadowFor(node);
diff --git a/third_party/WebKit/Source/core/dom/ng/flat_tree_traversal_ng.cc b/third_party/WebKit/Source/core/dom/ng/flat_tree_traversal_ng.cc index ebc2e39..c9397c6 100644 --- a/third_party/WebKit/Source/core/dom/ng/flat_tree_traversal_ng.cc +++ b/third_party/WebKit/Source/core/dom/ng/flat_tree_traversal_ng.cc
@@ -33,11 +33,11 @@ namespace blink { -static inline ElementShadow* ShadowFor(const Node& node) { +ElementShadow* ShadowFor(const Node& node) { return node.IsElementNode() ? ToElement(node).Shadow() : nullptr; } -static inline bool CanBeDistributedToV0InsertionPoint(const Node& node) { +bool CanBeDistributedToV0InsertionPoint(const Node& node) { return node.IsInV0ShadowTree() || node.IsChildOfV0ShadowHost(); }
diff --git a/third_party/WebKit/Source/core/dom/ng/flat_tree_traversal_ng.h b/third_party/WebKit/Source/core/dom/ng/flat_tree_traversal_ng.h index ca433a6..81d0c079 100644 --- a/third_party/WebKit/Source/core/dom/ng/flat_tree_traversal_ng.h +++ b/third_party/WebKit/Source/core/dom/ng/flat_tree_traversal_ng.h
@@ -38,8 +38,12 @@ namespace blink { class ContainerNode; +class ElementShadow; class Node; +ElementShadow* ShadowFor(const Node& node); +bool CanBeDistributedToV0InsertionPoint(const Node& node); + // Flat tree version of |NodeTraversal|. // // None of member functions takes a |ShadowRoot| or an active insertion point,
diff --git a/third_party/WebKit/Source/core/editing/EditingStyleUtilities.cpp b/third_party/WebKit/Source/core/editing/EditingStyleUtilities.cpp index 003c48f..92d6a2f 100644 --- a/third_party/WebKit/Source/core/editing/EditingStyleUtilities.cpp +++ b/third_party/WebKit/Source/core/editing/EditingStyleUtilities.cpp
@@ -42,6 +42,32 @@ using namespace cssvalue; +namespace { + +Position AdjustedSelectionStartForStyleComputation(const Position& position) { + // This function is used by range style computations to avoid bugs like: + // <rdar://problem/4017641> REGRESSION (Mail): you can only bold/unbold a + // selection starting from end of line once + // It is important to skip certain irrelevant content at the start of the + // selection, so we do not wind up with a spurious "mixed" style. + + VisiblePosition visible_position = CreateVisiblePosition(position); + if (visible_position.IsNull()) + return Position(); + + // if the selection starts just before a paragraph break, skip over it + if (IsEndOfParagraph(visible_position)) { + return MostForwardCaretPosition( + NextPositionOf(visible_position).DeepEquivalent()); + } + + // otherwise, make sure to be at the start of the first selected node, + // instead of possibly at the end of the last node before the selection + return MostForwardCaretPosition(visible_position.DeepEquivalent()); +} + +} // anonymous namespace + bool EditingStyleUtilities::HasAncestorVerticalAlignStyle(Node& node, CSSValueID value) { for (Node& runner : NodeTraversal::InclusiveAncestorsOf(node)) {
diff --git a/third_party/WebKit/Source/core/editing/EditingUtilities.cpp b/third_party/WebKit/Source/core/editing/EditingUtilities.cpp index 129e4db..f1889dd 100644 --- a/third_party/WebKit/Source/core/editing/EditingUtilities.cpp +++ b/third_party/WebKit/Source/core/editing/EditingUtilities.cpp
@@ -2038,27 +2038,6 @@ layout_object->IsLayoutBlockFlow(); } -Position AdjustedSelectionStartForStyleComputation(const Position& position) { - // This function is used by range style computations to avoid bugs like: - // <rdar://problem/4017641> REGRESSION (Mail): you can only bold/unbold a - // selection starting from end of line once - // It is important to skip certain irrelevant content at the start of the - // selection, so we do not wind up with a spurious "mixed" style. - - VisiblePosition visible_position = CreateVisiblePosition(position); - if (visible_position.IsNull()) - return Position(); - - // if the selection starts just before a paragraph break, skip over it - if (IsEndOfParagraph(visible_position)) - return MostForwardCaretPosition( - NextPositionOf(visible_position).DeepEquivalent()); - - // otherwise, make sure to be at the start of the first selected node, - // instead of possibly at the end of the last node before the selection - return MostForwardCaretPosition(visible_position.DeepEquivalent()); -} - bool IsInPasswordField(const Position& position) { TextControlElement* text_control = EnclosingTextControl(position); return IsHTMLInputElement(text_control) &&
diff --git a/third_party/WebKit/Source/core/editing/EditingUtilities.h b/third_party/WebKit/Source/core/editing/EditingUtilities.h index 1d81e17c..d4ebbb4 100644 --- a/third_party/WebKit/Source/core/editing/EditingUtilities.h +++ b/third_party/WebKit/Source/core/editing/EditingUtilities.h
@@ -384,10 +384,6 @@ // Functions returning VisibleSelection VisibleSelection SelectionForParagraphIteration(const VisibleSelection&); -// TODO(editing-dev): We should move "adjustedSelectionStartForStyleComputation" -// to "EditingStyleUtilitie.cpp" as local function since it used only there. -Position AdjustedSelectionStartForStyleComputation(const Position&); - // Miscellaneous functions on Text inline bool IsWhitespace(UChar c) { return c == kNoBreakSpaceCharacter || c == ' ' || c == '\n' || c == '\t';
diff --git a/third_party/WebKit/Source/core/editing/Editor.cpp b/third_party/WebKit/Source/core/editing/Editor.cpp index 268cc4d..1b0bf64 100644 --- a/third_party/WebKit/Source/core/editing/Editor.cpp +++ b/third_party/WebKit/Source/core/editing/Editor.cpp
@@ -148,25 +148,6 @@ return false; } -EphemeralRange ComputeRangeForTranspose(LocalFrame& frame) { - const VisibleSelection& selection = - frame.Selection().ComputeVisibleSelectionInDOMTree(); - if (!selection.IsCaret()) - return EphemeralRange(); - - // Make a selection that goes back one character and forward two characters. - const VisiblePosition& caret = selection.VisibleStart(); - const VisiblePosition& next = - IsEndOfParagraph(caret) ? caret : NextPositionOf(caret); - const VisiblePosition& previous = PreviousPositionOf(next); - if (next.DeepEquivalent() == previous.DeepEquivalent()) - return EphemeralRange(); - const VisiblePosition& previous_of_previous = PreviousPositionOf(previous); - if (!InSameParagraph(next, previous_of_previous)) - return EphemeralRange(); - return MakeRange(previous_of_previous, next); -} - } // anonymous namespace Editor::RevealSelectionScope::RevealSelectionScope(Editor* editor) @@ -1429,68 +1410,6 @@ GetFrameSelection().RevealSelection(alignment, kDoNotRevealExtent); } -// TODO(yosin): We should move |Transpose()| into |ExecuteTranspose()| in -// "EditorCommand.cpp" -void Transpose(LocalFrame& frame) { - Editor& editor = frame.GetEditor(); - if (!editor.CanEdit()) - return; - - Document* const document = frame.GetDocument(); - - // TODO(editing-dev): The use of UpdateStyleAndLayoutIgnorePendingStylesheets - // needs to be audited. See http://crbug.com/590369 for more details. - document->UpdateStyleAndLayoutIgnorePendingStylesheets(); - - const EphemeralRange& range = ComputeRangeForTranspose(frame); - if (range.IsNull()) - return; - - // Transpose the two characters. - const String& text = PlainText(range); - if (text.length() != 2) - return; - const String& transposed = text.Right(1) + text.Left(1); - - if (DispatchBeforeInputInsertText( - EventTargetNodeForDocument(document), transposed, - InputEvent::InputType::kInsertTranspose, - new StaticRangeVector(1, StaticRange::Create(range))) != - DispatchEventResult::kNotCanceled) - return; - - // 'beforeinput' event handler may destroy document-> - if (frame.GetDocument() != document) - return; - - // TODO(editing-dev): The use of UpdateStyleAndLayoutIgnorePendingStylesheets - // needs to be audited. See http://crbug.com/590369 for more details. - document->UpdateStyleAndLayoutIgnorePendingStylesheets(); - - // 'beforeinput' event handler may change selection, we need to re-calculate - // range. - const EphemeralRange& new_range = ComputeRangeForTranspose(frame); - if (new_range.IsNull()) - return; - - const String& new_text = PlainText(new_range); - if (new_text.length() != 2) - return; - const String& new_transposed = new_text.Right(1) + new_text.Left(1); - - const SelectionInDOMTree& new_selection = - SelectionInDOMTree::Builder().SetBaseAndExtent(new_range).Build(); - - // Select the two characters. - if (CreateVisibleSelection(new_selection) != - frame.Selection().ComputeVisibleSelectionInDOMTree()) - frame.Selection().SetSelection(new_selection); - - // Insert the transposed characters. - editor.ReplaceSelectionWithText(new_transposed, false, false, - InputEvent::InputType::kInsertTranspose); -} - void Editor::AddToKillRing(const EphemeralRange& range) { if (should_start_new_kill_ring_sequence_) GetKillRing().StartNewSequence();
diff --git a/third_party/WebKit/Source/core/editing/Editor.h b/third_party/WebKit/Source/core/editing/Editor.h index 6a46173..6c263d7 100644 --- a/third_party/WebKit/Source/core/editing/Editor.h +++ b/third_party/WebKit/Source/core/editing/Editor.h
@@ -391,10 +391,6 @@ typing_style_ = style; } -// TODO(yosin): We should move |Transpose()| into |ExecuteTranspose()| in -// "EditorCommand.cpp" -void Transpose(LocalFrame&); - } // namespace blink #endif // Editor_h
diff --git a/third_party/WebKit/Source/core/editing/commands/CompositeEditCommand.cpp b/third_party/WebKit/Source/core/editing/commands/CompositeEditCommand.cpp index b363491..8928308d 100644 --- a/third_party/WebKit/Source/core/editing/commands/CompositeEditCommand.cpp +++ b/third_party/WebKit/Source/core/editing/commands/CompositeEditCommand.cpp
@@ -1245,6 +1245,8 @@ MostForwardCaretPosition(caret_after_delete.DeepEquivalent()); Node* node = position.AnchorNode(); + // InsertListCommandTest.CleanupNodeSameAsDestinationNode reaches here. + ABORT_EDITING_COMMAND_IF(destination_node == node); // Bail if we'd remove an ancestor of our destination. if (destination_node && destination_node->IsDescendantOf(node)) return;
diff --git a/third_party/WebKit/Source/core/editing/commands/EditorCommand.cpp b/third_party/WebKit/Source/core/editing/commands/EditorCommand.cpp index b501a314..aef24cc 100644 --- a/third_party/WebKit/Source/core/editing/commands/EditorCommand.cpp +++ b/third_party/WebKit/Source/core/editing/commands/EditorCommand.cpp
@@ -55,6 +55,7 @@ #include "core/editing/commands/ReplaceSelectionCommand.h" #include "core/editing/commands/TypingCommand.h" #include "core/editing/commands/UnlinkCommand.h" +#include "core/editing/iterators/TextIterator.h" #include "core/editing/serializers/Serialization.h" #include "core/editing/spellcheck/SpellChecker.h" #include "core/frame/ContentSettingsClient.h" @@ -218,6 +219,25 @@ return ranges; } +EphemeralRange ComputeRangeForTranspose(LocalFrame& frame) { + const VisibleSelection& selection = + frame.Selection().ComputeVisibleSelectionInDOMTree(); + if (!selection.IsCaret()) + return EphemeralRange(); + + // Make a selection that goes back one character and forward two characters. + const VisiblePosition& caret = selection.VisibleStart(); + const VisiblePosition& next = + IsEndOfParagraph(caret) ? caret : NextPositionOf(caret); + const VisiblePosition& previous = PreviousPositionOf(next); + if (next.DeepEquivalent() == previous.DeepEquivalent()) + return EphemeralRange(); + const VisiblePosition& previous_of_previous = PreviousPositionOf(previous); + if (!InSameParagraph(next, previous_of_previous)) + return EphemeralRange(); + return MakeRange(previous_of_previous, next); +} + } // anonymous namespace class EditorInternalCommand { @@ -1973,7 +1993,63 @@ Event*, EditorCommandSource, const String&) { - Transpose(frame); + Editor& editor = frame.GetEditor(); + if (!editor.CanEdit()) + return false; + + Document* const document = frame.GetDocument(); + + // TODO(editing-dev): The use of UpdateStyleAndLayoutIgnorePendingStylesheets + // needs to be audited. See http://crbug.com/590369 for more details. + document->UpdateStyleAndLayoutIgnorePendingStylesheets(); + + const EphemeralRange& range = ComputeRangeForTranspose(frame); + if (range.IsNull()) + return false; + + // Transpose the two characters. + const String& text = PlainText(range); + if (text.length() != 2) + return false; + const String& transposed = text.Right(1) + text.Left(1); + + if (DispatchBeforeInputInsertText( + EventTargetNodeForDocument(document), transposed, + InputEvent::InputType::kInsertTranspose, + new StaticRangeVector(1, StaticRange::Create(range))) != + DispatchEventResult::kNotCanceled) + return false; + + // 'beforeinput' event handler may destroy document-> + if (frame.GetDocument() != document) + return false; + + // TODO(editing-dev): The use of UpdateStyleAndLayoutIgnorePendingStylesheets + // needs to be audited. See http://crbug.com/590369 for more details. + document->UpdateStyleAndLayoutIgnorePendingStylesheets(); + + // 'beforeinput' event handler may change selection, we need to re-calculate + // range. + const EphemeralRange& new_range = ComputeRangeForTranspose(frame); + if (new_range.IsNull()) + return false; + + const String& new_text = PlainText(new_range); + if (new_text.length() != 2) + return false; + const String& new_transposed = new_text.Right(1) + new_text.Left(1); + + const SelectionInDOMTree& new_selection = + SelectionInDOMTree::Builder().SetBaseAndExtent(new_range).Build(); + + // Select the two characters. + if (CreateVisibleSelection(new_selection) != + frame.Selection().ComputeVisibleSelectionInDOMTree()) + frame.Selection().SetSelection(new_selection); + + // Insert the transposed characters. + editor.ReplaceSelectionWithText(new_transposed, false, false, + InputEvent::InputType::kInsertTranspose); return true; }
diff --git a/third_party/WebKit/Source/core/editing/commands/InsertListCommandTest.cpp b/third_party/WebKit/Source/core/editing/commands/InsertListCommandTest.cpp index e8a5740..79f0fad 100644 --- a/third_party/WebKit/Source/core/editing/commands/InsertListCommandTest.cpp +++ b/third_party/WebKit/Source/core/editing/commands/InsertListCommandTest.cpp
@@ -66,4 +66,30 @@ "</ul></dl>", GetSelectionTextFromBody(Selection().GetSelectionInDOMTree())); } + +// Refer https://crbug.com/798176 +TEST_F(InsertListCommandTest, CleanupNodeSameAsDestinationNode) { + GetDocument().setDesignMode("on"); + InsertStyleElement( + "* { -webkit-appearance:checkbox; }" + "br { visibility:hidden; }" + "colgroup { -webkit-column-count:2; }"); + Selection().SetSelection( + SetSelectionTextToBody("^<table><col></table>" + "<button></button>|")); + + InsertListCommand* command = InsertListCommand::Create( + GetDocument(), InsertListCommand::kUnorderedList); + + // Crash happens here. + EXPECT_FALSE(command->Apply()); + EXPECT_EQ( + "<ul><li><br></li></ul>" + "<br>" + "<table>|<colgroup><col>" + "<ul><li><br></li></ul>" + "</col></colgroup></table>" + "<button></button>", + GetSelectionTextFromBody(Selection().GetSelectionInDOMTree())); +} }
diff --git a/third_party/WebKit/Source/core/exported/WebDevToolsAgentImpl.cpp b/third_party/WebKit/Source/core/exported/WebDevToolsAgentImpl.cpp index 473bc47..baadf6b 100644 --- a/third_party/WebKit/Source/core/exported/WebDevToolsAgentImpl.cpp +++ b/third_party/WebKit/Source/core/exported/WebDevToolsAgentImpl.cpp
@@ -679,7 +679,6 @@ mojom::blink::DevToolsMessageChunkPtr chunk = mojom::blink::DevToolsMessageChunk::New(); chunk->is_first = pos == 0; - chunk->message_size = chunk->is_first ? response.length() * 2 : 0; chunk->is_last = pos + kMaxDevToolsMessageChunkSize >= response.length(); chunk->call_id = chunk->is_last ? call_id : 0; chunk->post_state =
diff --git a/third_party/WebKit/Source/core/frame/LocalDOMWindow.cpp b/third_party/WebKit/Source/core/frame/LocalDOMWindow.cpp index 642f55fb..f6a8d8e 100644 --- a/third_party/WebKit/Source/core/frame/LocalDOMWindow.cpp +++ b/third_party/WebKit/Source/core/frame/LocalDOMWindow.cpp
@@ -1110,7 +1110,7 @@ Element* element) { DCHECK(element); ComputedAccessibleNode* computed_accessible_node = - element->ComputedAccessibleNode(); + element->GetComputedAccessibleNode(); return computed_accessible_node->ComputePromiseProperty(script_state); }
diff --git a/third_party/WebKit/Source/core/frame/Location.idl b/third_party/WebKit/Source/core/frame/Location.idl index d7c9f26..c698b89c 100644 --- a/third_party/WebKit/Source/core/frame/Location.idl +++ b/third_party/WebKit/Source/core/frame/Location.idl
@@ -59,7 +59,8 @@ // mostly like the URLUtils interface, but with some members missing and // using DOMString instead of USVString. [SetterCallWith=(CurrentWindow,EnteredWindow), CrossOrigin=Setter, RaisesException=Setter] attribute URLString href; - [NotEnumerable] DOMString toString(); + // TODO(yukishiino): Use [Unforgeable] stringifier instead of toString. + DOMString toString(); [MeasureAs=LocationOrigin] readonly attribute USVString origin; [SetterCallWith=(CurrentWindow,EnteredWindow), RaisesException=Setter] attribute USVString protocol;
diff --git a/third_party/WebKit/Source/core/frame/csp/ContentSecurityPolicy.cpp b/third_party/WebKit/Source/core/frame/csp/ContentSecurityPolicy.cpp index bb3994c..fbb0abb 100644 --- a/third_party/WebKit/Source/core/frame/csp/ContentSecurityPolicy.cpp +++ b/third_party/WebKit/Source/core/frame/csp/ContentSecurityPolicy.cpp
@@ -684,9 +684,13 @@ // regardless of parser state. Once we have more data via the // 'ScriptWithCSPBypassingScheme*' metrics, make a decision about what // behavior to ship. https://crbug.com/653521 - if (parser_disposition == kNotParserInserted || - !RuntimeEnabledFeatures:: - ExperimentalContentSecurityPolicyFeaturesEnabled()) { + if ((parser_disposition == kNotParserInserted || + !RuntimeEnabledFeatures:: + ExperimentalContentSecurityPolicyFeaturesEnabled()) && + // The schemes where javascript:-URLs are blocked are usually privileged + // pages, so do not allow the CSP to be bypassed either. + !SchemeRegistry::ShouldTreatURLSchemeAsNotAllowingJavascriptURLs( + execution_context_->GetSecurityOrigin()->Protocol())) { return true; } }
diff --git a/third_party/WebKit/Source/core/frame/csp/ContentSecurityPolicyTest.cpp b/third_party/WebKit/Source/core/frame/csp/ContentSecurityPolicyTest.cpp index 72f40a320..e0c3926 100644 --- a/third_party/WebKit/Source/core/frame/csp/ContentSecurityPolicyTest.cpp +++ b/third_party/WebKit/Source/core/frame/csp/ContentSecurityPolicyTest.cpp
@@ -1176,6 +1176,52 @@ "https"); } +TEST_F(ContentSecurityPolicyTest, CSPBypassDisabledWhenSchemeIsPrivileged) { + const KURL base; + execution_context = CreateExecutionContext(); + execution_context->SetSecurityOrigin(secure_origin); + execution_context->SetURL(BlankURL()); + csp->BindToExecutionContext(execution_context.Get()); + csp->DidReceiveHeader("script-src http://example.com", + kContentSecurityPolicyHeaderTypeEnforce, + kContentSecurityPolicyHeaderSourceHTTP); + + const KURL allowed_url("http://example.com/script.js"); + const KURL http_url("http://not-example.com/script.js"); + const KURL blob_url(base, "blob:http://not-example.com/uuid"); + const KURL filesystem_url(base, "filesystem:http://not-example.com/file.js"); + + // The {Requests,Blob,Filesystem}AllowedWhenBypassingCSP tests have already + // ensured that RegisterURLSchemeAsBypassingContentSecurityPolicy works as + // expected. + // + // "http" is registered as bypassing CSP, but the context's scheme ("https") + // is marked as a privileged scheme, so the bypass rule should be ignored. + SchemeRegistry::RegisterURLSchemeAsBypassingContentSecurityPolicy("http"); + SchemeRegistry::RegisterURLSchemeAsNotAllowingJavascriptURLs("https"); + + EXPECT_TRUE(csp->AllowScriptFromSource( + allowed_url, String(), IntegrityMetadataSet(), kNotParserInserted, + ResourceRequest::RedirectStatus::kNoRedirect, + SecurityViolationReportingPolicy::kSuppressReporting)); + EXPECT_FALSE(csp->AllowScriptFromSource( + http_url, String(), IntegrityMetadataSet(), kNotParserInserted, + ResourceRequest::RedirectStatus::kNoRedirect, + SecurityViolationReportingPolicy::kSuppressReporting)); + EXPECT_FALSE(csp->AllowScriptFromSource( + blob_url, String(), IntegrityMetadataSet(), kNotParserInserted, + ResourceRequest::RedirectStatus::kNoRedirect, + SecurityViolationReportingPolicy::kSuppressReporting)); + EXPECT_FALSE(csp->AllowScriptFromSource( + filesystem_url, String(), IntegrityMetadataSet(), kNotParserInserted, + ResourceRequest::RedirectStatus::kNoRedirect, + SecurityViolationReportingPolicy::kSuppressReporting)); + + SchemeRegistry::RemoveURLSchemeRegisteredAsBypassingContentSecurityPolicy( + "http"); + SchemeRegistry::RemoveURLSchemeAsNotAllowingJavascriptURLs("https"); +} + TEST_F(ContentSecurityPolicyTest, IsValidCSPAttrTest) { // Empty string is invalid EXPECT_FALSE(ContentSecurityPolicy::IsValidCSPAttr(""));
diff --git a/third_party/WebKit/Source/core/html/HTMLAreaElement.idl b/third_party/WebKit/Source/core/html/HTMLAreaElement.idl index 59e4223428..b30b4c5 100644 --- a/third_party/WebKit/Source/core/html/HTMLAreaElement.idl +++ b/third_party/WebKit/Source/core/html/HTMLAreaElement.idl
@@ -29,7 +29,7 @@ // FIXME: ping should be a DOMTokenList. [CEReactions, Reflect] attribute USVString ping; [CEReactions, Reflect] attribute DOMString rel; - // FIXME: relList is missing + [SameObject, PutForwards=value] readonly attribute DOMTokenList relList; [CEReactions, Reflect, ReflectOnly=("","no-referrer","origin","no-referrer-when-downgrade","origin-when-cross-origin","unsafe-url"), ReflectMissing="", ReflectInvalid=""] attribute DOMString referrerPolicy; // obsolete members
diff --git a/third_party/WebKit/Source/core/html/HTMLCanvasElement.cpp b/third_party/WebKit/Source/core/html/HTMLCanvasElement.cpp index ed09115..46d50248 100644 --- a/third_party/WebKit/Source/core/html/HTMLCanvasElement.cpp +++ b/third_party/WebKit/Source/core/html/HTMLCanvasElement.cpp
@@ -94,15 +94,15 @@ namespace { // These values come from the WhatWG spec. -const int kDefaultWidth = 300; -const int kDefaultHeight = 150; +constexpr int kDefaultCanvasWidth = 300; +constexpr int kDefaultCanvasHeight = 150; #if defined(OS_ANDROID) // We estimate that the max limit for android phones is a quarter of that for // desktops based on local experimental results on Android One. -const int kMaxGlobalAcceleratedImageBufferCount = 25; +constexpr int kMaxGlobalAcceleratedImageBufferCount = 25; #else -const int kMaxGlobalAcceleratedImageBufferCount = 100; +constexpr int kMaxGlobalAcceleratedImageBufferCount = 100; #endif // We estimate the max limit of GPU allocated memory for canvases before Chrome @@ -112,13 +112,13 @@ // Each such canvas occupies 4000000 = 1000 * 500 * 2 * 4 bytes, where 2 is the // gpuBufferCount in UpdateMemoryUsage() and 4 means four bytes per pixel per // buffer. -const int kMaxGlobalGPUMemoryUsage = +constexpr int kMaxGlobalGPUMemoryUsage = 4000000 * kMaxGlobalAcceleratedImageBufferCount; // A default value of quality argument for toDataURL and toBlob // It is in an invalid range (outside 0.0 - 1.0) so that it will not be // misinterpreted as a user-input value -const int kUndefinedQualityValue = -1.0; +constexpr int kUndefinedQualityValue = -1.0; } // namespace @@ -126,7 +126,7 @@ : HTMLElement(canvasTag, document), ContextLifecycleObserver(&document), PageVisibilityObserver(document.GetPage()), - size_(kDefaultWidth, kDefaultHeight), + size_(kDefaultCanvasWidth, kDefaultCanvasHeight), ignore_reset_(false), origin_clean_(true), did_fail_to_create_buffer_(false), @@ -204,7 +204,7 @@ "Cannot resize canvas after call to transferControlToOffscreen()."); return; } - SetUnsignedIntegralAttribute(heightAttr, value, kDefaultHeight); + SetUnsignedIntegralAttribute(heightAttr, value, kDefaultCanvasHeight); } void HTMLCanvasElement::setWidth(unsigned value, @@ -215,7 +215,7 @@ "Cannot resize canvas after call to transferControlToOffscreen()."); return; } - SetUnsignedIntegralAttribute(widthAttr, value, kDefaultWidth); + SetUnsignedIntegralAttribute(widthAttr, value, kDefaultCanvasWidth); } void HTMLCanvasElement::SetSize(const IntSize& new_size) { @@ -548,13 +548,13 @@ AtomicString value = getAttribute(widthAttr); if (value.IsEmpty() || !ParseHTMLNonNegativeInteger(value, w) || w > 0x7fffffffu) - w = kDefaultWidth; + w = kDefaultCanvasWidth; unsigned h = 0; value = getAttribute(heightAttr); if (value.IsEmpty() || !ParseHTMLNonNegativeInteger(value, h) || h > 0x7fffffffu) - h = kDefaultHeight; + h = kDefaultCanvasHeight; if (Is2d()) { context_->Reset();
diff --git a/third_party/WebKit/Source/core/html/RelList.cpp b/third_party/WebKit/Source/core/html/RelList.cpp index f82234e..be265f01 100644 --- a/third_party/WebKit/Source/core/html/RelList.cpp +++ b/third_party/WebKit/Source/core/html/RelList.cpp
@@ -31,7 +31,7 @@ return tokens; } -static HashSet<AtomicString>& SupportedTokensAnchor() { +static HashSet<AtomicString>& SupportedTokensAnchorAndArea() { DEFINE_STATIC_LOCAL(HashSet<AtomicString>, tokens, ({ "noreferrer", "noopener", @@ -49,8 +49,9 @@ token_value == "modulepreload")) { return true; } - } else if (GetElement().HasTagName(aTag) && - SupportedTokensAnchor().Contains(token_value)) { + } else if ((GetElement().HasTagName(aTag) || + GetElement().HasTagName(areaTag)) && + SupportedTokensAnchorAndArea().Contains(token_value)) { return true; } return false;
diff --git a/third_party/WebKit/Source/core/html/media/HTMLAudioElement.h b/third_party/WebKit/Source/core/html/media/HTMLAudioElement.h index 1888e14e..43ebe15 100644 --- a/third_party/WebKit/Source/core/html/media/HTMLAudioElement.h +++ b/third_party/WebKit/Source/core/html/media/HTMLAudioElement.h
@@ -48,7 +48,7 @@ // WebMediaPlayerClient implementation. void MediaRemotingStarted( const WebString& remote_device_friendly_name) override {} - void MediaRemotingStopped() override {} + void MediaRemotingStopped(WebLocalizedString::Name error_msg) override {} private: HTMLAudioElement(Document&);
diff --git a/third_party/WebKit/Source/core/html/media/HTMLVideoElement.cpp b/third_party/WebKit/Source/core/html/media/HTMLVideoElement.cpp index 7679ca2..34fc776 100644 --- a/third_party/WebKit/Source/core/html/media/HTMLVideoElement.cpp +++ b/third_party/WebKit/Source/core/html/media/HTMLVideoElement.cpp
@@ -521,9 +521,10 @@ remoting_interstitial_->Show(remote_device_friendly_name); } -void HTMLVideoElement::MediaRemotingStopped() { +void HTMLVideoElement::MediaRemotingStopped( + WebLocalizedString::Name error_msg) { if (remoting_interstitial_) - remoting_interstitial_->Hide(); + remoting_interstitial_->Hide(error_msg); } WebMediaPlayer::DisplayType HTMLVideoElement::DisplayType() const {
diff --git a/third_party/WebKit/Source/core/html/media/HTMLVideoElement.h b/third_party/WebKit/Source/core/html/media/HTMLVideoElement.h index def38d5..f2fe629 100644 --- a/third_party/WebKit/Source/core/html/media/HTMLVideoElement.h +++ b/third_party/WebKit/Source/core/html/media/HTMLVideoElement.h
@@ -146,7 +146,7 @@ bool IsRemotingInterstitialVisible() const; void MediaRemotingStarted(const WebString& remote_device_friendly_name) final; - void MediaRemotingStopped() final; + void MediaRemotingStopped(WebLocalizedString::Name error_msg) final; WebMediaPlayer::DisplayType DisplayType() const final; private:
diff --git a/third_party/WebKit/Source/core/html/media/MediaRemotingInterstitial.cpp b/third_party/WebKit/Source/core/html/media/MediaRemotingInterstitial.cpp index 97c1f9b..a1db032 100644 --- a/third_party/WebKit/Source/core/html/media/MediaRemotingInterstitial.cpp +++ b/third_party/WebKit/Source/core/html/media/MediaRemotingInterstitial.cpp
@@ -15,6 +15,7 @@ constexpr double kStyleChangeTransSeconds = 0.2; constexpr double kHiddenAnimationSeconds = 0.3; +constexpr double kShowToastSeconds = 5; } // namespace @@ -23,7 +24,7 @@ MediaRemotingInterstitial::MediaRemotingInterstitial( HTMLVideoElement& videoElement) : HTMLDivElement(videoElement.GetDocument()), - toggle_insterstitial_timer_( + toggle_interstitial_timer_( videoElement.GetDocument().GetTaskRunner(TaskType::kUnthrottled), this, &MediaRemotingInterstitial::ToggleInterstitialTimerFired), @@ -44,11 +45,16 @@ cast_text_message_->SetShadowPseudoId( AtomicString("-internal-media-remoting-cast-text-message")); AppendChild(cast_text_message_); + + toast_message_ = HTMLDivElement::Create(GetDocument()); + toast_message_->SetShadowPseudoId( + AtomicString("-internal-media-remoting-toast-message")); + AppendChild(toast_message_); } void MediaRemotingInterstitial::Show( const WebString& remote_device_friendly_name) { - if (should_be_visible_) + if (IsVisible()) return; if (remote_device_friendly_name.IsEmpty()) { cast_text_message_->setInnerText( @@ -62,36 +68,70 @@ remote_device_friendly_name), ASSERT_NO_EXCEPTION); } - if (toggle_insterstitial_timer_.IsActive()) - toggle_insterstitial_timer_.Stop(); - should_be_visible_ = true; + if (toggle_interstitial_timer_.IsActive()) + toggle_interstitial_timer_.Stop(); + state_ = VISIBLE; RemoveInlineStyleProperty(CSSPropertyDisplay); - toggle_insterstitial_timer_.StartOneShot(kStyleChangeTransSeconds, FROM_HERE); -} - -void MediaRemotingInterstitial::Hide() { - if (!should_be_visible_) - return; - if (toggle_insterstitial_timer_.IsActive()) - toggle_insterstitial_timer_.Stop(); - should_be_visible_ = false; SetInlineStyleProperty(CSSPropertyOpacity, 0, CSSPrimitiveValue::UnitType::kNumber); - toggle_insterstitial_timer_.StartOneShot(kHiddenAnimationSeconds, FROM_HERE); + toggle_interstitial_timer_.StartOneShot(kStyleChangeTransSeconds, FROM_HERE); +} + +void MediaRemotingInterstitial::Hide(WebLocalizedString::Name error_msg) { + if (!IsVisible()) + return; + if (toggle_interstitial_timer_.IsActive()) + toggle_interstitial_timer_.Stop(); + if (error_msg == WebLocalizedString::kMediaRemotingStopNoText) { + state_ = HIDDEN; + } else { + String stop_text = GetVideoElement().GetLocale().QueryString( + WebLocalizedString::kMediaRemotingStopText); + if (error_msg != WebLocalizedString::kMediaRemotingStopText) { + stop_text = GetVideoElement().GetLocale().QueryString(error_msg) + ", " + + stop_text; + } + toast_message_->setInnerText(stop_text, ASSERT_NO_EXCEPTION); + state_ = TOAST; + } + SetInlineStyleProperty(CSSPropertyOpacity, 0, + CSSPrimitiveValue::UnitType::kNumber); + toggle_interstitial_timer_.StartOneShot(kHiddenAnimationSeconds, FROM_HERE); } void MediaRemotingInterstitial::ToggleInterstitialTimerFired(TimerBase*) { - toggle_insterstitial_timer_.Stop(); - if (should_be_visible_) { + toggle_interstitial_timer_.Stop(); + if (IsVisible()) { + // Show interstitial except the |toast_message_|. + background_image_->RemoveInlineStyleProperty(CSSPropertyDisplay); + cast_icon_->RemoveInlineStyleProperty(CSSPropertyDisplay); + cast_text_message_->RemoveInlineStyleProperty(CSSPropertyDisplay); + toast_message_->SetInlineStyleProperty(CSSPropertyDisplay, CSSValueNone); + SetInlineStyleProperty(CSSPropertyBackgroundColor, CSSValueBlack); SetInlineStyleProperty(CSSPropertyOpacity, 1, CSSPrimitiveValue::UnitType::kNumber); - } else { + } else if (state_ == HIDDEN) { SetInlineStyleProperty(CSSPropertyDisplay, CSSValueNone); + toast_message_->setInnerText(WebString(), ASSERT_NO_EXCEPTION); + } else { + // Show |toast_message_| only. + toast_message_->RemoveInlineStyleProperty(CSSPropertyDisplay); + SetInlineStyleProperty(CSSPropertyBackgroundColor, CSSValueTransparent); + SetInlineStyleProperty(CSSPropertyOpacity, 1, + CSSPrimitiveValue::UnitType::kNumber); + background_image_->SetInlineStyleProperty(CSSPropertyDisplay, CSSValueNone); + cast_icon_->SetInlineStyleProperty(CSSPropertyDisplay, CSSValueNone); + cast_text_message_->SetInlineStyleProperty(CSSPropertyDisplay, + CSSValueNone); + toast_message_->SetInlineStyleProperty( + CSSPropertyOpacity, 1, CSSPrimitiveValue::UnitType::kNumber); + state_ = HIDDEN; + toggle_interstitial_timer_.StartOneShot(kShowToastSeconds, FROM_HERE); } } void MediaRemotingInterstitial::DidMoveToNewDocument(Document& old_document) { - toggle_insterstitial_timer_.MoveToNewTaskRunner( + toggle_interstitial_timer_.MoveToNewTaskRunner( GetDocument().GetTaskRunner(TaskType::kUnthrottled)); HTMLDivElement::DidMoveToNewDocument(old_document); @@ -107,6 +147,7 @@ visitor->Trace(background_image_); visitor->Trace(cast_icon_); visitor->Trace(cast_text_message_); + visitor->Trace(toast_message_); HTMLDivElement::Trace(visitor); }
diff --git a/third_party/WebKit/Source/core/html/media/MediaRemotingInterstitial.h b/third_party/WebKit/Source/core/html/media/MediaRemotingInterstitial.h index 65c40e3..0df621b 100644 --- a/third_party/WebKit/Source/core/html/media/MediaRemotingInterstitial.h +++ b/third_party/WebKit/Source/core/html/media/MediaRemotingInterstitial.h
@@ -8,6 +8,7 @@ #include "core/html/HTMLDivElement.h" #include "platform/Timer.h" #include "platform/WebTaskRunner.h" +#include "public/platform/WebLocalizedString.h" namespace blink { @@ -23,22 +24,27 @@ // \-HTMLDivElement // | (-internal-media-remoting-cast-icon) // \-HTMLDivElement -// (-internal-media-remoting-cast-text-message) +// | (-internal-media-remoting-cast-text-message) +// |-HTMLDivElement +// (-internal-media-remoting-toast-message) class MediaRemotingInterstitial final : public HTMLDivElement { public: explicit MediaRemotingInterstitial(HTMLVideoElement&); - // Show/Hide Media Remoting interstitial. |remote_device_friendly_name| will - // be shown in the UI to indicate which device the content is rendered on. An + // Show Media Remoting interstitial. |remote_device_friendly_name| will be + // shown in the UI to indicate which device the content is rendered on. An // empty name indicates an unknown remote device. A default message will be // shown in this case. void Show(const WebString& remote_device_friendly_name); - void Hide(); + + // Hide Media Remoting interstitial. A text message may be displayed for five + // seconds according to |error_msg|. + void Hide(WebLocalizedString::Name error_msg); void OnPosterImageChanged(); // Query for whether the remoting interstitial is visible. - bool IsVisible() const { return should_be_visible_; } + bool IsVisible() const { return state_ == VISIBLE; } HTMLVideoElement& GetVideoElement() const { return *video_element_; } @@ -53,13 +59,19 @@ // Indicates whether the interstitial should be visible. It is set/changed // when Show()/Hide() is called. - bool should_be_visible_ = false; + enum State { + HIDDEN, // The interstitial is currently not showing. + VISIBLE, // The interstitial is currently visible except the toast. + TOAST, // Only the toast is visible. + }; + State state_ = HIDDEN; - TaskRunnerTimer<MediaRemotingInterstitial> toggle_insterstitial_timer_; + TaskRunnerTimer<MediaRemotingInterstitial> toggle_interstitial_timer_; Member<HTMLVideoElement> video_element_; Member<HTMLImageElement> background_image_; Member<HTMLDivElement> cast_icon_; Member<HTMLDivElement> cast_text_message_; + Member<HTMLDivElement> toast_message_; }; } // namespace blink
diff --git a/third_party/WebKit/Source/core/html/track/vtt/VTTRegion.cpp b/third_party/WebKit/Source/core/html/track/vtt/VTTRegion.cpp index 5aad17b..77ab90ed 100644 --- a/third_party/WebKit/Source/core/html/track/vtt/VTTRegion.cpp +++ b/third_party/WebKit/Source/core/html/track/vtt/VTTRegion.cpp
@@ -46,32 +46,33 @@ namespace blink { +namespace { // The following values default values are defined within the WebVTT Regions // Spec. // https://dvcs.w3.org/hg/text-tracks/raw-file/default/608toVTT/region.html // The region occupies by default 100% of the width of the video viewport. -static const double kDefaultWidth = 100; +constexpr double kDefaultRegionWidth = 100; // The region has, by default, 3 lines of text. -static const int kDefaultHeightInLines = 3; +constexpr int kDefaultHeightInLines = 3; // The region and viewport are anchored in the bottom left corner. -static const double kDefaultAnchorPointX = 0; -static const double kDefaultAnchorPointY = 100; +constexpr double kDefaultAnchorPointX = 0; +constexpr double kDefaultAnchorPointY = 100; // The region doesn't have scrolling text, by default. -static const bool kDefaultScroll = false; +constexpr bool kDefaultScroll = false; // Default region line-height (vh units) -static const float kLineHeight = 5.33; +constexpr float kLineHeight = 5.33; // Default scrolling animation time period (s). -static const float kScrollTime = 0.433; +constexpr float kScrollTime = 0.433; -static bool IsNonPercentage(double value, - const char* method, - ExceptionState& exception_state) { +bool IsNonPercentage(double value, + const char* method, + ExceptionState& exception_state) { if (value < 0 || value > 100) { exception_state.ThrowDOMException( kIndexSizeError, @@ -83,9 +84,11 @@ return false; } +} // namespace + VTTRegion::VTTRegion() : id_(g_empty_string), - width_(kDefaultWidth), + width_(kDefaultRegionWidth), lines_(kDefaultHeightInLines), region_anchor_(DoublePoint(kDefaultAnchorPointX, kDefaultAnchorPointY)), viewport_anchor_(DoublePoint(kDefaultAnchorPointX, kDefaultAnchorPointY)),
diff --git a/third_party/WebKit/Source/core/inspector/InspectorEmulationAgent.cpp b/third_party/WebKit/Source/core/inspector/InspectorEmulationAgent.cpp index ed6d6dc..224f875 100644 --- a/third_party/WebKit/Source/core/inspector/InspectorEmulationAgent.cpp +++ b/third_party/WebKit/Source/core/inspector/InspectorEmulationAgent.cpp
@@ -37,8 +37,7 @@ InspectorEmulationAgent::InspectorEmulationAgent( WebLocalFrameImpl* web_local_frame_impl) - : web_local_frame_(web_local_frame_impl), - virtual_time_observer_registered_(false) {} + : web_local_frame_(web_local_frame_impl) {} InspectorEmulationAgent::~InspectorEmulationAgent() {} @@ -78,9 +77,10 @@ setEmulatedMedia(String()); setCPUThrottlingRate(1); setDefaultBackgroundColorOverride(Maybe<protocol::DOM::RGBA>()); - if (virtual_time_observer_registered_) { + if (virtual_time_setup_) { + instrumenting_agents_->removeInspectorEmulationAgent(this); web_local_frame_->View()->Scheduler()->RemoveVirtualTimeObserver(this); - virtual_time_observer_registered_ = false; + virtual_time_setup_ = false; } setNavigatorOverrides(String()); return Response::OK(); @@ -131,43 +131,72 @@ Response InspectorEmulationAgent::setVirtualTimePolicy( const String& policy, - Maybe<double> budget, + Maybe<double> virtual_time_budget_ms, protocol::Maybe<int> max_virtual_time_task_starvation_count, + protocol::Maybe<bool> wait_for_navigation, double* virtual_time_base_ms) { + PendingVirtualTimePolicy new_policy; + new_policy.policy = WebViewScheduler::VirtualTimePolicy::kPause; if (protocol::Emulation::VirtualTimePolicyEnum::Advance == policy) { - web_local_frame_->View()->Scheduler()->SetVirtualTimePolicy( - WebViewScheduler::VirtualTimePolicy::kAdvance); - } else if (protocol::Emulation::VirtualTimePolicyEnum::Pause == policy) { - web_local_frame_->View()->Scheduler()->SetVirtualTimePolicy( - WebViewScheduler::VirtualTimePolicy::kPause); + new_policy.policy = WebViewScheduler::VirtualTimePolicy::kAdvance; } else if (protocol::Emulation::VirtualTimePolicyEnum:: PauseIfNetworkFetchesPending == policy) { - web_local_frame_->View()->Scheduler()->SetVirtualTimePolicy( - WebViewScheduler::VirtualTimePolicy::kDeterministicLoading); - } - WTF::TimeTicks virtual_time_base_ticks( - web_local_frame_->View()->Scheduler()->EnableVirtualTime()); - WTF::TimeDelta virtual_time_base_delta = - virtual_time_base_ticks - WTF::TimeTicks::UnixEpoch(); - *virtual_time_base_ms = virtual_time_base_delta.InMillisecondsF(); - if (!virtual_time_observer_registered_) { - web_local_frame_->View()->Scheduler()->AddVirtualTimeObserver(this); - virtual_time_observer_registered_ = true; + new_policy.policy = + WebViewScheduler::VirtualTimePolicy::kDeterministicLoading; } - if (budget.isJust()) { + if (virtual_time_budget_ms.isJust()) + new_policy.virtual_time_budget_ms = virtual_time_budget_ms.fromJust(); + + if (max_virtual_time_task_starvation_count.isJust()) { + new_policy.max_virtual_time_task_starvation_count = + max_virtual_time_task_starvation_count.fromJust(); + } + + if (wait_for_navigation.fromMaybe(false)) { + *virtual_time_base_ms = 0; + pending_virtual_time_policy_ = std::move(new_policy); + return Response::OK(); + } + + WTF::TimeDelta virtual_time_base_delta = + ApplyVirtualTimePolicy(new_policy) - WTF::TimeTicks::UnixEpoch(); + *virtual_time_base_ms = virtual_time_base_delta.InMillisecondsF(); + + return Response::OK(); +} + +WTF::TimeTicks InspectorEmulationAgent::ApplyVirtualTimePolicy( + const PendingVirtualTimePolicy& new_policy) { + web_local_frame_->View()->Scheduler()->SetVirtualTimePolicy( + new_policy.policy); + WTF::TimeTicks virtual_time_base_ticks( + web_local_frame_->View()->Scheduler()->EnableVirtualTime()); + if (!virtual_time_setup_) { + instrumenting_agents_->addInspectorEmulationAgent(this); + web_local_frame_->View()->Scheduler()->AddVirtualTimeObserver(this); + virtual_time_setup_ = true; + } + if (new_policy.virtual_time_budget_ms) { WTF::TimeDelta budget_amount = - WTF::TimeDelta::FromMillisecondsD(budget.fromJust()); + WTF::TimeDelta::FromMillisecondsD(*new_policy.virtual_time_budget_ms); web_local_frame_->View()->Scheduler()->GrantVirtualTimeBudget( budget_amount, WTF::Bind(&InspectorEmulationAgent::VirtualTimeBudgetExpired, WrapWeakPersistent(this))); } - if (max_virtual_time_task_starvation_count.isJust()) { + if (new_policy.max_virtual_time_task_starvation_count) { web_local_frame_->View()->Scheduler()->SetMaxVirtualTimeTaskStarvationCount( - max_virtual_time_task_starvation_count.fromJust()); + *new_policy.max_virtual_time_task_starvation_count); } - return Response::OK(); + return virtual_time_base_ticks; +} + +void InspectorEmulationAgent::FrameStartedLoading(LocalFrame*, FrameLoadType) { + if (pending_virtual_time_policy_) { + ApplyVirtualTimePolicy(*pending_virtual_time_policy_); + pending_virtual_time_policy_ = WTF::nullopt; + } } Response InspectorEmulationAgent::setNavigatorOverrides(
diff --git a/third_party/WebKit/Source/core/inspector/InspectorEmulationAgent.h b/third_party/WebKit/Source/core/inspector/InspectorEmulationAgent.h index 87042bf..34faf99 100644 --- a/third_party/WebKit/Source/core/inspector/InspectorEmulationAgent.h +++ b/third_party/WebKit/Source/core/inspector/InspectorEmulationAgent.h
@@ -9,7 +9,9 @@ #include "core/CoreExport.h" #include "core/inspector/InspectorBaseAgent.h" #include "core/inspector/protocol/Emulation.h" +#include "core/loader/FrameLoaderTypes.h" #include "platform/scheduler/renderer/web_view_scheduler.h" +#include "platform/wtf/Optional.h" #include "platform/wtf/Time.h" namespace blink { @@ -43,6 +45,7 @@ const String& policy, protocol::Maybe<double> virtual_time_budget_ms, protocol::Maybe<int> max_virtual_time_task_starvation_count, + protocol::Maybe<bool> wait_for_navigation, double* virtual_time_base_ms) override; protocol::Response setNavigatorOverrides(const String& platform) override; protocol::Response setDefaultBackgroundColorOverride( @@ -62,6 +65,9 @@ protocol::Maybe<protocol::Page::Viewport>) override; protocol::Response clearDeviceMetricsOverride() override; + // InspectorInstrumentation API + void FrameStartedLoading(LocalFrame*, FrameLoadType); + // InspectorBaseAgent overrides. protocol::Response disable() override; void Restore() override; @@ -76,8 +82,20 @@ WebViewImpl* GetWebViewImpl(); void VirtualTimeBudgetExpired(); + struct PendingVirtualTimePolicy { + WebViewScheduler::VirtualTimePolicy policy; + WTF::Optional<double> virtual_time_budget_ms; + WTF::Optional<int> max_virtual_time_task_starvation_count; + }; + WTF::TimeTicks ApplyVirtualTimePolicy( + const PendingVirtualTimePolicy& new_policy); + Member<WebLocalFrameImpl> web_local_frame_; - bool virtual_time_observer_registered_; + bool virtual_time_setup_ = false; + + // Supports a virtual time policy change scheduled to occur after any + // navigation has started. + WTF::Optional<PendingVirtualTimePolicy> pending_virtual_time_policy_; DISALLOW_COPY_AND_ASSIGN(InspectorEmulationAgent); };
diff --git a/third_party/WebKit/Source/core/inspector/browser_protocol.json b/third_party/WebKit/Source/core/inspector/browser_protocol.json index bcc20615..0cf1d72 100644 --- a/third_party/WebKit/Source/core/inspector/browser_protocol.json +++ b/third_party/WebKit/Source/core/inspector/browser_protocol.json
@@ -4998,6 +4998,12 @@ "description": "If set this specifies the maximum number of tasks that can be run before virtual is forced\nforwards to prevent deadlock.", "optional": true, "type": "integer" + }, + { + "name": "waitForNavigation", + "description": "If set the virtual time policy change should be deferred until any frame starts navigating.\nNote any previous deferred policy change is superseded.", + "optional": true, + "type": "boolean" } ], "returns": [
diff --git a/third_party/WebKit/Source/core/inspector/browser_protocol.pdl b/third_party/WebKit/Source/core/inspector/browser_protocol.pdl index fbde1ca..c04abd6 100644 --- a/third_party/WebKit/Source/core/inspector/browser_protocol.pdl +++ b/third_party/WebKit/Source/core/inspector/browser_protocol.pdl
@@ -2277,6 +2277,9 @@ # If set this specifies the maximum number of tasks that can be run before virtual is forced # forwards to prevent deadlock. optional integer maxVirtualTimeTaskStarvationCount + # If set the virtual time policy change should be deferred until any frame starts navigating. + # Note any previous deferred policy change is superseded. + optional boolean waitForNavigation returns # Absolute timestamp at which virtual time was first enabled (milliseconds since epoch). Runtime.Timestamp virtualTimeBase
diff --git a/third_party/WebKit/Source/core/layout/LayoutBoxModelObject.cpp b/third_party/WebKit/Source/core/layout/LayoutBoxModelObject.cpp index 406b1f6..6a9162d 100644 --- a/third_party/WebKit/Source/core/layout/LayoutBoxModelObject.cpp +++ b/third_party/WebKit/Source/core/layout/LayoutBoxModelObject.cpp
@@ -347,8 +347,8 @@ // gets the same layout after changing position property, although no // re-raster (rect-based invalidation) is needed, display items should // still update their paint offset. - // For SPv2, invalidation for paint offset change is done during PrePaint. - if (old_style && !RuntimeEnabledFeatures::SlimmingPaintV2Enabled()) { + // For SPv175, invalidation for paint offset change is done during PrePaint. + if (old_style && !RuntimeEnabledFeatures::SlimmingPaintV175Enabled()) { bool new_style_is_fixed_position = Style()->GetPosition() == EPosition::kFixed; bool old_style_is_fixed_position =
diff --git a/third_party/WebKit/Source/core/layout/LayoutInline.h b/third_party/WebKit/Source/core/layout/LayoutInline.h index 23f82e2..fcd69038 100644 --- a/third_party/WebKit/Source/core/layout/LayoutInline.h +++ b/third_party/WebKit/Source/core/layout/LayoutInline.h
@@ -330,6 +330,7 @@ void AddAnnotatedRegions(Vector<AnnotatedRegionValue>&) final; void UpdateFromStyle() final; + bool AnonymousHasStylePropagationOverride() final { return true; } LayoutInline* Clone() const;
diff --git a/third_party/WebKit/Source/core/layout/ng/inline/ng_inline_items_builder.cc b/third_party/WebKit/Source/core/layout/ng/inline/ng_inline_items_builder.cc index 7b20850..09b3037 100644 --- a/third_party/WebKit/Source/core/layout/ng/inline/ng_inline_items_builder.cc +++ b/third_party/WebKit/Source/core/layout/ng/inline/ng_inline_items_builder.cc
@@ -178,7 +178,6 @@ if (last_collapsible_space_ == CollapsibleSpace::kSpaceNoWrap && IsCollapsibleSpace(string[start]) && style->AutoWrap()) { AppendBreakOpportunity(style, layout_object); - mapping_builder_.AppendIdentityMapping(1); start++; last_collapsible_space_ = CollapsibleSpace::kSpace; }
diff --git a/third_party/WebKit/Source/core/layout/ng/inline/ng_inline_node.cc b/third_party/WebKit/Source/core/layout/ng/inline/ng_inline_node.cc index 7474ae9..07ffe60 100644 --- a/third_party/WebKit/Source/core/layout/ng/inline/ng_inline_node.cc +++ b/third_party/WebKit/Source/core/layout/ng/inline/ng_inline_node.cc
@@ -497,6 +497,15 @@ DCHECK_EQ(data, MutableData()); block_flow->ClearNeedsCollectInlines(); + +#if DCHECK_IS_ON() + // ComputeOffsetMappingIfNeeded() runs some integrity checks as part of + // creating offset mapping. Run the check, and discard the result. + DCHECK(!data->offset_mapping_); + ComputeOffsetMappingIfNeeded(); + DCHECK(data->offset_mapping_); + data->offset_mapping_.reset(); +#endif } const NGInlineNodeData& NGInlineNode::EnsureData() { @@ -605,18 +614,67 @@ // Shape each item with the full context of the entire node. HarfBuzzShaper shaper(text_content.Characters16(), text_content.length()); ShapeResultSpacing<String> spacing(text_content); - for (auto& item : *items) { - if (item.Type() != NGInlineItem::kText) + for (unsigned index = 0; index < items->size();) { + NGInlineItem& start_item = (*items)[index]; + if (start_item.Type() != NGInlineItem::kText) { + index++; continue; + } - const Font& font = item.Style()->GetFont(); - scoped_refptr<ShapeResult> shape_result = shaper.Shape( - &font, item.Direction(), item.StartOffset(), item.EndOffset()); + const Font& font = start_item.Style()->GetFont(); + TextDirection direction = start_item.Direction(); + unsigned end_index = index + 1; + unsigned end_offset = start_item.EndOffset(); + for (; end_index < items->size(); end_index++) { + const NGInlineItem& item = (*items)[end_index]; + if (item.Type() == NGInlineItem::kText) { + // Shape adjacent items together if the font and direction matches to + // allow ligatures and kerning to apply. + // TODO(kojii): Figure out the exact conditions under which this + // behavior is desirable. + if (font != item.Style()->GetFont() || direction != item.Direction()) + break; + end_offset = item.EndOffset(); + } else if (item.Type() == NGInlineItem::kOpenTag || + item.Type() == NGInlineItem::kCloseTag || + item.Type() == NGInlineItem::kOutOfFlowPositioned) { + // These items are opaque to shaping. + // Opaque items cannot have text, such as Object Replacement Characters, + // since such characters can affect shaping. + DCHECK_EQ(0u, item.Length()); + } else { + break; + } + } + scoped_refptr<ShapeResult> shape_result = + shaper.Shape(&font, direction, start_item.StartOffset(), end_offset); if (UNLIKELY(spacing.SetSpacing(font.GetFontDescription()))) shape_result->ApplySpacing(spacing); - item.shape_result_ = std::move(shape_result); + // If the text is from one item, use the ShapeResult as is. + if (end_offset == start_item.EndOffset()) { + start_item.shape_result_ = std::move(shape_result); + index++; + continue; + } + + // If the text is from multiple items, split the ShapeResult to + // corresponding items. + for (; index < end_index; index++) { + NGInlineItem& item = (*items)[index]; + if (item.Type() != NGInlineItem::kText) + continue; + + // We don't use SafeToBreak API here because this is not a line break. + // The ShapeResult is broken into multiple results, but they must look + // like they were not broken. + // + // When multiple code units shape to one glyph, such as ligatures, the + // item that has its first code unit keeps the glyph. + item.shape_result_ = + shape_result->SubRange(item.StartOffset(), item.EndOffset()); + } } }
diff --git a/third_party/WebKit/Source/core/paint/PaintPropertyTreeBuilder.cpp b/third_party/WebKit/Source/core/paint/PaintPropertyTreeBuilder.cpp index 2a032bf..c91e55df 100644 --- a/third_party/WebKit/Source/core/paint/PaintPropertyTreeBuilder.cpp +++ b/third_party/WebKit/Source/core/paint/PaintPropertyTreeBuilder.cpp
@@ -972,7 +972,7 @@ static bool NeedsInnerBorderRadiusClip(const LayoutObject& object) { if (!object.StyleRef().HasBorderRadius()) return false; - if (NeedsOverflowClip(object)) + if (object.IsBox() && NeedsOverflowClip(object)) return true; // LayoutReplaced applies inner border-radius clip on the foreground. This // doesn't apply to SVGRoot which uses the NeedsOverflowClip() rule above.
diff --git a/third_party/WebKit/Source/core/paint/PaintPropertyTreeBuilderTest.cpp b/third_party/WebKit/Source/core/paint/PaintPropertyTreeBuilderTest.cpp index 6b79140..a2351c7 100644 --- a/third_party/WebKit/Source/core/paint/PaintPropertyTreeBuilderTest.cpp +++ b/third_party/WebKit/Source/core/paint/PaintPropertyTreeBuilderTest.cpp
@@ -1191,6 +1191,8 @@ TEST_P(PaintPropertyTreeBuilderTest, SVGViewportContainer) { SetBodyInnerHTML(R"HTML( + <!-- border radius of inner svg elemnents should be ignored. --> + <style>svg { border-radius: 10px }</style> <svg id='svg'> <svg id='container1' width='30' height='30'></svg> <svg id='container2'
diff --git a/third_party/WebKit/Source/core/paint/SVGFilterPainter.cpp b/third_party/WebKit/Source/core/paint/SVGFilterPainter.cpp index e1e4e33..650eec8 100644 --- a/third_party/WebKit/Source/core/paint/SVGFilterPainter.cpp +++ b/third_party/WebKit/Source/core/paint/SVGFilterPainter.cpp
@@ -21,11 +21,12 @@ paint_controller_ = PaintController::Create(); context_ = WTF::WrapUnique(new GraphicsContext(*paint_controller_)); - // Content painted into a new PaintRecord in SPv2 will have an - // independent property tree set. if (RuntimeEnabledFeatures::SlimmingPaintV175Enabled()) { + // Use initial_context_'s current paint chunk properties so that any new + // chunk created during painting the content will be in the correct state. paint_controller_->UpdateCurrentPaintChunkProperties( - WTF::nullopt, PropertyTreeState::Root()); + WTF::nullopt, + initial_context_.GetPaintController().CurrentPaintChunkProperties()); } return context_.get(); } @@ -38,8 +39,10 @@ context_->BeginRecording(bounds); paint_controller_->CommitNewDisplayItems(); - paint_controller_->GetPaintArtifact().Replay(*context_, - PropertyTreeState::Root()); + paint_controller_->GetPaintArtifact().Replay( + *context_, initial_context_.GetPaintController() + .CurrentPaintChunkProperties() + .property_tree_state); 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/probe/CoreProbes.json5 b/third_party/WebKit/Source/core/probe/CoreProbes.json5 index 136dcbf..9e3cc43 100644 --- a/third_party/WebKit/Source/core/probe/CoreProbes.json5 +++ b/third_party/WebKit/Source/core/probe/CoreProbes.json5
@@ -70,6 +70,11 @@ "willSendXMLHttpOrFetchNetworkRequest", ] }, + Emulation: { + probes: [ + "frameStartedLoading", + ] + }, LayerTree: { probes: [ "didPaint",
diff --git a/third_party/WebKit/Source/devtools/front_end/application_test_runner/ServiceWorkersTestRunner.js b/third_party/WebKit/Source/devtools/front_end/application_test_runner/ServiceWorkersTestRunner.js index 21fdfeb..98e96c11d 100644 --- a/third_party/WebKit/Source/devtools/front_end/application_test_runner/ServiceWorkersTestRunner.js +++ b/third_party/WebKit/Source/devtools/front_end/application_test_runner/ServiceWorkersTestRunner.js
@@ -68,7 +68,12 @@ function registerServiceWorker(script, scope) { return navigator.serviceWorker.register(script, { scope: scope - }).then(reg => registrations[scope] = reg); + }) + .then(reg => registrations[scope] = reg) + .catch(err => { + return Promise.reject(new Error('Service Worker registration error: ' + + err.toString())); + }); } function waitForActivated(scope) {
diff --git a/third_party/WebKit/Source/devtools/front_end/host/UserMetrics.js b/third_party/WebKit/Source/devtools/front_end/host/UserMetrics.js index 872053b0..336bc67 100644 --- a/third_party/WebKit/Source/devtools/front_end/host/UserMetrics.js +++ b/third_party/WebKit/Source/devtools/front_end/host/UserMetrics.js
@@ -106,7 +106,7 @@ audits: 7, console: 8, layers: 9, - 'drawer-console': 10, + 'drawer-console-view': 10, 'drawer-animations': 11, 'drawer-network.config': 12, 'drawer-rendering': 13,
diff --git a/third_party/WebKit/Source/devtools/front_end/network/NetworkDataGridNode.js b/third_party/WebKit/Source/devtools/front_end/network/NetworkDataGridNode.js index ee3be8c55..dbbb00f 100644 --- a/third_party/WebKit/Source/devtools/front_end/network/NetworkDataGridNode.js +++ b/third_party/WebKit/Source/devtools/front_end/network/NetworkDataGridNode.js
@@ -410,35 +410,11 @@ var bRequest = b.requestOrFirstKnownChildRequest(); if (!aRequest || !bRequest) return !aRequest ? -1 : 1; - var aInitiator = NetworkLog.networkLog.initiatorInfoForRequest(aRequest); - var bInitiator = NetworkLog.networkLog.initiatorInfoForRequest(bRequest); - - if (aInitiator.type < bInitiator.type) - return -1; - if (aInitiator.type > bInitiator.type) - return 1; - - if (typeof aInitiator.__source === 'undefined') - aInitiator.__source = Bindings.displayNameForURL(aInitiator.url); - if (typeof bInitiator.__source === 'undefined') - bInitiator.__source = Bindings.displayNameForURL(bInitiator.url); - - if (aInitiator.__source < bInitiator.__source) - return -1; - if (aInitiator.__source > bInitiator.__source) - return 1; - - if (aInitiator.lineNumber < bInitiator.lineNumber) - return -1; - if (aInitiator.lineNumber > bInitiator.lineNumber) - return 1; - - if (aInitiator.columnNumber < bInitiator.columnNumber) - return -1; - if (aInitiator.columnNumber > bInitiator.columnNumber) - return 1; - - return aRequest.indentityCompare(bRequest); + if (!a._initiatorCell || !b._initiatorCell) + return !a._initiatorCell ? -1 : 1; + var aText = a._linkifiedInitiatorAnchor ? a._linkifiedInitiatorAnchor.textContent : a._initiatorCell.title; + var bText = b._linkifiedInitiatorAnchor ? b._linkifiedInitiatorAnchor.textContent : b._initiatorCell.title; + return aText.localeCompare(bText); } /** @@ -948,9 +924,14 @@ case SDK.NetworkRequest.InitiatorType.Script: var networkManager = SDK.NetworkManager.forRequest(request); - this._linkifiedInitiatorAnchor = this.parentView().linkifier.linkifyScriptLocation( - networkManager ? networkManager.target() : null, initiator.scriptId, initiator.url, initiator.lineNumber, - initiator.columnNumber); + if (initiator.stack) { + this._linkifiedInitiatorAnchor = this.parentView().linkifier.linkifyStackTraceTopFrame( + networkManager ? networkManager.target() : null, initiator.stack); + } else { + this._linkifiedInitiatorAnchor = this.parentView().linkifier.linkifyScriptLocation( + networkManager ? networkManager.target() : null, initiator.scriptId, initiator.url, initiator.lineNumber, + initiator.columnNumber); + } this._linkifiedInitiatorAnchor.title = ''; cell.appendChild(this._linkifiedInitiatorAnchor); this._appendSubtitle(cell, Common.UIString('Script'));
diff --git a/third_party/WebKit/Source/devtools/front_end/network_log/NetworkLog.js b/third_party/WebKit/Source/devtools/front_end/network_log/NetworkLog.js index ad8e4872..ed81beb 100644 --- a/third_party/WebKit/Source/devtools/front_end/network_log/NetworkLog.js +++ b/third_party/WebKit/Source/devtools/front_end/network_log/NetworkLog.js
@@ -174,6 +174,7 @@ var lineNumber = -Infinity; var columnNumber = -Infinity; var scriptId = null; + var initiatorStack = null; var initiator = request.initiator(); var redirectSource = request.redirectSource(); @@ -202,13 +203,21 @@ url = initiator.url; lineNumber = initiator.lineNumber || 0; } + if (initiator.stack && initiator.stack.callFrames && initiator.stack.callFrames.length) + initiatorStack = initiator.stack || null; } else if (initiator.type === Protocol.Network.InitiatorType.Preload) { type = SDK.NetworkRequest.InitiatorType.Preload; } } - request[NetworkLog.NetworkLog._initiatorDataSymbol].info = - {type: type, url: url, lineNumber: lineNumber, columnNumber: columnNumber, scriptId: scriptId}; + request[NetworkLog.NetworkLog._initiatorDataSymbol].info = { + type: type, + url: url, + lineNumber: lineNumber, + columnNumber: columnNumber, + scriptId: scriptId, + stack: initiatorStack + }; return request[NetworkLog.NetworkLog._initiatorDataSymbol].info; } @@ -473,7 +482,7 @@ RequestUpdated: Symbol('RequestUpdated') }; -/** @typedef {!{type: !SDK.NetworkRequest.InitiatorType, url: string, lineNumber: number, columnNumber: number, scriptId: ?string}} */ +/** @typedef {!{type: !SDK.NetworkRequest.InitiatorType, url: string, lineNumber: number, columnNumber: number, scriptId: ?string, stack: ?Protocol.Runtime.StackTrace}} */ NetworkLog.NetworkLog._InitiatorInfo; NetworkLog.NetworkLog._initiatorDataSymbol = Symbol('InitiatorData');
diff --git a/third_party/WebKit/Source/devtools/front_end/sources/NavigatorView.js b/third_party/WebKit/Source/devtools/front_end/sources/NavigatorView.js index a7a8d90..a2e519a2 100644 --- a/third_party/WebKit/Source/devtools/front_end/sources/NavigatorView.js +++ b/third_party/WebKit/Source/devtools/front_end/sources/NavigatorView.js
@@ -743,7 +743,7 @@ /** * @param {!Event} event - * @param {!Sources.NavigatorFolderTreeNode} node + * @param {!Sources.NavigatorTreeNode} node */ handleFolderContextMenu(event, node) { var path = node._folderPath || '';
diff --git a/third_party/WebKit/Source/devtools/front_end/ui/InspectorView.js b/third_party/WebKit/Source/devtools/front_end/ui/InspectorView.js index 9f0a6ad..b2b79d69 100644 --- a/third_party/WebKit/Source/devtools/front_end/ui/InspectorView.js +++ b/third_party/WebKit/Source/devtools/front_end/ui/InspectorView.js
@@ -55,6 +55,7 @@ this._drawerTabbedPane.rightToolbar().appendToolbarItem(closeDrawerButton); this._drawerSplitWidget.installResizer(this._drawerTabbedPane.headerElement()); this._drawerSplitWidget.setSidebarWidget(this._drawerTabbedPane); + this._drawerTabbedPane.addEventListener(UI.TabbedPane.Events.TabSelected, this._drawerTabSelected, this); // Create main area tabbed pane. this._tabbedLocation = UI.viewManager.createTabbedLocation( @@ -304,6 +305,14 @@ } /** + * @param {!Common.Event} event + */ + _drawerTabSelected(event) { + var tabId = /** @type {string} */ (event.data['tabId']); + Host.userMetrics.drawerShown(tabId); + } + + /** * @param {!UI.SplitWidget} splitWidget */ setOwnerSplit(splitWidget) {
diff --git a/third_party/WebKit/Source/devtools/front_end/ui/View.js b/third_party/WebKit/Source/devtools/front_end/ui/View.js index 04842c4..987367be 100644 --- a/third_party/WebKit/Source/devtools/front_end/ui/View.js +++ b/third_party/WebKit/Source/devtools/front_end/ui/View.js
@@ -357,8 +357,6 @@ } var locationName = this._locationNameByViewId.get(viewId); - if (locationName === 'drawer-view') - Host.userMetrics.drawerShown(viewId); var location = view[UI.ViewManager._Location.symbol]; if (location) {
diff --git a/third_party/WebKit/Source/modules/keyboard_lock/NavigatorKeyboardLock.cpp b/third_party/WebKit/Source/modules/keyboard_lock/NavigatorKeyboardLock.cpp index 312fde1..76a603c 100644 --- a/third_party/WebKit/Source/modules/keyboard_lock/NavigatorKeyboardLock.cpp +++ b/third_party/WebKit/Source/modules/keyboard_lock/NavigatorKeyboardLock.cpp
@@ -29,15 +29,14 @@ } // static -ScriptPromise NavigatorKeyboardLock::requestKeyboardLock( +ScriptPromise NavigatorKeyboardLock::keyboardLock( ScriptState* state, Navigator& navigator, const Vector<String>& keycodes) { - return NavigatorKeyboardLock::From(navigator).requestKeyboardLock( - state, keycodes); + return NavigatorKeyboardLock::From(navigator).keyboardLock(state, keycodes); } -ScriptPromise NavigatorKeyboardLock::requestKeyboardLock( +ScriptPromise NavigatorKeyboardLock::keyboardLock( ScriptState* state, const Vector<String>& keycodes) { DCHECK(state); @@ -46,7 +45,7 @@ // spec. See https://github.com/w3c/keyboard-lock/issues/18. return ScriptPromise::Reject( state, V8String(state->GetIsolate(), - "Last requestKeyboardLock() has not finished yet.")); + "Last keyboardLock() has not finished yet.")); } if (!EnsureServiceConnected()) { @@ -61,7 +60,7 @@ return request_keylock_resolver_->Promise(); } -void NavigatorKeyboardLock::cancelKeyboardLock() { +void NavigatorKeyboardLock::keyboardUnlock() { if (!EnsureServiceConnected()) { // Current frame is detached. return; @@ -71,8 +70,8 @@ } // static -void NavigatorKeyboardLock::cancelKeyboardLock(Navigator& navigator) { - NavigatorKeyboardLock::From(navigator).cancelKeyboardLock(); +void NavigatorKeyboardLock::keyboardUnlock(Navigator& navigator) { + NavigatorKeyboardLock::From(navigator).keyboardUnlock(); } bool NavigatorKeyboardLock::EnsureServiceConnected() {
diff --git a/third_party/WebKit/Source/modules/keyboard_lock/NavigatorKeyboardLock.h b/third_party/WebKit/Source/modules/keyboard_lock/NavigatorKeyboardLock.h index 7138025c..ae8ffab 100644 --- a/third_party/WebKit/Source/modules/keyboard_lock/NavigatorKeyboardLock.h +++ b/third_party/WebKit/Source/modules/keyboard_lock/NavigatorKeyboardLock.h
@@ -17,8 +17,8 @@ class ScriptPromiseResolver; -// The supplement of Navigator to process navigator.requestKeyboardLock() and -// navigator.cancelKeyboardLock() web APIs. This class forwards both requests +// The supplement of Navigator to process navigator.keyboardLock() and +// navigator.keyboardUnlock() web APIs. This class forwards both requests // directly to the browser process through mojo. class NavigatorKeyboardLock final : public GarbageCollectedFinalized<NavigatorKeyboardLock>, @@ -28,24 +28,25 @@ public: // Requests to receive a set of key codes // (https://w3c.github.io/uievents/#dom-keyboardevent-code) in string format. - // The Promise will be rejected if the user or browser do not allow the web - // page to use this API. Otherwise, web page should expect to receive the key - // presses once the Promise has been resolved. This API does best effort to - // deliver the key codes: due to the platform restrictions, some keys or key - // combinations may not be able to receive or intercept by the user agent. + // The Promise will be rejected if the user or browser does not allow the web + // page to use this API. Otherwise, the web page should expect to receive the + // key presses once the Promise has been resolved. This API does best effort + // to deliver the key codes: due to the platform restrictions, some keys or + // key combinations cannot be received or intercepted by the user agent. + // - TODO(joedow): Update concurrent promise behavior to match spec. // - Making two requests concurrently without waiting for one Promise to // finish is disallowed, the second Promise will be rejected immediately. // - Making a second request after the Promise of the first one has finished // is allowed; the second request will overwrite the key codes reserved. // - Passing in an empty keyCodes array will reserve all keys. - static ScriptPromise requestKeyboardLock(ScriptState*, - Navigator&, - const Vector<String>&); + static ScriptPromise keyboardLock(ScriptState*, + Navigator&, + const Vector<String>&); - // Removes all reserved keys. This function is also asynchronized, the web - // page may still receive reserved keys after this function has finished. Once + // Removes all reserved keys. This function is asynchronous so the web page + // may still receive reserved keys after this function has returned. Once // the web page is closed, the user agent implicitly executes this API. - static void cancelKeyboardLock(Navigator&); + static void keyboardUnlock(Navigator&); void Trace(blink::Visitor*); @@ -55,11 +56,10 @@ static NavigatorKeyboardLock& From(Navigator&); - ScriptPromise requestKeyboardLock(ScriptState*, const Vector<String>&); - void cancelKeyboardLock(); + ScriptPromise keyboardLock(ScriptState*, const Vector<String>&); + void keyboardUnlock(); - // Ensures the |service_| is correctly initialized. In case of the |service_| - // cannot be initialized, this function returns false. + // Returns true if |service_| is initialized and ready to be called. bool EnsureServiceConnected(); void LockRequestFinished(mojom::KeyboardLockRequestResult);
diff --git a/third_party/WebKit/Source/modules/keyboard_lock/NavigatorKeyboardLock.idl b/third_party/WebKit/Source/modules/keyboard_lock/NavigatorKeyboardLock.idl index 90e2db97..76593bd 100644 --- a/third_party/WebKit/Source/modules/keyboard_lock/NavigatorKeyboardLock.idl +++ b/third_party/WebKit/Source/modules/keyboard_lock/NavigatorKeyboardLock.idl
@@ -7,19 +7,19 @@ // 1. "System" should be removed from both the function names: these functions // are not for system keys or key combinations only. // See https://github.com/w3c/keyboard-lock/issues/6 -// 2. Returns Promise<void> from requestKeyboardLock() function: user agents can +// 2. Returns Promise<void> from keyboardLock() function: user agents can // decline the request, and web page can get a notification once the // requested keys should be received. // See https://github.com/w3c/keyboard-lock/issues/7 -// 3. The parameter of requestKeyboardLock() should be +// 3. The parameter of keyboardLock() should be // optional sequence<DOMString> keyCodes = [] // See https://github.com/w3c/keyboard-lock/issues/21 -// 4. cancelKeyboardLock() function is implicitly called whenever the unloading +// 4. keyboardUnlock() function is implicitly called whenever the unloading // document cleanup steps run with a document. // See https://github.com/w3c/keyboard-lock/issues/22 [ ImplementedAs=NavigatorKeyboardLock ] partial interface Navigator { - [SecureContext, RuntimeEnabled=KeyboardLock, CallWith=ScriptState] Promise<void> requestKeyboardLock(optional sequence<DOMString> keyCodes = []); - [SecureContext, RuntimeEnabled=KeyboardLock] void cancelKeyboardLock(); + [SecureContext, RuntimeEnabled=KeyboardLock, CallWith=ScriptState] Promise<void> keyboardLock(optional sequence<DOMString> keyCodes = []); + [SecureContext, RuntimeEnabled=KeyboardLock] void keyboardUnlock(); };
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 d9aba6a..f652349 100644 --- a/third_party/WebKit/Source/modules/media_controls/resources/legacyMediaControls.css +++ b/third_party/WebKit/Source/modules/media_controls/resources/legacyMediaControls.css
@@ -185,7 +185,7 @@ * full math expression is: * 15px + (36 - 15) * ((100vw - 400px) / (1920 - 400)). */ font-size: calc(9.5px + 1.38vw); - background-color: black; + background-color: transparent; opacity: 0; transition: opacity .3s ease-in-out; } @@ -241,6 +241,23 @@ margin: 0px; } +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/remoteplayback/RemotePlayback.cpp b/third_party/WebKit/Source/modules/remoteplayback/RemotePlayback.cpp index 06df75c..c4fd520 100644 --- a/third_party/WebKit/Source/modules/remoteplayback/RemotePlayback.cpp +++ b/third_party/WebKit/Source/modules/remoteplayback/RemotePlayback.cpp
@@ -357,7 +357,9 @@ DispatchEvent(Event::Create(EventTypeNames::disconnect)); if (RuntimeEnabledFeatures::NewRemotePlaybackPipelineEnabled() && media_element_->IsHTMLVideoElement()) { - ToHTMLVideoElement(media_element_)->MediaRemotingStopped(); + ToHTMLVideoElement(media_element_) + ->MediaRemotingStopped( + WebLocalizedString::kMediaRemotingStopNoText); } break; }
diff --git a/third_party/WebKit/Source/modules/webaudio/AudioNode.cpp b/third_party/WebKit/Source/modules/webaudio/AudioNode.cpp index a5caec8..f2e26d3 100644 --- a/third_party/WebKit/Source/modules/webaudio/AudioNode.cpp +++ b/third_party/WebKit/Source/modules/webaudio/AudioNode.cpp
@@ -542,7 +542,13 @@ #endif BaseAudioContext::GraphAutoLocker locker(context()); Handler().Dispose(); - if (context()->ContextState() == BaseAudioContext::kRunning) { + + // If the context is not closed, add this handler to the orphan + // list. The audio thread could be running and processing this + // handler right now, so deleting it now would be bad. By putting + // on the orphan list, the handler stays alive until it can be + // safely processed after the graph is not being processed. + if (context()->ContextState() != BaseAudioContext::kClosed) { context()->GetDeferredTaskHandler().AddRenderingOrphanHandler( std::move(handler_)); }
diff --git a/third_party/WebKit/Source/modules/websockets/WebSocketHandleImpl.cpp b/third_party/WebKit/Source/modules/websockets/WebSocketHandleImpl.cpp index 4832a715..646cb97 100644 --- a/third_party/WebKit/Source/modules/websockets/WebSocketHandleImpl.cpp +++ b/third_party/WebKit/Source/modules/websockets/WebSocketHandleImpl.cpp
@@ -63,11 +63,6 @@ mojom::blink::WebSocketClientPtr client_proxy; client_binding_.Bind(mojo::MakeRequest(&client_proxy, task_runner)); - // TODO(crbug.com/786608) remove the following CHECKs once bug is solved. - CHECK(url.IsValid()); - CHECK(site_for_cookies.IsValid()); - CHECK(origin); - websocket_->AddChannelRequest( url, protocols, origin, site_for_cookies, user_agent_override.IsNull() ? g_empty_string : user_agent_override,
diff --git a/third_party/WebKit/Source/platform/BUILD.gn b/third_party/WebKit/Source/platform/BUILD.gn index 2e010896..98eee36 100644 --- a/third_party/WebKit/Source/platform/BUILD.gn +++ b/third_party/WebKit/Source/platform/BUILD.gn
@@ -1833,7 +1833,6 @@ "geometry/LayoutSizeTest.cpp", "geometry/RegionTest.cpp", "graphics/BitmapImageTest.cpp", - "graphics/CanvasResourceTest.cpp", "graphics/CompositorElementIdTest.cpp", "graphics/ContiguousContainerTest.cpp", "graphics/DecodingImageGeneratorTest.cpp", @@ -2203,6 +2202,7 @@ sources = [ "graphics/Canvas2DLayerBridgeTest.cpp", "graphics/CanvasColorParamsTest.cpp", + "graphics/CanvasResourceTest.cpp", "graphics/ColorCorrectionTestUtils.cpp", "graphics/DeferredImageDecoderTest.cpp", "graphics/GraphicsLayerTest.cpp",
diff --git a/third_party/WebKit/Source/platform/audio/cpu/mips/VectorMathMSA.h b/third_party/WebKit/Source/platform/audio/cpu/mips/VectorMathMSA.h index 5754575c..04f4dacd 100644 --- a/third_party/WebKit/Source/platform/audio/cpu/mips/VectorMathMSA.h +++ b/third_party/WebKit/Source/platform/audio/cpu/mips/VectorMathMSA.h
@@ -211,7 +211,7 @@ int source_stride, float* sum_p, size_t frames_to_process) { - Scalar::Vsvesq(source_p, source_stride, sum_p, n); + Scalar::Vsvesq(source_p, source_stride, sum_p, frames_to_process); } static ALWAYS_INLINE void Zvmul(const float* real1p,
diff --git a/third_party/WebKit/Source/platform/graphics/CanvasResource.cpp b/third_party/WebKit/Source/platform/graphics/CanvasResource.cpp index a33dc2cc..418e296 100644 --- a/third_party/WebKit/Source/platform/graphics/CanvasResource.cpp +++ b/third_party/WebKit/Source/platform/graphics/CanvasResource.cpp
@@ -158,7 +158,7 @@ return image_ && image_->HasMailbox(); } -const gpu::SyncToken& CanvasResource_Bitmap::GetSyncToken() const { +const gpu::SyncToken& CanvasResource_Bitmap::GetSyncToken() { DCHECK(image_); // Calling code should check IsValid() before calling this. return image_->GetSyncToken(); } @@ -272,10 +272,7 @@ if (gpu_mailbox_.IsZero() && gl) { gl->GenMailboxCHROMIUM(gpu_mailbox_.name); gl->ProduceTextureDirectCHROMIUM(texture_id_, gpu_mailbox_.name); - } - if (mailbox_needs_new_sync_token_) { - mailbox_needs_new_sync_token_ = false; - gl->GenUnverifiedSyncTokenCHROMIUM(sync_token_.GetData()); + mailbox_needs_new_sync_token_ = true; } return gpu_mailbox_; } @@ -284,7 +281,13 @@ return !gpu_mailbox_.IsZero(); } -const gpu::SyncToken& CanvasResource_GpuMemoryBuffer::GetSyncToken() const { +const gpu::SyncToken& CanvasResource_GpuMemoryBuffer::GetSyncToken() { + if (mailbox_needs_new_sync_token_) { + auto gl = ContextGL(); + DCHECK(gl); // caller should already have early exited if !gl. + mailbox_needs_new_sync_token_ = false; + gl->GenUnverifiedSyncTokenCHROMIUM(sync_token_.GetData()); + } return sync_token_; }
diff --git a/third_party/WebKit/Source/platform/graphics/CanvasResource.h b/third_party/WebKit/Source/platform/graphics/CanvasResource.h index 668b2c1..bd4ab8c 100644 --- a/third_party/WebKit/Source/platform/graphics/CanvasResource.h +++ b/third_party/WebKit/Source/platform/graphics/CanvasResource.h
@@ -42,6 +42,7 @@ virtual bool IsValid() const = 0; virtual IntSize Size() const = 0; virtual const gpu::Mailbox& GetOrCreateGpuMailbox() = 0; + virtual const gpu::SyncToken& GetSyncToken() = 0; bool PrepareTransferableResource( viz::TransferableResource* out_resource, std::unique_ptr<viz::SingleReleaseCallback>* out_callback); @@ -57,7 +58,6 @@ CanvasResource(base::WeakPtr<CanvasResourceProvider>, SkFilterQuality); virtual GLenum TextureTarget() const = 0; virtual bool IsOverlayCandidate() const { return false; } - virtual const gpu::SyncToken& GetSyncToken() const = 0; virtual bool HasGpuMailbox() const = 0; gpu::gles2::GLES2Interface* ContextGL() const; GLenum GLFilter() const; @@ -98,7 +98,7 @@ const override; const gpu::Mailbox& GetOrCreateGpuMailbox() override; bool HasGpuMailbox() const override; - const gpu::SyncToken& GetSyncToken() const; + const gpu::SyncToken& GetSyncToken() override; CanvasResource_Bitmap(scoped_refptr<StaticBitmapImage>, base::WeakPtr<CanvasResourceProvider>, @@ -129,7 +129,7 @@ bool IsOverlayCandidate() const final { return true; } const gpu::Mailbox& GetOrCreateGpuMailbox() override; bool HasGpuMailbox() const override; - const gpu::SyncToken& GetSyncToken() const; + const gpu::SyncToken& GetSyncToken() override; base::WeakPtr<WebGraphicsContext3DProviderWrapper> ContextProviderWrapper() const override; void CopyFromTexture(GLuint source_texture, @@ -145,7 +145,7 @@ gpu::Mailbox gpu_mailbox_; gpu::SyncToken sync_token_; - bool mailbox_needs_new_sync_token_ = true; + bool mailbox_needs_new_sync_token_ = false; base::WeakPtr<WebGraphicsContext3DProviderWrapper> context_provider_wrapper_; std::unique_ptr<gfx::GpuMemoryBuffer> gpu_memory_buffer_; GLuint image_id_ = 0;
diff --git a/third_party/WebKit/Source/platform/graphics/CanvasResourceTest.cpp b/third_party/WebKit/Source/platform/graphics/CanvasResourceTest.cpp index adffd0f..9754b94 100644 --- a/third_party/WebKit/Source/platform/graphics/CanvasResourceTest.cpp +++ b/third_party/WebKit/Source/platform/graphics/CanvasResourceTest.cpp
@@ -4,10 +4,13 @@ #include "platform/graphics/CanvasResource.h" +#include "base/run_loop.h" +#include "components/viz/test/test_gpu_memory_buffer_manager.h" #include "platform/graphics/StaticBitmapImage.h" #include "platform/graphics/gpu/SharedGpuContext.h" #include "platform/graphics/test/FakeGLES2Interface.h" #include "platform/graphics/test/FakeWebGraphicsContext3DProvider.h" +#include "platform/testing/TestingPlatformSupport.h" #include "platform/wtf/Functional.h" #include "testing/gmock/include/gmock/gmock.h" #include "testing/gtest/include/gtest/gtest.h" @@ -15,6 +18,7 @@ using ::testing::_; using ::testing::Pointee; +using ::testing::Return; using ::testing::SetArrayArgument; using ::testing::Test; @@ -24,6 +28,23 @@ public: MOCK_METHOD2(ProduceTextureDirectCHROMIUM, void(GLuint, const GLbyte*)); MOCK_METHOD1(GenMailboxCHROMIUM, void(GLbyte*)); + MOCK_METHOD1(GenUnverifiedSyncTokenCHROMIUM, void(GLbyte*)); + MOCK_METHOD4(CreateImageCHROMIUM, + GLuint(ClientBuffer, GLsizei, GLsizei, GLenum)); +}; + +class FakePlatformSupport : public TestingPlatformSupport { + public: + void RunUntilStop() const { base::RunLoop().Run(); } + + void StopRunning() const { base::RunLoop().Quit(); } + + private: + gpu::GpuMemoryBufferManager* GetGpuMemoryBufferManager() override { + return &test_gpu_memory_buffer_manager_; + } + + viz::TestGpuMemoryBufferManager test_gpu_memory_buffer_manager_; }; class CanvasResourceTest : public Test { @@ -51,6 +72,13 @@ base::WeakPtr<WebGraphicsContext3DProviderWrapper> context_provider_wrapper_; }; +gpu::SyncToken GenTestSyncToken(int id) { + gpu::SyncToken token; + token.Set(gpu::CommandBufferNamespace::GPU_IO, + gpu::CommandBufferId::FromUnsafeValue(id), 1); + return token; +} + TEST_F(CanvasResourceTest, SkiaResourceNoMailboxLeak) { SkImageInfo image_info = SkImageInfo::MakeN32(10, 10, kPremul_SkAlphaType, nullptr); @@ -85,4 +113,66 @@ ::testing::Mock::VerifyAndClearExpectations(&gl_); } +TEST_F(CanvasResourceTest, GpuMemoryBufferSyncTokenRefresh) { + ScopedTestingPlatformSupport<FakePlatformSupport> platform; + + constexpr GLuint image_id = 1; + EXPECT_CALL(gl_, CreateImageCHROMIUM(_, _, _, _)).WillOnce(Return(image_id)); + scoped_refptr<CanvasResource> resource = + CanvasResource_GpuMemoryBuffer::Create( + IntSize(10, 10), CanvasColorParams(), + SharedGpuContext::ContextProviderWrapper(), + nullptr, // Resource provider + kLow_SkFilterQuality); + + EXPECT_TRUE(bool(resource)); + + ::testing::Mock::VerifyAndClearExpectations(&gl_); + + gpu::Mailbox test_mailbox; + test_mailbox.name[0] = 1; + EXPECT_CALL(gl_, GenMailboxCHROMIUM(_)) + .WillOnce(SetArrayArgument<0>( + test_mailbox.name, test_mailbox.name + GL_MAILBOX_SIZE_CHROMIUM)); + resource->GetOrCreateGpuMailbox(); + + ::testing::Mock::VerifyAndClearExpectations(&gl_); + + const gpu::SyncToken reference_token1 = GenTestSyncToken(1); + EXPECT_CALL(gl_, GenUnverifiedSyncTokenCHROMIUM(_)) + .WillOnce(SetArrayArgument<0>( + reinterpret_cast<const GLbyte*>(&reference_token1), + reinterpret_cast<const GLbyte*>(&reference_token1 + 1))); + gpu::SyncToken actual_token = resource->GetSyncToken(); + EXPECT_EQ(actual_token, reference_token1); + + ::testing::Mock::VerifyAndClearExpectations(&gl_); + + // Grabbing the mailbox again without making any changes must not result in + // a sync token refresh + EXPECT_CALL(gl_, GenMailboxCHROMIUM(_)).Times(0); + EXPECT_CALL(gl_, GenUnverifiedSyncTokenCHROMIUM(_)).Times(0); + resource->GetOrCreateGpuMailbox(); + actual_token = resource->GetSyncToken(); + EXPECT_EQ(actual_token, reference_token1); + + ::testing::Mock::VerifyAndClearExpectations(&gl_); + + // Grabbing the mailbox again after a content change must result in + // a sync token refresh, but the mailbox gets re-used. + EXPECT_CALL(gl_, GenMailboxCHROMIUM(_)).Times(0); + const gpu::SyncToken reference_token2 = GenTestSyncToken(2); + EXPECT_CALL(gl_, GenUnverifiedSyncTokenCHROMIUM(_)) + .WillOnce(SetArrayArgument<0>( + reinterpret_cast<const GLbyte*>(&reference_token2), + reinterpret_cast<const GLbyte*>(&reference_token2 + 1))); + resource->CopyFromTexture(1, // source texture id + GL_RGBA, GL_UNSIGNED_BYTE); + resource->GetOrCreateGpuMailbox(); + actual_token = resource->GetSyncToken(); + EXPECT_EQ(actual_token, reference_token2); + + ::testing::Mock::VerifyAndClearExpectations(&gl_); +} + } // namespace blink
diff --git a/third_party/WebKit/Source/platform/heap/HeapAllocator.h b/third_party/WebKit/Source/platform/heap/HeapAllocator.h index 92a1f63..0dd06be 100644 --- a/third_party/WebKit/Source/platform/heap/HeapAllocator.h +++ b/third_party/WebKit/Source/platform/heap/HeapAllocator.h
@@ -558,6 +558,7 @@ static const bool kNeedsDestruction = false; static const bool kCanInitializeWithMemset = true; static const bool kCanClearUnusedSlotsWithMemset = true; + static const bool kCanCopyWithMemcpy = true; static const bool kCanMoveWithMemcpy = true; }; @@ -690,6 +691,13 @@ } static PeekOutType Peek(const blink::Member<T>& value) { return value; } + + static void ConstructDeletedValue(blink::Member<T>& slot, bool) { + slot = WTF::kHashTableDeletedValue; + } + static bool IsDeletedValue(blink::Member<T> value) { + return value.IsHashTableDeletedValue(); + } }; template <typename T>
diff --git a/third_party/WebKit/Source/platform/heap/HeapTerminatedArray.h b/third_party/WebKit/Source/platform/heap/HeapTerminatedArray.h index 93ca458..da40954e 100644 --- a/third_party/WebKit/Source/platform/heap/HeapTerminatedArray.h +++ b/third_party/WebKit/Source/platform/heap/HeapTerminatedArray.h
@@ -6,6 +6,7 @@ #define HeapTerminatedArray_h #include "platform/heap/Heap.h" +#include "platform/wtf/ConstructTraits.h" #include "platform/wtf/TerminatedArray.h" #include "platform/wtf/TerminatedArrayBuilder.h" #include "platform/wtf/allocator/Partitions.h" @@ -38,6 +39,8 @@ static PassPtr Release(Ptr& ptr) { return ptr; } static PassPtr Create(size_t capacity) { + // No ConstructTraits as there are no real elements in the array after + // construction. return reinterpret_cast<HeapTerminatedArray*>( ThreadHeap::Allocate<HeapTerminatedArray>( WTF::Partitions::ComputeAllocationSize(capacity, sizeof(T)), @@ -45,10 +48,13 @@ } static PassPtr Resize(PassPtr ptr, size_t capacity) { - return reinterpret_cast<HeapTerminatedArray*>( + PassPtr array = reinterpret_cast<HeapTerminatedArray*>( ThreadHeap::Reallocate<HeapTerminatedArray>( ptr, WTF::Partitions::ComputeAllocationSize(capacity, sizeof(T)))); + WTF::ConstructTraits<T, VectorTraits<T>, HeapAllocator>:: + NotifyNewElements(reinterpret_cast<T*>(array), array->size()); + return array; } };
diff --git a/third_party/WebKit/Source/platform/heap/HeapTest.cpp b/third_party/WebKit/Source/platform/heap/HeapTest.cpp index b5eb1218..948f653 100644 --- a/third_party/WebKit/Source/platform/heap/HeapTest.cpp +++ b/third_party/WebKit/Source/platform/heap/HeapTest.cpp
@@ -1414,6 +1414,7 @@ } // namespace blink +WTF_ALLOW_MOVE_INIT_AND_COMPARE_WITH_MEM_FUNCTIONS(blink::TerminatedArrayItem); WTF_ALLOW_MOVE_INIT_AND_COMPARE_WITH_MEM_FUNCTIONS(blink::VectorObject); WTF_ALLOW_MOVE_INIT_AND_COMPARE_WITH_MEM_FUNCTIONS( blink::VectorObjectInheritedTrace);
diff --git a/third_party/WebKit/Source/platform/heap/IncrementalMarkingTest.cpp b/third_party/WebKit/Source/platform/heap/IncrementalMarkingTest.cpp index 62b6192d..e49b870 100644 --- a/third_party/WebKit/Source/platform/heap/IncrementalMarkingTest.cpp +++ b/third_party/WebKit/Source/platform/heap/IncrementalMarkingTest.cpp
@@ -175,6 +175,17 @@ // Member<T> support. ========================================================== // ============================================================================= +TEST(IncrementalMarkingTest, MemberReferenceAssignMember) { + Object* obj = Object::Create(); + Member<Object> m1; + Member<Object>& m2 = m1; + Member<Object> m3(obj); + { + ExpectWriteBarrierFires<Object> scope(ThreadState::Current(), {obj}); + m2 = m3; + } +} + TEST(IncrementalMarkingTest, WriteBarrierOnUnmarkedObject) { Object* parent = Object::Create(); Object* child = Object::Create(); @@ -355,13 +366,6 @@ } // namespace -TEST(IncrementalMarkingTest, HeapVectorAssumptions) { - static_assert(std::is_trivially_move_assignable<Member<Object>>::value, - "Member<T> should not be trivially move assignable"); - static_assert(std::is_trivially_copy_assignable<Member<Object>>::value, - "Member<T> should not be trivially copy assignable"); -} - TEST(IncrementalMarkingTest, HeapVectorPushBackMember) { Object* obj = Object::Create(); HeapVector<Member<Object>> vec; @@ -676,13 +680,13 @@ } // ============================================================================= -// HeapHashSet/HeapLinkedHashSet support. ====================================== +// HeapHashSet support. ======================================================== // ============================================================================= namespace { template <typename Container> -void Set() { +void Insert() { Object* obj = Object::Create(); Container container; { @@ -692,7 +696,7 @@ } template <typename Container> -void SetNoBarrier() { +void InsertNoBarrier() { Object* obj = Object::Create(); Container container; { @@ -780,9 +784,9 @@ } // namespace -TEST(IncrementalMarkingTest, HeapHashSetSet) { - Set<HeapHashSet<Member<Object>>>(); - SetNoBarrier<HeapHashSet<WeakMember<Object>>>(); +TEST(IncrementalMarkingTest, HeapHashSetInsert) { + Insert<HeapHashSet<Member<Object>>>(); + InsertNoBarrier<HeapHashSet<WeakMember<Object>>>(); } TEST(IncrementalMarkingTest, HeapHashSetCopy) { @@ -800,26 +804,6 @@ SwapNoBarrier<HeapHashSet<WeakMember<Object>>>(); } -TEST(IncrementalMarkingTest, HeapLinkedHashSetSet) { - Set<HeapLinkedHashSet<Member<Object>>>(); - SetNoBarrier<HeapLinkedHashSet<WeakMember<Object>>>(); -} - -TEST(IncrementalMarkingTest, HeapLinkedHashSetCopy) { - Copy<HeapLinkedHashSet<Member<Object>>>(); - CopyNoBarrier<HeapLinkedHashSet<WeakMember<Object>>>(); -} - -TEST(IncrementalMarkingTest, HeapLinkedHashSetMove) { - Move<HeapLinkedHashSet<Member<Object>>>(); - MoveNoBarrier<HeapLinkedHashSet<WeakMember<Object>>>(); -} - -TEST(IncrementalMarkingTest, HeapLinkedHashSetSwap) { - Swap<HeapLinkedHashSet<Member<Object>>>(); - SwapNoBarrier<HeapLinkedHashSet<WeakMember<Object>>>(); -} - class StrongWeakPair : public std::pair<Member<Object>, WeakMember<Object>> { DISALLOW_NEW_EXCEPT_PLACEMENT_NEW(); @@ -940,10 +924,73 @@ } // ============================================================================= -// HeapTerminatedArray support. ================================================ +// HeapLinkedHashSet support. ================================================== // ============================================================================= -namespace { +TEST(IncrementalMarkingTest, HeapLinkedHashSetInsert) { + Insert<HeapLinkedHashSet<Member<Object>>>(); + InsertNoBarrier<HeapLinkedHashSet<WeakMember<Object>>>(); +} + +TEST(IncrementalMarkingTest, HeapLinkedHashSetCopy) { + Copy<HeapLinkedHashSet<Member<Object>>>(); + CopyNoBarrier<HeapLinkedHashSet<WeakMember<Object>>>(); +} + +TEST(IncrementalMarkingTest, HeapLinkedHashSetMove) { + Move<HeapLinkedHashSet<Member<Object>>>(); + MoveNoBarrier<HeapLinkedHashSet<WeakMember<Object>>>(); +} + +TEST(IncrementalMarkingTest, HeapLinkedHashSetSwap) { + Swap<HeapLinkedHashSet<Member<Object>>>(); + SwapNoBarrier<HeapLinkedHashSet<WeakMember<Object>>>(); +} + +// ============================================================================= +// HeapHashCountedSet support. ================================================= +// ============================================================================= + +// HeapHashCountedSet does not support copy or move. + +TEST(IncrementalMarkingTest, HeapHashCountedSetInsert) { + Insert<HeapHashCountedSet<Member<Object>>>(); + InsertNoBarrier<HeapHashCountedSet<WeakMember<Object>>>(); +} + +TEST(IncrementalMarkingTest, HeapHashCountedSetSwap) { + // HeapHashCountedSet is not move constructible so we cannot use std::swap. + { + Object* obj1 = Object::Create(); + Object* obj2 = Object::Create(); + HeapHashCountedSet<Member<Object>> container1; + container1.insert(obj1); + HeapHashCountedSet<Member<Object>> container2; + container2.insert(obj2); + { + ExpectWriteBarrierFires<Object> scope(ThreadState::Current(), + {obj1, obj2}); + container1.swap(container2); + } + } + { + Object* obj1 = Object::Create(); + Object* obj2 = Object::Create(); + HeapHashCountedSet<WeakMember<Object>> container1; + container1.insert(obj1); + HeapHashCountedSet<WeakMember<Object>> container2; + container2.insert(obj2); + { + ExpectNoWriteBarrierFires<Object> scope(ThreadState::Current(), + {obj1, obj2}); + container1.swap(container2); + } + } +} + +// ============================================================================= +// HeapTerminatedArray support. ================================================ +// ============================================================================= class TerminatedArrayNode { DISALLOW_NEW_EXCEPT_PLACEMENT_NEW(); @@ -962,7 +1009,14 @@ bool is_last_in_array_; }; -} // namespace +} // namespace incremental_marking_test +} // namespace blink + +WTF_ALLOW_MOVE_INIT_AND_COMPARE_WITH_MEM_FUNCTIONS( + blink::incremental_marking_test::TerminatedArrayNode); + +namespace blink { +namespace incremental_marking_test { TEST(IncrementalMarkingTest, HeapTerminatedArrayBuilder) { Object* obj = Object::Create(); @@ -1035,7 +1089,7 @@ } } -TEST(IncrementalMarkingTest, HeapHashMapSetMemberOnlyValue) { +TEST(IncrementalMarkingTest, HeapHashMapSetMemberUpdateValue) { Object* obj1 = Object::Create(); Object* obj2 = Object::Create(); Object* obj3 = Object::Create(); @@ -1079,7 +1133,7 @@ } } -TEST(IncrementalMarkingTest, HeapHashMapCopyMember) { +TEST(IncrementalMarkingTest, HeapHashMapCopyMemberMember) { Object* obj1 = Object::Create(); Object* obj2 = Object::Create(); HeapHashMap<Member<Object>, Member<Object>> map1; @@ -1093,33 +1147,7 @@ } } -TEST(IncrementalMarkingTest, HeapHashMapInsertStrongWeakPairMember) { - Object* obj1 = Object::Create(); - Object* obj2 = Object::Create(); - Object* obj3 = Object::Create(); - HeapHashMap<StrongWeakPair, Member<Object>> map; - { - // Tests that the write barrier also fires for entities such as - // StrongWeakPair that don't overload assignment operators in translators. - ExpectWriteBarrierFires<Object> scope(ThreadState::Current(), {obj1, obj3}); - map.insert(StrongWeakPair(obj1, obj2), obj3); - } -} - -TEST(IncrementalMarkingTest, HeapHashMapInsertMemberStrongWeakPair) { - Object* obj1 = Object::Create(); - Object* obj2 = Object::Create(); - Object* obj3 = Object::Create(); - HeapHashMap<Member<Object>, StrongWeakPair> map; - { - // Tests that the write barrier also fires for entities such as - // StrongWeakPair that don't overload assignment operators in translators. - ExpectWriteBarrierFires<Object> scope(ThreadState::Current(), {obj1, obj2}); - map.insert(obj1, StrongWeakPair(obj2, obj3)); - } -} - -TEST(IncrementalMarkingTest, HeapHashMapCopyWeakMember) { +TEST(IncrementalMarkingTest, HeapHashMapCopyWeakMemberWeakMember) { Object* obj1 = Object::Create(); Object* obj2 = Object::Create(); HeapHashMap<WeakMember<Object>, WeakMember<Object>> map1; @@ -1162,6 +1190,163 @@ } } +TEST(IncrementalMarkingTest, HeapHashMapMoveMember) { + Object* obj1 = Object::Create(); + Object* obj2 = Object::Create(); + HeapHashMap<Member<Object>, Member<Object>> map1; + map1.insert(obj1, obj2); + { + ExpectWriteBarrierFires<Object> scope(ThreadState::Current(), {obj1, obj2}); + HeapHashMap<Member<Object>, Member<Object>> map2(std::move(map1)); + } +} + +TEST(IncrementalMarkingTest, HeapHashMapMoveWeakMember) { + Object* obj1 = Object::Create(); + Object* obj2 = Object::Create(); + HeapHashMap<WeakMember<Object>, WeakMember<Object>> map1; + map1.insert(obj1, obj2); + { + ExpectNoWriteBarrierFires<Object> scope(ThreadState::Current(), + {obj1, obj2}); + HeapHashMap<WeakMember<Object>, WeakMember<Object>> map2(std::move(map1)); + } +} + +TEST(IncrementalMarkingTest, HeapHashMapMoveMemberWeakMember) { + Object* obj1 = Object::Create(); + Object* obj2 = Object::Create(); + HeapHashMap<Member<Object>, WeakMember<Object>> map1; + map1.insert(obj1, obj2); + { + ExpectWriteBarrierFires<Object> scope(ThreadState::Current(), {obj1}); + HeapHashMap<Member<Object>, WeakMember<Object>> map2(std::move(map1)); + } +} + +TEST(IncrementalMarkingTest, HeapHashMapMoveWeakMemberMember) { + Object* obj1 = Object::Create(); + Object* obj2 = Object::Create(); + HeapHashMap<WeakMember<Object>, Member<Object>> map1; + map1.insert(obj1, obj2); + { + ExpectWriteBarrierFires<Object> scope(ThreadState::Current(), {obj2}); + HeapHashMap<WeakMember<Object>, Member<Object>> map2(std::move(map1)); + } +} + +TEST(IncrementalMarkingTest, HeapHashMapSwapMemberMember) { + Object* obj1 = Object::Create(); + Object* obj2 = Object::Create(); + Object* obj3 = Object::Create(); + Object* obj4 = Object::Create(); + HeapHashMap<Member<Object>, Member<Object>> map1; + map1.insert(obj1, obj2); + HeapHashMap<Member<Object>, Member<Object>> map2; + map2.insert(obj3, obj4); + { + ExpectWriteBarrierFires<Object> scope(ThreadState::Current(), + {obj1, obj2, obj3, obj4}); + std::swap(map1, map2); + } +} + +TEST(IncrementalMarkingTest, HeapHashMapSwapWeakMemberWeakMember) { + Object* obj1 = Object::Create(); + Object* obj2 = Object::Create(); + Object* obj3 = Object::Create(); + Object* obj4 = Object::Create(); + HeapHashMap<WeakMember<Object>, WeakMember<Object>> map1; + map1.insert(obj1, obj2); + HeapHashMap<WeakMember<Object>, WeakMember<Object>> map2; + map2.insert(obj3, obj4); + { + ExpectNoWriteBarrierFires<Object> scope(ThreadState::Current(), + {obj1, obj2, obj3, obj4}); + std::swap(map1, map2); + } +} + +TEST(IncrementalMarkingTest, HeapHashMapSwapMemberWeakMember) { + Object* obj1 = Object::Create(); + Object* obj2 = Object::Create(); + Object* obj3 = Object::Create(); + Object* obj4 = Object::Create(); + HeapHashMap<Member<Object>, WeakMember<Object>> map1; + map1.insert(obj1, obj2); + HeapHashMap<Member<Object>, WeakMember<Object>> map2; + map2.insert(obj3, obj4); + { + ExpectWriteBarrierFires<Object> scope(ThreadState::Current(), {obj1, obj3}); + std::swap(map1, map2); + } +} + +TEST(IncrementalMarkingTest, HeapHashMapSwapWeakMemberMember) { + Object* obj1 = Object::Create(); + Object* obj2 = Object::Create(); + Object* obj3 = Object::Create(); + Object* obj4 = Object::Create(); + HeapHashMap<WeakMember<Object>, Member<Object>> map1; + map1.insert(obj1, obj2); + HeapHashMap<WeakMember<Object>, Member<Object>> map2; + map2.insert(obj3, obj4); + { + ExpectWriteBarrierFires<Object> scope(ThreadState::Current(), {obj2, obj4}); + std::swap(map1, map2); + } +} + +TEST(IncrementalMarkingTest, HeapHashMapInsertStrongWeakPairMember) { + Object* obj1 = Object::Create(); + Object* obj2 = Object::Create(); + Object* obj3 = Object::Create(); + HeapHashMap<StrongWeakPair, Member<Object>> map; + { + // Tests that the write barrier also fires for entities such as + // StrongWeakPair that don't overload assignment operators in translators. + ExpectWriteBarrierFires<Object> scope(ThreadState::Current(), {obj1, obj3}); + map.insert(StrongWeakPair(obj1, obj2), obj3); + } +} + +TEST(IncrementalMarkingTest, HeapHashMapInsertMemberStrongWeakPair) { + Object* obj1 = Object::Create(); + Object* obj2 = Object::Create(); + Object* obj3 = Object::Create(); + HeapHashMap<Member<Object>, StrongWeakPair> map; + { + // Tests that the write barrier also fires for entities such as + // StrongWeakPair that don't overload assignment operators in translators. + ExpectWriteBarrierFires<Object> scope(ThreadState::Current(), {obj1, obj2}); + map.insert(obj1, StrongWeakPair(obj2, obj3)); + } +} + +TEST(IncrementalMarkingTest, HeapHashMapCopyKeysToVectorMember) { + Object* obj1 = Object::Create(); + Object* obj2 = Object::Create(); + HeapHashMap<Member<Object>, Member<Object>> map; + map.insert(obj1, obj2); + HeapVector<Member<Object>> vec; + { + ExpectWriteBarrierFires<Object> scope(ThreadState::Current(), {obj1}); + CopyKeysToVector(map, vec); + } +} + +TEST(IncrementalMarkingTest, HeapHashMapCopyValuesToVectorMember) { + Object* obj1 = Object::Create(); + Object* obj2 = Object::Create(); + HeapHashMap<Member<Object>, Member<Object>> map; + map.insert(obj1, obj2); + HeapVector<Member<Object>> vec; + { + ExpectWriteBarrierFires<Object> scope(ThreadState::Current(), {obj1}); + CopyValuesToVector(map, vec); + } +} + } // namespace incremental_marking_test } // namespace blink
diff --git a/third_party/WebKit/Source/platform/heap/Member.h b/third_party/WebKit/Source/platform/heap/Member.h index 754cadd6..3f402ad 100644 --- a/third_party/WebKit/Source/platform/heap/Member.h +++ b/third_party/WebKit/Source/platform/heap/Member.h
@@ -110,6 +110,11 @@ return *this; } + MemberBase& operator=(WTF::HashTableDeletedValueType) { + raw_ = reinterpret_cast<T*>(-1); + return *this; + } + MemberBase& operator=(std::nullptr_t) { raw_ = nullptr; return *this; @@ -227,6 +232,12 @@ return *this; } + Member& operator=(const Member& other) { + Parent::operator=(other); + WriteBarrier(this->raw_); + return *this; + } + template <typename U> Member& operator=(const Member<U>& other) { Parent::operator=(other); @@ -248,6 +259,11 @@ return *this; } + Member& operator=(WTF::HashTableDeletedValueType x) { + Parent::operator=(x); + return *this; + } + Member& operator=(std::nullptr_t) { Parent::operator=(nullptr); return *this; @@ -256,7 +272,7 @@ protected: ALWAYS_INLINE void WriteBarrier(const T* value) const { #if BUILDFLAG(BLINK_HEAP_INCREMENTAL_MARKING) - if (value) { + if (LIKELY(value && !this->IsHashTableDeletedValue())) { // The following method for retrieving a page works as allocation of // mixins on large object pages is prohibited. BasePage* const page = PageFromObject(value);
diff --git a/third_party/WebKit/Source/platform/scheduler/BUILD.gn b/third_party/WebKit/Source/platform/scheduler/BUILD.gn index 07466ea..8bff877 100644 --- a/third_party/WebKit/Source/platform/scheduler/BUILD.gn +++ b/third_party/WebKit/Source/platform/scheduler/BUILD.gn
@@ -40,12 +40,16 @@ "base/work_queue_sets.h", "child/cancelable_closure_holder.cc", "child/cancelable_closure_holder.h", + "child/compositor_metrics_helper.cc", + "child/compositor_metrics_helper.h", "child/compositor_worker_scheduler.cc", "child/compositor_worker_scheduler.h", "child/idle_canceled_delayed_task_sweeper.cc", "child/idle_canceled_delayed_task_sweeper.h", "child/idle_helper.cc", "child/idle_helper.h", + "child/metrics_helper.cc", + "child/metrics_helper.h", "child/pollable_thread_safe_flag.cc", "child/pollable_thread_safe_flag.h", "child/scheduler_helper.cc", @@ -61,6 +65,8 @@ "child/webthread_impl_for_worker_scheduler.h", "child/worker_global_scope_scheduler.cc", "child/worker_global_scope_scheduler.h", + "child/worker_metrics_helper.cc", + "child/worker_metrics_helper.h", "child/worker_scheduler.cc", "child/worker_scheduler.h", "child/worker_scheduler_helper.cc",
diff --git a/third_party/WebKit/Source/platform/scheduler/README.md b/third_party/WebKit/Source/platform/scheduler/README.md index 4c050c2..610e26ff 100644 --- a/third_party/WebKit/Source/platform/scheduler/README.md +++ b/third_party/WebKit/Source/platform/scheduler/README.md
@@ -46,14 +46,13 @@ * [Virtual time in Headless Chrome](https://docs.google.com/document/d/1dIMHIl1xutUXqXWRXqXrDd3bo9hachIt_ZkPK_BshUs/edit) * [Task traits](https://docs.google.com/document/d/1d6t7CTobtXLj1gXiBE8SVl_fxJjEazATxYHYGp5ppvE) * [Compositor and Display Scheduling presentation from scheduling summit](https://docs.google.com/presentation/d/1FpTy5DpIGKt8r2t785y6yrHETkg8v7JfJ26zUxaNDUg/edit?usp=sharing) -* [Modernizing task management in Chrome](https://docs.google.com/document/d/14Q22SKrhN9OykJgRLcHMQVzeXKVJCbx7xQvOeOoNQm4/edit#heading=h.rptt48atxb4e) +* [Simplifying Task Management in Chromium](https://docs.google.com/document/d/1fn0AmFsY7gWvStShOh7dUxOfHXjKgcfsr9I1ETbNe2I/edit) * [Outline of known work needed to fix resize](https://docs.google.com/a/chromium.org/document/d/1POLDq-L_T9iZ_Ul39sjOMiOO-yvLnmb1WFsH4JfIyVU/edit?usp=sharing_eid) * [Blink spatial scheduling](https://docs.google.com/document/d/1k9fL01wwRliVzZW_ibPT8-B9BADz7I87hpFoXFG37aI/edit?pli=1#) * [Throttling Blink's rendering pipeline for hidden content](https://docs.google.com/document/d/1Dd4qi1b_iX-OCZpelvXxizjq6dDJ76XNtk37SZEoTYQ/edit) * [Scheduling to avoid checkerboard in Chrome](https://docs.google.com/document/d/1OLp7x06CjBY-0J3TBQzXw8sALHznIx4rYixvnBTbUUA/edit#heading=h.9i2v5u7um22b) * [State of GPU scheduling](https://docs.google.com/document/d/15gbHgXPyhSlNu1Ku9HF-of8BNOpvsziV1F8IE-kRax4/edit#heading=h.jermw4ib9rwc) * [Scheduling architecture diagram](https://docs.google.com/drawings/d/1xcHpqhdcIsX0b_sGPuU1SZCsY87UTqJ67qvvbF29oLM/edit) -* [Blink Scheduler-dev BrownBag presentation](https://docs.google.com/presentation/d/1uda_oY0XGMsTsDt9xuWv_eWHWpt_F9VRuL6-5XqBUVY/edit#slide=id.g5e1a23a4d_2274) * [Event dispatch diagram](https://docs.google.com/drawings/d/1bUukRm-DV34sM7rL2_bSdxaQkZVMQ_5vOa7nzDnmnx8/edit) * [Proxying MessageLoop tasks to the Scheduler](https://docs.google.com/a/chromium.org/document/d/1qxdh2I61_aB_Uzh1QgNqvdWFBCL_E65G2smoSySw7KU/edit#heading=h.vit0krths7ns) * [Scheduling JS timer execution](https://docs.google.com/a/chromium.org/document/d/163ow-1wjd6L0rAN3V_U6t12eqVkq4mXDDjVaA4OuvCA/edit?usp=sharing_eid)
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 new file mode 100644 index 0000000..ca309322 --- /dev/null +++ b/third_party/WebKit/Source/platform/scheduler/child/compositor_metrics_helper.cc
@@ -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/scheduler/child/compositor_metrics_helper.h" + +namespace blink { +namespace scheduler { + +CompositorMetricsHelper::CompositorMetricsHelper() + : MetricsHelper(ThreadType::kCompositorThread) {} + +CompositorMetricsHelper::~CompositorMetricsHelper() {} + +void CompositorMetricsHelper::RecordTaskMetrics(WorkerTaskQueue* queue, + const TaskQueue::Task& task, + base::TimeTicks start_time, + base::TimeTicks end_time) { + MetricsHelper::RecordCommonTaskMetrics(queue, task, start_time, end_time); +} + +} // namespace scheduler +} // namespace blink
diff --git a/third_party/WebKit/Source/platform/scheduler/child/compositor_metrics_helper.h b/third_party/WebKit/Source/platform/scheduler/child/compositor_metrics_helper.h new file mode 100644 index 0000000..22891d7 --- /dev/null +++ b/third_party/WebKit/Source/platform/scheduler/child/compositor_metrics_helper.h
@@ -0,0 +1,31 @@ +// 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_COMPOSITOR_METRICS_HELPER_H_ +#define THIRD_PARTY_WEBKIT_SOURCE_PLATFORM_SCHEDULER_CHILD_COMPOSITOR_METRICS_HELPER_H_ + +#include "platform/scheduler/child/metrics_helper.h" +#include "platform/scheduler/child/worker_task_queue.h" + +namespace blink { +namespace scheduler { + +class PLATFORM_EXPORT CompositorMetricsHelper : public MetricsHelper { + public: + CompositorMetricsHelper(); + ~CompositorMetricsHelper(); + + void RecordTaskMetrics(WorkerTaskQueue* queue, + const TaskQueue::Task& task, + base::TimeTicks start_time, + base::TimeTicks end_time); + + private: + DISALLOW_COPY_AND_ASSIGN(CompositorMetricsHelper); +}; + +} // namespace scheduler +} // namespace blink + +#endif // THIRD_PARTY_WEBKIT_SOURCE_PLATFORM_SCHEDULER_CHILD_COMPOSITOR_METRICS_HELPER_H_
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 c4eb5c02..5666817 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
@@ -23,9 +23,7 @@ : WorkerScheduler( std::make_unique<WorkerSchedulerHelper>(std::move(task_queue_manager), this)), - thread_(thread), - compositor_thread_task_duration_reporter_( - "RendererScheduler.TaskDurationPerThreadType") {} + thread_(thread) {} CompositorWorkerScheduler::~CompositorWorkerScheduler() = default; @@ -40,8 +38,8 @@ const TaskQueue::Task& task, base::TimeTicks start, base::TimeTicks end) { - compositor_thread_task_duration_reporter_.RecordTask( - ThreadType::kCompositorThread, end - start); + compositor_metrics_helper_.RecordTaskMetrics(worker_task_queue, task, start, + end); } scoped_refptr<base::SingleThreadTaskRunner>
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 35b29aec..4cdaa89 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
@@ -9,6 +9,7 @@ #include "base/message_loop/message_loop.h" #include "base/single_thread_task_runner.h" #include "platform/PlatformExport.h" +#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" @@ -59,8 +60,8 @@ private: base::Thread* thread_; - TaskDurationMetricReporter<ThreadType> - compositor_thread_task_duration_reporter_; + + CompositorMetricsHelper compositor_metrics_helper_; DISALLOW_COPY_AND_ASSIGN(CompositorWorkerScheduler); };
diff --git a/third_party/WebKit/Source/platform/scheduler/child/metrics_helper.cc b/third_party/WebKit/Source/platform/scheduler/child/metrics_helper.cc new file mode 100644 index 0000000..ef650364 --- /dev/null +++ b/third_party/WebKit/Source/platform/scheduler/child/metrics_helper.cc
@@ -0,0 +1,26 @@ +// 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/scheduler/child/metrics_helper.h" + +namespace blink { +namespace scheduler { + +MetricsHelper::MetricsHelper(ThreadType thread_type) + : thread_type_(thread_type), + thread_task_duration_reporter_( + "RendererScheduler.TaskDurationPerThreadType") {} + +MetricsHelper::~MetricsHelper() {} + +void MetricsHelper::RecordCommonTaskMetrics(TaskQueue* queue, + const TaskQueue::Task& task, + base::TimeTicks start_time, + base::TimeTicks end_time) { + thread_task_duration_reporter_.RecordTask(thread_type_, + end_time - start_time); +} + +} // namespace scheduler +} // namespace blink
diff --git a/third_party/WebKit/Source/platform/scheduler/child/metrics_helper.h b/third_party/WebKit/Source/platform/scheduler/child/metrics_helper.h new file mode 100644 index 0000000..f8ab302b --- /dev/null +++ b/third_party/WebKit/Source/platform/scheduler/child/metrics_helper.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 THIRD_PARTY_WEBKIT_SOURCE_PLATFORM_SCHEDULER_CHILD_METRICS_HELPER_H_ +#define THIRD_PARTY_WEBKIT_SOURCE_PLATFORM_SCHEDULER_CHILD_METRICS_HELPER_H_ + +#include "base/optional.h" +#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" + +namespace blink { +namespace scheduler { + +class TaskQueue; + +// Helper class to take care of task metrics shared between main thread +// and worker threads of the renderer process, including per-thread +// task metrics. +// +// Each thread-specific scheduler should have its own subclass of MetricsHelper +// (RendererMetricsHelper, WorkerMetricsHelper, etc) and should call +// RecordCommonTaskMetrics manually. +// Note that this is code reuse, not data reuse -- each thread should have its +// own instantiation of this class. +class PLATFORM_EXPORT MetricsHelper { + public: + explicit MetricsHelper(ThreadType thread_type); + ~MetricsHelper(); + + protected: + // Record task metrics which are shared between threads. + void RecordCommonTaskMetrics(TaskQueue* queue, + const TaskQueue::Task& task, + base::TimeTicks start_time, + base::TimeTicks end_time); + + private: + ThreadType thread_type_; + + TaskDurationMetricReporter<ThreadType> thread_task_duration_reporter_; + + DISALLOW_COPY_AND_ASSIGN(MetricsHelper); +}; + +} // namespace scheduler +} // namespace blink + +#endif // THIRD_PARTY_WEBKIT_SOURCE_PLATFORM_SCHEDULER_CHILD_METRICS_HELPER_H_
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 new file mode 100644 index 0000000..4234754 --- /dev/null +++ b/third_party/WebKit/Source/platform/scheduler/child/worker_metrics_helper.cc
@@ -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/scheduler/child/worker_metrics_helper.h" + +namespace blink { +namespace scheduler { + +WorkerMetricsHelper::WorkerMetricsHelper() + : MetricsHelper(ThreadType::kWorkerThread) {} + +WorkerMetricsHelper::~WorkerMetricsHelper() {} + +void WorkerMetricsHelper::RecordTaskMetrics(WorkerTaskQueue* queue, + const TaskQueue::Task& task, + base::TimeTicks start_time, + base::TimeTicks end_time) { + MetricsHelper::RecordCommonTaskMetrics(queue, task, start_time, end_time); +} + +} // namespace scheduler +} // namespace blink
diff --git a/third_party/WebKit/Source/platform/scheduler/child/worker_metrics_helper.h b/third_party/WebKit/Source/platform/scheduler/child/worker_metrics_helper.h new file mode 100644 index 0000000..fdeb1ce --- /dev/null +++ b/third_party/WebKit/Source/platform/scheduler/child/worker_metrics_helper.h
@@ -0,0 +1,31 @@ +// 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_WORKER_METRICS_HELPER_H_ +#define THIRD_PARTY_WEBKIT_SOURCE_PLATFORM_SCHEDULER_CHILD_WORKER_METRICS_HELPER_H_ + +#include "platform/scheduler/child/metrics_helper.h" +#include "platform/scheduler/child/worker_task_queue.h" + +namespace blink { +namespace scheduler { + +class PLATFORM_EXPORT WorkerMetricsHelper : public MetricsHelper { + public: + WorkerMetricsHelper(); + ~WorkerMetricsHelper(); + + void RecordTaskMetrics(WorkerTaskQueue* queue, + const TaskQueue::Task& task, + base::TimeTicks start_time, + base::TimeTicks end_time); + + private: + DISALLOW_COPY_AND_ASSIGN(WorkerMetricsHelper); +}; + +} // namespace scheduler +} // namespace blink + +#endif // THIRD_PARTY_WEBKIT_SOURCE_PLATFORM_SCHEDULER_CHILD_WORKER_METRICS_HELPER_H_
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 44dafab..026da58 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
@@ -57,9 +57,7 @@ idle_helper_.IdleTaskRunner()), load_tracker_(helper_->NowTicks(), base::Bind(&ReportWorkerTaskLoad), - kWorkerThreadLoadTrackerReportingInterval), - worker_thread_task_duration_reporter_( - "RendererScheduler.TaskDurationPerThreadType") { + kWorkerThreadLoadTrackerReportingInterval) { initialized_ = false; thread_start_time_ = helper_->NowTicks(); load_tracker_.Resume(thread_start_time_); @@ -142,8 +140,7 @@ const TaskQueue::Task& task, base::TimeTicks start, base::TimeTicks end) { - worker_thread_task_duration_reporter_.RecordTask(ThreadType::kWorkerThread, - end - start); + worker_metrics_helper_.RecordTaskMetrics(worker_task_queue, task, start, end); } SchedulerHelper* WorkerSchedulerImpl::GetSchedulerHelperForTesting() {
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 505eb34..127bdc03 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
@@ -11,6 +11,7 @@ #include "platform/scheduler/base/task_time_observer.h" #include "platform/scheduler/child/idle_canceled_delayed_task_sweeper.h" #include "platform/scheduler/child/idle_helper.h" +#include "platform/scheduler/child/worker_metrics_helper.h" #include "platform/scheduler/child/worker_scheduler.h" #include "platform/scheduler/util/task_duration_metric_reporter.h" #include "platform/scheduler/util/thread_load_tracker.h" @@ -73,7 +74,8 @@ ThreadLoadTracker load_tracker_; bool initialized_; base::TimeTicks thread_start_time_; - TaskDurationMetricReporter<ThreadType> worker_thread_task_duration_reporter_; + + WorkerMetricsHelper worker_metrics_helper_; DISALLOW_COPY_AND_ASSIGN(WorkerSchedulerImpl); };
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 d076a4f..1730b6c 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
@@ -48,7 +48,8 @@ RendererSchedulerImpl* renderer_scheduler, base::TimeTicks now, bool renderer_backgrounded) - : renderer_scheduler_(renderer_scheduler), + : MetricsHelper(ThreadType::kMainThread), + renderer_scheduler_(renderer_scheduler), main_thread_load_tracker( now, base::Bind(&RendererMetricsHelper::RecordMainThreadTaskLoad, @@ -98,8 +99,6 @@ DURATION_PER_QUEUE_TYPE_METRIC_NAME ".HiddenMusic"), per_frame_status_duration_reporter(DURATION_PER_FRAME_TYPE_METRIC_NAME), per_task_type_duration_reporter(DURATION_PER_TASK_TYPE_METRIC_NAME), - main_thread_task_duration_reporter( - "RendererScheduler.TaskDurationPerThreadType"), main_thread_task_load_state(MainThreadTaskLoadState::kUnknown) { main_thread_load_tracker.Resume(now); if (renderer_backgrounded) { @@ -146,6 +145,8 @@ const TaskQueue::Task& task, base::TimeTicks start_time, base::TimeTicks end_time) { + MetricsHelper::RecordCommonTaskMetrics(queue, task, start_time, end_time); + MainThreadTaskQueue::QueueType queue_type = queue->queue_type(); base::TimeDelta duration = end_time - start_time; if (duration > kLongTaskDiscardingThreshold) @@ -204,8 +205,6 @@ MainThreadTaskQueue::QueueType::kCount); } - main_thread_task_duration_reporter.RecordTask(ThreadType::kMainThread, - duration); per_queue_type_task_duration_reporter.RecordTask(queue_type, duration); if (renderer_scheduler_->main_thread_only().renderer_backgrounded) {
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 f128194..d9a913e 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
@@ -9,6 +9,7 @@ #include "base/optional.h" #include "base/time/time.h" #include "platform/PlatformExport.h" +#include "platform/scheduler/child/metrics_helper.h" #include "platform/scheduler/renderer/frame_status.h" #include "platform/scheduler/renderer/main_thread_task_queue.h" #include "platform/scheduler/util/task_duration_metric_reporter.h" @@ -42,7 +43,7 @@ // Helper class to take care of metrics on behalf of RendererScheduler. // This class should be used only on the main thread. -class PLATFORM_EXPORT RendererMetricsHelper { +class PLATFORM_EXPORT RendererMetricsHelper : public MetricsHelper { public: static void RecordBackgroundedTransition( BackgroundedRendererTransition transition); @@ -115,8 +116,6 @@ TaskDurationMetricReporter<TaskType>; TaskDurationPerTaskTypeMetricReporter per_task_type_duration_reporter; - TaskDurationMetricReporter<ThreadType> main_thread_task_duration_reporter; - MainThreadTaskLoadState main_thread_task_load_state; DISALLOW_COPY_AND_ASSIGN(RendererMetricsHelper);
diff --git a/third_party/WebKit/Source/platform/weborigin/SchemeRegistry.cpp b/third_party/WebKit/Source/platform/weborigin/SchemeRegistry.cpp index e73e1b00..4b18af9 100644 --- a/third_party/WebKit/Source/platform/weborigin/SchemeRegistry.cpp +++ b/third_party/WebKit/Source/platform/weborigin/SchemeRegistry.cpp
@@ -209,6 +209,12 @@ scheme); } +void SchemeRegistry::RemoveURLSchemeAsNotAllowingJavascriptURLs( + const String& scheme) { + GetMutableURLSchemesRegistry().not_allowing_javascript_urls_schemes.erase( + scheme); +} + bool SchemeRegistry::ShouldTreatURLSchemeAsNotAllowingJavascriptURLs( const String& scheme) { DCHECK_EQ(scheme, scheme.LowerASCII());
diff --git a/third_party/WebKit/Source/platform/weborigin/SchemeRegistry.h b/third_party/WebKit/Source/platform/weborigin/SchemeRegistry.h index d3d54a4..d77dc0c 100644 --- a/third_party/WebKit/Source/platform/weborigin/SchemeRegistry.h +++ b/third_party/WebKit/Source/platform/weborigin/SchemeRegistry.h
@@ -83,6 +83,7 @@ // bookmarklets from running on sensitive pages). static void RegisterURLSchemeAsNotAllowingJavascriptURLs( const String& scheme); + static void RemoveURLSchemeAsNotAllowingJavascriptURLs(const String& scheme); static bool ShouldTreatURLSchemeAsNotAllowingJavascriptURLs( const String& scheme);
diff --git a/third_party/WebKit/Source/platform/wtf/TerminatedArray.h b/third_party/WebKit/Source/platform/wtf/TerminatedArray.h index 147645e..0882f7f 100644 --- a/third_party/WebKit/Source/platform/wtf/TerminatedArray.h +++ b/third_party/WebKit/Source/platform/wtf/TerminatedArray.h
@@ -25,7 +25,7 @@ public: // When TerminatedArray::Allocator implementations grow the backing // store, old is copied into the new and larger block. - static_assert(VectorTraits<T>::kCanCopyWithMemcpy, + static_assert(VectorTraits<T>::kCanMoveWithMemcpy, "Array elements must be memory copyable"); T& at(size_t index) { return reinterpret_cast<T*>(this)[index]; }
diff --git a/third_party/WebKit/Source/platform/wtf/VectorTraits.h b/third_party/WebKit/Source/platform/wtf/VectorTraits.h index 6769795..65d551d1 100644 --- a/third_party/WebKit/Source/platform/wtf/VectorTraits.h +++ b/third_party/WebKit/Source/platform/wtf/VectorTraits.h
@@ -86,7 +86,11 @@ // work. template <typename P> struct VectorTraits<scoped_refptr<P>> - : SimpleClassVectorTraits<scoped_refptr<P>> {}; + : SimpleClassVectorTraits<scoped_refptr<P>> { + // scoped_refptr cannot be copied using memcpy as the internals (e.g. ref + // count) depend on properly constructing the object. + static const bool kCanCopyWithMemcpy = false; +}; template <typename P> struct VectorTraits<std::unique_ptr<P>>
diff --git a/third_party/WebKit/Tools/Scripts/webkitpy/common/net/git_cl.py b/third_party/WebKit/Tools/Scripts/webkitpy/common/net/git_cl.py index 5baf5064..822343d 100644 --- a/third_party/WebKit/Tools/Scripts/webkitpy/common/net/git_cl.py +++ b/third_party/WebKit/Tools/Scripts/webkitpy/common/net/git_cl.py
@@ -153,7 +153,7 @@ self._host.print_('Timed out waiting%s.' % message) return None - def latest_try_jobs(self, builder_names=None, cq_only=False): + def latest_try_jobs(self, builder_names=None, cq_only=False, patchset=None): """Fetches a dict of Build to TryJobStatus for the latest try jobs. This includes jobs that are not yet finished and builds with infra @@ -163,6 +163,7 @@ Args: builder_names: Optional list of builders used to filter results. cq_only: If True, only include CQ jobs. + patchset: If given, use this patchset instead of the latest. Returns: A dict mapping Build objects to TryJobStatus objects, with @@ -171,7 +172,8 @@ # TODO(crbug.com/771438): Update filter_latest to handle Swarming tasks. return self.filter_latest( self.try_job_results( - builder_names, include_swarming_tasks=False, cq_only=cq_only)) + builder_names, include_swarming_tasks=False, cq_only=cq_only, + patchset=patchset)) @staticmethod def filter_latest(try_results): @@ -183,9 +185,9 @@ def try_job_results( self, builder_names=None, include_swarming_tasks=True, - cq_only=False): + cq_only=False, patchset=None): """Returns a dict mapping Build objects to TryJobStatus objects.""" - raw_results = self.fetch_raw_try_job_results() + raw_results = self.fetch_raw_try_job_results(patchset=patchset) build_to_status = {} for result in raw_results: if builder_names and result['builder_name'] not in builder_names: @@ -200,7 +202,7 @@ build_to_status[self._build(result)] = self._try_job_status(result) return build_to_status - def fetch_raw_try_job_results(self): + def fetch_raw_try_job_results(self, patchset=None): """Requests results of try jobs for the current CL and the parsed JSON. The return value is expected to be a list of dicts, which each are @@ -209,7 +211,10 @@ """ with self._host.filesystem.mkdtemp() as temp_directory: results_path = self._host.filesystem.join(temp_directory, 'try-results.json') - self.run(['try-results', '--json', results_path]) + command = ['try-results', '--json', results_path] + if patchset: + command.extend(['--patchset', str(patchset)]) + self.run(command) contents = self._host.filesystem.read_text_file(results_path) _log.debug('Fetched try results to file "%s".', results_path) self._host.filesystem.remove(results_path)
diff --git a/third_party/WebKit/Tools/Scripts/webkitpy/common/net/git_cl_mock.py b/third_party/WebKit/Tools/Scripts/webkitpy/common/net/git_cl_mock.py index 7c36dc1..21c7e69 100644 --- a/third_party/WebKit/Tools/Scripts/webkitpy/common/net/git_cl_mock.py +++ b/third_party/WebKit/Tools/Scripts/webkitpy/common/net/git_cl_mock.py
@@ -58,7 +58,7 @@ return None return 'closed' - def latest_try_jobs(self, builder_names=None): + def latest_try_jobs(self, builder_names=None, **_): return self.filter_latest(self._try_job_results) @staticmethod
diff --git a/third_party/WebKit/Tools/Scripts/webkitpy/common/net/git_cl_unittest.py b/third_party/WebKit/Tools/Scripts/webkitpy/common/net/git_cl_unittest.py index 2c2746a..1879d21 100644 --- a/third_party/WebKit/Tools/Scripts/webkitpy/common/net/git_cl_unittest.py +++ b/third_party/WebKit/Tools/Scripts/webkitpy/common/net/git_cl_unittest.py
@@ -95,6 +95,30 @@ ], ]) + def test_fetch_raw_try_job_results(self): + # Fetching raw try job results has a side effect of writing to and + # reading from a temporary JSON file. This test method verifies the + # command line used to fetch try job results. + host = MockHost() + host.filesystem.write_text_file( + '/__im_tmp/tmp_0_/try-results.json', '{}') + host.filesystem.write_text_file( + '/__im_tmp/tmp_1_/try-results.json', '{}') + git_cl = GitCL(host) + git_cl.fetch_raw_try_job_results() + git_cl.fetch_raw_try_job_results(patchset=7) + self.assertEqual(host.executive.calls, [ + [ + 'git', 'cl', 'try-results', + '--json', '/__im_tmp/tmp_0_/try-results.json', + ], + [ + 'git', 'cl', 'try-results', + '--json', '/__im_tmp/tmp_1_/try-results.json', + '--patchset', '7' + ] + ]) + def test_get_issue_number(self): host = MockHost() host.executive = MockExecutive(output='Issue number: 12345 (http://crrev.com/12345)') @@ -110,7 +134,7 @@ def test_wait_for_try_jobs_timeout(self): host = MockHost() git_cl = GitCL(host) - git_cl.fetch_raw_try_job_results = lambda: [ + git_cl.fetch_raw_try_job_results = lambda **_: [ { 'builder_name': 'some-builder', 'status': 'STARTED', @@ -133,7 +157,7 @@ def test_wait_for_try_jobs_no_results_not_considered_finished(self): host = MockHost() git_cl = GitCL(host) - git_cl.fetch_raw_try_job_results = lambda: [] + git_cl.fetch_raw_try_job_results = lambda **_: [] self.assertIsNone(git_cl.wait_for_try_jobs()) self.assertEqual( host.stdout.getvalue(), @@ -150,7 +174,7 @@ host = MockHost() host.executive = MockExecutive(output='closed') git_cl = GitCL(host) - git_cl.fetch_raw_try_job_results = lambda: [ + git_cl.fetch_raw_try_job_results = lambda **_: [ { 'builder_name': 'some-builder', 'status': 'STARTED', @@ -175,7 +199,7 @@ host = MockHost() host.executive = MockExecutive(output='lgtm') git_cl = GitCL(host) - git_cl.fetch_raw_try_job_results = lambda: [ + git_cl.fetch_raw_try_job_results = lambda **_: [ { 'builder_name': 'some-builder', 'status': 'COMPLETED', @@ -254,7 +278,7 @@ def test_latest_try_jobs_cq_only(self): git_cl = GitCL(MockHost()) - git_cl.fetch_raw_try_job_results = lambda: [ + git_cl.fetch_raw_try_job_results = lambda **_: [ { 'builder_name': 'cq-a', 'experimental': False, @@ -288,7 +312,7 @@ def test_latest_try_jobs(self): git_cl = GitCL(MockHost()) - git_cl.fetch_raw_try_job_results = lambda: [ + git_cl.fetch_raw_try_job_results = lambda **_: [ { 'builder_name': 'builder-b', 'status': 'COMPLETED', @@ -323,7 +347,7 @@ def test_latest_try_jobs_started_build_luci_url(self): git_cl = GitCL(MockHost()) - git_cl.fetch_raw_try_job_results = lambda: [ + git_cl.fetch_raw_try_job_results = lambda **_: [ { 'builder_name': 'builder-a', 'status': 'STARTED', @@ -337,7 +361,7 @@ def test_latest_try_jobs_started_build_buildbot_url(self): git_cl = GitCL(MockHost()) - git_cl.fetch_raw_try_job_results = lambda: [ + git_cl.fetch_raw_try_job_results = lambda **_: [ { 'builder_name': 'builder-a', 'status': 'STARTED', @@ -351,7 +375,7 @@ def test_latest_try_jobs_failures(self): git_cl = GitCL(MockHost()) - git_cl.fetch_raw_try_job_results = lambda: [ + git_cl.fetch_raw_try_job_results = lambda **_: [ { 'builder_name': 'builder-a', 'status': 'COMPLETED', @@ -376,7 +400,7 @@ def test_latest_try_jobs_ignores_swarming_task(self): git_cl = GitCL(MockHost()) - git_cl.fetch_raw_try_job_results = lambda: [ + git_cl.fetch_raw_try_job_results = lambda **_: [ { 'builder_name': 'builder-b', 'status': 'COMPLETED', @@ -415,7 +439,7 @@ def test_try_job_results_with_task_id_in_url(self): git_cl = GitCL(MockHost()) - git_cl.fetch_raw_try_job_results = lambda: [ + git_cl.fetch_raw_try_job_results = lambda **_: [ { 'builder_name': 'builder-a', 'status': 'COMPLETED', @@ -441,7 +465,7 @@ def test_try_job_results_with_unexpected_url_format(self): git_cl = GitCL(MockHost()) - git_cl.fetch_raw_try_job_results = lambda: [ + git_cl.fetch_raw_try_job_results = lambda **_: [ { 'builder_name': 'builder-a', 'status': 'COMPLETED',
diff --git a/third_party/WebKit/Tools/Scripts/webkitpy/tool/commands/rebaseline_cl.py b/third_party/WebKit/Tools/Scripts/webkitpy/tool/commands/rebaseline_cl.py index 74a36e0b..3e69e34 100644 --- a/third_party/WebKit/Tools/Scripts/webkitpy/tool/commands/rebaseline_cl.py +++ b/third_party/WebKit/Tools/Scripts/webkitpy/tool/commands/rebaseline_cl.py
@@ -60,6 +60,9 @@ '--builders', default=None, action='append', help=('Comma-separated-list of builders to pull new baselines ' 'from (can also be provided multiple times).')), + optparse.make_option( + '--patchset', default=None, + help='Patchset number to fetch new baselines from.'), self.no_optimize_option, self.results_directory_option, ]) @@ -90,7 +93,8 @@ try_builders.update(builder_names.split(',')) self._selected_try_bots = frozenset(try_builders) - jobs = self.git_cl.latest_try_jobs(self.selected_try_bots) + jobs = self.git_cl.latest_try_jobs( + self.selected_try_bots, patchset=options.patchset) self._log_jobs(jobs) builders_with_no_jobs = self.selected_try_bots - {b.builder_name for b in jobs}
diff --git a/third_party/WebKit/Tools/Scripts/webkitpy/tool/commands/rebaseline_cl_unittest.py b/third_party/WebKit/Tools/Scripts/webkitpy/tool/commands/rebaseline_cl_unittest.py index d81a0f4..a3ccba4 100644 --- a/third_party/WebKit/Tools/Scripts/webkitpy/tool/commands/rebaseline_cl_unittest.py +++ b/third_party/WebKit/Tools/Scripts/webkitpy/tool/commands/rebaseline_cl_unittest.py
@@ -118,6 +118,7 @@ 'test_name_file': None, 'verbose': False, 'builders': [], + 'patchset': None, } options.update(kwargs) return optparse.Values(dict(**options))
diff --git a/third_party/WebKit/public/platform/WebLocalizedString.h b/third_party/WebKit/public/platform/WebLocalizedString.h index e9dbaf2..f8d9d42 100644 --- a/third_party/WebKit/public/platform/WebLocalizedString.h +++ b/third_party/WebKit/public/platform/WebLocalizedString.h
@@ -92,6 +92,10 @@ kInputElementAltText, kMediaRemotingCastText, kMediaRemotingCastToUnknownDeviceText, + kMediaRemotingStopByErrorText, + kMediaRemotingStopByPlaybackQualityText, + kMediaRemotingStopNoText, + kMediaRemotingStopText, kMissingPluginText, kMultipleFileUploadText, kOtherColorLabel,
diff --git a/third_party/WebKit/public/platform/WebMediaPlayerClient.h b/third_party/WebKit/public/platform/WebMediaPlayerClient.h index c05d4591..55e2501 100644 --- a/third_party/WebKit/public/platform/WebMediaPlayerClient.h +++ b/third_party/WebKit/public/platform/WebMediaPlayerClient.h
@@ -32,6 +32,7 @@ #define WebMediaPlayerClient_h #include "WebCommon.h" +#include "WebLocalizedString.h" #include "WebMediaPlayer.h" #include "ui/gfx/color_space.h" @@ -117,13 +118,16 @@ // Returns the selected video track id (or an empty id if there's none). virtual WebMediaPlayer::TrackId GetSelectedVideoTrackId() = 0; - // Informs that media starts/stops being rendered and played back remotely. + // Informs that media starts being rendered and played back remotely. // |remote_device_friendly_name| will be shown in the remoting UI to indicate // which device the content is rendered on. An empty name indicates an unknown // remote device. A default message will be shown in this case. virtual void MediaRemotingStarted( const WebString& remote_device_friendly_name) = 0; - virtual void MediaRemotingStopped() = 0; + + // Informs that media stops being rendered remotely. |error_msg| corresponds + // to a localized string that explains the reason as user-readable text. + virtual void MediaRemotingStopped(WebLocalizedString::Name error_msg) = 0; // Returns whether the media element has native controls. It does not mean // that the controls are currently visible.
diff --git a/third_party/WebKit/public/web/devtools_agent.mojom b/third_party/WebKit/public/web/devtools_agent.mojom index 2ec4c35..b567e39 100644 --- a/third_party/WebKit/public/web/devtools_agent.mojom +++ b/third_party/WebKit/public/web/devtools_agent.mojom
@@ -14,10 +14,6 @@ // Whether this is a last chunk in a message. bool is_last; - // The total size of the message being sent in chunks, only comes in - // a first chunk. - uint32 message_size; - // Chunk data. string data;
diff --git a/tools/OWNERS b/tools/OWNERS index 36e45e9..5f1f711a 100644 --- a/tools/OWNERS +++ b/tools/OWNERS
@@ -39,8 +39,6 @@ per-file ipc_messages_log.py=yfriedman@chromium.org -per-file licenses.py=torne@chromium.org - per-file remove_stale_pyc_files.py=dtu@chromium.org per-file roll_angle.py=kbr@chromium.org
diff --git a/tools/android/loading/device_setup.py b/tools/android/loading/device_setup.py index cfa19bf0..16abfa6 100644 --- a/tools/android/loading/device_setup.py +++ b/tools/android/loading/device_setup.py
@@ -360,11 +360,6 @@ def RemoteSpeedIndexRecorder(device, connection, local_output_path): """Records on a device a video compatible for speed-index computation. - Note: - Chrome should be opened with the --disable-infobars command line argument to - avoid web page viewport size to be changed, that can change speed-index - value. - Args: device: (device_utils.DeviceUtils) Android device to connect to. connection: devtools connection.
diff --git a/tools/android/loading/sandwich_runner.py b/tools/android/loading/sandwich_runner.py index 5c3bb949..cb2a80d 100644 --- a/tools/android/loading/sandwich_runner.py +++ b/tools/android/loading/sandwich_runner.py
@@ -331,7 +331,6 @@ self._chrome_ctl = controller.RemoteChromeController(self.android_device) else: self._chrome_ctl = controller.LocalChromeController() - self._chrome_ctl.AddChromeArguments(['--disable-infobars']) self._chrome_ctl.AddChromeArguments(self.chrome_args) if self.cache_operation == CacheOperation.SAVE: self._chrome_ctl.SetSlowDeath()
diff --git a/tools/binary_size/libsupersize/linker_map_parser.py b/tools/binary_size/libsupersize/linker_map_parser.py index 128208ee..e726795 100644 --- a/tools/binary_size/libsupersize/linker_map_parser.py +++ b/tools/binary_size/libsupersize/linker_map_parser.py
@@ -229,9 +229,22 @@ symbol_gap_count += 1 syms.append(sym) + # .text.res_findResource_60 + # 0x00178de8 0x12a obj/... + # 0x00178de9 res_findResource_60 + # .text._ZN3url6ParsedC2Ev + # 0x0021ad62 0x2e obj/url/url/url_parse.o + # 0x0021ad63 url::Parsed::Parsed() + # .text.unlikely._ZN4base3CPUC2Ev + # 0x003f9d3c 0x48 obj/base/base/cpu.o + # 0x003f9d3d base::CPU::CPU() + full_name = name + if mangled_name and (not name or mangled_name.startswith('_Z') or + '._Z' in mangled_name): + full_name = mangled_name + sym = models.Symbol(section_name, size, address=address, - full_name=name or mangled_name, - object_path=path) + full_name=full_name, object_path=path) syms.append(sym) section_end_address = section_address + section_size if section_name != models.SECTION_BSS and (
diff --git a/tools/binary_size/libsupersize/testdata/Archive.golden b/tools/binary_size/libsupersize/testdata/Archive.golden index 867b021f..75c121e3 100644 --- a/tools/binary_size/libsupersize/testdata/Archive.golden +++ b/tools/binary_size/libsupersize/testdata/Archive.golden
@@ -58,7 +58,7 @@ .text@28f1c8(size_without_padding=20,padding=8,full_name=_GLOBAL__sub_I_SkDeviceProfile.cpp,object_path=third_party/icu/icuuc/ucnv_ext.o,source_path=,flags={startup},num_aliases=1) .text@28f1e0(size_without_padding=69120,padding=4,full_name=foo_bar,object_path=third_party/icu/icuuc/ucnv_ext.o,source_path=,flags={unlikely},num_aliases=1) .text@2a0000(size_without_padding=16,padding=32,full_name=blink::ContiguousContainerBase::shrinkToFit(),object_path=third_party/WebKit.a/PaintChunker.o,source_path=,flags={},num_aliases=1) -.text@2a0010(size_without_padding=12,padding=0,full_name=blink::ContiguousContainerBase::shrinkToFit(),object_path=third_party/WebKit.a/PaintChunker.o,source_path=,flags={clone},num_aliases=1) +.text@2a0010(size_without_padding=12,padding=0,full_name=blink::ContiguousContainerBase::shrinkToFit(),object_path=third_party/WebKit.a/PaintChunker.o,source_path=,flags={clone,hot},num_aliases=1) .text@2a0020(size_without_padding=24,padding=4,full_name=blink::ContiguousContainerBase::ContiguousContainerBase(blink::ContiguousContainerBase&&),object_path=third_party/WebKit.a/ContiguousContainer.o,source_path=,flags={},num_aliases=1) .text@2a1000(size_without_padding=0,padding=4040,full_name=** symbol gap 1,object_path=,source_path=,flags={},num_aliases=1) .text@2a1000(size_without_padding=94,padding=0,full_name=blink::PaintChunker::releasePaintChunks(),object_path=third_party/WebKit.a/ContiguousContainer.o,source_path=,flags={anon,clone},num_aliases=1)
diff --git a/tools/binary_size/libsupersize/testdata/Archive_OutputDirectory.golden b/tools/binary_size/libsupersize/testdata/Archive_OutputDirectory.golden index 0d62c6f..a8cf239b 100644 --- a/tools/binary_size/libsupersize/testdata/Archive_OutputDirectory.golden +++ b/tools/binary_size/libsupersize/testdata/Archive_OutputDirectory.golden
@@ -58,7 +58,7 @@ .text@28f1c8(size_without_padding=20,padding=8,full_name=_GLOBAL__sub_I_SkDeviceProfile.cpp,object_path=third_party/icu/icuuc/ucnv_ext.o,source_path=third_party/icu/ucnv_ext.c,flags={startup,gen},num_aliases=1) .text@28f1e0(size_without_padding=69120,padding=4,full_name=foo_bar,object_path=third_party/icu/icuuc/ucnv_ext.o,source_path=third_party/icu/ucnv_ext.c,flags={unlikely,gen},num_aliases=1) .text@2a0000(size_without_padding=16,padding=32,full_name=blink::ContiguousContainerBase::shrinkToFit(),object_path=third_party/WebKit.a/PaintChunker.o,source_path=third_party/paint.cc,flags={},num_aliases=1) -.text@2a0010(size_without_padding=12,padding=0,full_name=blink::ContiguousContainerBase::shrinkToFit(),object_path=third_party/WebKit.a/PaintChunker.o,source_path=third_party/paint.cc,flags={clone},num_aliases=1) +.text@2a0010(size_without_padding=12,padding=0,full_name=blink::ContiguousContainerBase::shrinkToFit(),object_path=third_party/WebKit.a/PaintChunker.o,source_path=third_party/paint.cc,flags={clone,hot},num_aliases=1) .text@2a0020(size_without_padding=24,padding=4,full_name=blink::ContiguousContainerBase::ContiguousContainerBase(blink::ContiguousContainerBase&&),object_path=third_party/WebKit.a/ContiguousContainer.o,source_path=third_party/container.c,flags={},num_aliases=1) .text@2a1000(size_without_padding=0,padding=4040,full_name=** symbol gap 1,object_path=,source_path=,flags={},num_aliases=1) .text@2a1000(size_without_padding=94,padding=0,full_name=blink::PaintChunker::releasePaintChunks(),object_path=third_party/WebKit.a/ContiguousContainer.o,source_path=third_party/container.c,flags={anon,clone},num_aliases=1)
diff --git a/tools/binary_size/libsupersize/testdata/mock_toolchain/mock_cppfilt.py b/tools/binary_size/libsupersize/testdata/mock_toolchain/mock_cppfilt.py index e7448a9..0d903a0a 100644 --- a/tools/binary_size/libsupersize/testdata/mock_toolchain/mock_cppfilt.py +++ b/tools/binary_size/libsupersize/testdata/mock_toolchain/mock_cppfilt.py
@@ -31,6 +31,34 @@ 'aramRef<_jlongArray*> const&, int)::atomic_histogram_pointer'), '_ZN12_GLOBAL__N_135g_AnimationFrameTimeHistogram_clazzE': ( '(anonymous namespace)::g_AnimationFrameTimeHistogram_clazz'), + '_ZN5blink23ContiguousContainerBase11shrinkToFitEv': ( + 'blink::ContiguousContainerBase::shrinkToFit()'), + '_ZN5blink23ContiguousContainerBase11shrinkToFitEv2.part.1234.isra.2': ( + 'blink::ContiguousContainerBase::shrinkToFit() [clone .part.1234] ' + '[clone .isra.2]'), + '_ZN5blink23ContiguousContainerBaseC2EOS0_': ( + 'blink::ContiguousContainerBase::ContiguousContainerBase(' + 'blink::ContiguousContainerBase&&)'), + '_ZN5blink12PaintChunker18releasePaintChunksEv': ( + 'blink::PaintChunker::releasePaintChunks()'), + '_ZN10_GLOBAL__N5blink12PaintChunker18releasePaintChunksEv.part.1': ( + '(anonymous namespace)::blink::PaintChunker::releasePaintChunks() ' + '[clone .part.1]'), + '_ZN6chrome5mojom11FilePatcher5Name_E': 'chrome::mojom::FilePatcher::Name_', + '_ZTV18ChromeMainDelegate': 'vtable for ChromeMainDelegate', + '_ZTVN6chrome5mojom34FieldTrialRecorderRequestValidatorE': ( + 'vtable for chrome::mojom::FieldTrialRecorder'), + '_ZTVN6chrome5mojom23FieldTrialRecorderProxyE': ( + 'vtable for chrome::mojom::FieldTrialRecorderProxy'), + ('_ZZN10_GLOBAL__N5blink20CSSValueKeywordsHash13findValueImplEPKcjE15value_' + 'word_list'): ('(anonymous namespace)::blink::CSSValueKeywordsHash::' + 'findValueImpl(char const*, unsigned int)::value_word_list'), + '_ZTV25ChromeMainDelegateAndroid': 'vtable for ChromeMainDelegateAndroid', + '_ZTVN4mojo15MessageReceiverE': 'vtable for mojo::MessageReceiver', + '_ZN6google8protobuf8internal19pLinuxKernelCmpxchgE': ( + 'google::protobuf::internal::pLinuxKernelCmpxchg'), + '_ZN6google8protobuf8internal25pLinuxKernelMemoryBarrierE': ( + 'google::protobuf::internal::pLinuxKernelMemoryBarrier'), }
diff --git a/tools/binary_size/libsupersize/testdata/test.map b/tools/binary_size/libsupersize/testdata/test.map index e1a6a12b..7e124bb 100644 --- a/tools/binary_size/libsupersize/testdata/test.map +++ b/tools/binary_size/libsupersize/testdata/test.map
@@ -92,14 +92,14 @@ .text._ZN5blink23ContiguousContainerBase11shrinkToFitEv 0x002a0000 0x10 obj/third_party/WebKit.a(PaintChunker.o) 0x002a0001 blink::ContiguousContainerBase::shrinkToFit() - .text.hot._ZN5blink23ContiguousContainerBase11shrinkToFitEv2 + .text.hot._ZN5blink23ContiguousContainerBase11shrinkToFitEv2.part.1234.isra.2 0x002a0010 0xc obj/third_party/WebKit.a(PaintChunker.o) - 0x002a0011 blink::ContiguousContainerBase::shrinkToFit() [clone .part.1234] [clone .isra.2] + 0x002a0011 blink::ContiguousContainerBase::shrinkToFit() .text._ZN5blink23ContiguousContainerBaseC2EOS0_ 0xffffffffffffffff 0x18 obj/third_party/WebKit.a(ContiguousContainer.o) 0x002a0021 blink::ContiguousContainerBase::ContiguousContainerBase(blink::ContiguousContainerBase&&) 0x002a0021 blink::ContiguousContainerBase::ContiguousContainerBase(blink::ContiguousContainerBase&&) - .text._ZN5blink12PaintChunker18releasePaintChunksEv + .text._ZN10_GLOBAL__N5blink12PaintChunker18releasePaintChunksEv.part.1 0x002a1000 0x5e obj/third_party/WebKit.a(ContiguousContainer.o) 0x002a1001 (anonymous namespace)::blink::PaintChunker::releasePaintChunks() [clone .part.1] @@ -127,7 +127,7 @@ 0x0284e398 chrome::mojom::FilePatcher::Name_ .rodata._ZN12_GLOBAL__N_1L37kAnimationFrameTimeHistogramClassPathE 0x028f3450 0x30 obj/third_party/WebKit.a(PaintChunker.o) - .rodata._ZZN5blink20CSSValueKeywordsHash13findValueImplEPKcjE15value_word_list + .rodata._ZZN10_GLOBAL__N5blink20CSSValueKeywordsHash13findValueImplEPKcjE15value_word_list 0x028f3480 0x4 obj/third_party/WebKit.a(PaintChunker.o) 0x028f3480 blink::(anonymous namespace)::CSSValueKeywordsHash::findValueImpl(char const*, unsigned int)::value_word_list
diff --git a/tools/metrics/histograms/enums.xml b/tools/metrics/histograms/enums.xml index 29ec92e..b23ae13 100644 --- a/tools/metrics/histograms/enums.xml +++ b/tools/metrics/histograms/enums.xml
@@ -24826,6 +24826,7 @@ <int value="-1963402827" label="enable-topchrome-md"/> <int value="-1962588488" label="SpeculativePreconnect:disabled"/> <int value="-1961648833" label="show_summary"/> + <int value="-1961497025" label="tint-gl-composited-content"/> <int value="-1961062505" label="VrBrowsingInCustomTab:disabled"/> <int value="-1960567385" label="KeepPrefetchedContentSuggestions:enabled"/> <int value="-1957328398" label="MacSystemShareMenu:disabled"/> @@ -42687,6 +42688,7 @@ <int value="5151071" label="extension_manifest_fetcher"/> <int value="5154306" label="blob_reader"/> <int value="5492492" label="google_url_tracker"/> + <int value="5576536" label="cast_udp_transport"/> <int value="5637379" label="gaia_oauth_client_get_tokens"/> <int value="6019475" label="safe_browsing_module_loader"/> <int value="7433837" label="refresh_token_annotation_request"/> @@ -42699,6 +42701,7 @@ <int value="13694792" label="desktop_ios_promotion"/> <int value="14257952" label="supervised_user_url_filter"/> <int value="15418154" label="ntp_snippets_fetch"/> + <int value="15952025" label="dial_get_app_info"/> <int value="16469669" label="background_fetch_context"/> <int value="16653985" label="content_suggestion_get_favicon"/> <int value="17188928" label="websocket_stream"/> @@ -42864,6 +42867,7 @@ <int value="119542033" label="gcm_unregistration"/> <int value="119677115" label="safe_search_url_reporter"/> <int value="120000562" label="cryptauth_find_eligible_unlock_devices"/> + <int value="120623198" label="pepper_tcp_socket"/> <int value="121068967" label="downloads_api_run_async"/> <int value="124950347" label="safe_browsing_incident"/> <int value="125522256" label="client_download_request"/>
diff --git a/tools/metrics/histograms/histograms.xml b/tools/metrics/histograms/histograms.xml index 8ed152f..1791698 100644 --- a/tools/metrics/histograms/histograms.xml +++ b/tools/metrics/histograms/histograms.xml
@@ -30668,6 +30668,15 @@ </summary> </histogram> +<histogram name="InstantTethering.Performance.ConnectToHostDuration" units="ms"> + <owner>hansberry@chromium.org</owner> + <summary> + The duration of time it takes for the client to connect to the host, from + the moment the user taps 'Connect', until the client connects to the host's + hotspot. This does not include timeouts. + </summary> +</histogram> + <histogram name="InstantTethering.Performance.ConnectToHotspotDuration" units="ms"> <owner>hansberry@chromium.org</owner> @@ -95284,6 +95293,19 @@ </summary> </histogram> +<histogram name="Webapp.Engagement.EngagementType" + enum="SiteEngagementServiceEngagementType"> + <owner>calamity@chromium.org</owner> + <owner>mgiuca@chromium.org</owner> + <summary> + The type of engagement (navigation, user input, etc.) which led to an + accumulation in site engagement within a PWA app window. Should be collected + for a subset of SiteEngagementService.EngagementType, which is triggered for + all browsing contexts. Recorded at the time of engagement accumulation + (e.g., when mouse is clicked). + </summary> +</histogram> + <histogram name="Webapp.Install.DisplayMode" enum="WebAppDisplayMode"> <owner>piotrs@chromium.org</owner> <summary>
diff --git a/tools/perf/benchmark.csv b/tools/perf/benchmark.csv index 6a12108..0bbdc83 100644 --- a/tools/perf/benchmark.csv +++ b/tools/perf/benchmark.csv
@@ -25,7 +25,7 @@ jetstream,hablich@chromium.org, kraken,hablich@chromium.org, load_library_perf_tests,, -loading.desktop,"kouhei@chormium.org, ksakamoto@chromium.org", +loading.desktop,"kouhei@chromium.org, ksakamoto@chromium.org", loading.mobile,"kouhei@chromium.org, ksakamoto@chromium.org", media.desktop,"johnchen@chromium.org, crouleau@chromium.org",Internals>Media media.mobile,"johnchen@chromium.org, crouleau@chromium.org",Internals>Media
diff --git a/tools/perf/benchmarks/loading.py b/tools/perf/benchmarks/loading.py index f25efc9..5c15375 100644 --- a/tools/perf/benchmarks/loading.py +++ b/tools/perf/benchmarks/loading.py
@@ -24,7 +24,7 @@ return tbm_options -@benchmark.Owner(emails=['kouhei@chormium.org', 'ksakamoto@chromium.org']) +@benchmark.Owner(emails=['kouhei@chromium.org', 'ksakamoto@chromium.org']) class LoadingDesktop(_LoadingBase): """ A benchmark measuring loading performance of desktop sites. """ SUPPORTED_PLATFORMS = [story.expectations.ALL_DESKTOP]
diff --git a/tools/tests/OWNERS b/tools/tests/OWNERS deleted file mode 100644 index fe94ff7a..0000000 --- a/tools/tests/OWNERS +++ /dev/null
@@ -1 +0,0 @@ -per-file licenses_test.py=torne@chromium.org
diff --git a/tools/traffic_annotation/summary/annotations.xml b/tools/traffic_annotation/summary/annotations.xml index 6ea1476..fee093d 100644 --- a/tools/traffic_annotation/summary/annotations.xml +++ b/tools/traffic_annotation/summary/annotations.xml
@@ -25,6 +25,7 @@ <item id="blob_reader" hash_code="5154306" type="0" content_hash_code="39702178" os_list="linux,windows" file_path="extensions/browser/blob_reader.cc"/> <item id="brandcode_config" hash_code="109679553" type="0" content_hash_code="128843792" os_list="linux,windows" file_path="chrome/browser/profile_resetter/brandcode_config_fetcher.cc"/> <item id="captive_portal_service" hash_code="88754904" type="0" content_hash_code="70737580" os_list="linux,windows" file_path="chrome/browser/captive_portal/captive_portal_service.cc"/> + <item id="cast_udp_transport" hash_code="5576536" type="0" content_hash_code="107643273" os_list="linux,windows" file_path="media/cast/net/udp_transport.cc"/> <item id="certificate_verifier" hash_code="113553577" type="0" content_hash_code="62346354" os_list="linux,windows" file_path="net/cert_net/cert_net_fetcher_impl.cc"/> <item id="chrome_apps_socket_api" hash_code="8591273" type="0" content_hash_code="70868355" os_list="linux,windows" file_path="extensions/browser/api/socket/socket.cc"/> <item id="chrome_cleaner" hash_code="27071967" type="0" content_hash_code="111240292" os_list="windows" file_path="chrome/browser/safe_browsing/chrome_cleaner/chrome_cleaner_fetcher_win.cc"/> @@ -60,6 +61,7 @@ <item id="devtools_hard_coded_data_source" hash_code="111565057" type="0" content_hash_code="46074423" os_list="linux,windows" file_path="chrome/browser/ui/webui/devtools_ui.cc"/> <item id="devtools_interceptor" hash_code="98123737" type="0" content_hash_code="19053470" os_list="linux,windows" file_path="content/browser/devtools/devtools_url_interceptor_request_job.cc"/> <item id="devtools_network_resource" hash_code="129652775" type="0" content_hash_code="24059212" os_list="linux,windows" file_path="chrome/browser/devtools/devtools_ui_bindings.cc"/> + <item id="dial_get_app_info" hash_code="15952025" type="0" content_hash_code="90542080" os_list="linux,windows" file_path="chrome/browser/media/router/discovery/dial/dial_app_info_fetcher.cc"/> <item id="dial_get_device_description" hash_code="50422598" type="0" content_hash_code="129827780" os_list="linux,windows" file_path="chrome/browser/media/router/discovery/dial/device_description_fetcher.cc"/> <item id="dom_distiller" hash_code="3989826" type="0" content_hash_code="106153970" os_list="linux,windows" file_path="components/dom_distiller/core/distiller_url_fetcher.cc"/> <item id="domain_reliability_report_upload" hash_code="108804096" type="0" content_hash_code="35902036" os_list="linux,windows" file_path="components/domain_reliability/uploader.cc"/> @@ -137,6 +139,7 @@ <item id="payment_manifest_downloader" hash_code="84045030" type="0" content_hash_code="19293316" os_list="linux,windows" file_path="components/payments/core/payment_manifest_downloader.cc"/> <item id="payments_sync_cards" hash_code="95588446" type="0" content_hash_code="56526513" os_list="linux,windows" file_path="components/autofill/core/browser/payments/payments_client.cc"/> <item id="pdf_plugin_placeholder" hash_code="56866367" type="0" content_hash_code="16907221" os_list="linux,windows" file_path="chrome/browser/plugins/pdf_plugin_placeholder_observer.cc"/> + <item id="pepper_tcp_socket" hash_code="120623198" type="0" content_hash_code="55474823" os_list="linux,windows" file_path="content/browser/renderer_host/pepper/pepper_tcp_socket_message_filter.cc"/> <item id="permission_reporting" hash_code="131741641" type="0" content_hash_code="7213535" os_list="linux,windows" file_path="chrome/browser/safe_browsing/permission_reporter.cc"/> <item id="permission_request_creator" hash_code="43206794" type="0" content_hash_code="73571699" os_list="linux,windows" file_path="chrome/browser/supervised_user/child_accounts/permission_request_creator_apiary.cc"/> <item id="persist_blob_to_indexed_db" hash_code="32030464" type="0" content_hash_code="35410079" os_list="linux,windows" file_path="content/browser/indexed_db/indexed_db_backing_store.cc"/> @@ -195,7 +198,7 @@ <item id="test" hash_code="3556498" type="0" reserved="1" os_list="linux,windows" file_path=""/> <item id="test_partial" hash_code="22096011" type="0" reserved="1" os_list="linux,windows" file_path=""/> <item id="thumbnail_source" hash_code="135251783" type="0" content_hash_code="31086298" os_list="linux,windows" file_path="chrome/browser/search/thumbnail_source.cc"/> - <item id="translate_url_fetcher" hash_code="137116619" type="0" content_hash_code="1127120" os_list="linux,windows" file_path="components/translate/core/browser/translate_url_fetcher.cc"/> + <item id="translate_url_fetcher" hash_code="137116619" type="0" content_hash_code="104217506" os_list="linux,windows" file_path="components/translate/core/browser/translate_url_fetcher.cc"/> <item id="undefined" hash_code="45578882" type="0" reserved="1" os_list="linux,windows" file_path=""/> <item id="undefined-656607" hash_code="28406789" type="0" reserved="1" os_list="linux,windows" file_path=""/> <item id="url_fetcher_downloader" hash_code="113231892" type="0" content_hash_code="61085066" os_list="linux,windows" file_path="components/update_client/url_fetcher_downloader.cc"/>
diff --git a/ui/android/BUILD.gn b/ui/android/BUILD.gn index c52b603..d79dff1 100644 --- a/ui/android/BUILD.gn +++ b/ui/android/BUILD.gn
@@ -65,6 +65,7 @@ "//skia", "//third_party/WebKit/public:blink_headers", "//ui/base", + "//ui/compositor", "//ui/display", "//ui/events", "//ui/events/devices",
diff --git a/ui/android/DEPS b/ui/android/DEPS index 6c151a2..6f43de6 100644 --- a/ui/android/DEPS +++ b/ui/android/DEPS
@@ -16,6 +16,7 @@ "+third_party/WebKit/public/platform/WebCursorInfo.h", "+third_party/skia", "+ui/base", + "+ui/compositor/compositor_lock.h", "+ui/display", "+ui/events", "+ui/gfx",
diff --git a/ui/android/delegated_frame_host_android.cc b/ui/android/delegated_frame_host_android.cc index 0442c2ae..594a7ff 100644 --- a/ui/android/delegated_frame_host_android.cc +++ b/ui/android/delegated_frame_host_android.cc
@@ -104,6 +104,7 @@ } else { support_->SubmitCompositorFrame(local_surface_id, std::move(frame)); } + compositor_attach_until_frame_lock_.reset(); } void DelegatedFrameHostAndroid::DidNotProduceFrame( @@ -166,6 +167,16 @@ WindowAndroidCompositor* compositor) { if (registered_parent_compositor_) DetachFromCompositor(); + // If this is the first frame since the compositor became visible, we want to + // take the compositor lock, preventing compositor frames from being produced + // until all delegated frames are ready. This improves the resume transition, + // preventing flashes. Set a 5 second timeout to prevent locking up the + // browser in cases where the renderer hangs or another factor prevents a + // frame from being produced. + if (compositor->IsDrawingFirstVisibleFrame()) { + compositor_attach_until_frame_lock_ = + compositor->GetCompositorLock(this, base::TimeDelta::FromSeconds(5)); + } compositor->AddChildFrameSink(frame_sink_id_); client_->SetBeginFrameSource(&begin_frame_source_); registered_parent_compositor_ = compositor; @@ -174,6 +185,7 @@ void DelegatedFrameHostAndroid::DetachFromCompositor() { if (!registered_parent_compositor_) return; + compositor_attach_until_frame_lock_.reset(); client_->SetBeginFrameSource(nullptr); support_->SetNeedsBeginFrame(false); registered_parent_compositor_->RemoveChildFrameSink(frame_sink_id_); @@ -222,6 +234,8 @@ client_->OnFrameTokenChanged(frame_token); } +void DelegatedFrameHostAndroid::CompositorLockTimedOut() {} + void DelegatedFrameHostAndroid::CreateNewCompositorFrameSinkSupport() { constexpr bool is_root = false; constexpr bool needs_sync_points = true;
diff --git a/ui/android/delegated_frame_host_android.h b/ui/android/delegated_frame_host_android.h index 3c020914..4b963dde 100644 --- a/ui/android/delegated_frame_host_android.h +++ b/ui/android/delegated_frame_host_android.h
@@ -14,6 +14,7 @@ #include "components/viz/service/frame_sinks/compositor_frame_sink_support.h" #include "services/viz/public/interfaces/compositing/compositor_frame_sink.mojom.h" #include "ui/android/ui_android_export.h" +#include "ui/compositor/compositor_lock.h" namespace cc { class SurfaceLayer; @@ -33,7 +34,8 @@ class UI_ANDROID_EXPORT DelegatedFrameHostAndroid : public viz::mojom::CompositorFrameSinkClient, public viz::ExternalBeginFrameSourceClient, - public viz::HostFrameSinkClient { + public viz::HostFrameSinkClient, + public ui::CompositorLockClient { public: class Client { public: @@ -102,6 +104,9 @@ void OnFirstSurfaceActivation(const viz::SurfaceInfo& surface_info) override; void OnFrameTokenChanged(uint32_t frame_token) override; + // ui::CompositorLockClient implementation. + void CompositorLockTimedOut() override; + void CreateNewCompositorFrameSinkSupport(); const viz::FrameSinkId frame_sink_id_; @@ -121,6 +126,11 @@ scoped_refptr<cc::SurfaceLayer> content_layer_; + // A lock that is held from the point at which we attach to the compositor to + // the point at which we submit our first frame to the compositor. This + // ensures that the compositor doesn't swap without a frame available. + std::unique_ptr<ui::CompositorLock> compositor_attach_until_frame_lock_; + DISALLOW_COPY_AND_ASSIGN(DelegatedFrameHostAndroid); };
diff --git a/ui/android/window_android_compositor.h b/ui/android/window_android_compositor.h index 2f4a328..7446d2a 100644 --- a/ui/android/window_android_compositor.h +++ b/ui/android/window_android_compositor.h
@@ -10,6 +10,7 @@ #include "components/viz/common/frame_sinks/copy_output_request.h" #include "components/viz/common/surfaces/frame_sink_id.h" #include "ui/android/ui_android_export.h" +#include "ui/compositor/compositor_lock.h" namespace cc { class Layer; @@ -32,6 +33,10 @@ virtual viz::FrameSinkId GetFrameSinkId() = 0; virtual void AddChildFrameSink(const viz::FrameSinkId& frame_sink_id) = 0; virtual void RemoveChildFrameSink(const viz::FrameSinkId& frame_sink_id) = 0; + virtual std::unique_ptr<CompositorLock> GetCompositorLock( + CompositorLockClient* client, + base::TimeDelta timeout) = 0; + virtual bool IsDrawingFirstVisibleFrame() const = 0; }; } // namespace ui
diff --git a/ui/arc/notification/arc_notification_manager.cc b/ui/arc/notification/arc_notification_manager.cc index 413ccf6..98553c4b 100644 --- a/ui/arc/notification/arc_notification_manager.cc +++ b/ui/arc/notification/arc_notification_manager.cc
@@ -15,6 +15,7 @@ #include "base/strings/utf_string_conversions.h" #include "components/arc/arc_bridge_service.h" #include "components/arc/arc_browser_context_keyed_service_factory_base.h" +#include "components/arc/arc_util.h" #include "ui/arc/notification/arc_notification_delegate.h" #include "ui/arc/notification/arc_notification_item_impl.h" #include "ui/arc/notification/arc_notification_view.h" @@ -23,6 +24,8 @@ namespace arc { namespace { +constexpr char kPlayStorePackageName[] = "com.android.vending"; + std::unique_ptr<message_center::MessageView> CreateCustomMessageView( const message_center::Notification& notification) { DCHECK_EQ(notification.notifier_id().type, @@ -119,6 +122,11 @@ void ArcNotificationManager::OnNotificationPosted( mojom::ArcNotificationDataPtr data) { + if (ShouldIgnoreNotification(data.get())) { + VLOG(3) << "Posted notification was ignored."; + return; + } + const std::string& key = data->key; auto it = items_.find(key); if (it == items_.end()) { @@ -136,6 +144,11 @@ void ArcNotificationManager::OnNotificationUpdated( mojom::ArcNotificationDataPtr data) { + if (ShouldIgnoreNotification(data.get())) { + VLOG(3) << "Updated notification was ignored."; + return; + } + const std::string& key = data->key; auto it = items_.find(key); if (it == items_.end()) @@ -340,4 +353,12 @@ ash::Shell::Get()->toast_manager()->Cancel(data->id); } +bool ArcNotificationManager::ShouldIgnoreNotification( + arc::mojom::ArcNotificationData* data) { + // Notifications from Play Store are ignored in Public Session and Kiosk mode. + // TODO: Use centralized const for Play Store package. + return data->package_name.has_value() && + *data->package_name == kPlayStorePackageName && IsRobotAccountMode(); +} + } // namespace arc
diff --git a/ui/arc/notification/arc_notification_manager.h b/ui/arc/notification/arc_notification_manager.h index 0e1917c..0705835 100644 --- a/ui/arc/notification/arc_notification_manager.h +++ b/ui/arc/notification/arc_notification_manager.h
@@ -78,6 +78,8 @@ const AccountId& main_profile_id, message_center::MessageCenter* message_center); + bool ShouldIgnoreNotification(mojom::ArcNotificationData* data); + ArcBridgeService* const arc_bridge_service_; // Owned by ArcServiceManager. const AccountId main_profile_id_; message_center::MessageCenter* const message_center_;
diff --git a/ui/aura/mus/window_tree_client.cc b/ui/aura/mus/window_tree_client.cc index 1764412..760d35f4 100644 --- a/ui/aura/mus/window_tree_client.cc +++ b/ui/aura/mus/window_tree_client.cc
@@ -2227,6 +2227,13 @@ DCHECK_NE(display_id1, display_id2); window_tree_host1->set_display_id(display_id2); window_tree_host2->set_display_id(display_id1); + + // Swap the accelerated widgets so each host paints to the correct display. + gfx::AcceleratedWidget widget1 = window_tree_host1->GetAcceleratedWidget(); + gfx::AcceleratedWidget widget2 = window_tree_host2->GetAcceleratedWidget(); + window_tree_host1->OverrideAcceleratedWidget(widget2); + window_tree_host2->OverrideAcceleratedWidget(widget1); + if (window_manager_client_) { window_manager_client_->SwapDisplayRoots( display_id1, display_id2, base::Bind(&OnAckMustSucceed, FROM_HERE));
diff --git a/ui/aura/mus/window_tree_client_unittest.cc b/ui/aura/mus/window_tree_client_unittest.cc index ee9a6886..c6ab771 100644 --- a/ui/aura/mus/window_tree_client_unittest.cc +++ b/ui/aura/mus/window_tree_client_unittest.cc
@@ -11,6 +11,7 @@ #include "base/macros.h" #include "base/memory/ptr_util.h" #include "base/strings/utf_string_conversions.h" +#include "build/build_config.h" #include "cc/base/switches.h" #include "components/viz/common/surfaces/surface_info.h" #include "mojo/public/cpp/bindings/map.h" @@ -2604,6 +2605,54 @@ std::move(key_event), false); } +// Test accelerated widget values cause compositor crashes without Ozone. +#if defined(USE_OZONE) +#define MAYBE_SwapDisplayRoots SwapDisplayRoots +#else +#define MAYBE_SwapDisplayRoots DISABLED_SwapDisplayRoots +#endif +TEST_F(WindowTreeClientWmTest, MAYBE_SwapDisplayRoots) { + display::Display display1(201); + ui::mojom::WindowDataPtr root_data1(ui::mojom::WindowData::New()); + root_data1->window_id = 101; + + display::Display display2(202); + ui::mojom::WindowDataPtr root_data2(ui::mojom::WindowData::New()); + root_data2->window_id = 102; + + const bool parent_drawn = true; + + // AuraTestBase ends up owning WindowTreeHost. + WindowTreeHostMus* window_tree_host1 = + WindowTreeClientPrivate(window_tree_client_impl()) + .CallWmNewDisplayAdded(display1, std::move(root_data1), parent_drawn); + WindowTreeHostMus* window_tree_host2 = + WindowTreeClientPrivate(window_tree_client_impl()) + .CallWmNewDisplayAdded(display2, std::move(root_data2), parent_drawn); + +#if defined(OS_WIN) || defined(OS_ANDROID) + gfx::AcceleratedWidget widget1 = reinterpret_cast<gfx::AcceleratedWidget>(1U); + gfx::AcceleratedWidget widget2 = reinterpret_cast<gfx::AcceleratedWidget>(2U); +#else + gfx::AcceleratedWidget widget1 = static_cast<gfx::AcceleratedWidget>(1U); + gfx::AcceleratedWidget widget2 = static_cast<gfx::AcceleratedWidget>(2U); +#endif + + window_tree_host1->OverrideAcceleratedWidget(widget1); + window_tree_host2->OverrideAcceleratedWidget(widget2); + EXPECT_EQ(widget1, window_tree_host1->GetAcceleratedWidget()); + EXPECT_EQ(widget2, window_tree_host2->GetAcceleratedWidget()); + + static_cast<WindowManagerClient*>(window_tree_client_impl()) + ->SwapDisplayRoots(window_tree_host1, window_tree_host2); + + // SwapDisplayRoots swaps the display ids and accelerated widgets. + EXPECT_EQ(display2.id(), window_tree_host1->display_id()); + EXPECT_EQ(display1.id(), window_tree_host2->display_id()); + EXPECT_EQ(widget2, window_tree_host1->GetAcceleratedWidget()); + EXPECT_EQ(widget1, window_tree_host2->GetAcceleratedWidget()); +} + TEST_F(WindowTreeClientWmTestHighDPI, BoundsChangeWhenAdded) { const gfx::Rect bounds(1, 2, 101, 102); std::unique_ptr<DisplayInitParams> display_params =
diff --git a/ui/base/ui_base_switches.cc b/ui/base/ui_base_switches.cc index 00a5ec67..ceb931cd 100644 --- a/ui/base/ui_base_switches.cc +++ b/ui/base/ui_base_switches.cc
@@ -124,6 +124,9 @@ const char kSlowDownCompositingScaleFactor[] = "slow-down-compositing-scale-factor"; +// Tint GL-composited color. +const char kTintGlCompositedContent[] = "tint-gl-composited-content"; + #if defined(USE_AURA) // Used to enable the mus service (aka the UI service). This makes mus run in // process. It is also used to notify the clients that the UI service is being
diff --git a/ui/base/ui_base_switches.h b/ui/base/ui_base_switches.h index a4201e68..c64df72 100644 --- a/ui/base/ui_base_switches.h +++ b/ui/base/ui_base_switches.h
@@ -41,6 +41,7 @@ UI_BASE_EXPORT extern const char kMaterialDesignInkDropAnimationSpeedSlow[]; UI_BASE_EXPORT extern const char kShowOverdrawFeedback[]; UI_BASE_EXPORT extern const char kSlowDownCompositingScaleFactor[]; +UI_BASE_EXPORT extern const char kTintGlCompositedContent[]; UI_BASE_EXPORT extern const char kTopChromeMD[]; UI_BASE_EXPORT extern const char kTopChromeMDMaterial[]; UI_BASE_EXPORT extern const char kTopChromeMDMaterialAuto[];
diff --git a/ui/views/controls/scrollbar/cocoa_scroll_bar.mm b/ui/views/controls/scrollbar/cocoa_scroll_bar.mm index b5364da3..1f977ae1 100644 --- a/ui/views/controls/scrollbar/cocoa_scroll_bar.mm +++ b/ui/views/controls/scrollbar/cocoa_scroll_bar.mm
@@ -68,6 +68,8 @@ // Returns true if the thumb is in pressed state. bool IsStatePressed() const; + void UpdateIsMouseOverTrack(bool mouse_over_track); + protected: // View: gfx::Size CalculatePreferredSize() const override; @@ -104,6 +106,15 @@ return GetState() == Button::STATE_PRESSED; } +void CocoaScrollBarThumb::UpdateIsMouseOverTrack(bool mouse_over_track) { + // The state should not change if the thumb is pressed. The thumb will be + // set back to its hover or normal state when the mouse is released. + if (IsStatePressed()) + return; + + SetState(mouse_over_track ? Button::STATE_HOVERED : Button::STATE_NORMAL); +} + gfx::Size CocoaScrollBarThumb::CalculatePreferredSize() const { int thickness = cocoa_scroll_bar_->ScrollbarThickness(); return gfx::Size(thickness, thickness); @@ -286,7 +297,9 @@ } void CocoaScrollBar::OnMouseEntered(const ui::MouseEvent& event) { - if (scroller_style_ != NSScrollerStyleOverlay) + GetCocoaScrollBarThumb()->UpdateIsMouseOverTrack(true); + + if (scroller_style_ == NSScrollerStyleLegacy) return; // If the scrollbar thumb did not completely fade away, then reshow it when @@ -310,6 +323,7 @@ } void CocoaScrollBar::OnMouseExited(const ui::MouseEvent& event) { + GetCocoaScrollBarThumb()->UpdateIsMouseOverTrack(false); ResetOverlayScrollbar(); }
diff --git a/ui/webui/resources/cr_components/chromeos/network/network_ip_config.js b/ui/webui/resources/cr_components/chromeos/network/network_ip_config.js index b064a48e..617486c 100644 --- a/ui/webui/resources/cr_components/chromeos/network/network_ip_config.js +++ b/ui/webui/resources/cr_components/chromeos/network/network_ip_config.js
@@ -45,7 +45,7 @@ * The currently visible IP Config property dictionary. The 'RoutingPrefix' * property is a human-readable mask instead of a prefix length. * @private {?{ - * ipv4: !CrOnc.IPConfigUIProperties, + * ipv4: (!CrOnc.IPConfigUIProperties|undefined), * ipv6: (!CrOnc.IPConfigUIProperties|undefined) * }} */ @@ -97,12 +97,13 @@ if (properties.IPConfigs || properties.StaticIPConfig) { // Update the 'ipConfig' property. - var ipv4 = CrOnc.getIPConfigForType(properties, CrOnc.IPType.IPV4); - var ipv6 = CrOnc.getIPConfigForType(properties, CrOnc.IPType.IPV6); - this.ipConfig_ = { - ipv4: this.getIPConfigUIProperties_(ipv4), - ipv6: this.getIPConfigUIProperties_(ipv6) - }; + var ipv4 = this.getIPConfigUIProperties_( + CrOnc.getIPConfigForType(properties, CrOnc.IPType.IPV4)); + var ipv6 = this.getIPConfigUIProperties_( + CrOnc.getIPConfigForType(properties, CrOnc.IPType.IPV6)); + if (ipv4 && !ipv6) + ipv6 = {IPAddress: this.i18n('loading')}; + this.ipConfig_ = {ipv4: ipv4, ipv6: ipv6}; } else { this.ipConfig_ = null; } @@ -139,15 +140,15 @@ /** * @param {!CrOnc.IPConfigProperties|undefined} ipconfig - * @return {!CrOnc.IPConfigUIProperties} A new IPConfigUIProperties object - * with RoutingPrefix expressed as a string mask instead of a prefix - * length. Returns an empty object if |ipconfig| is undefined. + * @return {!CrOnc.IPConfigUIProperties|undefined} A new IPConfigUIProperties + * object with RoutingPrefix expressed as a string mask instead of a + * prefix length. Returns undefined if |ipconfig| is not defined. * @private */ getIPConfigUIProperties_: function(ipconfig) { - var result = {}; if (!ipconfig) - return result; + return undefined; + var result = {}; for (var key in ipconfig) { var value = ipconfig[key]; if (key == 'RoutingPrefix') @@ -225,7 +226,9 @@ // This will also set IPAddressConfigType to STATIC. this.fire('ip-change', { field: 'StaticIPConfig', - value: this.getIPConfigProperties_(this.ipConfig_.ipv4) + value: this.ipConfig_.ipv4 ? + this.getIPConfigProperties_(this.ipConfig_.ipv4) : + {} }); }, });
diff --git a/ui/webui/resources/cr_elements/chromeos/network/cr_onc_types.js b/ui/webui/resources/cr_elements/chromeos/network/cr_onc_types.js index 3eedf5d..9a2d13ef 100644 --- a/ui/webui/resources/cr_elements/chromeos/network/cr_onc_types.js +++ b/ui/webui/resources/cr_elements/chromeos/network/cr_onc_types.js
@@ -307,16 +307,19 @@ CrOnc.getIPConfigForType = function(properties, type) { 'use strict'; /** @type {!CrOnc.IPConfigProperties|undefined} */ var ipConfig = undefined; + /** @type {!CrOnc.IPType|undefined} */ var ipType = undefined; var ipConfigs = properties.IPConfigs; if (ipConfigs) { for (var i = 0; i < ipConfigs.length; ++i) { ipConfig = ipConfigs[i]; - if (ipConfig.Type == type) + ipType = ipConfig.Type ? /** @type {CrOnc.IPType} */ (ipConfig.Type) : + undefined; + if (ipType == type) break; } } if (type != CrOnc.IPType.IPV4) - return ipConfig; + return type == ipType ? ipConfig : undefined; var staticIpConfig = /** @type {!CrOnc.IPConfigProperties|undefined} */ (